From 5020a30c9cdad2a04483d11b7361f58e18ffff18 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Wed, 14 Oct 2026 04:54:07 -0700 Subject: [PATCH] Add curvature dials to gradients, rendered as a pencil of circles on Vello GPU --- Cargo.lock | 6 +- Cargo.toml | 6 +- .../gradient_curvature_from_gradient_form.rs | 99 ++++ .../migrations/nodes/src/math_nodes/mod.rs | 1 + .../document/graph_operation/utility_types.rs | 22 +- .../node_graph/document_node_definitions.rs | 1 + .../document/node_graph/node_inspector.rs | 100 +++- .../messages/portfolio/document_migration.rs | 97 ++- .../graph_modification_utils.rs | 13 +- .../tool/tool_messages/gradient_tool.rs | 361 +++++++++++- .../src/components/widgets/NodeSection.svelte | 5 +- node-graph/libraries/core-types/src/lib.rs | 6 +- node-graph/libraries/core-types/src/list.rs | 5 + .../raster-kernels/src/raster_effects.rs | 21 +- .../libraries/rendering/src/dial_gradient.rs | 33 ++ node-graph/libraries/rendering/src/lib.rs | 1 + .../libraries/rendering/src/render_ext.rs | 30 +- .../libraries/rendering/src/renderer.rs | 252 +++++--- .../rendering/src/vello_scene_builder.rs | 99 +++- .../vector-types/src/dial_gradient.rs | 552 ++++++++++++++++++ .../libraries/vector-types/src/gradient.rs | 56 ++ node-graph/libraries/vector-types/src/lib.rs | 1 + .../wgpu-executor/src/vello_render/tests.rs | 62 +- node-graph/nodes/math/src/lib.rs | 22 +- 24 files changed, 1648 insertions(+), 203 deletions(-) create mode 100644 document/migrations/nodes/src/math_nodes/gradient_curvature_from_gradient_form.rs create mode 100644 node-graph/libraries/rendering/src/dial_gradient.rs create mode 100644 node-graph/libraries/vector-types/src/dial_gradient.rs diff --git a/Cargo.lock b/Cargo.lock index a558d872060..2d18223b060 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8084,7 +8084,7 @@ dependencies = [ [[package]] name = "vello_common" version = "0.3.0" -source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07" +source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" dependencies = [ "bytemuck", "fearless_simd", @@ -8099,7 +8099,7 @@ dependencies = [ [[package]] name = "vello_gpu" version = "0.3.0" -source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07" +source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" dependencies = [ "bytemuck", "hashbrown 0.17.1", @@ -8113,7 +8113,7 @@ dependencies = [ [[package]] name = "vello_gpu_shaders" version = "0.3.0" -source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07" +source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" dependencies = [ "naga", "wesl", diff --git a/Cargo.toml b/Cargo.toml index 2bfb070c9e4..63229b3555a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -315,6 +315,6 @@ debug = true 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 fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2 # TODO: Remove these once the fork's fixes are upstreamed and released -vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" } -vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" } -vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" } +vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } +vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } +vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" } diff --git a/document/migrations/nodes/src/math_nodes/gradient_curvature_from_gradient_form.rs b/document/migrations/nodes/src/math_nodes/gradient_curvature_from_gradient_form.rs new file mode 100644 index 00000000000..30f0f64b02b --- /dev/null +++ b/document/migrations/nodes/src/math_nodes/gradient_curvature_from_gradient_form.rs @@ -0,0 +1,99 @@ +use migration_core::attr::node::ui::DISPLAY_NAME; +use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration}; +use serde::{Deserialize, Serialize}; + +/// Frozen mirror of the `TaggedValue` variants this migration uses. +#[derive(Serialize, Deserialize)] +enum Tagged { + Number(f64), + GradientForm(GradientForm), +} + +#[derive(Serialize, Deserialize)] +enum GradientForm { + Linear, + Radial, +} + +const FORM: u32 = 1; + +/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for +/// radial. A wired form becomes linear, and a name it stored as its default is cleared. +#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)] +pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> { + let [_, form] = node.inputs() else { + return Err(MigrationError::invariant("Gradient Form has two inputs")); + }; + let [start, end] = match literal_of::(&form.input) { + Some(Tagged::GradientForm(GradientForm::Radial)) => [1., 0.5], + _ => [0., 0.], + }; + + inputs.set(FORM, literal(Tagged::Number(start))); + inputs.push(literal(Tagged::Number(end))); + + if node.attributes().get_typed::(DISPLAY_NAME).as_deref() == Some("Gradient Form") { + attributes.remove(node.id(), DISPLAY_NAME); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use document_graph_storage::TimeStamp; + use migration_core::{NodeInput, decl}; + use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo}; + + fn form(form: GradientForm) -> NodeInput { + literal(Tagged::GradientForm(form)) + } + + fn contract() -> SourceContract { + SourceContract { + display_names: &["Gradient Form"], + ..SourceContract::new(2, |random, slot| match slot { + 1 if random.below(2) == 0 => form(GradientForm::Radial), + 1 => form(GradientForm::Linear), + _ => literal(Tagged::Number(random.below(10) as f64)), + }) + } + } + + #[test] + fn rewrites_history() { + check_commutation(&GradientCurvatureFromGradientForm, &contract()); + check_undo(&GradientCurvatureFromGradientForm, &contract()); + } + + #[test] + fn forms_become_their_curvature_presets() { + let gradient = literal(Tagged::Number(0.)); + for (old_form, [start, end]) in [ + (form(GradientForm::Linear), [0., 0.]), + (form(GradientForm::Radial), [1., 0.5]), + (NodeInput::Import { index: 0 }, [0., 0.]), + ] { + let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm); + let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]); + let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap(); + + assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2))); + assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]); + } + } + + #[test] + fn only_the_old_default_name_is_cleared() { + for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] { + let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm); + let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]); + let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut(); + attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap(); + + let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap(); + + assert_eq!(migrated.node_instances[&node].attributes().get_typed::(DISPLAY_NAME).as_deref(), kept); + } + } +} diff --git a/document/migrations/nodes/src/math_nodes/mod.rs b/document/migrations/nodes/src/math_nodes/mod.rs index b81c16eb582..830b2b5502c 100644 --- a/document/migrations/nodes/src/math_nodes/mod.rs +++ b/document/migrations/nodes/src/math_nodes/mod.rs @@ -1,4 +1,5 @@ //! Migrations of the nodes in `math_nodes`. +mod gradient_curvature_from_gradient_form; mod math_formula_from_math_f; mod renames; diff --git a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs index 36091431153..824e24eaa37 100644 --- a/editor/src/messages/portfolio/document/graph_operation/utility_types.rs +++ b/editor/src/messages/portfolio/document/graph_operation/utility_types.rs @@ -6,7 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector}; use crate::messages::prelude::*; use crate::messages::tool::common_functionality::graph_modification_utils::{ - ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain, + ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain, }; use glam::{DAffine2, DVec2, IVec2}; use graph_craft::application_io::resource::ResourceId; @@ -761,20 +761,28 @@ 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 - /// from the default (`Linear`). + /// 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`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched. pub fn gradient_form_set(&mut self, gradient_form: GradientForm) { + use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput}; + 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 Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return }; + let Some(curvatures) = gradient_curvature_values(node) else { return }; + if GradientForm::from_dials(curvatures) == Some(gradient_form) { + return; + } + + let [start, end] = gradient_form.dials(); + self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true); + 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. diff --git a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs index 814d6f76d16..92b137e011f 100644 --- a/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs +++ b/editor/src/messages/portfolio/document/node_graph/document_node_definitions.rs @@ -686,6 +686,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)); diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index eb0261400de..fe54f672c00 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -254,6 +254,23 @@ pub(crate) struct ParameterOptions { pub step: Option, } +impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions { + fn from(field: &graphene_std::registry::FieldMetadata) -> Self { + Self { + soft_min: field.number_soft_min, + soft_max: field.number_soft_max, + hard_min: field.number_hard_min, + hard_max: field.number_hard_max, + slider: field.number_mode_range, + multiline: field.multiline, + progression: field.progression, + unit: field.unit, + display_decimal_places: field.number_display_decimal_places, + step: field.number_step, + } + } +} + /// The values a range slider's two ends map to linearly and the one its double-click restores, if known. #[derive(Clone, Copy)] pub struct SliderRange { @@ -3286,6 +3303,76 @@ 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 { + use graphene_std::math_nodes::gradient_curvature::*; + + // 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) => graph_modification_utils::gradient_curvature_values(document_node), + 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 make that form + 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, gradient_form, tooltip) in [ + ("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."), + ( + "Radial", + GradientForm::Radial, + "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start.", + ), + ] { + let [start, end] = gradient_form.dials(); + form.push( + TextButton::new(label) + .tooltip_description(tooltip) + .emphasized(curvatures.and_then(GradientForm::from_dials) == Some(gradient_form)) + .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 = |index: usize| { + let registry = graphene_std::registry::NODE_METADATA.lock().ok(); + let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index)); + field.map(ParameterOptions::from).unwrap_or_default() + }; + let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options(index), 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 { use graphene_std::vector::generator_nodes::rectangle::*; @@ -3443,18 +3530,7 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect .get(&proto_node_identifier) .and_then(|metadata| metadata.fields.get(input_index)) { - options = ParameterOptions { - soft_min: field.number_soft_min, - soft_max: field.number_soft_max, - hard_min: field.number_hard_min, - hard_max: field.number_hard_max, - slider: field.number_mode_range, - multiline: field.multiline, - progression: field.progression, - unit: field.unit, - display_decimal_places: field.number_display_decimal_places, - step: field.number_step, - }; + options = ParameterOptions::from(field); default_type = field.default_type.clone(); } diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index 7bf6c03b87d..fcd95dd78ec 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -21,7 +21,7 @@ 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; @@ -301,10 +301,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"], @@ -1689,6 +1685,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_ } } + // The "Gradient Form" node was replaced by "Gradient Curvature", with its two curvatures taking 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)> = 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"; @@ -5440,6 +5479,54 @@ mod tests { assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept"); } + #[test] + 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}; + + 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 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] fn test_no_duplicate_node_replacements() { let mut hashmap = HashMap::::new(); diff --git a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs index 1d3a222f470..12c51b0e7af 100644 --- a/editor/src/messages/tool/common_functionality/graph_modification_utils.rs +++ b/editor/src/messages/tool/common_functionality/graph_modification_utils.rs @@ -346,7 +346,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, @@ -428,6 +428,17 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in Some(get_chain_source_gradient_ramp(layer, network_interface)?.into()) } +/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed. +pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> { + use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput}; + + let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? { + &TaggedValue::Number(value) => Some(value), + _ => None, + }; + Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?]) +} + /// Get the gradient stops of a layer, if any. pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option { // Try to find the gradient stops value that is created by a Fill node first diff --git a/editor/src/messages/tool/tool_messages/gradient_tool.rs b/editor/src/messages/tool/tool_messages/gradient_tool.rs index 9fc10d28141..b3b42d9b4c3 100644 --- a/editor/src/messages/tool/tool_messages/gradient_tool.rs +++ b/editor/src/messages/tool/tool_messages/gradient_tool.rs @@ -29,6 +29,8 @@ pub struct GradientTool { #[derive(Default)] pub struct GradientOptions { gradient_form: GradientForm, + /// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen. + curvature_source: CurvatureSource, settings: GradientSettings, } @@ -92,12 +94,16 @@ impl<'a> MessageHandler> for Grad ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options { GradientOptionsUpdate::Form(gradient_form) => { self.options.gradient_form = gradient_form; + self.options.curvature_source = CurvatureSource::Form; apply_gradient_update( &mut self.data, context, responses, - |(_gradient, appearance)| appearance.gradient_form != gradient_form, - |(_gradient, appearance)| appearance.gradient_form = gradient_form, + |(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form, + |(_gradient, appearance)| { + appearance.gradient_form = gradient_form; + appearance.curvature_source = CurvatureSource::Form; + }, ); responses.add(ToolMessage::UpdateHints); responses.add(ToolMessage::UpdateCursor); @@ -192,14 +198,19 @@ impl<'a> MessageHandler> for Grad let mut needs_refresh = false; if let Some((_gradient, appearance)) = ¤t_gradient { - if self.options.gradient_form != appearance.gradient_form { + if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source { self.options.gradient_form = appearance.gradient_form; + self.options.curvature_source = appearance.curvature_source; needs_refresh = true; } if self.options.settings != appearance.settings { self.options.settings = appearance.settings; needs_refresh = true; } + } else if self.options.curvature_source != CurvatureSource::Form { + // With no gradient selected, the Form radio shows the form a new one gets + self.options.curvature_source = CurvatureSource::Form; + needs_refresh = true; } let has_gradient = current_gradient.is_some(); @@ -261,7 +272,11 @@ impl LayoutHolder for GradientTool { } .into() }); - let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance(); + let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32); + let gradient_form = RadioInput::new(gradient_form_entries) + .selected_index(selected_form) + .disabled(self.options.curvature_source == CurvatureSource::Graph) + .widget_instance(); // Display priority: the selected layer's stops, then any user-customized tool default, then the working colors let stops_value = self @@ -385,6 +400,7 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI gradient.stops, GradientAppearance { gradient_form: gradient.gradient_form, + curvature_source: CurvatureSource::Form, settings: gradient.settings, transform: gradient.transform, }, @@ -404,19 +420,35 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI struct GradientAppearance { transform: DAffine2, gradient_form: GradientForm, + /// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls. + // TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it + curvature_source: CurvatureSource, settings: GradientSettings, } +/// Where a gradient chain's curvatures come from, as told by its 'Gradient Curvature' node. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum CurvatureSource { + /// They make the form, or there's no node and the form's are implied. + #[default] + Form, + /// They're values that make neither form. + Custom, + /// They're fed from the graph or exposed, so only the graph can change them. + Graph, +} + /// Resolve the gradient transform, form, and spread by walking the chain feeding the layer. fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance { let target_input = gradient_chain_target_input(layer, network_interface); 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 = Vec::new(); let mut gradient_form: Option = None; + let mut curvature_source = CurvatureSource::Form; for node_id in network_interface .upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow) @@ -430,11 +462,16 @@ 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() { + let curvatures = graph_modification_utils::gradient_curvature_values(document_node); + let form = curvatures.and_then(GradientForm::from_dials); + + gradient_form = Some(form.unwrap_or_default()); + curvature_source = match (curvatures, form) { + (None, _) => CurvatureSource::Graph, + (Some(_), None) => CurvatureSource::Custom, + (Some(_), Some(_)) => CurvatureSource::Form, + }; } } @@ -444,6 +481,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod GradientAppearance { transform: composed_transform, gradient_form: gradient_form.unwrap_or_default(), + curvature_source, settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(), } } @@ -793,7 +831,9 @@ impl SelectedGradient { pub fn render_gradient(&mut self, responses: &mut VecDeque) { if let Some(layer) = self.layer { if self.is_gradient_chain { - dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses); + // Only a new gradient takes its form from the tool, as the Properties panel may have dialed an existing one after it was selected + let write_form = self.dragging == GradientDragTarget::New; + dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses); } else { responses.add(GraphOperationMessage::FillGradientSet { layer, @@ -829,8 +869,8 @@ impl SelectedGradient { } } -/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer. -fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque) { +/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer, including its form's curvatures if `write_form` is set. +fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque) { responses.add(GraphOperationMessage::GradientCyclicSet { layer, gradient_cyclic: appearance.settings.cyclic, @@ -848,10 +888,12 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien layer, transform: appearance.transform, }); - responses.add(GraphOperationMessage::GradientFormSet { - layer, - gradient_form: appearance.gradient_form, - }); + if write_form && appearance.curvature_source == CurvatureSource::Form { + responses.add(GraphOperationMessage::GradientFormSet { + layer, + gradient_form: appearance.gradient_form, + }); + } responses.add(GraphOperationMessage::GradientSpreadSet { layer, gradient_spread: appearance.settings.spread, @@ -1522,6 +1564,7 @@ impl Fsm for GradientToolFsmState { GradientAppearance { transform: DAffine2::IDENTITY, gradient_form: tool_options.gradient_form, + curvature_source: CurvatureSource::Form, settings: tool_options.settings, }, // A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted @@ -1940,7 +1983,8 @@ fn apply_gradient_update( // Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() { - dispatch_gradient_chain_writes(layer, &gradient, appearance, responses); + // Read fresh from the layer, so its form's curvatures change only if the update chose another form + dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses); } else { responses.add(GraphOperationMessage::FillGradientSet { layer, @@ -2108,6 +2152,7 @@ mod test_gradient { use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at}; use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN}; use crate::messages::input_mapper::utility_types::pointer::EditorPointerState; + use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance}; use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn; use crate::messages::portfolio::document::utility_types::misc::GroupFolderType; use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector}; @@ -2115,8 +2160,8 @@ mod test_gradient { use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id; pub use crate::test_utils::test_prelude::*; use glam::DAffine2; - use graph_craft::document::NodeInput; use graph_craft::document::value::TaggedValue; + use graph_craft::document::{NodeId, NodeInput}; use graphene_std::NodeParameter; use graphene_std::color::SRGBA8; use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation}; @@ -3366,7 +3411,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 +3420,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 +3429,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"); @@ -3532,6 +3577,276 @@ mod test_gradient { assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write"); } + /// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to. + async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 { + let document = editor.active_document(); + let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient"); + let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X); + let dragged_end = end + offset; + + editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await; + editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await; + editor + .mouseup( + EditorPointerState { + editor_position: dragged_end, + mouse_keys: MouseKeys::empty(), + ..Default::default() + }, + ModifierKeys::empty(), + ) + .await; + + dragged_end + } + + /// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses + /// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node. + async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) { + editor.active_document_mut().snapping_state.snapping_enabled = false; + let layer = create_gradient_list_layer(editor).await; + editor + .handle_message(GraphOperationMessage::GradientTransformSet { + layer, + transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)), + }) + .await; + editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await; + editor.select_tool(ToolType::Gradient).await; + + editor + .handle_message(GradientToolMessage::UpdateOptions { + options: super::GradientOptionsUpdate::Form(GradientForm::Radial), + }) + .await; + let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER); + let network_interface = &editor.active_document().network_interface; + let curvature_node_id = network_interface + .document_network() + .nodes + .keys() + .copied() + .find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference)) + .expect("Gradient Curvature node should have been inserted"); + + (layer, curvature_node_id) + } + + /// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do. + async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) { + use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput}; + + for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) { + editor + .handle_message(NodeGraphMessage::SetInputValue { + node_id: curvature_node_id, + input_index, + value: TaggedValue::Number(curvature).into(), + }) + .await; + } + } + + /// The start and end curvature inputs of a 'Gradient Curvature' node. + fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option; 2] { + use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput}; + + let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id]; + [node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()] + } + + /// The curvature inputs holding these values. + fn inputs_holding(curvatures: [f64; 2]) -> [Option; 2] { + curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false))) + } + + /// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages. + fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option, bool)> { + let form_radio = |widget: &WidgetInstance| match &*widget.widget { + Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)), + _ => None, + }; + + frontend_messages + .iter() + .rev() + .filter_map(|message| match message { + FrontendMessage::UpdateLayout { + layout_target: LayoutTarget::ToolOptions, + diff, + } => Some(diff), + _ => None, + }) + .flat_map(|diff| diff.iter().rev()) + .find_map(|widget_diff| match &widget_diff.new_value { + DiffUpdate::Widget(widget) => form_radio(widget), + DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio), + DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio), + }) + } + + #[tokio::test] + async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() { + use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await; + + // Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are + let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await; + let document = editor.active_document(); + let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag"); + let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X); + assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}"); + assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures"); + + // Choosing a form in the control bar is what sets them + editor + .handle_message(GradientToolMessage::UpdateOptions { + options: super::GradientOptionsUpdate::Form(GradientForm::Linear), + }) + .await; + assert_eq!( + curvature_inputs(&editor, curvature_node_id), + inputs_holding(GradientForm::Linear.dials()), + "choosing the linear form should set its curvatures" + ); + + // A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value + let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::primary_output(number_node_id), + input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput), + }) + .await; + drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await; + editor + .handle_message(GraphOperationMessage::GradientFormSet { + layer, + gradient_form: GradientForm::Radial, + }) + .await; + let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id); + assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}"); + assert_eq!(end_input, inputs_holding(GradientForm::Linear.dials())[1], "the end curvature beside a wired one should stay as it was"); + } + + #[tokio::test] + async fn stop_edits_keep_curvatures_dialed_while_the_stop_was_selected() { + use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len()); + + // Clicking the line inserts a stop and selects it, and a double-click opens its color picker + let document = editor.active_document(); + let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient"); + let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.)); + editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await; + editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await; + editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await; + editor.handle_message(GradientToolMessage::DoubleClick).await; + assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop"); + + // The Properties panel then dials curvatures of neither form while the stop stays selected + set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await; + + editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await; + assert_eq!( + curvature_inputs(&editor, curvature_node_id), + inputs_holding([0.5, 0.5]), + "recoloring the stop shouldn't reset the curvatures" + ); + + editor.press(Key::Delete, ModifierKeys::empty()).await; + assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop"); + assert_eq!( + curvature_inputs(&editor, curvature_node_id), + inputs_holding([0.5, 0.5]), + "deleting the stop shouldn't reset the curvatures" + ); + } + + #[tokio::test] + async fn dials_already_making_a_form_are_kept_by_writes_of_that_form() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + + // The start curvature's slider minimum is the same point as 1, so the tool draws these dials as the radial form + set_curvatures(&mut editor, curvature_node_id, [-1., 0.5]).await; + let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient"); + assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form)); + + drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await; + assert_eq!( + curvature_inputs(&editor, curvature_node_id), + inputs_holding([-1., 0.5]), + "a drag shouldn't rewrite dials making the form" + ); + + editor + .handle_message(GraphOperationMessage::GradientFormSet { + layer, + gradient_form: GradientForm::Radial, + }) + .await; + assert_eq!( + curvature_inputs(&editor, curvature_node_id), + inputs_holding([-1., 0.5]), + "setting the form they make shouldn't rewrite them" + ); + } + + #[tokio::test] + async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() { + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await; + + // Reselecting the layer has the tool read its curvatures, which make neither form + let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await; + assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen"); + + frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await); + assert_eq!( + latest_form_radio(&frontend_messages), + Some((Some(GradientForm::Linear as u32), false)), + "with nothing selected, the radio should show the linear form a new gradient gets" + ); + } + + #[tokio::test] + async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() { + use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput; + + let mut editor = EditorTestUtils::create(); + editor.new_document().await; + let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await; + + let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await; + editor + .handle_message(NodeGraphMessage::CreateWire { + output_connector: OutputConnector::primary_output(number_node_id), + input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput), + }) + .await; + + let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await; + assert_eq!( + latest_form_radio(&frontend_messages), + Some((None, true)), + "a wired curvature should leave no form chosen and the radio disabled" + ); + } + #[tokio::test] async fn drag_on_blank_layer_starts_gradient_chain() { use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops; diff --git a/frontend/src/components/widgets/NodeSection.svelte b/frontend/src/components/widgets/NodeSection.svelte index 76ea471b473..dc450dd4136 100644 --- a/frontend/src/components/widgets/NodeSection.svelte +++ b/frontend/src/components/widgets/NodeSection.svelte @@ -543,9 +543,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 { diff --git a/node-graph/libraries/core-types/src/lib.rs b/node-graph/libraries/core-types/src/lib.rs index f9e93aa84a3..1bdda66e9d7 100644 --- a/node-graph/libraries/core-types/src/lib.rs +++ b/node-graph/libraries/core-types/src/lib.rs @@ -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; diff --git a/node-graph/libraries/core-types/src/list.rs b/node-graph/libraries/core-types/src/list.rs index 510df7f96d0..3648de90464 100644 --- a/node-graph/libraries/core-types/src/list.rs +++ b/node-graph/libraries/core-types/src/list.rs @@ -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 diff --git a/node-graph/libraries/raster-kernels/src/raster_effects.rs b/node-graph/libraries/raster-kernels/src/raster_effects.rs index 844e2abb8e3..35466facc73 100644 --- a/node-graph/libraries/raster-kernels/src/raster_effects.rs +++ b/node-graph/libraries/raster-kernels/src/raster_effects.rs @@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer; use core_types::FallibleVec2Operations; use core_types::blending::BlendMode; use core_types::color::{linear_to_srgb, srgb_to_linear}; -use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_FORM, Item, List}; +use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_START_CURVATURE, Item, List}; use core_types::transfer_curve::TransferCurve; use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color}; use glam::{DAffine2, DMat2, DVec2}; @@ -33,6 +33,7 @@ use raster_types::parallel_rows::fill_rows; use raster_types::{CPU, Image, Raster}; use std::collections::HashMap; use std::ops::Range; +use vector_types::dial_gradient::PencilParameters; use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread}; mod styles; @@ -1229,7 +1230,7 @@ fn drawn_paint_colors(operation: &EffectOperation, transform: DAffine2, size: DV Some(colors) } -/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, linear or radial gradients, and those nested in a placement of their own. +/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, gradients, and those nested in a placement of their own. /// The paint's own adjustments are carried out first, and an image's own effects too. fn paint_sampler(paint: &Graphic) -> Option Color + Sync + '_>> { let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse()); @@ -1498,19 +1499,27 @@ fn drawn_gradient_color(samples: &[(f64, Color, Option)], spread: GradientS /// How far along the gradient each point lies, or `None` where its placement collapses it. fn gradient_position(item: &Item) -> Option f64 + Sync>> { let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); + let form = item.attribute_cloned_or_default::(ATTR_GRADIENT_FORM); + let dials = form.drawn_dials(item.attribute(ATTR_GRADIENT_START_CURVATURE).copied(), item.attribute(ATTR_GRADIENT_END_CURVATURE).copied()); + let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse()); - match item.attribute_cloned_or_default::(ATTR_GRADIENT_FORM) { + match GradientForm::from_dials(dials) { // Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them - GradientForm::Linear => { + Some(GradientForm::Linear) => { let axis = placement.matrix2.x_axis; let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis); let origin = placement.translation; (line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box f64 + Sync>) } - GradientForm::Radial => { - let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?; + Some(GradientForm::Radial) => { + let to_unit = to_unit?; Some(Box::new(move |point| to_unit.transform_point2(point).length())) } + // Any other dials span a pencil of circles in the gradient space the full placement maps from + None => { + let (to_unit, parameters) = (to_unit?, PencilParameters::new(dials[0], dials[1])); + Some(Box::new(move |point| parameters.t(to_unit.transform_point2(point)))) + } } } diff --git a/node-graph/libraries/rendering/src/dial_gradient.rs b/node-graph/libraries/rendering/src/dial_gradient.rs new file mode 100644 index 00000000000..9a251356add --- /dev/null +++ b/node-graph/libraries/rendering/src/dial_gradient.rs @@ -0,0 +1,33 @@ +//! Vello GPU's form of the dialed gradients that [`vector_types::dial_gradient`] lays out. + +pub use graphic_types::vector_types::dial_gradient::{AxisCircle, CrossingSelection, PencilParameters, SvgApproximation, Wrap}; +pub use graphic_types::vector_types::gradient::{LINEAR_DIALS, RADIAL_DIALS}; + +pub trait PencilParametersExt { + /// The same parameters for Vello GPU's pencil gradient paint. + fn to_vello(&self) -> vello_gpu::PencilGeometry; +} + +impl PencilParametersExt for PencilParameters { + 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, + } + } +} diff --git a/node-graph/libraries/rendering/src/lib.rs b/node-graph/libraries/rendering/src/lib.rs index 6909a3b2e78..45f74b24e39 100644 --- a/node-graph/libraries/rendering/src/lib.rs +++ b/node-graph/libraries/rendering/src/lib.rs @@ -1,5 +1,6 @@ pub mod convert_usvg_path; pub mod deferred_image; +pub mod dial_gradient; pub mod render_ext; mod renderer; mod svg_backdrop; diff --git a/node-graph/libraries/rendering/src/render_ext.rs b/node-graph/libraries/rendering/src/render_ext.rs index 3a29336b3b7..9deb22145b7 100644 --- a/node-graph/libraries/rendering/src/render_ext.rs +++ b/node-graph/libraries/rendering/src/render_ext.rs @@ -1,14 +1,14 @@ use crate::renderer::{ - ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible, + GradientShape, ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, 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; @@ -93,10 +93,10 @@ fn render_gradient_paint(item: Option>, svg_defs: &mut Str let item = item?; let (stops, settings) = painted_gradient(item)?; - 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 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. { @@ -138,7 +138,7 @@ fn render_gradient_paint(item: Option>, 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() @@ -153,23 +153,7 @@ fn render_gradient_paint(item: Option>, svg_defs: &mut Str }; let gradient_id = generate_uuid(); - - match gradient_form { - GradientForm::Linear => { - let _ = write!( - svg_defs, - r#"{}"#, - gradient_id, stop - ); - } - GradientForm::Radial => { - let _ = write!( - svg_defs, - r#"{}"#, - gradient_id, stop - ); - } - } + svg_defs.push_str(&svg_gradient_definition(shape, gradient_id, &format!("{gradient_spread}{gradient_transform}"), &stop)); Some(gradient_id) } diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index fe410c55365..018e239fa60 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -1,10 +1,11 @@ use crate::deferred_image::{self, DeferredContent, DeferredImage, EffectMap}; +use crate::dial_gradient::{PencilParameters, PencilParametersExt, SvgApproximation}; use crate::render_ext::{PaintTarget, RenderExt}; use crate::svg_backdrop::{self, OpenGroup, OpenGroups}; use crate::svg_blend_if; use crate::svg_layer_blend::{self, SvgLayerBlend}; 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}; @@ -21,8 +22,9 @@ 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_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, 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_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, + 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}; @@ -3077,22 +3079,50 @@ fn transform_relative_to(reference: DAffine2, transform: DAffine2) -> DAffine2 { } } -/// 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 form = item.attribute_cloned_or_default::(ATTR_GRADIENT_FORM); + let dials = form.drawn_dials(item.attribute(ATTR_GRADIENT_START_CURVATURE).copied(), item.attribute(ATTR_GRADIENT_END_CURVATURE).copied()); + + match GradientForm::from_dials(dials) { + Some(GradientForm::Linear) => Self::Linear, + Some(GradientForm::Radial) => Self::Radial, + None => Self::Pencil(PencilParameters::new(dials[0], dials[1])), + } + } + + /// 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, } } @@ -3102,9 +3132,9 @@ type GradientSamples = Vec<(f64, Color, Option)>; /// 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 +/// when the gradient's 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; @@ -3119,7 +3149,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 { @@ -3153,14 +3183,15 @@ fn peniko_color_stops(samples: &[(f64, Color, Option)]) -> 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, @@ -3170,6 +3201,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#"{stops}"#), + 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#"{stops}"#) + } + } +} + +/// 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)], 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 { @@ -3181,13 +3266,13 @@ 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, settings) = painted_gradient(gradient_item)?; - 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 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. { @@ -3201,19 +3286,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)) } @@ -4859,7 +4934,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; }; @@ -4869,7 +4944,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 { @@ -4950,7 +5025,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) { @@ -4961,7 +5036,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 { @@ -6357,13 +6432,13 @@ fn render_gradient_shape_svg( render_params: &RenderParams, ) { let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM); + let shape = GradientShape::of(item); let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" }; render.leaf_tag(tag, |attributes| { emit_endless_shape(attributes, thumbnail_rect); - 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 { @@ -6394,20 +6469,8 @@ fn render_gradient_shape_svg( }; // 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#"{stop_string}"# - ); - } - GradientForm::Radial => { - let _ = write!( - &mut attributes.0.svg_defs, - r#"{stop_string}"# - ); - } - } + 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}')")); @@ -6437,7 +6500,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS if compositing.effects.is_some_and(|(effects, _)| carried_out(effects)) { let (brush, brush_transform) = gradient_brush(item, source_gradient, settings, parent_transform); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| { - scene.fill_viewport(&brush, Some(brush_transform)) + scene.fill_viewport(brush.clone(), Some(brush_transform)) }); } @@ -6450,7 +6513,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS let (brush, brush_transform) = gradient_brush(item, &gradient, settings, parent_transform); let compositing = compositing.with_remaining_effects(&remaining); return draw_endless_item_with_effects(scene, &compositing, blend_mode, parent_transform, render_params, |scene| { - scene.fill_viewport(&brush, Some(brush_transform)) + scene.fill_viewport(brush.clone(), Some(brush_transform)) }); } @@ -6466,7 +6529,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS let masks = endless_masks(&compositing); let content_blend_mode = if masks.is_some() { BlendMode::Normal } else { paint.blend_mode }; draw_through_endless_masks(scene, &compositing, masks.as_ref(), paint.blend_mode, parent_transform, render_params, |scene| { - draw_endless_layer(scene, opacity, content_blend_mode, |scene| scene.fill_viewport(&brush, Some(brush_transform))); + draw_endless_layer(scene, opacity, content_blend_mode, |scene| scene.fill_viewport(brush.clone(), Some(brush_transform))); for &(overlay, blend_mode) in &paint.overlays { draw_endless_layer(scene, paint.opacity, blend_mode, |scene| scene.fill_viewport(SRGBA8::from(overlay).to_peniko_color(), None)); } @@ -6474,19 +6537,13 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS } /// The brush filling the viewport with a gradient item's `gradient` read with its `settings`, and the brush's transform, given the transform placing the item's space. -fn gradient_brush(item: ItemRef<'_, Gradient>, gradient: &Gradient, settings: GradientSettings, parent_transform: DAffine2) -> (peniko::Brush, kurbo::Affine) { - let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM); +fn gradient_brush(item: ItemRef<'_, Gradient>, gradient: &Gradient, settings: GradientSettings, parent_transform: DAffine2) -> (SceneBrush, kurbo::Affine) { + let shape = GradientShape::of(item); let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM); - let samples = spread_adjusted_samples(gradient, settings, gradient_form); + let samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start()); - let brush = peniko::Brush::Gradient(peniko::Gradient { - kind: unit_gradient_kind(gradient_form), - stops: peniko_color_stops(&samples), - extend: peniko_extend(settings.spread), - interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied, - ..Default::default() - }); - let brush_transform = kurbo::Affine::new(gradient_placement(parent_transform * transform, gradient_form).to_cols_array()); + let brush = gradient_scene_brush(shape, &samples, settings.spread); + let brush_transform = kurbo::Affine::new(gradient_placement(parent_transform * transform, shape).to_cols_array()); (brush, brush_transform) } @@ -6499,7 +6556,7 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator(items: impl Iterator) -> 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) { - 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; } @@ -6540,7 +6605,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) { - 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.); @@ -7265,18 +7330,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)]); } @@ -7289,7 +7354,7 @@ mod tests { space: GradientSpace::RgbGamma, ..Default::default() }, - GradientForm::Linear, + true, ); let colors: Vec = samples.iter().map(|&(_, color, _)| color).collect(); assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]); @@ -7322,6 +7387,33 @@ mod tests { assert_eq!(halvings(0.), [0]); } + #[test] + fn gradient_shape_follows_the_form_until_dialed() { + let shape = |form: Option, 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); + } + /// Writes the filters of each layer `effects` draw on content blending normally, in order, as a run starting at `capture_offset` in its item's list. fn write_filters(defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], capture_offset: usize, paints: &[String]) -> Vec { write_filters_at(defs, effects, fill, bounds, capture_offset, paints, 1.) diff --git a/node-graph/libraries/rendering/src/vello_scene_builder.rs b/node-graph/libraries/rendering/src/vello_scene_builder.rs index 4a8d9e20e0d..3d1f0692813 100644 --- a/node-graph/libraries/rendering/src/vello_scene_builder.rs +++ b/node-graph/libraries/rendering/src/vello_scene_builder.rs @@ -10,8 +10,8 @@ use graphic_types::{Adjustment, EffectOperation, 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; @@ -94,6 +94,45 @@ pub trait EffectsRenderer: Send { } } +/// What a fill or stroke paints with. +#[derive(Clone, Debug)] +pub enum SceneBrush { + /// A solid color, gradient, or image. + Peniko(Brush), + /// A gradient with a pencil of circles for its contours, which only Vello GPU's fork can draw. + PencilGradient(PencilGradient), +} + +impl From 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 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 for SceneBrush { + fn from(gradient: PencilGradient) -> Self { + Self::PencilGradient(gradient) + } +} + /// The pixels behind an image the scene draws. #[derive(Clone, Debug)] pub enum SceneImage { @@ -270,44 +309,41 @@ 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>, brush_transform: Option, shape: &impl Shape) { + pub fn fill(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into, brush_transform: Option, 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>, brush_transform: Option, path: &BezPath) { + pub fn fill_path(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into, brush_transform: Option, path: &BezPath) { if !self.drawing { return; } - let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; + 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>, brush_transform: Option, shape: &impl Shape) { + pub fn stroke(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into, brush_transform: Option, shape: &impl Shape) { if !self.drawing { return; } - let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; + 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>, brush_transform: Option) { + pub fn fill_viewport(&mut self, brush: impl Into, brush_transform: Option) { if !self.drawing { return; } - let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return }; + 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)); } @@ -698,22 +734,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 { + 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. diff --git a/node-graph/libraries/vector-types/src/dial_gradient.rs b/node-graph/libraries/vector-types/src/dial_gradient.rs new file mode 100644 index 00000000000..eb297b40923 --- /dev/null +++ b/node-graph/libraries/vector-types/src/dial_gradient.rs @@ -0,0 +1,552 @@ +//! Gradients with each of their two ends a contour dialed between a line, a circle, and a point, and 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, within the band between the end contours' crossings that lies nearest to the line's span from 0 to 1. +//! Where the band is that span, 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; + +/// Stands in for a t of infinity, on the contours that cross the gradient line 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 { + (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, + /// 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. On the outer arc between finite limit + // points, that's a band with its ends on opposite sides of their midpoint, which counts an end on a limit point as on its side. + let limit_values = limit_points.map(|point| point.value()); + let usable = |negative_arc: bool, 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)] if !negative_arc => { + let reference_x = (first + second) / 2.; + (band_start > reference_x) == (band_end > reference_x) + } + _ => true, + } + }; + + // Among the rest, prefer the band nearest to running from 0 to 1, measured continuously so the choice can't jump as a contour nears a point + let distance_from_unit_band = |&(_, band_start, band_end): &(bool, Homogeneous, Homogeneous)| { + band_start.value().map_or(f64::INFINITY, f64::abs) + band_end.value().map_or(f64::INFINITY, |band_end| (band_end - 1.).abs()) + }; + let chosen = candidates + .into_iter() + .filter(|&(negative_arc, band_start, band_end)| usable(negative_arc, band_start, band_end)) + .min_by(|a, b| distance_from_unit_band(a).total_cmp(&distance_from_unit_band(b))) + .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, 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, which crosses at 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 { + /// A stand-in SVG can draw: 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. Only concentric end circles draw the same as the pencil. + // TODO: Draw the other dials exactly in SVG, like with an image filled in from a GPU render + pub fn svg_approximation(&self) -> SvgApproximation { + let (Some((start_center, start_radius)), Some((end_center, end_radius))) = (self.start.center_and_radius(), self.end.center_and_radius()) else { + return SvgApproximation::Linear; + }; + + let nested = (start_center - end_center).abs() <= (start_radius - end_radius).abs(); + if !nested { + return SvgApproximation::Linear; + } + + SvgApproximation::Radial { + start_center, + start_radius, + end_center, + end_radius, + } + } +} + +/// 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::*; + use crate::gradient::{LINEAR_DIALS, RADIAL_DIALS}; + + 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}"); + } + } + } + } + } + + #[test] + fn every_dial_pair_puts_the_start_point_at_0_and_the_end_point_at_1() { + for start_step in -100..=100 { + for end_step in -100..=100 { + let (start_dial, end_dial) = (start_step as f64 / 100., end_step as f64 / 100.); + let parameters = PencilParameters::new(start_dial, end_dial); + + assert_close(parameters.t(DVec2::ZERO), 0., &format!("start point with dials ({start_dial}, {end_dial})")); + assert_close(parameters.t(DVec2::X), 1., &format!("end point with dials ({start_dial}, {end_dial})")); + } + } + } + + #[test] + fn dials_reaching_a_line_or_a_point_change_the_gradient_continuously() { + let nudge = 1e-6; + for (dials, nearby_dials) in [ + // The start crossing the line, with the end a small circle + ([nudge, 0.8], [-nudge, 0.8]), + // The end crossing the line, with the start a small circle + ([0.8, nudge], [0.8, -nudge]), + // The start shrinking to a point inside the end circle, on either side of its center + ([1., 0.2], [1. - nudge, 0.2]), + ([1., 0.6], [1. - nudge, 0.6]), + // The end shrinking to a point outside the start circle + ([0.8, 1.], [0.8, 1. - nudge]), + ([0.8, -1.], [0.8, -1. + nudge]), + // The start's point from either side of the dial's wrap seam + ([1. - nudge, 0.2], [-1. + nudge, 0.2]), + ] { + let (parameters, nearby_parameters) = (PencilParameters::new(dials[0], dials[1]), PencilParameters::new(nearby_dials[0], nearby_dials[1])); + for x in -6..=10 { + for y in -8..=8 { + let point = DVec2::new(x as f64 * 0.25 + 0.013, y as f64 * 0.25 + 0.007); + + // Clamped as the padded ramp draws it + let (t, nearby_t) = (parameters.t(point).clamp(0., 1.), nearby_parameters.t(point).clamp(0., 1.)); + assert!((t - nearby_t).abs() < 1e-3, "dials {dials:?} against {nearby_dials:?} at {point}: {t} against {nearby_t}"); + } + } + } + } +} diff --git a/node-graph/libraries/vector-types/src/gradient.rs b/node-graph/libraries/vector-types/src/gradient.rs index bd4910c1621..c2955ef9445 100644 --- a/node-graph/libraries/vector-types/src/gradient.rs +++ b/node-graph/libraries/vector-types/src/gradient.rs @@ -17,6 +17,44 @@ 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, + } + } + + /// The form these curvature dials make, if either, once wrapped like [`wrapped_dial`]. + pub fn from_dials(dials: [f64; 2]) -> Option { + match dials.map(|dial| wrapped_dial(dial, f64::NAN)) { + LINEAR_DIALS => Some(Self::Linear), + RADIAL_DIALS => Some(Self::Radial), + _ => None, + } + } + + /// The dials a gradient of this form is drawn with, each wrapped like [`wrapped_dial`], taking the form's own where its curvature attribute is absent. + pub fn drawn_dials(self, start_curvature: Option, end_curvature: Option) -> [f64; 2] { + let [start_preset, end_preset] = self.dials(); + [ + wrapped_dial(start_curvature.unwrap_or(start_preset), start_preset), + wrapped_dial(end_curvature.unwrap_or(end_preset), end_preset), + ] + } +} + +/// 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`). @@ -2063,6 +2101,24 @@ impl core_types::bounds::BoundingBox for Gradient { mod tests { use super::*; + #[test] + fn dials_make_a_form_only_at_its_presets_once_wrapped() { + assert_eq!(GradientForm::from_dials([0., 0.]), Some(GradientForm::Linear)); + assert_eq!(GradientForm::from_dials([1., 0.5]), Some(GradientForm::Radial)); + assert_eq!(GradientForm::from_dials([-1., 0.5]), Some(GradientForm::Radial)); + assert_eq!(GradientForm::from_dials([3., 0.5]), Some(GradientForm::Radial)); + assert_eq!(GradientForm::from_dials([2., -2.]), Some(GradientForm::Linear)); + + assert_eq!(GradientForm::from_dials([0.5, 0.25]), None); + assert_eq!(GradientForm::from_dials([f64::NAN, 0.]), None); + assert_eq!(GradientForm::from_dials([f64::INFINITY, 0.5]), None); + + // Absent curvatures take the form's own, and present ones override it + assert_eq!(GradientForm::Radial.drawn_dials(None, None), RADIAL_DIALS); + assert_eq!(GradientForm::Radial.drawn_dials(Some(-1.), Some(0.)), [1., 0.]); + assert_eq!(GradientForm::Linear.drawn_dials(Some(f64::NAN), Some(0.25)), [0., 0.25]); + } + #[test] fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() { assert!(Gradient::default().is_empty()); diff --git a/node-graph/libraries/vector-types/src/lib.rs b/node-graph/libraries/vector-types/src/lib.rs index a025562eb0f..fed88c098d2 100644 --- a/node-graph/libraries/vector-types/src/lib.rs +++ b/node-graph/libraries/vector-types/src/lib.rs @@ -1,6 +1,7 @@ #[macro_use] extern crate log; +pub mod dial_gradient; pub mod gradient; pub mod math; pub mod vector; diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index a371bfc545e..6c8a9f329ef 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -369,6 +369,54 @@ fn degenerate_strokes_render() { let Some(_) = render(size, draw) else { return }; } +#[test] +fn dial_gradients_match_their_cpu_evaluation() { + use rendering::dial_gradient::{PencilParameters, PencilParametersExt}; + + 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), + (0.8, 1.), + (0.9, 0.2), + (0.9, 0.9), + (0.001, 0.8), + // The outer arc through infinity, with the band offset from the start and with the wrap's t negative + (0.9, 0.6), + (0.6, 1.), + ] { + 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, fill: f32, min: f64, max: f64, size: UVec2) -> Option> { render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size) @@ -3448,8 +3496,8 @@ fn captured_box_blurs_hold_their_results_for_svg_however_slight() { fn cpu_evaluated_effects_match_the_gpu_passes() { use core_types::Color as GraphicColor; use core_types::blending::BlendMode; - use core_types::list::ATTR_GRADIENT_FORM; use core_types::list::Item; + use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_START_CURVATURE}; use core_types::transfer_curve::TransferCurve; use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use glam::DVec2; @@ -3759,17 +3807,20 @@ fn cpu_evaluated_effects_match_the_gpu_passes() { blend_mode: BlendMode::Normal, opacity: 100., }); - let gradient = |form: GradientForm, transform: DAffine2| { + let gradient_item = |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)) + Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform) }; + let gradient = |form: GradientForm, transform: DAffine2| Graphic::from(gradient_item(transform).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.))); + // Curvature dials between the two forms, with contours filling in as a pencil of circles + let dialed = gradient_item(DAffine2::from_translation(DVec2::new(55., 70.)) * DAffine2::from_scale(DVec2::splat(30.))); + let dialed = Graphic::from(dialed.with_attribute(ATTR_GRADIENT_START_CURVATURE, 0.5).with_attribute(ATTR_GRADIENT_END_CURVATURE, 0.25)); // A checkerboard spanning the render from `start` to `end` with a pixel for each of the render's, so sampling it needs no interpolation let checkerboard = |start: u32, end: u32| { @@ -3810,11 +3861,13 @@ fn cpu_evaluated_effects_match_the_gpu_passes() { overlay(&linear, BlendMode::Normal, 40.), overlay(&radial, BlendMode::Multiply, 100.), overlay(&checker, BlendMode::Screen, 100.), + overlay(&dialed, BlendMode::Normal, 100.), ]); // Outlines drawn with paints placed on their own, the image covering the outline as well as the content paint_cases.extend([ vec![outline(linear.clone(), 6., StrokeAlign::Outside, false)], vec![outline(radial.clone(), 8., StrokeAlign::Center, false)], + vec![outline(dialed.clone(), 8., StrokeAlign::Center, false)], vec![outline(checkerboard(min - 10, max + 10), 9., StrokeAlign::Center, false)], ]); // Bevels with gloss contours, contours, and textures @@ -3935,6 +3988,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() { vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)], vec![mask(&linear, MaskMode::Luminance, 100., 6., false)], vec![mask(&radial, MaskMode::Alpha, 100., 0., false)], + vec![mask(&dialed, MaskMode::Luminance, 100., 0., false)], vec![mask(&mask_image, MaskMode::Luminance, 100., 2., false), mask_shadow.clone()], vec![mask_shadow.clone(), mask(&linear, MaskMode::Luminance, 80., 0., true)], vec![blur(2., false, false), mask(&radial, MaskMode::Luminance, 100., 1.5, false), mask_shadow.clone()], diff --git a/node-graph/nodes/math/src/lib.rs b/node-graph/nodes/math/src/lib.rs index 89a5b02ba57..552902f8ecd 100644 --- a/node-graph/nodes/math/src/lib.rs +++ b/node-graph/nodes/math/src/lib.rs @@ -1922,11 +1922,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_form: Item) -> Item { +/// 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"), version(2))] +fn gradient_curvature( + _: impl Ctx, + gradient: Item, + /// The curve of the contour through the start. + #[range] + #[soft(-1..1)] + start_curvature: Item, + /// The curve of the contour through the end. + #[range] + #[soft(-1..1)] + end_curvature: Item, +) -> Item { 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 }