feat(drawings): generate bounded polygon hatch marks
This commit is contained in:
1 parent
3dc7804c28
commit
009fe45bdc
7 files changed
+1869
-25
No files matched your search
@@ -16,12 +16,18 @@
|
||||
//! drawing records and paper-scene construction are separate from this model. Readers
|
||||
//! must also bound encoded bytes and allocations before constructing the records.
|
||||
|
||||
mod budget;
|
||||
mod clip;
|
||||
mod generate;
|
||||
|
||||
use std::f64::consts::FRAC_PI_4;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::Vec2;
|
||||
|
||||
pub use generate::{Mark, generate};
|
||||
|
||||
/// The most parallel-line families in one pattern.
|
||||
pub const MAX_FAMILIES: usize = 64;
|
||||
/// The most entries in one family's repeating dash sequence.
|
||||
@@ -131,6 +137,10 @@ impl Pattern {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod clip_tests;
|
||||
#[cfg(test)]
|
||||
mod generate_tests;
|
||||
#[cfg(test)]
|
||||
#[path = "hatch_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,76 @@
|
||||
//! One cumulative budget for preparation, clipping and pattern expansion.
|
||||
|
||||
use super::Invalid;
|
||||
|
||||
/// Internal limits can tighten, but never enlarge, the production ceilings.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Limits {
|
||||
pub input_pieces: usize,
|
||||
pub candidate_lines: usize,
|
||||
pub work: usize,
|
||||
pub events: usize,
|
||||
pub dash_steps: usize,
|
||||
pub marks: usize,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self { input_pieces: 8192, candidate_lines: 10000, work: 2000000, events: 65536, dash_steps: 200000, marks: 40000 }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Budget {
|
||||
limits: Limits,
|
||||
used: Limits,
|
||||
}
|
||||
|
||||
impl Default for Budget {
|
||||
fn default() -> Self {
|
||||
Self::new(Limits::default())
|
||||
}
|
||||
}
|
||||
|
||||
impl Budget {
|
||||
pub fn new(limits: Limits) -> Self {
|
||||
Self { limits, used: Limits { input_pieces: 0, candidate_lines: 0, work: 0, events: 0, dash_steps: 0, marks: 0 } }
|
||||
}
|
||||
|
||||
pub fn input_pieces(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(&mut self.used.input_pieces, n, self.limits.input_pieces.min(Limits::default().input_pieces), "input piece budget exhausted")
|
||||
}
|
||||
|
||||
pub fn candidate_lines(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(
|
||||
&mut self.used.candidate_lines,
|
||||
n,
|
||||
self.limits.candidate_lines.min(Limits::default().candidate_lines),
|
||||
"candidate line budget exhausted",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn work(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(&mut self.used.work, n, self.limits.work.min(Limits::default().work), "geometry work budget exhausted")
|
||||
}
|
||||
|
||||
pub fn events(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(&mut self.used.events, n, self.limits.events.min(Limits::default().events), "boundary event budget exhausted")
|
||||
}
|
||||
|
||||
pub fn dash_steps(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(&mut self.used.dash_steps, n, self.limits.dash_steps.min(Limits::default().dash_steps), "dash step budget exhausted")
|
||||
}
|
||||
|
||||
pub fn marks(&mut self, n: usize) -> Result<(), Invalid> {
|
||||
charge(&mut self.used.marks, n, self.limits.marks.min(Limits::default().marks), "output mark budget exhausted")
|
||||
}
|
||||
}
|
||||
|
||||
fn charge(used: &mut usize, n: usize, limit: usize, message: &'static str) -> Result<(), Invalid> {
|
||||
let next = used.checked_add(n).ok_or(Invalid(message))?;
|
||||
if next > limit {
|
||||
return Err(Invalid(message));
|
||||
}
|
||||
*used = next;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
//! Analytic Line-only clipping. Uncertain predicates refuse the whole operation.
|
||||
//!
|
||||
//! Preparation proves simple, exactly closed loops and disjoint interior holes.
|
||||
//! Consequently even-odd crossings equal outer minus the union of holes. Boundary
|
||||
//! intervals are removed separately; isolated contacts split, never join, spans.
|
||||
|
||||
use crate::{Region2, Seg2, Vec2};
|
||||
|
||||
use super::budget::{Budget, Limits};
|
||||
use super::{Invalid, MAX_LENGTH_MM};
|
||||
|
||||
type Result<T> = std::result::Result<T, Invalid>;
|
||||
const UNCERTAIN: Invalid = Invalid("unresolved clipping arithmetic");
|
||||
|
||||
/// A closed enclosure of a real arithmetic result on represented f64 inputs.
|
||||
/// This is deliberately a filter, not an arbitrary-precision fallback.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Bound {
|
||||
lo: f64,
|
||||
hi: f64,
|
||||
}
|
||||
|
||||
impl Bound {
|
||||
fn point(x: f64) -> Result<Self> {
|
||||
Self::new(x, x)
|
||||
}
|
||||
|
||||
fn new(lo: f64, hi: f64) -> Result<Self> {
|
||||
if lo.is_finite() && hi.is_finite() && lo <= hi { Ok(Self { lo, hi }) } else { Err(UNCERTAIN) }
|
||||
}
|
||||
|
||||
fn add(self, other: Self) -> Result<Self> {
|
||||
let low = sum(self.lo, other.lo)?;
|
||||
let high = sum(self.hi, other.hi)?;
|
||||
Self::new(low.lo, high.hi)
|
||||
}
|
||||
|
||||
fn neg(self) -> Self {
|
||||
Self { lo: -self.hi, hi: -self.lo }
|
||||
}
|
||||
|
||||
fn sub(self, other: Self) -> Result<Self> {
|
||||
self.add(other.neg())
|
||||
}
|
||||
|
||||
fn mul(self, other: Self) -> Result<Self> {
|
||||
let mut lo = f64::INFINITY;
|
||||
let mut hi = f64::NEG_INFINITY;
|
||||
for (a, b) in [(self.lo, other.lo), (self.lo, other.hi), (self.hi, other.lo), (self.hi, other.hi)] {
|
||||
let v = product(a, b)?;
|
||||
lo = lo.min(v.lo);
|
||||
hi = hi.max(v.hi);
|
||||
}
|
||||
Self::new(lo, hi)
|
||||
}
|
||||
|
||||
fn div(self, other: Self) -> Result<Self> {
|
||||
if other.lo <= 0.0 && other.hi >= 0.0 {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
let mut lo = f64::INFINITY;
|
||||
let mut hi = f64::NEG_INFINITY;
|
||||
for (a, b) in [(self.lo, other.lo), (self.lo, other.hi), (self.hi, other.lo), (self.hi, other.hi)] {
|
||||
let q = a / b;
|
||||
let v = if a == 0.0 || b.abs() == 1.0 || a == b || a == -b { Self::point(q)? } else { Self::new(q.next_down(), q.next_up())? };
|
||||
lo = lo.min(v.lo);
|
||||
hi = hi.max(v.hi);
|
||||
}
|
||||
Self::new(lo, hi)
|
||||
}
|
||||
|
||||
fn sign(self) -> Result<i8> {
|
||||
if self.lo > 0.0 {
|
||||
Ok(1)
|
||||
} else if self.hi < 0.0 {
|
||||
Ok(-1)
|
||||
} else if self.lo == 0.0 && self.hi == 0.0 {
|
||||
Ok(0)
|
||||
} else {
|
||||
Err(UNCERTAIN)
|
||||
}
|
||||
}
|
||||
|
||||
fn middle(self) -> Result<f64> {
|
||||
let value = self.lo + (self.hi - self.lo) * 0.5;
|
||||
if value.is_finite() && value >= self.lo && value <= self.hi { Ok(value) } else { Err(UNCERTAIN) }
|
||||
}
|
||||
}
|
||||
|
||||
// Error-free addition (with gradual underflow). Reject overflow before using
|
||||
// the residual. Exact operations retain exact zero, rather than an EPS band.
|
||||
fn sum(a: f64, b: f64) -> Result<Bound> {
|
||||
let value = a + b;
|
||||
if !value.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
let part = value - a;
|
||||
let error = (a - (value - part)) + (b - part);
|
||||
if !error.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
Bound::new(if error < 0.0 { value.next_down() } else { value }, if error > 0.0 { value.next_up() } else { value })
|
||||
}
|
||||
|
||||
fn product(a: f64, b: f64) -> Result<Bound> {
|
||||
let value = a * b;
|
||||
if !value.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
if a == 0.0 || b == 0.0 || a.abs() == 1.0 || b.abs() == 1.0 {
|
||||
return Bound::point(value);
|
||||
}
|
||||
// Bound the exact product's quantum from BOTH operands, not the exponent
|
||||
// of its rounded result (which can carry across a power-of-two boundary).
|
||||
// If this quantum is smaller than the least subnormal, even a normal
|
||||
// product can have a nonzero FMA residual that rounds to zero.
|
||||
if quantum_exponent(a) + quantum_exponent(b) < -1074 {
|
||||
return Bound::new(value.next_down(), value.next_up());
|
||||
}
|
||||
// Here the exact product and the rounded value are both multiples of
|
||||
// 2^-1074 or larger. A nonzero residual therefore cannot round to zero.
|
||||
let error = a.mul_add(b, -value);
|
||||
if !error.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
Bound::new(if error < 0.0 { value.next_down() } else { value }, if error > 0.0 { value.next_up() } else { value })
|
||||
}
|
||||
|
||||
fn quantum_exponent(value: f64) -> i32 {
|
||||
let exponent = ((value.to_bits() >> 52) & 0x7ff) as i32;
|
||||
if exponent == 0 { -1074 } else { exponent - 1075 }
|
||||
}
|
||||
|
||||
fn difference(a: f64, b: f64) -> Result<Bound> {
|
||||
sum(a, -b)
|
||||
}
|
||||
|
||||
fn orient(a: Vec2, b: Vec2, p: Vec2) -> Result<i8> {
|
||||
let ax = difference(b.x, a.x)?;
|
||||
let ay = difference(b.y, a.y)?;
|
||||
let px = difference(p.x, a.x)?;
|
||||
let py = difference(p.y, a.y)?;
|
||||
ax.mul(py)?.sub(ay.mul(px)?)?.sign()
|
||||
}
|
||||
|
||||
fn in_box(p: Vec2, a: Vec2, b: Vec2) -> bool {
|
||||
p.x >= a.x.min(b.x) && p.x <= a.x.max(b.x) && p.y >= a.y.min(b.y) && p.y <= a.y.max(b.y)
|
||||
}
|
||||
|
||||
fn intersect(a: Vec2, b: Vec2, c: Vec2, d: Vec2) -> Result<bool> {
|
||||
if a.x.max(b.x) < c.x.min(d.x) || c.x.max(d.x) < a.x.min(b.x) || a.y.max(b.y) < c.y.min(d.y) || c.y.max(d.y) < a.y.min(b.y) {
|
||||
return Ok(false);
|
||||
}
|
||||
let ab_c = orient(a, b, c)?;
|
||||
let ab_d = orient(a, b, d)?;
|
||||
let cd_a = orient(c, d, a)?;
|
||||
let cd_b = orient(c, d, b)?;
|
||||
Ok((ab_c == 0 && in_box(c, a, b))
|
||||
|| (ab_d == 0 && in_box(d, a, b))
|
||||
|| (cd_a == 0 && in_box(a, c, d))
|
||||
|| (cd_b == 0 && in_box(b, c, d))
|
||||
|| (ab_c * ab_d < 0 && cd_a * cd_b < 0))
|
||||
}
|
||||
|
||||
fn push<T>(items: &mut Vec<T>, item: T) -> Result<()> {
|
||||
items.try_reserve(1).map_err(|_| Invalid("clipping allocation failed"))?;
|
||||
items.push(item);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn edge(points: &[Vec2], i: usize) -> Result<(Vec2, Vec2)> {
|
||||
let a = points.get(i).copied().ok_or(Invalid("invalid prepared edge"))?;
|
||||
let next = if i + 1 == points.len() { 0 } else { i + 1 };
|
||||
let b = points.get(next).copied().ok_or(Invalid("invalid prepared edge"))?;
|
||||
Ok((a, b))
|
||||
}
|
||||
|
||||
fn simple(points: &[Vec2], budget: &mut Budget) -> Result<()> {
|
||||
for i in 0..points.len() {
|
||||
let (a, b) = edge(points, i)?;
|
||||
for j in i + 1..points.len() {
|
||||
budget.work(1)?;
|
||||
let (c, d) = edge(points, j)?;
|
||||
if j == i + 1 || (i == 0 && j + 1 == points.len()) {
|
||||
let (p, q, r) = if j == i + 1 { (a, b, d) } else { (c, d, b) };
|
||||
if orient(p, q, r)? == 0 && !in_box(q, p, r) {
|
||||
return Err(Invalid("overlapping adjacent boundary edges"));
|
||||
}
|
||||
} else if intersect(a, b, c, d)? {
|
||||
return Err(Invalid("boundary is not a simple loop"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn separate(a: &[Vec2], b: &[Vec2], budget: &mut Budget) -> Result<()> {
|
||||
for i in 0..a.len() {
|
||||
let (p, q) = edge(a, i)?;
|
||||
for j in 0..b.len() {
|
||||
budget.work(1)?;
|
||||
let (r, s) = edge(b, j)?;
|
||||
if intersect(p, q, r, s)? {
|
||||
return Err(Invalid("region boundaries touch or intersect"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn inside(points: &[Vec2], p: Vec2, budget: &mut Budget) -> Result<bool> {
|
||||
let mut parity = false;
|
||||
for i in 0..points.len() {
|
||||
budget.work(1)?;
|
||||
let (a, b) = edge(points, i)?;
|
||||
let crosses = (a.y > p.y) != (b.y > p.y);
|
||||
if crosses || in_box(p, a, b) {
|
||||
let side = orient(a, b, p)?;
|
||||
if side == 0 && in_box(p, a, b) {
|
||||
return Err(Invalid("region boundaries touch"));
|
||||
}
|
||||
if crosses && (side > 0) == (b.y > a.y) {
|
||||
parity = !parity;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(parity)
|
||||
}
|
||||
|
||||
/// Owned and immutable after complete, bounded topology validation.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct PreparedRegion {
|
||||
loops: Vec<Vec<Vec2>>,
|
||||
}
|
||||
|
||||
impl PreparedRegion {
|
||||
pub fn new(region: &Region2, budget: &mut Budget) -> Result<Self> {
|
||||
if region.holes.len() > Limits::default().input_pieces / 3 {
|
||||
return Err(Invalid("too many region holes"));
|
||||
}
|
||||
let mut loops = Vec::new();
|
||||
for boundary in region.loops() {
|
||||
let n = boundary.segs.len();
|
||||
budget.input_pieces(n)?;
|
||||
budget.work(n)?;
|
||||
if n < 3 {
|
||||
return Err(Invalid("a polygon loop needs at least three edges"));
|
||||
}
|
||||
let mut points = Vec::new();
|
||||
for (i, seg) in boundary.segs.iter().enumerate() {
|
||||
seg.check(MAX_LENGTH_MM).map_err(Invalid)?;
|
||||
let Seg2::Line { a, b } = *seg else { return Err(Invalid("not supported yet: non-Line hatch boundary")) };
|
||||
let next = boundary.segs.get(if i + 1 == n { 0 } else { i + 1 }).ok_or(Invalid("invalid boundary edge"))?;
|
||||
let Seg2::Line { a: next_start, .. } = *next else { return Err(Invalid("not supported yet: non-Line hatch boundary")) };
|
||||
if b != next_start {
|
||||
return Err(Invalid("hatch boundary must be exactly closed"));
|
||||
}
|
||||
push(&mut points, a)?;
|
||||
}
|
||||
simple(&points, budget)?;
|
||||
push(&mut loops, points)?;
|
||||
}
|
||||
let (outer, holes) = loops.split_first().ok_or(Invalid("missing outer boundary"))?;
|
||||
for (i, hole) in holes.iter().enumerate() {
|
||||
separate(outer, hole, budget)?;
|
||||
let p = hole.first().copied().ok_or(Invalid("empty hole"))?;
|
||||
if !inside(outer, p, budget)? {
|
||||
return Err(Invalid("hole is not strictly inside outer boundary"));
|
||||
}
|
||||
for other in holes.iter().skip(i + 1) {
|
||||
separate(hole, other, budget)?;
|
||||
let q = other.first().copied().ok_or(Invalid("empty hole"))?;
|
||||
if inside(hole, q, budget)? || inside(other, p, budget)? {
|
||||
return Err(Invalid("holes must not overlap or nest"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self { loops })
|
||||
}
|
||||
|
||||
/// Encloses all vertex projections, including possible extremal candidates.
|
||||
pub fn normal_bounds(&self, frame: &Frame, budget: &mut Budget) -> Result<(f64, f64)> {
|
||||
let mut lo = f64::INFINITY;
|
||||
let mut hi = f64::NEG_INFINITY;
|
||||
for points in &self.loops {
|
||||
for &p in points {
|
||||
budget.work(1)?;
|
||||
let (_, h) = frame.project(p)?;
|
||||
lo = lo.min(h.lo);
|
||||
hi = hi.max(h.hi);
|
||||
}
|
||||
}
|
||||
let bounds = Bound::new(lo, hi)?;
|
||||
Ok((bounds.lo, bounds.hi))
|
||||
}
|
||||
|
||||
pub fn clip(&self, frame: &Frame, offset: f64, budget: &mut Budget) -> Result<ClippedLine> {
|
||||
let offset = Bound::point(offset)?;
|
||||
let mut events = Vec::new();
|
||||
let mut base = 0usize;
|
||||
for points in &self.loops {
|
||||
let mut projected = Vec::new();
|
||||
for (i, &p) in points.iter().enumerate() {
|
||||
budget.work(1)?;
|
||||
let (t, height) = frame.project(p)?;
|
||||
let h = height.sub(offset)?;
|
||||
let sign = h.sign()?;
|
||||
let key = base.checked_add(i).ok_or(UNCERTAIN)?;
|
||||
let vertex = Projected { t, h, sign, key };
|
||||
if sign == 0 {
|
||||
event(&mut events, Event { at: t, key: Key::Vertex(key), toggle: false, boundary: 0 }, budget)?;
|
||||
}
|
||||
push(&mut projected, vertex)?;
|
||||
}
|
||||
for (i, a) in projected.iter().copied().enumerate() {
|
||||
budget.work(1)?;
|
||||
let b = projected.get(if i + 1 == projected.len() { 0 } else { i + 1 }).copied().ok_or(UNCERTAIN)?;
|
||||
if a.sign == 0 && b.sign == 0 {
|
||||
let (first, last) = if a.t.hi < b.t.lo {
|
||||
(a, b)
|
||||
} else if b.t.hi < a.t.lo {
|
||||
(b, a)
|
||||
} else {
|
||||
return Err(UNCERTAIN);
|
||||
};
|
||||
event(&mut events, Event { at: first.t, key: Key::Vertex(first.key), toggle: false, boundary: 1 }, budget)?;
|
||||
event(&mut events, Event { at: last.t, key: Key::Vertex(last.key), toggle: false, boundary: -1 }, budget)?;
|
||||
} else if (a.sign > 0) != (b.sign > 0) {
|
||||
let (at, key) = if a.sign == 0 {
|
||||
(a.t, Key::Vertex(a.key))
|
||||
} else if b.sign == 0 {
|
||||
(b.t, Key::Vertex(b.key))
|
||||
} else {
|
||||
let fraction = a.h.neg().div(b.h.sub(a.h)?)?;
|
||||
(a.t.add(b.t.sub(a.t)?.mul(fraction)?)?, Key::Edge(a.key))
|
||||
};
|
||||
event(&mut events, Event { at, key, toggle: true, boundary: 0 }, budget)?;
|
||||
}
|
||||
}
|
||||
base = base.checked_add(points.len()).ok_or(UNCERTAIN)?;
|
||||
}
|
||||
sweep(events, budget)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Frame {
|
||||
origin: Vec2,
|
||||
tangent: Vec2,
|
||||
norm_squared: Bound,
|
||||
}
|
||||
|
||||
impl Frame {
|
||||
pub fn new(origin: Vec2, tangent: Vec2) -> Result<Self> {
|
||||
if !origin.is_finite() || origin.x.abs() > MAX_LENGTH_MM || origin.y.abs() > MAX_LENGTH_MM || !tangent.is_finite() {
|
||||
return Err(Invalid("invalid hatch frame"));
|
||||
}
|
||||
let scale = tangent.x.abs().max(tangent.y.abs());
|
||||
if scale == 0.0 {
|
||||
return Err(Invalid("invalid hatch tangent"));
|
||||
}
|
||||
// Scaling before hypot also handles subnormal and very large directions.
|
||||
// Refuse if normalization would erase a nonzero direction component.
|
||||
let scaled = tangent / scale;
|
||||
let normalized = scaled / scaled.len();
|
||||
if !normalized.is_finite() || (tangent.x != 0.0 && normalized.x == 0.0) || (tangent.y != 0.0 && normalized.y == 0.0) {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
let tangent = normalized;
|
||||
let norm_squared = product(tangent.x, tangent.x)?.add(product(tangent.y, tangent.y)?)?;
|
||||
if norm_squared.sign()? != 1 {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
Ok(Self { origin, tangent, norm_squared })
|
||||
}
|
||||
|
||||
pub fn tangent(&self) -> Vec2 {
|
||||
self.tangent
|
||||
}
|
||||
|
||||
pub fn normal(&self) -> Vec2 {
|
||||
self.tangent().perp()
|
||||
}
|
||||
|
||||
/// Rounded endpoint on the represented frame; never an accuracy certificate.
|
||||
pub fn point(&self, offset: f64, t: f64) -> Result<Vec2> {
|
||||
if !offset.is_finite() || !t.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
let p = self.origin + self.normal() * offset + self.tangent * t;
|
||||
if !p.is_finite() || p.x.abs() > MAX_LENGTH_MM || p.y.abs() > MAX_LENGTH_MM {
|
||||
return Err(Invalid("non-finite or excessive hatch output point"));
|
||||
}
|
||||
Ok(p)
|
||||
}
|
||||
|
||||
fn project(&self, p: Vec2) -> Result<(Bound, Bound)> {
|
||||
let x = difference(p.x, self.origin.x)?;
|
||||
let y = difference(p.y, self.origin.y)?;
|
||||
let u = self.tangent;
|
||||
let t = x.mul(Bound::point(u.x)?)?.add(y.mul(Bound::point(u.y)?)?)?.div(self.norm_squared)?;
|
||||
let h = x.mul(Bound::point(-u.y)?)?.add(y.mul(Bound::point(u.x)?)?)?.div(self.norm_squared)?;
|
||||
Ok((t, h))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(super) struct Span {
|
||||
pub start: f64,
|
||||
pub end: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct ClippedLine {
|
||||
spans: Vec<Span>,
|
||||
ends: Vec<(Bound, Bound)>,
|
||||
}
|
||||
|
||||
impl ClippedLine {
|
||||
pub fn spans(&self) -> &[Span] {
|
||||
&self.spans
|
||||
}
|
||||
|
||||
/// Boundary contacts are excluded, including a zero-parity reflex vertex.
|
||||
/// A parameter inside an uncertain contact enclosure is refused, not guessed.
|
||||
pub fn contains_strict(&self, t: f64, budget: &mut Budget) -> Result<bool> {
|
||||
// A query costs work even when there are no spans or its input is invalid.
|
||||
budget.work(1)?;
|
||||
if !t.is_finite() {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
for &(start, end) in &self.ends {
|
||||
budget.work(1)?;
|
||||
if t > start.hi && t < end.lo {
|
||||
return Ok(true);
|
||||
}
|
||||
for contact in [start, end] {
|
||||
if t >= contact.lo && t <= contact.hi {
|
||||
if contact.lo == contact.hi {
|
||||
return Ok(false);
|
||||
}
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Projected {
|
||||
t: Bound,
|
||||
h: Bound,
|
||||
sign: i8,
|
||||
key: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
enum Key {
|
||||
Vertex(usize),
|
||||
Edge(usize),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Event {
|
||||
at: Bound,
|
||||
key: Key,
|
||||
toggle: bool,
|
||||
boundary: i32,
|
||||
}
|
||||
|
||||
fn event(events: &mut Vec<Event>, e: Event, budget: &mut Budget) -> Result<()> {
|
||||
budget.events(1)?;
|
||||
budget.work(1)?;
|
||||
push(events, e)
|
||||
}
|
||||
|
||||
// Fallible insertion sort charges every comparison/move and can stop immediately
|
||||
// at the work limit. Ordinary polygon scanlines have few events; large cases may
|
||||
// honestly exhaust this budget rather than run an unaccounted sorting phase.
|
||||
fn sort(events: &mut [Event], budget: &mut Budget) -> Result<()> {
|
||||
for i in 1..events.len() {
|
||||
let current = events.get(i).copied().ok_or(UNCERTAIN)?;
|
||||
let mut j = i;
|
||||
while j > 0 {
|
||||
budget.work(1)?;
|
||||
let previous = events.get(j - 1).copied().ok_or(UNCERTAIN)?;
|
||||
if previous.at.lo.total_cmp(¤t.at.lo).then(previous.key.cmp(¤t.key)).is_le() {
|
||||
break;
|
||||
}
|
||||
*events.get_mut(j).ok_or(UNCERTAIN)? = previous;
|
||||
j -= 1;
|
||||
}
|
||||
*events.get_mut(j).ok_or(UNCERTAIN)? = current;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn sweep(mut events: Vec<Event>, budget: &mut Budget) -> Result<ClippedLine> {
|
||||
sort(&mut events, budget)?;
|
||||
let mut spans = Vec::new();
|
||||
let mut ends = Vec::new();
|
||||
let mut events = events.into_iter().peekable();
|
||||
let mut previous: Option<Bound> = None;
|
||||
let mut parity = false;
|
||||
let mut boundary = 0i32;
|
||||
while let Some(first) = events.next() {
|
||||
budget.work(1)?;
|
||||
if let Some(start) = previous {
|
||||
if start.hi >= first.at.lo {
|
||||
return Err(Invalid("unresolved boundary contact ordering"));
|
||||
}
|
||||
if parity && boundary == 0 {
|
||||
push(&mut spans, Span { start: start.middle()?, end: first.at.middle()? })?;
|
||||
push(&mut ends, (start, first.at))?;
|
||||
}
|
||||
}
|
||||
parity ^= first.toggle;
|
||||
boundary = boundary.checked_add(first.boundary).ok_or(UNCERTAIN)?;
|
||||
while events.peek().is_some_and(|next| next.key == first.key) {
|
||||
budget.work(1)?;
|
||||
let next = events.next().ok_or(UNCERTAIN)?;
|
||||
if next.at != first.at {
|
||||
return Err(UNCERTAIN);
|
||||
}
|
||||
parity ^= next.toggle;
|
||||
boundary = boundary.checked_add(next.boundary).ok_or(UNCERTAIN)?;
|
||||
}
|
||||
if boundary < 0 {
|
||||
return Err(Invalid("inconsistent boundary intervals"));
|
||||
}
|
||||
previous = Some(first.at);
|
||||
}
|
||||
if parity || boundary != 0 {
|
||||
return Err(Invalid("inconsistent boundary crossings"));
|
||||
}
|
||||
Ok(ClippedLine { spans, ends })
|
||||
}
|
||||
@@ -0,0 +1,477 @@
|
||||
use std::f64::consts::{FRAC_PI_4, PI, SQRT_2};
|
||||
|
||||
use crate::hatch::budget::{Budget, Limits};
|
||||
use crate::hatch::clip::{ClippedLine, Frame, PreparedRegion};
|
||||
use crate::hatch::{self, Family, Invalid, Mark, Pattern};
|
||||
use crate::{Loop2, MAX_BEZIER_CTRL, Region2, Seg2, Vec2};
|
||||
|
||||
const TOL: f64 = 1e-9;
|
||||
type Segment = (Vec2, Vec2);
|
||||
|
||||
fn p(x: f64, y: f64) -> Vec2 {
|
||||
Vec2::new(x, y)
|
||||
}
|
||||
|
||||
fn polygon(points: &[(f64, f64)]) -> Loop2 {
|
||||
let vertices: Vec<Vec2> = points.iter().map(|&(x, y)| p(x, y)).collect();
|
||||
let segs = vertices.iter().zip(vertices.iter().cycle().skip(1)).map(|(&a, &b)| Seg2::Line { a, b }).collect();
|
||||
Loop2 { segs }
|
||||
}
|
||||
|
||||
fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> Loop2 {
|
||||
polygon(&[(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
|
||||
}
|
||||
|
||||
fn plate() -> Region2 {
|
||||
Region2 { outer: rectangle(0.0, 0.0, 40.0, 20.0), holes: vec![] }
|
||||
}
|
||||
|
||||
fn perforated_plate() -> Region2 {
|
||||
Region2 { outer: plate().outer, holes: vec![polygon(&[(10.0, 5.0), (10.0, 15.0), (20.0, 15.0), (20.0, 5.0)])] }
|
||||
}
|
||||
|
||||
fn assert_point(actual: Vec2, expected: Vec2) {
|
||||
assert!(actual.dist(expected) <= TOL, "actual {actual:?}, expected {expected:?}");
|
||||
}
|
||||
|
||||
fn assert_spans(line: &ClippedLine, expected: &[(f64, f64)]) {
|
||||
assert_eq!(line.spans().len(), expected.len());
|
||||
for (span, &(start, end)) in line.spans().iter().zip(expected) {
|
||||
assert!(span.start < span.end);
|
||||
assert!((span.start - start).abs() <= TOL, "actual start {}, expected {start}", span.start);
|
||||
assert!((span.end - end).abs() <= TOL, "actual end {}, expected {end}", span.end);
|
||||
}
|
||||
}
|
||||
|
||||
fn horizontal_with_budget(region: &Region2, y: f64, budget: &mut Budget) -> Result<ClippedLine, Invalid> {
|
||||
let prepared = PreparedRegion::new(region, budget)?;
|
||||
let frame = Frame::new(Vec2::ZERO, Vec2::X)?;
|
||||
prepared.clip(&frame, y, budget)
|
||||
}
|
||||
|
||||
fn horizontal(region: &Region2, y: f64) -> (ClippedLine, Budget) {
|
||||
let mut budget = Budget::default();
|
||||
let line = horizontal_with_budget(region, y, &mut budget).unwrap();
|
||||
(line, budget)
|
||||
}
|
||||
|
||||
fn order(a: &Vec2, b: &Vec2) -> std::cmp::Ordering {
|
||||
a.x.total_cmp(&b.x).then_with(|| a.y.total_cmp(&b.y))
|
||||
}
|
||||
|
||||
fn canonical(segments: &[Segment]) -> Vec<Segment> {
|
||||
let mut sorted: Vec<Segment> = segments.iter().map(|&(a, b)| if order(&a, &b).is_gt() { (b, a) } else { (a, b) }).collect();
|
||||
sorted.sort_by(|(a, b), (c, d)| order(a, c).then_with(|| order(b, d)));
|
||||
sorted
|
||||
}
|
||||
|
||||
fn assert_segments(actual: &[Segment], expected: &[Segment], total_length: f64) {
|
||||
assert_eq!(actual.len(), expected.len());
|
||||
// Rounded points on x=0 need not sort in the same order as exact points.
|
||||
// Consume each matching segment once, preserving multiplicity without
|
||||
// requiring floating-point tie ordering to reproduce the analytic order.
|
||||
let mut unmatched = canonical(actual);
|
||||
for (c, d) in canonical(expected) {
|
||||
let found = unmatched.iter().position(|(a, b)| a.dist(c) <= TOL && b.dist(d) <= TOL);
|
||||
let Some(index) = found else { panic!("missing segment {c:?} -> {d:?}; remaining {unmatched:?}") };
|
||||
unmatched.swap_remove(index);
|
||||
}
|
||||
let length: f64 = actual.iter().map(|(a, b)| a.dist(*b)).sum();
|
||||
assert!((length - total_length).abs() <= TOL, "actual length {length}, expected {total_length}");
|
||||
}
|
||||
|
||||
fn diagonal_segments(region: &Region2, origin: Vec2, spacing: f64, members: &[i32]) -> Vec<Segment> {
|
||||
let mut budget = Budget::default();
|
||||
let prepared = PreparedRegion::new(region, &mut budget).unwrap();
|
||||
let frame = Frame::new(origin, p(1.0, 1.0)).unwrap();
|
||||
let mut segments = Vec::new();
|
||||
for &k in members {
|
||||
let offset = f64::from(k) * spacing;
|
||||
let line = prepared.clip(&frame, offset, &mut budget).unwrap();
|
||||
for span in line.spans() {
|
||||
assert!(span.start < span.end);
|
||||
// Independent 45-degree coordinate map, not Frame::point under test.
|
||||
let point = |t: f64| origin + p((t - offset) / SQRT_2, (t + offset) / SQRT_2);
|
||||
segments.push((point(span.start), point(span.end)));
|
||||
}
|
||||
}
|
||||
segments
|
||||
}
|
||||
|
||||
fn generated_diagonal_segments(region: &Region2) -> Vec<Segment> {
|
||||
let pattern = Pattern {
|
||||
name: "ORIGINAL_45".into(),
|
||||
description: "Independent rectangle and hole oracles".into(),
|
||||
families: vec![Family { angle: FRAC_PI_4, origin: Vec2::ZERO, delta_x: 0.0, delta_y: 5.0, dashes: vec![] }],
|
||||
};
|
||||
let before = pattern.clone();
|
||||
let marks = hatch::generate(&pattern, region).unwrap();
|
||||
assert_eq!(pattern, before);
|
||||
marks
|
||||
.into_iter()
|
||||
.map(|mark| match mark {
|
||||
Mark::Line { a, b } => (a, b),
|
||||
Mark::Dot { .. } => panic!("a continuous family must not produce dots"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn diagonal_expected() -> Vec<Segment> {
|
||||
let r = SQRT_2;
|
||||
// y-x=5*sqrt(2)*k, intersected by hand with [0,40] x [0,20].
|
||||
vec![
|
||||
(p(25.0 * r, 0.0), p(40.0, 40.0 - 25.0 * r)),
|
||||
(p(20.0 * r, 0.0), p(40.0, 40.0 - 20.0 * r)),
|
||||
(p(15.0 * r, 0.0), p(40.0, 40.0 - 15.0 * r)),
|
||||
(p(10.0 * r, 0.0), p(20.0 + 10.0 * r, 20.0)),
|
||||
(p(5.0 * r, 0.0), p(20.0 + 5.0 * r, 20.0)),
|
||||
(p(0.0, 0.0), p(20.0, 20.0)),
|
||||
(p(0.0, 5.0 * r), p(20.0 - 5.0 * r, 20.0)),
|
||||
(p(0.0, 10.0 * r), p(20.0 - 10.0 * r, 20.0)),
|
||||
]
|
||||
}
|
||||
|
||||
fn perforated_expected() -> Vec<Segment> {
|
||||
let r = SQRT_2;
|
||||
// The hole [10,20] x [5,15] cuts only members -2, -1 and 0.
|
||||
vec![
|
||||
(p(25.0 * r, 0.0), p(40.0, 40.0 - 25.0 * r)),
|
||||
(p(20.0 * r, 0.0), p(40.0, 40.0 - 20.0 * r)),
|
||||
(p(15.0 * r, 0.0), p(40.0, 40.0 - 15.0 * r)),
|
||||
(p(10.0 * r, 0.0), p(5.0 + 10.0 * r, 5.0)),
|
||||
(p(20.0, 20.0 - 10.0 * r), p(20.0 + 10.0 * r, 20.0)),
|
||||
(p(5.0 * r, 0.0), p(5.0 + 5.0 * r, 5.0)),
|
||||
(p(20.0, 20.0 - 5.0 * r), p(20.0 + 5.0 * r, 20.0)),
|
||||
(p(0.0, 0.0), p(10.0, 10.0)),
|
||||
(p(15.0, 15.0), p(20.0, 20.0)),
|
||||
(p(0.0, 5.0 * r), p(20.0 - 5.0 * r, 20.0)),
|
||||
(p(0.0, 10.0 * r), p(20.0 - 10.0 * r, 20.0)),
|
||||
]
|
||||
}
|
||||
|
||||
fn permute(region: &Region2, reverse: bool, shift: usize, translation: Vec2) -> Region2 {
|
||||
let change = |boundary: &Loop2| {
|
||||
let mut vertices: Vec<Vec2> = boundary
|
||||
.segs
|
||||
.iter()
|
||||
.map(|seg| match seg {
|
||||
Seg2::Line { a, .. } => *a + translation,
|
||||
_ => panic!("this test fixture contains only lines"),
|
||||
})
|
||||
.collect();
|
||||
if reverse {
|
||||
vertices.reverse();
|
||||
}
|
||||
let len = vertices.len();
|
||||
vertices.rotate_left(shift % len);
|
||||
let coords: Vec<_> = vertices.iter().map(|v| (v.x, v.y)).collect();
|
||||
polygon(&coords)
|
||||
};
|
||||
Region2 { outer: change(®ion.outer), holes: region.holes.iter().map(change).collect() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_uses_a_global_origin_and_normalizes_the_tangent_once() {
|
||||
let origin = p(11.0, -7.0);
|
||||
let frame = Frame::new(origin, p(6.0, 8.0)).unwrap();
|
||||
assert_point(frame.tangent(), p(0.6, 0.8));
|
||||
assert_point(frame.normal(), p(-0.8, 0.6));
|
||||
// O + 5*(-.8,.6) + 10*(.6,.8) = (13,4).
|
||||
assert_point(frame.point(5.0, 10.0).unwrap(), p(13.0, 4.0));
|
||||
assert_point(frame.point(-5.0, -10.0).unwrap(), p(9.0, -18.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn original_rectangle_at_45_degrees_has_eight_analytic_segments() {
|
||||
let region = plate();
|
||||
let before = region.clone();
|
||||
let actual = diagonal_segments(®ion, Vec2::ZERO, 5.0, &[-5, -4, -3, -2, -1, 0, 1, 2]);
|
||||
assert_segments(&actual, &diagonal_expected(), 220.0 * SQRT_2 - 150.0);
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hole_splits_three_diagonal_segments_and_preserves_exact_remaining_lengths() {
|
||||
let region = perforated_plate();
|
||||
let before = region.clone();
|
||||
let actual = diagonal_segments(®ion, Vec2::ZERO, 5.0, &[-5, -4, -3, -2, -1, 0, 1, 2]);
|
||||
assert_segments(&actual, &perforated_expected(), 185.0 * SQRT_2 - 120.0);
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_generator_enumerates_all_eight_rectangle_segments_at_45_degrees() {
|
||||
let region = plate();
|
||||
let before = region.clone();
|
||||
// The public path chooses members and constructs its own sin/cos frame.
|
||||
let actual = generated_diagonal_segments(®ion);
|
||||
assert_segments(&actual, &diagonal_expected(), 220.0 * SQRT_2 - 150.0);
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_generator_preserves_all_eleven_segments_around_the_hole() {
|
||||
let region = perforated_plate();
|
||||
let before = region.clone();
|
||||
let actual = generated_diagonal_segments(®ion);
|
||||
assert_segments(&actual, &perforated_expected(), 185.0 * SQRT_2 - 120.0);
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cyclic_starts_reverse_winding_translation_and_signed_member_spacing_preserve_geometry() {
|
||||
for reverse in [false, true] {
|
||||
for shift in [0, 1, 3] {
|
||||
for translation in [Vec2::ZERO, p(11.0, -7.0)] {
|
||||
let region = permute(&perforated_plate(), reverse, shift, translation);
|
||||
let expected: Vec<_> = perforated_expected().into_iter().map(|(a, b)| (a + translation, b + translation)).collect();
|
||||
for (spacing, members) in [(5.0, [-5, -4, -3, -2, -1, 0, 1, 2]), (-5.0, [-2, -1, 0, 1, 2, 3, 4, 5])] {
|
||||
let actual = diagonal_segments(®ion, translation, spacing, &members);
|
||||
assert_segments(&actual, &expected, 185.0 * SQRT_2 - 120.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conservative_normal_bounds_cover_the_original_vertices_without_rotating_the_origin() {
|
||||
let region = plate();
|
||||
let mut budget = Budget::default();
|
||||
let prepared = PreparedRegion::new(®ion, &mut budget).unwrap();
|
||||
let frame = Frame::new(p(11.0, -7.0), p(1.0, 1.0)).unwrap();
|
||||
let (lo, hi) = prepared.normal_bounds(&frame, &mut budget).unwrap();
|
||||
assert!(lo.is_finite() && hi.is_finite() && lo <= hi);
|
||||
// (P-O).n = (y-x+18)/sqrt(2), for the four original corners.
|
||||
for projection in [18.0 / SQRT_2, -22.0 / SQRT_2, -2.0 / SQRT_2, 38.0 / SQRT_2] {
|
||||
assert!(lo <= projection + TOL && hi >= projection - TOL);
|
||||
}
|
||||
// In the axis-aligned frame the extrema are exactly 0-(-7) and 20-(-7).
|
||||
// An inward bound is wrong even if it lies within the comparison tolerance.
|
||||
let axis_frame = Frame::new(p(11.0, -7.0), Vec2::X).unwrap();
|
||||
let (lo, hi) = prepared.normal_bounds(&axis_frame, &mut budget).unwrap();
|
||||
assert!(lo.is_finite() && hi.is_finite() && lo <= 7.0 && hi >= 27.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_boundary_runs_and_vertex_only_tangencies_have_no_ink_or_dots() {
|
||||
for y in [0.0, 20.0, -1.0, 21.0] {
|
||||
let (line, mut budget) = horizontal(&plate(), y);
|
||||
assert_spans(&line, &[]);
|
||||
for t in [0.0, 10.0, 40.0] {
|
||||
assert!(!line.contains_strict(t, &mut budget).unwrap());
|
||||
}
|
||||
}
|
||||
let (interior, mut budget) = horizontal(&plate(), 10.0);
|
||||
assert_spans(&interior, &[(0.0, 40.0)]);
|
||||
assert!(!interior.contains_strict(0.0, &mut budget).unwrap());
|
||||
assert!(interior.contains_strict(20.0, &mut budget).unwrap());
|
||||
assert!(!interior.contains_strict(40.0, &mut budget).unwrap());
|
||||
let triangle = Region2 { outer: polygon(&[(0.0, 0.0), (8.0, 0.0), (4.0, 4.0)]), holes: vec![] };
|
||||
let (tangent, mut budget) = horizontal(&triangle, 4.0);
|
||||
assert_spans(&tangent, &[]);
|
||||
assert!(!tangent.contains_strict(4.0, &mut budget).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn concave_collinear_shelf_and_hole_edge_are_subtracted_from_interior_spans() {
|
||||
let region = Region2 {
|
||||
outer: polygon(&[(0.0, 0.0), (12.0, 0.0), (12.0, 8.0), (8.0, 8.0), (8.0, 4.0), (4.0, 4.0), (4.0, 8.0), (0.0, 8.0)]),
|
||||
holes: vec![rectangle(1.0, 2.0, 3.0, 4.0)],
|
||||
};
|
||||
for reverse in [false, true] {
|
||||
let input = permute(®ion, reverse, 3, Vec2::ZERO);
|
||||
let (line, mut budget) = horizontal(&input, 4.0);
|
||||
assert_spans(&line, &[(0.0, 1.0), (3.0, 4.0), (8.0, 12.0)]);
|
||||
for t in [0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0] {
|
||||
assert!(!line.contains_strict(t, &mut budget).unwrap(), "boundary or exterior at {t}");
|
||||
}
|
||||
for t in [0.5, 3.5, 10.0] {
|
||||
assert!(line.contains_strict(t, &mut budget).unwrap());
|
||||
}
|
||||
let length: f64 = line.spans().iter().map(|span| span.end - span.start).sum();
|
||||
assert_eq!(length, 6.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflex_tangent_contact_splits_spans_without_a_parity_change() {
|
||||
let region = Region2 { outer: polygon(&[(0.0, 0.0), (2.0, 0.0), (4.0, 4.0), (6.0, 0.0), (8.0, 0.0), (8.0, 6.0), (0.0, 6.0)]), holes: vec![] };
|
||||
for reverse in [false, true] {
|
||||
let input = permute(®ion, reverse, 2, Vec2::ZERO);
|
||||
let (line, mut budget) = horizontal(&input, 4.0);
|
||||
assert_spans(&line, &[(0.0, 4.0), (4.0, 8.0)]);
|
||||
assert!(line.contains_strict(3.0, &mut budget).unwrap());
|
||||
assert!(!line.contains_strict(4.0, &mut budget).unwrap());
|
||||
assert!(line.contains_strict(5.0, &mut budget).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_representable_skinny_hole_is_not_joined_by_a_geometric_epsilon() {
|
||||
// 2^-40 is exactly representable and far below geom::EPS. All edges are
|
||||
// axis-aligned, so this case does not need a tolerance-based repair.
|
||||
let width = 1.0 / 1_099_511_627_776.0;
|
||||
let region = Region2 { outer: rectangle(0.0, 0.0, 8.0, 6.0), holes: vec![rectangle(4.0, 2.0, 4.0 + width, 4.0)] };
|
||||
let (line, mut budget) = horizontal(®ion, 3.0);
|
||||
let spans: Vec<_> = line.spans().iter().map(|span| (span.start, span.end)).collect();
|
||||
assert_eq!(spans, vec![(0.0, 4.0), (4.0 + width, 8.0)]);
|
||||
assert!(!line.contains_strict(4.0, &mut budget).unwrap());
|
||||
assert!(!line.contains_strict(4.0 + width / 2.0, &mut budget).unwrap());
|
||||
assert!(!line.contains_strict(4.0 + width, &mut budget).unwrap());
|
||||
assert!(line.contains_strict(4.0 - width, &mut budget).unwrap());
|
||||
assert!(line.contains_strict(4.0 + 2.0 * width, &mut budget).unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn underflowed_product_residual_is_not_an_exact_boundary_contact() {
|
||||
// u=2^-52, a=(2-u)*2^-485, b=(2-u)*2^-486, v=2^-969-2^-1021.
|
||||
let a = f64::from_bits(0x21af_ffff_ffff_ffff);
|
||||
let b = f64::from_bits(0x219f_ffff_ffff_ffff);
|
||||
let v = f64::from_bits(0x035f_ffff_ffff_fffe);
|
||||
// Exact real arithmetic gives a*b = v + 2^-1075. The product rounds to v
|
||||
// and its positive residual rounds to zero (half the smallest subnormal).
|
||||
// Thus the vertex (b,v) is below the line, not exactly on its boundary.
|
||||
assert_eq!(a, 2.0 * b);
|
||||
assert_eq!(a * b, v);
|
||||
assert_eq!(a.mul_add(b, -v), 0.0);
|
||||
let region = Region2 { outer: rectangle(b, v, a, 1.0), holes: vec![] };
|
||||
let before = region.clone();
|
||||
let mut budget = Budget::default();
|
||||
let prepared = PreparedRegion::new(®ion, &mut budget).unwrap();
|
||||
let frame = Frame::new(Vec2::ZERO, p(1.0, a)).unwrap();
|
||||
assert_eq!(prepared.clip(&frame, 0.0, &mut budget).unwrap_err(), Invalid("unresolved clipping arithmetic"));
|
||||
|
||||
// At this angle cos(a) rounds to 1 and sin(a) to a. The public generator
|
||||
// must also refuse the uncertainty, rather than return a false contact.
|
||||
let pattern = Pattern {
|
||||
name: "RESIDUAL_UNDERFLOW".into(),
|
||||
description: "Independent binary64 projection adversary".into(),
|
||||
families: vec![Family { angle: a, origin: Vec2::ZERO, delta_x: 0.0, delta_y: 2.0, dashes: vec![] }],
|
||||
};
|
||||
pattern.validate().unwrap();
|
||||
assert_eq!(hatch::generate(&pattern, ®ion).unwrap_err(), Invalid("unresolved clipping arithmetic"));
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strict_membership_queries_charge_work_even_for_an_empty_clipped_line() {
|
||||
let region = Region2 { outer: rectangle(0.0, 0.0, 1.0, 1.0), holes: vec![] };
|
||||
let (line, _preparation_budget) = horizontal(®ion, 2.0);
|
||||
assert_spans(&line, &[]);
|
||||
// Isolate the query's entry charge: there are no spans to visit.
|
||||
let mut query_budget = Budget::new(Limits { work: 0, ..Limits::default() });
|
||||
assert_eq!(line.contains_strict(0.0, &mut query_budget), Err(Invalid("geometry work budget exhausted")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_line_boundaries_are_refused_instead_of_flattened() {
|
||||
let mut controls = [Vec2::ZERO; MAX_BEZIER_CTRL];
|
||||
controls[..5].copy_from_slice(&[p(0.0, 0.0), p(2.0, -1.0), p(4.0, -2.0), p(6.0, -1.0), p(8.0, 0.0)]);
|
||||
for curve in [
|
||||
Seg2::Arc { center: p(4.0, 0.0), radius: 4.0, start: PI, sweep: PI },
|
||||
Seg2::Cubic { p0: p(0.0, 0.0), p1: p(2.0, -1.0), p2: p(6.0, -1.0), p3: p(8.0, 0.0) },
|
||||
Seg2::Conic { a: p(0.0, 0.0), apex: p(4.0, -2.0), b: p(8.0, 0.0), w: 0.5 },
|
||||
Seg2::Bezier { n: 4, p: controls },
|
||||
] {
|
||||
let mut region = Region2 { outer: rectangle(0.0, 0.0, 8.0, 6.0), holes: vec![] };
|
||||
region.outer.segs[0] = curve;
|
||||
let before = region.clone();
|
||||
assert!(PreparedRegion::new(®ion, &mut Budget::default()).is_err());
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
let region = Region2 { outer: plate().outer, holes: vec![Loop2::circle(p(20.0, 10.0), 2.0)] };
|
||||
assert!(PreparedRegion::new(®ion, &mut Budget::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_degenerate_self_crossing_and_self_touching_boundaries_are_refused() {
|
||||
let mut open = rectangle(0.0, 0.0, 8.0, 6.0);
|
||||
open.segs.pop();
|
||||
let mut disconnected = rectangle(0.0, 0.0, 8.0, 6.0);
|
||||
disconnected.segs[1] = Seg2::Line { a: p(8.0, 1.0), b: p(8.0, 6.0) };
|
||||
for outer in [
|
||||
Loop2 { segs: vec![] },
|
||||
polygon(&[(0.0, 0.0), (8.0, 0.0)]),
|
||||
polygon(&[(0.0, 0.0), (4.0, 0.0), (8.0, 0.0)]),
|
||||
polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 0.0), (0.0, 4.0)]),
|
||||
polygon(&[(0.0, 0.0), (8.0, 6.0), (0.0, 6.0), (8.0, 0.0)]),
|
||||
polygon(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (2.0, 2.0), (0.0, 4.0), (2.0, 2.0)]),
|
||||
polygon(&[(0.0, 0.0), (4.0, 0.0), (2.0, 0.0), (4.0, 4.0), (0.0, 4.0)]),
|
||||
open,
|
||||
disconnected,
|
||||
] {
|
||||
let region = Region2 { outer, holes: vec![] };
|
||||
let before = region.clone();
|
||||
assert!(PreparedRegion::new(®ion, &mut Budget::default()).is_err());
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outside_touching_crossing_nested_and_overlapping_holes_are_refused() {
|
||||
let outer = rectangle(0.0, 0.0, 10.0, 8.0);
|
||||
for holes in [
|
||||
vec![rectangle(11.0, 1.0, 12.0, 2.0)],
|
||||
vec![rectangle(0.0, 2.0, 2.0, 4.0)],
|
||||
vec![rectangle(-1.0, 2.0, 2.0, 4.0)],
|
||||
vec![polygon(&[(0.0, 0.0), (2.0, 1.0), (1.0, 2.0)])],
|
||||
vec![outer.clone()],
|
||||
vec![rectangle(-1.0, -1.0, 11.0, 9.0)],
|
||||
vec![rectangle(1.0, 1.0, 9.0, 7.0), rectangle(2.0, 2.0, 3.0, 3.0)],
|
||||
vec![rectangle(1.0, 1.0, 5.0, 5.0), rectangle(4.0, 2.0, 7.0, 6.0)],
|
||||
vec![rectangle(1.0, 1.0, 3.0, 3.0), rectangle(3.0, 1.0, 5.0, 3.0)],
|
||||
vec![rectangle(1.0, 1.0, 3.0, 3.0), rectangle(3.0, 3.0, 5.0, 5.0)],
|
||||
] {
|
||||
let region = Region2 { outer: outer.clone(), holes };
|
||||
let before = region.clone();
|
||||
assert!(PreparedRegion::new(®ion, &mut Budget::default()).is_err());
|
||||
assert_eq!(region, before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_coordinates_and_frames_fail_before_any_clipped_result() {
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, f64::MAX, -f64::MAX] {
|
||||
for corner in [(value, 0.0), (0.0, value)] {
|
||||
let region = Region2 { outer: polygon(&[corner, (8.0, 0.0), (8.0, 6.0), (0.0, 6.0)]), holes: vec![] };
|
||||
assert!(PreparedRegion::new(®ion, &mut Budget::default()).is_err());
|
||||
assert!(Frame::new(p(corner.0, corner.1), Vec2::X).is_err());
|
||||
}
|
||||
}
|
||||
for tangent in [Vec2::ZERO, p(f64::NAN, 1.0), p(1.0, f64::INFINITY), p(f64::NEG_INFINITY, 1.0)] {
|
||||
assert!(Frame::new(Vec2::ZERO, tangent).is_err());
|
||||
}
|
||||
let frame = Frame::new(Vec2::ZERO, Vec2::X).unwrap();
|
||||
let region = plate();
|
||||
let mut budget = Budget::default();
|
||||
let prepared = PreparedRegion::new(®ion, &mut budget).unwrap();
|
||||
let line = prepared.clip(&frame, 10.0, &mut budget).unwrap();
|
||||
for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
|
||||
assert!(frame.point(value, 1.0).is_err());
|
||||
assert!(frame.point(1.0, value).is_err());
|
||||
assert!(prepared.clip(&frame, value, &mut budget).is_err());
|
||||
assert!(line.contains_strict(value, &mut budget).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exhausted_input_work_and_event_budgets_refuse_instead_of_returning_a_prefix() {
|
||||
let region = plate();
|
||||
let mut input_budget = Budget::new(Limits { input_pieces: 3, ..Limits::default() });
|
||||
assert!(PreparedRegion::new(®ion, &mut input_budget).is_err());
|
||||
let mut no_work = Budget::new(Limits { work: 0, ..Limits::default() });
|
||||
assert!(PreparedRegion::new(®ion, &mut no_work).is_err());
|
||||
|
||||
// Spent counters cannot become reusable scratch capacity on a later call.
|
||||
let mut work = Budget::new(Limits { work: 1, ..Limits::default() });
|
||||
work.work(1).unwrap();
|
||||
assert!(horizontal_with_budget(®ion, 10.0, &mut work).is_err());
|
||||
let mut events = Budget::new(Limits { events: 1, ..Limits::default() });
|
||||
events.events(1).unwrap();
|
||||
assert!(horizontal_with_budget(®ion, 10.0, &mut events).is_err());
|
||||
// A fresh request still returns the complete span; refusal never mutates input.
|
||||
let (line, _budget) = horizontal(®ion, 10.0);
|
||||
assert_spans(&line, &[(0.0, 40.0)]);
|
||||
assert_eq!(region, plate());
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
//! Bounded expansion of stored paper-millimetre patterns over prepared line regions.
|
||||
|
||||
use crate::{Region2, Vec2};
|
||||
|
||||
use super::budget::{Budget, Limits};
|
||||
use super::clip::{ClippedLine, Frame, PreparedRegion, Span};
|
||||
use super::{Invalid, Pattern};
|
||||
|
||||
type Result<T> = std::result::Result<T, Invalid>;
|
||||
|
||||
// Leave representable integer neighbours for conservative range padding and cycle ends.
|
||||
const MAX_INDEX: f64 = 4_503_599_627_370_496.0;
|
||||
|
||||
/// One generated mark in paper millimetres. Dots remain points, not degenerate lines.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Mark {
|
||||
Line { a: Vec2, b: Vec2 },
|
||||
Dot { at: Vec2 },
|
||||
}
|
||||
|
||||
/// Expand a validated pattern over a supported simple region with straight boundaries.
|
||||
/// The result is complete or an error; inputs are never changed. Stored lengths already
|
||||
/// use paper millimetres, so this function applies no unit conversion or view scale.
|
||||
///
|
||||
/// Output follows family order, ascending signed line index and ascending dash cycles
|
||||
/// within each clipped span. A hole or boundary contact does not restart dash phase.
|
||||
/// Strokes retain their clipped endpoints; dots require strict interior membership.
|
||||
/// Every explicit zero retains its own dot, including coincident zeros across cycles.
|
||||
///
|
||||
/// Preparation, candidate lines, clipping, dash visits and marks share cumulative limits.
|
||||
/// Unsupported boundaries, exhausted limits, nonfinite arithmetic, unsafe indices or
|
||||
/// lost numeric progress return an error rather than truncated or repaired geometry.
|
||||
/// Line/phase products and dash-prefix sums must be exactly representable; some valid
|
||||
/// stored patterns therefore refuse expansion. Final coordinates remain rounded f64 values.
|
||||
pub fn generate(pattern: &Pattern, region: &Region2) -> Result<Vec<Mark>> {
|
||||
generate_with_limits(pattern, region, Limits::default())
|
||||
}
|
||||
|
||||
pub(super) fn generate_with_limits(pattern: &Pattern, region: &Region2, limits: Limits) -> Result<Vec<Mark>> {
|
||||
pattern.validate()?;
|
||||
let mut budget = Budget::new(limits);
|
||||
let region = PreparedRegion::new(region, &mut budget)?;
|
||||
let mut marks = Vec::new();
|
||||
for family in &pattern.families {
|
||||
budget.work(1)?;
|
||||
let frame = Frame::new(family.origin, Vec2::from_angle(family.angle))?;
|
||||
let (low, high) = region.normal_bounds(&frame, &mut budget)?;
|
||||
let a = finite(low / family.delta_y)?;
|
||||
let b = finite(high / family.delta_y)?;
|
||||
// Include neighbouring indices when projection/division rounds onto an integer.
|
||||
// These are candidates, not output promises; exterior candidates also cost budget.
|
||||
let lines = IndexRange::new(a.min(b).floor() - 1.0, a.max(b).ceil() + 1.0)?;
|
||||
budget.candidate_lines(lines.count()?)?;
|
||||
let cycle = Cycle::new(&family.dashes, &mut budget)?;
|
||||
let mut previous_offset = None;
|
||||
for k in lines.start..=lines.end {
|
||||
budget.work(1)?;
|
||||
let offset = certified_index_product(k, family.delta_y, "uncertified hatch spacing product")?;
|
||||
if let Some(previous) = previous_offset {
|
||||
let advances = if family.delta_y > 0.0 { offset > previous } else { offset < previous };
|
||||
if !advances {
|
||||
return Err(Invalid("line spacing loses numeric progress"));
|
||||
}
|
||||
}
|
||||
previous_offset = Some(offset);
|
||||
let clipped = region.clip(&frame, offset, &mut budget)?;
|
||||
if clipped.spans().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let phase = if cycle.entries.is_empty() { 0.0 } else { certified_index_product(k, family.delta_x, "uncertified hatch phase product")? };
|
||||
let member = Member { clipped: &clipped, frame: &frame, offset, phase };
|
||||
for span in clipped.spans() {
|
||||
budget.work(1)?;
|
||||
if !span.start.is_finite() || !span.end.is_finite() || span.start >= span.end {
|
||||
return Err(Invalid("invalid clipped span"));
|
||||
}
|
||||
if cycle.entries.is_empty() {
|
||||
push_line(&frame, offset, span.start, span.end, &mut budget, &mut marks)?;
|
||||
} else {
|
||||
cycle.expand(&member, span, &mut budget, &mut marks)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(marks)
|
||||
}
|
||||
|
||||
struct IndexRange {
|
||||
start: i64,
|
||||
end: i64,
|
||||
}
|
||||
|
||||
impl IndexRange {
|
||||
fn new(start: f64, end: f64) -> Result<Self> {
|
||||
if !start.is_finite() || !end.is_finite() || start.abs() > MAX_INDEX || end.abs() > MAX_INDEX || start > end {
|
||||
return Err(Invalid("hatch line or cycle index is not safely representable"));
|
||||
}
|
||||
// Callers supply floor/ceil values, and the checked range lies inside exact i64/f64 integers.
|
||||
Ok(Self { start: start as i64, end: end as i64 })
|
||||
}
|
||||
|
||||
fn count(&self) -> Result<usize> {
|
||||
let count = self.end.checked_sub(self.start).and_then(|n| n.checked_add(1)).ok_or(Invalid("hatch index count overflow"))?;
|
||||
usize::try_from(count).map_err(|_| Invalid("hatch index count exceeds the platform limit"))
|
||||
}
|
||||
}
|
||||
|
||||
struct Entry {
|
||||
start: f64,
|
||||
end: f64,
|
||||
value: f64,
|
||||
}
|
||||
|
||||
struct Cycle {
|
||||
entries: Vec<Entry>,
|
||||
period: f64,
|
||||
}
|
||||
|
||||
struct Member<'a> {
|
||||
clipped: &'a ClippedLine,
|
||||
frame: &'a Frame,
|
||||
offset: f64,
|
||||
phase: f64,
|
||||
}
|
||||
|
||||
impl Cycle {
|
||||
fn new(dashes: &[f64], budget: &mut Budget) -> Result<Self> {
|
||||
let mut entries = Vec::new();
|
||||
entries.try_reserve_exact(dashes.len()).map_err(|_| Invalid("cannot allocate hatch dash entries"))?;
|
||||
let mut period = 0.0;
|
||||
// Pattern::validate has already bounded this list to six entries.
|
||||
for &value in dashes {
|
||||
budget.work(1)?;
|
||||
let end = certified_cycle_sum(period, value.abs())?;
|
||||
if value != 0.0 && end <= period {
|
||||
return Err(Invalid("dash length loses numeric progress within its cycle"));
|
||||
}
|
||||
entries.push(Entry { start: period, end, value });
|
||||
period = end;
|
||||
}
|
||||
if !entries.is_empty() && period <= 0.0 {
|
||||
return Err(Invalid("dash cycle must have a positive period"));
|
||||
}
|
||||
Ok(Self { entries, period })
|
||||
}
|
||||
|
||||
fn expand(&self, member: &Member<'_>, span: &Span, budget: &mut Budget, marks: &mut Vec<Mark>) -> Result<()> {
|
||||
let first = finite(finite(span.start - member.phase)? / self.period)?.floor() - 1.0;
|
||||
let last = finite(finite(span.end - member.phase)? / self.period)?.floor() + 1.0;
|
||||
let cycles = IndexRange::new(first, last)?;
|
||||
let visits = cycles.count()?.checked_mul(self.entries.len()).ok_or(Invalid("dash visit count overflow"))?;
|
||||
// Reserve all visits before iteration, including gaps and cycles outside the span.
|
||||
// The previous cycle also owns any trailing zero coincident with this cycle's start.
|
||||
budget.dash_steps(visits)?;
|
||||
for j in cycles.start..=cycles.end {
|
||||
budget.work(1)?;
|
||||
let base = finite((j as f64).mul_add(self.period, member.phase))?;
|
||||
let next_j = j.checked_add(1).ok_or(Invalid("dash cycle index overflow"))?;
|
||||
let next_base = finite((next_j as f64).mul_add(self.period, member.phase))?;
|
||||
if next_base <= base {
|
||||
return Err(Invalid("dash cycle loses numeric progress"));
|
||||
}
|
||||
for entry in &self.entries {
|
||||
budget.work(1)?;
|
||||
let start = self.position(entry.start, base, next_base)?;
|
||||
let end = self.position(entry.end, base, next_base)?;
|
||||
if entry.value == 0.0 {
|
||||
// Query before the local-span filter: a rounded endpoint must not
|
||||
// silently discard a dot inside an uncertain contact enclosure.
|
||||
let inside = member.clipped.contains_strict(start, budget)?;
|
||||
if inside && start > span.start && start < span.end {
|
||||
let at = member.frame.point(member.offset, start)?;
|
||||
if !at.is_finite() {
|
||||
return Err(Invalid("dot position is not finite"));
|
||||
}
|
||||
budget.marks(1)?;
|
||||
marks.try_reserve(1).map_err(|_| Invalid("cannot allocate hatch output marks"))?;
|
||||
marks.push(Mark::Dot { at });
|
||||
}
|
||||
} else {
|
||||
if end <= start {
|
||||
return Err(Invalid("dash or gap loses numeric progress on its line"));
|
||||
}
|
||||
if entry.value > 0.0 {
|
||||
let a = start.max(span.start);
|
||||
let b = end.min(span.end);
|
||||
if a < b {
|
||||
push_line(member.frame, member.offset, a, b, budget, marks)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn position(&self, prefix: f64, base: f64, next_base: f64) -> Result<f64> {
|
||||
// Canonical cycle endpoints keep final and initial zeros exactly coincident.
|
||||
let t = if prefix == self.period { next_base } else { finite(base + prefix)? };
|
||||
if t < base || t > next_base {
|
||||
return Err(Invalid("dash phase is not representable within its cycle"));
|
||||
}
|
||||
Ok(t)
|
||||
}
|
||||
}
|
||||
|
||||
fn push_line(frame: &Frame, offset: f64, start: f64, end: f64, budget: &mut Budget, marks: &mut Vec<Mark>) -> Result<()> {
|
||||
let a = frame.point(offset, start)?;
|
||||
let b = frame.point(offset, end)?;
|
||||
let progress = (b - a).dot(frame.tangent());
|
||||
if !a.is_finite() || !b.is_finite() || a == b || !progress.is_finite() || progress <= 0.0 {
|
||||
return Err(Invalid("positive hatch span loses finite directional progress"));
|
||||
}
|
||||
budget.marks(1)?;
|
||||
marks.try_reserve(1).map_err(|_| Invalid("cannot allocate hatch output marks"))?;
|
||||
marks.push(Mark::Line { a, b });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finite(value: f64) -> Result<f64> {
|
||||
if value.is_finite() { Ok(value) } else { Err(Invalid("nonfinite hatch arithmetic")) }
|
||||
}
|
||||
|
||||
fn certified_index_product(index: i64, factor: f64, reason: &'static str) -> Result<f64> {
|
||||
let k = index as f64;
|
||||
let product = finite(k * factor)?;
|
||||
// k is an exactly represented integer from IndexRange. Its exact product
|
||||
// with a finite f64 is a multiple of the minimum subnormal, so a nonzero
|
||||
// residual cannot disappear below that value. This is not a certificate
|
||||
// for arbitrary f64 multiplication. A later FMA cannot recover a lost phase.
|
||||
if k.mul_add(factor, -product) != 0.0 {
|
||||
return Err(Invalid(reason));
|
||||
}
|
||||
Ok(product)
|
||||
}
|
||||
|
||||
fn certified_cycle_sum(prefix: f64, length: f64) -> Result<f64> {
|
||||
let value = finite(prefix + length)?;
|
||||
// TwoSum on finite bounded positive inputs, with gradual underflow. Reject
|
||||
// loss before repeating the period: many cycles could amplify a tiny residue.
|
||||
let part = value - prefix;
|
||||
let residual = (prefix - (value - part)) + (length - part);
|
||||
if residual != 0.0 {
|
||||
return Err(Invalid("uncertified hatch dash cycle sum"));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
//! Original analytic hatch-output cases; no external pattern library or CAD output.
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
use super::budget::Limits;
|
||||
use super::generate::generate_with_limits;
|
||||
use super::{Family, Mark, Pattern, generate};
|
||||
use crate::{Loop2, Region2, Seg2, Vec2};
|
||||
|
||||
// Comparison only, never an admission/snap tolerance. The rotated and decimal
|
||||
// fixtures stay within 66 mm: this is under 128 binary64 epsilons at that scale.
|
||||
// Axis-aligned dyadic fixtures below instead require exact coordinates.
|
||||
const ROUNDOFF_MM: f64 = 1e-12;
|
||||
|
||||
fn family(origin: [f64; 2], dx: f64, dy: f64, dashes: &[f64]) -> Family {
|
||||
Family { angle: 0.0, origin: Vec2::new(origin[0], origin[1]), delta_x: dx, delta_y: dy, dashes: dashes.to_vec() }
|
||||
}
|
||||
|
||||
fn pattern(families: Vec<Family>) -> Pattern {
|
||||
Pattern { name: "ORIGINAL_PHASE".into(), description: "Independent analytic output cases".into(), families }
|
||||
}
|
||||
|
||||
fn rectangle(x0: f64, y0: f64, x1: f64, y1: f64) -> Loop2 {
|
||||
Loop2::polygon(&[Vec2::new(x0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(x0, y1)])
|
||||
}
|
||||
|
||||
fn region(x0: f64, y0: f64, x1: f64, y1: f64) -> Region2 {
|
||||
Region2 { outer: rectangle(x0, y0, x1, y1), holes: vec![] }
|
||||
}
|
||||
|
||||
fn near_point(actual: Vec2, expected: [f64; 2], tolerance: f64) -> bool {
|
||||
actual.is_finite() && (actual.x - expected[0]).abs() <= tolerance && (actual.y - expected[1]).abs() <= tolerance
|
||||
}
|
||||
|
||||
fn assert_marks(marks: &[Mark], lines: &[[f64; 4]], dots: &[[f64; 2]], tolerance: f64) {
|
||||
// Match the complete multiset, allowing traversal and endpoint direction to
|
||||
// differ. Consuming each match separately preserves coincident dot instances.
|
||||
assert_eq!(marks.len(), lines.len() + dots.len(), "unexpected marks: {marks:?}");
|
||||
let mut unmatched = marks.to_vec();
|
||||
for &[ax, ay, bx, by] in lines {
|
||||
let found = unmatched.iter().position(|mark| match *mark {
|
||||
Mark::Line { a, b } => {
|
||||
assert!(a.is_finite() && b.is_finite() && a != b, "invalid stroke: {mark:?}");
|
||||
(near_point(a, [ax, ay], tolerance) && near_point(b, [bx, by], tolerance))
|
||||
|| (near_point(a, [bx, by], tolerance) && near_point(b, [ax, ay], tolerance))
|
||||
}
|
||||
Mark::Dot { .. } => false,
|
||||
});
|
||||
let Some(index) = found else { panic!("missing line {ax},{ay} -> {bx},{by}; remaining: {unmatched:?}") };
|
||||
unmatched.swap_remove(index);
|
||||
}
|
||||
for &at in dots {
|
||||
let found = unmatched.iter().position(|mark| match *mark {
|
||||
Mark::Dot { at: actual } => near_point(actual, at, tolerance),
|
||||
Mark::Line { .. } => false,
|
||||
});
|
||||
let Some(index) = found else { panic!("missing dot {at:?}; remaining: {unmatched:?}") };
|
||||
unmatched.swap_remove(index);
|
||||
}
|
||||
assert!(unmatched.is_empty(), "unexpected marks: {unmatched:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clipped_first_stroke_keeps_the_origin_and_negative_cycles() {
|
||||
// Strokes are [2 + 5*j, 5 + 5*j]. A reset at -5.5 also gives total
|
||||
// length 9, so only the individual endpoints distinguish the wrong phase.
|
||||
let p = pattern(vec![family([2.0, 0.0], 0.0, 10.0, &[3.0, -2.0])]);
|
||||
let r = region(-5.5, -0.5, 9.5, 0.5);
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[[-5.5, 0.0, -5.0, 0.0], [-3.0, 0.0, 0.0, 0.0], [2.0, 0.0, 5.0, 0.0], [7.0, 0.0, 9.5, 0.0]], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tangential_delta_changes_phase_once_for_positive_and_negative_members() {
|
||||
// k=-1,0,1 have y=-2,0,2 and x origins -1.5,0,1.5.
|
||||
let p = pattern(vec![family([0.0, 0.0], 1.5, 2.0, &[2.0, -3.0])]);
|
||||
let r = region(0.25, -2.5, 8.25, 2.5);
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(
|
||||
&marks,
|
||||
&[[0.25, -2.0, 0.5, -2.0], [3.5, -2.0, 5.5, -2.0], [0.25, 0.0, 2.0, 0.0], [5.0, 0.0, 7.0, 0.0], [1.5, 2.0, 3.5, 2.0], [6.5, 2.0, 8.25, 2.0]],
|
||||
&[],
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rotated_negative_deltas_keep_global_origin_and_signed_member_phase() {
|
||||
// u=(0,1), n=(-1,0), hence B_k=(4+3*k,1-k), k=-1,0,1,2.
|
||||
let mut f = family([4.0, 1.0], -1.0, -3.0, &[1.0, -2.0]);
|
||||
f.angle = FRAC_PI_2;
|
||||
let marks = generate(&pattern(vec![f]), ®ion(0.5, -0.5, 10.5, 5.5)).unwrap();
|
||||
assert_marks(
|
||||
&marks,
|
||||
&[
|
||||
[1.0, -0.5, 1.0, 0.0],
|
||||
[1.0, 2.0, 1.0, 3.0],
|
||||
[1.0, 5.0, 1.0, 5.5],
|
||||
[4.0, 1.0, 4.0, 2.0],
|
||||
[4.0, 4.0, 4.0, 5.0],
|
||||
[7.0, 0.0, 7.0, 1.0],
|
||||
[7.0, 3.0, 7.0, 4.0],
|
||||
[10.0, -0.5, 10.0, 0.0],
|
||||
[10.0, 2.0, 10.0, 3.0],
|
||||
[10.0, 5.0, 10.0, 5.5],
|
||||
],
|
||||
&[],
|
||||
ROUNDOFF_MM,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hole_splits_a_dash_without_pausing_or_restarting_its_cycle() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[3.0, -2.0])]);
|
||||
let mut r = region(-0.5, -0.75, 14.5, 0.75);
|
||||
r.holes.push(rectangle(2.5, -0.25, 8.5, 0.25).reversed());
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[[0.0, 0.0, 2.5, 0.0], [10.0, 0.0, 13.0, 0.0]], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_dots_keep_negative_cycles_and_phase_across_a_hole() {
|
||||
// Every cycle has stroke [4*j,4*j+1] and dot 4*j+2.
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[1.0, -1.0, 0.0, -2.0])]);
|
||||
let mut r = region(-2.5, -0.75, 10.5, 0.75);
|
||||
r.holes.push(rectangle(1.5, -0.25, 5.5, 0.25).reversed());
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[[0.0, 0.0, 1.0, 0.0], [8.0, 0.0, 9.0, 0.0]], &[[-2.0, 0.0], [6.0, 0.0], [10.0, 0.0]], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converted_paper_millimetres_and_common_translation_are_applied_once() {
|
||||
// Values are already converted by 12.7 mm per authored length. There is
|
||||
// no PAT reader or units argument in this generator-level output oracle.
|
||||
let p = pattern(vec![family([3.175, 1.5875], 6.35, 12.7, &[3.175, -3.175, 0.0, -6.35])]);
|
||||
let marks = generate(&p, ®ion(0.0, 0.0, 25.4, 3.175)).unwrap();
|
||||
assert_marks(&marks, &[[3.175, 1.5875, 6.35, 1.5875], [15.875, 1.5875, 19.05, 1.5875]], &[[9.525, 1.5875], [22.225, 1.5875]], ROUNDOFF_MM);
|
||||
|
||||
let translated = pattern(vec![family([43.175, -5.4125], 6.35, 12.7, &[3.175, -3.175, 0.0, -6.35])]);
|
||||
let marks = generate(&translated, ®ion(40.0, -7.0, 65.4, -3.825)).unwrap();
|
||||
assert_marks(
|
||||
&marks,
|
||||
&[[43.175, -5.4125, 46.35, -5.4125], [55.875, -5.4125, 59.05, -5.4125]],
|
||||
&[[49.525, -5.4125], [62.225, -5.4125]],
|
||||
ROUNDOFF_MM,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reversing_signed_member_parameterization_preserves_the_same_geometry() {
|
||||
let r = region(0.25, -2.5, 8.25, 2.5);
|
||||
let p = pattern(vec![family([0.0, 0.0], -1.5, -2.0, &[2.0, -3.0])]);
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(
|
||||
&marks,
|
||||
&[[0.25, -2.0, 0.5, -2.0], [3.5, -2.0, 5.5, -2.0], [0.25, 0.0, 2.0, 0.0], [5.0, 0.0, 7.0, 0.0], [1.5, 2.0, 3.5, 2.0], [6.5, 2.0, 8.25, 2.0]],
|
||||
&[],
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_loop_start_and_orientation_does_not_restart_the_pattern() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[3.0, -2.0])]);
|
||||
let outer = rectangle(-0.5, -0.75, 14.5, 0.75);
|
||||
let hole = rectangle(2.5, -0.25, 8.5, 0.25);
|
||||
for reverse_outer in [false, true] {
|
||||
for reverse_hole in [false, true] {
|
||||
for start in 0..4 {
|
||||
let mut r = Region2 {
|
||||
outer: if reverse_outer { outer.reversed() } else { outer.clone() },
|
||||
holes: vec![if reverse_hole { hole.reversed() } else { hole.clone() }],
|
||||
};
|
||||
r.outer.segs.rotate_left(start);
|
||||
r.holes[0].segs.rotate_left((start + 1) % 4);
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[[0.0, 0.0, 2.5, 0.0], [10.0, 0.0, 13.0, 0.0]], &[], 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn continuous_lines_ignore_tangential_phase_and_keep_holes() {
|
||||
let p = pattern(vec![family([7.0, 0.0], 3.5, 2.0, &[])]);
|
||||
let mut r = region(-1.5, -2.5, 4.5, 2.5);
|
||||
r.holes.push(rectangle(0.5, -0.25, 1.5, 0.25).reversed());
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[[-1.5, -2.0, 4.5, -2.0], [-1.5, 0.0, 0.5, 0.0], [1.5, 0.0, 4.5, 0.0], [-1.5, 2.0, 4.5, 2.0]], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_zero_tokens_are_distinct_even_at_neighboring_cycle_boundaries() {
|
||||
let r = region(-0.25, -0.5, 2.25, 0.5);
|
||||
let expected = [[0.0, 0.0], [0.0, 0.0], [1.0, 0.0], [1.0, 0.0], [2.0, 0.0], [2.0, 0.0]];
|
||||
for dashes in [&[0.0, 0.0, -1.0][..], &[0.0, -1.0, 0.0][..]] {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, dashes)]);
|
||||
let marks = generate_with_limits(&p, &r, Limits { marks: 6, ..Limits::default() }).unwrap();
|
||||
assert_marks(&marks, &[], &expected, 0.0);
|
||||
assert!(generate_with_limits(&p, &r, Limits { marks: 5, ..Limits::default() }).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dots_on_outer_and_hole_boundaries_are_omitted_but_interior_dots_remain() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[0.0, -1.0])]);
|
||||
let mut r = region(0.0, -0.75, 6.0, 0.75);
|
||||
r.holes.push(rectangle(2.0, -0.25, 4.0, 0.25).reversed());
|
||||
let marks = generate(&p, &r).unwrap();
|
||||
assert_marks(&marks, &[], &[[1.0, 0.0], [5.0, 0.0]], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stroke_retains_boundary_endpoints_without_becoming_a_dot() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[1.0, -1.0])]);
|
||||
let marks = generate(&p, ®ion(0.0, -0.5, 1.0, 0.5)).unwrap();
|
||||
assert_marks(&marks, &[[0.0, 0.0, 1.0, 0.0]], &[], 0.0);
|
||||
// At x=1 and x=2 the adjacent positive strokes have only point contact.
|
||||
let marks = generate(&p, ®ion(1.0, -0.5, 2.0, 0.5)).unwrap();
|
||||
assert_marks(&marks, &[], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_families_keep_their_own_origins_and_phase() {
|
||||
let p = pattern(vec![family([0.0, -0.25], 0.0, 10.0, &[1.0, -1.0]), family([0.5, 0.25], 0.0, 10.0, &[0.0, -2.0])]);
|
||||
let marks = generate(&p, ®ion(-0.25, -0.5, 3.25, 0.5)).unwrap();
|
||||
assert_marks(&marks, &[[0.0, -0.25, 1.0, -0.25], [2.0, -0.25, 3.0, -0.25]], &[[0.5, 0.25], [2.5, 0.25]], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_negative_cycles_paint_nothing_instead_of_continuous_lines() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 1.5, -2.0, &[-1.0, -2.0])]);
|
||||
let marks = generate(&p, ®ion(-4.5, -2.5, 4.5, 2.5)).unwrap();
|
||||
assert_marks(&marks, &[], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn painting_nothing_does_not_bypass_pattern_or_region_validation() {
|
||||
let gap = family([0.0, 0.0], 0.0, 10.0, &[-1.0]);
|
||||
let p = pattern(vec![gap.clone()]);
|
||||
let curved = Region2 { outer: Loop2::circle(Vec2::ZERO, 1.0), holes: vec![] };
|
||||
assert!(generate(&p, &curved).is_err());
|
||||
assert!(generate(&p, &Region2::default()).is_err());
|
||||
let mut open = region(-1.0, -0.5, 1.0, 0.5);
|
||||
open.outer.segs.truncate(3);
|
||||
assert!(generate(&p, &open).is_err());
|
||||
|
||||
let r = region(-1.0, -0.5, 1.0, 0.5);
|
||||
let invalid = Family { delta_y: 0.0, ..gap.clone() };
|
||||
assert!(generate(&pattern(vec![gap, invalid]), &r).is_err());
|
||||
let mut invalid_name = p;
|
||||
invalid_name.name.clear();
|
||||
assert!(generate(&invalid_name, &r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_later_invalid_family_refuses_the_entire_result() {
|
||||
let good = family([0.0, 0.0], 0.0, 10.0, &[]);
|
||||
let r = region(-1.0, -0.5, 1.0, 0.5);
|
||||
let mut bad = good.clone();
|
||||
bad.angle = f64::NAN;
|
||||
assert!(generate(&pattern(vec![good, bad]), &r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn supported_line_input_does_not_silently_accept_an_unsupported_hole() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[])]);
|
||||
let mut r = region(-2.0, -2.0, 2.0, 2.0);
|
||||
r.holes.push(Loop2::circle(Vec2::ZERO, 0.5).reversed());
|
||||
assert!(generate(&p, &r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn boundary_runs_are_omitted_without_shifting_the_interior_members() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 1.0, &[])]);
|
||||
let marks = generate(&p, ®ion(-1.0, 0.0, 1.0, 2.0)).unwrap();
|
||||
assert_marks(&marks, &[[-1.0, 1.0, 1.0, 1.0]], &[], 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_work_budget_can_refuse_a_small_otherwise_valid_pattern() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[1.0, -1.0])]);
|
||||
let r = region(-0.25, -0.5, 1.25, 0.5);
|
||||
assert_marks(&generate(&p, &r).unwrap(), &[[0.0, 0.0, 1.0, 0.0]], &[], 0.0);
|
||||
for limits in [
|
||||
Limits { input_pieces: 0, ..Limits::default() },
|
||||
Limits { candidate_lines: 0, ..Limits::default() },
|
||||
Limits { work: 0, ..Limits::default() },
|
||||
Limits { events: 0, ..Limits::default() },
|
||||
Limits { dash_steps: 0, ..Limits::default() },
|
||||
Limits { marks: 0, ..Limits::default() },
|
||||
] {
|
||||
assert!(generate_with_limits(&p, &r, limits).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn marks_are_counted_across_families_and_split_strokes_without_partial_success() {
|
||||
let first = family([0.0, -0.25], 0.0, 10.0, &[]);
|
||||
let second = family([0.0, 0.25], 0.0, 10.0, &[]);
|
||||
let mut r = region(-1.5, -0.5, 2.5, 0.5);
|
||||
r.holes.push(rectangle(0.0, -0.375, 1.0, 0.375).reversed());
|
||||
let p = pattern(vec![first, second]);
|
||||
let marks = generate_with_limits(&p, &r, Limits { marks: 4, ..Limits::default() }).unwrap();
|
||||
assert_marks(&marks, &[[-1.5, -0.25, 0.0, -0.25], [1.0, -0.25, 2.5, -0.25], [-1.5, 0.25, 0.0, 0.25], [1.0, 0.25, 2.5, 0.25]], &[], 0.0);
|
||||
assert!(generate_with_limits(&p, &r, Limits { marks: 3, ..Limits::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_lines_are_counted_even_without_marks() {
|
||||
let r = region(-0.25, -0.5, 0.25, 0.5);
|
||||
let f = family([0.0, 0.0], 0.0, 10.0, &[-1.0]);
|
||||
let p = pattern(vec![f.clone(), f]);
|
||||
assert!(generate(&p, &r).unwrap().is_empty());
|
||||
// Each family has member k=0 in the region; a one-line budget cannot
|
||||
// serve both. Conservative exterior candidates also consume this budget.
|
||||
assert!(generate_with_limits(&p, &r, Limits { candidate_lines: 1, ..Limits::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn candidate_lines_and_dash_steps_are_charged_for_a_visible_gap() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[1.0, -3.0])]);
|
||||
let r = region(1.25, -0.5, 3.75, 0.5);
|
||||
assert!(generate(&p, &r).unwrap().is_empty());
|
||||
assert!(generate_with_limits(&p, &r, Limits { candidate_lines: 0, ..Limits::default() }).is_err());
|
||||
assert!(generate_with_limits(&p, &r, Limits { dash_steps: 0, ..Limits::default() }).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subnormal_spacing_is_valid_data_but_cannot_expand_without_a_bound() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, f64::from_bits(1), &[])]);
|
||||
assert!(p.validate().is_ok());
|
||||
assert!(generate(&p, ®ion(-0.5, -0.5, 0.5, 0.5)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonzero_dash_step_that_cannot_advance_is_refused() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[1.0, -f64::from_bits(1)])]);
|
||||
assert!(p.validate().is_ok());
|
||||
assert!(generate(&p, ®ion(-0.25, -0.5, 2.25, 0.5)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolvable_far_phase_indices_are_not_saturated_into_a_success() {
|
||||
let p = pattern(vec![family([100_000.0, 0.0], 0.0, 10.0, &[2.0_f64.powi(-40), -2.0_f64.powi(-40)])]);
|
||||
let r = region(-2.0_f64.powi(-50), -0.5, 2.0_f64.powi(-50), 0.5);
|
||||
assert!(p.validate().is_ok());
|
||||
assert!(generate(&p, &r).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_or_nonfinite_line_boundaries_return_an_error() {
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[])]);
|
||||
for point in [Vec2::ZERO, Vec2::new(f64::NAN, 0.0), Vec2::new(f64::INFINITY, 0.0)] {
|
||||
let r = Region2 { outer: Loop2 { segs: vec![Seg2::Line { a: point, b: point }] }, holes: vec![] };
|
||||
assert!(generate(&p, &r).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_uncertified_large_member_phase_product_is_refused_explicitly() {
|
||||
// Independent integer oracle: k*dx = 99_999_000_000_099_999.
|
||||
// With period 100 and cycle -999_990_000_001_000, the visible stroke
|
||||
// would be exactly [-1,0]. Rounding k*dx first instead shifts it to [0,1].
|
||||
// D2 deliberately refuses this uncertified product instead of returning
|
||||
// shifted geometry. An unrelated topology/budget error must not pass.
|
||||
let k: i64 = 1_000_000_000_001;
|
||||
let dx: i64 = 99_999;
|
||||
let cycle: i128 = -999_990_000_001_000;
|
||||
let exact_start = i128::from(k) * i128::from(dx) + cycle * 100;
|
||||
assert_eq!(exact_start, -1);
|
||||
assert_eq!(exact_start + 1, 0);
|
||||
|
||||
// These dyadic bounds contain only member k and preserve their width
|
||||
// exactly. Stored origin, deltas and dashes all satisfy model admission.
|
||||
let dy = 2.0_f64.powi(-40);
|
||||
let p = pattern(vec![family([0.0, 0.0], dx as f64, dy, &[1.0, -99.0])]);
|
||||
let r = region(-2.0, (k as f64 - 0.25) * dy, 2.0, (k as f64 + 0.25) * dy);
|
||||
assert!(p.validate().is_ok());
|
||||
assert_eq!(generate(&p, &r), Err(super::Invalid("uncertified hatch phase product")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn advancing_dash_entries_with_an_inexact_cycle_sum_are_refused_explicitly() {
|
||||
// The exact sum of the stored binary64 values 0.1 and 0.2 is
|
||||
// 10_808_639_105_689_191 / 2^55: it lies between representable f64 values.
|
||||
// Both tokens advance, so this is loss of cycle precision, not stalled
|
||||
// progress. Repeating the rounded period would accumulate a phase error.
|
||||
let p = pattern(vec![family([0.0, 0.0], 0.0, 10.0, &[0.1, -0.2])]);
|
||||
let r = region(-0.25, -0.5, 1.25, 0.5);
|
||||
assert!(p.validate().is_ok());
|
||||
assert_eq!(generate(&p, &r), Err(super::Invalid("uncertified hatch dash cycle sum")));
|
||||
}
|
||||
+129
-25
@@ -1,10 +1,11 @@
|
||||
# Hatch patterns and PAT import (W38d D1)
|
||||
# Hatch patterns, PAT import and polygonal generation (W38d D1–D2)
|
||||
|
||||
D1 supplies a neutral hatch-pattern model and a bounded PAT reader for
|
||||
[W38d (#7062)][issue], following [the drawing-sketch handoff][handoff].
|
||||
It is a library foundation: it does not generate or clip hatch strokes, attach a
|
||||
fill to a sketch, save drawing records, change the paper scene or register a
|
||||
command. It does not complete W38d or implement section-derived hatching (W34).
|
||||
D2 adds bounded line-and-dot generation inside polygonal regions with holes.
|
||||
These are library foundations: they do not attach a fill to a sketch, save
|
||||
drawing records, change the paper scene or register a command. They do not
|
||||
complete W38d or implement section-derived hatching (W34).
|
||||
|
||||
## Public API
|
||||
|
||||
@@ -41,6 +42,20 @@ register, rename, merge or overwrite patterns.
|
||||
The reader does not open files or modify a document. It returns either the
|
||||
complete list or an error, with no partial list.
|
||||
|
||||
D2 adds [`hatch::generate`][generator], using the existing `geom::Region2`:
|
||||
|
||||
```rust
|
||||
generate(pattern: &Pattern, region: &Region2) -> Result<Vec<Mark>, hatch::Invalid>
|
||||
```
|
||||
|
||||
`Mark` is either `Line { a: Vec2, b: Vec2 }` or `Dot { at: Vec2 }`.
|
||||
These are transient geometric marks in the supplied region's paper XY frame,
|
||||
not paper-scene objects or saved fill records. A dot remains a point; it is not
|
||||
a zero-length line. Each explicit zero in a dash sequence produces its own
|
||||
eligible dot, even if another zero coincides with it. The call validates the pattern and supported region, leaves
|
||||
both inputs unchanged, and returns the complete result or an error. No partial
|
||||
output is returned after a failure.
|
||||
|
||||
## Coordinates, units and dash phase
|
||||
|
||||
All lengths in the neutral model are **paper millimetres at pattern scale 1**;
|
||||
@@ -55,7 +70,7 @@ p(k, t) = origin + k * (delta_x * u + delta_y * n) + t * u
|
||||
|
||||
`delta_x` shifts the phase along the line; `delta_y` is signed perpendicular
|
||||
spacing. The origin is not pre-rotated by the family angle. This formula defines
|
||||
the data's meaning; D1 does not enumerate family members.
|
||||
the data's meaning. D2 enumerates a bounded set of members that can meet the region.
|
||||
|
||||
PAT angles arrive in degrees and become radians. The length multiplier is
|
||||
`scale` for millimetres or `25.4 * scale` for inches. It applies once to both
|
||||
@@ -72,13 +87,13 @@ the reader does not guess a unit system from the filename or pattern name.
|
||||
An empty dash list means a continuous line. In a nonempty list, positive lengths
|
||||
draw, negative lengths leave gaps, and zero denotes a dot. The cycle length is
|
||||
the sum of absolute lengths. All-zero cycles are invalid; negative-only cycles
|
||||
are valid definitions that paint nothing. A later generator must keep phase
|
||||
anchored at `p(k, 0)` across clipped fragments and holes.
|
||||
are valid definitions that paint nothing. D2 keeps phase anchored at `p(k, 0)`
|
||||
across clipped fragments and holes; clipping does not restart the dash sequence.
|
||||
|
||||
The eventual paper adapter must keep, for example, a 3 mm hatch spacing at 3 mm
|
||||
on paper when a view scale changes. It must transform the region to paper
|
||||
coordinates without applying that view scale to the pattern a second time.
|
||||
D1 has no view or placement API. A multi-family pattern also has no single
|
||||
Neither D1 nor D2 has a view or placement API. A multi-family pattern also has no single
|
||||
intrinsic spacing: a future spacing control must define its relationship to
|
||||
pattern scale explicitly.
|
||||
|
||||
@@ -99,7 +114,7 @@ claims about every PAT implementation.
|
||||
| Nonempty dash cycle | Finite, strictly positive sum of absolute lengths |
|
||||
|
||||
There is no minimum positive spacing epsilon. A definition can pass D1 yet be
|
||||
too dense for a later bounded generator. Validation does not authorize unlimited
|
||||
too dense for D2's bounded generator. Validation does not authorize unlimited
|
||||
line, intersection, dash or point expansion.
|
||||
|
||||
## PAT text policy and errors
|
||||
@@ -153,31 +168,115 @@ reports expected line 3. UTF-8 errors identify the physical line where possible.
|
||||
Option and total byte-limit errors start with `PAT import:`, without an
|
||||
invented line number.
|
||||
|
||||
## D2 polygonal generation
|
||||
|
||||
The [clipper][clipper] accepts one `Region2`: an outer loop and zero or more
|
||||
holes, all made of `Seg2::Line`. Every loop must have at least three edges,
|
||||
close exactly, use finite nondegenerate segments and be simple. All input and
|
||||
generated coordinate components must lie within `+/-100000 mm`. Either loop
|
||||
orientation is accepted; the outer/hole roles come from `Region2`, not winding.
|
||||
Holes must lie strictly inside the outer loop, without touching, crossing or
|
||||
nesting within one another. Unsupported or
|
||||
uncertain geometry returns `hatch::Invalid`; the input is not snapped, repaired
|
||||
or approximated. Arcs, conics and Bézier segments are not supported in D2.
|
||||
|
||||
Clipping preserves positive-length interior spans and their boundary contacts.
|
||||
A span's endpoints may lie on the boundary; its interior must lie in material.
|
||||
An isolated contact splits spans, including a tangent contact that does not
|
||||
change crossing parity. A line running along a boundary does not paint that
|
||||
boundary: coincident boundary intervals are subtracted, rather than rejected
|
||||
merely for coincidence. Dots are emitted only in the strict interior, never at
|
||||
a boundary contact. The clipper does not bridge a hole or merge spans across a contact.
|
||||
|
||||
Numerical predicates use arithmetic enclosures for the represented inputs.
|
||||
Unresolved signs, overlapping contact bounds or a dot whose membership cannot
|
||||
be distinguished from a contact return an error. Endpoints and frame
|
||||
reconstruction are rounded floating-point values, not an exact coordinate or
|
||||
universal geometric-tolerance certificate. In particular, some mathematically
|
||||
valid polygons or near-contact patterns can be refused without a fallback.
|
||||
|
||||
The generator uses a normalized tangent and its left normal. In that frame,
|
||||
member `k` has normal offset `k * delta_y` and tangential dash phase
|
||||
`k * delta_x`. The phase is applied once, including for negative member indices,
|
||||
negative perpendicular spacing and negative dash-cycle positions. Output follows
|
||||
family order, ascending signed member index, then ascending cycles within each
|
||||
clipped span. This is not a global coordinate sort.
|
||||
|
||||
D2 also requires exact binary64 results for the products and sums that define
|
||||
repeated spacing and phase:
|
||||
|
||||
- Every candidate's `k * delta_y` must be exact before clipping.
|
||||
- For a nonempty dash sequence on a member with interior spans, `k * delta_x`
|
||||
must be exact before the cycle is expanded.
|
||||
- Every cumulative sum of absolute dash lengths, including the final period,
|
||||
must be exact before repeating the cycle.
|
||||
|
||||
Failure to establish any of these results returns `hatch::Invalid`. In
|
||||
particular, some decimal-valued patterns accepted by D1 cannot be generated by
|
||||
D2: for example, a dash sequence `[0.1, -0.2]` fails the exact cycle-sum check.
|
||||
Passing the finite-value and progress checks alone is insufficient.
|
||||
These checks concern the stored binary64 operands. They do not certify the
|
||||
original decimal text, the fused multiply-add used for cycle bases, the addition
|
||||
of a prefix to a cycle base, or the final reconstructed coordinates as exact.
|
||||
|
||||
### Work and output limits
|
||||
|
||||
One internal [budget][budget] spans preparation, every family, clipping, dash
|
||||
enumeration, dot membership queries and output. Its default cumulative caps are:
|
||||
|
||||
| Counter | Maximum per call |
|
||||
| --- | --- |
|
||||
| Input boundary pieces | 8,192 |
|
||||
| Candidate family lines | 10,000 |
|
||||
| Geometric work units | 2,000,000 |
|
||||
| Created contact/intersection events | 65,536 |
|
||||
| Dash steps | 200,000 |
|
||||
| Output marks, lines and dots together | 40,000 |
|
||||
|
||||
Candidate lines include conservative neighbours of the projected index range,
|
||||
including lines outside the region. Dash steps include every visited dash/gap/dot
|
||||
entry in the conservatively padded cycle range, even when it produces no mark.
|
||||
Repeated work across clipped spans also counts. The event cap counts all events
|
||||
created during the call; freeing or reusing temporary storage does not restore
|
||||
that budget. These counters are work limits,
|
||||
not elapsed-time or accuracy guarantees. The internal limit injection used by
|
||||
tests can lower these ceilings but cannot raise them, and is not a public API.
|
||||
Production uses the same generator with the defaults.
|
||||
|
||||
Budget or allocation failure, nonfinite arithmetic and unresolved numeric
|
||||
uncertainty fail the whole call. Member and cycle indices must fit the generator's safe integer range
|
||||
(`abs(index) <= 2^52`, including padded neighbours); nonzero spacing, dash and gap
|
||||
steps must still advance numerically. A far-away origin and very fine pattern
|
||||
can therefore be refused even when few visible marks would remain.
|
||||
Passing the D1 model validator does not guarantee a region can be generated
|
||||
within these bounds. There is no implicit coarse fallback or
|
||||
truncated successful result. Caller-side input-byte/allocation limits and any
|
||||
later paper-scene record limit remain separate responsibilities.
|
||||
|
||||
## Later phases and acceptance
|
||||
|
||||
D2 still needs bounded region clipping and its own independent geometry tests.
|
||||
A PAT dot must become an explicit point mark, such as a future
|
||||
`Mark::Dot { at }`; this is **not a D1 type**. It must not become a zero-length
|
||||
paper stroke: the current scene uses butt caps and rejects degenerate geometry.
|
||||
The future paper adapter must choose a deliberate visible representation.
|
||||
|
||||
The generator also needs separate caps for candidate lines, intersection work,
|
||||
dash steps and output marks, with whole-result refusal rather than truncated
|
||||
success. The paper scene's aggregate record limit remains a separate final
|
||||
check. General curved-region clipping is not supplied by D1.
|
||||
The future paper adapter must choose a visible representation for `Mark::Dot`;
|
||||
the current scene's butt-cap strokes reject degenerate geometry. D2 supplies no
|
||||
paper adapter, stroke width, colour, export, command or interactive preview.
|
||||
Curved-region clipping remains outside this slice.
|
||||
|
||||
Connecting fills to sketches waits for W38a's drawing-owned sketch record.
|
||||
The later W38d integration owns persistent boundary identity, retained geometry and lost
|
||||
reference reporting, commands and undo, embedded imported definitions, paper
|
||||
object kinds/layers and export acceptance. Section-derived hatching remains a
|
||||
separate feature. This slice adds no drawing-format field or new dependency.
|
||||
The later W38d integration owns persistent boundary identity, retained geometry
|
||||
and lost-reference reporting, commands and undo, embedded imported definitions,
|
||||
paper object kinds/layers and export acceptance. Section-derived hatching
|
||||
remains a separate feature. D1–D2 add no drawing-format field or new dependency.
|
||||
|
||||
D1 acceptance covers model validation and serde, converted units and phase data,
|
||||
Unicode/BOM/line-ending handling, strict final blanks, malformed numeric/header
|
||||
fields, duplicate ordering, and limit refusal. See the model and
|
||||
[PAT acceptance tests][tests] for the cases present in the candidate.
|
||||
Passing D1 tests does not establish clipping, paper output or interactive
|
||||
acceptance; actual commands and results belong to the PR's validation record.
|
||||
|
||||
D2 acceptance is split between [clipping tests][clip-tests] and
|
||||
[generation tests][generate-tests]: original analytic polygons and holes,
|
||||
contacts and boundary runs, global dash phase, strict interior dots, malformed
|
||||
or unsupported geometry, numeric refusal and cumulative caps. The actual test
|
||||
commands and results belong to the PR's validation record. Library checks do
|
||||
not establish paper output, persistence or interactive acceptance.
|
||||
|
||||
## Sources and licensing
|
||||
|
||||
@@ -197,6 +296,11 @@ protected tables or illustrations. See the repository's
|
||||
[handoff]: https://github.com/tangency-labs/solidcraft/issues/5425#issuecomment-6414961262
|
||||
[model]: ../crates/geom/src/hatch.rs
|
||||
[reader]: ../crates/io/src/pat.rs
|
||||
[generator]: ../crates/geom/src/hatch/generate.rs
|
||||
[clipper]: ../crates/geom/src/hatch/clip.rs
|
||||
[budget]: ../crates/geom/src/hatch/budget.rs
|
||||
[clip-tests]: ../crates/geom/src/hatch/clip_tests.rs
|
||||
[generate-tests]: ../crates/geom/src/hatch/generate_tests.rs
|
||||
[tests]: ../crates/io/src/pat_tests.rs
|
||||
[pat-reference]: https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-Customization/files/GUID-A6F2E6FF-1717-44B6-A476-0CA817ADD77E.htm
|
||||
[dash-reference]: https://help.autodesk.com/cloudhelp/2026/ENU/AutoCAD-Customization/files/GUID-B67FADB9-0F10-4536-ABC4-BB7D8BDDF5B1.htm
|
||||
Reference in new issue
Block a user