Packaging Tools: a crease, partial cut or perforation can fold at its own angle

Set Fold Angle… (Object › Plug-ins › Packaging Tools) gives the selected
fold lines their own fold angle, from -180° to 180°, in place of their
role's 90° away from or toward the print, to the millionth of a degree;
reset: true takes it away. The angle is kept in the line's data under
vc-fold-angle, which native files and SVG with Preserve Editing keep and
plain SVG export leaves out of the path's attributes. A line keeps its
angle when it is given another role. The Fold Lines panel shows a Fold
Angle field for the selected lines it can change, empty when they
differ, and a Reset button.

- addon.packaging.setFoldAngle is one undo step, none when nothing
  changes, and is dimmed while the selection holds no Crease, Partial Cut
  or Perforation line that is neither locked nor hidden. An angle stored
  as other text for the same number counts as unchanged.
- addon.packaging.roles also returns foldLines, foldAngle, ownAngles and
  storedAngles for the lines Set Fold Angle can change, which are none
  while nothing is selected.
- A hinge folds at the angle of the line with the most length in it,
  counting a line the planar map splits into pieces whole and a line's
  subpaths on top of each other once; among lines of equal length the
  lowest id wins, in any line order. Before, it took the role of its
  longest piece, so a hinge whose lines have different roles can now
  fold the other way when a split line is the longer one.
- Fold Preview: a panel folded flat onto another (180°) is drawn behind
  that panel's printed side, and at -180° in front of it; a flap folded
  back over a folded panel lies between it and the panel before; a 0°
  hinge keeps its panel level with its parent. Panels in one plane keep
  their order when the panels they fold from are seen edge on, and a
  panel that comes round onto another's plane lies on the side it came
  from. Only panels in one plane stack by these rules; panels in
  different planes go by depth, so folds a hair short of flat stay in
  order wherever the blank lies in the document. The stack is worked out
  from the blank's largest panel whichever panel the window folds about,
  so a double-click on another panel moves the blank without changing
  which panel shows. Panels that 90° folds bring into one plane, such as
  a carton's closing flaps, now stack by these rules too.
- Set Fold Angle…'s dialog keeps the angle within -180° to 180° as it is
  typed, as the panel's field does. Both show every decimal place the
  angle has. ui.menuDialog opens the dialog for
  addon.packaging.setFoldAngle, and gives the command's reason while
  the selection holds no line it can change.
- Set Fold Angle skips a locked or hidden path of a compound path that is
  named by id or selected without its compound. addon.packaging.setRole
  (Make Cut Line and the other Make ... Line items) now skips it too;
  before, it changed the whole compound.
- Folding: a hinge whose middle falls in a cutout turns its panel by the
  side its parent lies on next to the hinge's own pieces, not by a point
  anywhere inside the parent, which folded a panel the wrong way when
  the parent also ran on past the hinge.

Docs: docs/mcp.md (Fold angles), ROADMAP.
This commit is contained in:
dotCooCoo committed 2026-11-19 15:33:43 -08:00
1 parent 1233b23b19
commit 2ab519a630
56 files changed
+2882 -90

No files matched your search

