Symbols: refuse bad Symbolism Tools Options and find spacing with a k-d tree

tool.setOption for a Symbolism tool now refuses a method or Symbol
Sprayer value outside its lists, and a usePressure, showBrush,
proportional or affectsDensity that is not true or false, and sets
none of the values. The Symbolism Tools Options dialog checks the same
values before it gives the selected symbol sets a new density.

Scrunch: Average measured each instance's nearest neighbor by scanning
the grid cell around it, which compared every pair when many instances
shared a cell. A k-d tree of the instances under the brush now finds
each one's nearest neighbor.
This commit is contained in:
dotCooCoo committed 2026-11-15 22:51:30 -08:00
1 parent 6d470d9878
commit b3c15f6e73
7 files changed
+135 -32

No files matched your search

+66 -28
View File
@@ -163,34 +163,65 @@ pub(super) struct Mean {
pub gap: Option<f64>,
}
/// For each of `looks`, the distance to the nearest of the others (infinite for one alone). Each
/// is first looked for in the cells around it of a grid `cell` points wide: one found within `cell`
/// is the nearest, since every one that near is in those cells. Otherwise all are measured.
fn nearest_gaps(looks: &[&Look], cell: f64) -> Vec<f64> {
let cell = cell.max(1e-6);
let mut cells: HashMap<(i64, i64), Vec<usize>> = HashMap::new();
for (i, l) in looks.iter().enumerate() {
cells.entry(key(l.center, cell)).or_default().push(i);
/// The x (`axis` 0) or y (`axis` 1) of `p`.
fn coord(p: Point, axis: usize) -> f64 {
if axis == 0 { p.x } else { p.y }
}
/// Arrange `order` (indices into `pts`) as a k-d tree: the middle entry of each slice splits the
/// rest by x at even depths and by y at odd ones, the smaller values before it.
fn kd_build(order: &mut [usize], pts: &[Point], axis: usize) {
if order.len() <= 1 {
return;
}
let distance = |i: usize, j: usize| if i == j { None } else { Some(looks.get(j)?.center.distance(looks.get(i)?.center)) };
(0..looks.len())
let mid = order.len() / 2;
let at = |i: &usize| pts.get(*i).map_or(0.0, |p| coord(*p, axis));
order.select_nth_unstable_by(mid, |a, b| at(a).total_cmp(&at(b)));
let (left, right) = order.split_at_mut(mid);
kd_build(left, pts, 1 - axis);
kd_build(right.get_mut(1..).unwrap_or_default(), pts, 1 - axis);
}
/// The distance from `pts[i]` to the nearest of the others in k-d tree `order`, if nearer than
/// `best`. Instances on top of each other end the search: none can be nearer.
fn kd_nearest(order: &[usize], pts: &[Point], axis: usize, i: usize, best: &mut f64) {
let (Some(&j), Some(&p)) = (order.get(order.len() / 2), pts.get(i)) else { return };
let Some(&q) = pts.get(j) else { return };
if j != i {
*best = best.min(p.distance(q));
}
if *best == 0.0 {
return;
}
let (left, right) = order.split_at(order.len() / 2);
let right = right.get(1..).unwrap_or_default();
let diff = coord(p, axis) - coord(q, axis);
let (near, far) = if diff < 0.0 { (left, right) } else { (right, left) };
kd_nearest(near, pts, 1 - axis, i, best);
// The other side holds nothing nearer than the split line.
if diff.abs() < *best {
kd_nearest(far, pts, 1 - axis, i, best);
}
}
/// For each of `looks`, the distance to the nearest of the others (infinite for one alone), found
/// through a k-d tree of their centers.
fn nearest_gaps(looks: &[&Look]) -> Vec<f64> {
let pts: Vec<Point> = looks.iter().map(|l| l.center).collect();
let mut order: Vec<usize> = (0..pts.len()).collect();
kd_build(&mut order, &pts, 0);
(0..pts.len())
.map(|i| {
let mut best = f64::INFINITY;
for j in around(&cells, looks.get(i).map_or(Point::ZERO, |l| l.center), cell) {
best = distance(i, j).map_or(best, |d| best.min(d));
// Instances on top of each other: none can be nearer.
if best == 0.0 {
break;
}
}
if best <= cell { best } else { (0..looks.len()).filter_map(|j| distance(i, j)).fold(f64::INFINITY, f64::min) }
kd_nearest(&order, &pts, 0, i, &mut best);
best
})
.collect()
}
/// The [`Mean`] of `looks`, the instances under a brush centered on `at` (None for none), with
/// [`Mean::gap`] when `gap_cell` gives the grid width [`nearest_gaps`] uses.
pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option<f64>) -> Option<Mean> {
/// [`Mean::gap`] when `with_gap` is set.
pub(super) fn mean(looks: &[&Look], at: Point, with_gap: bool) -> Option<Mean> {
if looks.is_empty() {
return None;
}
@@ -215,7 +246,7 @@ pub(super) fn mean(looks: &[&Look], at: Point, gap_cell: Option<f64>) -> Option<
// Rotations that cancel out have no mean direction: the first instance's stands for it.
let angle = if sin.hypot(cos) > 1e-9 { sin.atan2(cos) } else { looks[0].angle };
// One instance under the brush has no spacing there.
let gap = gap_cell.filter(|_| looks.len() > 1).map(|cell| nearest_gaps(looks, cell).iter().sum::<f64>() / n);
let gap = (with_gap && looks.len() > 1).then(|| nearest_gaps(looks).iter().sum::<f64>() / n);
Some(Mean {
scale: (log_scale / n).exp(),
angle,
@@ -273,7 +304,7 @@ impl Grid {
pub fn mean(&self, at: Point, radius: f64, with_gap: bool) -> Option<Mean> {
let near: Vec<&Look> =
around(&self.cells, at, self.cell).filter_map(|i| self.looks.get(i)).filter(|l| l.center.distance(at) <= radius).collect();
mean(&near, at, with_gap.then_some(radius / 4.0))
mean(&near, at, with_gap)
}
}
@@ -358,20 +389,27 @@ mod tests {
Look { center: Point::new(x, y), scale: 1.0, angle: 0.0, opacity: 1.0, fill: None }
}
/// The distance from each instance in `from` to the nearest other one in `refs`, measured
/// against every other instance.
fn brute(refs: &[&Look], from: impl Iterator<Item = usize>) -> Vec<f64> {
from.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min)).collect()
}
/// The gaps are each instance's distance to its nearest neighbor, measured against every other
/// instance: close pairs whose members are far apart in the order, instances on top of each
/// other, and instances farther apart than the grid's cells.
/// other, instances far from all others, many instances close together, and many on one line.
#[test]
fn nearest_gaps_match_measuring_every_pair() {
let mut looks: Vec<Look> = (0..300).map(|i| at(f64::from(i % 20) * 9.0, f64::from(i / 20) * 7.0)).collect();
// The second member of each pair comes 300 places later.
looks.extend((0..300).map(|i| at(f64::from(i % 20) * 9.0 + 0.5, f64::from(i / 20) * 7.0)));
looks.extend([at(500.0, 500.0), at(500.0, 500.0), at(900.0, 40.0)]);
// 400 instances within one point of each other, and 200 on one upright line.
looks.extend((0..400).map(|i| at(700.0 + f64::from(i % 20) * 0.05, 700.0 + f64::from(i / 20) * 0.05)));
looks.extend((0..200).map(|i| at(-50.0, f64::from(i) * 1.5)));
let refs: Vec<&Look> = looks.iter().collect();
let brute: Vec<f64> = (0..refs.len())
.map(|i| (0..refs.len()).filter(|j| *j != i).map(|j| refs[i].center.distance(refs[j].center)).fold(f64::INFINITY, f64::min))
.collect();
assert_eq!(nearest_gaps(&refs, 10.0), brute);
assert_eq!(nearest_gaps(&refs[..1], 10.0), [f64::INFINITY]);
assert_eq!(nearest_gaps(&refs), brute(&refs, 0..refs.len()));
assert_eq!(nearest_gaps(&refs[..1]), [f64::INFINITY]);
assert_eq!(nearest_gaps(&refs[..0]), Vec::<f64>::new());
}
}
+1 -1
View File
@@ -1129,7 +1129,7 @@ pub(super) fn symbol_adjust(s: &mut Session, p: &Value) -> Result<Value> {
.then(|| {
let under = |n: &&Node| instance_center(n).is_some_and(|c| c.distance(*q) <= radius);
let looks: Vec<_> = candidates.iter().filter_map(|id| d.node(*id).filter(under).and_then(|n| look(d, n))).collect();
mean(&looks.iter().collect::<Vec<_>>(), *q, None)
mean(&looks.iter().collect::<Vec<_>>(), *q, false)
})
.flatten();
for id in &candidates {
@@ -119,6 +119,26 @@ fn average_brings_the_instances_under_the_brush_toward_their_mean() {
assert!(pa > oa && pb < 1.0 && (pa - pb).abs() < (1.0 - oa) / 2.0, "{pa} {pb} from {oa}");
}
/// `tool.setOption` refuses a Method, a Symbol Sprayer option or a checkbox value the Symbolism Tools
/// Options do not have, and sets none of the values given with it.
#[test]
fn bad_symbolism_tool_options_are_refused() {
let mut s = session();
let before = s.tool_options_of("symbolSizer");
for (values, want) in [
(json!({"proportional": false, "method": "smooth"}), "`method` must be one of userDefined, average, random"),
(json!({"sprayScrunch": "random"}), "`sprayScrunch` must be one of average, userDefined"),
(json!({"method": "average", "usePressure": 1}), "`usePressure` must be true or false"),
(json!({"affectsDensity": "yes"}), "`affectsDensity` must be true or false"),
] {
let r = s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "values": values}));
assert_eq!(r, Err(want.to_string()), "{values}");
assert_eq!(s.tool_options_of("symbolSizer"), before, "{values}");
}
s.set_tool_option_cmd(&json!({"tool": "symbolSizer", "key": "method", "value": "random"})).unwrap();
assert_eq!(s.tool_options_of("symbolSizer")["method"], json!("random"));
}
/// Average opacities below the Symbol Screener's least opacity (5%) stay below it: with the Screener
/// the instances meet at their mean, and a sprayed instance takes the mean of those under the brush.
#[test]
+1
View File
@@ -1347,6 +1347,7 @@ impl Session {
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
vectorcraft_tools::symbolism::check_options(tool.unwrap_or(self.tool.id()), &values)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
+24
View File
@@ -72,6 +72,30 @@ pub struct SymbolismTool {
pub affects_density: bool,
}
/// Checks the Symbolism Tools Options in `values` before `tool.setOption` sets any, when `tool` is
/// a symbolism tool: `method` that is not one of [`METHODS`], a Symbol Sprayer option that is not
/// one of [`SPRAY_MODES`], and `usePressure`, `showBrush`, `proportional` or `affectsDensity` that
/// is not true or false are errors. Ok for every other tool and every other key. Saved settings go
/// to the tool's `set_option` instead, which skips a value it cannot read.
pub fn check_options(tool: &str, values: &serde_json::Map<String, Value>) -> Result<(), String> {
if !tool.starts_with("symbol") || create(tool).is_none() {
return Ok(());
}
let must_be = |key: &str, names: &[&str]| format!("`{key}` must be one of {}", names.join(", "));
for (key, v) in values {
let error = match key.as_str() {
"usePressure" | "showBrush" | "proportional" | "affectsDensity" => (!v.is_boolean()).then(|| format!("`{key}` must be true or false")),
"method" => one_of(v, &METHODS).is_none().then(|| must_be(key, &METHODS)),
k if SPRAY_ATTRIBUTES.iter().any(|(a, _)| *a == k) => one_of(v, &SPRAY_MODES).is_none().then(|| must_be(key, &SPRAY_MODES)),
_ => None,
};
if let Some(e) = error {
return Err(e);
}
}
Ok(())
}
/// `v` as one of `allowed`, when it is one.
fn one_of(v: &Value, allowed: &[&'static str]) -> Option<&'static str> {
let s = v.as_str()?;
@@ -121,8 +121,10 @@ fn selected_sets(app: &VectorcraftApp) -> Vec<u64> {
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> DialogResult {
let mut values: Map<String, Value> =
NUMBERS.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.f64(k, 0.0)))).collect();
values.extend(SWITCHES.iter().filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.bool(k)))));
values.extend(SPRAY.iter().chain(&["method"]).filter(|k| d.fields.contains_key(**k)).map(|k| (k.to_string(), json!(d.str(k)))));
// The checkboxes and choices as the fields hold them, so a value the tools do not have is refused.
values.extend(SWITCHES.iter().chain(&SPRAY).chain(&["method"]).filter_map(|k| Some((k.to_string(), d.fields.get(*k)?.clone()))));
// An option `tool.setOption` refuses leaves the symbol sets as they are too.
vectorcraft_tools::symbolism::check_options(&d.str("tool"), &values)?;
let (from, to) = (d.f64(DENSITY_WAS, 0.0).clamp(1.0, 10.0), d.f64("density", 0.0).clamp(1.0, 10.0));
let sets = selected_sets(app);
if d.fields.contains_key(DENSITY_WAS) && from != to && !sets.is_empty() {
@@ -265,6 +267,22 @@ mod tests {
assert!(width(&app) < was * 0.8, "{} of {was}", width(&app));
assert_eq!(undo(&app), steps + 1);
assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0));
// An option the tools do not have: neither the set nor the options change.
let (was, steps) = (width(&app), undo(&app));
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("density".into(), json!(3));
d.fields.insert("method".into(), json!("smooth"));
assert!(super::super::confirm(&mut app).is_err());
assert_eq!((width(&app), undo(&app)), (was, steps));
app.run("tool.options", json!({"tool": "symbolSprayer"})).unwrap();
let d = app.ui.dialog.as_mut().unwrap();
d.fields.insert("density".into(), json!(3));
d.fields.insert("usePressure".into(), json!(1));
assert!(super::super::confirm(&mut app).is_err());
assert_eq!((width(&app), undo(&app)), (was, steps));
assert_eq!(app.session.tool_options_of("symbolSizer")["density"].as_f64(), Some(9.0));
app.ui.dialog = None;
// Without a set selected only the option changes.
app.run("select.set", json!({"ids": []})).unwrap();
let (was, steps) = (width(&app), undo(&app));
+3 -1
View File
@@ -11296,7 +11296,9 @@ intensity), and the Symbolism tools one brush: `diameter` (80), `intensity` (5),
`method` (`userDefined`), `showBrush` (true), `sprayScrunch`, `spraySize`, `spraySpin`, `sprayScreen`, `sprayStain`
and `sprayStyle` (each `average`), `proportional` (true) and `affectsDensity` (false); these starting values are
VectorCraft's own. With `showBrush` the brush's outline follows the pointer, with a dashed ring inside it at
`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). Interaction state (pins, a reference point) starts afresh. In the
`intensity`/10 of its radius (no ring at 10, with `usePressure` or for the Symbol Sprayer, which uses neither). For a
Symbolism tool, a `method` or Symbol Sprayer value not in those lists, or a `usePressure`, `showBrush`, `proportional`
or `affectsDensity` that is not true or false, is an error that sets none of the values. Interaction state (pins, a reference point) starts afresh. In the
desktop app, while the Artboard tool is in use, a change to its `selected` or `active` makes the artboard it then has
active the active artboard (the navigator's and the Artboards panel's).