mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 12:38:18 +00:00
Merge pull request #8440 from dotCooCoo/perf/ai-save-gradient-index
.ai save: gradient and pattern definitions are found by name and by gradient
This commit is contained in:
@@ -3431,6 +3431,133 @@ fn many_gradient_definitions_take_distinct_names_in_order() {
|
||||
assert_eq!(text, program(&doc));
|
||||
}
|
||||
|
||||
/// The program written from `doc`, with the gradient and pattern definitions found by comparing
|
||||
/// each in turn (`scanned`) or through their indexes.
|
||||
fn program_scanned(doc: &Document, scanned: bool) -> Vec<u8> {
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(scanned));
|
||||
let out = export_ai_editing(doc, &opts());
|
||||
writer::SCANNED_DEFINITIONS.with(|s| s.set(false));
|
||||
out.unwrap().program
|
||||
}
|
||||
|
||||
/// [`gradients_and_patterns`] with more rectangles, each filled with a gradient: `distinct` with
|
||||
/// gradients of their own; `reused` with one of `ramps` gradients in turn; one for each of
|
||||
/// `swatches` new gradient swatches, linked to it, with the swatch's gradient for every other one
|
||||
/// and another gradient for the rest; one with the gradient of an object whose style isn't written
|
||||
/// (an even-odd fill with a drop shadow), after that object; and two whose gradients
|
||||
/// differ only in the sign of a zero offset.
|
||||
fn many_gradients(distinct: u16, reused: u16, ramps: u16, swatches: u16) -> Document {
|
||||
let mut doc = gradients_and_patterns();
|
||||
let two = |a: Color, b: Color| ramp(GradientKind::Linear, &[(0.0, a, 1.0, 0.5), (1.0, b, 1.0, 0.5)]);
|
||||
let shade = |i: u16, n: u16| f32::from(i) / f32::from(n.max(1));
|
||||
let swatch_gradient = |i: u16| two(Color::gray(shade(i, swatches)), Color::rgb(1.0, 0.0, 0.0));
|
||||
let more = (0..swatches)
|
||||
.map(|i| Swatch { name: format!("Ramp {i}"), paint: gradient_paint(swatch_gradient(i), None, None), global: false, spot: false })
|
||||
.collect();
|
||||
swatches_plus(&mut doc, more);
|
||||
let mut paints = vec![];
|
||||
for i in 0..distinct {
|
||||
paints.push(gradient_paint(two(Color::rgb(shade(i, distinct), 0.5, 0.0), Color::rgb(0.0, 0.0, 1.0)), None, None));
|
||||
}
|
||||
for i in 0..reused {
|
||||
paints.push(gradient_paint(two(Color::rgb(0.0, shade(i % ramps.max(1), ramps), 0.5), Color::WHITE), None, None));
|
||||
}
|
||||
for i in 0..swatches {
|
||||
let g = if i % 2 == 0 { swatch_gradient(i) } else { two(Color::gray(shade(i, swatches)), Color::rgb(0.0, 1.0, 0.0)) };
|
||||
paints.push(gradient_paint(g, None, Some(&format!("Ramp {i}"))));
|
||||
}
|
||||
// The reader wouldn't read an even-odd fill with the style, so the style isn't written.
|
||||
let unstyled = two(Color::WHITE, Color::BLACK);
|
||||
let ap = Appearance {
|
||||
items: vec![AppearanceItem::Fill(FillLayer::new(gradient_paint(unstyled.clone(), None, None)))],
|
||||
effects: vec![fx("stylize.dropShadow", serde_json::json!({}))],
|
||||
contents_index: None,
|
||||
};
|
||||
let mut n = Node::path(doc.alloc_id(), shapes::rectangle(Rect::new(10.0, 10.0, 50.0, 40.0)), ap);
|
||||
if let NodeKind::Path { rule, .. } = &mut n.kind {
|
||||
*rule = FillRule::EvenOdd;
|
||||
}
|
||||
put(&mut doc, n);
|
||||
paints.push(gradient_paint(unstyled, None, None));
|
||||
let zero = |o: f32| ramp(GradientKind::Linear, &[(o, Color::rgb(0.2, 0.3, 0.4), 1.0, 0.5), (1.0, Color::BLACK, 1.0, 0.5)]);
|
||||
paints.extend([gradient_paint(zero(0.0), None, None), gradient_paint(zero(-0.0), None, None)]);
|
||||
for (i, p) in (0u16..).zip(paints) {
|
||||
let (x, y) = (f64::from(i % 60) * 5.0, f64::from(i / 60 % 40) * 5.0);
|
||||
let n = painted(&mut doc, shapes::rectangle(Rect::new(x, y, x + 4.0, y + 4.0)), vec![AppearanceItem::Fill(FillLayer::new(p))]);
|
||||
put(&mut doc, n);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
/// Gradient and pattern definitions found through their indexes are those found by comparing each
|
||||
/// in turn: the program is the same, byte for byte. A swatch's definition serves a paint linked to
|
||||
/// it only with the swatch's gradient; a gradient defined for a style that isn't written leaves its
|
||||
/// name free; gradients that differ only in the sign of a zero share a definition.
|
||||
#[test]
|
||||
fn indexed_definitions_write_the_same_program() {
|
||||
let doc = many_gradients(300, 300, 7, 6);
|
||||
let (indexed, scanned) = (program_scanned(&doc, false), program_scanned(&doc, true));
|
||||
let differ = indexed.iter().zip(&scanned).position(|(a, b)| a != b);
|
||||
assert!(indexed == scanned, "the programs differ from byte {differ:?} ({} and {} bytes)", indexed.len(), scanned.len());
|
||||
let text = String::from_utf8(indexed).unwrap();
|
||||
let names: Vec<&str> = text.lines().filter_map(|l| l.strip_prefix("%AI5_BeginGradient: ")).collect();
|
||||
// `gradients_and_patterns`'s 5, then 300 + 7 + 6 swatches' + 3 others linked to swatches + 1
|
||||
// after the style + 1 for both signs of zero.
|
||||
assert_eq!(names.len(), 5 + 300 + 7 + 6 + 3 + 1 + 1, "{names:?}");
|
||||
assert_eq!(names.iter().collect::<std::collections::HashSet<_>>().len(), names.len(), "{names:?}");
|
||||
assert_eq!(text.matches("%AI3_BeginPattern: (Dots)").count(), 1);
|
||||
}
|
||||
|
||||
/// A gradient paint is matched with the definitions of the same gradient, not with each
|
||||
/// definition: 1,000 gradients of their own and 1,000 paints of 10 others take a few comparisons
|
||||
/// each, where comparing each definition in turn takes hundreds of thousands.
|
||||
#[test]
|
||||
fn gradient_definitions_are_found_without_comparing_each() {
|
||||
let doc = many_gradients(1000, 1000, 10, 0);
|
||||
let comparisons = |scanned: bool| {
|
||||
writer::GRADIENT_COMPARISONS.with(|c| c.set(0));
|
||||
program_scanned(&doc, scanned);
|
||||
writer::GRADIENT_COMPARISONS.with(std::cell::Cell::get)
|
||||
};
|
||||
let (indexed, scanned) = (comparisons(false), comparisons(true));
|
||||
assert!(indexed <= 2 * 2010, "{indexed} comparisons through the index");
|
||||
assert!(scanned > 100 * indexed, "{scanned} comparisons scanning, {indexed} through the index");
|
||||
}
|
||||
|
||||
/// The time to write 5,000 rectangles with gradients of their own, 5,000 with 50 others and 20
|
||||
/// gradient swatches, with the definitions found by comparing each in turn and through their
|
||||
/// indexes: the median of 7 runs of each, alternating, with the programs compared. Run with
|
||||
/// `cargo test --release -p vectorcraft-eps --lib -- --ignored --nocapture gradient_definitions_timing`.
|
||||
#[test]
|
||||
#[ignore = "timing"]
|
||||
fn gradient_definitions_timing() {
|
||||
let doc = many_gradients(5000, 5000, 50, 20);
|
||||
let mut times = [vec![], vec![]];
|
||||
let mut programs: [Option<Vec<u8>>; 2] = [None, None];
|
||||
let mut how = "";
|
||||
for _ in 0..7 {
|
||||
for (k, scanned) in [true, false].into_iter().enumerate() {
|
||||
let (start, h) = thread_time();
|
||||
let program = program_scanned(&doc, scanned);
|
||||
times[k].push(thread_time().0.saturating_sub(start));
|
||||
how = h;
|
||||
programs[k].get_or_insert(program);
|
||||
}
|
||||
}
|
||||
assert_eq!(programs[0], programs[1]);
|
||||
for t in &mut times {
|
||||
t.sort();
|
||||
}
|
||||
let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
|
||||
println!("median of 7 runs ({how}):");
|
||||
println!("| definitions found | median (ms) | runs (ms) |");
|
||||
println!("|---|---:|---|");
|
||||
for (k, label) in ["by comparing each", "through the indexes"].into_iter().enumerate() {
|
||||
let runs: Vec<String> = times[k].iter().map(|d| format!("{:.1}", ms(*d))).collect();
|
||||
println!("| {label} | {:.1} | {} |", ms(times[k][3]), runs.join(", "));
|
||||
}
|
||||
}
|
||||
|
||||
/// A hard edge: a linear gradient whose stops all lie at one place is written from its last stop,
|
||||
/// and reads back with each stop on its side.
|
||||
#[test]
|
||||
|
||||
@@ -45,7 +45,8 @@ pub(super) use images::PAYLOAD;
|
||||
pub(super) use images::{IMAGE_DEPTH, IMAGES, LAST_SAMPLES_ONLY, LINKS_EMBEDDED, SAMPLE_LIMITS, SAMPLE_READS, SAMPLES_KEPT};
|
||||
#[cfg(test)]
|
||||
pub(super) use paints::{
|
||||
GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, STOP_LINKS, SWATCH_PLACEMENT, free_gradient_name,
|
||||
GRADIENT_COMPARISONS, GRADIENT_DITHER, GRADIENT_HUE, GRADIENT_PERCEPTUAL, GRADIENT_SHAPES, GRADIENTS, SCANNED_DEFINITIONS, STOP_LINKS,
|
||||
SWATCH_PLACEMENT, free_gradient_name,
|
||||
};
|
||||
#[cfg(test)]
|
||||
pub(super) use symbols::{MISSING_SYMBOL, SYMBOL_ART, SYMBOL_COUNT, SYMBOL_OPTIONS};
|
||||
@@ -200,11 +201,11 @@ pub(super) struct Writer<'a> {
|
||||
/// pattern's definition, the pattern's space turned y up.
|
||||
canvas: Affine,
|
||||
/// The gradient definitions, in the order they are first used.
|
||||
gradients: Vec<paints::GradientDef>,
|
||||
gradients: paints::GradientDefs,
|
||||
/// The number the next new gradient definition's name tries first (1 is `Gradient`).
|
||||
next_gradient: u64,
|
||||
/// The pattern definitions written, each after those its art uses.
|
||||
patterns: Vec<paints::PatternOut>,
|
||||
patterns: paints::PatternDefs,
|
||||
/// The patterns whose definitions are being written.
|
||||
defining: Vec<String>,
|
||||
/// Writing the palette: the definitions it adds are for its swatches only.
|
||||
@@ -357,9 +358,9 @@ impl<'a> Writer<'a> {
|
||||
grad_space: to_art,
|
||||
tile_grad_space: Affine::translate((-origin.0, origin.1)),
|
||||
canvas: Affine::new([1.0, 0.0, 0.0, -1.0, origin.0, origin.1]) * to_art,
|
||||
gradients: vec![],
|
||||
gradients: paints::GradientDefs::default(),
|
||||
next_gradient: 1,
|
||||
patterns: vec![],
|
||||
patterns: paints::PatternDefs::default(),
|
||||
defining: vec![],
|
||||
in_palette: false,
|
||||
canvas_origin: origin,
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
//! Gradients and patterns: their definitions in the setup, gradient instances on paths and the
|
||||
//! pattern operators (see [`crate::ai_editing`] for the form).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use vectorcraft_color::gradient::GradientGeom;
|
||||
use vectorcraft_color::swatch::REGISTRATION;
|
||||
@@ -46,6 +48,134 @@ pub(super) struct PatternOut {
|
||||
used: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
thread_local! {
|
||||
/// Whether [`GradientDefs`] and [`PatternDefs`] find definitions on this thread by comparing
|
||||
/// the gradient or name with each definition in turn.
|
||||
pub(in crate::ai_editing) static SCANNED_DEFINITIONS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||
/// How many times [`GradientDefs::find`] has compared two gradients on this thread.
|
||||
pub(in crate::ai_editing) static GRADIENT_COMPARISONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
|
||||
}
|
||||
|
||||
/// Are gradients `a` and `b` the same?
|
||||
fn same_gradient(a: &Gradient, b: &Gradient) -> bool {
|
||||
#[cfg(test)]
|
||||
GRADIENT_COMPARISONS.with(|c| c.set(c.get() + 1));
|
||||
a == b
|
||||
}
|
||||
|
||||
/// A key of `g` for [`GradientDefs`]: the same gradients have the same key (each number by its
|
||||
/// bits, with -0 as 0); different gradients may share one.
|
||||
fn gradient_key(g: &Gradient) -> u64 {
|
||||
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
|
||||
let mut h = std::hash::DefaultHasher::new();
|
||||
std::mem::discriminant(&g.kind).hash(&mut h);
|
||||
std::mem::discriminant(&g.method).hash(&mut h);
|
||||
(g.dither, g.spread, g.repeats, g.stops.len()).hash(&mut h);
|
||||
for s in &g.stops {
|
||||
let (model, c) = match s.color {
|
||||
Color::Rgb { r, g, b } => (0u8, [r, g, b, 0.0]),
|
||||
Color::Cmyk { c, m, y, k } => (1, [c, m, y, k]),
|
||||
Color::Gray { k } => (2, [k, 0.0, 0.0, 0.0]),
|
||||
Color::Lab { l, a, b } => (3, [l, a, b, 0.0]),
|
||||
};
|
||||
(model, c.map(bits), [s.offset, s.opacity, s.midpoint, s.tint].map(bits)).hash(&mut h);
|
||||
(&s.swatch, s.plates.map(|p| p.map(bits))).hash(&mut h);
|
||||
}
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The gradient definitions, in the order they are first used, found by name and by gradient
|
||||
/// without comparing each one.
|
||||
#[derive(Default)]
|
||||
pub(super) struct GradientDefs {
|
||||
list: Vec<GradientDef>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
/// The places in `list` of the definitions no swatch names, in order, by their gradient's key
|
||||
/// ([`gradient_key`]).
|
||||
ramps: HashMap<u64, Vec<usize>>,
|
||||
}
|
||||
|
||||
impl GradientDefs {
|
||||
/// Is `name` a definition's name?
|
||||
fn has_name(&self, name: &str) -> bool {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().any(|d| d.name == name);
|
||||
}
|
||||
self.names.contains_key(name)
|
||||
}
|
||||
|
||||
/// The place of the definition of `g`: the swatch `swatch` names when it is a gradient swatch
|
||||
/// of the same gradient, else the first definition of the same gradient that no swatch names.
|
||||
fn find(&self, g: &Gradient, swatch: Option<&str>) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return swatch
|
||||
.and_then(|s| self.list.iter().position(|d| d.swatch && d.name == s && same_gradient(&d.gradient, g)))
|
||||
.or_else(|| self.list.iter().position(|d| !d.swatch && same_gradient(&d.gradient, g)));
|
||||
}
|
||||
let held = |i: &usize, swatch: bool| self.list.get(*i).is_some_and(|d| d.swatch == swatch && same_gradient(&d.gradient, g));
|
||||
swatch
|
||||
.and_then(|s| self.names.get(s).copied().filter(|i| held(i, true)))
|
||||
.or_else(|| self.ramps.get(&gradient_key(g))?.iter().copied().find(|i| held(i, false)))
|
||||
}
|
||||
|
||||
/// Add `d`, whose name no definition has.
|
||||
fn push(&mut self, d: GradientDef) {
|
||||
let i = self.list.len();
|
||||
if !d.swatch {
|
||||
self.ramps.entry(gradient_key(&d.gradient)).or_default().push(i);
|
||||
}
|
||||
self.names.insert(d.name.clone(), i);
|
||||
self.list.push(d);
|
||||
}
|
||||
|
||||
/// Keep the first `len` definitions; the names of those removed are free again.
|
||||
fn truncate(&mut self, len: usize) {
|
||||
while self.list.len() > len {
|
||||
let Some(d) = self.list.pop() else { break };
|
||||
self.names.remove(&d.name);
|
||||
if !d.swatch {
|
||||
// Places are added in order, so the removed definition's is the last of its key's.
|
||||
let key = gradient_key(&d.gradient);
|
||||
if let Some(places) = self.ramps.get_mut(&key) {
|
||||
places.pop();
|
||||
if places.is_empty() {
|
||||
self.ramps.remove(&key);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern definitions written, each after those its art uses, found by name.
|
||||
#[derive(Default)]
|
||||
pub(super) struct PatternDefs {
|
||||
list: Vec<PatternOut>,
|
||||
/// Each definition's place in `list`, by its name (no two definitions share one).
|
||||
names: HashMap<String, usize>,
|
||||
}
|
||||
|
||||
impl PatternDefs {
|
||||
/// The place of pattern `name`'s definition.
|
||||
fn find(&self, name: &str) -> Option<usize> {
|
||||
#[cfg(test)]
|
||||
if SCANNED_DEFINITIONS.with(std::cell::Cell::get) {
|
||||
return self.list.iter().position(|p| p.name == name);
|
||||
}
|
||||
self.names.get(name).copied()
|
||||
}
|
||||
|
||||
/// Add `p`, whose name no definition has.
|
||||
fn push(&mut self, p: PatternOut) {
|
||||
self.names.insert(p.name.clone(), self.list.len());
|
||||
self.list.push(p);
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::ai_editing) const DIAMOND: &str =
|
||||
"diamond gradients are written as radial gradients through their corners, with the same stops, in the editing data for other apps";
|
||||
pub(in crate::ai_editing) const SPREAD: &str = "gradients that repeat or reflect are written with their stops repeated across the shape (at most 256 stops, padding past them) in the editing data for other apps";
|
||||
@@ -118,7 +248,7 @@ impl Writer<'_> {
|
||||
&& let stops = curve_as_stops(&g.gradient)
|
||||
&& let gradient = stops.unrolled_within(crate::import::MAX_GRADIENT_STOPS)
|
||||
&& writable_gradient(&gradient)
|
||||
&& !self.gradients.iter().any(|d| d.name == sw.name)
|
||||
&& !self.gradients.has_name(&sw.name)
|
||||
{
|
||||
self.gradients.push(GradientDef { name: sw.name.clone(), gradient: gradient.into_owned(), swatch: true, used: false });
|
||||
}
|
||||
@@ -131,17 +261,14 @@ impl Writer<'_> {
|
||||
/// swatch or a pattern).
|
||||
fn define_gradient(&mut self, g: &Gradient, swatch: Option<&str>) -> String {
|
||||
let used = !self.in_palette;
|
||||
let found = swatch
|
||||
.and_then(|s| self.gradients.iter().position(|d| d.swatch && d.name == s && d.gradient == *g))
|
||||
.or_else(|| self.gradients.iter().position(|d| !d.swatch && d.gradient == *g));
|
||||
if let Some(d) = found.and_then(|i| self.gradients.get_mut(i)) {
|
||||
let found = self.gradients.find(g, swatch);
|
||||
if let Some(d) = found.and_then(|i| self.gradients.list.get_mut(i)) {
|
||||
d.used |= used;
|
||||
return d.name.clone();
|
||||
}
|
||||
let (doc, gradients) = (self.doc, &self.gradients);
|
||||
let name = free_gradient_name(&mut self.next_gradient, |name| {
|
||||
gradients.iter().any(|d| d.name == name) || doc.swatch(name).is_some() || doc.pattern(name).is_some()
|
||||
});
|
||||
let name =
|
||||
free_gradient_name(&mut self.next_gradient, |name| gradients.has_name(name) || doc.swatch(name).is_some() || doc.pattern(name).is_some());
|
||||
self.gradients.push(GradientDef { name: name.clone(), gradient: g.clone(), swatch: false, used });
|
||||
name
|
||||
}
|
||||
@@ -149,14 +276,14 @@ impl Writer<'_> {
|
||||
/// The gradient definitions' state, for [`Self::gradient_rollback`]: their count, which ones the
|
||||
/// art uses, and the next name's number.
|
||||
pub(super) fn gradient_mark(&self) -> (usize, Vec<bool>, u64) {
|
||||
(self.gradients.len(), self.gradients.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
(self.gradients.list.len(), self.gradients.list.iter().map(|d| d.used).collect(), self.next_gradient)
|
||||
}
|
||||
|
||||
/// The gradient definitions as they were at `mark` ([`Self::gradient_mark`]).
|
||||
pub(super) fn gradient_rollback(&mut self, mark: (usize, Vec<bool>, u64)) {
|
||||
let (len, used, next) = mark;
|
||||
self.gradients.truncate(len);
|
||||
for (d, u) in self.gradients.iter_mut().zip(used) {
|
||||
for (d, u) in self.gradients.list.iter_mut().zip(used) {
|
||||
d.used = u;
|
||||
}
|
||||
self.next_gradient = next;
|
||||
@@ -476,7 +603,7 @@ impl Writer<'_> {
|
||||
if !self.defining.is_empty() || self.nest >= MAX_NEST || self.in_symbol {
|
||||
return false;
|
||||
}
|
||||
if self.patterns.iter().any(|p| p.name == name) {
|
||||
if self.patterns.find(name).is_some() {
|
||||
return true;
|
||||
}
|
||||
self.doc.pattern(name).is_some_and(tile_holds_art)
|
||||
@@ -492,7 +619,7 @@ impl Writer<'_> {
|
||||
return false;
|
||||
}
|
||||
let used = !self.in_palette;
|
||||
if let Some(p) = self.patterns.iter_mut().find(|p| p.name == name) {
|
||||
if let Some(p) = self.patterns.find(name).and_then(|i| self.patterns.list.get_mut(i)) {
|
||||
p.used |= used;
|
||||
return true;
|
||||
}
|
||||
@@ -582,7 +709,7 @@ impl Writer<'_> {
|
||||
/// uses).
|
||||
pub(in crate::ai_editing) fn definitions(&mut self, s: &mut String) {
|
||||
let defs = std::mem::take(&mut self.gradients);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.iter().partition(|d| d.used);
|
||||
let (used, unused): (Vec<&GradientDef>, Vec<&GradientDef>) = defs.list.iter().partition(|d| d.used);
|
||||
let _ = writeln!(s, "{} Bn", used.len());
|
||||
for d in &used {
|
||||
self.gradient_def(s, d);
|
||||
@@ -595,12 +722,12 @@ impl Writer<'_> {
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
}
|
||||
self.gradients = defs;
|
||||
for p in self.patterns.iter().filter(|p| p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
if self.patterns.iter().any(|p| !p.used) {
|
||||
if self.patterns.list.iter().any(|p| !p.used) {
|
||||
s.push_str("%AI5_Begin_NonPrinting\nNp\n");
|
||||
for p in self.patterns.iter().filter(|p| !p.used) {
|
||||
for p in self.patterns.list.iter().filter(|p| !p.used) {
|
||||
s.push_str(&p.text);
|
||||
}
|
||||
s.push_str("%AI5_End_NonPrinting--\n");
|
||||
@@ -729,3 +856,94 @@ fn tile_holds_art(def: &PatternDef) -> bool {
|
||||
b.x0 >= room.x0 && b.y0 >= room.y0 && b.x1 <= room.x1 && b.y1 <= room.y1
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn two(a: f32, b: Color) -> Gradient {
|
||||
Gradient::new(GradientKind::Linear, vec![GradientStop::new(a, Color::rgb(0.2, 0.4, 0.6)), GradientStop::new(1.0, b)])
|
||||
}
|
||||
|
||||
fn def(name: &str, gradient: Gradient, swatch: bool) -> GradientDef {
|
||||
GradientDef { name: name.into(), gradient, swatch, used: true }
|
||||
}
|
||||
|
||||
/// The same gradients have the same key, a zero of either sign included.
|
||||
#[test]
|
||||
fn a_zero_of_either_sign_gives_the_same_key() {
|
||||
assert_eq!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(-0.0, Color::BLACK)));
|
||||
assert_eq!(two(0.0, Color::BLACK), two(-0.0, Color::BLACK));
|
||||
assert_ne!(gradient_key(&two(0.0, Color::BLACK)), gradient_key(&two(0.0, Color::WHITE)));
|
||||
}
|
||||
|
||||
/// Definitions whose gradients share a key are told apart by their gradients, the first of the
|
||||
/// same gradient found; a gradient that isn't equal to itself is found in none.
|
||||
#[test]
|
||||
fn definitions_that_share_a_key_are_told_apart() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Gradient", white.clone(), false));
|
||||
defs.push(def("Gradient 2", black.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
// Every definition under the black gradient's key, as if the keys of both were the same.
|
||||
defs.ramps = HashMap::from([(gradient_key(&black), vec![0, 1, 2])]);
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
defs.ramps.insert(gradient_key(&white), vec![0, 1, 2]);
|
||||
assert_eq!(defs.find(&white, None), Some(0));
|
||||
let nan = two(f32::NAN, Color::BLACK);
|
||||
defs.push(def("Gradient 4", nan.clone(), false));
|
||||
assert_eq!(defs.find(&nan, None), None);
|
||||
}
|
||||
|
||||
/// A swatch's definition is found by the swatch's name and gradient; a definition that no
|
||||
/// swatch names, for the same gradient without the name or with another.
|
||||
#[test]
|
||||
fn a_swatch_definition_is_found_by_its_name_and_gradient() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", black.clone(), true));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), None);
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), None);
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&black, Some("Ramp")), Some(0));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, Some("Ramp")), Some(2));
|
||||
assert_eq!(defs.find(&black, Some("Other")), Some(1));
|
||||
}
|
||||
|
||||
/// Definitions removed leave their names free and are no longer found; those kept still are.
|
||||
#[test]
|
||||
fn removed_definitions_free_their_names() {
|
||||
let (black, white) = (two(0.0, Color::BLACK), two(0.0, Color::WHITE));
|
||||
let mut defs = GradientDefs::default();
|
||||
defs.push(def("Ramp", white.clone(), true));
|
||||
defs.push(def("Gradient", black.clone(), false));
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
defs.push(def("Gradient 3", black.clone(), false));
|
||||
defs.truncate(2);
|
||||
assert!(defs.has_name("Ramp") && defs.has_name("Gradient"));
|
||||
assert!(!defs.has_name("Gradient 2") && !defs.has_name("Gradient 3"));
|
||||
assert_eq!(defs.find(&black, None), Some(1));
|
||||
assert_eq!(defs.find(&white, None), None);
|
||||
assert_eq!(defs.ramps.values().map(Vec::len).sum::<usize>(), 1);
|
||||
defs.push(def("Gradient 2", white.clone(), false));
|
||||
assert_eq!(defs.find(&white, None), Some(2));
|
||||
defs.truncate(0);
|
||||
assert!(defs.list.is_empty() && defs.names.is_empty() && defs.ramps.is_empty());
|
||||
}
|
||||
|
||||
/// A pattern's definition is found by its name.
|
||||
#[test]
|
||||
fn pattern_definitions_are_found_by_name() {
|
||||
let mut defs = PatternDefs::default();
|
||||
assert_eq!(defs.find("Dots"), None);
|
||||
for name in ["Dots", "Checks"] {
|
||||
defs.push(PatternOut { name: name.into(), text: String::new(), used: false });
|
||||
}
|
||||
assert_eq!((defs.find("Dots"), defs.find("Checks"), defs.find("Stripes")), (Some(0), Some(1), None));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user