Compare commits

...
30 changed files with 1666 additions and 167 deletions

No files matched your search

Generated
+3 -3
View File
@@ -8084,7 +8084,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
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=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
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=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
source = "git+https://github.com/Keavon/vello.git?rev=4b584f7f16f00c155c47d3980deea419d5c89f0a#4b584f7f16f00c155c47d3980deea419d5c89f0a"
dependencies = [
"naga",
"wesl",
+3 -3
View File
@@ -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 = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4b584f7f16f00c155c47d3980deea419d5c89f0a" }
@@ -0,0 +1,63 @@
use migration_core::{Inputs, NodeInput, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
GradientModel(GradientModel),
GradientDirection(GradientDirection),
}
#[derive(Serialize, Deserialize)]
enum GradientModel {
Standard,
}
#[derive(Serialize, Deserialize)]
enum GradientDirection {
Along,
}
/// 'Fill' gained the model and direction it gives the gradient it paints, set to the Standard model and the Along direction a gradient without them already has.
#[migration("graphene_core::vector::FillNode"@2 => @3)]
pub fn fill_v2(inputs: &mut Inputs) {
for input in added_inputs() {
inputs.push(input);
}
}
/// The model and the direction.
fn added_inputs() -> [NodeInput; 2] {
[literal(Tagged::GradientModel(GradientModel::Standard)), literal(Tagged::GradientDirection(GradientDirection::Along))]
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&FillV2, &contract());
check_undo(&FillV2, &contract());
}
#[test]
fn keeps_the_inputs_and_adds_the_default_model_and_direction() {
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
let mut fixture = Fixture::new(&FillV2);
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@2), inputs.clone());
let migrated = fixture.migrate(&FillV2).unwrap();
let mut expected = inputs;
expected.extend(added_inputs());
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@3)));
assert_eq!(fixture.inputs(&migrated, fill), expected);
}
}
@@ -1,6 +1,7 @@
//! Migrations of the nodes in `graphene_core`.
mod fill_v1;
mod fill_v2;
mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_upload_texture_node;
mod renames;
@@ -31,8 +31,8 @@ use graphene_std::vector::misc::{
WeldMethod,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
StrokeJoin,
DashPattern, FillChoice, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign,
StrokeCap, StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{
@@ -470,6 +470,7 @@ macro_rules! inspectable_types {
Item<BlendMode>,
Item<GradientForm>,
Item<GradientModel>,
Item<GradientDirection>,
Item<GradientSpread>,
Item<GradientSpace>,
Item<GradientHueDirection>,
@@ -1286,6 +1287,7 @@ impl_table_item_layout_for_choice_enum!(
MinimumMaximumMode,
GradientForm,
GradientModel,
GradientDirection,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -1482,6 +1484,7 @@ macro_rules! known_item_types {
BlendMode,
GradientForm,
GradientModel,
GradientDirection,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -7,7 +7,7 @@ use graph_craft::document::NodeId;
use graphene_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, VectorModificationType};
use std::sync::Arc;
@@ -62,6 +62,14 @@ pub enum GraphOperationMessage {
/// The start and end curvatures.
curvatures: [f64; 2],
},
GradientModelSet {
layer: LayerNodeIdentifier,
model: GradientModel,
},
GradientDirectionSet {
layer: LayerNodeIdentifier,
direction: GradientDirection,
},
GradientSpreadSet {
layer: LayerNodeIdentifier,
gradient_spread: GradientSpread,
@@ -91,6 +91,16 @@ impl MessageHandler<GraphOperationMessage, GraphOperationMessageContext<'_>> for
modify_inputs.gradient_curvature_set(curvatures);
}
}
GraphOperationMessage::GradientModelSet { layer, model } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_model_set(model);
}
}
GraphOperationMessage::GradientDirectionSet { layer, direction } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_direction_set(direction);
}
}
GraphOperationMessage::GradientSpreadSet { layer, gradient_spread } => {
if let Some(mut modify_inputs) = ModifyInputsContext::new_with_layer(layer, network_interface, responses) {
modify_inputs.gradient_spread_set(gradient_spread);
@@ -16,7 +16,7 @@ use graph_craft::document::{NodeId, NodeInput};
use graph_craft::{ProtoNodeIdentifier, list};
use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::style::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSettings, GradientSpace, GradientSpread, PaintOrder, Stroke};
use graphene_std::vector::{Gradient, GradientRamp, Vector, VectorModification, VectorModificationType};
use graphene_std::{Artboard, Color, Graphic};
use kurbo::BezPath;
@@ -820,6 +820,55 @@ impl<'a> ModifyInputsContext<'a> {
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
/// Set the model of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
pub fn gradient_model_set(&mut self, model: GradientModel) {
use graphene_std::NodeParameter;
use graphene_std::math_nodes::gradient_model;
let value = TaggedValue::GradientModel(model);
let fill_input = graphene_std::vector::fill::ModelInput::INDEX;
self.gradient_choice_set(fill_input, gradient_model::IDENTIFIER, gradient_model::ModelInput::INDEX, value, model == GradientModel::default());
}
/// Set the direction of the layer's gradient, as [`Self::gradient_choice_set`] sets a choice.
pub fn gradient_direction_set(&mut self, direction: GradientDirection) {
use graphene_std::NodeParameter;
use graphene_std::math_nodes::gradient_direction;
let value = TaggedValue::GradientDirection(direction);
let fill_input = graphene_std::vector::fill::DirectionInput::INDEX;
self.gradient_choice_set(
fill_input,
gradient_direction::IDENTIFIER,
gradient_direction::DirectionInput::INDEX,
value,
direction == GradientDirection::default(),
);
}
/// Set a choice of how the layer's gradient is drawn: in the Fill node's input at `fill_input` where the Fill holds the gradient as a value, or else in the input at
/// `node_input` of the last node of this `identifier` in the chain, inserting one only for a value other than the default. A choice the graph feeds is left as it is.
fn gradient_choice_set(&mut self, fill_input: usize, identifier: ProtoNodeIdentifier, node_input: usize, value: TaggedValue, is_default: bool) {
let Some(output_layer) = self.get_output_layer() else { return };
let (node_id, input_index) = match get_fill_node_id_with_direct_fill_input(output_layer, self.network_interface) {
Some(fill_node_id) => (fill_node_id, fill_input),
None => {
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, !is_default) else {
return;
};
(node_id, node_input)
}
};
let node = self.network_interface.document_network().nodes.get(&node_id);
let current = node.and_then(|node| node.inputs.get(input_index)).and_then(NodeInput::as_non_exposed_value);
if current.is_some_and(|current| *current != value) {
self.set_input_with_refresh(InputConnector::node_at_index(node_id, input_index), NodeInput::value(value, false), false);
}
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
pub fn gradient_spread_set(&mut self, gradient_spread: GradientSpread) {
let Some(output_layer) = self.get_output_layer() else { return };
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
};
use graphene_std::vector::style::{
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
FillChoice, Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops,
StrokeAlign, StrokeCap, StrokeJoin, build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
@@ -435,6 +435,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// =========================
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientDirection>(x) => enum_choice::<GradientDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
assert_eq!(fill_node.inputs.len(), 10, "the legacy Fill should upgrade to the 10-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
@@ -1033,7 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
let fill_node = &network.nodes[&node_id];
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
assert_eq!(fill_node.inputs.len(), 10, "the eight-input Fill should come out in the modern 10-input shape");
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
assert_eq!(
curvatures,
@@ -5663,8 +5663,19 @@ mod tests {
let node = &document.network_interface.document_network().nodes[&fill_id];
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
assert_eq!(values, expected, "the form should become its curvatures before the placement");
let expected = [
TaggedValue::Number(-1.),
TaggedValue::Number(0.5),
TaggedValue::Bool(true),
TaggedValue::DAffine2(placement),
TaggedValue::GradientModel(Default::default()),
TaggedValue::GradientDirection(Default::default()),
]
.map(Some);
assert_eq!(
values, expected,
"the form should become its curvatures before the placement, followed by the default model and direction"
);
}
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
@@ -5709,6 +5720,7 @@ mod tests {
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_DIRECTION),
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
)),
_ => None,
@@ -5749,7 +5761,7 @@ mod tests {
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
let mut old_inputs = NodeTemplate {
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
inputs: [&inputs[..4], &[form], &inputs[6..8]].concat(),
..Default::default()
};
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
@@ -11,7 +11,7 @@ use graphene_std::Color;
use graphene_std::raster::BlendMode;
use graphene_std::text::{Font, TypesettingConfig};
use graphene_std::vector::misc::ManipulatorPointId;
use graphene_std::vector::style::{FillChoice, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::style::{FillChoice, GradientDirection, GradientModel, PaintOrder, StrokeAlign, StrokeCap, StrokeJoin, initial_gradient_transform_for_bounding_box};
use graphene_std::vector::{Gradient, GradientForm, GradientRamp, GradientSettings, PointId, SegmentId, VectorModificationType};
use graphene_std::{NodeParameter, ParameterRef};
use std::collections::VecDeque;
@@ -859,6 +859,9 @@ pub struct FillNodeGradient {
pub curvatures: Option<[f64; 2]>,
/// The form its curvatures make, which is linear for any that make neither.
pub gradient_form: GradientForm,
/// Its model and direction, each unless the graph feeds it.
pub model: Option<GradientModel>,
pub direction: Option<GradientDirection>,
pub settings: GradientSettings,
pub transform: DAffine2,
/// Whether the transform input holds a plain value (so it may be written to) rather than a wire.
@@ -876,6 +879,14 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
let stops = Gradient::from(ramp);
let curvatures = fill_node_curvatures(fill_node);
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
let model = match fill_node.input(fill::ModelInput).and_then(NodeInput::as_non_exposed_value) {
Some(&TaggedValue::GradientModel(model)) => Some(model),
_ => None,
};
let direction = match fill_node.input(fill::DirectionInput).and_then(NodeInput::as_non_exposed_value) {
Some(&TaggedValue::GradientDirection(direction)) => Some(direction),
_ => None,
};
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
let transform = match (has_transform, transform_input) {
@@ -888,6 +899,8 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
stops,
curvatures,
gradient_form,
model,
direction,
settings,
transform,
transform_is_value: transform_input.is_some(),
@@ -23,7 +23,9 @@ use graph_craft::document::value::TaggedValue;
use graphene_std::color::SRGBA8;
use graphene_std::raster::color::Color;
use graphene_std::vector::gradient_standard::{curvature_radius, radius_curvature};
use graphene_std::vector::style::{FillChoice, Gradient, GradientForm, GradientInterpolation, GradientRamp, GradientSettings, GradientStop, build_transform_with_y_preservation, wrapped_curvature};
use graphene_std::vector::style::{
FillChoice, Gradient, GradientDirection, GradientForm, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientStop, build_transform_with_y_preservation, wrapped_curvature,
};
#[derive(Default, ExtractField)]
pub struct GradientTool {
@@ -38,6 +40,12 @@ pub struct GradientOptions {
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
curvature_source: CurvatureSource,
settings: GradientSettings,
/// The selected gradient's model and direction, or with none selected, those a new gradient gets.
model: GradientModel,
direction: GradientDirection,
/// Whether the graph feeds the selected gradient's model or direction, so only the graph can change it.
model_from_graph: bool,
direction_from_graph: bool,
}
#[impl_message(Message, ToolMessage, Gradient)]
@@ -71,6 +79,8 @@ pub enum GradientToolMessage {
#[derive(PartialEq, Eq, Clone, Debug, Hash, serde::Serialize, serde::Deserialize)]
pub enum GradientOptionsUpdate {
Form(GradientForm),
Model(GradientModel),
Direction(GradientDirection),
ReverseStops,
ReverseDirection,
}
@@ -115,6 +125,28 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
responses.add(ToolMessage::UpdateHints);
responses.add(ToolMessage::UpdateCursor);
}
GradientOptionsUpdate::Model(model) => {
self.options.model = model;
apply_gradient_choice(
&mut self.data,
context,
responses,
|appearance| appearance.model.is_some_and(|current| current != model),
|appearance| appearance.model = appearance.model.map(|_| model),
|layer| GraphOperationMessage::GradientModelSet { layer, model }.into(),
);
}
GradientOptionsUpdate::Direction(direction) => {
self.options.direction = direction;
apply_gradient_choice(
&mut self.data,
context,
responses,
|appearance| appearance.direction.is_some_and(|current| current != direction),
|appearance| appearance.direction = appearance.direction.map(|_| direction),
|layer| GraphOperationMessage::GradientDirectionSet { layer, direction }.into(),
);
}
GradientOptionsUpdate::ReverseStops => {
apply_gradient_update(
&mut self.data,
@@ -214,9 +246,18 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
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
let (model, direction) = (appearance.model.unwrap_or(self.options.model), appearance.direction.unwrap_or(self.options.direction));
let (model_from_graph, direction_from_graph) = (appearance.model.is_none(), appearance.direction.is_none());
if (self.options.model, self.options.direction, self.options.model_from_graph, self.options.direction_from_graph) != (model, direction, model_from_graph, direction_from_graph) {
(self.options.model, self.options.direction) = (model, direction);
(self.options.model_from_graph, self.options.direction_from_graph) = (model_from_graph, direction_from_graph);
needs_refresh = true;
}
} else if self.options.curvature_source != CurvatureSource::Form || self.options.model_from_graph || self.options.direction_from_graph {
// With no gradient selected, the radios show what a new one gets
self.options.curvature_source = CurvatureSource::Form;
(self.options.model_from_graph, self.options.direction_from_graph) = (false, false);
needs_refresh = true;
}
@@ -333,6 +374,38 @@ impl LayoutHolder for GradientTool {
})
.widget_instance();
let direction_entries = RadioEntryData::list_from_choice_type(|direction| {
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::Direction(direction),
}
.into()
});
let direction = RadioInput::new(direction_entries)
.selected_index((!self.options.direction_from_graph).then_some(self.options.direction as u32))
.disabled(self.options.direction_from_graph)
.widget_instance();
// Each model draws the forms and end circles sharing a center alike, which its tooltip says since it stays enabled for them
let model_entries = RadioEntryData::list_from_choice_type(|model| {
GradientToolMessage::UpdateOptions {
options: GradientOptionsUpdate::Model(model),
}
.into()
})
.into_iter()
.map(|entry| {
let description = format!(
"{}\n\nThe linear and radial forms, and end circles sharing a center, look the same in either model.",
entry.tooltip_description
);
entry.tooltip_description(description)
})
.collect();
let model = RadioInput::new(model_entries)
.selected_index((!self.options.model_from_graph).then_some(self.options.model as u32))
.disabled(self.options.model_from_graph)
.widget_instance();
widgets.extend([
stops_widget,
Separator::new(SeparatorStyle::Related).widget_instance(),
@@ -341,6 +414,10 @@ impl LayoutHolder for GradientTool {
gradient_form,
Separator::new(SeparatorStyle::Related).widget_instance(),
reverse_direction,
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
direction,
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
model,
]);
Layout(vec![LayoutGroup::row(widgets)])
@@ -410,6 +487,8 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
gradient_form,
curvature_source,
curvatures: drawn_curvatures(gradient.curvatures, gradient_form),
model: gradient.model,
direction: gradient.direction,
settings: gradient.settings,
transform: gradient.transform,
transform_is_wired: !gradient.transform_is_value,
@@ -437,6 +516,9 @@ struct GradientAppearance {
curvature_source: CurvatureSource,
/// The start and end curvatures it's drawn with, each wrapped into the range starting at -1. Those of its form when fed from the graph.
curvatures: [f64; 2],
/// Its model and direction, each unless the graph feeds it.
model: Option<GradientModel>,
direction: Option<GradientDirection>,
settings: GradientSettings,
}
@@ -489,11 +571,16 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let gradient_model_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_model::IDENTIFIER);
let gradient_direction_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_direction::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
let mut curvature_source = CurvatureSource::Form;
let mut curvatures: Option<[f64; 2]> = None;
// The most downstream enabled node of each sets the model and direction, each `None` where the graph feeds its value
let mut model: Option<Option<GradientModel>> = None;
let mut direction: Option<Option<GradientDirection>> = None;
for node_id in network_interface
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
@@ -511,6 +598,23 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
curvatures = graph_modification_utils::gradient_curvature_values(document_node);
let (form, source) = CurvatureSource::of(curvatures);
(gradient_form, curvature_source) = (Some(form), source);
} else if reference == gradient_model_reference && model.is_none() && network_interface.is_visible(&node_id, &[]) {
model = Some(
match document_node.input(graphene_std::math_nodes::gradient_model::ModelInput).and_then(|input| input.as_non_exposed_value()) {
Some(&TaggedValue::GradientModel(value)) => Some(value),
_ => None,
},
);
} else if reference == gradient_direction_reference && direction.is_none() && network_interface.is_visible(&node_id, &[]) {
direction = Some(
match document_node
.input(graphene_std::math_nodes::gradient_direction::DirectionInput)
.and_then(|input| input.as_non_exposed_value())
{
Some(&TaggedValue::GradientDirection(value)) => Some(value),
_ => None,
},
);
}
}
@@ -524,6 +628,8 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
gradient_form,
curvature_source,
curvatures: drawn_curvatures(curvatures, gradient_form),
model: model.unwrap_or(Some(GradientModel::default())),
direction: direction.unwrap_or(Some(GradientDirection::default())),
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
}
}
@@ -1252,6 +1358,11 @@ impl SelectedGradient {
curvatures: self.appearance.curvatures,
});
}
// Likewise, only a new gradient takes its model and direction from the tool
if self.dragging == GradientDragTarget::New {
dispatch_model_and_direction_writes(layer, self.appearance, responses);
}
}
}
@@ -1278,6 +1389,16 @@ impl SelectedGradient {
}
}
/// Write a gradient's model and direction, each unless the graph feeds it, to the Fill node holding it or the chain feeding the layer.
fn dispatch_model_and_direction_writes(layer: LayerNodeIdentifier, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
if let Some(model) = appearance.model {
responses.add(GraphOperationMessage::GradientModelSet { layer, model });
}
if let Some(direction) = appearance.direction {
responses.add(GraphOperationMessage::GradientDirectionSet { layer, direction });
}
}
/// 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<Message>) {
responses.add(GraphOperationMessage::GradientCyclicSet {
@@ -2051,6 +2172,8 @@ impl Fsm for GradientToolFsmState {
gradient_form: tool_options.gradient_form,
curvature_source: CurvatureSource::Form,
curvatures: tool_options.gradient_form.curvatures(),
model: Some(tool_options.model),
direction: Some(tool_options.direction),
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
@@ -2524,6 +2647,7 @@ fn apply_gradient_update(
transform: Some(appearance.transform),
});
}
dispatch_model_and_direction_writes(layer, appearance, responses);
}
}
@@ -2541,6 +2665,50 @@ fn apply_gradient_update(
responses.add(ToolMessage::RefreshToolOptions);
}
/// Set a choice of how each selected layer's gradient is drawn in one history step, sending `message` for each gradient whose choice `differs` while leaving its other
/// attributes as they are, and making the same choice with `update` for the gradient being edited.
fn apply_gradient_choice(
data: &mut GradientToolData,
context: &mut ToolActionMessageContext,
responses: &mut VecDeque<Message>,
differs: impl Fn(&GradientAppearance) -> bool,
update: impl Fn(&mut GradientAppearance),
message: impl Fn(LayerNodeIdentifier) -> Message,
) {
let selected_layers: Vec<_> = context
.document
.network_interface
.selected_nodes()
.selected_visible_layers(&context.document.network_interface)
.collect();
let mut transaction_started = false;
for layer in selected_layers {
if NodeGraphLayer::is_raster_layer(layer, &mut context.document.network_interface) {
continue;
}
if let Some((_, appearance, _)) = resolve_gradient(layer, &context.document.network_interface)
&& differs(&appearance)
{
if !transaction_started {
responses.add(DocumentMessage::StartTransaction);
transaction_started = true;
}
responses.add(message(layer));
}
}
if transaction_started {
responses.add(DocumentMessage::EndTransaction);
}
if let Some(selected_gradient) = &mut data.selected_gradient {
update(&mut selected_gradient.appearance);
}
responses.add(InspectorMessage::Refresh);
responses.add(ToolMessage::RefreshToolOptions);
}
/// Set new gradient stops on every selected layer's gradient. Unlike `apply_gradient_update`, this doesn't open its own
/// transaction so it can be called repeatedly during a color picker drag and have all the changes coalesced into a
/// single undo entry by the surrounding 'on_commit' callback.
@@ -2707,7 +2875,7 @@ mod test_gradient {
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};
use graphene_std::vector::style::{GradientDirection, GradientForm, GradientModel, GradientSpread, build_transform_with_y_preservation};
use graphene_std::vector::style::{GradientHueDirection, GradientInterpolation, GradientSettings, GradientSpace};
use graphene_std::vector::{Gradient, GradientRamp, GradientStop, fill};
@@ -4254,8 +4422,13 @@ mod test_gradient {
/// 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<u32>, bool)> {
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
latest_radio(frontend_messages, "Linear")
}
/// The chosen entry and whether it's disabled of the radio whose first entry is `first_entry`, as last sent to the control bar among these frontend messages.
fn latest_radio(frontend_messages: &[FrontendMessage], first_entry: &str) -> Option<(Option<u32>, bool)> {
let radio = |widget: &WidgetInstance| match &*widget.widget {
Widget::RadioInput(radio_input) if radio_input.entries.first().is_some_and(|entry| entry.value == first_entry) => Some((radio_input.selected_index, radio_input.disabled)),
_ => None,
};
@@ -4271,9 +4444,9 @@ mod test_gradient {
})
.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),
DiffUpdate::Widget(widget) => radio(widget),
DiffUpdate::Layout(layout) => layout.iter().find_map(radio),
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(radio),
})
}
@@ -5067,6 +5240,229 @@ mod test_gradient {
assert_stops_at_positions(&fill_stop_positions(&mut editor).await, &[0., 0.5 + 1. / 190., 1.], 1e-6);
}
/// Draws a rectangle and a gradient across it with the Gradient tool, returning the rectangle's layer and the Fill node holding the gradient.
async fn fill_gradient_rectangle(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
editor.active_document_mut().snapping_state.snapping_enabled = false;
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
let document = editor.active_document();
let layer = document
.network_interface
.selected_nodes()
.selected_layers(document.metadata())
.next()
.expect("the rectangle is selected");
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
(layer, fill_id)
}
/// A Fill node's model and direction inputs.
fn fill_model_and_direction(editor: &EditorTestUtils, fill_id: NodeId) -> [Option<NodeInput>; 2] {
use graphene_std::vector::fill::{DirectionInput, ModelInput};
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
[node.input(ModelInput).cloned(), node.input(DirectionInput).cloned()]
}
/// The model and direction inputs holding these values.
fn model_and_direction_holding(model: GradientModel, direction: GradientDirection) -> [Option<NodeInput>; 2] {
[TaggedValue::GradientModel(model), TaggedValue::GradientDirection(direction)].map(|value| Some(NodeInput::value(value, false)))
}
fn choose_model(model: GradientModel) -> GradientToolMessage {
GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Model(model),
}
}
fn choose_direction(direction: GradientDirection) -> GradientToolMessage {
GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Direction(direction),
}
}
#[tokio::test]
async fn the_model_and_direction_set_a_fill_gradients_own_inputs_in_a_history_step_each() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (_, fill_id) = fill_gradient_rectangle(&mut editor).await;
assert_eq!(
fill_model_and_direction(&editor, fill_id),
model_and_direction_holding(GradientModel::Standard, GradientDirection::Along)
);
editor.handle_message(choose_direction(GradientDirection::Across)).await;
editor.handle_message(choose_model(GradientModel::Apollonian)).await;
assert_eq!(
fill_model_and_direction(&editor, fill_id),
model_and_direction_holding(GradientModel::Apollonian, GradientDirection::Across)
);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
fill_model_and_direction(&editor, fill_id),
model_and_direction_holding(GradientModel::Standard, GradientDirection::Across),
"undoing should take back only the model"
);
editor.handle_message(DocumentMessage::Undo).await;
assert_eq!(
fill_model_and_direction(&editor, fill_id),
model_and_direction_holding(GradientModel::Standard, GradientDirection::Along)
);
}
#[tokio::test]
async fn the_model_and_direction_insert_chain_nodes_only_for_other_values_than_the_defaults() {
use graphene_std::math_nodes::{gradient_direction, gradient_model};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = create_gradient_list_layer(&mut editor).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
// The value held by the input of the one node of this kind, if the graph has one
let held = |editor: &EditorTestUtils, identifier, input_index: usize| {
let network_interface = &editor.active_document().network_interface;
let reference = DefinitionIdentifier::ProtoNode(identifier);
let mut nodes = network_interface
.document_network()
.nodes
.iter()
.filter(|(node_id, _)| network_interface.reference(node_id, &[]).as_ref() == Some(&reference));
nodes.next().and_then(|(_, node)| node.inputs[input_index].as_value().cloned())
};
let direction_held = |editor: &EditorTestUtils| held(editor, gradient_direction::IDENTIFIER, 1);
let model_held = |editor: &EditorTestUtils| held(editor, gradient_model::IDENTIFIER, 1);
editor.handle_message(choose_direction(GradientDirection::Along)).await;
editor.handle_message(choose_model(GradientModel::Standard)).await;
assert_eq!((direction_held(&editor), model_held(&editor)), (None, None), "the defaults need no nodes");
editor.handle_message(choose_direction(GradientDirection::Across)).await;
editor.handle_message(choose_model(GradientModel::Apollonian)).await;
assert_eq!(direction_held(&editor), Some(TaggedValue::GradientDirection(GradientDirection::Across)));
assert_eq!(model_held(&editor), Some(TaggedValue::GradientModel(GradientModel::Apollonian)));
// Back at the default, the node stays and holds it
editor.handle_message(choose_direction(GradientDirection::Along)).await;
assert_eq!(direction_held(&editor), Some(TaggedValue::GradientDirection(GradientDirection::Along)));
}
#[tokio::test]
async fn choosing_a_model_or_direction_leaves_the_gradients_wired_placement_alone() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = create_gradient_list_layer(&mut editor).await;
editor
.handle_message(GraphOperationMessage::GradientTransformSet {
layer,
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
})
.await;
// The placement's translation fed by a wire, which only the graph may change
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let network_interface = &editor.active_document().network_interface;
let transform_node_id = network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&transform_reference))
.expect("a 'Transform' node should place the gradient");
let vec2_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(vec2_node_id),
input_connector: InputConnector::node_at_index(transform_node_id, 1),
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor.handle_message(choose_direction(GradientDirection::Across)).await;
editor.handle_message(choose_model(GradientModel::Apollonian)).await;
let translation = &editor.active_document().network_interface.document_network().nodes[&transform_node_id].inputs[1];
assert!(matches!(translation, NodeInput::Node { .. }), "the wired translation should stay wired, not {translation:?}");
}
#[tokio::test]
async fn the_direction_radio_is_disabled_for_a_direction_fed_from_the_graph() {
use graphene_std::math_nodes::gradient_direction::{DirectionInput, IDENTIFIER};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let layer = create_gradient_list_layer(&mut editor).await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor.handle_message(choose_direction(GradientDirection::Across)).await;
// Exposing the inserted node's direction leaves it to the graph
let reference = DefinitionIdentifier::ProtoNode(IDENTIFIER);
let network_interface = &editor.active_document().network_interface;
let direction_node_id = network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&reference))
.expect("a 'Gradient Direction' node should have been inserted");
let input_connector = InputConnector::node(direction_node_id, DirectionInput);
let mut frontend_messages = editor
.handle_message(NodeGraphMessage::ExposeInput {
input_connector,
set_to_exposed: true,
start_transaction: false,
})
.await;
// The pointer moving over the canvas has the tool read the selected gradient again
let pointer_move = || GradientToolMessage::PointerMove {
constrain_axis: Key::Shift,
lock_angle: Key::Control,
};
frontend_messages.extend(editor.handle_message(pointer_move()).await);
assert_eq!(latest_radio(&frontend_messages, "Along"), Some((None, true)), "an exposed direction should leave the radio disabled");
assert_ne!(
latest_radio(&frontend_messages, "Standard").map(|(_, disabled)| disabled),
Some(true),
"the model radio should stay enabled"
);
// Choosing a direction leaves the exposed one as it is
editor.handle_message(choose_direction(GradientDirection::Along)).await;
let node = &editor.active_document().network_interface.document_network().nodes[&direction_node_id];
assert_eq!(
node.input(DirectionInput).and_then(NodeInput::as_value),
Some(&TaggedValue::GradientDirection(GradientDirection::Across))
);
// With nothing selected, the radio shows what a new gradient gets
let mut frontend_messages = editor.handle_message(DocumentMessage::DeselectAllLayers).await;
frontend_messages.extend(editor.handle_message(pointer_move()).await);
assert_eq!(latest_radio(&frontend_messages, "Along"), Some((Some(GradientDirection::Along as u32), false)));
}
#[tokio::test]
async fn with_nothing_selected_the_model_and_direction_are_what_new_gradients_get() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.select_tool(ToolType::Gradient).await;
editor.handle_message(choose_direction(GradientDirection::Across)).await;
editor.handle_message(choose_model(GradientModel::Apollonian)).await;
let (_, fill_id) = fill_gradient_rectangle(&mut editor).await;
assert_eq!(
fill_model_and_direction(&editor, fill_id),
model_and_direction_holding(GradientModel::Apollonian, GradientDirection::Across)
);
}
#[tokio::test]
async fn drag_on_blank_layer_starts_gradient_chain() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
@@ -571,6 +571,7 @@ tagged_value! {
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm),
GradientModel(vector::style::GradientModel),
GradientDirection(vector::style::GradientDirection),
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
GradientSpread(vector::style::GradientSpread),
GradientSpace(vector::style::GradientSpace),
@@ -26,7 +26,9 @@ use graphene_std::vector::misc::{
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
WeldMethod,
};
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{
DashPattern, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
@@ -271,6 +273,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
StrokeCap,
GradientForm,
GradientModel,
GradientDirection,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -516,6 +519,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(Item<BlendMode>),
attribute_value_node!(Item<GradientForm>),
attribute_value_node!(Item<GradientModel>),
attribute_value_node!(Item<GradientDirection>),
attribute_value_node!(Item<GradientSpread>),
attribute_value_node!(Item<GradientSpace>),
attribute_value_node!(Item<GradientHueDirection>),
+3 -3
View File
@@ -33,9 +33,9 @@ pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
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,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
ATTR_GRADIENT_MODEL, 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;
@@ -67,6 +67,8 @@ pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
/// Gradient's `GradientDirection` (`Along` or `Across`), whether its colors run from one end contour to the other or around each contour. Absent, it's `Along`.
pub const ATTR_GRADIENT_DIRECTION: &str = "gradient_direction";
/// 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
@@ -10,8 +10,8 @@ use core_types::none;
use core_types::ops::FromAnchorPosition;
use core_types::transform::Transform;
use core_types::{
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
Color,
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY,
ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color,
};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
@@ -19,7 +19,7 @@ use raster_types::{CPU, GPU, Raster};
pub use vector_types::Vector;
use vector_types::gradient_standard::GradientShape;
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
use vector_types::{Gradient, GradientModel, GradientSpread};
use vector_types::{Gradient, GradientDirection, GradientModel, GradientSpread};
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
@@ -859,6 +859,7 @@ fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
read::<GradientDirection>(attribute, ATTR_GRADIENT_DIRECTION).copied().unwrap_or_default(),
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
)
.paints_everywhere()
@@ -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_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, 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};
@@ -1510,6 +1510,7 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
placement,
);
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
@@ -1536,6 +1537,10 @@ fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Optio
let to_unit = to_unit?;
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
}
GradientShape::Across(across) => {
let to_unit = to_unit?;
Some(Box::new(move |point| across.chart.v(to_unit.transform_point2(point))))
}
}
}
@@ -1622,6 +1627,33 @@ mod tests {
assert!(alpha_at(5, 5) > 0.9, "{}", alpha_at(5, 5));
}
#[test]
fn gradients_read_across_their_contours_take_positions_around_them() {
use std::f64::consts::TAU;
use vector_types::gradient::GradientDirection;
// A sheared placement, which the linear form read across its line follows in full
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
let across = |[start, end]: [f64; 2]| {
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_TRANSFORM, placement)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end)
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
};
let (Some(linear), Some(radial)) = (gradient_position(&across([0., 0.])), gradient_position(&across([-1., 0.5]))) else {
panic!("both forms should be read across their contours");
};
for unit in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.7), DVec2::new(0.9, -0.4)] {
let point = placement.transform_point2(unit);
assert!(linear(point).is_some_and(|v| (v - unit.y).abs() < 1e-9), "linear at {unit}");
let angle = unit.y.atan2(unit.x).rem_euclid(TAU) / TAU;
assert!(radial(point).is_some_and(|v| (v - angle).abs() < 1e-9), "radial at {unit}");
}
}
#[test]
fn image_paints_fade_by_their_fill_once_with_effects_of_their_own() {
use graphic_types::EffectKind;
@@ -105,7 +105,7 @@ fn render_gradient_paint(
let shape = gradient_shape(item);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
let mut samples = spread_adjusted_samples(&stops, settings, shape);
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = item.paint_opacity(for_mask);
+226 -62
View File
@@ -21,7 +21,7 @@ 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_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE,
ATTR_EFFECTS, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL, 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,
};
@@ -37,6 +37,7 @@ use graphic_types::masks::{MaskMode, masked_radius_blur_levels};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::resampling::{EffectFrame, frame_of_bounds};
use graphic_types::vector_types::gradient::{Gradient, GradientForm};
use graphic_types::vector_types::gradient_across::{AcrossChart, GradientAcross};
use graphic_types::vector_types::gradient_apollonian::{AxisCircle, CrossingSelection, GradientApollonian};
use graphic_types::vector_types::gradient_standard::{AxisRamp, Cone, GradientShape, GradientStandard, HalfPlane, RampEnd};
use graphic_types::vector_types::vector::click_target::{ClickTarget, FreePoint, TargetPath};
@@ -3094,12 +3095,13 @@ fn transform_relative_to(reference: DAffine2, transform: DAffine2) -> DAffine2 {
}
}
/// How a gradient item's contours are laid out, decided by its curvatures and model.
/// How a gradient item's contours are laid out, decided by its curvatures and model, and which way its colors run.
pub(crate) fn gradient_shape(item: ItemRef<'_, Gradient>) -> GradientShape {
GradientShape::new(
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
item.attribute_cloned_or_default(ATTR_GRADIENT_DIRECTION),
item.attribute_cloned_or_default(ATTR_TRANSFORM),
)
}
@@ -3112,7 +3114,7 @@ pub(crate) fn gradient_draws_masked(item: ItemRef<'_, Gradient>) -> bool {
/// How SVG draws a gradient of this shape when it isn't one of the forms: as SVG 2 draws its curvatures, or under the Apollonian model, as its stand-in where no image the GPU renders replaces it.
pub(crate) fn svg_gradient_standard(shape: GradientShape) -> Option<GradientStandard> {
match shape {
GradientShape::Linear | GradientShape::Radial => None,
GradientShape::Linear | GradientShape::Radial | GradientShape::Across(_) => None,
GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => Some(gradient),
}
}
@@ -3156,11 +3158,12 @@ type GradientSamples = Vec<(f64, Color, Option<f64>)>;
/// The gradient's renderable samples, bracketed for the `Clear` spread (which neither SVG nor Vello supports natively) by transparent guard stops.
///
/// The guards share the unit range's end offsets, ordered so the pad extension paints transparency outward while the later
/// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. 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 {
/// of each pair of coincident stops cuts the paint off exactly at the range's boundaries. The guard at either end is left out
/// when the position of a gradient of this `shape` can't reach past it.
pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSettings, shape: GradientShape) -> GradientSamples {
let samples = gradient.interpolated_samples(settings);
if settings.spread != GradientSpread::Clear {
let (reaches_before_start, reaches_past_end) = (shape.reaches_before_start(), shape.reaches_past_end());
if settings.spread != GradientSpread::Clear || !(reaches_before_start || reaches_past_end) {
return samples;
}
@@ -3186,7 +3189,9 @@ pub(crate) fn spread_adjusted_samples(gradient: &Gradient, settings: GradientSet
if needs_end_anchor {
adjusted.push((1., last_color, None));
}
adjusted.push((1., Color::TRANSPARENT, None));
if reaches_past_end {
adjusted.push((1., Color::TRANSPARENT, None));
}
adjusted
}
@@ -3224,6 +3229,18 @@ fn unit_gradient_kind(gradient_form: GradientForm) -> peniko::GradientKind {
}
}
/// The linear form read across its contours, in its own space before the brush transform places it: the line from the origin along +Y to 1.
fn across_linear_kind() -> peniko::GradientKind {
peniko::LinearGradientPosition {
start: kurbo::Point::ORIGIN,
end: kurbo::Point::new(0., 1.),
}
.into()
}
/// The geometry of [`across_linear_kind`] as an SVG linear gradient's.
const ACROSS_LINEAR_GEOMETRY: &str = r#" x1="0" y1="0" x2="0" y2="1""#;
/// The radius an end circle shrunk to a point is drawn with, since SVG paints a gradient ending in a circle of radius 0 as its last stop's color rather than the cone's limit.
const POINT_END_RADIUS: f64 = 1e-7;
@@ -3332,6 +3349,9 @@ pub(crate) fn write_svg_gradient_paint(
GradientShape::Linear => return unmasked(server(defs, "linearGradient", r#" x1="0" y1="0" x2="1" y2="0""#, &format!("{spread}{}", placed(transform)), stops)),
GradientShape::Radial => return unmasked(server(defs, "radialGradient", r#" cx="0" cy="0" r="1""#, &format!("{spread}{}", placed(transform)), stops)),
GradientShape::Standard(gradient) | GradientShape::Apollonian(GradientApollonian { svg_stand_in: gradient, .. }) => gradient,
GradientShape::Across(GradientAcross { chart: AcrossChart::Nothing, .. }) => return Vec::new(),
// Read across the gradient line like the linear form, exactly for it or as the stand-in where no image the GPU renders replaces the others
GradientShape::Across(_) => return unmasked(server(defs, "linearGradient", ACROSS_LINEAR_GEOMETRY, &format!("{spread}{}", placed(transform)), stops)),
};
let linear = |[x1, x2]: [f64; 2]| format!(r#" x1="{x1}" y1="0" x2="{x2}" y2="0""#);
@@ -3420,7 +3440,9 @@ fn peniko_extend(gradient_spread: GradientSpread) -> peniko::Extend {
enum GradientBrush {
Peniko(peniko::Brush),
/// Apollonian circles, which only Vello GPU's fork draws.
Apollonian(vello_gpu::PencilGradient),
Apollonian(vello_gpu::ApollonianGradient),
/// A position running around the contours, which only Vello GPU's fork draws.
Polar(vello_gpu::PolarGradient),
}
impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
@@ -3428,6 +3450,7 @@ impl<'b> From<&'b GradientBrush> for SceneBrush<'b> {
match brush {
GradientBrush::Peniko(brush) => brush.into(),
GradientBrush::Apollonian(gradient) => gradient.into(),
GradientBrush::Polar(gradient) => gradient.into(),
}
}
}
@@ -3472,22 +3495,7 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
let brush = |kind: peniko::GradientKind, stops: peniko::ColorStops, extend: peniko::Extend| GradientBrush::Peniko(peniko::Brush::Gradient(gradient(kind, stops, extend)));
let ramp = |kind: peniko::GradientKind| brush(kind, peniko_color_stops(samples), peniko_extend(spread));
let gradient = match shape {
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::PencilGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Standard(gradient) => gradient,
};
// Ramps along the gradient line are placed like the linear form, and circles by the full placement
// Ramps along the gradient line, and steps across it, are placed like the linear form
let desheared = desheared_placement(placement);
let linear = |[start, end]: [f64; 2]| -> peniko::GradientKind {
peniko::LinearGradientPosition {
@@ -3496,15 +3504,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
}
.into()
};
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let stops = |colors: &[(f32, Color)]| {
let stop = |&(offset, color): &(f32, Color)| peniko::ColorStop {
offset,
@@ -3512,7 +3511,6 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
};
peniko::ColorStops(colors.iter().map(stop).collect())
};
let end_color = |end| end_stop_color(samples, end);
// A step at `at` from one color to the other, as a unit-long gradient there with both stops at its start
let step = |at: f64, direction: f64, [before, after]: [Color; 2]| {
@@ -3520,6 +3518,79 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
(brush, rebased_transform(desheared, at))
};
// An eraser opaque wherever a layer kept to one side of a line across the gradient line is hidden
let eraser = |keep: HalfPlane| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
};
let gradient = match shape {
GradientShape::Linear => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Linear)), gradient_placement(placement, shape)), None)])),
GradientShape::Radial => return Some(VelloGradientPaint(vec![((ramp(unit_gradient_kind(GradientForm::Radial)), placement), None)])),
// Its contours come from its own geometry, so its ramp takes the linear kind, which goes unused
GradientShape::Apollonian(parameters) => {
let ramp = gradient(unit_gradient_kind(GradientForm::Linear), peniko_color_stops(samples), peniko_extend(spread));
let apollonian = vello_gpu::ApollonianGradient {
ramp,
geometry: apollonian_geometry(&parameters),
};
return Some(VelloGradientPaint(vec![((GradientBrush::Apollonian(apollonian), placement), None)]));
}
GradientShape::Across(GradientAcross { chart, .. }) => {
let polar = |geometry| {
let ramp = gradient(across_linear_kind(), peniko_color_stops(samples), peniko_extend(spread));
GradientBrush::Polar(vello_gpu::PolarGradient { ramp, geometry })
};
// The angle of `(numerator[0] z + numerator[1]) / (denominator[0] z + denominator[1])` with real coefficients
let mobius_angle = |numerator: [f64; 2], denominator: [f64; 2]| {
let real = |[slope, intercept]: [f64; 2]| [[slope as f32, 0.], [intercept as f32, 0.]];
let measure = vello_gpu::PolarMeasure::Angle;
polar(vello_gpu::PolarGeometry::Mobius {
numerator: real(numerator),
denominator: real(denominator),
measure,
})
};
let (brush, keep) = match chart {
AcrossChart::Nothing => return None,
AcrossChart::Linear => (ramp(across_linear_kind()), None),
// Vello's own sweep gradient, which Graphite builds without, measures the same angle as `z - center`
AcrossChart::Concentric { center } => (mobius_angle([1., -center], [0., 1.]), None),
AcrossChart::Cone { cone, keep } => (polar(cone_angle_geometry(cone)), keep),
AcrossChart::Mobius { numerator, denominator } => (mobius_angle(numerator, denominator), None),
// `(z - (center_x, -half_height)) / (z - (center_x, half_height))`
AcrossChart::Bipolar { center_x, half_height, scale } => {
let (center_x, half_height) = (center_x as f32, half_height as f32);
let geometry = vello_gpu::PolarGeometry::Mobius {
numerator: [[1., 0.], [-center_x, half_height]],
denominator: [[1., 0.], [-center_x, -half_height]],
measure: vello_gpu::PolarMeasure::LogModulus { scale: scale as f32, offset: 0. },
};
(polar(geometry), None)
}
};
return Some(VelloGradientPaint(vec![((brush, placement), keep.map(eraser))]));
}
GradientShape::Standard(gradient) => gradient,
};
// Circles are placed by the full placement
let radial = |cone: Cone| -> peniko::GradientKind {
peniko::RadialGradientPosition {
start_center: kurbo::Point::new(cone.start_center, 0.),
start_radius: cone.start_radius as f32,
end_center: kurbo::Point::new(cone.end_center, 0.),
end_radius: cone.end_radius as f32,
}
.into()
};
let end_color = |end| end_stop_color(samples, end);
let layers: Vec<_> = standard_layers(gradient)
.into_iter()
.map(|(paint, mask)| {
@@ -3534,37 +3605,37 @@ fn vello_gradient_paint(shape: GradientShape, samples: &[(f64, Color, Option<f64
StandardPaint::Solid(end) => (GradientBrush::Peniko(peniko::Brush::Solid(peniko::Color::new(end_color(end).to_gamma_srgb_channels()))), placement),
};
// The eraser is opaque wherever the layer is hidden
let eraser = mask.map(|keep| {
let colors = if keep.keeps_before {
[Color::TRANSPARENT, Color::BLACK]
} else {
[Color::BLACK, Color::TRANSPARENT]
};
step(keep.at, 1., colors)
});
(paint, eraser)
(paint, mask.map(eraser))
})
.collect();
(!layers.is_empty()).then_some(VelloGradientPaint(layers))
}
/// SVG 2's cone as Vello GPU's polar gradient paint takes it, in single precision.
fn cone_angle_geometry(cone: Cone) -> vello_gpu::PolarGeometry {
vello_gpu::PolarGeometry::ConeAngle {
start_center: [cone.start_center as f32, 0.],
start_radius: cone.start_radius as f32,
end_center: [cone.end_center as f32, 0.],
end_radius: cone.end_radius as f32,
}
}
/// The Apollonian circles of a gradient as Vello GPU's Apollonian gradient paint takes them, in single precision.
fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeometry {
fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::ApollonianGeometry {
let circle = |circle: &AxisCircle| [circle.a as f32, circle.b as f32, circle.c as f32];
vello_gpu::PencilGeometry {
vello_gpu::ApollonianGeometry {
start: circle(&parameters.start),
end: circle(&parameters.end),
selection: match parameters.selection {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::PencilSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::PencilSelection::OnArc {
CrossingSelection::SameSideAs { radical_x } => vello_gpu::ApollonianSelection::SameSideAs { radical_x: radical_x as f32 },
CrossingSelection::OnArc { quadratic } => vello_gpu::ApollonianSelection::OnArc {
quadratic: quadratic.map(|coefficient| coefficient as f32),
},
},
wrap: parameters.wrap.map(|wrap| vello_gpu::PencilWrap {
wrap: parameters.wrap.map(|wrap| vello_gpu::ApollonianWrap {
reference_x: wrap.reference_x as f32,
band_side: wrap.band_side as f32,
t: wrap.t as f32,
@@ -3582,7 +3653,7 @@ fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transf
let shape = gradient_shape(gradient_item);
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
let mut samples = spread_adjusted_samples(&stops, settings, shape);
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = gradient_item.paint_opacity(for_mask);
@@ -6791,7 +6862,7 @@ fn render_gradient_shape_svg(
let shape = gradient_shape(item);
let tag = if thumbnail_rect.is_some() { "rect" } else { "polyline" };
let mut samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start());
let mut samples = spread_adjusted_samples(gradient, settings, shape);
with_two_stops_at_least(shape, &mut samples);
let mut stop_string = String::new();
@@ -6920,7 +6991,7 @@ fn render_gradient_item_to_vello(item: ItemRef<'_, Gradient>, scene: &mut VelloS
fn endless_gradient_paint(item: ItemRef<'_, Gradient>, gradient: &Gradient, settings: GradientSettings, parent_transform: DAffine2) -> Option<VelloGradientPaint> {
let shape = gradient_shape(item);
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(gradient, settings, shape.reaches_before_start());
let mut samples = spread_adjusted_samples(gradient, settings, shape);
with_two_stops_at_least(shape, &mut samples);
vello_gradient_paint(shape, &samples, settings.spread, parent_transform * transform)
@@ -6967,11 +7038,11 @@ fn collect_gradient_items_metadata<'a>(items: impl Iterator<Item = ItemRef<'a, G
}
}
/// The form of the control geometry a gradient item shows, which is linear for every shape but the radial one.
/// The form of the control geometry a gradient item shows, which is linear for every shape but the radial form's, read along or across its contours.
fn gradient_control_form(item: ItemRef<'_, Gradient>) -> GradientForm {
match gradient_shape(item) {
GradientShape::Radial => GradientForm::Radial,
GradientShape::Linear | GradientShape::Standard(_) | GradientShape::Apollonian(_) => GradientForm::Linear,
GradientShape::Radial | GradientShape::Across(GradientAcross { form: Some(GradientForm::Radial), .. }) => GradientForm::Radial,
GradientShape::Linear | GradientShape::Standard(_) | GradientShape::Apollonian(_) | GradientShape::Across(_) => GradientForm::Linear,
}
}
@@ -7665,7 +7736,7 @@ impl SvgRenderAttrs<'_> {
#[cfg(test)]
mod tests {
use super::*;
use vector_types::gradient::{GradientModel, GradientSpace};
use vector_types::gradient::{GradientDirection, GradientModel, GradientSpace};
#[test]
fn stacked_paint_colors_composite_in_straight_alpha() {
@@ -7715,18 +7786,18 @@ mod tests {
};
// Other spreads pass the samples through unchanged
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), true);
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Repeat), GradientShape::Linear);
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), true);
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Linear);
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), GradientShape::Radial.reaches_before_start());
let samples = spread_adjusted_samples(&gradient, settings(GradientSpread::Clear), GradientShape::Radial);
assert_eq!(samples, vec![(0., Color::BLACK, None), (1., Color::WHITE, None), (1., Color::TRANSPARENT, None)]);
}
@@ -7739,7 +7810,7 @@ mod tests {
space: GradientSpace::RgbGamma,
..Default::default()
},
true,
GradientShape::Linear,
);
let colors: Vec<Color> = samples.iter().map(|&(_, color, _)| color).collect();
assert_eq!(colors, vec![Color::TRANSPARENT, Color::BLACK, Color::BLACK, Color::TRANSPARENT]);
@@ -8054,6 +8125,99 @@ mod tests {
assert!(deferred_images_of(Graphic::Gradient(curved_gradient(crossing, GradientModel::Apollonian)), &thumbnail).is_empty());
}
/// A black to white gradient read in gamma across its contours, with these curvatures and model.
fn across_gradient(curvatures: [f64; 2], model: GradientModel) -> Item<Gradient> {
curved_gradient(curvatures, model).with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across)
}
#[test]
fn across_gradients_render_in_svg_as_the_linear_forms_ramp_across_its_line() {
use graphic_types::vector_types::gradient_standard::radius_curvature;
// The linear form's ramp across its line, toward the placement's y axis, is placed by the full placement under either model
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-5., 25.), DVec2::new(7., 3.));
let expected = format!(
r#"<linearGradient id="0" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="0" y2="1" gradientTransform="{}">{BLACK_TO_WHITE_STOPS}</linearGradient><polyline points="{ENDLESS_POINTS}" fill="url('#0')"/>"#,
format_transform_matrix(placement)
);
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let linear = across_gradient(GradientForm::Linear.curvatures(), model).with_attribute(ATTR_TRANSFORM, placement);
assert!(gradient_shape(ItemRef::Item(&linear)).svg_draws_exactly());
assert_eq!(gradient_svg(linear), expected, "{model:?} model");
}
// SVG only approximates every other shape, standing in with the same ramp where no image the GPU renders replaces it
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
let concentric = [radius_curvature(2.), radius_curvature(-1.)];
for (curvatures, model) in [
(GradientForm::Radial.curvatures(), GradientModel::Standard),
(crossing, GradientModel::Standard),
(crossing, GradientModel::Apollonian),
(concentric, GradientModel::Apollonian),
] {
let gradient = across_gradient(curvatures, model).with_attribute(ATTR_TRANSFORM, placement);
assert!(!gradient_shape(ItemRef::Item(&gradient)).svg_draws_exactly(), "curvatures {curvatures:?}, {model:?} model");
assert_eq!(gradient_svg(gradient), expected, "curvatures {curvatures:?}, {model:?} model");
}
// Identical end circles leave nothing to read across under the Standard model
let identical = radius_curvature(0.5);
assert_eq!(gradient_svg(across_gradient([identical, identical], GradientModel::Standard)), "");
}
#[test]
fn svg_across_gradients_svg_only_approximates_take_the_gpus_image() {
use glam::UVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
let view = Footprint {
resolution: UVec2::new(96, 64),
..Default::default()
};
let render_params = RenderParams {
view: Some(view),
..Default::default()
};
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
// Endless, and painting a vector, the radial form read around its center takes an image while the linear form's ramp across its line keeps its markup
let radial = across_gradient(GradientForm::Radial.curvatures(), GradientModel::Standard);
let linear = across_gradient(GradientForm::Linear.curvatures(), GradientModel::Standard);
assert_eq!(deferred_images_of(Graphic::Gradient(radial.clone()), &render_params).len(), 1);
assert!(deferred_images_of(Graphic::Gradient(linear.clone()), &render_params).is_empty());
let images_of = |paint: Item<Gradient>| deferred_images_of(Graphic::VectorList(List::new_from_item(square_painted(Coverage::new_fill(), paint))), &render_params);
for paint in [radial, across_gradient(crossing, GradientModel::Standard), across_gradient(crossing, GradientModel::Apollonian)] {
assert_eq!(images_of(paint).len(), 1);
}
assert!(images_of(linear).is_empty());
}
#[test]
fn clear_spreads_guard_only_the_ends_a_position_across_contours_passes() {
use graphic_types::vector_types::gradient_standard::radius_curvature;
let gradient = Gradient::from(vec![Color::BLACK, Color::WHITE]);
let clear = GradientSettings {
spread: GradientSpread::Clear,
space: GradientSpace::RgbGamma,
..Default::default()
};
let across = |[start, end]: [f64; 2], model| GradientShape::new(start, end, model, GradientDirection::Across, DAffine2::IDENTITY);
// An angle around the contours stays within the range, so it takes no guard
let winding = across(GradientForm::Radial.curvatures(), GradientModel::Standard);
assert!(!winding.reaches_before_start() && !winding.reaches_past_end());
assert_eq!(spread_adjusted_samples(&gradient, clear, winding), gradient.interpolated_samples(clear));
// A distance beside the gradient line reaches both ways, as the linear form's along it does
let crossing = [radius_curvature(0.6), radius_curvature(0.6)];
for shape in [across(GradientForm::Linear.curvatures(), GradientModel::Standard), across(crossing, GradientModel::Apollonian)] {
assert!(shape.reaches_before_start() && shape.reaches_past_end(), "{shape:?}");
assert_eq!(spread_adjusted_samples(&gradient, clear, shape), spread_adjusted_samples(&gradient, clear, GradientShape::Linear));
}
}
#[test]
fn a_cut_far_along_the_gradient_line_keeps_its_place_on_screen() {
use graphic_types::vector_types::gradient_standard::radius_curvature;
@@ -11,7 +11,7 @@ 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, PencilGradient, TextureId, TextureRegion};
use vello_gpu::{ApollonianGradient, Image, ImageSource, PaintType, PolarGradient, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1;
@@ -100,7 +100,9 @@ pub enum SceneBrush<'b> {
/// A solid color, gradient, or image.
Peniko(BrushRef<'b>),
/// A gradient whose contours are Apollonian circles, which only Vello GPU's fork draws.
Apollonian(&'b PencilGradient),
Apollonian(&'b ApollonianGradient),
/// A gradient whose position runs around its contours, which only Vello GPU's fork draws.
Polar(&'b PolarGradient),
}
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
@@ -133,12 +135,18 @@ impl From<&peniko::Color> for SceneBrush<'_> {
}
}
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> {
fn from(gradient: &'b PencilGradient) -> Self {
impl<'b> From<&'b ApollonianGradient> for SceneBrush<'b> {
fn from(gradient: &'b ApollonianGradient) -> Self {
Self::Apollonian(gradient)
}
}
impl<'b> From<&'b PolarGradient> for SceneBrush<'b> {
fn from(gradient: &'b PolarGradient) -> Self {
Self::Polar(gradient)
}
}
/// The pixels behind an image the scene draws.
#[derive(Clone, Debug)]
pub enum SceneImage {
@@ -744,7 +752,11 @@ impl<'a> VelloSceneBuilder<'a> {
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
let (paint, paint_to_brush) = match brush {
SceneBrush::Apollonian(gradient) => {
self.scene.set_pencil_gradient_paint(gradient.clone());
self.scene.set_apollonian_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Polar(gradient) => {
self.scene.set_polar_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
@@ -1856,6 +1856,19 @@ pub enum GradientModel {
Apollonian,
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[widget(Radio)]
pub enum GradientDirection {
/// Reads the colors from start to end, each contour taking one color.
#[default]
Along,
/// Reads the colors around each contour instead, once clockwise around curved ones, or beside the gradient line in the linear form. Except for the linear form, SVG exports include it as an image, and PDF exports show an approximation.
Across,
}
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
@@ -0,0 +1,479 @@
//! Gradients read across their contours rather than along them, where each point's position `v` runs around or beside the contour through it.
//!
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`], and `v` increases toward +y (clockwise on screen for an
//! unreflected placement). A winding chart measures an angle in turns within `[0, 1)`, wrapping at a seam on the +x side where the spread has no
//! effect. The others measure from the gradient line, 0 on it and one unit per gradient length across its midpoint, which the spread then repeats.
use crate::gradient::{GradientForm, GradientModel};
use crate::gradient_apollonian::{AxisCircle, CircleFamily, Homogeneous};
use crate::gradient_standard::{Cone, GradientStandard, HalfPlane, NEAR_LINE_RADIUS, curvature_radius};
use glam::DVec2;
use std::f64::consts::TAU;
/// How far apart a cone's two centers may be, relative to its size, for it to be drawn as concentric circles.
const CONCENTRIC_TOLERANCE: f64 = 1e-9;
/// A gradient read across its contours.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GradientAcross {
pub chart: AcrossChart,
/// The form its curvatures make, if either.
pub form: Option<GradientForm>,
}
/// How each point of a gradient read across its contours finds its position `v`, in gradient space.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AcrossChart {
/// The linear form's: `v = y`.
Linear,
/// Concentric circles': the angle around their shared center at `(center, 0)`, from the +x ray.
Concentric { center: f64 },
/// SVG 2's cone's: the angle of the point around the center of the cone's circle through it, unpainted where the cone is and past `keep`'s line.
Cone { cone: Cone, keep: Option<HalfPlane> },
/// Apollonian circles nesting around two limit points: the angle of `M(z) = (n₀ z + n₁) / (d₀ z + d₁)`, which sends the limit point the
/// end contour encloses to 0 and the other to infinity, so each contour of constant `v` is an arc from one limit point to the other.
Mobius { numerator: [f64; 2], denominator: [f64; 2] },
/// Apollonian circles crossing at `(center_x, ±half_height)`: `scale · ln(|z - (center_x, -half_height)| / |z - (center_x, half_height)|)`,
/// the bipolar coordinate whose contours are the circles around the two crossings.
Bipolar { center_x: f64, half_height: f64, scale: f64 },
/// Unpainted everywhere, as SVG 2 leaves identical end circles.
Nothing,
}
impl AcrossChart {
/// The chart of a gradient with these curvatures, which must be finite and within -1 to 1, and model.
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel) -> Self {
match (GradientForm::from_curvatures([start_curvature, end_curvature]), model) {
(Some(GradientForm::Linear), _) => Self::Linear,
(Some(GradientForm::Radial), _) => Self::Concentric { center: 0. },
(None, GradientModel::Standard) => Self::standard(start_curvature, end_curvature),
(None, GradientModel::Apollonian) => Self::apollonian(start_curvature, end_curvature),
}
}
/// The angle around SVG 2's circles, painting where the Standard model's gradient read along them paints.
fn standard(start_curvature: f64, end_curvature: f64) -> Self {
match GradientStandard::new(start_curvature, end_curvature) {
GradientStandard::Cone(cone) => Self::cone(cone, None),
// A line end and a nearly flat cone, drawn as a profile along the gradient line, measure around the cone that's drawn at the flattest radius
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => Self::cone(near_line_cone(start_curvature, end_curvature), keep),
GradientStandard::Profile { .. } => Self::cone(near_line_cone(start_curvature, end_curvature), None),
GradientStandard::Nothing => Self::Nothing,
}
}
fn cone(cone: Cone, keep: Option<HalfPlane>) -> Self {
let size = cone.start_center.abs().max(cone.end_center.abs()).max(cone.start_radius).max(cone.end_radius);
let concentric = (cone.end_center - cone.start_center).abs() <= CONCENTRIC_TOLERANCE * size;
match keep {
None if concentric => Self::Concentric { center: cone.start_center },
_ => Self::Cone { cone, keep },
}
}
/// The angle around the limit points of the Apollonian circles, or the bipolar coordinate beside their crossings.
fn apollonian(start_curvature: f64, end_curvature: f64) -> Self {
// Identical end circles span no family of circles, and draw the linear form's plain ramp
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
return Self::Linear;
}
let (start, end) = (AxisCircle::start(start_curvature), AxisCircle::end(end_curvature));
match CircleFamily::of(start, end) {
CircleFamily::Crossing { radical_x } => Self::bipolar(start, end, radical_x),
CircleFamily::Nesting { limit_points } => Self::mobius(start, end, limit_points),
}
}
fn bipolar(start: AxisCircle, end: AxisCircle, radical_x: f64) -> Self {
// The crossings lie on whichever end contour is rounder, which places them most precisely
let circle = if start.a.abs() >= end.a.abs() { start } else { end };
let half_height = (-(circle.b * radical_x + circle.c) / circle.a - radical_x * radical_x).max(0.).sqrt().max(f64::MIN_POSITIVE);
// The coordinate's rate across the gradient line at its midpoint is `half_height / (half_height² + (1/2 - radical_x)²)` before this scale
let midpoint_offset = 0.5 - radical_x;
let scale = (half_height * half_height + midpoint_offset * midpoint_offset) / (2. * half_height);
Self::Bipolar {
center_x: radical_x,
half_height,
scale,
}
}
fn mobius(start: AxisCircle, end: AxisCircle, limit_points: [Homogeneous; 2]) -> Self {
// With nonnegative denominators, a point's sign on a contour doesn't depend on how it's scaled
let oriented = |point: Homogeneous| {
let sign = if point.denominator < 0. { -1. } else { 1. };
Homogeneous {
numerator: point.numerator * sign,
denominator: point.denominator * sign,
}
};
let [first, second] = limit_points.map(oriented);
// The limit point inside the end contour, or the start contour where the end is a line, is negative on it (or zero, for a point contour on it)
let inside = |circle: AxisCircle, point: Homogeneous| {
let Homogeneous { numerator, denominator } = point;
circle.a * (circle.a * numerator * numerator + circle.b * numerator * denominator + circle.c * denominator * denominator)
};
let enclosing = if end.a != 0. { end } else { start };
let (enclosed, other) = if inside(enclosing, first) <= inside(enclosing, second) {
(first, second)
} else {
(second, first)
};
// Concentric circles have their other limit point at infinity, about which the angle is around their shared center
let Some(center) = enclosed.value() else { return Self::Linear };
if other.denominator == 0. {
return Self::Concentric { center };
}
// `M(z) = ±(z - enclosed) / (other - z)`, signed so `M` is positive on the +x ray from the enclosed limit point as `other` passes through infinity
let product = other.numerator * enclosed.denominator - enclosed.numerator * other.denominator;
let sign = if product < 0. { -1. } else { 1. };
Self::Mobius {
numerator: [sign * enclosed.denominator, -sign * enclosed.numerator],
denominator: [-other.denominator, other.numerator],
}
}
/// The position at `point`, or `None` where it's unpainted.
pub fn v(&self, point: DVec2) -> Option<f64> {
match *self {
Self::Linear => Some(point.y),
Self::Concentric { center } => Some(turns(point.y, point.x - center)),
Self::Cone { cone, keep } => {
if keep.is_some_and(|keep| !keep.keeps(point.x)) {
return None;
}
let t = cone.t(point)?;
let center = cone.start_center + t * (cone.end_center - cone.start_center);
Some(turns(point.y, point.x - center))
}
Self::Mobius { numerator, denominator } => {
// The angle of `numerator / denominator` is that of `numerator · conj(denominator)`
let affine = |[slope, intercept]: [f64; 2]| DVec2::new(slope * point.x + intercept, slope * point.y);
let (numerator, denominator) = (affine(numerator), affine(denominator));
Some(turns(numerator.y * denominator.x - numerator.x * denominator.y, numerator.dot(denominator)))
}
Self::Bipolar { center_x, half_height, scale } => {
// The squared distances to the crossings differ by `4 half_height y`, whose ratio's logarithm keeps its precision near the gradient line
let to_upper = DVec2::new(point.x - center_x, point.y - half_height).length_squared();
Some(scale * 0.5 * (4. * half_height * point.y / to_upper).ln_1p())
}
Self::Nothing => None,
}
}
/// Whether it measures an angle, wrapping from 1 back to 0 at a seam, rather than a distance from the gradient line.
pub fn winds(&self) -> bool {
matches!(self, Self::Concentric { .. } | Self::Cone { .. } | Self::Mobius { .. })
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Linear | Self::Concentric { .. } | Self::Mobius { .. } | Self::Bipolar { .. } => true,
Self::Cone { cone, keep } => keep.is_none() && cone.is_nested(),
Self::Nothing => false,
}
}
/// Whether SVG draws it exactly, which only the linear form's ramp across the gradient line is (and nothing at all).
pub fn svg_draws_exactly(&self) -> bool {
matches!(self, Self::Linear | Self::Nothing)
}
}
/// The cone between the end contours with these curvatures, each a nearly flat circle or a line drawn at the flattest radius a cone is (a line bowing toward the other end).
fn near_line_cone(start_curvature: f64, end_curvature: f64) -> Cone {
let near_line_radius = |curvature: f64| {
let radius = curvature_radius(curvature);
if radius.is_infinite() {
NEAR_LINE_RADIUS
} else {
radius.clamp(-NEAR_LINE_RADIUS, NEAR_LINE_RADIUS)
}
};
Cone::between(near_line_radius(start_curvature), near_line_radius(end_curvature))
}
/// The angle of `(x, y)` from the +x axis toward the +y axis, in turns within `[0, 1)`.
fn turns(y: f64, x: f64) -> f64 {
let turns = y.atan2(x).rem_euclid(TAU) / TAU;
if turns >= 1. { 0. } else { turns }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
use crate::gradient_apollonian::GradientApollonian;
use crate::gradient_standard::radius_curvature;
/// Points spread over a view around the gradient line, kept off its exact rational coordinates.
fn sample_points() -> impl Iterator<Item = DVec2> {
(-30..=40).flat_map(|x| (-25..=25).map(move |y| DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007)))
}
/// The distance between two angles in turns, the short way around.
fn turn_distance(first: f64, second: f64) -> f64 {
let distance = (first - second).rem_euclid(1.);
distance.min(1. - distance)
}
/// Curvature pairs of every kind: circles crossing, nested, apart, and concentric, lines and points beside them, and nearly flat circles.
fn curvature_pairs() -> Vec<[f64; 2]> {
let mut pairs: Vec<[f64; 2]> = [
(0., 0.75),
(0.2, 1.5),
(2., -0.5),
(0.6, 0.6),
(-0.3, -0.3),
(0., -0.4),
(2., -1.),
(-0.5, 1.5),
(0.8, 1e9),
(-0.3, 1e9),
(1e9, 0.25),
(1e9, 2.),
(3000., -2500.),
(0.3, 2500.),
]
.into_iter()
.map(|(start, end)| [radius_curvature(start), radius_curvature(end)])
.collect();
pairs.extend([[1., 0.3], [1., 1.], [0.8, -1.], [0.4, 0.], [0., -0.4], [-0.3, 0.]]);
pairs
}
#[test]
fn the_linear_form_reads_across_the_gradient_line() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1], model);
assert_eq!(chart, AcrossChart::Linear);
for point in sample_points() {
assert_eq!(chart.v(point), Some(point.y));
}
}
}
#[test]
fn the_radial_form_reads_the_angle_around_its_center() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1], model);
for point in sample_points() {
let expected = point.y.atan2(point.x).rem_euclid(TAU) / TAU;
assert!(turn_distance(chart.v(point).unwrap(), expected) < 1e-12, "{model:?} at {point}");
}
// Clockwise on screen, from the seam along the gradient line
assert!((chart.v(DVec2::new(0., 1.)).unwrap() - 0.25).abs() < 1e-12);
assert!(chart.v(DVec2::new(0.5, 1e-9)).unwrap() < 1e-6 && chart.v(DVec2::new(0.5, -1e-9)).unwrap() > 1. - 1e-6);
}
}
#[test]
fn both_models_read_concentric_circles_around_their_center() {
// The start circle centered at its radius and the end at 1 minus its own share a center, with the end circle outside or inside the start circle
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
let [standard, apollonian] = [GradientModel::Standard, GradientModel::Apollonian].map(|model| AcrossChart::new(curvatures[0], curvatures[1], model));
let cone = AcrossChart::Cone {
cone: Cone::between(start_radius, 1. - start_radius),
keep: None,
};
assert!(matches!(standard, AcrossChart::Concentric { .. }), "{standard:?}");
assert!(matches!(apollonian, AcrossChart::Concentric { .. }), "{apollonian:?}");
for point in sample_points() {
let expected = (point.y).atan2(point.x - start_radius).rem_euclid(TAU) / TAU;
for (chart, name) in [(standard, "Standard"), (apollonian, "Apollonian"), (cone, "cone")] {
let v = chart.v(point).unwrap_or_else(|| panic!("{name} leaves {point} unpainted with start radius {start_radius}"));
assert!(turn_distance(v, expected) < 1e-9, "{name} with start radius {start_radius} at {point}: {v} rather than {expected}");
}
}
}
}
#[test]
fn standard_contours_of_constant_position_are_rays_from_the_apex() {
// Off-center pairs with an apex where the cone's circles shrink to a point
for (start, end) in [(0., 0.75), (0.2, 1.5), (0.6, 0.3), (-0.3, -0.6), (2., -0.5)] {
let cone = Cone::between(start, end);
let chart = AcrossChart::new(radius_curvature(start), radius_curvature(end), GradientModel::Standard);
assert!(matches!(chart, AcrossChart::Cone { .. }), "({start}, {end}) should be a cone, not {chart:?}");
let delta_radius = cone.end_radius - cone.start_radius;
let apex_t = -cone.start_radius / delta_radius;
let apex = DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.);
for angle in (0..24).map(|step| (step as f64 + 0.37) * TAU / 24.) {
let direction = DVec2::from_angle(angle);
let positions: Vec<f64> = [0.2, 0.5, 1., 2., 4.].into_iter().filter_map(|distance| chart.v(apex + direction * distance)).collect();
for &v in &positions {
assert!(turn_distance(v, positions[0]) < 1e-9, "({start}, {end}) along the ray at {angle}: {positions:?}");
}
}
}
}
#[test]
fn across_paints_exactly_where_along_does() {
for curvatures in curvature_pairs() {
let standard = GradientStandard::new(curvatures[0], curvatures[1]);
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Standard);
// A line end's cut and a nearly flat cone's split are drawn as straight lines across the gradient line, which the cone drawn at the flattest radius only nears
let cut = match standard {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Profile { split, .. } => Some(split),
_ => None,
};
for point in sample_points() {
if cut.is_some_and(|cut| (point.x - cut).abs() < 0.1 * point.y.abs().max(0.1)) {
continue;
}
assert_eq!(chart.v(point).is_some(), standard.t(point).is_some(), "Standard curvatures {curvatures:?} at {point}: {chart:?}");
}
// Apollonian circles paint everywhere, read along or across them
let chart = AcrossChart::new(curvatures[0], curvatures[1], GradientModel::Apollonian);
assert!(chart.paints_everywhere(), "Apollonian curvatures {curvatures:?}: {chart:?}");
assert!(sample_points().all(|point| chart.v(point).is_some()), "Apollonian curvatures {curvatures:?}: {chart:?}");
}
}
#[test]
fn positions_change_continuously_except_at_seams_and_where_contours_meet() {
const STEP: f64 = 0.01;
for curvatures in curvature_pairs() {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(curvatures[0], curvatures[1], model);
// Where every contour of constant position meets, and a cut across the gradient line
let mut singular_points = Vec::new();
let mut cut = None;
match chart {
AcrossChart::Concentric { center } => singular_points.push(DVec2::new(center, 0.)),
AcrossChart::Cone { cone, keep } => {
let apex_t = -cone.start_radius / (cone.end_radius - cone.start_radius);
singular_points.push(DVec2::new(cone.start_center + apex_t * (cone.end_center - cone.start_center), 0.));
cut = keep.map(|keep| keep.at);
}
AcrossChart::Mobius { numerator, denominator } => {
singular_points.push(DVec2::new(-numerator[1] / numerator[0], 0.));
singular_points.push(DVec2::new(-denominator[1] / denominator[0], 0.));
}
AcrossChart::Bipolar { center_x, half_height, .. } => {
singular_points.push(DVec2::new(center_x, half_height));
singular_points.push(DVec2::new(center_x, -half_height));
}
AcrossChart::Linear | AcrossChart::Nothing => {}
}
let near_singular = |point: DVec2| singular_points.iter().any(|singular| (point - *singular).length() < 0.2) || cut.is_some_and(|cut| (point.x - cut).abs() < 0.02);
for point in sample_points().filter(|&point| !near_singular(point)) {
for neighbor in [point + DVec2::new(STEP, 0.), point + DVec2::new(0., STEP)] {
if near_singular(neighbor) {
continue;
}
let (Some(v), Some(neighbor_v)) = (chart.v(point), chart.v(neighbor)) else { continue };
let change = if chart.winds() { turn_distance(v, neighbor_v) } else { (v - neighbor_v).abs() };
assert!(change < 0.05, "{model:?} curvatures {curvatures:?} from {point} to {neighbor}: {v} to {neighbor_v} in {chart:?}");
}
}
}
}
}
#[test]
fn the_bipolar_chart_nears_the_linear_forms_as_crossing_curvatures_flatten() {
// Over the view, the chart strays from `y` in proportion to the curvatures
for curvature in [1e-3, 1e-4, 1e-6] {
let tolerance = 300. * curvature;
for [start, end] in [[curvature, curvature], [curvature, 2. * curvature], [3. * curvature, curvature]] {
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
assert!(matches!(chart, AcrossChart::Bipolar { .. }), "({start}, {end}) should cross, not {chart:?}");
for point in sample_points() {
let v = chart.v(point).unwrap();
assert!((v - point.y).abs() < tolerance, "({start}, {end}) at {point}: {v}");
}
}
}
// Zero on the gradient line, and one unit per gradient length across its midpoint
let chart = AcrossChart::new(0.6, 0.4, GradientModel::Apollonian);
assert!(chart.v(DVec2::new(0.3, 0.)).unwrap().abs() < 1e-15);
let rate = (chart.v(DVec2::new(0.5, 1e-6)).unwrap() - chart.v(DVec2::new(0.5, -1e-6)).unwrap()) / 2e-6;
assert!((rate - 1.).abs() < 1e-6, "{rate}");
}
#[test]
fn apollonian_angles_run_around_the_limit_point_inside_the_end_contour() {
// The start point inside the end circle, which encloses the start point as its limit point
let start_point = AcrossChart::new(-1., 0.3, GradientModel::Apollonian);
let AcrossChart::Mobius { numerator, .. } = start_point else { panic!("{start_point:?}") };
assert!((-numerator[1] / numerator[0]).abs() < 1e-12, "{start_point:?}");
// The end a point, which is its own limit point
let end_point = AcrossChart::new(0.8, 1., GradientModel::Apollonian);
let AcrossChart::Mobius { numerator, .. } = end_point else { panic!("{end_point:?}") };
assert!((-numerator[1] / numerator[0] - 1.).abs() < 1e-9, "{end_point:?}");
// Near the enclosed limit point, the position is the angle around it, from the seam on the +x side
for angle in [0.1, 1., 2., 3., 4., 5., 6.] {
let point = DVec2::from_angle(angle) * 1e-7;
assert!(turn_distance(start_point.v(point).unwrap(), angle / TAU) < 1e-5, "at angle {angle}");
}
}
#[test]
fn the_apollonian_chart_is_found_for_every_curvature_pair() {
for start_step in -10..=10 {
for end_step in -10..=10 {
let (start, end) = (start_step as f64 / 10., end_step as f64 / 10.);
let chart = AcrossChart::new(start, end, GradientModel::Apollonian);
let along = GradientApollonian::new(start, end);
for point in sample_points() {
let v = chart.v(point);
assert!(v.is_some_and(|v| !v.is_nan()), "({start}, {end}) at {point}: {v:?} in {chart:?}");
assert!(!along.t(point).is_nan());
}
}
}
}
#[test]
fn extreme_curvatures_compute_finitely() {
let extremes = [4e-309, -4e-309, 1e-300, 6e-31, -6e-31, 7e-31, -7e-31, 1e-17, -1e-17];
let curvatures = extremes.iter().flat_map(|&extreme| {
[
[extreme, 0.],
[0., extreme],
[extreme, 0.3],
[-0.3, extreme],
[extreme, extreme],
[extreme, -extreme],
[extreme, 1. - 1e-16],
]
});
for [start, end] in curvatures {
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let chart = AcrossChart::new(start, end, model);
for point in sample_points() {
let v = chart.v(point);
assert!(v.is_none_or(|v| !v.is_nan()), "{model:?} curvatures ({start}, {end}) at {point}: {chart:?}");
}
}
}
}
}
@@ -60,20 +60,20 @@ impl AxisCircle {
/// 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,
pub(crate) struct Homogeneous {
pub(crate) numerator: f64,
pub(crate) denominator: f64,
}
impl Homogeneous {
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
pub(crate) const INFINITY: Self = Self { numerator: 1., denominator: 0. };
fn value(&self) -> Option<f64> {
pub(crate) fn value(&self) -> Option<f64> {
(self.denominator != 0.).then(|| self.numerator / self.denominator)
}
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
fn normalized(self) -> Self {
pub(crate) fn normalized(self) -> Self {
let scale = self.numerator.abs().max(self.denominator.abs());
if scale == 0. {
return self;
@@ -85,6 +85,51 @@ impl Homogeneous {
}
}
/// How the family of circles two end contours span is laid out.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum CircleFamily {
/// The end contours cross, so every member passes through the two points where the line member at `radical_x` meets them.
Crossing { radical_x: f64 },
/// The members nest around two limit points (normalized), which coincide where the end contours touch.
Nesting { limit_points: [Homogeneous; 2] },
}
impl CircleFamily {
pub(crate) fn of(start: AxisCircle, end: AxisCircle) -> Self {
// The members of the family 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 family 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);
return Self::Crossing { radical_x: -line.c / line.b };
}
// 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()
});
Self::Nesting { limit_points }
}
}
/// 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.);
@@ -139,37 +184,10 @@ impl GradientApollonian {
let start = AxisCircle::start(start_curvature);
let end = AxisCircle::end(end_curvature);
// The members of the family 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 family 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., svg_stand_in);
}
// 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()
});
let limit_points = match CircleFamily::of(start, end) {
CircleFamily::Crossing { radical_x } => return Self::with_band(start, end, CrossingSelection::SameSideAs { radical_x }, None, 0., 1., svg_stand_in),
CircleFamily::Nesting { limit_points } => limit_points,
};
// Each crossing's place relative to the limit points, negative between them and positive beyond them
let arc_quadratic = arc_quadratic(limit_points);
@@ -10,7 +10,8 @@
//! Where SVG 2 leaves the plane unpainted, so does it. A line end takes SVG 2's own limit as that end's circle flattens bowing
//! toward the other end. The Apollonian drawing of the same curvatures is in [`crate::gradient_apollonian`].
use crate::gradient::{GradientForm, GradientModel, wrapped_curvature};
use crate::gradient::{GradientDirection, GradientForm, GradientModel, wrapped_curvature};
use crate::gradient_across::{AcrossChart, GradientAcross};
use crate::gradient_apollonian::GradientApollonian;
use glam::{DAffine2, DVec2};
use std::f64::consts::FRAC_PI_2;
@@ -345,7 +346,7 @@ impl GradientStandard {
}
}
/// How a gradient's contours are laid out, decided by its curvatures and model.
/// How a gradient's contours are laid out, decided by its curvatures and model, and how its colors run, decided by its direction.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientShape {
/// The linear form: both ends are lines.
@@ -356,19 +357,27 @@ pub enum GradientShape {
Standard(GradientStandard),
/// Any other curvatures, drawn as Apollonian circles.
Apollonian(GradientApollonian),
/// Any curvatures, with the colors running around the contours rather than from one end to the other.
Across(GradientAcross),
}
impl GradientShape {
/// The shape of a gradient with these curvatures, each wrapped like [`wrapped_curvature`] and a line where it isn't finite, placed by `transform`.
/// With curvatures other than a form's, a collapsed placement (like a zero-length gradient line) leaves the last stop's color, as SVG does.
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, transform: DAffine2) -> Self {
pub fn new(start_curvature: f64, end_curvature: f64, model: GradientModel, direction: GradientDirection, transform: DAffine2) -> Self {
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
let form = GradientForm::from_curvatures([start, end]);
let collapsed = !transform.matrix2.determinant().recip().is_finite();
match GradientForm::from_curvatures([start, end]) {
Some(GradientForm::Linear) => Self::Linear,
Some(GradientForm::Radial) => Self::Radial,
None if !transform.matrix2.determinant().recip().is_finite() => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
None if model == GradientModel::Apollonian => {
match (form, direction) {
(None, _) if collapsed => Self::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }),
(_, GradientDirection::Across) => Self::Across(GradientAcross {
chart: AcrossChart::new(start, end, model),
form,
}),
(Some(GradientForm::Linear), GradientDirection::Along) => Self::Linear,
(Some(GradientForm::Radial), GradientDirection::Along) => Self::Radial,
(None, GradientDirection::Along) if model == GradientModel::Apollonian => {
// Identical end circles span no family of circles, so they draw the plain ramp
let (start_radius, end_radius) = (curvature_radius(start), curvature_radius(end));
if start_radius.is_finite() && end_radius.is_finite() && Cone::between(start_radius, end_radius).is_identical() {
@@ -377,13 +386,22 @@ impl GradientShape {
Self::Apollonian(GradientApollonian::new(start, end))
}
None => Self::Standard(GradientStandard::new(start, end)),
(None, GradientDirection::Along) => Self::Standard(GradientStandard::new(start, end)),
}
}
/// Whether its position can fall before the start, which only a radial gradient's can't since its distance from the center never goes below zero.
/// Whether its position can fall before the start, which a radial gradient's distance from its center and an angle around the contours can't.
pub fn reaches_before_start(&self) -> bool {
!matches!(self, Self::Radial)
match self {
Self::Radial => false,
Self::Across(across) => !across.chart.winds(),
Self::Linear | Self::Standard(_) | Self::Apollonian(_) => true,
}
}
/// Whether its position can fall past the end, which an angle around the contours can't.
pub fn reaches_past_end(&self) -> bool {
!matches!(self, Self::Across(across) if across.chart.winds())
}
/// Whether it paints every point, rather than leaving some unpainted.
@@ -391,11 +409,15 @@ impl GradientShape {
match self {
Self::Linear | Self::Radial | Self::Apollonian(_) => true,
Self::Standard(gradient) => gradient.paints_everywhere(),
Self::Across(across) => across.chart.paints_everywhere(),
}
}
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles, other than those between concentric end circles drawn as SVG 2's cone.
/// Whether SVG draws it exactly, which it does unless it's Apollonian circles (other than those between concentric end circles drawn as SVG 2's cone), or read across contours other than the linear form's.
pub fn svg_draws_exactly(&self) -> bool {
if let Self::Across(across) = self {
return across.chart.svg_draws_exactly();
}
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
return true;
};
@@ -743,7 +765,7 @@ mod tests {
fn a_zero_length_gradient_line_leaves_the_last_stop_once_curved() {
let collapsed = DAffine2::from_cols(DVec2::ZERO, DVec2::Y, DVec2::new(3., 4.));
for model in [GradientModel::Standard, GradientModel::Apollonian] {
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, collapsed);
let shape = |[start, end]: [f64; 2]| GradientShape::new(start, end, model, GradientDirection::Along, collapsed);
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
// The forms keep drawing as they always have
@@ -755,7 +777,7 @@ mod tests {
#[test]
fn apollonian_gradients_stand_in_for_svg_with_its_own_drawing_where_that_paints_everywhere() {
let placement = DAffine2::IDENTITY;
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) {
let stand_in = |curvatures: [f64; 2]| match GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) {
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
};
@@ -773,22 +795,25 @@ mod tests {
// Identical end circles span no family of circles, so they draw the plain ramp everywhere
let identical = radius_curvature(0.5);
assert_eq!(GradientShape::new(identical, identical, GradientModel::Apollonian, placement), GradientShape::Standard(plain_ramp));
assert_eq!(
GradientShape::new(identical, identical, GradientModel::Apollonian, GradientDirection::Along, placement),
GradientShape::Standard(plain_ramp)
);
// The forms stay native under either model
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, placement), GradientShape::Linear);
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, placement), GradientShape::Radial);
assert_eq!(GradientShape::new(0., 0., GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Linear);
assert_eq!(GradientShape::new(-1., 0.5, GradientModel::Apollonian, GradientDirection::Along, placement), GradientShape::Radial);
}
#[test]
fn svg_draws_every_shape_exactly_but_apollonian_circles_it_cant_draw_as_a_cone() {
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, DAffine2::IDENTITY).svg_draws_exactly();
let exact = |curvatures: [f64; 2], model: GradientModel| GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Along, DAffine2::IDENTITY).svg_draws_exactly();
// Concentric end circles, the start centered at its radius and the end at 1 minus its own, have Apollonian circles that are SVG 2's cone
for [start, end] in [[2., -1.], [-0.5, 1.5], [0.25, 0.75]] {
let curvatures = [radius_curvature(start), radius_curvature(end)];
assert!(matches!(
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, DAffine2::IDENTITY),
GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, DAffine2::IDENTITY),
GradientShape::Apollonian(_)
));
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
+4 -1
View File
@@ -2,6 +2,7 @@
extern crate log;
pub mod gradient;
pub mod gradient_across;
pub mod gradient_apollonian;
pub mod gradient_standard;
pub mod math;
@@ -9,7 +10,9 @@ pub mod vector;
// Re-export commonly used types at the crate root
pub use core_types as gcore;
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use gradient::{
Gradient, GradientDirection, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop,
};
pub use math::QuadExt;
pub use vector::Vector;
pub use vector::reference_point::ReferencePoint;
@@ -7,7 +7,7 @@ use crate::WgpuExecutor;
use core_types::blending::BlendMode;
use glam::{DAffine2, UVec2};
use graphic_types::MinimumMaximumMode;
use graphic_types::vector_types::gradient::{GradientModel, GradientSpread};
use graphic_types::vector_types::gradient::{GradientDirection, GradientModel, GradientSpread};
use rendering::vello_scene_builder::VelloSceneBuilder;
use vello_gpu::kurbo::{Affine, BezPath, Line, ParamCurve, PathSeg, Point, Rect, Stroke, Vec2};
use vello_gpu::peniko::{self, Color, Fill};
@@ -555,7 +555,7 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
[0.9, 0.6],
[0.6, 1.],
] {
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) else {
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, GradientDirection::Along, placement) else {
panic!("curvatures {curvatures:?} should draw Apollonian circles");
};
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
@@ -575,6 +575,114 @@ fn apollonian_gradients_match_their_cpu_evaluation() {
}
}
#[test]
fn across_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use std::fmt::Write;
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100), and then sheared
let placements = [
DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.)),
DAffine2::from_cols(DVec2::new(50., 10.), DVec2::new(15., 35.), DVec2::new(60., 100.)),
];
let radius = radius_curvature;
let (standard, apollonian) = (GradientModel::Standard, GradientModel::Apollonian);
let settings = [
([0., 0.], standard, "the linear form"),
([-1., 0.5], standard, "the radial form"),
([radius(2.), radius(-1.)], standard, "concentric circles"),
([-1., radius(0.75)], standard, "a focal point inside the end circle, off its center"),
([radius(0.2), radius(1.5)], standard, "a focal circle nested inside the end circle"),
([radius(0.6), radius(0.6)], standard, "crossing circles"),
([radius(-0.2), radius(-0.4)], standard, "separate circles"),
([radius(0.8), 0.], standard, "an end line beside a start circle reaching past the end"),
([radius(0.45), 0.], standard, "an end line beside a start circle nearly reaching the end"),
([radius(0.6), 0.], standard, "an end line beside a start circle just past the end"),
([radius(3000.), radius(-4000.)], standard, "both ends nearly flat around an apex"),
([radius(2.), radius(-1.)], apollonian, "concentric Apollonian circles"),
([1., 0.3], apollonian, "Apollonian circles around the start point"),
([0.9, 0.2], apollonian, "nested Apollonian circles"),
([0.8, 1.], apollonian, "Apollonian circles around the end point"),
([1., 1.], apollonian, "Apollonian circles of two points"),
([0.6, 0.6], apollonian, "crossing Apollonian circles"),
([0.5, 0.25], apollonian, "crossing Apollonian circles of different sizes"),
];
let mut report = String::new();
for (curvatures, model, setting) in settings {
for placement in placements {
for spread in [GradientSpread::Pad, GradientSpread::Repeat] {
let Some(line) = compare_across_gradient_with_cpu(curvatures, model, placement, spread, setting) else {
return;
};
let _ = writeln!(report, "{line}");
}
}
}
eprintln!("{report}");
}
/// Renders a black to white gradient read across its contours, with these curvatures and model, placed by `placement` and read with `spread`, into a
/// 200 by 200 view, and checks each pixel against the CPU's evaluation, returning a line describing how they compare, or `None` without a GPU.
fn compare_across_gradient_with_cpu(curvatures: [f64; 2], model: GradientModel, placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
use core_types::list::{ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_SPREAD};
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientShape;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), model) {
graphic_types::Graphic::Gradient(item) => {
graphic_types::Graphic::Gradient(item.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Across).with_attribute(ATTR_GRADIENT_SPREAD, spread))
}
graphic => graphic,
};
let pixels = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))?;
// The CPU's level at a point on the screen, or `None` where it's unpainted, which the spread repeats only where the position doesn't wind
let GradientShape::Across(across) = GradientShape::new(curvatures[0], curvatures[1], model, GradientDirection::Across, placement) else {
panic!("{setting} should be read across its contours");
};
let to_gradient = placement.inverse();
let level_at = |point: DVec2| {
let v = across.chart.v(to_gradient.transform_point2(point))?;
let position = match spread {
_ if across.chart.winds() => v,
GradientSpread::Repeat => v - v.floor(),
_ => v.clamp(0., 1.),
};
Some((position * 255.).round() as i32)
};
let expected = |x: i32, y: i32| level_at(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
// Each pixel takes the level at its center, except within two pixels of a seam where the position wraps, a step, or an edge of the painted area, which only rounding and antialiasing tell apart
let (mut worst, mut beside_steps, mut disagreements) = (0, 0, 0);
for y in 2..size.y as i32 - 2 {
for x in 2..size.x as i32 - 2 {
let neighborhood: Vec<Option<i32>> = (-2..=2).flat_map(|dy| (-2..=2).map(move |dx| (x + dx, y + dy))).map(|(x, y)| expected(x, y)).collect();
let painted_neighbors = neighborhood.iter().filter(|level| level.is_some()).count();
let levels = neighborhood.iter().flatten();
let (lowest, highest) = (*levels.clone().min().unwrap_or(&0), *levels.max().unwrap_or(&255));
let [red, _, _, alpha] = pixel(&pixels, size, x as u32, y as u32);
match (alpha, expected(x, y)) {
(0, None) => {}
(255, Some(level)) if painted_neighbors == 25 && highest - lowest <= 64 => worst = worst.max((red as i32 - level).abs()),
(255, Some(_)) => beside_steps += 1,
_ if painted_neighbors != 0 && painted_neighbors != 25 => {}
_ => disagreements += 1,
}
}
}
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
Some(format!("{context}: within {worst} levels, {beside_steps} pixels beside seams and steps"))
}
#[test]
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
+8
View File
@@ -1952,6 +1952,14 @@ fn gradient_model(_: impl Ctx, gradient: Item<Gradient>, model: Item<vector_type
gradient
}
/// Sets which way the colors of each gradient in the input list run: Along, from the start contour to the end contour, or Across, around each contour.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_direction(_: impl Ctx, gradient: Item<Gradient>, direction: Item<vector_types::GradientDirection>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_DIRECTION, *direction.element());
gradient
}
/// Sets how each gradient in the input list extends past its endpoints: Pad, Reflect, Repeat, or Clear.
#[node_macro::node(category("Gradient"), icon("NodeGradientSpread"))]
fn gradient_spread(_: impl Ctx, gradient: Item<Gradient>, gradient_spread: Item<vector_types::GradientSpread>) -> Item<Gradient> {
+78 -5
View File
@@ -10,8 +10,8 @@ use core_types::math::spread::spread_factors;
use core_types::transform::{Footprint, Transform};
use core_types::uuid::NodeId;
use core_types::{
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL,
ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl,
ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_GRADIENT_DIRECTION, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, CloneVarArgs, Color, Context, Ctx, ExtractAll, InjectFootprint, OwnedContextImpl,
};
use core_types::{Interrupt, NodeError};
use glam::{DAffine2, DMat2, DVec2};
@@ -24,7 +24,7 @@ use kurbo::{Affine, BezPath, DEFAULT_ACCURACY, Line, ParamCurve, ParamCurveArcle
use rand::{RngExt, SeedableRng};
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::gradient::{GradientDirection, GradientModel, build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::vector::SetVectorPaths;
use vector_types::vector::algorithms::bezpath_algorithms::{
self, PoissonDiskError, PoissonDiskSampler, SampleCountError, TValue, bezpath_area_centroid_and_area, bezpath_length_centroid_and_length, eval_pathseg_euclidean, evaluate_bezpath, split_bezpath,
@@ -408,7 +408,7 @@ fn vary_cover_colors<T: VectorListIterMut>(
}
/// Applies a fill style to the vector content, giving an appearance to the area within the interior of the geometry.
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(2))]
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(3))]
fn fill<V>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
@@ -421,19 +421,22 @@ fn fill<V>(
_end_curvature: Item<f64>,
_has_transform: Item<bool>,
_transform: Item<DAffine2>,
_model: Item<GradientModel>,
_direction: Item<GradientDirection>,
) -> Item<V>
where
Item<V>: VectorItemMut + Send,
{
let (_start_curvature, _end_curvature) = (_start_curvature.into_element(), _end_curvature.into_element());
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
let (_model, _direction) = (_model.into_element(), _direction.into_element());
let mut content = content;
// Keeping the wire envelope's attributes would nest the paint as a group, changing how it renders, so only its effects carry over
let mut paint = paint_with_envelope_effects(paint);
// Stamp the gradient styling inputs onto any gradient paint missing them, whether the paint arrived as a picker value or a wire
// TODO: Stop reading whether the gradient has curvatures or a transform, since an absent attribute should mean the same as its default.
// TODO: Stop reading whether the gradient has curvatures, a model, a direction, or a transform, since an absent attribute should mean the same as its default.
// These reads tell a gradient picked in a widget, which needs styling and placing, from a wired one carrying its own, until paint inputs can tell those apart by type.
let (needs_curvatures, needs_transform) = match &paint {
Graphic::Gradient(item) => (
@@ -446,6 +449,18 @@ where
),
_ => (false, false),
};
// The model and direction are stamped only when they differ from the default an absent attribute already reads as
let (needs_model, needs_direction) = match &paint {
Graphic::Gradient(item) => (
_model != GradientModel::default() && item.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
_direction != GradientDirection::default() && item.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
),
Graphic::GradientList(list) => (
_model != GradientModel::default() && list.iter_attribute_values::<GradientModel>(ATTR_GRADIENT_MODEL).is_none(),
_direction != GradientDirection::default() && list.iter_attribute_values::<GradientDirection>(ATTR_GRADIENT_DIRECTION).is_none(),
),
_ => (false, false),
};
let stamped_transform = needs_transform.then(|| {
// Without an explicit placement, derive one covering the paint target's bounding box (the CSS `auto` behavior)
@@ -483,6 +498,12 @@ where
if let Some(transform) = stamped_transform {
item.set_attribute(ATTR_TRANSFORM, transform);
}
if needs_model {
item.set_attribute(ATTR_GRADIENT_MODEL, _model);
}
if needs_direction {
item.set_attribute(ATTR_GRADIENT_DIRECTION, _direction);
}
}
Graphic::GradientList(list) => {
if needs_curvatures {
@@ -497,6 +518,13 @@ where
*value = transform;
}
}
if needs_model {
list.iter_attribute_values_mut_or_default::<GradientModel>(ATTR_GRADIENT_MODEL).for_each(|value| *value = _model);
}
if needs_direction {
list.iter_attribute_values_mut_or_default::<GradientDirection>(ATTR_GRADIENT_DIRECTION)
.for_each(|value| *value = _direction);
}
}
_ => {}
}
@@ -4944,6 +4972,51 @@ mod test {
assert!(appearance.has_painted_cover(Cover::Fill), "the fill of a rank-0 vector should be styled like a list element");
}
// Fill gives a gradient it paints its model and direction where the gradient lacks them, unless they're the defaults an absent one reads as
#[test]
fn fill_stamps_a_gradients_model_and_direction_only_where_missing() {
let filled = |gradient: Item<Gradient>, model: GradientModel, direction: GradientDirection| {
let square = create_vector_item(Rect::new(0., 0., 10., 10.).to_path(DEFAULT_ACCURACY), DAffine2::IDENTITY);
let filled = super::fill(
Footprint::default(),
square,
item(Graphic::Gradient(gradient)),
item(Color::BLACK),
item(Gradient::default()),
item(0.),
item(0.),
item(false),
item(DAffine2::IDENTITY),
item(model),
item(direction),
);
let appearance = filled.attribute::<Appearance>(ATTR_APPEARANCE).expect("the fill should give the square an appearance");
let Some(Graphic::Gradient(gradient)) = appearance.first_paint_of(Cover::Fill) else {
panic!("the fill should paint the gradient")
};
(
gradient.attribute::<GradientModel>(ATTR_GRADIENT_MODEL).copied(),
gradient.attribute::<GradientDirection>(ATTR_GRADIENT_DIRECTION).copied(),
)
};
let plain = item(Gradient::from(vec![Color::BLACK, Color::WHITE]));
assert_eq!(filled(plain.clone(), GradientModel::Standard, GradientDirection::Along), (None, None));
assert_eq!(
filled(plain.clone(), GradientModel::Apollonian, GradientDirection::Across),
(Some(GradientModel::Apollonian), Some(GradientDirection::Across))
);
// A gradient's own model and direction stay, even at their defaults
let own = plain
.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Standard)
.with_attribute(ATTR_GRADIENT_DIRECTION, GradientDirection::Along);
assert_eq!(
filled(own, GradientModel::Apollonian, GradientDirection::Across),
(Some(GradientModel::Standard), Some(GradientDirection::Along))
);
}
// Fill's automatic gradient placement measures rank-0 vector content instead of falling back to the unit box
#[test]
fn vector_item_mut_reaches_a_rank_0_vector_graphic() {