Compare commits

...
53 changed files with 2148 additions and 532 deletions

No files matched your search

Generated
+3 -4
View File
@@ -1900,7 +1900,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
dependencies = [
"bytemuck",
"libm",
"serde_core",
]
@@ -6491,7 +6490,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -6506,7 +6505,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -6520,7 +6519,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"naga",
"wesl",
+5 -5
View File
@@ -194,7 +194,7 @@ color = "0.3"
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"nostd-libm",
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
@@ -220,7 +220,7 @@ pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.4"
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
"full",
@@ -281,6 +281,6 @@ debug = true
[patch.crates-io]
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
# TODO: Remove these once the fork's fixes are upstreamed and released
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
@@ -759,20 +759,26 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let [start, end] = match gradient_form {
GradientForm::Linear => LINEAR_DIALS,
GradientForm::Radial => RADIAL_DIALS,
};
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -611,10 +611,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
..Default::default()
},
NodeTemplate {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::scope(raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string()),
],
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
..Default::default()
@@ -837,6 +834,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -3000,6 +3001,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
}
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
let curvatures = match get_document_node(node_id, context) {
Ok(document_node) => {
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
Some(&TaggedValue::Number(value)) => Some(value),
_ => None,
};
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
}
Err(err) => {
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
return Vec::new();
}
};
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
let mut form = vec![
TextLabel::new("Form")
.tooltip_label("Form")
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
.widget_instance(),
];
add_blank_assist(&mut form);
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
for (label, [start, end], tooltip) in [
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
] {
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures == Some([start, end]))
.disabled(curvatures.is_none())
.on_update(move |_: &TextButton| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
.widget_instance(),
);
}
// The same sliders the curvatures would get without this panel
let options = ParameterOptions {
soft_min: Some(-1.),
soft_max: Some(1.),
slider: true,
..Default::default()
};
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(curvature(StartCurvatureInput::INDEX));
layout.extend(curvature(EndCurvatureInput::INDEX));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -737,6 +737,22 @@ mod tests {
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
}
#[test]
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
use graphene_std::raster_types::{CPU, GPU, Raster};
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
assert!(
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
"a CPU raster should upload through the input adapter"
);
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
}
#[test]
fn items_promote_onto_list_inputs() {
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
@@ -16,12 +16,11 @@ use graphene_std::ParameterRef;
use graphene_std::ProtoNodeIdentifier;
use graphene_std::extract_xy::XY;
use graphene_std::raster::RedGreenBlueAlpha;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -300,10 +299,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
aliases: &["math_nodes::GradientTypeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -534,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -543,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -1273,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
}
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -1635,6 +1636,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
})
.collect();
for (node_id, network_path) in &gradient_form_nodes {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
reset_default_display_name(document, node_id, network_path, "Gradient Form");
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
graphene_std::renderer::dial_gradient::LINEAR_DIALS
}
};
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
@@ -1859,35 +1903,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(TaggedValue::Integer(integer), exposed), &network_path);
}
let cpu_raster_type_defaults: Vec<(NodeId, Vec<NodeId>, usize, Type, bool)> = document
.network_interface
.document_network()
.recursive_nodes()
.flat_map(|(node_id, node, path)| {
node.inputs
.iter()
.enumerate()
.filter_map(|(index, input)| {
let NodeInput::Value { tagged_value, exposed } = input else { return None };
let TaggedValue::TypeDefault(stored_type) = &**tagged_value else { return None };
let gpu_type = if *stored_type == item!(Raster<CPU>) {
item!(Raster<GPU>)
} else if *stored_type == list!(Raster<CPU>) {
list!(Raster<GPU>)
} else {
return None;
};
Some((*node_id, path.clone(), index, gpu_type, *exposed))
})
.collect::<Vec<_>>()
})
.collect();
for (node_id, network_path, index, gpu_type, exposed) in cpu_raster_type_defaults {
document
.network_interface
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::type_default(gpu_type, exposed), &network_path);
}
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
@@ -2425,7 +2440,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -3565,7 +3579,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
image_to_channels::IDENTIFIER,
graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
@@ -3575,8 +3589,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::image::IDENTIFIER,
graphene_std::platform_application_io::bytes_to_image::IDENTIFIER,
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
graphene_std::platform_application_io::rasterize::IDENTIFIER,
]
@@ -4672,7 +4684,7 @@ mod tests {
migrate(&mut document);
let image_node = &document.network_interface.document_network().nodes[&image_id];
assert_eq!(image_node.inputs.len(), 3, "the image node should gain its placeholder primary input and pipeline scope input");
assert_eq!(image_node.inputs.len(), 2, "the image node should gain its placeholder primary input");
let migrated = &image_node.inputs[1];
match legacy_input.as_value() {
None => assert_eq!(migrated.as_node(), Some(upstream_id), "the wire should sit at input 1"),
@@ -4708,24 +4720,51 @@ mod tests {
}
#[test]
fn cpu_raster_type_defaults_become_gpu_defaults() {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut blur_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::effects::blur::IDENTIFIER))
.expect("the definition should exist")
.default_node_template();
blur_template.inputs[0] = NodeInput::type_default(item!(Raster<CPU>), true);
document.network_interface.insert_node(node_id, blur_template, &[]);
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
migrate(&mut document);
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, dials) in [
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
] {
let mut document = DocumentMessageHandler::default();
let placeholder = || NodeInput::value(TaggedValue::None, false);
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![placeholder()],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
form_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![placeholder(); 2],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
migrate(&mut document);
let migrated = &document.network_interface.document_network().nodes[&node_id].inputs[0];
assert_eq!(
migrated.as_value(),
Some(&TaggedValue::TypeDefault(item!(Raster<GPU>))),
"the CPU raster default should become the GPU raster default"
);
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
let node = &document.network_interface.document_network().nodes[&form_id];
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(
[curvature(1), curvature(2)],
dials.map(|dial| Some(TaggedValue::Number(dial))),
"{form:?} should become its curvature presets"
);
}
}
#[test]
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
// A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_form_reference
&& gradient_form.is_none()
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
// Curvatures other than the radial form's are drawn with the linear form's controls
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
Some(&TaggedValue::Number(value)) => value,
_ => 0.,
};
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
}
}
@@ -3366,7 +3369,7 @@ mod test_gradient {
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3375,7 +3378,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3384,10 +3387,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Form node should have been inserted")
.expect("Gradient Curvature node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
+79
View File
@@ -1238,3 +1238,82 @@ mod test {
}
}
}
#[cfg(test)]
mod raster_input_adapter_tests {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graphene_std::Effects;
use graphene_std::list::{ATTR_EFFECTS, Item};
use graphene_std::ops::ConvertAsync;
use graphene_std::raster_nodes::adjustments::invert;
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::transform::Footprint;
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
editor.new_document().await;
editor.create_raster_image(Image::new(4, 4, color), None).await;
let image = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let mut ids = Vec::new();
let mut previous = OutputConnector::node(image, 0);
for (index, identifier) in nodes.iter().enumerate() {
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
let input = InputConnector::node_at_index(id, 0);
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
previous = OutputConnector::node(id, 0);
ids.push(id);
}
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
ids
}
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
let executor = editor.gpu_executor();
raster.convert(Footprint::DEFAULT, executor).await
}
#[tokio::test]
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
let reached_median: Item<Raster<CPU>> = instrumented
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
.next()
.expect("the image should arrive at Median as a CPU raster");
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
// Median at its default radius passes its input through, so its output shows what the adapter gave it
let output = instrumented
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
.next()
.expect("Median should output a GPU raster");
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
let raster = read(&editor, output.into_element()).await;
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
}
#[tokio::test]
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
}
}
+32
View File
@@ -63,6 +63,11 @@ impl EditorTestUtils {
editor
}
/// The GPU executor the graph runs on.
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
}
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
let mut responses = self.editor.handle_message(message);
while self.woken.swap(false, Ordering::Relaxed) {
@@ -108,6 +113,33 @@ impl EditorTestUtils {
Ok(instrumented)
}
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
}
self.finish_evaluation().await
}
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
async fn finish_evaluation(&mut self) -> Result<(), String> {
self.runtime.run().await;
let frontend_messages = self.dispatch(Message::Wake);
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err("Graph should render".to_string());
}
for message in frontend_messages {
message.check_node_graph_error();
}
Ok(())
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
const MAX_ITERATIONS: usize = 16;
@@ -540,9 +540,10 @@
margin-left: 8px;
}
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
@@ -383,8 +383,28 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
#[cfg(feature = "gpu")]
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
{
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
use wgpu_executor::WgpuPipelineCache;
macro_rules! gpu_raster_input_adapter {
($path:ty, $from:ty) => {
async_node!(
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
$path,
input: Context,
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
)
};
}
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
node_types.push(item_to_list_node!(element: Raster<GPU>));
}
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{
@@ -17,7 +17,6 @@ workspace = true
[features]
default = ["serde"]
serde = ["dep:serde", "glam/serde", "half/serde"]
nightly = []
type_id_logging = []
dealloc_nodes = []
wasm = ["tsify", "wasm-bindgen"]
+3 -3
View File
@@ -33,9 +33,9 @@ pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_TYPE,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use num_traits;
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
@@ -15,11 +15,9 @@ publish.workspace = true
workspace = true
[features]
default = ["std"]
std = ["dep:kurbo"]
derive = ["graphene-hash-derive"]
[dependencies]
graphene-hash-derive = { path = "derive", optional = true }
glam = { workspace = true }
kurbo = { workspace = true, optional = true }
kurbo = { workspace = true }
@@ -1,8 +1,3 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "derive")]
pub use graphene_hash_derive::CacheHash;
@@ -66,7 +61,6 @@ impl_via_hash! {
glam::BVec2, glam::BVec3, glam::BVec4,
}
#[cfg(feature = "std")]
impl_via_hash! {
String,
}
@@ -154,7 +148,6 @@ impl_glam_array! {
}
// kurbo path types: hash each element's verb and point coordinates via to_bits().
#[cfg(feature = "std")]
impl CacheHash for kurbo::Point {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -163,7 +156,6 @@ impl CacheHash for kurbo::Point {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::PathEl {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&core::mem::discriminant(self), state);
@@ -183,7 +175,6 @@ impl CacheHash for kurbo::PathEl {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::BezPath {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -224,7 +215,6 @@ impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for Vec<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -232,7 +222,6 @@ impl<T: CacheHash> CacheHash for Vec<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -243,7 +232,6 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -251,7 +239,6 @@ impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -1,5 +1,6 @@
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
use crate::Graphic;
use crate::effects::{EffectKind, ParameterVisitor};
use core_types::Color;
use core_types::blending::BlendMode;
@@ -120,7 +121,7 @@ impl Adjustment {
Self::ColorBalance(_) => EffectKind::ColorBalance,
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
Self::ColorLookup { .. } => EffectKind::ColorLookup,
Self::ColorOverlay { .. } => EffectKind::ColorOverlay,
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
}
}
@@ -270,7 +271,12 @@ impl Adjustment {
}
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
Self::ColorOverlay { color, blend_mode, opacity } => {
visitor.parameter("color", color, Color::BLACK);
// Rides the row as the paint of the Paint Overlay node, which stamps it
let mut paint = Graphic::from(*color);
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
if let Graphic::Color(paint) = paint {
*color = *paint.element();
}
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
@@ -2,13 +2,16 @@
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
use crate::Graphic;
use crate::adjustment::Adjustment;
use core_types::ATTR_TRANSFORM;
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, Item, List};
use dyn_any::DynAny;
use glam::{DMat2, DVec2, DVec3};
use glam::{DAffine2, DMat2, DVec2, DVec3};
use std::fmt::Debug;
use vector_types::vector::style::StrokeAlign;
@@ -32,6 +35,8 @@ pub enum EffectKind {
Outline,
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
BevelAndEmboss,
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
PaintOverlay,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
@@ -52,7 +57,6 @@ pub enum EffectKind {
ColorBalance,
PhotoFilter,
ColorLookup,
ColorOverlay,
}
impl std::fmt::Display for EffectKind {
@@ -66,6 +70,7 @@ impl std::fmt::Display for EffectKind {
Self::Satin => "Satin",
Self::Outline => "Outline",
Self::BevelAndEmboss => "Bevel & Emboss",
Self::PaintOverlay => "Paint Overlay",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
@@ -85,7 +90,6 @@ impl std::fmt::Display for EffectKind {
Self::ColorBalance => "Color Balance",
Self::PhotoFilter => "Photo Filter",
Self::ColorLookup => "Color Lookup",
Self::ColorOverlay => "Color Overlay",
})
}
}
@@ -145,6 +149,29 @@ pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3
(across * altitude.cos()).extend(altitude.sin())
}
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
let unplaced = match paint {
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
_ => false,
};
if !unplaced {
return None;
}
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
let mut paint = paint.clone();
match &mut paint {
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
_ => {}
}
Some(paint)
}
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
@@ -167,7 +194,20 @@ impl Effect {
pub fn operation(&self) -> EffectOperation {
let mut operation = EffectOperation::placeholder(self.kind());
operation.visit_parameters(&mut ReadParameters(&self.0));
operation
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
match operation {
EffectOperation::PaintOverlay {
paint: Graphic::Color(color),
blend_mode,
opacity,
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: *color.element(),
blend_mode,
opacity,
}),
operation => operation,
}
}
}
@@ -295,6 +335,14 @@ pub enum EffectOperation {
highlight_color: Color,
shadow_color: Color,
},
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
PaintOverlay {
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
paint: Graphic,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
Adjustment(Adjustment),
}
@@ -314,6 +362,7 @@ impl EffectOperation {
Self::Satin { .. } => EffectKind::Satin,
Self::Outline { .. } => EffectKind::Outline,
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
@@ -330,7 +379,7 @@ impl EffectOperation {
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::Outline { weight, .. } => weight.max(0.),
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
Self::Adjustment(_) => 0.,
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
}
}
@@ -387,6 +436,11 @@ impl EffectOperation {
highlight_color: Color::TRANSPARENT,
shadow_color: Color::TRANSPARENT,
},
EffectKind::PaintOverlay => Self::PaintOverlay {
paint: Graphic::default(),
blend_mode: BlendMode::default(),
opacity: 0.,
},
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
@@ -422,11 +476,6 @@ impl EffectOperation {
preserve_luminosity: false,
}),
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
EffectKind::ColorOverlay => Self::Adjustment(Adjustment::ColorOverlay {
color: Color::TRANSPARENT,
blend_mode: Default::default(),
opacity: 0.,
}),
}
}
@@ -487,6 +536,11 @@ impl EffectOperation {
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
}
Self::PaintOverlay { paint, blend_mode, opacity } => {
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
}
}
@@ -524,6 +578,7 @@ impl ParameterVisitor for ReadParameters<'_> {
#[cfg(test)]
mod tests {
use super::*;
use vector_types::{Gradient, GradientStop};
#[test]
fn rows_round_trip_their_operations_eliding_defaults() {
@@ -573,12 +628,43 @@ mod tests {
highlight_color: Color::YELLOW,
shadow_color: Color::BLUE,
},
EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
position,
midpoint: 0.5,
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
}))),
blend_mode: BlendMode::Multiply,
opacity: 60.,
},
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::GREEN,
blend_mode: BlendMode::Screen,
opacity: 100.,
}),
];
for operation in operations {
assert_eq!(Effect::new(&operation).operation(), operation);
}
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
let solid = EffectOperation::PaintOverlay {
paint: Graphic::from(Color::RED),
blend_mode: BlendMode::Normal,
opacity: 50.,
};
let solid_row = Effect::new(&solid);
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
assert_eq!(
solid_row.operation(),
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 50.,
})
);
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
}
@@ -606,7 +692,7 @@ mod tests {
ColorBalance,
PhotoFilter,
ColorLookup,
ColorOverlay,
PaintOverlay,
];
for kind in kinds {
let operation = EffectOperation::default_for(kind);
@@ -14,7 +14,7 @@ pub use vector_types;
pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, stamp_effect};
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
@@ -3,6 +3,7 @@
use crate::{RasterKernel, Wgsl, gpu_params};
use core_types::Color;
use core_types::blending::BlendMode;
/// A color as the premultiplied, gamma-encoded channels the passes work with, carried in a [`Color`] to be passed to them.
pub fn premultiplied_gamma_channels(color: Color) -> Color {
@@ -244,3 +245,19 @@ impl RasterKernel for KeepEmpty {
Wgsl::function(include_str!("wgsl/effect_keep_empty.wgsl"))
}
}
gpu_params! {
/// The image (input 0) with a straight-alpha linear-light paint (input 1) mixed over its colors by a blend mode, as much as the paint covers and `opacity` lets it, keeping the image's alpha.
#[derive(Clone)]
pub struct PaintOverlay {
pub blend_mode: BlendMode,
pub opacity: f32,
}
}
impl RasterKernel for PaintOverlay {
const INPUTS: usize = 2;
fn wgsl() -> Wgsl {
Wgsl::function(format!("{}\n{}", include_str!("wgsl/blending.wgsl"), include_str!("wgsl/effect_paint_overlay.wgsl")))
}
}
@@ -0,0 +1,18 @@
// The blend modes work on straight linear colors, as they do for a solid color overlay
fn kernel(coord: vec2<i32>) -> vec4<f32> {
let parameters = params();
let image = input_0_load(coord);
let paint = input_1_load(coord);
if image.a <= 0. {
return vec4<f32>(0.);
}
if paint.a <= 0. {
return image;
}
let backdrop = vec4<f32>(srgb_to_linear(image.rgb / image.a), 1.);
let blended = apply_blend_mode(vec4<f32>(paint.rgb, 1.), backdrop, parameters.blend_mode);
let mixed = mix(backdrop.rgb, blended.rgb, parameters.opacity * paint.a);
return vec4<f32>(linear_to_srgb(mixed) * image.a, image.a);
}
@@ -0,0 +1,541 @@
//! Gradients whose two ends are each a contour dialed between a line, a circle, and a point, with the contours between
//! them filling in as the pencil of circles the two end contours span.
//!
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its dial
//! `α ∈ [-1, 1]`: 0 is the line perpendicular to the gradient line, ±1 is the endpoint itself, and in between is a circle
//! bowing toward (positive) or away from (negative) the other endpoint.
//!
//! The contours between are the members of the pencil the end contours span. Each member is spaced by where it crosses
//! the gradient line, so a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
use glam::DVec2;
use std::f64::consts::FRAC_PI_2;
pub use graphic_types::vector_types::gradient::{LINEAR_DIALS, RADIAL_DIALS};
/// Stands in for a t of infinity, on the contours whose crossing with the gradient line is at infinity.
const UNBOUNDED_T: f64 = 1e6;
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
/// or a point where it has zero radius.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AxisCircle {
pub a: f64,
pub b: f64,
pub c: f64,
}
impl AxisCircle {
/// The contour through the start point at the origin, dialed by `alpha` toward the end point.
pub fn start(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self { a: sin, b: -2. * cos, c: 0. }
}
/// The contour through the end point at (1, 0), dialed by `alpha` toward the start point.
pub fn end(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self {
a: sin,
b: 2. * cos - 2. * sin,
c: sin - 2. * cos,
}
}
pub fn value(&self, point: DVec2) -> f64 {
self.a * point.length_squared() + self.b * point.x + self.c
}
/// The points where it crosses the gradient line, in homogeneous form.
fn crossings(&self) -> [Homogeneous; 2] {
solve_quadratic(self.a, self.b, self.c)
}
/// The member of the pencil `self·weight + other·other_weight`.
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
Self {
a: self.a * weight + other.a * other_weight,
b: self.b * weight + other.b * other_weight,
c: self.c * weight + other.c * other_weight,
}
}
}
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Homogeneous {
numerator: f64,
denominator: f64,
}
impl Homogeneous {
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
fn value(&self) -> Option<f64> {
(self.denominator != 0.).then(|| self.numerator / self.denominator)
}
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
fn normalized(self) -> Self {
let scale = self.numerator.abs().max(self.denominator.abs());
if scale == 0. {
return self;
}
Self {
numerator: self.numerator / scale,
denominator: self.denominator / scale,
}
}
}
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
let discriminant = (b * b - 4. * a * c).max(0.);
let sign = if b >= 0. { 1. } else { -1. };
let q = -0.5 * (b + sign * discriminant.sqrt());
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
}
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CrossingSelection {
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
/// on the same side of `radical_x` as the pixel.
SameSideAs { radical_x: f64 },
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
OnArc { quadratic: [f64; 3] },
}
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Wrap {
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
pub reference_x: f64,
/// Which side of `reference_x` the band is on, `1` or `-1`.
pub band_side: f64,
/// The t of the crossings on the far side of infinity.
pub t: f64,
}
/// Everything needed to find the t of any pixel in a dialed gradient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PencilParameters {
pub start: AxisCircle,
pub end: AxisCircle,
pub selection: CrossingSelection,
pub wrap: Option<Wrap>,
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
pub t_scale: f64,
pub t_offset: f64,
}
impl PencilParameters {
/// The parameters of the gradient with these two dials, which must be finite and within -1 to 1.
pub fn new(start_dial: f64, end_dial: f64) -> Self {
let start = AxisCircle::start(start_dial);
let end = AxisCircle::end(end_dial);
// The members of the pencil that are points have a zero discriminant, which as a quadratic form in the two members'
// weights has these coefficients. Its determinant says whether the pencil has two such points (it's hyperbolic), none
// (elliptic, where the end contours cross), or one (parabolic, where they touch).
let point_quadratic_start = start.b * start.b - 4. * start.a * start.c;
let point_quadratic_cross = start.b * end.b - 2. * (start.a * end.c + end.a * start.c);
let point_quadratic_end = end.b * end.b - 4. * end.a * end.c;
let determinant = point_quadratic_start * point_quadratic_end - point_quadratic_cross * point_quadratic_cross;
let scale = point_quadratic_start.abs().max(point_quadratic_end.abs()).max(point_quadratic_cross.abs()).max(f64::MIN_POSITIVE);
if determinant > 1e-12 * scale * scale {
// The line through the two points where the end contours cross is the member with no curvature
let line = start.combine(end.a, &end, -start.a);
let radical_x = -line.c / line.b;
return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1.);
}
// The limit points are where the point members sit, with a point member of no curvature being the point at infinity
let limit_points = point_member_weights(point_quadratic_start, point_quadratic_cross, point_quadratic_end).map(|(start_weight, end_weight)| {
let member = start.combine(start_weight, &end, end_weight);
let magnitude = member.a.abs().max(member.b.abs()).max(member.c.abs());
if member.a.abs() <= 1e-12 * magnitude {
return Homogeneous::INFINITY;
}
Homogeneous {
numerator: -member.b,
denominator: 2. * member.a,
}
.normalized()
});
// Each crossing's place relative to the limit points, negative between them and positive beyond them
let arc_quadratic = arc_quadratic(limit_points);
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
crossings
.into_iter()
.min_by(|a, b| {
let (a, b) = (arc_of(*a), arc_of(*b));
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
})
.unwrap_or(Homogeneous::INFINITY)
};
let candidates = [true, false].map(|negative_arc| {
let band_start = choose_on_arc(start.crossings(), negative_arc);
let band_end = choose_on_arc(end.crossings(), negative_arc);
(negative_arc, band_start, band_end)
});
// A band through infinity would give a contour within it an infinite t, so it's unusable. Among the rest, prefer the
// band that keeps the endpoints at t of 0 and 1.
let limit_values = limit_points.map(|point| point.value());
let usable = |band_start: Homogeneous, band_end: Homogeneous| {
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
return false;
};
match limit_values {
[Some(first), Some(second)] => {
let (low, high) = (first.min(second), first.max(second));
let beyond = |y: f64| {
if y > high {
1
} else if y < low {
-1
} else {
0
}
};
// On the outer arc, crossings on opposite sides of the limit points lie across infinity from each other
beyond(band_start) * beyond(band_end) >= 0
}
_ => true,
}
};
let truthfulness = |band_start: Homogeneous, band_end: Homogeneous| {
let is = |point: Homogeneous, target: f64| point.value().is_some_and(|value| (value - target).abs() < 1e-9);
is(band_start, 0.) as u8 + is(band_end, 1.) as u8
};
let chosen = candidates
.into_iter()
.filter(|&(_, band_start, band_end)| usable(band_start, band_end))
.max_by_key(|&(_, band_start, band_end)| truthfulness(band_start, band_end))
.unwrap_or(candidates[1]);
let (negative_arc, band_start, band_end) = chosen;
// Choosing the smallest value picks the crossing on the chosen arc
let sign = if negative_arc { 1. } else { -1. };
let selection = CrossingSelection::OnArc {
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
};
let band_start = band_start.value().unwrap_or(0.);
let band_end = band_end.value().unwrap_or(1.);
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
let wrap = match (negative_arc, limit_values) {
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
let reference_x = (first + second) / 2.;
let band_side = if band_start > reference_x { 1. } else { -1. };
let t_direction = (band_end - band_start).signum();
Some(Wrap {
reference_x,
band_side,
t: band_side * t_direction * UNBOUNDED_T,
})
}
_ => None,
};
Self::with_band(start, end, selection, wrap, band_start, band_end)
}
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64) -> Self {
let width = band_end - band_start;
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
Self {
start,
end,
selection,
wrap,
t_scale: 1. / width,
t_offset: -band_start / width,
}
}
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
pub fn t(&self, point: DVec2) -> f64 {
let start_value = self.start.value(point);
let end_value = self.end.value(point);
let scale = start_value.abs().max(end_value.abs());
if scale == 0. {
return 0.;
}
let (start_value, end_value) = (start_value / scale, end_value / scale);
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
// roots of this quadratic
let a = end_value * self.start.a - start_value * self.end.a;
let b = end_value * self.start.b - start_value * self.end.b;
let c = end_value * self.start.c - start_value * self.end.c;
let roots = solve_quadratic(a, b, c);
let crossing = match self.selection {
CrossingSelection::SameSideAs { radical_x } => {
// A pixel on the dividing line itself is on the line member, whose crossing is the finite root
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
let (first, second) = (side(roots[0]), side(roots[1]));
let first_wins = if first == second {
roots[0].denominator.abs() >= roots[1].denominator.abs()
} else {
first > second
};
if first_wins { roots[0] } else { roots[1] }
}
CrossingSelection::OnArc { quadratic } => {
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
roots[0]
} else {
roots[1]
}
}
};
if let Some(wrap) = self.wrap
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
{
return wrap.t;
}
if crossing.denominator == 0. {
let direction = crossing.numerator * self.t_scale;
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
}
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
}
}
impl PencilParameters {
/// The same parameters for Vello GPU's pencil gradient paint.
pub fn to_vello(&self) -> vello_gpu::PencilGeometry {
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
vello_gpu::PencilGeometry {
start: circle(&self.start),
end: circle(&self.end),
selection: match self.selection {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
quadratic: quadratic.map(|coefficient| coefficient as f32),
},
},
wrap: self.wrap.map(|wrap| vello_gpu::PencilWrap {
reference_x: wrap.reference_x as f32,
band_side: wrap.band_side as f32,
t: wrap.t as f32,
}),
t_scale: self.t_scale as f32,
t_offset: self.t_offset as f32,
}
}
/// The closest gradient SVG can express: a radial gradient from the start circle to the end circle when one nests inside
/// the other, or else the linear gradient along the gradient line.
pub fn svg_approximation(&self) -> SvgApproximation {
let (Some(start), Some(end)) = (self.start.center_and_radius(), self.end.center_and_radius()) else {
return SvgApproximation::Linear;
};
let distance = (start.0 - end.0).abs();
let nested = distance <= (start.1 - end.1).abs();
if !nested {
return SvgApproximation::Linear;
}
SvgApproximation::Radial {
start_center: start.0,
start_radius: start.1,
end_center: end.0,
end_radius: end.1,
}
}
}
/// A gradient SVG can draw in place of a dialed one, in gradient space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum SvgApproximation {
Linear,
/// From the start circle, as SVG's focal circle, out to the end circle, both centered on the gradient line.
Radial {
start_center: f64,
start_radius: f64,
end_center: f64,
end_radius: f64,
},
}
impl AxisCircle {
/// Where its center sits on the gradient line, and its radius, unless it's a line.
fn center_and_radius(&self) -> Option<(f64, f64)> {
if self.a.abs() < 1e-9 {
return None;
}
let center = -self.b / (2. * self.a);
let radius = (center * center - self.c / self.a).max(0.).sqrt();
Some((center, radius))
}
}
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
let discriminant = (cross * cross - start * end).max(0.).sqrt();
if start.abs() < 1e-12 && end.abs() < 1e-12 {
// Both end contours are points already
[(1., 0.), (0., 1.)]
} else if start.abs() >= end.abs() {
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
} else {
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
}
}
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
let orient = |point: Homogeneous| {
if point.denominator < 0. {
Homogeneous {
numerator: -point.numerator,
denominator: -point.denominator,
}
} else {
point
}
};
let (first, second) = (orient(first), orient(second));
[
first.denominator * second.denominator,
-(first.denominator * second.numerator + first.numerator * second.denominator),
first.numerator * second.numerator,
]
}
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
let Homogeneous { numerator, denominator } = point;
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_close(actual: f64, expected: f64, context: &str) {
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
}
#[test]
fn radial_dials_space_contours_by_radius() {
let parameters = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
for angle in [0., 0.7, 2., 3.1, 4.5] {
let point = DVec2::from_angle(angle) * radius;
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
}
}
}
#[test]
fn linear_dials_space_contours_by_distance_along_the_line() {
let parameters = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
assert_close(parameters.t(point), point.x, &format!("point {point}"));
}
}
#[test]
fn concentric_dials_space_contours_by_radius_between_the_ends() {
// The donut: a hole of radius 1 centered 1 before the start, and an end circle of radius 2 around the same center
let parameters = PencilParameters::new(-0.5, 0.5_f64.atan() / FRAC_PI_2);
let center = DVec2::new(-1., 0.);
for radius in [1., 1.25, 1.5, 2., 3.] {
for angle in [0., 1., 2.5, 4.] {
let point = center + DVec2::from_angle(angle) * radius;
assert_close(parameters.t(point), radius - 1., &format!("radius {radius} at angle {angle}"));
}
}
}
#[test]
fn point_dials_space_contours_by_distance_ratio() {
let parameters = PencilParameters::new(1., 1.);
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
let ratio = point.length() / (point - DVec2::X).length();
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
}
}
#[test]
fn dials_near_a_preset_render_like_it() {
let radial = PencilParameters::new(RADIAL_DIALS[0], RADIAL_DIALS[1]);
let near_radial = PencilParameters::new(RADIAL_DIALS[0] - 1e-7, RADIAL_DIALS[1] + 1e-7);
let linear = PencilParameters::new(LINEAR_DIALS[0], LINEAR_DIALS[1]);
let near_linear = PencilParameters::new(LINEAR_DIALS[0] + 1e-7, LINEAR_DIALS[1] - 1e-7);
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
}
}
#[test]
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
// The start point sits inside the end circle, off its center
let parameters = PencilParameters::new(1., 0.6);
assert_close(parameters.t(DVec2::X), 1., "end point");
let inside = parameters.t(DVec2::new(0.5, 0.));
assert!(inside > 0. && inside < 1., "inside: {inside}");
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
let t = parameters.t(point);
assert!(t > 1., "outside at {point}: {t}");
}
}
#[test]
fn crossing_contours_fan_through_their_lens() {
let parameters = PencilParameters::new(0.6, 0.6);
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
}
// Mirrored across the gradient line
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
}
#[test]
fn every_dial_pair_gives_a_number_everywhere() {
for start_step in -10..=10 {
for end_step in -10..=10 {
let parameters = PencilParameters::new(start_step as f64 / 10., end_step as f64 / 10.);
for x in -8..=8 {
for y in -8..=8 {
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
let t = parameters.t(point);
assert!(!t.is_nan(), "dials ({start_step}, {end_step}) at {point}");
}
}
}
}
}
}
@@ -1,4 +1,5 @@
pub mod convert_usvg_path;
pub mod dial_gradient;
pub mod render_ext;
mod renderer;
pub mod to_peniko;
@@ -1,14 +1,14 @@
use crate::renderer::{
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples, transform_is_invertible,
GradientShape, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_settings_from_item, spread_adjusted_samples,
svg_gradient_definition, transform_is_invertible,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::color::SRGBA8;
use core_types::list::List;
use core_types::uuid::generate_uuid;
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use core_types::{ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::vector_types::gradient::GradientForm;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write;
use vector_types::Gradient;
@@ -88,11 +88,11 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
let item = item?;
let stops = item.element()?;
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let shape = GradientShape::of(item);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let settings = gradient_settings_from_item(item);
let mut samples = spread_adjusted_samples(stops, settings, gradient_form);
let mut samples = spread_adjusted_samples(stops, settings, shape.reaches_before_start());
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
@@ -134,7 +134,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
let document_transform = item_transform * local_gradient_transform;
let placement = gradient_placement(document_transform, gradient_form);
let placement = gradient_placement(document_transform, shape);
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
let gradient_transform = if gradient_transform.is_empty() {
String::new()
@@ -149,23 +149,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
};
let gradient_id = generate_uuid();
match gradient_form {
GradientForm::Linear => {
let _ = write!(
svg_defs,
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
gradient_id, stop
);
}
GradientForm::Radial => {
let _ = write!(
svg_defs,
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
gradient_id, stop
);
}
}
svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &format!("{gradient_spread}{gradient_transform}"), &stop));
Some(gradient_id)
}
+333 -118
View File
@@ -1,6 +1,7 @@
use crate::dial_gradient::{LINEAR_DIALS, PencilParameters, RADIAL_DIALS, SvgApproximation};
use crate::render_ext::{PaintTarget, RenderExt};
use crate::to_peniko::{BlendModeExt, ToPenikoColor};
use crate::vello_scene_builder::VelloSceneBuilder;
use crate::vello_scene_builder::{SceneBrush, VelloSceneBuilder};
use core_types::CacheHash;
use core_types::FallibleVec2Operations;
use core_types::blending::{BlendMode, blend_colors};
@@ -17,21 +18,21 @@ use core_types::transform::Footprint;
use core_types::uuid::{NodeId, generate_uuid};
use core_types::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_FORM, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY,
ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION,
ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
};
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2};
use graphene_resource::Resource;
use graphic_types::raster_types::{CPU, GPU, Raster, Storage, Texture};
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::gradient::{Gradient, GradientForm, wrapped_dial};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
use graphic_types::vector_types::vector::misc::dvec2_to_point;
use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, StrokeCap, StrokeJoin};
use graphic_types::vector_types::vector::{
GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths,
};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, Effects, FillAndStroke, Graphic, Vector};
use graphic_types::{Adjustment, Appearance, Artboard, BevelStyle, Cover, Coverage, EffectOperation, Effects, FillAndStroke, Graphic, Vector, fitted_paint};
use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape};
use num_traits::Zero;
use raster_kernels::adjustments::{adjust_color, adjusted_raster, leading_adjustments, preserves_alpha};
@@ -247,17 +248,45 @@ impl ItemCompositing<'_> {
}
}
/// Draws the content `draw` draws through the effects group, given the content's bounds in the scene's space.
/// Rendering a split scene calls `draw` again for each part.
fn draw_with_effects(&self, scene: &mut VelloSceneBuilder, bounds: impl FnOnce() -> RenderBoundingBox, mut draw: impl FnMut(&mut VelloSceneBuilder)) {
/// Draws the content `draw` draws through the effects group, given the content's bounds in the scene's space. Rendering a split scene calls `draw` again for each part.
/// `transform` maps the space the content's item is placed in, where the paint overlays' paints are placed too, into the scene's space.
fn draw_with_effects(
&self,
scene: &mut VelloSceneBuilder,
transform: DAffine2,
render_params: &RenderParams,
bounds: impl FnOnce() -> RenderBoundingBox,
mut draw: impl FnMut(&mut VelloSceneBuilder),
) {
let Some((effects, fill)) = self.effects else { return draw(scene) };
let bounds = match bounds() {
RenderBoundingBox::Rectangle([min, max]) => Some(kurbo::Rect::new(min.x, min.y, max.x, max.y)),
RenderBoundingBox::Rectangle(bounds) => Some(bounds),
RenderBoundingBox::Infinite => None,
RenderBoundingBox::None => return draw(scene),
};
scene.draw_effects(effects, fill, bounds, &mut draw);
// A paint fitted to the content's bounds is placed in the scene's space they're measured in
let paint_params = render_params.for_pattern();
let paints: Vec<(Graphic, DAffine2)> = effects
.operations()
.filter_map(|operation| match operation {
EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| match bounds.and_then(|bounds| fitted_paint(&paint, bounds)) {
Some(fitted) => (fitted, DAffine2::IDENTITY),
None => (paint, transform),
})
.collect();
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
if let Some((paint, transform)) = paints.get(index) {
paint.render_to_vello(scene, *transform, &paint_params);
}
};
let bounds = bounds.map(|[min, max]| kurbo::Rect::new(min.x, min.y, max.x, max.y));
scene.draw_effects(effects, fill, bounds, &mut draw_paint, &mut draw);
}
/// The opacity for content drawn without the effects group, as SVG draws content its filter can't apply to.
@@ -303,13 +332,30 @@ impl ItemCompositing<'_> {
/// Writes the SVG filter carrying out the effects, if there are any to apply, given the content's bounds in the current user space.
/// Returns the reference for the `filter` attribute of a group wrapping the content, which also takes the item's opacity and blend mode.
fn svg_filter(&self, render: &mut SvgRender, bounds: impl FnOnce() -> RenderBoundingBox) -> Option<String> {
fn svg_filter(&self, render: &mut SvgRender, render_params: &RenderParams, bounds: impl FnOnce() -> RenderBoundingBox) -> Option<String> {
let (effects, fill) = self.effects?;
// Effects change nothing visible about content without edges, like a color or gradient layer filling everything
let RenderBoundingBox::Rectangle(bounds) = bounds() else { return None };
let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform, self.pixel_scale)?;
// The paint overlays' paints that aren't solid colors, drawn as markup in the user space, where the content's bounds fit those without a placement
let paint_params = render_params.for_pattern();
let paints: Vec<String> = effects
.operations()
.filter_map(|operation| match operation {
EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| {
let paint = fitted_paint(&paint, bounds).unwrap_or(paint);
let mut paint_render = SvgRender::new();
paint_render.transform = render.transform;
paint.render_svg(&mut paint_render, &paint_params);
format!("<defs>{}</defs>{}", paint_render.svg_defs, paint_render.svg.to_svg_string())
})
.collect();
let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform, self.pixel_scale, &paints)?;
Some(format!("url(#{id})"))
}
}
@@ -487,6 +533,30 @@ impl SvgFilterPrimitives {
)
}
/// A paint's markup, drawn in the user space, as an image filling the `region` of it from its minimum to its maximum corner.
/// Filters take outside graphics only as images, which an embedded SVG document keeps portable to viewers that can't reference elements.
fn paint_image(&mut self, markup: &str, [min, max]: [DVec2; 2]) -> String {
use base64::Engine;
let size = max - min;
let document = format!(
r#"<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:graphite="https://graphite.art" viewBox="{} {} {} {}" width="{}" height="{}" preserveAspectRatio="none">{markup}</svg>"#,
min.x, min.y, size.x, size.y, size.x, size.y
);
let href = format!("data:image/svg+xml;base64,{}", base64::engine::general_purpose::STANDARD.encode(document));
let placement = format!(r#"x="{}" y="{}" width="{}" height="{}" preserveAspectRatio="none""#, min.x, min.y, size.x, size.y);
self.push("feImage", &format!(r#"href="{href}" {placement}"#), "")
}
/// The image with the paint mixed over its colors by the blend mode, keeping its alpha.
fn overlay(&mut self, image: &str, paint: &str, blend_mode: BlendMode) -> String {
// SVG has no counterpart for some blend modes, which paint normally instead
let mode = blend_mode.to_svg_style_name().unwrap_or("normal");
let blended = self.push("feBlend", &format!(r#"in="{paint}" in2="{image}" mode="{mode}""#), "");
self.push("feComposite", &format!(r#"in="{blended}" in2="{image}" operator="atop""#), "")
}
/// The coverage tinted `color`.
fn tint(&mut self, coverage: &str, color: Color) -> String {
let flood = self.push(
@@ -604,8 +674,8 @@ impl SvgFilterPrimitives {
/// Writes an SVG filter into `svg_defs` that carries out `effects` like the GPU passes do, returning its ID, or `None` if the user space is degenerate.
/// `bounds` is the content's extent in the filtered group's user space, which `user_to_document` maps into the document space the effects' lengths are measured in.
/// `pixel_scale` is how many output pixels span a document unit.
fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2, pixel_scale: f64) -> Option<String> {
/// `pixel_scale` is how many output pixels span a document unit, and `paints` holds the markup of the paint overlays' paints that aren't solid colors, in order.
fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2, pixel_scale: f64, paints: &[String]) -> Option<String> {
use graphic_types::effects::{bevel_light, outline_extents};
use graphic_types::{BevelDirection, EffectOperation, GlowSource};
@@ -616,7 +686,12 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
let document_to_user = user_to_document.matrix2.inverse();
let length_scale = determinant.abs().sqrt().recip();
// The filter covers how far the effects reach past the content
let reach = effects.reach() * length_scale;
let region = [bounds[0] - reach, bounds[1] + reach];
let mut primitives = SvgFilterPrimitives::default();
let mut paints = paints.iter();
// The content at full strength, which casts every silhouette, and the content faded by the fill, which shows in the result
let mut full = "SourceGraphic".to_string();
@@ -721,6 +796,18 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
primitives.shade_within(&mut full, &mut filled, &coverage, color);
}
}
EffectOperation::PaintOverlay { blend_mode, opacity, .. } => {
let Some(markup) = paints.next() else { continue };
let mut paint = primitives.paint_image(markup, region);
if opacity < 100. {
let slope = opacity / 100.;
paint = primitives.push("feComponentTransfer", &format!(r#"in="{paint}""#), &format!(r#"<feFuncA type="linear" slope="{slope}" />"#));
}
filled = filled.map(|filled| primitives.overlay(&filled, &paint, blend_mode));
full = primitives.overlay(&full, &paint, blend_mode);
}
EffectOperation::Adjustment(ref adjustment) => {
filled = filled.map(|filled| primitives.adjust(&filled, adjustment));
full = primitives.adjust(&full, adjustment);
@@ -739,9 +826,7 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32,
}
}
// The filter covers how far the effects reach past the content
let reach = effects.reach() * length_scale;
let (min, max) = (bounds[0] - reach, bounds[1] + reach);
let [min, max] = region;
let id = format!("effects-{}", generate_uuid());
write!(
svg_defs,
@@ -1138,22 +1223,51 @@ pub(crate) fn transform_is_invertible(transform: DAffine2) -> bool {
transform.matrix2.determinant().recip().is_finite()
}
/// Maps a gradient's `transform` into the frame handed to the renderer: radial keeps the full matrix (so a
/// How a gradient's contours are laid out, decided by its form and curvature dials.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum GradientShape {
/// Both ends are lines.
Linear,
/// The start is a point at the center of the end circle.
Radial,
/// Any other pair of dialed end contours, with the pencil of circles they span filling in between.
Pencil(PencilParameters),
}
impl GradientShape {
pub(crate) fn of(item: ItemRef<'_, Gradient>) -> Self {
let preset = item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM).dials();
let dial = |key: &str, preset: f64| wrapped_dial(item.attribute_cloned_or(key, preset), preset);
let dials = [dial(ATTR_GRADIENT_START_CURVATURE, preset[0]), dial(ATTR_GRADIENT_END_CURVATURE, preset[1])];
match dials {
LINEAR_DIALS => Self::Linear,
RADIAL_DIALS => Self::Radial,
[start, end] => Self::Pencil(PencilParameters::new(start, end)),
}
}
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero.
pub(crate) fn reaches_before_start(&self) -> bool {
!matches!(self, Self::Radial)
}
}
/// Maps a gradient's `transform` into the frame handed to the renderer: most shapes keep the full matrix (so a
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
/// represent since it stores only two endpoints.
pub(crate) fn gradient_placement(transform: DAffine2, gradient_form: GradientForm) -> DAffine2 {
match gradient_form {
GradientForm::Radial => transform,
GradientForm::Linear => {
let axis = transform.matrix2.x_axis;
let band_normal = transform.matrix2.y_axis.perp();
let line = axis.try_project_onto(band_normal).unwrap_or(axis);
DAffine2 {
matrix2: DMat2::from_cols(line, line.perp()),
translation: transform.translation,
}
}
pub(crate) fn gradient_placement(transform: DAffine2, shape: GradientShape) -> DAffine2 {
if shape != GradientShape::Linear {
return transform;
}
let axis = transform.matrix2.x_axis;
let band_normal = transform.matrix2.y_axis.perp();
let line = axis.try_project_onto(band_normal).unwrap_or(axis);
DAffine2 {
matrix2: DMat2::from_cols(line, line.perp()),
translation: transform.translation,
}
}
@@ -1163,9 +1277,9 @@ type GradientSamples = Vec<(f64, Color, Option<f64>)>;
/// The gradient's renderable samples, bracketed for the `Clear` spread (which neither SVG nor Vello supports natively) by transparent guard stops.
///
/// The guards share the unit range's end offsets, ordered so the pad extension paints transparency outward while the later
/// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. A radial gradient needs no guard
/// at its start, since its sampling distance never goes below the center.
pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSettings, gradient_form: GradientForm) -> GradientSamples {
/// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. The guard at the start is left out
/// for a gradient whose position can't reach before it.
pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSettings, reaches_before_start: bool) -> GradientSamples {
let samples = gradient.interpolated_samples(settings);
if settings.spread != GradientSpread::Clear {
return samples;
@@ -1180,7 +1294,7 @@ pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSet
let mut adjusted = Vec::with_capacity(samples.len() + 4);
// Lead with the transparent guard, then anchor the visible range's start color
if gradient_form == GradientForm::Linear {
if reaches_before_start {
adjusted.push((0., Color::TRANSPARENT, None));
}
if needs_start_anchor {
@@ -1214,14 +1328,15 @@ fn peniko_color_stops(samples: &[(f64, Color, Option<f64>)]) -> peniko::ColorSto
}
/// The gradient in its own space before the brush transform places it: the line from the origin along +X to 1 for linear, or the unit circle about the origin for radial.
fn unit_gradient_kind(gradient_form: GradientForm) -> peniko::GradientKind {
match gradient_form {
GradientForm::Linear => peniko::LinearGradientPosition {
/// A pencil gradient's contours come from its own geometry, so it takes the linear kind, which goes unused.
fn unit_gradient_kind(shape: GradientShape) -> peniko::GradientKind {
match shape {
GradientShape::Linear | GradientShape::Pencil(_) => peniko::LinearGradientPosition {
start: kurbo::Point::ORIGIN,
end: kurbo::Point::new(1., 0.),
}
.into(),
GradientForm::Radial => peniko::RadialGradientPosition {
GradientShape::Radial => peniko::RadialGradientPosition {
start_center: kurbo::Point::ORIGIN,
start_radius: 0.,
end_center: kurbo::Point::ORIGIN,
@@ -1231,6 +1346,60 @@ fn unit_gradient_kind(gradient_form: GradientForm) -> peniko::GradientKind {
}
}
/// The SVG element defining a gradient of this shape in the unit gradient's own space, with `attributes` (like its spread
/// and transform) added. SVG has no dialed contours, so a pencil gradient is drawn as the closest gradient SVG has.
pub(crate) fn svg_gradient_definition(shape: GradientShape, id: u64, attributes: &str, stops: &str) -> String {
let approximation = match shape {
GradientShape::Linear => SvgApproximation::Linear,
GradientShape::Radial => SvgApproximation::Radial {
start_center: 0.,
start_radius: 0.,
end_center: 0.,
end_radius: 1.,
},
GradientShape::Pencil(parameters) => parameters.svg_approximation(),
};
match approximation {
SvgApproximation::Linear => format!(r#"<linearGradient id="{id}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{attributes}>{stops}</linearGradient>"#),
SvgApproximation::Radial {
start_center,
start_radius,
end_center,
end_radius,
} => {
// SVG's default focal circle is the point at the center, so it's written only where it differs
let focal = if start_center == end_center && start_radius == 0. {
String::new()
} else {
format!(r#" fx="{start_center}" fy="0" fr="{start_radius}""#)
};
format!(r#"<radialGradient id="{id}" gradientUnits="userSpaceOnUse" cx="{end_center}" cy="0" r="{end_radius}"{focal}{attributes}>{stops}</radialGradient>"#)
}
}
}
/// The scene brush painting a gradient of this shape with these samples, in the unit gradient's own space.
fn gradient_scene_brush(shape: GradientShape, samples: &[(f64, Color, Option<f64>)], spread: GradientSpread) -> SceneBrush {
let ramp = peniko::Gradient {
kind: unit_gradient_kind(shape),
extend: peniko_extend(spread),
stops: peniko_color_stops(samples),
// Straight alpha, keeping parity with the SVG renderer's stop interpolation
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
..Default::default()
};
match shape {
GradientShape::Pencil(parameters) => vello_gpu::PencilGradient {
ramp,
geometry: parameters.to_vello(),
}
.into(),
GradientShape::Linear | GradientShape::Radial => peniko::Brush::Gradient(ramp).into(),
}
}
/// The peniko extend mode for a spread; `Clear` rides pad, with the transparent guard stops from `spread_adjusted_samples` doing the clearing.
fn peniko_extend(gradient_spread: GradientSpread) -> peniko::Extend {
match gradient_spread {
@@ -1242,14 +1411,14 @@ fn peniko_extend(gradient_spread: GradientSpread) -> peniko::Extend {
/// The Vello brush for one gradient item, paired with its placement transform.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
fn create_peniko_gradient_brush(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<(peniko::Brush, DAffine2)> {
fn create_gradient_brush(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<(SceneBrush, DAffine2)> {
let stops = gradient_item.element()?;
let gradient_form: GradientForm = gradient_item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let shape = GradientShape::of(gradient_item);
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
let settings = gradient_settings_from_item(gradient_item);
let mut samples = spread_adjusted_samples(stops, settings, gradient_form);
let mut samples = spread_adjusted_samples(stops, settings, shape.reaches_before_start());
let paint_opacity = gradient_item.paint_opacity(for_mask);
if paint_opacity < 1. {
@@ -1263,19 +1432,9 @@ fn create_peniko_gradient_brush(gradient_item: ItemRef<'_, Gradient>, multiplied
}
}
let peniko_stops = peniko_color_stops(&samples);
// The unit gradient is placed by the desheared frame so a non-uniform transform produces the intended ellipse
let gradient_to_device = gradient_placement(multiplied_transform * gradient_transform, gradient_form);
let brush = peniko::Brush::Gradient(peniko::Gradient {
kind: unit_gradient_kind(gradient_form),
extend: peniko_extend(settings.spread),
stops: peniko_stops,
// Straight alpha, keeping parity with the SVG renderer's stop interpolation
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
..Default::default()
});
let gradient_to_device = gradient_placement(multiplied_transform * gradient_transform, shape);
let brush = gradient_scene_brush(shape, &samples, settings.spread);
Some((brush, gradient_to_device))
}
@@ -1443,7 +1602,7 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
let render_item = |render: &mut SvgRender| {
// The filter also covers how far the effects nested inside reach past the content, measured in this user space
let document_scale = render.transform.matrix2.determinant().abs().sqrt();
let filter = compositing.svg_filter(render, || match element.bounding_box(transform, true) {
let filter = compositing.svg_filter(render, render_params, || match element.bounding_box(transform, true) {
RenderBoundingBox::Rectangle([min, max]) => {
let nested_reach = nested_effects_reach(element) / document_scale;
RenderBoundingBox::Rectangle([min - nested_reach, max + nested_reach])
@@ -1499,12 +1658,12 @@ fn render_graphic_item_to_vello<'a>(
next_clips: bool,
mask_element_and_transform: &mut Option<(&'a Graphic, DAffine2)>,
scene: &mut VelloSceneBuilder,
transform: DAffine2,
parent_transform: DAffine2,
render_params: &RenderParams,
) {
let Some(element) = item.element() else { return };
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let transform = transform * item_transform;
let transform = parent_transform * item_transform;
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
// This item's declared appearance (if any) cascades to descendants lacking their own
let child_render_params = item
@@ -1550,7 +1709,7 @@ fn render_graphic_item_to_vello<'a>(
bounds => bounds,
};
let draw_content = |scene: &mut VelloSceneBuilder| {
compositing.draw_with_effects(scene, effects_bounds, |scene| element.render_to_vello(scene, transform, render_params));
compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, |scene| element.render_to_vello(scene, transform, render_params));
};
if next_clips && mask_element_and_transform.is_none() {
@@ -1740,7 +1899,7 @@ impl Render for Graphic {
}
Graphic::RasterCPU(item) => render_raster_cpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::RasterGPU(item) => render_raster_gpu_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, render_params),
Graphic::Color(item) => render_color_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Gradient(item) => render_gradient_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::Text(item) => render_text_item_to_vello(ItemRef::Item(item), scene, transform, render_params),
Graphic::GraphicList(list) => list.render_to_vello(scene, transform, render_params),
@@ -2403,7 +2562,7 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
};
let render_shape = |render: &mut SvgRender| {
let filter = compositing.svg_filter(render, || {
let filter = compositing.svg_filter(render, render_params, || {
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let stroke = appearance().and_then(|appearance| appearance.fill_and_stroke().stroke);
let paths = item.attribute::<List<Path>>(ATTR_PATHS).unwrap_or_else(|| no_paths());
@@ -2602,7 +2761,7 @@ fn render_vector_item_to_vello(
scene.fill_path(fill_rule, element_affine, &fill, None, path);
};
let gradient_fill = |scene: &mut VelloSceneBuilder, gradient_item: ItemRef<'_, Gradient>| {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(gradient_item, &multiplied_transform, render_params.for_mask) else {
let Some((brush, gradient_to_device)) = create_gradient_brush(gradient_item, &multiplied_transform, render_params.for_mask) else {
return;
};
@@ -2612,7 +2771,7 @@ fn render_vector_item_to_vello(
Default::default()
};
let brush_transform = kurbo::Affine::new((inverse_element_transform * gradient_to_device).to_cols_array());
scene.fill_path(fill_rule, element_affine, &brush, Some(brush_transform), path);
scene.fill_path(fill_rule, element_affine, brush, Some(brush_transform), path);
};
match paint {
@@ -2691,7 +2850,7 @@ fn render_vector_item_to_vello(
scene.fill_path(peniko::Fill::NonZero, element_affine, &brush, None, &outline);
};
let gradient_stroke = |scene: &mut VelloSceneBuilder, gradient_item: ItemRef<'_, Gradient>| {
let Some((brush, gradient_to_device)) = create_peniko_gradient_brush(gradient_item, &multiplied_transform, render_params.for_mask) else {
let Some((brush, gradient_to_device)) = create_gradient_brush(gradient_item, &multiplied_transform, render_params.for_mask) else {
return;
};
let inverse_element_transform = if transform_is_invertible(element_transform) {
@@ -2702,7 +2861,7 @@ fn render_vector_item_to_vello(
let brush_transform = kurbo::Affine::new((inverse_element_transform * gradient_to_device).to_cols_array());
let outline = placed.stroke_outline(&stroke, scene.stroke_tolerance(element_affine));
scene.fill_path(peniko::Fill::NonZero, element_affine, &brush, Some(brush_transform), &outline);
scene.fill_path(peniko::Fill::NonZero, element_affine, brush, Some(brush_transform), &outline);
};
match paint {
@@ -2744,7 +2903,7 @@ fn render_vector_item_to_vello(
}
_ => {
let effects_bounds = || layer_geometry.map_or(RenderBoundingBox::None, |(layer_affine, layer_rect)| rect_bounds(layer_affine.transform_rect_bbox(layer_rect)));
compositing.draw_with_effects(scene, effects_bounds, |scene| {
compositing.draw_with_effects(scene, parent_transform, render_params, effects_bounds, |scene| {
if use_layer {
let cloned_element = element.clone();
@@ -3163,7 +3322,9 @@ fn render_raster_image_svg<T>(item: ItemRef<'_, T>, image: &Raster<CPU>, coverag
}
};
let filter = compositing.svg_filter(render, || RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()));
let filter = compositing.svg_filter(render, render_params, || {
RenderBoundingBox::Rectangle((transform * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box())
});
// A filter's wrapping group takes the opacity and blend mode instead
let (opacity, blend_mode) = match filter {
@@ -3300,7 +3461,7 @@ fn render_raster_cpu_item_to_vello(item: ItemRef<'_, Raster<CPU>>, scene: &mut V
let sampler = peniko::ImageSampler::new().with_extend(peniko::Extend::Pad);
let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box());
compositing.draw_with_effects(scene, item_bounds, |scene| {
compositing.draw_with_effects(scene, transform, render_params, item_bounds, |scene| {
let image_transform = kurbo::Affine::new(image_transform.to_cols_array());
match &adjusted_texture {
Some(texture) => scene.draw_texture(texture.clone(), sampler, image_transform),
@@ -3463,7 +3624,7 @@ fn render_raster_gpu_item_to_vello(item: ItemRef<'_, Raster<GPU>>, scene: &mut V
let image_transform = transform * transform_attribute * coverage * DAffine2::from_scale(1. / DVec2::new(width as f64, height as f64));
let item_bounds = || RenderBoundingBox::Rectangle((transform * transform_attribute * coverage * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box());
compositing.draw_with_effects(scene, item_bounds, |scene| {
compositing.draw_with_effects(scene, transform, render_params, item_bounds, |scene| {
scene.draw_texture(texture.clone(), sampler, kurbo::Affine::new(image_transform.to_cols_array()))
});
@@ -3490,9 +3651,9 @@ impl Render for List<Color> {
}
}
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, _parent_transform: DAffine2, render_params: &RenderParams) {
fn render_to_vello(&self, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) {
for index in 0..self.len() {
render_color_item_to_vello(ItemRef::ListItem(self, index), scene, render_params);
render_color_item_to_vello(ItemRef::ListItem(self, index), scene, parent_transform, render_params);
}
}
}
@@ -3527,7 +3688,7 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende
}
/// Draws one item of color content into the Vello scene, covering the whole render area.
fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, render_params: &RenderParams) {
fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBuilder, parent_transform: DAffine2, render_params: &RenderParams) {
let Some(color) = item.element() else { return };
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let compositing = item.compositing(render_params);
@@ -3542,7 +3703,7 @@ fn render_color_item_to_vello(item: ItemRef<'_, Color>, scene: &mut VelloSceneBu
layer = true;
}
compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(vello_color, None));
compositing.draw_with_effects(scene, parent_transform, render_params, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(vello_color, None));
if layer {
scene.pop_layer();
@@ -3635,7 +3796,7 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu
let blend_mode: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let opacity_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY, 1.);
let opacity_fill_attr: f64 = item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.);
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let shape = GradientShape::of(item);
let settings = gradient_settings_from_item(item);
let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" };
render.leaf_tag(tag, |attributes| {
@@ -3652,7 +3813,7 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu
attributes.push("points", format!("{MAX},{MAX} -{MAX},{MAX} -{MAX},-{MAX} {MAX},-{MAX}"));
}
let samples = spread_adjusted_samples(gradient, settings, gradient_form);
let samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start());
let mut stop_string = String::new();
for (position, color, original_midpoint) in samples {
@@ -3683,20 +3844,8 @@ fn render_gradient_item_svg_with_thumbnail_rect(item: ItemRef<'_, Gradient>, thu
};
// The unit gradient line is the +X unit vector in local space, before the item's transform is applied
match gradient_form {
GradientForm::Linear => {
let _ = write!(
&mut attributes.0.svg_defs,
r#"<linearGradient id="{gradient_id}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread_attribute}{gradient_transform_attribute}>{stop_string}</linearGradient>"#
);
}
GradientForm::Radial => {
let _ = write!(
&mut attributes.0.svg_defs,
r#"<radialGradient id="{gradient_id}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread_attribute}{gradient_transform_attribute}>{stop_string}</radialGradient>"#
);
}
}
let definition_attributes = format!("{gradient_spread_attribute}{gradient_transform_attribute}");
attributes.0.svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &definition_attributes, &stop_string));
attributes.push("fill", format!("url('#{gradient_id}')"));
@@ -3719,7 +3868,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
{
let Some(gradient) = item.element() else { return };
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let shape = GradientShape::of(item);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let blend_mode_attr: BlendMode = item.attribute_cloned_or_default(ATTR_BLEND_MODE);
let compositing = item.compositing(render_params);
@@ -3729,22 +3878,9 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
let opacity = compositing.opacity;
let settings = gradient_settings_from_item(item);
let samples = spread_adjusted_samples(gradient, settings, gradient_form);
let stops = peniko_color_stops(&samples);
let extend = peniko_extend(settings.spread);
let kind = unit_gradient_kind(gradient_form);
let fill = peniko::Brush::Gradient(peniko::Gradient {
kind,
stops,
extend,
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
..Default::default()
});
let brush_transform = kurbo::Affine::new(gradient_placement(gradient_transform, gradient_form).to_cols_array());
let samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start());
let fill = gradient_scene_brush(shape, &samples, settings.spread);
let brush_transform = kurbo::Affine::new(gradient_placement(gradient_transform, shape).to_cols_array());
let mut layer = false;
if opacity < 1. || blend_mode_attr != BlendMode::default() {
@@ -3752,7 +3888,13 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
layer = true;
}
compositing.draw_with_effects(scene, || RenderBoundingBox::Infinite, |scene| scene.fill_viewport(&fill, Some(brush_transform)));
compositing.draw_with_effects(
scene,
parent_transform,
render_params,
|| RenderBoundingBox::Infinite,
|scene| scene.fill_viewport(fill.clone(), Some(brush_transform)),
);
if layer {
scene.pop_layer();
@@ -3769,7 +3911,7 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
let mut outline_targets = Vec::new();
let mut click_targets = Vec::new();
for item in items {
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let gradient_form = gradient_control_form(item);
let item_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
// The first item's transform is the reference all targets bake against
@@ -3795,9 +3937,17 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
}
}
/// The form whose control geometry a gradient item shows, which is linear for every shape but the radial one.
fn gradient_control_form(item: ItemRef<'_, Gradient>) -> GradientForm {
match GradientShape::of(item) {
GradientShape::Radial => GradientForm::Radial,
GradientShape::Linear | GradientShape::Pencil(_) => GradientForm::Linear,
}
}
/// Collects one gradient item's control geometry as a click target when its interior is draggable.
fn add_gradient_item_click_targets(item: ItemRef<'_, Gradient>, click_targets: &mut Vec<ClickTarget>) {
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let gradient_form = gradient_control_form(item);
if !gradient_control_interior_is_clickable(gradient_form) {
return;
}
@@ -3810,7 +3960,7 @@ fn add_gradient_item_click_targets(item: ItemRef<'_, Gradient>, click_targets: &
/// Collects one gradient item's control geometry as an outline target.
fn add_gradient_item_outline_targets(item: ItemRef<'_, Gradient>, outlines: &mut Vec<ClickTarget>) {
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
let gradient_form = gradient_control_form(item);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut target = ClickTarget::new_with_path(gradient_control_outline(gradient_form), 0.);
@@ -4059,7 +4209,7 @@ fn render_text_item_svg(item: ItemRef<'_, String>, render: &mut SvgRender, rende
return;
}
let filter = compositing.svg_filter(render, || layout_bounds);
let filter = compositing.svg_filter(render, render_params, || layout_bounds);
let filtered = filter.is_some();
// Wrap all glyph <path> elements in a <g> with the item's transform/opacity/blend-mode, which a filter's wrapping group takes instead
@@ -4158,6 +4308,8 @@ fn render_text_item_to_vello(item: ItemRef<'_, String>, scene: &mut VelloSceneBu
compositing.draw_with_effects(
scene,
transform,
render_params,
|| rect_bounds(transformed_bounds()),
|scene| {
text_nodes::for_each_styled_glyph_run(&layout, text, typesetting, |glyph_run, x_offset, space_extra| {
@@ -4354,18 +4506,18 @@ mod tests {
};
// Other spreads pass the samples through unchanged
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), GradientForm::Linear);
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), true);
assert_eq!(samples, gradient.interpolated_samples(settings(GradientSpread::Pad)));
// The guards share the range ends' exact offsets, ordered so the pad extension resolves to the transparent outer stops
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientForm::Linear);
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), true);
assert_eq!(
samples,
vec![(0., Color::TRANSPARENT, None), (0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]
);
// A radial has no guard below the center
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientForm::Radial);
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Radial.reaches_before_start());
assert_eq!(samples, vec![(0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]);
}
@@ -4378,7 +4530,7 @@ mod tests {
space: GradientSpace::RgbGamma,
..Default::default()
},
GradientForm::Linear,
true,
);
let colors: Vec<Color> = samples.iter().map(|&(_, color, _)| color).collect();
assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]);
@@ -4411,6 +4563,33 @@ mod tests {
assert_eq!(halvings(0.), [0]);
}
#[test]
fn gradient_shape_follows_the_form_until_dialed() {
let shape = |form: Option<GradientForm>, dials: Option<(f64, f64)>| {
let mut item = Item::new_from_element(Gradient::from(Vec::new()));
if let Some(form) = form {
item.set_attribute(ATTR_GRADIENT_FORM, form);
}
if let Some((start, end)) = dials {
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end);
}
GradientShape::of(ItemRef::Item(&item))
};
assert_eq!(shape(None, None), GradientShape::Linear);
assert_eq!(shape(Some(GradientForm::Radial), None), GradientShape::Radial);
// The dials override the form, and either one's presets take the native path
assert_eq!(shape(Some(GradientForm::Radial), Some((0., 0.))), GradientShape::Linear);
assert_eq!(shape(None, Some((1., 0.5))), GradientShape::Radial);
assert!(matches!(shape(None, Some((0.5, 0.25))), GradientShape::Pencil(_)));
// A dial wraps around, with -1 and 3 both being the end's own point like 1
assert_eq!(shape(None, Some((-1., 0.5))), GradientShape::Radial);
assert_eq!(shape(None, Some((3., 0.5))), GradientShape::Radial);
}
#[test]
fn svg_effects_filters_measure_lengths_in_the_document() {
use graphic_types::EffectOperation;
@@ -4431,6 +4610,7 @@ mod tests {
[DVec2::ZERO, DVec2::splat(10.)],
DAffine2::from_scale(DVec2::splat(2.)),
1.,
&[],
)
.unwrap();
@@ -4449,7 +4629,7 @@ mod tests {
gamma: false,
};
let mut defs = String::new();
write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY, 1.).unwrap();
write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY, 1., &[]).unwrap();
// The fill fades a copy of the content, which is blurred in linear light and passed through as the filter's last result
assert!(defs.contains(r#"<feFuncA type="linear" slope="0.5" />"#), "{defs}");
@@ -4458,13 +4638,13 @@ mod tests {
}
#[test]
fn svg_effects_filters_carry_out_inner_glows_satins_outlines_and_bevels() {
fn svg_effects_filters_carry_out_inner_glows_satins_outlines_bevels_and_paint_overlays() {
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{BevelDirection, EffectOperation, GlowSource};
let filter = |operation| {
let mut defs = String::new();
write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 1.).unwrap();
write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 1., &[]).unwrap();
defs
};
let invert = r#"<feFuncA type="linear" slope="-1" intercept="1" />"#;
@@ -4513,9 +4693,34 @@ mod tests {
shadow_color: Color::BLACK,
};
let mut bevel_defs = String::new();
write_svg_effects_filter(&mut bevel_defs, &Effects::from_operations([bevel]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 2.).unwrap();
write_svg_effects_filter(&mut bevel_defs, &Effects::from_operations([bevel]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 2., &[]).unwrap();
assert!(bevel_defs.contains(r#"operator="erode" radius="2""#) && bevel_defs.contains(r#"stdDeviation="1""#), "{bevel_defs}");
assert_eq!(bevel_defs.matches(r#"surfaceScale="4""#).count(), 2, "{bevel_defs}");
// A paint overlay embeds its paint's markup as an image of the filter region, then blends it over the content within the content's alpha
let overlay = EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::default()),
blend_mode: BlendMode::Multiply,
opacity: 50.,
};
let mut overlay_defs = String::new();
let paints = [r#"<rect width="10" height="10" fill="red" />"#.to_string()];
write_svg_effects_filter(
&mut overlay_defs,
&Effects::from_operations([overlay]),
1.,
[DVec2::ZERO, DVec2::splat(10.)],
DAffine2::IDENTITY,
1.,
&paints,
)
.unwrap();
assert!(
overlay_defs.contains(r#"<feImage href="data:image/svg+xml;base64,"#) && overlay_defs.contains(r#"x="0" y="0" width="10" height="10""#),
"{overlay_defs}"
);
assert!(overlay_defs.contains(r#"<feFuncA type="linear" slope="0.5" />"#), "{overlay_defs}");
assert!(overlay_defs.contains(r#"mode="multiply""#) && overlay_defs.contains(r#"operator="atop""#), "{overlay_defs}");
}
#[test]
@@ -4532,6 +4737,7 @@ mod tests {
[DVec2::ZERO, DVec2::ONE],
DAffine2::IDENTITY,
1.,
&[],
)
.unwrap();
defs
@@ -4589,7 +4795,16 @@ mod tests {
true
}
fn render_effects(&mut self, _: glam::UVec2, _: kurbo::Affine, _: &Effects, _: f32, _: DMat2, _: &mut dyn FnMut(&mut VelloSceneBuilder)) -> graphic_types::raster_types::Texture {
fn render_effects(
&mut self,
_: glam::UVec2,
_: kurbo::Affine,
_: &Effects,
_: f32,
_: DMat2,
_: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
_: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> graphic_types::raster_types::Texture {
panic!("the vector is drawn through an effects group");
}
@@ -4,8 +4,8 @@ use graphic_types::{Adjustment, Effects};
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
use std::borrow::Cow;
use std::collections::HashMap;
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
use vello_gpu::peniko::{self, BlendMode, Brush, Fill};
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1;
@@ -33,15 +33,64 @@ pub trait EffectsRenderer: Send {
/// Whether the GPU can carry out effects, without which effects groups draw their content faded by their fill.
fn renders_effects(&self) -> bool;
/// Renders the content `draw` draws, placed by `view`, into a texture of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
/// Renders the content `draw` draws, and each paint overlay's paint `draw_paint` draws by index, placed by `view` in textures of `size`, returning a straight-alpha texture of the same size with `effects` carried out on it.
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, and `fill` fades the content but not the shadows and glows cast from it.
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture;
#[expect(clippy::too_many_arguments)]
fn render_effects(
&mut self,
size: UVec2,
view: Affine,
effects: &Effects,
fill: f32,
lengths_to_pixels: DMat2,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Texture;
/// A straight-alpha texture of the size of the CPU `raster`, with `adjustments` carried out on its pixels, kept for as long as they're drawn that way.
/// `None` if they can't be carried out.
fn adjust_raster(&mut self, raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Option<Texture>;
}
/// What a fill or stroke paints with.
#[derive(Clone, Debug)]
pub enum SceneBrush {
/// A solid color, gradient, or image.
Peniko(Brush),
/// A gradient whose contours are a pencil of circles, which only Vello GPU's fork can draw.
PencilGradient(PencilGradient),
}
impl From<Brush> for SceneBrush {
fn from(brush: Brush) -> Self {
Self::Peniko(brush)
}
}
impl From<&Brush> for SceneBrush {
fn from(brush: &Brush) -> Self {
Self::Peniko(brush.clone())
}
}
impl From<peniko::Color> for SceneBrush {
fn from(color: peniko::Color) -> Self {
Self::Peniko(Brush::Solid(color))
}
}
impl From<&peniko::Gradient> for SceneBrush {
fn from(gradient: &peniko::Gradient) -> Self {
Self::Peniko(Brush::Gradient(gradient.clone()))
}
}
impl From<PencilGradient> for SceneBrush {
fn from(gradient: PencilGradient) -> Self {
Self::PencilGradient(gradient)
}
}
/// The pixels behind an image the scene draws.
#[derive(Clone, Debug)]
pub enum SceneImage {
@@ -139,35 +188,32 @@ impl<'a> VelloSceneBuilder<'a> {
}
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
pub fn fill(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
}
/// Like [`Self::fill`] for a path, which it draws without copying.
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
pub fn fill_path(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, path: &BezPath) {
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_path(&finite_path(path));
}
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
pub fn stroke(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>, shape: &impl Shape) {
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_stroke(stroke.clone());
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
}
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
pub fn fill_viewport(&mut self, brush: impl Into<SceneBrush>, brush_transform: Option<Affine>) {
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(Affine::IDENTITY);
self.scene.set_paint(paint);
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
}
@@ -241,9 +287,9 @@ impl<'a> VelloSceneBuilder<'a> {
self.effects_renderer.as_deref_mut().filter(|renderer| renderer.renders_effects())?.adjust_raster(raster, adjustments)
}
/// Draws the content `draw` draws with `effects` carried out on it, given the area it covers in the space of the drawn content, or `None` if unbounded.
/// `fill` fades the content but not the shadows and glows cast from it. Rendering a split scene calls `draw` again for each part.
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
/// Draws the content `draw` draws with `effects` carried out on it, within `bounds` in the space of the drawn content (or everywhere for `None`), drawing again for each part of a split render.
/// `draw_paint` draws each paint overlay's paint by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
pub fn draw_effects(&mut self, effects: &Effects, fill: f32, bounds: Option<Rect>, draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder), draw: &mut dyn FnMut(&mut VelloSceneBuilder)) {
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) {
self.push_viewport_layer(peniko::Mix::Normal, fill);
draw(self);
@@ -273,7 +319,7 @@ impl<'a> VelloSceneBuilder<'a> {
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * self.view;
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw);
let result = renderer.render_effects(size, content_view, effects, fill, lengths_to_device * resolution, draw_paint, draw);
// Draw the result where the content was
self.images.push(SceneImage::Texture { texture: result, minified: false });
@@ -294,22 +340,31 @@ impl<'a> VelloSceneBuilder<'a> {
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
}
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
match brush {
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
BrushRef::Image(image) => {
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
Some((
PaintType::Image(Image {
image: source,
sampler: image.sampler,
}),
texture_to_image,
))
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn set_paint(&mut self, brush: SceneBrush) -> Option<Affine> {
let brush = match brush {
SceneBrush::Peniko(brush) => brush,
SceneBrush::PencilGradient(gradient) => {
self.scene.set_pencil_gradient_paint(gradient);
return Some(Affine::IDENTITY);
}
}
};
let (paint, paint_to_brush) = match brush {
Brush::Solid(color) => (PaintType::Solid(color), Affine::IDENTITY),
Brush::Gradient(gradient) => (PaintType::Gradient(gradient), Affine::IDENTITY),
Brush::Image(image) => {
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image))?;
let paint = PaintType::Image(Image {
image: source,
sampler: image.sampler,
});
(paint, texture_to_image)
}
};
self.scene.set_paint(paint);
Some(paint_to_brush)
}
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
@@ -16,6 +16,26 @@ pub enum GradientForm {
Radial,
}
/// The curvature dials of the linear form: both ends are lines.
pub const LINEAR_DIALS: [f64; 2] = [0., 0.];
/// The curvature dials of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
pub const RADIAL_DIALS: [f64; 2] = [1., 0.5];
impl GradientForm {
/// The curvature dials of the start and end contours that make this form.
pub fn dials(self) -> [f64; 2] {
match self {
Self::Linear => LINEAR_DIALS,
Self::Radial => RADIAL_DIALS,
}
}
}
/// A curvature dial wrapped into the range ending at 1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
pub fn wrapped_dial(dial: f64, preset: f64) -> f64 {
if dial.is_finite() { 1. - (1. - dial).rem_euclid(2.) } else { preset }
}
/// A gradient's stops: a list of colors (linear, unassociated alpha) whose optional `position` and `midpoint`
/// attributes place each stop along the 0 to 1 range. Stops lacking the `position` attribute distribute evenly,
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
+10 -2
View File
@@ -152,12 +152,20 @@ impl WgpuExecutor {
);
self.context().queue.lock().submit([encoder.finish()]);
let (sender, mut receiver) = futures::channel::oneshot::channel();
let (sender, receiver) = futures::channel::oneshot::channel();
buffer.slice(..).map_async(wgpu::MapMode::Read, move |result| {
let _ = sender.send(result);
});
let _ = device.poll(wgpu::wgt::PollType::wait_indefinitely());
let Ok(Some(mapping)) = receiver.try_recv() else {
// A poll on another thread can be the one running the callback, which may not have finished by the time this poll returns
#[cfg(not(target_family = "wasm"))]
let mapping = futures::executor::block_on(receiver).ok();
#[cfg(target_family = "wasm")]
let mapping = {
let mut receiver = receiver;
receiver.try_recv().ok().flatten()
};
let Some(mapping) = mapping else {
anyhow::bail!("The GPU didn't map the texture's pixels for reading");
};
mapping?;
@@ -48,12 +48,6 @@ impl PipelineCache {
pub fn executor(&self) -> Option<&WgpuExecutor> {
self.executor.get()
}
/// Runs the pipeline, or returns `None` when it was never initialized because no GPU is available.
pub fn try_run<P: Pipeline>(&self, args: &P::Args<'_>) -> Option<P::Out> {
self.executor.get()?;
self.run::<P>(args).ok()
}
}
impl std::fmt::Debug for PipelineCache {
@@ -5,15 +5,20 @@ use crate::WgpuPipelineCache;
use crate::raster_kernel::{MAX_FRAME_SIDE, adjust_raster, blur_raster, run_raster_kernel};
use crate::shader_runtime::raster_kernel_runtime::RasterKernelInput;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::math::quad::Quad;
use core_types::ops::Convert;
use core_types::transform::Footprint;
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, NodeError};
use glam::{DAffine2, DMat2, DVec2, UVec2};
use graphic_types::effects::{bevel_light, bevel_smoothing, outline_extents};
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource};
use graphic_types::effects::{bevel_light, bevel_smoothing, fitted_paint, outline_extents};
use graphic_types::{Adjustment, BevelDirection, EffectOperation, Effects, GlowSource, Graphic};
use raster_kernels::RasterKernel;
use raster_kernels::adjustments::{leading_adjustments, preserves_alpha};
use raster_kernels::blur::BlurSpace;
use raster_kernels::effects::*;
use raster_types::{GPU, Raster, Storage};
use raster_types::{CPU, GPU, Raster, Storage};
use rendering::vello_scene_builder::VelloSceneBuilder;
use rendering::{Render, RenderParams};
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
@@ -41,6 +46,16 @@ pub fn evaluate_raster_effects(item: Item<Raster<GPU>>, pipeline: &WgpuPipelineC
Ok(item)
}
/// The CPU raster uploaded with its effects carried out into its pixels, for the Eager node and the input adapter that feeds a CPU raster to a node taking only GPU rasters.
pub fn upload_raster(image: Item<Raster<CPU>>, pipeline: &WgpuPipelineCache) -> Result<Item<Raster<GPU>>, NodeError> {
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to upload a raster"))?;
let (image, attributes) = image.into_parts();
let uploaded: Raster<GPU> = image.convert(Footprint::DEFAULT, executor);
evaluate_raster_effects(Item::from_parts(uploaded, attributes), pipeline)
}
/// The larger raster of the effects carried out on `raster`, an item's whose `transform` is kept, with the coverage placing that larger raster where the original's pixels were.
/// `None` when there's nothing to carry out, or the raster is empty or its placement can't be inverted.
fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOperation], fill: f32, pipeline: &WgpuPipelineCache) -> Result<Option<Raster<GPU>>, NodeError> {
@@ -78,9 +93,24 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
margin = margin.min(((DVec2::splat(MAX_FRAME_SIDE as f64) - size.as_dvec2()) / 2.).max(DVec2::ZERO).floor());
let grown_size = grown(margin).as_uvec2();
// A paint is placed in the space the raster's item is placed in, or fitted to the raster's extent there, and rendered over the grown raster's pixels
let parent_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * placement.inverse();
let bounds = (placement * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box();
let mut render_paint = |_: usize, paint: &Graphic| {
let executor = pipeline.executor().ok_or_else(|| NodeError::new("A GPU is required to render a paint"))?;
let fitted = fitted_paint(paint, bounds);
let paint = fitted.as_ref().unwrap_or(paint);
let render_params = RenderParams::default().for_pattern();
let mut draw = |scene: &mut VelloSceneBuilder| paint.render_to_vello(scene, DAffine2::IDENTITY, &render_params);
let texture = executor
.render_vello_raster(grown_size, parent_to_pixels, &mut draw)
.map_err(|error| NodeError::new(error.to_string()))?;
Ok(Raster::<GPU>::new_gpu(texture))
};
let mut pass = EffectsPass::new(raster, grown_size, DAffine2::from_translation(-margin), fill, lengths_to_pixels, pipeline)?;
for operation in operations {
pass.apply(operation)?;
pass.apply(operation, &mut render_paint)?;
}
let result = pass.finish()?;
@@ -89,17 +119,18 @@ fn evaluate(raster: &Raster<GPU>, transform: DAffine2, operations: &[EffectOpera
}
/// Carries out `operations` in order on `content`, a straight-alpha raster in the pixels `lengths_to_pixels` maps the effects' lengths onto, into a raster of its size.
/// `fill` fades the content but not the shadows and glows cast from it.
/// `fill` fades the content but not the shadows and glows cast from it, and `render_paint` renders each paint overlay's paint, by its index among them, over the same pixels.
pub fn apply_effects(
content: &Raster<GPU>,
operations: impl IntoIterator<Item = EffectOperation>,
fill: f32,
lengths_to_pixels: DMat2,
render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>,
pipeline: &WgpuPipelineCache,
) -> Result<Raster<GPU>, NodeError> {
let mut pass = EffectsPass::new(content, content.size(), DAffine2::IDENTITY, fill, lengths_to_pixels, pipeline)?;
for operation in operations {
pass.apply(&operation)?;
pass.apply(&operation, render_paint)?;
}
Ok(pass.finish()?.with_coverage(content.coverage()))
}
@@ -115,6 +146,8 @@ pub struct EffectsPass<'a> {
filled: Option<Raster<GPU>>,
/// The shadows and glows stacked beneath the content.
beneath: Option<Raster<GPU>>,
/// How many paint overlays have been carried out.
paint_overlays: usize,
}
impl<'a> EffectsPass<'a> {
@@ -131,11 +164,12 @@ impl<'a> EffectsPass<'a> {
full,
filled,
beneath: None,
paint_overlays: 0,
})
}
/// Carries out the next effect.
pub fn apply(&mut self, operation: &EffectOperation) -> Result<(), NodeError> {
/// Carries out the next effect, with `render_paint` rendering a paint overlay's paint, by its index among them, into a straight-alpha raster over the images' pixels.
pub fn apply(&mut self, operation: &EffectOperation, render_paint: &mut dyn FnMut(usize, &Graphic) -> Result<Raster<GPU>, NodeError>) -> Result<(), NodeError> {
let lengths_to_pixels = self.lengths_to_pixels;
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
@@ -244,6 +278,19 @@ impl<'a> EffectsPass<'a> {
self.shade_within(&coverage, color)?;
}
}
EffectOperation::PaintOverlay { ref paint, blend_mode, opacity } => {
let paint = render_paint(self.paint_overlays, paint)?;
self.paint_overlays += 1;
let overlay = PaintOverlay {
blend_mode,
opacity: (opacity / 100.) as f32,
};
self.full = self.run(&overlay, &[&self.full, &paint])?;
if let Some(filled) = &self.filled {
self.filled = Some(self.run(&overlay, &[filled, &paint])?);
}
}
EffectOperation::Adjustment(ref adjustment) => {
self.full = self.adjust_image(&self.full, adjustment)?;
if let Some(filled) = &self.filled {
@@ -12,7 +12,7 @@ use raster_kernels::adjustments::{AdjustmentVisitor, visit_kernel};
use raster_kernels::blur::{BlurHalve, BlurHorizontal, BlurPass, BlurSpace, BlurUpsample, BlurVertical, MAX_BLUR_REACH, blur_extent};
use raster_kernels::generators::visit_generator_kernel;
use raster_kernels::{GpuParams, MapColor, RasterKernel, RasterKernelVisitor, ToGpuParams, map_color_module, raster_kernel_module};
use raster_types::{GPU, Raster, Storage};
use raster_types::{GPU, ImageError, Raster, Storage};
use std::any::{TypeId, type_name};
/// The format of intermediate rasters a [`RasterKernel::FILTERED`] kernel reads, half-float precision but filterable on WebGL2 unlike [`RASTER_FORMAT`].
@@ -41,9 +41,17 @@ fn run<K: ToGpuParams + 'static>(
output_size,
output_format,
};
pipeline
.try_run::<RasterKernelRuntime>(&args)
.ok_or_else(|| NodeError::new("A GPU is required to process a GPU raster"))
if let Some(executor) = pipeline.executor() {
let limit = executor.context().device.limits().max_texture_dimension_2d;
if output_size.max_element() > limit {
return Err(ImageError::TooLarge {
width: output_size.x,
height: output_size.y,
}
.into());
}
}
Ok(pipeline.run::<RasterKernelRuntime>(&args)?)
}
fn raster_format(pipeline: &WgpuPipelineCache) -> WgpuTextureFormat {
@@ -6,7 +6,7 @@ use core_types::graphene_hash::CacheHash;
use core_types::ops::Convert;
use core_types::transform::Footprint;
use glam::{DMat2, UVec2};
use graphic_types::{Adjustment, Effects};
use graphic_types::{Adjustment, Effects, Graphic};
use raster_types::{CPU, GPU, Raster, Texture, WeakCPU};
use rendering::vello_scene_builder::{EffectsRenderer, SceneImage, VelloSceneBuilder, image_downscale_factor, image_texture_size};
use std::collections::HashMap;
@@ -305,14 +305,31 @@ impl EffectsRenderer for RenderContext<'_> {
self.kernels.executor().is_some()
}
fn render_effects(&mut self, size: UVec2, view: Affine, effects: &Effects, fill: f32, lengths_to_pixels: DMat2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Texture {
fn render_effects(
&mut self,
size: UVec2,
view: Affine,
effects: &Effects,
fill: f32,
lengths_to_pixels: DMat2,
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
) -> Texture {
// Rendered into a raster of the content, which the effects are carried out on with the same kernels as a raster's own effects
let executor = self.kernels.executor().expect("effects are only rendered with a GPU");
let kernels = self.kernels;
let executor = kernels.executor().expect("effects are only rendered with a GPU");
let content = executor.request_texture_with_format(size, executor.raster_format());
self.render_area(draw, view, size, &content);
let content = Raster::<GPU>::new_gpu(content);
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, self.kernels) {
// The paint overlays' paints, each rendered over the same pixels as the content
let mut render_paint = |index: usize, _: &Graphic| {
let paint = executor.request_texture_with_format(size, executor.raster_format());
self.render_area(&mut |scene| draw_paint(index, scene), view, size, &paint);
Ok(Raster::<GPU>::new_gpu(paint))
};
match apply_effects(&content, effects.operations(), fill, lengths_to_pixels, &mut render_paint, kernels) {
Ok(result) => result
.texture()
.cloned()
@@ -12,7 +12,7 @@ fn executor() -> Option<&'static WgpuExecutor> {
EXECUTOR.get_or_init(|| futures::executor::block_on(WgpuExecutor::new())).as_ref()
}
/// Held while a test uses the shared GPU, since another test's work can delay or intercept a render's readback.
/// Held while a test uses the shared GPU, since another test's work can delay a render's readback.
fn take_turn() -> std::sync::MutexGuard<'static, ()> {
static TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
TURN.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
@@ -274,13 +274,65 @@ fn degenerate_strokes_render() {
let Some(_) = render(size, draw) else { return };
}
#[test]
fn dial_gradients_match_their_cpu_evaluation() {
use rendering::dial_gradient::PencilParameters;
let size = UVec2::new(200, 200);
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
let gradient_to_pixels = Affine::new([50., 0., 0., 50., 60., 100.]);
for dials in [(1., 0.6), (0.6, 0.6), (-0.5, 0.2952), (1., 1.), (0.5, 0.25), (0.3, -0.3)] {
let parameters = PencilParameters::new(dials.0, dials.1);
let ramp = peniko::Gradient::new_linear((0., 0.), (1., 0.)).with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]);
let gradient = vello_gpu::PencilGradient {
ramp,
geometry: parameters.to_vello(),
};
let draw = |scene: &mut VelloSceneBuilder| scene.fill_viewport(gradient.clone(), Some(gradient_to_pixels));
let Some(pixels) = render(size, draw) else { return };
let mut worst = 0_i32;
for y in (5..195).step_by(10) {
for x in (5..195).step_by(10) {
let point = gradient_to_pixels.inverse() * vello_gpu::kurbo::Point::new(x as f64 + 0.5, y as f64 + 0.5);
let t = parameters.t(glam::DVec2::new(point.x, point.y)).clamp(0., 1.);
let expected = (t * 255.).round() as i32;
let actual = pixel(&pixels, size, x, y)[0] as i32;
worst = worst.max((expected - actual).abs());
}
}
assert!(worst <= 3, "dials {dials:?} differ from the CPU evaluation by up to {worst} levels");
}
}
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
let square = Rect::new(min, min, max, max);
let effects = graphic_types::Effects::from_operations(effects);
use rendering::{Render, RenderParams};
let square = Rect::new(min, min, max, max);
// The paint overlays' paints, drawn as the renderer does for content placed in the scene's space
let paints: Vec<graphic_types::Graphic> = (effects.iter())
.filter_map(|operation| match operation {
graphic_types::EffectOperation::PaintOverlay { paint, .. } => Some(paint),
_ => None,
})
.map(|paint| graphic_types::fitted_paint(paint, [glam::DVec2::splat(min), glam::DVec2::splat(max)]).unwrap_or_else(|| paint.clone()))
.collect();
let mut draw_paint = |index: usize, scene: &mut VelloSceneBuilder| {
if let Some(paint) = paints.get(index) {
paint.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default().for_pattern());
}
};
let effects = graphic_types::Effects::from_operations(effects);
render(size, |scene| {
scene.draw_effects(&effects, fill, Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
scene.draw_effects(&effects, fill, Some(square), &mut draw_paint, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
});
})
}
@@ -461,6 +513,46 @@ fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit");
}
#[test]
fn paint_overlays_stretch_unplaced_paints_across_the_content() {
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::Item;
use graphic_types::raster_types::{Image, Raster};
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
use graphic_types::{EffectOperation, Graphic};
let size = UVec2::new(128, 128);
let overlay = |paint: Graphic| EffectOperation::PaintOverlay {
paint,
blend_mode: BlendMode::Normal,
opacity: 100.,
};
let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 64 && blue < 64 && alpha == 255;
let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 64 && green < 64 && alpha == 255;
// A gradient from red to blue runs from the square's left edge to its right edge
let stops = [(0., GraphicColor::RED), (1., GraphicColor::BLUE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Gradient::new(stops)))], 1., 30., 80., size) else {
return;
};
assert!(reddish(pixel(&pixels, size, 31, 55)), "the start at the left edge: {:?}", pixel(&pixels, size, 31, 55));
assert!(bluish(pixel(&pixels, size, 78, 55)), "the end at the right edge: {:?}", pixel(&pixels, size, 78, 55));
assert_eq!(pixel(&pixels, size, 25, 55)[3], 0, "nothing outside the content");
// An image of a red pixel beside a blue one covers the square, each pixel half of it
let image = Image {
width: 2,
height: 1,
data: vec![GraphicColor::RED, GraphicColor::BLUE],
};
let Some(pixels) = render_square_with_effects(vec![overlay(Graphic::from(Item::new_from_element(Raster::new_cpu(image))))], 1., 30., 80., size) else {
return;
};
assert!(reddish(pixel(&pixels, size, 35, 40)), "the left half: {:?}", pixel(&pixels, size, 35, 40));
assert!(bluish(pixel(&pixels, size, 75, 70)), "the right half: {:?}", pixel(&pixels, size, 75, 70));
}
#[test]
fn later_shadows_stack_over_earlier_ones_beneath_the_content() {
use core_types::Color as GraphicColor;
@@ -505,8 +597,10 @@ fn nested_effects_groups_render_inside_out() {
gamma: false,
}]);
let draw = |scene: &mut VelloSceneBuilder| {
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |scene| {
scene.draw_effects(&blur, 1., Some(square), &mut |scene| scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square));
scene.draw_effects(&shadow, 1., Some(square.inflate(12., 12.)), &mut |_, _| {}, &mut |scene| {
scene.draw_effects(&blur, 1., Some(square), &mut |_, _| {}, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
});
});
};
@@ -617,6 +711,8 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
use crate::raster_effects::evaluate_raster_effects;
use crate::shader_runtime::raster_kernel_runtime::RasterKernelRuntime;
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::ATTR_GRADIENT_FORM;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::ops::{Convert, ConvertAsync};
use core_types::transform::Footprint;
@@ -624,8 +720,9 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
use glam::DVec2;
use graphic_types::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
use graphic_types::raster_types::{CPU, GPU, Image, Raster, Storage};
use graphic_types::vector_types::gradient::{Gradient, GradientForm, GradientStop};
use graphic_types::vector_types::vector::style::StrokeAlign;
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource};
use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource, Graphic};
let size = UVec2::new(160, 160);
let (min, max) = (50, 100);
@@ -747,7 +844,62 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
let pipeline = WgpuPipelineCache::default();
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
for effects in cases {
// Paint overlays over a colored backdrop, their paints placed on their own since the raster and the square fit unplaced paints to different bounds
let backdrop = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: GraphicColor::from_rgbaf32_unchecked(0.3, 0.6, 0.2, 1.),
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let gradient = |form: GradientForm, transform: DAffine2| {
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
position,
midpoint: 0.5,
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
});
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
};
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
// A checkerboard with a pixel for each of the square's, so sampling it needs no interpolation
let checker = Image {
width: 50,
height: 50,
data: (0..2500)
.map(|index| match (index % 50 / 5 + index / 50 / 5) % 2 {
0 => GraphicColor::RED,
_ => GraphicColor::from_rgbaf32_unchecked(0., 0., 1., 0.5),
})
.collect(),
};
let checker_placement = DAffine2::from_translation(DVec2::splat(50.)) * DAffine2::from_scale(DVec2::splat(50.));
let checker = Graphic::from(Item::new_from_element(Raster::new_cpu(checker)).with_attribute(ATTR_TRANSFORM, checker_placement));
let overlay = |paint: &Graphic, blend_mode, opacity| {
vec![
backdrop.clone(),
EffectOperation::PaintOverlay {
paint: paint.clone(),
blend_mode,
opacity,
},
]
};
// Hard Mix's threshold and the hue of the gradient's grays turn the slightest rounding into large differences, so they take the checkerboard's exact colors instead
let ill_conditioned = [BlendMode::HardMix, BlendMode::Hue];
let mut paint_cases: Vec<_> = (BlendMode::list().into_iter().flatten())
.filter(|blend_mode| !ill_conditioned.contains(blend_mode))
.map(|&blend_mode| overlay(&linear, blend_mode, 100.))
.collect();
paint_cases.extend(ill_conditioned.map(|blend_mode| overlay(&checker, blend_mode, 100.)));
paint_cases.extend([
overlay(&linear, BlendMode::Normal, 40.),
overlay(&radial, BlendMode::Multiply, 100.),
overlay(&checker, BlendMode::Screen, 100.),
]);
for effects in cases.into_iter().chain(paint_cases) {
for fill in [1., 0.5] {
let Some(rendered) = render_square_with_effects(effects.clone(), fill, min as f64, max as f64, size) else {
return;
@@ -792,7 +944,16 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() {
}
}
}
assert!(worst <= 2, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
// Modes that divide, or land near black where the gamma encoding is steepest, amplify the rounding of the rendered paint's eight bits
use BlendMode::*;
let tolerance = match effects.last() {
Some(EffectOperation::PaintOverlay {
blend_mode: ColorBurn | LinearBurn | ColorDodge | HardLight | VividLight | LinearLight | PinLight,
..
}) => 8,
_ => 2,
};
assert!(worst <= tolerance, "{effects:?} at fill {fill} differs from the render by up to {worst} levels");
}
}
}
@@ -885,7 +1046,7 @@ fn effects_groups_carry_out_adjustments_like_their_kernels_map_colors() {
let effects = Effects::from_operations(run.iter().cloned().map(EffectOperation::Adjustment));
let draw = |scene: &mut VelloSceneBuilder| {
let bounds = Rect::new(0., 0., size.x as f64, size.y as f64);
scene.draw_effects(&effects, 1., Some(bounds), &mut |scene| {
scene.draw_effects(&effects, 1., Some(bounds), &mut |_, _| {}, &mut |scene| {
scene.draw_raster(raster.clone(), peniko::ImageSampler::new(), Affine::IDENTITY)
});
};
@@ -914,7 +1075,7 @@ fn effects_groups_keep_the_empty_space_empty_when_an_adjustment_changes_alpha()
let square = Rect::new(4., 4., 12., 12.);
let effects = Effects::from_operations([EffectOperation::Adjustment(Adjustment::MakeOpaque)]);
let draw = |scene: &mut VelloSceneBuilder| {
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |scene| {
scene.draw_effects(&effects, 1., Some(Rect::new(0., 0., 16., 16.)), &mut |_, _| {}, &mut |scene| {
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::new([1., 1., 1., 0.5]), None, &square)
});
};
+3 -3
View File
@@ -10,7 +10,7 @@ use vector_types::Gradient;
fn blend_mode<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// The choice of equation that controls how brightness and color blends between overlapping pixels.
blend_mode: Item<BlendMode>,
@@ -29,7 +29,7 @@ fn blend_mode<T>(
fn opacity<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// Whether the *Opacity* property is enabled, multiplying the existing opacity by the chosen percentage.
#[widget(ParsedWidgetOverride::Hidden)]
@@ -76,7 +76,7 @@ fn opacity<T>(
fn clipping_mask<T>(
_: impl Ctx,
/// The content that will be composited when rendering.
#[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String)]
#[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// Whether the content inherits the alpha of the content beneath it.
clip: Item<bool>,
+4 -4
View File
@@ -85,8 +85,8 @@ fn step_real_time<T>(
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
@@ -95,8 +95,8 @@ fn step_real_time<T>(
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -131,8 +131,8 @@ fn step_animation_time<T>(
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
@@ -141,8 +141,8 @@ fn step_animation_time<T>(
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -25,8 +25,8 @@ fn context_modification<T>(
Context -> Item<DVec2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Artboard>,
Context -> Item<Gradient>,
@@ -38,8 +38,8 @@ fn context_modification<T>(
Context -> List<DVec2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Artboard>,
Context -> List<Gradient>,
+1 -1
View File
@@ -16,8 +16,8 @@ fn create_artboard<T: IntoGraphicList>(
Context -> List<Graphic>,
Context -> List<Vector>,
Context -> List<String>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> Item<DAffine2>, // TODO: Remove this
+19 -19
View File
@@ -30,8 +30,8 @@ fn remove_at_index<T: graphic_types::graphic::OmitIndex + Clone + Default>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -64,8 +64,8 @@ fn item_at_index<T: Clone + Default + Send + Sync + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -102,8 +102,8 @@ fn filter<T: Send + Sync + Clone + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -135,8 +135,8 @@ fn reverse<T: Send + Sync + Clone + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -160,8 +160,8 @@ fn shift<T: Send + Sync + Clone + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -205,8 +205,8 @@ fn shuffle<T: Send + Sync + Clone + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -277,8 +277,8 @@ fn slice<T: Send + Sync + Clone + 'static>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -351,9 +351,9 @@ fn sort<T: ElementOrder + Clone + Send + Sync + 'static, U: ElementOrder + Send
_: impl Ctx,
/// The list of data to reorder.
#[implementations(
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>, List<Artboard>,
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
List<String>, List<bool>, List<f64>, List<i64>, List<DVec2>, List<DAffine2>, List<Vector>, List<Graphic>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>, List<Artboard>,
)]
list: List<T>,
/// The optional list of orderable values, corresponding item-to-item with the input list, to sort by instead of the items' own values.
@@ -412,8 +412,8 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -428,8 +428,8 @@ fn map<Item: AnyHash + Send + Sync + CacheHash + Clone>(
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -489,8 +489,8 @@ fn mirror<T: BoundingBox + HasText + Send + Clone + 'static>(
#[implementations(
Context -> Item<Graphic>,
Context -> Item<Vector>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<String>,
@@ -598,8 +598,8 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -911,8 +911,8 @@ fn extend<T: Send + Clone>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -930,8 +930,8 @@ fn extend<T: Send + Clone>(
List<DAffine2>,
List<Vector>,
List<Graphic>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Artboard>,
@@ -951,9 +951,9 @@ fn extend<T: Send + Clone>(
#[node_macro::node(category(""))]
fn legacy_layer_extend<T: Send + Clone>(
_: impl Ctx,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>)] base: List<T>,
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)] base: List<T>,
#[expose]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<GPU>>, List<Raster<CPU>>, List<Color>, List<Gradient>)]
#[implementations(List<Artboard>, List<Graphic>, List<Vector>, List<String>, List<Raster<CPU>>, List<Raster<GPU>>, List<Color>, List<Gradient>)]
new: List<T>,
nested_node_path: Item<NodeIdPath>,
) -> List<T> {
@@ -981,8 +981,8 @@ fn into_group<T: Into<Graphic>>(
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<String>,
@@ -1,10 +1,11 @@
use core_types::Ctx;
use core_types::NodeError;
use core_types::color::SRGBA8;
use core_types::list::{Item, List};
use core_types::math::bbox::Bbox;
use core_types::ops::{Convert, ConvertAsync};
use core_types::ops::ConvertAsync;
use core_types::transform::Footprint;
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM, Interrupt, NodeError};
use core_types::{ATTR_EDITOR_MERGED_LAYERS, ATTR_TRANSFORM};
use glam::{DAffine2, UVec2};
pub use graph_craft::application_io::resource::{Resource, ResourceHash};
pub use graph_craft::application_io::*;
@@ -12,8 +13,8 @@ pub use graph_craft::document::value::RenderOutputType;
#[cfg(target_family = "wasm")]
pub use graphene_canvas_utils as canvas_utils;
use graphic_types::Graphic;
use graphic_types::raster_types::Image;
use graphic_types::raster_types::{GPU, Raster, Storage};
use graphic_types::raster_types::{CPU, GPU, Raster, Storage};
use graphic_types::raster_types::{Image, ImageError};
use raster_nodes::raster_kernel::raster_kernel_pipeline;
use rendering::{Render, RenderParams};
use std::sync::Arc;
@@ -219,15 +220,14 @@ fn pending_resource(_primary: &(), _url: &Item<String>) -> Item<Resource> {
///
/// Supports the formats: PNG, JPG, GIF, WEBP, TIFF, BMP, TGA, ICO, HDR, EXR.
#[node_macro::node(category("Data: I/O"), icon("NodeBytesToImage"), name("Bytes to Image"), memoize)]
fn bytes_to_image(_: impl Ctx, data: Item<Resource>, #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<::wgpu_executor::WgpuPipelineCache>) -> Result<Item<Raster<GPU>>, Interrupt> {
fn bytes_to_image(_: impl Ctx, data: Item<Resource>) -> Result<Item<Raster<CPU>>, ImageError> {
let data = data.into_element();
if data.is_empty() {
return Ok(Item::default());
}
let image = Image::from_encoded(data.as_ref()).map_err(NodeError::new)?;
let image = Image::from_encoded(data.as_ref())?;
let executor = pipeline.element().executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to load an image"))?;
Ok(Item::new_from_element(Raster::new_cpu(image).convert(Footprint::DEFAULT, executor)))
Ok(Item::new_from_element(Raster::new_cpu(image)))
}
/// Renders a view of the input graphic within an area defined by the *Footprint*.
@@ -325,7 +325,6 @@ mod tests {
use super::*;
use core_types::Color;
use glam::DVec2;
use graphic_types::raster_types::CPU;
#[tokio::test]
async fn rasterize_renders_the_footprint_area_at_its_resolution() {
+1 -1
View File
@@ -30,8 +30,8 @@ fn render_intermediate<T: 'static + Render + WasmNotSend + Send + Sync>(
Context -> List<Artboard>,
Context -> List<Graphic>,
Context -> List<Vector>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<String>,
+20 -6
View File
@@ -1609,8 +1609,8 @@ fn switch<T: Send>(
Context -> Item<DAffine2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
@@ -1639,8 +1639,8 @@ fn switch<T: Send>(
Context -> Item<DAffine2>,
Context -> Item<Vector>,
Context -> Item<Graphic>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<Artboard>,
@@ -1814,11 +1814,25 @@ fn gradient_value(_: impl Ctx, _primary: (), #[default(Color::BLACK, Color::WHIT
gradient
}
/// Sets the form (linear or radial) of each gradient in the input list.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_form(_: impl Ctx, gradient: Item<Gradient>, gradient_form: Item<vector_types::GradientForm>) -> Item<Gradient> {
/// Curves the contours at the start and end of each gradient in the input list between straight lines, circles, and points, with the contours between following along.
///
/// Each end runs from -1 to 1. At 0 its contour is a straight line, at 1 or -1 it shrinks to the end's own point, and between it is a circle through the end that bows toward the other end when positive or away from it when negative. A linear gradient is 0 at both ends, and a radial gradient is 1 at its start and 0.5 at its end.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"), inspector("gradient_curvature_inspector"))]
fn gradient_curvature(
_: impl Ctx,
gradient: Item<Gradient>,
/// The curve of the contour through the start.
#[range]
#[soft(-1..1)]
start_curvature: Item<f64>,
/// The curve of the contour through the end.
#[range]
#[soft(-1..1)]
end_curvature: Item<f64>,
) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_FORM, *gradient_form.element());
gradient.set_attribute(core_types::ATTR_GRADIENT_START_CURVATURE, *start_curvature.element());
gradient.set_attribute(core_types::ATTR_GRADIENT_END_CURVATURE, *end_curvature.element());
gradient
}
@@ -1,14 +1,7 @@
use crate::effects::ApplyEffect;
use crate::raster_kernel::raster_kernel_pipeline;
use core_types::Ctx;
use core_types::Interrupt;
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
use graphic_types::{Adjustment, Graphic, Vector};
use raster_types::{CPU, GPU, Raster};
use vector_types::Gradient;
use wgpu_executor::WgpuPipelineCache;
pub use core_types::blending::{apply_blend_mode, blend_colors};
@@ -33,66 +26,10 @@ fn mix_colors(
under
}
// TODO: Rename to "Paint Overlay" and take a `Graphic` paint like the `Fill` node, enabling this to serve the cases of Color Overlay, Gradient Overlay, and Pattern Overlay.
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
fn color_overlay<T: ApplyEffect>(
_: impl Ctx,
#[implementations(
Raster<CPU>,
Color,
Gradient,
Graphic,
Vector,
Raster<GPU>,
String,
)]
image: Item<T>,
#[default(Color::BLACK)] color: Item<Color>,
blend_mode: Item<BlendMode>,
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
opacity: Item<f64>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let adjustment = Adjustment::ColorOverlay {
color: color.into_element(),
blend_mode: blend_mode.into_element(),
opacity: opacity.into_element(),
};
Ok(T::apply_adjustment(image, adjustment, pipeline.element())?)
}
#[cfg(test)]
mod test {
use core_types::blending::BlendMode;
use core_types::color::Color;
use core_types::list::Item;
#[test]
fn color_overlay_multiply() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
// Color { red: 0., green: 1., blue: 0., alpha: 1. }
let overlay_color = Color::GREEN;
// 100% of the output should come from the multiplied value
let opacity = 100.;
let result = super::color_overlay(
(),
Item::new_from_element(image_color),
overlay_color.into(),
BlendMode::Multiply.into(),
opacity.into(),
Item::default(),
);
let result = result.unwrap().into_element();
// The output should just be the original green and alpha channels (as we multiply them by 1 and other channels by 0)
assert_eq!(result, Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
#[test]
fn mix_colors_paints_over_at_its_opacity() {
+151 -11
View File
@@ -1,16 +1,17 @@
use crate::raster_kernel::raster_kernel_pipeline;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
use core_types::ops::Convert;
use core_types::transform::Footprint;
use core_types::{ATTR_OPACITY_FILL, Color, Ctx, Interrupt, NodeError};
use core_types::blending::BlendMode;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item, List};
use core_types::{ATTR_OPACITY_FILL, CacheHash, Color, Ctx, Interrupt, NodeError};
use glam::DVec2;
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{Adjustment, BevelDirection, BevelStyle, Effect, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_effect};
use raster_kernels::adjustments::{adjust_color, adjust_gradient, preserves_alpha};
use std::hash::{DefaultHasher, Hasher};
use std::sync::{Arc, Mutex, PoisonError};
use vector_types::vector::style::StrokeAlign;
use vector_types::{Gradient, GradientSettings};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::raster_effects::evaluate_raster_effects;
use wgpu_executor::raster_effects::{evaluate_raster_effects, upload_raster};
use wgpu_executor::raster_kernel::adjust_raster;
/// Content an effect can be carried out on. A GPU raster has the effect carried out into its pixels at once, with the same kernels the renderer uses,
@@ -397,6 +398,40 @@ fn bevel_and_emboss<T: ApplyEffect>(
)
}
/// Paints over the input graphics within their shape, mixing the paint with their colors by a blend mode.
#[node_macro::node(category("Raster: Effect"), icon("NodeColorOverlay"))]
fn paint_overlay<T: ApplyEffect>(
_: impl Ctx,
/// The content to paint over.
#[implementations(Raster<CPU>, Graphic, Vector, Raster<GPU>, Color, Gradient, String)]
content: Item<T>,
/// The color, gradient, image, or other graphic to paint with. A gradient or image without its own placement stretches across the content.
#[default(Color::BLACK)]
paint: Item<Graphic>,
/// How the paint mixes with the content's colors.
blend_mode: Item<BlendMode>,
/// How strongly the paint shows.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
opacity: Item<f64>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<T>, Interrupt> {
let (blend_mode, opacity) = (blend_mode.into_element(), opacity.into_element());
// The paint is the element alone, since the wire envelope's attributes would nest it as a group
Ok(match paint.into_element() {
Graphic::None(_) | Graphic::NoneList(_) => content,
// A solid paint mixes the same into every pixel, as an adjustment
Graphic::Color(color) => {
let color = *color.element();
T::apply_adjustment(content, Adjustment::ColorOverlay { color, blend_mode, opacity }, pipeline.element())?
}
paint => T::apply_effect(content, EffectOperation::PaintOverlay { paint, blend_mode, opacity }, pipeline.element())?,
})
}
/// Uploads an image to the GPU and carries out its effects into the pixels, at the image's own resolution, for what comes next to run on the GPU right away.
#[node_macro::node(category("Raster"), icon("NodeUploadTexture"))]
fn eager(
@@ -405,21 +440,56 @@ fn eager(
image: Item<Raster<CPU>>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<Raster<GPU>>, Interrupt> {
let pipeline = pipeline.element();
let executor = pipeline.executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to upload a raster"))?;
Ok(upload_raster(image, pipeline.element())?)
}
let (image, attributes) = image.into_parts();
let uploaded: Raster<GPU> = image.convert(Footprint::DEFAULT, executor);
/// The `input_adapter` row uploading a CPU raster wire for an input that only takes GPU rasters, by the same steps as the Eager node.
/// The upload is kept until the wire carries other pixels or effects, so it's made once however often the consuming node runs.
#[node_macro::node(category("_Adapters"), skip_impl)]
fn upload_item(_: impl Ctx, value: Item<Raster<CPU>>, pipeline: Item<WgpuPipelineCache>, #[data] cache: Arc<Mutex<Option<(u64, Item<Raster<GPU>>)>>>) -> Result<Item<Raster<GPU>>, Interrupt> {
Ok(uploaded(cache, &value, || upload_raster(value.clone(), pipeline.element()))?)
}
Ok(evaluate_raster_effects(Item::from_parts(uploaded, attributes), pipeline)?)
/// The `List` counterpart of `upload_item`.
#[node_macro::node(category("_Adapters"), skip_impl)]
fn upload_list(_: impl Ctx, value: List<Raster<CPU>>, pipeline: Item<WgpuPipelineCache>, #[data] cache: Arc<Mutex<Option<(u64, List<Raster<GPU>>)>>>) -> Result<List<Raster<GPU>>, Interrupt> {
let upload = || value.clone().into_iter().map(|item| upload_raster(item, pipeline.element())).collect::<Result<List<_>, _>>();
Ok(uploaded(cache, &value, upload)?)
}
/// The `input_adapter` row passing a GPU raster wire through, taking the pipeline only since every row under one identifier takes the same inputs.
#[node_macro::node(category("_Adapters"), skip_impl)]
fn pass_raster<'i, T: 'i + Send>(_: impl Ctx, value: T, _pipeline: Item<WgpuPipelineCache>) -> T {
value
}
/// The result of `upload` for `source`, reusing the last one if it was for the same pixels and effects.
fn uploaded<S: CacheHash, T: Clone>(cache: &Mutex<Option<(u64, T)>>, source: &S, upload: impl FnOnce() -> Result<T, NodeError>) -> Result<T, NodeError> {
let mut hasher = DefaultHasher::new();
source.cache_hash(&mut hasher);
let hash = hasher.finish();
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
if let Some((_, result)) = cache.as_ref().filter(|(cached_hash, _)| *cached_hash == hash) {
return Ok(result.clone());
}
let result = upload()?;
*cache = Some((hash, result.clone()));
Ok(result)
}
#[cfg(test)]
mod tests {
use super::*;
use core_types::ATTR_TRANSFORM;
use core_types::Node;
use core_types::context::OwnedContextImpl;
use core_types::list::ATTR_EFFECTS;
use core_types::ops::ConvertAsync;
use core_types::ops::{Convert, ConvertAsync};
use core_types::poll::Poll;
use core_types::transform::Footprint;
use core_types::value::PrecomputedItemNode;
use glam::{DAffine2, UVec2};
use graphic_types::Effects;
use graphic_types::raster_types::{Image, Storage};
@@ -584,4 +654,74 @@ mod tests {
assert_color(raster.data[0], Color::BLACK);
});
}
#[test]
fn paint_overlay_multiplies_a_color_into_the_content() {
let image_color = Color::from_rgbaf32_unchecked(0.7, 0.6, 0.5, 0.4);
let result = super::paint_overlay(
(),
Item::new_from_element(image_color),
Item::new_from_element(Graphic::from(Color::GREEN)),
BlendMode::Multiply.into(),
100_f64.into(),
Item::default(),
);
// Multiplying by green keeps only the green channel, and the content keeps its own alpha
assert_eq!(result.unwrap().into_element(), Color::from_rgbaf32_unchecked(0., image_color.g(), 0., image_color.a()));
}
#[test]
fn the_input_adapter_uploads_a_raster_once_until_its_pixels_or_effects_change() {
futures::executor::block_on(async {
let Some(executor) = WgpuExecutor::new().await else { return };
let pipeline = WgpuPipelineCache::default();
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
let pipeline = Item::new_from_element(pipeline);
let cache = Default::default();
let upload = |item: &Item<Raster<CPU>>| super::upload_item((), &cache, item.clone(), pipeline.clone()).unwrap();
let plain = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE)));
let first = upload(&plain);
assert_eq!(upload(&plain).element().texture(), first.element().texture(), "the same pixels stay uploaded");
// Stamps carried out before anything reads the pixels, leaving none behind
let inverted = Raster::<CPU>::apply_adjustment(plain, Adjustment::Invert, pipeline.element()).unwrap();
let second = upload(&inverted);
assert_ne!(second.element().texture(), first.element().texture(), "other effects are uploaded anew");
assert!(second.attribute::<Effects>(ATTR_EFFECTS).is_none());
let raster: Raster<CPU> = second.into_element().convert(Footprint::DEFAULT, executor.clone()).await;
assert_color(raster.data[0], Color::BLACK);
});
}
#[test]
fn the_input_adapter_keeps_its_upload_when_the_footprint_changes() {
futures::executor::block_on(async {
let Some(executor) = WgpuExecutor::new().await else { return };
let pipeline = WgpuPipelineCache::default();
executor.pipeline_init::<RasterKernelRuntime>(&pipeline);
let raster = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, Color::WHITE)));
let adapter = UploadItemNode::new(PrecomputedItemNode::new(raster), PrecomputedItemNode::new(Item::new_from_element(pipeline)));
let upload_under = |translation: DVec2| {
let footprint = Footprint {
transform: DAffine2::from_translation(translation),
..Footprint::DEFAULT
};
let context = OwnedContextImpl::default().with_footprint(footprint).into_context();
let Poll::Final(uploaded) = adapter.eval(&context) else {
panic!("the upload should finish at once")
};
uploaded
};
let first = upload_under(DVec2::ZERO);
let panned = upload_under(DVec2::new(500., -300.));
assert_eq!(panned.element().texture(), first.element().texture(), "panning shouldn't upload the raster again");
});
}
}
-1
View File
@@ -5,7 +5,6 @@ pub mod dehaze;
pub mod effects;
pub mod filter;
pub mod image_color_palette;
pub mod parallel_rows;
pub mod raster_kernel;
pub mod std_nodes;
@@ -1,60 +0,0 @@
//! Spreads per-row image work across threads on platforms that have them.
/// Below this many pixels, starting threads costs more than they save.
#[cfg(not(target_family = "wasm"))]
const MIN_PIXELS_FOR_THREADS: usize = 65_536;
/// Calls `fill_row` with the index and pixels of each row of `pixels`, an image `width` pixels wide.
/// On native platforms, bands of rows run on separate threads, so `fill_row` must not depend on the order rows are filled in.
pub fn fill_rows<P: Send>(pixels: &mut [P], width: usize, fill_row: impl Fn(usize, &mut [P]) + Sync) {
if width == 0 {
return;
}
#[cfg(not(target_family = "wasm"))]
if pixels.len() >= MIN_PIXELS_FOR_THREADS {
let threads = std::thread::available_parallelism().map_or(1, |threads| threads.get());
let rows_per_band = (pixels.len() / width).div_ceil(threads).max(1);
std::thread::scope(|scope| {
for (band_index, band) in pixels.chunks_mut(rows_per_band * width).enumerate() {
let fill_row = &fill_row;
let fill_band = move |band: &mut [P]| {
for (row_in_band, row) in band.chunks_mut(width).enumerate() {
fill_row(band_index * rows_per_band + row_in_band, row);
}
};
// The band is handed over only once its thread has started, so it can be filled here instead if the system won't start one
let (sender, receiver) = std::sync::mpsc::channel();
match std::thread::Builder::new().spawn_scoped(scope, move || receiver.recv().map(fill_band)) {
Ok(_) => {
let _ = sender.send(band);
}
Err(_) => fill_band(band),
}
}
});
return;
}
for (y, row) in pixels.chunks_mut(width).enumerate() {
fill_row(y, row);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_row_is_filled_with_its_own_index() {
// Large enough to run on threads where there are any, with a ragged count of rows per band
let (width, height) = (300, 301);
let mut pixels = vec![0_usize; width * height];
fill_rows(&mut pixels, width, |y, row| row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = y * width + x));
assert!(pixels.iter().enumerate().all(|(index, pixel)| *pixel == index));
}
}
+6 -9
View File
@@ -5,14 +5,13 @@ use core_types::ATTR_TRANSFORM;
use core_types::context::{Ctx, ExtractFootprint};
use core_types::list::Item;
use core_types::math::bbox::Bbox;
use core_types::ops::Convert;
use core_types::transform::{Footprint, Transform};
use core_types::transform::Transform;
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DVec2, UVec2};
use graphene_resource::Resource;
use graphic_types::generator::{GeneratorPattern, NoiseSettings};
use raster_types::Image;
use raster_types::{GPU, Raster, Storage};
use raster_types::{CPU, GPU, Raster, Storage};
use raster_types::{Image, ImageError};
use wgpu_executor::WgpuPipelineCache;
use wgpu_executor::raster_kernel::render_generator;
@@ -204,16 +203,14 @@ fn image(
/// The image file to display.
#[widget(ParsedWidgetOverride::Custom = "image_file")]
resource: Item<Resource>,
#[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item<WgpuPipelineCache>,
) -> Result<Item<Raster<GPU>>, Interrupt> {
) -> Result<Item<Raster<CPU>>, ImageError> {
let resource = resource.into_element();
if resource.is_empty() {
return Ok(Item::default());
}
let image = Image::from_encoded(resource.as_ref()).map_err(NodeError::new)?;
let image = Image::from_encoded(resource.as_ref())?;
let executor = pipeline.element().executor().cloned().ok_or_else(|| NodeError::new("A GPU is required to load an image"))?;
Ok(Item::new_from_element(Raster::new_cpu(image).convert(Footprint::DEFAULT, executor)))
Ok(Item::new_from_element(Raster::new_cpu(image)))
}
/// Generates customizable procedural noise patterns.
+4 -4
View File
@@ -53,8 +53,8 @@ fn repeat<T: Send + Clone + 'static>(
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -98,8 +98,8 @@ fn repeat_array<T: Send + Clone + 'static>(
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -160,8 +160,8 @@ fn repeat_radial<T: Send + Clone + 'static>(
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -220,8 +220,8 @@ fn repeat_on_points<T: Send + Clone + 'static>(
Context -> List<DAffine2>,
Context -> List<Vector>,
Context -> List<Graphic>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
Context -> List<Artboard>,
@@ -18,8 +18,8 @@ fn transform<T: Send + 'static>(
Context -> Item<Graphic>,
Context -> Item<String>,
Context -> Item<Vector>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
)]
@@ -95,8 +95,8 @@ fn reset_transform<T: 'static>(
#[implementations(
Context -> Item<Graphic>,
Context -> Item<Vector>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<String>,
@@ -143,8 +143,8 @@ fn replace_transform<T: 'static>(
#[implementations(
Context -> Item<Graphic>,
Context -> Item<Vector>,
Context -> Item<Raster<GPU>>,
Context -> Item<Raster<CPU>>,
Context -> Item<Raster<GPU>>,
Context -> Item<Color>,
Context -> Item<Gradient>,
Context -> Item<String>,
@@ -182,7 +182,7 @@ fn replaced_transform_context<T, N: Node<Context<'static>, Output = Item<T>>>(
/// Obtains the transform of the input content.
#[node_macro::node(category("Transform"), icon("NodeExtractTransform"), path(core_types::vector))]
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<GPU>, Raster<CPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
fn extract_transform<T: Send>(_: impl Ctx, #[implementations(Graphic, Vector, Raster<CPU>, Raster<GPU>, Color, Gradient, String, Artboard)] content: Item<T>) -> Item<DAffine2> {
Item::new_from_element(content.attribute_cloned_or_default(ATTR_TRANSFORM))
}
+2 -2
View File
@@ -553,8 +553,8 @@ fn copy_to_points<I: Send + Clone>(
Context -> List<Graphic>,
Context -> List<Vector>,
Context -> List<String>,
Context -> List<Raster<GPU>>,
Context -> List<Raster<CPU>>,
Context -> List<Raster<GPU>>,
Context -> List<Color>,
Context -> List<Gradient>,
)]
@@ -1263,8 +1263,8 @@ fn pack_strips<T: Send + Clone>(
#[implementations(
List<Graphic>,
List<Vector>,
List<Raster<GPU>>,
List<Raster<CPU>>,
List<Raster<GPU>>,
)]
elements: List<T>,
#[default(0.)]
+1
View File
@@ -25,6 +25,7 @@ interpreted-executor = { workspace = true }
[dev-dependencies]
# Workspace dependencies
interpreted-executor = { workspace = true, features = ["gpu"] }
core-types = { workspace = true }
dyn-any = { workspace = true }
futures = { workspace = true }
+156 -1
View File
@@ -216,8 +216,17 @@ impl Preprocessor {
generated_nodes += 1;
let mut original_location = OriginalLocation::default();
original_location.auto_convert_index = Some(i);
// An adapter whose rows also take a second input gets the pipeline, which it uploads a CPU raster wire with
let takes_pipeline = into_node_registry
.get(&input_adapter_identifier)
.is_some_and(|rows| rows.keys().any(|node_io| node_io.inputs.len() == 2));
let mut adapter_inputs = vec![NodeInput::import(generic!(X), i)];
if takes_pipeline {
adapter_inputs.push(NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER));
}
let document_node = DocumentNode {
inputs: vec![NodeInput::import(generic!(X), i)],
inputs: adapter_inputs,
implementation: DocumentNodeImplementation::ProtoNode(input_adapter_identifier),
visible: true,
compile_metadata: forwarding,
@@ -689,6 +698,8 @@ pub fn input_adapter_identifier<Implementations>(input_types: &HashSet<Type>, no
_ => collapse_item_list_pair(input_types)?,
};
let element_name = match input_type.nested_type() {
// Type names drop the generics that tell a GPU raster from a CPU one
Type::Item(element) | Type::List(element) if **element == concrete!(raster_types::Raster<raster_types::GPU>) => "Raster<GPU>".to_string(),
Type::Item(element) | Type::List(element) => element.identifier_name(),
nested if nested.identifier_name() == "ListDyn" => "ListDyn".to_string(),
_ => return None,
@@ -829,4 +840,148 @@ mod tests {
assert!(compile_metadata(&identifier).forwards_input, "{identifier:?} should forward its input");
}
}
#[test]
fn a_cpu_raster_wire_uploads_through_one_adapter_that_ignores_the_footprint() {
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::item;
use graph_craft::proto::TypingContext;
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
use graphene_std::raster_nodes::std_nodes::channels_to_image;
use graphene_std::raster_types::{CPU, Raster};
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct NoSpawner;
impl Spawn for NoSpawner {
fn spawn(&self, _: Task) {}
}
// A CPU raster wired to all four of a node's inputs which only take GPU rasters
let source = NodeId(0);
let wire = || NodeInput::node(source, 0);
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
(
source,
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::TypeDefault(item!(Raster<CPU>)), false)],
implementation: DocumentNodeImplementation::ProtoNode(ops::passthrough::IDENTIFIER),
..Default::default()
},
),
(
NodeId(1),
DocumentNode {
inputs: vec![
NodeInput::value(TaggedValue::None, false),
wire(),
wire(),
wire(),
wire(),
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
],
implementation: DocumentNodeImplementation::ProtoNode(channels_to_image::IDENTIFIER),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
let proto_network = Compiler {}.compile_single(network).unwrap().network;
// The compiled graph type checks, since a CPU raster feeds the GPU-only inputs through the adapter
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
typing_context.update(&proto_network).expect("the CPU raster wire should reach the GPU-only inputs");
let identifier = ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>");
let adapters: Vec<_> = proto_network.nodes.iter().filter(|(_, node)| node.identifier == identifier).collect();
let distinct_ids: HashSet<_> = adapters.iter().map(|(id, _)| *id).collect();
assert_eq!(
distinct_ids.len(),
1,
"the identical adapters of the four inputs should share one stable ID, and so one node in the executor"
);
let (_, adapter) = adapters[0];
assert!(
!adapter.upstream_context_features.contains(core_types::ContextFeatures::FOOTPRINT),
"neither the adapter nor what feeds it should read the footprint, leaving it unaffected by panning"
);
}
#[test]
fn a_footprint_dependent_raster_warns_at_a_footprint_invariant_node_and_feeds_others_unconverted() {
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::graphene_compiler::Compiler;
use graph_craft::proto::{GraphErrorType, TypingContext};
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline;
use graphene_std::raster_nodes::std_nodes::mandelbrot;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
struct NoSpawner;
impl Spawn for NoSpawner {
fn spawn(&self, _: Task) {}
}
let compile = |consumer: ProtoNodeIdentifier| {
let network = NodeNetwork {
exports: vec![NodeInput::node(NodeId(1), 0)],
nodes: [
(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::scope(raster_kernel_pipeline::IDENTIFIER)],
implementation: DocumentNodeImplementation::ProtoNode(mandelbrot::IDENTIFIER),
..Default::default()
},
),
(
NodeId(1),
DocumentNode {
inputs: vec![
NodeInput::node(NodeId(0), 0),
NodeInput::value(TaggedValue::Number(10.), false),
NodeInput::scope(raster_kernel_pipeline::IDENTIFIER),
],
implementation: DocumentNodeImplementation::ProtoNode(consumer),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
let runtime = AsyncRuntime::new(Arc::new(NoSpawner), Arc::new(std::time::Instant::now()));
let mut network = wrap_network_in_scope(network, Arc::new(PlatformEditorApi::default()), runtime.handle());
Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
let compiled = Compiler {}.compile_single(network).unwrap();
let mut typing_context = TypingContext::new(&interpreted_executor::node_registry::NODE_REGISTRY);
typing_context.update(&compiled.network).expect("a GPU raster should reach the GPU-only input");
compiled.warnings
};
let warnings = compile(dehaze::IDENTIFIER);
assert_eq!(warnings.len(), 1, "Dehaze should warn about reading the footprint through its input: {warnings:?}");
assert!(warnings[0].error == GraphErrorType::FootprintDependentInput);
assert!(compile(median_filter::IDENTIFIER).is_empty(), "a node that isn't footprint invariant shouldn't warn");
}
}