diff --git a/Cargo.lock b/Cargo.lock index 3a91211871..d780911c11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1224,6 +1224,14 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "craft-plotter" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=9101c4fc226f5f111b5a890a6c5c19bf3991fd76#9101c4fc226f5f111b5a890a6c5c19bf3991fd76" +dependencies = [ + "thiserror 2.0.21", +] + [[package]] name = "craft-print" version = "0.1.0" @@ -6720,6 +6728,7 @@ version = "0.24.1" dependencies = [ "craft-dxf", "craft-image-codecs 0.1.0 (git+https://github.com/storytold/craft-libs?rev=a499742a9389f47d10cdc61e4cdbf4e5f07f48cd)", + "craft-plotter", "image", "kurbo 0.13.1", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index e246dbf705..891cce208d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,7 @@ craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9 # EPS container, previews, ASCII85 and DSC comments (craft-libs#778). craft-eps = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } # DXF tags, reader and writer (craft-libs#778, #926, #927). +craft-plotter = { git = "https://github.com/storytold/craft-libs", rev = "9101c4fc226f5f111b5a890a6c5c19bf3991fd76" } craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } # WMF, EMF and EMF+ reader (craft-libs#778). craft-metafile = { git = "https://github.com/storytold/craft-libs", rev = "a499742a9389f47d10cdc61e4cdbf4e5f07f48cd" } diff --git a/crates/cad/Cargo.toml b/crates/cad/Cargo.toml index f2f9158730..1cbf8dc431 100644 --- a/crates/cad/Cargo.toml +++ b/crates/cad/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] craft-dxf = { workspace = true } +craft-plotter = { workspace = true } vectorcraft-geom = { workspace = true } vectorcraft-color = { workspace = true } vectorcraft-doc = { workspace = true } diff --git a/crates/cad/src/hpgl/lex.rs b/crates/cad/src/hpgl/lex.rs index 5025d07c6f..cc9b8b5efe 100644 --- a/crates/cad/src/hpgl/lex.rs +++ b/crates/cad/src/hpgl/lex.rs @@ -1,428 +1,2 @@ -//! The bytes of an HP-GL file as instructions: two-letter mnemonics and the parameters that follow -//! them, read one at a time as the plot asks for them. Printer escape sequences (PCL, HP RTL, the -//! HP-GL device-control escapes) and PJL lines around and between the instructions are skipped, -//! with the data their escapes carry. - -/// The end-of-text character, the default label terminator. -pub(super) const ETX: u8 = 3; -const ESC: u8 = 0x1b; - -/// The most digits of a number that count: longer ones are read as their first digits. -const MAX_DIGITS: usize = 18; - -/// What the bytes being read hold. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Mode { - /// HP-GL instructions. - Hpgl, - /// PCL or HP RTL: escape sequences and their data, nothing to draw. - Pcl, - /// After a Universal Exit Language: PJL lines until a language starts. - Pjl, -} - -/// One item of a PE (Polyline Encoded) instruction. -#[derive(Clone, Copy, Debug, PartialEq)] -pub(super) enum PeItem { - /// Select pen. - Pen(i64), - /// Rectangle mode: the following coordinates come in fours. - Rect, - /// A coordinate pair, after a pen-up flag (`up`) and an absolute flag (`absolute`). - Point { x: f64, y: f64, up: bool, absolute: bool }, -} - -/// The state of one PE instruction being read. -#[derive(Clone, Copy, Debug, Default)] -pub(super) struct Pe { - seven_bit: bool, - fraction_bits: u32, - up: bool, - absolute: bool, -} - -pub(super) struct Lexer<'a> { - b: &'a [u8], - at: usize, - mode: Mode, - /// The file holds HP RTL or PCL raster image data. - pub raster: bool, -} - -/// Is `c` a byte that separates numeric parameters (or white space between instructions)? -fn separator(c: u8) -> bool { - matches!(c, b' ' | b',' | b'\t' | b'\r' | b'\n' | 0) -} - -impl<'a> Lexer<'a> { - pub fn new(b: &'a [u8]) -> Self { - Self { b, at: 0, mode: Mode::Hpgl, raster: false } - } - - fn peek(&self) -> Option { - self.b.get(self.at).copied() - } - - /// Whether everything has been read. - pub fn done(&self) -> bool { - self.at >= self.b.len() - } - - /// How many bytes have been read. - pub fn pos(&self) -> usize { - self.at - } - - /// The next instruction's mnemonic, in upper case; `strict`: only white space, semicolons and - /// escape sequences may come before it (anything else gives `None`, as the end does). - pub fn op(&mut self, strict: bool) -> Option<[u8; 2]> { - loop { - let c = self.peek()?; - if c == ESC { - self.escape(); - continue; - } - match self.mode { - Mode::Pcl => { - self.at += 1; - continue; - } - Mode::Pjl => { - if separator(c) { - self.at += 1; - } else if c == b'@' { - self.pjl_line(); - } else { - self.mode = Mode::Hpgl; - } - continue; - } - Mode::Hpgl => {} - } - let next = self.b.get(self.at + 1).copied(); - if c.is_ascii_alphabetic() - && let Some(n) = next.filter(u8::is_ascii_alphabetic) - { - self.at += 2; - return Some([c.to_ascii_uppercase(), n.to_ascii_uppercase()]); - } - if strict && !(separator(c) || c == b';' || c < 0x20) { - return None; - } - self.at += 1; - } - } - - /// One `@PJL` line: an `ENTER LANGUAGE` command picks what follows. - fn pjl_line(&mut self) { - let rest = &self.b[self.at..]; - let end = rest.iter().position(|&c| c == b'\n').map_or(rest.len(), |n| n + 1); - // A command names its language within its first 256 bytes; longer lines aren't copied. - let line = String::from_utf8_lossy(&rest[..end.min(256)]).to_ascii_uppercase(); - if let Some(lang) = line.split_once("LANGUAGE").map(|(_, l)| l.trim_start_matches([' ', '=']).trim()) { - self.mode = if lang.starts_with("HPGL") { Mode::Hpgl } else { Mode::Pcl }; - } - self.at += end; - } - - /// An escape sequence at the current byte, with the data it carries. - fn escape(&mut self) { - self.at += 1; - let Some(c) = self.peek() else { return }; - self.at += 1; - match c { - // Universal Exit Language (`ESC%-12345X`) and the language switches (`ESC%#B` to HP-GL, - // `ESC%#A` to PCL or HP RTL). - b'%' => { - let (_, end) = self.value(); - match end { - Some(b'X') => self.mode = Mode::Pjl, - Some(b'B') => self.mode = Mode::Hpgl, - Some(b'A') => self.mode = Mode::Pcl, - _ => {} - } - } - // Reset: PCL follows, until a language switch. - b'E' => self.mode = Mode::Pcl, - // HP-GL device control: `ESC.` and a letter, with parameters up to a colon. - b'.' => { - let Some(kind) = self.peek() else { return }; - self.at += 1; - if !b"()YZBEJKLORUX".contains(&kind) { - let rest = &self.b[self.at..self.b.len().min(self.at + 80)]; - if let Some(n) = rest.iter().position(|&c| c == b':') - && rest[..n].iter().all(|c| c.is_ascii_digit() || matches!(c, b';' | b' ' | b',')) - { - self.at += n + 1; - } - } - } - // Parameterized PCL: a group character, then values each ending in a letter (upper case - // ends the sequence); `W`, `*b…V` (raster data by plane) and `&p…X` (transparent print - // data) are followed by that many bytes of data. Without a group character (`ESC(8U`, - // `ESC)0N`), one value and the letter ending it. - 0x21..=0x2f => { - let Some(group) = self.peek().filter(|g| (0x60..=0x7e).contains(g)) else { - self.value(); - return; - }; - self.at += 1; - loop { - let (v, end) = self.value(); - let Some(end) = end else { return }; - let upper = end.to_ascii_uppercase(); - if upper == b'W' || (c, group, upper) == (b'*', b'b', b'V') || (c, group, upper) == (b'&', b'p', b'X') { - let n = v.max(0.0).min((self.b.len() - self.at) as f64) as usize; - if (c, group) == (b'*', b'b') && n > 0 { - self.raster = true; - } - self.at += n; - } - if (c, group, end) == (b'*', b'r', b'A') { - self.raster = true; - } - if !end.is_ascii_lowercase() { - return; - } - } - } - // A two-character escape. - _ => {} - } - } - - /// A PCL value (`[+-]digits[.digits]`, any part missing) and the character that ends it; `None` - /// when that is not a letter or `@` (which is then left unread). - fn value(&mut self) -> (f64, Option) { - let v = self.number_here().unwrap_or(0.0); - match self.peek() { - Some(c) if c.is_ascii_alphabetic() || c == b'@' => { - self.at += 1; - (v, Some(c)) - } - _ => (v, None), - } - } - - /// A number starting at the current byte (`[+-]digits[.digits]`), `None` when it has no digit - /// (its sign and point are read all the same). - fn number_here(&mut self) -> Option { - let mut neg = false; - if let Some(c @ (b'+' | b'-')) = self.peek() { - neg = c == b'-'; - self.at += 1; - } - let (mut v, mut digits, mut scale) = (0.0f64, 0usize, 1.0f64); - let mut point = false; - while let Some(c) = self.peek() { - if c.is_ascii_digit() { - if digits < MAX_DIGITS { - if point { - scale /= 10.0; - v += f64::from(c - b'0') * scale; - } else { - v = v * 10.0 + f64::from(c - b'0'); - } - } else if !point { - // Past the digits that count, an integer part keeps its size. - v *= 10.0; - } - digits += 1; - } else if c == b'.' && !point { - point = true; - } else { - break; - } - self.at += 1; - } - let v = v.min(f64::MAX); - (digits > 0).then_some(if neg { -v } else { v }) - } - - /// The next numeric parameter of the instruction being read, or `None` at its end (a semicolon - /// ending it is read). - pub fn number(&mut self) -> Option { - loop { - let c = self.peek()?; - if separator(c) { - self.at += 1; - } else if c.is_ascii_digit() || matches!(c, b'+' | b'-' | b'.') { - if let Some(v) = self.number_here() { - return Some(v); - } - } else { - if c == b';' { - self.at += 1; - } - return None; - } - } - } - - /// Up to `out.len()` numeric parameters into `out` (the rest are read and dropped) → how many. - pub fn numbers(&mut self, out: &mut [f64]) -> usize { - let mut n = 0; - while let Some(v) = self.number() { - if let Some(slot) = out.get_mut(n) { - *slot = v; - } - n += 1; - } - n.min(out.len()) - } - - /// Read and drop the parameters of the instruction being read: numbers and quoted strings. - pub fn params(&mut self) { - loop { - while self.number().is_some() {} - if self.peek() != Some(b'"') { - return; - } - self.quoted(); - } - } - - /// Read and drop numeric parameters → whether a semicolon ended them (an instruction the reader - /// doesn't know, written out in full). - pub fn closed_params(&mut self) -> bool { - while self.number().is_some() {} - self.at > 0 && self.b.get(self.at - 1) == Some(&b';') - } - - /// A comment (CO): its quoted string or nothing, then the terminator or the end → whether it - /// is one. - pub fn comment(&mut self) -> bool { - while self.peek().is_some_and(separator) { - self.at += 1; - } - match self.peek() { - Some(b'"') => self.quoted(), - Some(b';') => { - self.at += 1; - true - } - None => true, - Some(_) => false, - } - } - - /// The text of a label, up to and including `terminator` (or the end). - pub fn label(&mut self, terminator: u8) { - let rest = &self.b[self.at..]; - self.at += rest.iter().position(|&c| c == terminator).map_or(rest.len(), |n| n + 1); - } - - /// A quoted string (CO): the parameters up to its closing quote, then the terminator → whether - /// there was one. - pub fn quoted(&mut self) -> bool { - while self.peek().is_some_and(separator) { - self.at += 1; - } - let found = self.peek() == Some(b'"'); - if found { - self.at += 1; - let rest = &self.b[self.at..]; - self.at += rest.iter().position(|&c| c == b'"').map_or(rest.len(), |n| n + 1); - } - if self.peek() == Some(b';') { - self.at += 1; - } - found - } - - /// The character right after the mnemonic (DT, SM), `None` when it is a semicolon or the end - /// (the semicolon is read). - pub fn char(&mut self) -> Option { - let c = self.peek()?; - self.at += 1; - (c != b';').then_some(c) - } - - /// The next item of a PE instruction, `None` at its end (its semicolon is read). - pub fn pe(&mut self, st: &mut Pe) -> Option { - loop { - let raw = self.peek()?; - let c = raw & 0x7f; - // Spaces, deletes, control characters and bytes 128 to 160 and 255 are ignored. - if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { - self.at += 1; - continue; - } - match c { - b';' => { - self.at += 1; - return None; - } - // Flags keep their meaning with the eighth bit set; digits are 63 and up (191 and up). - b':' | b'<' | b'>' | b'=' | b'7' | b'9' if raw < 63 || (0xb7..191).contains(&raw) => { - self.at += 1; - match c { - b':' => return self.pe_value(st).map(PeItem::Pen).or_else(|| self.end_pe()), - b'<' => st.up = true, - b'>' => match self.pe_value(st) { - Some(n) => st.fraction_bits = n.clamp(0, 52) as u32, - None => return self.end_pe(), - }, - b'=' => st.absolute = true, - b'7' => st.seven_bit = true, - _ => return Some(PeItem::Rect), - } - } - _ => { - let scale = 0.5f64.powi(st.fraction_bits as i32); - let (Some(x), Some(y)) = (self.pe_value(st), self.pe_value(st)) else { return self.end_pe() }; - let item = PeItem::Point { x: x as f64 * scale, y: y as f64 * scale, up: st.up, absolute: st.absolute }; - (st.up, st.absolute) = (false, false); - return Some(item); - } - } - } - } - - /// The rest of a PE instruction that can't be decoded: see [`Lexer::skip_pe`]. - fn end_pe(&mut self) -> Option { - self.skip_pe(); - None - } - - /// The data of a PE instruction, up to and including its semicolon, unread: its data is never - /// read as instructions. - pub fn skip_pe(&mut self) { - let rest = &self.b[self.at..]; - self.at += rest.iter().position(|&c| c == b';').map_or(rest.len(), |n| n + 1); - } - - /// One encoded PE number, `None` when the instruction ends inside it (or a byte that is no - /// digit comes first, which is read). - fn pe_value(&mut self, st: &Pe) -> Option { - let (base, low, high): (u64, std::ops::RangeInclusive, std::ops::RangeInclusive) = - if st.seven_bit { (32, 63..=94, 95..=126) } else { (64, 63..=126, 191..=254) }; - let (mut v, mut place) = (0u64, 1u64); - loop { - let raw = self.peek()?; - let c = if st.seven_bit { raw & 0x7f } else { raw }; - if raw <= 32 || raw == 127 || (128..=160).contains(&raw) || raw == 255 { - self.at += 1; - continue; - } - if c == b';' { - return None; - } - self.at += 1; - let (digit, last) = if low.contains(&c) { - (u64::from(c - 63), false) - } else if high.contains(&c) { - (u64::from(c - high.start()), true) - } else { - return None; - }; - v = v.saturating_add(digit.saturating_mul(place)); - place = place.saturating_mul(base); - if last { - // The low bit is the sign. - let n = i64::try_from(v >> 1).unwrap_or(i64::MAX); - return Some(if v & 1 == 1 { -n } else { n }); - } - } - } -} +//! Shared HP-GL byte lexer; drawing interpretation remains local. +pub(super) use craft_plotter::hpgl::lex::{ETX, Lexer, Pe, PeItem}; diff --git a/crates/color/src/harmony.rs b/crates/color/src/harmony.rs index 8bdff7103d..2cca6e264d 100644 --- a/crates/color/src/harmony.rs +++ b/crates/color/src/harmony.rs @@ -294,13 +294,19 @@ impl GuideOptions { } } +/// The share of the way to its target (black or white, cool or warm, gray or full color) that the +/// variation at `step` goes: 0 at the center, the options' reach at the outermost steps. +pub fn step_fraction(opts: &GuideOptions, step: i32) -> f32 { + (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach() +} + /// Variation of `c` at `step` (−steps..=steps: negative towards shades/cool/muted, positive towards /// tints/warm/vivid; 0 is `c` itself), in `c`'s model. pub fn variation(c: Color, opts: &GuideOptions, step: i32) -> Color { if step == 0 { return c; } - let f = (step.unsigned_abs() as f32 / opts.steps.max(1) as f32).min(1.0) * opts.reach(); + let f = step_fraction(opts, step); let v = match opts.variation { Variation::TintsShades => c.lerp(if step < 0 { &Color::BLACK } else { &Color::WHITE }, f), Variation::WarmCool => { diff --git a/crates/doc/src/blend.rs b/crates/doc/src/blend.rs index c7c3e408b4..f8b62ac815 100644 --- a/crates/doc/src/blend.rs +++ b/crates/doc/src/blend.rs @@ -2174,6 +2174,70 @@ pub fn blend_steps(keys: &[Arc], spec: &BlendSpec) -> Vec { StepCount::default().blend(keys, spec, Rail::new(keys, spec).as_ref()).0 } +/// Does each pair of `keys` blended with `spec` ask for the same number of steps +/// ([`blend_step_count`]) when each coordinate it counts from moves by up to `length` points and, +/// for Smooth Color, the difference between keys of different colors by up to `color` (0 to 1)? +/// False when a count sits that close to where it changes, and for Smooth Color by distance when +/// the keys are at most `4 × length` wide or high. Specified Steps always asks for the same number. +pub fn blend_steps_settled(keys: &[Arc], spec: &BlendSpec, length: f64, color: f64) -> bool { + let rail = Rail::new(keys, spec); + keys.windows(2).enumerate().all(|(i, w)| { + let [a, b] = w else { return true }; + match spec.spacing { + BlendSpacing::Steps(_) => true, + // The count is `len / d` rounded, which grows with `len`. + BlendSpacing::Distance(d) => { + let len = rail.as_ref().map_or_else(|| center_of(a).distance(center_of(b)), |r| r.len(i)); + let count = |len: f64| blend_step_count(a, b, BlendSpacing::Distance(d), len); + count(len - length) == count(len + length) + } + BlendSpacing::SmoothColor => smooth_color_settled(a, b, length, color), + } + }) +} + +/// [`blend_steps_settled`] for one pair of Smooth Color keys. Each count [`blend_step_count`] +/// takes grows with what it counts from (the color difference, the keys' reach, the distance +/// between their edges in key sizes), so the pair is settled when the least and the most of +/// these ask for the same count. +fn smooth_color_settled(a: &Node, b: &Node, length: f64, color: f64) -> bool { + let bounds = a.visual_bounds().zip(b.visual_bounds()); + let by_level = |d: f64| level_steps(d.max(0.0)) as usize; + match (color_distance(a, b), bounds) { + // Colors that differ, but by too little to count, or by little more: moving them may cross + // where they stop counting as the same. (The same colors stay the same.) + (Some(d), _) if d > 0.0 && d * 255.0 <= 1e-3 + color * 255.0 => false, + (Some(d), Some((ba, bb))) if d * 255.0 > 1e-3 => { + let (ca, cb) = (ba.center(), bb.center()); + let reach = + [(ca.x - cb.x).abs(), (ca.y - cb.y).abs(), ba.width(), ba.height(), bb.width(), bb.height()].into_iter().fold(0.0f64, f64::max); + // The centers and sizes move by up to twice `length`. + let by_density = |r: f64| (8.0 * r.max(0.0) + 0.5).floor().clamp(1.0, 254.0) as usize; + let least = by_level(d - color).min(by_density(reach - 2.0 * length)); + let most = by_level(d + color).min(by_density(reach + 2.0 * length)); + reach.is_finite() && least == most + } + (Some(d), None) if d * 255.0 > 1e-3 => by_level(d - color) == by_level(d + color), + (_, Some((ba, bb))) => { + let (w, h) = ((ba.width() + bb.width()) / 2.0, (ba.height() + bb.height()) / 2.0); + if w <= 4.0 * length || h <= 4.0 * length { + return false; + } + let dx = (ba.x0 - bb.x0).abs().max((ba.x1 - bb.x1).abs()); + let dy = (ba.y0 - bb.y0).abs().max((ba.y1 - bb.y1).abs()); + // Each edge moves by up to `length`: the distances between them by up to twice that, + // and the mean sizes too. + let q = |dx: f64, dy: f64, w: f64, h: f64| (dx.max(0.0) / w).max(dy.max(0.0) / h); + let count = |q: f64| ((q + 0.5).floor() - 1.0).clamp(1.0, 1000.0) as usize; + let m = 2.0 * length; + let least = q(dx - m, dy - m, w + m, h + m); + let most = q(dx + m, dy + m, w - m, h - m); + least.is_finite() && most.is_finite() && count(least) == count(most) + } + (_, None) => true, + } +} + /// Evaluate a blend: the keys and generated steps in paint order. The steps keep to /// [`MAX_BLEND_STEPS`] in all ([`blend_steps`]). pub fn blend_expand(keys: &[Arc], spec: &BlendSpec) -> Vec { @@ -3535,4 +3599,46 @@ mod tests { let (keys, spec) = blend_parts(&outer).unwrap(); assert_eq!(blend_steps(keys, spec), vec![99]); } + + /// A count is settled when moving the lengths by 0.01 pt and the colors by 0.001 can't change + /// it: Specified Steps always; Specified Distance unless the spine's length is a half step from + /// where its count changes; Smooth Color unless the colors differ by too little to count, the + /// color difference or the keys' reach sits where its count changes, or keys of the same color + /// are at most four times 0.01 pt wide. + #[test] + fn steps_settle_unless_rounding_can_change_their_count() { + let (length, color) = (0.01, 0.001); + let settled = |a: Node, b: Node, spacing: BlendSpacing| { + let spec = BlendSpec { spacing, ..Default::default() }; + blend_steps_settled(&[Arc::new(a), Arc::new(b)], &spec, length, color) + }; + let filled = |x: f64, size: f64, c: Color| smooth_key((x, 0.0), (size, size), Paint::solid(c), Paint::None, 0.0); + let gray = |x: f64| filled(x, 10.0, Color::rgb(0.5, 0.5, 0.5)); + + // The keys' centers are 100 pt apart: 100 / 25 is 4, and 100 / (100 / 3.5) is 3.5. + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Steps(3))); + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::Distance(25.0))); + assert!(!settled(gray(0.0), gray(100.0), BlendSpacing::Distance(100.0 / 3.5))); + + // Smooth Color between colors that differ: by a 2,000th of a step, by 51 steps of 255 + // (settled) and by 51.5 (where the count changes). + let red = |x: f64, r: f32| filled(x, 10.0, Color::rgb(r, 0.0, 0.0)); + assert!(!settled(red(0.0, 0.0), red(100.0, 0.0005), BlendSpacing::SmoothColor)); + assert!(settled(red(0.0, 0.0), red(100.0, 51.0 / 255.0), BlendSpacing::SmoothColor)); + assert!(!settled(red(0.0, 0.0), red(100.0, 51.5 / 255.0), BlendSpacing::SmoothColor)); + // Black to white is counted by the keys' reach, eight steps a point: 10 pt is settled, + // 10.0625 pt (80.5 steps) is not. + let near = |size: f64| settled(filled(0.0, size, Color::BLACK), filled(5.0, size, Color::WHITE), BlendSpacing::SmoothColor); + assert!(near(10.0)); + assert!(!near(10.0625)); + // Keys without bounds are counted by their colors alone. + let bare = |r: f32| Node::path(NodeId(1), PathData::default(), Appearance::basic(Paint::solid(Color::rgb(r, 0.0, 0.0)), Paint::None, 0.0)); + assert!(settled(bare(0.0), bare(51.0 / 255.0), BlendSpacing::SmoothColor)); + assert!(!settled(bare(0.0), bare(51.5 / 255.0), BlendSpacing::SmoothColor)); + // Keys of the same color are counted by distance in key sizes; keys 0.04 pt wide or less + // are never settled. + assert!(settled(gray(0.0), gray(100.0), BlendSpacing::SmoothColor)); + assert!(!settled(filled(0.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.04, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor)); + assert!(settled(filled(0.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), filled(100.0, 0.05, Color::rgb(0.5, 0.5, 0.5)), BlendSpacing::SmoothColor)); + } } diff --git a/crates/engine/src/cmd/fileio/commands.rs b/crates/engine/src/cmd/fileio/commands.rs index 818aaa632f..554d088b79 100644 --- a/crates/engine/src/cmd/fileio/commands.rs +++ b/crates/engine/src/cmd/fileio/commands.rs @@ -36,7 +36,7 @@ pub fn specs() -> Vec { "Export Document", [], None, - "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: lossy WebP isn't available yet: written lossless, with a warning), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", + "{path?, format?: svg|svgz|pdf|ai|png|jpg|webp|gif|png8|txt|dxf|eps|emf|wmf|hpgl|tiff|bmp|tga|psd|vectorcraft|template (default: from the path's extension, else png; png8 writes an indexed .png; ait, a .ait template, is written by file.saveAsTemplate; an exporter plug-in's format is plugin., which an extension only it lists picks too), params?: {…} (an exporter plug-in's parameters; missing ones take their defaults, see plugin.info), selectedOnly?: false (the selected objects alone, in the layers and groups that hold them; an object of a blend, envelope, repeat or intertwine on its own), includeArtboardFill?: true (raster, PDF, SVG and EPS draw each exported artboard's background color behind its art, a transparent background too; false leaves it out), artboard?: 0, artboards?: [i…], rect?: [x, y, width, height] (raster formats: that area of the page in points, y down, instead of an artboard; not with artboard, artboards, range or useArtboards), range?: \"1-3, 5\" | \"all\" (1-based; PDF and .ai write one page per artboard, default all; SVG writes one file per artboard, {stem}-{artboard}.svg; raster formats write one artboard), useArtboards?: true (raster: one file per chosen artboard, default all, {stem}-{artboard}.{ext}; pdf/ai: every page) | false (pdf/ai/raster: the bounds of the visible art; pdf/ai: of the layers the file draws, without editing data, with a warning, and ai refuses pdfCompatible: false; SVG has it as an SVG option), ppi?: number (raster formats: pixels per inch, stored in the file; wins over scale; without either, the document's raster effects resolution), scale?: number (pixels per point), background?: transparent|white|black|\"#rrggbb\" (jpg: white when transparent; #rrggbbaa and #rgba are refused here and in matte), antiAlias?: none|art (default)|type (text snapped to pixels), interlaced?: false (png, Adam7), embedIcc?: true (png: an sRGB chunk marks the colours as sRGB), quality?: 90 (jpg: 0–100), colorModel?: rgb|cmyk|gray (jpg), method?: baseline|optimized|progressive, scans?: 3 (3–5, progressive), embedIcc?: true, imageMap?: none|client|server (an HTML or NCSA map of the objects with a URL, written as .html / .map), colors?: 256 (gif/png8: 2–256), reduction?: perceptual|selective (default)|adaptive|web|blackWhite|gray, dither?: none|diffusion (default)|pattern|noise, ditherAmount?: 100, transparency?: true, matte?: white|\"#rrggbb\"|none, interlaced?, lossless?: true (webp: every pixel kept exactly; false writes lossy WebP, a smaller file that loses some detail), quality?: 90 (webp with lossless: false: 0–100, higher keeps more detail in a larger file; more than 100 is refused), encoding?: utf8|utf16 (txt: the stories in stacking order, back to front, a thread once; utf16 with a byte order mark), lineEndings?: lf|crlf, selectionOnly?: false, svg?: {styling, outlineText, images, objectIds, decimals, minify, responsive, useArtboards, preserveEditing, metadata, fewerTspans, hiddenLayers, encoding, profile, embedFonts, variableData} (see document.formats), …the SVG options given flat instead, …the PDF options of document.exportPdf, …the DXF options of document.exportDxf (useArtboards: one drawing per artboard), …the EPS options of document.exportEps (useArtboards: one file per artboard, {stem}_{artboard}.eps, after a central {stem}.eps of the whole document when there are two or more and art shows; else the visible art), …emf and wmf write one picture of the artboard (useArtboards: true one file per chosen artboard, false the bounds of the visible art; EMF keeps curves, clipping, transparent images and gradients as images clipped to their shape; WMF flattens curves into polygons behind a placeable header; what a format leaves out comes back in warnings), …hpgl writes a plot of the artboard as pen moves for plotters and cutters (each visible path once along its line in plotter units; useArtboards: true one file per chosen artboard, false the bounds of the art it plots, without placed images, unpainted paths and art at 0% opacity), hpglVersion?: hpgl (default: IN, SP, PU, PD) | hpgl2 (also NP and PC pen colors, each pen's paths as one encoded polyline PE), curveTolerance?: 0.1 (points, 0.01 to 10), pens?: [\"#rrggbb\"…] (pen 1 first, up to 255; each path takes the nearest; default a pen per color in the order the art first draws in it, numbered alike in every file), origin?: bottomLeft (default) | center, sortPaths?: false (each pen's next path the nearest), insideFirst?: false (a path after the pen's paths that lie inside it), colorModel?: rgb|cmyk|gray (tiff: rgb keeps transparency as an alpha channel), lzw?: true, byteOrder?: little|big, embedIcc?: true, colorModel?: rgb|gray (bmp), depth?: 24 (bmp: 1 black and white, 4|8 a palette by reduction and dither, 16, 24, 32 with alpha), fileFormat?: windows|os2 (1, 4, 8 or 24 bits), rle?: false (4 and 8 bits, windows), flipRows?: false (top-down rows), depth?: 24 (tga: 16 one-bit alpha, 24, 32 with alpha), colorModel?: rgb|cmyk|gray (psd), layers?: true (each top-level layer a pixel layer with its opacity and blend mode; a background colour is a Background layer; false: one flat image, on white), preserveText?: false (with layers: horizontal and vertical point type in solid colors, with left-to-right paragraphs that set only their alignment, without strokes, effects or an appearance of its own, becomes editable type layers with their pixels; a layer holding it becomes a group, unless other art in it blends in a mode other than normal; refused with layers: false), maxEditability?: false (layers and sublayers become groups, each object a layer named as in the Layers panel, text by its text; clipping, masked or knockout layers stay one layer), hiddenLayers?: false (hidden layers and objects written hidden instead of left out), embedIcc?: true (at most 30000 pixels a side; formats without alpha are flattened on white)} → {path, format, bytes, warnings, files?: [path…] (several), linked?: [path…] (linked images, image maps)}; no path → {dataBase64, format, bytes, warnings, files?: [{name, dataBase64}], linked?: [{name, dataBase64}]}. A key no format takes, and an unknown key inside a PDF or EPS option's object, are refused; a key only another format takes is not used, and warnings name it. Under automation read roots, svg and svgz, and the files that carry the native document (vectorcraft, template, eps, ai of every artboard with useArtboards not false but a version 7 file, pdf of every artboard with preserveEditing on and useArtboards not false), are refused, before any file is written, while the document links a JavaScript file outside them (svgInteractivity; a URL is not checked), or while the file would name a linked image's file outside them (images: link, preserveEditing, or an image whose pixels the document doesn't hold; a URL is not checked). Never changes the document's path", has_doc, export::export ), @@ -54,7 +54,7 @@ pub fn specs() -> Vec { "Export for Screens", ["File", "Export"], None, - "{folder?, zip?: false (one .zip of every file, each deflated or stored, whichever is smaller: no folder → {name, dataBase64, bytes, files: [name…]}; with a folder it is written there → {path, bytes, files}), artboard?: index | artboards?: [index…] | range?: \"1-3\" (default all), assets?: [asset id…] (instead of artboards: each asset's art alone, cropped to its bounds and named after the asset; see assets.list), layers?: [layer id…] (instead of artboards: each layer's art alone, sublayers included, named after the layer), selection?: one|each (instead of artboards: the selected art as one file, or a file per selected object, named after it), fullDocument?: false (one file per format instead: a PDF of every artboard, other formats the bounds of all visible art, named after the document), includeBleed?: false (artboards grown by the document's bleed; a PDF page keeps the artboard as its TrimBox and puts its row's bleed around it once, the document's bleed when the row sets none and its preset gives none or 0), includeArtboardFill?: true (Include Artboard Fill: each artboard's background color behind its art; false leaves it out), pdfs?: multiple|single (Export PDFs As: with several artboards, single writes them as the pages of one PDF per PDF row, named after the document; refused with assets, layers or selection: each), exportPreset?: (a preset of document.exportPresets.list: its settings, under these params), subfolders?: false (each row's files in a sub-folder: its folder, else its size for raster (1x, 2x, 100w…) or its format (SVG, PDF)), folders?: none|rows (as subfolders)|format (a folder per extension: png, svg, pdf…)|item (a folder per artboard, asset, layer or object)|itemFormat (item/extension) (default: rows with subfolders or a preset, else none), name?: (a file name pattern instead of the item's name, with for the document, for the artboard, asset, layer or object, from 1, #### for the counter zero-padded to the run of #, , , (else the row's suffix ends the name), YYYYMMDD, YYYY-MM-DD, YYYY, ,