Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e65a33d3e3 | ||
|
|
506d419084 | ||
|
|
be22b97b70 | ||
|
|
effaf49113 | ||
|
|
dc911d80d1 | ||
|
|
4ae2e1db65 | ||
|
|
7dc82dc7bb | ||
|
|
884fc53700 | ||
|
|
1aaff713aa | ||
|
|
dadb5f00ee | ||
|
|
d2fcae512e |
No files matched your search
Generated
+22
@@ -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,11 @@ dependencies = [
|
||||
"cadmpeg-registry",
|
||||
"chardetng",
|
||||
"encoding_rs",
|
||||
"flate2",
|
||||
"gltf",
|
||||
"log",
|
||||
"pdf-writer",
|
||||
"png",
|
||||
"quick-xml",
|
||||
"rustix 1.1.5",
|
||||
"serde",
|
||||
@@ -4298,6 +4319,7 @@ dependencies = [
|
||||
"solidcraft-geom",
|
||||
"solidcraft-kernel",
|
||||
"thiserror 2.0.21",
|
||||
"tiny-skia",
|
||||
"zip 9.0.4",
|
||||
]
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -40,6 +40,7 @@ use serde_json::{Value, json};
|
||||
use solidcraft_doc::Document;
|
||||
|
||||
use crate::Session;
|
||||
use crate::io::civil;
|
||||
|
||||
/// Reports kept (the oldest, and recovered kernel panics, go first).
|
||||
pub const MAX_REPORTS: usize = 20;
|
||||
@@ -148,21 +149,6 @@ fn now_ms() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
|
||||
}
|
||||
|
||||
/// `secs` since 1970 as (year, month, day, hour, minute, second) in UTC.
|
||||
fn civil(secs: u64) -> (i64, i64, i64, u64, u64, u64) {
|
||||
let days = i64::try_from(secs / 86_400).unwrap_or(0);
|
||||
let rem = secs % 86_400;
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
(yoe + era * 400 + i64::from(m <= 2), m, d, rem / 3600, rem % 3600 / 60, rem % 60)
|
||||
}
|
||||
|
||||
/// `2026-10-12T14:03:22Z`.
|
||||
pub fn utc(secs: u64) -> String {
|
||||
let (y, m, d, h, mi, s) = civil(secs);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! The paper scene: what a sheet shows, as strokes and fills in sheet millimetres, for the writers
|
||||
//! that put it in a file (DXF, SVG, PNG, PDF). Plain data with one check, [`Scene::validate`]:
|
||||
//! nothing here is saved, drawn on screen or made by a command yet. Text, clips, line patterns and
|
||||
//! styles are later additions.
|
||||
//! nothing here is saved, drawn on screen or made by a command yet. Text, clips and styles are
|
||||
//! later additions.
|
||||
//!
|
||||
//! - Coordinates are millimetres from the sheet's lower-left corner, x to the right and y up;
|
||||
//! angles are radians, anticlockwise. A line's width is its width on paper, centred on its path.
|
||||
@@ -10,6 +10,9 @@
|
||||
//! - A stroke has butt caps and miter joins with a miter limit of 4 (a join sharper than about 29°
|
||||
//! is bevelled). A closed stroke joins at its start instead of having two caps. A fill is
|
||||
//! painted even-odd, so a hole is a hole whichever way its loop runs.
|
||||
//! - A dashed stroke's pattern ([`Dashes`]) runs along its whole path, round a closed one, in
|
||||
//! paper millimetres: a dashed line looks the same at any view scale. Each dash has the
|
||||
//! stroke's caps and joins.
|
||||
//! - Each group says which object on the sheet drew it, by an id, and what kind of object that is.
|
||||
//! The id is opaque here: it names one object within the sheet, and several groups may come from
|
||||
//! the same object. DXF and PDF put a group on the layer its kind names ([`ObjectKind::layer`]).
|
||||
@@ -23,14 +26,19 @@
|
||||
//! within ±2e5 mm;
|
||||
//! - a stroke's pieces meeting end to start within [`EPS`], and its ends too when it is closed;
|
||||
//! every loop of a fill closed the same way;
|
||||
//! - a line width above 0 and at most [`MAX_LINE_MM`].
|
||||
//! - a line width above 0 and at most [`MAX_LINE_MM`];
|
||||
//! - a dash pattern of 2 to 12 lengths, an even count, each above 0 and at most [`MAX_DASH_MM`],
|
||||
//! its phase from 0 up to (not including) the pattern's length, and at most [`MAX_DASHES`]
|
||||
//! dashes along the stroke, counted from its pieces' lengths ([`Seg2::length`]).
|
||||
//!
|
||||
//! It does not certify simple loops, holes inside their outer loop or a path that never doubles
|
||||
//! back. Validation after parsing cannot bound parsing allocations: an encoded-input boundary must
|
||||
//! also limit bytes and nesting.
|
||||
//!
|
||||
//! Writers read a [`Prepared`] scene, which only [`Scene::prepare`] makes, so none reads one that
|
||||
//! wasn't checked. Clipping will happen there too, once, before any writer (A8).
|
||||
//! wasn't checked, and format it on their number grid ([`Prepared::on_grid`], [`grid`]'s rules),
|
||||
//! so every format draws the same joints, closures and merges. Clipping will happen in
|
||||
//! `prepare` too, once, before any writer (A8).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -38,8 +46,18 @@ use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
use crate::{EPS, Region2, Seg2, Vec2};
|
||||
|
||||
pub mod flatten;
|
||||
pub mod grid;
|
||||
|
||||
pub use flatten::flatten;
|
||||
pub use grid::{Grid, GridDashes, GridGroup, GridItem, GridPath, GridPoint, GridReport, OnGrid, Piece};
|
||||
|
||||
/// The widest line a scene may draw, in millimetres.
|
||||
pub const MAX_LINE_MM: f64 = 10.0;
|
||||
/// The longest dash or gap a pattern may have, in millimetres.
|
||||
pub const MAX_DASH_MM: f64 = 1000.0;
|
||||
/// The most dashes one stroke may need: what a writer cuts it into stays bounded.
|
||||
pub const MAX_DASHES: f64 = 1e6;
|
||||
/// The longest side a sheet may have, in millimetres.
|
||||
pub const MAX_SIDE_MM: f64 = 5000.0;
|
||||
/// Groups, items, loops and curve pieces a scene may hold in all.
|
||||
@@ -103,12 +121,41 @@ impl ObjectKind {
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Item {
|
||||
/// A line `width_mm` wide along `path`, each piece starting where the one before ends. A
|
||||
/// closed stroke also ends where it starts.
|
||||
Stroke { path: Vec<Seg2>, closed: bool, width_mm: f64 },
|
||||
/// closed stroke also ends where it starts. With a `pattern` it is dashed; without, solid.
|
||||
Stroke {
|
||||
path: Vec<Seg2>,
|
||||
closed: bool,
|
||||
width_mm: f64,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pattern: Option<Dashes>,
|
||||
},
|
||||
/// A region painted solid.
|
||||
Fill { region: Region2 },
|
||||
}
|
||||
|
||||
/// A dashed line's pattern: dash and gap lengths in turn, starting with a dash, and how far into
|
||||
/// the pattern the stroke starts.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Dashes {
|
||||
pub lengths_mm: Vec<f64>,
|
||||
pub phase_mm: f64,
|
||||
}
|
||||
|
||||
impl Dashes {
|
||||
/// Checks the pattern, and the dashes it needs along `path`, against the module's notes.
|
||||
fn check(&self, path: &[Seg2]) -> Result<()> {
|
||||
let n = self.lengths_mm.len();
|
||||
require((2..=12).contains(&n) && n.is_multiple_of(2), "a dash pattern has an even count of 2 to 12 lengths")?;
|
||||
require(self.lengths_mm.iter().all(|l| *l > 0.0 && *l <= MAX_DASH_MM), "each dash and gap is above 0 and at most 1000 mm")?;
|
||||
let period: f64 = self.lengths_mm.iter().sum();
|
||||
require(self.phase_mm >= 0.0 && self.phase_mm < period, "a dash pattern's phase is from 0 up to its length")?;
|
||||
// Counted as writers that cut a line into its dashes count them: pairs along the length.
|
||||
let length: f64 = path.iter().map(Seg2::length).sum();
|
||||
require(length / period * (n / 2) as f64 <= MAX_DASHES, "a dashed line needs at most 1,000,000 dashes")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("paper scene: {0}")]
|
||||
pub struct Invalid(pub &'static str);
|
||||
@@ -196,7 +243,7 @@ impl Scene {
|
||||
require([x, y].into_iter().all(|side| side > 0.0 && side <= MAX_SIDE_MM), "each side of the sheet is above 0 and at most 5000 mm")?;
|
||||
for item in self.groups.iter().flat_map(|g| &g.items) {
|
||||
match item {
|
||||
Item::Stroke { path, closed, width_mm } => {
|
||||
Item::Stroke { path, closed, width_mm, pattern } => {
|
||||
require(*width_mm > 0.0 && *width_mm <= MAX_LINE_MM, "a line is above 0 and at most 10 mm wide")?;
|
||||
require(!path.is_empty(), "a stroke has at least one piece")?;
|
||||
pieces(path)?;
|
||||
@@ -204,6 +251,9 @@ impl Scene {
|
||||
if *closed {
|
||||
require(path.last().zip(path.first()).is_some_and(|(a, b)| meet(a, b)), "a closed stroke ends where it starts")?;
|
||||
}
|
||||
if let Some(dashes) = pattern {
|
||||
dashes.check(path)?;
|
||||
}
|
||||
}
|
||||
Item::Fill { region } => {
|
||||
for l in region.loops() {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
//! A path on a writer's grid as straight lines (#4890, A4), for a writer that draws only lines
|
||||
//! (PNG): every point of every curve lies within the tolerance of them, and a path that would need
|
||||
//! more than [`MAX_POINTS`] points is refused, never drawn coarser. It is the one flattener for the
|
||||
//! paper scene: a writer that needs a curve as lines (PDF or DXF for what they can't hold) uses it.
|
||||
//!
|
||||
//! 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. Each piece is the curve [`Piece::seg`](super::Piece::seg) says.
|
||||
|
||||
use super::{GridPath, Invalid, Result};
|
||||
use crate::Vec2;
|
||||
|
||||
/// The most points one path may flatten to.
|
||||
pub const MAX_POINTS: usize = 1 << 20;
|
||||
|
||||
/// `path`'s points, from its start, joined by lines within `tolerance` steps (above 0) of its
|
||||
/// curves. A closed path's closing line is left to the reader, as on the grid.
|
||||
pub fn flatten(path: &GridPath, tolerance: f64) -> Result<Vec<Vec2>> {
|
||||
if !(tolerance > 0.0 && tolerance.is_finite()) {
|
||||
return Err(Invalid("a flattening tolerance is above 0"));
|
||||
}
|
||||
let mut points = vec![path.start.vec()];
|
||||
let mut at = path.start;
|
||||
for piece in &path.pieces {
|
||||
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(piece.to().vec());
|
||||
at = piece.to();
|
||||
}
|
||||
Ok(points)
|
||||
}
|
||||
|
||||
/// `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<usize> {
|
||||
let n = bound.ceil().max(1.0);
|
||||
if n.is_finite() && so_far as f64 + n <= MAX_POINTS as f64 {
|
||||
Ok(n as usize)
|
||||
} else {
|
||||
Err(Invalid("a curve needs over 1,048,576 points at this resolution"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
|
||||
use super::*;
|
||||
use crate::Seg2;
|
||||
use crate::paper::{Grid, GridItem, Group, Item, ObjectKind, Scene};
|
||||
|
||||
/// The scene's one stroke along `seg` on the nanometre grid.
|
||||
fn on_grid(seg: Seg2) -> GridPath {
|
||||
let scene = Scene {
|
||||
size_mm: Vec2::new(420.0, 297.0),
|
||||
groups: vec![Group {
|
||||
object: 1,
|
||||
kind: ObjectKind::DrawingBorder,
|
||||
items: vec![Item::Stroke { path: vec![seg], closed: false, width_mm: 0.35, pattern: None }],
|
||||
}],
|
||||
};
|
||||
let on = scene.prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap();
|
||||
let GridItem::Stroke { path, .. } = &on.groups[0].items[0] else { panic!("a stroke") };
|
||||
path.clone()
|
||||
}
|
||||
|
||||
fn distance_to_lines(p: Vec2, points: &[Vec2]) -> f64 {
|
||||
points.windows(2).map(|w| p.extend(0.0).dist_to_segment(w[0].extend(0.0), w[1].extend(0.0))).fold(f64::INFINITY, f64::min)
|
||||
}
|
||||
|
||||
/// Every curve point within the tolerance of the lines, every line point on (or, for a chord,
|
||||
/// within the tolerance of) the curve, in nanometres: arcs either way round of every size,
|
||||
/// cubics and parabolas.
|
||||
#[test]
|
||||
fn every_curve_lies_within_the_tolerance_of_its_lines() {
|
||||
let p = Vec2::new;
|
||||
let mm = |x: f64| x * 1e6;
|
||||
for tolerance in [1.0, 132.3, 1323.0, 1e5] {
|
||||
for (radius, start, sweep) in [(10.0, 0.0, FRAC_PI_2), (10.0, 1.0, -FRAC_PI_2), (0.01, 0.3, TAU), (1e4, -2.0, -PI), (250.0, 0.2, 1e-4)] {
|
||||
let center = p(100.0, 100.0);
|
||||
let points = flatten(&on_grid(Seg2::Arc { center, radius, start, sweep }), tolerance).unwrap();
|
||||
let c = p(mm(center.x), mm(center.y));
|
||||
for q in &points {
|
||||
assert!((q.dist(c) - mm(radius)).abs() < 4.0, "a point on the circle: r {radius}, {:?}", q);
|
||||
}
|
||||
for k in 0..=1000 {
|
||||
let on = c + Vec2::from_angle(start + sweep * f64::from(k) / 1000.0) * mm(radius);
|
||||
let d = distance_to_lines(on, &points);
|
||||
assert!(d <= tolerance + 2.0, "arc r {radius} sweep {sweep}, tolerance {tolerance}: {d}");
|
||||
}
|
||||
}
|
||||
let cubic = [p(0.0, 0.0), p(10.0, 40.0), p(30.0, -20.0), p(40.0, 0.0)];
|
||||
let points = flatten(&on_grid(Seg2::Cubic { p0: cubic[0], p1: cubic[1], p2: cubic[2], p3: cubic[3] }), tolerance).unwrap();
|
||||
for k in 0..=1000 {
|
||||
let (t, s) = (f64::from(k) / 1000.0, 1.0 - f64::from(k) / 1000.0);
|
||||
let q = cubic[0] * (s * s * s) + cubic[1] * (3.0 * s * s * t) + cubic[2] * (3.0 * s * t * t) + cubic[3] * (t * t * t);
|
||||
assert!(distance_to_lines(p(mm(q.x), mm(q.y)), &points) <= tolerance + 2.0, "cubic at {t}, tolerance {tolerance}");
|
||||
}
|
||||
let (a, c, b) = (p(0.0, 0.0), p(10.0, 30.0), p(20.0, 0.0));
|
||||
let points = flatten(&on_grid(Seg2::Conic { a, apex: c, b, w: 1.0 }), tolerance).unwrap();
|
||||
for k in 0..=1000 {
|
||||
let (t, s) = (f64::from(k) / 1000.0, 1.0 - f64::from(k) / 1000.0);
|
||||
let q = a * (s * s) + c * (2.0 * s * t) + b * (t * t);
|
||||
assert!(distance_to_lines(p(mm(q.x), mm(q.y)), &points) <= tolerance + 2.0, "parabola at {t}, tolerance {tolerance}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// As few points as the bounds allow, the last each piece's own end; lines as they are.
|
||||
#[test]
|
||||
fn the_point_counts_are_the_bounds() {
|
||||
let p = Vec2::new;
|
||||
// A quarter turn of 10 mm within 1 µm: 2·acos(1 − 1e3 / 1e7) a step, 56 steps.
|
||||
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(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);
|
||||
// A parabola whose second difference is 60 mm, within 1 µm: √(0.25 · 6e7 / 1e3) → 123.
|
||||
let parabola = on_grid(Seg2::Conic { a: p(0.0, 0.0), apex: p(10.0, 30.0), b: p(20.0, 0.0), w: 1.0 });
|
||||
assert_eq!(flatten(¶bola, 1e3).unwrap().len(), 1 + 123);
|
||||
let line = on_grid(Seg2::Line { a: p(1.0, 2.0), b: p(3.0, 4.0) });
|
||||
assert_eq!(flatten(&line, 1e3).unwrap(), [p(1e6, 2e6), p(3e6, 4e6)]);
|
||||
// A tolerance wider than the radius: eighth turns, so one chord for half a radian.
|
||||
let tiny = on_grid(Seg2::Arc { center: p(50.0, 50.0), radius: 1e-3, start: 0.0, sweep: 0.5 });
|
||||
assert_eq!(flatten(&tiny, 1e4).unwrap().len(), 2);
|
||||
}
|
||||
|
||||
/// Over the cap is refused, never coarser; a tolerance must be above 0.
|
||||
#[test]
|
||||
fn too_many_points_or_no_tolerance_is_refused() {
|
||||
let circle = on_grid(Seg2::Arc { center: Vec2::new(0.0, 0.0), radius: 1e5, start: 0.0, sweep: TAU });
|
||||
assert!(flatten(&circle, 1e3).is_ok());
|
||||
let e = flatten(&circle, 0.1).unwrap_err();
|
||||
assert!(e.0.contains("1,048,576"), "{e}");
|
||||
for tolerance in [0.0, -1.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(flatten(&circle, tolerance).is_err(), "{tolerance}");
|
||||
}
|
||||
// The cap counts the points a path already has: it may reach the cap, never pass it.
|
||||
assert_eq!(steps(10.0, MAX_POINTS - 10).ok(), Some(10));
|
||||
assert!(steps(10.0, MAX_POINTS - 9).is_err());
|
||||
assert!(steps(0.5, MAX_POINTS).is_err(), "a curve is at least one step");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,308 @@
|
||||
//! A prepared scene on a writer's number grid (#4890, C4): the one walk every writer formats, so
|
||||
//! each format draws the same joints, closures and merges.
|
||||
//!
|
||||
//! - Every coordinate is a whole number of the grid's steps, x to the right and y up as in the
|
||||
//! scene, so a joint is one point and a writer's flip or scale of whole numbers is exact.
|
||||
//! - A closed path ends exactly on its start; a closing line is left to the writer's close
|
||||
//! (SVG's `Z`, PDF's `h`).
|
||||
//! - A piece ending within [`SLIVER_STEPS`] of where the path is merges into the next, and is
|
||||
//! counted. A path's last piece has no next, so it is kept unless it has no length.
|
||||
//! - A width, dash or gap under half a step is one step, and is counted. A dash pattern's phase is
|
||||
//! taken within the pattern's length on the grid.
|
||||
//! - Circular arcs come in pieces of at most a quarter turn ([`arc_pieces`]). Ellipses, hyperbolas
|
||||
//! and Béziers above degree 3 aren't walked yet (A3b): a scene with one is refused.
|
||||
|
||||
use super::{Invalid, Item, ObjectKind, Prepared, Result, arc_pieces};
|
||||
use crate::{Seg2, Vec2};
|
||||
|
||||
/// The largest number put on a grid, in millimetres either way: far past any scene's 2e5.
|
||||
const MAX_NUMBER_MM: f64 = 9e9;
|
||||
/// Pieces ending this many steps or fewer from where the path is are merged into the next.
|
||||
pub const SLIVER_STEPS: i64 = 10;
|
||||
|
||||
/// A writer's number grid: `per_mm` steps a millimetre.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Grid {
|
||||
per_mm: f64,
|
||||
}
|
||||
|
||||
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.
|
||||
pub fn new(per_mm: f64) -> Option<Grid> {
|
||||
(1.0..=1e9).contains(&per_mm).then_some(Grid { per_mm })
|
||||
}
|
||||
|
||||
pub fn per_mm(self) -> f64 {
|
||||
self.per_mm
|
||||
}
|
||||
|
||||
/// `v` millimetres as whole steps.
|
||||
pub fn steps(self, v: f64) -> Result<i64> {
|
||||
let n = (v * self.per_mm).round();
|
||||
if n.abs() <= MAX_NUMBER_MM * self.per_mm { Ok(n as i64) } else { Err(Invalid("a number too large (or not a number) for the grid")) }
|
||||
}
|
||||
|
||||
pub fn point(self, p: Vec2) -> Result<GridPoint> {
|
||||
Ok(GridPoint { x: self.steps(p.x)?, y: self.steps(p.y)? })
|
||||
}
|
||||
}
|
||||
|
||||
/// A point on a grid, in whole steps.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct GridPoint {
|
||||
pub x: i64,
|
||||
pub y: i64,
|
||||
}
|
||||
|
||||
/// One piece of a path on the grid, from where the path is to `to`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Piece {
|
||||
Line {
|
||||
to: GridPoint,
|
||||
},
|
||||
/// A circular arc of at most a quarter turn, of `radius` steps, turning clockwise (y up) when
|
||||
/// `clockwise`.
|
||||
Arc {
|
||||
radius: i64,
|
||||
clockwise: bool,
|
||||
to: GridPoint,
|
||||
},
|
||||
Cubic {
|
||||
c1: GridPoint,
|
||||
c2: GridPoint,
|
||||
to: GridPoint,
|
||||
},
|
||||
/// A parabola: a conic of weight 1 with its control point `c`.
|
||||
Quadratic {
|
||||
c: GridPoint,
|
||||
to: GridPoint,
|
||||
},
|
||||
}
|
||||
|
||||
impl Piece {
|
||||
pub fn to(&self) -> GridPoint {
|
||||
match *self {
|
||||
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
|
||||
/// left to the writer's close.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GridPath {
|
||||
pub start: GridPoint,
|
||||
pub pieces: Vec<Piece>,
|
||||
pub closed: bool,
|
||||
}
|
||||
|
||||
/// An item on the grid.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GridItem {
|
||||
/// A stroke `width` steps wide, at least one, dashed when it has `dashes`.
|
||||
Stroke { width: i64, path: GridPath, dashes: Option<GridDashes> },
|
||||
/// A fill's loops, each closed.
|
||||
Fill { loops: Vec<GridPath> },
|
||||
}
|
||||
|
||||
/// A dash pattern on the grid: dash and gap lengths in turn, each at least one step, and the
|
||||
/// phase, from 0 up to the pattern's length.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GridDashes {
|
||||
pub lengths: Vec<i64>,
|
||||
pub phase: i64,
|
||||
}
|
||||
|
||||
/// A group's items on the grid, in paint order.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct GridGroup {
|
||||
pub object: u64,
|
||||
pub kind: ObjectKind,
|
||||
pub items: Vec<GridItem>,
|
||||
}
|
||||
|
||||
/// What the grid made of a scene that the scene didn't say.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct GridReport {
|
||||
/// Widths under half a step, made one step.
|
||||
pub widths_snapped: usize,
|
||||
/// Pieces too short for the grid, merged into the next.
|
||||
pub pieces_merged: usize,
|
||||
/// Dashes and gaps under half a step, made one step.
|
||||
pub dashes_snapped: usize,
|
||||
}
|
||||
|
||||
/// A scene on a grid: the sheet's size, its groups in paint order, and the report.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct OnGrid {
|
||||
pub size: GridPoint,
|
||||
pub groups: Vec<GridGroup>,
|
||||
pub report: GridReport,
|
||||
}
|
||||
|
||||
impl Prepared<'_> {
|
||||
/// The scene on `grid`, by the rules in this module's notes: what every writer formats.
|
||||
pub fn on_grid(&self, grid: Grid) -> Result<OnGrid> {
|
||||
let mut report = GridReport::default();
|
||||
let mut groups = Vec::with_capacity(self.groups().len());
|
||||
for group in self.groups() {
|
||||
let mut items = Vec::with_capacity(group.items.len());
|
||||
for item in &group.items {
|
||||
match item {
|
||||
Item::Stroke { path, closed, width_mm, pattern } => {
|
||||
let Some(path) = walk(grid, path, *closed, &mut report)? else { continue };
|
||||
let width = at_least_one(grid.steps(*width_mm)?, &mut report.widths_snapped);
|
||||
let dashes = match pattern {
|
||||
Some(d) => {
|
||||
let mut lengths = Vec::with_capacity(d.lengths_mm.len());
|
||||
for l in &d.lengths_mm {
|
||||
lengths.push(at_least_one(grid.steps(*l)?, &mut report.dashes_snapped));
|
||||
}
|
||||
// Rounded on its own, the phase can reach the rounded pattern's length.
|
||||
let phase = grid.steps(d.phase_mm)? % lengths.iter().sum::<i64>();
|
||||
Some(GridDashes { lengths, phase })
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
items.push(GridItem::Stroke { width, path, dashes });
|
||||
}
|
||||
Item::Fill { region } => {
|
||||
let mut loops = Vec::new();
|
||||
for l in region.loops() {
|
||||
loops.extend(walk(grid, &l.segs, true, &mut report)?);
|
||||
}
|
||||
items.push(GridItem::Fill { loops });
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.push(GridGroup { object: group.object, kind: group.kind, items });
|
||||
}
|
||||
Ok(OnGrid { size: grid.point(self.size_mm())?, groups, report })
|
||||
}
|
||||
}
|
||||
|
||||
/// `steps`, or one step when it rounds to none, counted in `snapped`.
|
||||
fn at_least_one(steps: i64, snapped: &mut usize) -> i64 {
|
||||
if steps == 0 {
|
||||
*snapped += 1;
|
||||
return 1;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// `segs` on the grid (`None` when it has no pieces).
|
||||
fn walk(grid: Grid, segs: &[Seg2], closed: bool, report: &mut GridReport) -> Result<Option<GridPath>> {
|
||||
let (Some(first), Some((last, body))) = (segs.first(), segs.split_last()) else { return Ok(None) };
|
||||
let start = grid.point(first.start())?;
|
||||
let mut w = Walk { grid, start, at: start, pieces: Vec::with_capacity(segs.len()), report };
|
||||
for seg in body {
|
||||
w.piece(seg, false, false)?;
|
||||
}
|
||||
if !closed {
|
||||
w.piece(last, false, true)?;
|
||||
} else if !matches!(last, Seg2::Line { .. }) {
|
||||
w.piece(last, true, true)?;
|
||||
}
|
||||
Ok(Some(GridPath { start, pieces: w.pieces, closed }))
|
||||
}
|
||||
|
||||
/// A path being walked: where it started and where it is.
|
||||
struct Walk<'r> {
|
||||
grid: Grid,
|
||||
start: GridPoint,
|
||||
at: GridPoint,
|
||||
pieces: Vec<Piece>,
|
||||
report: &'r mut GridReport,
|
||||
}
|
||||
|
||||
impl Walk<'_> {
|
||||
/// Whether a piece ending at `end` is too short to keep: it merges into the next. A path's
|
||||
/// last piece (`keep`) has no next, so it is kept unless it has no length: an open path ends
|
||||
/// where it ends, a closed one on its start exactly.
|
||||
fn merged(&mut self, end: GridPoint, keep: bool) -> bool {
|
||||
if keep {
|
||||
return end == self.at;
|
||||
}
|
||||
let (dx, dy) = (end.x - self.at.x, end.y - self.at.y);
|
||||
let short = dx.abs() <= SLIVER_STEPS && dy.abs() <= SLIVER_STEPS && dx * dx + dy * dy <= SLIVER_STEPS * SLIVER_STEPS;
|
||||
if short {
|
||||
self.report.pieces_merged += 1;
|
||||
}
|
||||
short
|
||||
}
|
||||
|
||||
fn push(&mut self, piece: Piece) {
|
||||
self.at = piece.to();
|
||||
self.pieces.push(piece);
|
||||
}
|
||||
|
||||
/// One piece, from where the path is: `closing` makes its end the path's start, and `keep`
|
||||
/// marks the path's last piece ([`Walk::merged`]).
|
||||
fn piece(&mut self, seg: &Seg2, closing: bool, keep: bool) -> Result<()> {
|
||||
let end = if closing { self.start } else { self.grid.point(seg.end())? };
|
||||
match *seg {
|
||||
Seg2::Line { .. } => {
|
||||
if !self.merged(end, keep) {
|
||||
self.push(Piece::Line { to: end });
|
||||
}
|
||||
}
|
||||
Seg2::Arc { center, radius, start, sweep } => {
|
||||
let (radius_steps, clockwise) = (self.grid.steps(radius)?, sweep < 0.0);
|
||||
let mut ends = arc_pieces(center, radius, start, sweep).peekable();
|
||||
while let Some(p) = ends.next() {
|
||||
let final_piece = ends.peek().is_none();
|
||||
let to = if final_piece { end } else { self.grid.point(p)? };
|
||||
if !self.merged(to, keep && final_piece) {
|
||||
self.push(Piece::Arc { radius: radius_steps, clockwise, to });
|
||||
}
|
||||
}
|
||||
}
|
||||
Seg2::Cubic { p1, p2, .. } => {
|
||||
let (c1, c2) = (self.grid.point(p1)?, self.grid.point(p2)?);
|
||||
self.push(Piece::Cubic { c1, c2, to: end });
|
||||
}
|
||||
Seg2::Conic { apex, w, .. } if (w - 1.0).abs() <= 1e-12 => {
|
||||
let c = self.grid.point(apex)?;
|
||||
self.push(Piece::Quadratic { c, to: end });
|
||||
}
|
||||
Seg2::Conic { .. } | Seg2::Bezier { .. } => {
|
||||
return Err(Invalid("not supported yet: ellipses, hyperbolas and Béziers above degree 3 on paper (#4890, A3b)"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::f64::consts::{PI, TAU};
|
||||
use std::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
|
||||
use serde_json::json;
|
||||
|
||||
@@ -14,7 +14,7 @@ fn line(a: Vec2, b: Vec2) -> Seg2 {
|
||||
}
|
||||
|
||||
fn stroke(path: Vec<Seg2>, closed: bool, width_mm: f64) -> Item {
|
||||
Item::Stroke { path, closed, width_mm }
|
||||
Item::Stroke { path, closed, width_mm, pattern: None }
|
||||
}
|
||||
|
||||
fn fill(outer: Loop2, holes: Vec<Loop2>) -> Item {
|
||||
@@ -303,3 +303,159 @@ fn unknown_fields_kinds_and_ids_are_refused_when_read() {
|
||||
v["groups"][0]["object"] = json!(u64::MAX);
|
||||
read(v).unwrap().validate().unwrap();
|
||||
}
|
||||
|
||||
/// A grid counts whole steps: half a step and less rounds to the nearer, -0 is 0, and a number
|
||||
/// too large or not a number is refused. A grid has 1 to 1e9 steps a millimetre.
|
||||
#[test]
|
||||
fn a_grid_counts_whole_steps_and_refuses_what_it_cannot_hold() {
|
||||
let nm = Grid::NANOMETRE;
|
||||
assert_eq!((nm.steps(-0.0).unwrap(), nm.steps(4e-7).unwrap(), nm.steps(6e-7).unwrap()), (0, 0, 1));
|
||||
assert_eq!(nm.steps(9e9).unwrap(), 9_000_000_000_000_000);
|
||||
for v in [f64::NAN, f64::INFINITY, 1e10, -1e10] {
|
||||
assert!(nm.steps(v).is_err(), "{v}");
|
||||
}
|
||||
for per_mm in [1.0, 2048.0, 1e9] {
|
||||
assert_eq!(Grid::new(per_mm).map(Grid::per_mm), Some(per_mm));
|
||||
}
|
||||
for per_mm in [0.0, 0.999, 1e9 + 1.0, -2048.0, f64::NAN, f64::INFINITY] {
|
||||
assert!(Grid::new(per_mm).is_none(), "{per_mm}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The A3 border on the nanometre grid: y up as in the scene, the closing line left to the
|
||||
/// writer's close, each fill loop closed, nothing snapped or merged.
|
||||
#[test]
|
||||
fn a_scene_on_the_grid_keeps_y_up_and_leaves_the_closing_line_to_the_writer() {
|
||||
let on = a3().prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap();
|
||||
let g = |x: i64, y: i64| GridPoint { x: x * 1_000_000, y: y * 1_000_000 };
|
||||
assert_eq!(on.size, g(420, 297));
|
||||
let group = &on.groups[0];
|
||||
assert_eq!((group.object, group.kind, group.items.len()), (1, ObjectKind::DrawingBorder, 3));
|
||||
let GridItem::Stroke { width, path, dashes: None } = &group.items[0] else { panic!("{:?}", group.items[0]) };
|
||||
assert_eq!(*width, 700_000);
|
||||
let lines = |points: &[GridPoint]| points.iter().map(|&to| Piece::Line { to }).collect::<Vec<_>>();
|
||||
assert_eq!(*path, GridPath { start: g(20, 10), pieces: lines(&[g(410, 10), g(410, 287), g(20, 287)]), closed: true });
|
||||
let GridItem::Fill { loops } = &group.items[1] else { panic!("{:?}", group.items[1]) };
|
||||
assert_eq!(*loops, [GridPath { start: g(0, 0), pieces: lines(&[g(10, 0), g(10, 5), g(0, 5)]), closed: true }]);
|
||||
assert_eq!(on.report, GridReport::default());
|
||||
}
|
||||
|
||||
/// Slivers are measured in the grid's own steps: a 5 mm piece goes straight on to the next on a
|
||||
/// 1 mm grid, and stays on the nanometre grid. An arc's quarters keep its radius and turn, in
|
||||
/// steps; a width under half a step is one step. A curve the walk can't take yet is refused.
|
||||
#[test]
|
||||
fn slivers_and_radii_are_in_the_grids_own_steps() {
|
||||
let millimetre = Grid::new(1.0).unwrap();
|
||||
let walk = |scene: &Scene, grid: Grid| scene.prepare().unwrap().on_grid(grid).unwrap();
|
||||
let path = |on: &OnGrid| match &on.groups[0].items[0] {
|
||||
GridItem::Stroke { width, path, .. } => (*width, path.clone()),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let three = open(vec![line(p(0.0, 0.0), p(100.0, 0.0)), line(p(100.0, 0.0), p(105.0, 0.0)), line(p(105.0, 0.0), p(200.0, 0.0))]);
|
||||
let coarse = walk(&three, millimetre);
|
||||
let to = |x: i64| Piece::Line { to: GridPoint { x, y: 0 } };
|
||||
assert_eq!(path(&coarse).1.pieces, [to(100), to(200)]);
|
||||
assert_eq!(coarse.report, GridReport { widths_snapped: 1, pieces_merged: 1, dashes_snapped: 0 }, "0.35 mm is under half a 1 mm step");
|
||||
assert_eq!(path(&coarse).0, 1);
|
||||
// The boundary both ways: 10 steps along x merge, 11 don't; a (6, 8) step merges, (7, 8) doesn't.
|
||||
for (dx, dy, merged) in [(10.0, 0.0, 1), (11.0, 0.0, 0), (6.0, 8.0, 1), (7.0, 8.0, 0)] {
|
||||
let (a, b) = (p(100.0, 0.0), p(100.0 + dx, dy));
|
||||
let scene = open(vec![line(p(0.0, 0.0), a), line(a, b), line(b, p(200.0, 50.0))]);
|
||||
assert_eq!(walk(&scene, millimetre).report.pieces_merged, merged, "({dx}, {dy})");
|
||||
}
|
||||
let fine = walk(&three, Grid::NANOMETRE);
|
||||
assert_eq!((path(&fine).1.pieces.len(), fine.report), (3, GridReport::default()));
|
||||
// A clockwise half turn of radius 10 round (50, 50) from the top: two quarters.
|
||||
let half = open(vec![Seg2::Arc { center: p(50.0, 50.0), radius: 10.0, start: FRAC_PI_2, sweep: -PI }]);
|
||||
let arc = |x, y| Piece::Arc { radius: 10, clockwise: true, to: GridPoint { x, y } };
|
||||
assert_eq!(
|
||||
path(&walk(&half, millimetre)).1,
|
||||
GridPath { start: GridPoint { x: 50, y: 60 }, pieces: vec![arc(60, 50), arc(50, 40)], closed: false }
|
||||
);
|
||||
let ellipse = open(vec![Seg2::Conic { a: p(0.0, 0.0), apex: p(10.0, 10.0), b: p(20.0, 0.0), w: 0.5 }]);
|
||||
let refused = ellipse.prepare().unwrap().on_grid(Grid::NANOMETRE).unwrap_err();
|
||||
assert!(refused.0.contains("not supported yet"), "{refused}");
|
||||
}
|
||||
|
||||
fn dashed(path: Vec<Seg2>, closed: bool, lengths_mm: &[f64], phase_mm: f64) -> Scene {
|
||||
sheet(vec![Item::Stroke { path, closed, width_mm: 0.35, pattern: Some(Dashes { lengths_mm: lengths_mm.to_vec(), phase_mm }) }])
|
||||
}
|
||||
|
||||
/// A pattern has 2 to 12 lengths, an even count, each above 0 and at most 1000 mm; its phase is
|
||||
/// from 0 up to, not including, the pattern's length.
|
||||
#[test]
|
||||
fn a_dash_pattern_is_an_even_2_to_12_lengths_with_its_phase_inside_it() {
|
||||
let pattern = |lengths: &[f64], phase| dashed(vec![line(p(0.0, 0.0), p(100.0, 0.0))], false, lengths, phase).validate();
|
||||
for n in [2, 4, 12] {
|
||||
pattern(&vec![1.0; n], 0.0).unwrap();
|
||||
}
|
||||
for n in [0, 1, 3, 11, 13, 14] {
|
||||
assert_eq!(pattern(&vec![1.0; n], 0.0), Err(Invalid("a dash pattern has an even count of 2 to 12 lengths")), "{n}");
|
||||
}
|
||||
for length in [1e-9, 1000.0] {
|
||||
pattern(&[length, 1.0], 0.0).unwrap();
|
||||
pattern(&[1.0, length], 0.0).unwrap();
|
||||
}
|
||||
for length in [0.0, -0.0, -1.0, 1000f64.next_up(), f64::NAN, f64::INFINITY] {
|
||||
assert_eq!(pattern(&[1.0, length], 0.0), Err(Invalid("each dash and gap is above 0 and at most 1000 mm")), "{length}");
|
||||
}
|
||||
for phase in [0.0, -0.0, 1.5, 3f64.next_down()] {
|
||||
pattern(&[1.0, 2.0], phase).unwrap();
|
||||
}
|
||||
for phase in [3.0, (-0.0f64).next_down(), -1.0, 4.0, f64::NAN, f64::INFINITY] {
|
||||
assert_eq!(pattern(&[1.0, 2.0], phase), Err(Invalid("a dash pattern's phase is from 0 up to its length")), "{phase}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A dashed line needs at most a million dashes, counted as pairs along its length. A line of
|
||||
/// exactly a million patterns of 2⁻¹³ mm is the bound; an arc counts its own length, not its
|
||||
/// chord's.
|
||||
#[test]
|
||||
fn a_dashed_line_needs_at_most_a_million_dashes() {
|
||||
const TOO_MANY: Invalid = Invalid("a dashed line needs at most 1,000,000 dashes");
|
||||
let half = 2f64.powi(-14);
|
||||
let along = |x: f64, lengths: &[f64]| dashed(vec![line(p(0.0, 0.0), p(x, 0.0))], false, lengths, 0.0).validate();
|
||||
along(122.0703125, &[half, half]).unwrap();
|
||||
assert_eq!(along(122.0703125f64.next_up(), &[half, half]), Err(TOO_MANY));
|
||||
// Two dashes a pattern: the same length is twice the count.
|
||||
assert_eq!(along(122.0703125, &[half / 2.0; 4]), Err(TOO_MANY));
|
||||
along(61.03515625, &[half / 2.0; 4]).unwrap();
|
||||
// A quarter turn of radius 100 is 157 mm long; its chord is 141 mm.
|
||||
let quarter = vec![Seg2::Arc { center: p(0.0, 0.0), radius: 100.0, start: 0.0, sweep: FRAC_PI_2 }];
|
||||
assert_eq!(dashed(quarter, false, &[7.5e-5, 7.5e-5], 0.0).validate(), Err(TOO_MANY));
|
||||
along(141.5, &[7.5e-5, 7.5e-5]).unwrap();
|
||||
}
|
||||
|
||||
/// A pattern is written only when a stroke has one, so a solid stroke reads and writes as before;
|
||||
/// unknown fields in it are refused.
|
||||
#[test]
|
||||
fn a_pattern_round_trips_and_a_solid_stroke_has_none() {
|
||||
let scene = dashed(rectangle(p(20.0, 10.0), p(410.0, 287.0)).segs, true, &[4.2, 1.05], 0.5);
|
||||
scene.validate().unwrap();
|
||||
let value = serde_json::to_value(&scene).unwrap();
|
||||
assert_eq!(value["groups"][0]["items"][0]["pattern"], json!({"lengths_mm": [4.2, 1.05], "phase_mm": 0.5}));
|
||||
assert_eq!(serde_json::from_value::<Scene>(value.clone()).unwrap(), scene);
|
||||
let mut v = value.clone();
|
||||
v["groups"][0]["items"][0]["pattern"]["unit"] = json!("mm");
|
||||
assert!(serde_json::from_value::<Scene>(v).is_err());
|
||||
let solid = serde_json::to_value(a3()).unwrap();
|
||||
assert!(solid["groups"][0]["items"][0].get("pattern").is_none());
|
||||
}
|
||||
|
||||
/// On the grid a pattern is in whole steps: a length under half a step is one step, counted, and
|
||||
/// the phase, rounded on its own, is taken within the rounded pattern.
|
||||
#[test]
|
||||
fn a_pattern_on_the_grid_is_in_whole_steps() {
|
||||
let stroke = |lengths: &[f64], phase, grid| {
|
||||
let on = dashed(vec![line(p(0.0, 0.0), p(100.0, 0.0))], false, lengths, phase).prepare().unwrap().on_grid(grid).unwrap();
|
||||
let GridItem::Stroke { dashes: Some(dashes), .. } = &on.groups[0].items[0] else { panic!("{:?}", on.groups[0].items[0]) };
|
||||
(dashes.clone(), on.report.dashes_snapped)
|
||||
};
|
||||
let millimetre = Grid::new(1.0).unwrap();
|
||||
let grid_dashes = |lengths: &[i64], phase| GridDashes { lengths: lengths.to_vec(), phase };
|
||||
assert_eq!(stroke(&[4.2, 1.05], 0.5, Grid::NANOMETRE), (grid_dashes(&[4_200_000, 1_050_000], 500_000), 0));
|
||||
assert_eq!(stroke(&[4.2, 1.05], 0.5, millimetre), (grid_dashes(&[4, 1], 1), 0));
|
||||
assert_eq!(stroke(&[0.4, 0.3, 2.0, 0.5], 0.0, millimetre), (grid_dashes(&[1, 1, 2, 1], 0), 2));
|
||||
// 2.7 rounds to 3, past the rounded pattern's 2: a step into it.
|
||||
assert_eq!(stroke(&[1.4, 1.4], 2.7, millimetre), (grid_dashes(&[1, 1], 1), 0));
|
||||
}
|
||||
+21
-21
@@ -571,36 +571,36 @@ impl Seg2 {
|
||||
Seg2::Cubic { .. } | Seg2::Conic { .. } | Seg2::Bezier { .. } => self.integrate(|s, t| 0.5 * s.point_at(t).cross(s.derivative(t))),
|
||||
}
|
||||
}
|
||||
/// Polyline approximation (including both end points) with at most `tol` chord error.
|
||||
pub fn polyline(&self, tol: f64) -> Vec<Vec2> {
|
||||
/// How many equal steps of `t` keep every chord within `tol` (above 0) of the segment, unrounded
|
||||
/// and with no floor or cap: an arc by its chord's bulge, the others by the largest second
|
||||
/// difference of their controls (Wang's bound).
|
||||
pub fn chords(&self, tol: f64) -> f64 {
|
||||
// A chord over 1/k of t strays at most an eighth of the second derivative's bound over k².
|
||||
let bound = |d2: f64| (d2 / (8.0 * tol)).sqrt();
|
||||
match *self {
|
||||
Seg2::Line { a, b } => vec![a, b],
|
||||
Seg2::Line { .. } => 1.0,
|
||||
Seg2::Arc { radius, sweep, .. } => {
|
||||
let tol = tol.max(radius.abs() * 1e-6).max(1e-9);
|
||||
let step = if tol < radius { 2.0 * (1.0 - tol / radius).clamp(-1.0, 1.0).acos() } else { TAU / 8.0 };
|
||||
let n = ((sweep.abs() / step.max(1e-6)).ceil() as usize).clamp(2, 4096);
|
||||
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => {
|
||||
// Chord error of n pieces ≈ max second difference / (8 n²).
|
||||
let bow = (p0 - p1 * 2.0 + p2).len().max((p1 - p2 * 2.0 + p3).len()) * 6.0;
|
||||
let n = ((bow / (8.0 * tol.max(1e-9))).sqrt().ceil() as usize).clamp(2, 4096);
|
||||
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
|
||||
}
|
||||
Seg2::Conic { a, apex, b, w } => {
|
||||
let bow = (a - apex * 2.0 + b).len() * 2.0 * w.max(1.0);
|
||||
let n = ((bow / (8.0 * tol.max(1e-9))).sqrt().ceil() as usize).clamp(2, 4096);
|
||||
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
|
||||
sweep.abs() / if tol < radius { 2.0 * (1.0 - tol / radius).clamp(-1.0, 1.0).acos() } else { TAU / 8.0 }
|
||||
}
|
||||
Seg2::Cubic { p0, p1, p2, p3 } => bound((p0 - p1 * 2.0 + p2).len().max((p1 - p2 * 2.0 + p3).len()) * 6.0),
|
||||
Seg2::Conic { a, apex, b, w } => bound((a - apex * 2.0 + b).len() * 2.0 * w.max(1.0)),
|
||||
Seg2::Bezier { n, ref p } => {
|
||||
// Second derivative ≤ n(n−1) × the largest second difference of the controls.
|
||||
let c = Self::bez(n, p);
|
||||
let d2 = c.windows(3).map(|w| (w[0] - w[1] * 2.0 + w[2]).len()).fold(0.0, f64::max) * (n as f64) * (n as f64 - 1.0);
|
||||
let k = ((d2 / (8.0 * tol.max(1e-9))).sqrt().ceil() as usize).clamp(2, 4096);
|
||||
(0..=k).map(|i| self.point_at(i as f64 / k as f64)).collect()
|
||||
bound(c.windows(3).map(|w| (w[0] - w[1] * 2.0 + w[2]).len()).fold(0.0, f64::max) * (n as f64) * (n as f64 - 1.0))
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Polyline approximation (including both end points) with at most `tol` chord error
|
||||
/// ([`Seg2::chords`]) in 2 to 4096 pieces, an arc's tolerance at least a millionth of its radius.
|
||||
pub fn polyline(&self, tol: f64) -> Vec<Vec2> {
|
||||
if let Seg2::Line { a, b } = *self {
|
||||
return vec![a, b];
|
||||
}
|
||||
let tol = if let Seg2::Arc { radius, .. } = *self { tol.max(radius.abs() * 1e-6) } else { tol }.max(1e-9);
|
||||
let n = (self.chords(tol).ceil() as usize).clamp(2, 4096);
|
||||
(0..=n).map(|i| self.point_at(i as f64 / n as f64)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A closed loop of segments, each starting where the previous one ends.
|
||||
|
||||
@@ -22,6 +22,12 @@ serde_json = { workspace = true }
|
||||
sha2 = { workspace = true }
|
||||
chardetng = { workspace = true }
|
||||
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.
|
||||
|
||||
@@ -664,6 +664,22 @@ pub fn read_stl(bytes: &[u8]) -> Result<Vec<[[f32; 3]; 3]>> {
|
||||
/// Most triangles we read from one STL file.
|
||||
pub const MAX_STL_TRIANGLES: usize = 20_000_000;
|
||||
|
||||
/// `secs` since 1970 as (year, month, day, hour, minute, second) in UTC: crash reports' stamps and
|
||||
/// sheet PDFs' dates.
|
||||
pub fn civil(secs: u64) -> (i64, i64, i64, u64, u64, u64) {
|
||||
let days = i64::try_from(secs / 86_400).unwrap_or(0);
|
||||
let rem = secs % 86_400;
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
(yoe + era * 400 + i64::from(m <= 2), m, d, rem / 3600, rem % 3600 / 60, rem % 60)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
+53
-14
@@ -550,30 +550,69 @@ outer
|
||||
});
|
||||
}
|
||||
|
||||
/// 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<u8> {
|
||||
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 }] };
|
||||
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() {
|
||||
use solidcraft_geom::paper::{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 items = vec![
|
||||
Item::Stroke { path: border.segs.clone(), closed: true, width_mm: 0.7 },
|
||||
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 },
|
||||
Item::Fill { region: Region2 { outer: border, holes: vec![] } },
|
||||
];
|
||||
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 write = |b: &[u8]| -> Option<usize> {
|
||||
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 written as a 25 dpi sheet PNG: an error or an image, never a panic.
|
||||
#[test]
|
||||
fn paper_scenes_survive_mutation_into_png() {
|
||||
let json = paper_scene_json();
|
||||
let options = crate::paper::PngOptions { dpi: 25.0, colour: crate::paper::PngColour::Grey };
|
||||
let write = |b: &[u8]| -> Option<usize> {
|
||||
let scene: solidcraft_geom::paper::Scene = serde_json::from_slice(b).ok()?;
|
||||
let mut out = Vec::new();
|
||||
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 { layers: true, title: Some("Sheet 1".into()), output_time: Some(1_761_436_800) };
|
||||
let write = |b: &[u8]| -> Option<usize> {
|
||||
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+/";
|
||||
|
||||
+24
-1
@@ -1,5 +1,28 @@
|
||||
//! A sheet's paper scene (`geom::paper`) in a file: SVG first (A3, #4890); DXF, PNG 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$}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
//! A paper scene as a vector PDF (#4890, P1): one page the sheet's size, its lines and fills,
|
||||
//! geometry and optional-content layers (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.
|
||||
//! - **Layers:** nonempty groups share one PDF optional-content group for each
|
||||
//! distinct paper object kind. Group order remains the original paint order,
|
||||
//! and each kind's PDF layer uses ObjectKind::layer, as in DXF. Empty
|
||||
//! groups do not invent layers. Consecutive painted groups of the same kind
|
||||
//! share one marked-content run; empty groups do not interrupt it. All present
|
||||
//! layers start visible.
|
||||
//! Set [`PdfOptions::layers`] to false for the same vector marks without layers.
|
||||
//! - **Content size:** every append checks the cumulative byte limit before growing the
|
||||
//! buffer, including inside a path/arc and the final graphics-state restore. Allocation
|
||||
//! failure is an error. The limit is for uncompressed content, not total export memory.
|
||||
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
use std::io::Write as _;
|
||||
|
||||
use flate2::Compression;
|
||||
use flate2::write::ZlibEncoder;
|
||||
use pdf_writer::{Date, Filter, Name, Pdf, Rect, Ref, TextStr};
|
||||
use solidcraft_geom::paper::{Grid, GridDashes, GridGroup, GridItem, GridPath, GridPoint, GridReport, ObjectKind, 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, PartialEq, Eq)]
|
||||
pub struct PdfOptions {
|
||||
/// The document's title, left out when `None` or empty.
|
||||
pub title: Option<String>,
|
||||
/// 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<u64>,
|
||||
/// Include optional-content layers by object kind (default true). False writes
|
||||
/// the same vector marks in paint order, without layer objects or markers.
|
||||
pub layers: bool,
|
||||
}
|
||||
|
||||
impl Default for PdfOptions {
|
||||
fn default() -> Self {
|
||||
Self { title: None, output_time: None, layers: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<u8>, 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 layers = if options.layers { collect_layers(&on.groups)? } else { Vec::new() };
|
||||
let content = content_with_limit_and_layers(&on.groups, options.layers.then_some(layers.as_slice()), MAX_DRAWING_BYTES)?;
|
||||
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();
|
||||
{
|
||||
let mut root = pdf.catalog(catalog);
|
||||
root.pages(tree);
|
||||
if !layers.is_empty() {
|
||||
// PDF 1.5 optional content: one group per used paper object kind.
|
||||
// The default configuration orders all layers and starts them ON.
|
||||
let mut properties = root.insert(Name(b"OCProperties")).dict();
|
||||
properties.insert(Name(b"OCGs")).array().items(layers.iter().map(|l| l.reference));
|
||||
let mut default = properties.insert(Name(b"D")).dict();
|
||||
default.insert(Name(b"Order")).array().items(layers.iter().map(|l| l.reference));
|
||||
default.insert(Name(b"ON")).array().items(layers.iter().map(|l| l.reference));
|
||||
default.pair(Name(b"BaseState"), Name(b"ON"));
|
||||
}
|
||||
}
|
||||
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);
|
||||
{
|
||||
let mut resources = writer.resources();
|
||||
if !layers.is_empty() {
|
||||
let mut properties = resources.insert(Name(b"Properties")).dict();
|
||||
for layer in &layers {
|
||||
properties.pair(Name(layer.tag.as_bytes()), layer.reference);
|
||||
}
|
||||
}
|
||||
}
|
||||
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);
|
||||
for layer in &layers {
|
||||
let mut group = pdf.indirect(layer.reference).dict();
|
||||
group.pair(Name(b"Type"), Name(b"OCG"));
|
||||
group.pair(Name(b"Name"), TextStr(layer.kind.layer()));
|
||||
}
|
||||
Ok((pdf.finish(), on.report))
|
||||
}
|
||||
|
||||
/// `secs` since 1970 as a PDF date in UTC, refused past the year 9999.
|
||||
fn date(secs: u64) -> Result<Date> {
|
||||
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))
|
||||
}
|
||||
|
||||
/// One PDF layer for every kind with actual paper marks, in first paint order.
|
||||
struct Layer {
|
||||
kind: ObjectKind,
|
||||
reference: Ref,
|
||||
tag: String,
|
||||
}
|
||||
|
||||
fn collect_layers(groups: &[GridGroup]) -> Result<Vec<Layer>> {
|
||||
let mut layers: Vec<Layer> = Vec::new();
|
||||
for group in groups.iter().filter(|group| !group.items.is_empty()) {
|
||||
if layers.iter().any(|layer| layer.kind == group.kind) {
|
||||
continue;
|
||||
}
|
||||
layers.try_reserve(1).map_err(|_| IoError::Invalid("the sheet PDF: cannot allocate its layer list".into()))?;
|
||||
let index = i32::try_from(layers.len()).ok().and_then(|n| n.checked_add(6)).ok_or_else(|| IoError::Invalid("too many PDF layers".into()))?;
|
||||
layers.push(Layer { kind: group.kind, reference: Ref::new(index), tag: format!("L{}", layers.len()) });
|
||||
}
|
||||
Ok(layers)
|
||||
}
|
||||
|
||||
/// The page's content stream: the scene in millimetres, scaled to points once.
|
||||
#[cfg(test)]
|
||||
fn content(groups: &[GridGroup]) -> Result<String> {
|
||||
content_with_limit(groups, MAX_DRAWING_BYTES)
|
||||
}
|
||||
|
||||
// The private seam permits smaller test limits, never a higher production cap.
|
||||
#[cfg(test)]
|
||||
fn content_with_limit(groups: &[GridGroup], max_bytes: usize) -> Result<String> {
|
||||
let layers = collect_layers(groups)?;
|
||||
content_with_limit_and_layers(groups, Some(&layers), max_bytes)
|
||||
}
|
||||
|
||||
fn content_with_limit_and_layers(groups: &[GridGroup], layers: Option<&[Layer]>, max_bytes: usize) -> Result<String> {
|
||||
let mut w = Content::new(max_bytes)?;
|
||||
w.append(&format!("q {PT_PER_MM:.9} 0 0 {PT_PER_MM:.9} 0 0 cm 0 J 0 j 4 M\n"))?;
|
||||
let mut active_kind = None;
|
||||
for group in groups.iter().filter(|group| !group.items.is_empty()) {
|
||||
if let Some(layers) = layers {
|
||||
let layer = layers.iter().find(|layer| layer.kind == group.kind).ok_or_else(|| IoError::Invalid("missing paper PDF layer".into()))?;
|
||||
if active_kind != Some(group.kind) {
|
||||
if active_kind.is_some() {
|
||||
w.append("EMC\n")?;
|
||||
}
|
||||
w.append("/OC /")?;
|
||||
w.append(&layer.tag)?;
|
||||
w.append(" BDC\n")?;
|
||||
active_kind = Some(group.kind);
|
||||
}
|
||||
}
|
||||
for item in &group.items {
|
||||
match item {
|
||||
GridItem::Stroke { width, path, dashes } => {
|
||||
if w.width != Some(*width) {
|
||||
w.number(*width)?;
|
||||
w.append(" 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.append(if path.closed { "s\n" } else { "S\n" })?;
|
||||
}
|
||||
GridItem::Fill { loops } => {
|
||||
for l in loops {
|
||||
w.path(l)?;
|
||||
w.append("h\n")?;
|
||||
}
|
||||
w.append("f*\n")?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if active_kind.is_some() {
|
||||
w.append("EMC\n")?;
|
||||
}
|
||||
w.append("Q\n")?;
|
||||
Ok(w.out)
|
||||
}
|
||||
|
||||
// One growth path for every operand/operator. Reserve geometrically, capped at
|
||||
// the allowance, rather than repeatedly reallocating for individual numbers.
|
||||
fn append_bounded(out: &mut String, text: &str, max_bytes: usize) -> Result<()> {
|
||||
let length = out
|
||||
.len()
|
||||
.checked_add(text.len())
|
||||
.filter(|&n| n <= max_bytes)
|
||||
.ok_or_else(|| IoError::Invalid(format!("the PDF's drawing would be over {max_bytes} bytes")))?;
|
||||
if length > out.capacity() {
|
||||
let capacity = out.capacity().saturating_mul(2).max(length).min(max_bytes);
|
||||
out.try_reserve_exact(capacity - out.len())
|
||||
.map_err(|_| IoError::Invalid("the sheet PDF: cannot allocate its bounded content buffer".into()))?;
|
||||
}
|
||||
out.push_str(text);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Content {
|
||||
out: String,
|
||||
max_bytes: usize,
|
||||
// Reuse a small buffer for the existing shared integer formatter. Any i64
|
||||
// on this grid needs at most 21 bytes, including a minus sign and point.
|
||||
number_text: String,
|
||||
/// The stroke width and dash pattern last set, so each is written only when it changes.
|
||||
width: Option<i64>,
|
||||
dashes: Option<GridDashes>,
|
||||
}
|
||||
|
||||
impl Content {
|
||||
fn new(max_bytes: usize) -> Result<Self> {
|
||||
let mut number_text = String::new();
|
||||
number_text.try_reserve_exact(32).map_err(|_| IoError::Invalid("the sheet PDF: cannot allocate its number buffer".into()))?;
|
||||
Ok(Self { out: String::new(), max_bytes: max_bytes.min(MAX_DRAWING_BYTES), number_text, width: None, dashes: None })
|
||||
}
|
||||
|
||||
fn append(&mut self, text: &str) -> Result<()> {
|
||||
append_bounded(&mut self.out, text, self.max_bytes)
|
||||
}
|
||||
|
||||
fn number(&mut self, n: i64) -> Result<()> {
|
||||
self.number_text.clear();
|
||||
push_mm(&mut self.number_text, n, DECIMALS);
|
||||
append_bounded(&mut self.out, &self.number_text, self.max_bytes)
|
||||
}
|
||||
|
||||
fn point(&mut self, p: GridPoint) -> Result<()> {
|
||||
self.number(p.x)?;
|
||||
self.append(" ")?;
|
||||
self.number(p.y)?;
|
||||
self.append(" ")
|
||||
}
|
||||
|
||||
/// `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 })
|
||||
}
|
||||
|
||||
/// A dash pattern `[on off ...] phase d`, or a solid line `[] 0 d`.
|
||||
fn dashes(&mut self, dashes: Option<&GridDashes>) -> Result<()> {
|
||||
self.append("[")?;
|
||||
if let Some(d) = dashes {
|
||||
for (i, length) in d.lengths.iter().enumerate() {
|
||||
if i > 0 {
|
||||
self.append(" ")?;
|
||||
}
|
||||
self.number(*length)?;
|
||||
}
|
||||
}
|
||||
self.append("] ")?;
|
||||
self.number(dashes.map_or(0, |d| d.phase))?;
|
||||
self.append(" 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.append("m\n")?;
|
||||
let mut at = path.start;
|
||||
for piece in &path.pieces {
|
||||
match *piece {
|
||||
Piece::Line { to } => {
|
||||
self.point(to)?;
|
||||
self.append("l\n")?;
|
||||
}
|
||||
Piece::Cubic { c1, c2, to } => {
|
||||
self.point(c1)?;
|
||||
self.point(c2)?;
|
||||
self.point(to)?;
|
||||
self.append("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.append("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.append("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<usize> {
|
||||
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;
|
||||
@@ -0,0 +1,788 @@
|
||||
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<Item>) -> Scene {
|
||||
Scene { size_mm: size, groups: vec![Group { object: 1, kind: ObjectKind::DrawingBorder, items }] }
|
||||
}
|
||||
|
||||
fn stroke(path: Vec<Seg2>, closed: bool, width_mm: f64, pattern: Option<Dashes>) -> Item {
|
||||
Item::Stroke { path, closed, width_mm, pattern }
|
||||
}
|
||||
|
||||
fn pdf(scene: &Scene, options: &PdfOptions) -> Vec<u8> {
|
||||
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<f64>)> {
|
||||
let spaced = content.replace('[', " [ ").replace(']', " ] ");
|
||||
let mut ops = Vec::new();
|
||||
let mut operands = Vec::new();
|
||||
for token in spaced.split_whitespace() {
|
||||
match token.parse::<f64>() {
|
||||
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 { layers: true, 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<f64> = 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 { layers: true, 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 { layers: true, 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}");
|
||||
}
|
||||
|
||||
/// Check this writer's single xref subsection using byte positions, never decoded text.
|
||||
/// This intentionally checks our emitted layout, not arbitrary third-party PDFs.
|
||||
fn check_xref(bytes: &[u8]) -> std::result::Result<usize, String> {
|
||||
let marker = b"startxref\n";
|
||||
let at = bytes.windows(marker.len()).rposition(|w| w == marker).ok_or("missing startxref")? + marker.len();
|
||||
let number = bytes.get(at..).ok_or("missing xref offset")?.split(|b| b.is_ascii_whitespace()).next().ok_or("missing xref offset")?;
|
||||
let start: usize = std::str::from_utf8(number).map_err(|_| "xref offset is not ASCII")?.parse().map_err(|_| "invalid xref offset")?;
|
||||
let tail = bytes.get(start..).ok_or("xref offset outside file")?;
|
||||
let rest = tail.strip_prefix(b"xref\n0 ").ok_or("xref offset is not the expected subsection")?;
|
||||
let end_of_count = rest.iter().position(|&c| c == b'\n').ok_or("truncated xref count")?;
|
||||
let count: usize =
|
||||
std::str::from_utf8(&rest[..end_of_count]).map_err(|_| "xref count is not ASCII")?.parse().map_err(|_| "invalid xref count")?;
|
||||
// Five fixed objects plus up to five distinct current ObjectKinds, and the free object.
|
||||
if !(6..=11).contains(&count) {
|
||||
return Err(format!("unexpected PDF object count {count}"));
|
||||
}
|
||||
let table = rest.get(end_of_count + 1..).ok_or("truncated xref table")?;
|
||||
let entry_bytes = count.checked_mul(20).ok_or("xref count overflow")?;
|
||||
let entries = table.get(..entry_bytes).ok_or("truncated xref entries")?;
|
||||
let (entries, remainder) = entries.as_chunks::<20>();
|
||||
if !remainder.is_empty() {
|
||||
return Err("xref entry does not occupy 20 bytes".into());
|
||||
}
|
||||
for (n, entry) in entries.iter().enumerate() {
|
||||
if ![&b" \n"[..], &b"\r\n"[..]].contains(&&entry[18..]) {
|
||||
return Err(format!("entry {n} does not occupy 20 bytes"));
|
||||
}
|
||||
if n == 0 {
|
||||
if &entry[..18] != b"0000000000 65535 f" {
|
||||
return Err("invalid free entry".into());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if &entry[10..18] != b" 00000 n" {
|
||||
return Err(format!("object {n} is not in use"));
|
||||
}
|
||||
let offset: usize =
|
||||
std::str::from_utf8(&entry[..10]).map_err(|_| "object offset is not ASCII")?.parse().map_err(|_| "invalid object offset")?;
|
||||
let expected = format!("{n} 0 obj\n");
|
||||
if offset >= start || !bytes.get(offset..).is_some_and(|tail| tail.starts_with(expected.as_bytes())) {
|
||||
return Err(format!("object {n} does not start at byte {offset}"));
|
||||
}
|
||||
}
|
||||
Ok(start)
|
||||
}
|
||||
|
||||
/// Geometry/paint use the 10 nm grid; the one unit transform has its own accuracy.
|
||||
/// Expectations are independent of the writer's constants and formatting helper.
|
||||
fn check_number_grid(content: &str) -> std::result::Result<(), String> {
|
||||
let spaced = content.replace('[', " [ ").replace(']', " ] ");
|
||||
let mut operands = Vec::new();
|
||||
let mut transforms = 0;
|
||||
for token in spaced.split_whitespace() {
|
||||
if let Ok(value) = token.parse::<f64>() {
|
||||
if !value.is_finite() || token.contains(['e', 'E']) || (value == 0.0 && token.starts_with('-')) {
|
||||
return Err(format!("invalid emitted number {token}"));
|
||||
}
|
||||
operands.push((token, value));
|
||||
} else if token != "[" && token != "]" {
|
||||
let decimals = if token == "cm" { 9 } else { 5 };
|
||||
if operands.iter().any(|(raw, _)| raw.split_once('.').is_some_and(|(_, fraction)| fraction.len() > decimals)) {
|
||||
return Err(format!("too many decimals for {token}: {operands:?}"));
|
||||
}
|
||||
if token == "cm" {
|
||||
transforms += 1;
|
||||
let values: Vec<_> = operands.iter().map(|(_, n)| *n).collect();
|
||||
let [sx, xy, yx, sy, tx, ty] = values.as_slice() else { return Err("cm needs six numbers".into()) };
|
||||
if sx != sy || [*xy, *yx, *tx, *ty] != [0.0; 4] {
|
||||
return Err("the page transform must be one uniform scale, without a flip or translation".into());
|
||||
}
|
||||
// 72 / 25.4 = 360 / 127. Across 5,000 mm the written scale may
|
||||
// contribute at most 1e-6 mm; this does not certify a viewer or printer.
|
||||
if (sx * 127.0 / 360.0 - 1.0).abs() * 5000.0 > 1e-6 {
|
||||
return Err("the written millimetre-to-point scale is insufficiently accurate".into());
|
||||
}
|
||||
}
|
||||
operands.clear();
|
||||
}
|
||||
}
|
||||
if transforms != 1 || !operands.is_empty() {
|
||||
return Err("expected exactly one complete page transform".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 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)]);
|
||||
for title in ["ASCII", "\u{00c7}", "\u{65e5}\u{672c}\u{1f642}", "(sheet 1) \\ title"] {
|
||||
let bytes = pdf(&sheet, &PdfOptions { layers: true, title: Some(title.into()), output_time: Some(0) });
|
||||
assert!(check_xref(&bytes).is_ok(), "{title:?}: {:?}", check_xref(&bytes));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_byte_offset_oracle_refuses_shifted_or_corrupted_references() {
|
||||
let bytes = pdf(&scene(p(420.0, 297.0), vec![]), &PdfOptions { layers: true, title: Some("\u{00c7}".into()), output_time: None });
|
||||
let start = check_xref(&bytes).unwrap();
|
||||
let mut shifted = bytes.clone();
|
||||
shifted.insert(9, b' ');
|
||||
assert!(check_xref(&shifted).is_err(), "inserting a byte must invalidate the old offsets");
|
||||
let mut wrong = bytes;
|
||||
let first_object = start + b"xref\n0 6\n".len() + 20;
|
||||
wrong[first_object..first_object + 10].copy_from_slice(b"0000000001");
|
||||
assert!(check_xref(&wrong).is_err(), "an object offset into the header must fail");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_number_oracle_separates_page_scale_from_the_coordinate_grid() {
|
||||
let prefix = "q 2.834645669 0 0 2.834645669 0 0 cm ";
|
||||
let valid = format!("{prefix}0.35 w [4.2 1.05] 0.5 d 0 0 m 4999.12345 5000 l S Q");
|
||||
assert!(check_number_grid(&valid).is_ok());
|
||||
for bad in [
|
||||
valid.replace("4999.12345", "4999.123456"),
|
||||
valid.replace("0.35 w", "0.350001 w"),
|
||||
valid.replace("4.2 1.05", "4.200001 1.05"),
|
||||
valid.replace("2.834645669", "2.83465"),
|
||||
valid.replace("0.35 w", "3.5e-1 w"),
|
||||
valid.replace("0.35 w", "NaN w"),
|
||||
valid.replace("0 0 m", "-0 0 m"),
|
||||
format!("{prefix}{valid}"),
|
||||
"q 0 0 m 1 1 l S Q".into(),
|
||||
] {
|
||||
assert!(check_number_grid(&bad).is_err(), "fault escaped the oracle: {bad}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Arcs are cubics within a ten-thousandth of a millimetre, from a 0.5 mm radius to 5 m, and a
|
||||
/// parabola is its cubic; geometry/paint have five decimals, and the page scale is checked separately.
|
||||
#[test]
|
||||
fn arcs_are_cubics_within_a_ten_thousandth_of_a_millimetre() {
|
||||
for (c, radius, start, sweep) in [
|
||||
(p(2500.0, 2500.0), 0.5, 0.4, TAU),
|
||||
(p(2500.0, 2500.0), 40.0, 0.4, TAU),
|
||||
(p(2500.0, 2500.0), 300.0, 0.4, 2.5),
|
||||
(p(2500.0, 2500.0), 2000.0, 0.4, 0.3),
|
||||
(p(2500.0, 2500.0), 40.0, 0.4, -2.5),
|
||||
(p(0.0, 0.0), 5000.0, 0.0, FRAC_PI_2),
|
||||
] {
|
||||
let arc = scene(p(5000.0, 5000.0), vec![stroke(vec![Seg2::Arc { center: c, radius, start, sweep }], false, 0.35, None)]);
|
||||
let content = content(&pdf(&arc, &NONE));
|
||||
let cubics = cubics(&content);
|
||||
assert!(cubics.len() >= (sweep.abs() / FRAC_PI_2).ceil() as usize, "{radius}: {}", cubics.len());
|
||||
assert!(cubics.first().unwrap()[0].dist(c + Vec2::from_angle(start) * radius) <= 1e-5);
|
||||
assert!(cubics.last().unwrap()[3].dist(c + Vec2::from_angle(start + sweep) * radius) <= 1e-5);
|
||||
for cubic in &cubics {
|
||||
for k in 0..=64 {
|
||||
let off = (bezier(*cubic, f64::from(k) / 64.0).dist(c) - radius).abs();
|
||||
assert!(off <= 1e-4, "r {radius}: {off} mm off at {k}/64");
|
||||
}
|
||||
}
|
||||
assert!(check_number_grid(&content).is_ok(), "{:?}: {content}", check_number_grid(&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 { layers: true, title: Some("x".repeat(1000)), output_time: None }).is_ok());
|
||||
let e = paper_pdf(&prepared, &PdfOptions { layers: true, title: Some("x".repeat(1001)), output_time: None }).unwrap_err();
|
||||
assert!(e.to_string().contains("1000 characters"), "{e}");
|
||||
let e = paper_pdf(&prepared, &PdfOptions { layers: true, title: None, output_time: Some(MAX_OUTPUT_TIME + 1) }).unwrap_err();
|
||||
assert!(e.to_string().contains("9999"), "{e}");
|
||||
}
|
||||
|
||||
// Small private limits exercise the real content writer without allocating a
|
||||
// maximum-sized scene. They can tighten, never raise, the production ceiling.
|
||||
#[test]
|
||||
fn content_budget_includes_the_header_and_the_final_graphics_restore() {
|
||||
let expected = "q 2.834645669 0 0 2.834645669 0 0 cm 0 J 0 j 4 M\nQ\n";
|
||||
assert_eq!(super::content_with_limit(&[], expected.len()).unwrap(), expected);
|
||||
for limit in 0..expected.len() {
|
||||
assert!(super::content_with_limit(&[], limit).is_err(), "accepted {limit} bytes for an empty sheet's stream");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_budget_stops_inside_one_long_path_before_its_paint_operator() {
|
||||
let path = GridPath {
|
||||
start: GridPoint { x: 0, y: 0 },
|
||||
pieces: (1..=128).map(|i| Piece::Line { to: GridPoint { x: i * 100_000, y: 0 } }).collect(),
|
||||
closed: false,
|
||||
};
|
||||
let mut writer = Content::new(96).unwrap();
|
||||
assert!(writer.path(&path).is_err(), "the path must stop before the whole item is built");
|
||||
assert!(writer.out.len() <= 96, "oversized partial content was allocated");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_budget_stops_inside_one_arcs_cubic_expansion() {
|
||||
// The arc is already in grid steps, as Piece::seg supplies it. A 5 m
|
||||
// quarter circle needs several cubics; even one input piece must be bounded.
|
||||
let mut writer = Content::new(64).unwrap();
|
||||
let arc = Seg2::Arc { center: Vec2::ZERO, radius: 500_000_000.0, start: 0.0, sweep: FRAC_PI_2 };
|
||||
assert!(writer.arc(arc, GridPoint { x: 0, y: 500_000_000 }).is_err());
|
||||
assert!(writer.out.len() <= 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_budget_is_cumulative_over_groups_and_fill_loops() {
|
||||
let square = Loop2::polygon(&[p(0.0, 0.0), p(2.0, 0.0), p(2.0, 2.0), p(0.0, 2.0)]);
|
||||
let source = Scene {
|
||||
size_mm: p(20.0, 20.0),
|
||||
groups: vec![
|
||||
Group { object: 1, kind: ObjectKind::DrawingBorder, items: vec![stroke(square.segs.clone(), true, 0.35, None)] },
|
||||
Group { object: 2, kind: ObjectKind::TitleBlock, items: vec![Item::Fill { region: Region2 { outer: square, holes: vec![] } }] },
|
||||
],
|
||||
};
|
||||
let on = source.prepare().unwrap().on_grid(Grid::TEN_NANOMETRES).unwrap();
|
||||
let complete = super::content(&on.groups).unwrap();
|
||||
assert_eq!(super::content_with_limit(&on.groups, complete.len()).unwrap(), complete);
|
||||
assert!(super::content_with_limit(&on.groups, complete.len() - 1).is_err(), "the final Q is part of the cumulative limit");
|
||||
let first = super::content(&on.groups[..1]).unwrap();
|
||||
assert!(super::content_with_limit(&on.groups, first.len()).is_err(), "groups must share one allowance");
|
||||
assert_eq!(Content::new(usize::MAX).unwrap().max_bytes, MAX_DRAWING_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_budget_rejects_an_append_before_mutating_existing_bytes() {
|
||||
let mut w = Content::new(4).unwrap();
|
||||
w.append("abc").unwrap();
|
||||
assert!(w.append("de").is_err());
|
||||
assert_eq!(w.out, "abc");
|
||||
w.append("d").unwrap();
|
||||
assert_eq!(w.out, "abcd");
|
||||
w.append("").unwrap();
|
||||
assert!(w.append("e").is_err());
|
||||
assert_eq!(w.out, "abcd");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_budget_reuses_the_original_formatter_at_integer_extremes() {
|
||||
for (n, expected) in [
|
||||
(0, "0"),
|
||||
(1, "0.00001"),
|
||||
(-1, "-0.00001"),
|
||||
(100_000, "1"),
|
||||
(-100_000, "-1"),
|
||||
(i64::MAX, "92233720368547.75807"),
|
||||
(i64::MIN, "-92233720368547.75808"),
|
||||
] {
|
||||
let mut w = Content::new(expected.len()).unwrap();
|
||||
w.number(n).unwrap();
|
||||
assert_eq!(w.out, expected);
|
||||
let mut too_small = Content::new(expected.len() - 1).unwrap();
|
||||
assert!(too_small.number(n).is_err());
|
||||
assert!(too_small.out.is_empty());
|
||||
}
|
||||
}
|
||||
/// P3: one optional-content group per nonempty kind, shared across repeats.
|
||||
/// The scene's drawing order remains the content stream's paint order.
|
||||
#[test]
|
||||
fn pdf_layers_share_object_kinds_and_keep_noncontiguous_paint_order() {
|
||||
let path = |y: f64| vec![Seg2::Line { a: p(10.0, y), b: p(100.0, y) }];
|
||||
let sheet = Scene {
|
||||
size_mm: p(210.0, 297.0),
|
||||
groups: vec![
|
||||
Group { object: 10, kind: ObjectKind::TitleBlock, items: vec![stroke(path(10.0), false, 0.35, None)] },
|
||||
Group { object: 20, kind: ObjectKind::DrawingBorder, items: vec![stroke(path(20.0), false, 0.35, None)] },
|
||||
Group { object: 11, kind: ObjectKind::TitleBlock, items: vec![stroke(path(30.0), false, 0.35, None)] },
|
||||
Group { object: 30, kind: ObjectKind::SheetBorder, items: vec![] },
|
||||
],
|
||||
};
|
||||
let bytes = pdf(&sheet, &NONE);
|
||||
assert!(check_xref(&bytes).is_ok(), "{:?}", check_xref(&bytes));
|
||||
assert_eq!(pdf(&sheet, &NONE), bytes, "layer order and object ids must be deterministic");
|
||||
let file = text(&bytes);
|
||||
assert!(file.contains("/OCProperties"), "the catalog must declare optional content");
|
||||
assert!(file.contains("/OCGs [6 0 R 7 0 R]"), "the same kind must reuse its OCG: {file}");
|
||||
assert!(file.contains("/Order [6 0 R 7 0 R]"), "the visible layers are ordered");
|
||||
assert!(file.contains("/ON [6 0 R 7 0 R]"), "both are visible by default");
|
||||
assert!(file.contains("/BaseState /ON"), "the default state is ON");
|
||||
assert!(file.contains("/Name (TITLE_BLOCK)") && file.contains("/Name (DRAWING_BORDER)"));
|
||||
assert!(!file.contains("/Name (SHEET_BORDER)"), "an empty group has no painted layer");
|
||||
assert!(file.contains("/Properties") && file.contains("/L0 6 0 R") && file.contains("/L1 7 0 R"));
|
||||
let stream = content(&bytes);
|
||||
let markers: Vec<_> = stream.lines().filter(|line| line.ends_with(" BDC") || *line == "EMC").collect();
|
||||
assert_eq!(markers, ["/OC /L0 BDC", "EMC", "/OC /L1 BDC", "EMC", "/OC /L0 BDC", "EMC"]);
|
||||
assert_eq!(stream.lines().filter(|line| *line == "S").count(), 3);
|
||||
assert!(check_number_grid(&stream).is_ok());
|
||||
}
|
||||
|
||||
/// Every current paper kind has one independently named layer, without sorting
|
||||
/// noncontiguous groups or losing graphics state across marked-content boundaries.
|
||||
#[test]
|
||||
fn pdf_layers_cover_all_five_kinds_and_preserve_paint_and_styles() {
|
||||
let line = |y: f64| vec![Seg2::Line { a: p(10.0, y), b: p(100.0, y) }];
|
||||
let dashed = Some(Dashes { lengths_mm: vec![4.0, 2.0], phase_mm: 0.0 });
|
||||
let square = Loop2::polygon(&[p(10.0, 30.0), p(20.0, 30.0), p(20.0, 40.0), p(10.0, 40.0)]);
|
||||
let sheet = Scene {
|
||||
size_mm: p(210.0, 297.0),
|
||||
groups: vec![
|
||||
Group { object: 10, kind: ObjectKind::TitleBlock, items: vec![stroke(line(10.0), false, 0.35, None)] },
|
||||
Group { object: 20, kind: ObjectKind::DrawingBorder, items: vec![stroke(line(20.0), false, 0.7, dashed.clone())] },
|
||||
Group { object: 30, kind: ObjectKind::PartsList, items: vec![Item::Fill { region: Region2 { outer: square, holes: vec![] } }] },
|
||||
Group { object: 40, kind: ObjectKind::RevisionTable, items: vec![stroke(line(50.0), false, 0.7, dashed)] },
|
||||
Group { object: 50, kind: ObjectKind::SheetBorder, items: vec![stroke(line(60.0), false, 0.35, None)] },
|
||||
Group { object: 11, kind: ObjectKind::TitleBlock, items: vec![stroke(line(70.0), false, 0.35, None)] },
|
||||
Group { object: 60, kind: ObjectKind::DrawingBorder, items: vec![] },
|
||||
],
|
||||
};
|
||||
let bytes = pdf(&sheet, &NONE);
|
||||
assert_eq!(pdf(&sheet, &NONE), bytes);
|
||||
assert!(check_xref(&bytes).is_ok(), "{:?}", check_xref(&bytes));
|
||||
let file = text(&bytes);
|
||||
for key in ["OCGs", "Order", "ON"] {
|
||||
assert!(file.contains(&format!("/{key} [6 0 R 7 0 R 8 0 R 9 0 R 10 0 R]")), "{file}");
|
||||
}
|
||||
assert!(file.contains("/BaseState /ON"));
|
||||
assert_eq!(file.matches("/Type /OCG\n").count(), 5, "one OCG per kind, with no empty-group duplicate");
|
||||
// Literal expected names and references are independent of ObjectKind::layer.
|
||||
for (number, name) in [(6, "TITLE_BLOCK"), (7, "DRAWING_BORDER"), (8, "PARTS_LIST"), (9, "REVISION_TABLE"), (10, "SHEET_BORDER")] {
|
||||
let header = format!("{number} 0 obj\n");
|
||||
let object = file.split_once(&header).unwrap().1.split_once("endobj").unwrap().0;
|
||||
assert!(object.contains("/Type /OCG") && object.contains(&format!("/Name ({name})")), "{object}");
|
||||
assert_eq!(file.matches(&format!("/Name ({name})")).count(), 1);
|
||||
assert!(file.contains(&format!("/L{} {number} 0 R", number - 6)));
|
||||
}
|
||||
let stream = content(&bytes);
|
||||
let markers: Vec<_> = stream.lines().filter(|line| line.ends_with(" BDC") || *line == "EMC").collect();
|
||||
assert_eq!(
|
||||
markers,
|
||||
["/OC /L0 BDC", "EMC", "/OC /L1 BDC", "EMC", "/OC /L2 BDC", "EMC", "/OC /L3 BDC", "EMC", "/OC /L4 BDC", "EMC", "/OC /L0 BDC", "EMC",]
|
||||
);
|
||||
let operators = ops(&stream);
|
||||
let paints: Vec<_> = operators.iter().map(|(op, _)| op.as_str()).filter(|op| ["S", "h", "f*"].contains(op)).collect();
|
||||
assert_eq!(paints, ["S", "S", "h", "f*", "S", "S", "S"]);
|
||||
let starts: Vec<_> = operators.iter().filter(|(op, _)| op == "m").map(|(_, n)| (n[0], n[1])).collect();
|
||||
assert_eq!(starts, [(10.0, 10.0), (10.0, 20.0), (10.0, 30.0), (10.0, 50.0), (10.0, 60.0), (10.0, 70.0)]);
|
||||
let styles: Vec<(&str, &[f64])> = operators.iter().filter(|(op, _)| op == "w" || op == "d").map(|(op, n)| (op.as_str(), n.as_slice())).collect();
|
||||
assert_eq!(styles, [("w", &[0.35][..]), ("w", &[0.7][..]), ("d", &[4.0, 2.0, 0.0][..]), ("w", &[0.35][..]), ("d", &[0.0][..])]);
|
||||
assert!(check_number_grid(&stream).is_ok());
|
||||
// A reviewer may retain these exact asserted bytes for independent PDF readers.
|
||||
if let Some(path) = std::env::var_os("SOLIDCRAFT_PDF_LAYER_REVIEW_OUTPUT") {
|
||||
let written = std::fs::write(&path, &bytes);
|
||||
assert!(written.is_ok(), "could not write the asserted layer fixture to {path:?}: {written:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// P3: no phantom layer dictionary on a truly empty scene, and content
|
||||
/// limits include all OCG markers instead of silently cutting them off.
|
||||
#[test]
|
||||
fn pdf_layers_obey_content_budget_and_skip_empty_groups() {
|
||||
let empty = scene(p(210.0, 297.0), vec![]);
|
||||
let bytes = pdf(&empty, &NONE);
|
||||
assert!(check_xref(&bytes).is_ok());
|
||||
assert!(!text(&bytes).contains("/OCProperties"));
|
||||
assert!(!content(&bytes).contains(" BDC"));
|
||||
let line = scene(p(210.0, 297.0), vec![stroke(vec![Seg2::Line { a: p(10.0, 10.0), b: p(100.0, 10.0) }], false, 0.35, None)]);
|
||||
let grid = line.prepare().unwrap().on_grid(Grid::TEN_NANOMETRES).unwrap();
|
||||
let full = super::content_with_limit(&grid.groups, MAX_DRAWING_BYTES).unwrap();
|
||||
assert!(full.contains("/OC /L0 BDC") && full.contains("EMC"));
|
||||
assert_eq!(super::content_with_limit(&grid.groups, full.len()).unwrap(), full);
|
||||
assert!(super::content_with_limit(&grid.groups, full.len() - 1).is_err());
|
||||
}
|
||||
|
||||
/// Flat PDF is the same ordered vector paint, not a hidden or rasterized layer.
|
||||
#[test]
|
||||
fn flat_pdf_omits_optional_content_and_preserves_vector_paint() {
|
||||
let line = |y| vec![Seg2::Line { a: p(10.0, y), b: p(100.0, y) }];
|
||||
let sheet = Scene {
|
||||
size_mm: p(210.0, 297.0),
|
||||
groups: vec![
|
||||
Group { object: 1, kind: ObjectKind::TitleBlock, items: vec![stroke(line(10.0), false, 0.35, None)] },
|
||||
Group {
|
||||
object: 2,
|
||||
kind: ObjectKind::DrawingBorder,
|
||||
items: vec![stroke(line(20.0), false, 0.7, Some(Dashes { lengths_mm: vec![4.0, 2.0], phase_mm: 1.0 }))],
|
||||
},
|
||||
Group {
|
||||
object: 3,
|
||||
kind: ObjectKind::PartsList,
|
||||
items: vec![Item::Fill {
|
||||
region: Region2 { outer: Loop2::polygon(&[p(10.0, 30.0), p(20.0, 30.0), p(20.0, 40.0), p(10.0, 40.0)]), holes: vec![] },
|
||||
}],
|
||||
},
|
||||
Group { object: 4, kind: ObjectKind::RevisionTable, items: vec![stroke(line(50.0), false, 0.7, None)] },
|
||||
Group { object: 5, kind: ObjectKind::SheetBorder, items: vec![] },
|
||||
Group {
|
||||
object: 6,
|
||||
kind: ObjectKind::TitleBlock,
|
||||
items: vec![stroke(vec![Seg2::Arc { center: p(50.0, 70.0), radius: 10.0, start: 0.0, sweep: FRAC_PI_2 }], false, 0.35, None)],
|
||||
},
|
||||
],
|
||||
};
|
||||
let layered_options = PdfOptions { title: Some("Flat Ç sheet".into()), output_time: Some(0), ..PdfOptions::default() };
|
||||
assert!(layered_options.layers && PdfOptions::default().layers);
|
||||
let flat_options = PdfOptions { layers: false, ..layered_options.clone() };
|
||||
let layered = pdf(&sheet, &layered_options);
|
||||
let flat = pdf(&sheet, &flat_options);
|
||||
assert_eq!(pdf(&sheet, &flat_options), flat);
|
||||
assert!(check_xref(&flat).is_ok());
|
||||
let file = text(&flat);
|
||||
for forbidden in ["/OCProperties", "/OCGs", "/Type /OCG", "/Properties", "/BaseState", "/Order", "/ON"] {
|
||||
assert!(!file.contains(forbidden), "flat output contains {forbidden}");
|
||||
}
|
||||
let flat_stream = content(&flat);
|
||||
assert!(!flat_stream.contains("BDC") && !flat_stream.contains("EMC"));
|
||||
let without_layers =
|
||||
content(&layered).lines().filter(|line| !line.ends_with(" BDC") && *line != "EMC").map(|line| format!("{line}\n")).collect::<String>();
|
||||
assert_eq!(flat_stream, without_layers, "all geometry, styles and paint order retained");
|
||||
let operators = ops(&flat_stream);
|
||||
let paint: Vec<_> = operators.iter().filter(|(op, _)| ["S", "h", "f*"].contains(&op.as_str())).map(|(op, _)| op.as_str()).collect();
|
||||
assert_eq!(paint, ["S", "S", "h", "f*", "S", "S"]);
|
||||
assert!(operators.iter().any(|(op, _)| op == "c"), "arc stays vector cubic geometry");
|
||||
assert!(check_number_grid(&flat_stream).is_ok());
|
||||
// Dictionary entries are indented. Compare exact, uniquely present values
|
||||
// as bytes, retaining the title's UTF-16BE rather than lossy UTF-8 text.
|
||||
let property = |bytes: &[u8], key: &str| {
|
||||
bytes
|
||||
.split(|&byte| byte == b'\n')
|
||||
.map(|line| line.trim_ascii_start())
|
||||
.filter_map(|line| line.strip_prefix(key.as_bytes()))
|
||||
.filter(|value| value.first().is_some_and(u8::is_ascii_whitespace))
|
||||
.map(|value| value.trim_ascii().to_vec())
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let producer = format!("(SolidCraft {})", env!("CARGO_PKG_VERSION"));
|
||||
for (key, expected) in [
|
||||
("/MediaBox", "[0 0 595.2756 841.8898]"),
|
||||
("/Producer", producer.as_str()),
|
||||
("/Title", "<FEFF0046006C00610074002000C7002000730068006500650074>"),
|
||||
("/CreationDate", "(D:19700101000000Z)"),
|
||||
("/ModDate", "(D:19700101000000Z)"),
|
||||
] {
|
||||
let flat_value = property(&flat, key);
|
||||
let layered_value = property(&layered, key);
|
||||
assert_eq!(flat_value, [expected.as_bytes().to_vec()], "flat {key} is present once with the expected value");
|
||||
assert_eq!(layered_value, [expected.as_bytes().to_vec()], "layered {key} is present once with the expected value");
|
||||
assert_eq!(flat_value, layered_value, "{key}");
|
||||
}
|
||||
// Optional independent-reader fixture, after all ordinary acceptance assertions.
|
||||
if let Some(path) = std::env::var_os("SOLIDCRAFT_PDF_FLAT_REVIEW_OUTPUT") {
|
||||
let written = std::fs::write(&path, &flat);
|
||||
assert!(written.is_ok(), "could not write the asserted flat fixture to {path:?}: {written:?}");
|
||||
let layered_path = std::path::PathBuf::from(&path).with_extension("layered.pdf");
|
||||
let written = std::fs::write(&layered_path, &layered);
|
||||
assert!(written.is_ok(), "could not write the matching layered fixture to {layered_path:?}: {written:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_pdf_empty_scene_and_content_budget_keep_their_boundaries() {
|
||||
let options = PdfOptions { layers: false, ..PdfOptions::default() };
|
||||
let empty = scene(p(210.0, 297.0), vec![]);
|
||||
assert_eq!(pdf(&empty, &options), pdf(&empty, &PdfOptions::default()), "empty groups invent no layer in either mode");
|
||||
let line = scene(p(210.0, 297.0), vec![stroke(vec![Seg2::Line { a: p(10.0, 10.0), b: p(100.0, 10.0) }], false, 0.35, None)]);
|
||||
let grid = line.prepare().unwrap().on_grid(Grid::TEN_NANOMETRES).unwrap();
|
||||
let flat = super::content_with_limit_and_layers(&grid.groups, None, MAX_DRAWING_BYTES).unwrap();
|
||||
assert_eq!(super::content_with_limit_and_layers(&grid.groups, None, flat.len()).unwrap(), flat);
|
||||
assert!(super::content_with_limit_and_layers(&grid.groups, None, flat.len() - 1).is_err());
|
||||
assert!(
|
||||
super::content_with_limit_and_layers(&grid.groups, Some(&[]), MAX_DRAWING_BYTES).is_err(),
|
||||
"missing enabled layer is not silently flattened"
|
||||
);
|
||||
assert!(super::content_with_limit(&grid.groups, flat.len()).is_err(), "markers remain charged on the layered path");
|
||||
}
|
||||
|
||||
/// Cam's original public-safe P1 sample is a byte oracle independent of the new
|
||||
/// flat path: no layer metadata or content marker may leak into this output.
|
||||
#[test]
|
||||
fn flat_pdf_reproduces_the_original_p1_a3_sample_bytes() {
|
||||
use sha2::Digest as _;
|
||||
let rect = |a: Vec2, b: Vec2| {
|
||||
let c = [a, p(b.x, a.y), b, p(a.x, b.y)];
|
||||
(0..4).map(|i| Seg2::Line { a: c[i], b: c[(i + 1) % 4] }).collect()
|
||||
};
|
||||
let centre = Some(Dashes { lengths_mm: vec![12.0, 3.0, 1.0, 3.0], phase_mm: 0.0 });
|
||||
let sheet = Scene {
|
||||
size_mm: p(420.0, 297.0),
|
||||
groups: vec![
|
||||
Group {
|
||||
object: 1,
|
||||
kind: ObjectKind::DrawingBorder,
|
||||
items: vec![
|
||||
stroke(rect(p(20.0, 10.0), p(410.0, 287.0)), true, 0.7, None),
|
||||
Item::Fill { region: Region2 { outer: Loop2 { segs: rect(p(0.0, 287.0), p(10.0, 297.0)) }, holes: vec![] } },
|
||||
Item::Fill { region: Region2 { outer: Loop2 { segs: rect(p(410.0, 0.0), p(420.0, 10.0)) }, holes: vec![] } },
|
||||
],
|
||||
},
|
||||
Group {
|
||||
object: 2,
|
||||
kind: ObjectKind::DrawingBorder,
|
||||
items: vec![
|
||||
stroke(rect(p(120.0, 90.0), p(300.0, 210.0)), true, 0.5, None),
|
||||
stroke(Loop2::circle(p(210.0, 150.0), 40.0).segs, true, 0.5, None),
|
||||
stroke(vec![Seg2::Line { a: p(160.0, 150.0), b: p(260.0, 150.0) }], false, 0.25, centre.clone()),
|
||||
stroke(vec![Seg2::Line { a: p(210.0, 100.0), b: p(210.0, 200.0) }], false, 0.25, centre),
|
||||
stroke(vec![Seg2::Arc { center: p(120.0, 90.0), radius: 15.0, start: 0.0, sweep: FRAC_PI_2 }], false, 0.35, None),
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
let options = PdfOptions { title: Some("A3 sample".into()), output_time: Some(1_800_000_000), layers: false };
|
||||
let bytes = pdf(&sheet, &options);
|
||||
assert_eq!(bytes.len(), 1063);
|
||||
assert_eq!(format!("{:x}", sha2::Sha256::digest(&bytes)), "0de09bc342566206514754fc2ed7836156fbe10ba444e8ebb66427b10dd89c02");
|
||||
assert_eq!(pdf(&sheet, &options), bytes);
|
||||
assert!(check_xref(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_pdf_groups_share_one_run_without_reordering_noncontiguous_layers() {
|
||||
let groups = [
|
||||
(1, ObjectKind::TitleBlock, 10.0),
|
||||
(2, ObjectKind::TitleBlock, 20.0),
|
||||
(3, ObjectKind::DrawingBorder, 30.0),
|
||||
(4, ObjectKind::TitleBlock, 40.0),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(object, kind, y)| Group { object, kind, items: vec![stroke(vec![Seg2::Line { a: p(10.0, y), b: p(20.0, y) }], false, 0.35, None)] })
|
||||
.collect();
|
||||
let sheet = Scene { size_mm: p(210.0, 297.0), groups };
|
||||
let bytes = pdf(&sheet, &NONE);
|
||||
assert_eq!(pdf(&sheet, &NONE), bytes);
|
||||
assert!(check_xref(&bytes).is_ok());
|
||||
let file = text(&bytes);
|
||||
assert_eq!(file.matches("/Type /OCG\n").count(), 2);
|
||||
for key in ["OCGs", "Order", "ON"] {
|
||||
assert!(file.contains(&format!("/{key} [6 0 R 7 0 R]")));
|
||||
}
|
||||
assert!(file.contains("/Name (TITLE_BLOCK)") && file.contains("/Name (DRAWING_BORDER)"));
|
||||
let stream = content(&bytes);
|
||||
let markers: Vec<_> = stream.lines().filter(|line| line.ends_with(" BDC") || *line == "EMC").collect();
|
||||
assert_eq!(markers, ["/OC /L0 BDC", "EMC", "/OC /L1 BDC", "EMC", "/OC /L0 BDC", "EMC"]);
|
||||
let operators = ops(&stream);
|
||||
let starts: Vec<_> = operators.iter().filter(|(op, _)| op == "m").map(|(_, n)| (n[0], n[1])).collect();
|
||||
assert_eq!(starts, [(10.0, 10.0), (10.0, 20.0), (10.0, 30.0), (10.0, 40.0)]);
|
||||
assert_eq!(operators.iter().filter(|(op, _)| op == "S").count(), 4);
|
||||
if let Some(path) = std::env::var_os("SOLIDCRAFT_PDF_COALESCING_REVIEW_OUTPUT") {
|
||||
let flat = pdf(&sheet, &PdfOptions { layers: false, ..NONE.clone() });
|
||||
let written = std::fs::write(&path, &bytes);
|
||||
assert!(written.is_ok(), "could not write the asserted coalescing fixture to {path:?}: {written:?}");
|
||||
let flat_path = std::path::PathBuf::from(&path).with_extension("flat.pdf");
|
||||
let written = std::fs::write(&flat_path, &flat);
|
||||
assert!(written.is_ok(), "could not write the matching flat fixture to {flat_path:?}: {written:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_pdf_groups_do_not_break_adjacent_painted_runs_or_invent_layers() {
|
||||
for insert_empty in [false, true] {
|
||||
let mut groups = vec![Group { object: 0, kind: ObjectKind::SheetBorder, items: vec![] }];
|
||||
for (object, y) in [(1, 10.0), (2, 20.0)] {
|
||||
if insert_empty {
|
||||
groups.push(Group { object: 100 + object, kind: ObjectKind::DrawingBorder, items: vec![] });
|
||||
}
|
||||
groups.push(Group {
|
||||
object,
|
||||
kind: ObjectKind::TitleBlock,
|
||||
items: vec![stroke(vec![Seg2::Line { a: p(10.0, y), b: p(20.0, y) }], false, 0.35, None)],
|
||||
});
|
||||
}
|
||||
groups.push(Group { object: 200, kind: ObjectKind::RevisionTable, items: vec![] });
|
||||
let sheet = Scene { size_mm: p(210.0, 297.0), groups };
|
||||
let bytes = pdf(&sheet, &NONE);
|
||||
let file = text(&bytes);
|
||||
assert_eq!(file.matches("/Type /OCG\n").count(), 1);
|
||||
for absent in ["SHEET_BORDER", "DRAWING_BORDER", "REVISION_TABLE"] {
|
||||
assert!(!file.contains(&format!("/Name ({absent})")));
|
||||
}
|
||||
let stream = content(&bytes);
|
||||
let markers: Vec<_> = stream.lines().filter(|line| line.ends_with(" BDC") || *line == "EMC").collect();
|
||||
assert_eq!(markers, ["/OC /L0 BDC", "EMC"]);
|
||||
assert_eq!(ops(&stream).iter().filter(|(op, _)| op == "S").count(), 2);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_merged_pdf_run_keeps_all_paint_and_shared_width_and_dash_state() {
|
||||
let line = |y| vec![Seg2::Line { a: p(10.0, y), b: p(20.0, y) }];
|
||||
let dashed = Some(Dashes { lengths_mm: vec![4.0, 2.0], phase_mm: 0.0 });
|
||||
let square = Loop2::polygon(&[p(10.0, 30.0), p(20.0, 30.0), p(20.0, 40.0), p(10.0, 40.0)]);
|
||||
let items = [
|
||||
stroke(line(10.0), false, 0.35, None),
|
||||
stroke(line(20.0), false, 0.7, dashed.clone()),
|
||||
Item::Fill { region: Region2 { outer: square, holes: vec![] } },
|
||||
stroke(line(50.0), false, 0.7, dashed),
|
||||
stroke(line(60.0), false, 0.7, None),
|
||||
];
|
||||
let sheet = Scene {
|
||||
size_mm: p(210.0, 297.0),
|
||||
groups: items.into_iter().enumerate().map(|(i, item)| Group { object: i as u64, kind: ObjectKind::TitleBlock, items: vec![item] }).collect(),
|
||||
};
|
||||
let before = sheet.clone();
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
let (bytes, report) = paper_pdf(&prepared, &NONE).unwrap();
|
||||
let flat_options = PdfOptions { layers: false, ..NONE.clone() };
|
||||
let (flat, flat_report) = paper_pdf(&prepared, &flat_options).unwrap();
|
||||
assert_eq!(sheet, before);
|
||||
assert_eq!(report, flat_report);
|
||||
let stream = content(&bytes);
|
||||
let markers: Vec<_> = stream.lines().filter(|line| line.ends_with(" BDC") || *line == "EMC").collect();
|
||||
assert_eq!(markers, ["/OC /L0 BDC", "EMC"]);
|
||||
let operators = ops(&stream);
|
||||
let paints: Vec<_> = operators.iter().filter(|(op, _)| ["S", "h", "f*"].contains(&op.as_str())).map(|(op, _)| op.as_str()).collect();
|
||||
assert_eq!(paints, ["S", "S", "h", "f*", "S", "S"]);
|
||||
let styles: Vec<_> = operators.iter().filter(|(op, _)| op == "w" || op == "d").map(|(op, n)| (op.as_str(), n.as_slice())).collect();
|
||||
assert_eq!(styles, [("w", &[0.35][..]), ("w", &[0.7][..]), ("d", &[4.0, 2.0, 0.0][..]), ("d", &[0.0][..])]);
|
||||
let starts: Vec<_> = operators.iter().filter(|(op, _)| op == "m").map(|(_, n)| (n[0], n[1])).collect();
|
||||
assert_eq!(starts, [(10.0, 10.0), (10.0, 20.0), (10.0, 30.0), (10.0, 50.0), (10.0, 60.0)]);
|
||||
let stripped = stream.lines().filter(|line| !line.ends_with(" BDC") && *line != "EMC").map(|line| format!("{line}\n")).collect::<String>();
|
||||
assert_eq!(stripped, content(&flat));
|
||||
assert!(check_xref(&bytes).is_ok() && check_xref(&flat).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merged_pdf_run_limits_charge_transitions_and_the_final_close() {
|
||||
let groups = [(1, ObjectKind::TitleBlock, 10.0), (2, ObjectKind::TitleBlock, 20.0), (3, ObjectKind::DrawingBorder, 30.0)]
|
||||
.into_iter()
|
||||
.map(|(object, kind, y)| Group { object, kind, items: vec![stroke(vec![Seg2::Line { a: p(10.0, y), b: p(20.0, y) }], false, 0.35, None)] })
|
||||
.collect();
|
||||
let sheet = Scene { size_mm: p(210.0, 297.0), groups };
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
let grid = prepared.on_grid(Grid::TEN_NANOMETRES).unwrap();
|
||||
// Literal independent stream: adjacent objects retain two strokes within
|
||||
// L0; only the change to L1 closes and reopens marked content.
|
||||
let expected = concat!(
|
||||
"q 2.834645669 0 0 2.834645669 0 0 cm 0 J 0 j 4 M\n",
|
||||
"/OC /L0 BDC\n0.35 w\n10 10 m\n20 10 l\nS\n10 20 m\n20 20 l\nS\n",
|
||||
"EMC\n/OC /L1 BDC\n10 30 m\n20 30 l\nS\nEMC\nQ\n",
|
||||
);
|
||||
assert_eq!(super::content_with_limit(&grid.groups, expected.len()).unwrap(), expected);
|
||||
assert!(super::content_with_limit(&grid.groups, expected.len() - 1).is_err());
|
||||
for tail in ["EMC\n/OC /L1 BDC\n", "/OC /L1 BDC\n", "EMC\nQ\n"] {
|
||||
let prefix = expected.find(tail).unwrap();
|
||||
assert!(super::content_with_limit(&grid.groups, prefix + tail.len() - 1).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
//! A paper scene as a sheet PNG (#4890, A4): the sheet at its size in pixels at a chosen dpi.
|
||||
//!
|
||||
//! - **Geometry** is the scene on the nanometre grid ([`Prepared::on_grid`]), the one SVG writes, so
|
||||
//! both draw the same joints, closures and merges. Curves are flattened within 1/8 px
|
||||
//! ([`paper::flatten`]) and tiny-skia is given lines only: its own flattening stops at 64 lines a
|
||||
//! curve, more than a pixel off on a large arc at a high dpi.
|
||||
//! - **Paint** as the scene says: black, strokes with butt caps and miter joins (limit 4), fills
|
||||
//! even-odd. Each line is stroked once, then filled band by band; a line under a pixel wide is
|
||||
//! drawn as tiny-skia's hairline instead, its coverage scaled by its width, so it never vanishes.
|
||||
//! - **Dashes:** a dashed line is cut into its dashes along the flattened line (tiny-skia's
|
||||
//! dashing, the pattern scaled to pixels), then stroked like any line; the dashes' points count
|
||||
//! against [`MAX_POINTS`] too.
|
||||
//! - **Bands:** the sheet is drawn [`BAND_BYTES`] of pixels at a time, with a row above and below
|
||||
//! that isn't written, and streamed into the file, so an A0 sheet at 2400 dpi (8.9 billion
|
||||
//! pixels) needs no more memory than an A4 one, and the bytes are the same whatever the band.
|
||||
//! - **The file** records its dpi (`pHYs`), so it prints at the sheet's size, and is sRGB.
|
||||
|
||||
use std::io::Write;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use solidcraft_geom::paper::{self, Grid, GridDashes, GridItem, GridPath, GridReport, Prepared};
|
||||
use tiny_skia::{Color, FillRule, LineCap, LineJoin, Paint, Path, PathBuilder, Pixmap, Stroke, StrokeDash, Transform};
|
||||
|
||||
use crate::{IoError, Result};
|
||||
|
||||
/// The resolutions a sheet PNG may have, in dots per inch.
|
||||
pub const DPI: RangeInclusive<f64> = 25.0..=2400.0;
|
||||
/// The most points a sheet's lines may flatten to in all.
|
||||
pub const MAX_POINTS: usize = 1 << 24;
|
||||
/// The pixels drawn at a time, as RGBA bytes.
|
||||
const BAND_BYTES: usize = 16 << 20;
|
||||
/// Rows drawn above and below each band and not written: tiny-skia starts an edge a little
|
||||
/// differently where a clip cuts it, so no written row sits on a cut and bands change nothing.
|
||||
const MARGIN: u32 = 1;
|
||||
|
||||
/// How a sheet PNG stores its pixels.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum PngColour {
|
||||
/// 8-bit greyscale on white paper.
|
||||
#[default]
|
||||
Grey,
|
||||
/// One bit a pixel, black or white, every line at least a pixel wide so none drops out.
|
||||
BlackWhite,
|
||||
/// 24-bit colour on white paper.
|
||||
Rgb,
|
||||
/// 32-bit colour, the paper transparent.
|
||||
Transparent,
|
||||
}
|
||||
|
||||
/// A sheet PNG's resolution and colour.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct PngOptions {
|
||||
pub dpi: f64,
|
||||
pub colour: PngColour,
|
||||
}
|
||||
|
||||
impl Default for PngOptions {
|
||||
fn default() -> Self {
|
||||
PngOptions { dpi: 300.0, colour: PngColour::Grey }
|
||||
}
|
||||
}
|
||||
|
||||
/// What writing a sheet PNG did: the grid's report, and the image's width and height in pixels.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct PngReport {
|
||||
pub grid: GridReport,
|
||||
pub pixels: [u32; 2],
|
||||
}
|
||||
|
||||
/// The scene as a sheet PNG written to `out`.
|
||||
pub fn paper_png(scene: &Prepared, options: PngOptions, out: impl Write) -> Result<PngReport> {
|
||||
write(scene, options, out, BAND_BYTES)
|
||||
}
|
||||
|
||||
fn write(scene: &Prepared, options: PngOptions, out: impl Write, band_bytes: usize) -> Result<PngReport> {
|
||||
let PngOptions { dpi, colour } = options;
|
||||
if !DPI.contains(&dpi) {
|
||||
return Err(IoError::Invalid(format!("a sheet PNG is 25 to 2400 dpi, not {dpi}")));
|
||||
}
|
||||
let on = scene.on_grid(Grid::NANOMETRE).map_err(|e| IoError::Invalid(e.to_string()))?;
|
||||
let px = dpi / 25.4e6; // pixels a nanometre
|
||||
let pixels = [on.size.x, on.size.y].map(|n| ((n as f64 * px).round() as u32).max(1));
|
||||
let mut sheet = Sheet { px, height: on.size.y as f64, tolerance: 0.125 / px, points: 0 };
|
||||
let mut shapes = Vec::new();
|
||||
for item in on.groups.iter().flat_map(|g| &g.items) {
|
||||
match item {
|
||||
GridItem::Stroke { width, path, dashes } => {
|
||||
let mut builder = PathBuilder::new();
|
||||
sheet.trace(&mut builder, path)?;
|
||||
let Some(mut line) = builder.finish() else { continue };
|
||||
if let Some(dashes) = dashes {
|
||||
let Some(dashed) = sheet.dash(&line, dashes)? else { continue };
|
||||
line = dashed;
|
||||
}
|
||||
let width = (*width as f64 * px) as f32;
|
||||
let stroke = Stroke {
|
||||
width: if colour == PngColour::BlackWhite { width.max(1.0) } else { width },
|
||||
miter_limit: 4.0,
|
||||
line_cap: LineCap::Butt,
|
||||
line_join: LineJoin::Miter,
|
||||
dash: None,
|
||||
};
|
||||
// A line under a pixel wide is drawn as tiny-skia's hairline, its coverage scaled by its
|
||||
// width: its outline would fall between the rows the rasteriser samples and vanish.
|
||||
let thin = colour != PngColour::BlackWhite && width < 1.0;
|
||||
shapes.extend(if thin { Some(Shape::Thin(line, stroke)) } else { line.stroke(&stroke, 1.0).map(Shape::Fill) });
|
||||
}
|
||||
GridItem::Fill { loops } => {
|
||||
let mut builder = PathBuilder::new();
|
||||
for l in loops {
|
||||
sheet.trace(&mut builder, l)?;
|
||||
}
|
||||
shapes.extend(builder.finish().map(Shape::EvenOdd));
|
||||
}
|
||||
}
|
||||
}
|
||||
let png_error = |e: png::EncodingError| IoError::Invalid(format!("the sheet PNG: {e}"));
|
||||
let mut encoder = png::Encoder::new(out, pixels[0], pixels[1]);
|
||||
let (colour_type, depth) = match colour {
|
||||
PngColour::Grey => (png::ColorType::Grayscale, png::BitDepth::Eight),
|
||||
PngColour::BlackWhite => (png::ColorType::Grayscale, png::BitDepth::One),
|
||||
PngColour::Rgb => (png::ColorType::Rgb, png::BitDepth::Eight),
|
||||
PngColour::Transparent => (png::ColorType::Rgba, png::BitDepth::Eight),
|
||||
};
|
||||
encoder.set_color(colour_type);
|
||||
encoder.set_depth(depth);
|
||||
encoder.set_source_srgb(png::SrgbRenderingIntent::Perceptual);
|
||||
let per_metre = (dpi / 0.0254).round() as u32;
|
||||
encoder.set_pixel_dims(Some(png::PixelDimensions { xppu: per_metre, yppu: per_metre, unit: png::Unit::Meter }));
|
||||
let mut header = encoder.write_header().map_err(png_error)?;
|
||||
let mut stream = header.stream_writer().map_err(png_error)?;
|
||||
|
||||
let width = pixels[0] as usize;
|
||||
let rows = (band_bytes / (width * 4)).clamp(1, pixels[1] as usize) as u32;
|
||||
let mut band = Pixmap::new(pixels[0], rows + 2 * MARGIN).ok_or_else(|| IoError::Invalid("the sheet PNG: no room for a band of pixels".into()))?;
|
||||
// A hairline reaches at most a pixel past its line: into the margin rows, never a written one.
|
||||
let spans: Vec<(f32, f32)> = shapes
|
||||
.iter()
|
||||
.map(|(Shape::Fill(path) | Shape::EvenOdd(path) | Shape::Thin(path, _))| (path.bounds().top(), path.bounds().bottom()))
|
||||
.collect();
|
||||
let mut paint = Paint { anti_alias: colour != PngColour::BlackWhite, ..Paint::default() };
|
||||
paint.set_color(Color::BLACK);
|
||||
let mut row = Vec::with_capacity(width * 4);
|
||||
let mut top = 0;
|
||||
while top < pixels[1] {
|
||||
let n = rows.min(pixels[1] - top);
|
||||
band.fill(if colour == PngColour::Transparent { Color::TRANSPARENT } else { Color::WHITE });
|
||||
let shift = Transform::from_translate(0.0, MARGIN as f32 - top as f32);
|
||||
for (shape, (y0, y1)) in shapes.iter().zip(&spans) {
|
||||
if *y1 >= top as f32 - MARGIN as f32 && *y0 <= (top + n + MARGIN) as f32 {
|
||||
match shape {
|
||||
Shape::Fill(path) => band.fill_path(path, &paint, FillRule::Winding, shift, None),
|
||||
Shape::EvenOdd(path) => band.fill_path(path, &paint, FillRule::EvenOdd, shift, None),
|
||||
Shape::Thin(line, stroke) => band.stroke_path(line, &paint, stroke, shift, None),
|
||||
}
|
||||
}
|
||||
}
|
||||
for line in band.pixels().chunks_exact(width).skip(MARGIN as usize).take(n as usize) {
|
||||
row.clear();
|
||||
match colour {
|
||||
PngColour::Grey => row.extend(line.iter().map(|p| luma(p.red(), p.green(), p.blue()))),
|
||||
PngColour::BlackWhite => row.extend(line.chunks(8).map(|eight| {
|
||||
// Most significant bit first; 1 is white.
|
||||
eight.iter().enumerate().fold(0u8, |byte, (i, p)| byte | (u8::from(luma(p.red(), p.green(), p.blue()) >= 128) << (7 - i)))
|
||||
})),
|
||||
PngColour::Rgb => row.extend(line.iter().flat_map(|p| [p.red(), p.green(), p.blue()])),
|
||||
PngColour::Transparent => row.extend(line.iter().flat_map(|p| {
|
||||
let c = p.demultiply();
|
||||
[c.red(), c.green(), c.blue(), c.alpha()]
|
||||
})),
|
||||
}
|
||||
stream.write_all(&row).map_err(|e| IoError::Invalid(format!("the sheet PNG: {e}")))?;
|
||||
}
|
||||
top += n;
|
||||
}
|
||||
stream.finish().map_err(png_error)?;
|
||||
header.finish().map_err(png_error)?;
|
||||
Ok(PngReport { grid: on.report, pixels })
|
||||
}
|
||||
|
||||
/// What a band draws for one item.
|
||||
enum Shape {
|
||||
/// A stroke's outline, filled non-zero.
|
||||
Fill(Path),
|
||||
/// A fill's loops, filled even-odd.
|
||||
EvenOdd(Path),
|
||||
/// A line under a pixel wide, stroked as a hairline.
|
||||
Thin(Path, Stroke),
|
||||
}
|
||||
|
||||
/// The luma of an sRGB pixel, Rec. 709's weights in 256ths.
|
||||
fn luma(r: u8, g: u8, b: u8) -> u8 {
|
||||
((u32::from(r) * 54 + u32::from(g) * 183 + u32::from(b) * 19 + 128) >> 8) as u8
|
||||
}
|
||||
|
||||
/// The sheet in pixels: the grid's nanometres scaled, y flipped to the page's top, curves
|
||||
/// flattened within the tolerance, the points counted against [`MAX_POINTS`].
|
||||
struct Sheet {
|
||||
/// Pixels a nanometre.
|
||||
px: f64,
|
||||
/// The sheet's height, in nanometres.
|
||||
height: f64,
|
||||
/// The flattening tolerance, in nanometres.
|
||||
tolerance: f64,
|
||||
points: usize,
|
||||
}
|
||||
|
||||
impl Sheet {
|
||||
/// `n` more points, refused past [`MAX_POINTS`] in all.
|
||||
fn count(&mut self, n: usize) -> Result<()> {
|
||||
self.points += n;
|
||||
if self.points > MAX_POINTS {
|
||||
return Err(IoError::Invalid(format!("the sheet needs over {MAX_POINTS} points at this resolution")));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `path` onto `builder` in pixels, closed when it is.
|
||||
fn trace(&mut self, builder: &mut PathBuilder, path: &GridPath) -> Result<()> {
|
||||
let points = paper::flatten(path, self.tolerance).map_err(|e| IoError::Invalid(e.to_string()))?;
|
||||
self.count(points.len())?;
|
||||
let at = |p: solidcraft_geom::Vec2| ((p.x * self.px) as f32, ((self.height - p.y) * self.px) as f32);
|
||||
for (i, p) in points.into_iter().enumerate() {
|
||||
let (x, y) = at(p);
|
||||
if i == 0 { builder.move_to(x, y) } else { builder.line_to(x, y) }
|
||||
}
|
||||
if path.closed {
|
||||
builder.close();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `line` cut into its dashes, the pattern scaled to pixels, or `None` when all of it falls in
|
||||
/// a gap, which only a line no longer than the pattern can. tiny-skia gives the same answer
|
||||
/// when it gives up past a million dashes, so a longer line without dashes is refused.
|
||||
fn dash(&mut self, line: &Path, dashes: &GridDashes) -> Result<Option<Path>> {
|
||||
let px = |steps: i64| (steps as f64 * self.px) as f32;
|
||||
let pattern = StrokeDash::new(dashes.lengths.iter().map(|l| px(*l)).collect(), px(dashes.phase));
|
||||
if let Some(dashed) = pattern.and_then(|pattern| line.dash(&pattern, 1.0)) {
|
||||
self.count(dashed.len())?;
|
||||
return Ok(Some(dashed));
|
||||
}
|
||||
let points = line.points();
|
||||
let length: f64 = points.iter().zip(points.iter().skip(1)).map(|(a, b)| f64::from(a.distance(*b))).sum();
|
||||
if length <= dashes.lengths.iter().sum::<i64>() as f64 * self.px {
|
||||
return Ok(None);
|
||||
}
|
||||
Err(IoError::Invalid("a dashed line has too many dashes to draw".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "png_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,356 @@
|
||||
use std::f64::consts::{FRAC_PI_2, TAU};
|
||||
|
||||
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 line(a: Vec2, b: Vec2) -> Seg2 {
|
||||
Seg2::Line { a, b }
|
||||
}
|
||||
|
||||
/// Anticlockwise from `min`.
|
||||
fn rectangle(min: Vec2, max: Vec2) -> Loop2 {
|
||||
Loop2::polygon(&[min, p(max.x, min.y), max, p(min.x, max.y)])
|
||||
}
|
||||
|
||||
fn scene(size: Vec2, items: Vec<Item>) -> Scene {
|
||||
Scene { size_mm: size, groups: vec![Group { object: 1, kind: ObjectKind::DrawingBorder, items }] }
|
||||
}
|
||||
|
||||
/// A 20 × 10 mm sheet: a 1 mm line along y = 5 from x = 2 to 18, and a 6 × 3 mm fill at (2, 1)
|
||||
/// with a 2 × 1 mm hole at (4, 2). At 254 dpi a millimetre is 10 pixels.
|
||||
fn small() -> Scene {
|
||||
scene(
|
||||
p(20.0, 10.0),
|
||||
vec![
|
||||
Item::Stroke { path: vec![line(p(2.0, 5.0), p(18.0, 5.0))], closed: false, width_mm: 1.0, pattern: None },
|
||||
Item::Fill { region: Region2 { outer: rectangle(p(2.0, 1.0), p(8.0, 4.0)), holes: vec![rectangle(p(4.0, 2.0), p(6.0, 3.0))] } },
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
struct Image {
|
||||
info: png::Info<'static>,
|
||||
/// One byte a sample, rows top down: 1-bit images unpacked to 0 or 255.
|
||||
samples: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
fn channels(&self) -> usize {
|
||||
self.info.color_type.samples()
|
||||
}
|
||||
|
||||
/// The samples of the pixel at column `x`, row `y` from the top.
|
||||
fn at(&self, x: usize, y: usize) -> &[u8] {
|
||||
let c = self.channels();
|
||||
let i = (y * self.info.width as usize + x) * c;
|
||||
&self.samples[i..i + c]
|
||||
}
|
||||
}
|
||||
|
||||
fn bytes(scene: &Scene, options: PngOptions) -> (Vec<u8>, PngReport) {
|
||||
let mut out = Vec::new();
|
||||
let report = paper_png(&scene.prepare().unwrap(), options, &mut out).unwrap();
|
||||
(out, report)
|
||||
}
|
||||
|
||||
fn read(bytes: &[u8]) -> Image {
|
||||
let mut decoder = png::Decoder::new(std::io::Cursor::new(bytes.to_vec()));
|
||||
decoder.set_transformations(png::Transformations::EXPAND);
|
||||
let mut reader = decoder.read_info().unwrap();
|
||||
let mut samples = vec![0; reader.output_buffer_size().unwrap()];
|
||||
reader.next_frame(&mut samples).unwrap();
|
||||
let info = reader.info().clone();
|
||||
if info.bit_depth == png::BitDepth::One {
|
||||
// EXPAND makes a 1-bit grey sample 0 or 255 a byte.
|
||||
assert!(samples.iter().all(|s| *s == 0 || *s == 255));
|
||||
}
|
||||
Image { info, samples }
|
||||
}
|
||||
|
||||
fn image(scene: &Scene, options: PngOptions) -> Image {
|
||||
read(&bytes(scene, options).0)
|
||||
}
|
||||
|
||||
const AT_254: PngOptions = PngOptions { dpi: 254.0, colour: PngColour::Grey };
|
||||
|
||||
/// A sheet is its size at the dpi, rounded, and says its dpi, so it prints at the sheet's size:
|
||||
/// 300 dpi greyscale unless asked, sRGB.
|
||||
#[test]
|
||||
fn a_sheet_is_its_size_at_the_dpi_and_records_it() {
|
||||
let a4 = scene(p(210.0, 297.0), vec![]);
|
||||
assert_eq!(PngOptions::default(), PngOptions { dpi: 300.0, colour: PngColour::Grey });
|
||||
let (data, report) = bytes(&a4, PngOptions::default());
|
||||
assert_eq!(report.pixels, [2480, 3508]);
|
||||
let image = read(&data);
|
||||
assert_eq!((image.info.width, image.info.height), (2480, 3508));
|
||||
assert_eq!((image.info.color_type, image.info.bit_depth), (png::ColorType::Grayscale, png::BitDepth::Eight));
|
||||
let dims = image.info.pixel_dims.unwrap();
|
||||
assert_eq!((dims.xppu, dims.yppu, dims.unit), (11811, 11811, png::Unit::Meter));
|
||||
assert!(image.info.srgb.is_some());
|
||||
assert!(image.samples.iter().all(|s| *s == 255), "blank paper is white");
|
||||
assert_eq!(bytes(&a4, PngOptions { dpi: 25.0, ..PngOptions::default() }).1.pixels, [207, 292]);
|
||||
}
|
||||
|
||||
/// The line and the fill land on their pixels: the line 10 rows deep round row 50 with butt ends,
|
||||
/// the fill's ring black and its hole white.
|
||||
#[test]
|
||||
fn lines_and_fills_land_on_their_pixels() {
|
||||
let image = image(&small(), AT_254);
|
||||
assert_eq!((image.info.width, image.info.height), (200, 100));
|
||||
let grey = |x, y| image.at(x, y)[0];
|
||||
for (x, y, value, what) in [
|
||||
(100, 45, 0, "the line's top row"),
|
||||
(100, 54, 0, "its bottom row"),
|
||||
(100, 44, 255, "above it"),
|
||||
(100, 55, 255, "below it"),
|
||||
(20, 50, 0, "its first column"),
|
||||
(19, 50, 255, "before its butt end"),
|
||||
(179, 50, 0, "its last column"),
|
||||
(180, 50, 255, "after it"),
|
||||
(30, 75, 0, "the fill's ring"),
|
||||
(50, 75, 255, "the fill's hole"),
|
||||
(90, 75, 255, "beside the fill"),
|
||||
] {
|
||||
assert_eq!(grey(x, y), value, "{what}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Each colour: its PNG type, black ink and white (or no) paper.
|
||||
#[test]
|
||||
fn each_colour_has_its_type_ink_and_paper() {
|
||||
for (colour, kind, depth, ink, paper) in [
|
||||
(PngColour::Grey, png::ColorType::Grayscale, png::BitDepth::Eight, &[0][..], &[255][..]),
|
||||
(PngColour::BlackWhite, png::ColorType::Grayscale, png::BitDepth::One, &[0], &[255]),
|
||||
(PngColour::Rgb, png::ColorType::Rgb, png::BitDepth::Eight, &[0, 0, 0], &[255, 255, 255]),
|
||||
(PngColour::Transparent, png::ColorType::Rgba, png::BitDepth::Eight, &[0, 0, 0, 255], &[0, 0, 0, 0]),
|
||||
] {
|
||||
let image = image(&small(), PngOptions { dpi: 254.0, colour });
|
||||
assert_eq!((image.info.color_type, image.info.bit_depth), (kind, depth), "{colour:?}");
|
||||
assert_eq!(image.at(100, 50), ink, "{colour:?}: the line");
|
||||
// Either side of its butt end, bits 3 and 4 of a 1-bit row's third byte.
|
||||
assert_eq!((image.at(19, 50), image.at(20, 50)), (paper, ink), "{colour:?}: the line's start");
|
||||
assert_eq!(image.at(100, 20), paper, "{colour:?}: the paper");
|
||||
}
|
||||
}
|
||||
|
||||
/// A line far thinner than a pixel is a light grey in greyscale, and a full black pixel in black
|
||||
/// and white, so it doesn't drop out, even between two rows' centres; edges are anti-aliased only
|
||||
/// where there is grey, and black and white inks a pixel when its centre is inside.
|
||||
#[test]
|
||||
fn a_hairline_stays_a_pixel_wide_in_black_and_white() {
|
||||
// 50.25 rows from the top: between the centres of rows 49 and 50.
|
||||
let hair =
|
||||
scene(p(20.0, 10.0), vec![Item::Stroke { path: vec![line(p(2.0, 4.975), p(18.0, 4.975))], closed: false, width_mm: 0.01, pattern: None }]);
|
||||
let column = |colour| {
|
||||
let image = image(&hair, PngOptions { dpi: 254.0, colour });
|
||||
(40..60).map(|y| image.at(100, y)[0]).collect::<Vec<u8>>()
|
||||
};
|
||||
let grey = column(PngColour::Grey);
|
||||
assert!(grey.iter().all(|v| *v > 200) && grey.iter().any(|v| *v < 255), "a tenth of a pixel is light grey: {grey:?}");
|
||||
let bw = column(PngColour::BlackWhite);
|
||||
assert_eq!(bw.iter().filter(|v| **v == 0).count(), 1, "one black pixel across: {bw:?}");
|
||||
let edge = image(&small(), PngOptions { dpi: 100.0, colour: PngColour::Grey });
|
||||
assert!(edge.samples.iter().any(|v| *v != 0 && *v != 255), "greyscale edges are anti-aliased");
|
||||
// A bar a fifth of a pixel wide over column 100's centre: grey in greyscale, black in black and white.
|
||||
let bar = scene(p(20.0, 10.0), vec![Item::Fill { region: Region2 { outer: rectangle(p(10.045, 2.0), p(10.065, 8.0)), holes: vec![] } }]);
|
||||
let grey = image(&bar, AT_254).at(100, 50)[0];
|
||||
assert!(grey > 0 && grey < 255, "under half a pixel is grey: {grey}");
|
||||
assert_eq!(image(&bar, PngOptions { dpi: 254.0, colour: PngColour::BlackWhite }).at(100, 50), [0], "its centre is inside");
|
||||
}
|
||||
|
||||
/// A closed outline is joined where it starts, like its other corners, not left with two butt ends.
|
||||
#[test]
|
||||
fn a_closed_outline_joins_at_its_start() {
|
||||
let square = rectangle(p(2.0, 2.0), p(8.0, 8.0)).segs;
|
||||
let outline = scene(p(10.0, 10.0), vec![Item::Stroke { path: square, closed: true, width_mm: 1.0, pattern: None }]);
|
||||
let image = image(&outline, AT_254);
|
||||
// A quarter of a millimetre outside each corner, inside the 1 mm line's mitred corner.
|
||||
for (x, y, what) in [(17, 82, "the start"), (82, 82, "the second corner"), (82, 17, "the third"), (17, 17, "the fourth")] {
|
||||
assert_eq!(image.at(x, y), [0], "{what}, ({x}, {y})");
|
||||
}
|
||||
}
|
||||
|
||||
/// Arcs are drawn from lines within 1/8 px: on a 40 mm circle at 600 dpi, every pixel the stroke's
|
||||
/// middle crosses is black and pixels a pixel outside its 0.5 mm width are white, at 64 angles.
|
||||
#[test]
|
||||
fn a_large_circle_is_round_to_the_pixel() {
|
||||
let c = p(50.0, 50.0);
|
||||
let circle = scene(
|
||||
p(100.0, 100.0),
|
||||
vec![Item::Stroke { path: vec![Seg2::Arc { center: c, radius: 40.0, start: 0.0, sweep: TAU }], closed: true, width_mm: 0.5, pattern: None }],
|
||||
);
|
||||
let image = image(&circle, PngOptions { dpi: 600.0, colour: PngColour::Grey });
|
||||
let per_mm = 600.0 / 25.4;
|
||||
let pixel = |q: Vec2| image.at((q.x * per_mm) as usize, ((100.0 - q.y) * per_mm) as usize)[0];
|
||||
for k in 0..64 {
|
||||
let towards = Vec2::from_angle(TAU * f64::from(k) / 64.0);
|
||||
assert_eq!(pixel(c + towards * 40.0), 0, "on the circle at {k}/64");
|
||||
for r in [40.0 - 0.25 - 1.5 / per_mm, 40.0 + 0.25 + 1.5 / per_mm] {
|
||||
assert_eq!(pixel(c + towards * r), 255, "off the circle at {k}/64, r {r}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drawn a few rows at a time or all at once, the file is the same bytes; and again the same bytes.
|
||||
#[test]
|
||||
fn bands_change_nothing_and_the_bytes_repeat() {
|
||||
let mut items = small().groups.remove(0).items;
|
||||
items.push(Item::Stroke {
|
||||
path: vec![Seg2::Arc { center: p(14.0, 3.0), radius: 2.5, start: 0.3, sweep: 1.5 * FRAC_PI_2 }],
|
||||
closed: false,
|
||||
width_mm: 0.35,
|
||||
pattern: None,
|
||||
});
|
||||
let sheet = scene(p(20.0, 10.0), items);
|
||||
let prepared = sheet.prepare().unwrap();
|
||||
for colour in [PngColour::Grey, PngColour::BlackWhite, PngColour::Rgb, PngColour::Transparent] {
|
||||
let options = PngOptions { dpi: 300.0, colour };
|
||||
let whole = &mut Vec::new();
|
||||
write(&prepared, options, &mut *whole, usize::MAX).unwrap();
|
||||
let width = read(whole).info.width as usize;
|
||||
for band_rows in [1, 3, 7] {
|
||||
let rows = &mut Vec::new();
|
||||
write(&prepared, options, &mut *rows, band_rows * width * 4).unwrap();
|
||||
assert_eq!(whole, rows, "{colour:?}, {band_rows} rows a band");
|
||||
}
|
||||
assert_eq!(bytes(&sheet, options).0, *whole, "{colour:?}: the same bytes again");
|
||||
}
|
||||
}
|
||||
|
||||
/// Out of range resolutions, a curve the walk can't take yet, and more points than the cap are
|
||||
/// refused, never drawn some other way.
|
||||
#[test]
|
||||
fn what_cannot_be_drawn_is_refused() {
|
||||
let prepared_small = small();
|
||||
let prepared = prepared_small.prepare().unwrap();
|
||||
for dpi in [24.9, 2400.1, 0.0, -300.0, f64::NAN, f64::INFINITY] {
|
||||
let e = paper_png(&prepared, PngOptions { dpi, colour: PngColour::Grey }, Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("25 to 2400 dpi"), "{dpi}: {e}");
|
||||
}
|
||||
for dpi in [25.0, 2400.0] {
|
||||
assert!(paper_png(&prepared, PngOptions { dpi, colour: PngColour::Grey }, Vec::new()).is_ok(), "{dpi}");
|
||||
}
|
||||
let ellipse = scene(
|
||||
p(20.0, 10.0),
|
||||
vec![Item::Stroke {
|
||||
path: vec![Seg2::Conic { a: p(0.0, 0.0), apex: p(5.0, 5.0), b: p(10.0, 0.0), w: 0.5 }],
|
||||
closed: false,
|
||||
width_mm: 0.35,
|
||||
pattern: None,
|
||||
}],
|
||||
);
|
||||
let e = paper_png(&ellipse.prepare().unwrap(), PngOptions::default(), Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("not supported yet"), "{e}");
|
||||
// 1,000 circles of 100 m at 2400 dpi, each about 19,000 points: over 2^24 in all. A small sheet,
|
||||
// so a cap that failed would cost seconds, not hours.
|
||||
let big = Loop2::circle(p(0.0, 0.0), 1e5);
|
||||
let circles = (0..1000).map(|_| Item::Fill { region: Region2 { outer: big.clone(), holes: vec![] } }).collect();
|
||||
let e =
|
||||
paper_png(&scene(p(20.0, 10.0), circles).prepare().unwrap(), PngOptions { dpi: 2400.0, colour: PngColour::Grey }, Vec::new()).unwrap_err();
|
||||
assert!(e.to_string().contains("16777216 points"), "{e}");
|
||||
}
|
||||
|
||||
/// The dark runs along row `y`, as pixel ranges.
|
||||
fn runs(image: &Image, y: usize) -> Vec<(usize, usize)> {
|
||||
let mut runs = Vec::new();
|
||||
let mut start = None;
|
||||
for x in 0..=image.info.width as usize {
|
||||
let dark = x < image.info.width as usize && image.at(x, y)[0] < 128;
|
||||
match (dark, start) {
|
||||
(true, None) => start = Some(x),
|
||||
(false, Some(s)) => {
|
||||
runs.push((s, x));
|
||||
start = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
runs
|
||||
}
|
||||
|
||||
/// The dashes, as millimetre ranges along a line of `length`, that SVG draws from a dasharray of
|
||||
/// one dash and gap and an offset: what a reader of the SVG's numbers expects.
|
||||
fn svg_dashes(dash: f64, gap: f64, offset: f64, length: f64) -> Vec<(f64, f64)> {
|
||||
let mut at = -offset;
|
||||
let mut dashes = Vec::new();
|
||||
while at < length {
|
||||
if at + dash > 0.0 {
|
||||
dashes.push((at.max(0.0), (at + dash).min(length)));
|
||||
}
|
||||
at += dash + gap;
|
||||
}
|
||||
dashes
|
||||
}
|
||||
|
||||
/// A 100 mm stroke dashed 4.2 and 1.05 mm (ISO 128-2's dashed line at d = 0.35 mm) has 20
|
||||
/// dashes, 19 whole and the first 0.25 mm of the 20th, at the SVG's positions to the pixel; the
|
||||
/// phase moves them, and one inside a gap starts the line in it. At 508 dpi a millimetre is 20
|
||||
/// pixels, and these ends fall between pixels.
|
||||
#[test]
|
||||
fn a_dashed_line_has_the_svgs_dashes_to_the_pixel() {
|
||||
for (phase_mm, count) in [(0.0, 20), (0.5, 20), (4.5, 19)] {
|
||||
let pattern = Some(Dashes { lengths_mm: vec![4.2, 1.05], phase_mm });
|
||||
let sheet =
|
||||
scene(p(110.0, 20.0), vec![Item::Stroke { path: vec![line(p(5.0, 10.0), p(105.0, 10.0))], closed: false, width_mm: 1.0, pattern }]);
|
||||
let (text, _) = crate::paper::paper_svg(&sheet.prepare().unwrap()).unwrap();
|
||||
let text = String::from_utf8(text).unwrap();
|
||||
let number = |name: &str| text.split(&format!("{name}=\"")).nth(1).map(|t| t.split('"').next().unwrap().to_string());
|
||||
let array: Vec<f64> = number("stroke-dasharray").unwrap().split(' ').map(|n| n.parse().unwrap()).collect();
|
||||
let offset: f64 = number("stroke-dashoffset").map_or(0.0, |n| n.parse().unwrap());
|
||||
let expected: Vec<(usize, usize)> = svg_dashes(array[0], array[1], offset, 100.0)
|
||||
.iter()
|
||||
.map(|(a, b)| (((5.0 + a) * 20.0).round() as usize, ((5.0 + b) * 20.0).round() as usize))
|
||||
.collect();
|
||||
assert_eq!(expected.len(), count, "{phase_mm}");
|
||||
let image = image(&sheet, PngOptions { dpi: 508.0, colour: PngColour::Grey });
|
||||
assert_eq!(runs(&image, 200), expected, "phase {phase_mm}");
|
||||
}
|
||||
let last = svg_dashes(4.2, 1.05, 0.0, 100.0).last().copied().unwrap();
|
||||
assert!((last.1 - last.0 - 0.25).abs() < 1e-9, "{last:?}");
|
||||
}
|
||||
|
||||
/// A closed square's pattern runs round its corners and joins at its start: 6 mm dashes and 2 mm
|
||||
/// gaps round a 10 mm square from its lower-left corner, anticlockwise.
|
||||
#[test]
|
||||
fn a_closed_strokes_dashes_run_round_its_corners() {
|
||||
let pattern = Some(Dashes { lengths_mm: vec![6.0, 2.0], phase_mm: 0.0 });
|
||||
let square = rectangle(p(5.0, 5.0), p(15.0, 15.0)).segs;
|
||||
let sheet = scene(p(20.0, 20.0), vec![Item::Stroke { path: square, closed: true, width_mm: 0.5, pattern }]);
|
||||
let image = image(&sheet, AT_254);
|
||||
// Pixel centres at (x, y) mm from the lower-left corner.
|
||||
let dark = |x: f64, y: f64| image.at((x * 10.0) as usize, ((20.0 - y) * 10.0) as usize)[0] < 128;
|
||||
// Along the bottom: dash 0-6, gap 6-8, dash 8-14 round the corner to 4 mm up the right side.
|
||||
assert!(dark(8.0, 5.0) && !dark(12.0, 5.0) && dark(14.0, 5.0) && dark(15.0, 7.0));
|
||||
// Gap 14-16 (4-6 mm up), dash 16-22 (6 mm up, round the top corner, 2 mm left).
|
||||
assert!(!dark(15.0, 10.0) && dark(15.0, 13.0) && dark(13.5, 15.0) && !dark(12.0, 15.0));
|
||||
// The last dash, 32-38, ends 2 mm above the start; the gap 38-40 reaches it.
|
||||
assert!(dark(5.0, 12.0) && !dark(5.0, 6.0));
|
||||
}
|
||||
|
||||
/// A line that falls in a gap draws nothing; one past tiny-skia's million dashes is refused, not
|
||||
/// drawn solid or left out; the dashes' points count against the sheet's.
|
||||
#[test]
|
||||
fn a_line_in_a_gap_draws_nothing_and_too_many_dashes_are_refused() {
|
||||
let mut sheet = Sheet { px: 1.0, height: 0.0, tolerance: 0.125, points: 0 };
|
||||
let line = |length: f32| {
|
||||
let mut builder = PathBuilder::new();
|
||||
builder.move_to(0.0, 0.0);
|
||||
builder.line_to(length, 0.0);
|
||||
builder.finish().unwrap()
|
||||
};
|
||||
let pattern = |lengths: &[i64], phase| GridDashes { lengths: lengths.to_vec(), phase };
|
||||
assert!(sheet.dash(&line(1.0), &pattern(&[1, 10], 2)).unwrap().is_none());
|
||||
assert_eq!(sheet.points, 0);
|
||||
assert!(sheet.dash(&line(1.0), &pattern(&[1, 10], 0)).unwrap().is_some());
|
||||
assert!(sheet.points > 0);
|
||||
let refused = sheet.dash(&line(3e6), &pattern(&[1, 1], 0)).unwrap_err();
|
||||
assert!(refused.to_string().contains("too many dashes"), "{refused}");
|
||||
sheet.points = MAX_POINTS - 3;
|
||||
assert!(sheet.dash(&line(100.0), &pattern(&[1, 1], 0)).unwrap_err().to_string().contains("points"));
|
||||
}
|
||||
+85
-175
@@ -1,63 +1,61 @@
|
||||
//! A paper scene as SVG (#4890, A3): one user unit a millimetre, the paper's size in mm, and the
|
||||
//! scene's own curves where SVG has them.
|
||||
//!
|
||||
//! - **Numbers** are whole nanometres, written as millimetres with up to six decimals: no exponent, no "-0",
|
||||
//! nothing that depends on the locale. They are also the writer's state, so a joint is written
|
||||
//! once and a closed path ends exactly on its first point.
|
||||
//! - **y is flipped** by writing the page height less y, so the file's numbers are page
|
||||
//! coordinates, with no transform. After the flip an anticlockwise arc turns the negative way,
|
||||
//! so its sweep flag is 0.
|
||||
//! - **Curves:** lines `L`, circular arcs `A` in pieces of at most a quarter turn (a half turn's
|
||||
//! centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`. Ellipses,
|
||||
//! hyperbolas and Béziers above degree 3 aren't written yet (A3b): a scene with one is refused.
|
||||
//! - **Numbers** are the scene on the nanometre grid ([`Prepared::on_grid`], whose rules give the
|
||||
//! joints, closures and merges), written as millimetres with up to six decimals: no exponent, no
|
||||
//! "-0", nothing that depends on the locale.
|
||||
//! - **y is flipped** by writing the page height less y, exact on the grid, so the file's numbers
|
||||
//! are page coordinates, with no transform. After the flip an anticlockwise arc turns the
|
||||
//! negative way, so its sweep flag is 0.
|
||||
//! - **Curves:** lines `L`, circular arcs `A` in the grid's pieces of at most a quarter turn (a half
|
||||
//! turn's centre is ill-conditioned once its ends are rounded), cubics `C`, parabolas `Q`.
|
||||
//! - **Paint:** strokes `stroke-width`, with butt caps, miter joins and a miter limit of 4 on the
|
||||
//! root; fills black, even-odd. One `<path>` per item, so each stays one object in an editor.
|
||||
//! - **Dashes** are the stroke's own `stroke-dasharray`, and `stroke-dashoffset` when its phase
|
||||
//! isn't 0, in millimetres: SVG runs the pattern along the whole path and round a closed one.
|
||||
//! - **Groups** are `<g data-object="…" data-kind="…">`: object ids repeat and start with a digit,
|
||||
//! so they can't be XML ids. No background: the page stays transparent, as cutters want.
|
||||
//!
|
||||
//! What the grid can't express is counted, never an error: a width under half a nanometre is
|
||||
//! written as one, and a piece ending within 10 nanometres of where the path is goes straight on
|
||||
//! to the next.
|
||||
|
||||
use std::fmt::Write;
|
||||
|
||||
use solidcraft_geom::paper::{Item, Prepared, arc_pieces};
|
||||
use solidcraft_geom::{Region2, Seg2, Vec2};
|
||||
use solidcraft_geom::paper::{Grid, GridDashes, GridItem, GridPath, GridPoint, GridReport, Piece, Prepared};
|
||||
|
||||
use crate::{IoError, MAX_DRAWING_BYTES, Result};
|
||||
|
||||
/// The largest number written, in millimetres either way: far past any scene's 2e5.
|
||||
const MAX_NUMBER_MM: f64 = 9e9;
|
||||
/// Pieces ending this many grid steps or fewer from where the path is are merged (1e-5 mm).
|
||||
const SLIVER_STEPS: i64 = 10;
|
||||
|
||||
/// What writing a scene did that the scene didn't say.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct SvgReport {
|
||||
/// Widths under half a nanometre, written as one nanometre.
|
||||
pub widths_snapped: usize,
|
||||
/// Pieces too short for the nanometre grid, merged into the next.
|
||||
pub pieces_merged: usize,
|
||||
}
|
||||
/// What writing a scene did that the scene didn't say: the grid's report.
|
||||
pub type SvgReport = GridReport;
|
||||
|
||||
/// A scene's SVG document, and what writing it did.
|
||||
pub fn paper_svg(scene: &Prepared) -> Result<(Vec<u8>, SvgReport)> {
|
||||
let mut w = Writer { out: String::new(), height: nano(scene.size_mm().y)?, report: SvgReport::default(), at: (0, 0), first: (0, 0) };
|
||||
let (width, height) = (number(nano(scene.size_mm().x)?), number(w.height));
|
||||
let on = scene.on_grid(Grid::NANOMETRE).map_err(|e| IoError::Invalid(e.to_string()))?;
|
||||
let mut w = Writer { out: String::new(), height: on.size.y };
|
||||
let (width, height) = (number(on.size.x), number(on.size.y));
|
||||
w.out.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
|
||||
let _ = writeln!(
|
||||
w.out,
|
||||
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"{width}mm\" height=\"{height}mm\" viewBox=\"0 0 {width} {height}\" \
|
||||
fill=\"none\" stroke=\"#000\" stroke-linecap=\"butt\" stroke-linejoin=\"miter\" stroke-miterlimit=\"4\">"
|
||||
);
|
||||
for group in scene.groups() {
|
||||
for group in &on.groups {
|
||||
let kind = serde_json::to_value(group.kind).ok().and_then(|v| v.as_str().map(str::to_string)).unwrap_or_default();
|
||||
let _ = writeln!(w.out, "<g data-object=\"{}\" data-kind=\"{kind}\">", group.object);
|
||||
for item in &group.items {
|
||||
match item {
|
||||
Item::Stroke { path, closed, width_mm } => w.stroke(path, *closed, *width_mm)?,
|
||||
Item::Fill { region } => w.fill(region)?,
|
||||
GridItem::Stroke { width, path, dashes } => {
|
||||
w.out.push_str("<path stroke-width=\"");
|
||||
push_number(&mut w.out, *width);
|
||||
if let Some(dashes) = dashes {
|
||||
w.dashes(dashes);
|
||||
}
|
||||
w.out.push_str("\" d=\"");
|
||||
w.path(path);
|
||||
}
|
||||
GridItem::Fill { loops } => {
|
||||
w.out.push_str("<path fill=\"#000\" stroke=\"none\" fill-rule=\"evenodd\" d=\"");
|
||||
loops.iter().for_each(|l| w.path(l));
|
||||
}
|
||||
}
|
||||
w.out.push_str("\"/>\n");
|
||||
if w.out.len() > MAX_DRAWING_BYTES {
|
||||
return Err(IoError::Invalid(format!("the SVG would be over {} MiB", MAX_DRAWING_BYTES >> 20)));
|
||||
}
|
||||
@@ -65,30 +63,15 @@ pub fn paper_svg(scene: &Prepared) -> Result<(Vec<u8>, SvgReport)> {
|
||||
w.out.push_str("</g>\n");
|
||||
}
|
||||
w.out.push_str("</svg>\n");
|
||||
Ok((w.out.into_bytes(), w.report))
|
||||
Ok((w.out.into_bytes(), on.report))
|
||||
}
|
||||
|
||||
/// A value in millimetres as whole nanometres.
|
||||
fn nano(v: f64) -> Result<i64> {
|
||||
let n = (v * 1e6).round();
|
||||
if n.abs() <= MAX_NUMBER_MM * 1e6 { Ok(n as i64) } else { Err(IoError::Invalid("a number too large (or not a number) for the SVG".into())) }
|
||||
}
|
||||
|
||||
/// 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 or arc.
|
||||
/// [`push_number`] as its own text, for the numbers written once per document.
|
||||
fn number(n: i64) -> String {
|
||||
let mut text = String::new();
|
||||
push_number(&mut text, n);
|
||||
@@ -99,141 +82,68 @@ struct Writer {
|
||||
out: String,
|
||||
/// The page height, in nanometres: y is written as this less y.
|
||||
height: i64,
|
||||
report: SvgReport,
|
||||
/// Where the path is, and where its subpath started, on the grid.
|
||||
at: (i64, i64),
|
||||
first: (i64, i64),
|
||||
}
|
||||
|
||||
impl Writer {
|
||||
/// A scene point on the page's grid.
|
||||
fn grid(&self, p: Vec2) -> Result<(i64, i64)> {
|
||||
Ok((nano(p.x)?, self.height - nano(p.y)?))
|
||||
}
|
||||
|
||||
fn point(&mut self, (x, y): (i64, i64)) {
|
||||
push_number(&mut self.out, x);
|
||||
fn point(&mut self, p: GridPoint) {
|
||||
push_number(&mut self.out, p.x);
|
||||
self.out.push(' ');
|
||||
push_number(&mut self.out, y);
|
||||
push_number(&mut self.out, self.height - p.y);
|
||||
}
|
||||
|
||||
/// Starts a subpath at `p`.
|
||||
fn move_to(&mut self, p: Vec2) -> Result<()> {
|
||||
let at = self.grid(p)?;
|
||||
/// A dashed stroke's attributes, written inside the open `stroke-width` value: it closes that
|
||||
/// value and leaves its own last one open.
|
||||
fn dashes(&mut self, dashes: &GridDashes) {
|
||||
self.out.push_str("\" stroke-dasharray=\"");
|
||||
for (i, length) in dashes.lengths.iter().enumerate() {
|
||||
if i > 0 {
|
||||
self.out.push(' ');
|
||||
}
|
||||
push_number(&mut self.out, *length);
|
||||
}
|
||||
if dashes.phase != 0 {
|
||||
self.out.push_str("\" stroke-dashoffset=\"");
|
||||
push_number(&mut self.out, dashes.phase);
|
||||
}
|
||||
}
|
||||
|
||||
/// A path's `d`: a closed one ends with `Z`, which draws its closing line.
|
||||
fn path(&mut self, path: &GridPath) {
|
||||
self.out.push('M');
|
||||
self.point(at);
|
||||
(self.at, self.first) = (at, at);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether a piece ending at `end` is too short to write: it is merged into the next. A path's
|
||||
/// last piece (`keep`) has no next, so it is written unless it has no length: an open path
|
||||
/// ends where it ends, a closed one on its first point exactly.
|
||||
fn merged(&mut self, end: (i64, i64), keep: bool) -> bool {
|
||||
if keep {
|
||||
return end == self.at;
|
||||
}
|
||||
let (dx, dy) = (end.0 - self.at.0, end.1 - self.at.1);
|
||||
let short = dx.abs() <= SLIVER_STEPS && dy.abs() <= SLIVER_STEPS && dx * dx + dy * dy <= SLIVER_STEPS * SLIVER_STEPS;
|
||||
if short {
|
||||
self.report.pieces_merged += 1;
|
||||
}
|
||||
short
|
||||
}
|
||||
|
||||
/// One piece, from where the path is: `closing` makes its end the subpath's first point, and
|
||||
/// `keep` marks the path's last piece ([`Writer::merged`]).
|
||||
fn piece(&mut self, seg: &Seg2, closing: bool, keep: bool) -> Result<()> {
|
||||
let end = if closing { self.first } else { self.grid(seg.end())? };
|
||||
match *seg {
|
||||
Seg2::Line { .. } => {
|
||||
if !self.merged(end, keep) {
|
||||
self.point(path.start);
|
||||
for piece in &path.pieces {
|
||||
match *piece {
|
||||
Piece::Line { to } => {
|
||||
self.out.push('L');
|
||||
self.point(end);
|
||||
self.at = end;
|
||||
self.point(to);
|
||||
}
|
||||
Piece::Arc { radius, clockwise, to } => {
|
||||
self.out.push('A');
|
||||
push_number(&mut self.out, radius);
|
||||
self.out.push(' ');
|
||||
push_number(&mut self.out, radius);
|
||||
let _ = write!(self.out, " 0 0 {} ", u8::from(clockwise));
|
||||
self.point(to);
|
||||
}
|
||||
Piece::Cubic { c1, c2, to } => {
|
||||
self.out.push('C');
|
||||
self.point(c1);
|
||||
self.out.push(' ');
|
||||
self.point(c2);
|
||||
self.out.push(' ');
|
||||
self.point(to);
|
||||
}
|
||||
Piece::Quadratic { c, to } => {
|
||||
self.out.push('Q');
|
||||
self.point(c);
|
||||
self.out.push(' ');
|
||||
self.point(to);
|
||||
}
|
||||
}
|
||||
Seg2::Arc { center, radius, start, sweep } => {
|
||||
let r = number(nano(radius)?);
|
||||
let flag = u8::from(sweep < 0.0);
|
||||
let mut ends = arc_pieces(center, radius, start, sweep).peekable();
|
||||
while let Some(p) = ends.next() {
|
||||
let final_piece = ends.peek().is_none();
|
||||
let to = if final_piece { end } else { self.grid(p)? };
|
||||
if !self.merged(to, keep && final_piece) {
|
||||
let _ = write!(self.out, "A{r} {r} 0 0 {flag} ");
|
||||
self.point(to);
|
||||
self.at = to;
|
||||
}
|
||||
}
|
||||
}
|
||||
Seg2::Cubic { p1, p2, .. } => {
|
||||
let (c1, c2) = (self.grid(p1)?, self.grid(p2)?);
|
||||
self.out.push('C');
|
||||
self.point(c1);
|
||||
self.out.push(' ');
|
||||
self.point(c2);
|
||||
self.out.push(' ');
|
||||
self.point(end);
|
||||
self.at = end;
|
||||
}
|
||||
Seg2::Conic { apex, w, .. } if (w - 1.0).abs() <= 1e-12 => {
|
||||
let c = self.grid(apex)?;
|
||||
self.out.push('Q');
|
||||
self.point(c);
|
||||
self.out.push(' ');
|
||||
self.point(end);
|
||||
self.at = end;
|
||||
}
|
||||
Seg2::Conic { .. } | Seg2::Bezier { .. } => {
|
||||
return Err(IoError::Invalid("not supported yet: SVG of ellipses, hyperbolas and Béziers above degree 3 (#4890, A3b)".into()));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A path's pieces after its `M`: a closed one ends exactly on its first point, a line back to
|
||||
/// it as `Z`.
|
||||
fn pieces(&mut self, path: &[Seg2], closed: bool) -> Result<()> {
|
||||
let Some((last, body)) = path.split_last() else { return Ok(()) };
|
||||
for seg in body {
|
||||
self.piece(seg, false, false)?;
|
||||
if path.closed {
|
||||
self.out.push('Z');
|
||||
}
|
||||
if !closed {
|
||||
return self.piece(last, false, true);
|
||||
}
|
||||
if !matches!(last, Seg2::Line { .. }) {
|
||||
self.piece(last, true, true)?;
|
||||
}
|
||||
self.out.push('Z');
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stroke(&mut self, path: &[Seg2], closed: bool, width_mm: f64) -> Result<()> {
|
||||
let Some(first) = path.first() else { return Ok(()) };
|
||||
let mut width = nano(width_mm)?;
|
||||
if width == 0 {
|
||||
width = 1;
|
||||
self.report.widths_snapped += 1;
|
||||
}
|
||||
self.out.push_str("<path stroke-width=\"");
|
||||
push_number(&mut self.out, width);
|
||||
self.out.push_str("\" d=\"");
|
||||
self.move_to(first.start())?;
|
||||
self.pieces(path, closed)?;
|
||||
self.out.push_str("\"/>\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn fill(&mut self, region: &Region2) -> Result<()> {
|
||||
self.out.push_str("<path fill=\"#000\" stroke=\"none\" fill-rule=\"evenodd\" d=\"");
|
||||
for l in region.loops() {
|
||||
let Some(first) = l.segs.first() else { continue };
|
||||
self.move_to(first.start())?;
|
||||
self.pieces(&l.segs, true)?;
|
||||
}
|
||||
self.out.push_str("\"/>\n");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use std::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
|
||||
use solidcraft_geom::paper::{Group, ObjectKind, Scene};
|
||||
use solidcraft_geom::{Loop2, Region2};
|
||||
use solidcraft_geom::paper::{Dashes, Group, Item, ObjectKind, Scene};
|
||||
use solidcraft_geom::{Loop2, Region2, Seg2, Vec2};
|
||||
|
||||
use super::*;
|
||||
use crate::{Geom2, read_svg};
|
||||
@@ -15,7 +15,7 @@ fn line(a: Vec2, b: Vec2) -> Seg2 {
|
||||
}
|
||||
|
||||
fn stroke(path: Vec<Seg2>, closed: bool, width_mm: f64) -> Item {
|
||||
Item::Stroke { path, closed, width_mm }
|
||||
Item::Stroke { path, closed, width_mm, pattern: None }
|
||||
}
|
||||
|
||||
/// Anticlockwise from `min`.
|
||||
@@ -101,14 +101,12 @@ fn cubics_and_parabolas_are_written_and_other_conics_refused() {
|
||||
}
|
||||
|
||||
/// Numbers are whole nanometres: no exponent, no "-0", trailing zeros trimmed; a width under half
|
||||
/// a nanometre is written as one and reported.
|
||||
/// a nanometre is written as one and reported (the grid's own rounding is `geom`'s test).
|
||||
#[test]
|
||||
fn numbers_are_whole_nanometres() {
|
||||
for (n, text) in [(0, "0"), (1, "0.000001"), (-1, "-0.000001"), (1_500_000, "1.5"), (-420_000_000, "-420"), (123_456_789, "123.456789")] {
|
||||
assert_eq!(number(n), text);
|
||||
}
|
||||
assert_eq!((nano(-0.0).unwrap(), nano(4e-7).unwrap(), nano(6e-7).unwrap()), (0, 0, 1));
|
||||
assert!(nano(f64::NAN).is_err() && nano(1e10).is_err());
|
||||
let thin = sheet(vec![stroke(vec![line(p(0.0, 0.0), p(1.0, 0.0))], false, 1e-9)]);
|
||||
let (text, report) = svg(&thin);
|
||||
assert!(text.contains("stroke-width=\"0.000001\""), "{text}");
|
||||
@@ -163,3 +161,16 @@ fn the_svg_reader_reads_it_back() {
|
||||
let (c, a, b) = arcs[0];
|
||||
assert!(c.dist(p(50.0, 50.0)) < 3e-6 && a.dist(p(60.0, 50.0)) < 3e-6 && b.dist(p(50.0, 60.0)) < 3e-6, "{:?}", arcs[0]);
|
||||
}
|
||||
|
||||
/// A dashed stroke carries its pattern in millimetres, its offset only when its phase isn't 0.
|
||||
#[test]
|
||||
fn a_dashed_stroke_has_its_dasharray_and_offset() {
|
||||
let path = |phase_mm| {
|
||||
let pattern = Some(Dashes { lengths_mm: vec![4.2, 1.05], phase_mm });
|
||||
let scene = sheet(vec![Item::Stroke { path: vec![line(p(5.0, 10.0), p(105.0, 10.0))], closed: false, width_mm: 1.0, pattern }]);
|
||||
let (text, _) = svg(&scene);
|
||||
text.lines().find(|l| l.starts_with("<path")).unwrap().to_string()
|
||||
};
|
||||
assert_eq!(path(0.0), "<path stroke-width=\"1\" stroke-dasharray=\"4.2 1.05\" d=\"M5 287L105 287\"/>");
|
||||
assert_eq!(path(0.5), "<path stroke-width=\"1\" stroke-dasharray=\"4.2 1.05\" stroke-dashoffset=\"0.5\" d=\"M5 287L105 287\"/>");
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
# WIP PDF serial-runner prerequisite source proposal
|
||||
|
||||
Isolated runner prerequisite for the actual PDF base of PR #7626. Pending owner coordination: https://github.com/tangency-labs/solidcraft/issues/5425#issuecomment-6415005697 . This is a source proposal only, not applied to the PDF P2 branch and not executed. It preserves the original gates rather than replacing them with a selected test subset. The source delta comes from the previously published #5494 runner history; aggregate render changes are not included.
|
||||
|
||||
This branch preserves unfinished work at Judit's request. It does not replace the existing contributor claims or PRs, and is not ready for merge. Original parent history and authorship are retained. No tests were run to create this preservation branch.
|
||||
+159
-32
@@ -1,9 +1,10 @@
|
||||
//! `cargo xtask test`: build the workspace's tests once, then run every test binary at the same
|
||||
//! time. `cargo test` runs them one after another, so one slow binary held up all the others;
|
||||
//! the doc tests and any other `side` jobs run alongside on their own thread.
|
||||
//! `cargo xtask test`: build the workspace's tests once, then run every test binary.
|
||||
//! By default they all run at once, with sequential doc/wasm `side` jobs alongside.
|
||||
//! SOLIDCRAFT_TEST_JOBS opts into a shared bound for test binaries and those side jobs.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Mutex, mpsc};
|
||||
use std::time::Instant;
|
||||
|
||||
use crate::{cargo, root};
|
||||
@@ -16,45 +17,83 @@ struct TestBin {
|
||||
}
|
||||
|
||||
/// Build the tests with `cargo_args` (e.g. `--locked`), run each binary with `test_args`, and run
|
||||
/// the `side` jobs one after another meanwhile. Each prints a line when it ends; a failure prints
|
||||
/// its whole output.
|
||||
/// the `side` jobs in order. A configured job bound includes the sequential side-job worker.
|
||||
/// Each prints a line when it ends; a failure prints its whole output and does not cancel work.
|
||||
pub fn run(cargo_args: &[&str], test_args: &[&str], side: Vec<(String, Command)>) -> Result<(), String> {
|
||||
let limit = job_limit(std::env::var_os("SOLIDCRAFT_TEST_JOBS").as_deref())?;
|
||||
let bins = build(cargo_args)?;
|
||||
let start = Instant::now();
|
||||
let (tx, rx) = mpsc::channel::<(String, Result<String, String>, f64)>();
|
||||
let side_count = side.len();
|
||||
let mut batches = Vec::with_capacity(bins.len() + 1);
|
||||
if !side.is_empty() {
|
||||
batches.push(side);
|
||||
}
|
||||
for b in &bins {
|
||||
let mut c = Command::new(&b.exe);
|
||||
c.args(test_args).current_dir(&b.dir).env("CARGO_MANIFEST_DIR", &b.dir);
|
||||
batches.push(vec![(b.label.clone(), c)]);
|
||||
}
|
||||
let jobs = limit.unwrap_or(batches.len()).min(batches.len());
|
||||
eprintln!("test: {} binaries, {side_count} side jobs; at most {jobs} concurrent top-level commands", bins.len());
|
||||
let mut failed = Vec::new();
|
||||
std::thread::scope(|scope| {
|
||||
for b in &bins {
|
||||
let tx = tx.clone();
|
||||
scope.spawn(move || {
|
||||
run_bounded(
|
||||
batches,
|
||||
jobs,
|
||||
|batch, tx| {
|
||||
for (label, c) in batch {
|
||||
let t0 = Instant::now();
|
||||
let mut c = Command::new(&b.exe);
|
||||
c.args(test_args).current_dir(&b.dir).env("CARGO_MANIFEST_DIR", &b.dir);
|
||||
let _ = tx.send((b.label.clone(), finish(c), t0.elapsed().as_secs_f64()));
|
||||
});
|
||||
}
|
||||
let tx_side = tx.clone();
|
||||
scope.spawn(move || {
|
||||
for (label, c) in side {
|
||||
let t0 = Instant::now();
|
||||
let _ = tx_side.send((label, finish(c), t0.elapsed().as_secs_f64()));
|
||||
let _ = tx.send((label, finish(c), t0.elapsed().as_secs_f64()));
|
||||
}
|
||||
});
|
||||
drop(tx);
|
||||
for (label, result, secs) in rx {
|
||||
match result {
|
||||
Ok(summary) => println!("ok {label:<44} {secs:6.1}s {summary}"),
|
||||
Err(output) => {
|
||||
println!("FAIL {label:<44} {secs:6.1}s\n{output}");
|
||||
failed.push(label);
|
||||
}
|
||||
},
|
||||
|(label, result, secs)| match result {
|
||||
Ok(summary) => println!("ok {label:<44} {secs:6.1}s {summary}"),
|
||||
Err(output) => {
|
||||
println!("FAIL {label:<44} {secs:6.1}s\n{output}");
|
||||
failed.push(label);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
println!("test: {} binaries in {:.1}s", bins.len(), start.elapsed().as_secs_f64());
|
||||
if failed.is_empty() { Ok(()) } else { Err(format!("failed: {}", failed.join(", "))) }
|
||||
}
|
||||
|
||||
/// An absent limit preserves the existing unbounded default; invalid input fails before the test build.
|
||||
fn job_limit(value: Option<&OsStr>) -> Result<Option<usize>, String> {
|
||||
let Some(value) = value else { return Ok(None) };
|
||||
value
|
||||
.to_str()
|
||||
.and_then(|v| v.parse::<usize>().ok())
|
||||
.filter(|n| *n > 0)
|
||||
.map(Some)
|
||||
.ok_or_else(|| "SOLIDCRAFT_TEST_JOBS must be a positive integer".into())
|
||||
}
|
||||
|
||||
/// Workers only hold the queue lock while taking a job. Reporting remains live, and neither
|
||||
/// a failed job nor a failed side command removes any remaining work from the queue.
|
||||
fn run_bounded<T: Send, R: Send>(tasks: Vec<T>, jobs: usize, work: impl Fn(T, &mpsc::Sender<R>) + Sync, mut report: impl FnMut(R)) {
|
||||
let workers = jobs.max(1).min(tasks.len());
|
||||
let queue = Mutex::new(tasks.into_iter());
|
||||
let (tx, rx) = mpsc::channel();
|
||||
std::thread::scope(|scope| {
|
||||
for _ in 0..workers {
|
||||
let queue = &queue;
|
||||
let work = &work;
|
||||
let tx = tx.clone();
|
||||
scope.spawn(move || {
|
||||
loop {
|
||||
let task = queue.lock().unwrap_or_else(std::sync::PoisonError::into_inner).next();
|
||||
let Some(task) = task else { break };
|
||||
work(task, &tx);
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
for result in rx {
|
||||
report(result);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Run to the end: the last `test result:` line on success, all output on failure.
|
||||
fn finish(mut c: Command) -> Result<String, String> {
|
||||
let out = c.stdin(Stdio::null()).output().map_err(|e| format!("failed to spawn: {e}"))?;
|
||||
@@ -103,3 +142,91 @@ pub fn doc_tests(cargo_args: &[&str], test_args: &[&str]) -> (String, Command) {
|
||||
c.args(["test", "--workspace", "--profile", "ci", "--doc"]).args(cargo_args).arg("--").args(test_args);
|
||||
("doc tests".into(), c)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{job_limit, run_bounded};
|
||||
use std::ffi::OsStr;
|
||||
use std::sync::Barrier;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
#[test]
|
||||
fn job_limit_is_opt_in_and_rejects_invalid_values() {
|
||||
assert_eq!(job_limit(None).unwrap(), None);
|
||||
for value in [1, 2, usize::MAX] {
|
||||
assert_eq!(job_limit(Some(OsStr::new(&value.to_string()))).unwrap(), Some(value));
|
||||
}
|
||||
for value in ["", "0", "-1", "two", "1.5", " 2", "2 ", "184467440737095516150"] {
|
||||
assert!(job_limit(Some(OsStr::new(value))).is_err(), "{value:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_workers_run_every_job_after_failure_with_budgets_one_and_two() {
|
||||
for budget in [1, 2] {
|
||||
let active = AtomicUsize::new(0);
|
||||
let peak = AtomicUsize::new(0);
|
||||
let first_wave = Barrier::new(budget);
|
||||
let mut results = Vec::new();
|
||||
run_bounded(
|
||||
(0..8).collect(),
|
||||
budget,
|
||||
|id, tx| {
|
||||
let now = active.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
peak.fetch_max(now, Ordering::SeqCst);
|
||||
if id < budget {
|
||||
first_wave.wait();
|
||||
}
|
||||
active.fetch_sub(1, Ordering::SeqCst);
|
||||
let outcome = if id == 0 { Err("deliberate first-job failure") } else { Ok(()) };
|
||||
tx.send((id, outcome)).unwrap();
|
||||
},
|
||||
|result| results.push(result),
|
||||
);
|
||||
assert_eq!(peak.load(Ordering::SeqCst), budget);
|
||||
assert_eq!(active.load(Ordering::SeqCst), 0);
|
||||
results.sort_by_key(|(id, _)| *id);
|
||||
assert_eq!(results.iter().map(|(id, _)| *id).collect::<Vec<_>>(), (0..8).collect::<Vec<_>>());
|
||||
assert_eq!(results.iter().filter(|(_, result)| result.is_err()).count(), 1);
|
||||
assert_eq!(results[0].1, Err("deliberate first-job failure"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn side_batch_keeps_order_and_failure_does_not_skip_docs_or_binaries() {
|
||||
for budget in [1, 2] {
|
||||
let batches = vec![
|
||||
vec![("wasm", Err("deliberate wasm failure")), ("doc tests", Ok("passed"))],
|
||||
vec![("test one", Ok("passed"))],
|
||||
vec![("test two", Ok("passed"))],
|
||||
];
|
||||
let mut results = Vec::new();
|
||||
run_bounded(
|
||||
batches,
|
||||
budget,
|
||||
|batch, tx| {
|
||||
for result in batch {
|
||||
tx.send(result).unwrap();
|
||||
}
|
||||
},
|
||||
|result| results.push(result),
|
||||
);
|
||||
assert_eq!(results.len(), 4);
|
||||
assert!(results.iter().position(|(label, _)| *label == "wasm") < results.iter().position(|(label, _)| *label == "doc tests"));
|
||||
results.sort_by_key(|(label, _)| *label);
|
||||
assert_eq!(
|
||||
results,
|
||||
vec![("doc tests", Ok("passed")), ("test one", Ok("passed")), ("test two", Ok("passed")), ("wasm", Err("deliberate wasm failure"))]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_queue_and_excess_budget_do_not_invent_jobs() {
|
||||
let mut results = Vec::new();
|
||||
run_bounded(Vec::<usize>::new(), 2, |id, tx| tx.send(id).unwrap(), |id| results.push(id));
|
||||
assert!(results.is_empty());
|
||||
run_bounded(vec![7], usize::MAX, |id, tx| tx.send(id).unwrap(), |id| results.push(id));
|
||||
assert_eq!(results, [7]);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user