mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 19:11:26 +00:00
Merge main into fix/export3d-revolve-side-graphics
This commit is contained in:
@@ -34,6 +34,18 @@ pub enum LineKind {
|
||||
Perforation,
|
||||
}
|
||||
|
||||
impl LineKind {
|
||||
/// The angle (degrees) a line of this kind folds at: 90 for a Crease or a Perforation, -90 for
|
||||
/// a Partial Cut. A positive angle folds away from the printed side; none for a Cut.
|
||||
pub fn fold_angle(self) -> Option<f64> {
|
||||
match self {
|
||||
LineKind::Cut => None,
|
||||
LineKind::Crease | LineKind::Perforation => Some(90.0),
|
||||
LineKind::PartialCut => Some(-90.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A fold line: the path (document coordinates), its kind, and a key the issues name it by.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FoldLine {
|
||||
@@ -57,10 +69,18 @@ pub struct Panel {
|
||||
pub area: f64,
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// A point inside the panel, or the middle of its bounds for one too thin to find one in.
|
||||
pub fn point_inside(&self) -> Option<Point> {
|
||||
point_in(&self.outline)
|
||||
}
|
||||
}
|
||||
|
||||
/// The hinge between panels `a` and `b` (indices into the blank's panels, `a` < `b`): the straight
|
||||
/// line from `from` to `to`, made of the lines `keys`. `straight` is false when its pieces are not on
|
||||
/// one straight line within the tolerance; `from` and `to` are then on the line through its longest
|
||||
/// piece.
|
||||
/// piece. `angle` (degrees) is the fold angle of the kind of line its longest piece is
|
||||
/// ([`LineKind::fold_angle`]).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Hinge {
|
||||
pub a: usize,
|
||||
@@ -69,6 +89,7 @@ pub struct Hinge {
|
||||
pub to: Point,
|
||||
pub keys: Vec<u64>,
|
||||
pub straight: bool,
|
||||
pub angle: f64,
|
||||
}
|
||||
|
||||
/// What can be wrong with fold lines, in the order [`blanks`] lists them.
|
||||
@@ -1276,7 +1297,9 @@ impl Context<'_> {
|
||||
let sp = p.path.subpaths.first()?;
|
||||
Some((sp.anchors.first()?.p, sp.anchors.last()?.p))
|
||||
};
|
||||
let (p0, p1) = group.iter().filter_map(|p| chord(p)).max_by(|x, y| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?;
|
||||
let ((p0, p1), longest) =
|
||||
group.iter().filter_map(|p| Some((chord(p)?, p))).max_by(|(x, _), (y, _)| x.0.distance(x.1).total_cmp(&y.0.distance(y.1)))?;
|
||||
let angle = longest.lines.iter().filter_map(|&l| self.lines.get(l)?.kind.fold_angle()).next().unwrap_or(90.0);
|
||||
let len = p0.distance(p1);
|
||||
// The longest piece only sets the direction; the length check is on the whole hinge below.
|
||||
if len.is_nan() || len <= 1e-9 {
|
||||
@@ -1308,7 +1331,7 @@ impl Context<'_> {
|
||||
let mut keys = self.keys(lines);
|
||||
keys.sort_unstable();
|
||||
keys.dedup();
|
||||
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight })
|
||||
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, keys, straight, angle })
|
||||
}
|
||||
|
||||
/// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a
|
||||
@@ -1426,7 +1449,7 @@ impl Context<'_> {
|
||||
/// The base panel of `panels`: the largest by area; panels whose areas differ by less than 1e-9 of
|
||||
/// the larger tie, and the tie goes to the one whose inside point is highest on the page, then
|
||||
/// leftmost.
|
||||
fn base_panel(panels: &[Panel]) -> Option<usize> {
|
||||
pub fn base_panel(panels: &[Panel]) -> Option<usize> {
|
||||
let top = panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max);
|
||||
if !top.is_finite() {
|
||||
return None;
|
||||
@@ -1440,5 +1463,9 @@ fn base_panel(panels: &[Panel]) -> Option<usize> {
|
||||
.map(|(i, _)| i)
|
||||
}
|
||||
|
||||
mod pose;
|
||||
pub mod raster;
|
||||
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
//! A blank folded into its 3D shape ([`fold`]).
|
||||
//!
|
||||
//! The flat blank lies at z = 0 with document x to the right and document y flipped so y points up;
|
||||
//! the printed side faces +z. The base panel stays in place. The other panels are reached from it
|
||||
//! through a breadth-first tree of hinges, each panel's hinges taken in the order of their ends (y,
|
||||
//! then x, the first end first), so the tree does not depend on the order the lines were drawn in. A child
|
||||
//! panel turns about its hinge by the hinge's angle times the fold amount; a positive angle moves it
|
||||
//! toward -z, away from the printed side, whichever way the hinge was drawn. Hinges outside the tree
|
||||
//! close a loop of panels: [`FoldedHinge::gap`] says how far apart their two placements end up when
|
||||
//! the blank is folded all the way.
|
||||
|
||||
use std::collections::{HashSet, VecDeque};
|
||||
|
||||
use vectorcraft_geom::{PathData, PathEl, Point, Shape as _};
|
||||
|
||||
use super::{Blank, base_panel, point_in};
|
||||
|
||||
/// Most points a panel's outline is flattened to; a panel with more is left out of the collision
|
||||
/// test and the preview.
|
||||
pub const MAX_POLYGON_POINTS: usize = 1 << 16;
|
||||
|
||||
type V3 = [f64; 3];
|
||||
|
||||
fn sub(a: V3, b: V3) -> V3 {
|
||||
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
|
||||
}
|
||||
|
||||
fn add(a: V3, b: V3) -> V3 {
|
||||
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
|
||||
}
|
||||
|
||||
fn scale(a: V3, s: f64) -> V3 {
|
||||
[a[0] * s, a[1] * s, a[2] * s]
|
||||
}
|
||||
|
||||
fn dot(a: V3, b: V3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
fn cross(a: V3, b: V3) -> V3 {
|
||||
[a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
|
||||
}
|
||||
|
||||
fn length(a: V3) -> f64 {
|
||||
dot(a, a).sqrt()
|
||||
}
|
||||
|
||||
/// A document point on the flat blank (y flipped so it points up, z = 0).
|
||||
pub(super) fn flat(p: Point) -> V3 {
|
||||
[p.x, -p.y, 0.0]
|
||||
}
|
||||
|
||||
/// Where a panel is: a rotation `m` (rows) and a translation `t`, taking a point of the flat
|
||||
/// blank (see [`flat`]) to its place in 3D.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Pose {
|
||||
pub m: [[f64; 3]; 3],
|
||||
pub t: [f64; 3],
|
||||
}
|
||||
|
||||
impl Pose {
|
||||
/// The flat blank's own place.
|
||||
pub const IDENTITY: Pose = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], t: [0.0; 3] };
|
||||
|
||||
/// Where the flat point `v` goes.
|
||||
pub fn apply(&self, v: [f64; 3]) -> [f64; 3] {
|
||||
add(self.turn(v), self.t)
|
||||
}
|
||||
|
||||
/// The direction `v` turned by the rotation alone.
|
||||
pub fn turn(&self, v: [f64; 3]) -> [f64; 3] {
|
||||
let [a, b, c] = self.m;
|
||||
[dot(a, v), dot(b, v), dot(c, v)]
|
||||
}
|
||||
|
||||
/// Where the document point `p` goes.
|
||||
pub fn place(&self, p: Point) -> [f64; 3] {
|
||||
self.apply(flat(p))
|
||||
}
|
||||
|
||||
/// The direction the printed side faces.
|
||||
pub fn normal(&self) -> [f64; 3] {
|
||||
self.turn([0.0, 0.0, 1.0])
|
||||
}
|
||||
|
||||
/// This pose followed, in the flat blank's terms, by a right-handed turn of `theta` radians
|
||||
/// about the line through `at` along the unit direction `axis`: the pose of a panel hinged to
|
||||
/// this one there.
|
||||
fn turned_about(&self, at: V3, axis: V3, theta: f64) -> Pose {
|
||||
let (s, c) = theta.sin_cos();
|
||||
let [x, y, z] = axis;
|
||||
// Rodrigues' rotation matrix.
|
||||
let r = [
|
||||
[c + x * x * (1.0 - c), x * y * (1.0 - c) - z * s, x * z * (1.0 - c) + y * s],
|
||||
[y * x * (1.0 - c) + z * s, c + y * y * (1.0 - c), y * z * (1.0 - c) - x * s],
|
||||
[z * x * (1.0 - c) - y * s, z * y * (1.0 - c) + x * s, c + z * z * (1.0 - c)],
|
||||
];
|
||||
let mut m = [[0.0; 3]; 3];
|
||||
for (i, row) in m.iter_mut().enumerate() {
|
||||
for (j, cell) in row.iter_mut().enumerate() {
|
||||
*cell = (0..3).map(|k| self.m[i][k] * r[k][j]).sum();
|
||||
}
|
||||
}
|
||||
// p ↦ self(r (p - at) + at) = (self.m r) p + self.m (at - r at) + self.t
|
||||
let r_at = [dot(r[0], at), dot(r[1], at), dot(r[2], at)];
|
||||
Pose { m, t: add(self.turn(sub(at, r_at)), self.t) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A folded panel: where it is, its parent in the fold tree (`None` for the base and for a panel no
|
||||
/// chain of hinges joins to it, which stays flat where it is) and how many hinges lie between it
|
||||
/// and the base.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FoldedPanel {
|
||||
pub pose: Pose,
|
||||
pub parent: Option<usize>,
|
||||
pub depth: usize,
|
||||
}
|
||||
|
||||
/// A folded hinge: its panels, its angle (degrees, before the fold amount), whether it is in the
|
||||
/// fold tree and, for one that is not, how far apart its two placements end up with every hinge at
|
||||
/// its full angle, whatever the fold amount (`gap`, points), and whether that is close enough to call
|
||||
/// it closed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct FoldedHinge {
|
||||
pub a: usize,
|
||||
pub b: usize,
|
||||
pub angle: f64,
|
||||
pub tree: bool,
|
||||
pub closes: bool,
|
||||
pub gap: f64,
|
||||
}
|
||||
|
||||
/// A blank folded at one amount.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Folded {
|
||||
pub base: usize,
|
||||
pub panels: Vec<FoldedPanel>,
|
||||
/// The panels in breadth-first order from the base, the panels not joined to it last.
|
||||
pub order: Vec<usize>,
|
||||
pub hinges: Vec<FoldedHinge>,
|
||||
/// Pairs of panels (`a` < `b`) that pass through each other.
|
||||
pub collisions: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
/// The panel of `blank` that `p` (document coordinates) lies in.
|
||||
pub fn panel_at(blank: &Blank, p: Point) -> Option<usize> {
|
||||
blank.panels.iter().position(|panel| panel.outline.to_bezpath().winding(p) != 0)
|
||||
}
|
||||
|
||||
/// Which of `blanks` to fold, and about which of its panels: the blank and panel `at` (document
|
||||
/// coordinates) lies in, or, without a point, the blank with the largest panel (the first of equals)
|
||||
/// and its base panel. `None` when `at` lies in no panel, or no blank has a panel.
|
||||
pub fn pick(blanks: &[Blank], at: Option<Point>) -> Option<(usize, usize)> {
|
||||
match at {
|
||||
Some(p) => blanks.iter().enumerate().find_map(|(i, b)| Some((i, panel_at(b, p)?))),
|
||||
None => {
|
||||
let largest = |b: &Blank| b.panels.iter().map(|p| p.area).fold(f64::NEG_INFINITY, f64::max);
|
||||
let (i, b) =
|
||||
blanks.iter().enumerate().filter(|(_, b)| !b.panels.is_empty()).fold(None, |best: Option<(usize, &Blank)>, (i, b)| match best {
|
||||
Some((_, kept)) if largest(kept) >= largest(b) => best,
|
||||
_ => Some((i, b)),
|
||||
})?;
|
||||
Some((i, base_panel(&b.panels)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `blank` folded about its panel `base` (the largest when `None`) by `amount` (0, flat, to 1, every
|
||||
/// hinge at its angle). `tolerance` (points) is how far apart a closing hinge's placements may end
|
||||
/// up and still close (or 0.5% of its length, when that is more), and how far apart two panels in
|
||||
/// one plane may lie and still be stacked rather than crossing. `None` when the blank has no
|
||||
/// panels, `base` is not one of them, or `amount` is not from 0 to 1.
|
||||
pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) -> Option<Folded> {
|
||||
let base = match base {
|
||||
Some(b) => b,
|
||||
None => base_panel(&blank.panels)?,
|
||||
};
|
||||
if base >= blank.panels.len() || !(0.0..=1.0).contains(&amount) {
|
||||
return None;
|
||||
}
|
||||
let tolerance = if tolerance.is_finite() && tolerance > 0.0 { tolerance } else { 0.01 };
|
||||
let n = blank.panels.len();
|
||||
// Each panel's hinges, by the place they start (y, then x), then by the other panel.
|
||||
let mut by_panel: Vec<Vec<usize>> = vec![vec![]; n];
|
||||
for (i, h) in blank.hinges.iter().enumerate() {
|
||||
for p in [h.a, h.b] {
|
||||
if let Some(list) = by_panel.get_mut(p) {
|
||||
list.push(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
// A hinge's ends, the one first by (y, x) first.
|
||||
let ends = |i: &usize| {
|
||||
blank.hinges.get(*i).map_or([f64::INFINITY; 4], |h| {
|
||||
let (s, e) = if (h.from.y, h.from.x) <= (h.to.y, h.to.x) { (h.from, h.to) } else { (h.to, h.from) };
|
||||
[s.y, s.x, e.y, e.x]
|
||||
})
|
||||
};
|
||||
for list in &mut by_panel {
|
||||
list.sort_by(|a, b| {
|
||||
let (ka, kb) = (ends(a), ends(b));
|
||||
ka.iter().zip(&kb).fold(std::cmp::Ordering::Equal, |o, (x, y)| o.then(x.total_cmp(y))).then(a.cmp(b))
|
||||
});
|
||||
}
|
||||
let centers: Vec<Option<V3>> = blank.panels.iter().map(|p| point_in(&p.outline).map(flat)).collect();
|
||||
let (panels, tree, order) = place(blank, &by_panel, ¢ers, base, amount);
|
||||
// Closing hinges are measured with every hinge at its full angle, so a blank that closes when
|
||||
// folded is not reported open part of the way there.
|
||||
let full = if amount == 1.0 { None } else { Some(place(blank, &by_panel, ¢ers, base, 1.0).0) };
|
||||
let measured = full.as_deref().unwrap_or(&panels);
|
||||
let hinges = blank
|
||||
.hinges
|
||||
.iter()
|
||||
.zip(&tree)
|
||||
.map(|(h, &tree)| {
|
||||
let (pa, pb) = (measured.get(h.a).map(|p| p.pose), measured.get(h.b).map(|p| p.pose));
|
||||
let gap = match (pa, pb) {
|
||||
(Some(pa), Some(pb)) if !tree => [h.from, h.to].iter().map(|&e| length(sub(pa.place(e), pb.place(e)))).fold(0.0, f64::max),
|
||||
_ => 0.0,
|
||||
};
|
||||
let closes = tree || gap <= tolerance.max(0.005 * h.from.distance(h.to));
|
||||
FoldedHinge { a: h.a, b: h.b, angle: h.angle, tree, closes, gap }
|
||||
})
|
||||
.collect();
|
||||
let collisions = collisions(blank, &panels, tolerance);
|
||||
Some(Folded { base, panels, order, hinges, collisions })
|
||||
}
|
||||
|
||||
/// The panels of `blank` placed by the fold tree from `base` with each hinge at `amount` of its
|
||||
/// angle, which hinges are in the tree, and the panels in breadth-first order (the panels not
|
||||
/// joined to the base last).
|
||||
fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: usize, amount: f64) -> (Vec<FoldedPanel>, Vec<bool>, Vec<usize>) {
|
||||
let n = blank.panels.len();
|
||||
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n];
|
||||
let mut reached = vec![false; n];
|
||||
let mut tree = vec![false; blank.hinges.len()];
|
||||
let mut order = Vec::with_capacity(n);
|
||||
let mut queue = VecDeque::from([base]);
|
||||
if let Some(r) = reached.get_mut(base) {
|
||||
*r = true;
|
||||
}
|
||||
while let Some(p) = queue.pop_front() {
|
||||
order.push(p);
|
||||
let Some(parent) = panels.get(p).cloned() else { continue };
|
||||
for &hi in by_panel.get(p).map(Vec::as_slice).unwrap_or_default() {
|
||||
let Some(h) = blank.hinges.get(hi) else { continue };
|
||||
let child = if h.a == p { h.b } else { h.a };
|
||||
if reached.get(child) != Some(&false) {
|
||||
continue;
|
||||
}
|
||||
let (mut from, mut to) = (flat(h.from), flat(h.to));
|
||||
let len = length(sub(to, from));
|
||||
if !(len.is_finite() && len > 0.0) {
|
||||
continue;
|
||||
}
|
||||
// The parent on the left of the hinge's direction, the child on its right. The side is
|
||||
// read next to the hinge, so a parent with a notch or an arm past the hinge's line still
|
||||
// turns the child the right way; the panel's inside point is the fallback.
|
||||
let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len)) {
|
||||
Some(left) => left,
|
||||
None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0),
|
||||
};
|
||||
if !left {
|
||||
std::mem::swap(&mut from, &mut to);
|
||||
}
|
||||
let axis = scale(sub(to, from), 1.0 / len);
|
||||
let theta = (h.angle * amount).to_radians();
|
||||
if !theta.is_finite() {
|
||||
continue;
|
||||
}
|
||||
if let Some(slot) = panels.get_mut(child) {
|
||||
*slot = FoldedPanel { pose: parent.pose.turned_about(from, axis, theta), parent: Some(p), depth: parent.depth + 1 };
|
||||
}
|
||||
if let Some(r) = reached.get_mut(child) {
|
||||
*r = true;
|
||||
}
|
||||
if let Some(t) = tree.get_mut(hi) {
|
||||
*t = true;
|
||||
}
|
||||
queue.push_back(child);
|
||||
}
|
||||
}
|
||||
order.extend((0..n).filter(|&i| reached.get(i) == Some(&false)));
|
||||
(panels, tree, order)
|
||||
}
|
||||
|
||||
/// Whether `outline` lies on the left of the line from `from` to `to` (flat coordinates, `len` apart)
|
||||
/// next to its middle: `Some(true)` when a point just off the middle on the left is inside it and
|
||||
/// the matching point on the right is not, `Some(false)` the other way round, `None` when no offset
|
||||
/// tells them apart. The nearest offset is tried first.
|
||||
fn side_of(outline: &PathData, from: V3, to: V3, len: f64) -> Option<bool> {
|
||||
let bp = outline.to_bezpath();
|
||||
let mid = scale(add(from, to), 0.5);
|
||||
let left = [-(to[1] - from[1]) / len, (to[0] - from[0]) / len, 0.0];
|
||||
let doc = |v: V3| Point::new(v[0], -v[1]);
|
||||
let mut offsets = [1e-3, 0.25, len * 0.01];
|
||||
offsets.sort_by(f64::total_cmp);
|
||||
offsets.into_iter().find_map(|off| {
|
||||
let (l, r) = (bp.winding(doc(add(mid, scale(left, off)))) != 0, bp.winding(doc(sub(mid, scale(left, off)))) != 0);
|
||||
(l != r).then_some(l)
|
||||
})
|
||||
}
|
||||
|
||||
/// The rings of `path` flattened to `tolerance`, in document coordinates; `None` past
|
||||
/// [`MAX_POLYGON_POINTS`] points.
|
||||
pub fn polygon(path: &PathData, tolerance: f64) -> Option<Vec<Vec<Point>>> {
|
||||
let mut rings: Vec<Vec<Point>> = vec![];
|
||||
let mut count = 0usize;
|
||||
let mut fits = true;
|
||||
vectorcraft_geom::flatten(path.to_bezpath(), tolerance, |el| {
|
||||
if !fits {
|
||||
return;
|
||||
}
|
||||
match el {
|
||||
PathEl::MoveTo(p) => rings.push(vec![p]),
|
||||
PathEl::LineTo(p) => match rings.last_mut() {
|
||||
Some(r) => r.push(p),
|
||||
None => rings.push(vec![p]),
|
||||
},
|
||||
_ => return,
|
||||
}
|
||||
count += 1;
|
||||
fits = count <= MAX_POLYGON_POINTS;
|
||||
});
|
||||
rings.retain(|r| r.len() >= 3);
|
||||
(fits && rings.iter().flatten().all(|p| p.is_finite())).then_some(rings)
|
||||
}
|
||||
|
||||
/// A panel placed in 3D: its rings, the plane it lies in (unit normal and offset) and its bounds.
|
||||
struct Placed {
|
||||
rings: Vec<Vec<V3>>,
|
||||
normal: V3,
|
||||
offset: f64,
|
||||
lo: V3,
|
||||
hi: V3,
|
||||
}
|
||||
|
||||
/// The pairs of `panels` that pass through each other. Two panels hinged to each other are not
|
||||
/// tested, nor two in parallel planes (stacked in one plane, or apart).
|
||||
fn collisions(blank: &Blank, panels: &[FoldedPanel], tolerance: f64) -> Vec<(usize, usize)> {
|
||||
let placed: Vec<Option<Placed>> = blank
|
||||
.panels
|
||||
.iter()
|
||||
.zip(panels)
|
||||
.map(|(panel, f)| {
|
||||
let rings: Vec<Vec<V3>> =
|
||||
polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| f.pose.place(p)).collect()).collect();
|
||||
let all = rings.iter().flatten();
|
||||
let lo = all.clone().fold([f64::INFINITY; 3], |a, p| [a[0].min(p[0]), a[1].min(p[1]), a[2].min(p[2])]);
|
||||
let hi = all.fold([f64::NEG_INFINITY; 3], |a, p| [a[0].max(p[0]), a[1].max(p[1]), a[2].max(p[2])]);
|
||||
let normal = f.pose.normal();
|
||||
let offset = dot(normal, f.pose.t);
|
||||
Some(Placed { rings, normal, offset, lo, hi })
|
||||
})
|
||||
.collect();
|
||||
let hinged: HashSet<(usize, usize)> = blank.hinges.iter().map(|h| (h.a.min(h.b), h.a.max(h.b))).collect();
|
||||
let mut out = vec![];
|
||||
for (i, a) in placed.iter().enumerate() {
|
||||
let Some(a) = a else { continue };
|
||||
for (j, b) in placed.iter().enumerate().skip(i + 1) {
|
||||
let Some(b) = b else { continue };
|
||||
if hinged.contains(&(i, j)) || (0..3).any(|k| a.hi[k] + tolerance < b.lo[k] || b.hi[k] + tolerance < a.lo[k]) {
|
||||
continue;
|
||||
}
|
||||
let line = cross(a.normal, b.normal);
|
||||
let along = length(line);
|
||||
if along.is_nan() || along <= 1e-9 {
|
||||
continue;
|
||||
}
|
||||
let u = scale(line, 1.0 / along);
|
||||
let on_a = crossings(&a.rings, b.normal, b.offset, u, tolerance);
|
||||
let on_b = crossings(&b.rings, a.normal, a.offset, u, tolerance);
|
||||
if on_a.iter().any(|x| on_b.iter().any(|y| x.1.min(y.1) - x.0.max(y.0) > tolerance)) {
|
||||
out.push((i, j));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where `rings` cross the plane `normal · p = offset`: the spans of the line along `u` that lie
|
||||
/// inside them, by their place along `u`. A panel with no point more than `tolerance` to one side
|
||||
/// of the plane only touches it, and crosses it nowhere; otherwise points within `tolerance` of it
|
||||
/// count as on its positive side.
|
||||
fn crossings(rings: &[Vec<V3>], normal: V3, offset: f64, u: V3, tolerance: f64) -> Vec<(f64, f64)> {
|
||||
let side = |p: V3| dot(normal, p) - offset;
|
||||
let sides = rings.iter().flatten().map(|&p| side(p));
|
||||
let (above, below) = sides.fold((false, false), |(a, b), s| (a || s > tolerance, b || s < -tolerance));
|
||||
if !(above && below) {
|
||||
return vec![];
|
||||
}
|
||||
let mut at = vec![];
|
||||
for ring in rings {
|
||||
for (k, &p) in ring.iter().enumerate() {
|
||||
let Some(&q) = ring.get((k + 1) % ring.len()) else { continue };
|
||||
let (sp, sq) = (side(p), side(q));
|
||||
if (sp >= -tolerance) != (sq >= -tolerance) {
|
||||
let t = (sp / (sp - sq)).clamp(0.0, 1.0);
|
||||
at.push(dot(u, add(p, scale(sub(q, p), t))));
|
||||
}
|
||||
}
|
||||
}
|
||||
at.retain(|x| x.is_finite());
|
||||
at.sort_by(f64::total_cmp);
|
||||
at.as_chunks::<2>().0.iter().map(|&[a, b]| (a, b)).collect()
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
//! Draws a [`Folded`] blank as pixels: each panel's outline is projected through the view and filled
|
||||
//! by scanline, with a depth buffer, and each pixel takes its color from a raster of the flat print
|
||||
//! (the printed side) or from the inside color (the back), shaded by the panel's slope to a fixed
|
||||
//! light. The inverse of the panel's projective map gives the flat point under every pixel, so the
|
||||
//! print is drawn without seams under perspective. With perspective, each panel is cut at a near
|
||||
//! plane in front of the eye before it is projected.
|
||||
|
||||
use vectorcraft_geom::{Point, Rect};
|
||||
|
||||
use super::pose::{Folded, polygon};
|
||||
use super::{Blank, Panel};
|
||||
|
||||
/// Most pixels a side of the view or of the print raster may have.
|
||||
pub const MAX_SIDE: u32 = 4096;
|
||||
/// Most pixels the view may have in all (2,048 × 1,024; 32 MiB of buffers).
|
||||
pub const MAX_PIXELS: u32 = 1 << 21;
|
||||
/// The share of the eye's distance a panel is cut at in front of the eye.
|
||||
const NEAREST: f64 = 1e-3;
|
||||
/// How far apart (points of view depth) two panels may be and still tie.
|
||||
const TIE: f64 = 1e-4;
|
||||
/// The light's direction: above, to the left of and toward the viewer.
|
||||
const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74];
|
||||
|
||||
type V3 = [f64; 3];
|
||||
|
||||
fn dot(a: V3, b: V3) -> f64 {
|
||||
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
|
||||
}
|
||||
|
||||
/// The view: its size in pixels, its turn (degrees: `rotate_x` tips the top toward the viewer,
|
||||
/// `rotate_y` turns the right side toward the viewer), its scale (pixels per point at the center's
|
||||
/// depth), how far it is moved (pixels), its perspective (the field of view in degrees; 0 for none)
|
||||
/// and the 3D point at its middle.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Camera {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub rotate_x: f64,
|
||||
pub rotate_y: f64,
|
||||
pub scale: f64,
|
||||
pub pan: [f64; 2],
|
||||
pub perspective: f64,
|
||||
pub center: [f64; 3],
|
||||
}
|
||||
|
||||
impl Camera {
|
||||
/// The turn from 3D to the view's own axes (x right, y up, z toward the viewer), as rows.
|
||||
fn rotation(&self) -> [[f64; 3]; 3] {
|
||||
let (sx, cx) = self.rotate_x.to_radians().sin_cos();
|
||||
let (sy, cy) = (-self.rotate_y).to_radians().sin_cos();
|
||||
// Rx · Ry
|
||||
[[cy, 0.0, sy], [sx * sy, cx, -sx * cy], [-cx * sy, sx, cx * cy]]
|
||||
}
|
||||
|
||||
/// The point `p` in the view's own axes, its middle at the origin.
|
||||
pub fn to_view(&self, p: V3) -> V3 {
|
||||
let r = self.rotation();
|
||||
let d = [p[0] - self.center[0], p[1] - self.center[1], p[2] - self.center[2]];
|
||||
[dot(r[0], d), dot(r[1], d), dot(r[2], d)]
|
||||
}
|
||||
|
||||
/// The distance (points) from the eye to the view's middle and the focal length (pixels) under
|
||||
/// perspective; `None` without it.
|
||||
fn eye(&self) -> Option<(f64, f64)> {
|
||||
if self.perspective <= 0.0 || self.perspective >= 180.0 {
|
||||
return None;
|
||||
}
|
||||
let half = f64::from(self.width.min(self.height)) / 2.0;
|
||||
let focal = half / (self.perspective.to_radians() / 2.0).tan();
|
||||
let eye = focal / self.scale;
|
||||
(focal.is_finite() && eye.is_finite() && eye > 0.0).then_some((eye, focal))
|
||||
}
|
||||
|
||||
fn usable(&self) -> bool {
|
||||
let finite =
|
||||
[self.rotate_x, self.rotate_y, self.scale, self.pan[0], self.pan[1], self.perspective].iter().chain(&self.center).all(|v| v.is_finite());
|
||||
let pixels = u64::from(self.width) * u64::from(self.height);
|
||||
finite && self.scale > 0.0 && (1..=MAX_SIDE).contains(&self.width) && (1..=MAX_SIDE).contains(&self.height) && pixels <= u64::from(MAX_PIXELS)
|
||||
}
|
||||
}
|
||||
|
||||
/// One level of the print raster: premultiplied RGBA, 4 bytes a pixel.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Level {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Level {
|
||||
/// The color at pixel `(x, y)`, clamped to the edges.
|
||||
fn at(&self, x: i64, y: i64) -> [f32; 4] {
|
||||
let x = x.clamp(0, i64::from(self.width) - 1);
|
||||
let y = y.clamp(0, i64::from(self.height) - 1);
|
||||
let i = usize::try_from((y * i64::from(self.width) + x) * 4).unwrap_or(usize::MAX);
|
||||
match self.pixels.get(i..i.saturating_add(4)) {
|
||||
Some(&[r, g, b, a]) => [f32::from(r), f32::from(g), f32::from(b), f32::from(a)],
|
||||
_ => [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// The color at `(x, y)` (pixels), between the four nearest pixels.
|
||||
fn sample(&self, x: f64, y: f64) -> [f32; 4] {
|
||||
let (fx, fy) = (x - 0.5, y - 0.5);
|
||||
let (x0, y0) = (fx.floor(), fy.floor());
|
||||
let (tx, ty) = ((fx - x0) as f32, (fy - y0) as f32);
|
||||
let (x0, y0) = (x0 as i64, y0 as i64);
|
||||
let (a, b, c, d) = (self.at(x0, y0), self.at(x0 + 1, y0), self.at(x0, y0 + 1), self.at(x0 + 1, y0 + 1));
|
||||
let mut out = [0.0; 4];
|
||||
for (k, o) in out.iter_mut().enumerate() {
|
||||
let top = a[k] + (b[k] - a[k]) * tx;
|
||||
let bottom = c[k] + (d[k] - c[k]) * tx;
|
||||
*o = top + (bottom - top) * ty;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// This level at half its size, rounded up, each pixel the mean of the pixels it covers weighted
|
||||
/// by the area of the full print they cover. A pixel of this level is `step` pixels of the full
|
||||
/// print (`base` pixels across and down) on a side, and fewer in the last column and row when
|
||||
/// `base` is not a multiple of `step`.
|
||||
fn half(&self, base: (u32, u32), step: u32) -> Option<Level> {
|
||||
let (w, h) = (self.width.div_ceil(2), self.height.div_ceil(2));
|
||||
if (w, h) == (self.width, self.height) {
|
||||
return None;
|
||||
}
|
||||
// The pixels of the full print that column or row `i` of this level covers, or 0 past it.
|
||||
let covers = |i: u32, side: u32| u64::from(side).saturating_sub(u64::from(i) * u64::from(step)).min(u64::from(step)) as f32;
|
||||
let mut pixels = Vec::with_capacity(w as usize * h as usize * 4);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let mut sum = [0.0f32; 4];
|
||||
let mut area = 0.0;
|
||||
for (sx, sy) in [(2 * x, 2 * y), (2 * x + 1, 2 * y), (2 * x, 2 * y + 1), (2 * x + 1, 2 * y + 1)] {
|
||||
if sx >= self.width || sy >= self.height {
|
||||
continue;
|
||||
}
|
||||
let a = covers(sx, base.0) * covers(sy, base.1);
|
||||
let p = self.at(i64::from(sx), i64::from(sy));
|
||||
for (s, c) in sum.iter_mut().zip(p) {
|
||||
*s += c * a;
|
||||
}
|
||||
area += a;
|
||||
}
|
||||
for s in sum {
|
||||
pixels.push(if area > 0.0 { (s / area).round() as u8 } else { 0 });
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Level { width: w, height: h, pixels })
|
||||
}
|
||||
}
|
||||
|
||||
/// The flat print: the document rect it covers and its raster at full size and halved again and
|
||||
/// again down to one pixel.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Print {
|
||||
pub region: Rect,
|
||||
pub levels: Vec<Level>,
|
||||
}
|
||||
|
||||
impl Print {
|
||||
/// The print of `region` from `pixels` (premultiplied RGBA, `width` × `height`); `None` when
|
||||
/// the sizes do not agree, a side is 0 or more than [`MAX_SIDE`], or the region is empty.
|
||||
pub fn new(region: Rect, width: u32, height: u32, pixels: Vec<u8>) -> Option<Print> {
|
||||
let fits = (1..=MAX_SIDE).contains(&width) && (1..=MAX_SIDE).contains(&height);
|
||||
let empty = !(region.width() > 0.0 && region.height() > 0.0 && region.is_finite());
|
||||
if !fits || empty || pixels.len() != width as usize * height as usize * 4 {
|
||||
return None;
|
||||
}
|
||||
let mut levels = vec![Level { width, height, pixels }];
|
||||
let mut step = 1;
|
||||
while let Some(next) = levels.last().and_then(|l| l.half((width, height), step)) {
|
||||
levels.push(next);
|
||||
step *= 2;
|
||||
}
|
||||
Some(Print { region, levels })
|
||||
}
|
||||
|
||||
/// The print's color (premultiplied, 0 to 255) at document point `p`, from the level whose
|
||||
/// pixels are closest to `footprint` points across; transparent outside the region.
|
||||
fn sample(&self, p: Point, footprint: f64) -> [f32; 4] {
|
||||
let Some(base) = self.levels.first() else { return [0.0; 4] };
|
||||
if !self.region.contains(p) {
|
||||
return [0.0; 4];
|
||||
}
|
||||
let per_point = f64::from(base.width) / self.region.width();
|
||||
let level = if footprint.is_finite() && footprint > 0.0 { (footprint * per_point).log2().floor().max(0.0) as usize } else { 0 };
|
||||
let level = level.min(self.levels.len() - 1);
|
||||
let Some(l) = self.levels.get(level) else { return [0.0; 4] };
|
||||
// Each level halves the one before it, so a pixel of level n covers 2ⁿ of the first's.
|
||||
let shrink = f64::from(1u32 << level);
|
||||
let sx = f64::from(base.width) / self.region.width() / shrink;
|
||||
let sy = f64::from(base.height) / self.region.height() / shrink;
|
||||
l.sample((p.x - self.region.x0) * sx, (p.y - self.region.y0) * sy)
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`render`] draws: a folded blank, its print (if any), the color of the board's back and of
|
||||
/// its printed side where the print has no art (straight RGBA; the board is opaque, so their alpha
|
||||
/// is not used), and the view.
|
||||
pub struct Scene<'a> {
|
||||
pub blank: &'a Blank,
|
||||
pub folded: &'a Folded,
|
||||
pub print: Option<&'a Print>,
|
||||
pub inside: [u8; 4],
|
||||
pub outside: [u8; 4],
|
||||
pub camera: Camera,
|
||||
}
|
||||
|
||||
/// A drawn view: premultiplied RGBA, 4 bytes a pixel, transparent where no panel is; and for each
|
||||
/// pixel the panel drawn there plus 1 (0 for none).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Image {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub pixels: Vec<u8>,
|
||||
pub panels: Vec<u16>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
/// The panel drawn at pixel `(x, y)`.
|
||||
pub fn panel_at(&self, x: u32, y: u32) -> Option<usize> {
|
||||
if x >= self.width || y >= self.height {
|
||||
return None;
|
||||
}
|
||||
let i = y as usize * self.width as usize + x as usize;
|
||||
self.panels.get(i).and_then(|&p| usize::from(p).checked_sub(1))
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D bounds of `blank`'s panels folded as `folded` places them (low and high corners).
|
||||
pub fn bounds(blank: &Blank, folded: &Folded) -> Option<(V3, V3)> {
|
||||
let mut lo = [f64::INFINITY; 3];
|
||||
let mut hi = [f64::NEG_INFINITY; 3];
|
||||
for (panel, f) in blank.panels.iter().zip(&folded.panels) {
|
||||
let Some(b) = panel.outline.bounds() else { continue };
|
||||
for c in [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x0, b.y1), Point::new(b.x1, b.y1)] {
|
||||
let p = f.pose.place(c);
|
||||
for k in 0..3 {
|
||||
lo[k] = lo[k].min(p[k]);
|
||||
hi[k] = hi[k].max(p[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
lo.iter().chain(&hi).all(|v| v.is_finite()).then_some((lo, hi))
|
||||
}
|
||||
|
||||
/// A panel ready to fill: its projective map from the flat blank to the view and back, its depth
|
||||
/// plane in view terms, and its color factors.
|
||||
struct Mapped {
|
||||
/// Flat (u, v, 1) → (x w, y w, w) in pixels, as rows.
|
||||
forward: [[f64; 3]; 3],
|
||||
/// The inverse of `forward`.
|
||||
inverse: [[f64; 3]; 3],
|
||||
/// View depth at flat (u, v): u a + v b + c.
|
||||
depth: [f64; 3],
|
||||
printed: bool,
|
||||
shade: f32,
|
||||
}
|
||||
|
||||
fn mul(m: &[[f64; 3]; 3], v: V3) -> V3 {
|
||||
[dot(m[0], v), dot(m[1], v), dot(m[2], v)]
|
||||
}
|
||||
|
||||
fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
|
||||
let [[a, b, c], [d, e, f], [g, h, i]] = *m;
|
||||
let co = [e * i - f * h, f * g - d * i, d * h - e * g];
|
||||
let det = a * co[0] + b * co[1] + c * co[2];
|
||||
if !(det.is_finite() && det.abs() > 1e-300) {
|
||||
return None;
|
||||
}
|
||||
let inv = [
|
||||
[co[0] / det, (c * h - b * i) / det, (b * f - c * e) / det],
|
||||
[co[1] / det, (a * i - c * g) / det, (c * d - a * f) / det],
|
||||
[co[2] / det, (b * g - a * h) / det, (a * e - b * d) / det],
|
||||
];
|
||||
inv.iter().flatten().all(|v| v.is_finite()).then_some(inv)
|
||||
}
|
||||
|
||||
fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> {
|
||||
let r = camera.rotation();
|
||||
let turn = |v: V3| mul(&r, f.pose.turn(v));
|
||||
let (a, b) = (turn([1.0, 0.0, 0.0]), turn([0.0, 1.0, 0.0]));
|
||||
let o = camera.to_view(f.pose.t);
|
||||
let (cx, cy) = (f64::from(camera.width) / 2.0 + camera.pan[0], f64::from(camera.height) / 2.0 + camera.pan[1]);
|
||||
let normal = turn([0.0, 0.0, 1.0]);
|
||||
let (w, k, printed) = match camera.eye() {
|
||||
Some((eye, focal)) => ([-a[2], -b[2], eye - o[2]], focal, dot(normal, [-o[0], -o[1], eye - o[2]]) > 0.0),
|
||||
None => ([0.0, 0.0, 1.0], camera.scale, normal[2] > 0.0),
|
||||
};
|
||||
let x = [cx * w[0] + k * a[0], cx * w[1] + k * b[0], cx * w[2] + k * o[0]];
|
||||
let y = [cy * w[0] - k * a[1], cy * w[1] - k * b[1], cy * w[2] - k * o[1]];
|
||||
let forward = [x, y, w];
|
||||
let inverse = invert(&forward)?;
|
||||
let facing = if printed { normal } else { [-normal[0], -normal[1], -normal[2]] };
|
||||
let shade = (0.6 + 0.4 * dot(facing, LIGHT).max(0.0)) as f32;
|
||||
Some(Mapped { forward, inverse, depth: [a[2], b[2], o[2]], printed, shade })
|
||||
}
|
||||
|
||||
/// `ring` (flat points) cut to the side of the plane `w · (u, v, 1) ≥ near`.
|
||||
fn clip(ring: &[[f64; 2]], w: V3, near: f64) -> Vec<[f64; 2]> {
|
||||
let at = |p: [f64; 2]| dot(w, [p[0], p[1], 1.0]) - near;
|
||||
let mut out = Vec::with_capacity(ring.len() + 4);
|
||||
for (k, &p) in ring.iter().enumerate() {
|
||||
let Some(&q) = ring.get((k + 1) % ring.len()) else { continue };
|
||||
let (dp, dq) = (at(p), at(q));
|
||||
if dp >= 0.0 {
|
||||
out.push(p);
|
||||
}
|
||||
if (dp >= 0.0) != (dq >= 0.0) {
|
||||
let t = dp / (dp - dq);
|
||||
out.push([p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The buffers [`render`] fills.
|
||||
struct Target {
|
||||
width: usize,
|
||||
height: usize,
|
||||
color: Vec<u8>,
|
||||
depth: Vec<f64>,
|
||||
rank: Vec<u16>,
|
||||
panel: Vec<u16>,
|
||||
}
|
||||
|
||||
/// One panel's fill: its map, rank (for ties), panel number and colors.
|
||||
struct Fill<'a> {
|
||||
mapped: &'a Mapped,
|
||||
rank: u16,
|
||||
panel: u16,
|
||||
print: Option<&'a Print>,
|
||||
inside: [f32; 4],
|
||||
outside: [f32; 4],
|
||||
}
|
||||
|
||||
impl Fill<'_> {
|
||||
/// The document point under pixel center `(x, y)`, or `None` behind the eye.
|
||||
fn flat_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
|
||||
let [u, v, w] = mul(&self.mapped.inverse, [x, y, 1.0]);
|
||||
(w > 0.0 && w.is_finite()).then(|| (u / w, v / w)).filter(|(u, v)| u.is_finite() && v.is_finite())
|
||||
}
|
||||
|
||||
/// The color of the panel at flat point `(u, v)`, `footprint` points across a pixel.
|
||||
fn color(&self, u: f64, v: f64, footprint: f64) -> [f32; 4] {
|
||||
let base = if self.mapped.printed {
|
||||
let p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u, -v), footprint));
|
||||
let under = 1.0 - p[3] / 255.0;
|
||||
[p[0] + self.outside[0] * under, p[1] + self.outside[1] * under, p[2] + self.outside[2] * under, 255.0]
|
||||
} else {
|
||||
self.inside
|
||||
};
|
||||
let s = self.mapped.shade;
|
||||
[base[0] * s, base[1] * s, base[2] * s, base[3]]
|
||||
}
|
||||
|
||||
/// Fill the span of row `row` from `x0` to `x1` (pixel coordinates) into `target`.
|
||||
fn span(&self, target: &mut Target, row: usize, x0: f64, x1: f64) {
|
||||
let first = (x0 - 0.5).ceil().max(0.0);
|
||||
let last = ((x1 - 0.5).ceil() - 1.0).min(target.width as f64 - 1.0);
|
||||
if first > last {
|
||||
return;
|
||||
}
|
||||
let y = row as f64 + 0.5;
|
||||
for col in first as usize..=last as usize {
|
||||
let x = col as f64 + 0.5;
|
||||
let Some((u, v)) = self.flat_at(x, y) else { continue };
|
||||
let [a, b, c] = self.mapped.depth;
|
||||
let z = u * a + v * b + c;
|
||||
let i = row * target.width + col;
|
||||
let (Some(&zb), Some(&rb)) = (target.depth.get(i), target.rank.get(i)) else { continue };
|
||||
let wins = z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb);
|
||||
if !wins {
|
||||
continue;
|
||||
}
|
||||
// The print's footprint is the longer of a pixel's two sides in flat terms.
|
||||
let across = |dx: f64, dy: f64| self.flat_at(x + dx, y + dy).map_or(0.0, |(u2, v2)| (u2 - u).hypot(v2 - v));
|
||||
let footprint = across(1.0, 0.0).max(across(0.0, 1.0));
|
||||
let color = self.color(u, v, footprint);
|
||||
if let Some(px) = target.color.get_mut(i * 4..i * 4 + 4) {
|
||||
for (o, c) in px.iter_mut().zip(color) {
|
||||
*o = c.round().clamp(0.0, 255.0) as u8;
|
||||
}
|
||||
}
|
||||
if let Some(d) = target.depth.get_mut(i) {
|
||||
*d = z;
|
||||
}
|
||||
if let Some(r) = target.rank.get_mut(i) {
|
||||
*r = self.rank;
|
||||
}
|
||||
if let Some(p) = target.panel.get_mut(i) {
|
||||
*p = self.panel;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the projected `rings` (pixel coordinates), even-odd, into `target`.
|
||||
fn rings(&self, target: &mut Target, rings: &[Vec<[f64; 2]>]) {
|
||||
let ys = rings.iter().flatten().map(|p| p[1]);
|
||||
let (lo, hi) = ys.fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), y| (lo.min(y), hi.max(y)));
|
||||
if !(lo.is_finite() && hi.is_finite()) {
|
||||
return;
|
||||
}
|
||||
let first = (lo - 0.5).ceil().max(0.0);
|
||||
let last = (hi - 0.5).floor().min(target.height as f64 - 1.0);
|
||||
if first > last {
|
||||
return;
|
||||
}
|
||||
let mut xs = vec![];
|
||||
for row in first as usize..=last as usize {
|
||||
let y = row as f64 + 0.5;
|
||||
xs.clear();
|
||||
for ring in rings {
|
||||
for (k, p) in ring.iter().enumerate() {
|
||||
let Some(q) = ring.get((k + 1) % ring.len()) else { continue };
|
||||
if (p[1] <= y) != (q[1] <= y) {
|
||||
xs.push(p[0] + (y - p[1]) * (q[0] - p[0]) / (q[1] - p[1]));
|
||||
}
|
||||
}
|
||||
}
|
||||
xs.retain(|x| x.is_finite());
|
||||
xs.sort_by(f64::total_cmp);
|
||||
for &[a, b] in xs.as_chunks::<2>().0 {
|
||||
self.span(target, row, a, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The board color `c` as drawn: its RGB, opaque.
|
||||
fn opaque(c: [u8; 4]) -> [f32; 4] {
|
||||
[f32::from(c[0]), f32::from(c[1]), f32::from(c[2]), 255.0]
|
||||
}
|
||||
|
||||
/// The outline rings of `panel` in flat terms (u, v), flattened finely enough for `scale` pixels a
|
||||
/// point.
|
||||
fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> {
|
||||
let b = panel.outline.bounds()?;
|
||||
let tolerance = (0.25 / scale).max((b.width() + b.height()) * 1e-5).max(1e-6);
|
||||
Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect())
|
||||
}
|
||||
|
||||
/// `scene` drawn; `None` when the view is not usable (a size of 0, a side over [`MAX_SIDE`], more
|
||||
/// than [`MAX_PIXELS`] pixels, or a value that is not finite). Panels whose map is not finite, or whose outline has more than
|
||||
/// [`super::MAX_POLYGON_POINTS`] points, are left out.
|
||||
pub fn render(scene: &Scene) -> Option<Image> {
|
||||
let camera = scene.camera;
|
||||
if !camera.usable() {
|
||||
return None;
|
||||
}
|
||||
let (width, height) = (camera.width as usize, camera.height as usize);
|
||||
let pixels = width * height;
|
||||
let mut target =
|
||||
Target { width, height, color: vec![0; pixels * 4], depth: vec![f64::NEG_INFINITY; pixels], rank: vec![0; pixels], panel: vec![0; pixels] };
|
||||
let (inside, outside) = (opaque(scene.inside), opaque(scene.outside));
|
||||
let near = camera.eye().map(|(eye, _)| eye * NEAREST);
|
||||
for (rank, &pi) in scene.folded.order.iter().enumerate() {
|
||||
let (Some(panel), Some(f)) = (scene.blank.panels.get(pi), scene.folded.panels.get(pi)) else { continue };
|
||||
let Some(mapped) = map_panel(&camera, f) else { continue };
|
||||
let Some(rings) = flat_rings(panel, camera.scale) else { continue };
|
||||
let projected: Vec<Vec<[f64; 2]>> = rings
|
||||
.iter()
|
||||
.map(|r| match near {
|
||||
Some(near) => clip(r, mapped.forward[2], near),
|
||||
None => r.clone(),
|
||||
})
|
||||
.filter(|r| r.len() >= 3)
|
||||
.map(|r| {
|
||||
r.into_iter()
|
||||
.filter_map(|[u, v]| {
|
||||
let [x, y, w] = mul(&mapped.forward, [u, v, 1.0]);
|
||||
let p = [x / w, y / w];
|
||||
(w > 0.0 && p[0].is_finite() && p[1].is_finite()).then_some(p)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.filter(|r| r.len() >= 3)
|
||||
.collect();
|
||||
let fill = Fill {
|
||||
mapped: &mapped,
|
||||
rank: u16::try_from(rank + 1).unwrap_or(u16::MAX),
|
||||
panel: u16::try_from(pi + 1).unwrap_or(u16::MAX),
|
||||
print: scene.print,
|
||||
inside,
|
||||
outside,
|
||||
};
|
||||
fill.rings(&mut target, &projected);
|
||||
}
|
||||
Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,257 @@
|
||||
use vectorcraft_geom::{PathData, Point, Rect, SubPath};
|
||||
|
||||
use super::super::{Blank, Folded, FoldedPanel, Panel, Pose};
|
||||
use super::*;
|
||||
|
||||
fn square(x0: f64, y0: f64, x1: f64, y1: f64) -> SubPath {
|
||||
SubPath::polyline(&[Point::new(x0, y0), Point::new(x1, y0), Point::new(x1, y1), Point::new(x0, y1)], true)
|
||||
}
|
||||
|
||||
fn panel(subpaths: Vec<SubPath>) -> Panel {
|
||||
Panel { outline: PathData::new(subpaths), area: 0.0 }
|
||||
}
|
||||
|
||||
/// A blank of `panels` and a fold that places each at `poses`, in the order given.
|
||||
fn scene_of(panels: Vec<Panel>, poses: Vec<Pose>) -> (Blank, Folded) {
|
||||
let n = panels.len();
|
||||
let folded = Folded {
|
||||
base: 0,
|
||||
panels: poses.into_iter().map(|pose| FoldedPanel { pose, parent: None, depth: 0 }).collect(),
|
||||
order: (0..n).collect(),
|
||||
hinges: vec![],
|
||||
collisions: vec![],
|
||||
};
|
||||
(Blank { panels, hinges: vec![], holes: vec![] }, folded)
|
||||
}
|
||||
|
||||
/// Facing the printed side, 100 × 100 pixels, one pixel a point, the flat square 0..100 filling it.
|
||||
fn front() -> Camera {
|
||||
Camera { width: 100, height: 100, rotate_x: 0.0, rotate_y: 0.0, scale: 1.0, pan: [0.0; 2], perspective: 0.0, center: [50.0, -50.0, 0.0] }
|
||||
}
|
||||
|
||||
fn moved(z: f64) -> Pose {
|
||||
Pose { t: [0.0, 0.0, z], ..Pose::IDENTITY }
|
||||
}
|
||||
|
||||
fn pixel(img: &Image, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = (y * img.width + x) as usize * 4;
|
||||
[img.pixels[i], img.pixels[i + 1], img.pixels[i + 2], img.pixels[i + 3]]
|
||||
}
|
||||
|
||||
/// A 2 × 2 print of the square 0..100: red, green on top; blue, white below.
|
||||
fn quads() -> Print {
|
||||
let px = [[255, 0, 0, 255], [0, 255, 0, 255], [0, 0, 255, 255], [255, 255, 255, 255]];
|
||||
Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 2, 2, px.concat()).expect("a print")
|
||||
}
|
||||
|
||||
const WHITE: [u8; 4] = [255, 255, 255, 255];
|
||||
|
||||
#[test]
|
||||
fn a_flat_panel_takes_the_print_s_color_under_each_pixel() {
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
let print = quads();
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
|
||||
let shade = 0.6 + 0.4 * 0.74;
|
||||
let lit = |c: f64| (c * shade).round() as u8;
|
||||
assert_eq!(pixel(&img, 5, 5), [lit(255.0), 0, 0, 255], "top left is red");
|
||||
assert_eq!(pixel(&img, 94, 5), [0, lit(255.0), 0, 255], "top right is green");
|
||||
assert_eq!(pixel(&img, 5, 94), [0, 0, lit(255.0), 255], "bottom left is blue");
|
||||
assert_eq!(img.panel_at(50, 50), Some(0));
|
||||
// Where the print has no art, the board's printed side shows.
|
||||
let empty = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 1, 1, vec![0; 4]).expect("a print");
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&empty), inside: [0, 0, 0, 255], outside: [200, 100, 50, 255], camera: front() })
|
||||
.expect("drawn");
|
||||
assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_board_is_opaque_whatever_the_alpha_of_its_colors() {
|
||||
let shade = 0.6 + 0.4 * 0.74;
|
||||
let lit = |c: f64| (c * shade).round() as u8;
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
for a in [0, 128] {
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: [200, 100, 50, a], camera: front() })
|
||||
.expect("drawn");
|
||||
assert_eq!(pixel(&img, 50, 50), [lit(200.0), lit(100.0), lit(50.0), 255], "outside alpha {a}");
|
||||
}
|
||||
// A transparent inside color draws opaque too, on the nearer of two panels seen from the back.
|
||||
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
|
||||
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(5.0)]);
|
||||
let camera = Camera { rotate_y: 180.0, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 200, 0, 0], outside: WHITE, camera }).expect("drawn");
|
||||
let [r, g, bl, a] = pixel(&img, 50, 50);
|
||||
assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_squeezed_only_up_and_down_on_screen_samples_a_halved_level() {
|
||||
// 64 × 64, rows alternating black and white: halved, they average to gray.
|
||||
let mut px = vec![];
|
||||
for y in 0..64 {
|
||||
for _ in 0..64 {
|
||||
px.extend(if y % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
|
||||
}
|
||||
}
|
||||
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print");
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
// Tipped 80°: about 5.8 points a pixel up and down, 1 across.
|
||||
let camera = Camera { rotate_x: 80.0, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
|
||||
let reds: Vec<u8> = (0..img.height)
|
||||
.flat_map(|y| (0..img.width).map(move |x| (x, y)))
|
||||
.filter(|&(x, y)| img.panel_at(x, y).is_some())
|
||||
.map(|(x, y)| pixel(&img, x, y)[0])
|
||||
.collect();
|
||||
assert!(!reds.is_empty());
|
||||
let (lo, hi) = (reds.iter().min().copied().unwrap_or(0), reds.iter().max().copied().unwrap_or(0));
|
||||
assert!(hi - lo <= 2, "an even gray, not black and white rows: {lo} to {hi}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_back_of_a_panel_shows_the_inside_color() {
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
let print = quads();
|
||||
let camera = Camera { rotate_y: 180.0, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0, 200, 0, 255], outside: WHITE, camera }).expect("drawn");
|
||||
let [r, g, bl, a] = pixel(&img, 50, 50);
|
||||
assert!(r == 0 && bl == 0 && g > 100 && a == 255, "{:?}", [r, g, bl, a]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nearer_of_two_panels_shows_and_a_tie_goes_to_the_later_one() {
|
||||
let whole = || panel(vec![square(0.0, 0.0, 100.0, 100.0)]);
|
||||
let draw = |z: f64| {
|
||||
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, moved(z)]);
|
||||
render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn")
|
||||
};
|
||||
assert_eq!(draw(5.0).panel_at(50, 50), Some(1), "panel 1 is in front");
|
||||
assert_eq!(draw(-5.0).panel_at(50, 50), Some(0), "panel 1 is behind");
|
||||
assert_eq!(draw(0.0).panel_at(50, 50), Some(1), "a tie goes to the panel later in the order");
|
||||
// Panels that cross: each shows where it is nearer.
|
||||
let tilted = Pose { m: [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.5, 0.0, 1.0]], t: [0.0, 0.0, -25.0] };
|
||||
let (b, f) = scene_of(vec![whole(), whole()], vec![Pose::IDENTITY, tilted]);
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
|
||||
assert_eq!(img.panel_at(20, 50), Some(0), "the tilted panel is behind on the left");
|
||||
assert_eq!(img.panel_at(80, 50), Some(1), "and in front on the right");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hole_in_a_panel_is_left_empty() {
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0), square(30.0, 30.0, 70.0, 70.0)])], vec![Pose::IDENTITY]);
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera: front() }).expect("drawn");
|
||||
assert_eq!(img.panel_at(50, 50), None);
|
||||
assert_eq!(pixel(&img, 50, 50), [0; 4]);
|
||||
assert_eq!(img.panel_at(10, 50), Some(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panel_past_the_eye_at_a_wide_perspective_is_cut_at_the_near_plane() {
|
||||
// A long panel standing out of the page toward the viewer, through the eye.
|
||||
let toward = Pose { m: [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], t: [0.0, -50.0, 0.0] };
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, -1000.0, 100.0, 1000.0)])], vec![toward]);
|
||||
for perspective in [1.0, 60.0, 160.0, 179.0] {
|
||||
let camera = Camera { perspective, scale: 8.0, rotate_x: 30.0, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: None, inside: [0, 0, 0, 255], outside: WHITE, camera }).expect("drawn");
|
||||
let drawn = img.panels.iter().filter(|&&p| p != 0).count();
|
||||
assert!(drawn > 0, "{perspective}°: some of it shows");
|
||||
assert_eq!(img.pixels.len(), 100 * 100 * 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unusable_views_and_prints_are_refused() {
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
for camera in [
|
||||
Camera { width: 0, ..front() },
|
||||
Camera { height: MAX_SIDE + 1, ..front() },
|
||||
Camera { width: MAX_SIDE, height: MAX_PIXELS / MAX_SIDE + 1, ..front() },
|
||||
Camera { scale: 0.0, ..front() },
|
||||
Camera { rotate_x: f64::NAN, ..front() },
|
||||
Camera { center: [f64::INFINITY, 0.0, 0.0], ..front() },
|
||||
] {
|
||||
assert!(render(&Scene { blank: &b, folded: &f, print: None, inside: [0; 4], outside: WHITE, camera }).is_none(), "{camera:?}");
|
||||
}
|
||||
let region = Rect::new(0.0, 0.0, 10.0, 10.0);
|
||||
assert!(Print::new(region, 2, 2, vec![0; 15]).is_none(), "too few bytes");
|
||||
assert!(Print::new(region, 0, 2, vec![]).is_none());
|
||||
assert!(Print::new(region, MAX_SIDE + 1, 1, vec![0; (MAX_SIDE as usize + 1) * 4]).is_none());
|
||||
assert!(Print::new(Rect::new(0.0, 0.0, 0.0, 10.0), 1, 1, vec![0; 4]).is_none(), "an empty region");
|
||||
let p = Print::new(region, 8, 4, vec![255; 8 * 4 * 4]).expect("a print");
|
||||
assert_eq!(p.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(8, 4), (4, 2), (2, 1), (1, 1)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn halving_an_odd_sized_print_keeps_its_last_row_and_column() {
|
||||
// 3 × 3, transparent but for an opaque white last column and last row.
|
||||
let mut px = vec![0u8; 3 * 3 * 4];
|
||||
for i in [2, 5, 6, 7, 8] {
|
||||
px[i * 4..i * 4 + 4].copy_from_slice(&[255; 4]);
|
||||
}
|
||||
let p = Print::new(Rect::new(0.0, 0.0, 30.0, 30.0), 3, 3, px).expect("a print");
|
||||
let half = &p.levels[1];
|
||||
assert_eq!((half.width, half.height), (2, 2));
|
||||
// The bottom right pixel of the half level covers only the corner pixel.
|
||||
assert_eq!(&half.pixels[12..16], &[255; 4]);
|
||||
assert_eq!(&half.pixels[0..4], &[0; 4], "the top left covers four transparent pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_far_smaller_on_screen_samples_a_halved_level() {
|
||||
// Columns alternate black and white: halved, they average to gray.
|
||||
let mut px = vec![];
|
||||
for _ in 0..4 {
|
||||
for x in 0..4 {
|
||||
px.extend(if x % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
|
||||
}
|
||||
}
|
||||
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 4, 4, px).expect("a print");
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
// 100 points in 2 pixels: 2 print pixels a view pixel.
|
||||
let camera = Camera { width: 2, height: 2, scale: 0.02, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
|
||||
let [r, ..] = pixel(&img, 0, 0);
|
||||
assert!((80..=150).contains(&r), "gray, not a black or white column: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_print_sixteen_times_smaller_on_screen_samples_a_level_halved_four_times() {
|
||||
// 64 × 64, columns in bands of 4 alternating black and white: halved twice, they still alternate;
|
||||
// halved four times, they average to gray.
|
||||
let mut px = vec![];
|
||||
for _ in 0..64 {
|
||||
for x in 0..64 {
|
||||
px.extend(if (x / 4) % 2 == 0 { [0, 0, 0, 255] } else { [255, 255, 255, 255] });
|
||||
}
|
||||
}
|
||||
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 64, 64, px).expect("a print");
|
||||
assert_eq!(print.levels.len(), 7, "64 down to 1");
|
||||
let (b, f) = scene_of(vec![panel(vec![square(0.0, 0.0, 100.0, 100.0)])], vec![Pose::IDENTITY]);
|
||||
// 100 points in 3 pixels: about 21 print pixels a view pixel.
|
||||
let camera = Camera { width: 3, height: 3, scale: 0.03, ..front() };
|
||||
let img = render(&Scene { blank: &b, folded: &f, print: Some(&print), inside: [0; 4], outside: WHITE, camera }).expect("drawn");
|
||||
let [r, ..] = pixel(&img, 0, 1);
|
||||
assert!((90..=140).contains(&r), "gray, not a black or white band: {r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_halved_level_weighs_an_odd_last_column_by_the_area_it_covers() {
|
||||
// 9 × 9, black but for a white last column: a ninth of the print, so the one-pixel level is
|
||||
// a ninth white (255 / 9 is about 28), not half.
|
||||
let mut px = vec![];
|
||||
for _ in 0..9 {
|
||||
for x in 0..9 {
|
||||
px.extend(if x == 8 { [255, 255, 255, 255] } else { [0, 0, 0, 255] });
|
||||
}
|
||||
}
|
||||
let print = Print::new(Rect::new(0.0, 0.0, 100.0, 100.0), 9, 9, px).expect("a print");
|
||||
assert_eq!(print.levels.iter().map(|l| (l.width, l.height)).collect::<Vec<_>>(), vec![(9, 9), (5, 5), (3, 3), (2, 2), (1, 1)]);
|
||||
assert_eq!(print.levels.last().map(|l| l.pixels.clone()), Some(vec![28, 28, 28, 255]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_bounds_take_in_every_folded_panel() {
|
||||
let (b, f) =
|
||||
scene_of(vec![panel(vec![square(0.0, 0.0, 10.0, 10.0)]), panel(vec![square(0.0, 0.0, 10.0, 10.0)])], vec![Pose::IDENTITY, moved(-7.0)]);
|
||||
let (lo, hi) = bounds(&b, &f).expect("bounds");
|
||||
assert_eq!((lo, hi), ([0.0, -10.0, -7.0], [10.0, 0.0, 0.0]));
|
||||
}
|
||||
@@ -913,4 +913,323 @@ proptest! {
|
||||
sorted.sort_by_key(|i| i.code);
|
||||
prop_assert_eq!(sorted, issues);
|
||||
}
|
||||
|
||||
/// Random fold lines fold at any amount without a panic, every pose finite and every panel
|
||||
/// keeping its shape.
|
||||
#[test]
|
||||
fn random_blanks_fold_to_finite_poses(
|
||||
segs in proptest::collection::vec((1u8..4, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0, -50.0f64..50.0), 1..8),
|
||||
amount in 0.0f64..=1.0,
|
||||
) {
|
||||
let kinds = [LineKind::Cut, LineKind::Crease, LineKind::PartialCut, LineKind::Perforation];
|
||||
let mut lines: Vec<FoldLine> = segs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &(k, a, b, c, d))| line(kinds[usize::from(k)], &[(a, b), (c, d)], false, i as u64))
|
||||
.collect();
|
||||
lines.push(cut(&[(-40.0, -40.0), (40.0, -40.0), (40.0, 40.0), (-40.0, 40.0)], 99));
|
||||
let (blanks, _) = blanks(&lines, TOL);
|
||||
for b in &blanks {
|
||||
let Some(f) = fold(b, None, amount, TOL) else { continue };
|
||||
prop_assert_eq!(f.panels.len(), b.panels.len());
|
||||
prop_assert_eq!(f.order.len(), b.panels.len());
|
||||
for p in &f.panels {
|
||||
prop_assert!(p.pose.m.iter().flatten().chain(&p.pose.t).all(|v| v.is_finite()));
|
||||
let n = p.pose.normal();
|
||||
prop_assert!((n[0] * n[0] + n[1] * n[1] + n[2] * n[2] - 1.0).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The 3D corners of panel `i` of `b` folded as `f` places them.
|
||||
fn corners(b: &Blank, f: &Folded, i: usize) -> Vec<[f64; 3]> {
|
||||
let rings = polygon(&b.panels[i].outline, 0.01).expect("a polygon");
|
||||
rings.into_iter().flatten().map(|p| f.panels[i].pose.place(p)).collect()
|
||||
}
|
||||
|
||||
fn flat_center(b: &Blank, i: usize) -> [f64; 3] {
|
||||
let c = point_in(&b.panels[i].outline).expect("a point inside");
|
||||
[c.x, -c.y, 0.0]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slotted_box_folds_every_panel_onto_a_face_of_the_box_with_the_print_outside() {
|
||||
let (b, issues) = check(¬ched_box());
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
let b = &b[0];
|
||||
let f = fold(b, None, 1.0, TOL).expect("folds");
|
||||
// The base panel is the leftmost of the two largest body panels: x 20 to 120, y 30 to 110.
|
||||
let base = &b.panels[f.base];
|
||||
assert_eq!(base.outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((20.0, 30.0)));
|
||||
// The box: the base panel's face (z = 0), 60 deep (the narrow body panels' width).
|
||||
let (lo, hi) = ([20.0, -110.0, -60.0], [120.0, -30.0, 0.0]);
|
||||
let middle = [70.0, -70.0, -30.0];
|
||||
for i in 0..b.panels.len() {
|
||||
let points = corners(b, &f, i);
|
||||
let face = (0..3).find_map(|k| [lo[k], hi[k]].into_iter().find(|&at| points.iter().all(|p| (p[k] - at).abs() < 1e-6)).map(|at| (k, at)));
|
||||
let (k, at) = face.unwrap_or_else(|| panic!("panel {i} lies on no face of the box: {points:?}"));
|
||||
for p in &points {
|
||||
for j in 0..3 {
|
||||
assert!(p[j] > lo[j] - 1e-6 && p[j] < hi[j] + 1e-6, "panel {i} reaches out of the box: {p:?}");
|
||||
}
|
||||
}
|
||||
// The printed side faces out of the box.
|
||||
let n = f.panels[i].pose.normal();
|
||||
assert!((n[k].abs() - 1.0).abs() < 1e-9, "panel {i} is square to its face: {n:?}");
|
||||
assert!(n[k] * (at - middle[k]) > 0.0, "panel {i}'s print faces out: {n:?}");
|
||||
}
|
||||
assert!(f.hinges.iter().all(|h| h.tree && h.closes && (h.angle - 90.0).abs() < 1e-12), "{:?}", f.hinges);
|
||||
assert!(f.collisions.is_empty(), "the stacked flaps and the glue flap do not cross: {:?}", f.collisions);
|
||||
assert_eq!(f.order.first(), Some(&f.base));
|
||||
assert_eq!(f.order.len(), 13);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn at_amount_0_the_blank_is_flat() {
|
||||
let (b, _) = check(¬ched_box());
|
||||
let f = fold(&b[0], None, 0.0, TOL).expect("folds");
|
||||
for p in &f.panels {
|
||||
for (row, want) in p.pose.m.iter().zip(Pose::IDENTITY.m) {
|
||||
assert!(row.iter().zip(want).all(|(a, b)| (a - b).abs() < 1e-12), "{:?}", p.pose);
|
||||
}
|
||||
assert!(p.pose.t.iter().all(|v| v.abs() < 1e-9), "{:?}", p.pose);
|
||||
}
|
||||
}
|
||||
|
||||
/// A 100 × 60 rectangle split by a line of `kind` at x = 60 (drawn upward when `up`), turned by
|
||||
/// `quarter` quarter turns about the origin and mirrored in x when `mirror`.
|
||||
fn two_panels(kind: LineKind, quarter: u8, mirror: bool, up: bool) -> Vec<FoldLine> {
|
||||
let at = |(x, y): (f64, f64)| {
|
||||
let x = if mirror { -x } else { x };
|
||||
(0..quarter).fold((x, y), |(x, y), _| (-y, x))
|
||||
};
|
||||
let outline: Vec<(f64, f64)> = [(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)].into_iter().map(at).collect();
|
||||
let (a, b) = if up { ((60.0, 60.0), (60.0, 0.0)) } else { ((60.0, 0.0), (60.0, 60.0)) };
|
||||
vec![cut(&outline, 1), line(kind, &[at(a), at(b)], false, 2)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_crease_folds_away_from_the_print_and_a_partial_cut_toward_it_however_it_is_drawn() {
|
||||
for quarter in 0..4 {
|
||||
for mirror in [false, true] {
|
||||
for up in [false, true] {
|
||||
for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::Perforation, -1.0), (LineKind::PartialCut, 1.0)] {
|
||||
let case = format!("{kind:?}, {quarter} quarter turns, mirrored {mirror}, drawn up {up}");
|
||||
let (b, issues) = check(&two_panels(kind, quarter, mirror, up));
|
||||
assert!(issues.is_empty(), "{case}: {issues:?}");
|
||||
let b = &b[0];
|
||||
let f = fold(b, None, 1.0, TOL).expect("folds");
|
||||
let child = 1 - f.base;
|
||||
let h = &b.hinges[0];
|
||||
let hinge = [(h.from.x + h.to.x) / 2.0, -(h.from.y + h.to.y) / 2.0, 0.0];
|
||||
let c = flat_center(b, child);
|
||||
let away = [c[0] - hinge[0], c[1] - hinge[1], 0.0];
|
||||
let along = [h.to.x - h.from.x, h.from.y - h.to.y];
|
||||
let off_line = (along[0] * away[1] - along[1] * away[0]).abs() / along[0].hypot(along[1]);
|
||||
let placed = f.panels[child].pose.apply(c);
|
||||
// The child stands up out of the plane: behind it for a crease, in front of it
|
||||
// for a partial cut, at its distance from the hinge.
|
||||
assert!(placed[2] * sign > 0.0, "{case}: {placed:?}");
|
||||
assert!((placed[2].abs() - off_line).abs() < 1e-6, "{case}: {placed:?} {off_line}");
|
||||
// Its printed side faces away from the base panel after a crease, back toward
|
||||
// it after a partial cut.
|
||||
let n = f.panels[child].pose.normal();
|
||||
assert!((n[0] * away[0] + n[1] * away[1]) * -sign > 0.0, "{case}: {n:?}");
|
||||
// Half way, the child is half way round.
|
||||
let half = fold(b, None, 0.5, TOL).expect("folds");
|
||||
let z = half.panels[child].pose.normal()[2];
|
||||
assert!((z - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{case}: {z}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A 100 × 100 square divided into four panels by a crease across it each way.
|
||||
fn crossed() -> Vec<FoldLine> {
|
||||
vec![
|
||||
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)], 1),
|
||||
crease((50.0, 0.0), (50.0, 100.0), 2),
|
||||
crease((0.0, 50.0), (100.0, 50.0), 3),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_of_hinges_closes_when_flat_and_reports_its_gap_when_folded() {
|
||||
let (b, issues) = check(&crossed());
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
let b = &b[0];
|
||||
assert_eq!((b.panels.len(), b.hinges.len()), (4, 4));
|
||||
let folded = fold(b, None, 1.0, TOL).expect("folds");
|
||||
let closing: Vec<&FoldedHinge> = folded.hinges.iter().filter(|h| !h.tree).collect();
|
||||
assert_eq!(closing.len(), 1, "three hinges make the tree, one closes the loop");
|
||||
assert!(!closing[0].closes && closing[0].gap > 10.0, "{closing:?}");
|
||||
// The gap is measured folded all the way, whatever the amount: flat or half way, the loop is
|
||||
// still reported open by the same gap.
|
||||
for amount in [0.0, 0.5] {
|
||||
let part = fold(b, None, amount, TOL).expect("folds");
|
||||
let h = part.hinges.iter().find(|h| !h.tree).expect("a closing hinge");
|
||||
assert!(!h.closes && (h.gap - closing[0].gap).abs() < 1e-9, "{amount}: {h:?}");
|
||||
}
|
||||
// The base is the top-left panel: four equal panels tie, and the highest, then leftmost, wins.
|
||||
assert_eq!(b.panels[folded.base].outline.bounds().map(|r| (r.x0.round(), r.y0.round())), Some((0.0, 0.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hinges_that_start_at_one_point_fold_the_same_in_any_line_order() {
|
||||
// About the bottom-right panel, its two hinges both start at the middle of the square.
|
||||
let lines = crossed();
|
||||
let orders = [[0, 1, 2], [0, 2, 1], [2, 1, 0], [1, 2, 0], [1, 0, 2], [2, 0, 1]];
|
||||
let mut seen = None;
|
||||
for order in orders {
|
||||
let lines: Vec<FoldLine> = order.iter().map(|&i| lines[i].clone()).collect();
|
||||
let (b, issues) = check(&lines);
|
||||
assert!(issues.is_empty(), "{order:?}: {issues:?}");
|
||||
let b = &b[0];
|
||||
let base = panel_at(b, p(75.0, 75.0)).expect("the bottom-right panel");
|
||||
let f = fold(b, Some(base), 1.0, TOL).expect("folds");
|
||||
let closing = f.hinges.iter().zip(&b.hinges).find(|(h, _)| !h.tree).map(|(_, h)| ((h.from.x + h.to.x) / 2.0, (h.from.y + h.to.y) / 2.0));
|
||||
let top_left = panel_at(b, p(25.0, 25.0)).expect("the top-left panel");
|
||||
let placed = f.panels[top_left].pose.place(p(25.0, 25.0)).map(|v| (v * 1e6).round());
|
||||
let got = (closing, placed);
|
||||
assert_eq!(seen.get_or_insert(got), &got, "{order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A 100 × 60 rectangle: the left 60 pt is one panel, the right is split across at y = 30, and the
|
||||
/// line between them bends by `lean` pt over its lower half.
|
||||
fn leaning(lean: f64) -> Vec<FoldLine> {
|
||||
vec![
|
||||
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1),
|
||||
crease((60.0, 0.0), (60.0, 30.0), 2),
|
||||
crease((60.0, 30.0), (60.0 + lean, 60.0), 3),
|
||||
crease((60.0, 30.0), (100.0, 30.0), 4),
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_loop_closes_within_the_tolerance_or_half_a_percent_of_its_hinge() {
|
||||
// Both right panels turn about one line, so the hinge between them closes exactly.
|
||||
let gap = |lean: f64, amount: f64| {
|
||||
let (b, issues) = check(&leaning(lean));
|
||||
assert!(issues.is_empty(), "{lean}: {issues:?}");
|
||||
let b = &b[0];
|
||||
assert_eq!((b.panels.len(), b.hinges.len()), (3, 3));
|
||||
let base = panel_at(b, p(30.0, 30.0)).expect("the left panel");
|
||||
let f = fold(b, Some(base), amount, TOL).expect("folds");
|
||||
let h = f.hinges.iter().find(|h| !h.tree).expect("a closing hinge").clone();
|
||||
(h.closes, h.gap)
|
||||
};
|
||||
let (closes, at) = gap(0.0, 1.0);
|
||||
assert!(closes && at < 1e-9, "{at}");
|
||||
// A small lean opens it by more than the 0.1 pt tolerance but less than 0.5% of its 40 pt
|
||||
// length (0.2 pt): still closed.
|
||||
let (closes, at) = gap(0.1, 1.0);
|
||||
assert!(closes && at > TOL && at <= 0.2, "{at}");
|
||||
// A larger lean opens it past both, flat or folded.
|
||||
for amount in [0.0, 1.0] {
|
||||
let (closes, at) = gap(1.0, amount);
|
||||
assert!(!closes && at > 0.2, "{amount}: {at}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_panel_no_hinge_joins_stays_flat_where_it_is() {
|
||||
let lines = vec![
|
||||
cut(&[(0.0, 0.0), (50.0, 0.0), (50.0, 49.95), (100.0, 49.95), (100.0, 99.95), (50.0, 99.95), (50.0, 50.0), (0.0, 50.0)], 1),
|
||||
crease((50.0, 49.95), (50.0, 50.0), 2),
|
||||
];
|
||||
let (b, _) = check(&lines);
|
||||
let b = &b[0];
|
||||
assert_eq!((b.panels.len(), b.hinges.len()), (2, 0));
|
||||
let f = fold(b, None, 1.0, TOL).expect("folds");
|
||||
let loose = 1 - f.base;
|
||||
assert_eq!(f.panels[loose].parent, None);
|
||||
assert_eq!(f.panels[loose].pose, Pose::IDENTITY);
|
||||
assert_eq!(f.order, vec![f.base, loose], "the loose panel comes last");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_child_of_a_notched_panel_folds_away_from_the_print() {
|
||||
// The base is an L: a 30 × 140 strip with an 80 pt arm along its top running right to x = 300.
|
||||
// The child, below the arm past a 2 pt slot, is hinged to the strip along x = 30.
|
||||
let lines = vec![
|
||||
cut(&[(0.0, 0.0), (300.0, 0.0), (300.0, 80.0), (30.0, 80.0), (30.0, 82.0), (300.0, 82.0), (300.0, 140.0), (0.0, 140.0)], 1),
|
||||
crease((30.0, 82.0), (30.0, 140.0), 2),
|
||||
];
|
||||
let (b, issues) = check(&lines);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
let b = &b[0];
|
||||
let base = panel_at(b, p(15.0, 110.0)).expect("the L");
|
||||
let child = panel_at(b, p(150.0, 110.0)).expect("the child");
|
||||
// The L's inside point lies in its arm, on the child's side of the hinge's line.
|
||||
let inside = b.panels[base].point_inside().expect("a point inside");
|
||||
assert!(inside.x > 30.0, "{inside:?}");
|
||||
for (kind, sign) in [(LineKind::Crease, -1.0), (LineKind::PartialCut, 1.0)] {
|
||||
let mut lines = lines.clone();
|
||||
lines[1].kind = kind;
|
||||
let (b, _) = check(&lines);
|
||||
let f = fold(&b[0], Some(base), 1.0, TOL).expect("folds");
|
||||
let placed = f.panels[child].pose.place(p(150.0, 110.0));
|
||||
assert!(placed[2] * sign > 99.0, "{kind:?}: {placed:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_lid_folded_over_the_base_crosses_the_taller_wall_opposite() {
|
||||
// A strip: a 120 pt lid, a 30 pt wall, the 100 pt base and a 60 pt wall, all 50 pt deep.
|
||||
let lines = vec![
|
||||
cut(&[(0.0, 0.0), (310.0, 0.0), (310.0, 50.0), (0.0, 50.0)], 1),
|
||||
crease((120.0, 0.0), (120.0, 50.0), 2),
|
||||
crease((150.0, 0.0), (150.0, 50.0), 3),
|
||||
crease((250.0, 0.0), (250.0, 50.0), 4),
|
||||
];
|
||||
let (b, issues) = check(&lines);
|
||||
assert!(issues.is_empty(), "{issues:?}");
|
||||
let b = &b[0];
|
||||
let base = panel_at(b, p(200.0, 25.0)).expect("the base panel");
|
||||
let (lid, wall) = (panel_at(b, p(60.0, 25.0)).unwrap(), panel_at(b, p(280.0, 25.0)).unwrap());
|
||||
let f = fold(b, Some(base), 1.0, TOL).expect("folds");
|
||||
assert_eq!(f.collisions, vec![(lid.min(wall), lid.max(wall))]);
|
||||
// Half folded, nothing crosses yet.
|
||||
assert!(fold(b, Some(base), 0.4, TOL).expect("folds").collisions.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_base_is_the_panel_under_a_point_and_the_same_in_any_input_order() {
|
||||
let lines = vec![cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1), crease((50.0, 0.0), (50.0, 60.0), 2)];
|
||||
let (b, _) = check(&lines);
|
||||
assert_eq!(panel_at(&b[0], p(500.0, 500.0)), None, "a point outside every panel");
|
||||
let right = panel_at(&b[0], p(75.0, 30.0)).expect("the right panel");
|
||||
assert_eq!(fold(&b[0], Some(right), 1.0, TOL).expect("folds").base, right);
|
||||
let mut reversed = lines.clone();
|
||||
reversed.reverse();
|
||||
let (r, _) = check(&reversed);
|
||||
for blank in [&b[0], &r[0]] {
|
||||
let f = fold(blank, None, 1.0, TOL).expect("folds");
|
||||
// Equal panels: the leftmost wins.
|
||||
assert_eq!(blank.panels[f.base].outline.bounds().map(|r| r.x0.round()), Some(0.0));
|
||||
}
|
||||
assert!(fold(&b[0], Some(9), 1.0, TOL).is_none(), "no panel 9");
|
||||
assert!(fold(&b[0], None, 1.5, TOL).is_none(), "past 1");
|
||||
assert!(fold(&b[0], None, f64::NAN, TOL).is_none());
|
||||
assert!(fold(&Blank::default(), None, 1.0, TOL).is_none(), "no panels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() {
|
||||
let (b, _) = check(&two_panels(LineKind::PartialCut, 0, false, false));
|
||||
assert_eq!(b[0].hinges[0].angle, -90.0);
|
||||
let (b, _) = check(&two_panels(LineKind::Perforation, 0, false, false));
|
||||
assert_eq!(b[0].hinges[0].angle, 90.0);
|
||||
// A crease and a short partial cut on one line: the crease is the longer piece.
|
||||
let lines = vec![
|
||||
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 60.0), (0.0, 60.0)], 1),
|
||||
line(LineKind::PartialCut, &[(60.0, 0.0), (60.0, 10.0)], false, 2),
|
||||
crease((60.0, 10.0), (60.0, 60.0), 3),
|
||||
];
|
||||
let (b, _) = check(&lines);
|
||||
assert_eq!(b[0].hinges.len(), 1);
|
||||
assert_eq!(b[0].hinges[0].angle, 90.0);
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ mod solid;
|
||||
mod visibility;
|
||||
pub use solid::{
|
||||
Bevel, BevelShape, DepthPlane, Extrude, FaceMap, Facet, Inflate, MeshFace, PlanarFace, TOO_COMPLEX_SOLID, View, extrude, extrude_face_map,
|
||||
extrude_mesh_face, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face,
|
||||
extrude_mesh_face, extrude_side_size, inflate, inflate_each, inflate_together, plane, plane_face_map, plane_mesh_face,
|
||||
};
|
||||
pub use visibility::{VisibleFace, visible_faces};
|
||||
mod shading;
|
||||
@@ -389,7 +389,9 @@ pub struct Face {
|
||||
pub plane: Option<DepthPlane>,
|
||||
}
|
||||
|
||||
/// Where a face of Revolve's swept side lies on the side surface, unrolled flat: x runs around the
|
||||
/// Where a face of a side surface lies on it unrolled flat, for the graphics mapped onto it. On
|
||||
/// Extrude & Bevel's side ([`Facet::surface`]) x runs along the outline and y from the front toward
|
||||
/// the back. On Revolve's swept side x runs around the
|
||||
/// axis and y along the profile, in points. x is the angle from the middle of the surface times the
|
||||
/// point's own distance from the axis, so a graphic keeps its size at every distance and wraps
|
||||
/// farther around the axis where the profile comes closer to it. y is the length along the profile
|
||||
|
||||
@@ -19,6 +19,7 @@ mod inflate;
|
||||
mod membrane;
|
||||
mod outline;
|
||||
mod rings;
|
||||
mod side;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use build::EXTRUDED;
|
||||
@@ -27,7 +28,7 @@ pub(crate) use build::PLANES;
|
||||
#[cfg(test)]
|
||||
use build::{Camera, cuts, edge_distance, newell, section};
|
||||
pub(crate) use build::{Face3, Keep, extrude_faces, plane_faces};
|
||||
pub use build::{extrude, plane};
|
||||
pub use build::{extrude, extrude_side_size, plane};
|
||||
pub use face_map::{FaceMap, MeshFace, extrude_face_map, extrude_mesh_face, plane_face_map, plane_mesh_face};
|
||||
#[cfg(test)]
|
||||
use inflate::GRID_WORK;
|
||||
@@ -218,11 +219,14 @@ pub struct Extrude {
|
||||
/// Keep the faces of a closed solid that are turned away from the viewer (Draw Hidden Faces,
|
||||
/// and the classic Wireframe surface), drawn behind the faces turned toward it.
|
||||
pub hidden: bool,
|
||||
/// Graphics are mapped onto the side: the pieces of the walls and bevels of the solid's longest
|
||||
/// contour carry a [`Facet::surface`]. Off by default, which leaves the facets without one.
|
||||
pub map_surface: bool,
|
||||
}
|
||||
|
||||
impl Default for Extrude {
|
||||
fn default() -> Self {
|
||||
Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false }
|
||||
Self { depth: 50.0, twist: 0.0, taper: 1.0, cap: true, bevel: None, hidden: false, map_surface: false }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -249,21 +253,24 @@ impl Default for Inflate {
|
||||
}
|
||||
}
|
||||
|
||||
/// A planar face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the
|
||||
/// art itself, or a plane's only face) or its back cap.
|
||||
/// A face of a solid that a graphic can be mapped onto: Extrude & Bevel's front cap (the art itself,
|
||||
/// or a plane's only face), its back cap, or its side (the walls and bevels, unrolled flat:
|
||||
/// [`Facet::surface`]). Only the caps are planar.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum PlanarFace {
|
||||
Front,
|
||||
Back,
|
||||
Side,
|
||||
}
|
||||
|
||||
impl PlanarFace {
|
||||
pub const ALL: [PlanarFace; 2] = [Self::Front, Self::Back];
|
||||
pub const ALL: [PlanarFace; 3] = [Self::Front, Self::Back, Self::Side];
|
||||
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Self::Front => "front",
|
||||
Self::Back => "back",
|
||||
Self::Side => "side",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -296,6 +303,10 @@ pub struct Facet {
|
||||
/// The planar end of the solid the facet is: Extrude & Bevel's front or back cap, or a plane
|
||||
/// (its front). `None` for every other facet.
|
||||
pub end: Option<PlanarFace>,
|
||||
/// For a piece of Extrude & Bevel's side built for graphics ([`Extrude::map_surface`]): where
|
||||
/// its corners lie on the side unrolled flat, for a graphic mapped onto it. x runs along the
|
||||
/// outline and y from the front toward the back ([`crate::SurfaceCell`]).
|
||||
pub surface: Option<crate::SurfaceCell>,
|
||||
/// The face's plane in view space and the projection it was drawn with, for its depth at a
|
||||
/// point of the drawing ([`Facet::depth_at`]). `None` for a face whose corners lie more than
|
||||
/// 0.001 pt off one plane (a piece of a twisted wall) or reach the eye.
|
||||
@@ -384,6 +395,8 @@ impl Facet {
|
||||
// A revolved cap is not one of the planar faces graphics map onto.
|
||||
end: None,
|
||||
away: false,
|
||||
// Revolve's graphics are drawn from its faces, before they become facets.
|
||||
surface: None,
|
||||
plane: face.plane,
|
||||
#[cfg(test)]
|
||||
view: vec![],
|
||||
|
||||
@@ -5,6 +5,7 @@ use super::rings::{
|
||||
CURVE_PIECES, MAX_PIECES, MAX_PLANE_POINTS, MAX_SOLID_POINTS, Ring, Span, TOO_COMPLEX_SURFACE, curve_pieces, inset, left, signed_area,
|
||||
solid_rings_traced, square_corners,
|
||||
};
|
||||
use super::side;
|
||||
use super::{
|
||||
Bevel, DepthPlane, Extrude, Facet, FillRule, MAX_FACES, MAX_SOLID_FACES, ParamCurve, PathData, PlanarFace, Point, Rect, Revolve, V3, View,
|
||||
eye_distance, perspective_scale,
|
||||
@@ -211,6 +212,7 @@ impl<'a> Builder<'a> {
|
||||
side: false,
|
||||
away: behind,
|
||||
end: None,
|
||||
surface: None,
|
||||
plane,
|
||||
#[cfg(test)]
|
||||
view,
|
||||
@@ -249,11 +251,13 @@ impl<'a> Builder<'a> {
|
||||
/// wall with `cuts` (see [`cuts`]) as `cuts[i]` quads along edge `i`. `outward` is the
|
||||
/// direction (before rotation) the band faces away from the solid, for orienting normals.
|
||||
pub(super) fn band(&mut self, a: &[V3], b: &[V3], cuts: &[usize], outward: impl Fn(usize) -> V3) -> Result<(), String> {
|
||||
self.curved_band(a, b, cuts, outward, None)
|
||||
self.curved_band(a, b, cuts, outward, None, None)
|
||||
}
|
||||
|
||||
/// [`Builder::band`], with `curves` the pieces of curve the rings' edges follow and the
|
||||
/// outlines at `a` and `b`: a quad whose edge is not cut keeps its edges along the profile curved.
|
||||
/// With `side`, each quad carries where its corners lie on the side unrolled flat
|
||||
/// ([`Facet::surface`]).
|
||||
pub(super) fn curved_band(
|
||||
&mut self,
|
||||
a: &[V3],
|
||||
@@ -261,6 +265,7 @@ impl<'a> Builder<'a> {
|
||||
cuts: &[usize],
|
||||
outward: impl Fn(usize) -> V3,
|
||||
mut curves: Option<WallCurves>,
|
||||
side: Option<SideBand>,
|
||||
) -> Result<(), String> {
|
||||
let n = a.len().min(b.len());
|
||||
// At 0 and 1, the corners themselves.
|
||||
@@ -295,6 +300,21 @@ impl<'a> Builder<'a> {
|
||||
&& let Some(f) = self.facets.last_mut()
|
||||
{
|
||||
f.side = true;
|
||||
if let Some(s) = side.as_ref()
|
||||
&& let (Some([x0, x1]), Some(page)) = (s.x.get(i).copied(), f.contours.first())
|
||||
{
|
||||
let (u0, u1) = (x0 + (x1 - x0) * s0, x0 + (x1 - x0) * s1);
|
||||
let [y0, y1] = s.y;
|
||||
// The face shows the side's outside when it was neither turned around to
|
||||
// show its inside (on a hollow solid) nor kept turned away.
|
||||
let n = normal.unit();
|
||||
let outward = !f.away && f.normal[0] * n.0 + f.normal[1] * n.1 + f.normal[2] * n.2 > 0.0;
|
||||
f.surface = Some(crate::SurfaceCell {
|
||||
page: page.clone(),
|
||||
uv: vec![Point::new(u0, y0), Point::new(u1, y0), Point::new(u1, y1), Point::new(u0, y1)],
|
||||
outward,
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(w) = curves.as_mut().filter(|_| pieces == 1)
|
||||
&& let Some(span) = w.spans.get(i).copied().flatten()
|
||||
@@ -353,6 +373,13 @@ pub(super) struct WallCurves<'a> {
|
||||
pub(super) budget: &'a mut Budget,
|
||||
}
|
||||
|
||||
/// Where a band of the side lies on the side unrolled flat ([`super::side`]): the x of each end of
|
||||
/// each edge of its rings, and the y of its two rings.
|
||||
pub(super) struct SideBand<'a> {
|
||||
pub(super) x: &'a [[f64; 2]],
|
||||
pub(super) y: [f64; 2],
|
||||
}
|
||||
|
||||
/// Where a point of the art goes in view space at one step: [`Camera::place`] after a [`Turn`],
|
||||
/// at depth `z`, as one affine map worked out once for the step.
|
||||
pub(super) struct Placing {
|
||||
@@ -667,7 +694,17 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio
|
||||
})
|
||||
.collect();
|
||||
let mut budget = Budget::default();
|
||||
for ((ring, traced), pieces) in rings.iter().zip(&traced).zip(&pieces) {
|
||||
// With graphics on the side, the longest contour's pieces carry where they lie on it unrolled.
|
||||
let unrolled = o
|
||||
.map_surface
|
||||
.then(|| {
|
||||
let k = side::longest(&rings)?;
|
||||
let y = side::across_steps(&steps.iter().map(|s| (s.inset, s.t)).collect::<Vec<_>>(), o.depth);
|
||||
Some((k, side::along_ring(rings.get(k)?)?, y))
|
||||
})
|
||||
.flatten();
|
||||
for (r, ((ring, traced), pieces)) in rings.iter().zip(&traced).zip(&pieces).enumerate() {
|
||||
let unrolled = unrolled.as_ref().filter(|(k, ..)| *k == r);
|
||||
let placed: Vec<Vec<V3>> = steps.iter().map(|s| ring_at(ring, s)).collect();
|
||||
for (k, pair) in placed.windows(2).enumerate() {
|
||||
let ([a, c], Some(s0), Some(s1)) = (pair, steps.get(k), steps.get(k + 1)) else { continue };
|
||||
@@ -684,7 +721,8 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio
|
||||
// stay straight, within the sampling tolerance.
|
||||
let (near, far) = (along.get(k).filter(|_| k == 0), along.get(k + 1).filter(|_| k + 2 == steps.len()));
|
||||
let curves = (near.is_some() || far.is_some()).then(|| WallCurves { spans: &traced.spans, near, far, budget: &mut budget });
|
||||
b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves)?;
|
||||
let side = unrolled.and_then(|(_, x, y)| Some(SideBand { x, y: [*y.get(k)?, *y.get(k + 1)?] }));
|
||||
b.curved_band(a, c, pieces, |i| outward(ring, i, face), curves, side)?;
|
||||
}
|
||||
}
|
||||
if o.cap {
|
||||
@@ -705,6 +743,31 @@ pub(crate) fn extrude_faces(path: &PathData, rule: FillRule, bounds: Rect, optio
|
||||
Ok(b.finish())
|
||||
}
|
||||
|
||||
/// The size of Extrude & Bevel's side unrolled flat ([`super::side`]), for a solid of `path` built
|
||||
/// as [`extrude`] builds it: the length of its longest contour's outline, the length across its
|
||||
/// bevels and walls, front to back, and the width about x = 0 that does not reach the side's cut.
|
||||
/// `None` with a depth of 0, for invalid bounds, and for a shape [`extrude`] refuses.
|
||||
pub fn extrude_side_size(path: &PathData, rule: FillRule, bounds: Rect, options: Extrude) -> Option<(f64, f64, f64)> {
|
||||
check_bounds(bounds).ok()?;
|
||||
let o = options.sanitized();
|
||||
if o.depth <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let steps = steps(&o);
|
||||
let (bands, caps) = (steps.len().saturating_sub(1), if o.cap { 2 } else { 0 });
|
||||
let size = bounds.width().max(bounds.height());
|
||||
let most = curve_pieces(path, size, bands, caps).ok()?;
|
||||
let side = steps.iter().map(|s| s.inset).find(|w| *w != 0.0).unwrap_or(0.0);
|
||||
let traced: Vec<Ring> = solid_rings_traced(path, rule, size, MAX_SOLID_POINTS, most).ok()?.iter().map(|r| square_corners(r, side)).collect();
|
||||
let rings: Vec<&[Point]> = traced.iter().map(|r| r.points.as_slice()).collect();
|
||||
// A solid past the face limit is refused, as [`extrude_faces`] refuses it.
|
||||
let edges = rings.iter().map(|r| r.len()).fold(0usize, usize::saturating_add);
|
||||
if edges.saturating_mul(bands).saturating_add(caps) > MAX_SOLID_FACES {
|
||||
return None;
|
||||
}
|
||||
side::size(&rings, &steps.iter().map(|s| (s.inset, s.t)).collect::<Vec<_>>(), o.depth)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// How many Rotate planes (and Extrude & Bevel solids with no depth) this thread has built, for
|
||||
|
||||
@@ -145,7 +145,8 @@ impl FaceMap {
|
||||
|
||||
/// The map of Extrude & Bevel's cap `face` for a solid built with `bounds`, `options` and `view`,
|
||||
/// as [`super::extrude`] builds it. With a depth of 0 the art is a plane, whose only face is the
|
||||
/// front. `None` for a hollow solid (no caps), for the back of a plane, and for invalid bounds.
|
||||
/// front. `None` for a hollow solid (no caps), for the back of a plane, for the side (which is not
|
||||
/// planar), and for invalid bounds.
|
||||
pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<FaceMap> {
|
||||
check_bounds(bounds).ok()?;
|
||||
let o = options.sanitized();
|
||||
@@ -159,6 +160,7 @@ pub fn extrude_face_map(bounds: Rect, options: Extrude, view: View, face: Planar
|
||||
let (t, side) = match face {
|
||||
PlanarFace::Front => (0.0, 1.0),
|
||||
PlanarFace::Back => (1.0, -1.0),
|
||||
PlanarFace::Side => return None,
|
||||
};
|
||||
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t);
|
||||
let at = placing.place(bounds.center());
|
||||
@@ -235,7 +237,7 @@ impl MeshFace {
|
||||
/// Extrude & Bevel's cap `face` in the solid's mesh ([`MeshFace`]), for a solid built with
|
||||
/// `bounds`, `options` and `view`, as [`extrude_face_map`] maps it on the page. With a depth of 0
|
||||
/// the art is a plane ([`plane_mesh_face`]). `None` for a hollow solid, for the back of a plane,
|
||||
/// and for invalid bounds.
|
||||
/// for the side, and for invalid bounds.
|
||||
pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: PlanarFace) -> Option<MeshFace> {
|
||||
check_bounds(bounds).ok()?;
|
||||
let o = options.sanitized();
|
||||
@@ -249,6 +251,7 @@ pub fn extrude_mesh_face(bounds: Rect, options: Extrude, view: View, face: Plana
|
||||
let (t, side) = match face {
|
||||
PlanarFace::Front => (0.0, 1.0),
|
||||
PlanarFace::Back => (1.0, -1.0),
|
||||
PlanarFace::Side => return None,
|
||||
};
|
||||
let placing = Placing::new(&camera, bounds.center(), Turn::new(bounds, o.twist, o.taper, t), o.depth / 2.0 - o.depth * t);
|
||||
Some(MeshFace::new(&camera, &placing, bounds.center(), side, false))
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Extrude & Bevel's side unrolled flat, for the graphics mapped onto it ([`super::Facet::surface`]).
|
||||
//!
|
||||
//! x runs along the outline of the solid's longest contour, through its corners and curves, and y
|
||||
//! runs from the front cap's edge toward the back cap's, across the bevels and the walls. Both are
|
||||
//! lengths in points: x along the art's own outline (the front cap's edge, or with a bevel carved
|
||||
//! into the shape the walls' outline), y along the outline's steps (the slant
|
||||
//! of each bevel step and the depth of the walls), before the twist and the taper, which carry the
|
||||
//! graphic with the side. x is 0 where the contour's top crosses the vertical line through the
|
||||
//! middle of its bounds and grows clockwise around the outline as the front is seen on the page, so
|
||||
//! a graphic reads the right way round from outside the side. y is 0 half way along the steps. The
|
||||
//! side is cut at the anchor of the contour nearest half way around from x = 0.
|
||||
|
||||
use super::rings::signed_area;
|
||||
use super::{Point, Rect};
|
||||
|
||||
/// The length of the outline of `ring`.
|
||||
fn perimeter(ring: &[Point]) -> f64 {
|
||||
ring.iter().zip(ring.iter().cycle().skip(1)).take(ring.len()).map(|(a, b)| a.distance(*b)).sum()
|
||||
}
|
||||
|
||||
/// The ring of `rings` with the longest outline (the first of equal ones), which carries the side's
|
||||
/// graphics. `None` when no ring has a finite length above 0.
|
||||
pub(super) fn longest(rings: &[&[Point]]) -> Option<usize> {
|
||||
rings
|
||||
.iter()
|
||||
.map(|r| perimeter(r))
|
||||
.enumerate()
|
||||
.filter(|(_, l)| l.is_finite() && *l > 0.0)
|
||||
.fold(None, |best: Option<(usize, f64)>, (k, l)| if best.is_some_and(|(_, top)| top >= l) { best } else { Some((k, l)) })
|
||||
.map(|(k, _)| k)
|
||||
}
|
||||
|
||||
/// The x of each end of each edge of `ring` (point `i` to point `i + 1`, the last back to the first),
|
||||
/// as the module describes. `None` for a ring with no length or bounds that are not finite.
|
||||
pub(super) fn along_ring(ring: &[Point]) -> Option<Vec<[f64; 2]>> {
|
||||
let n = ring.len();
|
||||
if n < 2 {
|
||||
return None;
|
||||
}
|
||||
let edges = || ring.iter().zip(ring.iter().cycle().skip(1)).map(|(a, b)| (*a, *b));
|
||||
let lengths: Vec<f64> = edges().map(|(a, b)| a.distance(b)).collect();
|
||||
let total: f64 = lengths.iter().sum();
|
||||
if !total.is_finite() || total <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let mut starts = Vec::with_capacity(n);
|
||||
let mut at = 0.0;
|
||||
for l in &lengths {
|
||||
starts.push(at);
|
||||
at += l;
|
||||
}
|
||||
let bounds = ring.iter().fold(None, |b: Option<Rect>, p| Some(b.map_or(Rect::from_points(*p, *p), |b| b.union_pt(*p))))?;
|
||||
let middle = bounds.center().x;
|
||||
// Where x = 0: the crossing of the middle line nearest the top, as a length along the ring.
|
||||
let mut origin: Option<(f64, f64)> = None;
|
||||
let mut keep = |y: f64, s: f64| {
|
||||
if origin.is_none_or(|(top, _)| y < top) {
|
||||
origin = Some((y, s));
|
||||
}
|
||||
};
|
||||
for ((a, b), (s, l)) in edges().zip(starts.iter().zip(&lengths)) {
|
||||
if (a.x - middle) * (b.x - middle) > 0.0 {
|
||||
continue;
|
||||
}
|
||||
if a.x == b.x {
|
||||
// An edge along the middle line: its upper end.
|
||||
if a.y <= b.y { keep(a.y, *s) } else { keep(b.y, s + l) }
|
||||
} else {
|
||||
let t = (middle - a.x) / (b.x - a.x);
|
||||
keep(a.y + (b.y - a.y) * t, s + l * t);
|
||||
}
|
||||
}
|
||||
let (_, origin) = origin?;
|
||||
// The cut: the anchor nearest half way around from the origin.
|
||||
let opposite = (origin + total / 2.0).rem_euclid(total);
|
||||
let round = |d: f64| {
|
||||
let d = d.rem_euclid(total);
|
||||
d.min(total - d)
|
||||
};
|
||||
let cut = starts
|
||||
.iter()
|
||||
.copied()
|
||||
.fold(None, |best: Option<f64>, s| if best.is_some_and(|b| round(b - opposite) <= round(s - opposite)) { best } else { Some(s) })?;
|
||||
let from_cut = (origin - cut).rem_euclid(total);
|
||||
// The ring runs clockwise on the page (y down) when it encloses positive area: x grows along it.
|
||||
let sign = if signed_area(ring) >= 0.0 { 1.0 } else { -1.0 };
|
||||
Some(
|
||||
starts
|
||||
.iter()
|
||||
.zip(&lengths)
|
||||
.map(|(s, l)| {
|
||||
let a = (s - cut).rem_euclid(total) - from_cut;
|
||||
[a * sign, (a + l) * sign]
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
|
||||
/// The y of each of an extrusion's `steps`, each its inset (points) and its depth fraction (0 front,
|
||||
/// 1 back) of a solid `depth` points deep: the length along the steps from their middle, growing
|
||||
/// toward the back.
|
||||
pub(super) fn across_steps(steps: &[(f64, f64)], depth: f64) -> Vec<f64> {
|
||||
let mut out = Vec::with_capacity(steps.len());
|
||||
let mut at = 0.0;
|
||||
for (k, (inset, t)) in steps.iter().enumerate() {
|
||||
if let Some((i0, t0)) = k.checked_sub(1).and_then(|k| steps.get(k)) {
|
||||
at += (inset - i0).hypot(depth * (t - t0));
|
||||
}
|
||||
out.push(at);
|
||||
}
|
||||
let middle = at / 2.0;
|
||||
out.into_iter().map(|y| y - middle).collect()
|
||||
}
|
||||
|
||||
/// The size of Extrude & Bevel's side unrolled, around the longest of `rings` and across the steps
|
||||
/// `steps` (each inset and depth fraction) of a solid `depth` points deep: the length around it,
|
||||
/// the length across it, and the width about x = 0 that does not reach the side's cut (twice the
|
||||
/// distance from x = 0 to the nearer end of the cut side). `None` when the side has no length
|
||||
/// either way.
|
||||
pub(super) fn size(rings: &[&[Point]], steps: &[(f64, f64)], depth: f64) -> Option<(f64, f64, f64)> {
|
||||
let ring = rings.get(longest(rings)?)?;
|
||||
let across = across_steps(steps, depth);
|
||||
let height = across.last().zip(across.first()).map_or(0.0, |(b, a)| b - a);
|
||||
let width = perimeter(ring);
|
||||
let xs = along_ring(ring)?;
|
||||
let (lo, hi) = xs.iter().flatten().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), x| (lo.min(*x), hi.max(*x)));
|
||||
let span = 2.0 * (-lo).min(hi);
|
||||
(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0).then_some((width, height, span.clamp(0.0, width)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "tests_side.rs"]
|
||||
mod tests;
|
||||
@@ -438,9 +438,11 @@ fn malformed_and_degenerate_input_is_bounded() {
|
||||
cap: true,
|
||||
bevel: Some(Bevel { width: f64::NAN, height: 1e12, repeat: usize::MAX, space: 7.0, ..Bevel::default() }),
|
||||
hidden: false,
|
||||
map_surface: true,
|
||||
};
|
||||
let f = extrude(&p, FillRule::EvenOdd, b, wild, View { rotation_x: f64::NAN, perspective: 900.0, ..front() }).unwrap();
|
||||
assert!(f.iter().flat_map(|f| f.contours.iter().flatten()).all(|q| q.x.is_finite() && q.y.is_finite()));
|
||||
assert!(f.iter().filter_map(|f| f.surface.as_ref()).flat_map(|c| c.uv.iter()).all(|q| q.x.is_finite() && q.y.is_finite()));
|
||||
assert!(
|
||||
inflate(
|
||||
&p,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
use vectorcraft_geom::{BezPath, FillRule, PathData, Point, Rect};
|
||||
|
||||
use super::super::{Bevel, Extrude, View, extrude, extrude_side_size};
|
||||
use super::{across_steps, along_ring, longest};
|
||||
|
||||
fn square(r: Rect, hole: Option<Rect>) -> PathData {
|
||||
let mut b = BezPath::new();
|
||||
b.move_to((r.x0, r.y0));
|
||||
b.line_to((r.x1, r.y0));
|
||||
b.line_to((r.x1, r.y1));
|
||||
b.line_to((r.x0, r.y1));
|
||||
b.close_path();
|
||||
if let Some(h) = hole {
|
||||
b.move_to((h.x0, h.y0));
|
||||
b.line_to((h.x0, h.y1));
|
||||
b.line_to((h.x1, h.y1));
|
||||
b.line_to((h.x1, h.y0));
|
||||
b.close_path();
|
||||
}
|
||||
PathData::from_bezpath(&b)
|
||||
}
|
||||
|
||||
/// x is 0 at the top of the middle line and grows clockwise on the page; the side is cut at the
|
||||
/// anchor nearest half way around (the first of two equally near).
|
||||
#[test]
|
||||
fn x_runs_clockwise_from_the_top_middle() {
|
||||
let ring = [Point::new(0.0, 0.0), Point::new(10.0, 0.0), Point::new(10.0, 10.0), Point::new(0.0, 10.0)];
|
||||
assert_eq!(along_ring(&ring).unwrap(), vec![[-5.0, 5.0], [5.0, 15.0], [-25.0, -15.0], [-15.0, -5.0]]);
|
||||
// The same outline run the other way gives each point the same x, apart from the seam, which
|
||||
// is now at (0, 10), its first anchor of the two equally near.
|
||||
let back: Vec<Point> = ring.iter().rev().copied().collect();
|
||||
let x = along_ring(&back).unwrap();
|
||||
assert_eq!(x, vec![[25.0, 15.0], [15.0, 5.0], [5.0, -5.0], [-5.0, -15.0]]);
|
||||
assert_eq!(along_ring(&[Point::ZERO, Point::ZERO]), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn y_runs_across_the_steps_from_their_middle() {
|
||||
// A 4 × 3 pt bevel step, then 20 pt of wall, on a solid 30 pt deep.
|
||||
let y = across_steps(&[(0.0, 0.0), (-4.0, 0.1), (-4.0, 0.1 + 20.0 / 30.0)], 30.0);
|
||||
let expected = [-12.5, -7.5, 12.5];
|
||||
for (a, b) in y.iter().zip(expected) {
|
||||
assert!((a - b).abs() < 1e-9, "{y:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// With graphics on the side, every piece of the walls of the longest contour carries its place on
|
||||
/// the side unrolled, and no other facet does: x along the outline and y from the front to the back.
|
||||
#[test]
|
||||
fn the_longest_contours_walls_carry_their_place_on_the_side() {
|
||||
let (outer, inner) = (Rect::new(0.0, 0.0, 100.0, 60.0), Rect::new(30.0, 20.0, 70.0, 40.0));
|
||||
let path = square(outer, Some(inner));
|
||||
let o = Extrude { depth: 40.0, map_surface: true, ..Extrude::default() };
|
||||
// Seen from above: the top wall faces the viewer and keeps its x on the page.
|
||||
let top = View { rotation_x: -90.0, ..View::default() };
|
||||
let facets = extrude(&path, FillRule::NonZero, outer, o, top).unwrap();
|
||||
let cells: Vec<_> = facets.iter().filter_map(|f| f.surface.as_ref().map(|c| (f, c))).collect();
|
||||
assert!(!cells.is_empty());
|
||||
assert!(cells.iter().all(|(f, c)| f.side && f.end.is_none() && c.uv.len() == 4 && c.page.len() == 4));
|
||||
let seen: Vec<_> = cells.iter().filter(|(_, c)| c.outward).collect();
|
||||
assert_eq!(seen.len(), 1, "only the top wall of the outline faces the viewer");
|
||||
for (_, c) in seen {
|
||||
for (uv, page) in c.uv.iter().zip(&c.page) {
|
||||
assert!((page.x - (50.0 + uv.x)).abs() < 1e-6, "{uv:?} {page:?}");
|
||||
assert!(uv.y.abs() <= 20.0 + 1e-9);
|
||||
}
|
||||
}
|
||||
// Only the outline's top wall is drawn (the walls seen edge-on have no area on the page, and the
|
||||
// bottom wall faces away); the hole's walls carry none. Without graphics no facet carries one.
|
||||
assert_eq!(cells.len(), 1);
|
||||
let turned = View { rotation_x: -60.0, rotation_y: 30.0, ..View::default() };
|
||||
let hollow = extrude(&path, FillRule::NonZero, outer, Extrude { cap: false, ..o }, turned).unwrap();
|
||||
let hollow: Vec<_> = hollow.iter().filter_map(|f| f.surface.as_ref()).collect();
|
||||
// A hollow solid shows the insides of its far walls: they carry a cell that is not outward.
|
||||
assert!(hollow.iter().any(|c| c.outward) && hollow.iter().any(|c| !c.outward), "{}", hollow.len());
|
||||
let plain = extrude(&path, FillRule::NonZero, outer, Extrude { map_surface: false, ..o }, top).unwrap();
|
||||
assert!(plain.iter().all(|f| f.surface.is_none()));
|
||||
assert_eq!(plain.len(), facets.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_side_measures_around_the_outline_and_across_the_bevels() {
|
||||
let outer = Rect::new(0.0, 0.0, 100.0, 60.0);
|
||||
let path = square(outer, None);
|
||||
let plain = Extrude { depth: 40.0, ..Extrude::default() };
|
||||
// The cut is at a bottom corner, 110 pt each way from the top's middle: 220 pt about x = 0
|
||||
// stay clear of it.
|
||||
assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, plain), Some((320.0, 40.0, 220.0)));
|
||||
// A 3 × 4 pt classic bevel outside adds its 5 pt slant and takes 4 pt of the wall.
|
||||
let bevel = Extrude { bevel: Some(Bevel { width: 3.0, height: 4.0, ..Bevel::default() }), ..plain };
|
||||
let (w, h, span) = extrude_side_size(&path, FillRule::NonZero, outer, bevel).unwrap();
|
||||
assert!((w - 320.0).abs() < 1e-9 && (h - 41.0).abs() < 1e-9 && (span - 220.0).abs() < 1e-9, "{w} {h} {span}");
|
||||
assert_eq!(extrude_side_size(&path, FillRule::NonZero, outer, Extrude { depth: 0.0, ..plain }), None);
|
||||
let rings = [&[Point::ZERO, Point::new(1.0, 0.0), Point::new(0.0, 1.0)][..], &[Point::ZERO, Point::new(5.0, 0.0), Point::new(0.0, 5.0)][..]];
|
||||
assert_eq!(longest(&rings), Some(1));
|
||||
}
|
||||
Reference in New Issue
Block a user