mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 19:11:26 +00:00
Merge pull request #8178 from dotCooCoo/feat/image-trace-split-view
Image Trace: Split View shows the source image and the result on either side of a divider
This commit is contained in:
@@ -145,7 +145,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Make",
|
||||
["Object", "Image Trace"],
|
||||
None,
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
"{id?: image or Image Trace group (default: selection), preset?: name (imageTrace.presets), savedPreset?: {settings} (a saved preset's settings, which the journal records so a replay traces with them after the preset is changed, renamed or deleted; used in place of the saved preset `preset` names), enhanced?: false (the preset's enhanced version: with Auto Grouping, and with Shapes in all but High Fidelity Photo; Flat Logo has none and is traced as it is), params?: {mode: \"blackAndWhite\"|\"grayscale\"|\"color\"|\"logo\", threshold: 0-255, palette: \"limited\"|\"fullTone\"|\"automatic\"|\"documentLibrary\" (color mode; limited: the `colors` best colours, fullTone: as many as the tones need, more with colorDetail, split into at least colorDetail colors where the image has that many before colors that look alike merge (less than 5 apart in Oklab × 100 and thoroughly mixed, or less than 1.5 and mixed in patches), automatic: flat art with its own colours, else as many as the tones need without fullTone's least count, merging close RGB colors, documentLibrary: at most `colors` of the library's colours, as they are), colors: 2-256, colorDetail: 0-100 (fullTone, automatic), library: \"document\" (the document's swatches) or a swatch library id or name (swatch.library.list; documentLibrary), colorGroup?: name (color mode, documentLibrary with library \"document\": the colors of that document color group instead of every swatch; \"\" is every swatch), paths: 0-100, corners: 0-100, noise: px (an area smaller than this joins the color it shares the longest border with; when that color is far from its own and the area is 2 px or more, or a single pixel whose longest border is not tied between colors, it joins the neighboring color nearest its pixels among those sharing at least a tenth of that border), method: \"abutting\"|\"overlapping\" (abutting with fills, not mode logo: a \"Seam Fills\" clip group under the paths holds strokes along the edges two filled paths share, 1.5 image pixels wide (VectorCraft's own width), in the color of the lower path (on an image stretched more one way than another, each stroke's outline in image pixels as a filled path), clipped to the image's box within the traced paths' box; paths that became live shapes get none; the paths are not changed), ignoreWhite (leave out white areas), ignoreColor?: \"#rrggbb\" (with ignoreWhite: the colour left out instead of white), ignoreBackground: false (with ignoreWhite: only the areas of the ignored color that reach the image's edge are left out), keepColors?: [\"#rrggbb\"…] (not mode logo: only the palette colors within about 30 levels of a listed color are traced; empty: every color), snapCurvesToLines, shapes: false (filled outlines that are a circle, an ellipse, a rectangle or a regular polygon come out as that live shape), autoGrouping: false (each path that has others inside it is grouped with them), gradients: false (grayscale and color: an area whose colour changes evenly along one direction is one path with a linear gradient fill), fills: true, strokes: false (Create: lines up to strokeWidth wide become stroked centre lines; without fills, wider areas become stroked outlines), strokeWidth: px (10), logoColors?: [\"#rrggbb\"…] (mode logo: flat-colour logos only; colours found automatically or named here, at most ten; white is its own color, and a named color with every channel 245 or more is taken as that white, except with logoColors named, logoWhite false and no ignoreWhite; noise = areas under noise/10 px ignored; edges to a fraction of a pixel, sharp corners restored, lines and circles snapped; enclosed transparent areas are painted white while white is its own color, and stay holes with ignoreWhite or without a white of its own; fills/strokes are ignored; gradients and photos are refused, judged by the image's own colors also when logoColors are named), logoWhite: true (mode logo with logoColors named; false traces the named colors only: white areas take the nearest of them, a named white is kept and enclosed transparent areas stay holes; with ignoreWhite, white areas are left out either way)}, view?: as imageTrace.setView (default: the traced object's own, else tracingResult; the Split view keeps the traced object's divider, else 0.5, and imageTrace.setView sets it), ids?: [id…] (instead of id)} → {id, paths, anchors, colors, warnings: [text…] (the image is over 1500 px on a side, so it traces more slowly; or it was traced scaled down; Flat Logo names only the size it traced a larger image at; or a keepColors color matches none the trace found, or nothing was traced)}",
|
||||
has_selection_or_ids,
|
||||
|s, p| trace_make(s, p, false)
|
||||
),
|
||||
@@ -181,7 +181,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Image Trace View",
|
||||
[],
|
||||
None,
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"} how they draw on screen; exports, printing and Expand keep the tracing result → {ids, view}",
|
||||
"{id?|ids?: Image Trace objects (default: selection), view: \"tracingResult\"|\"tracingResultWithOutlines\"|\"outlines\"|\"outlinesWithSourceImage\"|\"sourceImage\"|\"split\" (the source image on the part of the image left of a divider across it, and the tracing result everywhere else), split?: 0-1 (the divider: the fraction of the source image's width, from its left edge, that shows the image; kept as it was when omitted, 0.5 for a new one)} how they draw on screen; exports, printing and Expand keep the tracing result, and tracing again keeps the view and the divider → {ids, view, split (view split: the first object's divider)}",
|
||||
has_selection_or_ids,
|
||||
trace_set_view
|
||||
),
|
||||
|
||||
@@ -58,6 +58,12 @@ fn view_param(cmd: &str, p: &Value) -> Result<Option<TraceView>> {
|
||||
v.as_str().and_then(TraceView::from_id).map(Some).ok_or_else(|| bad(cmd, format!("view must be one of {}", ids())))
|
||||
}
|
||||
|
||||
/// The `split` param (the Split view's divider, 0 to 1), if given.
|
||||
fn split_param(cmd: &str, p: &Value) -> Result<Option<f64>> {
|
||||
let Some(v) = p.get("split").filter(|v| !v.is_null()) else { return Ok(None) };
|
||||
v.as_f64().filter(|f| (0.0..=1.0).contains(f)).map(Some).ok_or_else(|| bad(cmd, "split must be a number from 0 to 1"))
|
||||
}
|
||||
|
||||
/// A saved Image Trace preset ([`crate::Prefs::trace_presets`]): a name and its settings.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
@@ -1026,9 +1032,14 @@ pub(super) fn trace_make(s: &mut Session, p: &Value, expand: bool) -> Result<Val
|
||||
let mut g = Node::group(gid, children);
|
||||
g.name = if expand { None } else { Some(TRACE_NAME.into()) };
|
||||
if !expand {
|
||||
// Tracing again keeps the object's view unless another is asked for.
|
||||
// Tracing again keeps the object's view unless another is asked for, and the Split
|
||||
// view's divider.
|
||||
let view = view.unwrap_or_else(|| src.trace_view());
|
||||
g.extras_mut().trace = Some(Box::new(json!({ "preset": preset_label, "params": params_json, "view": view.id() })));
|
||||
let mut t = json!({ "preset": preset_label, "params": params_json, "view": view.id() });
|
||||
if let Some(split) = src.extras().trace.as_deref().and_then(|t| t.get("split")).filter(|v| !v.is_null()) {
|
||||
t["split"] = split.clone();
|
||||
}
|
||||
g.extras_mut().trace = Some(Box::new(t));
|
||||
}
|
||||
let (par, idx, _) = d.position(target).ok_or(EngineError::NoNode(target))?;
|
||||
d.remove(target)?;
|
||||
@@ -1127,23 +1138,37 @@ fn trace_targets(s: &Session, p: &Value) -> Result<Vec<NodeId>> {
|
||||
pub(super) fn trace_set_view(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const C: &str = "imageTrace.setView";
|
||||
let view = view_param(C, p)?.ok_or_else(|| bad(C, "view is required"))?;
|
||||
let split = split_param(C, p)?;
|
||||
let targets = trace_targets(s, p)?;
|
||||
let d = &s.doc()?.doc;
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view)) {
|
||||
return Ok(json!({ "ids": ids_json(&targets), "view": view.id() }));
|
||||
let result = |d: &vectorcraft_doc::Document| {
|
||||
let mut r = json!({ "ids": ids_json(&targets), "view": view.id() });
|
||||
if view == TraceView::Split
|
||||
&& let Some(n) = targets.first().and_then(|g| d.node(*g))
|
||||
{
|
||||
r["split"] = json!(split.unwrap_or_else(|| n.trace_split()));
|
||||
}
|
||||
r
|
||||
};
|
||||
if targets.iter().all(|g| d.node(*g).is_some_and(|n| n.trace_view() == view && split.is_none_or(|f| n.trace_split() == f))) {
|
||||
return Ok(result(d));
|
||||
}
|
||||
s.edit("Image Trace View", |d, _| {
|
||||
for g in &targets {
|
||||
let n = d.node_mut(*g).ok_or(EngineError::NoNode(*g))?;
|
||||
if n.extras_if_any().and_then(|e| e.trace.as_deref()).is_none_or(|t| !t.is_object()) {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom" })));
|
||||
}
|
||||
if let Some(t) = n.extras_if_any().and_then(|e| e.trace.as_deref_mut()).and_then(Value::as_object_mut) {
|
||||
t.insert("view".into(), json!(view.id()));
|
||||
} else {
|
||||
n.extras_mut().trace = Some(Box::new(json!({ "preset": "Custom", "view": view.id() })));
|
||||
if let Some(f) = split {
|
||||
t.insert("split".into(), json!(f));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
Ok(json!({ "ids": ids_json(&targets), "view": view.id() }))
|
||||
Ok(result(&s.doc()?.doc))
|
||||
}
|
||||
|
||||
pub(super) fn trace_release(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
|
||||
@@ -8617,6 +8617,54 @@ fn image_trace_view_is_stored_kept_and_validated() {
|
||||
assert!(s.execute("imageTrace.setView", &json!({"id": a.0, "view": "outlines"})).is_err());
|
||||
}
|
||||
|
||||
/// The Split view's divider is set with the view, kept when omitted, when tracing again and through
|
||||
/// save and open, adds no undo step when unchanged and one when changed, and is checked. On screen
|
||||
/// the source image shows left of it and the result right of it; exports draw the result.
|
||||
#[test]
|
||||
fn image_trace_split_view_keeps_and_validates_its_divider() {
|
||||
let mut s = session();
|
||||
let g = disc_on_blue(&mut s);
|
||||
// The image covers 50 to 250 across; the disc 90 to 210, so the divider moves over the disc.
|
||||
let r = s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap();
|
||||
assert_eq!((r["view"].as_str(), r["split"].as_f64()), (Some("split"), Some(0.5)));
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
let r = s.execute("imageTrace.setView", &json!({"view": "split", "split": 0.25})).unwrap();
|
||||
assert_eq!(r["split"].as_f64(), Some(0.25));
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1);
|
||||
assert_eq!(node(&s, g).trace_split(), 0.25);
|
||||
for same in [json!({"view": "split", "split": 0.25}), json!({"view": "split"})] {
|
||||
let r = s.execute("imageTrace.setView", &same).unwrap();
|
||||
assert_eq!(r["split"].as_f64(), Some(0.25), "{same}");
|
||||
assert_eq!(s.doc().unwrap().history.undo.len(), steps + 1, "{same}: no undo step");
|
||||
}
|
||||
// Pixels at y = 60 (above the disc): the image's blue left of x = 100, white right of it.
|
||||
let blue = |p: [u8; 4]| p[0] < 200 && p[2] > 245;
|
||||
let white = |p: [u8; 4]| p[0] > 245 && p[1] > 245 && p[2] > 245;
|
||||
let screen = render_doc(&s, true);
|
||||
assert!(blue(screen.pixel(60, 60)) && blue(screen.pixel(95, 60)), "{:?}", screen.pixel(95, 60));
|
||||
assert!(white(screen.pixel(105, 60)) && white(screen.pixel(240, 60)), "{:?}", screen.pixel(105, 60));
|
||||
let export = render_doc(&s, false);
|
||||
assert!(white(export.pixel(60, 60)), "exports draw the tracing result");
|
||||
// Another view keeps the divider for when Split is chosen again.
|
||||
s.execute("imageTrace.setView", &json!({"view": "outlines"})).unwrap();
|
||||
assert_eq!(node(&s, g).trace_split(), 0.25);
|
||||
s.execute("imageTrace.setView", &json!({"view": "split"})).unwrap();
|
||||
let g = NodeId(s.execute("imageTrace.make", &json!({"id": g.0, "params": {"ignoreWhite": true, "noise": 30}})).unwrap()["id"].as_u64().unwrap());
|
||||
assert_eq!((node(&s, g).trace_view(), node(&s, g).trace_split()), (vectorcraft_doc::TraceView::Split, 0.25), "tracing again");
|
||||
let back = vectorcraft_format::load(&vectorcraft_format::save(&s.doc().unwrap().doc, false)).unwrap();
|
||||
assert_eq!((back.node(g).unwrap().trace_view(), back.node(g).unwrap().trace_split()), (vectorcraft_doc::TraceView::Split, 0.25));
|
||||
// Bad dividers are refused and change nothing.
|
||||
let steps = s.doc().unwrap().history.undo.len();
|
||||
for bad in [json!(-0.1), json!(1.01), json!("0.5"), json!(true), json!([0.5])] {
|
||||
assert!(s.execute("imageTrace.setView", &json!({"view": "split", "split": bad})).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!((s.doc().unwrap().history.undo.len(), node(&s, g).trace_split()), (steps, 0.25));
|
||||
for edge in [0.0, 1.0] {
|
||||
s.execute("imageTrace.setView", &json!({"view": "split", "split": edge})).unwrap();
|
||||
assert_eq!(node(&s, g).trace_split(), edge);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_trace_views_draw_on_screen_only_and_expand_to_the_result() {
|
||||
let mut s = session();
|
||||
|
||||
Reference in New Issue
Block a user