diff --git a/Cargo.lock b/Cargo.lock index 43eecfdbb..dfa43a768 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3070,6 +3070,18 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pdf-writer" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753" +dependencies = [ + "bitflags 2.13.2", + "itoa", + "memchr", + "ryu", +] + [[package]] name = "peniko" version = "0.6.1" @@ -3749,6 +3761,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "same-file" version = "1.0.6" @@ -4287,8 +4305,10 @@ dependencies = [ "cadmpeg-registry", "chardetng", "encoding_rs", + "flate2", "gltf", "log", + "pdf-writer", "png", "quick-xml", "rustix 1.1.5", diff --git a/Cargo.toml b/Cargo.toml index 3d81e5829..eeba3061b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -83,6 +83,10 @@ image = { version = "0.25", default-features = false, features = ["png", "hdr"] png = "0.18.1" # LZW for GIF animations (MIT OR Apache-2.0, pure Rust; already in the tree through image's tiff). weezl = "0.1.12" +# sheet PDFs (MIT OR Apache-2.0, pure Rust; brings ryu, Apache-2.0 OR BSL-1.0) +pdf-writer = "0.15" +# deflate for PDF content streams (MIT OR Apache-2.0; already in the tree through zip) +flate2 = "1.1" # rasterises the UI icon SVGs (BSD-3-Clause, pure Rust, builds for wasm) tiny-skia = { version = "0.12", default-features = false, features = ["std", "simd"] } # build scripts: reads the icon palette (MIT OR Apache-2.0) diff --git a/crates/geom/src/paper/flatten.rs b/crates/geom/src/paper/flatten.rs index 2c54b4ade..87d8f113a 100644 --- a/crates/geom/src/paper/flatten.rs +++ b/crates/geom/src/paper/flatten.rs @@ -6,11 +6,10 @@ //! Each piece becomes the [`Seg2`] it is and takes [`Seg2::chords`]' steps, the bound //! [`Seg2::polyline`] uses too. `polyline` itself doesn't fit here: it floors an arc's tolerance at //! a millionth of its radius and caps a piece at 4096 steps, both coarser than asked, without a -//! word. An arc comes from the walk as its ends, radius and direction, which fix its centre (well -//! conditioned up to the walk's quarter turns). +//! word. Each piece is the curve [`Piece::seg`](super::Piece::seg) says. -use super::{GridPath, GridPoint, Invalid, Piece, Result}; -use crate::{Seg2, Vec2}; +use super::{GridPath, Invalid, Result}; +use crate::Vec2; /// The most points one path may flatten to. pub const MAX_POINTS: usize = 1 << 20; @@ -21,37 +20,18 @@ pub fn flatten(path: &GridPath, tolerance: f64) -> Result> { if !(tolerance > 0.0 && tolerance.is_finite()) { return Err(Invalid("a flattening tolerance is above 0")); } - let mut points = vec![v(path.start)]; - let mut at = v(path.start); + let mut points = vec![path.start.vec()]; + let mut at = path.start; for piece in &path.pieces { - let to = v(piece.to()); - let seg = match *piece { - Piece::Line { .. } => Seg2::Line { a: at, b: to }, - Piece::Arc { radius, clockwise, .. } => { - let r = radius as f64; - let half = at.dist(to) / 2.0; - // The centre sits off the chord's middle, left of it for an anticlockwise turn. - let off = (r * r - half * half).max(0.0).sqrt(); - let side = (to - at).normalized().map_or(Vec2::new(0.0, 0.0), Vec2::perp); - let center = (at + to) / 2.0 + side * if clockwise { -off } else { off }; - let sweep = 2.0 * (half / r).min(1.0).asin() * if clockwise { -1.0 } else { 1.0 }; - Seg2::Arc { center, radius: r, start: (at - center).angle(), sweep } - } - Piece::Cubic { c1, c2, .. } => Seg2::Cubic { p0: at, p1: v(c1), p2: v(c2), p3: to }, - Piece::Quadratic { c, .. } => Seg2::Conic { a: at, apex: v(c), b: to, w: 1.0 }, - }; + let seg = piece.seg(at); let n = steps(seg.chords(tolerance), points.len())?; points.extend((1..n).map(|i| seg.point_at(i as f64 / n as f64))); - points.push(to); - at = to; + points.push(piece.to().vec()); + at = piece.to(); } Ok(points) } -fn v(p: GridPoint) -> Vec2 { - Vec2::new(p.x as f64, p.y as f64) -} - /// `bound` rounded up to whole steps, at least one, refused when a path that has `so_far` points /// would go over [`MAX_POINTS`]. fn steps(bound: f64, so_far: usize) -> Result { @@ -136,7 +116,7 @@ mod tests { let quarter = on_grid(Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: FRAC_PI_2 }); let points = flatten(&quarter, 1e3).unwrap(); assert_eq!(points.len(), 57); - assert_eq!(points.last().copied(), Some(v(quarter.pieces[0].to()))); + assert_eq!(points.last().copied(), Some(quarter.pieces[0].to().vec())); // A cubic whose largest second difference is √1700 ≈ 41.2 mm, within 1 µm: √(0.75 · 4.12e7 / 1e3) → 176. let cubic = on_grid(Seg2::Cubic { p0: p(0.0, 0.0), p1: p(10.0, 40.0), p2: p(30.0, 40.0), p3: p(40.0, 0.0) }); assert_eq!(flatten(&cubic, 1e3).unwrap().len(), 1 + 176); diff --git a/crates/geom/src/paper/grid.rs b/crates/geom/src/paper/grid.rs index ebcf3fe61..284156273 100644 --- a/crates/geom/src/paper/grid.rs +++ b/crates/geom/src/paper/grid.rs @@ -29,6 +29,8 @@ pub struct Grid { impl Grid { /// Whole nanometres, six decimals of a millimetre: SVG's numbers. pub const NANOMETRE: Grid = Grid { per_mm: 1e6 }; + /// Steps of 10 nm, five decimals of a millimetre: PDF's numbers (ISO 32000-1 Annex C's precision). + pub const TEN_NANOMETRES: Grid = Grid { per_mm: 1e5 }; /// A grid of `per_mm` steps a millimetre, from 1 to 1e9. A power of two keeps every number /// exact in binary floating point, as a writer of 32-bit numbers (PDF) wants. @@ -89,6 +91,34 @@ impl Piece { Piece::Line { to } | Piece::Arc { to, .. } | Piece::Cubic { to, .. } | Piece::Quadratic { to, .. } => to, } } + + /// The curve this piece is, from `from`, in steps. An arc's ends, radius and direction fix its + /// centre, well conditioned up to the walk's quarter turns. + pub fn seg(&self, from: GridPoint) -> Seg2 { + let (at, to) = (from.vec(), self.to().vec()); + match *self { + Piece::Line { .. } => Seg2::Line { a: at, b: to }, + Piece::Arc { radius, clockwise, .. } => { + let r = radius as f64; + let half = at.dist(to) / 2.0; + // The centre sits off the chord's middle, left of it for an anticlockwise turn. + let off = (r * r - half * half).max(0.0).sqrt(); + let side = (to - at).normalized().map_or(Vec2::new(0.0, 0.0), Vec2::perp); + let center = (at + to) / 2.0 + side * if clockwise { -off } else { off }; + let sweep = 2.0 * (half / r).min(1.0).asin() * if clockwise { -1.0 } else { 1.0 }; + Seg2::Arc { center, radius: r, start: (at - center).angle(), sweep } + } + Piece::Cubic { c1, c2, .. } => Seg2::Cubic { p0: at, p1: c1.vec(), p2: c2.vec(), p3: to }, + Piece::Quadratic { c, .. } => Seg2::Conic { a: at, apex: c.vec(), b: to, w: 1.0 }, + } + } +} + +impl GridPoint { + /// The point in steps, as a [`Vec2`]. + pub fn vec(self) -> Vec2 { + Vec2::new(self.x as f64, self.y as f64) + } } /// A path on the grid: its pieces from `start`. A closed one ends on `start`, its closing line diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index bb5cb0b94..92468c779 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -25,6 +25,9 @@ encoding_rs = { workspace = true } # Sheet PNGs (src/paper/png.rs). png = { workspace = true } tiny-skia = { workspace = true } +# Sheet PDFs (src/paper/pdf.rs). +pdf-writer = { workspace = true } +flate2 = { workspace = true } # A plain fsync where a network share refuses Apple's full flush (src/safe_write.rs); already in # the tree through tempfile. diff --git a/crates/io/src/mutate.rs b/crates/io/src/mutate.rs index 6b3f7e6db..df5e3953e 100644 --- a/crates/io/src/mutate.rs +++ b/crates/io/src/mutate.rs @@ -550,68 +550,69 @@ outer }); } - /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, - /// never a panic. - #[test] - fn paper_scenes_survive_mutation_into_svg() { + /// An A3 paper scene's JSON for the writers' mutation tests: a closed border, a dashed arc, and + /// a fill with a hole. + fn paper_scene_json() -> Vec { use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Scene}; use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; let p = Vec2::new; let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; + let dashes = Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; let items = vec![ Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, Item::Stroke { path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], closed: false, width_mm: 0.35, - pattern: Some(dashes()), + pattern: Some(dashes), }, - Item::Fill { region: Region2 { outer: border, holes: vec![] } }, + Item::Fill { region: Region2 { outer: border, holes: vec![Loop2::circle(p(100.0, 100.0), 20.0)] } }, ]; let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; - let json = serde_json::to_vec(&scene).unwrap(); + serde_json::to_vec(&scene).unwrap() + } + + /// A paper scene's JSON, mutated, read, prepared and written as SVG: an error or a document, + /// never a panic. + #[test] + fn paper_scenes_survive_mutation_into_svg() { + let json = paper_scene_json(); let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; - crate::paper::paper_svg(&prepared).ok().map(|(bytes, _)| bytes.len()) + let scene: solidcraft_geom::paper::Scene = serde_json::from_slice(b).ok()?; + crate::paper::paper_svg(&scene.prepare().ok()?).ok().map(|(bytes, _)| bytes.len()) }; assert!(write(&json).is_some()); survives("paper scene to SVG", &mutations(&json, true, 0x5a3), usize::MAX, write); } - /// The same scene's JSON, mutated, read, prepared and written as a 25 dpi sheet PNG: an error or - /// an image, never a panic. + /// The same scene written as a 25 dpi sheet PNG: an error or an image, never a panic. #[test] fn paper_scenes_survive_mutation_into_png() { - use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Scene}; - use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; - let p = Vec2::new; - let border = Loop2::polygon(&[p(20.0, 10.0), p(410.0, 10.0), p(410.0, 287.0), p(20.0, 287.0)]); - let dashes = || Dashes { lengths_mm: vec![4.2, 1.05, 0.5, 1.05], phase_mm: 0.5 }; - let items = vec![ - Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7, pattern: None }, - Item::Stroke { - path: vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: 0.0, sweep: 4.0 }], - closed: false, - width_mm: 0.35, - pattern: Some(dashes()), - }, - Item::Fill { region: Region2 { outer: border, holes: vec![Loop2::circle(p(100.0, 100.0), 20.0)] } }, - ]; - let scene = Scene { size_mm: p(420.0, 297.0), groups: vec![Group { object: 7, kind: ObjectKind::DrawingBorder, items }] }; - let json = serde_json::to_vec(&scene).unwrap(); + let json = paper_scene_json(); let options = crate::paper::PngOptions { dpi: 25.0, colour: crate::paper::PngColour::Grey }; let write = |b: &[u8]| -> Option { - let scene: Scene = serde_json::from_slice(b).ok()?; - let prepared = scene.prepare().ok()?; + let scene: solidcraft_geom::paper::Scene = serde_json::from_slice(b).ok()?; let mut out = Vec::new(); - crate::paper::paper_png(&prepared, options, &mut out).ok().map(|_| out.len()) + crate::paper::paper_png(&scene.prepare().ok()?, options, &mut out).ok().map(|_| out.len()) }; assert!(write(&json).is_some()); survives("paper scene to PNG", &mutations(&json, true, 0x5a4), usize::MAX, write); } + /// The same scene written as a PDF with a title and a date: an error or a document, never a + /// panic. + #[test] + fn paper_scenes_survive_mutation_into_pdf() { + let json = paper_scene_json(); + let options = crate::paper::PdfOptions { title: Some("Sheet 1".into()), output_time: Some(1_761_436_800) }; + let write = |b: &[u8]| -> Option { + let scene: solidcraft_geom::paper::Scene = serde_json::from_slice(b).ok()?; + crate::paper::paper_pdf(&scene.prepare().ok()?, &options).ok().map(|(bytes, _)| bytes.len()) + }; + assert!(write(&json).is_some()); + survives("paper scene to PDF", &mutations(&json, true, 0x5a5), usize::MAX, write); + } + /// Standard base64 (RFC 4648) of `bytes`, for a data URI. fn base64(bytes: &[u8]) -> String { const A: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; diff --git a/crates/io/src/paper.rs b/crates/io/src/paper.rs index 0c89e2279..a5b8f77fe 100644 --- a/crates/io/src/paper.rs +++ b/crates/io/src/paper.rs @@ -1,7 +1,28 @@ -//! A sheet's paper scene (`geom::paper`) in a file: SVG (A3, #4890) and sheet PNG (A4); DXF and PDF follow. +//! A sheet's paper scene (`geom::paper`) in a file: SVG (A3, #4890), sheet PNG (A4) and PDF (P1); +//! DXF follows. +use std::fmt::Write; + +mod pdf; mod png; mod svg; +pub use pdf::{PdfOptions, PdfReport, paper_pdf}; pub use png::{DPI, MAX_POINTS, PngColour, PngOptions, PngReport, paper_png}; pub use svg::{SvgReport, paper_svg}; + +/// Grid steps written as millimetres onto `out`, on a grid of 10^`decimals` steps a millimetre: +/// the integer part, then up to `decimals` decimals without trailing zeros. No exponent, no "-0", +/// nothing that depends on the locale. +fn push_mm(out: &mut String, n: i64, decimals: u32) { + let unit = 10_u64.pow(decimals); + let (sign, n) = if n < 0 { ("-", n.unsigned_abs()) } else { ("", n.unsigned_abs()) }; + let (whole, mut part, mut digits) = (n / unit, n % unit, decimals as usize); + let _ = write!(out, "{sign}{whole}"); + if part != 0 { + while part % 10 == 0 { + (part, digits) = (part / 10, digits - 1); + } + let _ = write!(out, ".{part:0digits$}"); + } +} diff --git a/crates/io/src/paper/pdf.rs b/crates/io/src/paper/pdf.rs new file mode 100644 index 000000000..b0b03dd44 --- /dev/null +++ b/crates/io/src/paper/pdf.rs @@ -0,0 +1,260 @@ +//! A paper scene as a vector PDF (#4890, P1): one page the sheet's size, its lines and fills, +//! geometry only (text follows with P2). +//! +//! - **The file** comes from `pdf-writer`: a catalog, one page whose MediaBox is the sheet in +//! points, its content deflated, and an Info dictionary with the Producer, the Title when there +//! is one (ISO 32000-1 14.3.3: leave out what isn't known) and dates only from +//! [`PdfOptions::output_time`], never the clock, so a scene always gives the same bytes. +//! - **Numbers** are the scene on a 10 nm grid ([`Grid::TEN_NANOMETRES`], whose walk gives the +//! joints, closures and merges SVG and PNG draw), written as millimetres with up to five +//! decimals (Annex C's precision) inside one `cm` that scales millimetres to points. y is up on +//! the page as in the scene, so nothing flips. +//! - **Curves:** lines `l` and cubics `c` as they are; a parabola raised to a cubic; an arc's +//! pieces (each at most a quarter turn) cut into cubics that stay within [`ARC_TOLERANCE_MM`], +//! their rounding onto the grid included. +//! - **Paint:** strokes at their width `w` (the walk never gives 0, which 8.4.3.2 says is a device +//! pixel and shouldn't be used), butt caps, miter joins and a miter limit of 4, dashed by `d`; +//! fills black, even-odd (`f*`). Black on no background, as SVG. + +use std::f64::consts::FRAC_PI_2; +use std::fmt::Write as _; +use std::io::Write as _; + +use flate2::Compression; +use flate2::write::ZlibEncoder; +use pdf_writer::{Date, Filter, Pdf, Rect, Ref, TextStr}; +use solidcraft_geom::paper::{Grid, GridDashes, GridGroup, GridItem, GridPath, GridPoint, GridReport, Piece, Prepared}; +use solidcraft_geom::{Seg2, Vec2}; + +use super::push_mm; +use crate::{IoError, MAX_DRAWING_BYTES, Result}; + +/// How far an arc's cubics may stray from the arc, rounding onto the grid included. +pub const ARC_TOLERANCE_MM: f64 = 1e-4; +/// Points a millimetre. +const PT_PER_MM: f64 = 72.0 / 25.4; +/// The smallest page side, in points (Annex C). +const MIN_PAGE_PT: f64 = 3.0; +/// The most characters a title may have. +const MAX_TITLE_CHARS: usize = 1000; +/// The last second a PDF date can hold: 9999-12-31 23:59:59 UTC. +const MAX_OUTPUT_TIME: u64 = 253_402_300_799; +/// Decimals of a millimetre on the grid. +const DECIMALS: u32 = 5; + +/// What a sheet PDF says beyond the scene. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PdfOptions { + /// The document's title, left out when `None` or empty. + pub title: Option, + /// When the PDF was made, in seconds since 1970 (UTC): its creation and modification dates. + /// Without it the file has no dates. + pub output_time: Option, +} + +/// What writing a scene did that the scene didn't say: the grid's report. +pub type PdfReport = GridReport; + +/// A scene's PDF document, and what writing it did. +pub fn paper_pdf(scene: &Prepared, options: &PdfOptions) -> Result<(Vec, PdfReport)> { + let title = options.title.as_deref().filter(|t| !t.is_empty()); + if title.is_some_and(|t| t.chars().count() > MAX_TITLE_CHARS) { + return Err(IoError::Invalid(format!("a sheet PDF's title is at most {MAX_TITLE_CHARS} characters"))); + } + let date = options.output_time.map(date).transpose()?; + let on = scene.on_grid(Grid::TEN_NANOMETRES).map_err(|e| IoError::Invalid(e.to_string()))?; + let page = [on.size.x, on.size.y].map(|n| n as f64 / Grid::TEN_NANOMETRES.per_mm() * PT_PER_MM); + if page.iter().any(|side| *side < MIN_PAGE_PT) { + return Err(IoError::Invalid(format!("a sheet PDF's page is at least {MIN_PAGE_PT} pt (about 1.06 mm) a side"))); + } + + let content = content(&on.groups)?; + let mut deflate = ZlibEncoder::new(Vec::new(), Compression::default()); + let compressed = deflate.write_all(content.as_bytes()).and_then(|()| deflate.finish()); + let compressed = compressed.map_err(|e| IoError::Invalid(format!("the sheet PDF: {e}")))?; + + // Each object's number, used once (pdf-writer panics on a number written twice). + let (catalog, tree, page_id, contents, info) = (Ref::new(1), Ref::new(2), Ref::new(3), Ref::new(4), Ref::new(5)); + let mut pdf = Pdf::new(); + pdf.catalog(catalog).pages(tree); + pdf.pages(tree).kids([page_id]).count(1); + let mut writer = pdf.page(page_id); + writer.parent(tree).media_box(Rect::new(0.0, 0.0, page[0] as f32, page[1] as f32)).contents(contents); + writer.resources(); + drop(writer); + pdf.stream(contents, &compressed).filter(Filter::FlateDecode); + let mut doc = pdf.document_info(info); + doc.producer(TextStr(concat!("SolidCraft ", env!("CARGO_PKG_VERSION")))); + if let Some(title) = title { + doc.title(TextStr(title)); + } + if let Some(date) = date { + doc.creation_date(date).modified_date(date); + } + drop(doc); + Ok((pdf.finish(), on.report)) +} + +/// `secs` since 1970 as a PDF date in UTC, refused past the year 9999. +fn date(secs: u64) -> Result { + if secs > MAX_OUTPUT_TIME { + return Err(IoError::Invalid("a sheet PDF's date is at most the year 9999".into())); + } + let (year, month, day, hour, minute, second) = crate::civil(secs); + let (month, day) = (u8::try_from(month).unwrap_or(1), u8::try_from(day).unwrap_or(1)); + let [hour, minute, second] = [hour, minute, second].map(|v| u8::try_from(v).unwrap_or(0)); + Ok(Date::new(u16::try_from(year).unwrap_or(0)).month(month).day(day).hour(hour).minute(minute).second(second).utc_offset_hour(0)) +} + +/// The page's content stream: the scene in millimetres, scaled to points once. +fn content(groups: &[GridGroup]) -> Result { + let mut w = Content { out: String::new(), width: None, dashes: None }; + let _ = writeln!(w.out, "q {PT_PER_MM:.9} 0 0 {PT_PER_MM:.9} 0 0 cm 0 J 0 j 4 M"); + for item in groups.iter().flat_map(|g| &g.items) { + match item { + GridItem::Stroke { width, path, dashes } => { + if w.width != Some(*width) { + w.number(*width); + w.out.push_str(" w\n"); + w.width = Some(*width); + } + if w.dashes.as_ref() != dashes.as_ref() { + w.dashes(dashes.as_ref()); + w.dashes.clone_from(dashes); + } + w.path(path)?; + // A closed path's closing line, then the stroke: `s`. + w.out.push_str(if path.closed { "s\n" } else { "S\n" }); + } + GridItem::Fill { loops } => { + for l in loops { + w.path(l)?; + w.out.push_str("h\n"); + } + w.out.push_str("f*\n"); + } + } + if w.out.len() > MAX_DRAWING_BYTES { + return Err(IoError::Invalid(format!("the PDF's drawing would be over {} MiB", MAX_DRAWING_BYTES >> 20))); + } + } + w.out.push_str("Q\n"); + Ok(w.out) +} + +struct Content { + out: String, + /// The stroke width and dash pattern last set, so each is written only when it changes. + width: Option, + dashes: Option, +} + +impl Content { + fn number(&mut self, n: i64) { + push_mm(&mut self.out, n, DECIMALS); + } + + fn point(&mut self, p: GridPoint) { + self.number(p.x); + self.out.push(' '); + self.number(p.y); + self.out.push(' '); + } + + /// `p` in steps, rounded onto the grid. + fn near(&mut self, p: Vec2) -> Result<()> { + if !p.is_finite() { + return Err(IoError::Invalid("the sheet PDF: a curve point is not a number".into())); + } + self.point(GridPoint { x: p.x.round() as i64, y: p.y.round() as i64 }); + Ok(()) + } + + /// A dash pattern `[on off …] phase d`, or a solid line `[] 0 d`. + fn dashes(&mut self, dashes: Option<&GridDashes>) { + self.out.push('['); + if let Some(d) = dashes { + for (i, length) in d.lengths.iter().enumerate() { + if i > 0 { + self.out.push(' '); + } + self.number(*length); + } + } + self.out.push_str("] "); + self.number(dashes.map_or(0, |d| d.phase)); + self.out.push_str(" d\n"); + } + + /// A path from its start; a closed one's closing line is left to the caller's `h` or `s`. + fn path(&mut self, path: &GridPath) -> Result<()> { + self.point(path.start); + self.out.push_str("m\n"); + let mut at = path.start; + for piece in &path.pieces { + match *piece { + Piece::Line { to } => { + self.point(to); + self.out.push_str("l\n"); + } + Piece::Cubic { c1, c2, to } => { + self.point(c1); + self.point(c2); + self.point(to); + self.out.push_str("c\n"); + } + // A parabola is the cubic with its control points two thirds of the way to `c`. + Piece::Quadratic { c, to } => { + let (a, c, b) = (at.vec(), c.vec(), to.vec()); + self.near(a + (c - a) * (2.0 / 3.0))?; + self.near(b + (c - b) * (2.0 / 3.0))?; + self.point(to); + self.out.push_str("c\n"); + } + Piece::Arc { .. } => self.arc(piece.seg(at), piece.to())?, + } + at = piece.to(); + } + Ok(()) + } + + /// An arc piece as cubics within [`ARC_TOLERANCE_MM`], ending exactly on `to`. + fn arc(&mut self, arc: Seg2, to: GridPoint) -> Result<()> { + let Seg2::Arc { center, radius, start, sweep } = arc else { + return Err(IoError::Invalid("the sheet PDF: an arc piece isn't an arc".into())); + }; + let n = cubics_for(radius, sweep).ok_or_else(|| IoError::Invalid("the sheet PDF: an arc needs too many cubics".into()))?; + let h = sweep / n as f64; + let k = 4.0 / 3.0 * (h / 4.0).tan() * radius; + let tangent = |a: f64| Vec2::new(-a.sin(), a.cos()); + for i in 0..n { + let (a0, a1) = (start + h * i as f64, start + h * (i + 1) as f64); + let (p0, p3) = (center + Vec2::from_angle(a0) * radius, center + Vec2::from_angle(a1) * radius); + self.near(p0 + tangent(a0) * k)?; + self.near(p3 - tangent(a1) * k)?; + if i + 1 == n { + self.point(to) + } else { + self.near(p3)? + } + self.out.push_str("c\n"); + } + Ok(()) + } +} + +/// How many equal cubics keep an arc of `radius` steps and `sweep` (at most a quarter turn) within +/// the tolerance. The 4/3·tan(θ/4) cubic of a θ arc strays at most r·(2/27)·sin⁶(θ/4)/cos²(θ/4) +/// from it, outward; each control point rounded onto the grid moves the curve at most half a +/// step's diagonal more. +fn cubics_for(radius: f64, sweep: f64) -> Option { + let tolerance = ARC_TOLERANCE_MM * Grid::TEN_NANOMETRES.per_mm() - std::f64::consts::FRAC_1_SQRT_2; + let strays = |theta: f64| radius * (2.0 / 27.0) * (theta / 4.0).sin().powi(6) / (theta / 4.0).cos().powi(2); + (sweep.is_finite() && sweep.abs() <= FRAC_PI_2 + 1e-9 && radius.is_finite()) + .then(|| (1..=64).find(|&n| strays(sweep.abs() / n as f64) <= tolerance)) + .flatten() +} + +#[cfg(test)] +#[path = "pdf_tests.rs"] +mod tests; diff --git a/crates/io/src/paper/pdf_tests.rs b/crates/io/src/paper/pdf_tests.rs new file mode 100644 index 000000000..e26e70518 --- /dev/null +++ b/crates/io/src/paper/pdf_tests.rs @@ -0,0 +1,204 @@ +use std::f64::consts::{FRAC_PI_2, TAU}; +use std::io::Read; + +use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Scene}; +use solidcraft_geom::{Loop2, Region2, Seg2, Vec2}; + +use super::*; + +fn p(x: f64, y: f64) -> Vec2 { + Vec2::new(x, y) +} + +fn scene(size: Vec2, items: Vec) -> Scene { + Scene { size_mm: size, groups: vec![Group { object: 1, kind: ObjectKind::DrawingBorder, items }] } +} + +fn stroke(path: Vec, closed: bool, width_mm: f64, pattern: Option) -> Item { + Item::Stroke { path, closed, width_mm, pattern } +} + +fn pdf(scene: &Scene, options: &PdfOptions) -> Vec { + paper_pdf(&scene.prepare().unwrap(), options).unwrap().0 +} + +fn text(bytes: &[u8]) -> String { + String::from_utf8_lossy(bytes).into_owned() +} + +/// The page's content stream, inflated. +fn content(bytes: &[u8]) -> String { + let at = bytes.windows(7).position(|w| w == b"stream\n").unwrap() + 7; + let end = at + bytes[at..].windows(10).position(|w| w == b"endstream\n" || w == b"\nendstream").unwrap(); + let mut out = String::new(); + flate2::read::ZlibDecoder::new(&bytes[at..end]).read_to_string(&mut out).unwrap(); + out +} + +/// The content's operators, each with its operands, numbers read as numbers. +fn ops(content: &str) -> Vec<(String, Vec)> { + let spaced = content.replace('[', " [ ").replace(']', " ] "); + let mut ops = Vec::new(); + let mut operands = Vec::new(); + for token in spaced.split_whitespace() { + match token.parse::() { + Ok(n) => operands.push(n), + Err(_) if token == "[" || token == "]" => {} + Err(_) => ops.push((token.to_string(), std::mem::take(&mut operands))), + } + } + ops +} + +/// Each cubic in the content as its four points, in millimetres. +fn cubics(content: &str) -> Vec<[Vec2; 4]> { + let (mut at, mut out) = (p(0.0, 0.0), Vec::new()); + for (op, n) in ops(content) { + match op.as_str() { + "m" | "l" => at = p(n[0], n[1]), + "c" => { + out.push([at, p(n[0], n[1]), p(n[2], n[3]), p(n[4], n[5])]); + at = p(n[4], n[5]); + } + _ => {} + } + } + out +} + +fn bezier([p0, p1, p2, p3]: [Vec2; 4], t: f64) -> Vec2 { + let s = 1.0 - t; + p0 * (s * s * s) + p1 * (3.0 * s * s * t) + p2 * (3.0 * s * t * t) + p3 * (t * t * t) +} + +const NONE: PdfOptions = PdfOptions { title: None, output_time: None }; + +/// An A3 sheet's page is A3 in points, and the PDF says who made it. +#[test] +fn an_a3_sheet_is_its_size_in_points() { + let bytes = pdf(&scene(p(420.0, 297.0), vec![]), &NONE); + let file = text(&bytes); + assert!(file.starts_with("%PDF-"), "{}", &file[..20]); + assert!(file.contains("/MediaBox [0 0 1190.5511 841.8898]"), "{file}"); + assert!(file.contains(&format!("/Producer (SolidCraft {})", env!("CARGO_PKG_VERSION"))), "{file}"); + assert!(!file.contains("/Title"), "no title asked for: {file}"); +} + +/// A 100 mm edge at 1:2 is a 50 mm line on paper: 141.732 pt across the page. +#[test] +fn fifty_millimetres_on_paper_are_141_732_points() { + let line = scene(p(210.0, 297.0), vec![stroke(vec![Seg2::Line { a: p(10.0, 20.0), b: p(60.0, 20.0) }], false, 0.5, None)]); + let ops = ops(&content(&pdf(&line, &NONE))); + let cm = ops.iter().find(|(op, _)| op == "cm").unwrap(); + assert_eq!(cm.1[..4], [cm.1[0], 0.0, 0.0, cm.1[0]], "one scale, millimetres to points"); + let ends: Vec = ops.iter().filter(|(op, _)| op == "m" || op == "l").map(|(_, n)| n[0]).collect(); + assert_eq!(ends, [10.0, 60.0]); + assert!(((ends[1] - ends[0]) * cm.1[0] - 141.732).abs() < 1e-3, "{}", (ends[1] - ends[0]) * cm.1[0]); +} + +/// The same scene gives the same bytes; the dates come only from `output_time`, in UTC. +#[test] +fn the_same_scene_gives_the_same_bytes_and_dates_come_only_from_output_time() { + let sheet = scene(p(210.0, 297.0), vec![stroke(vec![Seg2::Line { a: p(10.0, 20.0), b: p(60.0, 20.0) }], false, 0.5, None)]); + assert_eq!(pdf(&sheet, &NONE), pdf(&sheet, &NONE)); + assert!(!text(&pdf(&sheet, &NONE)).contains("Date")); + let leap_day = PdfOptions { title: Some("Sheet 1".into()), output_time: Some(951_782_400) }; + let file = text(&pdf(&sheet, &leap_day)); + assert!(file.contains("/CreationDate (D:20000229000000Z)") && file.contains("/ModDate (D:20000229000000Z)"), "{file}"); + assert!(file.contains("/Title (Sheet 1)"), "{file}"); + assert_eq!(pdf(&sheet, &leap_day), pdf(&sheet, &leap_day)); + let last = PdfOptions { title: Some(String::new()), output_time: Some(MAX_OUTPUT_TIME) }; + let file = text(&pdf(&sheet, &last)); + assert!(file.contains("(D:99991231235959Z)") && !file.contains("/Title"), "{file}"); +} + +/// The trailer's `startxref` points at the table, and each entry at its `N 0 obj`. +#[test] +fn every_cross_reference_points_at_its_object() { + let sheet = scene(p(420.0, 297.0), vec![stroke(Loop2::circle(p(100.0, 100.0), 40.0).segs, true, 0.7, None)]); + let bytes = pdf(&sheet, &PdfOptions { title: Some("Ç".into()), output_time: Some(0) }); + let file = text(&bytes); + let start: usize = file.rsplit("startxref").next().unwrap().split_whitespace().next().unwrap().parse().unwrap(); + assert!(file[start..].starts_with("xref\n0 6\n"), "{}", &file[start..start + 20]); + let entries = &file[start + "xref\n0 6\n".len()..]; + for (n, entry) in entries.as_bytes().chunks(20).take(6).enumerate().skip(1) { + let entry = std::str::from_utf8(entry).unwrap(); + let offset: usize = entry[..10].parse().unwrap(); + assert!(entry[10..].starts_with(" 00000 n"), "{entry:?}"); + assert!(file[offset..].starts_with(&format!("{n} 0 obj")), "object {n} at {offset}"); + } +} + +/// Arcs are cubics within a ten-thousandth of a millimetre, from a 0.5 mm radius to 2 m, and a +/// parabola is its cubic; every number has at most five decimals. +#[test] +fn arcs_are_cubics_within_a_ten_thousandth_of_a_millimetre() { + for (radius, sweep) in [(0.5, TAU), (40.0, TAU), (300.0, 2.5), (2000.0, 0.3)] { + let c = p(2500.0, 2500.0); + let arc = scene(p(5000.0, 5000.0), vec![stroke(vec![Seg2::Arc { center: c, radius, start: 0.4, sweep }], false, 0.35, None)]); + let content = content(&pdf(&arc, &NONE)); + let cubics = cubics(&content); + assert!(cubics.len() >= (sweep / FRAC_PI_2).ceil() as usize, "{radius}: {}", cubics.len()); + for cubic in &cubics { + for k in 0..=64 { + let off = (bezier(*cubic, f64::from(k) / 64.0).dist(c) - radius).abs(); + assert!(off <= ARC_TOLERANCE_MM, "r {radius}: {off} mm off at {k}/64"); + } + } + assert!(content.split_whitespace().all(|t| t.split('.').nth(1).is_none_or(|d| d.len() <= 5)), "{content}"); + } + let parabola = scene( + p(100.0, 100.0), + vec![stroke(vec![Seg2::Conic { a: p(10.0, 10.0), apex: p(30.0, 50.0), b: p(50.0, 10.0), w: 1.0 }], false, 0.35, None)], + ); + let cubic = cubics(&content(&pdf(¶bola, &NONE)))[0]; + for k in 0..=16 { + let t = f64::from(k) / 16.0; + let s = 1.0 - t; + let on = p(10.0, 10.0) * (s * s) + p(30.0, 50.0) * (2.0 * s * t) + p(50.0, 10.0) * (t * t); + assert!(bezier(cubic, t).dist(on) <= 1e-5, "{t}"); + } +} + +/// Strokes and fills are painted as SVG and PNG paint them: butt caps, miter joins, a miter limit +/// of 4, each width and dash pattern set once until it changes, a closed outline closed, fills +/// even-odd. +#[test] +fn strokes_and_fills_are_painted_as_the_other_writers_paint_them() { + let dashed = Some(Dashes { lengths_mm: vec![4.2, 1.05], phase_mm: 0.5 }); + let line = |y: f64| vec![Seg2::Line { a: p(10.0, y), b: p(100.0, y) }]; + let sheet = scene( + p(210.0, 297.0), + vec![ + stroke(line(10.0), false, 0.35, None), + stroke(line(20.0), false, 0.35, dashed.clone()), + stroke(line(30.0), false, 0.35, dashed), + stroke(line(40.0), false, 0.7, None), + stroke(Loop2::polygon(&[p(10.0, 50.0), p(50.0, 50.0), p(50.0, 90.0)]).segs, true, 0.7, None), + Item::Fill { region: Region2 { outer: Loop2::circle(p(150.0, 150.0), 20.0), holes: vec![Loop2::circle(p(150.0, 150.0), 10.0)] } }, + ], + ); + let content = content(&pdf(&sheet, &NONE)); + assert!(content.starts_with("q 2.834645669 0 0 2.834645669 0 0 cm 0 J 0 j 4 M\n") && content.ends_with("Q\n"), "{content}"); + let ops = ops(&content); + let set: Vec<(&str, &[f64])> = ops.iter().filter(|(op, _)| op == "w" || op == "d").map(|(op, n)| (op.as_str(), n.as_slice())).collect(); + assert_eq!(set, [("w", &[0.35][..]), ("d", &[4.2, 1.05, 0.5][..]), ("w", &[0.7][..]), ("d", &[0.0][..])], "{content}"); + let paints: Vec<&str> = ops.iter().map(|(op, _)| op.as_str()).filter(|op| ["S", "s", "f*", "h"].contains(op)).collect(); + assert_eq!(paints, ["S", "S", "S", "S", "s", "h", "h", "f*"], "{content}"); +} + +/// A page under 3 pt a side, a title over 1,000 characters and a date past the year 9999 are +/// refused. +#[test] +fn what_cannot_be_written_is_refused() { + let tiny = scene(p(1.0, 297.0), vec![]); + let e = paper_pdf(&tiny.prepare().unwrap(), &NONE).unwrap_err(); + assert!(e.to_string().contains("at least 3 pt"), "{e}"); + let sheet = scene(p(210.0, 297.0), vec![]); + let prepared = sheet.prepare().unwrap(); + assert!(paper_pdf(&prepared, &PdfOptions { title: Some("x".repeat(1000)), output_time: None }).is_ok()); + let e = paper_pdf(&prepared, &PdfOptions { title: Some("x".repeat(1001)), output_time: None }).unwrap_err(); + assert!(e.to_string().contains("1000 characters"), "{e}"); + let e = paper_pdf(&prepared, &PdfOptions { title: None, output_time: Some(MAX_OUTPUT_TIME + 1) }).unwrap_err(); + assert!(e.to_string().contains("9999"), "{e}"); +} diff --git a/crates/io/src/paper/svg.rs b/crates/io/src/paper/svg.rs index 9f05d74bc..48995ef3b 100644 --- a/crates/io/src/paper/svg.rs +++ b/crates/io/src/paper/svg.rs @@ -66,18 +66,9 @@ pub fn paper_svg(scene: &Prepared) -> Result<(Vec, SvgReport)> { Ok((w.out.into_bytes(), on.report)) } -/// Nanometres written as millimetres onto `out`: the integer part, then up to six decimals -/// without trailing zeros. +/// Nanometres written as millimetres onto `out`, with up to six decimals. fn push_number(out: &mut String, n: i64) { - let (sign, n) = if n < 0 { ("-", n.unsigned_abs()) } else { ("", n.unsigned_abs()) }; - let (whole, mut part, mut digits) = (n / 1_000_000, n % 1_000_000, 6); - let _ = write!(out, "{sign}{whole}"); - if part != 0 { - while part % 10 == 0 { - (part, digits) = (part / 10, digits - 1); - } - let _ = write!(out, ".{part:0digits$}"); - } + super::push_mm(out, n, 6); } /// [`push_number`] as its own text, for the numbers written once per document.