mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cc1c343bf3 |
No files matched your search
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
|
|||||||
const MAX_RUN_PAGES = 10;
|
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
|
// 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";
|
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;
|
const MAX_VERDICT_LOOKUPS = 5;
|
||||||
|
|
||||||
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
||||||
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
|
|||||||
return newestFirst(runs);
|
return newestFirst(runs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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)
|
// 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)
|
||||||
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
|
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
|
||||||
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
||||||
const run = finishedRunsNewestFirst[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 { 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 || []);
|
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;
|
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
|
|||||||
const decision = readDecision();
|
const decision = readDecision();
|
||||||
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
||||||
const passed = PASSING_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
|
// 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) {
|
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
|
||||||
@@ -48,10 +47,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||||
|
|
||||||
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran
|
// 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" : superseded ? "superseded" : retried ? "retry" : "verdict";
|
const result = passed ? "approved" : retried ? "retry" : "verdict";
|
||||||
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
||||||
|
|
||||||
function readDecision(): Decision {
|
function readDecision(): Decision {
|
||||||
|
|||||||
@@ -176,8 +176,6 @@ jobs:
|
|||||||
env:
|
env:
|
||||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||||
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
|
||||||
# GPU tests made through `for_tests()` fail rather than skip when the software Vulkan driver above can't make a device
|
|
||||||
WGPU_BACKEND: vulkan
|
|
||||||
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
# The desktop crates need CEF, and `third-party-licenses` only pulls it in through its `desktop` feature, so it runs on its own without `--all-features`
|
||||||
run: >-
|
run: >-
|
||||||
cargo test --workspace --all-features
|
cargo test --workspace --all-features
|
||||||
|
|||||||
@@ -64,12 +64,7 @@ jobs:
|
|||||||
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
||||||
run: exit 1
|
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
|
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
|
||||||
- name: 🔁 Fail without a verdict
|
- name: 🔁 Fail without a verdict
|
||||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
|
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
|
||||||
run: exit 1
|
run: exit 1
|
||||||
Generated
+7
-10
@@ -585,7 +585,6 @@ name = "blending-nodes"
|
|||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"core-types",
|
"core-types",
|
||||||
"futures",
|
|
||||||
"glam",
|
"glam",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
@@ -593,7 +592,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
"text-nodes",
|
"text-nodes",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
"wgpu-executor",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -2677,6 +2675,7 @@ dependencies = [
|
|||||||
"math-nodes",
|
"math-nodes",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"path-bool-nodes",
|
"path-bool-nodes",
|
||||||
|
"raster-kernels",
|
||||||
"raster-nodes",
|
"raster-nodes",
|
||||||
"rendering",
|
"rendering",
|
||||||
"repeat-nodes",
|
"repeat-nodes",
|
||||||
@@ -5438,11 +5437,9 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
"graphic-types",
|
|
||||||
"interpreted-executor",
|
"interpreted-executor",
|
||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"wgpu-executor",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5749,6 +5746,8 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graphene-resource",
|
"graphene-resource",
|
||||||
"graphic-types",
|
"graphic-types",
|
||||||
|
"half",
|
||||||
|
"log",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
@@ -5773,14 +5772,12 @@ dependencies = [
|
|||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"rendering",
|
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tsify",
|
"tsify",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"wgpu-executor",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8079,6 +8076,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"ollev",
|
"ollev",
|
||||||
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
@@ -8086,7 +8084,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_common"
|
name = "vello_common"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"fearless_simd",
|
"fearless_simd",
|
||||||
@@ -8101,7 +8099,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_gpu"
|
name = "vello_gpu"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"hashbrown 0.17.1",
|
"hashbrown 0.17.1",
|
||||||
@@ -8115,7 +8113,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_gpu_shaders"
|
name = "vello_gpu_shaders"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"naga",
|
"naga",
|
||||||
"wesl",
|
"wesl",
|
||||||
@@ -8586,7 +8584,6 @@ dependencies = [
|
|||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"rendering",
|
"rendering",
|
||||||
"svg-convert",
|
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"vello_gpu",
|
"vello_gpu",
|
||||||
"web-sys",
|
"web-sys",
|
||||||
|
|||||||
+3
-3
@@ -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
|
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
|
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
|
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
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,7 +1,5 @@
|
|||||||
//! Migrations of the nodes in `graphene_core`.
|
//! 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 passthrough_from_upload_texture_node;
|
||||||
mod renames;
|
mod renames;
|
||||||
mod vary_colors_from_assign_colors;
|
mod vary_colors_from_assign_colors;
|
||||||
-36
@@ -1,36 +0,0 @@
|
|||||||
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]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
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,5 +1,4 @@
|
|||||||
//! Migrations of the nodes in `math_nodes`.
|
//! Migrations of the nodes in `math_nodes`.
|
||||||
|
|
||||||
mod gradient_curvature_from_gradient_form;
|
|
||||||
mod math_formula_from_math_f;
|
mod math_formula_from_math_f;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -6,6 +6,5 @@ mod mandelbrot_v2;
|
|||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
mod noise_pattern_v2;
|
mod noise_pattern_v2;
|
||||||
mod passthrough_from_extend_image_to_bounds;
|
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
use migration_core::{Inputs, migration};
|
|
||||||
|
|
||||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
|
||||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
|
||||||
pub fn passthrough_from_extend_image_to_bounds(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(&PassthroughFromExtendImageToBounds, &contract());
|
|
||||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_image_and_drops_the_bounds() {
|
|
||||||
let (image, bounds) = (literal(1.), literal(2.));
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
|
||||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
|
||||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,12 +4,3 @@ use migration_core::rename;
|
|||||||
|
|
||||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||||
|
|
||||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
|
||||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
|
||||||
|
|
||||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
|
||||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
|
||||||
|
|
||||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
|
||||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
|
||||||
@@ -13,7 +13,7 @@ pub enum ClipboardMessage {
|
|||||||
CopyLayers,
|
CopyLayers,
|
||||||
CutLayers,
|
CutLayers,
|
||||||
WriteItems { items: Vec<ApplicationDataItem> },
|
WriteItems { items: Vec<ApplicationDataItem> },
|
||||||
Rendered { id: u64, svg: Result<Option<String>, String> },
|
Rendered { id: u64, svg: Option<String> },
|
||||||
Loaded { id: u64, content: DataTransfer },
|
Loaded { id: u64, content: DataTransfer },
|
||||||
PasteItems { items: Vec<ApplicationDataItem> },
|
PasteItems { items: Vec<ApplicationDataItem> },
|
||||||
PasteLayers { entries: Vec<ApplicationDataLayer> },
|
PasteLayers { entries: Vec<ApplicationDataLayer> },
|
||||||
|
|||||||
@@ -246,15 +246,6 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
|||||||
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
|
let Some(PendingCopy::Rendering { items, loads, .. }) = self.pending_copy.take_if(|pending| pending.id() == id) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
// The layers still copy, without an SVG
|
|
||||||
let svg = svg.unwrap_or_else(|error| {
|
|
||||||
responses.add(DialogMessage::DisplayDialogError {
|
|
||||||
title: "Unable to copy as SVG".to_string(),
|
|
||||||
description: error,
|
|
||||||
});
|
|
||||||
None
|
|
||||||
});
|
|
||||||
self.finish_copy(items, loads, svg, resource_storage, responses);
|
self.finish_copy(items, loads, svg, resource_storage, responses);
|
||||||
}
|
}
|
||||||
ClipboardMessage::Loaded { id, content } => {
|
ClipboardMessage::Loaded { id, content } => {
|
||||||
@@ -674,212 +665,6 @@ mod test {
|
|||||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The bounds of what the SVG draws, strokes included, and the size of its frame.
|
|
||||||
fn drawn_bounds_and_frame(svg: &str) -> (usvg::Rect, usvg::Size) {
|
|
||||||
let tree = usvg::Tree::from_str(svg, &usvg::Options::default()).unwrap_or_else(|error| panic!("the SVG should parse ({error}): {svg}"));
|
|
||||||
(tree.root().abs_stroke_bounding_box(), tree.size())
|
|
||||||
}
|
|
||||||
|
|
||||||
// A layer is copied as what it adds to the group holding it, so the group's move is left out of both its frame and what it draws
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_frames_a_grouped_layer_without_its_groups_transform() {
|
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
|
||||||
use glam::DAffine2;
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 100., 50.).await;
|
|
||||||
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
|
||||||
editor
|
|
||||||
.handle_message(DocumentMessage::GroupSelectedLayers {
|
|
||||||
group_folder_type: GroupFolderType::Layer,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let group = rectangle.parent(editor.active_document().metadata()).expect("the rectangle should be grouped");
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::TransformChange {
|
|
||||||
layer: group,
|
|
||||||
transform: DAffine2::from_translation(DVec2::new(500., 300.)),
|
|
||||||
transform_in: TransformIn::Local,
|
|
||||||
skip_rerender: false,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![rectangle.to_node()] }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the grouped rectangle should render an SVG");
|
|
||||||
|
|
||||||
// The frame grows past the stroke by as far as its miter joins could reach
|
|
||||||
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
|
||||||
let within_frame = drawn.left() >= 0. && drawn.top() >= 0. && drawn.right() <= frame.width() && drawn.bottom() <= frame.height();
|
|
||||||
assert!(within_frame, "the rectangle should be drawn within the frame, at {drawn:?} in {frame:?}: {svg}");
|
|
||||||
assert!(frame.width() < 120. && frame.height() < 70., "the frame should hold only the rectangle: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Any node can be shown as a layer, which adds everything it outputs
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_draws_a_layer_that_is_not_a_merge() {
|
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 100., 50.).await;
|
|
||||||
let rectangle = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle").to_node();
|
|
||||||
|
|
||||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
|
||||||
let content_node = network_interface
|
|
||||||
.upstream_flow_back_from_nodes(vec![rectangle], &[], FlowType::HorizontalFlow)
|
|
||||||
.nth(1)
|
|
||||||
.expect("the layer should have a content chain");
|
|
||||||
network_interface.set_to_node_or_layer(&content_node, &[], true);
|
|
||||||
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![content_node] }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the layer should render an SVG");
|
|
||||||
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// An artboard holds its own content, so the other layers copied with it are left out of the SVG
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_of_artboards_and_other_layers_draws_only_the_artboards() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.drag_tool(ToolType::Artboard, 0., 0., 200., 100., ModifierKeys::empty()).await;
|
|
||||||
editor.draw_rect(500., 500., 600., 600.).await;
|
|
||||||
|
|
||||||
let layers = editor.active_document().metadata().all_layers().map(|layer| layer.to_node()).collect();
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: layers }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the artboard should render an SVG");
|
|
||||||
|
|
||||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
|
||||||
assert!(
|
|
||||||
(frame.width() - 200.).abs() < 1. && (frame.height() - 100.).abs() < 1.,
|
|
||||||
"the SVG should be framed to the artboard alone: {svg}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The frame keeps the content's exact size, rather than whole pixels that would round a fifth of a unit away to nothing
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_keeps_a_fractional_frame() {
|
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
|
||||||
use glam::DAffine2;
|
|
||||||
use graphene_std::vector::style::Stroke;
|
|
||||||
|
|
||||||
// A square shrunk to a fifth of a unit across, with only a fill
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 100., 100.).await;
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().expect("the drawn rectangle");
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::StrokeSet {
|
|
||||||
layer,
|
|
||||||
color: None,
|
|
||||||
stroke: Stroke::default(),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::TransformSet {
|
|
||||||
layer,
|
|
||||||
transform: DAffine2::from_scale(DVec2::splat(0.002)),
|
|
||||||
transform_in: TransformIn::Local,
|
|
||||||
skip_rerender: false,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the square should render an SVG");
|
|
||||||
|
|
||||||
let (drawn, frame) = drawn_bounds_and_frame(svg);
|
|
||||||
assert!(
|
|
||||||
(frame.width() - 0.2).abs() < 1e-4 && (frame.height() - 0.2).abs() < 1e-4,
|
|
||||||
"the frame should be the square's size: {svg}"
|
|
||||||
);
|
|
||||||
assert!((drawn.width() - 0.2).abs() < 1e-4 && drawn.left().abs() < 1e-4, "the square should fill the frame: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the viewport to `size` pixels and gives back the size of the part of the document it shows.
|
|
||||||
async fn view_of_size(editor: &mut EditorTestUtils, size: DVec2) -> DVec2 {
|
|
||||||
use graphene_std::math::quad::Quad;
|
|
||||||
|
|
||||||
editor.set_viewport_size(DVec2::ZERO, size).await;
|
|
||||||
let viewport_to_document = editor.active_document().metadata().document_to_viewport.inverse();
|
|
||||||
let [min, max] = (viewport_to_document * Quad::from_box([DVec2::ZERO, size])).bounding_box();
|
|
||||||
max - min
|
|
||||||
}
|
|
||||||
|
|
||||||
// Content drawn for its view, like a brush stroke's image or tiles covering the view, is framed to the view it was copied in
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_frames_content_drawn_for_its_view_to_that_view() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let view = view_of_size(&mut editor, DVec2::new(400., 300.)).await;
|
|
||||||
let framed_to_view = |svg: &str| {
|
|
||||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
|
||||||
(frame.width() as f64 - view.x).abs() < 1e-3 && (frame.height() as f64 - view.y).abs() < 1e-3
|
|
||||||
};
|
|
||||||
|
|
||||||
// A brush stroke
|
|
||||||
editor.handle_message(PreferencesMessage::BrushTool { enabled: true }).await;
|
|
||||||
editor.drag_tool(ToolType::Brush, 50., 50., 150., 100., ModifierKeys::empty()).await;
|
|
||||||
let brush = editor.active_document().metadata().all_layers().next().expect("the brush layer");
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![brush.to_node()] }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the brush layer should render an SVG");
|
|
||||||
assert!(framed_to_view(svg), "the brush layer should be framed to the {view} view: {svg}");
|
|
||||||
assert!(svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"), "the stroke should be the GPU's image: {svg}");
|
|
||||||
|
|
||||||
// A rectangle tiled across the view
|
|
||||||
editor.draw_rect(0., 0., 20., 20.).await;
|
|
||||||
let tiled = editor.active_document().metadata().all_layers().next().expect("the rectangle");
|
|
||||||
let tile = DefinitionIdentifier::ProtoNode(graphene_std::repeat::tile::IDENTIFIER);
|
|
||||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type: tile, layer: tiled }).await;
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![tiled.to_node()] }).await;
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the tiled layer should render an SVG");
|
|
||||||
assert!(framed_to_view(svg), "the tiled layer should be framed to the {view} view: {svg}");
|
|
||||||
assert!(svg.matches("<path").count() > 1, "the view should hold several tiles: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg_attr(miri, ignore)]
|
|
||||||
#[tokio::test]
|
|
||||||
async fn copied_svg_draws_generators_as_the_gpus_render() {
|
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::OutputConnector;
|
|
||||||
use graph_craft::document::NodeId;
|
|
||||||
|
|
||||||
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.create_raster_image(graphene_std::raster::Image::new(1, 1, Color::BLACK), None).await;
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().expect("the image layer").to_node();
|
|
||||||
let mandelbrot = NodeId::new();
|
|
||||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
|
||||||
node_id: Some(mandelbrot),
|
|
||||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
|
|
||||||
xy: None,
|
|
||||||
add_transaction: true,
|
|
||||||
});
|
|
||||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
|
||||||
output_connector: OutputConnector::primary_output(mandelbrot),
|
|
||||||
input_connector: InputConnector::node_at_index(layer, 1),
|
|
||||||
});
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] }).await;
|
|
||||||
|
|
||||||
// The SVG frames the fractal's body, hundreds of units across rather than the image's one, and embeds the GPU's image of it where its placeholder stood
|
|
||||||
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
|
||||||
let svg = copied_svg(&clipboard).expect("the Mandelbrot layer should render an SVG");
|
|
||||||
let (_, frame) = drawn_bounds_and_frame(svg);
|
|
||||||
assert!(frame.width() > 100., "{svg}");
|
|
||||||
assert!(svg.matches("data:image/png;base64,").count() == 1 && !svg.contains("deferred-image"), "{svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// - paste
|
/// - paste
|
||||||
/// - assert that ellipse was copied
|
/// - assert that ellipse was copied
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -31,8 +31,7 @@ use graphene_std::vector::misc::{
|
|||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||||
StrokeJoin,
|
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||||
use graphene_std::{
|
use graphene_std::{
|
||||||
@@ -409,6 +408,7 @@ macro_rules! inspectable_types {
|
|||||||
List<DVec2>,
|
List<DVec2>,
|
||||||
List<DAffine2>,
|
List<DAffine2>,
|
||||||
List<BlendMode>,
|
List<BlendMode>,
|
||||||
|
List<GradientForm>,
|
||||||
List<GradientSpread>,
|
List<GradientSpread>,
|
||||||
List<GradientSpace>,
|
List<GradientSpace>,
|
||||||
List<GradientHueDirection>,
|
List<GradientHueDirection>,
|
||||||
@@ -469,7 +469,6 @@ macro_rules! inspectable_types {
|
|||||||
Item<DAffine2>,
|
Item<DAffine2>,
|
||||||
Item<BlendMode>,
|
Item<BlendMode>,
|
||||||
Item<GradientForm>,
|
Item<GradientForm>,
|
||||||
Item<GradientModel>,
|
|
||||||
Item<GradientSpread>,
|
Item<GradientSpread>,
|
||||||
Item<GradientSpace>,
|
Item<GradientSpace>,
|
||||||
Item<GradientHueDirection>,
|
Item<GradientHueDirection>,
|
||||||
@@ -1285,7 +1284,6 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
MaskMode,
|
MaskMode,
|
||||||
MinimumMaximumMode,
|
MinimumMaximumMode,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -1481,7 +1479,6 @@ macro_rules! known_item_types {
|
|||||||
TransferCurve,
|
TransferCurve,
|
||||||
BlendMode,
|
BlendMode,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
|
|||||||
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
|
|||||||
layer: LayerNodeIdentifier,
|
layer: LayerNodeIdentifier,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
gradient: Gradient,
|
gradient: Gradient,
|
||||||
/// The form whose curvatures the Fill takes, or `None` to keep its own.
|
gradient_form: GradientForm,
|
||||||
gradient_form: Option<GradientForm>,
|
|
||||||
gradient_settings: GradientSettings,
|
gradient_settings: GradientSettings,
|
||||||
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
||||||
transform: Option<DAffine2>,
|
transform: Option<DAffine2>,
|
||||||
|
|||||||
+2
-2
@@ -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),
|
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||||
}
|
}
|
||||||
usvg::Paint::RadialGradient(radial) => {
|
usvg::Paint::RadialGradient(radial) => {
|
||||||
let gradient_transform = usvg_transform(radial.transform());
|
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),
|
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||||
}
|
}
|
||||||
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
|
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::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||||
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,
|
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
|
||||||
};
|
};
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::application_io::resource::ResourceId;
|
use graph_craft::application_io::resource::ResourceId;
|
||||||
@@ -450,8 +450,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||||
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 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 {
|
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;
|
return;
|
||||||
@@ -491,22 +490,11 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 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(
|
self.set_input_with_refresh(
|
||||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
|
||||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
|
||||||
true,
|
false,
|
||||||
);
|
);
|
||||||
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() {
|
if existing_fill_node_id.is_none() {
|
||||||
self.restore_default_stroke_order();
|
self.restore_default_stroke_order();
|
||||||
@@ -773,28 +761,20 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||||
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
|
/// from the default (`Linear`).
|
||||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
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 Some(output_layer) = self.get_output_layer() else { return };
|
||||||
|
|
||||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
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 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;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||||
let Some(curvatures) = gradient_curvature_values(node) else { return };
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||||
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.
|
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use crate::application::Environment;
|
use crate::application::Environment;
|
||||||
use crate::consts::{
|
use crate::consts::{
|
||||||
DOUBLE_CLICK_ALLOWED_TRAVEL, VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX,
|
VIEWPORT_ROTATE_SNAP_INTERVAL, VIEWPORT_SCROLL_RATE, VIEWPORT_ZOOM_LEVELS, VIEWPORT_ZOOM_MIN_FRACTION_COVER, VIEWPORT_ZOOM_MOUSE_RATE, VIEWPORT_ZOOM_SCALE_MAX, VIEWPORT_ZOOM_SCALE_MIN,
|
||||||
VIEWPORT_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||||
};
|
};
|
||||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||||
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
use crate::messages::input_mapper::utility_types::keyboard::{Key, MouseMotion};
|
||||||
use crate::messages::input_mapper::utility_types::pointer::{MouseKeys, ViewportPosition};
|
use crate::messages::input_mapper::utility_types::pointer::ViewportPosition;
|
||||||
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
use crate::messages::portfolio::document::navigation::utility_types::NavigationOperation;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
use crate::messages::portfolio::document::utility_types::misc::PTZ;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||||
@@ -34,8 +34,6 @@ pub struct NavigationMessageHandler {
|
|||||||
abortable_pan_start: Option<f64>,
|
abortable_pan_start: Option<f64>,
|
||||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||||
artwork_behind_graph: bool,
|
artwork_behind_graph: bool,
|
||||||
/// Where a middle press began panning the open node graph, kept until the pointer travels too far for its release to still be a click.
|
|
||||||
graph_middle_click_start: Option<ViewportPosition>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[message_handler_data]
|
#[message_handler_data]
|
||||||
@@ -101,10 +99,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
|||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
self.navigation_operation = NavigationOperation::Pan { pan_original_for_abort: ptz.pan };
|
||||||
|
|
||||||
// Released before traveling far, a middle press that pans the open graph is instead a click on the node under it
|
|
||||||
let middle_press_in_graph = graph_view_overlay_open && ipp.mouse.mouse_keys == MouseKeys::MIDDLE;
|
|
||||||
self.graph_middle_click_start = middle_press_in_graph.then_some(ipp.mouse.position);
|
|
||||||
}
|
}
|
||||||
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
NavigationMessage::BeginCanvasTilt { was_dispatched_from_menu } => {
|
||||||
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
let Some(ptz) = get_ptz(document_ptz, network_interface, graph_view_overlay_open, breadcrumb_network_path) else {
|
||||||
@@ -347,13 +341,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
|||||||
responses.add(ToolMessage::UpdateCursor);
|
responses.add(ToolMessage::UpdateCursor);
|
||||||
responses.add(ToolMessage::UpdateHints);
|
responses.add(ToolMessage::UpdateHints);
|
||||||
responses.add(NavigateToolMessage::End);
|
responses.add(NavigateToolMessage::End);
|
||||||
|
|
||||||
// Not a pan after all, but a middle click in the graph
|
|
||||||
let middle_click_start = self.graph_middle_click_start.take();
|
|
||||||
let middle_released = !ipp.mouse.mouse_keys.contains(MouseKeys::MIDDLE);
|
|
||||||
if !abort_transform && middle_released && middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) <= DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
|
||||||
responses.add(NodeGraphMessage::MiddleClick);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
NavigationMessage::EndCanvasPTZWithClick { commit_key } => {
|
||||||
self.finish_operation_with_click = false;
|
self.finish_operation_with_click = false;
|
||||||
@@ -430,10 +417,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
NavigationMessage::PointerMove { snap } => {
|
NavigationMessage::PointerMove { snap } => {
|
||||||
if self.graph_middle_click_start.is_some_and(|start| start.distance(ipp.mouse.position) > DOUBLE_CLICK_ALLOWED_TRAVEL) {
|
|
||||||
self.graph_middle_click_start = None;
|
|
||||||
}
|
|
||||||
|
|
||||||
match self.navigation_operation {
|
match self.navigation_operation {
|
||||||
NavigationOperation::None => {}
|
NavigationOperation::None => {}
|
||||||
NavigationOperation::Pan { .. } => {
|
NavigationOperation::Pan { .. } => {
|
||||||
|
|||||||
@@ -686,7 +686,6 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
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("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("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("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_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));
|
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||||
|
|||||||
@@ -170,8 +170,6 @@ pub enum NodeGraphMessage {
|
|||||||
PointerOutsideViewport {
|
PointerOutsideViewport {
|
||||||
shift: Key,
|
shift: Key,
|
||||||
},
|
},
|
||||||
/// Sent when the middle button is released where it was pressed in the graph, rather than having panned it.
|
|
||||||
MiddleClick,
|
|
||||||
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
/// Sent every frame while a dragged wire hovers a node, to expand it once the hover delay passes.
|
||||||
WireHoverTick,
|
WireHoverTick,
|
||||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||||
@@ -439,7 +437,6 @@ impl NodeGraphMessage {
|
|||||||
| Self::PointerMove { .. }
|
| Self::PointerMove { .. }
|
||||||
| Self::PointerUp
|
| Self::PointerUp
|
||||||
| Self::PointerOutsideViewport { .. }
|
| Self::PointerOutsideViewport { .. }
|
||||||
| Self::MiddleClick
|
|
||||||
| Self::WireHoverTick
|
| Self::WireHoverTick
|
||||||
| Self::SendGlide
|
| Self::SendGlide
|
||||||
| Self::GlideTick
|
| Self::GlideTick
|
||||||
|
|||||||
@@ -1752,20 +1752,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
|||||||
self.auto_panning.stop(&messages, responses);
|
self.auto_panning.stop(&messages, responses);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Middle-clicking a node toggles its visibility
|
|
||||||
NodeGraphMessage::MiddleClick => {
|
|
||||||
if !graph_view_overlay_open || network_interface.is_read_only(breadcrumb_network_path) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let Some(node_id) = network_interface.node_from_click(ipp.mouse.position, breadcrumb_network_path) else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::ToggleVisibility {
|
|
||||||
node_id,
|
|
||||||
network_path: breadcrumb_network_path.to_vec(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
NodeGraphMessage::WireHoverTick => {
|
NodeGraphMessage::WireHoverTick => {
|
||||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
|
|||||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
build_transform_with_y_preservation,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||||
@@ -254,23 +254,6 @@ pub(crate) struct ParameterOptions {
|
|||||||
pub step: Option<f64>,
|
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.
|
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct SliderRange {
|
pub struct SliderRange {
|
||||||
@@ -434,7 +417,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
// AUTO-GENERATED ENUM TYPES
|
// 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::<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::<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::<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(),
|
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||||
@@ -3304,80 +3286,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
|||||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
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> {
|
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||||
|
|
||||||
@@ -3535,7 +3443,18 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
|||||||
.get(&proto_node_identifier)
|
.get(&proto_node_identifier)
|
||||||
.and_then(|metadata| metadata.fields.get(input_index))
|
.and_then(|metadata| metadata.fields.get(input_index))
|
||||||
{
|
{
|
||||||
options = ParameterOptions::from(field);
|
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,
|
||||||
|
};
|
||||||
default_type = field.default_type.clone();
|
default_type = field.default_type.clone();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3924,25 +3843,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
|||||||
let entries = [GradientForm::Linear, GradientForm::Radial]
|
let entries = [GradientForm::Linear, GradientForm::Radial]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&gradient_form| {
|
.map(|&gradient_form| {
|
||||||
let [start, end] = gradient_form.curvatures();
|
|
||||||
RadioEntryData::new(format!("{:?}", gradient_form))
|
RadioEntryData::new(format!("{:?}", gradient_form))
|
||||||
.label(gradient_form.to_string())
|
.label(gradient_form.to_string())
|
||||||
.on_update(move |_| Message::Batched {
|
.on_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
|
||||||
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)
|
.on_commit(commit_value)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ impl FrontendGraphDataType {
|
|||||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||||
// A generator draws pixels like an image, at whatever resolution is needed
|
// A generator draws pixels like an image, at whatever resolution is needed
|
||||||
"Generator" => Self::Raster,
|
"Generator" => Self::Raster,
|
||||||
"Pixels" => Self::Raster,
|
|
||||||
raster if raster.starts_with("Raster") => Self::Raster,
|
raster if raster.starts_with("Raster") => Self::Raster,
|
||||||
_ => Self::General,
|
_ => Self::General,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||||
let fill_node = &network.nodes[&node_id];
|
let fill_node = &network.nodes[&node_id];
|
||||||
|
|
||||||
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
|
||||||
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
||||||
assert!(
|
assert!(
|
||||||
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
||||||
@@ -1033,13 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
|||||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||||
let fill_node = &network.nodes[&node_id];
|
let fill_node = &network.nodes[&node_id];
|
||||||
|
|
||||||
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
|
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
|
||||||
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
|
|
||||||
assert_eq!(
|
|
||||||
curvatures,
|
|
||||||
[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 paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||||
|
|||||||
-57
@@ -3399,63 +3399,6 @@ async fn visibility_and_lock_toggles_made_in_an_open_transaction_undo_together()
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn middle_clicking_a_node_in_the_graph_toggles_its_visibility_but_middle_dragging_only_pans() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 100., 100.).await;
|
|
||||||
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected").to_node();
|
|
||||||
editor.handle_message(DocumentMessage::GraphViewOverlay { open: true }).await;
|
|
||||||
|
|
||||||
let is_visible = |editor: &EditorTestUtils| editor.active_document().network_interface.is_visible(&layer, &[]);
|
|
||||||
let graph_pan = |editor: &EditorTestUtils| {
|
|
||||||
editor
|
|
||||||
.active_document()
|
|
||||||
.network_interface
|
|
||||||
.network_metadata(&[])
|
|
||||||
.unwrap()
|
|
||||||
.persistent_metadata
|
|
||||||
.navigation_metadata
|
|
||||||
.node_graph_ptz
|
|
||||||
.pan
|
|
||||||
};
|
|
||||||
let layer_in_viewport = |editor: &EditorTestUtils| {
|
|
||||||
let network_interface = &editor.active_document().network_interface;
|
|
||||||
let [min, max] = network_interface.node_bounding_box(&layer, &[]).expect("the layer should have bounds");
|
|
||||||
let node_graph_to_viewport = network_interface.network_metadata(&[]).unwrap().persistent_metadata.navigation_metadata.node_graph_to_viewport;
|
|
||||||
|
|
||||||
(0..=(max.x - min.x) as i32)
|
|
||||||
.map(|x| node_graph_to_viewport.transform_point2(DVec2::new(min.x + x as f64, (min.y + max.y) / 2.)))
|
|
||||||
.find(|&point| network_interface.node_from_click(point, &[]) == Some(layer))
|
|
||||||
.expect("the layer should be pressable")
|
|
||||||
};
|
|
||||||
let pointer_state = |position: DVec2, mouse_keys: MouseKeys| EditorPointerState {
|
|
||||||
editor_position: position,
|
|
||||||
mouse_keys,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
// Pressed and released with a wobble too small to count as a drag
|
|
||||||
let start = layer_in_viewport(&editor);
|
|
||||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
|
||||||
assert!(is_visible(&editor), "pressing the middle button shouldn't toggle the layer yet");
|
|
||||||
editor.mouseup(pointer_state(start + DVec2::new(2., 0.), MouseKeys::empty()), ModifierKeys::empty()).await;
|
|
||||||
assert!(!is_visible(&editor), "a middle click on the layer should hide it");
|
|
||||||
|
|
||||||
// Dragged away and back before the release
|
|
||||||
let start = layer_in_viewport(&editor);
|
|
||||||
let pan_before = graph_pan(&editor);
|
|
||||||
editor.mousedown(pointer_state(start, MouseKeys::MIDDLE), ModifierKeys::empty()).await;
|
|
||||||
editor.move_mouse(start.x + 40., start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
|
||||||
assert_ne!(graph_pan(&editor), pan_before, "a middle drag should pan the graph");
|
|
||||||
editor.move_mouse(start.x, start.y, ModifierKeys::empty(), MouseKeys::MIDDLE).await;
|
|
||||||
editor.mouseup(pointer_state(start, MouseKeys::empty()), ModifierKeys::empty()).await;
|
|
||||||
assert!(!is_visible(&editor), "a middle drag shouldn't toggle the layer, even if released where it was pressed");
|
|
||||||
|
|
||||||
editor.handle_message(DocumentMessage::Undo).await;
|
|
||||||
assert!(is_visible(&editor), "one undo should revert the middle click");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
|||||||
use graphene_std::transform::ScaleType;
|
use graphene_std::transform::ScaleType;
|
||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::uuid::NodeId;
|
||||||
use graphene_std::vector::graphic_types;
|
use graphene_std::vector::graphic_types;
|
||||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::f64::consts::PI;
|
use std::f64::consts::PI;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
@@ -121,10 +121,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_std::raster::SampleImageNode",
|
"graphene_std::raster::SampleImageNode",
|
||||||
"graphene_std::raster::SampleNode",
|
"graphene_std::raster::SampleNode",
|
||||||
"raster_nodes::std_nodes::SampleImageNode",
|
"raster_nodes::std_nodes::SampleImageNode",
|
||||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
|
||||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
|
||||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
|
||||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
@@ -185,6 +181,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphic_nodes::graphic::ExtractElementNode",
|
"graphic_nodes::graphic::ExtractElementNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
|
||||||
|
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
||||||
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
||||||
@@ -301,6 +301,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||||
|
aliases: &["math_nodes::GradientTypeNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||||
aliases: &["math_nodes::SpreadMethodNode"],
|
aliases: &["math_nodes::SpreadMethodNode"],
|
||||||
@@ -549,13 +553,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
|
||||||
},
|
|
||||||
NodeReplacement {
|
|
||||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
|
||||||
aliases: &[
|
aliases: &[
|
||||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
|
||||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_std::raster::CombineChannelsNode",
|
"graphene_std::raster::CombineChannelsNode",
|
||||||
@@ -573,6 +572,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_core::raster::ExposureNode",
|
"graphene_core::raster::ExposureNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||||
|
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||||
@@ -1569,13 +1572,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||||
let split_wrapper_replacements = [
|
let split_wrapper_replacements = [
|
||||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||||
];
|
];
|
||||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -1621,7 +1624,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||||
@@ -1640,7 +1643,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
if EXTRACT_XY.contains(&name) {
|
if EXTRACT_XY.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -1686,52 +1689,6 @@ 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.
|
// "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.
|
// 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";
|
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||||
@@ -2537,18 +2494,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
document.network_interface.replace_implementation(node_id, network_path, &mut 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)?;
|
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
|
// Content: no change
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
|
|
||||||
@@ -2692,11 +2637,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 7;
|
inputs_count = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
|
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
|
||||||
// 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.
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
|
||||||
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 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)?;
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
@@ -2719,36 +2661,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 7;
|
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)
|
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
@@ -3252,17 +3164,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
// Sample Image nodes, now passthroughs, drop their old title
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
|
||||||
|
|
||||||
if inputs_count > 1 {
|
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.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)?;
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||||
@@ -4212,20 +4116,6 @@ 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
|
// 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) {
|
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
||||||
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
||||||
@@ -4988,40 +4878,6 @@ 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
|
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
|
||||||
#[test]
|
#[test]
|
||||||
fn every_into_group_alias_resets_the_merge_definition() {
|
fn every_into_group_alias_resets_the_merge_definition() {
|
||||||
@@ -5584,204 +5440,6 @@ mod tests {
|
|||||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
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]
|
#[test]
|
||||||
fn test_no_duplicate_node_replacements() {
|
fn test_no_duplicate_node_replacements() {
|
||||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||||
@@ -6331,35 +5989,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
|
||||||
use glam::DAffine2;
|
|
||||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
|
||||||
|
|
||||||
let (image, extend) = (NodeId(1), NodeId(2));
|
|
||||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
|
||||||
.expect("the Image definition should exist")
|
|
||||||
.default_node_template();
|
|
||||||
let extend_template = NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
|
||||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
|
||||||
display_name: "Extend Image to Bounds".to_string(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
document.network_interface.insert_node(image, image_template, &[]);
|
|
||||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
|
||||||
|
|
||||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
|
||||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
|
||||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
|
||||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
|
||||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
|||||||
@@ -1123,10 +1123,20 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
|||||||
self.executor.submit_thumbnails_in_view(document, document_id);
|
self.executor.submit_thumbnails_in_view(document, document_id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) {
|
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||||
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id),
|
let layers = self.active_document().map(|document| {
|
||||||
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }),
|
let selected = document.partition_selection().layers;
|
||||||
},
|
let mut layers = document
|
||||||
|
.metadata()
|
||||||
|
.all_layers()
|
||||||
|
.filter(|layer| selected.contains(layer))
|
||||||
|
.map(|layer| layer.to_node())
|
||||||
|
.collect::<Vec<_>>();
|
||||||
|
layers.reverse();
|
||||||
|
layers
|
||||||
|
});
|
||||||
|
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
||||||
|
}
|
||||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||||
responses.add(MenuBarMessage::SendLayout);
|
responses.add(MenuBarMessage::SendLayout);
|
||||||
|
|||||||
@@ -217,7 +217,7 @@ impl DrawingToolState {
|
|||||||
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: graphene_std::vector::Gradient::from(&ramp),
|
gradient: graphene_std::vector::Gradient::from(&ramp),
|
||||||
gradient_form: None,
|
gradient_form: Default::default(),
|
||||||
gradient_settings: (&ramp).into(),
|
gradient_settings: (&ramp).into(),
|
||||||
transform: None,
|
transform: None,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -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
|
// 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 generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||||
let setters = [
|
let setters = [
|
||||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||||
@@ -428,17 +428,6 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
|
|||||||
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
|
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.
|
/// Get the gradient stops of a layer, if any.
|
||||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
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
|
// Try to find the gradient stops value that is created by a Fill node first
|
||||||
@@ -841,23 +830,9 @@ 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`).
|
/// 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 struct FillNodeGradient {
|
||||||
pub stops: Gradient,
|
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 gradient_form: GradientForm,
|
||||||
pub settings: GradientSettings,
|
pub settings: GradientSettings,
|
||||||
pub transform: DAffine2,
|
pub transform: DAffine2,
|
||||||
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
|||||||
};
|
};
|
||||||
let settings = GradientSettings::from(ramp);
|
let settings = GradientSettings::from(ramp);
|
||||||
let stops = Gradient::from(ramp);
|
let stops = Gradient::from(ramp);
|
||||||
let curvatures = fill_node_curvatures(fill_node);
|
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
|
||||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
Some(&TaggedValue::GradientForm(value)) => value,
|
||||||
|
_ => GradientForm::default(),
|
||||||
|
};
|
||||||
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
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_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||||
let transform = match (has_transform, transform_input) {
|
let transform = match (has_transform, transform_input) {
|
||||||
@@ -886,7 +863,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
|||||||
|
|
||||||
Some(FillNodeGradient {
|
Some(FillNodeGradient {
|
||||||
stops,
|
stops,
|
||||||
curvatures,
|
|
||||||
gradient_form,
|
gradient_form,
|
||||||
settings,
|
settings,
|
||||||
transform,
|
transform,
|
||||||
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
|||||||
use graphene_std::vector::fill;
|
use graphene_std::vector::fill;
|
||||||
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
|
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 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))) {
|
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
|
||||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||||
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
|||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: Gradient::from(ramp),
|
gradient: Gradient::from(ramp),
|
||||||
gradient_form: None,
|
gradient_form,
|
||||||
gradient_settings: ramp.into(),
|
gradient_settings: ramp.into(),
|
||||||
transform: Some(transform),
|
transform: Some(transform),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,8 +29,6 @@ pub struct GradientTool {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct GradientOptions {
|
pub struct GradientOptions {
|
||||||
gradient_form: GradientForm,
|
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,
|
settings: GradientSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,16 +92,12 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
|||||||
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
||||||
GradientOptionsUpdate::Form(gradient_form) => {
|
GradientOptionsUpdate::Form(gradient_form) => {
|
||||||
self.options.gradient_form = gradient_form;
|
self.options.gradient_form = gradient_form;
|
||||||
self.options.curvature_source = CurvatureSource::Form;
|
|
||||||
apply_gradient_update(
|
apply_gradient_update(
|
||||||
&mut self.data,
|
&mut self.data,
|
||||||
context,
|
context,
|
||||||
responses,
|
responses,
|
||||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|
||||||
|(_gradient, appearance)| {
|
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|
||||||
appearance.gradient_form = gradient_form;
|
|
||||||
appearance.curvature_source = CurvatureSource::Form;
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
responses.add(ToolMessage::UpdateHints);
|
responses.add(ToolMessage::UpdateHints);
|
||||||
responses.add(ToolMessage::UpdateCursor);
|
responses.add(ToolMessage::UpdateCursor);
|
||||||
@@ -198,19 +192,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
|||||||
|
|
||||||
let mut needs_refresh = false;
|
let mut needs_refresh = false;
|
||||||
if let Some((_gradient, appearance)) = ¤t_gradient {
|
if let Some((_gradient, appearance)) = ¤t_gradient {
|
||||||
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source {
|
if self.options.gradient_form != appearance.gradient_form {
|
||||||
self.options.gradient_form = appearance.gradient_form;
|
self.options.gradient_form = appearance.gradient_form;
|
||||||
self.options.curvature_source = appearance.curvature_source;
|
|
||||||
needs_refresh = true;
|
needs_refresh = true;
|
||||||
}
|
}
|
||||||
if self.options.settings != appearance.settings {
|
if self.options.settings != appearance.settings {
|
||||||
self.options.settings = appearance.settings;
|
self.options.settings = appearance.settings;
|
||||||
needs_refresh = true;
|
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();
|
let has_gradient = current_gradient.is_some();
|
||||||
@@ -272,11 +261,7 @@ impl LayoutHolder for GradientTool {
|
|||||||
}
|
}
|
||||||
.into()
|
.into()
|
||||||
});
|
});
|
||||||
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(Some(self.options.gradient_form as u32)).widget_instance();
|
||||||
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
|
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||||
let stops_value = self
|
let stops_value = self
|
||||||
@@ -396,12 +381,10 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
|||||||
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
|
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 = 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((
|
return Some((
|
||||||
gradient.stops,
|
gradient.stops,
|
||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
gradient_form,
|
gradient_form: gradient.gradient_form,
|
||||||
curvature_source,
|
|
||||||
settings: gradient.settings,
|
settings: gradient.settings,
|
||||||
transform: gradient.transform,
|
transform: gradient.transform,
|
||||||
},
|
},
|
||||||
@@ -421,48 +404,19 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
|||||||
struct GradientAppearance {
|
struct GradientAppearance {
|
||||||
transform: DAffine2,
|
transform: DAffine2,
|
||||||
gradient_form: GradientForm,
|
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,
|
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.
|
/// 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 {
|
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
||||||
let target_input = gradient_chain_target_input(layer, network_interface);
|
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 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 transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||||
|
|
||||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||||
let mut gradient_form: Option<GradientForm> = None;
|
let mut gradient_form: Option<GradientForm> = None;
|
||||||
let mut curvature_source = CurvatureSource::Form;
|
|
||||||
|
|
||||||
for node_id in network_interface
|
for node_id in network_interface
|
||||||
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
||||||
@@ -476,9 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
|||||||
|
|
||||||
if reference == transform_reference {
|
if reference == transform_reference {
|
||||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
} else if reference == gradient_form_reference
|
||||||
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
|
&& gradient_form.is_none()
|
||||||
(gradient_form, curvature_source) = (Some(form), source);
|
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||||
|
{
|
||||||
|
gradient_form = Some(*value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -488,7 +444,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
|||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
transform: composed_transform,
|
transform: composed_transform,
|
||||||
gradient_form: gradient_form.unwrap_or_default(),
|
gradient_form: gradient_form.unwrap_or_default(),
|
||||||
curvature_source,
|
|
||||||
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -838,15 +793,12 @@ impl SelectedGradient {
|
|||||||
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
||||||
if let Some(layer) = self.layer {
|
if let Some(layer) = self.layer {
|
||||||
if self.is_gradient_chain {
|
if self.is_gradient_chain {
|
||||||
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected
|
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
|
||||||
let write_form = self.dragging == GradientDragTarget::New;
|
|
||||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
|
|
||||||
} else {
|
} else {
|
||||||
// Only a new gradient takes its form from the tool, as with a chain
|
|
||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: self.gradient.clone(),
|
gradient: self.gradient.clone(),
|
||||||
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
|
gradient_form: self.appearance.gradient_form,
|
||||||
gradient_settings: self.appearance.settings,
|
gradient_settings: self.appearance.settings,
|
||||||
transform: Some(self.appearance.transform),
|
transform: Some(self.appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -877,8 +829,8 @@ impl SelectedGradient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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.
|
/// 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, write_form: bool, responses: &mut VecDeque<Message>) {
|
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||||
responses.add(GraphOperationMessage::GradientCyclicSet {
|
responses.add(GraphOperationMessage::GradientCyclicSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_cyclic: appearance.settings.cyclic,
|
gradient_cyclic: appearance.settings.cyclic,
|
||||||
@@ -896,12 +848,10 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
|
|||||||
layer,
|
layer,
|
||||||
transform: appearance.transform,
|
transform: appearance.transform,
|
||||||
});
|
});
|
||||||
if write_form && appearance.curvature_source == CurvatureSource::Form {
|
|
||||||
responses.add(GraphOperationMessage::GradientFormSet {
|
responses.add(GraphOperationMessage::GradientFormSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_form: appearance.gradient_form,
|
gradient_form: appearance.gradient_form,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
responses.add(GraphOperationMessage::GradientSpreadSet {
|
responses.add(GraphOperationMessage::GradientSpreadSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_spread: appearance.settings.spread,
|
gradient_spread: appearance.settings.spread,
|
||||||
@@ -1572,7 +1522,6 @@ impl Fsm for GradientToolFsmState {
|
|||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
gradient_form: tool_options.gradient_form,
|
gradient_form: tool_options.gradient_form,
|
||||||
curvature_source: CurvatureSource::Form,
|
|
||||||
settings: tool_options.settings,
|
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
|
// 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
|
||||||
@@ -1991,13 +1940,12 @@ 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
|
// 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() {
|
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
|
||||||
// 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, responses);
|
||||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
|
|
||||||
} else {
|
} else {
|
||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient,
|
gradient,
|
||||||
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
|
gradient_form: appearance.gradient_form,
|
||||||
gradient_settings: appearance.settings,
|
gradient_settings: appearance.settings,
|
||||||
transform: Some(appearance.transform),
|
transform: Some(appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -2063,7 +2011,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
|||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: new_gradient.clone(),
|
gradient: new_gradient.clone(),
|
||||||
gradient_form: None,
|
gradient_form: appearance.gradient_form,
|
||||||
gradient_settings: settings,
|
gradient_settings: settings,
|
||||||
transform: Some(appearance.transform),
|
transform: Some(appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -2160,7 +2108,6 @@ mod test_gradient {
|
|||||||
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
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::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
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::graph_operation::utility_types::TransformIn;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||||
@@ -2168,8 +2115,8 @@ mod test_gradient {
|
|||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
||||||
pub use crate::test_utils::test_prelude::*;
|
pub use crate::test_utils::test_prelude::*;
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
|
use graph_craft::document::NodeInput;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{NodeId, NodeInput};
|
|
||||||
use graphene_std::NodeParameter;
|
use graphene_std::NodeParameter;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
||||||
@@ -3419,7 +3366,7 @@ mod test_gradient {
|
|||||||
.await;
|
.await;
|
||||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
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 Curvature' node onto the Fill's fill input wire.
|
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||||
editor.select_tool(ToolType::Gradient).await;
|
editor.select_tool(ToolType::Gradient).await;
|
||||||
editor
|
editor
|
||||||
@@ -3428,7 +3375,7 @@ mod test_gradient {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||||
let form_node_id = {
|
let form_node_id = {
|
||||||
let network_interface = &editor.active_document().network_interface;
|
let network_interface = &editor.active_document().network_interface;
|
||||||
network_interface
|
network_interface
|
||||||
@@ -3437,10 +3384,10 @@ mod test_gradient {
|
|||||||
.keys()
|
.keys()
|
||||||
.copied()
|
.copied()
|
||||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||||
.expect("Gradient Curvature node should have been inserted")
|
.expect("Gradient Form node should have been inserted")
|
||||||
};
|
};
|
||||||
|
|
||||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
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");
|
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||||
@@ -3585,347 +3532,6 @@ mod test_gradient {
|
|||||||
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
|
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]
|
#[tokio::test]
|
||||||
async fn drag_on_blank_layer_starts_gradient_chain() {
|
async fn drag_on_blank_layer_starts_gradient_chain() {
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation
|
|||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::{Item, List};
|
use graphene_std::list::{Item, List};
|
||||||
use graphene_std::math::quad::Quad;
|
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
@@ -115,8 +114,7 @@ pub enum NodeGraphUpdate {
|
|||||||
Observations(HashMap<ObservationKey, InspectResult>),
|
Observations(HashMap<ObservationKey, InspectResult>),
|
||||||
ClipboardSvg {
|
ClipboardSvg {
|
||||||
id: u64,
|
id: u64,
|
||||||
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered.
|
svg: Option<String>,
|
||||||
svg: Result<Option<String>, String>,
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,28 +229,13 @@ impl NodeGraphExecutor {
|
|||||||
.expect("Failed to send the context overrides");
|
.expect("Failed to send the context overrides");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Has the runtime render what the selected layers add as an SVG, which it sends back once their content is final.
|
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||||
/// The `viewport_size` is in viewport pixels.
|
if document_id.is_none() || self.node_graph_document != document_id {
|
||||||
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) {
|
return ClipboardMessage::Rendered { id, svg: None }.into();
|
||||||
let network_interface = &document.network_interface;
|
}
|
||||||
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
|
|
||||||
|
|
||||||
// Painted from the bottom up
|
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
||||||
let selected = document.partition_selection().layers;
|
Message::NoOp
|
||||||
let mut layers: Vec<_> = document.metadata().all_layers().filter(|layer| selected.contains(layer)).map(|layer| layer.to_node()).collect();
|
|
||||||
layers.reverse();
|
|
||||||
|
|
||||||
// The network as it is now, since the runtime applies a graph update sent before this one only after it reads this
|
|
||||||
let request = ClipboardSvgRequest {
|
|
||||||
id,
|
|
||||||
network: network_interface.document_network().clone(),
|
|
||||||
resources: document.resources.registry.clone(),
|
|
||||||
previewed: network_interface.previewed_nodes(),
|
|
||||||
layer_paths: network_interface.layer_paths(),
|
|
||||||
layers,
|
|
||||||
view,
|
|
||||||
};
|
|
||||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg(request)).expect("Failed to send runtime request");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||||
@@ -452,7 +435,28 @@ impl NodeGraphExecutor {
|
|||||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||||
}
|
}
|
||||||
.ok_or_else(|| "No bounding box".to_string())?;
|
.ok_or_else(|| "No bounding box".to_string())?;
|
||||||
let render_config = export_render_config(bounds, export_config.scale_factor, export_format);
|
|
||||||
|
let resolution_in_document_space = bounds[1] - bounds[0];
|
||||||
|
let export_resolution = resolution_in_document_space * export_config.scale_factor;
|
||||||
|
let resolution = export_resolution.round().as_uvec2();
|
||||||
|
let transform = DAffine2::from_translation(bounds[0]).inverse();
|
||||||
|
let viewport = Footprint {
|
||||||
|
resolution,
|
||||||
|
transform,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
let render_config = RenderConfig {
|
||||||
|
viewport,
|
||||||
|
scale: export_config.scale_factor,
|
||||||
|
time: Default::default(),
|
||||||
|
pointer: DVec2::ZERO,
|
||||||
|
export_format,
|
||||||
|
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
||||||
|
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||||
|
for_export: true,
|
||||||
|
for_eyedropper: false,
|
||||||
|
};
|
||||||
|
|
||||||
// Execute the node graph
|
// Execute the node graph
|
||||||
self.sender
|
self.sender
|
||||||
@@ -470,7 +474,7 @@ impl NodeGraphExecutor {
|
|||||||
ExecutionContext {
|
ExecutionContext {
|
||||||
export_config: Some(export_config),
|
export_config: Some(export_config),
|
||||||
document_id,
|
document_id,
|
||||||
document_to_viewport: render_config.viewport.transform,
|
document_to_viewport: viewport.transform,
|
||||||
measure_fill: None,
|
measure_fill: None,
|
||||||
},
|
},
|
||||||
));
|
));
|
||||||
@@ -1196,28 +1200,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The render of an export framed to these bounds in document space, drawn at `scale` pixels per unit.
|
|
||||||
fn export_render_config(bounds: [DVec2; 2], scale: f64, export_format: ExportFormat) -> RenderConfig {
|
|
||||||
let resolution = ((bounds[1] - bounds[0]) * scale).round().as_uvec2();
|
|
||||||
let viewport = Footprint {
|
|
||||||
resolution,
|
|
||||||
transform: DAffine2::from_translation(bounds[0]).inverse(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
RenderConfig {
|
|
||||||
viewport,
|
|
||||||
scale,
|
|
||||||
time: Default::default(),
|
|
||||||
pointer: DVec2::ZERO,
|
|
||||||
export_format,
|
|
||||||
// The viewport's render mode is only a way of viewing the artwork, which exports show as it is
|
|
||||||
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
|
||||||
for_export: true,
|
|
||||||
for_eyedropper: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||||
DialogMessage::DisplayDialogError {
|
DialogMessage::DisplayDialogError {
|
||||||
|
|||||||
@@ -17,9 +17,9 @@ use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface,
|
|||||||
use graphene_std::raster_types::Raster;
|
use graphene_std::raster_types::Raster;
|
||||||
use graphene_std::runtime::AsyncRuntime;
|
use graphene_std::runtime::AsyncRuntime;
|
||||||
use graphene_std::vector::style::RenderMode;
|
use graphene_std::vector::style::RenderMode;
|
||||||
use graphene_std::{Artboard, Context, ContextFeatures, Generations, NodeError, OwnedContextImpl, Poll};
|
use graphene_std::{Context, NodeError, Poll};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||||
use interpreted_executor::layer_paths::{export_layers, write_layer_paths};
|
use interpreted_executor::layer_paths::write_layer_paths;
|
||||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use observer::Observer;
|
use observer::Observer;
|
||||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||||
@@ -52,8 +52,6 @@ pub struct NodeRuntime {
|
|||||||
pending_export: Option<ExecutionRequest>,
|
pending_export: Option<ExecutionRequest>,
|
||||||
pending_eyedropper: Option<ExecutionRequest>,
|
pending_eyedropper: Option<ExecutionRequest>,
|
||||||
pending_thumbnails: Option<DocumentId>,
|
pending_thumbnails: Option<DocumentId>,
|
||||||
/// The latest copy's SVG, evaluated from its own network until its content is final.
|
|
||||||
pending_clipboard: Option<PendingClipboard>,
|
|
||||||
/// The network the executor last compiled successfully, with previews applied.
|
/// The network the executor last compiled successfully, with previews applied.
|
||||||
old_graph: Option<NodeNetwork>,
|
old_graph: Option<NodeNetwork>,
|
||||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
||||||
@@ -61,6 +59,7 @@ pub struct NodeRuntime {
|
|||||||
async_runtime: Option<AsyncRuntime>,
|
async_runtime: Option<AsyncRuntime>,
|
||||||
|
|
||||||
editor_api: Arc<PlatformEditorApi>,
|
editor_api: Arc<PlatformEditorApi>,
|
||||||
|
resources: ResourceRegistry,
|
||||||
node_graph_errors: GraphErrors,
|
node_graph_errors: GraphErrors,
|
||||||
node_graph_warnings: GraphErrors,
|
node_graph_warnings: GraphErrors,
|
||||||
thumbnails: Thumbnails,
|
thumbnails: Thumbnails,
|
||||||
@@ -108,37 +107,11 @@ pub enum GraphRuntimeRequest {
|
|||||||
key: ObservationKey,
|
key: ObservationKey,
|
||||||
observation: Option<Observation>,
|
observation: Option<Observation>,
|
||||||
},
|
},
|
||||||
ClipboardSvg(ClipboardSvgRequest),
|
ClipboardSvg {
|
||||||
RenderOverlays(OverlayContext),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The layers a copy renders as an SVG, with the document network as it was when they were copied.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct ClipboardSvgRequest {
|
|
||||||
pub(super) id: u64,
|
|
||||||
pub(super) network: NodeNetwork,
|
|
||||||
pub(super) resources: ResourceRegistry,
|
|
||||||
/// The node each network renders in place of its export, paired with that network's path.
|
|
||||||
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
|
|
||||||
/// Full path from the root network to every layer.
|
|
||||||
pub(super) layer_paths: Vec<Vec<NodeId>>,
|
|
||||||
/// The copied layers, in the order they're painted.
|
|
||||||
pub(super) layers: Vec<NodeId>,
|
|
||||||
/// The part of the document in view, which frames content drawn for its view.
|
|
||||||
pub(super) view: [DVec2; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A copy's SVG, held until its content is final.
|
|
||||||
struct PendingClipboard {
|
|
||||||
id: u64,
|
id: u64,
|
||||||
/// The output of the network made for the copy, which keeps its nodes compiled through a cut that removes the layers from the document's.
|
layers: Vec<NodeId>,
|
||||||
output: OutputHandle,
|
},
|
||||||
/// The compiled node giving what the copied layers add, whose bounds frame the SVG.
|
RenderOverlays(OverlayContext),
|
||||||
content: NodeId,
|
|
||||||
/// The part of the document in view when they were copied.
|
|
||||||
view: [DVec2; 2],
|
|
||||||
/// The SVG's frame, once it's known.
|
|
||||||
frame: Option<[DVec2; 2]>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -185,9 +158,9 @@ impl NodeRuntime {
|
|||||||
pending_export: None,
|
pending_export: None,
|
||||||
pending_eyedropper: None,
|
pending_eyedropper: None,
|
||||||
pending_thumbnails: None,
|
pending_thumbnails: None,
|
||||||
pending_clipboard: None,
|
|
||||||
old_graph: None,
|
old_graph: None,
|
||||||
compile_failed: false,
|
compile_failed: false,
|
||||||
|
resources: ResourceRegistry::default(),
|
||||||
async_runtime: None,
|
async_runtime: None,
|
||||||
|
|
||||||
editor_api: PlatformEditorApi {
|
editor_api: PlatformEditorApi {
|
||||||
@@ -224,7 +197,6 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut graph = None;
|
let mut graph = None;
|
||||||
let mut clipboard = None;
|
|
||||||
for request in self.receiver.try_iter() {
|
for request in self.receiver.try_iter() {
|
||||||
match request {
|
match request {
|
||||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||||
@@ -251,8 +223,10 @@ impl NodeRuntime {
|
|||||||
self.observations_changed = true;
|
self.observations_changed = true;
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
// The clipboard waits only for its latest copy
|
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
|
||||||
GraphRuntimeRequest::ClipboardSvg(request) => clipboard = Some(request),
|
let svg = self.old_graph.as_ref().and_then(|network| thumbnails::layers_svg(&layers, network, &self.executor));
|
||||||
|
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
||||||
|
}
|
||||||
GraphRuntimeRequest::RenderOverlays(context) => {
|
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||||
self.overlays = Some(context);
|
self.overlays = Some(context);
|
||||||
self.overlays_stale = true;
|
self.overlays_stale = true;
|
||||||
@@ -260,11 +234,6 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Compiled before a graph update that cuts the copied layers lets their nodes go
|
|
||||||
if let Some(request) = clipboard {
|
|
||||||
self.compile_clipboard_svg(request);
|
|
||||||
}
|
|
||||||
|
|
||||||
let Some(GraphUpdate {
|
let Some(GraphUpdate {
|
||||||
mut network,
|
mut network,
|
||||||
resources,
|
resources,
|
||||||
@@ -279,8 +248,11 @@ impl NodeRuntime {
|
|||||||
apply_previews(&mut network, &previewed);
|
apply_previews(&mut network, &previewed);
|
||||||
write_layer_paths(&mut network, &layers);
|
write_layer_paths(&mut network, &layers);
|
||||||
self.observer.replace_all(observations);
|
self.observer.replace_all(observations);
|
||||||
|
self.resources = resources;
|
||||||
|
|
||||||
let result = self.update_network(network.clone(), &resources);
|
self.node_graph_errors.clear();
|
||||||
|
self.node_graph_warnings.clear();
|
||||||
|
let result = self.update_network(network.clone());
|
||||||
self.compile_failed = result.is_err();
|
self.compile_failed = result.is_err();
|
||||||
if result.is_ok() {
|
if result.is_ok() {
|
||||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||||
@@ -333,10 +305,6 @@ impl NodeRuntime {
|
|||||||
self.run_viewport(viewport).await;
|
self.run_viewport(viewport).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
if dirty && let Some(clipboard) = self.pending_clipboard.take() {
|
|
||||||
self.run_clipboard(clipboard);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||||
if self.overlays_stale {
|
if self.overlays_stale {
|
||||||
texture = self.composite_viewport_frame();
|
texture = self.composite_viewport_frame();
|
||||||
@@ -430,70 +398,6 @@ impl NodeRuntime {
|
|||||||
self.respond(request, result, observations).await;
|
self.respond(request, result, observations).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates the copy's network as an export framed to its content, sending its SVG once that's final, and otherwise keeping it to evaluate again when a task lands.
|
|
||||||
fn run_clipboard(&mut self, mut clipboard: PendingClipboard) {
|
|
||||||
let generations = self.async_runtime().snapshot();
|
|
||||||
|
|
||||||
let frame = match clipboard.frame {
|
|
||||||
Some(frame) => frame,
|
|
||||||
None => {
|
|
||||||
let Some(frame) = self.clipboard_frame(&clipboard, &generations) else {
|
|
||||||
self.pending_clipboard = Some(clipboard);
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
match frame {
|
|
||||||
Ok(Some(frame)) => *clipboard.frame.insert(frame),
|
|
||||||
Ok(None) => return self.send_clipboard_svg(clipboard.id, Ok(None)),
|
|
||||||
Err(message) => return self.send_clipboard_svg(clipboard.id, Err(message)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The render covers whole pixels, rounded outward, while the SVG's frame keeps the content's exact size
|
|
||||||
let size = frame[1] - frame[0];
|
|
||||||
let covered = size.ceil();
|
|
||||||
let context = export_render_config([frame[0], frame[0] + covered], 1., ExportFormat::Svg).into_context_with_generations(generations);
|
|
||||||
match self.settled(clipboard.output.node(), || self.executor.execute(&clipboard.output, context).map_err(|error| error.to_string())) {
|
|
||||||
Some(output) => self.send_clipboard_svg(clipboard.id, output.and_then(svg_text).map(|svg| svg.map(|svg| with_frame_size(svg, covered, size)))),
|
|
||||||
None => self.pending_clipboard = Some(clipboard),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The frame of the copy's SVG once it's known, unless it has no area.
|
|
||||||
/// Content drawn for its view is framed to the view it was copied in, while other content is framed to its bounds, which are the same in any view.
|
|
||||||
fn clipboard_frame(&self, clipboard: &PendingClipboard, generations: &Generations) -> Option<Result<Option<[DVec2; 2]>, String>> {
|
|
||||||
let has_area = |[min, max]: &[DVec2; 2]| (*max - *min).cmpgt(DVec2::ZERO).all();
|
|
||||||
|
|
||||||
if self.executor.tree().context_features(clipboard.content).contains(ContextFeatures::FOOTPRINT) {
|
|
||||||
return Some(Ok(Some(clipboard.view).filter(has_area)));
|
|
||||||
}
|
|
||||||
|
|
||||||
let context = OwnedContextImpl::default()
|
|
||||||
.with_footprint(export_render_config(clipboard.view, 1., ExportFormat::Svg).viewport)
|
|
||||||
.with_real_time(0.)
|
|
||||||
.with_animation_time(0.)
|
|
||||||
.with_generations(generations.clone())
|
|
||||||
.into_context();
|
|
||||||
let content = self.settled(clipboard.content, || self.executor.tree().evaluate(clipboard.content, &context).map_err(|error| error.to_string()))?;
|
|
||||||
Some(content.map(|content| exported_bounds(content).filter(has_area)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value an evaluation of the node gives once it's final, `None` while it's pending or partial, or else what went wrong.
|
|
||||||
fn settled<T>(&self, node: NodeId, evaluate: impl FnOnce() -> Result<Poll<T>, String>) -> Option<Result<T, String>> {
|
|
||||||
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(evaluate)).unwrap_or_else(|payload| {
|
|
||||||
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
|
||||||
Err(format!("Panicked: {}", message.unwrap_or("no message")))
|
|
||||||
});
|
|
||||||
|
|
||||||
match result {
|
|
||||||
Ok(Poll::Pending | Poll::Partial(_)) => None,
|
|
||||||
Ok(Poll::Final(value)) => Some(Ok(value)),
|
|
||||||
Ok(Poll::Fallback(boxed)) => Some(Ok(boxed.0)),
|
|
||||||
Ok(Poll::Error(error)) => Some(Err(self.resolve_errors(node, &error).to_string())),
|
|
||||||
Err(message) => Some(Err(message)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||||
if let Some(viewport) = self.pending {
|
if let Some(viewport) = self.pending {
|
||||||
@@ -532,9 +436,9 @@ impl NodeRuntime {
|
|||||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||||
let (value, error) = *boxed;
|
let (value, error) = *boxed;
|
||||||
ExecutionResult::Fallback(value, self.resolve_errors(self.output.node(), &error))
|
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||||
}
|
}
|
||||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(self.output.node(), &error)),
|
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
||||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||||
Err(payload) => {
|
Err(payload) => {
|
||||||
let response = ExecutionResponse {
|
let response = ExecutionResponse {
|
||||||
@@ -602,121 +506,42 @@ impl NodeRuntime {
|
|||||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_network(&mut self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||||
self.node_graph_errors.clear();
|
|
||||||
self.node_graph_warnings.clear();
|
|
||||||
|
|
||||||
let CompiledNetwork { network: proto_network, warnings } = match self.compile_network(graph, resources) {
|
|
||||||
Ok(compiled_network) => compiled_network,
|
|
||||||
Err((message, errors)) => {
|
|
||||||
self.node_graph_errors = errors;
|
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
self.node_graph_warnings = warnings;
|
|
||||||
|
|
||||||
let result = match self.executor.update(proto_network) {
|
|
||||||
Ok((output, types)) => {
|
|
||||||
self.output = output;
|
|
||||||
Ok(types)
|
|
||||||
}
|
|
||||||
Err((types, errors)) => {
|
|
||||||
let message = format!("{errors:?}");
|
|
||||||
self.node_graph_errors = errors;
|
|
||||||
Err((types, message))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Every held output's sources, so the tasks they spawn bump their generations when they land
|
|
||||||
self.async_runtime().update_sources(self.executor.sources());
|
|
||||||
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Compiles the network of the copied layers beside the document's, to be evaluated until its SVG is final.
|
|
||||||
fn compile_clipboard_svg(&mut self, request: ClipboardSvgRequest) {
|
|
||||||
let ClipboardSvgRequest {
|
|
||||||
id,
|
|
||||||
mut network,
|
|
||||||
resources,
|
|
||||||
previewed,
|
|
||||||
layer_paths,
|
|
||||||
layers,
|
|
||||||
view,
|
|
||||||
} = request;
|
|
||||||
self.pending_clipboard = None;
|
|
||||||
|
|
||||||
// Made as the document's network is, so it shares the document's compiled nodes
|
|
||||||
apply_previews(&mut network, &previewed);
|
|
||||||
write_layer_paths(&mut network, &layer_paths);
|
|
||||||
let Some(content_node) = export_layers(&mut network, &layers) else {
|
|
||||||
self.send_clipboard_svg(id, Ok(None));
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
let proto_network = match self.compile_network(network, &resources) {
|
|
||||||
Ok(compiled_network) => compiled_network.network,
|
|
||||||
Err((message, _)) => {
|
|
||||||
self.send_clipboard_svg(id, Err(message));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The last of the proto nodes at the stack's path, which may wrap it, gives what the stack outputs
|
|
||||||
let content_path = Some(vec![content_node]);
|
|
||||||
let Some(&(content, _)) = proto_network.nodes.iter().rev().find(|(_, node)| node.original_location.path == content_path) else {
|
|
||||||
self.send_clipboard_svg(id, Err("The copied layers' content didn't compile".to_string()));
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
// The document's updates keep the source map, so the types they send the editor stay whole
|
|
||||||
let output = match self.executor.insert_beside(proto_network) {
|
|
||||||
Ok(output) => output,
|
|
||||||
Err(errors) => {
|
|
||||||
self.send_clipboard_svg(id, Err(format!("{errors:?}")));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
self.async_runtime().update_sources(self.executor.sources());
|
|
||||||
|
|
||||||
self.pending_clipboard = Some(PendingClipboard {
|
|
||||||
id,
|
|
||||||
output,
|
|
||||||
content,
|
|
||||||
view,
|
|
||||||
frame: None,
|
|
||||||
});
|
|
||||||
self.dirty.store(true, Ordering::Release);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send_clipboard_svg(&self, id: u64, svg: Result<Option<String>, String>) {
|
|
||||||
self.sender.send(NodeGraphUpdate::ClipboardSvg { id, svg }).expect("Failed to send response");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Wraps the network with the render node in its scope, then preprocesses and compiles it, or else gives back why it failed with the errors on its nodes.
|
|
||||||
fn compile_network(&self, graph: NodeNetwork, resources: &ResourceRegistry) -> Result<CompiledNetwork, (String, GraphErrors)> {
|
|
||||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||||
|
|
||||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)) {
|
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||||
return Err((e.to_string(), Vec::new()));
|
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
// We assume only one output
|
// We assume only one output
|
||||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||||
|
|
||||||
let c = Compiler {};
|
let c = Compiler {};
|
||||||
let compiled_network = match c.compile_single(scoped_network) {
|
let CompiledNetwork { network: proto_network, warnings } = match c.compile_single(scoped_network) {
|
||||||
Ok(compiled_network) => compiled_network,
|
Ok(compiled_network) => compiled_network,
|
||||||
Err(CompileError::Graph(errors)) => return Err((format!("{errors:?}"), errors)),
|
Err(CompileError::Graph(errors)) => {
|
||||||
Err(CompileError::Message(message)) => return Err((message, Vec::new())),
|
let message = format!("{errors:?}");
|
||||||
|
self.node_graph_errors = errors;
|
||||||
|
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
|
||||||
|
}
|
||||||
|
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||||
};
|
};
|
||||||
|
self.node_graph_warnings = warnings;
|
||||||
|
|
||||||
assert_ne!(compiled_network.network.nodes.len(), 0, "No proto nodes exist?");
|
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||||
Ok(compiled_network)
|
let updated = self.executor.update(proto_network).map(|(output, types)| {
|
||||||
|
self.output = output;
|
||||||
|
types
|
||||||
|
});
|
||||||
|
let result = updated.map_err(|(types, e)| {
|
||||||
|
self.node_graph_errors.clone_from(&e);
|
||||||
|
(types, format!("{e:?}"))
|
||||||
|
});
|
||||||
|
self.async_runtime().update_sources(self.executor.sources());
|
||||||
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The errors of an evaluation of the `output` node, each traced through the nodes it passed.
|
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
||||||
fn resolve_errors(&self, output: NodeId, error: &NodeError) -> EvaluationErrors {
|
|
||||||
let source_map = self.executor.tree().source_map();
|
let source_map = self.executor.tree().source_map();
|
||||||
let paths = |node: NodeId| -> NodePaths {
|
let paths = |node: NodeId| -> NodePaths {
|
||||||
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
||||||
@@ -724,6 +549,7 @@ impl NodeRuntime {
|
|||||||
paths.into()
|
paths.into()
|
||||||
};
|
};
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
|
let output = self.output.node();
|
||||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||||
while let Some((mut trace, node, error)) = pending.pop() {
|
while let Some((mut trace, node, error)) = pending.pop() {
|
||||||
let passed = self.executor.trace_error(node, error);
|
let passed = self.executor.trace_error(node, error);
|
||||||
@@ -754,54 +580,6 @@ impl ExecutionResult {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The area an export of the copied layers' content shows, unless it's endless, like a lone noise pattern, while a fractal's is the body a thumbnail shows.
|
|
||||||
fn exported_bounds(content: graphene_std::registry::Any) -> Option<[DVec2; 2]> {
|
|
||||||
let bounds = match content.downcast_ref::<List<Graphic>>() {
|
|
||||||
Some(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
|
|
||||||
None => artboard_clip_bounds(content.downcast_ref::<List<Artboard>>()?),
|
|
||||||
};
|
|
||||||
|
|
||||||
match bounds {
|
|
||||||
RenderBoundingBox::Rectangle([min, max]) if min.is_finite() && max.is_finite() => Some([min, max]),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The SVG with its frame narrowed from the whole pixels its render `covered` to the content's exact `size`.
|
|
||||||
fn with_frame_size(svg: String, covered: DVec2, size: DVec2) -> String {
|
|
||||||
let frame = |size: DVec2| format!(r#"viewBox="0 0 {} {}" width="{}" height="{}""#, size.x, size.y, size.x, size.y);
|
|
||||||
svg.replacen(&frame(covered), &frame(size), 1)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The union of the artboards' clipping rectangles, which frames what's visible of them better than their unclipped content does.
|
|
||||||
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
|
||||||
let mut combined: Option<[DVec2; 2]> = None;
|
|
||||||
for index in 0..artboards.len() {
|
|
||||||
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
|
||||||
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
|
||||||
let bounds = [location, location + dimensions];
|
|
||||||
combined = Some(match combined {
|
|
||||||
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
|
||||||
None => bounds,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
match combined {
|
|
||||||
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
|
||||||
None => RenderBoundingBox::None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The text of an SVG render's output.
|
|
||||||
fn svg_text(value: TaggedValue) -> Result<Option<String>, String> {
|
|
||||||
match value {
|
|
||||||
TaggedValue::RenderOutput(RenderOutput {
|
|
||||||
data: RenderOutputType::Svg { svg, .. },
|
|
||||||
..
|
|
||||||
}) => Ok(Some(svg)),
|
|
||||||
_ => Err("The render gave no SVG".to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
|
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
|
||||||
match poll {
|
match poll {
|
||||||
Poll::Final(output) | Poll::Partial(output) => Some(output),
|
Poll::Final(output) | Poll::Partial(output) => Some(output),
|
||||||
@@ -1240,232 +1018,6 @@ mod tests {
|
|||||||
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
|
assert!(!svg.contains("deferred-image"), "the markup standing in for the image should be replaced: {svg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn an_svg_export_of_a_generator_settles_once_its_image_is_read_back() {
|
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
|
||||||
use graphene_std::raster::Image;
|
|
||||||
use graphene_std::raster::color::Color;
|
|
||||||
|
|
||||||
// A Mandelbrot layer, made from an image layer by feeding the fractal into its content instead, over a rectangle framing the export
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(0., 0., 64., 64.).await;
|
|
||||||
editor.create_raster_image(Image::new(1, 1, Color::BLACK), None).await;
|
|
||||||
let layer = editor.get_selected_layer().await.expect("the pasted image should be selected").to_node();
|
|
||||||
let mandelbrot = NodeId::new();
|
|
||||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
|
||||||
node_id: Some(mandelbrot),
|
|
||||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER),
|
|
||||||
xy: None,
|
|
||||||
add_transaction: true,
|
|
||||||
});
|
|
||||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
|
||||||
output_connector: OutputConnector::primary_output(mandelbrot),
|
|
||||||
input_connector: InputConnector::node_at_index(layer, 1),
|
|
||||||
});
|
|
||||||
editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
|
||||||
|
|
||||||
// The evaluation the readback wakes draws the same placeholders again, so the image it read back fills them and the export finishes
|
|
||||||
send_export(&mut editor, FileType::Svg);
|
|
||||||
let mut saved = None;
|
|
||||||
for _ in 0..100 {
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
saved = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
|
||||||
FrontendMessage::TriggerSaveFile { content, .. } => Some(content),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
if saved.is_some() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let Some(saved) = saved else { panic!("the export never finished") };
|
|
||||||
|
|
||||||
let svg = String::from_utf8(saved.into_vec()).expect("the export should be SVG text");
|
|
||||||
assert!(
|
|
||||||
svg.contains("data:image/png;base64,") && !svg.contains("deferred-image"),
|
|
||||||
"the fractal's image should fill its placeholder: {svg}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Lets the runtime handle what's queued until the clipboard is written, giving back the SVG written with the copied layers, if any.
|
|
||||||
async fn clipboard_svg_once_written(editor: &mut EditorTestUtils, mut messages: Vec<FrontendMessage>) -> Option<String> {
|
|
||||||
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
|
||||||
|
|
||||||
for _ in 0..1000 {
|
|
||||||
let written = messages.iter().find_map(|message| match message {
|
|
||||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
if let Some(content) = written {
|
|
||||||
return content.0.iter().find_map(|item| match &item.data {
|
|
||||||
TransferData::Svg(svg) => Some(svg.clone()),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
messages = editor.dispatch(Message::Wake);
|
|
||||||
}
|
|
||||||
panic!("the clipboard was never written");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_cut_waits_through_document_updates_for_its_outstanding_tasks_then_writes_once() {
|
|
||||||
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
|
||||||
|
|
||||||
/// Runs each task at once, or holds it while `holding` until the test runs it.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct HeldTasks {
|
|
||||||
holding: AtomicBool,
|
|
||||||
held: std::sync::Mutex<Vec<Task>>,
|
|
||||||
}
|
|
||||||
impl Spawn for HeldTasks {
|
|
||||||
fn spawn(&self, task: Task) {
|
|
||||||
match self.holding.load(Ordering::Relaxed) {
|
|
||||||
true => self.held.lock().unwrap().push(task),
|
|
||||||
false => futures::executor::block_on(task),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let svgs_written = |messages: &[FrontendMessage]| -> Vec<String> {
|
|
||||||
let written = messages.iter().filter_map(|message| match message {
|
|
||||||
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
let svgs = written.flat_map(|content| &content.0).filter_map(|item| match &item.data {
|
|
||||||
TransferData::Svg(svg) => Some(svg.clone()),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
svgs.collect()
|
|
||||||
};
|
|
||||||
|
|
||||||
let tasks = Arc::new(HeldTasks::default());
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.runtime.replace_task_executor(tasks.clone(), Arc::new(|| {}));
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
|
||||||
|
|
||||||
// The traced layer's tasks are held from the start, so it's still unfinished when it's cut
|
|
||||||
tasks.holding.store(true, Ordering::Relaxed);
|
|
||||||
add_traced_noise_layer(&mut editor).await;
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
editor.dispatch(Message::Wake);
|
|
||||||
assert!(!tasks.held.lock().unwrap().is_empty(), "the layer should have tasks out");
|
|
||||||
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
|
||||||
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer] });
|
|
||||||
let mut messages = editor.dispatch(ClipboardMessage::CutLayers);
|
|
||||||
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
|
|
||||||
|
|
||||||
// Document updates after the cut leave the copy's network alone, outliving the executor's grace for orphaned nodes
|
|
||||||
for _ in 0..3 {
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
messages.extend(editor.dispatch(Message::Wake));
|
|
||||||
}
|
|
||||||
assert!(svgs_written(&messages).is_empty(), "nothing should be written while the tasks are out");
|
|
||||||
assert!(editor.runtime.pending_clipboard.is_some(), "the copy should hold its network");
|
|
||||||
|
|
||||||
// Released, the tasks land and the trace runs to its end
|
|
||||||
tasks.holding.store(false, Ordering::Relaxed);
|
|
||||||
let held = std::mem::take(&mut *tasks.held.lock().unwrap());
|
|
||||||
held.into_iter().for_each(futures::executor::block_on);
|
|
||||||
for _ in 0..1000 {
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
messages.extend(editor.dispatch(Message::Wake));
|
|
||||||
}
|
|
||||||
|
|
||||||
let svgs = svgs_written(&messages);
|
|
||||||
assert_eq!(svgs.len(), 1, "the SVG should be written once");
|
|
||||||
assert!(svgs[0].contains("<path"), "the SVG should hold the traced shapes: {}", svgs[0]);
|
|
||||||
assert!(editor.runtime.pending_clipboard.is_none(), "the copy should let its network go");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The copy's network is compiled ahead of the edit sent with it, so the edit's node is compiled before the document's update reaches it
|
|
||||||
#[tokio::test]
|
|
||||||
async fn the_types_of_an_edit_sent_with_a_copy_reach_the_editor() {
|
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
|
||||||
use graphene_std::blending_nodes::effects::drop_shadow;
|
|
||||||
|
|
||||||
let mut editor = editor().await;
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
editor.dispatch(Message::Wake);
|
|
||||||
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
|
||||||
let shadow_type = DefinitionIdentifier::ProtoNode(drop_shadow::IDENTIFIER);
|
|
||||||
editor.dispatch(NodeGraphMessage::CreateNodeInLayerWithTransaction {
|
|
||||||
node_type: shadow_type.clone(),
|
|
||||||
layer,
|
|
||||||
});
|
|
||||||
let interface = &editor.active_document().network_interface;
|
|
||||||
let shadow = interface
|
|
||||||
.document_network()
|
|
||||||
.nodes
|
|
||||||
.keys()
|
|
||||||
.copied()
|
|
||||||
.find(|node_id| interface.reference(node_id, &[]) == Some(shadow_type.clone()));
|
|
||||||
let shadow = shadow.expect("the shadow should be added");
|
|
||||||
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
|
||||||
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
|
||||||
clipboard_svg_once_written(&mut editor, messages).await.expect("the layer should render an SVG");
|
|
||||||
|
|
||||||
let types = &editor.active_document().network_interface.resolved_types.types;
|
|
||||||
assert!(types.keys().any(|path| path.first() == Some(&shadow)), "the shadow's types should reach the editor");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The edit, the copy, and the cut taking the edited layer away all reach the runtime in one queue
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_copy_renders_the_document_as_it_was_when_copied() {
|
|
||||||
use graphene_std::raster::color::Color;
|
|
||||||
|
|
||||||
let mut editor = editor().await;
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
editor.dispatch(Message::Wake);
|
|
||||||
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
|
||||||
editor.dispatch(GraphOperationMessage::FillColorSet { layer, color: Some(Color::RED) });
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
|
||||||
let mut messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
|
||||||
messages.extend(editor.dispatch(ClipboardMessage::CutLayers));
|
|
||||||
|
|
||||||
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the cut layer should render an SVG");
|
|
||||||
assert!(svg.to_lowercase().contains("#ff0000"), "the SVG should show the edited fill: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn a_copy_renders_while_another_layer_fails_to_compile() {
|
|
||||||
let mut editor = editor().await;
|
|
||||||
editor.draw_rect(200., 0., 300., 100.).await;
|
|
||||||
let copied = editor.active_document().metadata().all_layers().nth(1).expect("the first rectangle drawn").to_node();
|
|
||||||
|
|
||||||
// The top layer fails to compile
|
|
||||||
break_compile(&mut editor);
|
|
||||||
send_update(&mut editor);
|
|
||||||
editor.runtime.update();
|
|
||||||
editor.runtime.run().await;
|
|
||||||
editor.dispatch(Message::Wake);
|
|
||||||
assert!(editor.runtime.compile_failed, "the document should fail to compile");
|
|
||||||
|
|
||||||
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![copied] });
|
|
||||||
let messages = editor.dispatch(ClipboardMessage::CopyLayers);
|
|
||||||
let svg = clipboard_svg_once_written(&mut editor, messages).await.expect("the copied layer should render an SVG");
|
|
||||||
assert!(svg.contains("<path"), "the SVG should draw the rectangle: {svg}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
|
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
|
||||||
let mut editor = editor().await;
|
let mut editor = editor().await;
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
use super::{artboard_clip_bounds, evaluated_output};
|
use super::evaluated_output;
|
||||||
use crate::messages::frontend::FrontendMessage;
|
use crate::messages::frontend::FrontendMessage;
|
||||||
use atlas::ThumbnailAtlasLayout;
|
use atlas::ThumbnailAtlasLayout;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
|
|||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||||
use graphene_std::renderer::Render;
|
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::{Footprint, RenderQuality};
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
@@ -276,11 +276,11 @@ impl ThumbnailContent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The area the content covers once rendered.
|
/// The area the content covers once rendered, counting the effects drawn through maps and images only if they're `maps_resolved`, which the clipboard's SVG leaves out.
|
||||||
fn content_bounds(&self) -> RenderBoundingBox {
|
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
||||||
match self {
|
match self {
|
||||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics),
|
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
||||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||||
@@ -289,7 +289,7 @@ impl ThumbnailContent {
|
|||||||
|
|
||||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||||
fn bounds(&self) -> [DVec2; 2] {
|
fn bounds(&self) -> [DVec2; 2] {
|
||||||
let bounds = match self.content_bounds() {
|
let bounds = match self.content_bounds(true) {
|
||||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||||
_ => [DVec2::ZERO, DVec2::ONE],
|
_ => [DVec2::ZERO, DVec2::ONE],
|
||||||
};
|
};
|
||||||
@@ -297,6 +297,38 @@ impl ThumbnailContent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Renders what each of these document layers adds, painted in the given order, as one SVG framed to their combined bounds, or `None` if they render nothing.
|
||||||
|
pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<String> {
|
||||||
|
let contents: Vec<ThumbnailContent> = layers
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&layer| ThumbnailContent::evaluate(executor, thumbnail_source(&[layer], network, executor)?))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
let bounds = contents
|
||||||
|
.iter()
|
||||||
|
.filter_map(|content| match content.content_bounds(false) {
|
||||||
|
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => Some(bounds),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.reduce(|[min, max], [other_min, other_max]| [min.min(other_min), max.max(other_max)])?;
|
||||||
|
|
||||||
|
let render_params = RenderParams {
|
||||||
|
footprint: Footprint::from_bounds(bounds, RenderQuality::Full),
|
||||||
|
thumbnail: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let mut render = SvgRender::new();
|
||||||
|
for content in &contents {
|
||||||
|
content.graphic().render_svg(&mut render, &render_params);
|
||||||
|
}
|
||||||
|
if render.svg.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
render.format_svg(bounds[0], bounds[1]);
|
||||||
|
|
||||||
|
Some(render.svg.to_svg_string())
|
||||||
|
}
|
||||||
|
|
||||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||||
let source = layer_content(layer_path, network)?.source(network)?;
|
let source = layer_content(layer_path, network)?.source(network)?;
|
||||||
@@ -329,6 +361,25 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
|
||||||
|
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
|
||||||
|
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
|
||||||
|
let mut combined: Option<[DVec2; 2]> = None;
|
||||||
|
for index in 0..artboards.len() {
|
||||||
|
let location: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_LOCATION, index);
|
||||||
|
let dimensions: DVec2 = artboards.attribute_cloned_or_default(graphene_std::ATTR_DIMENSIONS, index);
|
||||||
|
let bounds = [location, location + dimensions];
|
||||||
|
combined = Some(match combined {
|
||||||
|
Some(existing) => [existing[0].min(bounds[0]), existing[1].max(bounds[1])],
|
||||||
|
None => bounds,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
match combined {
|
||||||
|
Some(bounds) => RenderBoundingBox::Rectangle(bounds),
|
||||||
|
None => RenderBoundingBox::None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
|
/// Expands an AABB outward (centered) to match the Layers panel thumbnail's 3:2 aspect ratio, padding the smaller axis
|
||||||
/// so the input's extent is always preserved.
|
/// so the input's extent is always preserved.
|
||||||
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
|
|||||||
let render_params = RenderParams {
|
let render_params = RenderParams {
|
||||||
footprint: Footprint::BOUNDLESS,
|
footprint: Footprint::BOUNDLESS,
|
||||||
render_output_type: RenderOutputType::Vello,
|
render_output_type: RenderOutputType::Vello,
|
||||||
|
thumbnail: true,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
let cell_size = layout.cell_size.as_dvec2();
|
let cell_size = layout.cell_size.as_dvec2();
|
||||||
|
|||||||
@@ -117,18 +117,11 @@ impl EditorTestUtils {
|
|||||||
panic!("Failed to evaluate graph: {e}");
|
panic!("Failed to evaluate graph: {e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// The copied layers' SVG waits for the readbacks of the GPU images it holds, each landing before a later run
|
|
||||||
let mut frontend_messages = self.dispatch(message);
|
let mut frontend_messages = self.dispatch(message);
|
||||||
for _ in 0..100 {
|
|
||||||
self.runtime.update();
|
self.runtime.update();
|
||||||
self.runtime.run().await;
|
self.runtime.run().await;
|
||||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||||
|
|
||||||
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
frontend_messages
|
frontend_messages
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|message| match message {
|
.filter_map(|message| match message {
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
import { getContext, onMount, onDestroy } from "svelte";
|
import { getContext, onMount, onDestroy } from "svelte";
|
||||||
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
import LayoutCol from "/src/components/layout/LayoutCol.svelte";
|
||||||
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
import WidgetLayout from "/src/components/widgets/WidgetLayout.svelte";
|
||||||
import { createDragToggleManager, destroyDragToggleManager } from "/src/managers/drag-toggle";
|
|
||||||
import type { DragToggleListener } from "/src/managers/drag-toggle";
|
|
||||||
import { inspectorLayout } from "/src/stores/portfolio";
|
import { inspectorLayout } from "/src/stores/portfolio";
|
||||||
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
import { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
||||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||||
@@ -25,15 +23,7 @@
|
|||||||
let lastDragClientY = 0;
|
let lastDragClientY = 0;
|
||||||
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
|
const autoScroller = createAutoScroller(() => calculateInsertIndex(lastDragClientY));
|
||||||
|
|
||||||
// Everything one middle-button drag across the section headers paints is one history step
|
|
||||||
const dragToggleListener: DragToggleListener = {
|
|
||||||
groups: ["inspector-section-visibility"],
|
|
||||||
engagedChanged: (engaged) => (engaged ? editor.startTransaction() : editor.endTransaction()),
|
|
||||||
};
|
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
createDragToggleManager(dragToggleListener);
|
|
||||||
|
|
||||||
addEventListener("pointermove", draggingPointerMove);
|
addEventListener("pointermove", draggingPointerMove);
|
||||||
addEventListener("pointerup", draggingPointerUp);
|
addEventListener("pointerup", draggingPointerUp);
|
||||||
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
|
// A drag cut short by the pointer being canceled or the window losing focus won't get the release that ends it
|
||||||
@@ -46,8 +36,6 @@
|
|||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
destroyDragToggleManager(dragToggleListener);
|
|
||||||
|
|
||||||
removeEventListener("pointermove", draggingPointerMove);
|
removeEventListener("pointermove", draggingPointerMove);
|
||||||
removeEventListener("pointerup", draggingPointerUp);
|
removeEventListener("pointerup", draggingPointerUp);
|
||||||
removeEventListener("pointercancel", abortDrag);
|
removeEventListener("pointercancel", abortDrag);
|
||||||
|
|||||||
@@ -331,7 +331,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
const dragToggleListener: DragToggleListener = {
|
const dragToggleListener: DragToggleListener = {
|
||||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
|
||||||
activeGroupChanged: (group) => {
|
activeGroupChanged: (group) => {
|
||||||
activeDragToggleGroup = group;
|
activeDragToggleGroup = group;
|
||||||
},
|
},
|
||||||
@@ -343,15 +342,6 @@
|
|||||||
editor.toggleNodeVisibilityLayerPanel(id);
|
editor.toggleNodeVisibilityLayerPanel(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Middle-clicking one of the chain's node buttons toggles that node's visibility
|
|
||||||
function chainIconsAuxClick(e: MouseEvent, listing: LayerListingInfo) {
|
|
||||||
if (e.button !== 1) return;
|
|
||||||
|
|
||||||
const chainNodeButton = e.target instanceof Element ? e.target.closest("[data-chain-node]") : undefined;
|
|
||||||
const chainNode = chainNodeButton ? listing.entry?.chainNodes[Number(chainNodeButton.getAttribute("data-chain-node"))] : undefined;
|
|
||||||
if (chainNode) toggleNodeVisibilityLayerPanel(chainNode.id);
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggleLayerLock(id: bigint) {
|
function toggleLayerLock(id: bigint) {
|
||||||
editor.toggleLayerLock(id);
|
editor.toggleLayerLock(id);
|
||||||
}
|
}
|
||||||
@@ -1204,7 +1194,6 @@
|
|||||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||||
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
||||||
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
|
|
||||||
on:pointerenter={() => hoverRow(index)}
|
on:pointerenter={() => hoverRow(index)}
|
||||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||||
>
|
>
|
||||||
@@ -1354,8 +1343,6 @@
|
|||||||
data-chain-node={slot.nodeIndex}
|
data-chain-node={slot.nodeIndex}
|
||||||
data-chain-gap-before={slot.reorderablePosition}
|
data-chain-gap-before={slot.reorderablePosition}
|
||||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
|
||||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
|
||||||
/>
|
/>
|
||||||
{/if}
|
{/if}
|
||||||
{/if}
|
{/if}
|
||||||
@@ -1372,17 +1359,12 @@
|
|||||||
: entry.chainExpanded
|
: entry.chainExpanded
|
||||||
? "Stop listing this layer's chain one node per row."
|
? "Stop listing this layer's chain one node per row."
|
||||||
: "List this layer's chain one node per row, beneath the layer."}
|
: "List this layer's chain one node per row, beneath the layer."}
|
||||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
|
||||||
data-drag-toggle-state={entry.visible ? "visible" : "hidden"}
|
|
||||||
on:click={(e) => {
|
on:click={(e) => {
|
||||||
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
||||||
if (entry.chainNodes.length === 0) return;
|
if (entry.chainNodes.length === 0) return;
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
editor.toggleLayerChainExpanded(listing.id);
|
editor.toggleLayerChainExpanded(listing.id);
|
||||||
}}
|
}}
|
||||||
on:auxclick={(e) => {
|
|
||||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
|
|
||||||
}}
|
|
||||||
>
|
>
|
||||||
<IconLabel
|
<IconLabel
|
||||||
icon={entry.iconName}
|
icon={entry.iconName}
|
||||||
@@ -1413,15 +1395,10 @@
|
|||||||
data-chain-row-node={slot.nodeIndex}
|
data-chain-row-node={slot.nodeIndex}
|
||||||
data-chain-gap-before={slot.reorderablePosition}
|
data-chain-gap-before={slot.reorderablePosition}
|
||||||
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
data-chain-gap-after={slot.reorderablePosition === undefined ? undefined : slot.reorderablePosition + 1}
|
||||||
data-middle-drag-toggle-group="layer-chain-visibility"
|
|
||||||
data-drag-toggle-state={chainNode.visible ? "visible" : "hidden"}
|
|
||||||
on:pointerdown={(e) => {
|
on:pointerdown={(e) => {
|
||||||
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
||||||
}}
|
}}
|
||||||
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||||
on:auxclick={(e) => {
|
|
||||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
|
|
||||||
}}
|
|
||||||
on:dblclick={(e) => {
|
on:dblclick={(e) => {
|
||||||
// Only the node's icon opens it in the graph
|
// Only the node's icon opens it in the graph
|
||||||
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
|
if (e.target instanceof Element && e.target.closest("[data-chain-node-row-icon]")) editor.showNodeInGraph(chainNode.id);
|
||||||
|
|||||||
@@ -41,12 +41,6 @@
|
|||||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||||
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
||||||
}
|
}
|
||||||
|
|
||||||
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
|
|
||||||
if (e.button !== 1 || widgetData.disabled) return;
|
|
||||||
|
|
||||||
editor.toggleNodeVisibilityInspector(widgetData.id);
|
|
||||||
}
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
||||||
@@ -82,16 +76,7 @@
|
|||||||
{/if}
|
{/if}
|
||||||
{/each}
|
{/each}
|
||||||
{:else}
|
{:else}
|
||||||
<button
|
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||||
class="header"
|
|
||||||
class:expanded
|
|
||||||
class:expandable
|
|
||||||
data-inspector-reorder-handle={reorderable ? "" : undefined}
|
|
||||||
data-middle-drag-toggle-group={widgetData.disabled ? undefined : "inspector-section-visibility"}
|
|
||||||
data-drag-toggle-state={widgetData.visible ? "visible" : "hidden"}
|
|
||||||
onclick={toggleExpandedWithModifiers}
|
|
||||||
onauxclick={toggleVisibilityWithMiddleClick}
|
|
||||||
>
|
|
||||||
<div
|
<div
|
||||||
class="icon-slot"
|
class="icon-slot"
|
||||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||||
@@ -558,10 +543,9 @@
|
|||||||
margin-left: 8px;
|
margin-left: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A label with no expose button before it lines up with the parameter names that follow one
|
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||||
> .text-label:first-child {
|
> .text-label:only-child {
|
||||||
margin-left: calc(20px + 8px + 8px);
|
margin-left: calc(20px + 8px + 8px);
|
||||||
--wire-indent: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
> .separator.horizontal.unrelated {
|
> .separator.horizontal.unrelated {
|
||||||
|
|||||||
@@ -8,30 +8,21 @@
|
|||||||
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
// The gesture only engages once the pointer crosses from the source into a different sibling, so plain
|
||||||
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
// clicks still toggle as usual. When engaged, the source is clicked once (toggling it) and any sibling
|
||||||
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
// the pointer enters whose state still matches the source's recorded starting state is also clicked.
|
||||||
//
|
|
||||||
// Peers toggled by the middle button declare data-middle-drag-toggle-group instead, and toggle on an `auxclick`
|
|
||||||
// rather than a click. Their gesture engages on the press, which toggles the source at once.
|
|
||||||
|
|
||||||
export type DragToggleListener = {
|
export type DragToggleListener = {
|
||||||
// The groups whose gestures this listener is told about
|
|
||||||
groups: string[];
|
|
||||||
// Given the group of the pressed button, and undefined once the press ends
|
// Given the group of the pressed button, and undefined once the press ends
|
||||||
activeGroupChanged?: (activeGroup: string | undefined) => void;
|
activeGroupChanged?: (activeGroup: string | undefined) => void;
|
||||||
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
|
// Told when the gesture engages, before any of its clicks, and again when it ends, so its clicks can form one history step
|
||||||
engagedChanged?: (engaged: boolean) => void;
|
engagedChanged?: (engaged: boolean) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
const MIDDLE_BUTTON = 1;
|
|
||||||
|
|
||||||
const listeners = new Set<DragToggleListener>();
|
const listeners = new Set<DragToggleListener>();
|
||||||
let activeGroup: string | undefined = undefined;
|
let activeGroup: string | undefined = undefined;
|
||||||
let middleButtonGesture = false;
|
|
||||||
let source: HTMLElement | undefined = undefined;
|
let source: HTMLElement | undefined = undefined;
|
||||||
let startingState: string | undefined = undefined;
|
let startingState: string | undefined = undefined;
|
||||||
let visited = new WeakSet<Element>();
|
let visited = new WeakSet<Element>();
|
||||||
let engaged = false;
|
let engaged = false;
|
||||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||||
let suppressNextAuxClick = false;
|
|
||||||
|
|
||||||
export function createDragToggleManager(listener: DragToggleListener) {
|
export function createDragToggleManager(listener: DragToggleListener) {
|
||||||
listeners.add(listener);
|
listeners.add(listener);
|
||||||
@@ -47,13 +38,12 @@ export function createDragToggleManager(listener: DragToggleListener) {
|
|||||||
window.addEventListener("blur", onPointerUp);
|
window.addEventListener("blur", onPointerUp);
|
||||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||||
window.addEventListener("click", onClickCapture, true);
|
window.addEventListener("click", onClickCapture, true);
|
||||||
window.addEventListener("auxclick", onAuxClickCapture, true);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function destroyDragToggleManager(listener: DragToggleListener) {
|
export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||||
// A consumer leaving mid-gesture still hears it end
|
// A consumer leaving mid-gesture still hears it end
|
||||||
if (engaged && activeGroup && listener.groups.includes(activeGroup)) listener.engagedChanged?.(false);
|
if (engaged) listener.engagedChanged?.(false);
|
||||||
listeners.delete(listener);
|
listeners.delete(listener);
|
||||||
|
|
||||||
// Uninstall the window event listeners only once the last consumer leaves
|
// Uninstall the window event listeners only once the last consumer leaves
|
||||||
@@ -64,120 +54,83 @@ export function destroyDragToggleManager(listener: DragToggleListener) {
|
|||||||
window.removeEventListener("pointercancel", onPointerUp);
|
window.removeEventListener("pointercancel", onPointerUp);
|
||||||
window.removeEventListener("blur", onPointerUp);
|
window.removeEventListener("blur", onPointerUp);
|
||||||
window.removeEventListener("click", onClickCapture, true);
|
window.removeEventListener("click", onClickCapture, true);
|
||||||
window.removeEventListener("auxclick", onAuxClickCapture, true);
|
|
||||||
|
|
||||||
activeGroup = undefined;
|
activeGroup = undefined;
|
||||||
middleButtonGesture = false;
|
|
||||||
source = undefined;
|
source = undefined;
|
||||||
startingState = undefined;
|
startingState = undefined;
|
||||||
visited = new WeakSet();
|
visited = new WeakSet();
|
||||||
engaged = false;
|
engaged = false;
|
||||||
suppressNextClickFromSource = undefined;
|
suppressNextClickFromSource = undefined;
|
||||||
suppressNextAuxClick = false;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function listenersOfGroup(group: string): DragToggleListener[] {
|
|
||||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
|
||||||
}
|
|
||||||
|
|
||||||
function notifyActiveGroupChange(group: string | undefined) {
|
function notifyActiveGroupChange(group: string | undefined) {
|
||||||
const previousGroup = activeGroup;
|
|
||||||
activeGroup = group;
|
activeGroup = group;
|
||||||
|
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
|
||||||
const notifiedGroup = group || previousGroup;
|
|
||||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function groupAttribute(middleButton: boolean): string {
|
function findMember(target: EventTarget | undefined): HTMLElement | undefined {
|
||||||
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
|
|
||||||
}
|
|
||||||
|
|
||||||
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
|
|
||||||
if (!(target instanceof Element)) return undefined;
|
if (!(target instanceof Element)) return undefined;
|
||||||
const found = target.closest(`[${groupAttribute(middleButton)}]`);
|
const found = target.closest("[data-drag-toggle-group]");
|
||||||
return found instanceof HTMLElement ? found : undefined;
|
return found instanceof HTMLElement ? found : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function memberState(member: HTMLElement): string | undefined {
|
|
||||||
return member.getAttribute("data-drag-toggle-state") || undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toggle(member: HTMLElement) {
|
|
||||||
if (middleButtonGesture) member.dispatchEvent(new MouseEvent("auxclick", { button: MIDDLE_BUTTON, bubbles: true }));
|
|
||||||
else member.click();
|
|
||||||
}
|
|
||||||
|
|
||||||
function engage() {
|
|
||||||
if (!activeGroup || !source) return;
|
|
||||||
|
|
||||||
engaged = true;
|
|
||||||
visited.add(source);
|
|
||||||
listenersOfGroup(activeGroup).forEach((listener) => listener.engagedChanged?.(true));
|
|
||||||
if (memberState(source) === startingState) toggle(source);
|
|
||||||
}
|
|
||||||
|
|
||||||
function onPointerDown(e: PointerEvent) {
|
function onPointerDown(e: PointerEvent) {
|
||||||
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
|
if (e.button !== 0) return;
|
||||||
suppressNextClickFromSource = undefined;
|
suppressNextClickFromSource = undefined;
|
||||||
suppressNextAuxClick = false;
|
|
||||||
|
|
||||||
const middleButton = e.button === MIDDLE_BUTTON;
|
const found = findMember(e.target || undefined);
|
||||||
const found = findMember(e.target || undefined, middleButton);
|
|
||||||
if (!found) return;
|
if (!found) return;
|
||||||
|
|
||||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||||
e.stopPropagation();
|
e.stopPropagation();
|
||||||
|
|
||||||
middleButtonGesture = middleButton;
|
|
||||||
source = found;
|
source = found;
|
||||||
startingState = memberState(found);
|
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||||
visited = new WeakSet();
|
visited = new WeakSet();
|
||||||
engaged = false;
|
engaged = false;
|
||||||
|
|
||||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||||
|
|
||||||
if (middleButton) engage();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function onPointerMove(e: PointerEvent) {
|
function onPointerMove(e: PointerEvent) {
|
||||||
if (!activeGroup || !source) return;
|
if (!activeGroup || !source) return;
|
||||||
|
|
||||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
const member = findMember(e.target || undefined);
|
||||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
if (!member || member.getAttribute("data-drag-toggle-group") !== activeGroup) return;
|
||||||
|
|
||||||
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
// Engages only when the cursor crosses from the source to a different peer, so tiny wobbles over the source don't trigger
|
||||||
if (member === source || visited.has(member)) return;
|
if (member === source || visited.has(member)) return;
|
||||||
|
|
||||||
// First crossing engages the drag and toggles the source as part of the operation
|
// First crossing engages the drag and toggles the source as part of the operation
|
||||||
if (!engaged) engage();
|
if (!engaged) {
|
||||||
|
engaged = true;
|
||||||
|
visited.add(source);
|
||||||
|
listeners.forEach((listener) => listener.engagedChanged?.(true));
|
||||||
|
if ((source.getAttribute("data-drag-toggle-state") || undefined) === startingState) source.click();
|
||||||
|
}
|
||||||
|
|
||||||
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
// Toggle only peers still in the starting state, so we don't flip ones already at the target state
|
||||||
if (memberState(member) !== startingState) return;
|
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||||
|
|
||||||
visited.add(member);
|
visited.add(member);
|
||||||
toggle(member);
|
member.click();
|
||||||
}
|
}
|
||||||
|
|
||||||
function onPointerUp(e: Event) {
|
function onPointerUp(e: Event) {
|
||||||
if (!activeGroup) return;
|
if (!activeGroup) return;
|
||||||
const endedGroup = activeGroup;
|
|
||||||
|
|
||||||
// An engaged drag already toggled the source, so its release's click won't toggle it again
|
// An engaged drag already clicked the source, so the click its release sends is suppressed rather than toggling it again
|
||||||
if (engaged && source && e.type === "pointerup") {
|
if (engaged && source && e.type === "pointerup") suppressNextClickFromSource = source;
|
||||||
if (middleButtonGesture) suppressNextAuxClick = true;
|
|
||||||
else suppressNextClickFromSource = source;
|
|
||||||
}
|
|
||||||
const wasEngaged = engaged;
|
const wasEngaged = engaged;
|
||||||
|
|
||||||
middleButtonGesture = false;
|
|
||||||
source = undefined;
|
source = undefined;
|
||||||
startingState = undefined;
|
startingState = undefined;
|
||||||
visited = new WeakSet();
|
visited = new WeakSet();
|
||||||
engaged = false;
|
engaged = false;
|
||||||
|
|
||||||
notifyActiveGroupChange(undefined);
|
notifyActiveGroupChange(undefined);
|
||||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
function onClickCapture(e: Event) {
|
function onClickCapture(e: Event) {
|
||||||
@@ -188,15 +141,6 @@ function onClickCapture(e: Event) {
|
|||||||
suppressNextClickFromSource = undefined;
|
suppressNextClickFromSource = undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unlike a click, this isn't limited to the source, since a drag's auxclick lands on the ancestor shared by its press and release
|
|
||||||
function onAuxClickCapture(e: MouseEvent) {
|
|
||||||
if (!suppressNextAuxClick || e.button !== MIDDLE_BUTTON) return;
|
|
||||||
suppressNextAuxClick = false;
|
|
||||||
|
|
||||||
e.stopPropagation();
|
|
||||||
e.preventDefault();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
|
||||||
import.meta.hot?.accept((newModule) => {
|
import.meta.hot?.accept((newModule) => {
|
||||||
const carried = Array.from(listeners);
|
const carried = Array.from(listeners);
|
||||||
|
|||||||
@@ -360,11 +360,15 @@ impl NodeNetwork {
|
|||||||
};
|
};
|
||||||
let value_node_id = gen_id();
|
let value_node_id = gen_id();
|
||||||
let merged_node_id = map_ids(id, value_node_id);
|
let merged_node_id = map_ids(id, value_node_id);
|
||||||
let original_location = OriginalLocation {
|
let mut original_location = OriginalLocation {
|
||||||
|
path: Some(path.to_vec()),
|
||||||
dependants: vec![vec![id]],
|
dependants: vec![vec![id]],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if let Some(path) = &mut original_location.path {
|
||||||
|
path.push(value_node_id);
|
||||||
|
}
|
||||||
collection.insert(
|
collection.insert(
|
||||||
merged_node_id,
|
merged_node_id,
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ fn flatten_add_expected() -> NodeNetwork {
|
|||||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||||
original_location: OriginalLocation {
|
original_location: OriginalLocation {
|
||||||
|
path: Some(vec![NodeId(4)]),
|
||||||
dependants: vec![vec![NodeId(10)]],
|
dependants: vec![vec![NodeId(10)]],
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
|||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
use graphene_application_io::resource::ResourceHash;
|
use graphene_application_io::resource::ResourceHash;
|
||||||
use graphene_application_io::resource::ResourceId;
|
use graphene_application_io::resource::ResourceId;
|
||||||
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||||
use graphic_types::vector_types::vector::style::DashPattern;
|
use graphic_types::vector_types::vector::style::DashPattern;
|
||||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||||
@@ -400,11 +400,6 @@ macro_rules! tagged_value {
|
|||||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||||
// Pixels are read back from an image, so a `Pixels` input holds the empty image
|
|
||||||
if **element == concrete!(Pixels) {
|
|
||||||
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
@@ -421,9 +416,6 @@ macro_rules! tagged_value {
|
|||||||
if **element == concrete!(Stroke) {
|
if **element == concrete!(Stroke) {
|
||||||
return Some(TaggedValue::Strokes(Vec::new()));
|
return Some(TaggedValue::Strokes(Vec::new()));
|
||||||
}
|
}
|
||||||
if **element == concrete!(Pixels) {
|
|
||||||
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
|
||||||
}
|
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
@@ -578,7 +570,6 @@ tagged_value! {
|
|||||||
StrokeAlign(vector::style::StrokeAlign),
|
StrokeAlign(vector::style::StrokeAlign),
|
||||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||||
GradientForm(vector::style::GradientForm),
|
GradientForm(vector::style::GradientForm),
|
||||||
GradientModel(vector::style::GradientModel),
|
|
||||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||||
GradientSpread(vector::style::GradientSpread),
|
GradientSpread(vector::style::GradientSpread),
|
||||||
GradientSpace(vector::style::GradientSpace),
|
GradientSpace(vector::style::GradientSpace),
|
||||||
|
|||||||
@@ -65,23 +65,17 @@ impl DynamicExecutor {
|
|||||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||||
#[cfg_attr(debug_assertions, inline(never))]
|
#[cfg_attr(debug_assertions, inline(never))]
|
||||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
let (output, add) = self.insert_nodes(proto_network, true)?;
|
let (output, add) = self.insert_nodes(proto_network)?;
|
||||||
let remove = self.free_orphaned_nodes();
|
let remove = self.free_orphaned_nodes();
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
let (output, add) = self.insert_nodes(proto_network, true)?;
|
let (output, add) = self.insert_nodes(proto_network)?;
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds the [`ProtoNetwork`] of an output held beside the one the editor shows, reusing nodes where possible.
|
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||||
/// The source map and the type deltas stay those of the networks given to [`Self::update`], so this records no document paths and frees nothing.
|
|
||||||
pub fn insert_beside(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
|
||||||
self.insert_nodes(proto_network, false).map(|(output, _)| output).map_err(|(_, errors)| errors)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork, records_paths: bool) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
|
||||||
self.typing_context.update(&proto_network).map_err(|e| {
|
self.typing_context.update(&proto_network).map_err(|e| {
|
||||||
// If there is an error then get types that have been resolved before the error
|
// If there is an error then get types that have been resolved before the error
|
||||||
let add = proto_network
|
let add = proto_network
|
||||||
@@ -104,10 +98,7 @@ impl DynamicExecutor {
|
|||||||
})?;
|
})?;
|
||||||
|
|
||||||
let output = proto_network.output;
|
let output = proto_network.output;
|
||||||
let add = self
|
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||||
.tree
|
|
||||||
.update(proto_network, &self.typing_context, records_paths)
|
|
||||||
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
|
||||||
self.outputs.retain(|output| output.strong_count() > 0);
|
self.outputs.retain(|output| output.strong_count() > 0);
|
||||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||||
let output = held.unwrap_or_else(|| {
|
let output = held.unwrap_or_else(|| {
|
||||||
@@ -301,22 +292,20 @@ impl BorrowTree {
|
|||||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||||
let mut nodes = BorrowTree::default();
|
let mut nodes = BorrowTree::default();
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
nodes.push_node(id, node, typing_context, true)?
|
nodes.push_node(id, node, typing_context)?
|
||||||
}
|
}
|
||||||
Ok(nodes)
|
Ok(nodes)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Pushes new nodes into the tree, giving back the document paths whose entries in the source map changed, if it `records_paths`.
|
/// Pushes new nodes into the tree
|
||||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext, records_paths: bool) -> Result<Vec<Path>, GraphErrors> {
|
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
|
||||||
let mut new_nodes: Vec<_> = Vec::new();
|
let mut new_nodes: Vec<_> = Vec::new();
|
||||||
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
// TODO: Problem: When a passthrough node is connected directly to an export the first input to the passthrough node is not added to the proto network, while the second input is. This means the primary input does not have a type.
|
||||||
for (id, node) in proto_network.nodes {
|
for (id, node) in proto_network.nodes {
|
||||||
if !self.nodes.contains_key(&id) {
|
if !self.nodes.contains_key(&id) {
|
||||||
if records_paths {
|
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
}
|
self.push_node(id, node, typing_context)?;
|
||||||
self.push_node(id, node, typing_context, records_paths)?;
|
} else if self.update_source_map(id, typing_context, &node) {
|
||||||
} else if records_paths && self.update_source_map(id, typing_context, &node) {
|
|
||||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -523,16 +512,14 @@ impl BorrowTree {
|
|||||||
///
|
///
|
||||||
/// # Notes
|
/// # Notes
|
||||||
///
|
///
|
||||||
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node, if it `records_path`.
|
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node.
|
||||||
/// - Handles different types of construction arguments:
|
/// - Handles different types of construction arguments:
|
||||||
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
|
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
|
||||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||||
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
|
||||||
/// - Returns an error if no constructor is found for the given node ID.
|
/// - Returns an error if no constructor is found for the given node ID.
|
||||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext, records_path: bool) -> Result<(), GraphErrors> {
|
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||||
if records_path {
|
|
||||||
self.update_source_map(id, typing_context, &proto_node);
|
self.update_source_map(id, typing_context, &proto_node);
|
||||||
}
|
|
||||||
self.context_features.insert(id, proto_node.upstream_context_features);
|
self.context_features.insert(id, proto_node.upstream_context_features);
|
||||||
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
let path = proto_node.original_location.path.clone().unwrap_or_default();
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ fn push_node_sync() {
|
|||||||
let mut tree = BorrowTree::default();
|
let mut tree = BorrowTree::default();
|
||||||
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
let val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
||||||
let context = TypingContext::default();
|
let context = TypingContext::default();
|
||||||
tree.push_node(NodeId(0), val_1_protonode, &context, true).unwrap();
|
tree.push_node(NodeId(0), val_1_protonode, &context).unwrap();
|
||||||
let _node = tree.get(NodeId(0)).unwrap();
|
let _node = tree.get(NodeId(0)).unwrap();
|
||||||
let result: Option<Item<i64>> = tree.eval(NodeId(0), &());
|
let result: Option<Item<i64>> = tree.eval(NodeId(0), &());
|
||||||
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
|
assert_eq!(result.map(|item| *item.element()), Some(2_i64));
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
||||||
|
|
||||||
use crate::node_registry::NODE_REGISTRY;
|
use crate::node_registry::NODE_REGISTRY;
|
||||||
|
use graph_craft::ProtoNodeIdentifier;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete, list};
|
use graphene_std::NodeParameter;
|
||||||
use graphene_std::graphic::{as_graphic, extend, write_layer_path};
|
use graphene_std::graphic::{extend, write_layer_path};
|
||||||
use graphene_std::list::NodeIdPath;
|
use graphene_std::list::NodeIdPath;
|
||||||
use graphene_std::{Artboard, Graphic, NodeParameter};
|
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||||
|
|
||||||
@@ -108,112 +108,6 @@ pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>])
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces the network's export with the stack of what these layers add, in the given order, giving back the root node making it, or `None` if they add nothing.
|
|
||||||
/// An artboard holds its own content, so when any of the layers adds one, only the artboards are stacked.
|
|
||||||
pub fn export_layers(network: &mut NodeNetwork, layers: &[NodeId]) -> Option<NodeId> {
|
|
||||||
// O(layers * depth)
|
|
||||||
let mut added = Vec::new();
|
|
||||||
for &layer in layers {
|
|
||||||
let Some(content) = layer_content(&[layer], network) else { continue };
|
|
||||||
let Some(source) = content.source(network) else { continue };
|
|
||||||
let artboard = outputs_artboards(source, network);
|
|
||||||
|
|
||||||
let Some(root_input) = surface_layer_content(network, layer, content) else { continue };
|
|
||||||
added.push((layer, root_input, artboard));
|
|
||||||
}
|
|
||||||
|
|
||||||
let artboards = added.iter().any(|&(_, _, artboard)| artboard);
|
|
||||||
let seed = if artboards { list!(Artboard) } else { list!(Graphic) };
|
|
||||||
|
|
||||||
let mut stack = NodeInput::type_default(seed, false);
|
|
||||||
for (layer, root_input, _) in added.into_iter().filter(|&(_, _, artboard)| artboard == artboards) {
|
|
||||||
// Extend joins lists of one type, so what other layers add is converted to graphics as the base input of 'Merge' does
|
|
||||||
let content = if artboards {
|
|
||||||
root_input
|
|
||||||
} else {
|
|
||||||
let as_graphic_id = exported_layer_node_id("as graphic", layer);
|
|
||||||
network.nodes.insert(as_graphic_id, proto_node(as_graphic::IDENTIFIER, vec![root_input]));
|
|
||||||
NodeInput::node(as_graphic_id, 0)
|
|
||||||
};
|
|
||||||
|
|
||||||
let extend_id = exported_layer_node_id("extend", layer);
|
|
||||||
network.nodes.insert(extend_id, proto_node(extend::IDENTIFIER, vec![stack, content]));
|
|
||||||
stack = NodeInput::node(extend_id, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
let stack_node = stack.as_node();
|
|
||||||
network.exports = vec![stack];
|
|
||||||
stack_node
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Makes what the layer adds an output of the layer node at the root, giving back the input that refers to it there.
|
|
||||||
fn surface_layer_content(network: &mut NodeNetwork, layer: NodeId, content: LayerContent) -> Option<NodeInput> {
|
|
||||||
let LayerContent::Added { network_path, extend } = content else {
|
|
||||||
return Some(NodeInput::node(layer, 0));
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut passed_on = network.nested_network(&network_path)?.nodes.get(&extend)?.inputs.get(extend::NewInput::INDEX)?.clone();
|
|
||||||
|
|
||||||
// Each network from the Extend node's out to the layer's gives it as an extra export, which layers made from the same network share
|
|
||||||
for depth in (1..=network_path.len()).rev() {
|
|
||||||
let holder = network_mut(network, &network_path[..depth])?;
|
|
||||||
let output_index = match holder.exports.iter().position(|export| *export == passed_on) {
|
|
||||||
Some(index) => index,
|
|
||||||
None => {
|
|
||||||
holder.exports.push(passed_on);
|
|
||||||
holder.exports.len() - 1
|
|
||||||
}
|
|
||||||
};
|
|
||||||
passed_on = NodeInput::node(network_path[depth - 1], output_index);
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(passed_on)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether every type the proto node at this path may output is an artboard type, looking through nodes that output what their first input is given.
|
|
||||||
fn outputs_artboards(mut source: Vec<NodeId>, network: &NodeNetwork) -> bool {
|
|
||||||
let is_artboard = |ty: &Type| matches!(ty.nested_type(), Type::Item(element) | Type::List(element) if **element == concrete!(Artboard));
|
|
||||||
|
|
||||||
loop {
|
|
||||||
let Some((node_id, network_path)) = source.split_last() else { return false };
|
|
||||||
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
|
|
||||||
let Some(implementations) = NODE_REGISTRY.get(identifier) else { return false };
|
|
||||||
|
|
||||||
if implementations.keys().all(|types| is_artboard(&types.return_value)) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
let passes_first_input_on = |types: &graphene_std::NodeIOTypes| types.inputs.first().is_some_and(|input| input.nested_type() == types.return_value.nested_type());
|
|
||||||
if !implementations.keys().all(passes_first_input_on) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
source = input_source;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ID of a node that `export_layers` adds at the root for the layer with this ID.
|
|
||||||
fn exported_layer_node_id(purpose: &str, layer: NodeId) -> NodeId {
|
|
||||||
let mut hasher = DefaultHasher::new();
|
|
||||||
"exported layer".hash(&mut hasher);
|
|
||||||
purpose.hash(&mut hasher);
|
|
||||||
layer.hash(&mut hasher);
|
|
||||||
NodeId(hasher.finish())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
|
||||||
DocumentNode {
|
|
||||||
inputs,
|
|
||||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How the layer path writer fares with what a proto node outputs.
|
/// How the layer path writer fares with what a proto node outputs.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
enum CarriesLayerPath {
|
enum CarriesLayerPath {
|
||||||
@@ -342,6 +236,14 @@ mod tests {
|
|||||||
assert_eq!(network, unchanged);
|
assert_eq!(network, unchanged);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
inputs,
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn definition_node(id: NetworkId) -> DocumentNode {
|
fn definition_node(id: NetworkId) -> DocumentNode {
|
||||||
DocumentNode {
|
DocumentNode {
|
||||||
implementation: DocumentNodeImplementation::Definition(id),
|
implementation: DocumentNodeImplementation::Definition(id),
|
||||||
@@ -419,110 +321,4 @@ mod tests {
|
|||||||
assert!(matches!(output_can_carry_layer_path(&identifier), CarriesLayerPath::Always), "{identifier:?} should carry a layer path");
|
assert!(matches!(output_can_carry_layer_path(&identifier), CarriesLayerPath::Always), "{identifier:?} should carry a layer path");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the exported stack's Extend nodes are given at the root, bottom up, each with whether it's converted to a graphic, and what the stack starts from.
|
|
||||||
fn exported_stack(network: &NodeNetwork) -> (Vec<(NodeInput, bool)>, NodeInput) {
|
|
||||||
let mut added = Vec::new();
|
|
||||||
let mut stack = network.exports[0].clone();
|
|
||||||
while let Some(extend_node) = stack.as_node().and_then(|node_id| network.nodes.get(&node_id)) {
|
|
||||||
assert_eq!(extend_node.implementation, DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER));
|
|
||||||
|
|
||||||
let content = &extend_node.inputs[extend::NewInput::INDEX];
|
|
||||||
let as_graphic_node = content.as_node().map(|node_id| &network.nodes[&node_id]);
|
|
||||||
added.push(match as_graphic_node {
|
|
||||||
Some(node) if node.implementation == DocumentNodeImplementation::ProtoNode(as_graphic::IDENTIFIER) => (node.inputs[0].clone(), true),
|
|
||||||
_ => (content.clone(), false),
|
|
||||||
});
|
|
||||||
|
|
||||||
stack = extend_node.inputs[extend::BaseInput::INDEX].clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
added.reverse();
|
|
||||||
(added, stack)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn exported_layers_stack_as_graphics_in_the_order_given() {
|
|
||||||
let merge = NetworkId(1);
|
|
||||||
let rectangle = || proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
|
||||||
let mut network = NodeNetwork {
|
|
||||||
exports: vec![NodeInput::node(NodeId(20), 0)],
|
|
||||||
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(merge)), (NodeId(30), rectangle())]
|
|
||||||
.into_iter()
|
|
||||||
.collect(),
|
|
||||||
definitions: [(merge, merge_like(rectangle()))].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
assert!(export_layers(&mut network, &[NodeId(20), NodeId(30), NodeId(10)]).is_some());
|
|
||||||
|
|
||||||
// The network both 'Merge' layers are made from gives what its Extend node adds as one extra export, while the plain node gives its output
|
|
||||||
assert_eq!(network.definitions[&merge].exports, vec![NodeInput::node(NodeId(1), 0), NodeInput::node(NodeId(2), 0)]);
|
|
||||||
let (added, start) = exported_stack(&network);
|
|
||||||
assert_eq!(start, NodeInput::type_default(list!(Graphic), false));
|
|
||||||
assert_eq!(
|
|
||||||
added,
|
|
||||||
[(NodeInput::node(NodeId(20), 1), true), (NodeInput::node(NodeId(30), 0), true), (NodeInput::node(NodeId(10), 1), true)]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// A layer made from a network holding a 'Merge' node passes what that node's Extend node adds out through both networks
|
|
||||||
#[test]
|
|
||||||
fn a_nested_extend_nodes_content_is_exported_through_each_network_around_it() {
|
|
||||||
let (merge, outer) = (NetworkId(1), NetworkId(2));
|
|
||||||
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
|
||||||
let outer_network = NodeNetwork {
|
|
||||||
exports: vec![NodeInput::node(NodeId(30), 0)],
|
|
||||||
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let mut network = NodeNetwork {
|
|
||||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
|
||||||
nodes: [(NodeId(10), definition_node(outer))].into_iter().collect(),
|
|
||||||
definitions: [(merge, merge_like(rectangle)), (outer, outer_network)].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
assert!(export_layers(&mut network, &[NodeId(10)]).is_some());
|
|
||||||
|
|
||||||
assert_eq!(network.definitions[&merge].exports[1], NodeInput::node(NodeId(2), 0));
|
|
||||||
assert_eq!(network.definitions[&outer].exports[1], NodeInput::node(NodeId(30), 1));
|
|
||||||
assert_eq!(exported_stack(&network).0, [(NodeInput::node(NodeId(10), 1), true)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// An artboard holds its own content, so the other layers copied with it are left out
|
|
||||||
#[test]
|
|
||||||
fn exported_artboards_leave_out_the_other_layers() {
|
|
||||||
let (merge, artboard) = (NetworkId(1), NetworkId(2));
|
|
||||||
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
|
||||||
let create_artboard = proto_node(graphene_std::artboard::create_artboard::IDENTIFIER, Vec::new());
|
|
||||||
let mut network = NodeNetwork {
|
|
||||||
exports: vec![NodeInput::node(NodeId(20), 0)],
|
|
||||||
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(artboard))].into_iter().collect(),
|
|
||||||
definitions: [(merge, merge_like(rectangle)), (artboard, merge_like(create_artboard))].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
assert!(export_layers(&mut network, &[NodeId(10), NodeId(20)]).is_some());
|
|
||||||
|
|
||||||
let (added, start) = exported_stack(&network);
|
|
||||||
assert_eq!(start, NodeInput::type_default(list!(Artboard), false));
|
|
||||||
assert_eq!(added, [(NodeInput::node(NodeId(20), 1), false)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn hidden_layers_export_nothing() {
|
|
||||||
let rectangle = DocumentNode {
|
|
||||||
visible: false,
|
|
||||||
..proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new())
|
|
||||||
};
|
|
||||||
let mut network = NodeNetwork {
|
|
||||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
|
||||||
nodes: [(NodeId(10), rectangle)].into_iter().collect(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
assert_eq!(export_layers(&mut network, &[NodeId(10)]), None);
|
|
||||||
assert_eq!(exported_stack(&network), (Vec::new(), NodeInput::type_default(list!(Graphic), false)));
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ use graphene_std::vector::misc::{
|
|||||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||||
@@ -68,6 +68,7 @@ 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<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<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<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<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<GradientSpace>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
||||||
@@ -154,14 +155,24 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
|
||||||
|
// which the new compiler selects by signature
|
||||||
|
macro_rules! also_under_own_identifier {
|
||||||
|
($module:ident, $row:expr) => {{
|
||||||
|
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
|
||||||
|
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
|
||||||
|
[row, own]
|
||||||
|
}};
|
||||||
|
}
|
||||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||||
macro_rules! input_adapter_row {
|
macro_rules! input_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||||
@@ -253,7 +264,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.extend(input_adapter_node!(element: $element));
|
entries.extend(input_adapter_node!(element: $element));
|
||||||
entries.push(item_to_list_node!(element: $element));
|
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -270,7 +281,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -359,9 +369,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||||
macro_rules! list_dyn_rows {
|
macro_rules! list_dyn_rows {
|
||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -381,6 +392,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
DVec2,
|
DVec2,
|
||||||
DAffine2,
|
DAffine2,
|
||||||
BlendMode,
|
BlendMode,
|
||||||
|
GradientForm,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -393,8 +405,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.push(bundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
|
||||||
entries.push(unbundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -440,8 +452,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||||
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
||||||
// Context nullification can wrap the read-back adapter's output
|
|
||||||
node_types.extend(cache_chain_nodes!(Pixels));
|
|
||||||
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
||||||
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
||||||
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
||||||
@@ -456,10 +466,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
||||||
macro_rules! embed_adapter_row {
|
macro_rules! embed_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -476,10 +487,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||||
macro_rules! convert_adapter_node {
|
macro_rules! convert_adapter_node {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -498,30 +510,22 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||||
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
|
|
||||||
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
|
|
||||||
macro_rules! read_back_node {
|
|
||||||
($node:ty, wire: $wire:ty) => {
|
|
||||||
async_node!(
|
|
||||||
identifier: graphene_std::read_back::INPUT_ADAPTER,
|
|
||||||
$node,
|
|
||||||
input: Context,
|
|
||||||
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
|
|
||||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
|
|
||||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||||
macro_rules! attribute_value_node {
|
macro_rules! attribute_value_node {
|
||||||
(Item<$element:ty>) => {
|
(Item<$element:ty>) => {
|
||||||
|
also_under_own_identifier!(
|
||||||
|
item_to_attribute_value,
|
||||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
(List<$element:ty>) => {
|
(List<$element:ty>) => {
|
||||||
|
also_under_own_identifier!(
|
||||||
|
list_to_attribute_value,
|
||||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
attribute_value_node!(Item<f64>),
|
attribute_value_node!(Item<f64>),
|
||||||
attribute_value_node!(Item<i64>),
|
attribute_value_node!(Item<i64>),
|
||||||
attribute_value_node!(Item<bool>),
|
attribute_value_node!(Item<bool>),
|
||||||
@@ -531,7 +535,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
attribute_value_node!(Item<Color>),
|
attribute_value_node!(Item<Color>),
|
||||||
attribute_value_node!(Item<BlendMode>),
|
attribute_value_node!(Item<BlendMode>),
|
||||||
attribute_value_node!(Item<GradientForm>),
|
attribute_value_node!(Item<GradientForm>),
|
||||||
attribute_value_node!(Item<GradientModel>),
|
|
||||||
attribute_value_node!(Item<GradientSpread>),
|
attribute_value_node!(Item<GradientSpread>),
|
||||||
attribute_value_node!(Item<GradientSpace>),
|
attribute_value_node!(Item<GradientSpace>),
|
||||||
attribute_value_node!(Item<GradientHueDirection>),
|
attribute_value_node!(Item<GradientHueDirection>),
|
||||||
@@ -547,7 +550,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
attribute_value_node!(List<Raster<GPU>>),
|
attribute_value_node!(List<Raster<GPU>>),
|
||||||
attribute_value_node!(List<Graphic>),
|
attribute_value_node!(List<Graphic>),
|
||||||
attribute_value_node!(List<Artboard>),
|
attribute_value_node!(List<Artboard>),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
node_types.extend(attribute_value_rows);
|
node_types.extend(attribute_value_rows);
|
||||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||||
macro_rules! transform_list_node {
|
macro_rules! transform_list_node {
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ pub use graphene_hash;
|
|||||||
pub use graphene_hash::CacheHash;
|
pub use graphene_hash::CacheHash;
|
||||||
pub use list::{
|
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_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
|
ATTR_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_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_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_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
ATTR_TYPE,
|
||||||
};
|
};
|
||||||
pub use memo::MemoHash;
|
pub use memo::MemoHash;
|
||||||
pub use num_traits;
|
pub use num_traits;
|
||||||
|
|||||||
@@ -59,14 +59,8 @@ 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
|
// 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`).
|
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
|
||||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||||
/// Gradient's `f64` curvature for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, it's 0.
|
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||||
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.
|
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||||
@@ -1720,7 +1714,7 @@ impl<T: CacheHash> CacheHash for List<T> {
|
|||||||
self.element.as_slice().cache_hash(state);
|
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
|
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
|
||||||
// (e.g., gradient_spread) invalidate downstream graph caches as expected
|
// (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected
|
||||||
self.attributes.cache_hash_entries(state);
|
self.attributes.cache_hash_entries(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,17 @@ pub struct NodeFlags {
|
|||||||
pub forwards_input: bool,
|
pub forwards_input: bool,
|
||||||
pub inject_scope: bool,
|
pub inject_scope: bool,
|
||||||
pub asynchronous: bool,
|
pub asynchronous: bool,
|
||||||
|
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
|
||||||
|
pub adapter: Option<AdapterKind>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an adapter node changes the wire it is inserted on.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AdapterKind {
|
||||||
|
/// Converts the wire's element into another element type.
|
||||||
|
Conversion,
|
||||||
|
/// Changes the wire's rank, like raising an `Item` onto a `List`.
|
||||||
|
Rank,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Translation struct between macro and definition
|
// Translation struct between macro and definition
|
||||||
|
|||||||
@@ -86,8 +86,6 @@ pub enum Adjustment {
|
|||||||
opacity: f64,
|
opacity: f64,
|
||||||
},
|
},
|
||||||
Solarize,
|
Solarize,
|
||||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Adjustment {
|
impl Adjustment {
|
||||||
@@ -114,17 +112,6 @@ impl Adjustment {
|
|||||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||||
Self::Solarize => EffectKind::Solarize,
|
Self::Solarize => EffectKind::Solarize,
|
||||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
|
|
||||||
pub fn may_change_alpha(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::MakeOpaque { .. } => true,
|
|
||||||
Self::Levels(settings) => !settings.alpha.is_identity(),
|
|
||||||
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
|
|
||||||
_ => false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +141,7 @@ impl Adjustment {
|
|||||||
visitor.parameter("inverse", inverse, false);
|
visitor.parameter("inverse", inverse, false);
|
||||||
}
|
}
|
||||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
Self::Invert | Self::Solarize => {}
|
||||||
Self::BrightnessContrast {
|
Self::BrightnessContrast {
|
||||||
brightness,
|
brightness,
|
||||||
contrast,
|
contrast,
|
||||||
@@ -499,20 +486,6 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl LevelsRecord {
|
impl LevelsRecord {
|
||||||
/// The record leaving every value as it is, as its node's defaults do.
|
|
||||||
pub const IDENTITY: Self = Self {
|
|
||||||
shadows: 0.,
|
|
||||||
midtones: 1.,
|
|
||||||
highlights: 100.,
|
|
||||||
output_minimums: 0.,
|
|
||||||
output_maximums: 100.,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Whether the record leaves every value as it is.
|
|
||||||
pub fn is_identity(&self) -> bool {
|
|
||||||
*self == Self::IDENTITY
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||||
|
|||||||
@@ -490,7 +490,6 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
| EffectOperation::Median { .. }
|
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use core_types::Color;
|
|||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||||
@@ -60,8 +60,6 @@ pub enum EffectKind {
|
|||||||
FindEdges,
|
FindEdges,
|
||||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||||
MinimumMaximum,
|
MinimumMaximum,
|
||||||
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
|
||||||
Median,
|
|
||||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||||
Sharpen,
|
Sharpen,
|
||||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||||
@@ -119,8 +117,6 @@ pub enum EffectKind {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for EffectKind {
|
impl std::fmt::Display for EffectKind {
|
||||||
@@ -141,7 +137,6 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::Emboss => "Emboss",
|
Self::Emboss => "Emboss",
|
||||||
Self::FindEdges => "Find Edges",
|
Self::FindEdges => "Find Edges",
|
||||||
Self::MinimumMaximum => "Minimum/Maximum",
|
Self::MinimumMaximum => "Minimum/Maximum",
|
||||||
Self::Median => "Median",
|
|
||||||
Self::Sharpen => "Sharpen",
|
Self::Sharpen => "Sharpen",
|
||||||
Self::HighPass => "High Pass",
|
Self::HighPass => "High Pass",
|
||||||
Self::Speckle => "Speckle",
|
Self::Speckle => "Speckle",
|
||||||
@@ -180,7 +175,6 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::PhotoFilter => "Photo Filter",
|
Self::PhotoFilter => "Photo Filter",
|
||||||
Self::ColorLookup => "Color Lookup",
|
Self::ColorLookup => "Color Lookup",
|
||||||
Self::Solarize => "Solarize",
|
Self::Solarize => "Solarize",
|
||||||
Self::AlphaToGray => "Alpha to Gray",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,9 +218,6 @@ pub enum MinimumMaximumMode {
|
|||||||
Maximum,
|
Maximum,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
|
||||||
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
|
||||||
|
|
||||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct EffectCapture {
|
pub struct EffectCapture {
|
||||||
@@ -240,9 +231,6 @@ impl EffectCapture {
|
|||||||
/// Not an effect's coverage but the share of each pixel within the content that its fill lets what lies beneath show through,
|
/// Not an effect's coverage but the share of each pixel within the content that its fill lets what lies beneath show through,
|
||||||
/// which the parts of interior pieces blending with what lies beneath are cut to (see [`crate::effect_layers::PiecePlace::Through`]).
|
/// which the parts of interior pieces blending with what lies beneath are cut to (see [`crate::effect_layers::PiecePlace::Through`]).
|
||||||
pub const THROUGH_MASK: Self = Self { index: usize::MAX, plane: 0 };
|
pub const THROUGH_MASK: Self = Self { index: usize::MAX, plane: 0 };
|
||||||
|
|
||||||
/// The plane of a paint overlay or outline holding its drawn paint as the GPU renders it, for an SVG that can't draw the paint whole as markup.
|
|
||||||
pub const DRAWN_PAINT_PLANE: usize = usize::MAX;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space.
|
/// The offset a shadow cast by light from `angle` (in degrees counterclockwise from the right) falls at `distance` from the content, in the document's y-down space.
|
||||||
@@ -332,10 +320,21 @@ pub fn bevel_lit(gradient: DVec2, light: DVec3) -> f64 {
|
|||||||
(-gradient).extend(1.).normalize().dot(light).clamp(0., 1.)
|
(-gradient).extend(1.).normalize().dot(light).clamp(0., 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A bevel's highlight and shadow from 0 to 1, from how much brighter its surface is lit (after its gloss contour) than a flat surface's brightness `light_z`, negative where it's darker.
|
||||||
|
/// For PSD interop, the flat brightness stays as it is under a gloss contour, so a curve that moves it shades even flat ground.
|
||||||
|
pub fn bevel_lighting(brighter: f64, light_z: f64) -> (f64, f64) {
|
||||||
|
let highlight = if light_z < 1. { brighter / (1. - light_z) } else { 0. };
|
||||||
|
let shadow = if light_z > 0. { -brighter / light_z } else { 0. };
|
||||||
|
(highlight.clamp(0., 1.), shadow.clamp(0., 1.))
|
||||||
|
}
|
||||||
|
|
||||||
/// For PSD interop, under a gloss contour or a texture a bevel's highlight and shadow beneath the content reach no more than its height before its contour divided by this,
|
/// For PSD interop, under a gloss contour or a texture a bevel's highlight and shadow beneath the content reach no more than its height before its contour divided by this,
|
||||||
/// so the flat ground they shade ends at the slopes' foot. It's the same as [`GRADIENT_GLOW_FADE`].
|
/// so the flat ground they shade ends at the slopes' foot. It's the same as [`GRADIENT_GLOW_FADE`].
|
||||||
pub const BEVEL_FOOT_FADE: f64 = 0.12;
|
pub const BEVEL_FOOT_FADE: f64 = 0.12;
|
||||||
|
|
||||||
|
/// For PSD interop, the offsets from each pixel toward its right and lower neighbors at which an antialiased contour samples it, nine in all.
|
||||||
|
pub const ANTIALIASED_CONTOUR_OFFSETS: [f64; 3] = [0., 1. / 3., 2. / 3.];
|
||||||
|
|
||||||
/// Where a bevel's height `t` (0 at the foot of its slope and 1 on its top) falls along its contour, given the `range` percentage of the slope the contour spans.
|
/// Where a bevel's height `t` (0 at the foot of its slope and 1 on its top) falls along its contour, given the `range` percentage of the slope the contour spans.
|
||||||
/// For PSD interop, an inner bevel's contour spans the range down from the top, an outer bevel's spans it up from the foot, and an emboss's spans the whole slope.
|
/// For PSD interop, an inner bevel's contour spans the range down from the top, an outer bevel's spans it up from the foot, and an emboss's spans the whole slope.
|
||||||
pub fn slope_contour_input(t: f64, style: BevelStyle, range: f64) -> f64 {
|
pub fn slope_contour_input(t: f64, style: BevelStyle, range: f64) -> f64 {
|
||||||
@@ -368,6 +367,11 @@ pub fn extended_contour(contour: &TransferCurveEvaluator, (start_slope, end_slop
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// How much a texture's color sinks a bevel's surface, from its premultiplied gamma-encoded channels: their luma, so a transparent texture leaves it flat.
|
||||||
|
pub fn texture_gray([red, green, blue, _]: [f32; 4]) -> f32 {
|
||||||
|
0.299 * red + 0.587 * green + 0.114 * blue
|
||||||
|
}
|
||||||
|
|
||||||
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
||||||
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
||||||
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||||
@@ -450,17 +454,6 @@ impl Effects {
|
|||||||
self.operations().all(|operation| operation.changes_nothing())
|
self.operations().all(|operation| operation.changes_nothing())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
|
|
||||||
pub fn may_change_alpha(&self) -> bool {
|
|
||||||
self.operations().any(|operation| {
|
|
||||||
!operation.changes_nothing()
|
|
||||||
&& match &operation {
|
|
||||||
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
|
|
||||||
_ => true,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The effects of the given range of rows decoded into operations, in order.
|
/// The effects of the given range of rows decoded into operations, in order.
|
||||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||||
@@ -482,30 +475,17 @@ impl Effects {
|
|||||||
self.operations().map(|operation| operation.required_reach()).sum()
|
self.operations().map(|operation| operation.required_reach()).sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
|
||||||
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
|
||||||
pub fn content_grid_resolution(&self) -> Option<f64> {
|
|
||||||
let grid_resolution = |operation: EffectOperation| match operation {
|
|
||||||
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
|
||||||
_ => 1.,
|
|
||||||
};
|
|
||||||
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||||
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||||
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
let mut run_changes_something = false;
|
||||||
for (index, effect) in self.effects().enumerate() {
|
for (index, effect) in self.effects().enumerate() {
|
||||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||||
let operation = effect.operation();
|
let changes_something = !effect.operation().changes_nothing();
|
||||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
|
||||||
|
|
||||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
|
||||||
if let Some((transform, rows)) = runs.last_mut()
|
if let Some((transform, rows)) = runs.last_mut()
|
||||||
&& shares_grid
|
|
||||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||||
{
|
{
|
||||||
if changes_something && !run_changes_something {
|
if changes_something && !run_changes_something {
|
||||||
@@ -513,10 +493,9 @@ impl Effects {
|
|||||||
}
|
}
|
||||||
rows.end = index + 1;
|
rows.end = index + 1;
|
||||||
run_changes_something |= changes_something;
|
run_changes_something |= changes_something;
|
||||||
run_on_content_grid |= on_content_grid;
|
|
||||||
} else {
|
} else {
|
||||||
runs.push((stamped_transform, index..index + 1));
|
runs.push((stamped_transform, index..index + 1));
|
||||||
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
run_changes_something = changes_something;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
runs
|
runs
|
||||||
@@ -856,14 +835,8 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
|||||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||||
stamp_effect_on(item.attributes_mut(), effect);
|
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||||
}
|
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||||
|
|
||||||
/// Like [`stamp_effect`], given the item's attributes.
|
|
||||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
|
||||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
|
||||||
attributes
|
|
||||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
|
||||||
.0
|
.0
|
||||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||||
}
|
}
|
||||||
@@ -1113,11 +1086,6 @@ pub enum EffectOperation {
|
|||||||
radius: f64,
|
radius: f64,
|
||||||
mode: MinimumMaximumMode,
|
mode: MinimumMaximumMode,
|
||||||
},
|
},
|
||||||
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
|
||||||
Median {
|
|
||||||
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
Sharpen {
|
Sharpen {
|
||||||
/// Percent.
|
/// Percent.
|
||||||
amount: f64,
|
amount: f64,
|
||||||
@@ -1125,7 +1093,7 @@ pub enum EffectOperation {
|
|||||||
radius: f64,
|
radius: f64,
|
||||||
/// On a scale of 0 to 255.
|
/// On a scale of 0 to 255.
|
||||||
threshold: f64,
|
threshold: f64,
|
||||||
/// Whether the content is compared against its four nearest neighbors only along edges, by how steep the content's Sobel gradient is, rather than against the blur.
|
/// Whether the content is compared against its four nearest neighbors only along edges, as [`crate::filters::edge_gain`] ramps it, rather than against the blur.
|
||||||
edges_only: bool,
|
edges_only: bool,
|
||||||
},
|
},
|
||||||
HighPass {
|
HighPass {
|
||||||
@@ -1319,7 +1287,6 @@ impl EffectOperation {
|
|||||||
Self::Emboss { .. } => EffectKind::Emboss,
|
Self::Emboss { .. } => EffectKind::Emboss,
|
||||||
Self::FindEdges => EffectKind::FindEdges,
|
Self::FindEdges => EffectKind::FindEdges,
|
||||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||||
Self::Median { .. } => EffectKind::Median,
|
|
||||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||||
Self::HighPass { .. } => EffectKind::HighPass,
|
Self::HighPass { .. } => EffectKind::HighPass,
|
||||||
Self::Speckle { .. } => EffectKind::Speckle,
|
Self::Speckle { .. } => EffectKind::Speckle,
|
||||||
@@ -1420,8 +1387,6 @@ impl EffectOperation {
|
|||||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||||
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
|
||||||
Self::Median { radius } => *radius < 1.,
|
|
||||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1448,7 +1413,7 @@ impl EffectOperation {
|
|||||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||||
Self::DropShadow { .. }
|
Self::DropShadow { .. }
|
||||||
| Self::InnerShadow { .. }
|
| Self::InnerShadow { .. }
|
||||||
@@ -1462,12 +1427,6 @@ impl EffectOperation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
|
||||||
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
|
||||||
pub fn works_on_content_grid(&self) -> bool {
|
|
||||||
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||||
pub fn painted_reach(&self) -> f64 {
|
pub fn painted_reach(&self) -> f64 {
|
||||||
let keeps_coverage = matches!(
|
let keeps_coverage = matches!(
|
||||||
@@ -1481,8 +1440,6 @@ impl EffectOperation {
|
|||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
|
||||||
| Self::Median { .. }
|
|
||||||
| Self::Sharpen { .. }
|
| Self::Sharpen { .. }
|
||||||
| Self::HighPass { .. }
|
| Self::HighPass { .. }
|
||||||
);
|
);
|
||||||
@@ -1525,7 +1482,6 @@ impl EffectOperation {
|
|||||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||||
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
|
||||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||||
@@ -1620,7 +1576,7 @@ impl EffectOperation {
|
|||||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||||
Self::Feather { distance } => finite(distance),
|
Self::Feather { distance } => finite(distance),
|
||||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||||
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||||
Self::Speckle { amount, .. } => finite(amount),
|
Self::Speckle { amount, .. } => finite(amount),
|
||||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||||
@@ -1791,7 +1747,6 @@ impl EffectOperation {
|
|||||||
radius: 0.,
|
radius: 0.,
|
||||||
mode: MinimumMaximumMode::default(),
|
mode: MinimumMaximumMode::default(),
|
||||||
},
|
},
|
||||||
EffectKind::Median => Self::Median { radius: 0. },
|
|
||||||
EffectKind::Sharpen => Self::Sharpen {
|
EffectKind::Sharpen => Self::Sharpen {
|
||||||
amount: 0.,
|
amount: 0.,
|
||||||
radius: 0.,
|
radius: 0.,
|
||||||
@@ -1920,7 +1875,6 @@ impl EffectOperation {
|
|||||||
}),
|
}),
|
||||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2134,7 +2088,6 @@ impl EffectOperation {
|
|||||||
visitor.parameter("radius", radius, 1.);
|
visitor.parameter("radius", radius, 1.);
|
||||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||||
}
|
}
|
||||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
|
||||||
Self::Sharpen {
|
Self::Sharpen {
|
||||||
amount,
|
amount,
|
||||||
radius,
|
radius,
|
||||||
@@ -2437,7 +2390,6 @@ mod tests {
|
|||||||
radius: 7.,
|
radius: 7.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
EffectOperation::Median { radius: 3.5 },
|
|
||||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 180.,
|
amount: 180.,
|
||||||
@@ -2936,7 +2888,6 @@ mod tests {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
AlphaToGray,
|
|
||||||
PaintOverlay,
|
PaintOverlay,
|
||||||
];
|
];
|
||||||
for kind in kinds {
|
for kind in kinds {
|
||||||
@@ -3036,7 +2987,6 @@ mod tests {
|
|||||||
radius: 3.,
|
radius: 3.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
EffectOperation::Median { radius: 3.5 },
|
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 100.,
|
amount: 100.,
|
||||||
radius: 3.,
|
radius: 3.,
|
||||||
@@ -3060,28 +3010,6 @@ mod tests {
|
|||||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
|
||||||
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
|
||||||
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
|
||||||
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
|
||||||
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
|
||||||
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
|
||||||
let median = |radius| EffectOperation::Median { radius };
|
|
||||||
let nothing = median(0.);
|
|
||||||
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
|
||||||
|
|
||||||
// Effects changing nothing join a median's run, but nothing else does
|
|
||||||
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
|
||||||
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
|
||||||
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
|
||||||
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the GPU and SVG each carry out.
|
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||||
|
|
||||||
use crate::effects::EffectOperation;
|
use crate::effects::{EffectOperation, Effects};
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||||
@@ -164,7 +164,6 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
| EffectOperation::Median { .. }
|
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
@@ -182,6 +181,12 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
|||||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||||
|
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||||
|
pub fn has_filters(effects: &Effects) -> bool {
|
||||||
|
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||||
|
}
|
||||||
|
|
||||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||||
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||||
(DVec2::new(-1., -1.), [-1., -1.]),
|
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||||
@@ -201,6 +206,12 @@ pub const AVERAGE_VISIBILITY_RAMP: [f32; 2] = [8. / 255., 24. / 255.];
|
|||||||
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
||||||
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||||
|
|
||||||
|
/// How much of the visible colors' average a pixel is compared against, the rest being its own color, given how much of the blur around it lands on visible pixels.
|
||||||
|
pub fn average_weight(visibility: f32) -> f32 {
|
||||||
|
let [start, end] = AVERAGE_VISIBILITY_RAMP;
|
||||||
|
((visibility - start) / (end - start)).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
||||||
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
||||||
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
||||||
@@ -209,13 +220,23 @@ pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
|||||||
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
||||||
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
||||||
|
|
||||||
|
/// For PSD interop, the Sobel gradient lengths (as Find Edges measures them, on values from 0 to 1) between which Edges Only ramps from no change to the whole of it.
|
||||||
|
/// A step between flat areas has a quarter of that length at a sixteenth of full contrast, and its whole length at a quarter.
|
||||||
|
pub const EDGE_GAIN_RAMP: [f32; 2] = [0.25, 1.];
|
||||||
|
|
||||||
|
/// For PSD interop, the share of its change that Edges Only makes in a channel whose Sobel gradient has the length `gradient`.
|
||||||
|
pub fn edge_gain(gradient: f32) -> f32 {
|
||||||
|
let [start, end] = EDGE_GAIN_RAMP;
|
||||||
|
((gradient - start) / (end - start)).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
/// What unsharp masking or a high pass compares each pixel against.
|
/// What unsharp masking or a high pass compares each pixel against.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
pub enum UnsharpBlur {
|
pub enum UnsharpBlur {
|
||||||
/// A Gaussian blur with this standard deviation in document pixels.
|
/// A Gaussian blur with this standard deviation in document pixels.
|
||||||
Gaussian(f64),
|
Gaussian(f64),
|
||||||
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
||||||
/// Each channel is moved only part of the way toward it, by how steep its Sobel gradient is, so it changes only along edges.
|
/// Each channel is moved only part of the way toward it, by its [`edge_gain`], so it changes only along edges.
|
||||||
EdgeNeighbors,
|
EdgeNeighbors,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -350,6 +371,24 @@ impl FieldSampling {
|
|||||||
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The cell under the point `offset` pixels from the middle of the pixel at `pixel` (its column and row).
|
||||||
|
fn cell_at(&self, pixel: [usize; 2], offset: DVec2) -> IVec2 {
|
||||||
|
let position = DVec2::new(pixel[0] as f64, pixel[1] as f64) + 0.5 + offset;
|
||||||
|
self.origin_cell.wrapping_add((self.origin_fraction + self.pixel_axes * position).floor().as_ivec2())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cell under the middle of the pixel at `pixel`.
|
||||||
|
pub fn center_cell(&self, pixel: [usize; 2]) -> IVec2 {
|
||||||
|
self.cell_at(pixel, DVec2::ZERO)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The cells the pixel at `pixel` samples, row by row.
|
||||||
|
pub fn sample_cells(&self, pixel: [usize; 2]) -> impl Iterator<Item = IVec2> + '_ {
|
||||||
|
let place = |index: u32, count: u32, spread: f64| ((index as f64 + 0.5) / count as f64 - 0.5) * spread;
|
||||||
|
(0..self.counts.y)
|
||||||
|
.flat_map(move |row| (0..self.counts.x).map(move |column| self.cell_at(pixel, DVec2::new(place(column, self.counts.x, self.spreads.x), place(row, self.counts.y, self.spreads.y)))))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
//! Procedural patterns described by their settings, rendered by the GPU at whatever resolution is needed of whatever part is seen, and sampled at points by the `raster-kernels` crate.
|
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||||
|
|
||||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
|
|||||||
@@ -9,17 +9,13 @@ use core_types::math::quad::Quad;
|
|||||||
use core_types::none;
|
use core_types::none;
|
||||||
use core_types::ops::FromAnchorPosition;
|
use core_types::ops::FromAnchorPosition;
|
||||||
use core_types::transform::Transform;
|
use core_types::transform::Transform;
|
||||||
use core_types::{
|
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
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 dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use raster_types::{CPU, GPU, Raster};
|
use raster_types::{CPU, GPU, Raster};
|
||||||
pub use vector_types::Vector;
|
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::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||||
use vector_types::{Gradient, GradientModel, GradientSpread};
|
use vector_types::{Gradient, 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.
|
/// 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)]
|
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||||
@@ -630,17 +626,16 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
|
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||||
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
|
||||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||||
match self {
|
match self {
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => {
|
||||||
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
|
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||||
}
|
}
|
||||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
|
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||||
}),
|
}),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
@@ -649,22 +644,16 @@ impl Graphic {
|
|||||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => false,
|
Graphic::None(_) | Graphic::NoneList(_) => false,
|
||||||
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
|
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
|
||||||
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
|
||||||
Graphic::GraphicList(list) => {
|
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
||||||
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
|
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
||||||
}
|
|
||||||
Graphic::Vector(item) => {
|
|
||||||
!item_effects_may_change_alpha(item)
|
|
||||||
&& vector_is_guaranteed_fully_opaque(
|
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
)
|
),
|
||||||
}
|
|
||||||
Graphic::VectorList(list) => {
|
Graphic::VectorList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
&& !list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
vector_is_guaranteed_fully_opaque(
|
vector_is_guaranteed_fully_opaque(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
@@ -676,23 +665,19 @@ impl Graphic {
|
|||||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||||
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
|
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_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.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, and curved contours may leave gaps, leaving the rest of the region unpainted
|
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||||
Graphic::Gradient(item) => {
|
Graphic::Gradient(item) => {
|
||||||
item_opacity_is_full(item)
|
item_opacity_is_full(item)
|
||||||
&& !item_effects_may_change_alpha(item)
|
|
||||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
&& 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())
|
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||||
}
|
}
|
||||||
Graphic::GradientList(list) => {
|
Graphic::GradientList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
&& every_item_has_full_opacity(list)
|
&& every_item_has_full_opacity(list)
|
||||||
&& !list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
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()))
|
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -702,41 +687,27 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
||||||
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
|
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
|
||||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
|
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
|
||||||
item_opacity_is_zero(item)
|
|
||||||
|| (!item_effects_may_change_alpha(item)
|
|
||||||
&& vector_is_guaranteed_fully_transparent(
|
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS),
|
),
|
||||||
))
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
}
|
|
||||||
Graphic::VectorList(list) => {
|
|
||||||
every_item_has_zero_opacity(list)
|
|
||||||
|| (!list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
|
||||||
vector_is_guaranteed_fully_transparent(
|
vector_is_guaranteed_fully_transparent(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
|
||||||
)
|
)
|
||||||
}))
|
}),
|
||||||
}
|
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
||||||
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
|
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
|
||||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
|
||||||
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
||||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||||
Graphic::GradientList(list) => {
|
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
|
||||||
every_item_has_zero_opacity(list)
|
|
||||||
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
|
|
||||||
}
|
|
||||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||||
@@ -829,13 +800,12 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
||||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
|
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
|
||||||
if opacity <= f64::EPSILON {
|
if opacity <= f64::EPSILON {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
|
let fills_invisible = opacity_fill <= f64::EPSILON
|
||||||
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|
|
||||||
|| appearance.is_none_or(|appearance| {
|
|| appearance.is_none_or(|appearance| {
|
||||||
appearance
|
appearance
|
||||||
.covers_with_paints()
|
.covers_with_paints()
|
||||||
@@ -853,16 +823,6 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
|||||||
fills_invisible && strokes_invisible
|
fills_invisible && strokes_invisible
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
|
|
||||||
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
|
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
|
|
||||||
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
|
|
||||||
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
||||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
||||||
@@ -883,21 +843,6 @@ 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)
|
(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.
|
/// 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.
|
/// 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]> {
|
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
|
||||||
@@ -1342,64 +1287,4 @@ mod graphic_is_opaque_tests {
|
|||||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||||
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
|
|
||||||
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
|
||||||
use crate::effects::EffectOperation;
|
|
||||||
use crate::vector_types::vector::style::Stroke;
|
|
||||||
|
|
||||||
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
|
|
||||||
let colors = |alpha: f64, operation: EffectOperation| {
|
|
||||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
|
||||||
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
|
|
||||||
};
|
|
||||||
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
|
||||||
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
|
|
||||||
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
|
|
||||||
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
|
||||||
composite: record,
|
|
||||||
red: LevelsRecord::IDENTITY,
|
|
||||||
green: LevelsRecord::IDENTITY,
|
|
||||||
blue: LevelsRecord::IDENTITY,
|
|
||||||
alpha,
|
|
||||||
})))
|
|
||||||
};
|
|
||||||
let identity = LevelsRecord::IDENTITY;
|
|
||||||
let darkened = LevelsRecord { output_maximums: 50., ..identity };
|
|
||||||
|
|
||||||
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
|
|
||||||
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
|
|
||||||
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
|
|
||||||
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
|
|
||||||
|
|
||||||
// Effects that might fade a paint, or show a transparent one, leave it unknown
|
|
||||||
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
|
|
||||||
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
|
|
||||||
|
|
||||||
// A group's own effects act on all it wraps, though its zero opacity still hides it
|
|
||||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
|
|
||||||
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
|
|
||||||
|
|
||||||
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
|
|
||||||
let mut shape = Item::new_from_element(Vector::default());
|
|
||||||
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
|
|
||||||
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
|
|
||||||
let shadowed = shape
|
|
||||||
.clone()
|
|
||||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
|
|
||||||
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
|
|
||||||
|
|
||||||
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
|
|
||||||
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
|
|
||||||
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
|
|
||||||
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
|
|
||||||
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
|
|
||||||
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
|
|
||||||
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
|
|
||||||
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
|||||||
pub use blend_if::BlendIfChannel;
|
pub use blend_if::BlendIfChannel;
|
||||||
pub use effects::{
|
pub use effects::{
|
||||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||||
stamp_effect, stamp_effect_on, stamped_transform,
|
stamp_effect, stamped_transform,
|
||||||
};
|
};
|
||||||
pub use filters::NoiseDistribution;
|
pub use filters::NoiseDistribution;
|
||||||
pub use generator::Generator;
|
pub use generator::Generator;
|
||||||
|
|||||||
@@ -65,9 +65,12 @@ pub fn mask_feather_sigma(feather: f64) -> f64 {
|
|||||||
feather.max(0.)
|
feather.max(0.)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The alpha at or below which a feather counts content as absent, half an 8-bit level, so the faint tail of a blur doesn't count as content, though an 8-bit image's faintest alpha does.
|
||||||
|
pub const FEATHER_FOOTPRINT_ALPHA: f32 = 0.5 / 255.;
|
||||||
|
|
||||||
/// How far a feather of `distance` erodes the content's footprint, and the standard deviation of the Gaussian softening the eroded footprint, in the same units.
|
/// How far a feather of `distance` erodes the content's footprint, and the standard deviation of the Gaussian softening the eroded footprint, in the same units.
|
||||||
///
|
///
|
||||||
/// A feather multiplies the content by a strength made this way. The footprint is where the content's alpha exceeds half an 8-bit level, so the faint tail of a blur doesn't count as content, though an 8-bit image's faintest alpha does.
|
/// A feather multiplies the content by a strength made this way. The footprint is where the content's alpha exceeds [`FEATHER_FOOTPRINT_ALPHA`].
|
||||||
/// Its edge falls within the pixels bordering the absent area by their alpha relative to the largest beside them, so translucent content places it as opaque content does.
|
/// Its edge falls within the pixels bordering the absent area by their alpha relative to the largest beside them, so translucent content places it as opaque content does.
|
||||||
/// It is eroded by half the distance, measured in straight lines, then blurred by a Gaussian reaching three standard deviations, which end at the footprint's edge.
|
/// It is eroded by half the distance, measured in straight lines, then blurred by a Gaussian reaching three standard deviations, which end at the footprint's edge.
|
||||||
/// Across a straight edge, the strength rises along the normal distribution's cumulative curve from nothing at the edge, through half at half the distance, to full at the distance. Parts thinner than the distance fade away entirely.
|
/// Across a straight edge, the strength rises along the normal distribution's cumulative curve from nothing at the edge, through half at half the distance, to full at the distance. Parts thinner than the distance fade away entirely.
|
||||||
@@ -103,6 +106,11 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
|
|||||||
std::iter::once(0.).chain(blurred).collect()
|
std::iter::once(0.).chain(blurred).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
|
||||||
|
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
|
||||||
|
(mask_coverage(channels, MaskMode::LuminanceSvg) * 255.).round() as u8
|
||||||
|
}
|
||||||
|
|
||||||
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
||||||
///
|
///
|
||||||
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
||||||
|
|||||||
@@ -1302,6 +1302,12 @@ pub fn source_within_frame(edge_mode: GradientSpread, source: DVec2, size: DVec2
|
|||||||
/// The most pixels a pixelation tests one by one for one of its cells or dots, past which it sums each row's run of them at once, so a vast cell at a deep zoom stays affordable.
|
/// The most pixels a pixelation tests one by one for one of its cells or dots, past which it sums each row's run of them at once, so a vast cell at a deep zoom stays affordable.
|
||||||
pub const MAX_AVERAGED_PIXELS: f64 = 65_536.;
|
pub const MAX_AVERAGED_PIXELS: f64 = 65_536.;
|
||||||
|
|
||||||
|
/// How many pixels from the image's origin a pixelation's averaging scans at most along each axis, past which single-precision pixel centers aren't exact, so a vast cell or dot ends its scan there.
|
||||||
|
pub const MAX_AVERAGED_PIXEL_COORDINATE: f64 = 16_777_216.;
|
||||||
|
|
||||||
|
/// How many rows past the image's top and bottom a pixelation counts for a cell or dot one by one, past which each it counts stands for those beside it, since they hold only transparency.
|
||||||
|
pub const MAX_COUNTED_ROWS: f64 = 4096.;
|
||||||
|
|
||||||
/// For PSD interop, the area of a disc of `radius` clipped to the square cell `side` across that it's centered in.
|
/// For PSD interop, the area of a disc of `radius` clipped to the square cell `side` across that it's centered in.
|
||||||
pub fn disc_in_cell_area(radius: f64, side: f64) -> f64 {
|
pub fn disc_in_cell_area(radius: f64, side: f64) -> f64 {
|
||||||
let half = side / 2.;
|
let half = side / 2.;
|
||||||
@@ -1709,10 +1715,10 @@ impl EffectOperation {
|
|||||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
||||||
pub fn takes_frame(&self) -> bool {
|
pub fn takes_frame(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
||||||
Self::Twirl { .. }
|
Self::Twirl { .. }
|
||||||
| Self::Pinch { .. }
|
| Self::Pinch { .. }
|
||||||
| Self::Spherize { .. }
|
| Self::Spherize { .. }
|
||||||
|
|||||||
@@ -25,4 +25,6 @@ vector-types = { workspace = true }
|
|||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
fastnoise-lite = { workspace = true }
|
fastnoise-lite = { workspace = true }
|
||||||
glam = { workspace = true }
|
glam = { workspace = true }
|
||||||
|
half = { workspace = true }
|
||||||
|
log = { workspace = true }
|
||||||
thiserror = { workspace = true }
|
thiserror = { workspace = true }
|
||||||
@@ -30,12 +30,11 @@ pub enum StepKind {
|
|||||||
ColorLookup,
|
ColorLookup,
|
||||||
ColorOverlay,
|
ColorOverlay,
|
||||||
Solarize,
|
Solarize,
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StepKind {
|
impl StepKind {
|
||||||
/// Every kind, in the order of their codes.
|
/// Every kind, in the order of their codes.
|
||||||
pub const ALL: [StepKind; 22] = [
|
pub const ALL: [StepKind; 21] = [
|
||||||
StepKind::Desaturate,
|
StepKind::Desaturate,
|
||||||
StepKind::GammaCorrection,
|
StepKind::GammaCorrection,
|
||||||
StepKind::MakeOpaque,
|
StepKind::MakeOpaque,
|
||||||
@@ -57,7 +56,6 @@ impl StepKind {
|
|||||||
StepKind::ColorLookup,
|
StepKind::ColorLookup,
|
||||||
StepKind::ColorOverlay,
|
StepKind::ColorOverlay,
|
||||||
StepKind::Solarize,
|
StepKind::Solarize,
|
||||||
StepKind::AlphaToGray,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||||
@@ -271,7 +269,6 @@ mod tests {
|
|||||||
opacity: 50.,
|
opacity: 50.,
|
||||||
},
|
},
|
||||||
Adjustment::Solarize,
|
Adjustment::Solarize,
|
||||||
Adjustment::AlphaToGray,
|
|
||||||
];
|
];
|
||||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ use core_types::transfer_curve::TransferCurveEvaluator;
|
|||||||
use glam::Vec3;
|
use glam::Vec3;
|
||||||
use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute};
|
use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute};
|
||||||
use raster_types::parallel_rows::fill_rows;
|
use raster_types::parallel_rows::fill_rows;
|
||||||
use raster_types::{CPU, Raster};
|
|
||||||
use std::iter::once;
|
use std::iter::once;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use vector_types::gradient::{GradientEvaluator, SplineKnots, interpolation_endpoints};
|
use vector_types::gradient::{GradientEvaluator, SplineKnots, interpolation_endpoints};
|
||||||
@@ -37,20 +36,6 @@ pub fn adjust_colors(adjustment: &Adjustment, colors: &mut [Color]) {
|
|||||||
visit_kernel(adjustment, AdjustColors(colors));
|
visit_kernel(adjustment, AdjustColors(colors));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The raster with `adjustments` carried out on its colors, even those of transparent pixels, as for the adjustments leading its effects.
|
|
||||||
/// The result is kept with the raster's pixels, so adjusting them the same way again reuses it, ID and all.
|
|
||||||
pub fn adjusted_raster(raster: &Raster<CPU>, adjustments: &[Adjustment]) -> Raster<CPU> {
|
|
||||||
let mut hasher = std::hash::DefaultHasher::new();
|
|
||||||
adjustments.iter().for_each(|adjustment| core_types::graphene_hash::CacheHash::cache_hash(adjustment, &mut hasher));
|
|
||||||
let key = std::hash::Hasher::finish(&hasher);
|
|
||||||
|
|
||||||
raster.derived(key, |raster| {
|
|
||||||
let mut image = raster.data().clone();
|
|
||||||
adjustments.iter().for_each(|adjustment| adjust_colors(adjustment, &mut image.data));
|
|
||||||
Raster::new_cpu(image)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead.
|
/// The color with `adjustment` carried out on it. To adjust many colors one at a time, prepare a [`PreparedAdjustment`] once instead.
|
||||||
pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color {
|
pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color {
|
||||||
struct AdjustColor(Color);
|
struct AdjustColor(Color);
|
||||||
@@ -241,7 +226,6 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
|||||||
}
|
}
|
||||||
Adjustment::Invert => visitor.visit(Invert),
|
Adjustment::Invert => visitor.visit(Invert),
|
||||||
Adjustment::Solarize => visitor.visit(Solarize),
|
Adjustment::Solarize => visitor.visit(Solarize),
|
||||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
|
||||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||||
min_luminance: (min_luminance / 100.) as f32,
|
min_luminance: (min_luminance / 100.) as f32,
|
||||||
max_luminance: (max_luminance / 100.) as f32,
|
max_luminance: (max_luminance / 100.) as f32,
|
||||||
@@ -1137,20 +1121,6 @@ impl MapColor for Solarize {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
|
||||||
struct AlphaToGray;
|
|
||||||
|
|
||||||
impl MapColor for AlphaToGray {
|
|
||||||
fn map_cpu(&self, color: Color) -> Color {
|
|
||||||
let gray = srgb_to_linear(color.a());
|
|
||||||
color.map_rgb(|_| gray)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
|
||||||
steps.push(StepKind::AlphaToGray, []);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Threshold {
|
struct Threshold {
|
||||||
min_luminance: f32,
|
min_luminance: f32,
|
||||||
max_luminance: f32,
|
max_luminance: f32,
|
||||||
@@ -2037,69 +2007,4 @@ mod tests {
|
|||||||
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
|
|
||||||
use core_types::transfer_curve::TransferCurve;
|
|
||||||
use glam::DVec2;
|
|
||||||
use graphic_types::effects::{EffectKind, EffectOperation};
|
|
||||||
|
|
||||||
let kinds = [
|
|
||||||
EffectKind::Desaturate,
|
|
||||||
EffectKind::GammaCorrection,
|
|
||||||
EffectKind::MakeOpaque,
|
|
||||||
EffectKind::BrightnessContrast,
|
|
||||||
EffectKind::Levels,
|
|
||||||
EffectKind::Curves,
|
|
||||||
EffectKind::BlackAndWhite,
|
|
||||||
EffectKind::HueSaturation,
|
|
||||||
EffectKind::Invert,
|
|
||||||
EffectKind::Threshold,
|
|
||||||
EffectKind::GradientMap,
|
|
||||||
EffectKind::Vibrance,
|
|
||||||
EffectKind::ChannelMixer,
|
|
||||||
EffectKind::SelectiveColor,
|
|
||||||
EffectKind::Posterize,
|
|
||||||
EffectKind::Exposure,
|
|
||||||
EffectKind::ColorBalance,
|
|
||||||
EffectKind::PhotoFilter,
|
|
||||||
EffectKind::ColorLookup,
|
|
||||||
EffectKind::Solarize,
|
|
||||||
];
|
|
||||||
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
|
|
||||||
EffectOperation::Adjustment(adjustment) => adjustment,
|
|
||||||
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
|
|
||||||
let identity = settings::LevelsRecord::IDENTITY;
|
|
||||||
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
|
|
||||||
let levels = |composite, alpha| {
|
|
||||||
Adjustment::Levels(Box::new(settings::LevelsSettings {
|
|
||||||
composite,
|
|
||||||
red: identity,
|
|
||||||
green: identity,
|
|
||||||
blue: identity,
|
|
||||||
alpha,
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
|
|
||||||
let curves = |composite: TransferCurve, alpha: TransferCurve| {
|
|
||||||
Adjustment::Curves(Box::new(settings::CurvesSettings {
|
|
||||||
composite,
|
|
||||||
alpha,
|
|
||||||
..Default::default()
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
let settings = [
|
|
||||||
levels(darkened, identity),
|
|
||||||
levels(identity, darkened),
|
|
||||||
curves(curve.clone(), TransferCurve::default()),
|
|
||||||
curves(TransferCurve::default(), curve),
|
|
||||||
];
|
|
||||||
|
|
||||||
for adjustment in defaults.iter().chain(&settings) {
|
|
||||||
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,579 @@
|
|||||||
|
//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting.
|
||||||
|
//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas.
|
||||||
|
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
|
||||||
|
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||||
|
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||||
|
|
||||||
|
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
||||||
|
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
||||||
|
|
||||||
|
/// The largest box or tent half width, in pixels, convolved on the image itself rather than a halved copy.
|
||||||
|
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
||||||
|
|
||||||
|
/// The farthest texel from the center a kernel weighs, which fits every direct limit.
|
||||||
|
pub const MAX_KERNEL_REACH: usize = 24;
|
||||||
|
|
||||||
|
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||||
|
const MAX_LEVELS: u32 = 16;
|
||||||
|
|
||||||
|
/// How many passes after jump flooding to `reach` look for nearer seeds through the neighbors one chamfer step away, which settles the near misses within about 20 pixels.
|
||||||
|
/// Since a chamfer length is the shortest path of such steps, a pixel whose neighbor along that path found the nearest seed finds it too.
|
||||||
|
pub fn chamfer_passes(reach: f64) -> usize {
|
||||||
|
if reach > 16. { 4 } else { 2 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The steps of a chamfer path (one pixel straight or diagonally, or a knight's move) by rows from the top, the order the GPU visits them in too.
|
||||||
|
const CHAMFER_STEPS: [[i32; 2]; 16] = [
|
||||||
|
[-1, -2],
|
||||||
|
[1, -2],
|
||||||
|
[-2, -1],
|
||||||
|
[-1, -1],
|
||||||
|
[0, -1],
|
||||||
|
[1, -1],
|
||||||
|
[2, -1],
|
||||||
|
[-1, 0],
|
||||||
|
[1, 0],
|
||||||
|
[-2, 1],
|
||||||
|
[-1, 1],
|
||||||
|
[0, 1],
|
||||||
|
[1, 1],
|
||||||
|
[2, 1],
|
||||||
|
[-1, 2],
|
||||||
|
[1, 2],
|
||||||
|
];
|
||||||
|
|
||||||
|
/// A blur's kernel along one axis, sized in pixels.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum BlurKernel {
|
||||||
|
Gaussian {
|
||||||
|
sigma: f64,
|
||||||
|
},
|
||||||
|
Box {
|
||||||
|
radius: f64,
|
||||||
|
},
|
||||||
|
/// Weighs each texel by how far short of `radius` it lies, the shape of two box blurs of that width in a row.
|
||||||
|
Tent {
|
||||||
|
radius: f64,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlurKernel {
|
||||||
|
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
||||||
|
pub fn levels(self) -> u32 {
|
||||||
|
let (length, direct_limit) = match self {
|
||||||
|
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
||||||
|
Self::Box { radius } | Self::Tent { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
||||||
|
};
|
||||||
|
|
||||||
|
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
||||||
|
pub fn weights(self, levels: u32) -> Vec<f64> {
|
||||||
|
let level_scale = (1 << levels) as f64;
|
||||||
|
|
||||||
|
let weights: Vec<f64> = match self {
|
||||||
|
Self::Gaussian { sigma } => {
|
||||||
|
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
||||||
|
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
||||||
|
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
||||||
|
if sigma < NEGLIGIBLE_LENGTH {
|
||||||
|
return vec![1.];
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||||
|
}
|
||||||
|
Self::Box { radius } => {
|
||||||
|
let radius = radius / level_scale;
|
||||||
|
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
||||||
|
}
|
||||||
|
Self::Tent { radius } => {
|
||||||
|
let radius = radius / level_scale;
|
||||||
|
if radius <= 1. {
|
||||||
|
return vec![1.];
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||||
|
(0..=reach).map(|i| (radius - i as f64).max(0.)).collect()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||||
|
weights.into_iter().map(|weight| weight / total).collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
||||||
|
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
||||||
|
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
||||||
|
(radius + 1. - distance as f64).clamp(0., 1.)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
||||||
|
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
||||||
|
|
||||||
|
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
||||||
|
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
||||||
|
pub fn variable_box_scale(pixels: usize) -> f64 {
|
||||||
|
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
||||||
|
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
||||||
|
pub trait Sample: Copy + Default + Send + Sync {
|
||||||
|
fn scaled(self, factor: f32) -> Self;
|
||||||
|
fn plus(self, other: Self) -> Self;
|
||||||
|
fn max(self, other: Self) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sample for f32 {
|
||||||
|
fn scaled(self, factor: f32) -> Self {
|
||||||
|
self * factor
|
||||||
|
}
|
||||||
|
fn plus(self, other: Self) -> Self {
|
||||||
|
self + other
|
||||||
|
}
|
||||||
|
fn max(self, other: Self) -> Self {
|
||||||
|
f32::max(self, other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sample for [f32; 4] {
|
||||||
|
fn scaled(self, factor: f32) -> Self {
|
||||||
|
self.map(|channel| channel * factor)
|
||||||
|
}
|
||||||
|
fn plus(self, other: Self) -> Self {
|
||||||
|
std::array::from_fn(|channel| self[channel] + other[channel])
|
||||||
|
}
|
||||||
|
fn max(self, other: Self) -> Self {
|
||||||
|
std::array::from_fn(|channel| self[channel].max(other[channel]))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An image of [`Sample`]s in rows, which the operations read and write.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Plane<T> {
|
||||||
|
pub width: usize,
|
||||||
|
pub height: usize,
|
||||||
|
pub data: Vec<T>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Sample> Plane<T> {
|
||||||
|
pub fn new(width: usize, height: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
data: vec![T::default(); width * height],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plane of the same size whose pixels are `map` of this one's.
|
||||||
|
pub fn map<U: Sample>(&self, map: impl Fn(T) -> U + Sync) -> Plane<U> {
|
||||||
|
let mut mapped = Plane::new(self.width, self.height);
|
||||||
|
fill_rows(&mut mapped.data, self.width, |y, row| {
|
||||||
|
let source = &self.data[y * self.width..(y + 1) * self.width];
|
||||||
|
row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value));
|
||||||
|
});
|
||||||
|
mapped
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Combines this plane with `other`, of the same size, pixel by pixel.
|
||||||
|
pub fn zip<U: Sample, V: Sample>(&self, other: &Plane<U>, combine: impl Fn(T, U) -> V + Sync) -> Plane<V> {
|
||||||
|
let mut combined = Plane::new(self.width, self.height);
|
||||||
|
fill_rows(&mut combined.data, self.width, |y, row| {
|
||||||
|
let range = y * self.width..(y + 1) * self.width;
|
||||||
|
let pairs = self.data[range.clone()].iter().zip(&other.data[range]);
|
||||||
|
row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b));
|
||||||
|
});
|
||||||
|
combined
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||||
|
pub(crate) fn transposed(&self) -> Self {
|
||||||
|
let mut transposed = Self::new(self.height, self.width);
|
||||||
|
fill_rows(&mut transposed.data, self.height, |x, row| {
|
||||||
|
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
||||||
|
});
|
||||||
|
transposed
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels.
|
||||||
|
fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self {
|
||||||
|
let mut result = Self::new(width, self.height);
|
||||||
|
fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row));
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back.
|
||||||
|
fn along_both_axes<P>(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self {
|
||||||
|
let plane = along_rows(self, horizontal);
|
||||||
|
along_rows(plane.transposed(), vertical).transposed()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times
|
||||||
|
/// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling.
|
||||||
|
pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self {
|
||||||
|
self.along_both_axes(horizontal, vertical, |mut plane, kernel| {
|
||||||
|
let levels = kernel.levels();
|
||||||
|
let length = plane.width;
|
||||||
|
let level_length = |level: u32| length.div_ceil(1 << level);
|
||||||
|
|
||||||
|
for level in 1..=levels {
|
||||||
|
plane = plane.map_rows(level_length(level), halve_row);
|
||||||
|
}
|
||||||
|
|
||||||
|
let weights = kernel.weights(levels);
|
||||||
|
plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights));
|
||||||
|
|
||||||
|
for level in (0..levels).rev() {
|
||||||
|
plane = plane.map_rows(level_length(level), double_row);
|
||||||
|
}
|
||||||
|
plane
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges.
|
||||||
|
pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self {
|
||||||
|
self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset)))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The length of a whole-pixel offset along the shortest path of steps one pixel straight, one diagonally, or a knight's move away.
|
||||||
|
/// For PSD interop, layer styles measure distances this way, which rounds the corners they grow around into 16 sides rather than a circle.
|
||||||
|
pub fn chamfer_length([x, y]: [i32; 2]) -> f32 {
|
||||||
|
let (long, short) = (x.abs().max(y.abs()) as f32, x.abs().min(y.abs()) as f32);
|
||||||
|
match 2. * short <= long {
|
||||||
|
// Knight's moves and straight steps
|
||||||
|
true => (long - 2. * short) + 5_f32.sqrt() * short,
|
||||||
|
// Knight's moves and diagonal steps
|
||||||
|
false => 5_f32.sqrt() * (long - short) + std::f32::consts::SQRT_2 * (2. * short - long),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Plane<f32> {
|
||||||
|
/// Each pixel's distance to the silhouette's edge plus half a pixel, so a pixel beside a fully covered one lies one away and covered ones none, or infinity past `reach`.
|
||||||
|
/// Distances run by [`chamfer_length`] to the nearest covered pixel, then by its uncovered share within it, placing an antialiased edge between pixels.
|
||||||
|
pub fn distances_to_silhouette(&self, reach: f64) -> Self {
|
||||||
|
self.jump_flood(reach, |coverage| coverage > 0., |offset, coverage| chamfer_length(offset) + (0.5 - coverage) + 0.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each pixel's least [`chamfer_length`] to a seed plus the seed's own value, where the seeds are the pixels with finite values, or infinity past `reach`.
|
||||||
|
pub fn distances_through_seeds(&self, reach: f64) -> Self {
|
||||||
|
self.jump_flood(reach, f32::is_finite, |offset, value| chamfer_length(offset) + value)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each pixel's least `distance` to a seed, given its offset from the seed and the seed's value, or infinity past `reach`.
|
||||||
|
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none.
|
||||||
|
/// Seeds of differing values leave near misses, mostly settled by two more halving passes and then those of [`chamfer_passes`] along the chamfer steps. O(width × height × log(reach)).
|
||||||
|
pub(crate) fn jump_flood(&self, reach: f64, is_seed: impl Fn(f32) -> bool, distance: impl Fn([i32; 2], f32) -> f32 + Sync) -> Self {
|
||||||
|
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&value| is_seed(value).then_some([0, 0])).collect();
|
||||||
|
|
||||||
|
let (columns, rows) = (self.width as i32, self.height as i32);
|
||||||
|
// The offset runs from the seed to the pixel
|
||||||
|
let distance = |x: i32, y: i32, offset: [i32; 2]| distance(offset, self.data[((y - offset[1]) * columns + x - offset[0]) as usize]);
|
||||||
|
|
||||||
|
// The neighbors each pass looks at in the GPU's order: the eight a step away, then those one chamfer step away
|
||||||
|
let first_step = (reach.clamp(0., (columns.max(rows)) as f64).ceil() as u32 + 1).next_power_of_two() as i32;
|
||||||
|
let halvings = std::iter::successors(Some(first_step), |&step| (step > 1).then_some(step / 2)).chain([2, 1]);
|
||||||
|
let adjacent = CHAMFER_STEPS.iter().filter(|[x, y]| x.abs().max(y.abs()) == 1);
|
||||||
|
let around = |step: i32| adjacent.clone().map(|&[x, y]| [x * step, y * step]).collect::<Vec<_>>();
|
||||||
|
let passes = halvings.map(around).chain(std::iter::repeat_n(CHAMFER_STEPS.to_vec(), chamfer_passes(reach)));
|
||||||
|
|
||||||
|
for neighbors in passes {
|
||||||
|
let previous = nearest.clone();
|
||||||
|
|
||||||
|
// Each pixel keeps the nearest of the seeds that it and its neighbors have found so far
|
||||||
|
fill_rows(&mut nearest, self.width, |y, row| {
|
||||||
|
let y = y as i32;
|
||||||
|
for (x, best) in row.iter_mut().enumerate() {
|
||||||
|
let x = x as i32;
|
||||||
|
let mut best_distance = best.map_or(f32::INFINITY, |offset| distance(x, y, offset));
|
||||||
|
|
||||||
|
for &[neighbor_x, neighbor_y] in &neighbors {
|
||||||
|
let (from_x, from_y) = (x + neighbor_x, y + neighbor_y);
|
||||||
|
if from_x < 0 || from_y < 0 || from_x >= columns || from_y >= rows {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some([offset_x, offset_y]) = previous[(from_y * columns + from_x) as usize] else { continue };
|
||||||
|
|
||||||
|
let candidate = [offset_x - neighbor_x, offset_y - neighbor_y];
|
||||||
|
let candidate_distance = distance(x, y, candidate);
|
||||||
|
if candidate_distance < best_distance {
|
||||||
|
*best = Some(candidate);
|
||||||
|
best_distance = candidate_distance;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let data = nearest
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(index, offset)| offset.map_or(f32::INFINITY, |offset| distance(index as i32 % columns, index as i32 / columns, offset).max(0.)))
|
||||||
|
.collect();
|
||||||
|
Self {
|
||||||
|
width: self.width,
|
||||||
|
height: self.height,
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The silhouette grown outward by `distance` pixels, measured by [`chamfer_length`] so it rounds the corners it grows around.
|
||||||
|
/// The grown edge lies half a pixel short of the farthest pixel center it reaches past, and fades out over one pixel.
|
||||||
|
pub fn grown(&self, distance: f64) -> Self {
|
||||||
|
let reach = distance as f32 + 1.;
|
||||||
|
self.distances_to_silhouette(distance + 1.).map(|nearest| (reach - nearest).clamp(0., 1.))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends.
|
||||||
|
fn sample_row<T: Sample>(row: &[T], position: f64) -> T {
|
||||||
|
let last = row.len() as f64 - 1.;
|
||||||
|
let position = position.clamp(0., last.max(0.));
|
||||||
|
let index = position.floor() as usize;
|
||||||
|
let fraction = (position - index as f64) as f32;
|
||||||
|
|
||||||
|
match row.get(index + 1) {
|
||||||
|
Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)),
|
||||||
|
_ => row[index],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself.
|
||||||
|
fn halve_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||||
|
for (index, value) in target.iter_mut().enumerate() {
|
||||||
|
let first = source[2 * index];
|
||||||
|
let second = source.get(2 * index + 1).copied().unwrap_or(first);
|
||||||
|
*value = first.plus(second).scaled(0.5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into.
|
||||||
|
fn double_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||||
|
for (index, value) in target.iter_mut().enumerate() {
|
||||||
|
*value = sample_row(source, index as f64 / 2. - 0.25);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends.
|
||||||
|
fn convolve_row<T: Sample>(source: &[T], target: &mut [T], weights: &[f64]) {
|
||||||
|
let last = source.len() as isize - 1;
|
||||||
|
let at = |index: isize| source[index.clamp(0, last) as usize];
|
||||||
|
|
||||||
|
for (index, value) in target.iter_mut().enumerate() {
|
||||||
|
let index = index as isize;
|
||||||
|
let mut sum = at(index).scaled(weights[0] as f32);
|
||||||
|
for (distance, &weight) in weights.iter().enumerate().skip(1) {
|
||||||
|
let pair = at(index - distance as isize).plus(at(index + distance as isize));
|
||||||
|
sum = sum.plus(pair.scaled(weight as f32));
|
||||||
|
}
|
||||||
|
*value = sum;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves the row by `offset` pixels, with nothing beyond its ends.
|
||||||
|
fn shift_row<T: Sample>(source: &[T], target: &mut [T], offset: f64) {
|
||||||
|
let length = source.len() as f64;
|
||||||
|
for (index, value) in target.iter_mut().enumerate() {
|
||||||
|
let position = index as f64 - offset;
|
||||||
|
let floor = position.floor();
|
||||||
|
let fraction = (position - floor) as f32;
|
||||||
|
|
||||||
|
let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() };
|
||||||
|
*value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernel_weights_sum_to_one() {
|
||||||
|
for kernel in [
|
||||||
|
BlurKernel::Gaussian { sigma: 3. },
|
||||||
|
BlurKernel::Gaussian { sigma: 40. },
|
||||||
|
BlurKernel::Box { radius: 5.5 },
|
||||||
|
BlurKernel::Box { radius: 100. },
|
||||||
|
] {
|
||||||
|
let levels = kernel.levels();
|
||||||
|
let weights = kernel.weights(levels);
|
||||||
|
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||||
|
|
||||||
|
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
||||||
|
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn small_kernels_run_without_halving() {
|
||||||
|
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
||||||
|
assert_eq!(
|
||||||
|
BlurKernel::Gaussian {
|
||||||
|
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
||||||
|
}
|
||||||
|
.levels(),
|
||||||
|
1
|
||||||
|
);
|
||||||
|
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn gaussian_blur_spreads_a_point_with_the_requested_deviation() {
|
||||||
|
// A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count
|
||||||
|
for sigma in [2., 20.] {
|
||||||
|
let size = 401;
|
||||||
|
let mut plane = Plane::<f32>::new(size, 1);
|
||||||
|
plane.data[size / 2] = 1.;
|
||||||
|
|
||||||
|
let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. });
|
||||||
|
let total: f32 = blurred.data.iter().sum();
|
||||||
|
let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::<f64>() / total as f64;
|
||||||
|
|
||||||
|
assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}");
|
||||||
|
assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tents_weigh_texels_by_how_far_short_of_the_radius_they_lie() {
|
||||||
|
// For PSD interop, a size of 16 weighs the texels 16, 15, ..., 1 from the center outward
|
||||||
|
let weights = BlurKernel::Tent { radius: 16. }.weights(0);
|
||||||
|
assert_eq!(weights.len(), 17);
|
||||||
|
for (distance, &weight) in weights.iter().enumerate() {
|
||||||
|
assert!((weight - (16 - distance) as f64 / 256.).abs() < 1e-12, "texel {distance} weighs {weight}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A straight edge blurred by it reaches (S - i)(S + 1 - i) / 2S² at the i-th pixel past the edge
|
||||||
|
let mut plane = Plane::<f32>::new(64, 1);
|
||||||
|
plane.data[..32].fill(1.);
|
||||||
|
let blurred = plane.blurred(BlurKernel::Tent { radius: 16. }, BlurKernel::Tent { radius: 0. });
|
||||||
|
for i in 1..17 {
|
||||||
|
let expected = ((16 - i) * (17 - i)) as f32 / 512.;
|
||||||
|
assert!((blurred.data[31 + i] - expected).abs() < 1e-6, "pixel {i} past the edge is {}", blurred.data[31 + i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn growing_rounds_the_corners_it_grows_around() {
|
||||||
|
// A single pixel grows into a disk the distance across, rather than a square
|
||||||
|
let mut point = Plane::<f32>::new(21, 21);
|
||||||
|
point.data[10 * 21 + 10] = 1.;
|
||||||
|
let grown = point.grown(5.);
|
||||||
|
let at = |x: usize, y: usize| grown.data[y * 21 + x];
|
||||||
|
|
||||||
|
assert_eq!(at(15, 10), 1., "the full distance along an axis");
|
||||||
|
assert_eq!(at(16, 10), 0., "past the distance");
|
||||||
|
assert_eq!(at(15, 14), 0., "past the distance diagonally, where a square would still reach");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn chamfer_lengths_are_exact_along_their_steps() {
|
||||||
|
assert_eq!(chamfer_length([7, 0]), 7.);
|
||||||
|
assert!((chamfer_length([-4, 4]) - 4. * std::f32::consts::SQRT_2).abs() < 1e-5);
|
||||||
|
assert!((chamfer_length([2, -1]) - 5_f32.sqrt()).abs() < 1e-6);
|
||||||
|
// Between the steps, the path runs a little longer than a straight line
|
||||||
|
assert!((chamfer_length([3, 1]) - (1. + 5_f32.sqrt())).abs() < 1e-6);
|
||||||
|
assert!((chamfer_length([3, 2]) - (5_f32.sqrt() + std::f32::consts::SQRT_2)).abs() < 1e-6);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn distances_reach_no_farther_than_asked() {
|
||||||
|
let mut plane = Plane::<f32>::new(64, 1);
|
||||||
|
plane.data[0] = 1.;
|
||||||
|
let distances = plane.distances_to_silhouette(8.);
|
||||||
|
|
||||||
|
assert_eq!(distances.data[0], 0.);
|
||||||
|
assert_eq!(distances.data[5], 5.);
|
||||||
|
assert!(
|
||||||
|
distances.data[63].is_infinite() || distances.data[63] == 63.,
|
||||||
|
"a pixel far past the reach finds no seed or the true one"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn distances_from_seeds_of_differing_values_are_exact_within_their_reach() {
|
||||||
|
// An antialiased disk whose edge pixels seed with head starts set by their coverage away from half, as a Soft Chisel bevel's do
|
||||||
|
let side = 40;
|
||||||
|
let disk = Plane {
|
||||||
|
width: side,
|
||||||
|
height: side,
|
||||||
|
data: (0..side * side)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % side) as f64 + 0.5 - 20.3, (index / side) as f64 + 0.5 - 19.6);
|
||||||
|
(12.5 - (x * x + y * y).sqrt()).clamp(0., 1.) as f32
|
||||||
|
})
|
||||||
|
.collect(),
|
||||||
|
};
|
||||||
|
let head_starts = disk.map(|alpha| ((alpha - 0.5) * 22.).max(0.));
|
||||||
|
let reach = 11.;
|
||||||
|
|
||||||
|
// O(n²) over the pixel pairs, small enough here
|
||||||
|
let exactly = |values: &Plane<f32>, distance: &dyn Fn([i32; 2], f32) -> Option<f32>| {
|
||||||
|
(0..side * side)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % side) as i32, (index / side) as i32);
|
||||||
|
let candidates = (0..side * side).filter_map(|from| {
|
||||||
|
let offset = [x - (from % side) as i32, y - (from / side) as i32];
|
||||||
|
distance(offset, values.data[from])
|
||||||
|
});
|
||||||
|
candidates.fold(f32::INFINITY, f32::min)
|
||||||
|
})
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
|
||||||
|
let found = head_starts.distances_through_seeds(reach);
|
||||||
|
let exact = exactly(&head_starts, &|offset, value| Some(chamfer_length(offset) + value));
|
||||||
|
let found_edges = disk.distances_to_silhouette(reach);
|
||||||
|
let exact_edges = exactly(&disk, &|offset, coverage| (coverage > 0.).then(|| chamfer_length(offset) + 1. - coverage));
|
||||||
|
|
||||||
|
for index in 0..side * side {
|
||||||
|
if exact[index] <= reach as f32 {
|
||||||
|
assert!(
|
||||||
|
(found.data[index] - exact[index]).abs() < 1e-4,
|
||||||
|
"pixel {index} lies {} from the seeds, not {}",
|
||||||
|
found.data[index],
|
||||||
|
exact[index]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if exact_edges[index] <= reach as f32 {
|
||||||
|
assert!(
|
||||||
|
(found_edges.data[index] - exact_edges[index]).abs() < 1e-4,
|
||||||
|
"pixel {index} lies {} from the edge, not {}",
|
||||||
|
found_edges.data[index],
|
||||||
|
exact_edges[index]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn growing_the_outside_inward_covers_only_the_band_along_the_edges() {
|
||||||
|
let mut square = Plane::<f32>::new(21, 21);
|
||||||
|
for y in 2..19 {
|
||||||
|
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
||||||
|
}
|
||||||
|
let inward = square.map(|coverage| 1. - coverage).grown(3.);
|
||||||
|
let at = |x: usize, y: usize| inward.data[y * 21 + x];
|
||||||
|
|
||||||
|
assert_eq!(at(2, 10), 1., "at the edge");
|
||||||
|
assert_eq!(at(4, 10), 1., "the band's full width in");
|
||||||
|
assert_eq!(at(5, 10), 0., "past the band's width");
|
||||||
|
assert_eq!(at(10, 10), 0., "deep inside");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn shifting_moves_by_fractions_of_a_pixel() {
|
||||||
|
let mut plane = Plane::<f32>::new(4, 1);
|
||||||
|
plane.data[1] = 1.;
|
||||||
|
|
||||||
|
let shifted = plane.shifted(0.25, 0.);
|
||||||
|
|
||||||
|
assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,432 +0,0 @@
|
|||||||
//! How the effects' GPU passes are planned from their settings: blur kernels and the halvings they run on, the limits of other passes, motion blur shears, and the cells of pixelations and halftones.
|
|
||||||
//! SVG's filters size their blurs by some of these too.
|
|
||||||
|
|
||||||
use glam::{DMat2, DVec2};
|
|
||||||
use graphic_types::filters::fill_shifts;
|
|
||||||
use graphic_types::resampling::{EffectFrame, HalftoneScreen, PIXELATE_TIE_NUDGE, tie_nudge};
|
|
||||||
|
|
||||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
|
||||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
|
||||||
|
|
||||||
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
|
||||||
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
|
||||||
|
|
||||||
/// The largest box or tent half width, in pixels, convolved on the image itself rather than a halved copy.
|
|
||||||
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
|
||||||
|
|
||||||
/// The farthest texel from the center a kernel weighs, which fits every direct limit.
|
|
||||||
pub const MAX_KERNEL_REACH: usize = 24;
|
|
||||||
|
|
||||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
|
||||||
const MAX_LEVELS: u32 = 16;
|
|
||||||
|
|
||||||
/// How many passes after jump flooding to `reach` look for nearer seeds through the neighbors one chamfer step away, which settles the near misses within about 20 pixels.
|
|
||||||
/// Since a chamfer length is the shortest path of such steps, a pixel whose neighbor along that path found the nearest seed finds it too.
|
|
||||||
pub fn chamfer_passes(reach: f64) -> usize {
|
|
||||||
if reach > 16. { 4 } else { 2 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A blur's kernel along one axis, sized in pixels.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub enum BlurKernel {
|
|
||||||
Gaussian {
|
|
||||||
sigma: f64,
|
|
||||||
},
|
|
||||||
Box {
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
/// Weighs each texel by how far short of `radius` it lies, the shape of two box blurs of that width in a row.
|
|
||||||
Tent {
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BlurKernel {
|
|
||||||
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
|
||||||
pub fn levels(self) -> u32 {
|
|
||||||
let (length, direct_limit) = match self {
|
|
||||||
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
|
||||||
Self::Box { radius } | Self::Tent { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
|
||||||
};
|
|
||||||
|
|
||||||
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
|
||||||
pub fn weights(self, levels: u32) -> Vec<f64> {
|
|
||||||
let level_scale = (1 << levels) as f64;
|
|
||||||
|
|
||||||
let weights: Vec<f64> = match self {
|
|
||||||
Self::Gaussian { sigma } => {
|
|
||||||
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
|
||||||
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
|
||||||
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
|
||||||
if sigma < NEGLIGIBLE_LENGTH {
|
|
||||||
return vec![1.];
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
|
||||||
}
|
|
||||||
Self::Box { radius } => {
|
|
||||||
let radius = radius / level_scale;
|
|
||||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
|
||||||
}
|
|
||||||
Self::Tent { radius } => {
|
|
||||||
let radius = radius / level_scale;
|
|
||||||
if radius <= 1. {
|
|
||||||
return vec![1.];
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
|
||||||
(0..=reach).map(|i| (radius - i as f64).max(0.)).collect()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
|
||||||
weights.into_iter().map(|weight| weight / total).collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
|
||||||
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
|
||||||
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
|
||||||
(radius + 1. - distance as f64).clamp(0., 1.)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
|
||||||
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
|
||||||
|
|
||||||
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
|
||||||
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
|
||||||
pub fn variable_box_scale(pixels: usize) -> f64 {
|
|
||||||
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
|
||||||
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The whole-pixel shifts, nearest first, that a faint pixel looks along for a visible one within `reach` document pixels, measured through `document_to_pixels`. O(reach² log reach).
|
|
||||||
pub fn pixel_fill_shifts(reach: f64, document_to_pixels: DMat2) -> Vec<[isize; 2]> {
|
|
||||||
let mut seen = std::collections::HashSet::new();
|
|
||||||
let pixel_shift = |[x, y]: [i32; 2]| (document_to_pixels * DVec2::new(x as f64, y as f64)).round();
|
|
||||||
(fill_shifts(reach.ceil() as i32).into_iter().map(pixel_shift))
|
|
||||||
.map(|shift| [shift.x as isize, shift.y as isize])
|
|
||||||
.filter(|&shift| seen.insert(shift))
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The most samples a motion blur's box averages along its line at each pixel, past which its samples spread out evenly to cover it.
|
|
||||||
pub const MAX_MOTION_BLUR_SAMPLES: f64 = 1024.;
|
|
||||||
|
|
||||||
/// For PSD interop, a motion blur shears the image so its line runs along whichever axis it's closer to (the major axis), averages a box along that axis, and shears back.
|
|
||||||
/// Each shear interpolates across the minor axis with the Keys cubic kernel (a = -0.75), measured from the content's origin, which for an image is the corner PSD measures from.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct MotionBlurShear {
|
|
||||||
/// Whether the line is closer to vertical, so the shears move columns of pixels across rows rather than rows across columns.
|
|
||||||
pub vertical: bool,
|
|
||||||
/// How far the line moves across the minor axis for each pixel along the major axis.
|
|
||||||
pub slope: f64,
|
|
||||||
/// How many pixels the line spans along the major axis.
|
|
||||||
pub length: f64,
|
|
||||||
/// The fraction of a pixel the shears move the column (or row) at the start of the major axis back by, so they're measured from the anchor.
|
|
||||||
pub phase: f64,
|
|
||||||
/// Which way along the major axis the box leans at odd lengths: 1 toward its far end, or -1 toward its near end.
|
|
||||||
pub lean: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MotionBlurShear {
|
|
||||||
/// The shears of a line `distance` long (ignoring its sign) at `angle` (in degrees counterclockwise from the right), both in the effect space, given the map from its lengths into pixels, measured from `anchor` (in pixels).
|
|
||||||
pub fn new(angle: f64, distance: f64, lengths_to_pixels: DMat2, anchor: DVec2) -> Option<Self> {
|
|
||||||
let angle = angle.to_radians();
|
|
||||||
let line = DVec2::new(angle.cos(), -angle.sin()) * distance.abs();
|
|
||||||
let end = lengths_to_pixels * line;
|
|
||||||
|
|
||||||
// For PSD interop, a diagonal runs along the effect space's x axis, and in the pixels, along whichever axis that one lies nearer, so opposite and turned lines agree
|
|
||||||
let own_axis_vertical = nearer_y_axis(line).unwrap_or(false);
|
|
||||||
let own_axis = if own_axis_vertical { DVec2::Y } else { DVec2::X };
|
|
||||||
let vertical = nearer_y_axis(end).or_else(|| nearer_y_axis(lengths_to_pixels * own_axis)).unwrap_or(false);
|
|
||||||
let (major, minor, anchor) = if vertical { (end.y, end.x, anchor.y) } else { (end.x, end.y, anchor.x) };
|
|
||||||
if !(major.abs() >= 0.01 && major.is_finite() && minor.is_finite() && anchor.is_finite()) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
// A line shorter than a pixel slants in only as it lengthens, as PSD's whole-pixel line stays straight along an axis until it reaches across
|
|
||||||
let slope = minor / major * major.abs().min(1.);
|
|
||||||
|
|
||||||
// The box leans toward the end of the line farther along the effect space's axis nearest it, so it leans alike however the pixels lie in that space
|
|
||||||
let along_own_axis = if own_axis_vertical { line.y } else { line.x };
|
|
||||||
let lean = if (major > 0.) == (along_own_axis > 0.) { 1. } else { -1. };
|
|
||||||
|
|
||||||
Some(Self {
|
|
||||||
vertical,
|
|
||||||
slope,
|
|
||||||
length: major.abs(),
|
|
||||||
phase: (slope * anchor).rem_euclid(1.),
|
|
||||||
lean,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The span of the box along the major axis around each pixel: one pixel longer than the line, and for PSD interop, half a pixel toward the end of the axis it leans to at odd lengths.
|
|
||||||
pub fn box_span(&self) -> [f64; 2] {
|
|
||||||
let center = self.lean * (0.5 - (0.5 - (self.length / 2.).fract()).abs());
|
|
||||||
let half = (self.length + 1.) / 2.;
|
|
||||||
[center - half, center + half]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many pixels apart the box's samples are, so it takes no more than [`MAX_MOTION_BLUR_SAMPLES`].
|
|
||||||
pub fn stride(&self) -> f64 {
|
|
||||||
((self.length + 2.) / MAX_MOTION_BLUR_SAMPLES).ceil().max(1.)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `vector` lies nearer the y axis than the x axis, or `None` along a diagonal, to within rounding.
|
|
||||||
fn nearer_y_axis(vector: DVec2) -> Option<bool> {
|
|
||||||
let (x, y) = (vector.x.abs(), vector.y.abs());
|
|
||||||
((x - y).abs() > x.max(y) * 1e-9).then_some(y > x)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many cells a pixelation's tables hold at most for each pixel of the square on the region's longer side, past which its cells far outnumber the pixels, so most are slivers holding none.
|
|
||||||
/// A lattice turned from the region's axes spans about that square, rather than the region's area.
|
|
||||||
const TABLE_BUDGET_PER_SQUARE_PIXEL: usize = 4;
|
|
||||||
|
|
||||||
/// The most cells a pixelation's tables may hold however small the region is, so the margins around a small region's cells fit.
|
|
||||||
const MIN_TABLE_BUDGET: usize = 65_536;
|
|
||||||
|
|
||||||
/// The most cells a pixelation's table counts along each side, which the GPU's single-precision parameters hold exactly.
|
|
||||||
const MAX_TABLE_CELLS_ALONG_A_SIDE: usize = 16_777_216;
|
|
||||||
|
|
||||||
/// Whether a pixelation over a region `width` by `height` pixels makes its `tables` of cells `count` across and down.
|
|
||||||
/// Past this budget Pixelate leaves the content as it is and a halftone prints its tone, since the GPU would hold far more cells than pixels in its textures.
|
|
||||||
pub fn pixelation_table_fits(count: [usize; 2], tables: usize, width: usize, height: usize) -> bool {
|
|
||||||
let longest = width.max(height);
|
|
||||||
let budget = longest.saturating_mul(longest).saturating_mul(TABLE_BUDGET_PER_SQUARE_PIXEL).max(MIN_TABLE_BUDGET);
|
|
||||||
let cells = count[0].saturating_mul(count[1]).saturating_mul(tables);
|
|
||||||
cells <= budget && count.iter().all(|&count| count <= MAX_TABLE_CELLS_ALONG_A_SIDE)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pixelate's cells that a plane of pixels covers.
|
|
||||||
/// Columns and rows within the frame count from 0 at its near corner to its `last`, those before it count down from -1, and those past its far sides count on from one past its last.
|
|
||||||
pub struct PixelateCells {
|
|
||||||
/// How wide each cell is, in the effect space.
|
|
||||||
pub size: f64,
|
|
||||||
/// Where the cells within the frame start along each of its sides, in its local space: the last boundary between cells at or before its near corner.
|
|
||||||
pub start: DVec2,
|
|
||||||
/// How far a point nudges toward the frame's far corner before finding its cell, in the frame's local space, as [`tie_nudge`] gives it.
|
|
||||||
pub nudge: DVec2,
|
|
||||||
/// The column and row of the first cell the plane covers.
|
|
||||||
pub first: [i64; 2],
|
|
||||||
/// How many cells across and down the plane covers.
|
|
||||||
pub count: [usize; 2],
|
|
||||||
/// The column and row of the frame's last cell, at its far corner.
|
|
||||||
pub last: [i64; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PixelateCells {
|
|
||||||
/// The cells `size` across, with a corner at `offset` from the content's origin, that a plane `width` by `height` pixels covers in the `frame`.
|
|
||||||
pub fn new(size: f64, offset: DVec2, frame: &EffectFrame, width: usize, height: usize) -> Self {
|
|
||||||
let (to_local, half) = (frame.pixels_to_local(), frame.size / 2.);
|
|
||||||
let start = -half - (-half - (frame.origin + offset)).rem_euclid(DVec2::splat(size));
|
|
||||||
let last = (((half - start) / size).ceil() - 1.).max(DVec2::ZERO);
|
|
||||||
let mut cells = Self {
|
|
||||||
size,
|
|
||||||
start,
|
|
||||||
nudge: tie_nudge(size, PIXELATE_TIE_NUDGE, frame),
|
|
||||||
first: [0; 2],
|
|
||||||
count: [1; 2],
|
|
||||||
last: [last.x as i64, last.y as i64],
|
|
||||||
};
|
|
||||||
|
|
||||||
// Each axis numbers its cells in order, so the plane's corners hold the first and last it covers
|
|
||||||
let corners = [DVec2::ZERO, DVec2::new(width as f64, 0.), DVec2::new(0., height as f64), DVec2::new(width as f64, height as f64)];
|
|
||||||
let corner_cells = corners.map(|corner| cells.cell_at(to_local.transform_point2(corner), frame));
|
|
||||||
for axis in 0..2 {
|
|
||||||
let first = corner_cells.iter().map(|cell| cell[axis]).min().unwrap_or_default();
|
|
||||||
let end = corner_cells.iter().map(|cell| cell[axis]).max().unwrap_or_default();
|
|
||||||
cells.first[axis] = first;
|
|
||||||
cells.count[axis] = usize::try_from(end.saturating_sub(first).saturating_add(1)).unwrap_or(usize::MAX);
|
|
||||||
}
|
|
||||||
cells
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The column and row of the cell holding a point in the frame's local space, where the frame's sides belong to the cells within it.
|
|
||||||
pub fn cell_at(&self, local: DVec2, frame: &EffectFrame) -> [i64; 2] {
|
|
||||||
let (half, cuts) = (frame.size / 2., self.cuts_near_cells(frame));
|
|
||||||
let cell = ((local - self.start + self.nudge) / self.size).floor();
|
|
||||||
[0, 1].map(|axis| {
|
|
||||||
let cell = cell[axis] as i64;
|
|
||||||
match local[axis] {
|
|
||||||
coordinate if coordinate < -half[axis] => (cell - cuts[axis] as i64).min(-1),
|
|
||||||
coordinate if coordinate > half[axis] => cell.max(self.last[axis]) + 1,
|
|
||||||
_ => cell.clamp(0, self.last[axis]),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The boundary between cells nearest the frame's near corner along each of its sides, in its local space, and the column and row of the cell starting there.
|
|
||||||
/// Placed from there, the boundaries near the frame stay at the frame's own scale in single precision however wide the cells are.
|
|
||||||
pub fn boundary_near_frame(&self, frame: &EffectFrame) -> (DVec2, [i64; 2]) {
|
|
||||||
let past_start = (-frame.size / 2. - self.start).cmpgt(DVec2::splat(self.size / 2.));
|
|
||||||
(DVec2::select(past_start, self.start + self.size, self.start), [past_start.x as i64, past_start.y as i64])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the frame's near side cuts a cell along each of its sides, leaving its part before the side a cell of its own.
|
|
||||||
pub fn cuts_near_cells(&self, frame: &EffectFrame) -> [bool; 2] {
|
|
||||||
let cut = self.start.cmplt(-frame.size / 2.);
|
|
||||||
[cut.x, cut.y]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first cell of a halftone `screen`'s table of dots that the pixels of an image `width` by `height` may lie nearest (see [`HalftoneScreen::table_cell_at`]), and how many cells across and down from it they span,
|
|
||||||
/// with one more around each side than a pixel looks through past its nearest (see [`HalftoneScreen::neighborhood`]).
|
|
||||||
pub fn halftone_cells(width: usize, height: usize, screen: &HalftoneScreen, frame: &EffectFrame) -> ([i64; 2], [usize; 2]) {
|
|
||||||
let to_local = frame.pixels_to_local();
|
|
||||||
let corners = [DVec2::ZERO, DVec2::new(width as f64, 0.), DVec2::new(0., height as f64), DVec2::new(width as f64, height as f64)];
|
|
||||||
let snaps_together = screen.snaps_together(frame);
|
|
||||||
let cells = corners.map(|corner| screen.table_cell_at(to_local.transform_point2(corner) - frame.origin, snaps_together));
|
|
||||||
let margin = screen.neighborhood(frame).saturating_add(1);
|
|
||||||
|
|
||||||
let first = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).min().unwrap_or_default().saturating_sub(margin));
|
|
||||||
let last = [0, 1].map(|axis| cells.iter().map(|cell| cell[axis]).max().unwrap_or_default().saturating_add(margin));
|
|
||||||
(
|
|
||||||
first,
|
|
||||||
[0, 1].map(|axis| usize::try_from(last[axis].saturating_sub(first[axis]).saturating_add(1)).unwrap_or(usize::MAX)),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many cells across and down a halftone's table holds for each channel, as many as the most that any channel's `cells` from [`halftone_cells`] span.
|
|
||||||
pub fn halftone_table_count(cells: &[([i64; 2], [usize; 2]); 3]) -> [usize; 2] {
|
|
||||||
[0, 1].map(|axis| cells.iter().map(|(_, count)| count[axis]).max().unwrap_or(1))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use glam::DAffine2;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn kernel_weights_sum_to_one() {
|
|
||||||
for kernel in [
|
|
||||||
BlurKernel::Gaussian { sigma: 3. },
|
|
||||||
BlurKernel::Gaussian { sigma: 40. },
|
|
||||||
BlurKernel::Box { radius: 5.5 },
|
|
||||||
BlurKernel::Box { radius: 100. },
|
|
||||||
] {
|
|
||||||
let levels = kernel.levels();
|
|
||||||
let weights = kernel.weights(levels);
|
|
||||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
|
||||||
|
|
||||||
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
|
||||||
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn small_kernels_run_without_halving() {
|
|
||||||
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
|
||||||
assert_eq!(
|
|
||||||
BlurKernel::Gaussian {
|
|
||||||
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
|
||||||
}
|
|
||||||
.levels(),
|
|
||||||
1
|
|
||||||
);
|
|
||||||
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tents_weigh_texels_by_how_far_short_of_the_radius_they_lie() {
|
|
||||||
// For PSD interop, a size of 16 weighs the texels 16, 15, ..., 1 from the center outward
|
|
||||||
let weights = BlurKernel::Tent { radius: 16. }.weights(0);
|
|
||||||
assert_eq!(weights.len(), 17);
|
|
||||||
for (distance, &weight) in weights.iter().enumerate() {
|
|
||||||
assert!((weight - (16 - distance) as f64 / 256.).abs() < 1e-12, "texel {distance} weighs {weight}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn shear(angle: f64, distance: f64) -> MotionBlurShear {
|
|
||||||
MotionBlurShear::new(angle, distance, DMat2::IDENTITY, DVec2::ZERO).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn boxes_span_one_pixel_more_than_the_line_leaning_forward_at_odd_lengths() {
|
|
||||||
assert_eq!(shear(0., 10.).box_span(), [-5.5, 5.5]);
|
|
||||||
assert_eq!(shear(0., 11.).box_span(), [-5.5, 6.5]);
|
|
||||||
|
|
||||||
// The box leans toward the same end of the line in the effect space, which is the major axis's near end in flipped pixels
|
|
||||||
let flipped = MotionBlurShear::new(0., 11., DMat2::from_diagonal(DVec2::new(-1., 1.)), DVec2::ZERO).unwrap();
|
|
||||||
assert_eq!(flipped.box_span(), [-6.5, 5.5]);
|
|
||||||
assert_eq!(shear(180., 11.).box_span(), shear(0., 11.).box_span(), "opposite directions smear alike");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn opposite_directions_shear_alike_even_along_diagonals() {
|
|
||||||
for (angle, opposite) in [(0., 180.), (30., -150.), (45., -135.), (-45., 135.)] {
|
|
||||||
let (forward, backward) = (shear(angle, 10.), shear(opposite, 10.));
|
|
||||||
let boxes_match = forward.box_span().into_iter().zip(backward.box_span()).all(|(forward, backward)| (forward - backward).abs() < 1e-12);
|
|
||||||
assert_eq!(forward.vertical, backward.vertical, "lines at {angle} and {opposite} degrees run along different axes");
|
|
||||||
assert!((forward.slope - backward.slope).abs() < 1e-12, "lines at {angle} and {opposite} degrees slant differently");
|
|
||||||
assert!(boxes_match, "lines at {angle} and {opposite} degrees have different boxes");
|
|
||||||
}
|
|
||||||
|
|
||||||
// For PSD interop, whole-pixel diagonal lines run along x in either direction
|
|
||||||
for psd_angle in [45, -135] {
|
|
||||||
let (angle, distance) = graphic_types::resampling::motion_blur_from_psd(psd_angle, 11.);
|
|
||||||
assert!(!shear(angle, distance).vertical, "PSD's line at {psd_angle} degrees runs along y");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pixels turned a quarter, with or without rounding, put diagonals along the pixel axis the effect space's x turns onto
|
|
||||||
for turn in [DMat2::from_angle(std::f64::consts::FRAC_PI_2), DMat2::from_cols(DVec2::Y, -DVec2::X)] {
|
|
||||||
for angle in [45., -45., 135., -135.] {
|
|
||||||
let vertical = MotionBlurShear::new(angle, 10., turn, DVec2::ZERO).is_some_and(|turned| turned.vertical);
|
|
||||||
assert!(vertical, "a line at {angle} degrees through pixels turned by {turn} runs along x");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn huge_motion_blurs_spread_their_samples_out() {
|
|
||||||
let shear = shear(0., 5000.);
|
|
||||||
let [start, end] = shear.box_span();
|
|
||||||
assert!((end - start) / shear.stride() <= MAX_MOTION_BLUR_SAMPLES);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn negative_distances_smear_as_positive_ones_do() {
|
|
||||||
use graphic_types::EffectOperation;
|
|
||||||
|
|
||||||
// Through turned and unevenly scaled pixels, measured from an anchor off their corner
|
|
||||||
let lengths_to_pixels = DMat2::from_angle(0.3) * DMat2::from_diagonal(DVec2::new(1.5, 0.8));
|
|
||||||
let anchor = DVec2::new(3.2, -1.);
|
|
||||||
let blur = |angle, distance| EffectOperation::MotionBlur { angle, distance, gamma: false };
|
|
||||||
for (angle, distance) in [(0., 12.), (30., 7.5), (-70., 90.)] {
|
|
||||||
let shears = [distance, -distance].map(|distance| MotionBlurShear::new(angle, distance, lengths_to_pixels, anchor));
|
|
||||||
assert_eq!(shears[0], shears[1], "lines {distance} long at {angle} degrees shear differently");
|
|
||||||
|
|
||||||
assert!(!blur(angle, -distance).changes_nothing());
|
|
||||||
assert_eq!(blur(angle, -distance).reach(), blur(angle, distance).reach());
|
|
||||||
}
|
|
||||||
assert!(blur(0., 0.).changes_nothing());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn pixelation_tables_fit_the_cells_around_the_square_on_the_regions_longer_side() {
|
|
||||||
// A plane of 100 by 100 pixels in a frame stretched to 100 by 10^9 units, so cells 2 units across span 50 columns and 5 × 10^8 rows of cells, nearly all holding no pixel
|
|
||||||
let frame = EffectFrame::new(DAffine2::from_scale(DVec2::new(100., 1e9)), DAffine2::from_scale(DVec2::new(1., 1e-7))).unwrap();
|
|
||||||
let cells = PixelateCells::new(2., DVec2::ZERO, &frame, 100, 100);
|
|
||||||
assert!(!pixelation_table_fits(cells.count, 1, 100, 100), "the budget holds all {:?} cells around the plane", cells.count);
|
|
||||||
|
|
||||||
// A strip 4000 by 4 pixels within a frame turned an eighth, so cells 2 units across span about the square on its length
|
|
||||||
let (width, height) = (4000, 4);
|
|
||||||
let placement = DAffine2::from_translation(DVec2::new(2000., 2.))
|
|
||||||
* DAffine2::from_angle(std::f64::consts::FRAC_PI_4)
|
|
||||||
* DAffine2::from_translation(DVec2::splat(-3000.))
|
|
||||||
* DAffine2::from_scale(DVec2::splat(6000.));
|
|
||||||
let frame = EffectFrame::new(placement, DAffine2::IDENTITY).unwrap();
|
|
||||||
let cells = PixelateCells::new(2., DVec2::ZERO, &frame, width, height);
|
|
||||||
assert!(
|
|
||||||
pixelation_table_fits(cells.count, 1, width, height),
|
|
||||||
"the budget leaves out the {:?} cells around the strip",
|
|
||||||
cells.count
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,928 @@
|
|||||||
|
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||||
|
|
||||||
|
use crate::effect_kernels::{BlurKernel, Plane};
|
||||||
|
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||||
|
use graphic_types::effects::spans_along_axes;
|
||||||
|
use graphic_types::filters::{
|
||||||
|
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||||
|
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||||
|
};
|
||||||
|
use graphic_types::generator::pcg3d;
|
||||||
|
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
|
||||||
|
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||||
|
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||||
|
pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation: &EffectOperation, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||||
|
let document_to_pixels = pixels_to_effect.matrix2.inverse();
|
||||||
|
if let Some(convolution) = operation.convolution() {
|
||||||
|
return convolve(&plane, full.unwrap_or(&plane), &convolution, document_to_pixels);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||||
|
let sharpening = sharpening.map(|[amount, threshold]| (amount as f32, threshold as f32));
|
||||||
|
return unsharp_mask(&plane, full.unwrap_or(&plane), blur, sharpening, document_to_pixels);
|
||||||
|
}
|
||||||
|
|
||||||
|
match *operation {
|
||||||
|
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
|
||||||
|
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
|
||||||
|
EffectOperation::Speckle {
|
||||||
|
amount,
|
||||||
|
distribution,
|
||||||
|
monochromatic,
|
||||||
|
seed,
|
||||||
|
} => speckle(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||||
|
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
|
||||||
|
_ => plane,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole-pixel shifts, nearest first, that a faint pixel looks along for a visible one within `reach` document pixels, measured through `document_to_pixels`. O(reach² log reach).
|
||||||
|
pub fn pixel_fill_shifts(reach: f64, document_to_pixels: DMat2) -> Vec<[isize; 2]> {
|
||||||
|
let mut seen = std::collections::HashSet::new();
|
||||||
|
let pixel_shift = |[x, y]: [i32; 2]| (document_to_pixels * DVec2::new(x as f64, y as f64)).round();
|
||||||
|
(fill_shifts(reach.ceil() as i32).into_iter().map(pixel_shift))
|
||||||
|
.map(|shift| [shift.x as isize, shift.y as isize])
|
||||||
|
.filter(|&shift| seen.insert(shift))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each pixel's straight color, as the filters read it, with an alpha of 1 where there is one: its own if it's visible in the `full`-strength content, otherwise that of the first visible pixel along `shifts`,
|
||||||
|
/// or failing that its own if it has any coverage. O(width × height × shifts) for the faint pixels.
|
||||||
|
pub(crate) fn visible_colors(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, shifts: &[[isize; 2]]) -> Plane<[f32; 4]> {
|
||||||
|
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||||
|
let covered = |x: isize, y: isize, least_alpha: f32| {
|
||||||
|
let index = (x >= 0 && y >= 0 && x < columns && y < rows).then_some((y * columns + x) as usize)?;
|
||||||
|
let [red, green, blue, alpha] = plane.data[index];
|
||||||
|
(alpha > 0. && full.data[index][3] >= least_alpha).then(|| [red / alpha, green / alpha, blue / alpha, 1.])
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut colors = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut colors.data, plane.width, |y, row| {
|
||||||
|
for (x, color) in row.iter_mut().enumerate() {
|
||||||
|
let (x, y) = (x as isize, y as isize);
|
||||||
|
let nearest_visible = shifts.iter().find_map(|&[shift_x, shift_y]| covered(x + shift_x, y + shift_y, VISIBLE_ALPHA));
|
||||||
|
*color = nearest_visible.or_else(|| covered(x, y, 0.)).unwrap_or_default();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
colors
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A weighted copy of a plane shifted by a fixed fraction of a pixel, read as the four pixels around each position with their bilinear weights.
|
||||||
|
struct BilinearTap {
|
||||||
|
/// The whole-pixel part of the shift.
|
||||||
|
whole: [isize; 2],
|
||||||
|
/// The bilinear weights of the pixels at the whole shift and one past it along x, then the same one past it along y.
|
||||||
|
bilinear: [f32; 4],
|
||||||
|
weight: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BilinearTap {
|
||||||
|
fn new(shift: DVec2, weight: f32) -> Self {
|
||||||
|
let whole = shift.floor();
|
||||||
|
let [x, y] = (shift - whole).as_vec2().to_array();
|
||||||
|
Self {
|
||||||
|
whole: [whole.x as isize, whole.y as isize],
|
||||||
|
bilinear: [(1. - x) * (1. - y), x * (1. - y), (1. - x) * y, x * y],
|
||||||
|
weight,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weighted color between the four `corners` (straight colors with an alpha of 1 where there is one), interpolated among those with a color, matching the GPU's `color_between`.
|
||||||
|
/// Leaving out those without one continues the colors past the edges between pixels too, rather than fading toward black.
|
||||||
|
fn weighted(&self, corners: [[f32; 4]; 4]) -> [f32; 3] {
|
||||||
|
let (mut color, mut covered) = ([0.; 3], 0.);
|
||||||
|
for (corner, bilinear) in corners.into_iter().zip(self.bilinear) {
|
||||||
|
(0..3).for_each(|channel| color[channel] += corner[channel] * bilinear);
|
||||||
|
covered += corner[3] * bilinear;
|
||||||
|
}
|
||||||
|
if covered > 0. { color.map(|channel| channel / covered * self.weight) } else { [0.; 3] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The opaque colors a filter reads, as its surroundings describe, with the color it reads beyond their edges.
|
||||||
|
struct SurroundedColors {
|
||||||
|
colors: Plane<[f32; 4]>,
|
||||||
|
beyond: [f32; 4],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SurroundedColors {
|
||||||
|
/// The colors of the premultiplied pixels that a filter reading within `reach` document pixels sees, measured through `document_to_pixels`, those visible judged by the `full`-strength content.
|
||||||
|
fn new(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, surroundings: Surroundings, reach: f64, document_to_pixels: DMat2) -> Self {
|
||||||
|
match surroundings {
|
||||||
|
Surroundings::Continued => Self {
|
||||||
|
colors: visible_colors(plane, full, &pixel_fill_shifts(reach, document_to_pixels)),
|
||||||
|
beyond: [0.; 4],
|
||||||
|
},
|
||||||
|
Surroundings::Matted(gray) => {
|
||||||
|
let gray = gray as f32;
|
||||||
|
let over_gray = |channel: f32, alpha: f32| channel + gray * (1. - alpha);
|
||||||
|
Self {
|
||||||
|
colors: plane.map(|[red, green, blue, alpha]| [over_gray(red, alpha), over_gray(green, alpha), over_gray(blue, alpha), 1.]),
|
||||||
|
beyond: [gray, gray, gray, 1.],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The coverage of the premultiplied pixels in each channel, read with none beyond the plane's edges and every pixel counted when reading between them.
|
||||||
|
fn coverage(plane: &Plane<[f32; 4]>) -> Self {
|
||||||
|
Self {
|
||||||
|
colors: plane.map(|[.., alpha]| [alpha, alpha, alpha, 1.]),
|
||||||
|
beyond: [0., 0., 0., 1.],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(&self, x: isize, y: isize) -> [f32; 4] {
|
||||||
|
let (columns, rows) = (self.colors.width as isize, self.colors.height as isize);
|
||||||
|
match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||||
|
true => self.colors.data[(y * columns + x) as usize],
|
||||||
|
false => self.beyond,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The weighted sum of the colors that the `taps` read around a pixel.
|
||||||
|
fn sum(&self, x: isize, y: isize, taps: &[BilinearTap]) -> [f32; 3] {
|
||||||
|
let mut sum = [0.; 3];
|
||||||
|
for tap in taps {
|
||||||
|
let [shift_x, shift_y] = [x + tap.whole[0], y + tap.whole[1]];
|
||||||
|
let corners = [
|
||||||
|
self.at(shift_x, shift_y),
|
||||||
|
self.at(shift_x + 1, shift_y),
|
||||||
|
self.at(shift_x, shift_y + 1),
|
||||||
|
self.at(shift_x + 1, shift_y + 1),
|
||||||
|
];
|
||||||
|
let weighted = tap.weighted(corners);
|
||||||
|
(0..3).for_each(|channel| sum[channel] += weighted[channel]);
|
||||||
|
}
|
||||||
|
sum
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A filtered pixel as a premultiplied color: its straight `colors` given the coverage of `alpha`, or for matted surroundings, colors filtered over the gray and lifted back off it within that coverage.
|
||||||
|
fn uncovered(colors: [f32; 3], alpha: f32, surroundings: Surroundings) -> [f32; 4] {
|
||||||
|
let [red, green, blue] = match surroundings {
|
||||||
|
Surroundings::Continued => colors.map(|channel| channel.clamp(0., 1.) * alpha),
|
||||||
|
Surroundings::Matted(gray) => colors.map(|channel| (channel.clamp(0., 1.) - gray as f32 * (1. - alpha)).max(0.).min(alpha)),
|
||||||
|
};
|
||||||
|
[red, green, blue, alpha]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The premultiplied pixels with each one's color replaced by the weighted sum `convolution` describes, with its shifts measured through `document_to_pixels`.
|
||||||
|
/// It reads the colors as the convolution's surroundings describe, those visible judged by the `full`-strength content, then divides, raises, and clamps the sum, keeping each pixel's coverage unless it weighs that too. O(width × height × taps).
|
||||||
|
pub fn convolve(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, convolution: &Convolution, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
let taps: Vec<BilinearTap> = convolution
|
||||||
|
.taps
|
||||||
|
.iter()
|
||||||
|
.map(|&(shift, weight)| BilinearTap::new(document_to_pixels * shift, (weight / convolution.divisor) as f32))
|
||||||
|
.collect();
|
||||||
|
let offset = convolution.offset as f32;
|
||||||
|
let colors = SurroundedColors::new(plane, full, convolution.surroundings, convolution.reach(), document_to_pixels);
|
||||||
|
let coverage = convolution.weighs_coverage.then(|| SurroundedColors::coverage(plane));
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let (x, y) = (x as isize, y as isize);
|
||||||
|
let alpha = match &coverage {
|
||||||
|
Some(coverage) => coverage.sum(x, y, &taps)[0].clamp(0., 1.),
|
||||||
|
None => plane.data[y as usize * plane.width + x as usize][3],
|
||||||
|
};
|
||||||
|
if alpha <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let sum = colors.sum(x, y, &taps).map(|channel| channel + offset);
|
||||||
|
*pixel = uncovered(sum, alpha, convolution.surroundings);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each pixel's share of the full-strength content's coverage that the faded fill left, which a filter sharpening the coverage fades its result by. O(width × height).
|
||||||
|
pub fn fill_shares(full: &Plane<[f32; 4]>, filled: &Plane<[f32; 4]>) -> Plane<f32> {
|
||||||
|
full.zip(filled, |full, filled| if full[3] > 0. { (filled[3] / full[3]).min(1.) } else { 0. })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fill's filtered straight colors at the coverage of the full-strength content's filtered result, scaled by each pixel's share of it from [`fill_shares`],
|
||||||
|
/// so the fill fades the result as if after the filter. O(width × height).
|
||||||
|
pub fn faded_by_shares(filtered_filled: &Plane<[f32; 4]>, filtered_full: &Plane<[f32; 4]>, shares: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||||
|
let straight = |[red, green, blue, alpha]: [f32; 4]| [red / alpha, green / alpha, blue / alpha];
|
||||||
|
let colors = filtered_filled.zip(filtered_full, |filled, full| {
|
||||||
|
let [red, green, blue] = if filled[3] > 0. {
|
||||||
|
straight(filled)
|
||||||
|
} else if full[3] > 0. {
|
||||||
|
straight(full)
|
||||||
|
} else {
|
||||||
|
[0.; 3]
|
||||||
|
};
|
||||||
|
[red, green, blue, full[3]]
|
||||||
|
});
|
||||||
|
colors.zip(shares, |[red, green, blue, full_alpha], share| {
|
||||||
|
let alpha = full_alpha * share;
|
||||||
|
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The fill's straight colors at the coverage of the full-strength content, or where the fill left none, the full-strength content's own colors.
|
||||||
|
/// A filter reading colors over white (like a halftone) reads these undimmed by the fill, then [`faded_by_shares`] fades its result. O(width × height).
|
||||||
|
pub fn at_full_coverage(filled: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||||
|
let straight = |[red, green, blue, alpha]: [f32; 4]| [red / alpha, green / alpha, blue / alpha];
|
||||||
|
filled.zip(full, |filled, full| {
|
||||||
|
let [red, green, blue] = if filled[3] > 0. {
|
||||||
|
straight(filled)
|
||||||
|
} else if full[3] > 0. {
|
||||||
|
straight(full)
|
||||||
|
} else {
|
||||||
|
[0.; 3]
|
||||||
|
};
|
||||||
|
[red * full[3], green * full[3], blue * full[3], full[3]]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, each straight color and the coverage sharpened against the `blur` around it, measured through `document_to_pixels`, by the `amount` and `threshold` fractions [`unsharp_change`] takes.
|
||||||
|
/// The colors are compared against the average of those visible in the `full`-strength content alone (or where too few are, the pixel's own color), so the content's surroundings take no part.
|
||||||
|
/// With no amount and threshold, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept. O(width × height) per blur pass.
|
||||||
|
pub fn unsharp_mask(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, blur: UnsharpBlur, sharpening: Option<(f32, f32)>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
// The visible colors made opaque among the others left out, so dividing their blur by its alpha averages the visible colors alone
|
||||||
|
let visible = plane.zip(full, |[red, green, blue, alpha], [.., full_alpha]| match alpha > 0. && full_alpha >= VISIBLE_ALPHA {
|
||||||
|
true => [red / alpha, green / alpha, blue / alpha, 1.],
|
||||||
|
false => [0.; 4],
|
||||||
|
});
|
||||||
|
|
||||||
|
// A high pass keeps the coverage, so only unsharp masking blurs it
|
||||||
|
let (blurred_colors, blurred_coverage) = match blur {
|
||||||
|
UnsharpBlur::Gaussian(radius) => {
|
||||||
|
let sigma = radius.max(0.) * spans_along_axes(document_to_pixels);
|
||||||
|
let kernels = (BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y });
|
||||||
|
let blurred_coverage = sharpening.is_some().then(|| plane.map(|[.., alpha]| alpha).blurred(kernels.0, kernels.1));
|
||||||
|
(visible.blurred(kernels.0, kernels.1), blurred_coverage)
|
||||||
|
}
|
||||||
|
UnsharpBlur::EdgeNeighbors => {
|
||||||
|
let blurred_coverage = sharpening.is_some().then(|| neighbors_average(plane, document_to_pixels).map(|[.., alpha]| alpha));
|
||||||
|
(neighbors_average(&visible, document_to_pixels), blurred_coverage)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let gains = (blur == UnsharpBlur::EdgeNeighbors).then(|| edge_gains(plane, full, document_to_pixels));
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let index = y * plane.width + x;
|
||||||
|
let [red, green, blue, alpha] = plane.data[index];
|
||||||
|
if alpha <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where too little of the blur lands on visible colors to know their average, the pixel eases into being compared against its own color.
|
||||||
|
// Edges Only moves each channel only its gain's share of the way toward the average.
|
||||||
|
let own = [red / alpha, green / alpha, blue / alpha, alpha];
|
||||||
|
let blurred = blurred_colors.data[index];
|
||||||
|
let weight = average_weight(blurred[3]);
|
||||||
|
let gain = gains.as_ref().map_or([1.; 4], |gains| gains.data[index]);
|
||||||
|
let average: [f32; 3] = std::array::from_fn(|channel| {
|
||||||
|
if weight > 0. {
|
||||||
|
own[channel] + (blurred[channel] / blurred[3] - own[channel]) * weight * gain[channel]
|
||||||
|
} else {
|
||||||
|
own[channel]
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let coverage_average = blurred_coverage.as_ref().map_or(alpha, |blurred_coverage| alpha + (blurred_coverage.data[index] - alpha) * gain[3]);
|
||||||
|
let difference: [f32; 4] = std::array::from_fn(|channel| own[channel] - if channel == 3 { coverage_average } else { average[channel] });
|
||||||
|
|
||||||
|
let sharpened: [f32; 4] = match sharpening {
|
||||||
|
Some((amount, threshold)) => std::array::from_fn(|channel| (own[channel] + unsharp_change(difference[channel], amount, threshold)).clamp(0., 1.)),
|
||||||
|
None => std::array::from_fn(|channel| if channel == 3 { alpha } else { (difference[channel] + HIGH_PASS_GRAY).clamp(0., 1.) }),
|
||||||
|
};
|
||||||
|
let alpha = sharpened[3];
|
||||||
|
*pixel = [sharpened[0] * alpha, sharpened[1] * alpha, sharpened[2] * alpha, alpha];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The average of each pixel's four nearest neighbors ([`SHARPEN_NEIGHBORS`], measured through `document_to_pixels`) in every channel, read between pixels with none beyond the plane's edges,
|
||||||
|
/// as Edges Only compares against, matching the GPU's `neighbors_average`. O(width × height).
|
||||||
|
fn neighbors_average(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
let taps = SHARPEN_NEIGHBORS.map(|shift| BilinearTap::new(document_to_pixels * shift, 0.25));
|
||||||
|
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||||
|
let at = |x: isize, y: isize| match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||||
|
true => plane.data[(y * columns + x) as usize],
|
||||||
|
false => [0.; 4],
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut average = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut average.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
for tap in &taps {
|
||||||
|
let [x, y] = [x as isize + tap.whole[0], y as isize + tap.whole[1]];
|
||||||
|
let corners = [at(x, y), at(x + 1, y), at(x, y + 1), at(x + 1, y + 1)];
|
||||||
|
for (corner, bilinear) in corners.into_iter().zip(tap.bilinear) {
|
||||||
|
(0..4).for_each(|channel| pixel[channel] += corner[channel] * bilinear * tap.weight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
average
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the share of its change Edges Only makes in each channel of each pixel, the [`edge_gain`] of the channel's Sobel gradient there, matching the GPU's `edge_gains`.
|
||||||
|
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it. O(width × height).
|
||||||
|
fn edge_gains(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
// A faint pixel the gradient reads finds its nearest visible color within the square of a pixel around it
|
||||||
|
let colors = SurroundedColors::new(plane, full, Surroundings::Continued, 1., document_to_pixels);
|
||||||
|
let coverage = SurroundedColors::coverage(plane);
|
||||||
|
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||||
|
let (across, down) = (taps(0), taps(1));
|
||||||
|
|
||||||
|
let mut gains = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut gains.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||||
|
for (x, gain) in row.iter_mut().enumerate() {
|
||||||
|
let (x, y) = (x as isize, y as isize);
|
||||||
|
let [colors_across, colors_down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||||
|
let [coverage_across, coverage_down] = [coverage.sum(x, y, &across)[0], coverage.sum(x, y, &down)[0]];
|
||||||
|
|
||||||
|
*gain = std::array::from_fn(|channel| match channel {
|
||||||
|
3 => edge_gain(coverage_across.hypot(coverage_down)),
|
||||||
|
_ => edge_gain(colors_across[channel].hypot(colors_down[channel])),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
gains
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, each channel darkened by how steeply it changes, the length of its Sobel gradient, so edges show dark over white.
|
||||||
|
/// The content is matted over white, so its silhouette shows as an edge too. O(width × height).
|
||||||
|
pub fn find_edges(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
let surroundings = Surroundings::Matted(1.);
|
||||||
|
let colors = SurroundedColors::new(plane, plane, surroundings, 1., document_to_pixels);
|
||||||
|
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||||
|
let (across, down) = (taps(0), taps(1));
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let alpha = plane.data[y * plane.width + x][3];
|
||||||
|
if alpha <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (x, y) = (x as isize, y as isize);
|
||||||
|
let [across, down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||||
|
let edges = std::array::from_fn(|channel| 1. - across[channel].hypot(down[channel]));
|
||||||
|
*pixel = uncovered(edges, alpha, surroundings);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, each pixel's color is the lightest in the square of `radius` document pixels around it (or with `maximum` false, the darkest), and its coverage the opposite extreme.
|
||||||
|
/// The maximum spreads every covered pixel's straight color. The minimum spreads the darkest colors matted over white, lifted back off within the grown coverage, so faint pixels darken only as much as they cover.
|
||||||
|
/// A fractional radius mixes the whole radii around it. O(width × height).
|
||||||
|
pub fn neighborhood_extreme(plane: &Plane<[f32; 4]>, radius: f64, maximum: bool, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||||
|
let spans = spans_along_axes(document_to_pixels);
|
||||||
|
let ([near_x, far_x], fraction) = neighborhood_radii(radius, spans.x);
|
||||||
|
let ([near_y, far_y], _) = neighborhood_radii(radius, spans.y);
|
||||||
|
if near_x.max(near_y) == 0 && (fraction <= 0. || far_x.max(far_y) == 0) {
|
||||||
|
return plane.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Colors and coverage in the form the filter takes the extremes of, with uncovered pixels' colors (and those beyond the edges) at the identity of their extreme
|
||||||
|
let (prepared, beyond) = match maximum {
|
||||||
|
true => (
|
||||||
|
plane.map(|[red, green, blue, alpha]| match alpha > 0. {
|
||||||
|
true => [red / alpha, green / alpha, blue / alpha, alpha],
|
||||||
|
false => [0.; 4],
|
||||||
|
}),
|
||||||
|
[0.; 4],
|
||||||
|
),
|
||||||
|
false => (
|
||||||
|
plane.map(|[red, green, blue, alpha]| [red + 1. - alpha, green + 1. - alpha, blue + 1. - alpha, alpha]),
|
||||||
|
[1., 1., 1., 0.],
|
||||||
|
),
|
||||||
|
};
|
||||||
|
let extreme = move |first: [f32; 4], second: [f32; 4]| -> [f32; 4] {
|
||||||
|
std::array::from_fn(|channel| match (channel == 3) != maximum {
|
||||||
|
true => first[channel].max(second[channel]),
|
||||||
|
false => first[channel].min(second[channel]),
|
||||||
|
})
|
||||||
|
};
|
||||||
|
// Back to premultiplied colors, which for the minimum lifts white back off within the grown coverage
|
||||||
|
let premultiplied = move |[red, green, blue, alpha]: [f32; 4]| {
|
||||||
|
let channel = |channel: f32| match maximum {
|
||||||
|
true => channel * alpha,
|
||||||
|
false => (channel - (1. - alpha)).max(0.).min(alpha),
|
||||||
|
};
|
||||||
|
[channel(red), channel(green), channel(blue), alpha]
|
||||||
|
};
|
||||||
|
|
||||||
|
// The larger square's extremes grow from the smaller one's, as a square widened by another is the square of their radii summed
|
||||||
|
let near = extremes_in_squares(prepared, [near_x, near_y], beyond, extreme);
|
||||||
|
if fraction <= 0. {
|
||||||
|
return near.map(premultiplied);
|
||||||
|
}
|
||||||
|
let far = extremes_in_squares(near.clone(), [far_x - near_x, far_y - near_y], beyond, extreme);
|
||||||
|
near.zip(&far, |near, far| {
|
||||||
|
let (near, far) = (premultiplied(near), premultiplied(far));
|
||||||
|
std::array::from_fn(|channel| near[channel] + (far[channel] - near[channel]) * fraction as f32)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `extreme` of each rectangle reaching `across` and `down` pixels from each pixel, with `beyond` read past the edges, along the rows then the columns. O(width × height).
|
||||||
|
fn extremes_in_squares(plane: Plane<[f32; 4]>, [across, down]: [u32; 2], beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4] + Copy + Sync) -> Plane<[f32; 4]> {
|
||||||
|
let along_rows = |plane: Plane<[f32; 4]>, radius: u32| {
|
||||||
|
if radius == 0 {
|
||||||
|
return plane;
|
||||||
|
}
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
window_extremes(&plane.data[y * plane.width..(y + 1) * plane.width], row, radius as usize, beyond, extreme)
|
||||||
|
});
|
||||||
|
result
|
||||||
|
};
|
||||||
|
|
||||||
|
let plane = along_rows(plane, across);
|
||||||
|
match down {
|
||||||
|
0 => plane,
|
||||||
|
_ => along_rows(plane.transposed(), down).transposed(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `extreme` of each window of `2 × radius + 1` values along a row, with `beyond` read past its ends, by van Herk and Gil-Werman's blocks of extremes running from each block's start and to its end.
|
||||||
|
/// O(length) whatever the radius, since a window as wide as the row already holds all of it.
|
||||||
|
fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize, beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4]) {
|
||||||
|
let radius = radius.min(source.len());
|
||||||
|
let window = 2 * radius + 1;
|
||||||
|
let padded: Vec<[f32; 4]> = std::iter::repeat_n(beyond, radius).chain(source.iter().copied()).chain(std::iter::repeat_n(beyond, radius)).collect();
|
||||||
|
|
||||||
|
let mut from_start = padded.clone();
|
||||||
|
let mut to_end = padded.clone();
|
||||||
|
for index in 1..padded.len() {
|
||||||
|
if index % window != 0 {
|
||||||
|
from_start[index] = extreme(from_start[index - 1], padded[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for index in (0..padded.len() - 1).rev() {
|
||||||
|
if (index + 1) % window != 0 {
|
||||||
|
to_end[index] = extreme(to_end[index + 1], padded[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each window spans the end of one block and the start of the next
|
||||||
|
for (index, value) in target.iter_mut().enumerate() {
|
||||||
|
*value = extreme(to_end[index], from_start[index + window - 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||||
|
fn unit_interval(hash: u32) -> f32 {
|
||||||
|
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The three random values one field of the `seed` holds at a cell of the effect space.
|
||||||
|
pub(crate) fn field_values(cell: IVec2, seed: u32) -> [f32; 3] {
|
||||||
|
pcg3d([cell.x as u32, cell.y as u32, seed]).map(unit_interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The noise each of a pixel's colors takes before the amount scales it, averaged over the pixel's samples of the field: uniform from -1 to 1, or Gaussian with a deviation of 1 cut off at [`GAUSSIAN_NOISE_LIMIT`].
|
||||||
|
fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDistribution, monochromatic: bool, seed: i64) -> [f32; 3] {
|
||||||
|
let (offsets_seed, angles_seed) = (RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed));
|
||||||
|
|
||||||
|
let mut sum = [0.; 3];
|
||||||
|
let mut count = 0.;
|
||||||
|
for cell in sampling.sample_cells(pixel) {
|
||||||
|
let offsets = field_values(cell, offsets_seed);
|
||||||
|
let noise = match distribution {
|
||||||
|
NoiseDistribution::Uniform => offsets.map(|value| 2. * value - 1.),
|
||||||
|
// The Box-Muller transform of two uniform values into one with a normal distribution
|
||||||
|
NoiseDistribution::Gaussian => {
|
||||||
|
let angles = field_values(cell, angles_seed);
|
||||||
|
std::array::from_fn(|channel| ((-2. * offsets[channel].ln()).sqrt() * (std::f32::consts::TAU * angles[channel]).cos()).clamp(-GAUSSIAN_NOISE_LIMIT, GAUSSIAN_NOISE_LIMIT))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
(0..3).for_each(|channel| sum[channel] += noise[channel]);
|
||||||
|
count += 1.;
|
||||||
|
}
|
||||||
|
|
||||||
|
let average = sum.map(|channel| channel / count);
|
||||||
|
if monochromatic { [average[0]; 3] } else { average }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
|
||||||
|
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
|
||||||
|
pub fn speckle(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||||
|
let sampling = FieldSampling::new(pixels_to_effect);
|
||||||
|
let extent = noise_extent(amount, distribution) as f32;
|
||||||
|
let scale = (amount * sampling.deviation_scale) as f32;
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||||
|
if alpha <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let noise = noise_at(&sampling, [x, y], distribution, monochromatic, seed);
|
||||||
|
let noisy = |channel: f32, noise: f32| (channel / alpha + (noise * scale).clamp(-extent, extent)).clamp(0., 1.) * alpha;
|
||||||
|
*pixel = [noisy(red, noise[0]), noisy(green, noise[1]), noisy(blue, noise[2]), alpha];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, how much of a pixel Dissolve shows, from 0 to 1: the share of its samples passing the `opacity` (a fraction), and the threshold level from 0 to 254 its coverage must pass.
|
||||||
|
/// For pixels spanning more cells than they sample, the share deviates from the opacity less, as it would over them all.
|
||||||
|
fn dissolve_field(sampling: &FieldSampling, pixel: [usize; 2], opacity: f32, seed: i64) -> (f32, f32) {
|
||||||
|
let seed = RandomField::Dissolve.seed(seed);
|
||||||
|
|
||||||
|
let (mut shown, mut count) = (0., 0.);
|
||||||
|
for cell in sampling.sample_cells(pixel) {
|
||||||
|
shown += if field_values(cell, seed)[0] < opacity { 1. } else { 0. };
|
||||||
|
count += 1.;
|
||||||
|
}
|
||||||
|
let share = (opacity + (shown / count - opacity) * sampling.deviation_scale as f32).clamp(0., 1.);
|
||||||
|
|
||||||
|
let threshold = (field_values(sampling.center_cell(pixel), seed)[1] * 255.).floor();
|
||||||
|
(share, threshold)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// For PSD interop, the content shown fully opaque where the `opacity` (a fraction) and the coverage each pass a threshold of their own, random for each cell of the effect space, and hidden elsewhere.
|
||||||
|
/// The thresholds are fixed to those cells, which `pixels_to_effect` places the plane's pixels among, and pixels spanning several show the share of them passing. O(width × height × samples per pixel).
|
||||||
|
pub fn dissolve(plane: &Plane<[f32; 4]>, opacity: f64, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||||
|
let sampling = FieldSampling::new(pixels_to_effect);
|
||||||
|
let opacity = opacity as f32;
|
||||||
|
|
||||||
|
let mut result = Plane::new(plane.width, plane.height);
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate() {
|
||||||
|
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||||
|
if alpha <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The coverage passes a threshold level when it's at least one 8-bit level above it, a half level counting as the level below as browsers truncate it
|
||||||
|
let (share, threshold) = dissolve_field(&sampling, [x, y], opacity, seed);
|
||||||
|
let shown = if alpha * 255. > threshold + 0.5 { share } else { 0. };
|
||||||
|
*pixel = [red / alpha * shown, green / alpha * shown, blue / alpha * shown, shown];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn plane(width: usize, height: usize, data: Vec<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||||
|
Plane { width, height, data }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn kernels_of_any_shape_read_around_their_center() {
|
||||||
|
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||||
|
|
||||||
|
// An even row centers on its second weight, so its first reads the pixel to the left, moving the colors right
|
||||||
|
let line = plane(3, 1, vec![white, black, black]);
|
||||||
|
let even = convolve(&line, &line, &Convolution::custom(&[1., 0.], 2, 1., 0.), DMat2::IDENTITY);
|
||||||
|
assert_eq!(&even.data[1..], &[white, black]);
|
||||||
|
|
||||||
|
// A column reads the pixels above and below
|
||||||
|
let column = plane(1, 3, vec![white, black, black]);
|
||||||
|
let down = convolve(&column, &column, &Convolution::custom(&[1., 0., 0.], 1, 1., 0.), DMat2::IDENTITY);
|
||||||
|
assert_eq!(&down.data[1..], &[white, black]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kernel_of_one_weight_shifts_the_colors_within_the_coverage() {
|
||||||
|
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||||
|
let line = plane(4, 1, vec![black, white, black, [0.; 4]]);
|
||||||
|
|
||||||
|
// The weight right of the center reads the pixel to the right, moving the colors left
|
||||||
|
let right = [0., 0., 0., 0., 0., 1., 0., 0., 0.];
|
||||||
|
let shifted = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::IDENTITY);
|
||||||
|
assert_eq!(shifted.data, vec![white, black, black, [0.; 4]]);
|
||||||
|
|
||||||
|
// A shift of half a pixel splits between two
|
||||||
|
let halved = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(0.5)));
|
||||||
|
assert_eq!(halved.data, vec![[0.5, 0.5, 0.5, 1.], [0.5, 0.5, 0.5, 1.], black, [0.; 4]]);
|
||||||
|
|
||||||
|
// A shift past the edge reads between the colors continued past it and none further, which it leaves out rather than darkening toward
|
||||||
|
let edge = plane(5, 1, vec![white, white, [0.; 4], [0.; 4], [0.; 4]]);
|
||||||
|
let past_edge = convolve(&edge, &edge, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(1.25)));
|
||||||
|
assert_eq!(past_edge.data[1], white);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sums_are_divided_raised_and_clamped() {
|
||||||
|
let gray = [0.25, 0.25, 0.25, 0.5];
|
||||||
|
let line = plane(3, 1, vec![gray; 3]);
|
||||||
|
|
||||||
|
// Doubled to full brightness, then raised past it
|
||||||
|
let raised = convolve(&line, &line, &Convolution::custom(&[2.], 1, 1., 255. / 4.), DMat2::IDENTITY);
|
||||||
|
assert_eq!(raised.data[1], [0.5; 4]);
|
||||||
|
|
||||||
|
// The difference across a flat color is nothing, which the offset lifts to middle gray
|
||||||
|
let difference = convolve(&line, &line, &Convolution::custom(&[-1., 0., 1.], 3, 2., 255. / 2.), DMat2::IDENTITY);
|
||||||
|
assert_eq!(difference.data[1], [0.25, 0.25, 0.25, 0.5]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn colors_continue_past_the_edges_from_the_nearest_visible_pixel() {
|
||||||
|
let red = [1., 0., 0., 1.];
|
||||||
|
let faint_blue = [0., 0., 0.01, 0.01];
|
||||||
|
let line = plane(5, 1, vec![[0.; 4], [0.; 4], red, faint_blue, [0.; 4]]);
|
||||||
|
|
||||||
|
// Averaging three neighbors at the edge reads the red beyond it rather than black, leaving the red as it is
|
||||||
|
let averaged = convolve(&line, &line, &Convolution::custom(&[1., 1., 1.], 3, 3., 0.), DMat2::IDENTITY);
|
||||||
|
assert!((averaged.data[2][0] - 1.).abs() < 1e-6, "{:?}", averaged.data[2]);
|
||||||
|
// The faint pixel reads red rather than its own blue, keeping its own coverage
|
||||||
|
let faint = averaged.data[3];
|
||||||
|
assert!(faint[0] > 0. && faint[2] == 0. && faint[3] == 0.01, "{faint:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A white square of `inner` pixels in the middle of a transparent square of `outer` pixels.
|
||||||
|
fn white_square(outer: usize, inner: std::ops::Range<usize>) -> Plane<[f32; 4]> {
|
||||||
|
let mut square = Plane::new(outer, outer);
|
||||||
|
for y in inner.clone() {
|
||||||
|
square.data[y * outer + inner.start..y * outer + inner.end].fill([1.; 4]);
|
||||||
|
}
|
||||||
|
square
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emboss_grays_flat_colors_and_shows_the_silhouette_in_relief() {
|
||||||
|
let square = white_square(16, 4..12);
|
||||||
|
let embossed = convolve(&square, &square, &Convolution::emboss(0., 2., 100.), DMat2::IDENTITY);
|
||||||
|
let at = |x: usize| embossed.data[8 * 16 + x];
|
||||||
|
|
||||||
|
// The inside is flat, so it's middle gray
|
||||||
|
assert_eq!(at(8), [0.5, 0.5, 0.5, 1.]);
|
||||||
|
// Lit from the right, the right edge's white falls off to the gray beyond it, and the left edge rises from it
|
||||||
|
assert!(at(11)[0] < 0.5 && at(4)[0] > 0.5, "{:?} {:?}", at(11), at(4));
|
||||||
|
assert_eq!(at(2), [0.; 4], "nothing outside");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn find_edges_whitens_flat_colors_and_darkens_the_silhouette() {
|
||||||
|
let square = white_square(16, 4..12);
|
||||||
|
let edges = find_edges(&square, DMat2::IDENTITY);
|
||||||
|
let at = |x: usize, y: usize| edges.data[y * 16 + x];
|
||||||
|
|
||||||
|
assert_eq!(at(8, 8), [1.; 4]);
|
||||||
|
// Over white, the white square's edge has no contrast, so it stays white
|
||||||
|
assert_eq!(at(4, 8), [1.; 4]);
|
||||||
|
|
||||||
|
// A black square's edge against the white it's matted over is dark
|
||||||
|
let black = white_square(16, 4..12).map(|[_, _, _, alpha]| [0., 0., 0., alpha]);
|
||||||
|
let edges = find_edges(&black, DMat2::IDENTITY);
|
||||||
|
assert_eq!(edges.data[8 * 16 + 4], [0., 0., 0., 1.]);
|
||||||
|
assert_eq!(edges.data[8 * 16 + 8], [1.; 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn neighborhood_maximum_spreads_light_colors_as_coverage_shrinks() {
|
||||||
|
let mut square = white_square(16, 2..14);
|
||||||
|
square.data[8 * 16 + 8] = [0., 0., 0., 1.];
|
||||||
|
|
||||||
|
let maximum = neighborhood_extreme(&square, 1., true, DMat2::IDENTITY);
|
||||||
|
assert_eq!(maximum.data[8 * 16 + 8], [1.; 4], "the dark pixel takes its lighter neighbors' color");
|
||||||
|
assert_eq!(maximum.data[8 * 16 + 2], [0.; 4], "the coverage shrinks by the radius");
|
||||||
|
assert_eq!(maximum.data[8 * 16 + 3], [1.; 4]);
|
||||||
|
|
||||||
|
let minimum = neighborhood_extreme(&square, 1., false, DMat2::IDENTITY);
|
||||||
|
assert_eq!(minimum.data[9 * 16 + 9], [0., 0., 0., 1.], "the dark pixel spreads");
|
||||||
|
assert_eq!(minimum.data[8 * 16 + 1], [1.; 4], "the coverage grows by the radius, with the colors beyond taking no part");
|
||||||
|
|
||||||
|
// Half a radius more mixes halfway toward the next
|
||||||
|
let between = neighborhood_extreme(&square, 1.5, false, DMat2::IDENTITY);
|
||||||
|
assert_eq!(between.data[9 * 16 + 9], [0., 0., 0., 1.]);
|
||||||
|
assert_eq!(between.data[10 * 16 + 10], [0.5, 0.5, 0.5, 1.]);
|
||||||
|
assert_eq!(between.data[8 * 16], [0.5; 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn neighborhood_extremes_keep_faint_colors_and_a_zero_radius_changes_nothing() {
|
||||||
|
// A faint red block keeps its color at its own coverage, rather than taking either extreme's identity
|
||||||
|
let mut faint = plane(7, 7, vec![[0.; 4]; 49]);
|
||||||
|
for y in 1..6 {
|
||||||
|
faint.data[y * 7 + 1..y * 7 + 6].fill([0.04, 0., 0., 0.04]);
|
||||||
|
}
|
||||||
|
for maximum in [true, false] {
|
||||||
|
let extreme = neighborhood_extreme(&faint, 1., maximum, DMat2::IDENTITY);
|
||||||
|
let [red, green, blue, alpha] = extreme.data[3 * 7 + 3];
|
||||||
|
assert!(
|
||||||
|
(red - 0.04).abs() < 1e-6 && green.abs() < 1e-6 && blue.abs() < 1e-6 && (alpha - 0.04).abs() < 1e-6,
|
||||||
|
"{:?}",
|
||||||
|
extreme.data[3 * 7 + 3]
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(neighborhood_extreme(&faint, 0., maximum, DMat2::IDENTITY).data, faint.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
// At twice the zoom, a radius of one document pixel reaches two pixels
|
||||||
|
let mut dot = plane(9, 9, vec![[1.; 4]; 81]);
|
||||||
|
dot.data[4 * 9 + 4] = [0., 0., 0., 1.];
|
||||||
|
let spread = neighborhood_extreme(&dot, 1., false, DMat2::from_diagonal(DVec2::splat(2.)));
|
||||||
|
assert_eq!(spread.data[2 * 9 + 6], [0., 0., 0., 1.]);
|
||||||
|
assert_eq!(spread.data[9 + 4], [1.; 4]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_fill_fades_sharpened_coverage_evenly() {
|
||||||
|
// Sharpening the faded square alone would overshoot at its edge, where the full-strength square's clamp at full coverage hides it
|
||||||
|
let square = white_square(16, 4..12);
|
||||||
|
let faded = square.map(|pixel| pixel.map(|channel| channel * 0.5));
|
||||||
|
let sharpen = |plane: &Plane<[f32; 4]>| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((1., 0.)), DMat2::IDENTITY);
|
||||||
|
assert!(sharpen(&faded).data.iter().any(|pixel| pixel[3] > 0.5));
|
||||||
|
|
||||||
|
let result = faded_by_shares(&sharpen(&faded), &sharpen(&square), &fill_shares(&square, &faded));
|
||||||
|
assert!(result.data.iter().all(|pixel| pixel[3] == 0. || pixel[3] == 0.5), "{:?}", result.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn window_extremes_match_a_direct_search() {
|
||||||
|
let values: Vec<[f32; 4]> = (0..37).map(|index| [((index * 7919) % 31) as f32; 4]).collect();
|
||||||
|
for radius in [1, 2, 5, 40] {
|
||||||
|
let mut fast = vec![[0.; 4]; values.len()];
|
||||||
|
window_extremes(&values, &mut fast, radius, [-1.; 4], |first, second| std::array::from_fn(|channel| first[channel].max(second[channel])));
|
||||||
|
|
||||||
|
for (index, value) in fast.iter().enumerate() {
|
||||||
|
let window = (index as isize - radius as isize)..=(index as isize + radius as isize);
|
||||||
|
let direct = window.map(|at| values.get(at as usize).filter(|_| at >= 0).map_or(-1., |value| value[0])).fold(f32::MIN, f32::max);
|
||||||
|
assert_eq!(value[0], direct, "radius {radius} at {index}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsharp_masking_exaggerates_differences_past_its_threshold() {
|
||||||
|
// A gray line with a lighter middle, a step the blur softens
|
||||||
|
let mut line = plane(9, 1, vec![[0.5, 0.5, 0.5, 1.]; 9]);
|
||||||
|
line.data[4] = [0.6, 0.6, 0.6, 1.];
|
||||||
|
|
||||||
|
let gaussian = UnsharpBlur::Gaussian(1.);
|
||||||
|
let sharpened = unsharp_mask(&line, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||||
|
assert!(sharpened.data[4][0] > 0.6 && sharpened.data[3][0] < 0.5, "{:?}", sharpened.data);
|
||||||
|
assert_eq!(sharpened.data[4][3], 1., "full coverage stays full");
|
||||||
|
|
||||||
|
// A threshold past the exaggerated difference leaves every pixel as it is
|
||||||
|
let untouched = unsharp_mask(&line, &line, gaussian, Some((1., 0.2)), DMat2::IDENTITY);
|
||||||
|
assert_eq!(untouched.data, line.data);
|
||||||
|
|
||||||
|
// A high pass of a flat color is middle gray
|
||||||
|
let flat = plane(5, 1, vec![[0.3, 0.3, 0.3, 1.]; 5]);
|
||||||
|
assert_eq!(
|
||||||
|
unsharp_mask(&flat, &flat, UnsharpBlur::Gaussian(2.), None, DMat2::IDENTITY).data[2],
|
||||||
|
[HIGH_PASS_GRAY, HIGH_PASS_GRAY, HIGH_PASS_GRAY, 1.]
|
||||||
|
);
|
||||||
|
|
||||||
|
// A fill faint enough to fall below the visible threshold still averages the colors the full-strength content shows
|
||||||
|
let faint = line.map(|pixel| pixel.map(|channel| channel * 0.05));
|
||||||
|
let faint_sharpened = unsharp_mask(&faint, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||||
|
let straight = |pixel: [f32; 4]| pixel[0] / pixel[3];
|
||||||
|
assert!((straight(faint_sharpened.data[4]) - straight(sharpened.data[4])).abs() < 1e-4, "{:?}", faint_sharpened.data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn edges_only_sharpens_against_the_neighbors_as_far_as_an_edge_runs_through() {
|
||||||
|
// A gray step up by `height` between columns, across which the Sobel gradient is four times as long, read along the middle row
|
||||||
|
let step = |height: f32| {
|
||||||
|
let mut columns = plane(6, 3, vec![[0.4, 0.4, 0.4, 1.]; 18]);
|
||||||
|
(0..3).for_each(|y| (3..6).for_each(|x| columns.data[y * 6 + x] = [0.4 + height, 0.4 + height, 0.4 + height, 1.]));
|
||||||
|
columns
|
||||||
|
};
|
||||||
|
let sharpen = |plane: &Plane<[f32; 4]>, amount: f32, threshold: f32| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((amount, threshold)), DMat2::IDENTITY).data;
|
||||||
|
let close = |actual: f32, expected: f32| (actual - expected).abs() < 1e-5;
|
||||||
|
|
||||||
|
// A strong step sharpens fully, each side moving by its difference from its four neighbors' average, a quarter of the step, while flat areas stay
|
||||||
|
let strong = sharpen(&step(0.4), 1., 0.);
|
||||||
|
assert!(close(strong[8][0], 0.3) && close(strong[9][0], 0.9) && close(strong[7][0], 0.4), "{strong:?}");
|
||||||
|
|
||||||
|
// A step under a sixteenth of full contrast stays as it is, and one of an eighth sharpens a third as much
|
||||||
|
assert!(close(sharpen(&step(0.05), 1., 0.)[8][0], 0.4));
|
||||||
|
assert!(close(sharpen(&step(0.125), 1., 0.)[8][0], 0.4 - 0.125 / 4. / 3.));
|
||||||
|
|
||||||
|
// The threshold softens the change, which half the amount halves
|
||||||
|
assert!(close(sharpen(&step(0.4), 1., 0.05)[8][0], 0.35));
|
||||||
|
assert!(close(sharpen(&step(0.4), 0.5, 0.)[8][0], 0.35));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_kernel_applied_to_alpha_weighs_the_coverage_too() {
|
||||||
|
let mut line = plane(5, 1, vec![[0.; 4]; 5]);
|
||||||
|
line.data[2] = [0.6, 0.3, 0., 1.];
|
||||||
|
let average = Convolution::custom(&[1., 1., 1.], 3, 3., 0.);
|
||||||
|
|
||||||
|
// Averaged with its neighbors, the coverage of a lone pixel spreads a third of itself to each side
|
||||||
|
let spread = convolve(
|
||||||
|
&line,
|
||||||
|
&line,
|
||||||
|
&Convolution {
|
||||||
|
weighs_coverage: true,
|
||||||
|
..average.clone()
|
||||||
|
},
|
||||||
|
DMat2::IDENTITY,
|
||||||
|
);
|
||||||
|
let alphas: Vec<f32> = spread.data.iter().map(|pixel| pixel[3]).collect();
|
||||||
|
assert!(alphas.iter().zip([0., 1., 1., 1., 0.]).all(|(alpha, thirds)| (alpha - thirds / 3.).abs() < 1e-6), "{alphas:?}");
|
||||||
|
|
||||||
|
// Otherwise, the coverage stays as it is
|
||||||
|
let kept = convolve(&line, &line, &average, DMat2::IDENTITY);
|
||||||
|
assert!(kept.data.iter().zip(&line.data).all(|(kept, line)| kept[3] == line[3]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The mean and standard deviation of each color's offset from middle gray, and the correlation between the first two colors' offsets.
|
||||||
|
fn offset_statistics(noisy: &Plane<[f32; 4]>) -> ([f64; 3], [f64; 3], f64) {
|
||||||
|
let count = noisy.data.len() as f64;
|
||||||
|
let offsets: Vec<[f64; 3]> = noisy.data.iter().map(|pixel| std::array::from_fn(|channel| pixel[channel] as f64 / pixel[3] as f64 - 0.5)).collect();
|
||||||
|
let mean: [f64; 3] = std::array::from_fn(|channel| offsets.iter().map(|offset| offset[channel]).sum::<f64>() / count);
|
||||||
|
let deviation: [f64; 3] = std::array::from_fn(|channel| (offsets.iter().map(|offset| (offset[channel] - mean[channel]).powi(2)).sum::<f64>() / count).sqrt());
|
||||||
|
let covariance = offsets.iter().map(|offset| (offset[0] - mean[0]) * (offset[1] - mean[1])).sum::<f64>() / count;
|
||||||
|
(mean, deviation, covariance / (deviation[0] * deviation[1]))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noise_follows_its_distribution_independently_for_each_color() {
|
||||||
|
let gray = plane(256, 256, vec![[0.5, 0.5, 0.5, 1.]; 256 * 256]);
|
||||||
|
let amount = 0.2;
|
||||||
|
|
||||||
|
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
|
||||||
|
let uniform = speckle(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||||
|
let (mean, deviation, correlation) = offset_statistics(&uniform);
|
||||||
|
for channel in 0..3 {
|
||||||
|
assert!(
|
||||||
|
mean[channel].abs() < 0.002 && (deviation[channel] / (amount / 3_f64.sqrt()) - 1.).abs() < 0.02,
|
||||||
|
"{mean:?} {deviation:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(correlation.abs() < 0.02, "{correlation}");
|
||||||
|
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
|
||||||
|
|
||||||
|
// Gaussian noise deviates by the amount, cut off at its limit
|
||||||
|
let gaussian = speckle(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||||
|
let (_, deviation, _) = offset_statistics(&gaussian);
|
||||||
|
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
|
||||||
|
|
||||||
|
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
|
||||||
|
let monochromatic = speckle(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||||
|
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||||
|
let reseeded = speckle(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||||
|
assert_ne!(reseeded.data[..64], uniform.data[..64]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
|
||||||
|
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
|
||||||
|
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| speckle(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||||
|
|
||||||
|
// A plane placed three cells right and five down holds the same noise at the same cells
|
||||||
|
let placed = noise(&gray(16), DAffine2::IDENTITY);
|
||||||
|
let moved = noise(&gray(16), DAffine2::from_translation(DVec2::new(3., 5.)));
|
||||||
|
assert_eq!(moved.data[0], placed.data[5 * 16 + 3]);
|
||||||
|
assert_eq!(moved.data[16 + 2], placed.data[6 * 16 + 5]);
|
||||||
|
|
||||||
|
// Pixels spanning eight cells each deviate as an average over all 64 would, an eighth as much
|
||||||
|
let zoomed_out = noise(&gray(128), DAffine2::from_scale(DVec2::splat(8.)));
|
||||||
|
let (_, deviation, _) = offset_statistics(&zoomed_out);
|
||||||
|
assert!((deviation[0] / (0.3 / 3_f64.sqrt() / 8.) - 1.).abs() < 0.05, "{deviation:?}");
|
||||||
|
|
||||||
|
// Pixels at exactly one cell each take one sample, like zoomed in
|
||||||
|
assert_eq!(FieldSampling::new(DAffine2::IDENTITY).counts, glam::UVec2::ONE);
|
||||||
|
assert_eq!(FieldSampling::new(DAffine2::from_scale(DVec2::splat(0.25))).counts, glam::UVec2::ONE);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dissolve_shows_opaque_pixels_by_the_opacity_and_the_coverage() {
|
||||||
|
let shown_share = |plane: &Plane<[f32; 4]>| plane.data.iter().filter(|pixel| pixel[3] > 0.).count() as f64 / plane.data.len() as f64;
|
||||||
|
let red = |alpha: f32| plane(256, 256, vec![[alpha, 0., 0., alpha]; 256 * 256]);
|
||||||
|
|
||||||
|
// Where the content is opaque, the opacity's share shows, and a larger opacity shows those and more
|
||||||
|
let some = dissolve(&red(1.), 0.3, 0, DAffine2::IDENTITY);
|
||||||
|
let more = dissolve(&red(1.), 0.6, 0, DAffine2::IDENTITY);
|
||||||
|
assert!((shown_share(&some) - 0.3).abs() < 0.01 && (shown_share(&more) - 0.6).abs() < 0.01);
|
||||||
|
assert!(some.data.iter().zip(&more.data).all(|(some, more)| some[3] <= more[3]));
|
||||||
|
|
||||||
|
// Half-covered content shows half as much, each shown pixel fully opaque in its straight color
|
||||||
|
let half = dissolve(&red(0.5), 1., 0, DAffine2::IDENTITY);
|
||||||
|
assert!((shown_share(&half) - 127. / 255.).abs() < 0.01, "{}", shown_share(&half));
|
||||||
|
assert!(half.data.iter().all(|pixel| *pixel == [0.; 4] || *pixel == [1., 0., 0., 1.]));
|
||||||
|
|
||||||
|
// Pixels spanning several cells show the share of them passing the opacity
|
||||||
|
let zoomed_out = dissolve(&red(1.), 0.3, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||||
|
let average = zoomed_out.data.iter().map(|pixel| pixel[3] as f64).sum::<f64>() / zoomed_out.data.len() as f64;
|
||||||
|
assert!((average - 0.3).abs() < 0.01 && zoomed_out.data.iter().any(|pixel| pixel[3] == 0.5), "{average}");
|
||||||
|
|
||||||
|
// For PSD interop, the opacity and the coverage pass thresholds of their own, so equal products show different pixels, neither set holding the other
|
||||||
|
let quarter = dissolve(&red(64. / 255.), 1., 0, DAffine2::IDENTITY);
|
||||||
|
let half_at_half = dissolve(&red(128. / 255.), 0.5, 0, DAffine2::IDENTITY);
|
||||||
|
let only_in = |first: &Plane<[f32; 4]>, second: &Plane<[f32; 4]>| first.data.iter().zip(&second.data).filter(|(first, second)| first[3] > 0. && second[3] <= 0.).count();
|
||||||
|
assert!(only_in(&quarter, &half_at_half) > 1000 && only_in(&half_at_half, &quarter) > 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_values_lie_strictly_between_zero_and_one() {
|
||||||
|
assert!(unit_interval(u32::MAX) < 1. && unit_interval(0) > 0.);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,43 @@
|
|||||||
//! The point functions sampling each [`GeneratorPattern`] anywhere in its space, which the GPU's renders of it match.
|
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||||
|
|
||||||
use crate::mandelbrot::MandelbrotSetup;
|
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use glam::{DVec2, IVec2};
|
use glam::{DVec2, IVec2};
|
||||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
use raster_types::{Image, ImageError};
|
||||||
|
|
||||||
|
/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels.
|
||||||
|
/// Fails where an image of that size can't be allocated.
|
||||||
|
/// The rows are rendered in parallel on native targets.
|
||||||
|
pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result<Image<Color>, ImageError> {
|
||||||
|
let mut image = Image::try_new(width, height, Color::TRANSPARENT)?;
|
||||||
|
let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64);
|
||||||
|
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
||||||
|
|
||||||
|
match pattern {
|
||||||
|
// Across a known area, a Mandelbrot pattern follows a reference orbit as the GPU does
|
||||||
|
GeneratorPattern::Mandelbrot(settings) => {
|
||||||
|
let setup = MandelbrotSetup::new(settings);
|
||||||
|
let (plane_area, plane_texel) = (area.map(|point| setup.plane_point(point)), (pixel_size / setup.scale).min_element());
|
||||||
|
let reference = setup.reference_orbit(plane_area, plane_texel);
|
||||||
|
let interior_test = setup.has_interior_test() && resolves_in_32_bits(plane_area, plane_texel);
|
||||||
|
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||||
|
row.iter_mut().enumerate().for_each(|(x, pixel)| {
|
||||||
|
*pixel = pattern_gray(setup.sample(setup.plane_point(pixel_center(x, y)), reference.as_ref(), interior_test));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let sample = pattern_sampler(pattern);
|
||||||
|
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||||
|
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(image)
|
||||||
|
}
|
||||||
|
|
||||||
/// The area of the pattern's own space that a thumbnail frames, for a pattern with a part worth framing rather than one alike across the whole plane.
|
/// The area of the pattern's own space that a thumbnail frames, for a pattern with a part worth framing rather than one alike across the whole plane.
|
||||||
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
||||||
@@ -143,6 +177,35 @@ fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn renders_of_overlapping_areas_agree_where_they_overlap() {
|
||||||
|
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||||
|
seed: 7,
|
||||||
|
scale: 10.,
|
||||||
|
noise_type: NoiseType::OpenSimplex2,
|
||||||
|
domain_warp_type: DomainWarpType::None,
|
||||||
|
domain_warp_amplitude: 0.,
|
||||||
|
fractal_type: FractalType::FBm,
|
||||||
|
fractal_octaves: 3,
|
||||||
|
fractal_lacunarity: 2.,
|
||||||
|
fractal_gain: 0.5,
|
||||||
|
fractal_weighted_strength: 0.,
|
||||||
|
fractal_ping_pong_strength: 2.,
|
||||||
|
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||||
|
cellular_return_type: CellularReturnType::Nearest,
|
||||||
|
cellular_jitter: 1.,
|
||||||
|
});
|
||||||
|
|
||||||
|
// One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it
|
||||||
|
let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap();
|
||||||
|
let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap();
|
||||||
|
for y in 0..16 {
|
||||||
|
for x in 0..16 {
|
||||||
|
assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn pattern_values_show_as_the_gray_at_that_level() {
|
fn pattern_values_show_as_the_gray_at_that_level() {
|
||||||
for value in [0., 0.25, 0.5, 0.75, 1.] {
|
for value in [0., 0.25, 0.5, 0.75, 1.] {
|
||||||
@@ -176,20 +239,18 @@ mod tests {
|
|||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
// The centers of a grid of `cells` across the 4 by 4 units from the origin
|
|
||||||
let centers = |cells: usize| (0..cells * cells).map(move |index| (DVec2::new((index % cells) as f64, (index / cells) as f64) + 0.5) * 4. / cells as f64);
|
|
||||||
|
|
||||||
// Each unit cell keeps its value when sampled four times as finely
|
// Each unit cell keeps its value when sampled four times as finely
|
||||||
let sample = pattern_sampler(&white_noise(3));
|
let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap();
|
||||||
let coarse: Vec<Color> = centers(4).map(&sample).collect();
|
let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap();
|
||||||
for (index, point) in centers(16).enumerate() {
|
for y in 0..16 {
|
||||||
let (x, y) = (index % 16, index / 16);
|
for x in 0..16 {
|
||||||
assert_eq!(sample(point), coarse[(y / 4) * 4 + x / 4]);
|
assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The values spread across the whole range, and another seed gives others
|
// The values spread across the whole range, and another seed gives others
|
||||||
let luminances: Vec<f32> = coarse.iter().map(|color| color.r()).collect();
|
let luminances: Vec<f32> = coarse.data.iter().map(|color| color.r()).collect();
|
||||||
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
||||||
assert_ne!(centers(4).map(pattern_sampler(&white_noise(4))).collect::<Vec<_>>(), coarse);
|
assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,10 +1,16 @@
|
|||||||
//! Blends a pixel of a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
//! Blends a layer onto those beneath it by a blend mode, with the W3C Compositing and Blending formulas on gamma-encoded colors, as SVG and the GPU's layers blend.
|
||||||
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
||||||
|
|
||||||
|
use crate::effect_kernels::Plane;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
||||||
use core_types::color::BLEND_EDGE_TOLERANCE;
|
use core_types::color::BLEND_EDGE_TOLERANCE;
|
||||||
|
|
||||||
|
/// The premultiplied gamma-encoded `layer` blended by the mode onto the layers `below` it. O(width × height).
|
||||||
|
pub fn blend_layer(layer: &Plane<[f32; 4]>, below: &Plane<[f32; 4]>, blend_mode: BlendMode) -> Plane<[f32; 4]> {
|
||||||
|
layer.zip(below, |source, backdrop| blend_pixel(source, backdrop, blend_mode))
|
||||||
|
}
|
||||||
|
|
||||||
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
/// One premultiplied pixel blended onto another: its color mixes toward the blend of both as far as the backdrop covers it, and it then composites over the backdrop.
|
||||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||||
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
||||||
|
|||||||
@@ -4,12 +4,18 @@ pub mod adjustment_steps;
|
|||||||
pub mod adjustments;
|
pub mod adjustments;
|
||||||
mod blending;
|
mod blending;
|
||||||
pub mod color_lookup_table;
|
pub mod color_lookup_table;
|
||||||
pub mod effect_planning;
|
pub mod effect_kernels;
|
||||||
|
pub mod filter_kernels;
|
||||||
pub mod generators;
|
pub mod generators;
|
||||||
mod kernel;
|
mod kernel;
|
||||||
pub mod layer_blending;
|
pub mod layer_blending;
|
||||||
pub mod mandelbrot;
|
pub mod mandelbrot;
|
||||||
|
pub mod masks;
|
||||||
|
pub mod raster_effects;
|
||||||
|
pub mod resample_kernels;
|
||||||
pub mod value_effects;
|
pub mod value_effects;
|
||||||
|
pub mod warp_kernels;
|
||||||
|
|
||||||
pub use kernel::*;
|
pub use kernel::*;
|
||||||
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
pub use raster_effects::evaluate_raster_effects;
|
||||||
|
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||||
@@ -0,0 +1,408 @@
|
|||||||
|
//! The CPU twins of the GPU passes that mask, feather, and blur content by a radius mask.
|
||||||
|
|
||||||
|
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane, VARIABLE_BOX_MAX_VALUE, variable_box_scale};
|
||||||
|
use crate::raster_effects::{blur, premultiplied_gamma_channels, transferred};
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma, masked_radius_blur_code, masked_radius_blur_interpolation};
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
|
||||||
|
/// How much the mask shows the content at each pixel, from 0 to 1, given the `colors` its graphic draws over a plane of `width` by `height` pixels.
|
||||||
|
/// Its coverage is softened by the `feather` (in document pixels, `pixels_per_length` pixels each), then mapped through its `density` percentage, flipped if `invert`.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(crate) fn mask_strength(colors: &[Color], width: usize, height: usize, mode: MaskMode, density: f64, feather: f64, invert: bool, pixels_per_length: DVec2) -> Plane<f32> {
|
||||||
|
let coverage = Plane {
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
data: colors.iter().map(|&color| mask_coverage(premultiplied_gamma_channels(color), mode)).collect(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let sigma = mask_feather_sigma(feather) * pixels_per_length;
|
||||||
|
let coverage = match sigma.max_element() >= NEGLIGIBLE_LENGTH {
|
||||||
|
true => coverage.blurred(BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y }),
|
||||||
|
false => coverage,
|
||||||
|
};
|
||||||
|
|
||||||
|
let (slope, intercept) = mask_density_line(density, invert);
|
||||||
|
coverage.map(|coverage| (slope * coverage + intercept).clamp(0., 1.))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The premultiplied image faded at each pixel by the mask's `strength` there.
|
||||||
|
pub(crate) fn masked(image: &Plane<[f32; 4]>, strength: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||||
|
image.zip(strength, |pixel, strength| pixel.map(|channel| channel * strength))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much a footprint eroded by `erosion` pixels covers a pixel, given the pixel's distance to the area outside the footprint plus half a pixel and its share of that area, relative to its own coverage of the footprint.
|
||||||
|
fn erode(to_outside: f32, outside_coverage: f32, erosion: f32) -> f32 {
|
||||||
|
let coverage = 1. - outside_coverage;
|
||||||
|
let eroded = (to_outside - erosion).clamp(0., 1.);
|
||||||
|
if coverage > 0. { (eroded / coverage).min(1.) } else { eroded }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much a feather of `distance` pixels keeps of the `full`-strength content at each pixel, from 0 to 1, as [`feather_parts`] defines it, matching the GPU's `feather_strength`.
|
||||||
|
/// O(width × height × log(distance)).
|
||||||
|
pub(crate) fn feather_strength(full: &Plane<[f32; 4]>, distance: f64) -> Plane<f32> {
|
||||||
|
let (width, height) = (full.width, full.height);
|
||||||
|
let alpha_at = |x: usize, y: usize| full.data[y * width + x][3];
|
||||||
|
|
||||||
|
// The area outside the footprint, with its edge falling within the pixels bordering it by their alpha relative to the largest beside them
|
||||||
|
let mut outside = Plane::<f32>::new(width, height);
|
||||||
|
fill_rows(&mut outside.data, width, |y, row| {
|
||||||
|
for (x, outside_coverage) in row.iter_mut().enumerate() {
|
||||||
|
let alpha = alpha_at(x, y);
|
||||||
|
let neighbors = (y.saturating_sub(1)..(y + 2).min(height)).flat_map(|neighbor_y| (x.saturating_sub(1)..(x + 2).min(width)).map(move |neighbor_x| (neighbor_x, neighbor_y)));
|
||||||
|
let neighbor_alphas = neighbors.map(|(neighbor_x, neighbor_y)| alpha_at(neighbor_x, neighbor_y));
|
||||||
|
let (borders_absence, largest) = neighbor_alphas.fold((false, alpha), |(borders, largest), neighbor| (borders || neighbor <= FEATHER_FOOTPRINT_ALPHA, largest.max(neighbor)));
|
||||||
|
|
||||||
|
*outside_coverage = match (alpha <= FEATHER_FOOTPRINT_ALPHA, borders_absence) {
|
||||||
|
(true, _) => 1.,
|
||||||
|
(false, true) => 1. - (alpha / largest).min(1.),
|
||||||
|
(false, false) => 0.,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// The footprint eroded in straight lines, from each pixel's distance to the edge plus half a pixel, relative to the pixel's own coverage of the footprint so a feather of nothing keeps the content as it is
|
||||||
|
let (erosion, sigma) = feather_parts(distance);
|
||||||
|
let to_outside = outside.jump_flood(erosion + 2., |coverage| coverage > 0., |[x, y], coverage| (x as f32).hypot(y as f32) + (0.5 - coverage) + 0.5);
|
||||||
|
let eroded = to_outside.zip(&outside, |to_outside, outside_coverage| erode(to_outside, outside_coverage, erosion as f32));
|
||||||
|
|
||||||
|
match sigma >= NEGLIGIBLE_LENGTH {
|
||||||
|
true => eroded.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma }),
|
||||||
|
false => eroded,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A masked radius blur map's color in 8-bit channels as the GPU renders the map: straight, then premultiplied.
|
||||||
|
fn map_channels(color: Color) -> [f32; 4] {
|
||||||
|
let eight_bit = |channel: f32| (channel.clamp(0., 1.) * 255.).round() / 255.;
|
||||||
|
let [red, green, blue, alpha] = color.to_gamma_srgb_channels().map(eight_bit);
|
||||||
|
[eight_bit(red * alpha), eight_bit(green * alpha), eight_bit(blue * alpha), alpha]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 8-bit luminance code of each of a masked radius blur map's `colors` (see [`map_channels`]).
|
||||||
|
pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
||||||
|
colors.iter().map(|&color| masked_radius_blur_code(map_channels(color))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The luminance from 0 to 1 of each of a masked box blur map's `colors`, unrounded like the GPU's precise map texture, in the half floats the GPU keeps it in, which size the boxes finer than 8-bit codes could.
|
||||||
|
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
|
||||||
|
let luminance = |color: Color| {
|
||||||
|
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||||
|
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::LuminanceSvg).clamp(0., 1.)
|
||||||
|
};
|
||||||
|
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The premultiplied gamma-encoded `image` blurred by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels along each axis) each pixel's map luminance `codes` picks,
|
||||||
|
/// matching the GPU's `masked_radius_blur`, blurring in linear light if `linear`. O(width × height) for each of the levels.
|
||||||
|
pub(crate) fn masked_radius_blur(image: &Plane<[f32; 4]>, codes: &[u8], levels: &[DVec2], linear: bool) -> Plane<[f32; 4]> {
|
||||||
|
// Each code's level below and share of the level above, the same for every level and at any scale
|
||||||
|
let lengths: Vec<f64> = levels.iter().map(|level| level.max_element()).collect();
|
||||||
|
let interpolations: Vec<(usize, f32)> = (0..=255_u8)
|
||||||
|
.map(|code| {
|
||||||
|
let (below, above_parts) = masked_radius_blur_interpolation(code, &lengths);
|
||||||
|
(below, above_parts as f32 / 255.)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
// Only the levels some pixel takes a share of are blurred, so a map of one luminance blurs once or twice
|
||||||
|
let mut weighed = vec![false; levels.len()];
|
||||||
|
for &code in codes {
|
||||||
|
let (below, above_share) = interpolations[code as usize];
|
||||||
|
weighed[below] |= above_share < 1.;
|
||||||
|
if let Some(above) = weighed.get_mut(below + 1) {
|
||||||
|
*above |= above_share > 0.;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut sum = Plane::<[f32; 4]>::new(image.width, image.height);
|
||||||
|
for (index, &length) in levels.iter().enumerate().filter(|&(index, _)| weighed[index]) {
|
||||||
|
let blurred = match length.max_element() >= NEGLIGIBLE_LENGTH {
|
||||||
|
true => blur(image.clone(), (BlurKernel::Gaussian { sigma: length.x }, BlurKernel::Gaussian { sigma: length.y }), linear),
|
||||||
|
false => image.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let weight = |(below, above_share): (usize, f32)| match index {
|
||||||
|
_ if index == below => 1. - above_share,
|
||||||
|
_ if index == below + 1 => above_share,
|
||||||
|
_ => 0.,
|
||||||
|
};
|
||||||
|
// Summed in gamma on purpose (see `masked_radius_blur_interpolation`)
|
||||||
|
for ((sum, pixel), &code) in sum.data.iter_mut().zip(&blurred.data).zip(codes) {
|
||||||
|
let weight = weight(interpolations[code as usize]);
|
||||||
|
*sum = std::array::from_fn(|channel| sum[channel] + pixel[channel] * weight);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The premultiplied gamma-encoded `image` box blurred at each pixel by its own half width along each axis, the fraction of the `radius` in pixels its map's `luminances` give,
|
||||||
|
/// matching the GPU's `variable_box_blur`. Each box weighs pixels like [`BlurKernel::Box`], holding the edge pixels past the edges, in linear light if `linear`.
|
||||||
|
/// It sums each box from running sums (a summed-area table) of whole-number counts, exact at any size, so O(width × height) at any radius.
|
||||||
|
pub fn variable_box_blur(image: &Plane<[f32; 4]>, luminances: &[f32], radius: DVec2, linear: bool) -> Plane<[f32; 4]> {
|
||||||
|
let (width, height) = (image.width, image.height);
|
||||||
|
let summed = match linear {
|
||||||
|
true => std::borrow::Cow::Owned(image.map(transferred(srgb_to_linear))),
|
||||||
|
false => std::borrow::Cow::Borrowed(image),
|
||||||
|
};
|
||||||
|
let scale = variable_box_scale(width * height);
|
||||||
|
let count = |value: f32| (value.clamp(0., VARIABLE_BOX_MAX_VALUE) * scale as f32).round_ties_even() as u64;
|
||||||
|
|
||||||
|
// Two channels at a time, as the GPU sums them, keeping the running sums to 16 bytes a pixel
|
||||||
|
let mut averages = Plane::<[f32; 4]>::new(width, height);
|
||||||
|
for first in [0, 2] {
|
||||||
|
// Each channel counted in whole steps, summed over the pixels above and left of each corner between pixels, in rows of one more corner than pixels
|
||||||
|
let corners = width + 1;
|
||||||
|
let mut sums = vec![[0_u64; 2]; corners * (height + 1)];
|
||||||
|
for y in 0..height {
|
||||||
|
let mut row = [0_u64; 2];
|
||||||
|
for x in 0..width {
|
||||||
|
let pixel = summed.data[y * width + x];
|
||||||
|
row = [row[0] + count(pixel[first]), row[1] + count(pixel[first + 1])];
|
||||||
|
|
||||||
|
let above = sums[y * corners + x + 1];
|
||||||
|
sums[(y + 1) * corners + x + 1] = [above[0] + row[0], above[1] + row[1]];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let sum_at = |x: usize, y: usize| sums[y * corners + x];
|
||||||
|
|
||||||
|
// The counts over the pixels from `start` up to `end`, with those past the edges repeating the nearest edge pixel
|
||||||
|
let counts_continued = |start: [i64; 2], end: [i64; 2]| -> [f64; 2] {
|
||||||
|
let spans = |axis: usize, size: usize| {
|
||||||
|
let size = size as i64;
|
||||||
|
let (inner_start, inner_end) = (start[axis].clamp(0, size), end[axis].clamp(0, size));
|
||||||
|
[(0, 1, inner_start - start[axis]), (inner_start, inner_end, 1), (size - 1, size, end[axis] - inner_end)]
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut sum = [0.; 2];
|
||||||
|
for (start_x, end_x, count_x) in spans(0, width) {
|
||||||
|
for (start_y, end_y, count_y) in spans(1, height) {
|
||||||
|
if count_x <= 0 || count_y <= 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let [start_x, end_x, start_y, end_y] = [start_x, end_x, start_y, end_y].map(|corner| corner as usize);
|
||||||
|
let [top_left, top_right] = [sum_at(start_x, start_y), sum_at(end_x, start_y)];
|
||||||
|
let [bottom_left, bottom_right] = [sum_at(start_x, end_y), sum_at(end_x, end_y)];
|
||||||
|
let count = (count_x * count_y) as f64;
|
||||||
|
sum = std::array::from_fn(|channel| sum[channel] + count * ((bottom_right[channel] + top_left[channel]) - (bottom_left[channel] + top_right[channel])) as f64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum
|
||||||
|
};
|
||||||
|
|
||||||
|
fill_rows(&mut averages.data, width, |y, row| {
|
||||||
|
for (x, target) in row.iter_mut().enumerate() {
|
||||||
|
let index = y * width + x;
|
||||||
|
if luminances[index] <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A box of a fractional half width is the mix of the boxes of the whole half widths either side, weighed by that fraction along each axis
|
||||||
|
let half_width = radius * luminances[index] as f64;
|
||||||
|
let (whole, fraction) = (half_width.floor(), half_width - half_width.floor());
|
||||||
|
let mut sum = [0.; 2];
|
||||||
|
for wider in [[false, false], [true, false], [false, true], [true, true]] {
|
||||||
|
let along = |axis: usize| if wider[axis] { fraction[axis] } else { 1. - fraction[axis] };
|
||||||
|
let weight = along(0) * along(1);
|
||||||
|
if weight <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let reach = [0, 1].map(|axis| whole[axis] as i64 + wider[axis] as i64);
|
||||||
|
let rectangle = counts_continued([x as i64 - reach[0], y as i64 - reach[1]], [x as i64 + reach[0] + 1, y as i64 + reach[1] + 1]);
|
||||||
|
sum = std::array::from_fn(|channel| sum[channel] + weight * rectangle[channel]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let total = (2. * half_width.x + 1.) * (2. * half_width.y + 1.) * scale;
|
||||||
|
target[first..first + 2].copy_from_slice(&sum.map(|channel| (channel / total) as f32));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pixels not blurred keep their color, and the rest return to gamma from linear light
|
||||||
|
let encode = transferred(linear_to_srgb);
|
||||||
|
for ((average, &original), &luminance) in averages.data.iter_mut().zip(&image.data).zip(luminances) {
|
||||||
|
*average = match luminance > 0. {
|
||||||
|
false => original,
|
||||||
|
true if linear => encode(*average),
|
||||||
|
true => *average,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
averages
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use crate::effect_kernels::box_weight;
|
||||||
|
|
||||||
|
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||||||
|
fn normal_cdf(x: f64) -> f64 {
|
||||||
|
let z = x.abs() / std::f64::consts::SQRT_2;
|
||||||
|
let t = 1. / (1. + 0.327_591_1 * z);
|
||||||
|
let polynomial = t * (0.254_829_592 + t * (-0.284_496_736 + t * (1.421_413_741 + t * (-1.453_152_027 + t * 1.061_405_429))));
|
||||||
|
let erf = 1. - polynomial * (-z * z).exp();
|
||||||
|
if x >= 0. { 0.5 * (1. + erf) } else { 0.5 * (1. - erf) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plane of white content with the alpha `coverage` gives at each pixel's center.
|
||||||
|
fn content(size: usize, coverage: impl Fn(f64, f64) -> f32) -> Plane<[f32; 4]> {
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(size, size);
|
||||||
|
for (index, pixel) in plane.data.iter_mut().enumerate() {
|
||||||
|
let alpha = coverage((index % size) as f64 + 0.5, (index / size) as f64 + 0.5);
|
||||||
|
*pixel = [alpha; 4];
|
||||||
|
}
|
||||||
|
plane
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The feather's strength across a straight edge, as the definition gives it for a pixel center at `depth` within the edge.
|
||||||
|
fn expected(depth: f64, distance: f64) -> f64 {
|
||||||
|
normal_cdf((depth - distance / 2.) / (distance / 6.))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn feathers_follow_the_definition_across_straight_and_round_edges() {
|
||||||
|
let distance = 16.;
|
||||||
|
|
||||||
|
// A square from 8 to 56, measured across its left edge on its middle row
|
||||||
|
let square = content(64, |x, y| if (8. ..56.).contains(&x) && (8. ..56.).contains(&y) { 1. } else { 0. });
|
||||||
|
let strength = feather_strength(&square, distance);
|
||||||
|
for x in 8..30 {
|
||||||
|
let depth = x as f64 + 0.5 - 8.;
|
||||||
|
let actual = strength.data[32 * 64 + x] as f64;
|
||||||
|
assert!((actual - expected(depth, distance)).abs() < 0.03, "at depth {depth} the square keeps {actual}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// A disk of radius 28 with an antialiased edge, measured along a diagonal, where distances by chamfer steps would stray from straight lines
|
||||||
|
let disk = content(80, |x, y| (28.5 - (x - 40.).hypot(y - 40.)).clamp(0., 1.) as f32);
|
||||||
|
let strength = feather_strength(&disk, distance);
|
||||||
|
for step in 0..14 {
|
||||||
|
let (x, y) = (40 + 19 - step, 40 + 19 - step);
|
||||||
|
let depth = 28. - (x as f64 + 0.5 - 40.).hypot(y as f64 + 0.5 - 40.);
|
||||||
|
let actual = strength.data[y * 80 + x] as f64;
|
||||||
|
assert!((actual - expected(depth, distance)).abs() < 0.04, "at depth {depth} on the diagonal the disk keeps {actual}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn feathers_fade_thin_parts_and_hole_edges_and_keep_translucent_edges_where_opaque_ones_are() {
|
||||||
|
let distance = 12.;
|
||||||
|
|
||||||
|
// A strip thinner than the distance fades away entirely
|
||||||
|
let strip = content(48, |x, _| if (20. ..26.).contains(&x) { 1. } else { 0. });
|
||||||
|
let strength = feather_strength(&strip, distance);
|
||||||
|
assert!(strength.data[24 * 48 + 23] < 0.01, "the strip's middle keeps {}", strength.data[24 * 48 + 23]);
|
||||||
|
|
||||||
|
// A hole's edge fades like the outline's
|
||||||
|
let holed = content(64, |x, y| if (x - 32.).hypot(y - 32.) < 4. { 0. } else { 1. });
|
||||||
|
let strength = feather_strength(&holed, distance);
|
||||||
|
assert!(strength.data[32 * 64 + 36] < 0.05, "beside the hole the content keeps {}", strength.data[32 * 64 + 36]);
|
||||||
|
|
||||||
|
// Content at 40% places its edge as opaque content does
|
||||||
|
let opaque = feather_strength(&content(48, |x, _| if x >= 16. { 1. } else { 0. }), distance);
|
||||||
|
let translucent = feather_strength(&content(48, |x, _| if x >= 16. { 0.4 } else { 0. }), distance);
|
||||||
|
for x in 16..32 {
|
||||||
|
assert!(
|
||||||
|
(opaque.data[24 * 48 + x] - translucent.data[24 * 48 + x]).abs() < 1e-4,
|
||||||
|
"at {x} the translucent content is feathered differently"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_feather_of_almost_nothing_keeps_the_content_as_it_is() {
|
||||||
|
let disk = content(32, |x, y| (10.5 - (x - 16.).hypot(y - 16.)).clamp(0., 1.) as f32);
|
||||||
|
let strength = feather_strength(&disk, 0.01);
|
||||||
|
for (pixel, strength) in disk.data.iter().zip(&strength.data) {
|
||||||
|
if pixel[3] > 0. {
|
||||||
|
assert!(*strength > 0.98, "a pixel of alpha {} keeps only {strength}", pixel[3]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Premultiplied colors varying across the plane up to its edges, every seventh pixel transparent and some translucent.
|
||||||
|
fn colorful(width: usize, height: usize) -> Plane<[f32; 4]> {
|
||||||
|
let data = (0..width * height)
|
||||||
|
.map(|index| {
|
||||||
|
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
||||||
|
let alpha = [0., 0.5, 0.5, 1., 1., 1., 1.][index % 7];
|
||||||
|
[x * alpha, y * alpha, (1. - x * y) * alpha, alpha]
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Plane { width, height, data }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The box of `half_width` along each axis around a pixel of the plane, summed pixel by pixel with the edge pixels held past the edges.
|
||||||
|
fn summed_box(plane: &Plane<[f32; 4]>, x: usize, y: usize, half_width: DVec2) -> [f32; 4] {
|
||||||
|
let reach = half_width.ceil().as_i64vec2();
|
||||||
|
let (mut sum, mut total) = ([0.; 4], 0.);
|
||||||
|
for offset_y in -reach.y..=reach.y {
|
||||||
|
for offset_x in -reach.x..=reach.x {
|
||||||
|
let weight = box_weight(half_width.x, offset_x.unsigned_abs() as usize) * box_weight(half_width.y, offset_y.unsigned_abs() as usize);
|
||||||
|
let source_x = (x as i64 + offset_x).clamp(0, plane.width as i64 - 1) as usize;
|
||||||
|
let source_y = (y as i64 + offset_y).clamp(0, plane.height as i64 - 1) as usize;
|
||||||
|
let pixel = plane.data[source_y * plane.width + source_x];
|
||||||
|
|
||||||
|
sum = std::array::from_fn(|channel| sum[channel] + weight * pixel[channel] as f64);
|
||||||
|
total += weight;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sum.map(|channel| (channel / total) as f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn variable_box_blurs_box_each_pixel_by_its_own_fraction_of_the_radius() {
|
||||||
|
let image = colorful(37, 29);
|
||||||
|
// Luminances finer than 8-bit codes, with every 41st pixel unblurred
|
||||||
|
let luminances: Vec<f32> = (0..37 * 29).map(|index| if index % 41 == 0 { 0. } else { ((index * 37) % 1000) as f32 / 1000. }).collect();
|
||||||
|
let radius = DVec2::new(9.3, 6.);
|
||||||
|
|
||||||
|
for linear in [false, true] {
|
||||||
|
let blurred = variable_box_blur(&image, &luminances, radius, linear);
|
||||||
|
let decoded = if linear { image.map(transferred(srgb_to_linear)) } else { image.clone() };
|
||||||
|
|
||||||
|
// Counting in 4096 steps rounds by up to half a step, which gamma encoding stretches up to 13 times near black
|
||||||
|
let tolerance = if linear { 2e-3 } else { 2e-4 };
|
||||||
|
|
||||||
|
for (index, &luminance) in luminances.iter().enumerate() {
|
||||||
|
// A luminance of 0 leaves its pixel exactly as it is
|
||||||
|
if luminance <= 0. {
|
||||||
|
assert_eq!(blurred.data[index], image.data[index]);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let summed = summed_box(&decoded, index % 37, index / 37, radius * luminance as f64);
|
||||||
|
let expected = if linear { transferred(linear_to_srgb)(summed) } else { summed };
|
||||||
|
for channel in 0..4 {
|
||||||
|
let difference = (blurred.data[index][channel] - expected[channel]).abs();
|
||||||
|
assert!(
|
||||||
|
difference < tolerance,
|
||||||
|
"pixel {index} of luminance {luminance} differs by {difference} in channel {channel} (linear: {linear})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn variable_box_blurs_of_one_fraction_of_the_radius_are_the_box_blur_of_that_half_width() {
|
||||||
|
let image = colorful(48, 40);
|
||||||
|
let luminances = vec![0.6; 48 * 40];
|
||||||
|
let radius = DVec2::new(20., 12.5);
|
||||||
|
let half_width = radius * 0.6_f32 as f64;
|
||||||
|
|
||||||
|
for linear in [false, true] {
|
||||||
|
let variable = variable_box_blur(&image, &luminances, radius, linear);
|
||||||
|
let even = blur(image.clone(), (BlurKernel::Box { radius: half_width.x }, BlurKernel::Box { radius: half_width.y }), linear);
|
||||||
|
for (index, (variable, even)) in variable.data.iter().zip(&even.data).enumerate() {
|
||||||
|
for channel in 0..4 {
|
||||||
|
let difference = (variable[channel] - even[channel]).abs();
|
||||||
|
assert!(difference < 2e-4, "pixel {index} differs by {difference} in channel {channel} (linear: {linear})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,228 @@
|
|||||||
|
//! The CPU steps of the layer styles' finer options: the outline's paints, the bevel's contour and texture, and the glows' grain.
|
||||||
|
|
||||||
|
use crate::effect_kernels::{NEGLIGIBLE_LENGTH, Plane};
|
||||||
|
use crate::filter_kernels::field_values;
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||||
|
use glam::{DAffine2, DVec2, DVec3};
|
||||||
|
use graphic_types::effects::{
|
||||||
|
ANTIALIASED_CONTOUR_OFFSETS, BEVEL_FOOT_FADE, BevelStyle, GRADIENT_TABLE_SIZE, GlowFill, bevel_lighting, bevel_lit, contour_end_slopes, contour_gradient_position, extended_contour,
|
||||||
|
slope_contour_input, slope_contour_reshapes, texture_gray,
|
||||||
|
};
|
||||||
|
use graphic_types::filters::{FieldSampling, MAX_FIELD_SAMPLES_PER_AXIS, RandomField};
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
|
||||||
|
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
||||||
|
pub(super) struct OutlineBands {
|
||||||
|
pub outside: Option<Plane<f32>>,
|
||||||
|
pub inside: Option<Plane<f32>>,
|
||||||
|
pub positions: Option<Plane<f32>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bands of an outline reaching `outside` pixels past the edge of the `silhouette` and `inside` pixels within it.
|
||||||
|
/// With a contour gradient's `start` and `span` in pixels (see `contour_gradient_span`), it also places each pixel across the outline.
|
||||||
|
/// Both bands grow by chamfer distances, which also measure each pixel's center from the edge for its place. O(width × height × log(weight)).
|
||||||
|
pub(super) fn outline_bands(silhouette: &Plane<f32>, outside: f64, inside: f64, contour_gradient: Option<(f64, f64)>) -> OutlineBands {
|
||||||
|
let outward = (outside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.distances_to_silhouette(outside + 1.));
|
||||||
|
let inward = (inside >= NEGLIGIBLE_LENGTH || contour_gradient.is_some()).then(|| silhouette.map(|alpha| 1. - alpha).distances_to_silhouette(inside + 1.));
|
||||||
|
|
||||||
|
// The silhouette grown by the band's width, as `Plane::grown` grows it
|
||||||
|
let band = |distances: &Option<Plane<f32>>, width: f64| {
|
||||||
|
let reach = width as f32 + 1.;
|
||||||
|
distances
|
||||||
|
.as_ref()
|
||||||
|
.filter(|_| width >= NEGLIGIBLE_LENGTH)
|
||||||
|
.map(|distances| distances.map(|nearest| (reach - nearest).clamp(0., 1.)))
|
||||||
|
};
|
||||||
|
|
||||||
|
// Each pixel's center lies half a pixel short of its distance from the edge, inside or out
|
||||||
|
let positions = match (&outward, &inward, contour_gradient) {
|
||||||
|
(Some(outward), Some(inward), Some((start, span))) => Some(outward.zip(inward, |outward, inward| {
|
||||||
|
let signed_distance = (outward - 0.5).max(0.) - (inward - 0.5).max(0.);
|
||||||
|
contour_gradient_position(signed_distance, start as f32, span as f32)
|
||||||
|
})),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
OutlineBands {
|
||||||
|
outside: band(&outward, outside),
|
||||||
|
inside: band(&inward, inside),
|
||||||
|
positions,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The premultiplied gamma-encoded color of a contour `gradient` at each pixel's place across the outline, from the same table of samples the other renderers read.
|
||||||
|
pub(super) fn contour_gradient_colors(gradient: &GlowFill, positions: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||||
|
let Some((samples, opacity)) = gradient.gradient_samples(GRADIENT_TABLE_SIZE) else {
|
||||||
|
return positions.map(|_| [0.; 4]);
|
||||||
|
};
|
||||||
|
let last = GRADIENT_TABLE_SIZE - 1;
|
||||||
|
|
||||||
|
positions.map(|position| {
|
||||||
|
let [red, green, blue, alpha] = samples[((position * last as f32).round() as usize).min(last)];
|
||||||
|
let alpha = alpha * opacity;
|
||||||
|
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The gray of a bevel's texture at each pixel of a plane `width` by `height`, from its `colors` premultiplied in 8 bits as the GPU draws it.
|
||||||
|
pub(super) fn texture_grays(colors: Vec<Color>, width: usize, height: usize) -> Plane<f32> {
|
||||||
|
let data = colors
|
||||||
|
.into_iter()
|
||||||
|
.map(|color| {
|
||||||
|
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||||
|
texture_gray([red * alpha, green * alpha, blue * alpha, alpha].map(|channel| (channel * 255.).round() / 255.))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
Plane { width, height, data }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What shapes a bevel's surface besides its height: a contour reshaping its slopes across a percentage of them, and a texture's gray sinking it by a percentage of its span.
|
||||||
|
pub(super) struct BevelSurface<'a> {
|
||||||
|
pub style: BevelStyle,
|
||||||
|
pub slope_contour: &'a TransferCurve,
|
||||||
|
pub slope_range: f64,
|
||||||
|
/// Whether the slope contour is sampled at nine points across each pixel.
|
||||||
|
pub slope_antialiased: bool,
|
||||||
|
pub texture: Option<Plane<f32>>,
|
||||||
|
pub texture_depth: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offsets toward a pixel's right and lower neighbors at which an antialiased contour samples it, or just the pixel itself.
|
||||||
|
fn sample_offsets(antialiased: bool) -> Vec<[f64; 2]> {
|
||||||
|
match antialiased {
|
||||||
|
true => ANTIALIASED_CONTOUR_OFFSETS.iter().flat_map(|&y| ANTIALIASED_CONTOUR_OFFSETS.map(|x| [x, y])).collect(),
|
||||||
|
false => vec![[0., 0.]],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plane's value at `offset` from the pixel at `x` and `y` toward its right and lower neighbors, interpolated between them and holding the edge pixels beyond the edges.
|
||||||
|
fn sample_between(plane: &Plane<f32>, x: isize, y: isize, [offset_x, offset_y]: [f64; 2]) -> f64 {
|
||||||
|
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||||
|
let at = |x: isize, y: isize| plane.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
||||||
|
|
||||||
|
let top = at(x, y) * (1. - offset_x) + at(x + 1, y) * offset_x;
|
||||||
|
let bottom = at(x, y + 1) * (1. - offset_x) + at(x + 1, y + 1) * offset_x;
|
||||||
|
top * (1. - offset_y) + bottom * offset_y
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much each pixel of a bevel's surface is lit by the `light` past a flat surface's brightness (its highlight), and how much it falls short (its shadow), each from 0 to 1.
|
||||||
|
/// The surface's `height` runs from -0.5 at the slopes' foot to 0.5 at their top, which rise `rise` pixels as the `surface` options shape them, and it's lit through the `gloss` contour, antialiased if paired with true.
|
||||||
|
/// For PSD interop, a slope is the difference across a pixel's neighbors averaged over the three rows or columns they span, and antialiasing averages nine samples offset toward the right and lower neighbors.
|
||||||
|
/// O(width × height), nine times over when antialiased.
|
||||||
|
pub(super) fn bevel_shading(height: &Plane<f32>, surface: &BevelSurface, rise: f64, light: DVec3, gloss: Option<&(TransferCurveEvaluator, bool)>) -> [Plane<f32>; 2] {
|
||||||
|
let (columns, rows) = (height.width as isize, height.height as isize);
|
||||||
|
let reshaped = slope_contour_reshapes(surface.slope_contour, surface.style, surface.slope_range);
|
||||||
|
let contour = surface.slope_contour.evaluator();
|
||||||
|
let slopes = contour_end_slopes(&contour);
|
||||||
|
let texture_depth = surface.texture_depth / 100.;
|
||||||
|
|
||||||
|
// The surface's height in units of its span at an offset from a pixel, reshaped by the contour and sunk by the texture
|
||||||
|
let surface_at = |x: isize, y: isize, offset: [f64; 2]| {
|
||||||
|
let t = sample_between(height, x, y, offset) + 0.5;
|
||||||
|
let shaped = match reshaped {
|
||||||
|
true => extended_contour(&contour, slopes, slope_contour_input(t, surface.style, surface.slope_range)),
|
||||||
|
false => t,
|
||||||
|
};
|
||||||
|
shaped - surface.texture.as_ref().map_or(0., |texture| texture_depth * sample_between(texture, x, y, offset))
|
||||||
|
};
|
||||||
|
|
||||||
|
// How much brighter than flat ground each pixel is lit, averaged over the antialiased contour's samples, each lighting a whole grid of the surface offset alike
|
||||||
|
let offsets = sample_offsets(surface.slope_antialiased && reshaped);
|
||||||
|
let mut brighter = Plane::<f32>::new(height.width, height.height);
|
||||||
|
for &offset in &offsets {
|
||||||
|
let mut shifted = Plane::<f32>::new(height.width, height.height);
|
||||||
|
fill_rows(&mut shifted.data, height.width, |y, row| {
|
||||||
|
row.iter_mut().enumerate().for_each(|(x, value)| *value = surface_at(x as isize, y as isize, offset) as f32)
|
||||||
|
});
|
||||||
|
|
||||||
|
let at = |x: isize, y: isize| shifted.data[(y.clamp(0, rows - 1) * columns + x.clamp(0, columns - 1)) as usize] as f64;
|
||||||
|
fill_rows(&mut brighter.data, height.width, |y, row| {
|
||||||
|
let y = y as isize;
|
||||||
|
for (x, brighter) in row.iter_mut().enumerate() {
|
||||||
|
let x = x as isize;
|
||||||
|
let across = at(x + 1, y - 1) + at(x + 1, y) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x - 1, y) - at(x - 1, y + 1);
|
||||||
|
let down = at(x - 1, y + 1) + at(x, y + 1) + at(x + 1, y + 1) - at(x - 1, y - 1) - at(x, y - 1) - at(x + 1, y - 1);
|
||||||
|
*brighter += ((bevel_lit(DVec2::new(across, down) * rise / 6., light) - light.z) / offsets.len() as f64) as f32;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// The gloss contour reshapes how lit each pixel is, averaged likewise over samples toward its neighbors when antialiased
|
||||||
|
let brighter = match gloss {
|
||||||
|
Some((gloss, antialiased)) => {
|
||||||
|
let offsets = sample_offsets(*antialiased);
|
||||||
|
let mut glossy = Plane::<f32>::new(height.width, height.height);
|
||||||
|
fill_rows(&mut glossy.data, height.width, |y, row| {
|
||||||
|
for (x, value) in row.iter_mut().enumerate() {
|
||||||
|
let lit = |offset| gloss.evaluate(sample_between(&brighter, x as isize, y as isize, offset) + light.z).clamp(0., 1.);
|
||||||
|
*value = (offsets.iter().map(|&offset| lit(offset)).sum::<f64>() / offsets.len() as f64 - light.z) as f32;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
glossy
|
||||||
|
}
|
||||||
|
None => brighter,
|
||||||
|
};
|
||||||
|
|
||||||
|
let amounts = brighter.map(|brighter| {
|
||||||
|
let (highlight, shadow) = bevel_lighting(brighter as f64, light.z);
|
||||||
|
[highlight as f32, shadow as f32, 0., 0.]
|
||||||
|
});
|
||||||
|
[amounts.map(|[highlight, ..]| highlight), amounts.map(|[_, shadow, ..]| shadow)]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bevel's highlight and shadow `amounts` beneath the content, faded out across the slopes' foot by their `height` (from -0.5 at the foot), as a gloss contour or texture needs.
|
||||||
|
/// For PSD interop, that keeps the flat ground they shade from reaching past the foot.
|
||||||
|
pub(super) fn foot_faded(amounts: [Plane<f32>; 2], height: &Plane<f32>) -> [Plane<f32>; 2] {
|
||||||
|
amounts.map(|amount| amount.zip(height, |amount, height| amount.min((height + 0.5) / BEVEL_FOOT_FADE as f32)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The most samples of grain a pixel takes.
|
||||||
|
const MAX_GRAIN_SAMPLES: usize = (MAX_FIELD_SAMPLES_PER_AXIS * MAX_FIELD_SAMPLES_PER_AXIS) as usize;
|
||||||
|
|
||||||
|
/// The random grain roughening a glow, as [`GlowFill::grained_color_at`] takes it.
|
||||||
|
pub(super) struct GlowGrain {
|
||||||
|
/// Where each pixel samples the grain, fixed to the cells of the effect space.
|
||||||
|
pub sampling: FieldSampling,
|
||||||
|
/// The field of the grain that the glow's seed gives.
|
||||||
|
field: u32,
|
||||||
|
/// How much each sample offsets the alpha (the noise) and moves a gradient's color (the jitter).
|
||||||
|
pub amounts: [f64; 2],
|
||||||
|
/// Which pixels the grain reaches, if not all of them.
|
||||||
|
reaches: Option<Vec<bool>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlowGrain {
|
||||||
|
/// The grain roughening a glow filled with `paint` by the `noise` and `jitter` percentages with its `seed`, on a plane that `plane_to_effect` places in the effect space, or `None` if it changes nothing.
|
||||||
|
pub fn new(paint: &GlowFill, noise: f64, jitter: f64, seed: i64, plane_to_effect: DAffine2) -> Option<Self> {
|
||||||
|
let amounts = paint.grain_amounts(noise, jitter)?;
|
||||||
|
|
||||||
|
Some(Self {
|
||||||
|
sampling: FieldSampling::new(plane_to_effect),
|
||||||
|
field: RandomField::GlowGrain.seed(seed),
|
||||||
|
amounts,
|
||||||
|
reaches: None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The grain kept to the pixels no farther than `reach` from the content's edge, given each pixel's `distances` to it as [`Plane::distances_to_silhouette`] measures them.
|
||||||
|
pub fn within(self, distances: &Plane<f32>, reach: f32) -> Self {
|
||||||
|
let reaches = Some(distances.data.iter().map(|&distance| distance <= reach).collect());
|
||||||
|
Self { reaches, ..self }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The grain's samples from -1 to 1 at the pixel in column and row `pixel` (`index` in its plane), as many as the sampling takes, or `None` past its reach.
|
||||||
|
pub fn samples(&self, pixel: [usize; 2], index: usize) -> Option<([f64; MAX_GRAIN_SAMPLES], usize)> {
|
||||||
|
if self.reaches.as_ref().is_some_and(|reaches| !reaches[index]) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut samples = [0.; MAX_GRAIN_SAMPLES];
|
||||||
|
let mut count = 0;
|
||||||
|
for cell in self.sampling.sample_cells(pixel).take(MAX_GRAIN_SAMPLES) {
|
||||||
|
samples[count] = 2. * field_values(cell, self.field)[0] as f64 - 1.;
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
Some((samples, count))
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
|||||||
use crate::blending::overlay_paint;
|
use crate::blending::overlay_paint;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
|
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||||
use graphic_types::adjustment::Adjustment;
|
use graphic_types::adjustment::Adjustment;
|
||||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||||
use graphic_types::effects::{EffectOperation, Effects};
|
use graphic_types::effects::{EffectOperation, Effects};
|
||||||
@@ -258,24 +258,9 @@ pub fn adjusted_gradient_with_blend_ifs(
|
|||||||
Some((resampled, resampled_settings))
|
Some((resampled, resampled_settings))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
|
|
||||||
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
|
|
||||||
pub fn carries_out_every_effect(effects: &Effects) -> bool {
|
|
||||||
effects.operations().all(|operation| match operation {
|
|
||||||
EffectOperation::Adjustment(_) => true,
|
|
||||||
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
|
|
||||||
_ => operation.changes_nothing(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||||
filled_color_after_effects(color, effects, 1.)
|
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||||
}
|
|
||||||
|
|
||||||
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
|
|
||||||
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
|
|
||||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||||
@@ -285,15 +270,10 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
|
|||||||
|
|
||||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||||
filled_gradient_after_effects(gradient, settings, effects, 1.)
|
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
|
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
|
||||||
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
|
|
||||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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.
|
/// A color without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
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 {
|
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||||
@@ -306,27 +286,6 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
|||||||
item
|
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.
|
/// 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.
|
/// A gradient without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||||
@@ -392,21 +351,6 @@ mod tests {
|
|||||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
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]
|
#[test]
|
||||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||||
use graphic_types::blend_if::BlendIfRanges;
|
use graphic_types::blend_if::BlendIfRanges;
|
||||||
@@ -480,8 +424,10 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
||||||
|
use crate::raster_effects::{evaluate_raster_effects, premultiplied_gamma_channels};
|
||||||
use graphic_types::EffectKind;
|
use graphic_types::EffectKind;
|
||||||
use graphic_types::blend_if::BlendIfRanges;
|
use graphic_types::blend_if::BlendIfRanges;
|
||||||
|
use raster_types::{Image, Raster};
|
||||||
|
|
||||||
// Shown only where the gray is at least half
|
// Shown only where the gray is at least half
|
||||||
let mut hides_darks = BlendIfRanges::default();
|
let mut hides_darks = BlendIfRanges::default();
|
||||||
@@ -495,8 +441,15 @@ mod tests {
|
|||||||
opacity: 100.,
|
opacity: 100.,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Black consumed as a color, which the GPU's render of a raster of it agrees with (`blend_ifs_hide_rasters_through_adjustments_raising_alpha_as_they_hide_values` in wgpu-executor)
|
// Black consumed as a color, which agrees with a raster's pixel of it
|
||||||
let black_through = |rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
let black_through = |name: &str, rows: &[(EffectOperation, f64)]| {
|
||||||
|
let color = *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
||||||
|
let raster = evaluate_raster_effects(stamped(Raster::new_cpu(Image::new(1, 1, Color::BLACK)), rows));
|
||||||
|
let pixel = raster.element().data.first().copied().unwrap_or(Color::TRANSPARENT);
|
||||||
|
let (color_channels, pixel_channels) = (premultiplied_gamma_channels(color), premultiplied_gamma_channels(pixel));
|
||||||
|
assert!(close(color_channels, pixel_channels), "black {name}: {color_channels:?} vs the raster's {pixel_channels:?}");
|
||||||
|
color
|
||||||
|
};
|
||||||
|
|
||||||
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
||||||
let hidden = [
|
let hidden = [
|
||||||
@@ -505,11 +458,11 @@ mod tests {
|
|||||||
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]),
|
("made opaque and painted in the next run", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 2.), (red.clone(), 2.)]),
|
||||||
];
|
];
|
||||||
for (name, rows) in hidden {
|
for (name, rows) in hidden {
|
||||||
assert_eq!(black_through(&rows).a(), 0., "black {name}");
|
assert_eq!(black_through(name, &rows).a(), 0., "black {name}");
|
||||||
}
|
}
|
||||||
|
|
||||||
// In its own run, an overlay still paints within the full-strength black
|
// In its own run, an overlay still paints within the full-strength black
|
||||||
let painted = black_through(&[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
|
let painted = black_through("made opaque and painted", &[(blend_if.clone(), 1.), (make_opaque.clone(), 1.), (red, 1.)]);
|
||||||
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
|
assert!(close(gamma(painted), [1., 0., 0., 1.]), "{:?}", gamma(painted));
|
||||||
|
|
||||||
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
|
// A ramp made opaque stays hidden where it's dark, in the Blend If's run or the next
|
||||||
|
|||||||
@@ -0,0 +1,684 @@
|
|||||||
|
//! The Warp on the CPU, drawing the triangles of its tessellated patch in the order the GPU's mesh pass does.
|
||||||
|
|
||||||
|
use crate::effect_kernels::Plane;
|
||||||
|
use crate::resample_kernels::{pixel_area_within, sample_bilinear_within};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::resampling::{EffectFrame, WarpFragment, WarpTessellation};
|
||||||
|
use graphic_types::warp::WarpMesh;
|
||||||
|
use raster_types::parallel_rows::fill_rows;
|
||||||
|
|
||||||
|
/// A triangle of the tessellation, as its corners in the texels and their parameters (s, t), wound clockwise on screen.
|
||||||
|
struct Triangle {
|
||||||
|
corners: [DVec2; 3],
|
||||||
|
parameters: [DVec2; 3],
|
||||||
|
/// Twice its area.
|
||||||
|
area: f64,
|
||||||
|
/// Whether the patch turns its sheet over here, as where it folds over itself.
|
||||||
|
reversed: bool,
|
||||||
|
/// The part of the warp it draws.
|
||||||
|
fragment: WarpFragment,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Triangle {
|
||||||
|
/// The triangle drawing a `fragment` with these corners, wound clockwise on screen, or `None` if it covers no area.
|
||||||
|
/// It's reversed where its winding disagrees with the square's `orientation` (the sign of its placement's determinant), which is 0 for the fringe.
|
||||||
|
fn new(mut corners: [(DVec2, DVec2); 3], orientation: f64, fragment: WarpFragment) -> Option<Self> {
|
||||||
|
let area = |corners: &[(DVec2, DVec2); 3]| (corners[1].1 - corners[0].1).perp_dot(corners[2].1 - corners[0].1);
|
||||||
|
let reversed = area(&corners) * orientation < 0.;
|
||||||
|
if area(&corners) < 0. {
|
||||||
|
corners.swap(1, 2);
|
||||||
|
}
|
||||||
|
let area = area(&corners);
|
||||||
|
(area > 0. && area.is_finite()).then(|| Self {
|
||||||
|
corners: corners.map(|(_, texel)| texel),
|
||||||
|
parameters: corners.map(|(parameters, _)| parameters),
|
||||||
|
area,
|
||||||
|
reversed,
|
||||||
|
fragment,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The parameters (s, t) interpolated at a `point` in the texels, if the triangle covers it.
|
||||||
|
/// A point on an edge belongs to the triangle only along its top or left edges, so the triangles sharing it cover it once.
|
||||||
|
fn interpolated(&self, point: DVec2) -> Option<DVec2> {
|
||||||
|
let mut weights = [0.; 3];
|
||||||
|
for edge in 0..3 {
|
||||||
|
let (start, end) = (self.corners[(edge + 1) % 3], self.corners[(edge + 2) % 3]);
|
||||||
|
|
||||||
|
// Measured from the same end of the edge for both triangles sharing it, so roundoff can't leave a point on it outside both
|
||||||
|
let side = match (start.x, start.y) < (end.x, end.y) {
|
||||||
|
true => (end - start).perp_dot(point - start),
|
||||||
|
false => -(start - end).perp_dot(point - end),
|
||||||
|
};
|
||||||
|
|
||||||
|
// On screen, clockwise winding puts the top edge heading right and the left edges heading up
|
||||||
|
let top_or_left = (start.y == end.y && end.x > start.x) || end.y < start.y;
|
||||||
|
if side < 0. || (side == 0. && !top_or_left) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
weights[edge] = side / self.area;
|
||||||
|
}
|
||||||
|
Some(self.parameters[0] * weights[0] + self.parameters[1] * weights[1] + self.parameters[2] * weights[2])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Warp of the `mesh` (as fractions of its square) prepared for planes of one size, matching the GPU's mesh pass, so several planes warp through it with the work shared.
|
||||||
|
/// The fringe past the square's sides and corners is drawn first, then each triangle of the tessellation paints over those before it the content within the square that its texels' polished sources read,
|
||||||
|
/// leaving clear all that the bent square doesn't cover. For PSD interop, where it folds, the sheet turned over shows on top, like a flap of paper folded toward the viewer, so its triangles are drawn after the rest.
|
||||||
|
pub struct WarpRasterizer {
|
||||||
|
square: EffectFrame,
|
||||||
|
tessellation: Option<WarpTessellation>,
|
||||||
|
triangles: Vec<Option<Triangle>>,
|
||||||
|
/// The triangles each row of pixel centers may cross, in the order they're drawn.
|
||||||
|
crossing: Vec<Vec<u32>>,
|
||||||
|
width: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl WarpRasterizer {
|
||||||
|
/// The warp of the `mesh` within the `square` (see [`graphic_types::resampling::warp_frame`]) for planes `width` by `height`. O(triangles and the rows they cross).
|
||||||
|
pub fn new(mesh: &WarpMesh, square: &EffectFrame, width: usize, height: usize) -> Self {
|
||||||
|
let tessellation = WarpTessellation::new(mesh, square, DVec2::new(width as f64, height as f64));
|
||||||
|
let mut triangles = Vec::new();
|
||||||
|
let mut crossing: Vec<Vec<u32>> = vec![Vec::new(); height];
|
||||||
|
|
||||||
|
if let Some(tessellation) = &tessellation {
|
||||||
|
// The fringe's quads along the left, right, top, and bottom sides, then past the corners where both sides meet, each split into two triangles as the GPU draws them
|
||||||
|
let [columns, rows] = tessellation.cells;
|
||||||
|
let quad = |[first, second, third, fourth]: [(DVec2, DVec2); 4], fragment| [Triangle::new([first, second, third], 0., fragment), Triangle::new([first, third, fourth], 0., fragment)];
|
||||||
|
for side in (0..4).filter(|&side| tessellation.sides[side]) {
|
||||||
|
let segments = if side < 2 { rows } else { columns };
|
||||||
|
for along in 0..segments {
|
||||||
|
let corners = [(along, false), (along + 1, false), (along + 1, true), (along, true)].map(|(along, outer)| tessellation.fringe_vertex(side, along, outer));
|
||||||
|
triangles.extend(quad(corners, WarpFragment::PastSide(side)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for corner in (0..4).filter(|&corner| tessellation.sides[corner % 2] && tessellation.sides[2 + corner / 2]) {
|
||||||
|
let corners = [[false, false], [true, false], [true, true], [false, true]].map(|outer| tessellation.corner_vertex(corner, outer));
|
||||||
|
triangles.extend(quad(corners, WarpFragment::PastCorner(corner)));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Each cell's two triangles, cell by cell across each row of cells and row by row down, as the GPU draws them
|
||||||
|
let vertices: Vec<(DVec2, DVec2)> = (0..=rows)
|
||||||
|
.flat_map(|row| (0..=columns).map(move |column| (column, row)))
|
||||||
|
.map(|index| tessellation.vertex(index.into()))
|
||||||
|
.collect();
|
||||||
|
let corner = |column: u32, row: u32| vertices[(row * (columns + 1) + column) as usize];
|
||||||
|
let orientation = tessellation.source.matrix2.determinant().signum();
|
||||||
|
triangles.reserve(2 * (columns * rows) as usize);
|
||||||
|
for row in 0..rows {
|
||||||
|
for column in 0..columns {
|
||||||
|
let [top_left, top_right, bottom_left, bottom_right] = [corner(column, row), corner(column + 1, row), corner(column, row + 1), corner(column + 1, row + 1)];
|
||||||
|
triangles.extend([
|
||||||
|
Triangle::new([top_left, top_right, bottom_right], orientation, WarpFragment::Within),
|
||||||
|
Triangle::new([top_left, bottom_right, bottom_left], orientation, WarpFragment::Within),
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Those turned over are drawn after the rest
|
||||||
|
let drawn = [false, true]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|reversed| (triangles.iter().enumerate()).filter_map(move |(index, triangle)| Some((index, triangle.as_ref().filter(|triangle| triangle.reversed == reversed)?))));
|
||||||
|
for (index, triangle) in drawn {
|
||||||
|
let (top, bottom) = triangle
|
||||||
|
.corners
|
||||||
|
.iter()
|
||||||
|
.fold((f64::INFINITY, f64::NEG_INFINITY), |(top, bottom), corner| (top.min(corner.y), bottom.max(corner.y)));
|
||||||
|
let first = (top - 0.5).ceil().max(0.);
|
||||||
|
let last = (bottom - 0.5).floor().min(height as f64 - 1.);
|
||||||
|
if first <= last {
|
||||||
|
(first as usize..=last as usize).for_each(|y| crossing[y].push(index as u32));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Self {
|
||||||
|
square: *square,
|
||||||
|
tessellation,
|
||||||
|
triangles,
|
||||||
|
crossing,
|
||||||
|
width,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The `plane` (of the size the warp was prepared for) carried through the warp. O(width × height).
|
||||||
|
pub fn warped(&self, plane: &Plane<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||||
|
if plane.width != self.width || plane.height != self.crossing.len() {
|
||||||
|
log::error!(
|
||||||
|
"A Warp prepared for {} by {} pixels was given a plane {} by {}",
|
||||||
|
self.width,
|
||||||
|
self.crossing.len(),
|
||||||
|
plane.width,
|
||||||
|
plane.height
|
||||||
|
);
|
||||||
|
return plane.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut result = Plane::<[f32; 4]>::new(plane.width, plane.height);
|
||||||
|
let Some(tessellation) = &self.tessellation else { return result };
|
||||||
|
let area_within = pixel_area_within(&self.square);
|
||||||
|
|
||||||
|
// The triangles paint over each other from clear
|
||||||
|
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||||
|
let center_y = y as f64 + 0.5;
|
||||||
|
for triangle in self.crossing[y].iter().filter_map(|&index| self.triangles[index as usize].as_ref()) {
|
||||||
|
let (left, right) = triangle
|
||||||
|
.corners
|
||||||
|
.iter()
|
||||||
|
.fold((f64::INFINITY, f64::NEG_INFINITY), |(left, right), corner| (left.min(corner.x), right.max(corner.x)));
|
||||||
|
let first = (left - 0.5).ceil().max(0.);
|
||||||
|
let last = (right - 0.5).floor().min(plane.width as f64 - 1.);
|
||||||
|
if first > last {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (x, pixel) in row.iter_mut().enumerate().take(last as usize + 1).skip(first as usize) {
|
||||||
|
let target = DVec2::new(x as f64 + 0.5, center_y);
|
||||||
|
let Some(seed) = triangle.interpolated(target) else { continue };
|
||||||
|
let parameters = match triangle.fragment {
|
||||||
|
WarpFragment::Within => tessellation.polished(seed, target),
|
||||||
|
_ => seed,
|
||||||
|
};
|
||||||
|
|
||||||
|
// The content within the square there, faded by how much of the pixel the warped square covers, painted over what earlier triangles left
|
||||||
|
let shade = tessellation.shade(triangle.fragment, parameters, target);
|
||||||
|
let coverage = shade.coverage as f32;
|
||||||
|
if coverage <= 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let color = sample_bilinear_within(plane, tessellation.source.transform_point2(shade.read), &area_within);
|
||||||
|
let painted = color.map(|channel| channel * coverage);
|
||||||
|
*pixel = std::array::from_fn(|channel| painted[channel] + pixel[channel] * (1. - painted[3]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use glam::{DAffine2, UVec2};
|
||||||
|
use graphic_types::resampling::{warp_frame, warp_half_fade};
|
||||||
|
use graphic_types::warp::{Warp, WarpStyle};
|
||||||
|
|
||||||
|
/// The plane carried through the Warp of the `mesh` (as fractions of the `square`).
|
||||||
|
fn warped_plane(plane: &Plane<[f32; 4]>, mesh: &WarpMesh, square: &EffectFrame) -> Plane<[f32; 4]> {
|
||||||
|
WarpRasterizer::new(mesh, square, plane.width, plane.height).warped(plane)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A plane 60 by 40 of colors ramping across and down, with the warp's square its middle 40 by 20 pixels.
|
||||||
|
fn ramps() -> (Plane<[f32; 4]>, EffectFrame) {
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||||
|
plane.data = (0..60 * 40).map(|index| [(index % 60) as f32 / 60., (index / 60) as f32 / 40., 0.5, 1.]).collect();
|
||||||
|
let square = warp_frame(DAffine2::from_translation(DVec2::new(30., 20.)) * DAffine2::from_scale(DVec2::new(40., 20.)), DAffine2::IDENTITY).unwrap();
|
||||||
|
(plane, square)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn warp(style: WarpStyle, bend: f64) -> Warp {
|
||||||
|
Warp {
|
||||||
|
style,
|
||||||
|
bend,
|
||||||
|
horizontal_distortion: 0.,
|
||||||
|
vertical_distortion: 0.,
|
||||||
|
vertical: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_warp_without_bend_leaves_every_pixel_within_its_square_as_it_is_and_clears_the_rest() {
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.).mesh(square.size), &square);
|
||||||
|
|
||||||
|
// The square's sides run along the pixels' edges, so each pixel lies wholly within or past it
|
||||||
|
for (index, (warped, original)) in warped.data.iter().zip(&plane.data).enumerate() {
|
||||||
|
let within = (10..50).contains(&(index % 60)) && (10..30).contains(&(index / 60));
|
||||||
|
let expected = if within { *original } else { [0.; 4] };
|
||||||
|
let difference = warped.iter().zip(expected).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
||||||
|
assert!(difference < 1e-4, "pixel {index} became {warped:?} rather than {expected:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn each_pixel_shows_the_content_where_the_patch_carries_it_from() {
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
let mesh = warp(WarpStyle::Flag, 0.3).mesh(square.size);
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// The ramps read back where each point of the square lands
|
||||||
|
for uv in [DVec2::new(0.2, 0.3), DVec2::new(0.5, 0.5), DVec2::new(0.85, 0.6)] {
|
||||||
|
let landed = square.to_pixels.transform_point2(mesh.point(uv));
|
||||||
|
let pixel = landed.floor();
|
||||||
|
let color = warped.data[pixel.y as usize * 60 + pixel.x as usize];
|
||||||
|
|
||||||
|
// The pixel's center reads from near the point, which the ramps show to within a pixel
|
||||||
|
let source = square.to_pixels.transform_point2(uv);
|
||||||
|
assert!((color[0] * 60. - source.x as f32).abs() < 1.5, "{uv} reads across from {}, not {}", color[0] * 60., source.x);
|
||||||
|
assert!((color[1] * 40. - source.y as f32).abs() < 1.5, "{uv} reads down from {}, not {}", color[1] * 40., source.y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn what_lies_outside_the_square_and_what_the_bend_leaves_of_it_clear() {
|
||||||
|
// A flag only raises and lowers the square's content, lowering its top edge on the left and raising it on the right
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
let mesh = warp(WarpStyle::Flag, 0.2).mesh(square.size);
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// Beside the square, and above it where the flag lowers its top edge, all is clear
|
||||||
|
for (x, y) in [(55, 20), (3, 35), (20, 3)] {
|
||||||
|
assert_eq!(warped.data[y * 60 + x], [0.; 4], "({x}, {y}) isn't clear");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Where it lowers the top edge, what it leaves of the square is clear, and where it raises it, the square's top row shows above the square
|
||||||
|
assert!(warped.data[10 * 60 + 20][3] < 1e-3, "the square's top left shows {:?}", warped.data[10 * 60 + 20]);
|
||||||
|
let raised = warped.data[8 * 60 + 40];
|
||||||
|
assert!((raised[1] * 40. - 10.5).abs() < 1.5 && raised[3] > 0.99, "above the square's top right shows {raised:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the patch of the `mesh` turns over anywhere within its unit square, so parts of it overlap, by the sign of its Jacobian across a dense grid.
|
||||||
|
fn folds(mesh: &WarpMesh) -> bool {
|
||||||
|
(0..65 * 65).any(|index| {
|
||||||
|
let [_, along_u, along_v] = mesh.point_and_tangents(DVec2::new((index % 65) as f64, (index / 65) as f64) / 64.);
|
||||||
|
along_u.perp_dot(along_v) <= 1e-9
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many points of the unit square the patch of `mesh` (in pixels) carries onto `point`, found by splitting the square until its parts are small, then polishing each part's middle onto it.
|
||||||
|
/// A part whose polish settles outside it, or nowhere, splits further, as beside a fold's crease, and the points found from several parts count once.
|
||||||
|
fn preimages(mesh: &WarpMesh, point: DVec2) -> usize {
|
||||||
|
let mut found: Vec<DVec2> = Vec::new();
|
||||||
|
let mut parts = vec![(DVec2::ZERO, DVec2::ONE)];
|
||||||
|
while let Some((start, end)) = parts.pop() {
|
||||||
|
let [min, max] = mesh.over(start, end).hull_bounds();
|
||||||
|
if point.cmplt(min).any() || point.cmpgt(max).any() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let middle = (start + end) / 2.;
|
||||||
|
let split = [
|
||||||
|
(start, middle),
|
||||||
|
(DVec2::new(middle.x, start.y), DVec2::new(end.x, middle.y)),
|
||||||
|
(DVec2::new(start.x, middle.y), DVec2::new(middle.x, end.y)),
|
||||||
|
(middle, end),
|
||||||
|
];
|
||||||
|
let size = (end - start).max_element();
|
||||||
|
if size > 1. / 64. {
|
||||||
|
parts.extend(split);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut uv = middle;
|
||||||
|
for _ in 0..16 {
|
||||||
|
let [landed, along_u, along_v] = mesh.point_and_tangents(uv);
|
||||||
|
let (residual, determinant) = (landed - point, along_u.perp_dot(along_v));
|
||||||
|
if determinant.abs() < 1e-12 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
uv -= DVec2::new(residual.perp_dot(along_v), along_u.perp_dot(residual)) / determinant;
|
||||||
|
}
|
||||||
|
|
||||||
|
let settled = (mesh.point(uv) - point).length() < 1e-6;
|
||||||
|
if settled && uv.cmpge(DVec2::ZERO).all() && uv.cmple(DVec2::ONE).all() && found.iter().all(|other| other.distance(uv) > 1e-7) {
|
||||||
|
found.push(uv);
|
||||||
|
}
|
||||||
|
let within_part = uv.cmpge(start - 1e-9).all() && uv.cmple(end + 1e-9).all();
|
||||||
|
if !(settled && within_part) && size > 1. / 4096. {
|
||||||
|
parts.extend(split);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many layers of content show at each of 8 by 8 samples across `pixel` (its corner) after the Warp of the `mesh` (as fractions of the `square`):
|
||||||
|
/// one for each point of the square the patch carries onto it.
|
||||||
|
fn supersampled_layers(mesh: &WarpMesh, square: &EffectFrame, pixel: DVec2) -> [usize; 64] {
|
||||||
|
let in_pixels = mesh.transformed(square.to_pixels);
|
||||||
|
std::array::from_fn(|index| preimages(&in_pixels, pixel + (DVec2::new((index % 8) as f64, (index / 8) as f64) + 0.5) / 8.))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How much of the pixel with its corner at `pixel` the `square` itself covers, fading across its sides as a side the warp keeps in place does.
|
||||||
|
fn square_coverage(square: &EffectFrame, pixel: DVec2) -> f32 {
|
||||||
|
let (local, half, half_fade) = (square.pixels_to_local().transform_point2(pixel + 0.5), square.size / 2., warp_half_fade(square));
|
||||||
|
(0.5 + (half - local.abs()) / (2. * half_fade)).clamp(DVec2::ZERO, DVec2::ONE).element_product() as f32
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sides_a_bend_keeps_in_place_match_the_content_at_any_squeeze_and_offset() {
|
||||||
|
use WarpStyle::*;
|
||||||
|
|
||||||
|
// Content of one color reaching past a square 39 by 19 at quarter-pixel offsets and scaled between pixels (its corners on the reference's samples), and past squares slanted and turned off the grid,
|
||||||
|
// which fisheyes, waves, and twists bend across their range while keeping all four sides in place
|
||||||
|
let bends = (-25..=25)
|
||||||
|
.map(|step| step as f64 * 0.04)
|
||||||
|
.chain([0.58, 0.59, 0.6, 0.61, 0.66, 0.67, 0.68, 0.75, 0.76, 0.77, -0.59, -0.6, -0.76]);
|
||||||
|
let placements = [
|
||||||
|
DAffine2::from_cols_array(&[39., 0., 0., 19., 30., 20.]),
|
||||||
|
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.25, 20.5]),
|
||||||
|
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]),
|
||||||
|
DAffine2::from_cols_array(&[39., 0., 0., 19., 30.75, 20.75]),
|
||||||
|
DAffine2::from_cols_array(&[42.5, 0., 0., 20.75, 30.25, 20.375]),
|
||||||
|
DAffine2::from_cols_array(&[24., 0., 16., 14., 30.3, 20.6]),
|
||||||
|
DAffine2::from_translation(DVec2::new(30.4, 20.15)) * DAffine2::from_angle(0.5) * DAffine2::from_scale(DVec2::new(30., 14.)),
|
||||||
|
];
|
||||||
|
for (style, bend, placement) in [Fisheye, Wave, Twist]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(|style| bends.clone().flat_map(move |bend| placements.map(|placement| (style, bend, placement))))
|
||||||
|
{
|
||||||
|
let square = warp_frame(placement, DAffine2::IDENTITY).unwrap();
|
||||||
|
let mesh = warp(style, bend).mesh(square.size);
|
||||||
|
let folding = folds(&mesh);
|
||||||
|
let offset = placement.translation;
|
||||||
|
|
||||||
|
// The 3 by 3 pixels around each corner of an upright square, where its coverage is its area, with the layers a supersampled reference counts across them.
|
||||||
|
// A slanted square's edge fades by its coverage along its axes instead, as the square's own edge does, which the check of every pixel below holds it to.
|
||||||
|
let upright = placement.matrix2.x_axis.y == 0. && placement.matrix2.y_axis.x == 0.;
|
||||||
|
let corners = [DVec2::splat(-0.5), DVec2::new(0.5, -0.5), DVec2::new(-0.5, 0.5), DVec2::splat(0.5)].map(|corner| placement.transform_point2(corner));
|
||||||
|
let around_corners: Vec<(DVec2, [usize; 64])> = corners
|
||||||
|
.into_iter()
|
||||||
|
.filter(|_| upright)
|
||||||
|
.flat_map(|corner| (0..9).map(move |index| (corner - 1.5).floor() + DVec2::new((index % 3) as f64, (index / 3) as f64)))
|
||||||
|
.map(|pixel| (pixel, supersampled_layers(&mesh, &square, pixel)))
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
for alpha in [1., 0.5] {
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[alpha; 4]; 60 * 40],
|
||||||
|
..Plane::<[f32; 4]>::new(60, 40)
|
||||||
|
};
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// Where the patch doesn't fold, it shows the content within the square, clear past it, and the content faded by the square's coverage across its sides.
|
||||||
|
// Where it folds, the layers of opaque content cover at least that much.
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
let expected = alpha * square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
||||||
|
let error = pixel.iter().map(|channel| (channel - expected).abs()).fold(0., f32::max);
|
||||||
|
let (x, y) = (index % 60, index / 60);
|
||||||
|
if !folding {
|
||||||
|
assert!(
|
||||||
|
error < 1e-4,
|
||||||
|
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {pixel:?} rather than {expected} at ({x}, {y})"
|
||||||
|
);
|
||||||
|
} else if alpha == 1. {
|
||||||
|
assert!(pixel[3] > expected - 1e-4, "{style:?} at {bend} placed at {offset} shows {pixel:?}, short of {expected} at ({x}, {y})");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Around each corner, it matches the reference
|
||||||
|
for (pixel, layers) in &around_corners {
|
||||||
|
let reference = layers.iter().map(|&layers| 1. - (1. - alpha).powi(layers as i32)).sum::<f32>() / 64.;
|
||||||
|
let shown = warped.data[pixel.y as usize * 60 + pixel.x as usize][3];
|
||||||
|
assert!(
|
||||||
|
(shown - reference).abs() < 1e-3,
|
||||||
|
"{style:?} at {bend} placed at {offset}, alpha {alpha}, shows {shown} at {pixel} rather than {reference}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn strongly_bent_styles_keep_opaque_content_opaque_within_their_patch_at_any_scale() {
|
||||||
|
use WarpStyle::*;
|
||||||
|
|
||||||
|
// Opaque content past squares 120 by 90 at non-integer scales, which fish (whose sides curve back near each other) and other styles bend far, both ways and turned, and fish within smaller squares
|
||||||
|
let styles = [Fish, Arch, Bulge, Flag, Wave, Fisheye, Squeeze, Twist];
|
||||||
|
let cases = |styles: Vec<WarpStyle>, square: DVec2| {
|
||||||
|
styles.into_iter().flat_map(move |style| {
|
||||||
|
[-1., -0.6, 0.6, 1.].into_iter().flat_map(move |bend| {
|
||||||
|
[false, true]
|
||||||
|
.into_iter()
|
||||||
|
.flat_map(move |vertical| [0.91, 1.09, 1.37].map(move |scale| (style, bend, vertical, square * scale)))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
};
|
||||||
|
for (style, bend, vertical, size) in cases(styles.to_vec(), DVec2::new(120., 90.)).chain(cases(vec![Fish], DVec2::new(60., 40.))) {
|
||||||
|
let (width, height) = ((size.x * 3.) as usize, (size.y * 3.) as usize);
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[1.; 4]; width * height],
|
||||||
|
..Plane::<[f32; 4]>::new(width, height)
|
||||||
|
};
|
||||||
|
let center = DVec2::new(width as f64, height as f64) / 2. + DVec2::new(0.3, 0.2);
|
||||||
|
let square = warp_frame(DAffine2::from_translation(center) * DAffine2::from_scale(size), DAffine2::IDENTITY).unwrap();
|
||||||
|
let mesh = Warp { vertical, ..warp(style, bend) }.mesh(square.size);
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// Each pixel the patch carries a point of the square onto, which lies at least a pixel within the patch and two from the curves its sides bend into, is opaque
|
||||||
|
let in_pixels = mesh.transformed(square.to_pixels);
|
||||||
|
let sides: Vec<DVec2> = (0..=400)
|
||||||
|
.flat_map(|index| {
|
||||||
|
let t = index as f64 / 400.;
|
||||||
|
[DVec2::new(0., t), DVec2::new(1., t), DVec2::new(t, 0.), DVec2::new(t, 1.)]
|
||||||
|
})
|
||||||
|
.map(|uv| in_pixels.point(uv))
|
||||||
|
.collect();
|
||||||
|
for index in 0..101 * 101 {
|
||||||
|
let uv = DVec2::new((index % 101) as f64, (index / 101) as f64) / 100.;
|
||||||
|
let pixel = in_pixels.point(uv).floor();
|
||||||
|
let within_plane = pixel.cmpge(DVec2::ZERO).all() && pixel.x < width as f64 && pixel.y < height as f64;
|
||||||
|
if !within_plane || sides.iter().any(|side| side.distance(pixel + 0.5) < 2.) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
let alpha = warped.data[pixel.y as usize * width + pixel.x as usize][3];
|
||||||
|
let within_patch = || {
|
||||||
|
[DVec2::ZERO, DVec2::X, -DVec2::X, DVec2::Y, -DVec2::Y]
|
||||||
|
.iter()
|
||||||
|
.all(|&offset| preimages(&in_pixels, pixel + 0.5 + offset) > 0)
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
alpha > 0.99 || !within_patch(),
|
||||||
|
"{style:?} at {bend}, vertical {vertical}, within a square {size}, shows {alpha} at {pixel} from {uv}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sides_curving_sharply_toward_a_pixel_fade_it() {
|
||||||
|
// Opaque content past a square 10 by 200 that a flag waves far, so its top side's crest curves tightly past the pixel (28, 87), a third of a pixel within it
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[1.; 4]; 80 * 500],
|
||||||
|
..Plane::<[f32; 4]>::new(80, 500)
|
||||||
|
};
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[10., 0., 0., 200., 25.625, 300.75]), DAffine2::IDENTITY).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Flag, 1.).mesh(square.size), &square);
|
||||||
|
|
||||||
|
// It fades by the third of a pixel, as two thirds past the pixel's middle, though the curve's tangent where the pixel's source lies passes two pixels away
|
||||||
|
let alpha = warped.data[87 * 80 + 28][3];
|
||||||
|
assert!((alpha - 0.83).abs() < 0.02, "the pixel shows alpha {alpha}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fisheyes_squeezing_the_content_nearly_flat_against_a_side_keep_it_seamless() {
|
||||||
|
// Opaque content past a square with its top side three quarters of the way down a row of pixels, against which fisheyes squeeze the content nearly flat
|
||||||
|
for bend in [0.59, 0.6] {
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[1.; 4]; 60 * 40],
|
||||||
|
..Plane::<[f32; 4]>::new(60, 40)
|
||||||
|
};
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.25]), DAffine2::IDENTITY).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, bend).mesh(square.size), &square);
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
let expected = square_coverage(&square, DVec2::new((index % 60) as f64, (index / 60) as f64));
|
||||||
|
assert!(
|
||||||
|
(pixel[3] - expected).abs() < 1e-4,
|
||||||
|
"bent {bend}, ({}, {}) shows {pixel:?} rather than {expected}",
|
||||||
|
index % 60,
|
||||||
|
index / 60
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn slanted_squares_keep_the_content_as_it_is_past_corners_they_keep_in_place() {
|
||||||
|
// Opaque content past a square slanted to corners an eighth of a turn sharp, off the pixel grid, within which a fisheye keeps the sides in place
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[1.; 4]; 120 * 80],
|
||||||
|
..Plane::<[f32; 4]>::new(120, 80)
|
||||||
|
};
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[40., 0., 40., 40., 61., 40.75]), DAffine2::IDENTITY).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 0.4).mesh(square.size), &square);
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
let expected = square_coverage(&square, DVec2::new((index % 120) as f64, (index / 120) as f64));
|
||||||
|
assert!((pixel[3] - expected).abs() < 1e-4, "({}, {}) shows {pixel:?} rather than {expected}", index % 120, index / 120);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folds_returning_over_a_side_change_smoothly_as_the_side_moves() {
|
||||||
|
// Clear rows down through the one a square's top side runs through the middle of, and opaque rows below, which a fisheye folds out over the clear rows and back
|
||||||
|
let alpha_at = |down: f64| {
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||||
|
plane.data[11 * 60..].fill([1.; 4]);
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, down]), DAffine2::IDENTITY).unwrap();
|
||||||
|
warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square).data[10 * 60 + 30][3]
|
||||||
|
};
|
||||||
|
|
||||||
|
// Moving the side a fiftieth of a pixel across the pixel's center moves its fade only as far
|
||||||
|
let (above, below) = (alpha_at(19.99), alpha_at(20.01));
|
||||||
|
assert!((above - below).abs() < 0.03, "the pixel's alpha jumps from {above} to {below}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folds_out_past_a_side_clear_what_lies_outside_the_square_beneath_them() {
|
||||||
|
// Opaque rows down to just above a square's top side, and clear rows below, which a fisheye folds out over the rows above
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(60, 40);
|
||||||
|
plane.data[..10 * 60].fill([1.; 4]);
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[39., 0., 0., 19., 30.5, 20.]), DAffine2::IDENTITY).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Fisheye, 1.).mesh(square.size), &square);
|
||||||
|
|
||||||
|
// The fold carries only the square's clear content, and the rows above clear
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
assert!(pixel[3] < 1e-4, "({}, {}) shows {pixel:?}", index % 60, index / 60);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn content_well_outside_the_bent_square_clears() {
|
||||||
|
// Opaque content 80 by 60 pixels, within which a flag bends a square 30 by 20 at its middle
|
||||||
|
let plane = Plane {
|
||||||
|
data: vec![[1.; 4]; 80 * 60],
|
||||||
|
..Plane::<[f32; 4]>::new(80, 60)
|
||||||
|
};
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&[30., 0., 0., 20., 40., 30.]), DAffine2::IDENTITY).unwrap();
|
||||||
|
let mesh = warp(WarpStyle::Flag, 0.4).mesh(square.size);
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// The pixels within two and a half of where the patch carries the square, past which its edge's fade and its fringe's miters reach nothing
|
||||||
|
let in_pixels = mesh.transformed(square.to_pixels);
|
||||||
|
let mut near = vec![false; 80 * 60];
|
||||||
|
for index in 0..201 * 201 {
|
||||||
|
let point = in_pixels.point(DVec2::new((index % 201) as f64, (index / 201) as f64) / 200.);
|
||||||
|
for (x, y) in (-3..=3).flat_map(|y| (-3..=3).map(move |x| (x, y))) {
|
||||||
|
let pixel = (point - 0.5).round() + DVec2::new(x as f64, y as f64);
|
||||||
|
if (pixel + 0.5).distance(point) <= 2.5 && pixel.cmpge(DVec2::ZERO).all() && pixel.x < 80. && pixel.y < 60. {
|
||||||
|
near[pixel.y as usize * 80 + pixel.x as usize] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All else is clear, though the content was opaque there
|
||||||
|
let far: Vec<usize> = (0..80 * 60).filter(|&index| !near[index]).collect();
|
||||||
|
assert!(far.len() > 2000, "only {} pixels lie far from the patch", far.len());
|
||||||
|
for index in far {
|
||||||
|
assert_eq!(warped.data[index], [0.; 4], "({}, {}) shows {:?}", index % 80, index / 80, warped.data[index]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nothing_wholly_outside_a_slanted_or_turned_square_is_carried_through_it() {
|
||||||
|
// Clear content but for an opaque pixel just above the top side of a slanted square, which an upper arc raises past where the pixel lies,
|
||||||
|
// or just above the top corner of a square turned an eighth, which an arc bends far around
|
||||||
|
let cases = [
|
||||||
|
(UVec2::new(80, 40), UVec2::new(30, 9), WarpStyle::ArcUpper, 0.5, [40., 0., 40., 4., 50., 12.]),
|
||||||
|
(UVec2::new(80, 60), UVec2::new(40, 9), WarpStyle::Arc, 0.8, [20., 20., -20., 20., 40.5, 30.01]),
|
||||||
|
];
|
||||||
|
for (size, opaque, style, bend, transform) in cases {
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(size.x as usize, size.y as usize);
|
||||||
|
plane.data[(opaque.y * size.x + opaque.x) as usize] = [1.; 4];
|
||||||
|
let square = warp_frame(DAffine2::from_cols_array(&transform), DAffine2::IDENTITY).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(style, bend).mesh(square.size), &square);
|
||||||
|
|
||||||
|
// The patch carries none of the pixel anywhere, and the pixel clears where it lies
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
assert!(pixel[3] < 1e-3, "{style:?} shows {pixel:?} at ({}, {})", index % plane.width, index / plane.width);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn squares_far_smaller_than_a_pixel_paint_nothing_past_the_content() {
|
||||||
|
// Opaque content 25 pixels across at a hundredth of a pixel per unit, twisted within a square one unit across at its middle, which its reach keeps within the content
|
||||||
|
let mut plane = Plane::<[f32; 4]>::new(64, 64);
|
||||||
|
for y in 0..25 {
|
||||||
|
plane.data[y * 64..y * 64 + 25].fill([1.; 4]);
|
||||||
|
}
|
||||||
|
let square = warp_frame(DAffine2::from_translation(DVec2::splat(1275.)), DAffine2::from_scale(DVec2::splat(0.01))).unwrap();
|
||||||
|
let warped = warped_plane(&plane, &warp(WarpStyle::Twist, 0.8).mesh(square.size), &square);
|
||||||
|
|
||||||
|
for (index, pixel) in warped.data.iter().enumerate() {
|
||||||
|
let (x, y) = (index % 64, index / 64);
|
||||||
|
assert!((x < 25 && y < 25) || pixel[3] < 1e-3, "({x}, {y}) past the content shows {pixel:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn folds_show_the_sheet_turned_over_on_top() {
|
||||||
|
// Columns that double back across the middle, so it's covered by the left and right of the content and by the sheet between them turned over
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
||||||
|
let warped = warped_plane(&plane, &mesh, &square);
|
||||||
|
|
||||||
|
// For PSD interop, the middle shows the turned sheet, which reads near the content's middle rather than a quarter in from either side
|
||||||
|
let red = warped.data[20 * 60 + 30][0];
|
||||||
|
assert!((red - 0.49).abs() < 0.03, "the middle shows red {red}");
|
||||||
|
assert!(warped.data[20 * 60 + 30][3] > 0.999);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn mirrored_squares_fold_as_the_mirror_of_upright_ones() {
|
||||||
|
// The fold above in the square and content mirrored left to right, where the turned sheet winds the other way on screen
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
let mesh = WarpMesh(std::array::from_fn(|row| [0., 1.5, -0.5, 1.].map(|x| DVec2::new(x, row as f64 / 3.))));
|
||||||
|
let mirror = |index: usize| index - index % 60 + 59 - index % 60;
|
||||||
|
let mirrored_plane = Plane {
|
||||||
|
data: (0..60 * 40).map(|index| plane.data[mirror(index)]).collect(),
|
||||||
|
..plane.clone()
|
||||||
|
};
|
||||||
|
let mirrored_square = square.placed(DAffine2::from_translation(DVec2::new(60., 0.)) * DAffine2::from_scale(DVec2::new(-1., 1.)));
|
||||||
|
|
||||||
|
let upright = warped_plane(&plane, &mesh, &square);
|
||||||
|
let mirrored = warped_plane(&mirrored_plane, &mesh, &mirrored_square);
|
||||||
|
for (index, color) in upright.data.iter().enumerate() {
|
||||||
|
let difference = color.iter().zip(mirrored.data[mirror(index)]).map(|(a, b)| (a - b).abs()).fold(0., f32::max);
|
||||||
|
assert!(difference < 1e-3, "pixel {index} shows {color:?} upright but {:?} mirrored", mirrored.data[mirror(index)]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_style_at_its_extremes_paints_colors_within_range() {
|
||||||
|
use WarpStyle::*;
|
||||||
|
let (plane, square) = ramps();
|
||||||
|
|
||||||
|
for style in [Arc, ArcLower, ArcUpper, Arch, Bulge, ShellLower, ShellUpper, Flag, Wave, Fish, Rise, Fisheye, Inflate, Squeeze, Twist] {
|
||||||
|
for (bend, horizontal_distortion, vertical_distortion) in [(1., 0., 0.), (-1., 0., 0.), (1., 1., 1.), (-1., -1., 1.), (1., -1., -1.), (0., 1., -1.)] {
|
||||||
|
for vertical in [false, true] {
|
||||||
|
let warp = Warp {
|
||||||
|
style,
|
||||||
|
bend,
|
||||||
|
horizontal_distortion,
|
||||||
|
vertical_distortion,
|
||||||
|
vertical,
|
||||||
|
};
|
||||||
|
let warped = warped_plane(&plane, &warp.mesh(square.size), &square);
|
||||||
|
|
||||||
|
// Premultiplied, each color lies within its alpha, which lies within 0 to 1
|
||||||
|
let within = |pixel: &[f32; 4]| pixel.iter().all(|channel| channel.is_finite() && (0.0..=pixel[3] + 1e-4).contains(channel)) && pixel[3] <= 1. + 1e-4;
|
||||||
|
assert!(warped.data.iter().all(within), "{warp:?} paints colors out of range");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -312,29 +312,6 @@ mod cpu {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
|
|
||||||
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
|
|
||||||
pub struct Pixels(Raster<CPU>);
|
|
||||||
|
|
||||||
impl Pixels {
|
|
||||||
pub fn new(raster: Raster<CPU>) -> Self {
|
|
||||||
Self(raster)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn into_raster(self) -> Raster<CPU> {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for Pixels {
|
|
||||||
type Target = Image<Color>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
self.0.data()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub use gpu::GPU;
|
pub use gpu::GPU;
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
pub use gpu::{Texture, TextureWeakRef};
|
pub use gpu::{Texture, TextureWeakRef};
|
||||||
|
|||||||
@@ -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.
|
//! 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.
|
//! 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 or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
|
//! 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.
|
||||||
//! 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.
|
//! 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::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};
|
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.
|
/// What the GPU renders an image of for an SVG.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum DeferredContent {
|
pub enum DeferredContent {
|
||||||
/// 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.
|
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
|
||||||
Item(Graphic),
|
Item(Graphic),
|
||||||
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
/// 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.
|
/// 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,17 +1,14 @@
|
|||||||
use crate::deferred_image::{self, DeferredContent, DeferredImage};
|
|
||||||
use crate::renderer::{
|
use crate::renderer::{
|
||||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible,
|
||||||
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
|
||||||
};
|
};
|
||||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||||
use core_types::blending::BlendMode;
|
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::list::List;
|
use core_types::list::List;
|
||||||
use core_types::uuid::generate_uuid;
|
use core_types::uuid::generate_uuid;
|
||||||
use core_types::{ATTR_TRANSFORM, Color};
|
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
use graphic_types::resampling::frame_of_bounds;
|
use graphic_types::vector_types::gradient::GradientForm;
|
||||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
@@ -42,11 +39,13 @@ impl PaintTarget {
|
|||||||
pub trait RenderExt {
|
pub trait RenderExt {
|
||||||
type Output;
|
type Output;
|
||||||
|
|
||||||
/// The `render` draws the painted element in its user space before the `element_transform`, taking the paint's defs and any images the GPU renders for it.
|
/// `user_to_document` maps the user space the painted element sits in, before its `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view, in document pixels.
|
||||||
#[allow(clippy::too_many_arguments)]
|
#[allow(clippy::too_many_arguments)]
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
render: &mut SvgRender,
|
svg_defs: &mut String,
|
||||||
|
user_to_document: DAffine2,
|
||||||
|
paint_reach: f64,
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
stroke_transform: DAffine2,
|
||||||
@@ -73,7 +72,9 @@ impl RenderExt for List<Color> {
|
|||||||
|
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
_render: &mut SvgRender,
|
_svg_defs: &mut String,
|
||||||
|
_user_to_document: DAffine2,
|
||||||
|
_paint_reach: f64,
|
||||||
_item_transform: DAffine2,
|
_item_transform: DAffine2,
|
||||||
_element_transform: DAffine2,
|
_element_transform: DAffine2,
|
||||||
_stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
@@ -85,35 +86,26 @@ impl RenderExt for List<Color> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent.
|
||||||
/// 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.
|
||||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_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 mut stop = String::new();
|
||||||
|
|
||||||
let item = item?;
|
let item = item?;
|
||||||
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
|
let (stops, settings) = painted_gradient(item)?;
|
||||||
let shape = gradient_shape(item);
|
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
|
||||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
let mut samples = spread_adjusted_samples(&stops, settings, gradient_form);
|
||||||
with_two_stops_at_least(shape, &mut samples);
|
|
||||||
|
|
||||||
|
let paint_opacity = item.paint_opacity(for_mask);
|
||||||
if paint_opacity < 1. {
|
if paint_opacity < 1. {
|
||||||
for (_, color, _) in &mut samples {
|
for (_, color, _) in &mut samples {
|
||||||
*color = color.with_alpha(color.a() * paint_opacity);
|
*color = color.with_alpha(color.a() * paint_opacity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for &(position, color, original_midpoint) in &samples {
|
for (position, color, original_midpoint) in samples {
|
||||||
stop.push_str("<stop");
|
stop.push_str("<stop");
|
||||||
if position != 0. {
|
if position != 0. {
|
||||||
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
||||||
@@ -146,7 +138,13 @@ fn render_gradient_paint(
|
|||||||
|
|
||||||
let document_transform = item_transform * local_gradient_transform;
|
let document_transform = item_transform * local_gradient_transform;
|
||||||
|
|
||||||
let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape);
|
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_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
|
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
|
||||||
String::new()
|
String::new()
|
||||||
@@ -154,68 +152,49 @@ fn render_gradient_paint(
|
|||||||
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
|
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
|
||||||
};
|
};
|
||||||
|
|
||||||
// A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over
|
let gradient_id = generate_uuid();
|
||||||
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);
|
|
||||||
|
|
||||||
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));
|
match gradient_form {
|
||||||
let min = corners.into_iter().reduce(DVec2::min)?;
|
GradientForm::Linear => {
|
||||||
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);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (min, size) = pattern_area?;
|
|
||||||
let pattern_id = generate_uuid();
|
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
r#"<pattern id="{pattern_id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}" viewBox="{} {} {} {}">"#,
|
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
|
||||||
min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y
|
gradient_id, stop
|
||||||
);
|
);
|
||||||
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>");
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Some(pattern_id)
|
Some(gradient_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderExt for List<Gradient> {
|
impl RenderExt for List<Gradient> {
|
||||||
type Output = Option<u64>;
|
type Output = Option<u64>;
|
||||||
|
|
||||||
/// Adds the gradient def to the render's defs, returning the gradient ID, or `None` when the list is empty.
|
/// Adds the gradient def through mutating the first argument, returning the gradient ID, or `None` when the list is empty.
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
render: &mut SvgRender,
|
svg_defs: &mut String,
|
||||||
|
_user_to_document: DAffine2,
|
||||||
|
_paint_reach: f64,
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
bounds: DAffine2,
|
_bounds: DAffine2,
|
||||||
render_params: &RenderParams,
|
render_params: &RenderParams,
|
||||||
_target: PaintTarget,
|
_target: PaintTarget,
|
||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
render_gradient_paint(
|
render_gradient_paint(
|
||||||
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
|
(!self.is_empty()).then_some(ItemRef::ListItem(self, 0)),
|
||||||
&mut render.svg_defs,
|
svg_defs,
|
||||||
item_transform,
|
item_transform,
|
||||||
element_transform,
|
element_transform,
|
||||||
stroke_transform,
|
|
||||||
bounds,
|
|
||||||
render_params.for_mask,
|
render_params.for_mask,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -227,7 +206,9 @@ impl RenderExt for Stroke {
|
|||||||
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`.
|
/// Provide the shape-related SVG attributes for the stroke. The paint-related attributes for the stroke are generated from `Graphic::render` with `PaintTarget::Stroke`.
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
_render: &mut SvgRender,
|
_svg_defs: &mut String,
|
||||||
|
_user_to_document: DAffine2,
|
||||||
|
_paint_reach: f64,
|
||||||
_item_transform: DAffine2,
|
_item_transform: DAffine2,
|
||||||
_element_transform: DAffine2,
|
_element_transform: DAffine2,
|
||||||
_stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
@@ -286,7 +267,9 @@ impl RenderExt for Graphic {
|
|||||||
|
|
||||||
fn render(
|
fn render(
|
||||||
&self,
|
&self,
|
||||||
render: &mut SvgRender,
|
svg_defs: &mut String,
|
||||||
|
user_to_document: DAffine2,
|
||||||
|
paint_reach: f64,
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
stroke_transform: DAffine2,
|
||||||
@@ -295,32 +278,40 @@ impl RenderExt for Graphic {
|
|||||||
target: PaintTarget,
|
target: PaintTarget,
|
||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
let paint_attr = target.paint_attr();
|
let paint_attr = target.paint_attr();
|
||||||
let by_colors = paint_draws_by_its_colors(self);
|
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||||
Graphic::ColorList(color_list) if by_colors => color_list.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target),
|
Graphic::ColorList(color_list) => color_list.render(
|
||||||
Graphic::Gradient(item) if by_colors => render_gradient_paint(
|
svg_defs,
|
||||||
Some(ItemRef::Item(item)),
|
user_to_document,
|
||||||
&mut render.svg_defs,
|
paint_reach,
|
||||||
item_transform,
|
item_transform,
|
||||||
element_transform,
|
element_transform,
|
||||||
stroke_transform,
|
stroke_transform,
|
||||||
bounds,
|
bounds,
|
||||||
render_params.for_mask,
|
render_params,
|
||||||
)
|
target,
|
||||||
|
),
|
||||||
|
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask)
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.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
|
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||||
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
|
||||||
.render(render, item_transform, element_transform, stroke_transform, bounds, render_params, target)
|
.render(
|
||||||
|
svg_defs,
|
||||||
|
user_to_document,
|
||||||
|
paint_reach,
|
||||||
|
item_transform,
|
||||||
|
element_transform,
|
||||||
|
stroke_transform,
|
||||||
|
bounds,
|
||||||
|
render_params,
|
||||||
|
target,
|
||||||
|
)
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||||
Graphic::Color(_)
|
Graphic::Graphic(_)
|
||||||
| Graphic::ColorList(_)
|
|
||||||
| Graphic::Gradient(_)
|
|
||||||
| Graphic::Graphic(_)
|
|
||||||
| Graphic::Vector(_)
|
| Graphic::Vector(_)
|
||||||
| Graphic::RasterCPU(_)
|
| Graphic::RasterCPU(_)
|
||||||
| Graphic::RasterGPU(_)
|
| Graphic::RasterGPU(_)
|
||||||
@@ -344,7 +335,8 @@ impl RenderExt for Graphic {
|
|||||||
} else {
|
} else {
|
||||||
bounds
|
bounds
|
||||||
};
|
};
|
||||||
render_svg_pattern(render, self, element_transform * stroke_transform, stroke_transform, bounds, render_params)
|
let content_to_document = user_to_document * element_transform * stroke_transform;
|
||||||
|
render_svg_pattern(svg_defs, self, content_to_document, paint_reach, stroke_transform, bounds, render_params)
|
||||||
.map(|id| format!(r##" {paint_attr}="url(#{id})""##))
|
.map(|id| format!(r##" {paint_attr}="url(#{id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#))
|
||||||
}
|
}
|
||||||
@@ -352,10 +344,18 @@ impl RenderExt for Graphic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Emits an SVG `<pattern>` paint server into the render's defs that renders the given graphic as the paint content, and returns the pattern ID.
|
/// Emits an SVG `<pattern>` paint server into `svg_defs` that renders the given graphic as the paint content, and returns the pattern ID.
|
||||||
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
|
/// Currently, this function is only used for clipping-based filling and stroking, not considering tiling yet.
|
||||||
/// `content_transform` places the paint's own space in the render's user space, where `stroke_transform` places it inside the painted element's transform.
|
/// `content_to_document` maps the paint's own space, which `stroke_transform` places inside the painted element's `element_transform`, into the document, and the filters reading the element read it `paint_reach` past the view.
|
||||||
fn render_svg_pattern(render: &mut SvgRender, paint: &Graphic, content_transform: DAffine2, stroke_transform: DAffine2, bounds: DAffine2, render_params: &RenderParams) -> Option<String> {
|
fn render_svg_pattern(
|
||||||
|
svg_defs: &mut String,
|
||||||
|
paint: &Graphic,
|
||||||
|
content_to_document: DAffine2,
|
||||||
|
paint_reach: f64,
|
||||||
|
stroke_transform: DAffine2,
|
||||||
|
bounds: DAffine2,
|
||||||
|
render_params: &RenderParams,
|
||||||
|
) -> Option<String> {
|
||||||
let min = bounds.transform_point2(DVec2::ZERO);
|
let min = bounds.transform_point2(DVec2::ZERO);
|
||||||
let max = bounds.transform_point2(DVec2::ONE);
|
let max = bounds.transform_point2(DVec2::ONE);
|
||||||
let size = max - min;
|
let size = max - min;
|
||||||
@@ -364,42 +364,12 @@ fn render_svg_pattern(render: &mut SvgRender, paint: &Graphic, content_transform
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Render the pattern content recursively
|
// Render the pattern content recursively
|
||||||
let content_to_document = render.transform * content_transform;
|
|
||||||
let paint_params = render_params.for_pattern();
|
|
||||||
let mut content = SvgRender::new();
|
let mut content = SvgRender::new();
|
||||||
content.transform = content_to_document;
|
content.transform = content_to_document;
|
||||||
content.ancestors_reach = render.ancestors_reach;
|
content.ancestors_reach = paint_reach;
|
||||||
paint.render_svg(&mut content, &paint_params);
|
paint.render_svg(&mut content, &render_params.for_pattern());
|
||||||
let mut markup = content.svg.to_svg_string();
|
|
||||||
|
|
||||||
// A paint leaving out what only the GPU draws becomes the GPU's image of it, where something fills that
|
|
||||||
if content.paint_needs_gpu {
|
|
||||||
if render.drawing_deferred_markup || render_params.inside_pattern {
|
|
||||||
render.leave_out_for_gpu(render_params);
|
|
||||||
} else {
|
|
||||||
let id = generate_uuid();
|
|
||||||
render.deferred_images.push(DeferredImage {
|
|
||||||
id,
|
|
||||||
content: DeferredContent::Item(paint.clone()),
|
|
||||||
// Seen within the shape it fills, as Vello paints it
|
|
||||||
render_params: RenderParams {
|
|
||||||
paint_frame: Some(frame_of_bounds([min, max], content_to_document)),
|
|
||||||
..paint_params
|
|
||||||
},
|
|
||||||
user_to_document: content_to_document,
|
|
||||||
bounds: [min, max],
|
|
||||||
margin: render.ancestors_reach,
|
|
||||||
opacity: 1.,
|
|
||||||
blend_mode: BlendMode::Normal,
|
|
||||||
mask: None,
|
|
||||||
});
|
|
||||||
let (opening, closing) = deferred_image::image_markers(id);
|
|
||||||
markup = format!("{opening}{markup}{closing}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Unwrap the inner def element
|
// Unwrap the inner def element
|
||||||
let svg_defs = &mut render.svg_defs;
|
|
||||||
write!(svg_defs, "{}", content.svg_defs).unwrap();
|
write!(svg_defs, "{}", content.svg_defs).unwrap();
|
||||||
|
|
||||||
let pattern_transform = stroke_transform * DAffine2::from_translation(min);
|
let pattern_transform = stroke_transform * DAffine2::from_translation(min);
|
||||||
@@ -419,7 +389,7 @@ fn render_svg_pattern(render: &mut SvgRender, paint: &Graphic, content_transform
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
let content_shift = format_transform_matrix(DAffine2::from_translation(-min));
|
let content_shift = format_transform_matrix(DAffine2::from_translation(-min));
|
||||||
write!(svg_defs, r##"<g transform="{content_shift}">{markup}</g></pattern>"##).unwrap();
|
write!(svg_defs, r##"<g transform="{content_shift}">{}</g></pattern>"##, content.svg.to_svg_string()).unwrap();
|
||||||
|
|
||||||
Some(pattern_id)
|
Some(pattern_id)
|
||||||
}
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -7,7 +7,7 @@ use glam::DVec2;
|
|||||||
use graphic_types::effects::EffectCapture;
|
use graphic_types::effects::EffectCapture;
|
||||||
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
||||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||||
use raster_kernels::effect_planning::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
use raster_kernels::effect_kernels::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
||||||
use std::collections::BTreeMap;
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
||||||
@@ -98,8 +98,6 @@ impl SvgFilterPrimitives {
|
|||||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
EffectOperation::MinimumMaximum { .. } | EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||||
// No SVG primitive ranks values, and the GPU's median runs on the content's own grid besides
|
|
||||||
EffectOperation::Median { .. } => self.map_showing(capture, image),
|
|
||||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||||
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
EffectOperation::Speckle { amount, distribution, .. } => self.speckle(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ use glam::{DAffine2, DVec2};
|
|||||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||||
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
use graphic_types::masks::{MASK_LUMINANCE_WEIGHTS, MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||||
use graphic_types::{Appearance, Graphic};
|
use graphic_types::{Appearance, Graphic};
|
||||||
use raster_kernels::effect_planning::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
|
|
||||||
@@ -74,32 +74,21 @@ pub(super) fn holds_effects(graphic: &Graphic) -> bool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the graphic, anything nested in it, or any paint its appearance fills or strokes them with, is a GPU image or a generator, which only the GPU draws.
|
/// Whether the graphic or anything nested in it is a GPU image, which SVG markup can't draw.
|
||||||
fn holds_gpu_content(graphic: &Graphic) -> bool {
|
fn holds_gpu_image(graphic: &Graphic) -> bool {
|
||||||
fn paints_hold(appearance: Option<&Appearance>) -> bool {
|
|
||||||
appearance.is_some_and(|appearance| appearance.covers_with_paints().any(|(_, paint)| paint.is_some_and(holds_gpu_content)))
|
|
||||||
}
|
|
||||||
fn list_paints_hold<T>(list: &List<T>) -> bool {
|
|
||||||
(0..list.len()).any(|index| paints_hold(list.attribute(ATTR_APPEARANCE, index)))
|
|
||||||
}
|
|
||||||
|
|
||||||
match graphic {
|
match graphic {
|
||||||
Graphic::RasterGPU(_) | Graphic::Generator(_) => true,
|
Graphic::RasterGPU(_) => true,
|
||||||
Graphic::RasterGPUList(list) => !list.is_empty(),
|
Graphic::RasterGPUList(list) => !list.is_empty(),
|
||||||
Graphic::GeneratorList(list) => !list.is_empty(),
|
Graphic::Graphic(item) => holds_gpu_image(item.element()),
|
||||||
Graphic::Graphic(item) => paints_hold(item.attribute(ATTR_APPEARANCE)) || holds_gpu_content(item.element()),
|
Graphic::GraphicList(list) => list.iter_element_values().any(holds_gpu_image),
|
||||||
Graphic::GraphicList(list) => list_paints_hold(list) || list.iter_element_values().any(holds_gpu_content),
|
|
||||||
Graphic::Vector(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
|
|
||||||
Graphic::VectorList(list) => list_paints_hold(list),
|
|
||||||
Graphic::Text(item) => paints_hold(item.attribute(ATTR_APPEARANCE)),
|
|
||||||
Graphic::TextList(list) => list_paints_hold(list),
|
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether markup embedded as an image draws the graphic whole, which no map or image of the GPU's reaches, so it holds neither effects nor what only the GPU draws.
|
/// Whether SVG draws a blur's `radius_mask` as markup in its filter, keeping the blur resolution-independent, rather than taking its luminance as the GPU's map.
|
||||||
pub(super) fn draws_as_embedded_markup(graphic: &Graphic) -> bool {
|
/// Markup embedded as an image reaches no maps of the radius mask's own effects.
|
||||||
!holds_effects(graphic) && !holds_gpu_content(graphic)
|
pub(super) fn radius_mask_draws_as_markup(radius_mask: &Graphic) -> bool {
|
||||||
|
!holds_effects(radius_mask) && !holds_gpu_image(radius_mask)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A mask's graphic placed by its content's `placement`, which it follows.
|
/// A mask's graphic placed by its content's `placement`, which it follows.
|
||||||
@@ -198,7 +187,8 @@ pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effec
|
|||||||
mask_render.transform = render.transform;
|
mask_render.transform = render.transform;
|
||||||
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
|
mask_render.ancestors_reach = render.ancestors_reach + feather_reach;
|
||||||
mask.render_svg(&mut mask_render, &live_params);
|
mask.render_svg(&mut mask_render, &live_params);
|
||||||
render.take_gpu_images(&mut mask_render, render_params);
|
render.effect_maps.append(&mut mask_render.effect_maps);
|
||||||
|
render.deferred_images.append(&mut mask_render.deferred_images);
|
||||||
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
|
let markup = format!("<defs>{}</defs>{}", mask_render.svg_defs, mask_render.svg.to_svg_string());
|
||||||
|
|
||||||
let sigma = svg_feather_sigma(feather, length_scale);
|
let sigma = svg_feather_sigma(feather, length_scale);
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ use graphic_types::effects::{EffectCapture, GRADIENT_TABLE_SIZE, GlowFill};
|
|||||||
pub(super) enum OutlineBandColors {
|
pub(super) enum OutlineBandColors {
|
||||||
/// The markup of a drawn paint.
|
/// The markup of a drawn paint.
|
||||||
Drawn(String),
|
Drawn(String),
|
||||||
/// A drawn paint that embedding its markup as an image can't draw whole, which the GPU's map gives.
|
|
||||||
DrawnOnGpu,
|
|
||||||
ContourGradient(GlowFill),
|
ContourGradient(GlowFill),
|
||||||
/// The primitive holding the colors, once made.
|
/// The primitive holding the colors, once made.
|
||||||
Made(String),
|
Made(String),
|
||||||
@@ -20,10 +18,6 @@ impl SvgFilterPrimitives {
|
|||||||
let made = match colors {
|
let made = match colors {
|
||||||
OutlineBandColors::Made(made) => return made.clone(),
|
OutlineBandColors::Made(made) => return made.clone(),
|
||||||
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
|
OutlineBandColors::Drawn(markup) => self.paint_image(markup, region),
|
||||||
OutlineBandColors::DrawnOnGpu => self.map(EffectCapture {
|
|
||||||
index,
|
|
||||||
plane: EffectCapture::DRAWN_PAINT_PLANE,
|
|
||||||
}),
|
|
||||||
OutlineBandColors::ContourGradient(gradient) => {
|
OutlineBandColors::ContourGradient(gradient) => {
|
||||||
let positions = self.map(EffectCapture { index, plane: 2 });
|
let positions = self.map(EffectCapture { index, plane: 2 });
|
||||||
self.contour_gradient_colors(&positions, gradient)
|
self.contour_gradient_colors(&positions, gradient)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use graphic_types::effects::spans_along_axes;
|
|||||||
use graphic_types::{EffectOperation, Effects};
|
use graphic_types::{EffectOperation, Effects};
|
||||||
use kurbo::{BezPath, PathEl, Shape};
|
use kurbo::{BezPath, PathEl, Shape};
|
||||||
use linesweeper::topology::Topology;
|
use linesweeper::topology::Topology;
|
||||||
use raster_kernels::effect_planning::NEGLIGIBLE_LENGTH;
|
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
@@ -219,7 +219,7 @@ impl SvgRender {
|
|||||||
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
/// Whether the markup drawn since the backdrop `root` draws through canvases, as images and the GPU's images of content do in the viewport the `render_params` draw in,
|
||||||
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
/// even where the content reading it embeds its own images. O(segments drawn since the root).
|
||||||
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
fn draws_canvases_since(&self, root: usize, render_params: &RenderParams) -> bool {
|
||||||
let in_viewport = !(render_params.for_export || render_params.for_mask || render_params.inside_pattern);
|
let in_viewport = !(render_params.for_export || render_params.thumbnail || render_params.for_mask || render_params.inside_pattern);
|
||||||
let start = self.open_groups.groups[root].content_start;
|
let start = self.open_groups.groups[root].content_start;
|
||||||
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
let draws_canvas = |segment: &SvgSegment| segment.as_str().contains("data-canvas-placeholder") || deferred_image::holds_image_markers(segment.as_str());
|
||||||
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
in_viewport && self.svg[start..].iter().any(draws_canvas)
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
|||||||
use std::borrow::Cow;
|
use std::borrow::Cow;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
|
use vello_gpu::peniko::{self, BlendMode, BrushRef, Fill};
|
||||||
use vello_gpu::{Image, ImageSource, PaintType, PencilGradient, TextureId, TextureRegion};
|
use vello_gpu::{Image, ImageSource, PaintType, TextureId, TextureRegion};
|
||||||
|
|
||||||
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
/// Tolerance for turning shapes other than paths into paths, matching Vello's own.
|
||||||
const SHAPE_TOLERANCE: f64 = 0.1;
|
const SHAPE_TOLERANCE: f64 = 0.1;
|
||||||
@@ -94,51 +94,6 @@ 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.
|
/// The pixels behind an image the scene draws.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Clone, Debug)]
|
||||||
pub enum SceneImage {
|
pub enum SceneImage {
|
||||||
@@ -315,41 +270,44 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Fills a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
/// 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<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
pub fn fill<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||||
self.fill_path(fill_rule, transform, brush, brush_transform, &shape.to_path(SHAPE_TOLERANCE));
|
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.
|
/// 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<SceneBrush<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
pub fn fill_path<'b>(&mut self, fill_rule: Fill, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, path: &BezPath) {
|
||||||
if !self.drawing {
|
if !self.drawing {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||||
self.scene.set_transform(self.view * transform);
|
self.scene.set_transform(self.view * transform);
|
||||||
self.scene.set_fill_rule(fill_rule);
|
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.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||||
self.scene.fill_path(&finite_path(path));
|
self.scene.fill_path(&finite_path(path));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Strokes a shape given in the space of `transform`, with the brush placed by `transform * brush_transform`.
|
/// 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<SceneBrush<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
pub fn stroke<'b>(&mut self, stroke: &Stroke, transform: Affine, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>, shape: &impl Shape) {
|
||||||
if !self.drawing {
|
if !self.drawing {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||||
self.scene.set_transform(self.view * transform);
|
self.scene.set_transform(self.view * transform);
|
||||||
self.scene.set_stroke(stroke.clone());
|
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.set_paint_transform(brush_transform.unwrap_or(Affine::IDENTITY) * paint_to_brush);
|
||||||
self.scene.stroke_path(&finite_path(&shape.to_path(SHAPE_TOLERANCE)));
|
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.
|
/// 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<SceneBrush<'b>>, brush_transform: Option<Affine>) {
|
pub fn fill_viewport<'b>(&mut self, brush: impl Into<BrushRef<'b>>, brush_transform: Option<Affine>) {
|
||||||
if !self.drawing {
|
if !self.drawing {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
let Some(paint_to_brush) = self.set_paint(brush.into()) else { return };
|
let Some((paint, paint_to_brush)) = self.paint(brush.into()) else { return };
|
||||||
self.scene.set_transform(Affine::IDENTITY);
|
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.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));
|
self.scene.fill_rect(&Rect::new(0., 0., self.width() as f64, self.height() as f64));
|
||||||
}
|
}
|
||||||
@@ -584,12 +542,9 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
square && !operation.changes_nothing()
|
square && !operation.changes_nothing()
|
||||||
});
|
});
|
||||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||||
// Effects that don't commute with resampling, like a median, work on the content's own grid of a texel to each unit of the effect space, then resample to the view
|
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||||
let content_grid_resolution = effects.content_grid_resolution();
|
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||||
let (frame_to_device, lengths_to_frame) = match (content_grid_resolution, follows_viewport) {
|
false => {
|
||||||
(Some(_), _) => (effect_to_device, DMat2::IDENTITY),
|
|
||||||
(None, true) => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
|
||||||
(None, false) => {
|
|
||||||
let density = largest_stretch(effect_to_device.matrix2);
|
let density = largest_stretch(effect_to_device.matrix2);
|
||||||
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
(effect_to_device * DAffine2::from_scale(DVec2::splat(1. / density)), DMat2::from_diagonal(DVec2::splat(density)))
|
||||||
}
|
}
|
||||||
@@ -650,15 +605,7 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
|
|
||||||
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
// A region too large for one texture, or for its memory, renders at a lower resolution, which the blurs and shadows that make it so large hide.
|
||||||
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
// Its size rounds up to a size class so a group that moves between renders keeps reusing the same textures.
|
||||||
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt());
|
let resolution = (max_size as f64 / region.width().max(region.height())).min((max_area / region.area()).sqrt()).min(1.);
|
||||||
let resolution = resolution.min(content_grid_resolution.unwrap_or(1.)).min(1.);
|
|
||||||
|
|
||||||
// A coarsened content grid keeps its texels on one lattice of the effect space, so they don't slide across the content as the view pans
|
|
||||||
if content_grid_resolution.is_some() && resolution < 1. {
|
|
||||||
let snap = |coordinate: f64| (coordinate * resolution).floor() / resolution;
|
|
||||||
region = Rect::new(snap(region.x0), snap(region.y0), region.x1, region.y1);
|
|
||||||
}
|
|
||||||
|
|
||||||
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
let size_along = |length: f64| ((length * resolution).ceil() as u32).next_multiple_of(EFFECTS_SIZE_CLASS).min(max_size);
|
||||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||||
let origin = region.origin().to_vec2();
|
let origin = region.origin().to_vec2();
|
||||||
@@ -751,27 +698,22 @@ impl<'a> VelloSceneBuilder<'a> {
|
|||||||
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
|
self.scene.fill_rect(&Rect::new(0., 0., width as f64, height as f64));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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).
|
/// 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 set_paint(&mut self, brush: SceneBrush<'_>) -> Option<Affine> {
|
fn paint(&mut self, brush: BrushRef<'_>) -> Option<(PaintType, Affine)> {
|
||||||
let (paint, paint_to_brush) = match brush {
|
match brush {
|
||||||
SceneBrush::Apollonian(gradient) => {
|
BrushRef::Solid(color) => Some((PaintType::Solid(color), Affine::IDENTITY)),
|
||||||
self.scene.set_pencil_gradient_paint(gradient.clone());
|
BrushRef::Gradient(gradient) => Some((PaintType::Gradient(gradient.clone()), Affine::IDENTITY)),
|
||||||
return Some(Affine::IDENTITY);
|
BrushRef::Image(image) => {
|
||||||
}
|
|
||||||
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 (source, texture_to_image, _) = self.image_source(SceneImage::Pixels(image.image.clone()))?;
|
||||||
let paint = PaintType::Image(Image {
|
Some((
|
||||||
|
PaintType::Image(Image {
|
||||||
image: source,
|
image: source,
|
||||||
sampler: image.sampler,
|
sampler: image.sampler,
|
||||||
});
|
}),
|
||||||
(paint, texture_to_image)
|
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.
|
/// 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 crate::{affine, color};
|
||||||
use core_types::list::{ATTR_POSITION, Item};
|
use core_types::list::{ATTR_POSITION, Item};
|
||||||
use core_types::{ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_TRANSFORM};
|
use core_types::{ATTR_GRADIENT_FORM, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_TRANSFORM};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
|
use graphic_types::vector_types::{Gradient, GradientForm, GradientSpace, GradientSpread};
|
||||||
@@ -31,9 +31,7 @@ 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);
|
let mut item = Item::new_from_element(Gradient(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma);
|
||||||
|
|
||||||
if form != GradientForm::default() {
|
if form != GradientForm::default() {
|
||||||
let [start_curvature, end_curvature] = form.curvatures();
|
item.set_attribute(ATTR_GRADIENT_FORM, form);
|
||||||
item.set_attribute(ATTR_GRADIENT_START_CURVATURE, start_curvature);
|
|
||||||
item.set_attribute(ATTR_GRADIENT_END_CURVATURE, end_curvature);
|
|
||||||
}
|
}
|
||||||
let spread = match gradient.spread_method() {
|
let spread = match gradient.spread_method() {
|
||||||
usvg::SpreadMethod::Pad => GradientSpread::Pad,
|
usvg::SpreadMethod::Pad => GradientSpread::Pad,
|
||||||
|
|||||||
@@ -1,8 +1,5 @@
|
|||||||
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
use core_types::list::{ATTR_APPEARANCE, Item, List};
|
||||||
use core_types::{
|
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};
|
||||||
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 glam::{DAffine2, DVec2};
|
||||||
use graphic_types::effects::shadow_offset;
|
use graphic_types::effects::shadow_offset;
|
||||||
use graphic_types::raster_types::{Image, Raster};
|
use graphic_types::raster_types::{Image, Raster};
|
||||||
@@ -180,11 +177,7 @@ 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 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);
|
let gradient = gradient_of(&content, Cover::Fill);
|
||||||
let curvature = |key| gradient.and_then(|gradient| gradient.attribute::<f64>(key)).copied();
|
assert_eq!(gradient.and_then(|gradient| gradient.attribute::<GradientForm>(ATTR_GRADIENT_FORM)), Some(&GradientForm::Radial));
|
||||||
assert_eq!(
|
|
||||||
[curvature(ATTR_GRADIENT_START_CURVATURE), curvature(ATTR_GRADIENT_END_CURVATURE)],
|
|
||||||
GradientForm::Radial.curvatures().map(Some)
|
|
||||||
);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
gradient.and_then(|gradient| gradient.attribute::<DAffine2>(ATTR_TRANSFORM)),
|
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.)))
|
Some(&DAffine2::from_cols(DVec2::new(4., 0.), DVec2::new(0., 2.), DVec2::new(4., 2.)))
|
||||||
@@ -211,7 +204,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
|
|||||||
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
|
||||||
|
|
||||||
let clipped = group(&content, 0);
|
let clipped = group(&content, 0);
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||||
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -314,7 +307,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
|
|||||||
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
|
||||||
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
|
||||||
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
let clipped = within_region.and_then(Graphic::as_graphic_list);
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
|
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
|
||||||
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,40 +17,6 @@ pub enum GradientForm {
|
|||||||
Radial,
|
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`
|
/// 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,
|
/// 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`).
|
/// and stops lacking the `midpoint` attribute interpolate linearly (`0.5`).
|
||||||
@@ -1843,19 +1809,6 @@ 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)]
|
#[repr(C)]
|
||||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
#[derive(Default, PartialEq, Eq, Clone, Copy, Debug, Hash, graphene_hash::CacheHash, DynAny, node_macro::ChoiceType)]
|
||||||
@@ -2110,19 +2063,6 @@ impl core_types::bounds::BoundingBox for Gradient {
|
|||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
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]
|
#[test]
|
||||||
fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() {
|
fn default_is_empty_and_black_to_white_is_the_artist_starting_gradient() {
|
||||||
assert!(Gradient::default().is_empty());
|
assert!(Gradient::default().is_empty());
|
||||||
|
|||||||
@@ -1,530 +0,0 @@
|
|||||||
//! 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}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,820 +0,0 @@
|
|||||||
//! 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.);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,14 +2,12 @@
|
|||||||
extern crate log;
|
extern crate log;
|
||||||
|
|
||||||
pub mod gradient;
|
pub mod gradient;
|
||||||
pub mod gradient_apollonian;
|
|
||||||
pub mod gradient_standard;
|
|
||||||
pub mod math;
|
pub mod math;
|
||||||
pub mod vector;
|
pub mod vector;
|
||||||
|
|
||||||
// Re-export commonly used types at the crate root
|
// Re-export commonly used types at the crate root
|
||||||
pub use core_types as gcore;
|
pub use core_types as gcore;
|
||||||
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
pub use gradient::{Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStop};
|
||||||
pub use math::QuadExt;
|
pub use math::QuadExt;
|
||||||
pub use vector::Vector;
|
pub use vector::Vector;
|
||||||
pub use vector::reference_point::ReferencePoint;
|
pub use vector::reference_point::ReferencePoint;
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ use crate::vector::flatten::WorkingVector;
|
|||||||
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
|
use crate::vector::misc::{BezierHandles, HandleId, HandleType};
|
||||||
use crate::vector::path::{CurveType, Path, curve_types_of};
|
use crate::vector::path::{CurveType, Path, curve_types_of};
|
||||||
use core_types::list::{ATTR_ID, List};
|
use core_types::list::{ATTR_ID, List};
|
||||||
|
use core_types::uuid::generate_uuid;
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::DVec2;
|
use glam::DVec2;
|
||||||
use rustc_hash::{FxHashMap, FxHashSet};
|
use rustc_hash::{FxHashMap, FxHashSet};
|
||||||
@@ -1085,49 +1086,16 @@ impl VectorModification {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Hash sets and maps are hashed in key order, so equal modifications hash equally regardless of iteration order
|
// Intentionally non-deterministic: fields contain HashMaps with non-deterministic iteration order,
|
||||||
impl graphene_hash::CacheHash for PointModification {
|
// so we use a UUID to always bust the cache and force re-evaluation when any modification is present.
|
||||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
// This will not actually lead to a cache invalidation in most cases due to the
|
||||||
self.add.cache_hash(state);
|
// graph inputs being wrapped in a `MemoHash` wrapper.
|
||||||
sorted_set(&self.remove).cache_hash(state);
|
|
||||||
sorted_map(&self.delta).cache_hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl graphene_hash::CacheHash for SegmentModification {
|
|
||||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
|
||||||
self.add.cache_hash(state);
|
|
||||||
sorted_set(&self.remove).cache_hash(state);
|
|
||||||
sorted_map(&self.start_point).cache_hash(state);
|
|
||||||
sorted_map(&self.end_point).cache_hash(state);
|
|
||||||
sorted_map(&self.handle_primary).cache_hash(state);
|
|
||||||
sorted_map(&self.handle_end).cache_hash(state);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl graphene_hash::CacheHash for VectorModification {
|
impl graphene_hash::CacheHash for VectorModification {
|
||||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||||
self.points.cache_hash(state);
|
core::hash::Hash::hash(&generate_uuid(), state);
|
||||||
self.segments.cache_hash(state);
|
|
||||||
sorted_set(&self.add_g1_continuous).cache_hash(state);
|
|
||||||
sorted_set(&self.remove_g1_continuous).cache_hash(state);
|
|
||||||
sorted_set(&self.path_breaks).cache_hash(state);
|
|
||||||
sorted_set(&self.turned_on_load).cache_hash(state);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sorted_set<T: Ord>(set: &HashSet<T>) -> Vec<&T> {
|
|
||||||
let mut items: Vec<_> = set.iter().collect();
|
|
||||||
items.sort_unstable();
|
|
||||||
items
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sorted_map<K: Ord, V>(map: &HashMap<K, V>) -> Vec<(&K, &V)> {
|
|
||||||
let mut entries: Vec<_> = map.iter().collect();
|
|
||||||
entries.sort_unstable_by_key(|&(key, _)| key);
|
|
||||||
entries
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
|
// TODO: Do we want to enforce that all serialized/deserialized hashmaps are a vec of tuples?
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
|
/// Serializes as sorted `[[key, value], ...]` (sequence of pairs)
|
||||||
@@ -1295,23 +1263,6 @@ mod tests {
|
|||||||
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
|
format!("{anchors:?}\n{segments:?}\n{strokes:?}\n{pairs:?}")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn cache_hash(modification: &VectorModification) -> u64 {
|
|
||||||
let mut hasher = std::hash::DefaultHasher::new();
|
|
||||||
graphene_hash::CacheHash::cache_hash(modification, &mut hasher);
|
|
||||||
std::hash::Hasher::finish(&hasher)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn equal_modifications_hash_equally() {
|
|
||||||
let (vector, paths) = mixed_geometry();
|
|
||||||
|
|
||||||
let first = VectorModification::create_from_vector(&vector, &paths);
|
|
||||||
let second = VectorModification::create_from_vector(&vector, &paths);
|
|
||||||
|
|
||||||
assert_eq!(cache_hash(&first), cache_hash(&first));
|
|
||||||
assert_eq!(cache_hash(&first), cache_hash(&second));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
|
/// Every curve type, a weld where they change, a smooth anchor, and a second subpath.
|
||||||
fn mixed_geometry() -> (Vector, List<Path>) {
|
fn mixed_geometry() -> (Vector, List<Path>) {
|
||||||
let mut bezpath = BezPath::new();
|
let mut bezpath = BezPath::new();
|
||||||
|
|||||||
@@ -41,7 +41,6 @@ fastnoise-lite = { workspace = true, features = ["wgsl"] }
|
|||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
# Local dependencies
|
# Local dependencies
|
||||||
graphene-resource = { workspace = true }
|
graphene-resource = { workspace = true }
|
||||||
svg-convert = { workspace = true }
|
|
||||||
|
|
||||||
# Required dependencies
|
# Required dependencies
|
||||||
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
# Turns on the shader translators of every backend for the tests, whichever of them the platform's own backends build with
|
||||||
|
|||||||
@@ -21,7 +21,8 @@ impl Context {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// The context the GPU tests run on, which wgpu's environment variables can aim at each backend and shader compiler in turn.
|
/// The context the GPU tests run on, which wgpu's environment variables can aim at each backend and shader compiler in turn.
|
||||||
pub async fn for_tests() -> Option<Self> {
|
#[cfg(test)]
|
||||||
|
pub(crate) async fn for_tests() -> Option<Self> {
|
||||||
let context = ContextBuilder::new().with_environment_overrides().build().await;
|
let context = ContextBuilder::new().with_environment_overrides().build().await;
|
||||||
|
|
||||||
// A backend asked for by name fails the tests if it can't run them, rather than passing them all as skipped
|
// A backend asked for by name fails the tests if it can't run them, rather than passing them all as skipped
|
||||||
|
|||||||
@@ -1,133 +1,64 @@
|
|||||||
use crate::WgpuExecutor;
|
use crate::WgpuExecutor;
|
||||||
|
use core_types::ops::ConvertAsync;
|
||||||
use core_types::transform::Footprint;
|
use core_types::transform::Footprint;
|
||||||
use raster_types::{Raster, Texture};
|
use raster_types::{CPU, Raster, Texture};
|
||||||
use rendering::CanvasImage;
|
use rendering::CanvasImage;
|
||||||
use rendering::deferred_image::{DeferredImage, DeferredImagePlacement, EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_deferred_image, substitute_effect_map};
|
use rendering::deferred_image::{DeferredImage, DeferredImagePlacement, EffectMap, EffectMapPlacement, MAX_DEFERRED_IMAGE_PIXELS, substitute_deferred_image, substitute_effect_map};
|
||||||
|
|
||||||
/// The maps and images the GPU rendered for the placeholders of an SVG, with the first failure to render one in view, whose placeholder stays.
|
|
||||||
pub struct SvgPlaceholderRenders {
|
|
||||||
effect_maps: Vec<(EffectMapPlacement, Texture)>,
|
|
||||||
deferred_images: Vec<(DeferredImagePlacement, Texture)>,
|
|
||||||
failure: Option<anyhow::Error>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SvgPlaceholderRenders {
|
|
||||||
/// Whether nothing was rendered and nothing failed to, as when every placeholder is out of view.
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.effect_maps.is_empty() && self.deferred_images.is_empty() && self.failure.is_none()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether any of the maps and images an SVG of the view `footprint` takes from the GPU lie in view, needing a GPU to fill their placeholders.
|
|
||||||
pub fn svg_placeholders_in_view(effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> bool {
|
|
||||||
let (document_to_view, view_size) = (footprint.transform, footprint.resolution.as_dvec2());
|
|
||||||
effect_maps.iter().any(|map| map.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
|
|
||||||
|| deferred_images.iter().any(|deferred| deferred.layout(document_to_view, view_size, MAX_DEFERRED_IMAGE_PIXELS).is_some())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Logs the `error`, keeping it as the `failure` if it's the first.
|
|
||||||
fn record_failure(failure: &mut Option<anyhow::Error>, error: anyhow::Error) {
|
|
||||||
log::error!("{error:#}");
|
|
||||||
failure.get_or_insert(error);
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WgpuExecutor {
|
impl WgpuExecutor {
|
||||||
/// Renders the maps and images an SVG of the view `footprint` takes from the GPU. Those out of view keep their placeholders.
|
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
|
||||||
pub fn render_svg_placeholders(&self, effect_maps: &[EffectMap], deferred_images: &[DeferredImage], footprint: Footprint) -> SvgPlaceholderRenders {
|
/// Maps out of view, or that fail to render, keep their placeholders.
|
||||||
|
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
|
||||||
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
||||||
let mut failure = None;
|
|
||||||
|
|
||||||
let effect_maps = effect_maps
|
effect_maps
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|map| {
|
.filter_map(|map| {
|
||||||
let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
let layout = map.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
||||||
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) {
|
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| map.draw(scene, &layout)) {
|
||||||
Ok(texture) => Some((layout.placement, texture)),
|
Ok(texture) => Some((layout.placement, texture)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
record_failure(&mut failure, error.context("Failed to render a map of an effect's coverage for an SVG filter"));
|
log::error!("Failed to render a map of an effect's coverage for an SVG filter: {error}");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
let deferred_images = deferred_images
|
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
|
||||||
|
pub async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) {
|
||||||
|
for (placement, texture) in maps {
|
||||||
|
let map: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
||||||
|
substitute_effect_map(svg, &placement, &map);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
||||||
|
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
||||||
|
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
||||||
|
let max_pixels = MAX_DEFERRED_IMAGE_PIXELS.min(self.context().device.limits().max_texture_dimension_2d);
|
||||||
|
|
||||||
|
deferred_images
|
||||||
.iter()
|
.iter()
|
||||||
.filter_map(|deferred| {
|
.filter_map(|deferred| {
|
||||||
let layout = deferred.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
let layout = deferred.layout(footprint.transform, footprint.resolution.as_dvec2(), max_pixels)?;
|
||||||
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| deferred.draw(scene, &layout)) {
|
match self.render_vello(layout.size, layout.document_to_pixels, &mut |scene| deferred.draw(scene, &layout)) {
|
||||||
Ok(texture) => Some((layout.placement, texture)),
|
Ok(texture) => Some((layout.placement, texture)),
|
||||||
Err(error) => {
|
Err(error) => {
|
||||||
record_failure(&mut failure, error.context("Failed to render an image of content SVG can't draw"));
|
log::error!("Failed to render an image of content with effects SVG can't express: {error}");
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect()
|
||||||
|
|
||||||
SvgPlaceholderRenders {
|
|
||||||
effect_maps,
|
|
||||||
deferred_images,
|
|
||||||
failure,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reads back the `renders`, putting each in `svg` in place of its placeholder. Images drawn to canvases are added to `image_data`.
|
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content.
|
||||||
/// Fails with the first map or image that failed to render or read back, after putting in place all that didn't.
|
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) {
|
||||||
pub async fn substitute_svg_placeholders(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, renders: SvgPlaceholderRenders) -> anyhow::Result<()> {
|
|
||||||
let SvgPlaceholderRenders {
|
|
||||||
effect_maps,
|
|
||||||
deferred_images,
|
|
||||||
failure,
|
|
||||||
} = renders;
|
|
||||||
let maps_failure = self.resolve_effect_maps(svg, effect_maps).await.err();
|
|
||||||
let images_failure = self.resolve_deferred_svg_images(svg, image_data, deferred_images).await.err();
|
|
||||||
|
|
||||||
match failure.or(maps_failure).or(images_failure) {
|
|
||||||
Some(failure) => Err(failure),
|
|
||||||
None => Ok(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders the maps of effects' coverages that an SVG of the view `footprint` takes, with where its filters place each.
|
|
||||||
/// Maps out of view, or that fail to render, keep their placeholders.
|
|
||||||
pub fn render_effect_maps(&self, effect_maps: &[EffectMap], footprint: Footprint) -> Vec<(EffectMapPlacement, Texture)> {
|
|
||||||
self.render_svg_placeholders(effect_maps, &[], footprint).effect_maps
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads back the maps of effects' coverages, putting each in `svg` in place of its placeholder.
|
|
||||||
/// Fails with the first that fails to read back, after putting in place all that didn't.
|
|
||||||
async fn resolve_effect_maps(&self, svg: &mut String, maps: Vec<(EffectMapPlacement, Texture)>) -> anyhow::Result<()> {
|
|
||||||
let mut failure = None;
|
|
||||||
for (placement, texture) in maps {
|
|
||||||
match self.try_download(Raster::new_gpu(texture)).await {
|
|
||||||
Ok(map) => substitute_effect_map(svg, &placement, &map),
|
|
||||||
Err(error) => {
|
|
||||||
record_failure(&mut failure, error.context("Failed to read back a map of an effect's coverage for an SVG filter"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
failure.map_or(Ok(()), Err)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders images of the content an SVG of the view `footprint` describes defers to the GPU, with where the SVG draws each.
|
|
||||||
/// Content out of view, or that fails to render, keeps the markup standing in for it.
|
|
||||||
pub fn render_deferred_svg_images(&self, deferred_images: &[DeferredImage], footprint: Footprint) -> Vec<(DeferredImagePlacement, Texture)> {
|
|
||||||
self.render_svg_placeholders(&[], deferred_images, footprint).deferred_images
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Reads back the images of deferred content, putting each in `svg` in place of the markup standing in for its content. Images drawn to canvases are added to `image_data`.
|
|
||||||
/// Fails with the first that fails to read back, after putting in place all that didn't.
|
|
||||||
pub async fn resolve_deferred_svg_images(&self, svg: &mut String, image_data: &mut Vec<(u64, CanvasImage)>, images: Vec<(DeferredImagePlacement, Texture)>) -> anyhow::Result<()> {
|
|
||||||
let mut failure = None;
|
|
||||||
for (placement, texture) in images {
|
for (placement, texture) in images {
|
||||||
match self.try_download(Raster::new_gpu(texture)).await {
|
let image: Raster<CPU> = Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, self.clone()).await;
|
||||||
Ok(image) => substitute_deferred_image(svg, image_data, &placement, &image),
|
substitute_deferred_image(svg, image_data, &placement, &image);
|
||||||
Err(error) => {
|
|
||||||
record_failure(&mut failure, error.context("Failed to read back an image of content SVG can't draw"));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
failure.map_or(Ok(()), Err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,6 @@ mod buffer;
|
|||||||
mod context;
|
mod context;
|
||||||
mod deferred_svg_images;
|
mod deferred_svg_images;
|
||||||
mod pipeline;
|
mod pipeline;
|
||||||
mod raster_readback;
|
|
||||||
mod texture_cache;
|
mod texture_cache;
|
||||||
pub mod texture_conversion;
|
pub mod texture_conversion;
|
||||||
mod vello_adjustments;
|
mod vello_adjustments;
|
||||||
@@ -23,7 +22,6 @@ use wgpu::util::DeviceExt;
|
|||||||
pub use buffer::Buffer;
|
pub use buffer::Buffer;
|
||||||
pub use context::Context as WgpuContext;
|
pub use context::Context as WgpuContext;
|
||||||
pub use context::ContextBuilder as WgpuContextBuilder;
|
pub use context::ContextBuilder as WgpuContextBuilder;
|
||||||
pub use deferred_svg_images::{SvgPlaceholderRenders, svg_placeholders_in_view};
|
|
||||||
pub use pipeline::Pipeline as WgpuPipeline;
|
pub use pipeline::Pipeline as WgpuPipeline;
|
||||||
pub use pipeline::PipelineCache as WgpuPipelineCache;
|
pub use pipeline::PipelineCache as WgpuPipelineCache;
|
||||||
pub use pipeline::PipelineError as WgpuPipelineError;
|
pub use pipeline::PipelineError as WgpuPipelineError;
|
||||||
@@ -77,19 +75,6 @@ impl WgpuExecutor {
|
|||||||
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
/// Renders the document scene `draw` draws, with its content placed by `view`, into a new texture of `size` with straight alpha.
|
||||||
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
/// A render with more content than Vello GPU can hold calls `draw` again for each part it splits into.
|
||||||
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
pub fn render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
||||||
Ok(self.render_vello_and_failure(size, view, draw)?.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Like [`Self::render_vello`], but failing rather than leaving transparent a part Vello GPU fails to render, for a render read back as data.
|
|
||||||
pub fn try_render_vello(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<Texture> {
|
|
||||||
match self.render_vello_and_failure(size, view, draw)? {
|
|
||||||
(_, Some(failure)) => anyhow::bail!("Vello GPU failed to render: {failure}"),
|
|
||||||
(texture, None) => Ok(texture),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The texture [`Self::render_vello`] renders, with the first failure that left part of it transparent.
|
|
||||||
fn render_vello_and_failure(&self, size: UVec2, view: DAffine2, draw: &mut dyn FnMut(&mut VelloSceneBuilder)) -> Result<(Texture, Option<String>)> {
|
|
||||||
let limit = self.context().device.limits().max_texture_dimension_2d;
|
let limit = self.context().device.limits().max_texture_dimension_2d;
|
||||||
if size.x > limit || size.y > limit {
|
if size.x > limit || size.y > limit {
|
||||||
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
anyhow::bail!("Render size {size} exceeds the GPU's texture size limit of {limit}");
|
||||||
@@ -99,12 +84,11 @@ impl WgpuExecutor {
|
|||||||
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
let view = vello_gpu::kurbo::Affine::new(view.to_cols_array());
|
||||||
|
|
||||||
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
let mut canvas = self.inner.document_canvas.lock().unwrap_or_else(PoisonError::into_inner);
|
||||||
let failure = self
|
self.inner
|
||||||
.inner
|
|
||||||
.vello_renderer
|
.vello_renderer
|
||||||
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
.render(&mut canvas, &self.context().device, &self.context().queue, draw, view, size, &texture)?;
|
||||||
|
|
||||||
Ok((texture, failure))
|
Ok(texture)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
/// Renders a scene drawn beforehand, on a canvas the caller owns, into a new texture of the scene's size with straight alpha.
|
||||||
@@ -199,12 +183,6 @@ impl WgpuExecutor {
|
|||||||
Self::with_context(WgpuContext::new().await?)
|
Self::with_context(WgpuContext::new().await?)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The executor GPU tests run on, on the context [`WgpuContext::for_tests`] makes, or `None` without a GPU.
|
|
||||||
#[cfg(not(target_family = "wasm"))]
|
|
||||||
pub async fn for_tests() -> Option<Self> {
|
|
||||||
Self::with_context(WgpuContext::for_tests().await?)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
pub fn with_context(context: WgpuContext) -> Option<Self> {
|
||||||
let vello_renderer = VelloRenderer::new(&context.device, &context.adapter);
|
let vello_renderer = VelloRenderer::new(&context.device, &context.adapter);
|
||||||
|
|
||||||
|
|||||||
@@ -1,634 +0,0 @@
|
|||||||
use crate::WgpuExecutor;
|
|
||||||
use crate::texture_conversion::download_row_bytes;
|
|
||||||
use core_types::blending::BlendMode;
|
|
||||||
use core_types::list::{ATTR_EFFECTS, Item, List};
|
|
||||||
use core_types::transform::Footprint;
|
|
||||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
|
||||||
use graphic_types::Graphic;
|
|
||||||
use graphic_types::effects::{EffectOperation, Effects};
|
|
||||||
use raster_types::{CPU, Image, Pixels, Raster};
|
|
||||||
use rendering::{Render, RenderOutputType, RenderParams, leading_raster_adjustments};
|
|
||||||
|
|
||||||
/// The most pixels an image may grow to with the margin its effects paint into, beyond which the margin is cut short.
|
|
||||||
const MAX_PIXELS_WITH_MARGIN: f64 = (1 << 24) as f64;
|
|
||||||
|
|
||||||
/// The GPU's limits that a readback's renders and downloads stay within.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
struct ReadbackLimits {
|
|
||||||
/// The most pixels across or down a texture may have, which an image larger than it is downscaled to when uploaded whole.
|
|
||||||
texture_size: u32,
|
|
||||||
/// The most bytes a download buffer may hold.
|
|
||||||
buffer_size: u64,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ReadbackLimits {
|
|
||||||
fn of(executor: &WgpuExecutor) -> Self {
|
|
||||||
let limits = executor.context().device.limits();
|
|
||||||
Self {
|
|
||||||
texture_size: limits.max_texture_dimension_2d,
|
|
||||||
buffer_size: limits.max_buffer_size,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The largest tile, at most `max` pixels across and down, that a texture and its download buffer can hold, or `None` if not even one pixel fits.
|
|
||||||
fn tile_size(&self, max: UVec2) -> Option<UVec2> {
|
|
||||||
// Each row's bytes are padded to 256, which 64 pixels fill
|
|
||||||
let widest_row = (self.buffer_size / wgpu::COPY_BYTES_PER_ROW_ALIGNMENT as u64 * 64).min(u32::MAX as u64) as u32;
|
|
||||||
let width = max.x.min(self.texture_size).min(widest_row);
|
|
||||||
if width == 0 {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let height = max.y.min(self.texture_size).min((self.buffer_size / download_row_bytes(width) as u64).min(u32::MAX as u64) as u32);
|
|
||||||
(height > 0).then_some(UVec2::new(width, height))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl WgpuExecutor {
|
|
||||||
/// The image's pixels as it's drawn, with its effects and fill carried out at its own pixel grid, grown by whole pixels to hold what they paint past its edges.
|
|
||||||
/// The opacity and blend mode stay for whatever draws the result.
|
|
||||||
pub async fn read_back(&self, item: Item<Raster<CPU>>) -> anyhow::Result<Item<Pixels>> {
|
|
||||||
self.read_back_within(item, ReadbackLimits::of(self)).await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Like [`Self::read_back`], within the GPU `limits`.
|
|
||||||
async fn read_back_within(&self, item: Item<Raster<CPU>>, limits: ReadbackLimits) -> anyhow::Result<Item<Pixels>> {
|
|
||||||
let effects: Effects = item.attribute_cloned_or_default(ATTR_EFFECTS);
|
|
||||||
let transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
|
||||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.);
|
|
||||||
let size = UVec2::new(item.element().width, item.element().height);
|
|
||||||
|
|
||||||
// Nothing to carry out, or nothing to carry it out on
|
|
||||||
if (effects.change_nothing() && fill >= 1.) || size.cmpeq(UVec2::ZERO).any() || !transform.matrix2.determinant().is_normal() || !transform.is_finite() {
|
|
||||||
let raster = item.element().clone();
|
|
||||||
return Ok(carried_out(item, raster));
|
|
||||||
}
|
|
||||||
|
|
||||||
let reach = effects_reach(&effects, size.as_dvec2());
|
|
||||||
if !reach.is_finite() {
|
|
||||||
anyhow::bail!("The effects on a {} by {} image reach too far to render", size.x, size.y);
|
|
||||||
}
|
|
||||||
let margin = capped_margin(reach, size.as_dvec2());
|
|
||||||
let raster = self.render_at_pixel_grid(&item, &effects, transform, margin, reach, limits).await?;
|
|
||||||
|
|
||||||
let unit_margin = margin / size.as_dvec2();
|
|
||||||
let mut item = carried_out(item, raster);
|
|
||||||
item.set_attribute(
|
|
||||||
ATTR_TRANSFORM,
|
|
||||||
transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin),
|
|
||||||
);
|
|
||||||
Ok(item)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders the raster `item` placed by `transform` with its `effects`, one pixel of the render per pixel of its image, grown by `margin` pixels along each axis.
|
|
||||||
/// A render larger than the GPU's `limits` allow is drawn in tiles. When the whole image is too large to upload, each is drawn from a crop holding the pixels the effects `reach` past it.
|
|
||||||
async fn render_at_pixel_grid(&self, item: &Item<Raster<CPU>>, effects: &Effects, transform: DAffine2, margin: DVec2, reach: DVec2, limits: ReadbackLimits) -> anyhow::Result<Raster<CPU>> {
|
|
||||||
let image = item.element();
|
|
||||||
let size = UVec2::new(image.width, image.height);
|
|
||||||
let grown_size = size + 2 * margin.as_uvec2();
|
|
||||||
let document_to_pixels = DAffine2::from_translation(margin) * DAffine2::from_scale(size.as_dvec2()) * transform.inverse();
|
|
||||||
|
|
||||||
// The content on its own, without the opacity and blend mode that act on its effects' result as a whole
|
|
||||||
let mut content = item.clone();
|
|
||||||
content.remove_attribute::<f64>(ATTR_OPACITY);
|
|
||||||
content.remove_attribute::<BlendMode>(ATTR_BLEND_MODE);
|
|
||||||
|
|
||||||
// Each tile draws a crop of an image too large to upload whole, holding the pixels its effects read, unless they depend on the whole image's extent
|
|
||||||
let too_large_to_upload = size.cmpgt(UVec2::splat(limits.texture_size)).any();
|
|
||||||
let crops = too_large_to_upload && !effects.any_takes_frame() && !effects.reach_depends_on_size();
|
|
||||||
if too_large_to_upload && !crops {
|
|
||||||
log::warn!(
|
|
||||||
"A {} by {} image is read back at a lower resolution, since it's too large for the GPU and its effects depend on its whole extent",
|
|
||||||
size.x,
|
|
||||||
size.y
|
|
||||||
);
|
|
||||||
}
|
|
||||||
// A crop holds what the effects reach on both sides of its tile, which has to leave a texture room for at least a pixel, checked before the reach becomes an integer
|
|
||||||
let max_tile_size = match crops {
|
|
||||||
true => {
|
|
||||||
let room = DVec2::splat(limits.texture_size as f64) - 2. * reach;
|
|
||||||
if !room.cmpge(DVec2::ONE).all() {
|
|
||||||
anyhow::bail!("The effects on a {} by {} image reach too far past each pixel to render it in tiles the GPU can hold", size.x, size.y);
|
|
||||||
}
|
|
||||||
room.floor().as_uvec2()
|
|
||||||
}
|
|
||||||
false => grown_size,
|
|
||||||
};
|
|
||||||
let (margin, reach) = (margin.as_uvec2(), reach.as_uvec2());
|
|
||||||
let Some(tile_size) = limits.tile_size(max_tile_size) else {
|
|
||||||
anyhow::bail!("The GPU's textures and buffers can't hold a tile of a {} by {} image's render with its effects", size.x, size.y);
|
|
||||||
};
|
|
||||||
|
|
||||||
// The raster's render carries out its leading adjustments on its image's own pixels, which a crop's group can't, so each crop takes them as its own
|
|
||||||
let leading_adjustments = if crops { leading_raster_adjustments(&content).len() } else { 0 };
|
|
||||||
|
|
||||||
let whole = List::new_from_item(content.clone());
|
|
||||||
if !crops && grown_size.cmple(tile_size).all() {
|
|
||||||
return self.render_tile(&whole, document_to_pixels, grown_size).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut pixels = Image::try_new(grown_size.x, grown_size.y, Color::TRANSPARENT)?;
|
|
||||||
for tile_y in (0..grown_size.y).step_by(tile_size.y as usize) {
|
|
||||||
for tile_x in (0..grown_size.x).step_by(tile_size.x as usize) {
|
|
||||||
let origin = UVec2::new(tile_x, tile_y);
|
|
||||||
let size_in_tile = (grown_size - origin).min(tile_size);
|
|
||||||
let tile_to_pixels = DAffine2::from_translation(-origin.as_dvec2()) * document_to_pixels;
|
|
||||||
|
|
||||||
let tile = match crops {
|
|
||||||
// The tile spans the image's pixels from `origin - margin`, and its effects read up to their reach past it
|
|
||||||
true => {
|
|
||||||
let start = origin.saturating_sub(margin + reach);
|
|
||||||
let end = (origin + size_in_tile + reach).saturating_sub(margin).min(size);
|
|
||||||
self.render_tile(&cropped(&content, leading_adjustments, start, end), tile_to_pixels, size_in_tile).await?
|
|
||||||
}
|
|
||||||
false => self.render_tile(&whole, tile_to_pixels, size_in_tile).await?,
|
|
||||||
};
|
|
||||||
|
|
||||||
for row in 0..size_in_tile.y as usize {
|
|
||||||
let start = (origin.y as usize + row) * grown_size.x as usize + origin.x as usize;
|
|
||||||
let tile_row = &tile.data[row * size_in_tile.x as usize..(row + 1) * size_in_tile.x as usize];
|
|
||||||
pixels.data[start..start + size_in_tile.x as usize].copy_from_slice(tile_row);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(Raster::new_cpu(pixels))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Renders the `content` into an image of `size` pixels, which `document_to_pixels` places the document in, and reads it back.
|
|
||||||
async fn render_tile(&self, content: &(impl Render + Sync), document_to_pixels: DAffine2, size: UVec2) -> anyhow::Result<Raster<CPU>> {
|
|
||||||
let render_params = RenderParams {
|
|
||||||
render_output_type: RenderOutputType::Vello,
|
|
||||||
footprint: Footprint {
|
|
||||||
transform: document_to_pixels,
|
|
||||||
resolution: size,
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
for_export: true,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
let texture = self.try_render_vello(size, document_to_pixels, &mut |scene| content.render_to_vello(scene, DAffine2::IDENTITY, &render_params))?;
|
|
||||||
|
|
||||||
self.try_download(Raster::new_gpu(texture)).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The `item` with its image replaced by the `raster` its effects and fill are carried out in, without the attributes holding them.
|
|
||||||
fn carried_out(item: Item<Raster<CPU>>, raster: Raster<CPU>) -> Item<Pixels> {
|
|
||||||
let (_, attributes) = item.into_parts();
|
|
||||||
let mut item = Item::from_parts(Pixels::new(raster), attributes);
|
|
||||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
|
||||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
|
||||||
item
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The raster `content` drawn from only its image's pixels from `start` up to `end`, at their own resolution where they lie in the whole image.
|
|
||||||
/// The crop sits within a group taking the content's placement and effects, so the effects measure and place what they draw as for the whole image,
|
|
||||||
/// but for the first `leading_adjustments` of them, which the crop takes as its own for its render to carry out on its pixels.
|
|
||||||
fn cropped(content: &Item<Raster<CPU>>, leading_adjustments: usize, start: UVec2, end: UVec2) -> List<Graphic> {
|
|
||||||
let image = content.element();
|
|
||||||
let (size, crop_size) = (UVec2::new(image.width, image.height), end.saturating_sub(start));
|
|
||||||
if crop_size.cmpeq(UVec2::ZERO).any() {
|
|
||||||
return List::new();
|
|
||||||
}
|
|
||||||
|
|
||||||
let data = (start.y..end.y)
|
|
||||||
.flat_map(|y| {
|
|
||||||
let row = (y * size.x) as usize;
|
|
||||||
image.data[row + start.x as usize..row + end.x as usize].iter().copied()
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
let crop = Image {
|
|
||||||
width: crop_size.x,
|
|
||||||
height: crop_size.y,
|
|
||||||
data,
|
|
||||||
};
|
|
||||||
let placement = DAffine2::from_translation(start.as_dvec2() / size.as_dvec2()) * DAffine2::from_scale(crop_size.as_dvec2() / size.as_dvec2());
|
|
||||||
let mut crop = Item::new_from_element(Raster::new_cpu(crop)).with_attribute(ATTR_TRANSFORM, placement);
|
|
||||||
|
|
||||||
let effects: Effects = content.attribute_cloned_or_default(ATTR_EFFECTS);
|
|
||||||
let (_, attributes) = content.clone().into_parts();
|
|
||||||
if leading_adjustments == 0 {
|
|
||||||
return List::new_from_item(Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes));
|
|
||||||
}
|
|
||||||
|
|
||||||
crop.set_attribute(ATTR_EFFECTS, effects.run(0..leading_adjustments).into_owned());
|
|
||||||
let mut group = Item::from_parts(Graphic::RasterCPU(Box::new(crop)), attributes);
|
|
||||||
group.set_attribute(ATTR_EFFECTS, effects.after(leading_adjustments));
|
|
||||||
List::new_from_item(group)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How far, in whole pixels along each axis of an image of `size` pixels, its `effects` paint and read past each pixel and its edges.
|
|
||||||
fn effects_reach(effects: &Effects, size: DVec2) -> DVec2 {
|
|
||||||
// The content's unit square spans the image's pixels
|
|
||||||
let content_to_pixels = DAffine2::from_scale(size);
|
|
||||||
let reach = (effects.reach_around(content_to_pixels, [DVec2::ZERO, size], 0.) + effects.read_beyond_painted(content_to_pixels)).ceil();
|
|
||||||
|
|
||||||
// A feather fades the content toward its edges, finding them against the pixels past them
|
|
||||||
match effects.operations().any(|operation| matches!(operation, EffectOperation::Feather { distance } if distance > 0.)) {
|
|
||||||
true => reach.max(DVec2::ONE),
|
|
||||||
false => reach,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The margin an image of `size` pixels grows by to hold its effects' `reach`, cut short evenly past [`MAX_PIXELS_WITH_MARGIN`].
|
|
||||||
fn capped_margin(reach: DVec2, size: DVec2) -> DVec2 {
|
|
||||||
if (size + 2. * reach).element_product() <= MAX_PIXELS_WITH_MARGIN {
|
|
||||||
return reach;
|
|
||||||
}
|
|
||||||
|
|
||||||
let margin = (reach * margin_fraction_that_fits(size, reach)).floor();
|
|
||||||
if margin.max_element() < reach.max_element() {
|
|
||||||
log::warn!(
|
|
||||||
"The effects on a {} by {} image end at a hard edge {} pixels past it, short of the {} they reach, since the image can't grow past {MAX_PIXELS_WITH_MARGIN} pixels",
|
|
||||||
size.x,
|
|
||||||
size.y,
|
|
||||||
margin.max_element(),
|
|
||||||
reach.max_element()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
margin
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The fraction of `margin` that grows an image of `size` to [`MAX_PIXELS_WITH_MARGIN`], or 0 if the image alone already reaches it.
|
|
||||||
fn margin_fraction_that_fits(size: DVec2, margin: DVec2) -> f64 {
|
|
||||||
// The positive root of (width + 2 × fraction × margin width) × (height + 2 × fraction × margin height) = the limit
|
|
||||||
let quadratic = 4. * margin.x * margin.y;
|
|
||||||
let linear = 2. * (size.x * margin.y + size.y * margin.x);
|
|
||||||
let constant = size.element_product() - MAX_PIXELS_WITH_MARGIN;
|
|
||||||
if constant >= 0. || linear <= 0. {
|
|
||||||
return 0.;
|
|
||||||
}
|
|
||||||
|
|
||||||
let fraction = match quadratic > 0. {
|
|
||||||
true => (-linear + (linear * linear - 4. * quadratic * constant).sqrt()) / (2. * quadratic),
|
|
||||||
false => -constant / linear,
|
|
||||||
};
|
|
||||||
fraction.clamp(0., 1.)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use core_types::color::SRGBA8;
|
|
||||||
use core_types::list::ATTR_APPEARANCE;
|
|
||||||
use futures::executor::block_on;
|
|
||||||
use graphic_types::vector_types::vector::style::StrokeAlign;
|
|
||||||
use graphic_types::{Appearance, Coverage, Effect, Graphic, MaskMode, Vector, stamp_effect};
|
|
||||||
use vello_gpu::kurbo::{Rect, Shape};
|
|
||||||
|
|
||||||
/// The executor these tests share, or `None` without a GPU.
|
|
||||||
fn executor() -> Option<&'static WgpuExecutor> {
|
|
||||||
static EXECUTOR: std::sync::OnceLock<Option<WgpuExecutor>> = std::sync::OnceLock::new();
|
|
||||||
EXECUTOR.get_or_init(|| block_on(crate::WgpuContext::for_tests()).and_then(WgpuExecutor::with_context)).as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The size in the document of the pixels of an image scaled unevenly, 1 unit wide and 4 tall.
|
|
||||||
const TALL_PIXEL: DVec2 = DVec2::new(1., 4.);
|
|
||||||
|
|
||||||
/// An image of 20 by 20 pixels, each `pixel_size` in the document, colored by `color` at each pixel's column and row, with its corner at (100, 50).
|
|
||||||
fn image_of_pixels(pixel_size: DVec2, color: impl Fn(u32, u32) -> Color, effects: &[EffectOperation]) -> Item<Raster<CPU>> {
|
|
||||||
let data = (0..20 * 20).map(|index| color(index % 20, index / 20)).collect();
|
|
||||||
let transform = DAffine2::from_translation(DVec2::new(100., 50.)) * DAffine2::from_scale(20. * pixel_size);
|
|
||||||
|
|
||||||
let mut item = Item::new_from_element(Raster::new_cpu(Image { width: 20, height: 20, data })).with_attribute(ATTR_TRANSFORM, transform);
|
|
||||||
for effect in effects {
|
|
||||||
stamp_effect(&mut item, Effect::new(effect));
|
|
||||||
}
|
|
||||||
item
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The read-back image's color at a `point` in the document, transparent past its edges.
|
|
||||||
fn color_at(image: &Item<Pixels>, point: DVec2) -> Color {
|
|
||||||
let raster = image.element();
|
|
||||||
let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM);
|
|
||||||
let pixel = (transform.inverse().transform_point2(point) * DVec2::new(raster.width as f64, raster.height as f64)).floor();
|
|
||||||
|
|
||||||
let inside = pixel.cmpge(DVec2::ZERO).all() && pixel.x < raster.width as f64 && pixel.y < raster.height as f64;
|
|
||||||
if !inside {
|
|
||||||
return Color::TRANSPARENT;
|
|
||||||
}
|
|
||||||
raster.data[pixel.y as usize * raster.width as usize + pixel.x as usize]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_black(color: Color) -> bool {
|
|
||||||
color.a() > 0.98 && color.r().max(color.g()).max(color.b()) < 0.02
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_white(color: Color) -> bool {
|
|
||||||
color.a() > 0.98 && color.r().min(color.g()).min(color.b()) > 0.98
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_clear(color: Color) -> bool {
|
|
||||||
color.a() < 0.02
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_margin_too_large_is_cut_short_to_fit_the_pixel_limit() {
|
|
||||||
// A tall strip whose margins alone would grow it eightfold past the limit
|
|
||||||
let size = DVec2::new(1., 16_384.);
|
|
||||||
let margin = DVec2::splat(3000.);
|
|
||||||
|
|
||||||
let fitted = (margin * margin_fraction_that_fits(size, margin)).floor();
|
|
||||||
let grown_area = (size + 2. * fitted).element_product();
|
|
||||||
|
|
||||||
assert!(grown_area <= MAX_PIXELS_WITH_MARGIN, "the grown image has {grown_area} pixels");
|
|
||||||
assert!(grown_area > 0.99 * MAX_PIXELS_WITH_MARGIN, "the grown image has only {grown_area} pixels");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_image_without_effects_comes_back_as_it_is() {
|
|
||||||
let Some(executor) = executor() else { return };
|
|
||||||
|
|
||||||
let image = image_of_pixels(TALL_PIXEL, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 0.25), &[]);
|
|
||||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(**read_back.element(), *image.element().data());
|
|
||||||
assert_eq!(
|
|
||||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
|
||||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A fill fades the pixels read back the same whether no effects or an empty list of them is stamped, and goes with the effects while the other attributes stay.
|
|
||||||
#[test]
|
|
||||||
fn a_fill_fades_the_pixels_with_or_without_effects() {
|
|
||||||
let Some(executor) = executor() else { return };
|
|
||||||
|
|
||||||
let mut without_effects = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[]);
|
|
||||||
without_effects.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
|
||||||
without_effects.set_attribute(ATTR_OPACITY, 0.25);
|
|
||||||
without_effects.set_attribute(ATTR_BLEND_MODE, BlendMode::Multiply);
|
|
||||||
without_effects.set_attribute("unrelated", 7.);
|
|
||||||
let mut with_no_effects = without_effects.clone();
|
|
||||||
with_no_effects.set_attribute(ATTR_EFFECTS, Effects::default());
|
|
||||||
|
|
||||||
for image in [without_effects, with_no_effects] {
|
|
||||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
|
||||||
|
|
||||||
let faded = image.element().data.iter().map(|color| color.with_alpha(0.5)).collect();
|
|
||||||
assert_alike(read_back.element(), &Image { width: 20, height: 20, data: faded }, 2);
|
|
||||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
|
||||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
|
||||||
|
|
||||||
assert_eq!(read_back.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.), 0.25);
|
|
||||||
assert_eq!(read_back.attribute_cloned_or_default::<BlendMode>(ATTR_BLEND_MODE), BlendMode::Multiply);
|
|
||||||
assert_eq!(read_back.attribute_cloned_or::<f64>("unrelated", 0.), 7.);
|
|
||||||
assert_eq!(
|
|
||||||
read_back.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM),
|
|
||||||
image.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Levels adjustment bending each color channel its own way, and alpha by `alpha_midtones`.
|
|
||||||
fn uneven_levels(alpha_midtones: f64) -> graphic_types::Adjustment {
|
|
||||||
use graphic_types::adjustment::{LevelsRecord, LevelsSettings};
|
|
||||||
|
|
||||||
let record = |midtones, output_maximums| LevelsRecord {
|
|
||||||
shadows: 0.,
|
|
||||||
midtones,
|
|
||||||
highlights: 100.,
|
|
||||||
output_minimums: 0.,
|
|
||||||
output_maximums,
|
|
||||||
};
|
|
||||||
graphic_types::Adjustment::Levels(Box::new(LevelsSettings {
|
|
||||||
composite: record(1.4, 100.),
|
|
||||||
red: record(0.7, 90.),
|
|
||||||
green: record(1., 100.),
|
|
||||||
blue: record(1.2, 100.),
|
|
||||||
alpha: record(alpha_midtones, 100.),
|
|
||||||
}))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn adjustments_alone_are_read_back_as_their_definitions_draw_them() {
|
|
||||||
use graphic_types::Adjustment;
|
|
||||||
use raster_kernels::adjustments::adjust_color;
|
|
||||||
|
|
||||||
let Some(executor) = executor() else { return };
|
|
||||||
|
|
||||||
// Each pixel's color through the adjustments one after another, faded by `fill`
|
|
||||||
let adjusted = |image: &Item<Raster<CPU>>, adjustments: &[Adjustment], fill: f32| -> Image<Color> {
|
|
||||||
let data = (image.element().data.iter())
|
|
||||||
.map(|&color| adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color)))
|
|
||||||
.map(|color| color.with_alpha(color.a() * fill))
|
|
||||||
.collect();
|
|
||||||
Image { width: 20, height: 20, data }
|
|
||||||
};
|
|
||||||
|
|
||||||
// A Levels stack bending alpha
|
|
||||||
let adjustments = [uneven_levels(2.2), Adjustment::Invert];
|
|
||||||
let operations: Vec<_> = adjustments.iter().cloned().map(EffectOperation::Adjustment).collect();
|
|
||||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, (x + y) as f32 / 40.);
|
|
||||||
let image = image_of_pixels(DVec2::ONE, color, &operations);
|
|
||||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
|
||||||
assert_premultiplied_alike(read_back.element(), &adjusted(&image, &adjustments, 1.));
|
|
||||||
assert!(read_back.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
|
||||||
|
|
||||||
// Inverting keeps alpha, so a partial fill fades the inverted colors, and fully transparent pixels stay so
|
|
||||||
let color = |x: u32, y: u32| Color::from_rgbaf32_unchecked(x as f32 / 20., 0.25, 1., if y < 10 { 0. } else { 0.8 });
|
|
||||||
let mut image = image_of_pixels(DVec2::ONE, color, &[EffectOperation::Adjustment(Adjustment::Invert)]);
|
|
||||||
image.set_attribute(ATTR_OPACITY_FILL, 0.5);
|
|
||||||
let read_back = block_on(executor.read_back(image.clone())).unwrap();
|
|
||||||
assert!(read_back.attribute::<f64>(ATTR_OPACITY_FILL).is_none());
|
|
||||||
assert_premultiplied_alike(read_back.element(), &adjusted(&image, &[Adjustment::Invert], 0.5));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_margin_holds_what_a_median_reads_past_the_image() {
|
|
||||||
// A median reads its whole radius and the pixel past it, across the image's pixels of one unit each
|
|
||||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[EffectOperation::Median { radius: 2.5 }]);
|
|
||||||
let effects = image.attribute::<Effects>(ATTR_EFFECTS).unwrap();
|
|
||||||
assert_eq!(effects_reach(effects, DVec2::splat(20.)), DVec2::splat(3.));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effects_measure_lengths_in_the_document_across_unevenly_scaled_pixels() {
|
|
||||||
let Some(executor) = executor() else { return };
|
|
||||||
|
|
||||||
// An outline 8 units wide spans 8 of the image's pixels across, but only 2 of them down
|
|
||||||
let outline = EffectOperation::Outline {
|
|
||||||
paint: Color::BLACK.into(),
|
|
||||||
blend_mode: BlendMode::Normal,
|
|
||||||
weight: 8.,
|
|
||||||
align: StrokeAlign::Outside,
|
|
||||||
contour_gradient: false,
|
|
||||||
};
|
|
||||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[outline]))).unwrap();
|
|
||||||
|
|
||||||
// The content spans from (100, 50) to (120, 130)
|
|
||||||
assert!(is_white(color_at(&read_back, DVec2::new(110., 90.))), "the content");
|
|
||||||
assert!(is_black(color_at(&read_back, DVec2::new(94.5, 90.))), "within the outline, 5.5 units left of the content");
|
|
||||||
assert!(is_clear(color_at(&read_back, DVec2::new(89.5, 90.))), "past the outline, 10.5 units left of the content");
|
|
||||||
assert!(is_black(color_at(&read_back, DVec2::new(110., 44.))), "within the outline, 6 units above the content");
|
|
||||||
assert!(is_clear(color_at(&read_back, DVec2::new(110., 40.))), "past the outline, 10 units above the content");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn vector_masks_shape_the_pixels_read_back() {
|
|
||||||
let Some(executor) = executor() else { return };
|
|
||||||
|
|
||||||
// A mask lies in the content's own space, where the left half of its unit square covers the image's left half
|
|
||||||
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.1));
|
|
||||||
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
|
|
||||||
let mask = EffectOperation::Mask {
|
|
||||||
mask: Graphic::Vector(Box::new(left_half)),
|
|
||||||
mode: MaskMode::Alpha,
|
|
||||||
density: 100.,
|
|
||||||
feather: 0.,
|
|
||||||
invert: false,
|
|
||||||
};
|
|
||||||
let read_back = block_on(executor.read_back(image_of_pixels(TALL_PIXEL, |_, _| Color::WHITE, &[mask]))).unwrap();
|
|
||||||
|
|
||||||
assert!(is_white(color_at(&read_back, DVec2::new(105.5, 90.))), "the left half, which the mask shows");
|
|
||||||
assert!(is_clear(color_at(&read_back, DVec2::new(114.5, 90.))), "the right half, which the mask hides");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An outline of `weight` outside the content, in black.
|
|
||||||
fn outline(weight: f64) -> EffectOperation {
|
|
||||||
EffectOperation::Outline {
|
|
||||||
paint: Color::BLACK.into(),
|
|
||||||
blend_mode: BlendMode::Normal,
|
|
||||||
weight,
|
|
||||||
align: StrokeAlign::Outside,
|
|
||||||
contour_gradient: false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The limits of the shared GPU, and its executor, or `None` without a GPU.
|
|
||||||
fn executor_and_limits() -> Option<(&'static WgpuExecutor, ReadbackLimits)> {
|
|
||||||
let executor = executor()?;
|
|
||||||
Some((executor, ReadbackLimits::of(executor)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Asserts that two images have the same size and 8-bit pixels within `tolerance` levels of each other.
|
|
||||||
fn assert_alike(actual: &Image<Color>, expected: &Image<Color>, tolerance: u8) {
|
|
||||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
|
||||||
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
|
||||||
let (SRGBA8 { red, green, blue, alpha }, wanted) = (SRGBA8::from(*actual), SRGBA8::from(*expected));
|
|
||||||
let differences = [red.abs_diff(wanted.red), green.abs_diff(wanted.green), blue.abs_diff(wanted.blue), alpha.abs_diff(wanted.alpha)];
|
|
||||||
assert!(
|
|
||||||
differences.iter().all(|&difference| difference <= tolerance),
|
|
||||||
"pixel {index} is {actual:?} but {expected:?} in the other"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Asserts that two images have the same size and premultiplied gamma-encoded channels within the 8-bit rounding of a render's premultiplied texture and its straight download.
|
|
||||||
fn assert_premultiplied_alike(actual: &Image<Color>, expected: &Image<Color>) {
|
|
||||||
assert_eq!((actual.width, actual.height), (expected.width, expected.height));
|
|
||||||
let premultiplied = |color: Color| {
|
|
||||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
|
||||||
[red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.)
|
|
||||||
};
|
|
||||||
for (index, (actual, expected)) in actual.data.iter().zip(&expected.data).enumerate() {
|
|
||||||
let (shown, wanted) = (premultiplied(*actual), premultiplied(*expected));
|
|
||||||
let difference = (0..4).map(|channel| (shown[channel] - wanted[channel]).abs()).fold(0., f32::max);
|
|
||||||
assert!(difference <= 1.5, "pixel {index} is {actual:?} rather than {expected:?}, {difference} levels apart");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tiles_small_enough_for_the_download_buffer_match_one_render() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// Square pixels of the document's size keep the effects' working pixels on the render's, so neither render resamples them.
|
|
||||||
// A 2048 byte buffer holds 8 rows of up to 64 pixels, each padded to 256 bytes, so this render is drawn in tiles 8 pixels tall.
|
|
||||||
let image = image_of_pixels(DVec2::ONE, |x, y| Color::from_rgbaf32_unchecked(x as f32 / 20., y as f32 / 20., 0.5, 1.), &[outline(2.)]);
|
|
||||||
let small_buffer = ReadbackLimits { buffer_size: 2048, ..limits };
|
|
||||||
assert_eq!(small_buffer.tile_size(UVec2::splat(100)), Some(UVec2::new(100, 2048 / 512)));
|
|
||||||
|
|
||||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
|
||||||
let tiled = block_on(executor.read_back_within(image, small_buffer)).unwrap();
|
|
||||||
assert_alike(tiled.element(), whole.element(), 1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_image_too_large_to_upload_whole_keeps_its_own_pixels_in_crops() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// Alternating black and white columns, inverted and outlined, which a downscaled upload would average to gray
|
|
||||||
let columns = |x: u32, _| if x.is_multiple_of(2) { Color::BLACK } else { Color::WHITE };
|
|
||||||
let image = image_of_pixels(DVec2::ONE, columns, &[EffectOperation::Adjustment(graphic_types::Adjustment::Invert), outline(2.)]);
|
|
||||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
|
||||||
|
|
||||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
|
||||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
|
||||||
assert_alike(cropped.element(), whole.element(), 1);
|
|
||||||
|
|
||||||
for x in 0..20 {
|
|
||||||
let color = color_at(&cropped, DVec2::new(100.5 + x as f64, 60.5));
|
|
||||||
let inverted = if x % 2 == 0 { is_white(color) } else { is_black(color) };
|
|
||||||
assert!(inverted, "column {x} is {color:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn limits_too_small_for_any_tile_fail_without_panicking() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::WHITE, &[outline(2.)]);
|
|
||||||
let tiny_buffer = ReadbackLimits { buffer_size: 100, ..limits };
|
|
||||||
assert!(block_on(executor.read_back_within(image, tiny_buffer)).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_reach_too_far_for_any_crop_fails_without_overflowing() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// A box blur reaching past 2^31 pixels, on an image too wide for the texture limit, at one document unit per pixel
|
|
||||||
let blur = EffectOperation::Blur {
|
|
||||||
radius_mask: Graphic::default(),
|
|
||||||
radius: 2_147_483_647.,
|
|
||||||
box_blur: true,
|
|
||||||
gamma: false,
|
|
||||||
};
|
|
||||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(16_384, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(16_384., 64.)));
|
|
||||||
stamp_effect(&mut image, Effect::new(&blur));
|
|
||||||
let small_textures = ReadbackLimits { texture_size: 8192, ..limits };
|
|
||||||
|
|
||||||
assert!(block_on(executor.read_back_within(image, small_textures)).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn crops_carry_out_leading_adjustments_on_transparent_pixels_as_the_whole_image_does() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// Make Opaque raises the alpha of fully transparent pixels, which only the image's own pixels can carry, and the outline needs a render
|
|
||||||
let make_opaque = EffectOperation::Adjustment(graphic_types::Adjustment::MakeOpaque { strength: 100. });
|
|
||||||
let image = image_of_pixels(DVec2::ONE, |_, _| Color::from_rgbaf32_unchecked(1., 0., 0., 0.), &[make_opaque, outline(2.)]);
|
|
||||||
let small_textures = ReadbackLimits { texture_size: 16, ..limits };
|
|
||||||
|
|
||||||
let whole = block_on(executor.read_back_within(image.clone(), limits)).unwrap();
|
|
||||||
let cropped = block_on(executor.read_back_within(image, small_textures)).unwrap();
|
|
||||||
assert_alike(cropped.element(), whole.element(), 1);
|
|
||||||
let pixels = (0..20).flat_map(|y| (0..20).map(move |x| DVec2::new(100.5 + x as f64, 50.5 + y as f64)));
|
|
||||||
assert!(pixels.map(|point| color_at(&cropped, point)).all(|color| color.a() > 0.99), "the transparent pixels became opaque");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn crops_hold_the_pixels_effects_reach_past_a_margin_cut_short() {
|
|
||||||
let Some((executor, limits)) = executor_and_limits() else { return };
|
|
||||||
|
|
||||||
// A margin cut to nothing, as for an image too large to grow, still leaves the blur its neighbors across the tiles.
|
|
||||||
// The tiles are wide enough next to the blur's reach that its effects group keeps their full resolution.
|
|
||||||
let blur = EffectOperation::Blur {
|
|
||||||
radius_mask: Graphic::default(),
|
|
||||||
radius: 1.,
|
|
||||||
box_blur: false,
|
|
||||||
gamma: false,
|
|
||||||
};
|
|
||||||
let mut image = Item::new_from_element(Raster::new_cpu(Image::new(64, 64, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(64.)));
|
|
||||||
stamp_effect(&mut image, Effect::new(&blur));
|
|
||||||
let (effects, transform) = (image.attribute::<Effects>(ATTR_EFFECTS).unwrap().clone(), image.attribute_cloned_or_default(ATTR_TRANSFORM));
|
|
||||||
let reach = effects_reach(&effects, DVec2::splat(64.));
|
|
||||||
assert!(reach.min_element() > 0.);
|
|
||||||
let small_textures = ReadbackLimits { texture_size: 60, ..limits };
|
|
||||||
|
|
||||||
let whole = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, limits)).unwrap();
|
|
||||||
let cropped = block_on(executor.render_at_pixel_grid(&image, &effects, transform, DVec2::ZERO, reach, small_textures)).unwrap();
|
|
||||||
assert_alike(&cropped, &whole, 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -22,35 +22,23 @@ struct RasterGpuToRasterCpuConverter {
|
|||||||
padded_bytes_per_row: u32,
|
padded_bytes_per_row: u32,
|
||||||
_source: raster_types::Texture,
|
_source: raster_types::Texture,
|
||||||
}
|
}
|
||||||
/// The bytes in each row of a download buffer for an image `width` pixels wide, padded to the alignment copies need.
|
|
||||||
pub(crate) fn download_row_bytes(width: u32) -> u32 {
|
|
||||||
let bytes_per_pixel = 4; // RGBA8
|
|
||||||
(width * bytes_per_pixel).div_ceil(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT) * wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The buffer a texture of `width` by `height` pixels downloads into.
|
|
||||||
fn download_buffer(executor: &WgpuExecutor, width: u32, height: u32) -> Buffer {
|
|
||||||
executor.create_buffer(&wgpu::BufferDescriptor {
|
|
||||||
label: Some("texture_download_buffer"),
|
|
||||||
size: download_row_bytes(width) as u64 * height as u64,
|
|
||||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
|
||||||
mapped_at_creation: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RasterGpuToRasterCpuConverter {
|
impl RasterGpuToRasterCpuConverter {
|
||||||
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
fn new(executor: &WgpuExecutor, encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>) -> Self {
|
||||||
let buffer = download_buffer(executor, data_gpu.data().width(), data_gpu.data().height());
|
|
||||||
Self::with_buffer(encoder, data_gpu, buffer)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Copies the texture into the `buffer` made for its size, once the `encoder` is submitted.
|
|
||||||
fn with_buffer(encoder: &mut wgpu::CommandEncoder, data_gpu: Raster<GPU>, buffer: Buffer) -> Self {
|
|
||||||
let texture = data_gpu.data();
|
let texture = data_gpu.data();
|
||||||
let width = texture.width();
|
let width = texture.width();
|
||||||
let height = texture.height();
|
let height = texture.height();
|
||||||
let unpadded_bytes_per_row = width * 4;
|
let bytes_per_pixel = 4; // RGBA8
|
||||||
let padded_bytes_per_row = download_row_bytes(width);
|
let unpadded_bytes_per_row = width * bytes_per_pixel;
|
||||||
|
let align = wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;
|
||||||
|
let padded_bytes_per_row = unpadded_bytes_per_row.div_ceil(align) * align;
|
||||||
|
let buffer_size = padded_bytes_per_row as u64 * height as u64;
|
||||||
|
|
||||||
|
let buffer = executor.create_buffer(&wgpu::BufferDescriptor {
|
||||||
|
label: Some("texture_download_buffer"),
|
||||||
|
size: buffer_size,
|
||||||
|
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||||
|
mapped_at_creation: false,
|
||||||
|
});
|
||||||
|
|
||||||
encoder.copy_texture_to_buffer(
|
encoder.copy_texture_to_buffer(
|
||||||
wgpu::TexelCopyTextureInfo {
|
wgpu::TexelCopyTextureInfo {
|
||||||
@@ -85,7 +73,7 @@ impl RasterGpuToRasterCpuConverter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn convert(self, device: &wgpu::Device) -> anyhow::Result<Raster<CPU>> {
|
async fn convert(self, device: &wgpu::Device) -> Result<Raster<CPU>, wgpu::BufferAsyncError> {
|
||||||
let buffer_slice = self.buffer.slice(..);
|
let buffer_slice = self.buffer.slice(..);
|
||||||
let (sender, receiver) = futures::channel::oneshot::channel();
|
let (sender, receiver) = futures::channel::oneshot::channel();
|
||||||
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
buffer_slice.map_async(wgpu::MapMode::Read, move |result| {
|
||||||
@@ -116,12 +104,9 @@ impl RasterGpuToRasterCpuConverter {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let Ok(map_result) = map_result else {
|
map_result.expect("Failed to receive map result")?;
|
||||||
anyhow::bail!("The download of a {} by {} image was canceled before the GPU mapped its buffer", self.width, self.height);
|
|
||||||
};
|
|
||||||
map_result?;
|
|
||||||
|
|
||||||
let view = buffer_slice.get_mapped_range()?;
|
let view = buffer_slice.get_mapped_range().expect("Failed to get mapped range");
|
||||||
|
|
||||||
let row_stride = self.padded_bytes_per_row as usize;
|
let row_stride = self.padded_bytes_per_row as usize;
|
||||||
let row_bytes = self.unpadded_bytes_per_row as usize;
|
let row_bytes = self.unpadded_bytes_per_row as usize;
|
||||||
@@ -245,33 +230,3 @@ impl ConvertAsync<Raster<CPU>, WgpuExecutor> for Raster<GPU> {
|
|||||||
converter.convert(device).await.expect("Failed to download texture data")
|
converter.convert(device).await.expect("Failed to download texture data")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WgpuExecutor {
|
|
||||||
/// Downloads the GPU raster's pixels, failing rather than panicking when the GPU can't make or map the buffer they're copied into.
|
|
||||||
pub async fn try_download(&self, raster: Raster<GPU>) -> anyhow::Result<Raster<CPU>> {
|
|
||||||
let device = &self.context().device;
|
|
||||||
let (width, height) = (raster.data().width(), raster.data().height());
|
|
||||||
let buffer_size = download_row_bytes(width) as u64 * height as u64;
|
|
||||||
let limit = device.limits().max_buffer_size;
|
|
||||||
if buffer_size > limit {
|
|
||||||
anyhow::bail!("Downloading a {width} by {height} image takes a {buffer_size} byte buffer, past the GPU's limit of {limit} bytes");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Popped in the reverse order they're pushed, before awaiting either, since the scopes can't be held across an await
|
|
||||||
let out_of_memory = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory);
|
|
||||||
let validation = device.push_error_scope(wgpu::ErrorFilter::Validation);
|
|
||||||
let buffer = download_buffer(self, width, height);
|
|
||||||
let (validation, out_of_memory) = (validation.pop(), out_of_memory.pop());
|
|
||||||
if let Some(error) = validation.await.or(out_of_memory.await) {
|
|
||||||
anyhow::bail!("The GPU couldn't make the buffer to download a {width} by {height} image: {error}");
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
|
|
||||||
label: Some("fallible_texture_download_encoder"),
|
|
||||||
});
|
|
||||||
let converter = RasterGpuToRasterCpuConverter::with_buffer(&mut encoder, raster, buffer);
|
|
||||||
self.context().queue.submit([encoder.finish()]);
|
|
||||||
|
|
||||||
converter.convert(device).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -109,7 +109,6 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
|||||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||||
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ fn vertex(@builtin(vertex_index) index: u32) -> @builtin(position) vec4<f32> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// The straight color of the source pixel under `position`, in linear light if the source holds that, or else gamma-encoded,
|
// The straight color of the source pixel under `position`, in linear light if the source holds that, or else gamma-encoded,
|
||||||
// with a fully transparent pixel's color left at 0, matching `adjust_premultiplied`
|
// with a fully transparent pixel's color left at 0, matching `straight_linear_color`
|
||||||
fn source_color(position: vec4<f32>) -> vec4<f32> {
|
fn source_color(position: vec4<f32>) -> vec4<f32> {
|
||||||
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
let pixel = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||||
if pixel.a <= 0. {
|
if pixel.a <= 0. {
|
||||||
@@ -365,11 +365,6 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
|||||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
|
||||||
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
|
||||||
return vec4<f32>(vec3<f32>(color.a), color.a);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||||
|
|||||||
Loaded 100 of 149 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user