+1
View File
@@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-14: Packaging Tools add-on (Object › Plug-ins › Packaging Tools): fold line roles for dielines (Cut, Crease, Partial Cut, Perforation), each carried by the swatch on a path's top stroke through a per-document role table that native files keep; PDF prints a role line on its swatch's separation when that swatch is a spot color, as the default role swatches are, and SVG, DXF and HP-GL keep the stroke's color. Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line give the selected paths a role, overprinting by default, and make a missing role swatch; the Fold Lines panel counts each role in the selection or the document, and its Role Swatches… picks another swatch for a role (`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Check Fold Lines in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Check button): the fold lines of the selection or the document are split into blanks, panels and hinges (cut lines bound the material, and creases, partial cuts and perforations divide it into panels), and 15 kinds of issue are listed, errors and warnings, each naming its lines: cut lines that enclose nothing or end loose, gaps closed within a tolerance, a cut on top of a crease, duplicate lines, creases that end inside a panel, divide nothing, lie outside the blank or are not straight, gaps too narrow to map, fold lines in a hole, panels joined by no crease, and fold lines on a non-printing layer. The panel lists the issues in the interface language; clicking one selects its lines (`addon.packaging.check`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-16: Fold Preview in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and the Fold Lines panel's Fold Preview button): a window that folds the document's blank into its 3D shape about its largest panel, or the panel double-clicked, with the printed art on the outside of each panel (fold lines and non-printing layers left out, unless Show Fold Lines is on) and the board's inside color on the back. Creases and perforations fold 90° away from the print and partial cuts 90° toward it; a Fold slider goes from flat to folded, and the view turns by dragging and the arrow keys, zooms, moves and takes a perspective and seven view presets. The status line says when a joint does not close or two panels pass through each other (`addon.packaging.fold`, `ui.foldPreview`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Set Fold Angle in the Packaging Tools add-on (Object › Plug-ins › Packaging Tools, and a Fold Angle field with Reset in the Fold Lines panel): a crease, partial cut or perforation line can fold at its own angle, from -180° to 180°, instead of its role's 90° away from or toward the print; native files keep the angle, and the Fold Preview folds each hinge at the angle of the line with the most length in it (`addon.packaging.setFoldAngle`). A VectorCraft addition: headline numbers unchanged.
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
+1 -1
View File
@@ -839,7 +839,7 @@ pub(crate) const MAX_IMPORTED_PRESETS: usize = 1000;
pub(crate) use addons::{DecodedImages, refresh_color_masks};
/// Packaging Tools' blanks and the objects their print leaves out, for the Fold Preview window.
pub use addons::{fold_source, print_hidden};
pub use addons::{FoldAngles, fold_source, print_hidden, selection_fold_angles};
/// Document Info's category titles and the Objects category's count labels.
pub use docinfo::{CATEGORIES, OBJECT_LABELS};
pub use docmenu::guide_indexes;
+1 -1
View File
@@ -17,7 +17,7 @@ mod typetools;
mod units;
pub(crate) use image::{DecodedImages, refresh_color_masks};
pub use packaging::{fold_source, print_hidden};
pub use packaging::{FoldAngles, fold_source, print_hidden, selection_fold_angles};
pub(crate) use packaging::{role_swatch_edited, role_swatches_merged};
use super::CommandSpec;
+6 -2
View File
@@ -2,13 +2,16 @@
//! folded packaging. A path is a fold line when its top stroke is painted with the swatch of a line
//! role: Cut, Crease, Partial Cut or Perforation ([`roles`]). The document's role table maps each
//! role to its swatch, so every format that keeps the stroke's swatch keeps the role. Check Fold
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Its submenu
//! (Object › Plug-ins › Packaging Tools) and its Fold Lines panel are the UI's.
//! Lines ([`check`]) finds the panels and hinges the lines make and what is wrong with them. Set
//! Fold Angle ([`angle`]) gives a fold line its own angle. Its submenu (Object › Plug-ins ›
//! Packaging Tools) and its Fold Lines panel are the UI's.
mod angle;
mod check;
mod fold;
mod roles;
pub use angle::{FoldAngles, selection_fold_angles};
pub use fold::{fold_source, print_hidden};
pub(crate) use roles::{role_swatch_edited, role_swatches_merged};
@@ -17,6 +20,7 @@ use super::super::CommandSpec;
pub fn specs() -> Vec<CommandSpec> {
let mut v = roles::specs();
v.extend(check::specs());
v.extend(angle::specs());
v.extend(fold::specs());
v
}
@@ -0,0 +1,250 @@
//! Set Fold Angle (`addon.packaging.setFoldAngle`): the angle each fold line folds at. A Crease,
//! Partial Cut or Perforation line keeps its own angle in its data under [`KEY`], as a number of
//! degrees from -180 to 180; without one it folds at its role's angle (90° for a Crease or a
//! Perforation, -90° for a Partial Cut). A positive angle folds away from the printed side.
use std::collections::HashSet;
use std::sync::{Arc, Weak};
use serde_json::{Value, json};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use vectorcraft_three_d::fold::kept_angle;
use super::super::super::edit::refuse_symbol_part;
use super::super::super::overprint::edit_counted;
use super::super::super::pathops::number_given;
use super::super::super::{CommandSpec, bad, cmd, switch_or};
use super::check::kind;
use super::roles::{Role, RoleTable, editable_members, role_targets, taken_roots};
use crate::{Result, Session};
/// Object data key: a fold line's own fold angle, in degrees. Native save keeps it; SVG export
/// leaves `vc-` keys out.
pub(crate) const KEY: &str = "vc-fold-angle";
const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
/// The range a fold angle may take, in degrees.
const RANGE: std::ops::RangeInclusive<f64> = -180.0..=180.0;
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"addon.packaging.setFoldAngle",
"Set Fold Angle…",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{angle?: degrees -180..180, reset?: bool (false), ids?: [id…] (default: the selection)} give each Crease, Partial Cut and Perforation line among the objects (addon.packaging.roles; through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) its own fold angle, rounded to the millionth of a degree, or with reset: true take it away, so the line folds at its role's angle again: 90° for a Crease or a Perforation, -90° for a Partial Cut. A positive angle folds the panel away from the printed side, a negative one toward it; addon.packaging.fold and the Fold Preview window fold each hinge at the angle of the line with the most length in it. Cut lines and objects without a role are skipped and counted. Give exactly one of angle and reset: true. One undo step, none when nothing changes → {ids (the fold lines changed or kept), changed, skipped}",
has_fold_line,
set_fold_angle
)]
}
/// Why Set Fold Angle has nothing to change.
const NO_FOLD_LINE: &str = "select a crease, partial cut or perforation line that is neither locked nor hidden";
/// The last answer of [`has_fold_line`], with what it was for.
struct Answer {
/// The document (a weak reference keeps another document from taking the same address).
doc: Weak<Document>,
revision: u64,
/// The objects looked at: the selection, or the `ids` a command was given in its place.
objects: Vec<NodeId>,
found: bool,
}
thread_local! {
/// Menus ask [`has_fold_line`] on every refresh, and its answer changes only with the
/// document, its revision and the objects looked at.
static LAST_ANSWER: std::cell::RefCell<Option<Answer>> = const { std::cell::RefCell::new(None) };
}
/// The selection holds a line that folds and that Set Fold Angle can change, or an id of no object.
fn has_fold_line(s: &Session) -> std::result::Result<(), String> {
refuse_symbol_part(s).map_err(|e| e.to_string())?;
let st = s.doc().map_err(|e| e.to_string())?;
let objects = &st.selection.objects;
let kept = LAST_ANSWER.with_borrow(|last| match last {
Some(a) if a.revision == st.revision && a.objects == *objects && Weak::ptr_eq(&a.doc, &Arc::downgrade(&st.doc)) => Some(a.found),
_ => None,
});
let found = kept.unwrap_or_else(|| {
// An id of no object (given as `ids`) is left to the command, which names it.
let found = objects.iter().any(|id| st.doc.node(*id).is_none()) || any_fold_line(&st.doc, objects);
LAST_ANSWER.set(Some(Answer { doc: Arc::downgrade(&st.doc), revision: st.revision, objects: objects.clone(), found }));
found
});
if found { Ok(()) } else { Err(NO_FOLD_LINE.into()) }
}
/// Whether the objects `roots` of `d` hold a line that folds and can be changed, looking through
/// groups and clip groups as [`role_targets`] does and stopping at the first. As [`taken_roots`]
/// takes them, an object inside another one given is left out (a crease in a selected layer counts
/// no more than the layer does), a layer is left out, and a path of a compound path stands for the
/// compound path, which holds its role, unless it is locked or hidden.
fn any_fold_line(d: &Document, roots: &[NodeId]) -> bool {
fn find(n: &Node, hit: &dyn Fn(&Node) -> bool) -> bool {
match &n.kind {
// A group's clipping path draws no stroke.
NodeKind::Group { children, .. } => children.iter().any(|c| !matches!(c.kind, NodeKind::Path { clipping: true, .. }) && find(c, hit)),
_ => hit(n),
}
}
let table = RoleTable::of(d);
let editable = d.editable();
let hit = |n: &Node| table.role_of(n).is_some_and(folds) && editable(n.id);
let given: HashSet<NodeId> = roots.iter().copied().collect();
// Each object's place, from the document's lookup of ids.
let outer = |id: NodeId| -> Option<NodeId> {
let a = d.ancestry(id)?;
let (_, up) = a.split_last()?;
if up.iter().any(|p| given.contains(p)) {
return None;
}
match up.last().copied().filter(|p| matches!(d.node(*p).map(|n| &n.kind), Some(NodeKind::Compound { .. }))) {
// A locked or hidden path of a compound path is left out, as `editable_members` leaves it.
Some(_) if !editable(id) => None,
Some(compound) => Some(compound),
None => Some(id),
}
};
// An object given twice is looked through once.
let mut seen = HashSet::new();
roots
.iter()
.filter_map(|id| outer(*id))
.filter(|id| seen.insert(*id))
.filter_map(|id| d.node(id))
.filter(|n| !n.is_layer())
.any(|n| find(n, &hit))
}
/// The text `n`'s data holds under [`KEY`], if any.
fn stored(n: &Node) -> Option<&str> {
n.extras().attrs.as_deref()?.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.as_str())
}
/// `n`'s own fold angle: the number its data holds under [`KEY`], when it is a finite number from
/// -180 to 180, to the millionth of a degree it folds at ([`kept_angle`]). Anything else reads as
/// no angle of its own.
pub(super) fn own_angle(n: &Node) -> Option<f64> {
stored(n)?.trim().parse::<f64>().ok().filter(|a| a.is_finite() && RANGE.contains(a)).map(kept_angle)
}
/// Whether a line with `role` folds: every role but Cut.
pub(super) fn folds(role: Role) -> bool {
kind(role).fold_angle().is_some()
}
/// Writes `angle` (`None`: takes it away) into object `id`'s data → whether its data changed.
fn store(d: &mut Document, id: NodeId, angle: Option<f64>) -> bool {
// `+ 0.0` turns -0 into 0, so a line set to 0° reads "0".
let text = angle.map(|a| format!("{}", a + 0.0));
// Read first: taking the node to change it copies it, its geometry included. An angle stored
// as other text for the same number ("45.0") is kept; a reset removes any stored text.
let same = |n: &Node| match angle {
Some(a) => own_angle(n) == Some(a),
None => stored(n).is_none(),
};
if d.node(id).is_none_or(same) {
return false;
}
let Some(n) = d.node_mut(id) else { return false };
n.edit_attrs(|a| match text {
Some(text) => match a.data.iter_mut().find(|(k, _)| k == KEY) {
Some(e) => e.1 = text,
None => a.data.push((KEY.into(), text)),
},
None => a.data.retain(|(k, _)| k != KEY),
});
true
}
fn set_fold_angle(s: &mut Session, p: &Value) -> Result<Value> {
let angle = number_given(p, "angle", SET_FOLD_ANGLE)?;
let reset = switch_or(p, "reset", false, SET_FOLD_ANGLE)?;
let angle = match (angle, reset) {
(Some(_), true) => return Err(bad(SET_FOLD_ANGLE, "give `angle` or `reset: true`, not both")),
(None, false) => return Err(bad(SET_FOLD_ANGLE, "missing `angle`")),
(Some(a), false) if !RANGE.contains(&a) => return Err(bad(SET_FOLD_ANGLE, "`angle` must be from -180 to 180 degrees")),
// Kept to the millionth of a degree, the angle the line folds at.
(a, _) => a.map(kept_angle),
};
let (roots, named) = taken_roots(s, p, SET_FOLD_ANGLE)?;
let d = &s.doc()?.doc;
let (targets, skipped) = role_targets(d, &roots, false);
let mut skipped = skipped + named;
let mut ids = folding(d, &RoleTable::of(d), &targets);
{
let editable = d.editable();
ids.retain(|id| editable(*id));
}
skipped += targets.len() - ids.len();
if ids.is_empty() {
return Err(bad(SET_FOLD_ANGLE, NO_FOLD_LINE));
}
let label = if angle.is_some() { "Set Fold Angle" } else { "Reset Fold Angle" };
let changed = edit_counted(s, label, |d| Ok(ids.iter().filter(|id| store(d, **id, angle)).count()))?;
Ok(json!({ "ids": ids.iter().map(|i| i.0).collect::<Vec<_>>(), "changed": changed, "skipped": skipped }))
}
/// The lines among `ids` of `d` that fold (Crease, Partial Cut, Perforation), in order.
fn folding(d: &Document, table: &RoleTable, ids: &[NodeId]) -> Vec<NodeId> {
ids.iter().copied().filter(|id| d.node(*id).and_then(|n| table.role_of(n)).is_some_and(folds)).collect()
}
/// What Set Fold Angle can change among the objects `roots` of `d` (through groups and clip
/// groups, leaving out what is locked or hidden, as `addon.packaging.setFoldAngle` does).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct FoldAngles {
/// How many lines that fold it can change.
pub lines: usize,
/// The angle they all fold at (their own or their role's); `None` when they differ or there
/// are none.
pub angle: Option<f64>,
/// How many of them have an angle of their own.
pub own: usize,
/// How many of them hold text under [`KEY`], an angle or not: what `reset: true` takes away.
pub stored: usize,
}
/// The [`FoldAngles`] of the selected objects of the active document, as Set Fold Angle reads them
/// with no `ids` (nothing, while it would refuse the selection).
pub fn selection_fold_angles(s: &Session) -> FoldAngles {
match (taken_roots(s, &Value::Null, SET_FOLD_ANGLE), s.doc()) {
(Ok((roots, _)), Ok(st)) => fold_angles(&st.doc, &roots),
_ => FoldAngles::default(),
}
}
/// The [`FoldAngles`] of the outermost objects `roots` of `d`.
pub(super) fn fold_angles(d: &Document, roots: &[NodeId]) -> FoldAngles {
let table = RoleTable::of(d);
let editable = d.editable();
let mut f = FoldAngles::default();
for n in role_targets(d, &editable_members(d, roots.to_vec()).0, false).0.iter().filter_map(|id| d.node(*id)) {
// The role first: whether an object can be edited can take its bounds to find out.
if let Some(role) = table.role_of(n)
&& folds(role)
&& editable(n.id)
{
f.add(n, role);
}
}
f
}
impl FoldAngles {
/// Counts line `n`, which has `role` and can be changed; a line that does not fold is left out.
pub(super) fn add(&mut self, n: &Node, role: Role) {
let Some(default) = kind(role).fold_angle() else { return };
let own = own_angle(n);
let a = own.unwrap_or(default);
self.angle = if self.lines == 0 { Some(a) } else { self.angle.filter(|b| *b == a) };
self.lines += 1;
self.own += usize::from(own.is_some());
self.stored += usize::from(stored(n).is_some());
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,409 @@
//! Tests for Set Fold Angle: a fold line's own angle, where it is kept, and how the fold uses it.
use serde_json::{Value, json};
use super::{KEY, fold_angles, own_angle};
use crate::*;
const SET: &str = "addon.packaging.setFoldAngle";
fn session() -> Session {
let mut s = Session::new();
s.execute("file.new", &json!({"width": 600, "height": 600})).unwrap();
s
}
fn path(s: &mut Session, d: &str) -> u64 {
s.execute("path.create", &json!({ "d": d })).unwrap()["id"].as_u64().unwrap()
}
fn role(s: &mut Session, role: &str, ids: &[u64]) {
s.execute("addon.packaging.setRole", &json!({ "role": role, "ids": ids })).unwrap();
}
fn steps(s: &Session) -> usize {
s.doc().unwrap().history.undo.len()
}
fn err(s: &mut Session, p: Value) -> String {
s.execute(SET, &p).unwrap_err().to_string()
}
/// The text object `id`'s data holds under the fold angle key.
fn stored(s: &Session, id: u64) -> Option<String> {
let d = &s.doc().unwrap().doc;
let n = d.node(NodeId(id)).unwrap();
n.extras().attrs.as_deref().and_then(|a| a.data.iter().find(|(k, _)| k == KEY).map(|(_, v)| v.clone()))
}
/// A tray blank: a 100 pt base (x 140 to 240, y 140 to 240) with a 40 pt wall on each side →
/// (outline, creases: top, right, bottom, left).
fn tray(s: &mut Session) -> (u64, Vec<u64>) {
let outline = path(s, "M140 100 L240 100 L240 140 L280 140 L280 240 L240 240 L240 280 L140 280 L140 240 L100 240 L100 140 L140 140 Z");
let creases = vec![path(s, "M140 140 L240 140"), path(s, "M240 140 L240 240"), path(s, "M240 240 L140 240"), path(s, "M140 240 L140 140")];
role(s, "cut", &[outline]);
role(s, "crease", &creases);
s.execute("select.none", &json!({})).unwrap();
(outline, creases)
}
/// Whether panel `p` of a fold is the tray's top wall (y 100 to 140): the middle of the bounds of
/// its outline's points (absolute moves and lines only) is above the base.
fn top_wall(p: &Value) -> bool {
let d = p["outline"].as_str().unwrap();
let n: Vec<f64> = d.split(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-')).filter_map(|t| t.parse().ok()).collect();
let ys = n.iter().skip(1).step_by(2).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &t| (lo.min(t), hi.max(t)));
(ys.0 + ys.1) / 2.0 < 140.0
}
fn vector(v: &Value) -> [f64; 3] {
let a = v.as_array().unwrap();
[a[0].as_f64().unwrap(), a[1].as_f64().unwrap(), a[2].as_f64().unwrap()]
}
#[test]
fn set_fold_angle_keeps_the_angle_on_the_line_and_reset_takes_it_away() {
let mut s = session();
let (_, creases) = tray(&mut s);
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(0), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
assert_eq!(steps(&s), before + 1, "one undo step");
// The same angle again changes nothing and records no undo step.
let r = s.execute(SET, &json!({"angle": 45.0, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(0));
assert_eq!(steps(&s), before + 1);
// An angle is kept to the millionth of a degree, so one closer to 45 than that is 45.
let r = s.execute(SET, &json!({"angle": 45.00000001, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before + 1), "{r}");
s.execute(SET, &json!({"angle": 179.99999998, "ids": [creases[3]]})).unwrap();
assert_eq!(stored(&s, creases[3]).as_deref(), Some("180"));
s.execute("edit.undo", &json!({})).unwrap();
// A number as text, and the selection when ids is left out; -0 is kept as 0.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
let r = s.execute(SET, &json!({"angle": "-0"})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "{r}");
assert_eq!(stored(&s, creases[1]).as_deref(), Some("0"));
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0], creases[1], creases[3]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(2), "the line without an angle of its own is unchanged: {r}");
assert_eq!((stored(&s, creases[0]), stored(&s, creases[1])), (None, None));
// Nothing left to reset: no undo step.
let at = steps(&s);
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), at));
// Undo brings the angle back.
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
}
#[test]
fn bad_angles_and_targets_are_refused() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let plain = path(&mut s, "M10 10 L50 50");
let before = steps(&s);
let ids = json!([creases[0]]);
assert!(err(&mut s, json!({"ids": ids})).contains("missing `angle`"));
assert!(err(&mut s, json!({"angle": 30, "reset": true, "ids": ids})).contains("not both"));
assert!(err(&mut s, json!({"angle": 180.5, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": -181, "ids": ids})).contains("from -180 to 180"));
assert!(err(&mut s, json!({"angle": "wide", "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"angle": true, "ids": ids})).contains("must be a number"));
assert!(err(&mut s, json!({"reset": "yes", "ids": ids})).contains("true or false"));
// A cut line and a path without a role do not fold.
assert!(err(&mut s, json!({"angle": 30, "ids": [outline, plain]})).contains("crease, partial cut or perforation"));
// An id of no object is named as such, alone or beside a crease.
assert!(err(&mut s, json!({"angle": 30, "ids": [999_999]})).contains("no such object id 999999"));
assert!(err(&mut s, json!({"angle": 30, "ids": [creases[0], 999_999]})).contains("no such object id 999999"));
assert_eq!(steps(&s), before, "no refusal records an undo step");
// The ends of the range are allowed; cut lines and plain paths among fold lines are skipped.
let r = s.execute(SET, &json!({"angle": -180, "ids": [creases[0], outline, plain]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(2), &json!([creases[0]])), "{r}");
s.execute(SET, &json!({"angle": 180, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("180"));
assert_eq!(stored(&s, outline), None);
}
#[test]
fn set_fold_angle_is_dimmed_without_a_line_it_can_change() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let enabled = |s: &Session| (find_command(SET).unwrap().enabled)(s).is_ok();
assert!(!enabled(&s), "nothing selected");
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!(!enabled(&s), "a cut line does not fold");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
s.execute("select.set", &json!({"ids": [creases[0]]})).unwrap();
assert!(enabled(&s));
s.execute("object.lock", &json!({})).unwrap();
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(creases[0])]).lines, 0, "a locked crease can't be changed");
// A group holding a crease is enough.
s.execute("select.set", &json!({"ids": [creases[1], creases[2]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
assert!(enabled(&s));
// A layer selected with a crease in it: the crease is inside the layer, which is left out, as
// Set Fold Angle itself leaves them out.
let layer = s.doc().unwrap().doc.layer_of(NodeId(creases[3])).unwrap();
s.execute("select.set", &json!({"ids": [layer.0, creases[3]]})).unwrap();
assert_eq!(s.doc().unwrap().selection.objects.len(), 2, "both are selected");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert!(!enabled(&s), "dimmed as the command refuses it");
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
// With nothing selected the counts are the document's, but Set Fold Angle takes no line.
s.execute("select.set", &json!({"ids": []})).unwrap();
assert!(s.execute(SET, &json!({"angle": 30})).is_err());
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!(r["scope"].as_str(), Some("document"), "{r}");
assert_eq!(r["roles"][1]["count"].as_u64(), Some(4), "{r}");
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"], r["ownAngles"].as_u64()), (Some(0), &Value::Null, Some(0)), "{r}");
}
#[test]
fn a_crease_named_in_ids_is_set_after_the_menu_found_none_in_the_selection() {
let mut s = session();
let (outline, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [outline]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "a cut line does not fold");
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
assert_eq!(r["changed"].as_u64(), Some(1), "{r}");
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "the selection is still the cut line");
}
#[test]
fn the_selection_s_fold_angles_count_a_crease_and_its_selected_group_once() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [group, creases[0]]})).unwrap();
let f = crate::cmd::selection_fold_angles(&s);
assert_eq!((f.lines, f.angle, f.own), (2, None, 1), "{f:?}");
}
#[test]
fn a_locked_crease_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute(SET, &json!({"angle": 30, "ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}");
assert_eq!(stored(&s, creases[1]), None);
}
#[test]
fn a_locked_path_of_a_compound_crease_named_by_id_is_skipped() {
let mut s = session();
let (_, creases) = tray(&mut s);
let (a, b) = (path(&mut s, "M300 300 L400 300"), path(&mut s, "M300 320 L400 320"));
s.execute("select.set", &json!({"ids": [a, b]})).unwrap();
let compound = s.execute("object.compoundPath.make", &json!({})).unwrap()["id"].as_u64().unwrap();
role(&mut s, "crease", &[compound]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(NodeId(a)) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, json!({"angle": 30, "ids": [a]})).contains("crease, partial cut or perforation"));
// Named twice, it is skipped once.
let r = s.execute(SET, &json!({"angle": 30, "ids": [a, a, creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64(), &r["ids"]), (Some(1), Some(1), &json!([creases[0]])), "{r}");
assert_eq!(stored(&s, compound), None);
assert_eq!(fold_angles(&s.doc().unwrap().doc, &[NodeId(a)]).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a]})).unwrap();
assert!((find_command(SET).unwrap().enabled)(&s).is_err(), "dimmed");
assert!(err(&mut s, json!({"angle": 30})).contains("crease, partial cut or perforation"));
assert_eq!(crate::cmd::selection_fold_angles(&s).lines, 0);
let r = s.execute("addon.packaging.roles", &json!({})).unwrap();
assert_eq!((r["foldLines"].as_u64(), &r["foldAngle"]), (Some(0), &Value::Null), "{r}");
assert_eq!(stored(&s, compound), None);
// With its compound, given or selected, the locked path is part of the compound, not skipped.
let r = s.execute(SET, &json!({"angle": 20, "ids": [compound, a]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute("select.set", &json!({"ids": [compound, a]})).unwrap();
let r = s.execute(SET, &json!({"angle": 25})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(0)), "{r}");
s.execute(SET, &json!({"reset": true, "ids": [compound]})).unwrap();
// The compound named by id takes the angle; its other path, not locked, names it too.
let r = s.execute(SET, &json!({"angle": 30, "ids": [b]})).unwrap();
assert_eq!((r["changed"].as_u64(), &r["ids"]), (Some(1), &json!([compound])), "{r}");
assert_eq!(stored(&s, compound).as_deref(), Some("30"));
}
#[test]
fn a_damaged_angle_reads_as_none_of_its_own() {
let mut s = session();
let (_, creases) = tray(&mut s);
let mut n = s.doc().unwrap().doc.node(NodeId(creases[0])).cloned().unwrap();
for (text, want) in [("45", Some(45.0)), (" -30.5 ", Some(-30.5)), ("wide", None), ("NaN", None), ("inf", None), ("181", None), ("", None)] {
n.edit_attrs(|a| {
a.data.retain(|(k, _)| k != KEY);
a.data.push((KEY.into(), text.into()));
});
assert_eq!(own_angle(&n), want, "{text:?}");
}
}
#[test]
fn an_angle_stored_as_other_text_for_the_same_number_is_unchanged() {
let mut s = session();
let (_, creases) = tray(&mut s);
let id = NodeId(creases[0]);
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "45.0".into())));
}
Ok(())
})
.unwrap();
let before = steps(&s);
let r = s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), steps(&s)), (Some(0), before), "{r}");
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45.0"));
s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!(stored(&s, creases[0]), None);
// A reset also removes text that is not an angle.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(id) {
n.edit_attrs(|a| a.data.push((KEY.into(), "wide".into())));
}
Ok(())
})
.unwrap();
let r = s.execute(SET, &json!({"reset": true, "ids": [creases[0]]})).unwrap();
assert_eq!((r["changed"].as_u64(), stored(&s, creases[0])), (Some(1), None), "{r}");
}
#[test]
fn a_line_keeps_its_own_angle_through_a_role_change() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
role(&mut s, "partialCut", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
role(&mut s, "none", &[creases[0]]);
assert_eq!(stored(&s, creases[0]).as_deref(), Some("45"));
role(&mut s, "crease", &[creases[0]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(45.0), Some(1)), "{r}");
}
#[test]
fn native_save_and_preserve_editing_keep_the_angle_and_svg_leaves_it_out() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 120, "ids": [creases[0]]})).unwrap();
let svg = s.execute("document.export", &json!({"format": "svg"})).unwrap();
let svg = svg["text"]
.as_str()
.map(str::to_string)
.unwrap_or_else(|| String::from_utf8_lossy(&vectorcraft_format::base64_decode(svg["dataBase64"].as_str().unwrap()).unwrap()).into_owned());
assert!(svg.contains("<svg"), "{svg}");
assert!(!svg.contains("fold-angle"), "{svg}");
// An SVG with Preserve Editing reopens as the document it carries, the angle with it.
let editing = s.execute("document.serialize", &json!({"format": "svg", "preserveEditing": true})).unwrap();
let editing = editing["text"].as_str().unwrap().to_string();
let mut t = Session::new();
t.execute("document.open", &json!({"name": "box.svg", "dataBase64": vectorcraft_format::base64_encode(editing.as_bytes())})).unwrap();
assert_eq!(stored(&t, creases[0]).as_deref(), Some("120"));
let saved = s.execute("document.export", &json!({"format": "vectorcraft"})).unwrap();
s.execute("document.open", &json!({"name": "box.vectorcraft", "dataBase64": saved["dataBase64"]})).unwrap();
assert_eq!(stored(&s, creases[0]).as_deref(), Some("120"));
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
assert!(angles.contains(&120.0), "{r}");
}
#[test]
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
let mut s = session();
let (_, creases) = tray(&mut s);
// The top wall (y 100 to 140) folds at 45°.
s.execute(SET, &json!({"angle": 45, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut angles: Vec<f64> = r["hinges"].as_array().unwrap().iter().map(|h| h["angle"].as_f64().unwrap()).collect();
angles.sort_by(f64::total_cmp);
assert_eq!(angles, [45.0, 90.0, 90.0, 90.0]);
for (i, p) in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base) {
let z = vector(&p["frame"]["z"]);
let top = top_wall(p);
let tilt = if top { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
assert!((z[2] - tilt).abs() < 1e-9, "panel {i}: {p}");
}
}
#[test]
fn a_negative_angle_folds_a_crease_toward_the_print() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": -90, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.fold", &json!({})).unwrap();
let base = r["base"].as_u64().unwrap() as usize;
let mut up = 0;
for p in r["panels"].as_array().unwrap().iter().enumerate().filter(|(i, _)| *i != base).map(|(_, p)| p) {
// The top wall folds toward the print, so its printed side faces back over the base
// (toward -y in the y-up frame); the other walls stand square to the base as before.
let top = top_wall(p);
let z = vector(&p["frame"]["z"]);
if top {
assert!((z[1] + 1.0).abs() < 1e-9, "the top wall's print faces the base: {p}");
up += 1;
} else {
assert!(z[2].abs() < 1e-9, "{p}");
}
}
assert_eq!(up, 1);
}
#[test]
fn roles_reports_the_angle_the_selected_fold_lines_share() {
let mut s = session();
let (outline, creases) = tray(&mut s);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "the role's angle: {r}");
s.execute(SET, &json!({"angle": 30, "ids": [creases[0]]})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], creases[1]]})).unwrap();
assert_eq!((r["foldAngle"].clone(), r["ownAngles"].as_u64()), (Value::Null, Some(1)), "they differ: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[0], outline]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(30.0), Some(1)), "a cut line has no angle: {r}");
let r = s.execute("addon.packaging.roles", &json!({"ids": [outline]})).unwrap();
assert!(r["foldAngle"].is_null(), "{r}");
// A partial cut folds at -90° unless it has an angle of its own.
role(&mut s, "partialCut", &[creases[2]]);
let r = s.execute("addon.packaging.roles", &json!({"ids": [creases[2]]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["foldLines"].as_u64()), (Some(-90.0), Some(1)), "{r}");
}
#[test]
fn roles_leaves_locked_fold_lines_out_of_the_angle_as_set_fold_angle_does() {
let mut s = session();
let (_, creases) = tray(&mut s);
s.execute(SET, &json!({"angle": 45, "ids": [creases[1]]})).unwrap();
s.execute("select.set", &json!({"ids": [creases[0], creases[1]]})).unwrap();
s.execute("object.group", &json!({})).unwrap();
let group = s.doc().unwrap().selection.objects[0].0;
s.execute("select.set", &json!({"ids": [creases[1]]})).unwrap();
s.execute("object.lock", &json!({})).unwrap();
let r = s.execute("addon.packaging.roles", &json!({"ids": [group]})).unwrap();
assert_eq!(r["roles"][1]["count"].as_u64(), Some(2), "both are counted: {r}");
assert_eq!((r["foldLines"].as_u64(), r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(1), Some(90.0), Some(0)), "{r}");
// So Reset has nothing to change, as the panel shows it.
let r = s.execute(SET, &json!({"reset": true, "ids": [group]})).unwrap();
assert_eq!((r["changed"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(1)), "{r}");
let (lines, angle, own) = {
let f = fold_angles(&s.doc().unwrap().doc, &[NodeId(group)]);
(f.lines, f.angle, f.own)
};
assert_eq!((lines, angle, own), (1, Some(90.0), 0));
}
@@ -8,6 +8,7 @@ use vectorcraft_three_d::fold::{Blank, FoldLine, Issue, IssueCode, LineKind, MAX
use super::super::super::pathops::length_given;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, switch_or};
use super::angle::own_angle;
use super::roles::{Role, RoleTable, can_carry, role_targets};
use crate::{Result, Session};
@@ -92,7 +93,8 @@ fn on_non_printing_layer(d: &Document, id: NodeId) -> bool {
d.ancestry(id).unwrap_or_default().iter().filter_map(|a| d.node(*a)).any(|n| matches!(n.kind, NodeKind::Layer { printable: false, .. }))
}
fn kind(role: Role) -> LineKind {
/// The kind of fold line a line with `role` is.
pub(super) fn kind(role: Role) -> LineKind {
match role {
Role::Cut => LineKind::Cut,
Role::Crease => LineKind::Crease,
@@ -155,7 +157,7 @@ fn lines_of(d: &Document, scope: &'static str, targets: Vec<NodeId>) -> Lines {
non_printing.push(id.0);
}
segments = segments.saturating_add(path.subpaths.iter().map(|sp| sp.segment_count()).sum());
lines.push(FoldLine { path, kind: kind(role), key: id.0 });
lines.push(FoldLine { path, kind: kind(role), key: id.0, angle: own_angle(n) });
}
Lines { scope, lines, non_printing }
}
@@ -19,7 +19,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fold",
[],
None,
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: a Crease or a Perforation by 90° away from the printed side, a Partial Cut by 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
"{ids?: [id…] (default: the selection), base?: [x, y] (the panel under this point; default: the largest panel), amount?: 0..1 (1), tolerance?: pt 0.01..10 (0.1)} fold the blank that the fold lines among the objects make (as addon.packaging.check finds them; while nothing is selected and ids is left out, every fold line of the document) into its 3D shape. The base panel stays in place; every other panel turns about the hinges that join it to the base, each by its angle times amount: the angle of the line with the most length in it, which is the line's own (addon.packaging.setFoldAngle; a positive angle folds away from the printed side) or else its role's, a Crease or a Perforation 90° away from the printed side and a Partial Cut 90° toward it. Hinges that close a loop of panels are not turned about: gap is how far apart their two placements end up when every hinge is folded all the way, whatever amount is, and closes is true within tolerance or 0.5% of the hinge's length. Changes nothing in the document → {ok (no error), blank (the index of the blank folded, or null when none is), blanks, base, panels: [{outline (SVG path data, document coordinates), frame: {x, y, z, origin} (where the flat blank's x and y directions, its printed side and its origin go, in points: x right, y up, z toward the printed side of the flat blank), parent (null for the base and loose panels), depth}], hinges: [{a, b, angle (degrees), kind: tree|closing, closes, gap}], collisions: [[a, b]] (panels that pass through each other; panels stacked in one plane do not), issues (as addon.packaging.check)}. Errors: a base point in no panel",
has_doc,
fold_command
)]
@@ -10,6 +10,7 @@ use vectorcraft_color::swatch::REGISTRATION;
use vectorcraft_color::{Color, Paint, Swatch};
use vectorcraft_doc::{Document, Node, NodeId, NodeKind};
use super::super::super::edit::{outermost, refuse_symbol_part, roots_of};
use super::super::super::overprint::edit_counted;
use super::super::super::{CommandSpec, bad, checked_ids_or_selection, cmd, has_doc, has_selection, switch_or, text_param};
use crate::{Result, Session};
@@ -194,6 +195,41 @@ pub(super) fn can_carry(n: &Node) -> bool {
}
}
/// The objects a command that changes roles or angles takes for params `p`: `ids` (the outermost of
/// them), or else the selection (as `selected_roots` takes it), with a path of a compound path that
/// is locked or hidden, or in a locked or hidden group or layer, or on a locked artboard, left out
/// before it stands for its compound, and how many such paths were left out, each once.
pub(super) fn taken_roots(s: &Session, p: &Value, command: &str) -> Result<(Vec<NodeId>, usize)> {
if p.get("ids").is_some_and(|v| !v.is_null()) {
let roots = checked_ids_or_selection(s, p, command)?;
return Ok(editable_members(&s.doc()?.doc, roots));
}
refuse_symbol_part(s)?;
let st = s.doc()?;
// An object inside another selected one is left out first, as it is from `ids`.
let (kept, left) = editable_members(&st.doc, outermost(&st.doc, st.selection.in_paint_order(&st.doc)));
Ok((roots_of(&st.doc, kept), left))
}
/// `ids` less the paths of compound paths among them that are locked or hidden (or in a locked or
/// hidden group or layer, or on a locked artboard), and how many different ones were left out.
pub(super) fn editable_members(d: &Document, ids: Vec<NodeId>) -> (Vec<NodeId>, usize) {
let ok = d.editable();
let member = |id: NodeId| d.parent_of(id).is_some_and(|p| matches!(d.node(p).map(|n| &n.kind), Some(NodeKind::Compound { .. })));
let mut left = std::collections::HashSet::new();
let kept = ids
.into_iter()
.filter(|id| {
let out = member(*id) && !ok(*id);
if out {
left.insert(*id);
}
!out
})
.collect();
(kept, left.len())
}
/// The objects under the outermost objects `roots` that can carry a role, through groups and clip
/// groups, each once, and
/// how many of `roots` and their members can't (text, images, symbol instances and other objects).
@@ -257,7 +293,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Make Fold Line",
["Object", "Plug-ins", "Packaging Tools"],
None,
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
"{role: cut|crease|partialCut|perforation|none, ids?: [id…] (default: the selection), overprint?: bool (true)} give each path, compound path and live shape among the objects (through groups and clip groups; objects that are locked or hidden, in a locked or hidden group or layer, or on a locked artboard are left out and counted as skipped, even when named in ids) a fold line role: its top stroke is painted with the role's swatch (addon.packaging.roles) at 100% and shown, a path without a stroke gets a 1 pt stroke, and the stroke overprints, or with overprint: false does not. A missing role swatch is made as a global spot swatch (Cut 100% magenta, Crease 100% cyan, Partial Cut 100% yellow, Perforation 50% magenta and 50% cyan, in the document's color mode; named \"Cut 2\" and so on, in the role table too, when a color group or a swatch that can't carry a role, such as a process color that is not global, has the name). none takes the role away: a role stroke keeps the color it shows, no longer linked to the swatch, and stops overprinting. A line keeps its own fold angle (addon.packaging.setFoldAngle) through a role change and through none. Text, images, symbol instances and other objects are skipped and counted. One undo step, none when nothing changes → {ids (the objects that can carry a role), changed, skipped}",
has_selection,
set_role
),
@@ -266,7 +302,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Fold Lines",
[],
None,
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected)}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out",
"{ids?: [id…] (default: the selection)} the fold line roles → {roles: [{role: cut|crease|partialCut|perforation, name, swatch (the swatch that carries it), exists (the document has the swatch), count}], scope: ids|selection|document, selected (objects given or selected), foldLines, foldAngle, ownAngles, storedAngles}; count is how many of the paths, compound paths and live shapes among the objects (through groups, locked and hidden members included, each object once) have the role, or among every object of the document while nothing is selected and ids is left out. foldLines is how many of the Crease, Partial Cut and Perforation lines among them addon.packaging.setFoldAngle can change (those not locked or hidden; none while nothing is selected and ids is left out, or while the selection holds only a layer and objects in it), foldAngle the angle in degrees they all fold at (their own or their role's), null when they fold at different angles or there are none, ownAngles how many of them have an angle of their own, and storedAngles how many hold stored angle text, an angle or not, which setFoldAngle's reset: true removes",
has_doc,
roles
),
@@ -382,8 +418,9 @@ fn give_role(d: &mut Document, table: &RoleTable, id: NodeId, paint: Option<&Pai
fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
let role = role_param(p, SET_ROLE, true)?;
let overprint = switch_or(p, "overprint", true, SET_ROLE)?;
let roots = checked_ids_or_selection(s, p, SET_ROLE)?;
let (roots, left) = taken_roots(s, p, SET_ROLE)?;
let (ids, skipped) = role_targets(&s.doc()?.doc, &roots, true);
let skipped = skipped + left;
if ids.is_empty() {
return Err(bad(SET_ROLE, "select a path that is neither locked nor hidden: text, images and symbol instances can't have a fold line role"));
}
@@ -403,19 +440,38 @@ fn set_role(s: &mut Session, p: &Value) -> Result<Value> {
fn roles(s: &mut Session, p: &Value) -> Result<Value> {
let given = p.get("ids").is_some_and(|v| !v.is_null());
let roots = checked_ids_or_selection(s, p, ROLES)?;
let d = &s.doc()?.doc;
// The objects Set Fold Angle takes: a locked or hidden path of a compound path does not stand
// for its compound there. They are the objects the counts are of unless such a path was left
// out, and only then are those found apart.
let (taken, left) = taken_roots(s, p, ROLES)?;
let (roots, angle_roots) = if left == 0 { (taken, vec![]) } else { (checked_ids_or_selection(s, p, ROLES)?, taken) };
let st = s.doc()?;
let d = &st.doc;
let (scope, ids) = match (given, roots.is_empty()) {
(true, _) => ("ids", role_targets(d, &roots, false).0),
(false, false) => ("selection", role_targets(d, &roots, false).0),
(false, true) => ("document", document_targets(d)),
};
let whole = scope == "document";
// The lines Set Fold Angle can change are those of the objects it takes: with nothing selected,
// or a selection that holds no such object (only a layer and what is in it), it takes none,
// though the counts are the document's.
let angles_of_all = given || !roots.is_empty();
let table = RoleTable::of(d);
let mut counts = [0usize; 4];
for r in ids.iter().filter_map(|id| d.node(*id)).filter_map(|n| table.role_of(n)) {
let editable = d.editable();
let mut angles = super::angle::FoldAngles::default();
for n in ids.iter().filter_map(|id| d.node(*id)) {
let Some(r) = table.role_of(n) else { continue };
if let Some(c) = counts.get_mut(r.index()) {
*c += 1;
}
if left == 0 && angles_of_all && super::angle::folds(r) && editable(n.id) {
angles.add(n, r);
}
}
if !whole && left > 0 {
angles = super::angle::fold_angles(d, &angle_roots);
}
let rows: Vec<Value> = Role::ALL
.into_iter()
@@ -425,7 +481,10 @@ fn roles(s: &mut Session, p: &Value) -> Result<Value> {
json!({ "role": r.id(), "name": r.name(), "swatch": swatch, "exists": d.swatch(swatch).is_some(), "count": count })
})
.collect();
Ok(json!({ "roles": rows, "scope": scope, "selected": roots.len() }))
Ok(json!({
"roles": rows, "scope": scope, "selected": roots.len(),
"foldLines": angles.lines, "foldAngle": angles.angle, "ownAngles": angles.own, "storedAngles": angles.stored,
}))
}
fn set_role_swatch(s: &mut Session, p: &Value) -> Result<Value> {
@@ -537,4 +537,20 @@ fn compound_paths_carry_a_role() {
let r = set_role(&mut s, json!({"role": "crease", "ids": [a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["changed"].as_u64()), (json!([c.0]), Some(1)));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// A locked member named by id is skipped, and its compound keeps its role.
s.edit("Test", |d, _| {
if let Some(n) = d.node_mut(a) {
n.locked = true;
}
Ok(())
})
.unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut", "ids": [a.0]})).contains("neither locked nor hidden"));
// The same with the locked path selected.
s.execute("select.set", &json!({"ids": [a.0]})).unwrap();
assert!(err(&mut s, "addon.packaging.setRole", json!({"role": "cut"})).contains("neither locked nor hidden"));
assert_eq!(counts(&mut s, json!({"ids": [c.0]})), [0, 1, 0, 0]);
// Named twice, it is skipped once.
let r = set_role(&mut s, json!({"role": "cut", "ids": [a.0, a.0, b.0]}));
assert_eq!((r["ids"].clone(), r["skipped"].as_u64()), (json!([c.0]), Some(1)), "{r}");
}
@@ -43,6 +43,7 @@ pub(super) const ALLOWED: &[&str] = &[
"addon.packaging.check",
"addon.packaging.fold",
"addon.packaging.roles",
"addon.packaging.setFoldAngle",
"addon.packaging.setRole",
"addon.packaging.setRoleSwatch",
"addon.pathtools.addPoints",
+1 -1
View File
@@ -1411,7 +1411,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
),
(
"ui.widthPointEdit",
+55 -8
View File
@@ -46,12 +46,31 @@ impl LineKind {
}
}
/// A fold line: the path (document coordinates), its kind, and a key the issues name it by.
/// A fold line: the path (document coordinates), its kind, a key the issues name it by, and its
/// own fold angle (degrees), which a line that folds takes instead of its kind's.
#[derive(Clone, Debug)]
pub struct FoldLine {
pub path: PathData,
pub kind: LineKind,
pub key: u64,
pub angle: Option<f64>,
}
/// `angle` (degrees) to the whole millionth of a degree, the finest fold angle a line keeps. A fold
/// that close to flat is flat: the preview tells panels in one plane from panels a millionth of a
/// degree apart, but not from panels closer than that.
pub fn kept_angle(angle: f64) -> f64 {
(angle * 1e6).round() / 1e6 + 0.0
}
impl FoldLine {
/// The angle (degrees) the line folds at: its own angle when it has one from -180 to 180, to the
/// millionth of a degree ([`kept_angle`]), else its kind's ([`LineKind::fold_angle`]); none for
/// a Cut, whatever its own angle.
pub fn fold_angle(&self) -> Option<f64> {
let own = self.angle.filter(|a| (-180.0..=180.0).contains(a)).map(kept_angle);
self.kind.fold_angle().map(|default| own.unwrap_or(default))
}
}
/// One blank: its panels, the hinges between them, and its holes.
@@ -79,14 +98,17 @@ impl Panel {
/// 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. `angle` (degrees) is the fold angle of the kind of line its longest piece is
/// ([`LineKind::fold_angle`]).
/// piece. `angle` (degrees) is the fold angle ([`FoldLine::fold_angle`]) of the line with the most
/// length in the hinge, the one with the lowest key among lines of equal length. `on` is the middle
/// of its longest piece, a point where the two panels meet, which a hinge with gaps between its
/// pieces may not have at the middle of `from` to `to`.
#[derive(Clone, Debug)]
pub struct Hinge {
pub a: usize,
pub b: usize,
pub from: Point,
pub to: Point,
pub on: Point,
pub keys: Vec<u64>,
pub straight: bool,
pub angle: f64,
@@ -1297,9 +1319,34 @@ impl Context<'_> {
let sp = p.path.subpaths.first()?;
Some((sp.anchors.first()?.p, sp.anchors.last()?.p))
};
let ((p0, p1), longest) =
let ((p0, p1), _) =
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 lengths: Vec<f64> = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::<f64>()).collect();
// The angle of the line with the most length in the hinge, the one with the lowest key on a
// tie: a line the planar map split into several pieces counts whole.
let mut by_line: HashMap<usize, f64> = HashMap::new();
for (p, len) in group.iter().zip(&lengths) {
// Subpaths of one line on top of each other count once.
let mut lines = p.lines.clone();
lines.sort_unstable();
lines.dedup();
for l in lines {
*by_line.entry(l).or_default() += len;
}
}
let folding: Vec<(f64, f64, u64)> = by_line
.iter()
.filter_map(|(&l, &len)| {
let line = self.lines.get(l)?;
Some((line.fold_angle()?, len, line.key))
})
.collect();
// Lengths summed from pieces in another order differ in their last bits: a few epsilons per
// piece, and no more, so a line measurably longer still wins.
let most = folding.iter().map(|f| f.1).fold(0.0, f64::max);
let pieces = f64::from(u32::try_from(group.len()).unwrap_or(u32::MAX));
let rounding = 8.0 * f64::EPSILON * (pieces + 1.0) * most;
let angle = folding.iter().filter(|f| f.1 >= most - rounding).min_by_key(|f| f.2).map_or(90.0, |f| f.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 {
@@ -1321,7 +1368,7 @@ impl Context<'_> {
}
// The pieces' own length, not the span from the first to the last, which takes in the gaps
// between pieces that lie apart.
let length: f64 = group.iter().map(|p| p.path.to_bezpath().segments().map(|s| s.arclen(1e-3)).sum::<f64>()).sum();
let length: f64 = lengths.iter().sum();
if !(lo.is_finite() && hi.is_finite()) || hi - lo < self.tolerance || length.is_nan() || length < self.tolerance {
return None;
}
@@ -1331,7 +1378,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, angle })
Some(Hinge { a, b, from: p0 + d * lo, to: p0 + d * hi, on: p0.midpoint(p1), keys, straight, angle })
}
/// Creases with no hinge: outside every blank, or dividing no two panels; and creases beside a
@@ -1465,7 +1512,7 @@ pub fn base_panel(panels: &[Panel]) -> Option<usize> {
mod pose;
pub mod raster;
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, fold, panel_at, pick, polygon};
pub use pose::{Folded, FoldedHinge, FoldedPanel, MAX_POLYGON_POINTS, Pose, Stack, fold, panel_at, pick, polygon};
#[cfg(test)]
mod tests;
+135 -22
View File
@@ -19,6 +19,11 @@ use super::{Blank, base_panel, point_in};
/// test and the preview.
pub const MAX_POLYGON_POINTS: usize = 1 << 16;
/// How far apart two placements of a panel may turn a unit direction and still be one placement:
/// above the rounding of up to [`super::MAX_PANELS`] turns, below the turn of a hinge a millionth
/// of a degree from another ([`super::kept_angle`], 1.7e-8).
const TURNED: f64 = 1e-10;
type V3 = [f64; 3];
fn sub(a: V3, b: V3) -> V3 {
@@ -105,14 +110,24 @@ impl Pose {
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) }
}
/// This pose, taken about `origin` (a point less `origin` to its place less `origin`), in the
/// flat blank's own terms.
fn about(&self, origin: V3) -> Pose {
Pose { m: self.m, t: add(sub(self.t, self.turn(origin)), origin) }
}
}
/// 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.
/// A folded panel: where it is, the same about [`Folded::origin`] (`local`), 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,
/// Where the panel is with the flat blank moved so `origin` is at 0: it takes a flat point less
/// `origin` to its place less `origin`. Worked out in these terms, it keeps the rounding of a
/// blank far from the document's origin to the size of the blank.
pub local: Pose,
pub parent: Option<usize>,
pub depth: usize,
}
@@ -141,6 +156,28 @@ pub struct Folded {
pub hinges: Vec<FoldedHinge>,
/// Pairs of panels (`a` < `b`) that pass through each other.
pub collisions: Vec<(usize, usize)>,
/// The fold tree that panels folded flat onto each other stack by.
pub stack: Stack,
/// The middle of the blank's bounds (flat, see [`flat`]), which [`FoldedPanel::local`] is about.
pub origin: [f64; 3],
}
/// The fold tree that panels in one plane stack by: the tree from the blank's largest panel (its
/// `root`), whichever panel is the base, so choosing another base moves the folded blank without
/// changing which panel shows where they lie flat on each other. The base's own tree when the two
/// join different panels.
#[derive(Clone, Debug, Default)]
pub struct Stack {
pub root: usize,
/// Each panel's parent in this tree.
pub parent: Vec<Option<usize>>,
/// The panels in breadth-first order from `root`, the panels not joined to it last.
pub order: Vec<usize>,
/// For each panel, the way from the hinge it is folded on into its parent, as folded: a vector
/// in the parent's plane, across the hinge to the side the fold took the parent to be on, as
/// long as the corners of the parent's bounds reach that way. `None` for `root` and the
/// panels not joined to it.
pub toward_parent: Vec<Option<[f64; 3]>>,
}
/// The panel of `blank` that `p` (document coordinates) lies in.
@@ -204,10 +241,25 @@ pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) ->
});
}
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, &centers, base, amount);
// The corners of each panel's bounds (flat).
let corners: Vec<Option<[V3; 4]>> = blank
.panels
.iter()
.map(|p| p.outline.bounds().map(|b| [(b.x0, b.y0), (b.x1, b.y0), (b.x0, b.y1), (b.x1, b.y1)].map(|(x, y)| flat(Point::new(x, y)))))
.collect();
let origin = corners
.iter()
.flatten()
.flatten()
.fold(None, |b: Option<(V3, V3)>, c| {
Some(b.map_or((*c, *c), |(lo, hi)| ([lo[0].min(c[0]), lo[1].min(c[1]), 0.0], [hi[0].max(c[0]), hi[1].max(c[1]), 0.0])))
})
.map_or([0.0; 3], |(lo, hi)| scale(add(lo, hi), 0.5));
let placing = Placing { blank, by_panel: &by_panel, centers: &centers, corners: &corners, origin };
let (panels, tree, order, toward_parent) = place(&placing, 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, &centers, base, 1.0).0) };
let full = if amount == 1.0 { None } else { Some(place(&placing, base, 1.0).0) };
let measured = full.as_deref().unwrap_or(&panels);
let hinges = blank
.hinges
@@ -224,15 +276,64 @@ pub fn fold(blank: &Blank, base: Option<usize>, amount: f64, tolerance: f64) ->
})
.collect();
let collisions = collisions(blank, &panels, tolerance);
Some(Folded { base, panels, order, hinges, collisions })
let own = Stack { root: base, parent: panels.iter().map(|p| p.parent).collect(), order: order.clone(), toward_parent };
let stack = match base_panel(&blank.panels) {
Some(root) if root != base => {
let (placed, root_tree, root_order, toward) = place(&placing, root, amount);
// Whether the root's tree puts every panel where the base's does, moved with the root
// (which lies at the identity in its own): the same hinges do, and around a loop of
// panels another tree can leave out a fold that placed them. Each panel's turn is
// compared to within `TURNED` whatever its size or place, and its inside point by the
// poses about `origin` (`local`), to rounding at that distance from it.
let agrees = |r: &FoldedPanel| {
let near = |a: V3, b: V3| length(sub(a, b)) <= 1e-9 * (1.0 + length(a).max(length(b)));
placed.iter().zip(&panels).enumerate().all(|(i, (p, q))| {
let joined = (i == root || p.parent.is_some(), i == base || q.parent.is_some());
let at = centers.get(i).copied().flatten().map_or([0.0; 3], |c| sub(c, origin));
let turned = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
.into_iter()
.all(|e| length(sub(r.local.turn(p.local.turn(e)), q.local.turn(e))) <= TURNED);
joined.0 == joined.1 && (!joined.0 || (turned && near(r.local.apply(p.local.apply(at)), q.local.apply(at))))
})
};
match panels.get(root) {
// The root's tree in the base's terms.
Some(r) if root_tree == tree || agrees(r) => Stack {
root,
parent: placed.iter().map(|p| p.parent).collect(),
order: root_order,
toward_parent: toward.into_iter().map(|v| v.map(|v| r.pose.turn(v))).collect(),
},
_ => own,
}
}
_ => own,
};
Some(Folded { base, panels, order, hinges, collisions, stack, origin })
}
/// 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>) {
/// What [`place`] gives: the placed panels, which hinges are in the tree, the panels' order and
/// [`Stack::toward_parent`].
type Tree = (Vec<FoldedPanel>, Vec<bool>, Vec<usize>, Vec<Option<V3>>);
/// What [`place`] places: the blank, each panel's hinges in order, each panel's inside point and
/// bounds corners (flat), and the point the panels' local poses are about.
struct Placing<'a> {
blank: &'a Blank,
by_panel: &'a [Vec<usize>],
centers: &'a [Option<V3>],
corners: &'a [Option<[V3; 4]>],
origin: V3,
}
/// The panels of the blank placed by the fold tree from `base` with each hinge at `amount` of its
/// angle, which hinges are in the tree, the panels in breadth-first order (the panels not joined
/// to the base last), and [`Stack::toward_parent`].
fn place(placing: &Placing, base: usize, amount: f64) -> Tree {
let Placing { blank, by_panel, centers, corners, origin } = *placing;
let n = blank.panels.len();
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, parent: None, depth: 0 }; n];
let mut panels: Vec<FoldedPanel> = vec![FoldedPanel { pose: Pose::IDENTITY, local: Pose::IDENTITY, parent: None, depth: 0 }; n];
let mut toward_parent: Vec<Option<V3>> = vec![None; n];
let mut reached = vec![false; n];
let mut tree = vec![false; blank.hinges.len()];
let mut order = Vec::with_capacity(n);
@@ -257,7 +358,7 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
// 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)) {
let left = match blank.panels.get(p).and_then(|panel| side_of(&panel.outline, from, to, len, flat(h.on))) {
Some(left) => left,
None => centers.get(p).copied().flatten().is_none_or(|c| cross(sub(to, from), sub(c, from))[2] >= 0.0),
};
@@ -270,7 +371,15 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
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 };
let local = parent.local.turned_about(sub(from, origin), axis, theta);
*slot = FoldedPanel { pose: local.about(origin), local, parent: Some(p), depth: parent.depth + 1 };
}
// Across the hinge, to its left: into the parent, as far as the corners of its bounds
// reach that way.
let into = [-axis[1], axis[0], 0.0];
let reach = corners.get(p).copied().flatten().map_or(0.0, |c| c.into_iter().map(|c| dot(sub(c, from), into)).fold(0.0, f64::max));
if let Some(slot) = toward_parent.get_mut(child) {
*slot = Some(parent.pose.turn(scale(into, reach)));
}
if let Some(r) = reached.get_mut(child) {
*r = true;
@@ -282,23 +391,27 @@ fn place(blank: &Blank, by_panel: &[Vec<usize>], centers: &[Option<V3>], base: u
}
}
order.extend((0..n).filter(|&i| reached.get(i) == Some(&false)));
(panels, tree, order)
(panels, tree, order, toward_parent)
}
/// 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> {
/// next to it: `true` when a point just off the line on the left is inside it and the matching
/// point on the right is not, `false` the other way round. `on` (a point of the line where the
/// panels meet: [`super::Hinge::on`]) is tried first, then the middle and points a quarter and an
/// eighth of the way along, each with the nearest offset first; `None` when no point tells the
/// sides apart.
fn side_of(outline: &PathData, from: V3, to: V3, len: f64, on: V3) -> 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)
let along = [0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875].map(|t| add(from, scale(sub(to, from), t)));
std::iter::once(on).chain(along).find_map(|at| {
offsets.into_iter().find_map(|off| {
let (l, r) = (bp.winding(doc(add(at, scale(left, off)))) != 0, bp.winding(doc(sub(at, scale(left, off)))) != 0);
(l != r).then_some(l)
})
})
}
+236 -12
View File
@@ -16,8 +16,18 @@ pub const MAX_SIDE: u32 = 4096;
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.
/// How far apart (points of view depth) two panels in one plane may be and still tie.
const TIE: f64 = 1e-4;
/// How far apart (the sine of the angle) two panels' normals may be for the panels to lie in one
/// plane.
const PARALLEL: f64 = 1e-9;
/// How far apart two parallel panels' planes may be for the panels to lie in one plane: rounding,
/// as this many times the precision of a number at their distance from the origin for each hinge
/// that placed them.
const COPLANAR: f64 = 16.0 * f64::EPSILON;
/// How far across a panel's plane (the cosine to its normal) a fold's step may go and still count
/// as along it.
const ALONG: f64 = 1e-6;
/// The light's direction: above, to the left of and toward the viewer.
const LIGHT: [f64; 3] = [-0.37, 0.56, 0.74];
@@ -278,11 +288,11 @@ fn invert(m: &[[f64; 3]; 3]) -> Option<[[f64; 3]; 3]> {
inv.iter().flatten().all(|v| v.is_finite()).then_some(inv)
}
fn map_panel(camera: &Camera, f: &super::FoldedPanel) -> Option<Mapped> {
fn map_panel(camera: &Camera, pose: &super::Pose) -> Option<Mapped> {
let r = camera.rotation();
let turn = |v: V3| mul(&r, f.pose.turn(v));
let turn = |v: V3| mul(&r, 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 o = camera.to_view(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() {
@@ -326,18 +336,23 @@ struct Target {
panel: Vec<u16>,
}
/// One panel's fill: its map, rank (for ties), panel number and colors.
/// One panel's fill: its map, rank and plane (for ties: the plane of every panel by its index, as
/// [`planes`] gives them), panel number and colors.
struct Fill<'a> {
mapped: &'a Mapped,
rank: u16,
planes: &'a [u16],
panel: u16,
print: Option<&'a Print>,
/// The flat point the map is about ([`Folded::origin`]): a flat point less it is what
/// `mapped` maps.
origin: [f64; 2],
inside: [f32; 4],
outside: [f32; 4],
}
impl Fill<'_> {
/// The document point under pixel center `(x, y)`, or `None` behind the eye.
/// The flat point (less [`Fill::origin`]) 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())
@@ -346,7 +361,7 @@ impl Fill<'_> {
/// 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 p = self.print.map_or([0.0; 4], |pr| pr.sample(Point::new(u + self.origin[0], -(v + self.origin[1])), 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 {
@@ -370,8 +385,12 @@ impl Fill<'_> {
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);
let (Some(&zb), Some(&rb), Some(&pb)) = (target.depth.get(i), target.rank.get(i), target.panel.get(i)) else { continue };
// Panels in one plane tie within `TIE` and stack by rank; panels in different planes
// that pass this close go by depth alone. Panel numbers count from 1.
let plane = |p: u16| usize::from(p).checked_sub(1).and_then(|p| self.planes.get(p));
let one_plane = plane(self.panel).is_some_and(|a| plane(pb) == Some(a));
let wins = if one_plane { z > zb + TIE || ((z - zb).abs() <= TIE && self.rank > rb) } else { z > zb };
if !wins {
continue;
}
@@ -442,6 +461,161 @@ fn flat_rings(panel: &Panel, scale: f64) -> Option<Vec<Vec<[f64; 2]>>> {
Some(polygon(&panel.outline, tolerance)?.into_iter().map(|r| r.into_iter().map(|p| [p.x, -p.y]).collect()).collect())
}
/// The rank (from 1) each panel of `folded.order` takes in a depth tie, the higher one drawn. Each
/// fold puts a panel in a layer next to its parent in [`Folded::stack`]: behind the parent's printed
/// side for a positive angle, in front of it for a negative one, level with it for 0°. Layers are
/// compared fold by fold from the stack's root (the largest panel, whichever panel is the base), so
/// a panel folded back over its parent's parent lands between the two at any depth. A tie, between
/// panels in one plane, goes to the panel whose layer is nearer the viewer across that plane (the
/// side of the plane `camera` sees). Two folds into one layer stack by the stack's order, the later
/// one nearer seen from one side of their plane and the earlier one seen
/// from the other, and the panels folded on from each stay with it. Two panels folded flat onto each other
/// (±180°) tie in depth everywhere they overlap. A panel that comes back onto the plane of a panel
/// it branched from, after leaving it, takes the side of that plane it came back from for every
/// step up to the one it left by: the side the nearest panel out of the plane lies on from the
/// hinge it joins the plane at ([`super::Stack::toward_parent`]). `planes` gives each panel's plane, as
/// [`planes`] does.
fn tie_ranks(folded: &Folded, camera: &Camera, planes: &[u16]) -> Vec<u16> {
let n = folded.panels.len();
// Each panel's layer holds a step per fold up to the base: past the panels a blank can have,
// the order alone decides. So it does when every panel lies where it lies flat (a fold amount
// of 0), as panels there do not overlap.
if n > super::MAX_PANELS || folded.order.len() > super::MAX_PANELS || folded.panels.iter().all(|f| f.pose == super::Pose::IDENTITY) {
return (1..=folded.order.len()).map(|r| u16::try_from(r).unwrap_or(u16::MAX)).collect();
}
// The step each panel takes off its parent: the parent's printed side, negated for a positive
// angle; none for a 0° hinge or a panel without a parent.
// The parents are those of [`Folded::stack`], so the panels stack the same about any base.
let stack = &folded.stack;
let parent_of = |c: usize| stack.parent.get(c).copied().flatten();
let mut step: Vec<Option<V3>> = vec![None; n];
for c in 0..n {
let Some(p) = parent_of(c) else { continue };
let Some(h) = folded.hinges.iter().find(|h| (h.a, h.b) == (p, c) || (h.a, h.b) == (c, p)) else { continue };
let (Some(parent), Some(slot)) = (folded.panels.get(p), step.get_mut(c)) else { continue };
let [x, y, z] = parent.pose.normal();
*slot = match h.angle {
a if a > 0.0 => Some([-x, -y, -z]),
a if a < 0.0 => Some([x, y, z]),
_ => None,
};
}
// Each panel's layer, from the base out: +1 for a step toward the viewer across the panel's
// plane, -1 for one away from it, 0 for one along it. Comparing these in order puts a panel next
// to its parent, before any later step, however many folds deep.
// Each panel's place in the stack's order.
let mut place = vec![0usize; n];
for (i, &pi) in stack.order.iter().enumerate() {
if let Some(slot) = place.get_mut(pi) {
*slot = i;
}
}
// Each step also carries the place in `folded.order` of the panel that took it, so panels whose
// steps match up to a fold that branches stack by that branch: the later panel nearer seen from
// one side of their plane, the earlier one seen from the other, so the two sides show opposite
// panels. The rest of a branch stays with it.
// Whether the view sees each panel's printed side.
let sees_print: Vec<bool> = folded.panels.iter().map(|f| map_panel(camera, &f.pose).is_none_or(|m| m.printed)).collect();
// The nearest panel out of `pi`'s plane on its way to the base, and the side of that plane it
// lies on from the hinge it joins the panels in the plane at: 1 the side `n_view` points to, -1
// the other; `None` when every panel on the way lies in the plane. The plane is the one
// [`planes`] gives, the same that decides which panels tie, so a ramp however shallow leaves it
// and a stack folded a hair short of flat goes by depth instead.
let approach = |pi: usize, n_view: V3| -> Option<(usize, i8)> {
let (mut child, mut up) = (pi, parent_of(pi));
for _ in 0..n {
let c = up?;
if planes.get(c) != planes.get(pi)
&& let Some(Some(way)) = stack.toward_parent.get(child)
{
let d = dot(*way, n_view);
if d != 0.0 {
return Some((c, if d > 0.0 { 1 } else { -1 }));
}
}
(child, up) = (c, parent_of(c));
}
None
};
let layer = |pi: usize| -> Vec<(i8, i64)> {
let Some(f) = folded.panels.get(pi) else { return vec![] };
let printed = sees_print.get(pi).copied().unwrap_or(true);
let n_view = {
let [x, y, z] = f.pose.normal();
if printed { [x, y, z] } else { [-x, -y, -z] }
};
let mut out = vec![];
let mut at = Some(pi);
// From the nearest panel out of the plane on the way to the base, every step counts as on
// the side of the plane that panel lies on: a panel that comes round onto the plane of a
// panel it branched from lies on the side it came back from, whatever its folds before.
let (back_at, back_side) = approach(pi, n_view).map_or((None, 0), |(c, s)| (Some(c), s));
let mut returned = false;
// A panel's chain to the base is at most the panel count long.
for _ in 0..n {
let Some(c) = at else { break };
returned |= Some(c) == back_at;
if let Some(Some(s)) = step.get(c) {
let d = if returned { f64::from(back_side) } else { dot(*s, n_view) };
// Branches off one panel stack one way seen from that panel's printed side and the
// other way from its back, so the panels of one plane that compare a step off one
// parent agree, however the parent is turned.
let branch = place.get(c).map_or(i64::MAX, |&p| i64::try_from(p).unwrap_or(i64::MAX));
// A parent seen edge on gives no side: the panel that took the step gives it, and
// when that is edge on too, the largest part of the view's normal does. Each choice
// gives two panels of one plane the same sign however an edge-on dot rounds, and
// each turns over with the side of the plane the view is on.
let faces = |f: &super::FoldedPanel| {
let d = dot(f.pose.normal(), n_view);
(d.abs() > ALONG).then_some(d >= 0.0)
};
// The view's normal in the root's flat terms, so this too is the same about any base.
let largest = || {
let m = folded.panels.get(stack.root).map_or(super::Pose::IDENTITY.m, |r| r.pose.m);
let local = [0, 1, 2].map(|j| (0..3).map(|i| m[i][j] * n_view[i]).sum::<f64>());
local.into_iter().max_by(|a, b| a.abs().total_cmp(&b.abs())).is_none_or(|v| v >= 0.0)
};
let parent = parent_of(c).and_then(|p| folded.panels.get(p));
let parent_faces = parent.map_or(Some(true), faces).or_else(|| folded.panels.get(c).and_then(faces)).unwrap_or_else(largest);
let branch = if parent_faces { branch } else { -branch };
// Any step that is not along the plane counts whole, so a step seen from two panels
// of one plane counts the same for both.
out.push((i8::from(d > ALONG) - i8::from(d < -ALONG), branch));
}
at = parent_of(c);
}
out.reverse();
out
};
// Layers compared step by step, a missing step as none.
let compare = |a: &[(i8, i64)], b: &[(i8, i64)]| {
(0..a.len().max(b.len()))
.map(|k| a.get(k).copied().unwrap_or((0, 0)).cmp(&b.get(k).copied().unwrap_or((0, 0))))
.find(|o| o.is_ne())
.unwrap_or(std::cmp::Ordering::Equal)
};
// A panel alone in its plane ties with no other, so its layer is not worked out.
let mut in_plane = vec![0usize; planes.iter().map(|&p| usize::from(p) + 1).max().unwrap_or(0)];
for &p in planes {
if let Some(c) = in_plane.get_mut(usize::from(p)) {
*c += 1;
}
}
let alone = |pi: usize| planes.get(pi).and_then(|&p| in_plane.get(usize::from(p))).is_some_and(|&c| c <= 1);
let mut keys: Vec<(Vec<(i8, i64)>, usize)> =
folded.order.iter().enumerate().map(|(i, &pi)| (if alone(pi) { vec![] } else { layer(pi) }, i)).collect();
// Then by the stack's order, for panels that stack as one.
let placed = |i: usize| folded.order.get(i).and_then(|&pi| place.get(pi)).copied().unwrap_or(usize::MAX);
keys.sort_by(|a, b| compare(&a.0, &b.0).then(placed(a.1).cmp(&placed(b.1))).then(a.1.cmp(&b.1)));
let mut ranks = vec![0u16; folded.order.len()];
for (r, &(_, i)) in keys.iter().enumerate() {
if let Some(slot) = ranks.get_mut(i) {
*slot = u16::try_from(r + 1).unwrap_or(u16::MAX);
}
}
ranks
}
/// `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.
@@ -456,10 +630,17 @@ pub fn render(scene: &Scene) -> Option<Image> {
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 planes = planes(scene.folded, scene.blank);
let ranks = tie_ranks(scene.folded, &camera, &planes);
// Panels are drawn by their poses about the blank's middle (`FoldedPanel::local`), with the flat
// points and the view's center moved to match.
let o = scene.folded.origin;
let local = Camera { center: [camera.center[0] - o[0], camera.center[1] - o[1], camera.center[2] - o[2]], ..camera };
for (&pi, &rank) in scene.folded.order.iter().zip(&ranks) {
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(mapped) = map_panel(&local, &f.local) else { continue };
let Some(rings) = flat_rings(panel, camera.scale) else { continue };
let rings: Vec<Vec<[f64; 2]>> = rings.into_iter().map(|r| r.into_iter().map(|[u, v]| [u - o[0], v - o[1]]).collect()).collect();
let projected: Vec<Vec<[f64; 2]>> = rings
.iter()
.map(|r| match near {
@@ -480,9 +661,11 @@ pub fn render(scene: &Scene) -> Option<Image> {
.collect();
let fill = Fill {
mapped: &mapped,
rank: u16::try_from(rank + 1).unwrap_or(u16::MAX),
rank,
planes: &planes,
panel: u16::try_from(pi + 1).unwrap_or(u16::MAX),
print: scene.print,
origin: [o[0], o[1]],
inside,
outside,
};
@@ -491,5 +674,46 @@ pub fn render(scene: &Scene) -> Option<Image> {
Some(Image { width: camera.width, height: camera.height, pixels: target.color, panels: target.panel })
}
/// The plane each panel of `folded` lies in, as a number shared by the panels in one plane: their
/// normals parallel to within [`PARALLEL`] and their planes as far apart as rounding leaves them
/// ([`COPLANAR`] at their distance from [`Folded::origin`] for each hinge between them and the
/// base), so a parallel panel any measurable way behind another goes by depth. Each panel is
/// measured at the middle of its bounds in `blank`, by its pose about [`Folded::origin`]
/// ([`super::FoldedPanel::local`]), so where the blank lies in the document does not change the
/// planes. Past [`super::MAX_PANELS`] panels, one plane for all.
fn planes(folded: &Folded, blank: &Blank) -> Vec<u16> {
let n = folded.panels.len();
if n > super::MAX_PANELS {
return vec![0; n];
}
let length = |v: V3| dot(v, v).sqrt();
// Each plane's normal, a point of it, the size of the coordinates that point came from and the
// hinges that placed it.
let mut kinds: Vec<(V3, V3, f64, usize)> = vec![];
folded
.panels
.iter()
.enumerate()
.map(|(i, f)| {
let o = folded.origin;
let middle = blank.panels.get(i).and_then(|p| p.outline.bounds()).map_or([0.0; 3], |b| [b.center().x - o[0], -b.center().y - o[1], 0.0]);
let (normal, at) = (f.local.normal(), f.local.apply(middle));
let size = length(at).max(length(middle));
let same = |(m, p, s, d): &(V3, V3, f64, usize)| {
let c = [normal[1] * m[2] - normal[2] * m[1], normal[2] * m[0] - normal[0] * m[2], normal[0] * m[1] - normal[1] * m[0]];
let apart = dot(*m, [at[0] - p[0], at[1] - p[1], at[2] - p[2]]).abs();
// Saturating: a `Folded` built by a caller may carry any depth.
let hinges = f64::from(u32::try_from(f.depth.saturating_add(*d).saturating_add(1)).unwrap_or(u32::MAX));
length(c) <= PARALLEL && apart <= COPLANAR * hinges * (1.0 + size.max(*s))
};
let k = kinds.iter().position(same).unwrap_or_else(|| {
kinds.push((normal, at, size, f.depth));
kinds.len() - 1
});
u16::try_from(k).unwrap_or(u16::MAX)
})
.collect()
}
#[cfg(test)]
mod tests;
File diff suppressed because it is too large. Load diff
+203 -4
View File
@@ -13,7 +13,7 @@ fn poly(points: &[(f64, f64)], closed: bool) -> PathData {
}
fn line(kind: LineKind, points: &[(f64, f64)], closed: bool, key: u64) -> FoldLine {
FoldLine { path: poly(points, closed), kind, key }
FoldLine { path: poly(points, closed), kind, key, angle: None }
}
fn cut(points: &[(f64, f64)], key: u64) -> FoldLine {
@@ -188,7 +188,7 @@ fn a_round_tuck_flap_folds_like_any_panel() {
bp.curve_to(p(100.0, 10.0), p(80.0, 0.0), p(50.0, 0.0));
bp.curve_to(p(20.0, 0.0), p(0.0, 10.0), p(0.0, 40.0));
bp.close_path();
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1 }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let lines = vec![FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Cut, key: 1, angle: None }, crease((0.0, 40.0), (100.0, 40.0), 2)];
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(b[0].panels.len(), 2);
@@ -353,7 +353,7 @@ fn an_outline_drawn_twice_keeps_its_material() {
// The same two squares as the subpaths of one compound path.
let mut twice = poly(&square, true);
twice.subpaths.extend(poly(&square, true).subpaths);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1 }]);
let (b, issues) = check(&[FoldLine { path: twice, kind: LineKind::Cut, key: 1, angle: None }]);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(issues[0].keys, vec![1]);
assert_eq!(areas(&b[0]), vec![10_000_000]);
@@ -549,7 +549,7 @@ fn a_curved_crease_is_measured_at_its_farthest_point_from_its_line() {
bp.curve_to(p(10000.0 / 3.0 - off, 10000.0 / 3.0 + off), p(20000.0 / 3.0 + off, 20000.0 / 3.0 - off), p(10000.0, 10000.0));
let lines = vec![
cut(&[(0.0, 0.0), (10000.0, 0.0), (10000.0, 10000.0), (0.0, 10000.0)], 1),
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2 },
FoldLine { path: PathData::from_bezpath(&bp), kind: LineKind::Crease, key: 2, angle: None },
];
let (b, issues) = blanks(&lines, 10.0);
assert_eq!(codes(&issues), vec!["notStraight"], "{issues:?}");
@@ -1233,3 +1233,202 @@ fn a_partial_cut_takes_its_own_angle_and_a_hinge_its_longest_piece_s() {
assert_eq!(b[0].hinges.len(), 1);
assert_eq!(b[0].hinges[0].angle, 90.0);
}
#[test]
fn a_line_s_own_angle_takes_the_place_of_its_kind_s() {
let own = |kind, angle| FoldLine { path: poly(&[(0.0, 0.0), (1.0, 0.0)], false), kind, key: 1, angle };
assert_eq!(own(LineKind::Crease, Some(45.0)).fold_angle(), Some(45.0));
assert_eq!(own(LineKind::PartialCut, Some(30.0)).fold_angle(), Some(30.0));
assert_eq!(own(LineKind::Perforation, Some(-120.0)).fold_angle(), Some(-120.0));
assert_eq!(own(LineKind::PartialCut, None).fold_angle(), Some(-90.0));
// An angle that is not a number folds at the kind's; a cut never folds.
assert_eq!(own(LineKind::Crease, Some(f64::NAN)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::Crease, Some(f64::INFINITY)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::Crease, Some(f64::MAX)).fold_angle(), Some(90.0));
// Past -180 to 180, before rounding, as for an angle the engine stores.
assert_eq!(own(LineKind::Crease, Some(360.0)).fold_angle(), Some(90.0));
assert_eq!(own(LineKind::PartialCut, Some(-180.0000001)).fold_angle(), Some(-90.0));
assert_eq!(own(LineKind::Crease, Some(-180.0)).fold_angle(), Some(-180.0));
assert_eq!(own(LineKind::Cut, Some(45.0)).fold_angle(), None);
// To the millionth of a degree: closer to flat than that is flat.
assert_eq!(own(LineKind::Crease, Some(-179.99999998)).fold_angle(), Some(-180.0));
assert_eq!(own(LineKind::Crease, Some(179.9999994)).fold_angle(), Some(179.999999));
assert_eq!(own(LineKind::Crease, Some(-0.0000001)).fold_angle().map(f64::to_bits), Some(0.0f64.to_bits()));
}
#[test]
fn a_tray_wall_with_its_own_angle_stands_at_that_angle() {
let mut lines = tray();
// The wall below the base (y 90 to 120) folds at 45°, the others at 90°.
for l in lines.iter_mut().filter(|l| l.key == 12) {
l.angle = Some(45.0);
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
for (i, panel) in b.panels.iter().enumerate().filter(|(i, _)| *i != f.base) {
let n = f.panels[i].pose.normal();
// The cosine of the angle between the wall's print and the base's.
let lower = panel.outline.bounds().is_some_and(|r| r.y0 > 89.0);
let want = if lower { std::f64::consts::FRAC_1_SQRT_2 } else { 0.0 };
assert!((n[2] - want).abs() < 1e-9, "panel {i} ({lower}): {n:?}");
}
let h = b.hinges.iter().find(|h| h.keys == [12]).expect("the lower wall's hinge");
assert_eq!(h.angle, 45.0);
}
#[test]
fn a_hinge_takes_the_angle_of_its_longest_line_however_the_map_splits_it() {
// One hinge along y = 60: a 60 pt crease at 30° and a 40 pt crease at 120°. A crease that
// stops inside the panel above meets the first at x = 30, splitting it into two 30 pt pieces.
let mut lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1),
crease((0.0, 60.0), (60.0, 60.0), 2),
crease((60.0, 60.0), (100.0, 60.0), 3),
crease((30.0, 60.0), (30.0, 90.0), 4),
];
lines[1].angle = Some(30.0);
lines[2].angle = Some(120.0);
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
let hinges: Vec<_> = b[0].hinges.iter().filter(|h| h.keys.contains(&2)).collect();
assert_eq!(hinges.len(), 1, "{:?}", b[0].hinges);
assert_eq!((hinges[0].keys.clone(), hinges[0].angle), (vec![2, 3], 30.0));
}
#[test]
fn a_line_s_subpaths_on_top_of_each_other_count_once_toward_the_hinge_angle() {
// One hinge along y = 60: a 40 pt crease at 30° drawn as two subpaths on top of each other,
// and a 60 pt crease at 120°.
let mut twice = poly(&[(0.0, 60.0), (40.0, 60.0)], false);
twice.subpaths.extend(poly(&[(0.0, 60.0), (40.0, 60.0)], false).subpaths);
let lines = vec![
cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1),
FoldLine { path: twice, kind: LineKind::Crease, key: 2, angle: Some(30.0) },
FoldLine { path: poly(&[(40.0, 60.0), (100.0, 60.0)], false), kind: LineKind::Crease, key: 3, angle: Some(120.0) },
];
let (b, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["duplicate"], "{issues:?}");
assert_eq!(b[0].hinges.len(), 1, "{:?}", b[0].hinges);
assert_eq!(b[0].hinges[0].angle, 120.0);
}
#[test]
fn lines_of_equal_length_on_one_hinge_give_the_lowest_key_s_angle_in_any_order() {
let mut a = crease((0.0, 60.0), (50.0, 60.0), 5);
a.angle = Some(30.0);
let mut b = crease((50.0, 60.0), (100.0, 60.0), 3);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (100.0, 0.0), (100.0, 160.0), (0.0, 160.0)], 1);
for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline.clone(), b.clone(), a.clone()]] {
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
// The same along a diagonal, with the line of the higher key split in two by a crease that
// stops inside a panel: its pieces' lengths (2√2 and 10√2) add up to a little more than the
// other line's (12√2) in floating point.
let mut a = crease((0.0, 0.0), (12.0, 12.0), 5);
a.angle = Some(30.0);
let mut b = crease((12.0, 12.0), (24.0, 24.0), 3);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (24.0, 0.0), (24.0, 24.0), (0.0, 24.0)], 1);
let dangling = crease((2.0, 2.0), (6.0, 3.0), 4);
for lines in [vec![outline.clone(), a.clone(), b.clone(), dangling.clone()], vec![outline, dangling, b, a]] {
let (blanks, issues) = check(&lines);
assert_eq!(codes(&issues), vec!["danglingCrease"], "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
// A line 0.0005 pt longer than the other at 1,000,000 pt is longer, not a tie: its angle wins
// over the lower key's.
let mut a = crease((0.0, 60.0), (1_000_000.0, 60.0), 3);
a.angle = Some(30.0);
let end = 2_000_000.000_5;
let mut b = crease((1_000_000.0, 60.0), (end, 60.0), 5);
b.angle = Some(120.0);
let outline = cut(&[(0.0, 0.0), (end, 0.0), (end, 160.0), (0.0, 160.0)], 1);
for lines in [vec![outline.clone(), a.clone(), b.clone()], vec![outline, b, a]] {
let (blanks, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
assert_eq!(blanks[0].hinges.len(), 1, "{:?}", blanks[0].hinges);
assert_eq!(blanks[0].hinges[0].angle, 120.0, "{:?}", lines.iter().map(|l| l.key).collect::<Vec<_>>());
}
}
#[test]
fn a_loop_folded_about_another_panel_stacks_by_the_same_tree_wherever_it_lies() {
// A 100 × 100 blank cut into four 50 pt squares, its creases at 0° but for the one that closes
// the loop about the largest panel, at 0.001°: folded about a panel on that crease, the largest
// panel's tree places the panels up to 0.0009 pt from where the fold's own does. The same at the
// origin and 3,000,000 pt to the right.
let own_tree = |dx: f64| {
let lines = |closing: Option<u64>| {
let crease = |a: (f64, f64), b: (f64, f64), key: u64| {
let mut l = crease((a.0 + dx, a.1), (b.0 + dx, b.1), key);
l.angle = Some(if Some(key) == closing { 0.001 } else { 0.0 });
l
};
vec![
cut(&[(dx, 0.0), (100.0 + dx, 0.0), (100.0 + dx, 100.0), (dx, 100.0)], 1),
crease((50.0, 0.0), (50.0, 50.0), 2),
crease((50.0, 50.0), (50.0, 100.0), 3),
crease((0.0, 50.0), (50.0, 50.0), 4),
crease((50.0, 50.0), (100.0, 50.0), 5),
]
};
let (b, issues) = check(&lines(None));
assert!(issues.is_empty(), "{issues:?}");
let level = fold(&b[0], None, 1.0, TOL).expect("folds");
let closing = level.hinges.iter().position(|h| !h.tree).expect("a hinge closes the loop");
let key = b[0].hinges[closing].keys[0];
let (b, issues) = check(&lines(Some(key)));
assert!(issues.is_empty(), "{issues:?}");
let f = fold(&b[0], Some(b[0].hinges[closing].a), 1.0, TOL).expect("folds");
f.stack.root == f.base
};
assert!(own_tree(0.0), "the trees do not agree, so the fold's own tree");
assert!(own_tree(3_000_000.0), "far from the origin too");
}
#[test]
fn small_panels_far_from_the_middle_of_the_blank_stack_by_the_fold_s_own_tree() {
// A 2 × 2 grid of 5 pt squares at the end of a 1,000 pt strip, the largest panel, joined to the
// grid's right squares. Every crease is at 0° but the one between the two left squares, at a
// millionth of a degree: folded about a panel on it, the strip's tree leaves that crease out
// and places the other square at most 0.0000001 pt from where the fold's own tree does.
let mut lines = vec![
cut(&[(0.0, 0.0), (1010.0, 0.0), (1010.0, 10.0), (0.0, 10.0)], 1),
crease((5.0, 0.0), (5.0, 5.0), 2),
crease((5.0, 5.0), (5.0, 10.0), 3),
crease((0.0, 5.0), (5.0, 5.0), 4),
crease((5.0, 5.0), (10.0, 5.0), 5),
crease((10.0, 0.0), (10.0, 10.0), 6),
];
for l in &mut lines {
l.angle = Some(if l.key == 4 { 0.000001 } else { 0.0 });
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let h = b[0].hinges.iter().find(|h| h.keys == [4]).expect("the left squares' hinge");
let f = fold(&b[0], Some(h.a), 1.0, TOL).expect("folds");
assert!(f.hinges.iter().zip(&b[0].hinges).any(|(fh, h)| fh.tree && h.keys == [4]));
assert_eq!(f.stack.root, f.base, "the trees place a panel at different turns");
}
#[test]
fn a_negative_angle_folds_a_crease_toward_the_print() {
let mut lines = two_panels(LineKind::Crease, 0, false, false);
for l in lines.iter_mut().filter(|l| l.key == 2) {
l.angle = Some(-90.0);
}
let (b, issues) = check(&lines);
assert!(issues.is_empty(), "{issues:?}");
let b = &b[0];
let f = fold(b, None, 1.0, TOL).expect("folds");
let child = 1 - f.base;
let placed = f.panels[child].pose.apply(flat_center(b, child));
assert!(placed[2] > 0.0, "in front of the print: {placed:?}");
}
+79 -8
View File
@@ -1,8 +1,10 @@
//! Packaging Tools' submenu (Object › Plug-ins › Packaging Tools) and its Fold Lines panel. The
//! panel lists the fold line roles, each with its swatch's chip and how many of the selected objects
//! have it (of the whole document while nothing is selected); clicking a role gives the selected
//! paths that role (`addon.packaging.setRole`). Its menu's Role Swatches… picks the swatch that
//! carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! paths that role (`addon.packaging.setRole`). While the selection holds lines that fold, its Fold
//! Angle field shows the angle they fold at and sets it (`addon.packaging.setFoldAngle`, as Set Fold
//! Angle… in the submenu does), and Reset takes their own angles away. Its menu's Role Swatches…
//! picks the swatch that carries a role (`addon.packaging.setRoleSwatch`). Its Check button, like the Check Fold Lines menu
//! item, checks the fold lines (`addon.packaging.check`) and lists the issues found under it, each
//! with a Select button; each document's list is kept until that document changes. Its Fold Preview
//! button, like the Fold Preview menu item, shows the blank folded in 3D ([`preview`], `ui.foldPreview`).
@@ -27,6 +29,18 @@ pub const SET_ROLE: &str = "addon.packaging.setRole";
pub const SET_ROLE_SWATCH: &str = "addon.packaging.setRoleSwatch";
/// The command that checks the fold lines.
pub const CHECK: &str = "addon.packaging.check";
/// The command that sets or resets the fold angle of fold lines.
pub const SET_FOLD_ANGLE: &str = "addon.packaging.setFoldAngle";
/// The fold angles `addon.packaging.setFoldAngle` takes, in degrees.
pub const FOLD_ANGLES: std::ops::RangeInclusive<f64> = -180.0..=180.0;
/// The places a fold angle field shows `angle` to: all it has, so an angle such as 179.9999999° is
/// not shown as 180°, which typing 180 into the field would then leave unchanged; at least one, the
/// place the field's fine steps (a tenth of a degree) round to.
pub fn angle_places(angle: Option<f64>) -> usize {
// f64's Display is the shortest text that reads back as the same number, without an exponent.
angle.map_or(0, |a| format!("{a}").split_once('.').map_or(0, |(_, places)| places.len())).max(1)
}
/// The command that shows the Fold Preview window.
pub const PREVIEW: &str = "ui.foldPreview";
/// The roles by name, as `addon.packaging.setRole` and Role Swatches… take them.
@@ -50,6 +64,7 @@ pub fn menu() -> Vec<Item> {
make("Make Perforation Line", "perforation"),
Item::Sep,
Item::Cmd("Check Fold Lines", CHECK, Value::Null),
Item::Cmd("Set Fold Angle…", SET_FOLD_ANGLE, Value::Null),
Item::Sep,
Item::Cmd("Fold Preview", PREVIEW, json!({})),
]
@@ -211,15 +226,23 @@ struct Rows {
/// What they were read for: the document, its revision and its selection.
key: Option<(u64, u64, Vec<u64>)>,
rows: Vec<Row>,
/// Whether the rows count the selection (not the whole document).
selection: bool,
/// How many lines that fold (Crease, Partial Cut, Perforation) Set Fold Angle can change.
fold_lines: u64,
/// The angle they all fold at (`None`: they differ, or there are none).
angle: Option<f64>,
/// How many of them hold a stored angle, readable or not: what Reset takes away.
stored_angles: u64,
}
/// The rows for the active document as it is now, read again only when it changed.
fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Row> {
let Some(st) = app.session.active() else { return vec![] };
fn read_rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Rows {
let Some(st) = app.session.active() else { return Rows::default() };
let key = (st.uid, st.revision, st.selection.objects.iter().map(|id| id.0).collect::<Vec<_>>());
let mut kept: Rows = pstate(ctx, STATE);
if kept.key.as_ref() == Some(&key) {
return kept.rows;
return kept;
}
let answer = app.session.execute("addon.packaging.roles", &json!({})).unwrap_or(Value::Null);
let d = app.session.active().map(|st| st.doc.clone());
@@ -228,9 +251,55 @@ fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Row> {
let paint = d.as_ref().and_then(|d| d.swatch(&swatch)).map(|s| s.paint.clone());
Some((r["role"].as_str()?.to_string(), swatch, paint, r["count"].as_u64()?))
};
kept = Rows { key: Some(key), rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect() };
kept = Rows {
key: Some(key),
rows: answer["roles"].as_array().into_iter().flatten().filter_map(row).collect(),
selection: answer["scope"] == "selection",
fold_lines: answer["foldLines"].as_u64().unwrap_or(0),
angle: answer["foldAngle"].as_f64(),
stored_angles: answer["storedAngles"].as_u64().unwrap_or(0),
};
set_pstate(ctx, STATE, kept.clone());
kept.rows
kept
}
/// The role rows for the active document as it is now.
fn rows(app: &mut VectorcraftApp, ctx: &egui::Context) -> Vec<Row> {
read_rows(app, ctx).rows
}
/// The fields Set Fold Angle… opens with: `addon.packaging.setFoldAngle`'s options on the angle
/// the selected lines that it can change all fold at, else 90°. The command's reason while it
/// can't change any.
pub(crate) fn dialog_fields(app: &VectorcraftApp) -> Result<Value, String> {
let command = vectorcraft_engine::find_command(SET_FOLD_ANGLE).ok_or_else(|| format!("unknown command {SET_FOLD_ANGLE}"))?;
(command.enabled)(&app.session)?;
let angle = vectorcraft_engine::cmd::selection_fold_angles(&app.session).angle.unwrap_or(90.0);
Ok(json!({ "__command": SET_FOLD_ANGLE, "__label": "Set Fold Angle", "angle": angle }))
}
/// The Fold Angle row, while the selection holds lines that fold and can be changed: the angle
/// they all fold at (empty when they differ), which sets theirs when changed, and Reset, which
/// takes away the angles of their own.
fn show_angle(app: &mut VectorcraftApp, ui: &mut Ui, kept: &Rows) {
if !kept.selection || kept.fold_lines == 0 {
return;
}
let mut call = None;
ui.horizontal(|ui| {
widgets::field_label(ui, tl!("Fold Angle"));
if let Some(a) = widgets::mixed_field_within(ui, "fold-angle", kept.angle, "°", angle_places(kept.angle), 64.0, FOLD_ANGLES) {
call = Some(json!({ "angle": a }));
}
if ui.add_enabled_ui(kept.stored_angles > 0, |ui| widgets::flat_button_fit(ui, tl!("Reset"), 56.0)).inner.clicked() {
call = Some(json!({ "reset": true }));
}
});
if let Some(p) = call
&& let Err(e) = app.run(SET_FOLD_ANGLE, p)
{
app.status(e);
}
}
pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
@@ -244,7 +313,8 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
ui.add_space(4.0);
}
let mut picked = None;
for (role, swatch, paint, count) in rows(app, ui.ctx()) {
let kept = read_rows(app, ui.ctx());
for (role, swatch, paint, count) in kept.rows.iter().cloned() {
let label = ROLES.iter().find(|(_, id)| *id == role).map_or(role.as_str(), |(l, _)| *l);
let clicked = ui
.add_enabled_ui(selected, |ui| {
@@ -267,6 +337,7 @@ pub fn show(app: &mut VectorcraftApp, ui: &mut Ui) {
{
app.status(e);
}
show_angle(app, ui, &kept);
show_check(app, ui);
}
@@ -470,6 +470,8 @@ fn the_status_line_reports_open_joints_crossing_panels_and_other_blanks() {
order: vec![],
hinges: vec![hinge(true, true, 0.0), hinge(false, false, 12.34), hinge(false, false, 3.0), hinge(false, true, 0.05)],
collisions: vec![(0, 1)],
stack: Default::default(),
origin: [0.0; 3],
};
let lines = status(3, Some((&Blank::default(), &f)), true);
assert_eq!(
+157 -2
View File
@@ -1,7 +1,7 @@
use serde_json::json;
use vectorcraft_engine::Session;
use super::{CHECK, ID, ROLES, SET_ROLE, SET_ROLE_SWATCH, show};
use super::{CHECK, ID, ROLES, SET_FOLD_ANGLE, SET_ROLE, SET_ROLE_SWATCH, show};
use crate::tests_labels::painted_text;
use crate::{VectorcraftApp, menus};
@@ -274,12 +274,167 @@ fn every_issue_message_translates_in_every_complete_message_catalog() {
"ca", "nl", "da",
] {
let lang = crate::i18n::Lang::from_code(code).unwrap();
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0"]) {
let no_fold_line = "select a crease, partial cut or perforation line that is neither locked nor hidden";
for m in ISSUE_MESSAGES.into_iter().chain(["Panels: 3, hinges: 2, errors: 1, warnings: 0", no_fold_line]) {
assert_ne!(crate::i18n::message(lang, m), m, "{code}: {m}");
}
}
}
#[test]
fn set_fold_angle_opens_its_dialog_on_the_selected_lines_angle() {
let (mut app, a, b) = app();
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap();
let entries = menus::menu_entries(&app);
let item = entries.iter().find(|e| e.path == ["Object", "Plug-ins", "Packaging Tools"] && e.label == "Set Fold Angle…").expect("listed");
assert_eq!(item.command.as_deref(), Some(SET_FOLD_ANGLE));
let opened = |app: &mut VectorcraftApp| {
let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params);
menus::invoke(app, &target, p);
let d = app.ui.dialog.take().expect("a dialog");
assert_eq!((d.kind.as_str(), d.str("__command")), ("command", SET_FOLD_ANGLE.to_string()));
d.fields["angle"].as_f64()
};
app.run("select.set", json!({"ids": [a]})).unwrap();
assert_eq!(opened(&mut app), Some(90.0), "a crease folds at 90° until it has an angle of its own");
app.run(SET_FOLD_ANGLE, json!({"angle": 45})).unwrap();
assert_eq!(opened(&mut app), Some(45.0));
// The cut line does not fold, so the crease's angle is still the one shown.
app.run("select.set", json!({"ids": [a, b]})).unwrap();
assert_eq!(opened(&mut app), Some(45.0));
// Lines that differ open on 90°.
let c = app.run("shape.rectangle", json!({"x": 180, "y": 20, "width": 40, "height": 40})).unwrap()["id"].as_u64().unwrap();
app.run(SET_ROLE, json!({"role": "partialCut", "ids": [c]})).unwrap();
app.run("select.set", json!({"ids": [a, c]})).unwrap();
assert_eq!(opened(&mut app), Some(90.0));
// With only a cut line selected there is nothing to set: no dialog opens.
app.run("select.set", json!({"ids": [b]})).unwrap();
let (target, p) = menus::click_target(&item.label, SET_FOLD_ANGLE, &item.params);
menus::invoke(&mut app, &target, p);
assert!(app.ui.dialog.is_none());
// ui.menuDialog gives the command's reason.
let e = app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap_err();
assert!(e.contains("select a crease, partial cut or perforation line"), "{e}");
app.run("select.set", json!({"ids": [a]})).unwrap();
app.run("ui.menuDialog", json!({"command": SET_FOLD_ANGLE})).unwrap();
assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(45.0));
// The options dialog opened with an angle keeps it.
menus::invoke(&mut app, "ui.paramDialog", json!({"command": SET_FOLD_ANGLE, "label": "Set Fold Angle", "params": {"angle": 30}}));
assert_eq!(app.ui.dialog.take().expect("a dialog").fields["angle"].as_f64(), Some(30.0));
}
/// Set Fold Angle… keeps the angle typed into its dialog within -180° to 180°, so OK applies the
/// nearest end instead of closing on an angle the command refuses.
#[test]
fn set_fold_angle_s_dialog_keeps_the_angle_within_its_range() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let (mut app, a, _) = app();
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
app.run("select.set", json!({"ids": [a]})).unwrap();
menus::invoke(&mut app, SET_FOLD_ANGLE, json!({}));
assert!(app.ui.dialog.is_some(), "the dialog opens");
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1100.0, 900.0)).build_ui_state(
move |ui, app: &mut VectorcraftApp| {
if !std::mem::replace(&mut fonts, true) {
crate::theme::install_fonts(ui.ctx());
return;
}
crate::dialogs::show(app, ui.ctx());
},
app,
);
h.run_steps(5);
let all = egui::Modifiers { ctrl: true, command: true, ..Default::default() };
h.get_by_role_and_label(Role::TextInput, "Angle:").focus();
h.run_steps(2);
h.key_press_modifiers(all, egui::Key::A);
h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("181");
h.run_steps(2);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(180.0));
crate::dialogs::confirm(h.state_mut()).unwrap();
let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}");
// An angle typed with more places than the field shows is kept as typed, as the panel keeps it.
menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({}));
h.run_steps(3);
h.get_by_role_and_label(Role::TextInput, "Angle:").focus();
h.run_steps(2);
h.key_press_modifiers(all, egui::Key::A);
h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("179.9999");
h.run_steps(2);
h.key_press(egui::Key::Tab);
h.run_steps(3);
assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(179.9999));
crate::dialogs::confirm(h.state_mut()).unwrap();
let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!(r["foldAngle"].as_f64(), Some(179.9999), "{r}");
// Opened on an angle with more places than that, the dialog shows them all, so typing 180 sets 180.
h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 179.999999, "ids": [a]})).unwrap();
menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({}));
h.run_steps(3);
h.get_by_role_and_label(Role::TextInput, "Angle:").focus();
h.run_steps(2);
h.key_press_modifiers(all, egui::Key::A);
h.get_by_role_and_label(Role::TextInput, "Angle:").type_text("180");
h.run_steps(2);
h.key_press(egui::Key::Tab);
h.run_steps(3);
crate::dialogs::confirm(h.state_mut()).unwrap();
let r = h.state_mut().session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!(r["foldAngle"].as_f64(), Some(180.0), "{r}");
// A fine step from a whole angle steps a tenth of a degree.
h.state_mut().run(SET_FOLD_ANGLE, json!({"angle": 90, "ids": [a]})).unwrap();
menus::invoke(h.state_mut(), SET_FOLD_ANGLE, json!({}));
h.run_steps(3);
h.get_by_role_and_label(Role::TextInput, "Angle:").focus();
h.run_steps(2);
h.key_press_modifiers(all, egui::Key::ArrowUp);
h.run_steps(3);
assert_eq!(h.state().ui.dialog.as_ref().expect("still open").fields["angle"].as_f64(), Some(90.1));
}
#[test]
fn a_fold_angle_field_shows_every_place_the_angle_has() {
use super::angle_places;
assert_eq!([None, Some(90.0), Some(-135.5), Some(179.9999999), Some(1e-12)].map(angle_places), [1, 1, 1, 7, 12]);
}
#[test]
fn the_panel_shows_and_resets_the_selected_lines_fold_angle() {
let (mut app, a, b) = app();
app.run(SET_ROLE, json!({"role": "crease", "ids": [a]})).unwrap();
app.run(SET_ROLE, json!({"role": "cut", "ids": [b]})).unwrap();
app.run("select.set", json!({"ids": [b]})).unwrap();
let text = painted_text(&mut app, show);
assert!(!text.contains("Fold Angle"), "a cut line has no fold angle: {text}");
app.run("select.set", json!({"ids": [a]})).unwrap();
app.run(SET_FOLD_ANGLE, json!({"angle": 135})).unwrap();
let text = painted_text(&mut app, show);
assert!(text.contains("Fold Angle") && text.contains("135"), "{text}");
click_row(&mut app, "Reset");
let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64()), (Some(90.0), Some(0)), "{r}");
// Stored text that is not an angle: the field shows the role's angle, and Reset removes the text.
app.session
.edit("Test", |d, _| {
if let Some(n) = d.node_mut(vectorcraft_doc::NodeId(a)) {
n.edit_attrs(|at| at.data.push(("vc-fold-angle".into(), "wide".into())));
}
Ok(())
})
.unwrap();
let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!((r["foldAngle"].as_f64(), r["ownAngles"].as_u64(), r["storedAngles"].as_u64()), (Some(90.0), Some(0), Some(1)), "{r}");
click_row(&mut app, "Reset");
let r = app.session.execute("addon.packaging.roles", &json!({"ids": [a]})).unwrap();
assert_eq!(r["storedAngles"].as_u64(), Some(0), "{r}");
}
#[test]
fn the_panel_without_a_document_asks_for_one() {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
+9
View File
@@ -163,6 +163,15 @@ pub(super) fn length_range(command: &str, key: &str) -> Option<std::ops::RangeIn
}
}
/// The range of a number parameter (not a distance) of the commands this dialog edits, where the
/// command has one: the field keeps what is typed within it.
pub(super) fn number_range(command: &str, key: &str) -> Option<std::ops::RangeInclusive<f64>> {
match (command, key) {
(crate::addons::packaging::SET_FOLD_ANGLE, "angle") => Some(crate::addons::packaging::FOLD_ANGLES),
_ => None,
}
}
/// The order the fields of the commands this dialog edits come in, where the order of their
/// names isn't it (the rest follow, by name).
fn order(command: &str) -> &'static [&'static str] {
+8
View File
@@ -510,6 +510,14 @@ pub(super) fn param_fields(
changed = true;
}
}
Value::Number(n) if let Some(range) = super::command::number_range(&d.str("__command"), &k) => {
// Kept within the range as typed, and shown to the places a fold angle keeps.
let places = crate::addons::packaging::angle_places(n.as_f64());
if let Some(x) = crate::widgets::mixed_field_within(ui, ("fx-num", &k), n.as_f64(), "", places, 140.0, range) {
d.fields.insert(k.clone(), typed_number(x));
changed = true;
}
}
Value::Number(n) => {
// A resolution (Object › Rasterize's `ppi`) shows its unit in the UI language.
let suffix = if k == "ppi" { crate::i18n::fill_once(tl!("{n} ppi"), &[("n", "")]) } else { String::new() };
+5
View File
@@ -7653,6 +7653,11 @@ breakText Glyphs Глифи
No objects are selected. Няма избрани обекти.
Open a document to mark its fold lines. Отворете документ, за да отбележите линиите му на сгъване.
Remove Fold Line Role Премахни вида на линията
Fold Angle Ъгъл на сгъване
Set Fold Angle… Задай ъгъл на сгъване…
Set Fold Angle Задай ъгъл на сгъване
Reset Fold Angle Нулирай ъгъла на сгъване
@msg select a crease, partial cut or perforation line that is neither locked nor hidden изберете линия за биговане, частично рязане или перфорация, която не е заключена или скрита
Check Провери
Check Fold Lines Провери линиите на сгъване
@msg No cut lines are in the selection. В селекцията няма линии за рязане.
Can't render this file because it is too large.
+5
View File
@@ -7708,6 +7708,11 @@ shape Open Otvoren
No objects are selected. Nijedan objekat nije odabran.
Open a document to mark its fold lines. Otvorite dokument da označite njegove linije savijanja.
Remove Fold Line Role Ukloni vrstu linije
Fold Angle Ugao savijanja
Set Fold Angle… Postavi ugao savijanja…
Set Fold Angle Postavi ugao savijanja
Reset Fold Angle Poništi ugao savijanja
@msg select a crease, partial cut or perforation line that is neither locked nor hidden odaberite liniju bigovanja, djelimičnog rezanja ili perforacije koja nije zaključana ni skrivena
Check Provjeri
Check Fold Lines Provjeri linije savijanja
@msg No cut lines are in the selection. U odabiru nema linija rezanja.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -8610,6 +8610,11 @@ breakText Glyphs Glifs
No objects are selected. No hi ha cap objecte seleccionat.
Open a document to mark its fold lines. Obre un document per marcar-ne les línies de plegat.
Remove Fold Line Role Elimina el tipus de línia
Fold Angle Angle de plegat
Set Fold Angle… Defineix l’angle de plegat…
Set Fold Angle Defineix l’angle de plegat
Reset Fold Angle Restableix l’angle de plegat
@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccioneu una línia d’hendit, de tall parcial o de perforació que no estigui bloquejada ni amagada
Check Comprova
Check Fold Lines Comprova les línies de plegat
@msg No cut lines are in the selection. No hi ha cap línia de tall a la selecció.
Can't render this file because it is too large.
+5
View File
@@ -10406,6 +10406,11 @@ breakText Glyphs Glyfy
No objects are selected. Nejsou vybrány žádné objekty.
Open a document to mark its fold lines. Otevřete dokument, abyste označili jeho linie skladu.
Remove Fold Line Role Odstranit typ linie
Fold Angle Úhel skladu
Set Fold Angle… Nastavit úhel skladu…
Set Fold Angle Nastavit úhel skladu
Reset Fold Angle Obnovit úhel skladu
@msg select a crease, partial cut or perforation line that is neither locked nor hidden vyberte linii bigu, částečného řezu nebo perforace, která není zamčená ani skrytá
Tap Krátký stisk
Clear Hold Vymazat podržení
Hold Shortcuts Zkratky podržením
Can't render this file because it is too large.
+5
View File
@@ -10498,6 +10498,11 @@ breakText Glyphs Glyffer
No objects are selected. Ingen objekter er markeret.
Open a document to mark its fold lines. Åbn et dokument for at markere dets foldelinjer.
Remove Fold Line Role Fjern linjetype
Fold Angle Foldevinkel
Set Fold Angle… Angiv foldevinkel…
Set Fold Angle Angiv foldevinkel
Reset Fold Angle Nulstil foldevinkel
@msg select a crease, partial cut or perforation line that is neither locked nor hidden markér en rillelinje, delvis skærelinje eller perforeringslinje, der hverken er låst eller skjult
Check Kontrollér
Check Fold Lines Kontrollér foldelinjer
@msg No cut lines are in the selection. Der er ingen skærelinjer i markeringen.
Can't render this file because it is too large.
+5
View File
@@ -10019,6 +10019,11 @@ breakText Glyphs Glyphen
No objects are selected. Es sind keine Objekte ausgewählt.
Open a document to mark its fold lines. Öffnen Sie ein Dokument, um seine Faltlinien festzulegen.
Remove Fold Line Role Linienart entfernen
Fold Angle Faltwinkel
Set Fold Angle… Faltwinkel festlegen…
Set Fold Angle Faltwinkel festlegen
Reset Fold Angle Faltwinkel zurücksetzen
@msg select a crease, partial cut or perforation line that is neither locked nor hidden Wählen Sie eine Rill-, Teilschnitt- oder Perforationslinie aus, die weder gesperrt noch ausgeblendet ist
Tap Kurz drücken
Clear Hold Halten löschen
Hold Shortcuts Halte-Tastaturbefehle
Can't render this file because it is too large.
+5
View File
@@ -8584,6 +8584,11 @@ breakText Glyphs Γλύφοι
No objects are selected. Δεν έχουν επιλεγεί αντικείμενα.
Open a document to mark its fold lines. Ανοίξτε ένα έγγραφο για να σημειώσετε τις γραμμές δίπλωσής του.
Remove Fold Line Role Αφαίρεση τύπου γραμμής
Fold Angle Γωνία δίπλωσης
Set Fold Angle… Ορισμός γωνίας δίπλωσης…
Set Fold Angle Ορισμός γωνίας δίπλωσης
Reset Fold Angle Επαναφορά γωνίας δίπλωσης
@msg select a crease, partial cut or perforation line that is neither locked nor hidden επιλέξτε μια γραμμή πτύχωσης, μερικής κοπής ή διάτρησης που δεν είναι κλειδωμένη ούτε κρυφή
Check Έλεγχος
Check Fold Lines Έλεγχος γραμμών δίπλωσης
@msg No cut lines are in the selection. Η επιλογή δεν περιέχει γραμμές κοπής.
Can't render this file because it is too large.
+5
View File
@@ -10330,6 +10330,11 @@ breakText Glyphs Glifos
No objects are selected. No hay objetos seleccionados.
Open a document to mark its fold lines. Abre un documento para marcar sus líneas de plegado.
Remove Fold Line Role Quitar tipo de línea
Fold Angle Ángulo de plegado
Set Fold Angle… Definir ángulo de plegado…
Set Fold Angle Definir ángulo de plegado
Reset Fold Angle Restablecer ángulo de plegado
@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleccione una línea de hendido, de corte parcial o de perforación que no esté bloqueada ni oculta
Check Comprobar
Check Fold Lines Comprobar líneas de plegado
@msg No cut lines are in the selection. No hay líneas de corte en la selección.
Can't render this file because it is too large.
+5
View File
@@ -8667,6 +8667,11 @@ breakText Glyphs Merkit
No objects are selected. Objekteja ei ole valittu.
Open a document to mark its fold lines. Avaa asiakirja, niin voit merkitä sen taittoviivat.
Remove Fold Line Role Poista viivatyyppi
Fold Angle Taittokulma
Set Fold Angle… Aseta taittokulma…
Set Fold Angle Aseta taittokulma
Reset Fold Angle Palauta taittokulma
@msg select a crease, partial cut or perforation line that is neither locked nor hidden valitse nuuttausviiva, osittainen leikkausviiva tai rei’itysviiva, joka ei ole lukittu eikä piilotettu
Check Tarkista
Check Fold Lines Tarkista taittoviivat
@msg No cut lines are in the selection. Valinnassa ei ole leikkausviivoja.
Can't render this file because it contains an unexpected character in line 2 and column 73.
+5
View File
@@ -10391,6 +10391,11 @@ breakText Glyphs Glyphes
No objects are selected. Aucun objet n’est sélectionné.
Open a document to mark its fold lines. Ouvrez un document pour marquer ses lignes de pliage.
Remove Fold Line Role Supprimer le type de ligne
Fold Angle Angle de pliage
Set Fold Angle… Définir l’angle de pliage…
Set Fold Angle Définir l’angle de pliage
Reset Fold Angle Réinitialiser l’angle de pliage
@msg select a crease, partial cut or perforation line that is neither locked nor hidden sélectionnez une ligne de rainage, de découpe partielle ou de perforation qui n’est ni verrouillée ni masquée
Tap Appui bref
Clear Hold Effacer le maintien
Hold Shortcuts Raccourcis de maintien
Can't render this file because it is too large.
+5
View File
@@ -5396,6 +5396,11 @@ swatch [Registration] [રજિસ્ટ્રેશન]
No objects are selected. કોઈ ઑબ્જેક્ટ પસંદ કરેલ નથી.
Open a document to mark its fold lines. તેની ફોલ્ડ લાઇન્સ ચિહ્નિત કરવા દસ્તાવેજ ખોલો.
Remove Fold Line Role લાઇન પ્રકાર દૂર કરો
Fold Angle ફોલ્ડ ખૂણો
Set Fold Angle… ફોલ્ડ ખૂણો સેટ કરો…
Set Fold Angle ફોલ્ડ ખૂણો સેટ કરો
Reset Fold Angle ફોલ્ડ ખૂણો રીસેટ કરો
@msg select a crease, partial cut or perforation line that is neither locked nor hidden એવી ક્રીઝ, આંશિક કટ અથવા પર્ફોરેશન લાઇન પસંદ કરો જે લૉક કે છુપાયેલી ન હોય
Check ચેક કરો
Check Fold Lines ફોલ્ડ લાઇન્સ ચેક કરો
@msg No cut lines are in the selection. પસંદગીમાં કોઈ કટ લાઇન નથી.
Can't render this file because it contains an unexpected character in line 72 and column 5.
+5
View File
@@ -10012,6 +10012,11 @@ theme Appearance अपीयरेंस
No objects are selected. कोई ऑब्जेक्ट सिलेक्ट नहीं है।
Open a document to mark its fold lines. फ़ोल्ड लाइनें मार्क करने के लिए कोई डॉक्यूमेंट ओपन करें।
Remove Fold Line Role लाइन प्रकार हटाएँ
Fold Angle फ़ोल्ड कोण
Set Fold Angle… फ़ोल्ड कोण सेट करें…
Set Fold Angle फ़ोल्ड कोण सेट करें
Reset Fold Angle फ़ोल्ड कोण रीसेट करें
@msg select a crease, partial cut or perforation line that is neither locked nor hidden ऐसी क्रीज़, आंशिक कट या परफ़ोरेशन लाइन चुनें जो न लॉक हो न छिपी हो
Tap जल्दी दबाना
Clear Hold होल्ड साफ़ करें
Hold Shortcuts होल्ड शॉर्टकट
Can't render this file because it is too large.
+5
View File
@@ -10394,6 +10394,11 @@ breakText Glyphs Glifák
No objects are selected. Nincs kijelölt objektum.
Open a document to mark its fold lines. Nyiss meg egy dokumentumot a hajtásvonalai megjelöléséhez.
Remove Fold Line Role Vonaltípus eltávolítása
Fold Angle Hajtásszög
Set Fold Angle… Hajtásszög beállítása…
Set Fold Angle Hajtásszög beállítása
Reset Fold Angle Hajtásszög visszaállítása
@msg select a crease, partial cut or perforation line that is neither locked nor hidden jelöljön ki egy bigvonalat, részleges vágóvonalat vagy perforációs vonalat, amely nincs zárolva és nincs elrejtve
Tap Rövid lenyomás
Clear Hold Nyomva tartás törlése
Hold Shortcuts Nyomva tartásos billentyűparancsok
Can't render this file because it is too large.
+5
View File
@@ -7668,6 +7668,11 @@ breakText Glyphs Glif
No objects are selected. Tidak ada objek yang dipilih.
Open a document to mark its fold lines. Buka dokumen untuk menandai garis lipatnya.
Remove Fold Line Role Hapus jenis garis
Fold Angle Sudut lipat
Set Fold Angle… Atur sudut lipat…
Set Fold Angle Atur sudut lipat
Reset Fold Angle Atur ulang sudut lipat
@msg select a crease, partial cut or perforation line that is neither locked nor hidden pilih garis lekuk, garis potong sebagian, atau garis perforasi yang tidak terkunci dan tidak tersembunyi
Check Periksa
Check Fold Lines Periksa garis lipat
@msg No cut lines are in the selection. Tidak ada garis potong dalam seleksi.
Can't render this file because it contains an unexpected character in line 2563 and column 5.
+5
View File
@@ -10052,6 +10052,11 @@ breakText Glyphs Glifi
No objects are selected. Nessun oggetto selezionato.
Open a document to mark its fold lines. Apri un documento per segnarne le linee di piega.
Remove Fold Line Role Rimuovi tipo di linea
Fold Angle Angolo di piega
Set Fold Angle… Imposta angolo di piega…
Set Fold Angle Imposta angolo di piega
Reset Fold Angle Reimposta angolo di piega
@msg select a crease, partial cut or perforation line that is neither locked nor hidden seleziona una linea di cordonatura, di taglio parziale o di perforazione che non sia bloccata né nascosta
Tap Pressione breve
Clear Hold Cancella pressione prolungata
Hold Shortcuts Scorciatoie a pressione prolungata
Can't render this file because it is too large.
+5
View File
@@ -10116,6 +10116,11 @@ breakText Glyphs 字形
No objects are selected. オブジェクトが選択されていません。
Open a document to mark its fold lines. ドキュメントを開くと折り線を設定できます。
Remove Fold Line Role 線種を解除
Fold Angle 折り角度
Set Fold Angle… 折り角度を設定…
Set Fold Angle 折り角度を設定
Reset Fold Angle 折り角度をリセット
@msg select a crease, partial cut or perforation line that is neither locked nor hidden ロックも非表示もされていない筋入れ線、半抜き線またはミシン目線を選択してください
Tap 短押し
Clear Hold 長押しを消去
Hold Shortcuts 長押しショートカット
Can't render this file because it is too large.
+5
View File
@@ -10746,6 +10746,11 @@ font-script Japanese იაპონური
No objects are selected. ობიექტები არ არის მონიშნული.
Open a document to mark its fold lines. გახსენით დოკუმენტი მისი მოკეცვის ხაზების მარკირებისთვის.
Remove Fold Line Role ხაზის ტიპის მოხსნა
Fold Angle მოკეცვის კუთხე
Set Fold Angle… მოკეცვის კუთხის დაყენება…
Set Fold Angle მოკეცვის კუთხის დაყენება
Reset Fold Angle მოკეცვის კუთხის ჩამოყრა
@msg select a crease, partial cut or perforation line that is neither locked nor hidden მონიშნეთ ბიგის, ნაწილობრივი ჭრის ან პერფორაციის ხაზი, რომელიც არც ჩაკეტილია და არც დამალული
Check შემოწმება
Check Fold Lines მოკეცვის ხაზების შემოწმება
@msg No cut lines are in the selection. მონიშვნაში ჭრის ხაზები არ არის.
Can't render this file because it is too large.
+5
View File
@@ -10015,6 +10015,11 @@ breakText Glyphs 글리프
No objects are selected. 선택한 개체가 없습니다.
Open a document to mark its fold lines. 접는 선을 지정하려면 문서를 여세요.
Remove Fold Line Role 선 종류 제거
Fold Angle 접는 각도
Set Fold Angle… 접는 각도 설정…
Set Fold Angle 접는 각도 설정
Reset Fold Angle 접는 각도 재설정
@msg select a crease, partial cut or perforation line that is neither locked nor hidden 잠기거나 숨겨지지 않은 오시선, 하프 컷 선 또는 미싱선을 선택하세요
Tap 짧게 누르기
Clear Hold 길게 누르기 지우기
Hold Shortcuts 길게 누르기 단축키
Can't render this file because it is too large.
+5
View File
@@ -10443,6 +10443,11 @@ breakText Glyphs Glyphs
No objects are selected. Er zijn geen objecten geselecteerd.
Open a document to mark its fold lines. Open een document om de vouwlijnen te markeren.
Remove Fold Line Role Lijnsoort verwijderen
Fold Angle Vouwhoek
Set Fold Angle… Vouwhoek instellen…
Set Fold Angle Vouwhoek instellen
Reset Fold Angle Vouwhoek herstellen
@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecteer een rillijn, halve snijlijn of perforatielijn die niet vergrendeld of verborgen is
Tap Kort drukken
Clear Hold Vasthouden wissen
Hold Shortcuts Vasthoudsneltoetsen
Can't render this file because it is too large.
+5
View File
@@ -10269,6 +10269,11 @@ breakText Glyphs Glify
No objects are selected. Nie zaznaczono żadnych obiektów.
Open a document to mark its fold lines. Otwórz dokument, aby oznaczyć jego linie zgięcia.
Remove Fold Line Role Usuń rodzaj linii
Fold Angle Kąt zgięcia
Set Fold Angle… Ustaw kąt zgięcia…
Set Fold Angle Ustaw kąt zgięcia
Reset Fold Angle Resetuj kąt zgięcia
@msg select a crease, partial cut or perforation line that is neither locked nor hidden zaznacz linię bigowania, nacięcia lub perforacji, która nie jest zablokowana ani ukryta
Tap Krótkie naciśnięcie
Clear Hold Wyczyść przytrzymanie
Hold Shortcuts Skróty przytrzymania
Can't render this file because it is too large.
+5
View File
@@ -10478,6 +10478,11 @@ swatch Yellow Green Verde-amarelado
No objects are selected. Nenhum objeto selecionado.
Open a document to mark its fold lines. Abra um documento para marcar suas linhas de dobra.
Remove Fold Line Role Remover Tipo de Linha
Fold Angle Ângulo de Dobra
Set Fold Angle… Definir Ângulo de Dobra…
Set Fold Angle Definir Ângulo de Dobra
Reset Fold Angle Redefinir Ângulo de Dobra
@msg select a crease, partial cut or perforation line that is neither locked nor hidden selecione uma linha de vinco, de meio-corte ou de perfuração que não esteja bloqueada nem oculta
Tap Toque Rápido
Clear Hold Limpar Pressionamento Longo
Hold Shortcuts Atalhos de Pressionamento Longo
Can't render this file because it is too large.
+5
View File
@@ -10492,6 +10492,11 @@ shape Open Открытый
No objects are selected. Объекты не выделены.
Open a document to mark its fold lines. Откройте документ, чтобы отметить его линии сгиба.
Remove Fold Line Role Убрать тип линии
Fold Angle Угол сгиба
Set Fold Angle… Задать угол сгиба…
Set Fold Angle Задать угол сгиба
Reset Fold Angle Сбросить угол сгиба
@msg select a crease, partial cut or perforation line that is neither locked nor hidden выделите линию биговки, надреза или перфорации, которая не закреплена и не скрыта
Check Проверить
Check Fold Lines Проверить линии сгиба
@msg No cut lines are in the selection. В выделении нет линий реза.
Can't render this file because it is too large.
+5
View File
@@ -10096,6 +10096,11 @@ digits Hindi Hindi
No objects are selected. Inga objekt är markerade.
Open a document to mark its fold lines. Öppna ett dokument för att markera dess falslinjer.
Remove Fold Line Role Ta bort linjetyp
Fold Angle Falsvinkel
Set Fold Angle… Ange falsvinkel…
Set Fold Angle Ange falsvinkel
Reset Fold Angle Återställ falsvinkel
@msg select a crease, partial cut or perforation line that is neither locked nor hidden markera en biglinje, halvskärlinje eller perforeringslinje som varken är låst eller dold
Check Kontrollera
Check Fold Lines Kontrollera falslinjer
@msg No cut lines are in the selection. Det finns inga skärlinjer i markeringen.
Can't render this file because it is too large.
+5
View File
@@ -10364,6 +10364,11 @@ breakText Glyphs Glifler
No objects are selected. Hiçbir nesne seçili değil.
Open a document to mark its fold lines. Katlama çizgilerini işaretlemek için bir belgeyi açın.
Remove Fold Line Role Çizgi Türünü Kaldır
Fold Angle Katlama Açısı
Set Fold Angle… Katlama Açısını Ayarla…
Set Fold Angle Katlama Açısını Ayarla
Reset Fold Angle Katlama Açısını Sıfırla
@msg select a crease, partial cut or perforation line that is neither locked nor hidden kilitli ya da gizli olmayan bir pilyaj, yarım kesim veya perforaj çizgisi seçin
Tap Kısa Basma
Clear Hold Basılı Tutmayı Temizle
Hold Shortcuts Basılı Tutma Kısayolları
Can't render this file because it is too large.
+5
View File
@@ -10028,6 +10028,11 @@ breakText Glyphs Гліфи
No objects are selected. Об’єкти не виділено.
Open a document to mark its fold lines. Відкрийте документ, щоб позначити його лінії згину.
Remove Fold Line Role Прибрати тип лінії
Fold Angle Кут згину
Set Fold Angle… Задати кут згину…
Set Fold Angle Задати кут згину
Reset Fold Angle Скинути кут згину
@msg select a crease, partial cut or perforation line that is neither locked nor hidden виділіть лінію біговки, надрізу або перфорації, яка не закріплена й не прихована
Tap Коротке натискання
Clear Hold Очистити утримання
Hold Shortcuts Клавіші утримання
Can't render this file because it is too large.
+5
View File
@@ -8137,6 +8137,11 @@ breakText Glyphs Glyph
No objects are selected. Không có đối tượng nào được chọn.
Open a document to mark its fold lines. Mở tài liệu để đánh dấu các đường gấp của nó.
Remove Fold Line Role Bỏ loại đường
Fold Angle Góc gấp
Set Fold Angle… Đặt góc gấp…
Set Fold Angle Đặt góc gấp
Reset Fold Angle Đặt lại góc gấp
@msg select a crease, partial cut or perforation line that is neither locked nor hidden hãy chọn một đường cấn, đường cắt một phần hoặc đường đục lỗ không bị khóa và không bị ẩn
Check Kiểm tra
Check Fold Lines Kiểm tra đường gấp
@msg No cut lines are in the selection. Vùng chọn không có đường cắt nào.
Can't render this file because it is too large.
+5
View File
@@ -10253,6 +10253,11 @@ breakText Glyphs 字形
No objects are selected. 未选择任何对象。
Open a document to mark its fold lines. 打开文档以标记其折线。
Remove Fold Line Role 移除线条类型
Fold Angle 折叠角度
Set Fold Angle… 设置折叠角度…
Set Fold Angle 设置折叠角度
Reset Fold Angle 重置折叠角度
@msg select a crease, partial cut or perforation line that is neither locked nor hidden 请选择未锁定且未隐藏的压痕线、半切线或打孔线
Check 检查
Check Fold Lines 检查折线
@msg No cut lines are in the selection. 所选内容中没有切割线。
Can't render this file because it is too large.
+5
View File
@@ -10068,6 +10068,11 @@ breakText Glyphs 字符
No objects are selected. 未選取任何物件。
Open a document to mark its fold lines. 開啟文件以標記其摺線。
Remove Fold Line Role 移除線條類型
Fold Angle 摺疊角度
Set Fold Angle… 設定摺疊角度…
Set Fold Angle 設定摺疊角度
Reset Fold Angle 重設摺疊角度
@msg select a crease, partial cut or perforation line that is neither locked nor hidden 請選取未鎖定且未隱藏的壓痕線、半切線或打孔線
Check 檢查
Check Fold Lines 檢查摺線
@msg No cut lines are in the selection. 選取範圍中沒有切割線。
Can't render this file because it is too large.
+2
View File
@@ -75,6 +75,8 @@ pub(super) fn menu_dialog(app: &VectorcraftApp, id: &str) -> Option<(&'static st
("splitIntoGrid", crate::dialogs::path_ops::split_fields(size.0, size.1))
}
"object.vectorHalftone" => (crate::dialogs::halftone::KIND, crate::dialogs::halftone::fields()),
// Set Fold Angle… opens on the angle the selected fold lines fold at, while it can change one.
crate::addons::packaging::SET_FOLD_ANGLE => ("command", crate::addons::packaging::dialog_fields(app).ok()?),
crate::addons::pathtools::set_corners::COMMAND => {
(crate::addons::pathtools::set_corners::KIND, crate::addons::pathtools::set_corners::fields(app))
}
+5
View File
@@ -963,6 +963,11 @@ fn run_ui_part10(app: &mut VectorcraftApp, id: &str, p: &Value) -> Option<Result
crate::canvas::apply_requests(app, r);
match s("command").as_deref() {
Some(c) if crate::dialogs::envelope::opens(c) => crate::dialogs::envelope::open(app, c),
// Set Fold Angle's dialog says why it can't open, as the command does.
Some(crate::addons::packaging::SET_FOLD_ANGLE) => crate::addons::packaging::dialog_fields(app).map(|fields| {
app.ui.dialog = Some(crate::state::Dialog::new("command", fields));
Value::Null
}),
c => match c.and_then(|c| menu_dialog(app, c)) {
Some((kind, fields)) => {
app.ui.dialog = Some(crate::state::Dialog::new(kind, fields));
+1 -1
View File
@@ -1412,7 +1412,7 @@ pub const UI_COMMANDS: &[(&str, &str, &str, &str)] = &[
"ui.menuDialog",
"Menu Dialog",
"",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize; Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
"{command: object.move|object.rotate|object.scale|object.reflect|object.shear|object.transformEach|path.average|path.averageJoin|object.path.offsetPath|object.path.simplify|object.path.smooth|object.path.splitIntoGrid|object.vectorHalftone|artboard.rearrange|artboard.rename|object.envelope.makeWithWarp|object.envelope.resetWithWarp|object.envelope.makeWithMesh|object.envelope.resetWithMesh|object.envelope.options|addon.arrange.grid|addon.arrange.replace|addon.arrange.size|addon.packaging.setFoldAngle} open the dialog that command's menu item opens (dialog kind: move, rotate, scale, reflect, shear, transformEach, …, vectorHalftone, rearrangeArtboards, renameArtboards, envelopeWarp, envelopeMesh, envelopeOptions, arrangeGrid, arrangeReplace, arrangeSize, command for Set Fold Angle (its `angle` the selected fold lines' angle, refused while the selection has no fold line it can change); Scale and Transform Each have `corners` and `strokes`, from the preferences, which OK updates; Transform Each opens on the values it was last confirmed with (not `copy`), and its Copy button confirms with `copy: true`; the envelope dialogs start from the selected envelope, Make opens as Reset (`reset: true`) while one is selected)",
),
(
"ui.widthPointEdit",
+1 -1
View File
@@ -60,7 +60,7 @@ pub use labels::{dim_label, dim_name, divider, field_label, label_row, link_labe
pub(crate) use labels::{dim_label_width, field_panel_label, label_field, take_previous_label, text_width};
pub(crate) use numeric::{ANY, round_to, set_bare_numbers_are_points, typed_unit};
pub use numeric::{
SpinPick, mixed_field, mixed_field_named, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within,
SpinPick, mixed_field, mixed_field_named, mixed_field_within, num_field, num_field_live, num_field_named, num_field_refusing, num_field_within,
num_field_within_empty, opt_field, opt_field_named, plain_field_live, range_field, range_field_live, range_field_named, range_field_stepped,
size_field, size_field_named, slider, spin_field, spin_field_auto, spin_field_auto_named, spin_field_named, spin_field_stops_named, spin_kerning,
spin_length_within, spin_plain, spin_plain_named, spin_range,
+15
View File
@@ -842,6 +842,21 @@ pub fn mixed_field(ui: &mut Ui, id: impl std::hash::Hash, value: Option<f64>, su
mixed_field_named(ui, id, None, value, suffix, decimals, width)
}
/// [`mixed_field`] whose value is kept within `bounds`: steps stop at its ends, and a typed value
/// past one is brought to it.
pub fn mixed_field_within(
ui: &mut Ui,
id: impl std::hash::Hash,
value: Option<f64>,
suffix: &str,
decimals: usize,
width: f32,
bounds: RangeInclusive<f64>,
) -> Option<f64> {
let label = take_previous_label(ui);
bounded_field(ui, id, label, None, value, suffix, decimals, width, &bounds, None, false, false).map(|v| within(v, &bounds))
}
/// [`mixed_field`] for a row named explicitly instead of by an adjacent label widget.
pub fn mixed_field_named(
ui: &mut Ui,
+52 -15
View File
@@ -14304,10 +14304,11 @@ there is no step. → `{symbols: [name…], ids: [instance id…], skipped: [{la
## Packaging Tools add-on
Packaging Tools is a built-in add-on for the dielines of boxes and other folded packaging. Its commands are
`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check` and
`addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold Lines opens the Fold Lines panel,
Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run `addon.packaging.setRole` on the
selection, Check Fold Lines runs `addon.packaging.check`, and Fold Preview runs `ui.foldPreview`.
`addon.packaging.setRole`, `addon.packaging.roles`, `addon.packaging.setRoleSwatch`, `addon.packaging.check`,
`addon.packaging.setFoldAngle` and `addon.packaging.fold`. In the desktop app, Object › Plug-ins › Packaging Tools › Fold
Lines opens the Fold Lines panel, Make Cut Line, Make Crease Line, Make Partial Cut Line and Make Perforation Line run
`addon.packaging.setRole` on the selection, Check Fold Lines runs `addon.packaging.check`, Set Fold Angle… opens the
options of `addon.packaging.setFoldAngle`, and Fold Preview runs `ui.foldPreview`.
### Fold line roles
@@ -14338,11 +14339,17 @@ the color it shows, no longer linked to the swatch, and stops overprinting. Text
objects are skipped and counted. The command fails with an unknown role and when the objects hold no path it can change. One undo
step, none when nothing changes. Result: `{ids, changed, skipped}`.
`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected}`: each role's
swatch, whether the document has it, and how many of the objects have the role. It counts the selection, or every object
of the document while nothing is selected and `ids` is left out (`scope` says which). Locked and hidden objects are
counted in every scope, and an object is counted once when both it and its group are given. The Fold Lines panel shows
these counts; clicking a role gives the selected paths that role. With nothing selected the panel says so.
`addon.packaging.roles` (`{ids?}`) returns `{roles: [{role, name, swatch, exists, count}], scope, selected, foldLines,
foldAngle, ownAngles, storedAngles}`: each role's swatch, whether the document has it, and how many of the objects have
the role. It counts the selection, or every object of the document while nothing is selected and `ids` is left out
(`scope` says which). Locked and hidden objects are counted in every scope, and an object is counted once when both it
and its group are given. `foldLines` is how many of the Crease, Partial Cut and Perforation lines among them
`addon.packaging.setFoldAngle` can change, which leaves out locked and hidden lines; it is 0 while nothing is selected
and `ids` is left out, and while the selection holds only a layer and objects in it. `foldAngle` is the angle in degrees
those lines all fold at (see Fold angles), or null when they fold at different angles or there are none; `ownAngles` is
how many of them have an angle of their own, and `storedAngles` how many hold stored angle text, an angle or not, which
`reset: true` removes. The Fold Lines panel shows these counts; clicking a role gives the selected paths that role. With
nothing selected the panel says so.
`addon.packaging.setRoleSwatch` (`{role, swatch}`) makes another global or spot color swatch carry the role. Objects
stroked with the old swatch keep their color and no longer have the role. It fails with a missing swatch, a gradient or
@@ -14403,17 +14410,47 @@ The list is shown until the document changes.
{"name":"run_command","arguments":{"command":"addon.packaging.check","params":{"tolerance":0.5,"select":true}}}
```
### Fold angles
A Crease or a Perforation folds 90° away from the printed side, so the print ends up outside, and a Partial Cut folds
90° toward it. A Crease, Partial Cut or Perforation line can have an angle of its own instead, from -180° to 180°: a
positive angle folds away from the printed side and a negative one toward it. The angle is stored in the line's data
under `vc-fold-angle` as a number of degrees, rounded to the millionth of a degree (a stored value with more places
folds at it rounded the same way). Native files keep it. SVG export leaves it out of the path's attributes; an SVG with
`preserveEditing` keeps it in the document the SVG carries. A value that is not a number from -180 to 180 counts as no
angle of its own. A cut line ignores it. A line keeps its own angle when `addon.packaging.setRole` gives it another
role, or `none`, so a line made a Partial Cut after it was given 45° still folds at 45°; `reset: true` takes the angle
away. In the Fold Preview window, a panel folded flat onto another (180°) is drawn behind that panel's printed side, and
at -180° in front of it. Panels folded flat onto each other stack as they do when the blank is folded about its largest
panel, whichever panel the window folds about.
`addon.packaging.setFoldAngle` (`{angle?: -180..180, reset?: false, ids?}`) gives each Crease, Partial Cut and
Perforation line among the objects (the selection by default), through groups and clip groups, the angle, or with
`reset: true` takes the line's own angle away. Give exactly one of `angle` and `reset: true`. Locked and hidden objects
are skipped as `addon.packaging.setRole` skips them; cut lines and objects without a role are skipped and counted. The
command fails when the objects hold no Crease, Partial Cut or Perforation line it can change, and with an angle outside
the range or one that is not a number. One undo step, none when nothing changes. Result: `{ids, changed, skipped}`.
Set Fold Angle… opens its options (`ui.menuDialog {command: "addon.packaging.setFoldAngle"}`, kind `command`) on the
angle that the selected lines it can change fold at (90° when they differ), shown with every decimal place it has.
While the selection holds no such line, `ui.menuDialog` fails with the reason the command gives. While the selection
holds such lines, the Fold Lines panel shows a Fold Angle field with that angle, empty when they differ. Typing an angle there sets it, and the Reset button beside it takes their own angles away.
```json
{"name":"run_command","arguments":{"command":"addon.packaging.setFoldAngle","params":{"angle":135}}}
```
### Fold Preview
`addon.packaging.fold` (`{ids?, base?: [x, y], amount?: 1, tolerance?: 0.1}`) folds a blank into its 3D shape. It reads
the fold lines as `addon.packaging.check` does, and folds the blank that holds the base panel: the panel under `base`, or
the largest panel of all the blanks. The base panel stays in place. Every other panel turns about the hinges that join it
to the base, each by its angle times `amount` (0 is flat, 1 is folded): a Crease or a Perforation folds 90° away from
the printed side, so the print ends up outside, and a Partial Cut folds 90° toward it. A hinge that closes a loop of
panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all the way,
whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no chain of
hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel; anything
else is an error. The command does not change the document.
to the base, each by its angle times `amount` (0 is flat, 1 is folded). A hinge's angle is the fold angle of the line
with the most length in it (see Fold angles), the one with the lowest id among lines of equal length. A hinge that closes
a loop of panels is not turned about; `gap` says how far apart its two placements end up when every hinge is folded all
the way, whatever `amount` is, and it `closes` when that is within `tolerance` or 0.5% of its length. A panel that no
chain of hinges joins to the base stays flat where it is. `amount` must be from 0 to 1 and `base` a point in a panel;
anything else is an error. The command does not change the document.
Result: `{ok, blank, blanks, base, panels: [{outline, frame: {x, y, z, origin}, parent, depth}], hinges: [{a, b,
angle, kind, closes, gap}], collisions: [[a, b]], issues}`. `outline` is the panel's SVG path data in document