Compare commits

..
55 changed files with 4544 additions and 793 deletions

No files matched your search

+5 -2
View File
@@ -29,6 +29,8 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
const MAX_RUN_PAGES = 10;
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
const VERDICT_STEP_NAME = "Fail for the title's verdict";
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
const MAX_VERDICT_LOOKUPS = 5;
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
@@ -175,14 +177,15 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
return newestFirst(runs);
}
// The newest of the finished runs that reached a verdict on its title, skipping failures that didn't (such as when GitHub or the review service couldn't be reached)
// The newest finished run that reached a verdict on its title, skipping those that didn't (as when a service was unreachable or the title changed mid-run)
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
const run = finishedRunsNewestFirst[i];
if (run.conclusion === "success") return run;
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
const steps = jobs.flatMap((job) => job.steps || []);
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
if (run.conclusion === "success") return run;
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
}
+4 -3
View File
@@ -37,6 +37,7 @@ const pullRequestNumber = readEvent().pull_request.number;
const decision = readDecision();
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
const passed = PASSING_OUTCOMES.includes(decision.outcome);
const superseded = decision.outcome === "superseded";
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
@@ -47,10 +48,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
}
}
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
// The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
const result = passed ? "approved" : retried ? "retry" : "verdict";
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict";
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
function readDecision(): Decision {
+6 -1
View File
@@ -64,7 +64,12 @@ jobs:
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
run: exit 1
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
- name: ⏭️ Pass for a newer run's review
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
run: echo "A newer run reviews the changed title"
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
- name: 🔁 Fail without a verdict
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
run: exit 1
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=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -8099,7 +8099,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -8113,7 +8113,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
dependencies = [
"naga",
"wesl",
+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 = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
@@ -0,0 +1,111 @@
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
const GRADIENT_FORM: u32 = 4;
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
/// 'Fill' gives the gradient it paints the curvatures of a form, rather than the form: 0 and 0 for linear, and -1 and 0.5 for radial.
/// A wired form becomes linear, and the curvatures stay shown in the graph where the form was.
#[migration("graphene_core::vector::FillNode"@1 => @2)]
pub fn fill_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
let Some(form) = node.inputs().get(GRADIENT_FORM as usize) else {
return Err(MigrationError::invariant("Fill has a gradient form input"));
};
let [start, end] = match literal_of::<Tagged>(&form.input) {
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
_ => [0., 0.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(GRADIENT_FORM, curvature(start));
inputs.insert(GRADIENT_FORM + 1, curvature(end));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
const FORM_SLOT: usize = GRADIENT_FORM as usize;
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
fn form(form: GradientForm) -> NodeInput {
literal(Tagged::GradientForm(form))
}
fn contract() -> SourceContract {
SourceContract::new(7, |random, slot| match slot {
FORM_SLOT if random.below(2) == 0 => form(GradientForm::Radial),
FORM_SLOT => form(GradientForm::Linear),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
#[test]
fn rewrites_history() {
check_commutation(&FillV1, &contract());
check_undo(&FillV1, &contract());
}
#[test]
fn forms_become_their_curvature_presets() {
let other_inputs: Vec<NodeInput> = (0..7).map(|index| literal(Tagged::Number(index as f64))).collect();
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// The curvatures stay shown in the graph where an exposed or wired form was, and the inputs after them keep their values
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
let mut old_inputs = other_inputs.clone();
old_inputs[FORM_SLOT] = old_form;
let mut fixture = Fixture::new(&FillV1);
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@1), old_inputs);
let migrated = fixture.migrate(&FillV1).unwrap();
let mut expected = other_inputs.clone();
expected.splice(FORM_SLOT..=FORM_SLOT, [curvature(start, exposed), curvature(end, exposed)]);
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@2)));
assert_eq!(fixture.inputs(&migrated, fill), expected);
}
}
}
@@ -1,5 +1,7 @@
//! Migrations of the nodes in `graphene_core`.
mod fill_v1;
mod passthrough_from_read_attribute_gradient_form_node;
mod passthrough_from_upload_texture_node;
mod renames;
mod vary_colors_from_assign_colors;
@@ -0,0 +1,36 @@
use migration_core::{Inputs, migration};
/// 'Read Attribute Gradient Form' is gone since no node writes that attribute anymore, so it passes its content on and drops the attribute name.
#[migration("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
pub fn passthrough_from_read_attribute_gradient_form_node(inputs: &mut Inputs) {
inputs.truncate(1);
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&PassthroughFromReadAttributeGradientFormNode, &contract());
check_undo(&PassthroughFromReadAttributeGradientFormNode, &contract());
}
#[test]
fn keeps_the_content_and_drops_the_name() {
let (content, name) = (literal(1.), literal("gradient_form".to_string()));
let mut fixture = Fixture::new(&PassthroughFromReadAttributeGradientFormNode);
let read_attribute = fixture.add(decl!("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1), vec![content.clone(), name]);
let migrated = fixture.migrate(&PassthroughFromReadAttributeGradientFormNode).unwrap();
assert_eq!(fixture.declaration_of(&migrated, read_attribute), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
assert_eq!(fixture.inputs(&migrated, read_attribute), [content]);
}
}
@@ -0,0 +1,127 @@
use migration_core::attr::node::ui::DISPLAY_NAME;
use migration_core::{Attributes, Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variants this migration uses.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
#[serde(alias = "GradientType")]
GradientForm(GradientForm),
}
#[derive(Serialize, Deserialize)]
enum GradientForm {
Linear,
Radial,
}
const FORM: u32 = 1;
/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, -1 and 0.5 for
/// radial. A wired form becomes linear, the curvatures stay shown in the graph where the form was, and a name it stored as its default is cleared.
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
let [_, form] = node.inputs() else {
return Err(MigrationError::invariant("Gradient Form has two inputs"));
};
let [start, end] = match literal_of::<Tagged>(&form.input) {
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
_ => [0., 0.],
};
let exposed = match form.input {
NodeInput::Value { exposed, .. } => exposed,
_ => true,
};
let curvature = |curvature: f64| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
inputs.set(FORM, curvature(start));
inputs.push(curvature(end));
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
attributes.remove(node.id(), DISPLAY_NAME);
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use document_graph_storage::TimeStamp;
use migration_core::{decl, literal};
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn form(form: GradientForm) -> NodeInput {
literal(Tagged::GradientForm(form))
}
fn contract() -> SourceContract {
SourceContract {
display_names: &["Gradient Form"],
..SourceContract::new(2, |random, slot| match slot {
1 if random.below(2) == 0 => form(GradientForm::Radial),
1 => form(GradientForm::Linear),
_ => literal(Tagged::Number(random.below(10) as f64)),
})
}
}
#[test]
fn rewrites_history() {
check_commutation(&GradientCurvatureFromGradientForm, &contract());
check_undo(&GradientCurvatureFromGradientForm, &contract());
}
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
#[derive(Serialize)]
enum LegacyTagged {
GradientType(GradientForm),
}
#[test]
fn forms_become_their_curvature_presets() {
let gradient = literal(Tagged::Number(0.));
let shown_radial = NodeInput::Value {
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
exposed: true,
};
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
value: encode(&Tagged::Number(curvature)),
exposed,
};
// Curvatures stay shown in the graph where an exposed or wired form was
for (old_form, [start, end], exposed) in [
(form(GradientForm::Linear), [0., 0.], false),
(form(GradientForm::Radial), [-1., 0.5], false),
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
(shown_radial, [-1., 0.5], true),
(NodeInput::Import { index: 0 }, [0., 0.], true),
] {
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), curvature(start, exposed), curvature(end, exposed)]);
}
}
#[test]
fn only_the_old_default_name_is_cleared() {
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
}
}
}
@@ -1,4 +1,5 @@
//! Migrations of the nodes in `math_nodes`.
mod gradient_curvature_from_gradient_form;
mod math_formula_from_math_f;
mod renames;
@@ -31,7 +31,8 @@ use graphene_std::vector::misc::{
WeldMethod,
};
use graphene_std::vector::style::{
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
StrokeJoin,
};
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
use graphene_std::{
@@ -408,7 +409,6 @@ macro_rules! inspectable_types {
List<DVec2>,
List<DAffine2>,
List<BlendMode>,
List<GradientForm>,
List<GradientSpread>,
List<GradientSpace>,
List<GradientHueDirection>,
@@ -469,6 +469,7 @@ macro_rules! inspectable_types {
Item<DAffine2>,
Item<BlendMode>,
Item<GradientForm>,
Item<GradientModel>,
Item<GradientSpread>,
Item<GradientSpace>,
Item<GradientHueDirection>,
@@ -1284,6 +1285,7 @@ impl_table_item_layout_for_choice_enum!(
MaskMode,
MinimumMaximumMode,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -1479,6 +1481,7 @@ macro_rules! known_item_types {
TransferCurve,
BlendMode,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -26,7 +26,8 @@ pub enum GraphOperationMessage {
layer: LayerNodeIdentifier,
#[serde(skip)]
gradient: Gradient,
gradient_form: GradientForm,
/// The form whose curvatures the Fill takes, or `None` to keep its own.
gradient_form: Option<GradientForm>,
gradient_settings: GradientSettings,
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
transform: Option<DAffine2>,
@@ -1034,7 +1034,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
}
usvg::Paint::RadialGradient(radial) => {
let gradient_transform = usvg_transform(radial.transform());
@@ -1062,7 +1062,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
..Default::default()
};
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
}
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
};
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
use crate::messages::prelude::*;
use crate::messages::tool::common_functionality::graph_modification_utils::{
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain,
};
use glam::{DAffine2, DVec2, IVec2};
use graph_craft::application_io::resource::ResourceId;
@@ -450,7 +450,8 @@ impl<'a> ModifyInputsContext<'a> {
}
}
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
/// Paints the layer's Fill with `gradient`, giving its curvatures those of `gradient_form` if that's given, unless the graph feeds them.
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
return;
@@ -490,11 +491,22 @@ impl<'a> ModifyInputsContext<'a> {
}
}
self.set_input_with_refresh(
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
false,
);
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
if let Some(gradient_form) = gradient_form
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
{
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let [start_curvature, end_curvature] = gradient_form.curvatures();
self.set_input_with_refresh(
InputConnector::node(fill_node_id, StartCurvatureInput),
NodeInput::value(TaggedValue::Number(start_curvature), false),
true,
);
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
}
self.responses.add(NodeGraphMessage::RunDocumentGraph);
if existing_fill_node_id.is_none() {
self.restore_default_stroke_order();
@@ -761,20 +773,28 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
let Some(curvatures) = gradient_curvature_values(node) else { return };
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
return;
}
let [start, end] = gradient_form.curvatures();
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -686,6 +686,7 @@ fn static_node_inspector() -> NodeInspector {
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
@@ -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, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
build_transform_with_y_preservation,
FillChoice, Gradient, 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};
@@ -254,6 +254,23 @@ pub(crate) struct ParameterOptions {
pub step: Option<f64>,
}
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
fn from(field: &graphene_std::registry::FieldMetadata) -> Self {
Self {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
}
}
}
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
#[derive(Clone, Copy)]
pub struct SliderRange {
@@ -417,6 +434,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
// AUTO-GENERATED ENUM TYPES
// =========================
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::<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(),
@@ -3023,7 +3041,7 @@ pub(crate) fn spiral_inspector(node_id: NodeId, context: &mut NodeInspectorConte
let angular_resolution = number_widget(
ParameterWidgetsInfo::new(node_id, AngularResolutionInput, true, context),
NumberInput::default().min(0.).max(180.).range_min(Some(1.)).unit("°"),
NumberInput::default().min(1.).max(180.).unit("°"),
);
widgets.push(LayoutGroup::row(angular_resolution));
@@ -3286,6 +3304,80 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
}
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
let curvatures = match get_document_node(node_id, context) {
Ok(document_node) => graph_modification_utils::gradient_curvature_values(document_node),
Err(err) => {
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
return Vec::new();
}
};
// Each form's button sets both curvatures to the form's own, and stands out while they make that form
let mut form = vec![
TextLabel::new("Form")
.tooltip_label("Form")
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
.widget_instance(),
];
add_blank_assist(&mut form);
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
for (label, gradient_form, tooltip) in [
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
(
"Radial",
GradientForm::Radial,
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
),
] {
let [start, end] = gradient_form.curvatures();
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
.disabled(curvatures.is_none())
.on_update(move |_: &TextButton| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
.widget_instance(),
);
}
// The same sliders the parameters would get without this panel
let options = |index: usize| {
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
field.map(ParameterOptions::from).unwrap_or_default()
};
let mut row = |index: usize, ty: Type| {
context
.call_widget_override(&node_id, index)
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
};
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -3443,18 +3535,7 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
.get(&proto_node_identifier)
.and_then(|metadata| metadata.fields.get(input_index))
{
options = ParameterOptions {
soft_min: field.number_soft_min,
soft_max: field.number_soft_max,
hard_min: field.number_hard_min,
hard_max: field.number_hard_max,
slider: field.number_mode_range,
multiline: field.multiline,
progression: field.progression,
unit: field.unit,
display_decimal_places: field.number_display_decimal_places,
step: field.number_step,
};
options = ParameterOptions::from(field);
default_type = field.default_type.clone();
}
@@ -3843,9 +3924,25 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
let entries = [GradientForm::Linear, GradientForm::Radial]
.iter()
.map(|&gradient_form| {
let [start, end] = gradient_form.curvatures();
RadioEntryData::new(format!("{:?}", gradient_form))
.label(gradient_form.to_string())
.on_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
.on_update(move |_| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
})
.collect();
@@ -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(), 7, "the legacy Fill should upgrade to the 7-input shape");
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
assert!(
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
@@ -1033,7 +1033,13 @@ 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(), 7, "the eight-input Fill should fold down to the 7-input shape");
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
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,
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
"the linear form should become its curvatures"
);
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
@@ -21,7 +21,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -181,10 +181,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphic_nodes::graphic::ExtractElementNode",
],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
},
NodeReplacement {
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
@@ -301,10 +297,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
aliases: &["math_nodes::GradientTypeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -1689,6 +1681,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", with its two curvatures taking the presets of the form it set
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
})
.collect();
for (node_id, network_path) in &gradient_form_nodes {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
reset_default_display_name(document, node_id, network_path, "Gradient Form");
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(GradientForm::Radial)) => GradientForm::Radial.curvatures(),
Some(TaggedValue::GradientForm(GradientForm::Linear)) => GradientForm::Linear.curvatures(),
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
GradientForm::Linear.curvatures()
}
};
// The curvatures stay shown in the graph where an exposed or wired form was
let exposed = old_inputs.get(1).is_some_and(NodeInput::is_exposed);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), exposed), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), exposed), network_path);
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
@@ -2494,6 +2532,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// The 7-input shape's own gradient metadata defaults, which the steps after this one read until the legacy fill's values replace them below
let metadata_defaults = [
TaggedValue::GradientForm(GradientForm::Linear),
TaggedValue::Bool(false),
TaggedValue::DAffine2(glam::DAffine2::IDENTITY),
];
for (index, value) in (4..).zip(metadata_defaults) {
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
}
// Content: no change
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
@@ -2637,8 +2687,11 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
// so this era is told apart by its form at 4 or its spread at 5, either of which may be wired, where the modern shape holds curvatures.
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
let is_spread_method_fill = inputs_count == 8 && (matches!(value_at(4), Some(TaggedValue::GradientForm(_))) || matches!(value_at(5), Some(TaggedValue::GradientSpread(_))));
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && is_spread_method_fill {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
@@ -2661,6 +2714,36 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 7;
}
// The Fill node gives its gradient paint the curvatures of a form in place of its `_gradient_form` input, and they stay shown in the graph where the form was
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
// Content, paint, and backups keep their places, and the transform inputs move past the second curvature
for (index, input) in old_inputs.iter().enumerate().take(7) {
let index = match index {
4 => continue,
5.. => index + 1,
_ => index,
};
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
let form = old_inputs.get(4);
let curvatures = match form.and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(form)) => form.curvatures(),
_ => GradientForm::Linear.curvatures(),
};
let exposed = form.is_some_and(NodeInput::is_exposed);
for (index, curvature) in (4..).zip(curvatures) {
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(TaggedValue::Number(curvature), exposed), network_path);
}
inputs_count = 8;
}
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -4116,6 +4199,20 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// The removed Read Attribute Gradient Form node, under either of its names, degrades to a passthrough of its content
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
&& ["::ReadAttributeGradientFormNode", "::ReadAttributeGradientTypeNode"]
.iter()
.any(|name| identifier.as_str().ends_with(name))
{
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
}
}
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
@@ -4878,6 +4975,40 @@ mod tests {
);
}
// Read Attribute Gradient Form, under either of its names, opens as a passthrough of its content
#[test]
fn read_attribute_gradient_form_opens_as_a_passthrough() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
let name = NodeInput::value(TaggedValue::String("gradient_form".into()), false);
let identifiers = ["graphic_nodes::graphic::ReadAttributeGradientFormNode", "graphic_nodes::graphic::ReadAttributeGradientTypeNode"];
let nodes = identifiers
.iter()
.enumerate()
.map(|(index, &identifier)| {
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![content.clone(), name.clone()],
..Default::default()
};
(NodeId(index as u64), node_template)
})
.collect::<Vec<_>>();
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
for (index, identifier) in identifiers.iter().enumerate() {
let node = opened.network_interface.document_node(&NodeId(index as u64), &[]).expect("the node should still exist");
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), "{identifier}");
assert_eq!(node.inputs, [content.clone()], "{identifier}");
}
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
#[test]
fn every_into_group_alias_resets_the_merge_definition() {
@@ -5440,6 +5571,204 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
// Curvatures stay shown in the graph where an exposed form was
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, curvatures, exposed) in [
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
] {
let mut document = DocumentMessageHandler::default();
let placeholder = || NodeInput::value(TaggedValue::None, false);
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![placeholder()],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
form_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![placeholder(); 2],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), exposed), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&form_id];
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(
[curvature(1), curvature(2)],
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
"{form:?} should become its curvature presets"
);
assert_eq!(
[1, 2].map(|index| node.inputs[index].is_exposed()),
[exposed; 2],
"{form:?} exposed {exposed} should leave its curvatures so"
);
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
}
}
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
#[test]
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use glam::DAffine2;
let (source_id, fill_id) = (NodeId(1), NodeId(2));
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
let old_inputs = vec![
NodeInput::value(TaggedValue::None, false),
ramp(),
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
ramp(),
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
NodeInput::value(TaggedValue::None, false),
NodeInput::value(TaggedValue::Bool(true), false),
NodeInput::value(TaggedValue::DAffine2(placement), false),
];
let mut document = DocumentMessageHandler::default();
let source = NodeTemplate {
inputs: vec![NodeInput::value(TaggedValue::None, false)],
..Default::default()
};
document.network_interface.insert_node(source_id, source, &[]);
let fill = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
inputs: old_inputs,
..Default::default()
};
document.network_interface.insert_node(fill_id, fill, &[]);
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
migrate(&mut document);
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");
}
// 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
#[tokio::test]
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
use crate::test_utils::test_prelude::*;
use glam::DAffine2;
use graphene_std::graphic::extend;
use graphene_std::list::Item;
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
use graphene_std::vector::fill;
use graphene_std::vector::style::Gradient;
use graphene_std::vector_types::gradient_standard::GradientShape;
use graphene_std::{Appearance, Cover, Graphic};
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
let layer = instrumented
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
.next()
.expect("the layer is extended onto the root");
let mut render = SvgRender::new();
layer.element().render_svg(&mut render, &RenderParams::default());
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
let mut index = 0;
while let Some(found) = markup.find(r#"id=""#) {
let start = found + r#"id=""#.len();
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
index += 1;
}
let shape = match layer.element() {
Graphic::VectorList(vectors) => match vectors
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
{
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
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_TRANSFORM),
)),
_ => None,
},
_ => None,
};
(markup.replace(r#"ID=""#, r#"id=""#), shape)
}
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(10., 20., 110., 70.).await;
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
editor
.handle_message(GraphOperationMessage::FillGradientSet {
layer,
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
gradient_form: Some(GradientForm::Radial),
gradient_settings: Default::default(),
transform: Some(placement),
})
.await;
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
let (curved_svg, curved_shape) = painted(&mut editor).await;
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
assert_eq!(curved_shape, Some(GradientShape::Radial));
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
let document = editor.active_document_mut();
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
.upstream_node_id_from_protonode(fill::IDENTIFIER)
.expect("the layer has a Fill");
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
let mut old_inputs = NodeTemplate {
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
..Default::default()
};
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
let serialized = document.serialize_document();
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
editor
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
document_name: Some("Migrated".into()),
document_path: None,
document_serialized_content: serialized,
})
.await;
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
assert_eq!(migrated_svg, curved_svg);
assert_eq!(migrated_shape, curved_shape);
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -217,7 +217,7 @@ impl DrawingToolState {
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: graphene_std::vector::Gradient::from(&ramp),
gradient_form: Default::default(),
gradient_form: None,
gradient_settings: (&ramp).into(),
transform: None,
}),
@@ -14,7 +14,7 @@ use glam::DVec2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::FallibleVec2Operations;
use graphene_std::vector::algorithms::shapes::SpiralCurve;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
use std::f64::consts::TAU;
@@ -41,12 +41,13 @@ pub struct SpiralTurns {
pub handle_state: SpiralTurnsState,
initial_turns: f64,
initial_outer_radius: f64,
initial_spiral: SpiralCurve,
/// In degrees, as stored in the node.
initial_inner_radius: f64,
initial_growth_factor: f64,
initial_start_angle: f64,
previous_mouse_position: DVec2,
total_angle_delta: f64,
gizmo_type: GizmoType,
spiral_type: SpiralType,
}
impl SpiralTurns {
@@ -83,10 +84,12 @@ impl SpiralTurns {
) {
self.layer = Some(layer);
self.initial_turns = turns;
self.initial_growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
self.initial_inner_radius = inner_radius;
self.initial_outer_radius = outer_radius;
self.initial_spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
self.initial_start_angle = start_angle;
self.previous_mouse_position = mouse_position;
self.spiral_type = spiral_type;
self.gizmo_type = gizmo_type;
self.update_state(SpiralTurnsState::Hover);
}
@@ -97,9 +100,9 @@ impl SpiralTurns {
match &self.handle_state {
SpiralTurnsState::Inactive => {
if let Some((spiral_type, start_angle, inner_radius, outer_radius, turns, _)) = extract_spiral_parameters(layer, document) {
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
let end_point = viewport.transform_point2(spiral.point(turns * TAU));
let start_point = viewport.transform_point2(spiral.point(0.));
let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
let end_point = viewport.transform_point2(spiral_point(turns * TAU + start_angle.to_radians(), inner_radius, growth_factor, spiral_type));
let start_point = viewport.transform_point2(spiral_point(0. + start_angle.to_radians(), inner_radius, growth_factor, spiral_type));
if mouse_position.distance(end_point) < SPIRAL_END_HOVER_RADIUS {
self.store_initial_parameters(layer, inner_radius, outer_radius, turns, start_angle, mouse_position, GizmoType::End, spiral_type);
@@ -141,27 +144,17 @@ impl SpiralTurns {
/// How much the outer radius grows as the spiral gains a number of turns, keeping its growth and tightness the same.
fn outer_radius_change(&self, turns_gained: f64) -> f64 {
let growth_factor = self.initial_spiral.growth_factor;
match self.initial_spiral.spiral_type {
SpiralType::Archimedean => turns_gained * growth_factor * TAU,
SpiralType::Logarithmic => self.initial_outer_radius * ((growth_factor * TAU * turns_gained).exp() - 1.),
match self.spiral_type {
SpiralType::Archimedean => turns_gained * self.initial_growth_factor * TAU,
SpiralType::Logarithmic => self.initial_outer_radius * ((self.initial_growth_factor * TAU * turns_gained).exp() - 1.),
}
}
/// The start angle in degrees, the turns, and the inner radius that dragging the start writes for a number of turns.
/// The start moves along the spiral as turns come off or are added, leaving the rest of the spiral where it was.
/// The start angle in degrees, the turns, and the outer radius that dragging the start writes for a number of turns, which turns the start along as turns come off.
fn start_dragged_to(&self, turns: f64) -> (f64, f64, f64) {
let spiral = self.initial_spiral;
let mut turns = turns.max(0.5);
// An Archimedean spiral gains turns at its start only until its radius there shrinks to the center
if spiral.spiral_type == SpiralType::Archimedean && spiral.growth_factor > 0. {
turns = turns.min(self.initial_turns + spiral.inner_radius / (spiral.growth_factor * TAU));
}
let turns_taken_off = self.initial_turns - turns;
let inner_radius = spiral.radius(turns_taken_off * TAU).max(0.);
(self.initial_start_angle + turns_taken_off * 360., turns, inner_radius)
let outer_radius = (self.initial_outer_radius + self.outer_radius_change(-turns_taken_off)).max(0.1);
(self.initial_start_angle + turns_taken_off * 360., turns.max(0.5), outer_radius)
}
/// Snaps a number of turns to whole and half turns, judged by how far the pointer travels around the center on screen.
@@ -178,17 +171,17 @@ impl SpiralTurns {
let layer_to_viewport = document.metadata().transform_to_viewport(layer);
let on_screen_per_turn = TAU * pointer_travel_per_radian(layer_to_viewport, view.input.mouse.position);
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
let growth_factor = calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type);
let viewport_to_document = document.metadata().document_to_viewport.inverse();
let position_of = |turns_landed_on: f64| {
let point = match self.gizmo_type {
let (angle, growth_factor) = match self.gizmo_type {
GizmoType::Start => {
let (start_angle, turns, inner_radius) = self.start_dragged_to(turns_landed_on);
SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians()).point(0.)
let (start_angle, turns, outer_radius) = self.start_dragged_to(turns_landed_on);
(start_angle.to_radians(), calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type))
}
_ => spiral.point(turns_landed_on * TAU),
_ => (turns_landed_on * TAU + start_angle.to_radians(), growth_factor),
};
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(point))
viewport_to_document.transform_point2(layer_to_viewport.transform_point2(spiral_point(angle, inner_radius, growth_factor, spiral_type)))
};
// The whole and half turns around the asked-for number, counted in half turns
@@ -230,8 +223,9 @@ impl SpiralTurns {
return;
}
// The total angle dragged around the center, in degrees, as a number of full turns
// Increase the number of turns and outer radius in unison such that growth and tightness remain same
let total_delta = self.total_angle_delta + angle_delta;
// Convert the total angle (in degrees) to number of full turns
let turns_delta = total_delta / 360.;
// Dragging the start takes turns away rather than adding them
@@ -244,16 +238,21 @@ impl SpiralTurns {
let snap_correction = (self.snap_turns(view, snap_session, layer, free_turns) - free_turns) * direction;
let turns_delta = turns_delta + snap_correction;
// Calculate the new outer radius based on spiral type and turn change
let outer_radius_change = self.outer_radius_change(turns_delta);
// Skip if outer_radius calculation produced invalid values
if !outer_radius_change.is_finite() {
return;
}
let Some(node_id) = graph_modification_utils::get_spiral_id(layer, &document.network_interface) else {
return;
};
match self.gizmo_type {
GizmoType::Start => {
let (new_start_angle, new_turns, new_inner_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
if !new_inner_radius.is_finite() {
return;
}
let (new_start_angle, new_turns, new_outer_radius) = self.start_dragged_to(self.initial_turns - turns_delta);
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, StartAngleInput),
@@ -264,17 +263,12 @@ impl SpiralTurns {
input: NodeInput::value(TaggedValue::Number(new_turns), false),
});
responses.add(NodeGraphMessage::SetInput {
input_connector: InputConnector::node(node_id, InnerRadiusInput),
input: NodeInput::value(TaggedValue::Number(new_inner_radius), false),
input_connector: InputConnector::node(node_id, OuterRadiusInput),
input: NodeInput::value(TaggedValue::Number(new_outer_radius), false),
});
}
GizmoType::End => {
// The outer radius grows by the turns actually gained, so the spiral keeps its growth and tightness
let new_turns = (self.initial_turns + turns_delta).max(0.5);
let outer_radius_change = self.outer_radius_change(new_turns - self.initial_turns);
if !outer_radius_change.is_finite() {
return;
}
let new_outer_radius = (self.initial_outer_radius + outer_radius_change).max(0.1);
responses.add(NodeGraphMessage::SetInput {
@@ -346,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
// A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -428,6 +428,17 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
}
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
}
/// Get the gradient stops of a layer, if any.
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
// Try to find the gradient stops value that is created by a Fill node first
@@ -830,9 +841,23 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
}
}
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
&TaggedValue::Number(value) => Some(value),
_ => None,
};
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
}
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
pub struct FillNodeGradient {
pub stops: Gradient,
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
pub curvatures: Option<[f64; 2]>,
/// The form its curvatures make, which is linear for any that make neither.
pub gradient_form: GradientForm,
pub settings: GradientSettings,
pub transform: DAffine2,
@@ -849,10 +874,8 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
};
let settings = GradientSettings::from(ramp);
let stops = Gradient::from(ramp);
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
Some(&TaggedValue::GradientForm(value)) => value,
_ => GradientForm::default(),
};
let curvatures = fill_node_curvatures(fill_node);
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
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) {
@@ -863,6 +886,7 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
Some(FillNodeGradient {
stops,
curvatures,
gradient_form,
settings,
transform,
@@ -1005,10 +1029,6 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
use graphene_std::vector::fill;
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
Some(TaggedValue::GradientForm(value)) => *value,
_ => GradientForm::default(),
};
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
(true, Some(TaggedValue::DAffine2(value))) => *value,
@@ -1019,7 +1039,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: Gradient::from(ramp),
gradient_form,
gradient_form: None,
gradient_settings: ramp.into(),
transform: Some(transform),
});
@@ -14,7 +14,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::algorithms::shapes::SpiralCurve;
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, spiral_point};
use graphene_std::vector::misc::SpiralType;
use std::collections::VecDeque;
@@ -83,10 +83,11 @@ impl ShapeGizmoHandler for SpiralGizmoHandler {
/// Calculates the position of a spiral endpoint at a given angle offset (0 = start, TAU = end).
pub fn calculate_spiral_endpoints(layer: LayerNodeIdentifier, document: &DocumentMessageHandler, viewport: DAffine2, theta: f64) -> Option<DVec2> {
let (spiral_type, start_angle, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document)?;
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians());
let (spiral_type, start_angle, a, outer_radius, turns, _) = extract_spiral_parameters(layer, document)?;
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
let theta = turns * theta + start_angle.to_radians();
Some(viewport.transform_point2(spiral.point(turns * theta)))
Some(viewport.transform_point2(spiral_point(theta, a, b, spiral_type)))
}
#[derive(Default)]
@@ -29,6 +29,8 @@ pub struct GradientTool {
#[derive(Default)]
pub struct GradientOptions {
gradient_form: GradientForm,
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
curvature_source: CurvatureSource,
settings: GradientSettings,
}
@@ -92,12 +94,16 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
GradientOptionsUpdate::Form(gradient_form) => {
self.options.gradient_form = gradient_form;
self.options.curvature_source = CurvatureSource::Form;
apply_gradient_update(
&mut self.data,
context,
responses,
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|(_gradient, appearance)| {
appearance.gradient_form = gradient_form;
appearance.curvature_source = CurvatureSource::Form;
},
);
responses.add(ToolMessage::UpdateHints);
responses.add(ToolMessage::UpdateCursor);
@@ -192,14 +198,19 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
let mut needs_refresh = false;
if let Some((_gradient, appearance)) = &current_gradient {
if self.options.gradient_form != appearance.gradient_form {
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source {
self.options.gradient_form = appearance.gradient_form;
self.options.curvature_source = appearance.curvature_source;
needs_refresh = true;
}
if self.options.settings != appearance.settings {
self.options.settings = appearance.settings;
needs_refresh = true;
}
} else if self.options.curvature_source != CurvatureSource::Form {
// With no gradient selected, the Form radio shows the form a new one gets
self.options.curvature_source = CurvatureSource::Form;
needs_refresh = true;
}
let has_gradient = current_gradient.is_some();
@@ -261,7 +272,11 @@ impl LayoutHolder for GradientTool {
}
.into()
});
let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32);
let gradient_form = RadioInput::new(gradient_form_entries)
.selected_index(selected_form)
.disabled(self.options.curvature_source == CurvatureSource::Graph)
.widget_instance();
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
let stops_value = self
@@ -381,10 +396,12 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
return Some((
gradient.stops,
GradientAppearance {
gradient_form: gradient.gradient_form,
gradient_form,
curvature_source,
settings: gradient.settings,
transform: gradient.transform,
},
@@ -404,19 +421,48 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
struct GradientAppearance {
transform: DAffine2,
gradient_form: GradientForm,
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
curvature_source: CurvatureSource,
settings: GradientSettings,
}
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
enum CurvatureSource {
/// They make the form, or there's no node and the form's are implied.
#[default]
Form,
/// They're values that make neither form.
Custom,
/// They're fed from the graph or exposed, so only the graph can change them.
Graph,
}
impl CurvatureSource {
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
let form = curvatures.and_then(GradientForm::from_curvatures);
let source = match (curvatures, form) {
(None, _) => Self::Graph,
(Some(_), None) => Self::Custom,
(Some(_), Some(_)) => Self::Form,
};
(form.unwrap_or_default(), source)
}
}
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
let target_input = gradient_chain_target_input(layer, network_interface);
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
let mut curvature_source = CurvatureSource::Form;
for node_id in network_interface
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
@@ -430,11 +476,9 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_form_reference
&& gradient_form.is_none()
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
(gradient_form, curvature_source) = (Some(form), source);
}
}
@@ -444,6 +488,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
GradientAppearance {
transform: composed_transform,
gradient_form: gradient_form.unwrap_or_default(),
curvature_source,
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
}
}
@@ -793,12 +838,15 @@ impl SelectedGradient {
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
if let Some(layer) = self.layer {
if self.is_gradient_chain {
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected
let write_form = self.dragging == GradientDragTarget::New;
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
} else {
// Only a new gradient takes its form from the tool, as with a chain
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: self.gradient.clone(),
gradient_form: self.appearance.gradient_form,
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
gradient_settings: self.appearance.settings,
transform: Some(self.appearance.transform),
});
@@ -829,8 +877,8 @@ impl SelectedGradient {
}
}
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
/// 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 {
layer,
gradient_cyclic: appearance.settings.cyclic,
@@ -848,10 +896,12 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
layer,
transform: appearance.transform,
});
responses.add(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: appearance.gradient_form,
});
if write_form && appearance.curvature_source == CurvatureSource::Form {
responses.add(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: appearance.gradient_form,
});
}
responses.add(GraphOperationMessage::GradientSpreadSet {
layer,
gradient_spread: appearance.settings.spread,
@@ -1522,6 +1572,7 @@ impl Fsm for GradientToolFsmState {
GradientAppearance {
transform: DAffine2::IDENTITY,
gradient_form: tool_options.gradient_form,
curvature_source: CurvatureSource::Form,
settings: tool_options.settings,
},
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
@@ -1940,12 +1991,13 @@ fn apply_gradient_update(
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
// Read fresh from the layer, so its form's curvatures change only if the update chose another form
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
} else {
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient,
gradient_form: appearance.gradient_form,
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
gradient_settings: appearance.settings,
transform: Some(appearance.transform),
});
@@ -2011,7 +2063,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
responses.add(GraphOperationMessage::FillGradientSet {
layer,
gradient: new_gradient.clone(),
gradient_form: appearance.gradient_form,
gradient_form: None,
gradient_settings: settings,
transform: Some(appearance.transform),
});
@@ -2108,6 +2160,7 @@ mod test_gradient {
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
@@ -2115,8 +2168,8 @@ mod test_gradient {
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
pub use crate::test_utils::test_prelude::*;
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{NodeId, NodeInput};
use graphene_std::NodeParameter;
use graphene_std::color::SRGBA8;
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
@@ -3366,7 +3419,7 @@ mod test_gradient {
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3375,7 +3428,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3384,10 +3437,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Form node should have been inserted")
.expect("Gradient Curvature node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
@@ -3532,6 +3585,347 @@ mod test_gradient {
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
}
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
let dragged_end = end + offset;
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
editor
.mouseup(
EditorPointerState {
editor_position: dragged_end,
mouse_keys: MouseKeys::empty(),
..Default::default()
},
ModifierKeys::empty(),
)
.await;
dragged_end
}
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
editor.active_document_mut().snapping_state.snapping_enabled = false;
let layer = create_gradient_list_layer(editor).await;
editor
.handle_message(GraphOperationMessage::GradientTransformSet {
layer,
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
})
.await;
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
})
.await;
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let network_interface = &editor.active_document().network_interface;
let curvature_node_id = network_interface
.document_network()
.nodes
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
.expect("Gradient Curvature node should have been inserted");
assert_eq!(
curvature_inputs(editor, curvature_node_id),
inputs_holding(GradientForm::Radial.curvatures()),
"the inserted node should hold the radial form's curvatures"
);
(layer, curvature_node_id)
}
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
editor
.handle_message(NodeGraphMessage::SetInputValue {
node_id: curvature_node_id,
input_index,
value: TaggedValue::Number(curvature).into(),
})
.await;
}
}
/// The start and end curvature inputs of a 'Gradient Curvature' node.
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
}
/// The curvature inputs holding these values.
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
}
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
_ => None,
};
frontend_messages
.iter()
.rev()
.filter_map(|message| match message {
FrontendMessage::UpdateLayout {
layout_target: LayoutTarget::ToolOptions,
diff,
} => Some(diff),
_ => None,
})
.flat_map(|diff| diff.iter().rev())
.find_map(|widget_diff| match &widget_diff.new_value {
DiffUpdate::Widget(widget) => form_radio(widget),
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
})
}
#[tokio::test]
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
// Choosing a form in the control bar is what sets them
editor
.handle_message(GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
})
.await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding(GradientForm::Linear.curvatures()),
"choosing the linear form should set its curvatures"
);
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
})
.await;
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
editor
.handle_message(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: GradientForm::Radial,
})
.await;
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
assert_eq!(
end_input,
inputs_holding(GradientForm::Linear.curvatures())[1],
"the end curvature beside a wired one should stay as it was"
);
}
#[tokio::test]
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
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");
let curvatures = |editor: &EditorTestUtils| {
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
};
// Curvatures making neither form survive a drag of the gradient's end
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
let value = TaggedValue::Number(curvature).into();
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
}
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
// Choosing a form in the control bar is what sets them
let choose_form = |form| GradientToolMessage::UpdateOptions {
options: super::GradientOptionsUpdate::Form(form),
};
editor.handle_message(choose_form(GradientForm::Radial)).await;
assert_eq!(
curvatures(&editor),
inputs_holding(GradientForm::Radial.curvatures()),
"choosing the radial form should set its curvatures"
);
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
})
.await;
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
editor.handle_message(choose_form(GradientForm::Linear)).await;
let [start_input, end_input] = curvatures(&editor);
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
assert_eq!(
end_input,
inputs_holding(GradientForm::Radial.curvatures())[1],
"the end curvature beside a wired one should stay as it was"
);
}
#[tokio::test]
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
let document = editor.active_document();
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
editor.handle_message(GradientToolMessage::DoubleClick).await;
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([0.5, 0.5]),
"recoloring the stop shouldn't reset the curvatures"
);
editor.press(Key::Delete, ModifierKeys::empty()).await;
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([0.5, 0.5]),
"deleting the stop shouldn't reset the curvatures"
);
}
#[tokio::test]
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([1., 0.5]),
"a drag shouldn't rewrite curvatures making the form"
);
editor
.handle_message(GraphOperationMessage::GradientFormSet {
layer,
gradient_form: GradientForm::Radial,
})
.await;
assert_eq!(
curvature_inputs(&editor, curvature_node_id),
inputs_holding([1., 0.5]),
"setting the form they make shouldn't rewrite them"
);
}
#[tokio::test]
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
// Reselecting the layer has the tool read its curvatures, which make neither form
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
assert_eq!(
latest_form_radio(&frontend_messages),
Some((Some(GradientForm::Linear as u32), false)),
"with nothing selected, the radio should show the linear form a new gradient gets"
);
}
#[tokio::test]
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
editor
.handle_message(NodeGraphMessage::CreateWire {
output_connector: OutputConnector::primary_output(number_node_id),
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
})
.await;
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
assert_eq!(
latest_form_radio(&frontend_messages),
Some((None, true)),
"a wired curvature should leave no form chosen and the radio disabled"
);
}
#[tokio::test]
async fn drag_on_blank_layer_starts_gradient_chain() {
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
@@ -1654,7 +1654,7 @@ mod test_shape_tool {
use glam::DAffine2;
use graph_craft::document::NodeInput;
use graph_craft::document::value::TaggedValue;
use graphene_std::vector::algorithms::shapes::{SpiralCurve, heart_bezpath};
use graphene_std::vector::algorithms::shapes::{calculate_growth_factor, heart_bezpath};
use graphene_std::vector::generator_nodes::arc;
use graphene_std::vector::misc::{SpiralType, point_to_dvec2};
use kurbo::{Affine, CubicBez, ParamCurve, PathEl, PathSeg};
@@ -2213,17 +2213,12 @@ mod test_shape_tool {
let layer = draw_shape(&mut editor, ShapeType::Spiral, DVec2::new(300., 300.), DVec2::new(360., 300.)).await;
let turns_and_growth_factor_of = |document: &DocumentMessageHandler| {
let (spiral_type, start_angle, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters");
(turns, SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle.to_radians()).growth_factor)
};
let end_of = |document: &DocumentMessageHandler| {
let to_viewport = document.metadata().transform_to_viewport(layer);
calculate_spiral_endpoints(layer, document, to_viewport, TAU).expect("the spiral should have an end")
let (spiral_type, _, inner_radius, outer_radius, turns, _) = extract_spiral_parameters(layer, document).expect("the spiral should have its parameters");
(turns, calculate_growth_factor(inner_radius, turns, outer_radius, spiral_type))
};
let (turns, growth_factor) = turns_and_growth_factor_of(editor.active_document());
let end = end_of(editor.active_document());
// The start lands on a whole turn fewer, and the inner radius grows so the rest of the spiral stays where it was
// The start lands on a whole turn fewer, and the outer radius shrinks so the spiral keeps winding as it did
let whole = turns.ceil() - 1.;
let last = turn_spiral_start(&mut editor, layer, turns - (whole + 0.01)).await;
@@ -2234,9 +2229,6 @@ mod test_shape_tool {
"the growth factor is {dragged_growth_factor} rather than {growth_factor}"
);
let dragged_end = end_of(editor.active_document());
assert!(dragged_end.distance(end) < 1e-6, "the far end moved from {end} to {dragged_end}");
editor.left_mouseup(last.x, last.y, ModifierKeys::empty()).await;
}
@@ -558,9 +558,10 @@
margin-left: 8px;
}
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
@@ -570,6 +570,7 @@ tagged_value! {
StrokeAlign(vector::style::StrokeAlign),
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
GradientForm(vector::style::GradientForm),
GradientModel(vector::style::GradientModel),
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
GradientSpread(vector::style::GradientSpread),
GradientSpace(vector::style::GradientSpace),
@@ -26,7 +26,7 @@ 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, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::style::{DashPattern, 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};
@@ -68,7 +68,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientForm>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
@@ -271,6 +270,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
StrokeAlign,
StrokeCap,
GradientForm,
GradientModel,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -381,7 +381,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
DVec2,
DAffine2,
BlendMode,
GradientForm,
GradientSpread,
GradientSpace,
GradientHueDirection,
@@ -516,6 +515,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
attribute_value_node!(Item<Color>),
attribute_value_node!(Item<BlendMode>),
attribute_value_node!(Item<GradientForm>),
attribute_value_node!(Item<GradientModel>),
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_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
ATTR_TYPE,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_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;
+9 -3
View File
@@ -59,8 +59,14 @@ pub const ATTR_CLIP: &str = "clip";
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// Gradient's `f64` curvature for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, it's 0.
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
/// Gradient's `f64` curvature for the contour through its end, like `gradient_start_curvature` with the ends swapped.
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `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 `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
@@ -1714,7 +1720,7 @@ impl<T: CacheHash> CacheHash for List<T> {
self.element.as_slice().cache_hash(state);
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
// (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected
// (e.g., gradient_spread) invalidate downstream graph caches as expected
self.attributes.cache_hash_entries(state);
}
}
@@ -9,13 +9,17 @@ use core_types::math::quad::Quad;
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_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
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,
};
use dyn_any::DynAny;
use glam::{DAffine2, DVec2};
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, GradientSpread};
use vector_types::{Gradient, 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)]
@@ -667,10 +671,11 @@ impl Graphic {
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
Graphic::Gradient(item) => {
item_opacity_is_full(item)
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
&& item.element().iter().all(|stop| stop.color.is_opaque())
}
Graphic::GradientList(list) => {
@@ -678,6 +683,7 @@ impl Graphic {
&& every_item_has_full_opacity(list)
&& (0..list.len()).all(|index| {
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
})
}
@@ -843,6 +849,21 @@ fn every_item_has_full_opacity<T>(list: &List<T>) -> bool {
(0..list.len()).all(|index| list.attribute_cloned_or::<f64>(ATTR_OPACITY, index, 1.) >= 1. - f64::EPSILON && list.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, index, 1.) >= 1. - f64::EPSILON)
}
/// Whether a gradient with the attributes the `attribute` lookup gives paints every point, which curved contours leaving gaps unfilled don't.
fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>) -> bool {
fn read<'a, T: 'static>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>, key: &str) -> Option<&'a T> {
attribute(key).and_then(|value| value.downcast_ref::<T>())
}
GradientShape::new(
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::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
)
.paints_everywhere()
}
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
@@ -18,4 +18,4 @@ pub mod warp_kernels;
pub use kernel::*;
pub use raster_effects::evaluate_raster_effects;
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
use core_types::FallibleVec2Operations;
use core_types::blending::BlendMode;
use core_types::color::{linear_to_srgb, srgb_to_linear};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_FORM, Item, List};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_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};
@@ -33,7 +33,8 @@ use raster_types::parallel_rows::fill_rows;
use raster_types::{CPU, Image, Raster};
use std::collections::HashMap;
use std::ops::Range;
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
use vector_types::gradient::{Gradient, GradientSettings, GradientSpread};
use vector_types::gradient_standard::GradientShape;
mod styles;
@@ -1229,7 +1230,7 @@ fn drawn_paint_colors(operation: &EffectOperation, transform: DAffine2, size: DV
Some(colors)
}
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, linear or radial gradients, and those nested in a placement of their own.
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, gradients, and those nested in a placement of their own.
/// The paint's own adjustments are carried out first, and an image's own effects too.
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
@@ -1260,7 +1261,11 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
let item = evaluate_gradient_effects(item.clone());
let position = gradient_position(&item)?;
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(&item));
Some(Box::new(move |point| faded(evaluator.evaluate(position(point)), opacity)))
let spread = evaluator.settings().spread;
Some(Box::new(move |point| {
let color = position(point).map_or(Color::TRANSPARENT, |position| evaluator.evaluate(spread_position(position, spread)));
faded(color, opacity)
}))
}
Graphic::Graphic(item) => nested_sampler(item.element(), &|key| item.attributes().get_any(key)),
Graphic::GraphicList(list) => {
@@ -1408,7 +1413,9 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
let samples = gradient.interpolated_samples(settings);
Some(Box::new(move |point| {
let color = drawn_gradient_color(&samples, settings.spread, position(point));
let color = position(point).map_or(Color::TRANSPARENT, |position| {
drawn_gradient_color(&samples, settings.spread, spread_position(position, settings.spread))
});
premultiplied_gamma_channels(color).map(|channel| channel * opacity)
}))
}
@@ -1495,22 +1502,49 @@ fn drawn_gradient_color(samples: &[(f64, Color, Option<f64>)], spread: GradientS
}
}
/// How far along the gradient each point lies, or `None` where its placement collapses it.
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
/// How far along the gradient each point lies, or `None` where it's unpainted, or no function where its placement collapses a form.
/// A solid end stop's color is that end's infinite position, which [`spread_position`] keeps on that end under every spread.
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Option<f64> + Sync>> {
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let shape = 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),
placement,
);
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
match item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
match shape {
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
GradientForm::Linear => {
GradientShape::Linear => {
let axis = placement.matrix2.x_axis;
let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis);
let origin = placement.translation;
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box<dyn Fn(DVec2) -> f64 + Sync>)
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| Some((point - origin).dot(line) / line.length_squared())) as Box<dyn Fn(DVec2) -> Option<f64> + Sync>)
}
GradientForm::Radial => {
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
GradientShape::Radial => {
let to_unit = to_unit?;
Some(Box::new(move |point| Some(to_unit.transform_point2(point).length())))
}
// Any other curvatures draw in the gradient space the full placement maps from, which a collapsed placement leaves a solid color needing none
GradientShape::Standard(gradient) => {
let to_unit = to_unit.unwrap_or_default();
Some(Box::new(move |point| gradient.t(to_unit.transform_point2(point))))
}
// Apollonian circles paint every point, and a collapsed placement takes the Standard model's solid color instead
GradientShape::Apollonian(parameters) => {
let to_unit = to_unit?;
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
}
}
}
/// The position a `spread` reads along the ramp for one of a gradient's positions, which keeps an infinite one (a solid end stop) on that end's color under every spread but Clear.
fn spread_position(position: f64, spread: GradientSpread) -> f64 {
match (position.is_infinite(), spread) {
(true, GradientSpread::Repeat | GradientSpread::Reflect) if position > 0. => 1. - f64::EPSILON,
(true, GradientSpread::Repeat | GradientSpread::Reflect) => 0.,
_ => position,
}
}
@@ -1877,9 +1911,7 @@ mod tests {
// A ramp from black to white across far more than the content, which lights flat ground wherever it reaches
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
let ramp = Item::new_from_element(Gradient::new(stops))
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)))
.with_attribute(ATTR_GRADIENT_FORM, GradientForm::Linear);
let ramp = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)));
let mut emboss = EffectOperation::default_for(graphic_types::EffectKind::BevelAndEmboss);
if let EffectOperation::BevelAndEmboss { style, size, texture, .. } = &mut emboss {
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
use crate::blending::overlay_paint;
use core_types::Color;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
use graphic_types::adjustment::Adjustment;
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
use graphic_types::effects::{EffectOperation, Effects};
@@ -273,7 +273,7 @@ pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, e
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
}
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
/// A color without the effects attribute is returned as it is.
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
@@ -286,6 +286,27 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
item
}
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
let (adjustments, blend_ifs) = item
.attribute::<Effects>(ATTR_EFFECTS)
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
.unwrap_or_default();
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
let mut item = item;
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
item.remove_attribute::<Effects>(ATTR_EFFECTS);
item.remove_attribute::<f64>(ATTR_OPACITY);
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
item
}
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
/// A gradient without the effects attribute is returned as it is.
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
@@ -351,6 +372,21 @@ mod tests {
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
}
#[test]
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let unfilled = Item::new_from_element(Color::BLACK)
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
}
#[test]
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
use graphic_types::blend_if::BlendIfRanges;
@@ -1,7 +1,7 @@
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
//! Content with an effect no filter can carry out or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
//! are drawn as images in place of markup. Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
@@ -209,7 +209,7 @@ pub struct DeferredImage {
/// What the GPU renders an image of for an SVG.
#[derive(Clone)]
pub enum DeferredContent {
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
/// An item with effects SVG filters can't carry out or a paint SVG only approximates, but without its opacity and blend mode, which the image takes instead.
Item(Graphic),
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
@@ -1,14 +1,14 @@
use crate::renderer::{
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible,
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::color::SRGBA8;
use core_types::list::List;
use core_types::uuid::generate_uuid;
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use core_types::{ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::vector_types::gradient::GradientForm;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
use std::fmt::Write;
use vector_types::Gradient;
@@ -86,17 +86,27 @@ impl RenderExt for List<Color> {
}
}
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent.
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, for_mask: bool) -> Option<u64> {
fn render_gradient_paint(
item: Option<ItemRef<'_, Gradient>>,
svg_defs: &mut String,
item_transform: DAffine2,
element_transform: DAffine2,
stroke_transform: DAffine2,
bounds: DAffine2,
for_mask: bool,
) -> Option<u64> {
let mut stop = String::new();
let item = item?;
let (stops, settings) = painted_gradient(item)?;
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
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, gradient_form);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
@@ -105,7 +115,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
}
}
for (position, color, original_midpoint) in samples {
for &(position, color, original_midpoint) in &samples {
stop.push_str("<stop");
if position != 0. {
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
@@ -138,13 +148,7 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
let document_transform = item_transform * local_gradient_transform;
let placement = gradient_placement(document_transform, gradient_form);
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
let gradient_transform = if gradient_transform.is_empty() {
String::new()
} else {
format!(r#" gradientTransform="{gradient_transform}""#)
};
let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape);
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
String::new()
@@ -152,26 +156,45 @@ fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut Str
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
};
let gradient_id = generate_uuid();
// A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over
let masked = svg_gradient_standard(shape).is_some_and(|gradient| gradient.is_masked());
let pattern_area = if masked {
let inverse = |length: f64| if length > 0. { 1. / length } else { 0. };
let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length()));
let (local_min, local_max) = (bounds.transform_point2(DVec2::ZERO) - inflate, bounds.transform_point2(DVec2::ONE) + inflate);
match gradient_form {
GradientForm::Linear => {
let _ = write!(
svg_defs,
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
gradient_id, stop
);
}
GradientForm::Radial => {
let _ = write!(
svg_defs,
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
gradient_id, stop
);
let corners = [local_min, DVec2::new(local_max.x, local_min.y), DVec2::new(local_min.x, local_max.y), local_max].map(|corner| stroke_transform.transform_point2(corner));
let min = corners.into_iter().reduce(DVec2::min)?;
let size = corners.into_iter().reduce(DVec2::max)? - min;
if !(size.x > 0. && size.y > 0. && size.is_finite() && min.is_finite()) {
return None;
}
Some((min, size))
} else {
None
};
let area = pattern_area.map_or(String::new(), |(min, size)| format!(r#"rect x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, size.x, size.y));
let layers = write_svg_gradient_paint(svg_defs, shape, &samples, &stop, &gradient_spread, gradient_transform, &area);
if let [SvgGradientLayer { paint, mask: None }] = layers.as_slice() {
return Some(*paint);
}
Some(gradient_id)
let (min, size) = pattern_area?;
let pattern_id = generate_uuid();
let _ = write!(
svg_defs,
r#"<pattern id="{pattern_id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}" viewBox="{} {} {} {}">"#,
min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y
);
for SvgGradientLayer { paint, mask } in layers {
let mask = mask.map(|mask| format!(r#" mask="url(#{mask})""#)).unwrap_or_default();
let _ = write!(svg_defs, r#"<{area} fill="url(#{paint})"{mask} />"#);
}
svg_defs.push_str("</pattern>");
Some(pattern_id)
}
impl RenderExt for List<Gradient> {
@@ -185,8 +208,8 @@ impl RenderExt for List<Gradient> {
_paint_reach: f64,
item_transform: DAffine2,
element_transform: DAffine2,
_stroke_transform: DAffine2,
_bounds: DAffine2,
stroke_transform: DAffine2,
bounds: DAffine2,
render_params: &RenderParams,
_target: PaintTarget,
) -> Self::Output {
@@ -195,6 +218,8 @@ impl RenderExt for List<Gradient> {
svg_defs,
item_transform,
element_transform,
stroke_transform,
bounds,
render_params.for_mask,
)
}
@@ -292,7 +317,7 @@ impl RenderExt for Graphic {
render_params,
target,
),
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask)
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
File diff suppressed because it is too large. Load diff
@@ -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, TextureId, TextureRegion};
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
const SHAPE_TOLERANCE: f64 = 0.1;
@@ -94,6 +94,51 @@ pub trait EffectsRenderer: Send {
}
}
/// What a fill or stroke paints with.
#[derive(Clone, Copy, Debug)]
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),
}
impl<'b> From<BrushRef<'b>> for SceneBrush<'b> {
fn from(brush: BrushRef<'b>) -> Self {
Self::Peniko(brush)
}
}
impl<'b> From<&'b peniko::Brush> for SceneBrush<'b> {
fn from(brush: &'b peniko::Brush) -> Self {
Self::Peniko(brush.into())
}
}
impl<'b> From<&'b peniko::Gradient> for SceneBrush<'b> {
fn from(gradient: &'b peniko::Gradient) -> Self {
Self::Peniko(gradient.into())
}
}
impl From<peniko::Color> for SceneBrush<'_> {
fn from(color: peniko::Color) -> Self {
Self::Peniko(color.into())
}
}
impl From<&peniko::Color> for SceneBrush<'_> {
fn from(color: &peniko::Color) -> Self {
Self::Peniko((*color).into())
}
}
impl<'b> From<&'b PencilGradient> for SceneBrush<'b> {
fn from(gradient: &'b PencilGradient) -> Self {
Self::Apollonian(gradient)
}
}
/// The pixels behind an image the scene draws.
#[derive(Clone, Debug)]
pub enum SceneImage {
@@ -270,44 +315,41 @@ impl<'a> VelloSceneBuilder<'a> {
}
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
}
/// Like [`Self::fill`] for a path, which it draws without copying.
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_fill_rule(fill_rule);
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_path(&finite_path(path));
}
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(self.view * transform);
self.scene.set_stroke(stroke.clone());
self.scene.set_paint(paint);
self.scene.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
}
/// Fills the whole scene, which is how content without bounds (like a color or gradient layer) paints, with the brush placed by `brush_transform` in the space of the drawn content.
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
pub fn fill_viewport<'b>(&mut self, brush: impl Into<SceneBrush<'b>>, brush_transform: Option<Affine>) {
if !self.drawing {
return;
}
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
self.scene.set_transform(Affine::IDENTITY);
self.scene.set_paint(paint);
self.scene.set_paint_transform(self.view * brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
}
@@ -698,22 +740,27 @@ impl<'a> VelloSceneBuilder<'a> {
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
}
/// The Vello GPU paint for a brush, plus the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
match brush {
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
BrushRef::Image(image) => {
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
Some((
PaintType::Image(Image {
image: source,
sampler: image.sampler,
}),
texture_to_image,
))
/// Paints with `brush`, returning the transform from the paint's space into the brush's (which differ for an image drawn from a downscaled texture).
fn set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
let (paint, paint_to_brush) = match brush {
SceneBrush::Apollonian(gradient) => {
self.scene.set_pencil_gradient_paint(gradient.clone());
return Some(Affine::IDENTITY);
}
}
SceneBrush::Peniko(BrushRef::Solid(color)) => (PaintType::Solid(color), Affine::IDENTITY),
SceneBrush::Peniko(BrushRef::Gradient(gradient)) => (PaintType::Gradient(gradient.clone()), Affine::IDENTITY),
SceneBrush::Peniko(BrushRef::Image(image)) => {
let (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
let paint = PaintType::Image(Image {
image: source,
sampler: image.sampler,
});
(paint, texture_to_image)
}
};
self.scene.set_paint(paint);
Some(paint_to_brush)
}
/// The external texture standing for an image, with the transform from its texture's pixels onto the image's own pixels and its texture's size.
@@ -1,6 +1,6 @@
use crate::{affine, color};
use core_types::list::{ATTR_POSITION, Item};
use core_types::{ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_TRANSFORM};
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM};
use glam::{DAffine2, DVec2};
use graphic_types::Graphic;
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
@@ -31,7 +31,9 @@ fn paint(gradient: &usvg::BaseGradient, form: GradientForm, unit_placement: DAff
let mut item = Item::new_from_element(Gradient(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma);
if form != GradientForm::default() {
item.set_attribute(ATTR_GRADIENT_FORM, form);
let [start_curvature, end_curvature] = form.curvatures();
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
}
let spread = match gradient.spread_method() {
usvg::SpreadMethod::Pad => GradientSpread::Pad,
@@ -1,5 +1,8 @@
use core_types::list::{ATTR_APPEARANCE, Item, List};
use core_types::{ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode, Color};
use core_types::{
ATTR_BLEND_MODE, ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, BlendMode,
Color,
};
use glam::{DAffine2, DVec2};
use graphic_types::effects::shadow_offset;
use graphic_types::raster_types::{Image, Raster};
@@ -177,7 +180,11 @@ fn a_bounding_box_radial_gradient_on_a_wide_shape_is_placed_as_an_ellipse() -> R
let content = converted(r#"<radialGradient id="g"><stop stop-color="red"/><stop offset="1" stop-color="blue"/></radialGradient><rect width="8" height="4" fill="url(#g)"/>"#)?;
let gradient = gradient_of(&content, Cover::Fill);
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientForm>(ATTR_GRADIENT_FORM)), Some(&GradientForm::Radial));
let curvature = |key| gradient.and_then(|gradient| gradient.attribute::<f64>(key)).copied();
assert_eq!(
[curvature(ATTR_GRADIENT_START_CURVATURE), curvature(ATTR_GRADIENT_END_CURVATURE)],
GradientForm::Radial.curvatures().map(Some)
);
assert_eq!(
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 2.), DVec2::new(4., 2.)))
@@ -17,6 +17,40 @@ pub enum GradientForm {
Radial,
}
/// The curvatures of the linear form: both ends are lines.
pub const LINEAR_CURVATURES: [f64; 2] = [0., 0.];
/// The curvatures of the radial form: the start is a point at the center, and the end is the circle around it through the end point.
/// The point is -1 rather than 1 since animating from the linear form toward -1 keeps each circle nested in the next.
pub const RADIAL_CURVATURES: [f64; 2] = [-1., 0.5];
impl GradientForm {
/// The curvatures of the start and end contours that make this form.
pub fn curvatures(self) -> [f64; 2] {
match self {
Self::Linear => LINEAR_CURVATURES,
Self::Radial => RADIAL_CURVATURES,
}
}
/// The form these curvatures make, if either, once wrapped like [`wrapped_curvature`].
pub fn from_curvatures(curvatures: [f64; 2]) -> Option<Self> {
match curvatures.map(|curvature| wrapped_curvature(curvature, f64::NAN)) {
LINEAR_CURVATURES => Some(Self::Linear),
RADIAL_CURVATURES => Some(Self::Radial),
_ => None,
}
}
}
/// A curvature wrapped into the range starting at -1, since -1 and 1 are both the end's own point, or `preset` if it isn't finite.
pub fn wrapped_curvature(curvature: f64, preset: f64) -> f64 {
match curvature {
_ if (-1. ..1.).contains(&curvature) => curvature,
_ if curvature.is_finite() => (curvature + 1.).rem_euclid(2.) - 1.,
_ => preset,
}
}
/// A gradient's stops: a list of colors (linear, unassociated alpha) whose optional `position` and `midpoint`
/// attributes place each stop along the 0 to 1 range. Stops lacking the `position` attribute distribute evenly,
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
@@ -1809,6 +1843,19 @@ impl GradientEvaluator {
}
}
#[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 GradientModel {
/// Draws the contours between the two ends the way SVG and other apps do, each a circle interpolated between the two end circles. Where the end circles don't nest, it leaves gaps unpainted.
#[default]
Standard,
/// Draws the contours between the two ends as a single family of circles that never cross one another, except at points they all share, and together fill the whole plane. SVG exports include it as an image, and PDF exports show an approximation.
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)]
@@ -2063,6 +2110,19 @@ impl core_types::bounds::BoundingBox for Gradient {
mod tests {
use super::*;
#[test]
fn curvatures_make_a_form_only_at_its_presets_once_wrapped() {
assert_eq!(GradientForm::from_curvatures([0., 0.]), Some(GradientForm::Linear));
assert_eq!(GradientForm::from_curvatures([1., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([-1., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([3., 0.5]), Some(GradientForm::Radial));
assert_eq!(GradientForm::from_curvatures([2., -2.]), Some(GradientForm::Linear));
assert_eq!(GradientForm::from_curvatures([0.5, 0.25]), None);
assert_eq!(GradientForm::from_curvatures([f64::NAN, 0.]), None);
assert_eq!(GradientForm::from_curvatures([f64::INFINITY, 0.5]), None);
}
#[test]
fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() {
assert!(Gradient::default().is_empty());
@@ -0,0 +1,530 @@
//! The Apollonian drawing of a gradient's curved end contours: the contours between them fill in as the family of circles the
//! two end contours span, which never cross except where every one of them meets, and fill the whole plane.
//!
//! Everything here is in gradient space, laid out as in [`crate::gradient_standard`]. Each member of the family is spaced by where it
//! crosses the gradient line, within the band between the end contours' crossings that lies nearest to the line's span from 0 to 1.
//! Where the band is that span, a stop at 0.3 sits where the 0.3 contour crosses the line. This reproduces the linear and radial
//! forms exactly, since their contours cross the line at a distance in proportion to their place along the ramp.
use crate::gradient_standard::{AxisRamp, Cone, GradientStandard, curvature_radius};
use glam::DVec2;
use std::f64::consts::FRAC_PI_2;
/// Stands in for a t of infinity, on the contours that cross the gradient line at infinity.
const UNBOUNDED_T: f64 = 1e6;
/// A generalized circle `a(x² + y²) + bx + c = 0` with its center on the gradient line: a circle, a line where `a` is zero,
/// or a point where it has zero radius.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AxisCircle {
pub a: f64,
pub b: f64,
pub c: f64,
}
impl AxisCircle {
/// The contour through the start point at the origin, curved by `alpha` toward the end point.
pub fn start(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self { a: sin, b: -2. * cos, c: 0. }
}
/// The contour through the end point at (1, 0), curved by `alpha` toward the start point.
pub fn end(alpha: f64) -> Self {
let (sin, cos) = (alpha * FRAC_PI_2).sin_cos();
Self {
a: sin,
b: 2. * cos - 2. * sin,
c: sin - 2. * cos,
}
}
pub fn value(&self, point: DVec2) -> f64 {
self.a * point.length_squared() + self.b * point.x + self.c
}
/// The points where it crosses the gradient line, in homogeneous form.
fn crossings(&self) -> [Homogeneous; 2] {
solve_quadratic(self.a, self.b, self.c)
}
/// The member of the family `self·weight + other·other_weight`.
fn combine(&self, weight: f64, other: &Self, other_weight: f64) -> Self {
Self {
a: self.a * weight + other.a * other_weight,
b: self.b * weight + other.b * other_weight,
c: self.c * weight + other.c * other_weight,
}
}
}
/// A point on the gradient line in homogeneous form, `numerator / denominator`, so the point at infinity is just a zero denominator.
#[derive(Debug, Clone, Copy, PartialEq)]
struct Homogeneous {
numerator: f64,
denominator: f64,
}
impl Homogeneous {
const INFINITY: Self = Self { numerator: 1., denominator: 0. };
fn value(&self) -> Option<f64> {
(self.denominator != 0.).then(|| self.numerator / self.denominator)
}
/// Scaled so the larger of its two parts has a magnitude of 1, keeping products of points in range.
fn normalized(self) -> Self {
let scale = self.numerator.abs().max(self.denominator.abs());
if scale == 0. {
return self;
}
Self {
numerator: self.numerator / scale,
denominator: self.denominator / scale,
}
}
}
/// The roots of `a y² + b y + c = 0`, in homogeneous form so a vanishing `a` puts a root at infinity rather than dividing by zero.
fn solve_quadratic(a: f64, b: f64, c: f64) -> [Homogeneous; 2] {
let discriminant = (b * b - 4. * a * c).max(0.);
let sign = if b >= 0. { 1. } else { -1. };
let q = -0.5 * (b + sign * discriminant.sqrt());
[Homogeneous { numerator: q, denominator: a }.normalized(), Homogeneous { numerator: c, denominator: q }.normalized()]
}
/// How the crossing of a pixel's contour is told apart from the other place the same circle crosses the gradient line.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum CrossingSelection {
/// The end contours cross, so every member passes through the two points where they cross, and the gradient line is split by
/// the line through those points at `radical_x`. Each side of a member circle is its own contour, crossing the gradient line
/// on the same side of `radical_x` as the pixel.
SameSideAs { radical_x: f64 },
/// The end contours don't cross, so the members nest around two limit points that split the gradient line into two arcs, and
/// every member crosses each arc once. The crossing on the arc holding the gradient's band is the one where
/// `quadratic[0] y² + quadratic[1] y + quadratic[2]` (with `y` in homogeneous form) is smallest.
OnArc { quadratic: [f64; 3] },
}
/// Where the arc holding the band passes through infinity, the crossings beyond infinity on its other side.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Wrap {
/// A point on the gradient line between the two limit points, which separates the arc's two sides of infinity.
pub reference_x: f64,
/// Which side of `reference_x` the band is on, `1` or `-1`.
pub band_side: f64,
/// The t of the crossings on the far side of infinity.
pub t: f64,
}
/// Everything needed to find the t of any pixel in an Apollonian gradient.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GradientApollonian {
pub start: AxisCircle,
pub end: AxisCircle,
pub selection: CrossingSelection,
pub wrap: Option<Wrap>,
/// The t of a crossing at `y` is `y * t_scale + t_offset`.
pub t_scale: f64,
pub t_offset: f64,
/// What SVG draws in place of the Apollonian circles where no image the GPU renders of them can replace it.
pub svg_stand_in: GradientStandard,
}
impl GradientApollonian {
/// The parameters of the gradient with these two curvatures, which must be finite and within -1 to 1.
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
let svg_stand_in = svg_stand_in(start_curvature, end_curvature);
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()
});
// Each crossing's place relative to the limit points, negative between them and positive beyond them
let arc_quadratic = arc_quadratic(limit_points);
let arc_of = |point: Homogeneous| evaluate_homogeneous_quadratic(arc_quadratic, point.normalized());
// Find each end contour's crossing on each arc, where a point contour (a limit point itself) lies on both
let choose_on_arc = |crossings: [Homogeneous; 2], negative_arc: bool| {
crossings
.into_iter()
.min_by(|a, b| {
let (a, b) = (arc_of(*a), arc_of(*b));
if negative_arc { a.total_cmp(&b) } else { b.total_cmp(&a) }
})
.unwrap_or(Homogeneous::INFINITY)
};
let candidates = [true, false].map(|negative_arc| {
let band_start = choose_on_arc(start.crossings(), negative_arc);
let band_end = choose_on_arc(end.crossings(), negative_arc);
(negative_arc, band_start, band_end)
});
// A band through infinity would give a contour within it an infinite t, so it's unusable. On the outer arc between finite limit
// points, that's a band with its ends on opposite sides of their midpoint, which counts an end on a limit point as on its side.
let limit_values = limit_points.map(|point| point.value());
let usable = |negative_arc: bool, band_start: Homogeneous, band_end: Homogeneous| {
let (Some(band_start), Some(band_end)) = (band_start.value(), band_end.value()) else {
return false;
};
match limit_values {
[Some(first), Some(second)] if !negative_arc => {
let reference_x = (first + second) / 2.;
(band_start > reference_x) == (band_end > reference_x)
}
_ => true,
}
};
// Among the rest, prefer the band nearest to running from 0 to 1, measured continuously so the choice can't jump as a contour nears a point
let distance_from_unit_band = |&(_, band_start, band_end): &(bool, Homogeneous, Homogeneous)| {
band_start.value().map_or(f64::INFINITY, f64::abs) + band_end.value().map_or(f64::INFINITY, |band_end| (band_end - 1.).abs())
};
let chosen = candidates
.into_iter()
.filter(|&(negative_arc, band_start, band_end)| usable(negative_arc, band_start, band_end))
.min_by(|a, b| distance_from_unit_band(a).total_cmp(&distance_from_unit_band(b)))
.unwrap_or(candidates[1]);
let (negative_arc, band_start, band_end) = chosen;
// Choosing the smallest value picks the crossing on the chosen arc
let sign = if negative_arc { 1. } else { -1. };
let selection = CrossingSelection::OnArc {
quadratic: arc_quadratic.map(|coefficient| coefficient * sign),
};
let band_start = band_start.value().unwrap_or(0.);
let band_end = band_end.value().unwrap_or(1.);
// An outer arc between two finite limit points passes through infinity, beyond which its crossings belong past the band's far end
let wrap = match (negative_arc, limit_values) {
(false, [Some(first), Some(second)]) if (first - second).abs() > 0. => {
let reference_x = (first + second) / 2.;
let band_side = if band_start > reference_x { 1. } else { -1. };
let t_direction = (band_end - band_start).signum();
Some(Wrap {
reference_x,
band_side,
t: band_side * t_direction * UNBOUNDED_T,
})
}
_ => None,
};
Self::with_band(start, end, selection, wrap, band_start, band_end, svg_stand_in)
}
fn with_band(start: AxisCircle, end: AxisCircle, selection: CrossingSelection, wrap: Option<Wrap>, band_start: f64, band_end: f64, svg_stand_in: GradientStandard) -> Self {
let width = band_end - band_start;
let width = if width.abs() < 1e-12 { 1e-12_f64.copysign(width) } else { width };
Self {
start,
end,
selection,
wrap,
t_scale: 1. / width,
t_offset: -band_start / width,
svg_stand_in,
}
}
/// The gradient's t at `point` in gradient space, by the same steps the renderer's shader takes.
pub fn t(&self, point: DVec2) -> f64 {
let start_value = self.start.value(point);
let end_value = self.end.value(point);
let scale = start_value.abs().max(end_value.abs());
if scale == 0. {
return 0.;
}
let (start_value, end_value) = (start_value / scale, end_value / scale);
// The pixel's contour is the member where the end contours' values keep this ratio, which crosses the gradient line at the
// roots of this quadratic
let a = end_value * self.start.a - start_value * self.end.a;
let b = end_value * self.start.b - start_value * self.end.b;
let c = end_value * self.start.c - start_value * self.end.c;
let roots = solve_quadratic(a, b, c);
let crossing = match self.selection {
CrossingSelection::SameSideAs { radical_x } => {
// A pixel on the dividing line itself is on the line member, which crosses at the finite root
let side = |root: Homogeneous| (root.numerator - radical_x * root.denominator) * root.denominator * (point.x - radical_x);
let (first, second) = (side(roots[0]), side(roots[1]));
let first_wins = if first == second {
roots[0].denominator.abs() >= roots[1].denominator.abs()
} else {
first > second
};
if first_wins { roots[0] } else { roots[1] }
}
CrossingSelection::OnArc { quadratic } => {
if evaluate_homogeneous_quadratic(quadratic, roots[0]) <= evaluate_homogeneous_quadratic(quadratic, roots[1]) {
roots[0]
} else {
roots[1]
}
}
};
if let Some(wrap) = self.wrap
&& (crossing.numerator - wrap.reference_x * crossing.denominator) * crossing.denominator * wrap.band_side < 0.
{
return wrap.t;
}
if crossing.denominator == 0. {
let direction = crossing.numerator * self.t_scale;
return if direction == 0. { 0. } else { direction.signum() * UNBOUNDED_T };
}
crossing.numerator / crossing.denominator * self.t_scale + self.t_offset
}
}
/// SVG 2's own drawing of these curvatures where the end circles nest so it paints the whole plane, which is exact when they're concentric, or else the plain ramp.
fn svg_stand_in(start_curvature: f64, end_curvature: f64) -> GradientStandard {
let drawn = GradientStandard::new(start_curvature, end_curvature);
let (start_radius, end_radius) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
let nested = if start_radius.is_finite() && end_radius.is_finite() {
Cone::between(start_radius, end_radius).is_nested()
} else {
drawn.paints_everywhere()
};
if nested { drawn } else { GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None } }
}
/// The weights of the two members that are points, the roots of the homogeneous quadratic form `start s² + 2·cross·s·e + end e²`.
fn point_member_weights(start: f64, cross: f64, end: f64) -> [(f64, f64); 2] {
let discriminant = (cross * cross - start * end).max(0.).sqrt();
if start.abs() < 1e-12 && end.abs() < 1e-12 {
// Both end contours are points already
[(1., 0.), (0., 1.)]
} else if start.abs() >= end.abs() {
[((-cross + discriminant) / start, 1.), ((-cross - discriminant) / start, 1.)]
} else {
[(1., (-cross + discriminant) / end), (1., (-cross - discriminant) / end)]
}
}
/// The quadratic in a homogeneous point that is negative between the two limit points and positive beyond them.
fn arc_quadratic([first, second]: [Homogeneous; 2]) -> [f64; 3] {
// (y·d₁ - n₁)(y·d₂ - n₂) with the denominators kept nonnegative, so its sign doesn't depend on how each point is scaled
let orient = |point: Homogeneous| {
if point.denominator < 0. {
Homogeneous {
numerator: -point.numerator,
denominator: -point.denominator,
}
} else {
point
}
};
let (first, second) = (orient(first), orient(second));
[
first.denominator * second.denominator,
-(first.denominator * second.numerator + first.numerator * second.denominator),
first.numerator * second.numerator,
]
}
fn evaluate_homogeneous_quadratic([a, b, c]: [f64; 3], point: Homogeneous) -> f64 {
let Homogeneous { numerator, denominator } = point;
a * numerator * numerator + b * numerator * denominator + c * denominator * denominator
}
#[cfg(test)]
mod tests {
use super::*;
use crate::gradient::{LINEAR_CURVATURES, RADIAL_CURVATURES};
use crate::gradient_standard::{GradientStandard, radius_curvature};
fn assert_close(actual: f64, expected: f64, context: &str) {
assert!((actual - expected).abs() < 1e-6, "{context}: expected {expected}, got {actual}");
}
#[test]
fn radial_curvatures_space_contours_by_radius() {
let parameters = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
for radius in [0.1, 0.3, 0.75, 1., 1.5, 4.] {
for angle in [0., 0.7, 2., 3.1, 4.5] {
let point = DVec2::from_angle(angle) * radius;
assert_close(parameters.t(point), radius, &format!("radius {radius} at angle {angle}"));
}
}
}
#[test]
fn linear_curvatures_space_contours_by_distance_along_the_line() {
let parameters = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
for point in [DVec2::new(0.25, 0.), DVec2::new(0.6, 3.), DVec2::new(-2., -7.), DVec2::new(5., 0.5)] {
assert_close(parameters.t(point), point.x, &format!("point {point}"));
}
}
#[test]
fn concentric_curvatures_draw_what_svg_2_draws() {
// End circles sharing a center, where the start circle is centered at `k` and the end circle at `1 - k`, so they're concentric when the end's `k` is 1 minus the start's
for start_radius in [-1., -0.5, 0.25, 2., 3.] {
let curvatures = [radius_curvature(start_radius), radius_curvature(1. - start_radius)];
let (apollonian, cone) = (GradientApollonian::new(curvatures[0], curvatures[1]), GradientStandard::new(curvatures[0], curvatures[1]));
for x in -30..=40 {
for y in -25..=25 {
let point = DVec2::new(x as f64 * 0.1 + 0.0013, y as f64 * 0.1 + 0.0007);
let Some(expected) = cone.t(point) else {
panic!("concentric circles with start radius {start_radius} leave {point} unpainted");
};
assert!((apollonian.t(point) - expected).abs() < 1e-6 * expected.abs().max(1.), "start radius {start_radius} at {point}");
}
}
}
}
#[test]
fn point_curvatures_space_contours_by_distance_ratio() {
let parameters = GradientApollonian::new(1., 1.);
for point in [DVec2::new(0.5, 0.), DVec2::new(0.5, 2.), DVec2::new(0.2, 0.3), DVec2::new(3., -1.)] {
// The contours are the circles of Apollonius, each crossing the line between the points at y / (1 - y) = ratio
let ratio = point.length() / (point - DVec2::X).length();
assert_close(parameters.t(point), ratio / (1. + ratio), &format!("point {point}"));
}
}
#[test]
fn curvatures_near_a_preset_render_like_it() {
let radial = GradientApollonian::new(RADIAL_CURVATURES[0], RADIAL_CURVATURES[1]);
let near_radial = GradientApollonian::new(RADIAL_CURVATURES[0] + 1e-7, RADIAL_CURVATURES[1] + 1e-7);
let linear = GradientApollonian::new(LINEAR_CURVATURES[0], LINEAR_CURVATURES[1]);
let near_linear = GradientApollonian::new(LINEAR_CURVATURES[0] + 1e-7, LINEAR_CURVATURES[1] - 1e-7);
for point in [DVec2::new(0.3, 0.2), DVec2::new(-0.5, 0.4), DVec2::new(0.9, -0.1)] {
assert!((radial.t(point) - near_radial.t(point)).abs() < 1e-4, "near radial at {point}");
assert!((linear.t(point) - near_linear.t(point)).abs() < 1e-4, "near linear at {point}");
}
}
#[test]
fn focal_gradient_pads_everywhere_outside_its_end_circle() {
// The start point sits inside the end circle, off its center
let parameters = GradientApollonian::new(1., 0.6);
assert_close(parameters.t(DVec2::X), 1., "end point");
let inside = parameters.t(DVec2::new(0.5, 0.));
assert!(inside > 0. && inside < 1., "inside: {inside}");
for point in [DVec2::new(-5., 0.), DVec2::new(-0.5, 0.), DVec2::new(5., 0.), DVec2::new(0.3, 4.), DVec2::new(-40., 30.)] {
let t = parameters.t(point);
assert!(t > 1., "outside at {point}: {t}");
}
}
#[test]
fn crossing_contours_fan_through_their_lens() {
let parameters = GradientApollonian::new(0.6, 0.6);
assert!(matches!(parameters.selection, CrossingSelection::SameSideAs { .. }));
for x in [0., 0.1, 0.25, 0.5, 0.8, 1.] {
assert_close(parameters.t(DVec2::new(x, 0.)), x, &format!("on the line at {x}"));
}
// Mirrored across the gradient line
assert_close(parameters.t(DVec2::new(0.3, 0.2)), parameters.t(DVec2::new(0.3, -0.2)), "mirror");
}
#[test]
fn every_curvature_pair_gives_a_number_everywhere() {
for start_step in -10..=10 {
for end_step in -10..=10 {
let parameters = GradientApollonian::new(start_step as f64 / 10., end_step as f64 / 10.);
for x in -8..=8 {
for y in -8..=8 {
let point = DVec2::new(x as f64 * 0.37, y as f64 * 0.41);
let t = parameters.t(point);
assert!(!t.is_nan(), "curvatures ({start_step}, {end_step}) at {point}");
}
}
}
}
}
#[test]
fn every_curvature_pair_puts_the_start_point_at_0_and_the_end_point_at_1() {
for start_step in -100..=100 {
for end_step in -100..=100 {
let (start_curvature, end_curvature) = (start_step as f64 / 100., end_step as f64 / 100.);
let parameters = GradientApollonian::new(start_curvature, end_curvature);
assert_close(parameters.t(DVec2::ZERO), 0., &format!("start point with curvatures ({start_curvature}, {end_curvature})"));
assert_close(parameters.t(DVec2::X), 1., &format!("end point with curvatures ({start_curvature}, {end_curvature})"));
}
}
}
#[test]
fn curvatures_reaching_a_line_or_a_point_change_the_gradient_continuously() {
let nudge = 1e-6;
for (curvatures, nearby_curvatures) in [
// The start crossing the line, with the end a small circle
([nudge, 0.8], [-nudge, 0.8]),
// The end crossing the line, with the start a small circle
([0.8, nudge], [0.8, -nudge]),
// The start shrinking to a point inside the end circle, on either side of its center
([1., 0.2], [1. - nudge, 0.2]),
([1., 0.6], [1. - nudge, 0.6]),
// The end shrinking to a point outside the start circle
([0.8, 1.], [0.8, 1. - nudge]),
([0.8, -1.], [0.8, -1. + nudge]),
// The start's point from either side of the curvature's wrap seam
([1. - nudge, 0.2], [-1. + nudge, 0.2]),
] {
let (parameters, nearby_parameters) = (
GradientApollonian::new(curvatures[0], curvatures[1]),
GradientApollonian::new(nearby_curvatures[0], nearby_curvatures[1]),
);
for x in -6..=10 {
for y in -8..=8 {
let point = DVec2::new(x as f64 * 0.25 + 0.013, y as f64 * 0.25 + 0.007);
// Clamped as the padded ramp draws it
let (t, nearby_t) = (parameters.t(point).clamp(0., 1.), nearby_parameters.t(point).clamp(0., 1.));
assert!(
(t - nearby_t).abs() < 1e-3,
"curvatures {curvatures:?} against {nearby_curvatures:?} at {point}: {t} against {nearby_t}"
);
}
}
}
}
}
@@ -0,0 +1,820 @@
//! Gradients with each of their two ends a contour curved between a line, a circle, and a point, drawn as SVG 2's focal radial
//! gradient (the two-point cone) between the two end circles, and extended to the settings SVG 2 can't express.
//!
//! Everything here is in gradient space, where the gradient line runs from the start point at the origin to the end point
//! at (1, 0). Each end's contour passes through its endpoint with its center on the line, and is described by its curvature
//! `α ∈ [-1, 1]`, which sets its signed radius `k = cot(απ/2)` in gradient lengths: 0 is the line perpendicular to the
//! gradient line, ±1 is the endpoint itself, and in between is a circle bowing toward (positive) or away from (negative) the
//! other endpoint. The start circle is centered at `(k₀, 0)` and the end circle at `(1 - k₁, 0)`.
//!
//! 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_apollonian::GradientApollonian;
use glam::{DAffine2, DVec2};
use std::f64::consts::FRAC_PI_2;
/// Past this radius, in gradient lengths, the cone is drawn as its own profile along the gradient line, carried straight across it.
/// Renderers draw a cone this flat wrongly in single precision (Chromium already does at 10,000), while its circles sag from straight by
/// only about `y² / 2r`, within about 0.002 of the profile.
pub const NEAR_LINE_RADIUS: f64 = 2000.;
/// The flattest an end contour other than a line is drawn, as a radius in gradient lengths, which keeps every position renderers receive within single precision's range.
/// A curvature nearer 0 than this radius allows is drawn this flat on its own side, so only a curvature of exactly 0 is a line.
const FLATTEST_RADIUS: f64 = 1e30;
/// The narrowest a ramp along the gradient line is drawn, in gradient lengths, below which it's a step from its first to its last stop.
/// Vello draws a gradient with ends closer than 10⁻⁶ as its first stop's color.
const NARROWEST_RAMP: f64 = 1e-5;
/// The signed radius of an end contour in gradient lengths for its `curvature`: infinite for a line, 0 for a point, and otherwise at most 10³⁰ in size.
pub fn curvature_radius(curvature: f64) -> f64 {
if curvature == 0. {
return f64::INFINITY;
}
if curvature.abs() == 1. {
return 0.;
}
let (sin, cos) = (curvature * FRAC_PI_2).sin_cos();
(cos / sin).clamp(-FLATTEST_RADIUS, FLATTEST_RADIUS)
}
/// The curvature of an end contour with this signed radius in gradient lengths, the inverse of [`curvature_radius`] (giving -1 for a point).
pub fn radius_curvature(radius: f64) -> f64 {
if radius == 0. { -1. } else { radius.recip().atan() / FRAC_PI_2 }
}
/// SVG 2's two-point conical gradient: circle `t` has its center and radius interpolated between the start and end circles,
/// both centered on the gradient line, for every real `t`.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Cone {
pub start_center: f64,
pub start_radius: f64,
pub end_center: f64,
pub end_radius: f64,
}
impl Cone {
/// The largest `t` whose circle passes through `point` with a radius of at least 0, or `None` where SVG 2 leaves it unpainted.
pub fn t(&self, point: DVec2) -> Option<f64> {
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
let scale = delta_center * delta_center + delta_radius * delta_radius;
// The circles through `point` are the roots of `a t² - 2 b t + c`
let offset = point.x - self.start_center;
let a = delta_center * delta_center - delta_radius * delta_radius;
let b = offset * delta_center + self.start_radius * delta_radius;
let c = offset * offset + point.y * point.y - self.start_radius * self.start_radius;
let valid = |t: f64| (self.start_radius + t * delta_radius >= 0.).then_some(t);
let largest = |first: Option<f64>, second: Option<f64>| match (first, second) {
(Some(first), Some(second)) => Some(first.max(second)),
(first, second) => first.or(second),
};
// Internally tangent circles leave one finite root
if a.abs() < 1e-12 * scale {
return (b != 0.).then(|| c / (2. * b)).and_then(valid);
}
// Nested circles pass one circle through every point, which rounding mustn't lose where its two roots meet
let discriminant = b * b - a * c;
let discriminant = if a < 0. { discriminant.max(0.) } else { discriminant };
if discriminant < 0. {
return None;
}
// The roots `q / a` and `c / q`, found without the cancellation of subtracting nearly equal terms
let q = b + discriminant.sqrt().copysign(if b >= 0. { 1. } else { -1. });
let near_root = (q != 0.).then(|| c / q).and_then(valid);
largest(valid(q / a), near_root)
}
/// The cone between the end circles with these signed radii.
pub fn between(start: f64, end: f64) -> Self {
Self {
start_center: start,
start_radius: start.abs(),
end_center: 1. - end,
end_radius: end.abs(),
}
}
/// Whether its end circles are too close to tell apart, as renderers can't.
pub fn is_identical(&self) -> bool {
(self.end_center - self.start_center).abs() < 1e-6 && (self.end_radius - self.start_radius).abs() < 1e-6
}
/// Whether every point lies on a circle of the cone, which happens where one end circle lies within the other without touching it.
pub fn is_nested(&self) -> bool {
let (delta_center, delta_radius) = (self.end_center - self.start_center, self.end_radius - self.start_radius);
let a = delta_center * delta_center - delta_radius * delta_radius;
a < -1e-12 * (delta_center * delta_center + delta_radius * delta_radius)
}
}
/// A ramp along the gradient line, from `t = 0` where it crosses `x = start` to `t = 1` where it crosses `x = end`.
/// Each end is kept as exactly as it was found, and `width` (from `start` to `end`) without the cancellation of subtracting distant ends.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AxisRamp {
pub start: f64,
pub end: f64,
pub width: f64,
}
impl AxisRamp {
pub const PLAIN: Self = Self { start: 0., end: 1., width: 1. };
pub fn new(start: f64, end: f64) -> Self {
Self { start, end, width: end - start }
}
/// Whether it's too narrow to draw as a ramp, so it's drawn as a step from its first stop's color to its last stop's at `start`.
pub fn is_step(&self) -> bool {
self.width.abs() < NARROWEST_RAMP
}
/// Its end nearer the gradient's start, as `(x, t)`, which keeps positions measured from it precise near the start.
pub fn anchor(&self) -> (f64, f64) {
if self.end.abs() < self.start.abs() { (self.end, 1.) } else { (self.start, 0.) }
}
/// The position along the ramp at `x`, or a step's first or last end's [`RampEnd::t`].
pub fn t(&self, x: f64) -> f64 {
if self.is_step() {
let after = (x - self.start) * self.width >= 0.;
return if after { RampEnd::Last.t() } else { RampEnd::First.t() };
}
let (anchor, anchor_t) = self.anchor();
anchor_t + (x - anchor) / self.width
}
}
/// The side of the line `x = at` across the gradient line that a paint is kept to, leaving the other side unpainted.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct HalfPlane {
pub at: f64,
/// Whether it keeps the side before `at` along the gradient line, rather than the side after.
pub keeps_before: bool,
}
impl HalfPlane {
pub fn keeps(&self, x: f64) -> bool {
if self.keeps_before { x < self.at } else { x > self.at }
}
}
/// One of a ramp's two end stops.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RampEnd {
First,
Last,
}
impl RampEnd {
/// The position along the ramp, past every end and repeat, that a padded ramp shows this end's color at.
pub fn t(self) -> f64 {
match self {
Self::First => f64::NEG_INFINITY,
Self::Last => f64::INFINITY,
}
}
}
/// How a gradient with curved end contours is drawn, in gradient space.
// TODO: Under the Repeat and Reflect spreads, SVG 2's limits at a line end are `max(x, 0)` at an end line and `min(x / ℓ₁, 1)` at a start line, which are drawn
// as under the Pad spread instead, then repeated or reflected. Likewise, every Apollonian circle past the family's infinity takes the phase of the finite position standing in for it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientStandard {
/// SVG 2's cone.
Cone(Cone),
/// A ramp along the gradient line, kept to `keep` if given.
Ramp { ramp: AxisRamp, keep: Option<HalfPlane> },
/// An end stop's color, kept to `keep` if given.
Solid { end: RampEnd, keep: Option<HalfPlane> },
/// A nearly flat cone's profile along the gradient line, carried straight across it: a ramp before the line across it at `split` and another after.
Profile { split: f64, before: AxisRamp, after: AxisRamp },
/// Identical end circles, which SVG 2 leaves unpainted.
Nothing,
}
impl GradientStandard {
/// How a gradient with these two curvatures is drawn.
pub fn new(start_curvature: f64, end_curvature: f64) -> Self {
let (start, end) = (curvature_radius(start_curvature), curvature_radius(end_curvature));
match (start.is_infinite(), end.is_infinite()) {
(true, true) => Self::Ramp { ramp: AxisRamp::PLAIN, keep: None },
(false, true) => Self::end_line(start, true),
(true, false) => Self::start_line(end, true),
_ if start.abs().max(end.abs()) > NEAR_LINE_RADIUS => Self::profile(start, end),
_ => Self::cone(start, end),
}
}
/// SVG 2's cone between the start and end circles with these signed radii.
fn cone(start: f64, end: f64) -> Self {
// SVG 2 paints nothing between identical circles
let cone = Cone::between(start, end);
if cone.is_identical() { Self::Nothing } else { Self::Cone(cone) }
}
/// SVG 2's cone between nearly flat end circles with these signed radii, as its profile along the gradient line carried straight across it.
/// On the line, circle `t` passes through `x` where either edge of its diameter does, each edge moving in proportion to `t`. So each side
/// of the apex, where the circles shrink to a point, takes one ramp: the larger of the edges' `t` for circles of a radius of at least 0.
fn profile(start: f64, end: f64) -> Self {
// Each edge of the circles' diameters along the gradient line runs from `2s` on the start circle to `1 - 2e` on the end circle, each
// either an end's radius or 0, and moves by `1 - 2(s + e)`, summed first so distant edges don't lose the 1 to rounding
let edge = |start_radius: f64, end_radius: f64| AxisRamp {
start: 2. * start_radius,
end: 1. - 2. * end_radius,
width: 1. - 2. * (start_radius + end_radius),
};
let left = edge(start.min(0.), end.max(0.));
let right = edge(start.max(0.), end.min(0.));
let (start_left, start_right, delta_left) = (left.start, right.start, left.width);
let growth = 2. * (end.abs() - start.abs());
// An edge that moves, with its direction, whose `t` is the cone's on the side of the apex where its circles have a radius of at least 0
let edges = [left, right].into_iter().filter(|edge| edge.width != 0.).map(|edge| (edge, edge.width));
// With equal radii there's no apex, and the edge leading in `t` leads everywhere
if growth == 0. {
let leading = edges.max_by(|(a, _), (b, _)| a.t(0.).total_cmp(&b.t(0.))).map(|(ramp, _)| ramp);
return Self::sides(0., leading, leading);
}
// After the apex, the valid edges are those moving the way the diameter grows, and the steeper in `t` leads, while before it the reverse holds
let side = |after: bool| {
let valid = edges.clone().filter(|&(_, delta)| ((delta > 0.) == (growth > 0.)) == after);
let leading = valid.max_by(|(_, a), (_, b)| {
let steeper = a.recip().total_cmp(&b.recip());
if after { steeper } else { steeper.reverse() }
});
leading.map(|(ramp, _)| ramp)
};
// The apex lies where the diameter shrinks to 0
let apex_t = -(start_right - start_left) / growth;
let apex = start_left + apex_t * delta_left;
if !apex.is_finite() || apex.abs() > FLATTEST_RADIUS {
let ramp = side(apex < 0.);
return Self::sides(0., ramp, ramp);
}
Self::sides(apex, side(false), side(true))
}
/// The ramp `before` the line across the gradient line at `split` and the one `after`, each unpainted where `None`.
fn sides(split: f64, before: Option<AxisRamp>, after: Option<AxisRamp>) -> Self {
let keep = |keeps_before| Some(HalfPlane { at: split, keeps_before });
match (before, after) {
(Some(before), Some(after)) if before == after => Self::Ramp { ramp: before, keep: None },
(Some(before), Some(after)) => Self::Profile { split, before, after },
(Some(ramp), None) => Self::Ramp { ramp, keep: keep(true) },
(None, Some(ramp)) => Self::Ramp { ramp, keep: keep(false) },
(None, None) => Self::Nothing,
}
}
/// SVG 2's limit as the end contour flattens into a line, bowing `inward` toward the start or away from it, beside the start circle of signed radius `start`.
fn end_line(start: f64, inward: bool) -> Self {
// The start circle's crossing of the gradient line that the flattening end circles meet
let crossing = if inward { (2. * start).max(0.) } else { (2. * start).min(0.) };
if (crossing - 1.).abs() < 1e-9 {
return Self::Solid {
end: RampEnd::First,
keep: Some(HalfPlane { at: 1., keeps_before: true }),
};
}
// Unpainted past the crossing, except where it falls before the end point bowing inward
Self::Ramp {
ramp: AxisRamp::new(crossing, 1.),
keep: (!inward || crossing > 1.).then_some(HalfPlane { at: crossing, keeps_before: inward }),
}
}
/// SVG 2's limit as the start contour flattens into a line, bowing `inward` toward the end or away from it, beside the end circle of signed radius `end`.
fn start_line(end: f64, inward: bool) -> Self {
// Bowing inward, the flattening start circles meet the end circle's backward crossing, or else its forward one
let crossing = if inward { (1. - 2. * end).min(1.) } else { (1. - 2. * end).max(1.) };
if inward && crossing > 0. {
return Self::Ramp {
ramp: AxisRamp::new(0., crossing),
keep: None,
};
}
// The last stop's color fills the side of the crossing that SVG 2 paints
Self::Solid {
end: RampEnd::Last,
keep: Some(HalfPlane { at: crossing, keeps_before: !inward }),
}
}
/// Whether it draws as a paint masked to one side of a line: a paint kept to that side, or a profile's two sides.
pub fn is_masked(&self) -> bool {
matches!(self, Self::Ramp { keep: Some(_), .. } | Self::Solid { keep: Some(_), .. } | Self::Profile { .. })
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Cone(cone) => cone.is_nested(),
Self::Ramp { keep, .. } | Self::Solid { keep, .. } => keep.is_none(),
Self::Profile { .. } => true,
Self::Nothing => false,
}
}
/// The position along the ramp at `point`, or `None` where it's unpainted. An end stop's solid color is that end's [`RampEnd::t`].
pub fn t(&self, point: DVec2) -> Option<f64> {
let kept = |keep: &Option<HalfPlane>| keep.is_none_or(|keep| keep.keeps(point.x));
match self {
Self::Cone(cone) => cone.t(point),
Self::Ramp { ramp, keep } => kept(keep).then(|| ramp.t(point.x)),
Self::Solid { end, keep } => kept(keep).then(|| end.t()),
Self::Profile { split, before, after } => Some(if point.x < *split { before.t(point.x) } else { after.t(point.x) }),
Self::Nothing => None,
}
}
}
/// How a gradient's contours are laid out, decided by its curvatures and model.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum GradientShape {
/// The linear form: both ends are lines.
Linear,
/// The radial form: the start is a point at the center of the end circle.
Radial,
/// Any other curvatures, drawn as SVG 2 draws them.
Standard(GradientStandard),
/// Any other curvatures, drawn as Apollonian circles.
Apollonian(GradientApollonian),
}
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 {
let [start, end] = [start_curvature, end_curvature].map(|curvature| wrapped_curvature(curvature, 0.));
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 => {
// 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() {
return Self::Standard(GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
}
Self::Apollonian(GradientApollonian::new(start, end))
}
None => 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.
pub fn reaches_before_start(&self) -> bool {
!matches!(self, Self::Radial)
}
/// Whether it paints every point, rather than leaving some unpainted.
pub fn paints_everywhere(&self) -> bool {
match self {
Self::Linear | Self::Radial | Self::Apollonian(_) => true,
Self::Standard(gradient) => gradient.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.
pub fn svg_draws_exactly(&self) -> bool {
let Self::Apollonian(GradientApollonian { start, end, svg_stand_in, .. }) = self else {
return true;
};
// Each end circle is centered at `-b / 2a`, so they share a center where these products match
let (start_product, end_product) = (start.b * end.a, end.b * start.a);
let concentric = (start_product - end_product).abs() <= 1e-9 * (start_product.abs() + end_product.abs());
concentric && matches!(svg_stand_in, GradientStandard::Cone(_))
}
}
#[cfg(test)]
mod tests {
use super::*;
/// 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 position a padded ramp shows, or `None` where unpainted.
fn padded(t: Option<f64>) -> Option<f64> {
t.map(|t| t.clamp(0., 1.))
}
/// SVG 2's cone written independently in its circles' crossings of the gradient line, which stays precise for huge circles:
/// circle `t` spans the diameter from `left(t)` to `right(t)`, each interpolated between the end circles' own, and counts
/// where `right(t) >= left(t)`.
fn reference_t(start: f64, end: f64, point: DVec2) -> Option<f64> {
let (start_left, start_right) = ((2. * start).min(0.), (2. * start).max(0.));
let (end_left, end_right) = ((1. - 2. * end).min(1.), (1. - 2. * end).max(1.));
let (delta_left, delta_right) = (end_left - start_left, end_right - start_right);
let scale = (delta_left * delta_left + delta_right * delta_right) / 2.;
// `(x - left(t))(x - right(t)) + y² = 0`, expanded in `t`
let a = delta_left * delta_right;
let b = -((point.x - start_left) * delta_right + (point.x - start_right) * delta_left);
let c = (point.x - start_left) * (point.x - start_right) + point.y * point.y;
let discriminant = b * b - 4. * a * c;
let roots = match (a.abs() < 1e-12 * scale, discriminant >= 0.) {
(true, _) => vec![-c / b],
(false, true) => vec![(-b + discriminant.sqrt()) / (2. * a), (-b - discriminant.sqrt()) / (2. * a)],
(false, false) => Vec::new(),
};
roots
.into_iter()
.filter(|t| (start_right - start_left) + t * (delta_right - delta_left) >= -1e-9)
.max_by(|a, b| a.total_cmp(b))
}
/// Settings for each kind of pair of end circles, given by their signed radii, with what each is.
const CONE_SETTINGS: [(f64, f64, &str); 6] = [
(0., 0.75, "focal point inside the end circle, off its center"),
(0.2, 1.5, "focal circle nested inside the end circle"),
(2., -0.5, "end circle nested inside the start circle"),
(0.6, 0.6, "crossing circles"),
(-0.3, -0.3, "separate circles"),
(0., -0.4, "focal point outside the end circle"),
];
#[test]
fn cones_take_svg_2s_largest_valid_circle() {
for (start, end, setting) in CONE_SETTINGS {
let gradient = GradientStandard::new(radius_curvature(start), radius_curvature(end));
let GradientStandard::Cone(cone) = gradient else {
panic!("{setting} should draw as a cone, not {gradient:?}");
};
let mut unpainted = 0;
for point in sample_points() {
let (expected, actual) = (reference_t(start, end, point), gradient.t(point));
match (expected, actual) {
(Some(expected), Some(actual)) => {
assert!((expected - actual).abs() < 1e-6 * expected.abs().max(1.), "{setting} at {point}: {actual} rather than {expected}");
}
(None, None) => unpainted += 1,
_ => panic!("{setting} at {point}: {actual:?} rather than {expected:?}"),
}
}
// Only circles neither inside the other leave some of the plane unpainted
assert_eq!(unpainted > 0, !cone.is_nested(), "{setting}");
}
}
#[test]
fn a_focal_point_off_center_takes_svg_2s_largest_circle() {
// The focus at the start point, and the end circle of radius 0.75 centered at 0.25
let gradient = GradientStandard::new(-1., radius_curvature(0.75));
assert!((gradient.t(DVec2::new(-0.25, 0.)).unwrap() - 0.5).abs() < 1e-12);
}
#[test]
fn line_ends_are_svg_2s_limits_from_their_side() {
const FLAT: f64 = 1e6;
// The other end's signed radius, through circles of each size and bend and a point
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0.]);
for other in others {
for inward in [true, false] {
let flat = if inward { FLAT } else { -FLAT };
for (limit, [start, end], which) in [
(GradientStandard::end_line(other, inward), [other, flat], "end"),
(GradientStandard::start_line(other, inward), [flat, other], "start"),
] {
let cut = match limit {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep,
_ => panic!("an {which} line should draw as a ramp or solid color, not {limit:?}"),
};
for point in sample_points() {
// The cone's unpainted edge nears the cut line at a rate of the square root of its radius
if cut.is_some_and(|cut| (point.x - cut.at).abs() < 0.02) {
continue;
}
let (expected, actual) = (padded(reference_t(start, end, point)), padded(limit.t(point)));
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
}
}
#[test]
fn the_line_settings_take_the_chosen_limits() {
// Both lines, and an end line beside a start bowing away from it, are the plain ramp
assert_eq!(GradientStandard::new(0., 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
assert_eq!(GradientStandard::new(-0.3, 0.), GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None });
// An end line beside a start circle reaching past the end point is cut off past the start circle's far crossing
let start = 0.8;
let GradientStandard::Ramp { ramp, keep: Some(keep) } = GradientStandard::new(radius_curvature(start), 0.) else {
panic!("an end line beyond a large start circle should be cut off");
};
assert!((ramp.start - 2. * start).abs() < 1e-12 && ramp.end == 1.);
assert!(keep.keeps_before && (keep.at - 2. * start).abs() < 1e-12);
// A start line takes the ramp to the end circle's backward crossing, or the last stop past that crossing once the end circle reaches the start point
let GradientStandard::Ramp { ramp, keep: None } = GradientStandard::new(0., radius_curvature(0.25)) else {
panic!("a start line beside a small end circle should be a ramp");
};
assert!(ramp.start == 0. && (ramp.end - 0.5).abs() < 1e-12);
let GradientStandard::Solid { end: RampEnd::Last, keep: Some(keep) } = GradientStandard::new(0., radius_curvature(2.)) else {
panic!("a start line beside an end circle reaching the start point should be the last stop");
};
assert!(!keep.keeps_before && (keep.at + 3.).abs() < 1e-12);
}
#[test]
fn nearly_flat_cones_draw_their_profile_along_the_line() {
let settings = [
(0.3, 2500.),
(0.3, -2500.),
(2500., 0.2),
(-2500., 0.2),
(-0.4, 3000.),
(0., -2200.),
// Both ends nearly flat: equal radii bowing apart and together, and an apex before the start at x = -3
(-3000., 3000.),
(3000., -3000.),
(3000., -4000.),
];
for (start, end) in settings {
let profile = GradientStandard::new(radius_curvature(start), radius_curvature(end));
let split = match profile {
GradientStandard::Profile { split, .. } => Some(split),
GradientStandard::Ramp { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Nothing => None,
_ => panic!("({start}, {end}) should draw as its profile, not {profile:?}"),
};
// Within a level or two of the cone itself, except beside the apex, where the cone's circles are small and its edges lean
for point in sample_points() {
if split.is_some_and(|split| (point.x - split).abs() < 0.05 + 0.05 * point.y.abs()) {
continue;
}
let (expected, actual) = (padded(reference_t(start, end, point)), padded(profile.t(point)));
let context = format!("({start}, {end}) at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 0.01, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
// Codex's example, where the last stop shows everywhere
let both_flat = GradientStandard::new(radius_curvature(-3000.), radius_curvature(3000.));
assert_eq!(padded(both_flat.t(DVec2::new(0.5, 0.2))), Some(1.));
}
#[test]
fn the_profile_of_a_flattening_end_nears_the_line_limits() {
const FLAT: f64 = 1e9;
// The other end's signed radius, through circles of each size and bend and a point, and the start circle reaching the end point
let others = (-20..=20).filter(|&step| step != 0).map(|step| curvature_radius(step as f64 * 0.049)).chain([0., 0.5]);
for other in others {
for inward in [true, false] {
let flat = if inward { FLAT } else { -FLAT };
for (limit, profile, which) in [
(GradientStandard::end_line(other, inward), GradientStandard::profile(other, flat), "end"),
(GradientStandard::start_line(other, inward), GradientStandard::profile(flat, other), "start"),
] {
let cuts = [limit, profile].map(|gradient| match gradient {
GradientStandard::Ramp { keep, .. } | GradientStandard::Solid { keep, .. } => keep.map(|keep| keep.at),
GradientStandard::Profile { split, .. } => Some(split),
_ => None,
});
for point in sample_points() {
if cuts.iter().flatten().any(|cut| (point.x - cut).abs() < 1e-3) {
continue;
}
let (expected, actual) = (padded(limit.t(point)), padded(profile.t(point)));
let context = format!("{which} line bowing inward {inward}, beside radius {other} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
}
}
#[test]
fn an_end_line_through_a_start_circle_reaching_the_end_point_shows_the_first_stop() {
let before_end_point = Some(HalfPlane { at: 1., keeps_before: true });
assert_eq!(
GradientStandard::end_line(0.5, true),
GradientStandard::Solid {
end: RampEnd::First,
keep: before_end_point
}
);
let profile = GradientStandard::profile(0.5, 1e9);
for point in sample_points().filter(|point| (point.x - 1.).abs() > 1e-3) {
let t = padded(profile.t(point));
assert!(if point.x < 1. { t.is_some_and(|t| t < 1e-6) } else { t.is_none() }, "at {point}: {t:?}");
}
}
#[test]
fn internally_tangent_circles_leave_the_far_side_of_their_tangent_line_unpainted() {
// The start circle of radius 1 and the end circle of radius 0.5 touch at the start point
let gradient = GradientStandard::new(radius_curvature(1.), radius_curvature(0.5));
assert_eq!(gradient.t(DVec2::new(-1., 0.)), None);
assert!(gradient.t(DVec2::new(0.5, 0.)).is_some_and(|t| (t - 1.5).abs() < 1e-12));
}
#[test]
fn nearly_flat_cones_keep_their_ramps_ends_and_widths() {
// Equal radii of a million ramp from 2 million to the end point, reaching 1 exactly there so the Clear spread clears past it
let gradient = GradientStandard::profile(1e6, 1e6);
assert!((gradient.t(DVec2::new(0.75, 0.)).unwrap() - (1. + 0.25 / 1_999_999.)).abs() < 1e-15);
assert_eq!(gradient.t(DVec2::X), Some(1.));
// A ramp a gradient length wide, 200,000 gradient lengths before the start, stays a ramp
let gradient = GradientStandard::profile(-1e5, 1e5);
assert!((gradient.t(DVec2::new(-199_999.5, 0.)).unwrap() - 0.5).abs() < 1e-9);
// Opposite radii of 10¹⁶ keep the 1 that their distant edges differ by, which makes the start's edge lead
let at = DVec2::new(0.5, 0.);
assert!((GradientStandard::profile(-1e16, 1e16).t(at).unwrap() - (2e16 + 0.5)).abs() < 4.);
assert!((GradientStandard::profile(1e16, -1e16).t(at).unwrap() - 0.5).abs() < 1e-12);
}
#[test]
fn extreme_curvatures_compute_finitely() {
// Curvatures so near a line that their radii overflow when doubled, and either side of radii of 10³⁰ gradient lengths
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 {
let gradient = GradientStandard::new(start, end);
for point in sample_points() {
// A position may be an end stop's infinity but not a number lost to overflow
let t = gradient.t(point);
assert!(t.is_none_or(|t| !t.is_nan()), "curvatures ({start}, {end}) at {point}: {gradient:?}");
}
}
assert_eq!((curvature_radius(4e-309), curvature_radius(-4e-309)), (FLATTEST_RADIUS, -FLATTEST_RADIUS));
}
#[test]
fn curvatures_beside_zero_keep_their_side() {
// Beside a start circle reaching past the midpoint, an end flattening from either side nears a different limit than the line
let start = radius_curvature(0.4);
for side in [1., -1.] {
let beside_zero = GradientStandard::new(start, side * 1e-40);
let flattening = GradientStandard::new(start, radius_curvature(side * 1e20));
for point in sample_points() {
let (expected, actual) = (padded(flattening.t(point)), padded(beside_zero.t(point)));
let context = format!("end curvature beside 0 on side {side} at {point}");
match (expected, actual) {
(Some(expected), Some(actual)) => assert!((expected - actual).abs() < 1e-6, "{context}: {actual} rather than {expected}"),
(None, None) => {}
_ => panic!("{context}: {actual:?} rather than {expected:?}"),
}
}
}
}
#[test]
fn identical_circles_leave_nothing() {
let curvature = radius_curvature(0.5);
assert_eq!(GradientStandard::new(curvature, curvature), GradientStandard::Nothing);
}
#[test]
fn the_radial_preset_draws_distance_from_its_center() {
let gradient = GradientStandard::new(-1., 0.5);
for point in sample_points() {
let t = gradient.t(point).unwrap();
assert!((t - point.length()).abs() < 1e-9, "at {point}: {t}");
}
}
#[test]
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);
assert_eq!(shape([0.3, 0.2]), GradientShape::Standard(GradientStandard::Solid { end: RampEnd::Last, keep: None }));
// The forms keep drawing as they always have
assert_eq!(shape([0., 0.]), GradientShape::Linear);
assert_eq!(shape([-1., 0.5]), GradientShape::Radial);
}
}
#[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) {
GradientShape::Apollonian(apollonian) => apollonian.svg_stand_in,
shape => panic!("curvatures {curvatures:?} should draw Apollonian circles, not {shape:?}"),
};
// Concentric end circles draw SVG 2's own drawing, a cone or for huge ones its profile, while crossing ones draw the plain ramp however flat they are
let plain_ramp = GradientStandard::Ramp { ramp: AxisRamp::PLAIN, keep: None };
for concentric in [[radius_curvature(2.), radius_curvature(-1.)], [radius_curvature(3000.), radius_curvature(-2999.)]] {
let drawn = GradientStandard::new(concentric[0], concentric[1]);
assert!(drawn.paints_everywhere(), "{drawn:?}");
assert_eq!(stand_in(concentric), drawn);
}
for crossing in [0.6, 3000.] {
assert_eq!(stand_in([radius_curvature(crossing), radius_curvature(crossing)]), plain_ramp, "radii of {crossing}");
}
// 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));
// 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);
}
#[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();
// 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::Apollonian(_)
));
assert!(exact(curvatures, GradientModel::Apollonian), "radii {start} and {end}");
}
// Crossing, nested off center, a line beside a circle, a point beside a circle, and concentric ones so large SVG draws them by their profile
let off_center = [
[radius_curvature(0.6), radius_curvature(0.6)],
[radius_curvature(2.), radius_curvature(-0.5)],
[0., radius_curvature(0.5)],
[1., 0.3],
];
for curvatures in off_center.into_iter().chain([[radius_curvature(3000.), radius_curvature(-2999.)]]) {
assert!(!exact(curvatures, GradientModel::Apollonian), "curvatures {curvatures:?}");
assert!(exact(curvatures, GradientModel::Standard), "curvatures {curvatures:?} drawn as SVG 2 draws them");
}
// The forms stay native under either model
assert!(exact([0., 0.], GradientModel::Apollonian) && exact([-1., 0.5], GradientModel::Apollonian));
}
#[test]
fn radius_curvatures_invert_curvature_radii() {
for curvature in [-0.9, -0.5, -0.1, 0.1, 0.5, 0.9] {
assert!((radius_curvature(curvature_radius(curvature)) - curvature).abs() < 1e-12);
}
assert_eq!(curvature_radius(radius_curvature(0.)), 0.);
}
}
+3 -1
View File
@@ -2,12 +2,14 @@
extern crate log;
pub mod gradient;
pub mod gradient_apollonian;
pub mod gradient_standard;
pub mod math;
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, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
pub use math::QuadExt;
pub use vector::Vector;
pub use vector::reference_point::ReferencePoint;
@@ -423,11 +423,7 @@ fn compute_circular_subpath_details(left: DVec2, arc_point: DVec2, right: DVec2,
let center_to_arc_point = arc_point - center;
// Based on https://pomax.github.io/bezierinfo/#circles_cubic
let handle_offset_factor = if let Some(angle) = angle {
4. / 3. * (angle / 4.).tan()
} else {
super::shapes::HANDLE_OFFSET_FACTOR
};
let handle_offset_factor = if let Some(angle) = angle { 4. / 3. * (angle / 4.).tan() } else { 0.551784777779014 };
let p1 = dvec2_to_point(left - (left - center).perp() * handle_offset_factor);
let p2 = dvec2_to_point(arc_point + center_to_arc_point.perp() * handle_offset_factor);
@@ -5,27 +5,19 @@
mod heart;
use crate::vector::misc::{ArcType, SpiralType, bezpath_from_anchors_and_handles};
use glam::{DMat2, DVec2};
use glam::DVec2;
pub use heart::{HEART_SIZE, HeartProportions, heart_bezpath};
use kurbo::BezPath;
use std::f64::consts::{PI, SQRT_2, TAU};
use std::f64::consts::TAU;
/// Handle length of a quarter circle's cubic relative to its radius, 4(√2 − 1)/3, which puts each quarter's midpoint on the circle.
/// Other vector editors draw circles with it, so it's kept for interop over the 0.551915 that slightly lowers the largest error.
pub(crate) const HANDLE_OFFSET_FACTOR: f64 = 4. * (SQRT_2 - 1.) / 3.;
/// Constant from <https://pomax.github.io/bezierinfo/#circles_cubic>
const HANDLE_OFFSET_FACTOR: f64 = 0.551784777779014;
/// Relative growth per radian below which spiral arc lengths use a circle, since the closed forms divide by the growth.
const SPIRAL_CIRCLE_GROWTH: f64 = 1e-6;
/// The smallest radius of a logarithmic spiral, standing in for zero since such a spiral never reaches its center.
const LOGARITHMIC_SPIRAL_MIN_RADIUS: f64 = 1e-10;
/// Cubic parameters where the error peaks for the best fit to any smooth curve with the cubic's ends and end tangents on it.
/// To leading order that error is proportional to t²(1 − t)²((t − ½)² − q), with q = 0.0264731 equalizing its three peaks.
const SPIRAL_RIPPLE_PARAMETERS: [f64; 3] = [0.18222320647320767, 0.5, 0.8177767935267923];
/// The most anchors a generated shape can have before allocating them overflows the address space.
const MAX_SHAPE_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The most anchors a polygon or star can have before allocating them overflows the address space.
const MAX_POLYGON_ANCHORS: u64 = (isize::MAX as usize / size_of::<Anchor>()) as u64;
/// The failure of [`regular_polygon_bezpath`] and [`star_polygon_bezpath`].
#[derive(Debug, thiserror::Error)]
@@ -185,7 +177,7 @@ pub fn arc_bezpath(radius: f64, start_angle: f64, sweep_angle: f64, arc_type: Ar
/// Constructs a regular polygon (ngon). Based on `sides` and `radius`, which is the distance from the center to any vertex.
/// Fails when it has more sides than can be allocated.
pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result<BezPath, PolygonError> {
if sides > MAX_SHAPE_ANCHORS {
if sides > MAX_POLYGON_ANCHORS {
return Err(PolygonError::TooManySides(sides));
}
@@ -202,7 +194,7 @@ pub fn regular_polygon_bezpath(center: DVec2, sides: u64, radius: f64) -> Result
/// Constructs a star polygon (n-star). See [`regular_polygon_bezpath`], but with interspersed vertices at an `inner_radius`.
pub fn star_polygon_bezpath(center: DVec2, sides: u64, radius: f64, inner_radius: f64) -> Result<BezPath, PolygonError> {
// Each side has an outer and an inner anchor
if sides > MAX_SHAPE_ANCHORS / 2 {
if sides > MAX_POLYGON_ANCHORS / 2 {
return Err(PolygonError::TooManySides(sides));
}
@@ -258,239 +250,151 @@ pub fn arrow_bezpath(start: DVec2, end: DVec2, shaft_width: f64, head_width: f64
/// The failure of [`spiral_bezpath`].
#[derive(Debug, thiserror::Error)]
pub enum SpiralError {
#[error("A spiral with this many turns at this angular resolution is too large to fit in memory")]
TooManySegments,
#[error("The angular resolution must be greater than 0")]
AngularResolutionNotPositive,
#[error("The number of turns must be finite")]
TurnsNotFinite,
#[error("The start angle is too large to step through at this angular resolution")]
AngleTooLarge,
}
/// Constructs a spiral winding `turns` times from `inner_radius` out to `outer_radius`, rotated to start at `start_angle`, with a cubic every `angular_resolution` (both in radians).
pub fn spiral_bezpath(inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64, angular_resolution: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
let sweep = turns * TAU;
if sweep.is_nan() || sweep <= 0. {
return Ok(BezPath::new());
/// Constructs a spiral winding from an inner radius `a` out to `outer_radius`, sampled every `delta_theta` radians.
pub fn spiral_bezpath(a: f64, outer_radius: f64, turns: f64, start_angle: f64, delta_theta: f64, spiral_type: SpiralType) -> Result<BezPath, SpiralError> {
if delta_theta.is_nan() || delta_theta <= 0. {
return Err(SpiralError::AngularResolutionNotPositive);
}
if turns == f64::INFINITY {
return Err(SpiralError::TurnsNotFinite);
}
// Slightly under a whole number of segments counts as that number, so float error in the division adds no sliver segment at the end
let segment_count = (sweep / angular_resolution - 1e-9).ceil().max(1.);
if segment_count >= MAX_SHAPE_ANCHORS as f64 {
return Err(SpiralError::TooManySegments);
}
let segment_count = segment_count as usize;
let mut anchors = Vec::new();
let mut prev_in_handle = None;
let theta_end = turns * TAU + start_angle;
// Segment ends are multiples of the resolution rather than running sums, which would accumulate float error
let segment_end = |index: usize| if index == segment_count { sweep } else { index as f64 * angular_resolution };
let a = if spiral_type == SpiralType::Logarithmic { a.max(1e-10) } else { a };
let b = calculate_growth_factor(a, turns, outer_radius, spiral_type);
let spiral = SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, start_angle);
let mut anchors = Vec::with_capacity(segment_count + 1);
let mut in_handle = None;
for index in 0..segment_count {
let [start, start_handle, end_handle, _] = spiral.segment(segment_end(index), segment_end(index + 1));
anchors.push(Anchor::new(start, in_handle, Some(start_handle)));
in_handle = Some(end_handle);
let mut theta = start_angle;
while theta < theta_end {
let theta_next = f64::min(theta + delta_theta, theta_end);
// A step lost to the angle's float precision would never reach the end
if theta_next == theta {
return Err(SpiralError::AngleTooLarge);
}
let p0 = spiral_point(theta, a, b, spiral_type);
let p3 = spiral_point(theta_next, a, b, spiral_type);
let t0 = spiral_tangent(theta, a, b, spiral_type);
let t1 = spiral_tangent(theta_next, a, b, spiral_type);
let arc_length = spiral_arc_length(theta, theta_next, a, b, spiral_type);
let handle_distance = arc_length / 3.;
let p1 = p0 + handle_distance * t0;
let p2 = p3 - handle_distance * t1;
anchors.push(Anchor::new(p0, prev_in_handle, Some(p1)));
prev_in_handle = Some(p2);
// If final segment, end with anchor at theta_end
if (theta_next - theta_end).abs() < f64::EPSILON {
anchors.push(Anchor::new(p3, prev_in_handle, None));
break;
}
theta = theta_next;
}
anchors.push(Anchor::new(spiral.point(sweep), in_handle, None));
Ok(bezpath_from_anchors(&anchors, false))
}
/// A spiral starting at its inner radius in the direction of its start angle, its radius changing with the angle it sweeps from there.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct SpiralCurve {
pub spiral_type: SpiralType,
/// The radius at the start.
pub inner_radius: f64,
/// The change per radian swept, added to the radius of an Archimedean spiral or to the natural log of the radius of a logarithmic one.
pub growth_factor: f64,
/// The direction of the start in radians, which rotates the spiral without changing its shape.
pub start_angle: f64,
pub fn calculate_growth_factor(a: f64, turns: f64, outer_radius: f64, spiral_type: SpiralType) -> f64 {
match spiral_type {
SpiralType::Archimedean => {
let total_theta = turns * TAU;
(outer_radius - a) / total_theta
}
SpiralType::Logarithmic => {
let total_theta = turns * TAU;
((outer_radius.abs() / a).ln()) / total_theta
}
}
}
impl SpiralCurve {
/// The spiral winding `turns` times from `inner_radius` to `outer_radius`, rotated to start at `start_angle` radians.
pub fn new(spiral_type: SpiralType, inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64) -> Self {
let (inner_radius, total_growth) = match spiral_type {
SpiralType::Archimedean => (inner_radius, outer_radius - inner_radius),
SpiralType::Logarithmic => {
let inner_radius = inner_radius.max(LOGARITHMIC_SPIRAL_MIN_RADIUS);
let outer_radius = outer_radius.abs().max(LOGARITHMIC_SPIRAL_MIN_RADIUS);
(inner_radius, outer_radius.ln() - inner_radius.ln())
}
};
// With no turns to grow over, the spiral stays at its inner radius
let growth_factor = total_growth / (turns * TAU);
let growth_factor = if growth_factor.is_finite() { growth_factor } else { 0. };
Self {
spiral_type,
inner_radius,
growth_factor,
start_angle,
}
}
/// The radius at `angle` radians swept from the start.
pub fn radius(&self, angle: f64) -> f64 {
match self.spiral_type {
SpiralType::Archimedean => self.inner_radius + self.growth_factor * angle,
SpiralType::Logarithmic => self.inner_radius * (self.growth_factor * angle).exp(),
}
}
/// The point at `angle` radians swept from the start.
pub fn point(&self, angle: f64) -> DVec2 {
self.radius(angle) * self.outward(angle)
}
/// The unit direction from the center to the point at `angle` radians swept from the start, which turns counterclockwise with +Y pointing down.
fn outward(&self, angle: f64) -> DVec2 {
let (sin, cos) = (self.start_angle + angle).sin_cos();
DVec2::new(cos, -sin)
}
/// The point at `angle` radians swept from the start, and its first and second derivatives with respect to that angle.
fn derivatives(&self, angle: f64) -> [DVec2; 3] {
let radius = self.radius(angle);
let (radius_rate, radius_acceleration) = match self.spiral_type {
SpiralType::Archimedean => (self.growth_factor, 0.),
SpiralType::Logarithmic => (self.growth_factor * radius, self.growth_factor * self.growth_factor * radius),
};
// The outward direction turns toward `around` as the angle grows, and `around` toward the inward direction
let outward = self.outward(angle);
let around = DVec2::new(outward.y, -outward.x);
[
radius * outward,
radius_rate * outward + radius * around,
(radius_acceleration - radius) * outward + 2. * radius_rate * around,
]
}
/// The length along the spiral from `start` to `end` radians swept.
fn arc_length(&self, start: f64, end: f64) -> f64 {
let growth_factor = self.growth_factor;
match self.spiral_type {
SpiralType::Archimedean => {
let middle_radius = self.radius((start + end) / 2.);
if growth_factor.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (end - start);
}
// An antiderivative of the arc length, in terms of the radius
let antiderivative = |radius: f64| {
let hypotenuse = (radius * radius + growth_factor * growth_factor).sqrt();
(radius * hypotenuse + growth_factor * growth_factor * (radius + hypotenuse).ln()) / (2. * growth_factor)
};
antiderivative(self.radius(end)) - antiderivative(self.radius(start))
}
SpiralType::Logarithmic => {
let factor = (1. + growth_factor * growth_factor).sqrt();
if growth_factor.abs() < SPIRAL_CIRCLE_GROWTH {
return self.radius((start + end) / 2.) * factor * (end - start);
}
(self.radius(end) - self.radius(start)) * factor / growth_factor
}
}
}
/// The control points of the cubic closest to the spiral from `start` to `end` radians swept, its ends and end tangents on the spiral.
/// Its two handle lengths are solved so its largest distance from the spiral, which shrinks as the sixth power of the span, is as small as possible.
fn segment(&self, start: f64, end: f64) -> [DVec2; 4] {
let span = end - start;
let [start_point, start_velocity, _] = self.derivatives(start);
let [end_point, end_velocity, _] = self.derivatives(end);
let (start_tangent, end_tangent) = (start_velocity.normalize_or(DVec2::X), end_velocity.normalize_or(DVec2::X));
let cubic = |lengths: DVec2| [start_point, start_point + lengths.x * start_tangent, end_point - lengths.y * end_tangent, end_point];
// Both handles at a third of the arc length is the fallback where the fit fails, and past a half turn where it finds spurious solutions
let arc_third = DVec2::splat(self.arc_length(start, end) / 3.);
if span > PI * (1. + 1e-9) {
return cubic(arc_third);
}
// Coarse samples of the spiral seed each search for the spiral angle nearest a point on the cubic
let samples: [(f64, DVec2); 9] = std::array::from_fn(|index| {
let angle = start + span * index as f64 / 8.;
(angle, self.point(angle))
});
// The signed distance from the cubic at `t` to the spiral, and its slope in each handle length. `nearest` carries the angle found to the next search.
let error_and_slope = |lengths: DVec2, t: f64, nearest: &mut Option<f64>| {
let s = 1. - t;
let (start_weight, end_weight) = (3. * s * s * t, 3. * s * t * t);
let point = (s * s * s + start_weight) * start_point + start_weight * lengths.x * start_tangent + (t * t * t + end_weight) * end_point - end_weight * lengths.y * end_tangent;
let guess = nearest.unwrap_or_else(|| {
let closest = samples.iter().min_by(|(_, a), (_, b)| a.distance_squared(point).total_cmp(&b.distance_squared(point)));
closest.map_or(start, |&(angle, _)| angle)
});
let angle = self.nearest_angle(point, guess, start, end);
*nearest = Some(angle);
let [position, velocity, _] = self.derivatives(angle);
let normal = velocity.normalize_or(DVec2::X).perp();
let slope = DVec2::new(start_weight * normal.dot(start_tangent), -end_weight * normal.dot(end_tangent));
(normal.dot(point - position), slope)
};
// Errors this small are float noise with nothing left to improve
let noise_floor = 1e-13 * (start_point.length() + end_point.length());
// Newton's method on the handle lengths, first from the fallback (which finds the better of two solutions on steep spirals), then from a circle's lengths
let circle_factor = 4. / 3. * (span / 4.).tan();
let initial_guesses = [arc_third, circle_factor * DVec2::new(start_velocity.length(), end_velocity.length())];
'guesses: for mut lengths in initial_guesses {
let mut nearest = [None; 3];
for _ in 0..8 {
let [(error_a, slope_a), (error_middle, slope_middle), (error_b, slope_b)] =
std::array::from_fn(|index| error_and_slope(lengths, SPIRAL_RIPPLE_PARAMETERS[index], &mut nearest[index]));
// The largest error is smallest when its three peaks alternate in sign with equal size
let residual = DVec2::new(error_a + error_middle, error_middle + error_b);
let step = if residual.abs().element_sum() <= noise_floor {
DVec2::ZERO
} else {
DMat2::from_cols(slope_a + slope_middle, slope_middle + slope_b).transpose().inverse() * residual
};
if !step.is_finite() {
continue 'guesses;
}
// Neither handle changes by more than half its length in one step, which keeps both positive
let step = step * (0.5 * lengths / step.abs()).min_element().min(1.);
lengths -= step;
if step.abs().element_sum() <= 1e-9 * lengths.element_sum() {
return cubic(lengths);
}
}
}
cubic(arc_third)
}
/// The angle within `start..end` radians swept where the spiral comes nearest to `point`, searched from `guess`.
fn nearest_angle(&self, point: DVec2, guess: f64, start: f64, end: f64) -> f64 {
let max_step = (end - start) / 4.;
let mut angle = guess;
for _ in 0..6 {
let [position, velocity, acceleration] = self.derivatives(angle);
let offset = position - point;
// Newton's method on the squared distance, or Gauss-Newton where that distance isn't convex
let speed_squared = velocity.length_squared();
let second_derivative = speed_squared + offset.dot(acceleration);
let step = offset.dot(velocity) / if second_derivative > 0.25 * speed_squared { second_derivative } else { speed_squared };
if !step.is_finite() {
break;
}
angle = (angle - step.clamp(-max_step, max_step)).clamp(start, end);
}
angle
/// Returns a point on the given spiral type at angle `theta`.
pub fn spiral_point(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_point(theta, a, b),
SpiralType::Logarithmic => log_spiral_point(theta, a, b),
}
}
/// Returns the tangent direction at angle `theta` for the given spiral type.
fn spiral_tangent(theta: f64, a: f64, b: f64, spiral_type: SpiralType) -> DVec2 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_tangent(theta, a, b),
SpiralType::Logarithmic => log_spiral_tangent(theta, a, b),
}
}
/// Computes arc length between two angles for the given spiral type.
fn spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64, spiral_type: SpiralType) -> f64 {
match spiral_type {
SpiralType::Archimedean => archimedean_spiral_arc_length(theta_start, theta_end, a, b),
SpiralType::Logarithmic => log_spiral_arc_length(theta_start, theta_end, a, b),
}
}
/// Returns a point on a logarithmic spiral at angle `theta`.
fn log_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a * (b * theta).exp(); // a * e^(bθ)
DVec2::new(r * theta.cos(), -r * theta.sin())
}
/// Computes arc length along a logarithmic spiral between two angles.
fn log_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let factor = (1. + b * b).sqrt();
if b.abs() < SPIRAL_CIRCLE_GROWTH {
return a * (b * (theta_start + theta_end) / 2.).exp() * factor * (theta_end - theta_start);
}
(a / b) * factor * ((b * theta_end).exp() - (b * theta_start).exp())
}
/// Returns the tangent direction of a logarithmic spiral at angle `theta`.
fn log_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a * (b * theta).exp();
let dx = r * (b * theta.cos() - theta.sin());
let dy = r * (b * theta.sin() + theta.cos());
DVec2::new(dx, -dy).normalize_or(DVec2::X)
}
/// Returns a point on an Archimedean spiral at angle `theta`.
fn archimedean_spiral_point(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a + b * theta;
DVec2::new(r * theta.cos(), -r * theta.sin())
}
/// Returns the tangent direction of an Archimedean spiral at angle `theta`.
fn archimedean_spiral_tangent(theta: f64, a: f64, b: f64) -> DVec2 {
let r = a + b * theta;
let dx = b * theta.cos() - r * theta.sin();
let dy = b * theta.sin() + r * theta.cos();
DVec2::new(dx, -dy).normalize_or(DVec2::X)
}
/// Computes arc length along an Archimedean spiral between two angles.
fn archimedean_spiral_arc_length(theta_start: f64, theta_end: f64, a: f64, b: f64) -> f64 {
let middle_radius = a + b * (theta_start + theta_end) / 2.;
if b.abs() <= middle_radius.abs() * SPIRAL_CIRCLE_GROWTH {
return middle_radius.abs() * (theta_end - theta_start);
}
archimedean_spiral_arc_length_origin(theta_end, a, b) - archimedean_spiral_arc_length_origin(theta_start, a, b)
}
/// Computes arc length from origin to a point on Archimedean spiral at angle `theta`.
fn archimedean_spiral_arc_length_origin(theta: f64, a: f64, b: f64) -> f64 {
let r = a + b * theta;
let sqrt_term = (r * r + b * b).sqrt();
(r * sqrt_term + b * b * ((r + sqrt_term).ln())) / (2. * b)
}
@@ -7,6 +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 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};
@@ -369,6 +370,304 @@ fn degenerate_strokes_render() {
let Some(_) = render(size, draw) else { return };
}
/// A gradient from black to white read in gamma, placed by `placement`, with these curvatures and model, or none if `None`.
fn curved_black_to_white_gradient(placement: DAffine2, curvatures: Option<[f64; 2]>, model: GradientModel) -> graphic_types::Graphic {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_START_CURVATURE, Item};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use graphic_types::vector_types::gradient::{Gradient, GradientSpace};
let mut item = Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE]))
.with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma)
.with_attribute(ATTR_TRANSFORM, placement);
if let Some([start, end]) = curvatures {
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end);
item.set_attribute(ATTR_GRADIENT_MODEL, model);
}
graphic_types::Graphic::Gradient(item)
}
#[test]
fn curved_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 settings = [
([-1., radius(0.75)], "a focal point inside the end circle, off its center"),
([radius(0.2), radius(1.5)], "a focal circle nested inside the end circle"),
([radius(2.), radius(-0.5)], "an end circle nested inside the start circle"),
([radius(0.6), radius(0.6)], "crossing circles"),
([0.5, 0.25], "crossing circles of different sizes"),
([radius(-0.3), radius(-0.3)], "separate circles of the same size"),
([radius(-0.2), radius(-0.4)], "separate circles of different sizes"),
([-1., radius(-0.4)], "a focal point outside the end circle"),
([-1., -1.], "two points"),
([radius(0.5), radius(0.5)], "identical circles"),
([radius(0.3), radius(2500.)], "an end nearly a line"),
([radius(0.8), 0.], "an end line beside a start circle reaching past the end"),
([radius(-0.4), 0.], "an end line beside a start circle bowing away"),
([0., radius(2.)], "a start line beside an end circle reaching past the start"),
([radius(1.), radius(0.5)], "internally tangent circles"),
([radius(3000.), radius(-4000.)], "both ends nearly flat around an apex"),
([radius(-3000.), radius(3000.)], "both ends nearly flat, bowing apart"),
([7e-31, 0.3], "a start nearly too flat to draw as a circle"),
([4e-309, -1e-300], "both ends past computing as circles"),
];
let mut report = String::new();
for (curvatures, setting) in settings {
for placement in placements {
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, setting) else {
return;
};
let _ = writeln!(report, "{line}");
}
}
eprintln!("{report}");
}
#[test]
fn far_and_wide_curved_ramps_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::radius_curvature;
// Equal radii of a million ramp from 2 million to the end point, where t reaches 1 exactly, so Clear clears and Repeat restarts just past it
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
for spread in [GradientSpread::Clear, GradientSpread::Repeat] {
let curvatures = [radius_curvature(1e6), radius_curvature(1e6)];
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, spread, "equal radii of a million") else {
return;
};
eprintln!("{line}");
}
// A ramp a gradient length wide, 200,000 gradient lengths before the start, drawn across 100 pixels
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::new(100. * 200_000., 100.));
let curvatures = [radius_curvature(-1e5), radius_curvature(1e5)];
let Some(line) = compare_curved_gradient_with_cpu(curvatures, placement, GradientSpread::Pad, "a ramp 200,000 back") else {
return;
};
eprintln!("{line}");
}
/// Renders a black to white gradient with these curvatures, 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_curved_gradient_with_cpu(curvatures: [f64; 2], placement: DAffine2, spread: GradientSpread, setting: &str) -> Option<String> {
use core_types::list::ATTR_GRADIENT_SPREAD;
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientStandard;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let graphic = match curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Standard) {
graphic_types::Graphic::Gradient(item) => graphic_types::Graphic::Gradient(item.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
let gradient = GradientStandard::new(curvatures[0], curvatures[1]);
let to_gradient = placement.inverse();
let level_at = |point: DVec2| {
let t = gradient.t(to_gradient.transform_point2(point))?;
let position = match spread {
GradientSpread::Clear if !(0. ..=1.).contains(&t) => return None,
GradientSpread::Repeat if t.is_infinite() => (t > 0.) as u8 as f64,
GradientSpread::Repeat => t - t.floor(),
_ => t.clamp(0., 1.),
};
Some((position * 255.).round() as i32)
};
let center = |x: i32, y: i32| DVec2::new(x as f64 + 0.5, y as f64 + 0.5);
let expected = |x: i32, y: i32| level_at(center(x, y));
// Each pixel takes the level at its center, except that one beside a step in the ramp or an edge of the painted area may land anywhere between its neighbors' levels
let (mut worst, mut beside_steps, mut out_of_range, mut disagreements) = (0, 0, Vec::new(), 0);
for y in 1..size.y as i32 - 1 {
for x in 1..size.x as i32 - 1 {
let neighborhood: Vec<Option<i32>> = (-1..=1).flat_map(|dy| (-1..=1).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);
let red = red as i32;
match (alpha, expected(x, y)) {
(0, None) => {}
(255, Some(level)) if painted_neighbors == 9 && highest - lowest <= 32 => worst = worst.max((red - level).abs()),
(255, Some(_)) => {
beside_steps += 1;
// A center on a step (to within single precision) may take either side's level, which a sliver thinner than a pixel can hide from every neighbor
let nudged = [DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y].map(|direction| level_at(center(x, y) + direction * 1e-3));
let (lowest, highest) = nudged.iter().flatten().fold((lowest, highest), |(lowest, highest), &level| (lowest.min(level), highest.max(level)));
if red < lowest - 3 || red > highest + 3 {
let point = to_gradient.transform_point2(center(x, y));
out_of_range.push(format!("pixel ({x}, {y}) at {point} is {red} beside {lowest} to {highest}"));
}
}
_ if painted_neighbors != 0 && painted_neighbors != 9 => {}
_ => disagreements += 1,
}
}
}
let context = format!("{setting} {curvatures:?}, {spread:?}, placed by {placement:?}");
assert!(worst <= 3, "{context}: up to {worst} levels from the CPU");
assert!(out_of_range.is_empty(), "{context}: pixels beside steps out of their neighbors' range: {out_of_range:?}");
assert_eq!(disagreements, 0, "{context}: pixels disagreeing with the CPU on being painted");
Some(format!(
"{context}: within {worst} levels, {beside_steps} pixels beside steps in their neighbors' range, {disagreements} disagree on being painted"
))
}
#[test]
fn apollonian_gradients_match_their_cpu_evaluation() {
use glam::DVec2;
use graphic_types::vector_types::gradient_standard::GradientShape;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
// Gradient space spans 4 units across the render, with the gradient line from (60, 100) to (110, 100)
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
for curvatures in [
[1., 0.6],
[0.6, 0.6],
[-0.5, 0.2952],
[1., 1.],
[0.5, 0.25],
[0.3, -0.3],
[0.8, 1.],
[0.9, 0.2],
[0.9, 0.9],
[0.001, 0.8],
// The outer arc through infinity, with the band offset from the start and with the wrap's t negative
[0.9, 0.6],
[0.6, 1.],
] {
let GradientShape::Apollonian(parameters) = GradientShape::new(curvatures[0], curvatures[1], GradientModel::Apollonian, placement) else {
panic!("curvatures {curvatures:?} should draw Apollonian circles");
};
let graphic = curved_black_to_white_gradient(placement, Some(curvatures), GradientModel::Apollonian);
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
let mut worst = 0_i32;
for y in (5..195).step_by(10) {
for x in (5..195).step_by(10) {
let point = placement.inverse().transform_point2(DVec2::new(x as f64 + 0.5, y as f64 + 0.5));
let expected = (parameters.t(point).clamp(0., 1.) * 255.).round() as i32;
worst = worst.max((expected - pixel(&pixels, size, x, y)[0] as i32).abs());
}
}
assert!(worst <= 3, "curvatures {curvatures:?} differ from the CPU evaluation by up to {worst} levels");
}
}
#[test]
fn one_stop_curved_gradients_leave_their_gaps_unpainted() {
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, Item};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use glam::DVec2;
use graphic_types::vector_types::gradient::Gradient;
use graphic_types::vector_types::gradient_standard::radius_curvature;
use rendering::{Render, RenderParams};
let size = UVec2::new(200, 200);
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(50.), 0., DVec2::new(60., 100.));
// Crossing circles of radius 0.6, whose cone paints the strip within 0.6 of the gradient line, in one half-transparent red stop
let item = Item::new_from_element(Gradient::from(vec![GraphicColor::from_rgbaf32_unchecked(1., 0., 0., 0.5)]))
.with_attribute(ATTR_TRANSFORM, placement)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, radius_curvature(0.6))
.with_attribute(ATTR_GRADIENT_END_CURVATURE, radius_curvature(0.6));
let graphic = graphic_types::Graphic::Gradient(item);
let Some(pixels) = render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
// At (0.5, 0) on the cone and (0.5, 1) in its gap
let (on_cone, in_gap) = (pixel(&pixels, size, 85, 100)[3], pixel(&pixels, size, 85, 150)[3]);
assert!(on_cone.abs_diff(128) <= 1, "on the cone: alpha {on_cone}");
assert_eq!(in_gap, 0, "in the gap: alpha {in_gap}");
}
#[test]
fn gradient_presets_render_on_the_gpu_as_their_forms_did() {
use glam::DVec2;
use graphic_types::vector_types::GradientForm;
use rendering::{Render, RenderParams};
let size = UVec2::new(160, 120);
let placement = DAffine2::from_cols(DVec2::new(40., 10.), DVec2::new(-12., 30.), DVec2::new(70., 55.));
let render_graphic = |graphic: &graphic_types::Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
for form in [GradientForm::Linear, GradientForm::Radial] {
// The brush each form was drawn with before curvatures: the unit line placed without shear, or the unit circle placed as is
let (kind, brush_placement): (peniko::GradientKind, DAffine2) = match form {
GradientForm::Linear => {
let line = placement.matrix2.x_axis.project_onto(placement.matrix2.y_axis.perp());
let desheared = DAffine2::from_cols(line, line.perp(), placement.translation);
(
peniko::LinearGradientPosition {
start: Point::ORIGIN,
end: Point::new(1., 0.),
}
.into(),
desheared,
)
}
GradientForm::Radial => (
peniko::RadialGradientPosition {
start_center: Point::ORIGIN,
start_radius: 0.,
end_center: Point::ORIGIN,
end_radius: 1.,
}
.into(),
placement,
),
};
let brush = peniko::Brush::Gradient(
peniko::Gradient {
kind,
interpolation_alpha_space: peniko::InterpolationAlphaSpace::Unpremultiplied,
..Default::default()
}
.with_stops([Color::from_rgb8(0, 0, 0), Color::from_rgb8(255, 255, 255)]),
);
let Some(by_brush) = render(size, |scene| scene.fill_viewport(&brush, Some(Affine::new(brush_placement.to_cols_array())))) else {
return;
};
// Its curvatures draw those pixels under either model, and absent curvatures are the linear form's
let absent = (form == GradientForm::Linear).then_some((None, GradientModel::Apollonian));
for (curvatures, model) in [(Some(form.curvatures()), GradientModel::Standard), (Some(form.curvatures()), GradientModel::Apollonian)]
.into_iter()
.chain(absent)
{
let Some(by_curvatures) = render_graphic(&curved_black_to_white_gradient(placement, curvatures, model)) else {
return;
};
assert!(
by_curvatures == by_brush,
"{form:?} with curvatures {curvatures:?} and the {model:?} model should draw the pixels of its brush from before curvatures"
);
}
}
}
/// Renders an opaque white square from (`min`, `min`) to (`max`, `max`) through `effects` with `fill`.
fn render_square_with_effects(effects: Vec<graphic_types::EffectOperation>, fill: f32, min: f64, max: f64, size: UVec2) -> Option<Vec<[u8; 4]>> {
render_square_with_effects_in(effects, DAffine2::IDENTITY, fill, min, max, size)
@@ -3488,8 +3787,8 @@ fn captured_box_blurs_hold_their_results_for_svg_however_slight() {
fn cpu_evaluated_effects_match_the_gpu_passes() {
use core_types::Color as GraphicColor;
use core_types::blending::BlendMode;
use core_types::list::ATTR_GRADIENT_FORM;
use core_types::list::Item;
use core_types::list::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE};
use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM};
use glam::DVec2;
@@ -3799,17 +4098,30 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
blend_mode: BlendMode::Normal,
opacity: 100.,
});
let gradient = |form: GradientForm, transform: DAffine2| {
let gradient_item = |transform: DAffine2| {
let stops = [(0., [0.9, 0.1, 0.4, 1.]), (0.5, [0.2, 0.3, 0.9, 0.5]), (1., [1., 0.9, 0.7, 1.])].map(|(position, [red, green, blue, alpha])| GradientStop {
position,
midpoint: 0.5,
color: GraphicColor::from_rgbaf32_unchecked(red, green, blue, alpha),
});
let item = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform);
Graphic::from(item.with_attribute(ATTR_GRADIENT_FORM, form))
Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, transform)
};
let gradient = |form: GradientForm, transform: DAffine2| {
let [start_curvature, end_curvature] = form.curvatures();
Graphic::from(
gradient_item(transform)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature),
)
};
let linear = gradient(GradientForm::Linear, DAffine2::from_translation(DVec2::new(45., 60.)) * DAffine2::from_scale(DVec2::splat(60.)));
let radial = gradient(GradientForm::Radial, DAffine2::from_translation(DVec2::splat(75.)) * DAffine2::from_scale(DVec2::splat(30.)));
// Curvatures between the two forms, with crossing end circles whose cone leaves gaps unpainted, and the same curvatures drawn as Apollonian circles
let curved_item = gradient_item(DAffine2::from_translation(DVec2::new(55., 70.)) * DAffine2::from_scale(DVec2::splat(30.)))
.with_attribute(ATTR_GRADIENT_START_CURVATURE, 0.5)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, 0.25);
let curved = Graphic::from(curved_item.clone());
let apollonian = Graphic::from(curved_item.with_attribute(ATTR_GRADIENT_MODEL, GradientModel::Apollonian));
// A checkerboard spanning the render from `start` to `end` with a pixel for each of the render's, so sampling it needs no interpolation
let checkerboard = |start: u32, end: u32| {
@@ -3850,11 +4162,15 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
overlay(&linear, BlendMode::Normal, 40.),
overlay(&radial, BlendMode::Multiply, 100.),
overlay(&checker, BlendMode::Screen, 100.),
overlay(&curved, BlendMode::Normal, 100.),
overlay(&apollonian, BlendMode::Normal, 100.),
]);
// Outlines drawn with paints placed on their own, the image covering the outline as well as the content
paint_cases.extend([
vec![outline(linear.clone(), 6., StrokeAlign::Outside, false)],
vec![outline(radial.clone(), 8., StrokeAlign::Center, false)],
vec![outline(curved.clone(), 8., StrokeAlign::Center, false)],
vec![outline(apollonian.clone(), 8., StrokeAlign::Center, false)],
vec![outline(checkerboard(min - 10, max + 10), 9., StrokeAlign::Center, false)],
]);
// Bevels with gloss contours, contours, and textures
@@ -3975,6 +4291,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
vec![mask(&linear, MaskMode::Luminance, 100., 6., false)],
vec![mask(&radial, MaskMode::Alpha, 100., 0., false)],
vec![mask(&curved, MaskMode::Luminance, 100., 0., false)],
vec![mask(&mask_image, MaskMode::Luminance, 100., 2., false), mask_shadow.clone()],
vec![mask_shadow.clone(), mask(&linear, MaskMode::Luminance, 80., 0., true)],
vec![blur(2., false, false), mask(&radial, MaskMode::Luminance, 100., 1.5, false), mask_shadow.clone()],
+40 -14
View File
@@ -3,13 +3,13 @@ use core_types::blending::BlendMode;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::list::{Item, List};
use core_types::transfer_curve::TransferCurve;
use core_types::{ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, Ctx};
use core_types::{ATTR_TRANSFORM, Color, Ctx};
use glam::{DAffine2, DVec2};
use graphic_types::raster_types::{CPU, GPU, Raster};
use graphic_types::{
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectOperation, Generator, GlowSource, GlowTechnique, Graphic, Vector, linked_to_content, paint_with_envelope_effects, stamp_effect,
};
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
use raster_kernels::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
use vector_types::Gradient;
use vector_types::vector::style::{StrokeAlign, initial_gradient_transform_for_bounding_box};
@@ -99,7 +99,7 @@ fn drop_shadow<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::DropShadow {
color: evaluate_color_effects(color).into_element(),
color: evaluate_color_parameter(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -155,7 +155,7 @@ fn inner_shadow<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::InnerShadow {
color: evaluate_color_effects(color).into_element(),
color: evaluate_color_parameter(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -468,7 +468,7 @@ fn satin<T>(
stamp_effect(
&mut content,
Effect::new(&EffectOperation::Satin {
color: evaluate_color_effects(color).into_element(),
color: evaluate_color_parameter(color).into_element(),
blend_mode: *blend_mode.element(),
angle: *angle.element(),
distance: *distance.element(),
@@ -620,9 +620,9 @@ fn bevel_and_emboss<T: PaintFitBounds>(
soften: *soften.element(),
angle: *angle.element(),
altitude: *altitude.element(),
highlight_color: evaluate_color_effects(highlight_color).into_element(),
highlight_color: evaluate_color_parameter(highlight_color).into_element(),
highlight_blend_mode: *highlight_blend_mode.element(),
shadow_color: evaluate_color_effects(shadow_color).into_element(),
shadow_color: evaluate_color_parameter(shadow_color).into_element(),
shadow_blend_mode: *shadow_blend_mode.element(),
texture,
texture_depth: *texture_depth.element(),
@@ -661,11 +661,7 @@ fn paint_overlay<T: PaintFitBounds>(
let paint = match paint_with_envelope_effects(paint) {
Graphic::None(_) | Graphic::NoneList(_) => return content,
// A solid paint becomes a bare color, so its own opacity fades the color's alpha
Graphic::Color(color) => {
let opacity = color.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * color.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
let color = evaluate_color_effects(color).into_element();
Graphic::from(color.with_alpha(color.a() * opacity as f32))
}
Graphic::Color(color) => Graphic::from(evaluate_color_parameter(color).into_element()),
paint => paint_with_placement(&content, paint, _has_transform, _transform),
};
@@ -685,7 +681,7 @@ fn paint_overlay<T: PaintFitBounds>(
mod test {
use core_types::blending::BlendMode;
use core_types::list::{ATTR_EFFECTS, Item};
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM, Color};
use glam::{DAffine2, DVec2};
use graphic_types::raster_types::{Image, Raster};
use graphic_types::{Effects, Graphic};
@@ -775,6 +771,33 @@ mod test {
assert!(color.r() > 0.05 && color.r() < 0.95, "half the black paint leaves {color:?}");
}
#[test]
fn drop_shadow_fades_its_color_by_the_colors_own_opacity() {
use core_types::ATTR_OPACITY;
use core_types::transfer_curve::TransferCurve;
use graphic_types::EffectOperation;
let number = |value: f64| Item::new_from_element(value);
let shadowed = super::drop_shadow(
(),
Item::new_from_element(Raster::new_cpu(Image::new(1, 1, Color::WHITE))),
Item::new_from_element(Color::BLACK).with_attribute(ATTR_OPACITY, 0.5_f64),
BlendMode::Normal.into(),
number(120.),
number(5.),
number(0.),
number(5.),
Item::new_from_element(TransferCurve::default()),
true.into(),
);
let operation = shadowed.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| effects.operations().next());
let Some(EffectOperation::DropShadow { color, .. }) = operation else {
panic!("expected a drop shadow, got {operation:?}")
};
assert_eq!(color, Color::BLACK.with_alpha(0.5));
}
type PaintEffectNode<T> = fn(Item<T>, Graphic, bool, DAffine2) -> Item<T>;
fn paint_effect_nodes<T: super::PaintFitBounds>() -> [(&'static str, PaintEffectNode<T>); 3] {
@@ -825,7 +848,10 @@ mod test {
}
fn gradient_paints(transform: Option<DAffine2>, form: GradientForm) -> [Graphic; 2] {
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_GRADIENT_FORM, form);
let [start_curvature, end_curvature] = form.curvatures();
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
if let Some(transform) = transform {
gradient.set_attribute(ATTR_TRANSFORM, transform);
}
+1 -1
View File
@@ -53,7 +53,7 @@ fn create_artboard<T: IntoGraphicList>(
let normalized_location = location.min(location + dimensions);
let normalized_dimensions = dimensions.abs().max(DVec2::ONE);
let background = raster_kernels::evaluate_color_effects(background).into_element();
let background = raster_kernels::evaluate_color_parameter(background).into_element();
// Name is not stored here, it's resolved live from the parent layer's display name
Ok(Item::new_from_element(Artboard::new(content))
+18 -21
View File
@@ -12,7 +12,7 @@ use rand::seq::SliceRandom;
use raster_kernels::value_effects;
use raster_types::{CPU, GPU, Raster};
use std::cmp::Ordering;
use vector_types::gradient::{GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
use vector_types::gradient::{GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread};
use vector_types::{Gradient, ReferencePoint};
/// Returns the list with the item at the specified index removed.
@@ -649,7 +649,6 @@ fn write_attribute<T: AnyHash + Clone + Send + Sync + CacheHash>(
List<Generator>,
List<Artboard>,
List<BlendMode>,
List<GradientForm>,
List<GradientSpread>,
)]
content: List<T>,
@@ -806,24 +805,6 @@ fn read_attribute_blend_mode(
result
}
/// Reads a named `GradientForm` attribute from the input list, outputting each value as an element of a new `GradientForm[]`.
#[node_macro::node(category("Data: Attribute"), icon("NodeReadAttribute"))]
fn read_attribute_gradient_form(
_: impl Ctx,
content: ListDyn,
/// The attribute name (key) to read.
#[constant]
name: Item<String>,
) -> List<GradientForm> {
let name = name.into_element();
let mut result = List::with_capacity(content.len());
for index in 0..content.len() {
let Some(value) = content.attribute::<GradientForm>(&name, index) else { continue };
result.push(Item::new_from_element(*value));
}
result
}
/// Reads a named `GradientSpread` attribute from the input list, outputting each value as an element of a new `GradientSpread[]`.
#[node_macro::node(category("Data: Attribute"), icon("NodeReadAttribute"))]
fn read_attribute_gradient_spread(
@@ -1161,7 +1142,9 @@ fn flatten_gradient(_: impl Ctx, content: List<Graphic>) -> List<Gradient> {
/// Constructs a gradient from a `Color[]`, where each color becomes a gradient stop. A `position` attribute on the colors places their stops along the ramp and a `midpoint` attribute skews each transition, while colors carrying neither are distributed evenly across the 0 to 1 range.
#[node_macro::node(category("Gradient"), icon("NodeColorsToGradient"), name("Colors to Gradient"))]
fn colors_to_gradient(_: impl Ctx, colors: List<Graphic>) -> Item<Gradient> {
Item::new_from_element(Gradient::from(colors.into_flattened_list::<Color>()))
// Each color's own effects and opacity go into it before it becomes a stop
let colors: List<Color> = colors.into_flattened_list::<Color>().into_iter().map(value_effects::evaluate_color_parameter).collect();
Item::new_from_element(Gradient::from(colors))
}
/// Unwraps a gradient into a `Color[]` of its stops, keeping any `position` and `midpoint` attributes that place them along the ramp. Attributes belonging to the gradient as a whole (like spread and interpolation), rather than its individual color stops, are not preserved.
@@ -1442,4 +1425,18 @@ mod test {
expected.set_positions(&[0.25, 0.75]);
assert_eq!(colors_to_gradient((), embed_colors(colors)).element(), &expected, "each stop should keep its place");
}
#[test]
fn colors_to_gradient_carries_out_each_colors_effects_and_opacity() {
use core_types::ATTR_OPACITY;
use graphic_types::{Adjustment, EffectOperation};
let inverted = Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::Adjustment(Adjustment::Invert)]));
let half_opacity = Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY, 0.5_f64);
let colors: List<Color> = [inverted, half_opacity].into_iter().collect();
let gradient = colors_to_gradient((), embed_colors(colors));
let expected = Gradient::from(vec![Color::WHITE, Color::RED.with_alpha(0.5)]);
assert_eq!(gradient.element(), &expected, "the inverted black should become a white stop, and the half-opaque red a half-alpha one");
}
}
+26 -4
View File
@@ -1922,11 +1922,33 @@ fn gradient_value(_: impl Ctx, _primary: (), #[default(Color::BLACK, Color::WHIT
gradient
}
/// Sets the form (linear or radial) of each gradient in the input list.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_form(_: impl Ctx, gradient: Item<Gradient>, gradient_form: Item<vector_types::GradientForm>) -> Item<Gradient> {
/// Curves the contours at the start and end of each gradient in the input list between straight lines, circles, and points, with the contours between following along.
///
/// Each end runs from -1 to 1. At 0 its contour is a straight line, at 1 or -1 it shrinks to the end's own point, and between it is a circle through the end that bows toward the other end when positive or away from it when negative. A linear gradient is 0 at both ends, and a radial gradient is -1 at its start and 0.5 at its end.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"), inspector("gradient_curvature_inspector"), version(2))]
fn gradient_curvature(
_: impl Ctx,
gradient: Item<Gradient>,
/// The curve of the contour through the start.
#[slider]
#[soft(-1..1)]
start_curvature: Item<f64>,
/// The curve of the contour through the end.
#[slider]
#[soft(-1..1)]
end_curvature: Item<f64>,
) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_FORM, *gradient_form.element());
gradient.set_attribute(core_types::ATTR_GRADIENT_START_CURVATURE, *start_curvature.element());
gradient.set_attribute(core_types::ATTR_GRADIENT_END_CURVATURE, *end_curvature.element());
gradient
}
/// Sets how the contours between the curved start and end of each gradient in the input list are laid out: Standard or Apollonian.
#[node_macro::node(category("Gradient"), icon("NodeGradientForm"))]
fn gradient_model(_: impl Ctx, gradient: Item<Gradient>, model: Item<vector_types::GradientModel>) -> Item<Gradient> {
let mut gradient = gradient;
gradient.set_attribute(core_types::ATTR_GRADIENT_MODEL, *model.element());
gradient
}
+4 -3
View File
@@ -14,7 +14,7 @@ use graphic_types::adjustment::{
pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
use raster_kernels::{evaluate_color_effects, evaluate_gradient_effects};
use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects};
use raster_types::{CPU, GPU, Image, Raster};
use vector_types::Gradient;
@@ -414,7 +414,7 @@ fn black_and_white<T>(
) -> Item<T> {
let settings = BlackAndWhiteSettings {
use_tint: use_tint.into_element(),
tint: evaluate_color_effects(tint).into_element(),
tint: evaluate_color_parameter(tint).into_element(),
reds: reds.into_element(),
yellows: yellows.into_element(),
greens: greens.into_element(),
@@ -1417,7 +1417,7 @@ fn photo_filter<T>(
adjust(
image,
Adjustment::PhotoFilter {
color: evaluate_color_effects(color).into_element(),
color: evaluate_color_parameter(color).into_element(),
density: density.into_element(),
preserve_luminosity: preserve_luminosity.into_element(),
},
@@ -1460,6 +1460,7 @@ mod _graphene_hash_impls {
#[cfg(test)]
mod tests {
use super::*;
use raster_kernels::evaluate_color_effects;
/// Matched to within one 8-bit level.
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
+18 -2
View File
@@ -18,8 +18,8 @@ fn mix_colors(
#[default(100.)]
opacity: Item<f64>,
) -> Item<Color> {
let mut under = raster_kernels::evaluate_color_effects(under);
let over = raster_kernels::evaluate_color_effects(over);
let mut under = raster_kernels::evaluate_color_parameter(under);
let over = raster_kernels::evaluate_color_parameter(over);
let blend_mode = blend_mode.into_element();
let opacity = (opacity.into_element() / 100.) as f32;
@@ -41,4 +41,20 @@ mod test {
assert_eq!(mixed, Color::from_rgbaf32_unchecked(0.25, 0., 0.75, 1.));
}
#[test]
fn mix_colors_fades_each_color_by_its_opacity() {
use core_types::ATTR_OPACITY;
use core_types::list::Item;
let half_opacity = |color: Color| Item::new_from_element(color).with_attribute(ATTR_OPACITY, 0.5_f64);
let mix = |under: Item<Color>, over: Item<Color>| super::mix_colors((), under, over, BlendMode::Normal.into(), 100_f64.into());
assert_eq!(*mix(Color::TRANSPARENT.into(), half_opacity(Color::RED)).element(), Color::RED.with_alpha(0.5));
// The under color's opacity goes into its alpha, so the result carries none to fade it twice
let mixed = mix(half_opacity(Color::BLUE), Color::TRANSPARENT.into());
assert_eq!(*mixed.element(), Color::BLUE.with_alpha(0.5));
assert_eq!(mixed.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 1.);
}
}
+1 -100
View File
@@ -56,23 +56,17 @@ fn spiral(
_: impl Ctx,
_primary: (),
spiral_type: Item<SpiralType>,
#[hard(0..)]
#[default(5.)]
turns: Item<f64>,
#[default(5.)] turns: Item<f64>,
#[unit("°")]
#[default(0.)]
start_angle: Item<f64>,
#[unit(" px")]
#[hard(0..)]
#[default(0.)]
inner_radius: Item<f64>,
#[unit(" px")]
#[default(25)]
outer_radius: Item<f64>,
// Past a half turn no cubic follows the spiral closely
#[unit("°")]
#[hard(0..180)]
#[soft(1..)]
#[default(90.)]
angular_resolution: Item<f64>,
) -> Result<Item<Vector>, SpiralError> {
@@ -553,7 +547,6 @@ mod tests {
use super::*;
use core_types::list::{ATTR_DEPTH, ATTR_DISTANCE, ATTR_HEADING, ATTR_KIND, ATTR_SMOOTH, ATTR_STEP, ATTR_UV, ATTR_WIDTH};
use kurbo::ParamCurve;
use std::f64::consts::{PI, TAU};
use vector_types::vector::misc::point_to_dvec2;
use vector_types::vector::shared_paths_from_item_attributes;
@@ -797,98 +790,6 @@ mod tests {
}
}
/// Every control point of a spiral's cubics, in order.
fn spiral_control_points(inner_radius: f64, outer_radius: f64, turns: f64, start_angle: f64, angular_resolution: f64, spiral_type: SpiralType) -> Vec<DVec2> {
let bezpath = shapes::spiral_bezpath(inner_radius, outer_radius, turns, start_angle, angular_resolution, spiral_type).unwrap();
bezpath
.segments()
.flat_map(|segment| {
let cubic = segment.to_cubic();
[cubic.p0, cubic.p1, cubic.p2, cubic.p3]
})
.map(point_to_dvec2)
.collect()
}
// Between quarter-turn anchors, the best cubics stay within 0.02% of the spiral's radius
#[test]
fn spiral_cubics_stay_on_the_spiral_between_anchors() {
let (turns, angular_resolution) = (5., 90_f64.to_radians());
for (inner_radius, outer_radius, spiral_type) in [
(25., 25., SpiralType::Archimedean),
(20., 25., SpiralType::Archimedean),
(25., 25., SpiralType::Logarithmic),
(1., 100., SpiralType::Logarithmic),
] {
let bezpath = shapes::spiral_bezpath(inner_radius, outer_radius, turns, 0., angular_resolution, spiral_type).unwrap();
let spiral = shapes::SpiralCurve::new(spiral_type, inner_radius, outer_radius, turns, 0.);
// Each point's distance from the spiral at the same angle, unwrapped to the turn its segment winds through, relative to the spiral's radius there
let largest_error = bezpath
.segments()
.enumerate()
.flat_map(|(index, segment)| {
let middle = (index as f64 + 0.5) * angular_resolution;
(0..=64).map(move |step| {
let point = point_to_dvec2(segment.eval(step as f64 / 64.));
let angle = middle + (f64::atan2(-point.y, point.x) - middle + PI).rem_euclid(TAU) - PI;
let radius = spiral.radius(angle);
((point.length() - radius) / radius).abs()
})
})
.fold(0., f64::max);
assert!(largest_error < 2.5e-4, "{spiral_type:?} from {inner_radius} to {outer_radius} strays {largest_error} of its radius");
}
}
// Each segment's end is a multiple of the resolution, so a whole number of steps lands exactly on the end without a sliver segment after it
#[test]
fn spiral_has_one_segment_per_resolution_step() {
for (turns, degrees, segment_count) in [
(5., 30., 60),
(5., 60., 30),
(5., 22.5, 80),
(10., 45., 80),
(1., 60., 6),
(5., 1., 1800),
(5., 90., 20),
(1.25, 100., 5),
] {
let control_points = spiral_control_points(0., 25., turns, 0., f64::to_radians(degrees), SpiralType::Archimedean);
assert_eq!(control_points.len(), segment_count * 4, "{turns} turns at {degrees}°");
}
}
// The start angle rotates the spiral, which still winds from its inner radius to its outer radius
#[test]
fn spiral_start_angle_only_rotates_it() {
for spiral_type in [SpiralType::Archimedean, SpiralType::Logarithmic] {
let unrotated = spiral_control_points(5., 25., 2.5, 0., 45_f64.to_radians(), spiral_type);
let rotated = spiral_control_points(5., 25., 2.5, 90_f64.to_radians(), 45_f64.to_radians(), spiral_type);
// A quarter turn counterclockwise on screen, where +Y points down
let quarter_turn = DVec2::from_angle(-90_f64.to_radians());
assert!(unrotated.iter().zip(&rotated).all(|(unrotated, rotated)| quarter_turn.rotate(*unrotated).distance(*rotated) < 1e-9));
let (first, last) = (rotated.first().unwrap(), rotated.last().unwrap());
assert!((first.length() - 5.).abs() < 1e-9 && (last.length() - 25.).abs() < 1e-9, "{spiral_type:?} runs from {first} to {last}");
}
}
#[test]
fn logarithmic_spiral_to_a_zero_outer_radius_stays_finite() {
let control_points = spiral_control_points(10., 0., 2., 0., 90_f64.to_radians(), SpiralType::Logarithmic);
assert!(!control_points.is_empty() && control_points.iter().all(|point| point.is_finite()));
}
#[test]
fn spirals_report_more_segments_than_can_be_allocated() {
let endless = spiral((), (), item(SpiralType::Archimedean), item(f64::INFINITY), item(0.), item(0.), item(25.), item(90.));
assert!(matches!(endless, Err(SpiralError::TooManySegments)));
}
fn turtle(commands: &str) -> Item<Vector> {
turtle_varied(commands, 0., 0)
}
+21 -15
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_FORM, 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_END_CURVATURE, 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,6 @@ 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::GradientForm;
use vector_types::gradient::{build_transform_with_y_preservation, initial_gradient_transform_for_bounding_box};
use vector_types::vector::SetVectorPaths;
use vector_types::vector::algorithms::bezpath_algorithms::{
@@ -409,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"))]
#[node_macro::node(category("Vector: Style"), icon("NodeFill"), path(graphene_core::vector), inspector("fill_inspector"), version(2))]
fn fill<V>(
_: impl Ctx,
/// The content with vector paths to apply the fill style to.
@@ -418,14 +417,15 @@ fn fill<V>(
#[default(Color::BLACK)] paint: Item<Graphic>,
_backup_color: Item<Color>,
#[default(Color::BLACK, Color::WHITE)] _backup_gradient: Item<Gradient>,
_gradient_form: Item<GradientForm>,
_start_curvature: Item<f64>,
_end_curvature: Item<f64>,
_has_transform: Item<bool>,
_transform: Item<DAffine2>,
) -> Item<V>
where
Item<V>: VectorItemMut + Send,
{
let _gradient_form = _gradient_form.into_element();
let (_start_curvature, _end_curvature) = (_start_curvature.into_element(), _end_curvature.into_element());
let (_has_transform, _transform) = (_has_transform.into_element(), *_transform.element());
let mut content = content;
@@ -433,12 +433,15 @@ where
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 a form or transform, since an absent attribute should mean the same as its default.
// TODO: Stop reading whether the gradient has curvatures 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_form, needs_transform) = match &paint {
Graphic::Gradient(item) => (item.attribute::<GradientForm>(ATTR_GRADIENT_FORM).is_none(), item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none()),
let (needs_curvatures, needs_transform) = match &paint {
Graphic::Gradient(item) => (
item.attribute::<f64>(ATTR_GRADIENT_START_CURVATURE).is_none() && item.attribute::<f64>(ATTR_GRADIENT_END_CURVATURE).is_none(),
item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
),
Graphic::GradientList(list) => (
list.iter_attribute_values::<GradientForm>(ATTR_GRADIENT_FORM).is_none(),
list.iter_attribute_values::<f64>(ATTR_GRADIENT_START_CURVATURE).is_none() && list.iter_attribute_values::<f64>(ATTR_GRADIENT_END_CURVATURE).is_none(),
list.iter_attribute_values::<DAffine2>(ATTR_TRANSFORM).is_none(),
),
_ => (false, false),
@@ -473,17 +476,20 @@ where
match &mut paint {
Graphic::Gradient(item) => {
if needs_form {
item.set_attribute(ATTR_GRADIENT_FORM, _gradient_form);
if needs_curvatures {
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, _start_curvature);
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, _end_curvature);
}
if let Some(transform) = stamped_transform {
item.set_attribute(ATTR_TRANSFORM, transform);
}
}
Graphic::GradientList(list) => {
if needs_form {
for value in list.iter_attribute_values_mut_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
*value = _gradient_form;
if needs_curvatures {
for (key, curvature) in [(ATTR_GRADIENT_START_CURVATURE, _start_curvature), (ATTR_GRADIENT_END_CURVATURE, _end_curvature)] {
for value in list.iter_attribute_values_mut_or_default::<f64>(key) {
*value = curvature;
}
}
}
if let Some(transform) = stamped_transform {
+6 -2
View File
@@ -1,5 +1,7 @@
use core_types::Color;
use core_types::list::{ATTR_CLIPPING_MASK, ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_POSITION, ATTR_TRANSFORM, Item, List};
use core_types::list::{
ATTR_CLIPPING_MASK, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_POSITION, ATTR_TRANSFORM, Item, List,
};
use glam::{DAffine2, DMat2, DVec2, DVec3};
use graphene_hash::CacheHash;
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
@@ -225,8 +227,10 @@ fn gradient_item(gradient: &ollev::model::Gradient) -> Item<Gradient> {
}
};
let [start_curvature, end_curvature] = form.curvatures();
Item::new_from_element(Gradient(stops))
.with_attribute(ATTR_GRADIENT_FORM, form)
.with_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature)
.with_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature)
.with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma)
.with_attribute(ATTR_TRANSFORM, transform)
}