Compare commits

...
7 changed files with 557 additions and 36 deletions

No files matched your search

Generated
+78 -36
View File
@@ -317,7 +317,7 @@ name = "blending-nodes"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"glam 0.33.10", "glam 0.33.12",
"graphic-types", "graphic-types",
"node-macro", "node-macro",
"serde", "serde",
@@ -359,7 +359,7 @@ dependencies = [
"bytemuck", "bytemuck",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"graphic-types", "graphic-types",
"half", "half",
@@ -377,7 +377,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"serde", "serde",
] ]
@@ -834,7 +834,7 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
name = "control-protocol" name = "control-protocol"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"glam 0.33.10", "glam 0.33.12",
"serde", "serde",
"serde_json", "serde_json",
] ]
@@ -913,7 +913,7 @@ dependencies = [
"color", "color",
"ctor", "ctor",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"image", "image",
"kurbo", "kurbo",
@@ -1180,6 +1180,13 @@ version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8"
[[package]]
name = "diffrast"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
]
[[package]] [[package]]
name = "digest" name = "digest"
version = "0.10.7" version = "0.10.7"
@@ -1395,7 +1402,7 @@ name = "dyn-any"
version = "0.3.1" version = "0.3.1"
dependencies = [ dependencies = [
"dyn-any-derive", "dyn-any-derive",
"glam 0.33.10", "glam 0.33.12",
"reqwest", "reqwest",
] ]
@@ -1970,9 +1977,9 @@ dependencies = [
[[package]] [[package]]
name = "glam" name = "glam"
version = "0.33.10" version = "0.33.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8" checksum = "37bfe73dc8ec21f54d181e5a60554327ec3f1c600c455a75ccbfc65d2106a6c4"
dependencies = [ dependencies = [
"bytemuck", "bytemuck",
"libm", "libm",
@@ -2048,7 +2055,7 @@ dependencies = [
"core-types", "core-types",
"criterion", "criterion",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graph-craft", "graph-craft",
"graphene-animation", "graphene-animation",
"graphene-application-io", "graphene-application-io",
@@ -2082,7 +2089,7 @@ name = "graphene-animation"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"kurbo", "kurbo",
"serde", "serde",
@@ -2095,7 +2102,7 @@ dependencies = [
"blake3", "blake3",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"graphene-resource", "graphene-resource",
"log", "log",
@@ -2112,7 +2119,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-application-io", "graphene-application-io",
"log", "log",
"serde", "serde",
@@ -2150,7 +2157,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-animation", "graphene-animation",
"graphene-hash", "graphene-hash",
"graphic-types", "graphic-types",
@@ -2166,7 +2173,7 @@ dependencies = [
name = "graphene-hash" name = "graphene-hash"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"glam 0.33.10", "glam 0.33.12",
"graphene-hash-derive", "graphene-hash-derive",
] ]
@@ -2201,7 +2208,7 @@ dependencies = [
"bytemuck", "bytemuck",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graph-craft", "graph-craft",
"graphene-application-io", "graphene-application-io",
"graphene-canvas-utils", "graphene-canvas-utils",
@@ -2222,6 +2229,7 @@ dependencies = [
"transform-nodes", "transform-nodes",
"vector-nodes", "vector-nodes",
"vector-types", "vector-types",
"vectorize-nodes",
"vello", "vello",
"vello_encoding", "vello_encoding",
"wasm-bindgen", "wasm-bindgen",
@@ -2238,7 +2246,7 @@ dependencies = [
"brush-types", "brush-types",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphic-types", "graphic-types",
"node-macro", "node-macro",
"rand", "rand",
@@ -2254,7 +2262,7 @@ dependencies = [
"brush-types", "brush-types",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"node-macro", "node-macro",
"raster-types", "raster-types",
@@ -2275,7 +2283,7 @@ dependencies = [
"dirs", "dirs",
"fd-lock", "fd-lock",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graphite-desktop-ui", "graphite-desktop-ui",
"graphite-desktop-wrapper", "graphite-desktop-wrapper",
"interprocess", "interprocess",
@@ -2402,7 +2410,7 @@ dependencies = [
"dyn-any", "dyn-any",
"env_logger", "env_logger",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graph-craft", "graph-craft",
"graphene-hash", "graphene-hash",
"graphene-std", "graphene-std",
@@ -3012,7 +3020,7 @@ dependencies = [
"criterion", "criterion",
"dyn-any", "dyn-any",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graph-craft", "graph-craft",
"graphene-animation", "graphene-animation",
"graphene-core", "graphene-core",
@@ -3453,7 +3461,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-core", "graphene-core",
"graphic-types", "graphic-types",
"log", "log",
@@ -3666,7 +3674,7 @@ dependencies = [
"bytemuck", "bytemuck",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"half", "half",
"log", "log",
@@ -4108,7 +4116,7 @@ name = "path-bool-nodes"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"glam 0.33.10", "glam 0.33.12",
"graphic-types", "graphic-types",
"linesweeper", "linesweeper",
"log", "log",
@@ -4427,7 +4435,7 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graph-craft", "graph-craft",
"graphene-std", "graphene-std",
"interpreted-executor", "interpreted-executor",
@@ -4649,7 +4657,7 @@ dependencies = [
"dyn-any", "dyn-any",
"fastnoise-lite", "fastnoise-lite",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graphene-core", "graphene-core",
"graphene-hash", "graphene-hash",
"graphene-resource", "graphene-resource",
@@ -4697,7 +4705,7 @@ dependencies = [
"bytemuck", "bytemuck",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"image", "image",
"node-macro", "node-macro",
@@ -4885,7 +4893,7 @@ dependencies = [
"brush-types", "brush-types",
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"graphene-resource", "graphene-resource",
"graphic-types", "graphic-types",
@@ -4908,7 +4916,7 @@ version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"glam 0.33.10", "glam 0.33.12",
"graphene-core", "graphene-core",
"graphic-types", "graphic-types",
"kurbo", "kurbo",
@@ -5625,7 +5633,7 @@ name = "snapping"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"criterion", "criterion",
"glam 0.33.10", "glam 0.33.12",
"kurbo", "kurbo",
] ]
@@ -5697,7 +5705,7 @@ dependencies = [
"glam 0.30.10", "glam 0.30.10",
"glam 0.31.1", "glam 0.31.1",
"glam 0.32.1", "glam 0.32.1",
"glam 0.33.10", "glam 0.33.12",
"libm", "libm",
"num-traits", "num-traits",
"spirv-std-macros", "spirv-std-macros",
@@ -5942,7 +5950,7 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"fancy-regex", "fancy-regex",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"graphene-resource", "graphene-resource",
"ipsum", "ipsum",
@@ -6280,6 +6288,13 @@ version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
[[package]]
name = "tracer"
version = "0.1.0"
dependencies = [
"glam 0.33.12",
]
[[package]] [[package]]
name = "tracing" name = "tracing"
version = "0.1.41" version = "0.1.41"
@@ -6347,7 +6362,7 @@ name = "transform-nodes"
version = "0.0.0" version = "0.0.0"
dependencies = [ dependencies = [
"core-types", "core-types",
"glam 0.33.10", "glam 0.33.12",
"graphic-types", "graphic-types",
"node-macro", "node-macro",
"rand", "rand",
@@ -6601,7 +6616,7 @@ dependencies = [
"delaunator", "delaunator",
"dyn-any", "dyn-any",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graphene-core", "graphene-core",
"graphene-hash", "graphene-hash",
"graphic-types", "graphic-types",
@@ -6629,7 +6644,7 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"fixedbitset", "fixedbitset",
"glam 0.33.10", "glam 0.33.12",
"graphene-hash", "graphene-hash",
"kurbo", "kurbo",
"log", "log",
@@ -6646,6 +6661,24 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "vectorize-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"futures",
"glam 0.33.12",
"graphene-hash",
"graphic-types",
"kurbo",
"log",
"node-macro",
"raster-types",
"vector-types",
"vtrace",
]
[[package]] [[package]]
name = "vello" name = "vello"
version = "0.10.0" version = "0.10.0"
@@ -6697,6 +6730,15 @@ version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "vtrace"
version = "0.1.0"
dependencies = [
"diffrast",
"glam 0.33.12",
"tracer",
]
[[package]] [[package]]
name = "walkdir" name = "walkdir"
version = "2.5.0" version = "2.5.0"
@@ -6929,7 +6971,7 @@ dependencies = [
"clap", "clap",
"control-protocol", "control-protocol",
"getrandom 0.3.3", "getrandom 0.3.3",
"glam 0.33.10", "glam 0.33.12",
"image", "image",
"interprocess", "interprocess",
"serde", "serde",
@@ -7092,7 +7134,7 @@ dependencies = [
"core-types", "core-types",
"dyn-any", "dyn-any",
"futures", "futures",
"glam 0.33.10", "glam 0.33.12",
"graphene-application-io", "graphene-application-io",
"node-macro", "node-macro",
"raster-types", "raster-types",
+2
View File
@@ -97,6 +97,8 @@ text-nodes = { path = "node-graph/nodes/text" }
transform-nodes = { path = "node-graph/nodes/transform" } transform-nodes = { path = "node-graph/nodes/transform" }
vector-nodes = { path = "node-graph/nodes/vector" } vector-nodes = { path = "node-graph/nodes/vector" }
repeat-nodes = { path = "node-graph/nodes/repeat" } repeat-nodes = { path = "node-graph/nodes/repeat" }
vectorize-nodes = { path = "node-graph/nodes/vectorize" }
vtrace = { path = "../vtrace/vtrace" }
math-nodes = { path = "node-graph/nodes/math" } math-nodes = { path = "node-graph/nodes/math" }
path-bool-nodes = { path = "node-graph/nodes/path-bool" } path-bool-nodes = { path = "node-graph/nodes/path-bool" }
graph-craft = { path = "node-graph/graph-craft" } graph-craft = { path = "node-graph/graph-craft" }
+1
View File
@@ -59,6 +59,7 @@ brush-nodes = { workspace = true }
graphene-core = { workspace = true } graphene-core = { workspace = true }
graphic-nodes = { workspace = true } graphic-nodes = { workspace = true }
repeat-nodes = { workspace = true } repeat-nodes = { workspace = true }
vectorize-nodes = { workspace = true }
# Workspace dependencies # Workspace dependencies
log = { workspace = true } log = { workspace = true }
+1
View File
@@ -21,6 +21,7 @@ pub use text_nodes;
pub use transform_nodes; pub use transform_nodes;
pub use vector_nodes; pub use vector_nodes;
pub use vector_types; pub use vector_types;
pub use vectorize_nodes;
/// Backward compatibility re-exports /// Backward compatibility re-exports
pub mod vector { pub mod vector {
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "vectorize-nodes"
description = "Raster to vector tracing nodes for Graphene"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
core-types = { workspace = true }
vector-types = { workspace = true }
raster-types = { workspace = true }
graphic-types = { workspace = true }
graphene-hash = { workspace = true }
node-macro = { workspace = true }
vtrace = { workspace = true }
# Workspace dependencies
dyn-any = { workspace = true }
glam = { workspace = true }
kurbo = { workspace = true }
log = { workspace = true }
[dev-dependencies]
futures = { workspace = true }
+265
View File
@@ -0,0 +1,265 @@
use core_types::Color;
use core_types::list::{ATTR_CLIPPING_MASK, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_POSITION, ATTR_TRANSFORM, Item, List};
use glam::{DAffine2, DMat2, DVec2, DVec3};
use graphene_hash::CacheHash;
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
use kurbo::BezPath;
use vector_types::gradient::{Gradient, GradientForm, GradientSpace};
use vector_types::vector::style::{Stroke, StrokeCap, StrokeJoin};
use vtrace::model::{Curve, FillRule, Geometry, GradientShape, Instance, Model, Object, Paint, StrokeGeometry, Structure};
/// The [`RepeatStructure`] a group of instances was recognized as.
pub const ATTR_VTRACE_REPEAT: &str = "vtrace:repeat";
/// How a group of instances repeats its definition, instance `k` counted from 0 and moved from the first, in the traced image's pixels.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub enum RepeatStructure {
/// Each instance placed by its own transform.
#[default]
List,
/// Instance `k` moved by `k * step`.
Linear { step: DVec2 },
/// Instance `k` moved by `(k % columns) * a + (k / columns) * b`.
Grid { a: DVec2, b: DVec2, columns: usize },
/// Instance `k` turned about `center` by `k * step` radians.
Circular { center: DVec2, step: f64 },
}
impl From<&Structure> for RepeatStructure {
fn from(structure: &Structure) -> Self {
match *structure {
Structure::List => Self::List,
Structure::Linear { step } => Self::Linear { step },
Structure::Grid { a, b, columns } => Self::Grid { a, b, columns },
Structure::Circular { center, step } => Self::Circular { center, step },
}
}
}
/// Converts a traced model in pixel coordinates into Graphite content placed in the document by `pixels_to_document`.
pub fn model_to_graphic(model: &Model, pixels_to_document: DAffine2) -> List<Graphic> {
let converter = Converter { model };
let mut list = List::new();
for item in converter.items(&model.items) {
let mut item = item;
let transform: DAffine2 = item.attribute_cloned_or(ATTR_TRANSFORM, DAffine2::IDENTITY);
item.set_attribute(ATTR_TRANSFORM, pixels_to_document * transform);
list.push(item);
}
list
}
struct Converter<'a> {
model: &'a Model,
}
impl Converter<'_> {
/// Converts items bottom to top, wrapping each run of consecutive objects that share a clip into one clipped group.
fn items(&self, items: &[vtrace::model::Item]) -> Vec<Item<Graphic>> {
let mut converted = Vec::new();
let mut run: Option<(usize, Vec<Item<Graphic>>)> = None;
for item in items {
let (clip, graphic) = match item {
vtrace::model::Item::Object(object) => (object.clip, self.object(object)),
vtrace::model::Item::Group { items, .. } => (None, group(self.items(items))),
vtrace::model::Item::Instance(instance) => (None, self.instance(instance)),
vtrace::model::Item::Repeat { structure, instances } => {
let instances = instances.iter().map(|instance| self.instance(instance)).collect();
(None, group(instances).with_attribute(ATTR_VTRACE_REPEAT, RepeatStructure::from(structure)))
}
};
// Close the current run when the next item is not clipped the same way
if run.as_ref().is_some_and(|(run_clip, _)| Some(*run_clip) != clip)
&& let Some((run_clip, content)) = run.take()
{
converted.push(self.clipped(run_clip, content));
}
match clip {
Some(clip) => run.get_or_insert_with(|| (clip, Vec::new())).1.push(graphic),
None => converted.push(graphic),
}
}
if let Some((run_clip, content)) = run {
converted.push(self.clipped(run_clip, content));
}
converted
}
/// Wraps `content` in a group masked by clip `clip_index`, nested in further groups for the clip's ancestors.
fn clipped(&self, clip_index: usize, content: Vec<Item<Graphic>>) -> Item<Graphic> {
let Some(clip) = self.model.clips.get(clip_index) else {
log::error!("Traced object refers to missing clip {clip_index}");
return group(content);
};
// The clip's shape masks what follows it while its own fill stays invisible
let base = mask_base(loops_to_bezpath(&clip.loops, clip.rule));
let masked = std::iter::once(base).chain(content.into_iter().map(with_clipping_mask));
let clipped = group(masked.collect());
match clip.parent {
Some(parent) => self.clipped(parent, vec![clipped]),
None => clipped,
}
}
fn instance(&self, instance: &Instance) -> Item<Graphic> {
let Some(definition) = self.model.definitions.get(instance.definition) else {
log::error!("Traced instance refers to missing definition {}", instance.definition);
return group(Vec::new());
};
let transform = DAffine2::from_cols_array(&instance.transform);
group(self.items(definition)).with_attribute(ATTR_TRANSFORM, transform)
}
/// An object of the lowered model: no even-odd fill, path gradient, blur or radial focus is left (see [`crate::CAPABILITIES`]).
fn object(&self, object: &Object) -> Item<Graphic> {
let paint = paint(&object.paint);
let mut vector = match &object.geometry {
Geometry::Fill { loops, rule } => vector_item(loops_to_bezpath(loops, *rule)).into_fill(paint),
Geometry::Stroke(stroke) => vector_item(cubics_to_bezpath(&stroke.centerline, stroke.closed)).into_stroke(&stroke_style(stroke), paint),
};
if object.opacity < 1. {
vector.set_attribute(ATTR_OPACITY, object.opacity);
}
Item::new_from_element(Graphic::from(vector))
}
}
/// Styling helpers for a freshly built vector item.
trait VectorItemExt {
fn into_fill(self, paint: Graphic) -> Self;
fn into_stroke(self, stroke: &Stroke, paint: Graphic) -> Self;
}
impl VectorItemExt for Item<Vector> {
fn into_fill(mut self, paint: Graphic) -> Self {
stamp_coverage(&mut self, Coverage::new_fill(), paint, CoverPlacement::Above);
self
}
fn into_stroke(mut self, stroke: &Stroke, paint: Graphic) -> Self {
stamp_coverage(&mut self, Coverage::new_stroke(stroke), paint, CoverPlacement::Above);
self
}
}
fn stroke_style(stroke: &StrokeGeometry) -> Stroke {
let (dash_lengths, dash_offset) = stroke.dashes.clone().unwrap_or_default();
Stroke {
dash_lengths,
dash_offset,
cap: match stroke.cap {
vtrace::stroke::Cap::Butt => StrokeCap::Butt,
vtrace::stroke::Cap::Round => StrokeCap::Round,
vtrace::stroke::Cap::Square => StrokeCap::Square,
},
join: match stroke.join {
vtrace::stroke::Join::Miter => StrokeJoin::Miter,
vtrace::stroke::Join::Round => StrokeJoin::Round,
vtrace::stroke::Join::Bevel => StrokeJoin::Bevel,
},
..Stroke::new(stroke.width)
}
}
fn vector_item(path: BezPath) -> Item<Vector> {
Item::new_from_element(Vector::from_bezpath(path))
}
fn group(items: Vec<Item<Graphic>>) -> Item<Graphic> {
let mut list = List::new();
items.into_iter().for_each(|item| list.push(item));
Item::new_from_element(Graphic::Graphic(Box::new(Item::new_from_element(Graphic::GraphicList(list)))))
}
/// An invisible shape whose coverage masks the clipped items that follow it.
fn mask_base(path: BezPath) -> Item<Graphic> {
let base = vector_item(path).with_attribute(ATTR_OPACITY_FILL, 0.).into_fill(Graphic::from(Color::BLACK));
Item::new_from_element(Graphic::from(base))
}
/// Flags the content inside `item` as masked by its preceding sibling, where the renderer reads the flag.
fn with_clipping_mask(item: Item<Graphic>) -> Item<Graphic> {
let (mut graphic, attributes) = item.into_parts();
match &mut graphic {
Graphic::Vector(inner) => inner.set_attribute(ATTR_CLIPPING_MASK, true),
Graphic::Graphic(inner) => inner.set_attribute(ATTR_CLIPPING_MASK, true),
_ => log::error!("Vectorize produced an unexpected graphic kind to clip"),
}
Item::from_parts(graphic, attributes)
}
/// The sRGB gamma-encoded color vtrace works in, as Graphite's linear color.
fn color(color: DVec3, alpha: f64) -> Color {
let [red, green, blue] = color.as_vec3().to_array();
Color::from_gamma_srgb_channels(red, green, blue, alpha as f32)
}
fn paint(paint: &Paint) -> Graphic {
match paint {
Paint::Solid(solid) => Graphic::from(color(*solid, 1.)),
Paint::Gradient(gradient) => Graphic::Gradient(gradient_item(gradient)),
}
}
/// A linear or radial gradient in Graphite's form: its stops along the unit line or circle, placed by its transform.
fn gradient_item(gradient: &vtrace::model::Gradient) -> Item<Gradient> {
let mut stops = List::new();
for stop in gradient.stops() {
let [red, green, blue, alpha] = stop.color;
let stop_color = color(DVec3::new(red, green, blue), alpha);
stops.push(Item::new_from_element(stop_color).with_attribute(ATTR_POSITION, stop.offset));
}
let (form, transform) = match gradient.shape() {
GradientShape::Linear { start, end } => {
let axis = end - start;
(GradientForm::Linear, DAffine2::from_mat2_translation(DMat2::from_cols(axis, axis.perp()), start))
}
GradientShape::Radial { transform, .. } => (GradientForm::Radial, DAffine2::from_cols_array(&transform)),
GradientShape::Path { .. } => {
log::error!("Vectorize got a path gradient its lowering should have drawn as bands");
(GradientForm::Linear, DAffine2::IDENTITY)
}
};
Item::new_from_element(Gradient(stops))
.with_attribute(ATTR_GRADIENT_FORM, form)
.with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma)
.with_attribute(ATTR_TRANSFORM, transform)
}
fn cubics_to_bezpath(cubics: &[Curve], closed: bool) -> BezPath {
let point = |p: DVec2| kurbo::Point::new(p.x, p.y);
let mut path = BezPath::new();
let Some(first) = cubics.first() else { return path };
path.move_to(point(first[0]));
for [_, handle_start, handle_end, end] in cubics {
path.curve_to(point(*handle_start), point(*handle_end), point(*end));
}
if closed {
path.close_path();
}
path
}
/// The loops as one path; the lowering has wound them for Graphite's nonzero fill rule.
fn loops_to_bezpath(loops: &[Vec<Curve>], rule: FillRule) -> BezPath {
if rule == FillRule::EvenOdd {
log::error!("Vectorize got an even-odd fill its lowering should have wound for nonzero");
}
let mut path = BezPath::new();
for cubics in loops.iter().filter(|cubics| !cubics.is_empty()) {
cubics_to_bezpath(cubics, true).elements().iter().for_each(|&element| path.push(element));
}
path
}
+176
View File
@@ -0,0 +1,176 @@
mod convert;
pub use convert::{ATTR_VTRACE_REPEAT, RepeatStructure};
use core_types::ATTR_TRANSFORM;
use core_types::context::Ctx;
use core_types::list::{Item, List};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use raster_types::{CPU, Raster};
use std::ops::ControlFlow;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
/// What Graphite's renderer draws of vtrace's model; the rest is lowered into it by vtrace.
pub const CAPABILITIES: vtrace::Capabilities = vtrace::Capabilities {
even_odd: false,
path_gradients: false,
blur: false,
radial_focus: false,
clips: true,
dashes: true,
transparent_stops: true,
};
/// Counts the traces one node has started, kept as the node's own data, so a running trace stops once the same node starts a newer one
/// while other vectorize nodes tracing at the same time carry on.
#[derive(Debug, Clone, Default)]
pub struct TraceGeneration(Arc<AtomicU64>);
/// Traces an image into a stack of filled and stroked shapes, drawn bottom to top as an artist would layer them.
#[node_macro::node(category("Raster"), memoize)]
async fn vectorize(
_: impl Ctx,
/// The image to trace.
image: Item<Raster<CPU>>,
/// How much detail to keep, as a multiple of the level estimated from how busy the image is. Higher values spend more segments on smaller features.
#[default(1.)]
#[hard(0.01..)]
detail: Item<f64>,
/// How far the shapes may deviate from the image, as a multiple of the image's own noise. Higher values give fewer, simpler shapes.
#[default(1.)]
#[hard(0..)]
tolerance: Item<f64>,
#[data] generation: TraceGeneration,
) -> List<Graphic> {
let image_transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
let image = image.element();
let (width, height) = (image.width as usize, image.height as usize);
if width == 0 || height == 0 {
return List::new();
}
// Graphite's colors are linear light with straight alpha; vtrace composites transparency over white
let pixels: Vec<f32> = image.data.iter().flat_map(|color| [color.r(), color.g(), color.b(), color.a()]).collect();
let source = vtrace::Image {
pixels: vtrace::Pixels::RgbaF32 {
data: &pixels,
linear: true,
premultiplied: false,
},
width,
height,
};
let options = vtrace::TraceOptions {
tolerance: *tolerance.element(),
detail: vtrace::Detail::Scaled(*detail.element()),
host: CAPABILITIES,
..Default::default()
};
let traces = &generation.0;
let this = traces.fetch_add(1, Ordering::Relaxed) + 1;
let mut stage = "";
let progress = |progress: &vtrace::Progress| {
if progress.stage != stage {
stage = progress.stage;
log::debug!("Vectorize: {stage}");
}
if traces.load(Ordering::Relaxed) == this {
ControlFlow::Continue(())
} else {
ControlFlow::Break(())
}
};
let model = match vtrace::trace_with(&source, &options, progress) {
Ok(model) => model,
Err(vtrace::TraceError::Cancelled) => return List::new(),
Err(error) => {
log::error!("Vectorize could not trace the image: {error}");
return List::new();
}
};
// The traced coordinates are in pixels, while the image's transform maps the unit square onto the document
let pixels_to_document = image_transform * DAffine2::from_scale(DVec2::new(1. / width as f64, 1. / height as f64));
convert::model_to_graphic(&model, pixels_to_document)
}
#[cfg(test)]
mod test {
use super::*;
use core_types::Color;
use raster_types::Image;
/// An image of `width` by `height` pixels colored by `color` at each pixel's column and row.
fn raster(width: u32, height: u32, color: impl Fn(u32, u32) -> Color) -> Raster<CPU> {
let data = (0..width * height).map(|index| color(index % width, index / width)).collect();
Raster::new_cpu(Image {
width,
height,
data,
base64_string: None,
})
}
/// The shapes traced from `image` at `detail` and `tolerance`, by a node of its own.
fn trace(image: Raster<CPU>, detail: f64, tolerance: f64) -> List<Graphic> {
let (image, detail, tolerance) = (Item::new_from_element(image), Item::new_from_element(detail), Item::new_from_element(tolerance));
futures::executor::block_on(vectorize((), &TraceGeneration::default(), image, detail, tolerance))
}
const DARK: Color = Color::from_rgbaf32_unchecked(0.05, 0.1, 0.4, 1.);
/// A dark ring from `inner` to `inner + width` pixels out from the middle of a light square of `size` pixels.
fn ring(size: u32, inner: f64, width: f64) -> Raster<CPU> {
let center = size as f64 / 2.;
raster(size, size, |x, y| {
let distance = DVec2::new(x as f64 + 0.5, y as f64 + 0.5).distance(DVec2::splat(center));
if (inner..inner + width).contains(&distance) { DARK } else { Color::WHITE }
})
}
/// A dark ring on a light background, whose hole only an even-odd fill or a correctly wound nonzero fill leaves empty.
#[test]
fn traces_a_ring_into_shapes() {
let traced = trace(ring(64, 12.8, 12.8), 1., 1.);
assert!(!traced.is_empty(), "the ring traced into no shapes");
}
/// Rasters with too few pixels, too little contrast, or too little room for a shape, which panicked in debug builds (glam's
/// asserts on vectors without a direction), each traced at a few detail and tolerance settings.
#[test]
fn traces_degenerate_rasters() {
let gray = |value: f32| Color::from_rgbaf32_unchecked(value, value, value, 1.);
let rasters = [
("1x1", raster(1, 1, |_, _| DARK)),
("1x7", raster(1, 7, |_, y| if y % 2 == 0 { DARK } else { Color::WHITE })),
("7x1", raster(7, 1, |x, _| gray(x as f32 / 6.))),
("ring 1 px", ring(24, 6., 1.)),
("ring 2 px", ring(24, 6., 2.)),
("ring 3 px", ring(24, 6., 3.)),
("flat", raster(16, 16, |_, _| DARK)),
("clear", raster(16, 16, |_, _| Color::TRANSPARENT)),
("half alpha", raster(16, 16, |x, _| if x < 8 { DARK.with_alpha(0.5) } else { Color::TRANSPARENT })),
("checker", raster(16, 16, |x, y| if (x + y) % 2 == 0 { DARK } else { Color::WHITE })),
("ramp", raster(24, 8, |x, _| gray(x as f32 / 23.))),
("diagonals", raster(16, 16, |x, y| if (x + y) % 5 == 0 || x == y { DARK } else { Color::WHITE })),
("sparse dots", raster(24, 24, |x, y| if x % 7 == 3 && y % 7 == 3 { DARK } else { Color::WHITE })),
];
for (name, image) in rasters {
for (detail, tolerance) in [(0.25, 4.), (1., 1.), (4., 0.)] {
let traced = trace(image.clone(), detail, tolerance);
assert!(name != "flat" || !traced.is_empty(), "the flat raster traced into no shapes at detail {detail}, tolerance {tolerance}");
}
}
}
/// Two nodes tracing at once each finish their own trace: a trace stops only for a newer one of the same node.
#[test]
fn concurrent_nodes_do_not_cancel_each_other() {
let traces: Vec<_> = (0..4).map(|_| std::thread::spawn(|| trace(ring(64, 12.8, 12.8), 1., 1.))).collect();
for traced in traces {
assert!(!traced.join().unwrap().is_empty(), "a trace was cancelled by another node's");
}
}
}