mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dbba8b0877 |
No files matched your search
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
|
||||
const MAX_RUN_PAGES = 10;
|
||||
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
|
||||
const VERDICT_STEP_NAME = "Fail for the title's verdict";
|
||||
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
|
||||
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
|
||||
const MAX_VERDICT_LOOKUPS = 5;
|
||||
|
||||
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
||||
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
|
||||
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> {
|
||||
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
||||
const run = finishedRunsNewestFirst[i];
|
||||
if (run.conclusion === "success") return run;
|
||||
|
||||
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
|
||||
const steps = jobs.flatMap((job) => job.steps || []);
|
||||
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
|
||||
if (run.conclusion === "success") return run;
|
||||
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
|
||||
}
|
||||
|
||||
|
||||
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
|
||||
const decision = readDecision();
|
||||
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
||||
const passed = PASSING_OUTCOMES.includes(decision.outcome);
|
||||
const superseded = decision.outcome === "superseded";
|
||||
|
||||
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
|
||||
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
|
||||
@@ -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
|
||||
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict";
|
||||
// The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
|
||||
const result = passed ? "approved" : retried ? "retry" : "verdict";
|
||||
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
||||
|
||||
function readDecision(): Decision {
|
||||
|
||||
@@ -150,14 +150,20 @@ jobs:
|
||||
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
|
||||
|
||||
- name: 📤 Publish to Cloudflare Pages
|
||||
if: inputs.merge_queue == false && !github.event.pull_request.head.repo.fork
|
||||
if: inputs.merge_queue == false
|
||||
id: cloudflare
|
||||
continue-on-error: ${{ github.event_name != 'push' }}
|
||||
env:
|
||||
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
# Passed through the environment so a branch name can't inject shell syntax
|
||||
HEAD_BRANCH: ${{ inputs.checkout_ref || github.head_ref || github.ref_name }}
|
||||
run: |
|
||||
if [ -z "$CLOUDFLARE_API_TOKEN" ]; then
|
||||
echo "No Cloudflare API token available (fork PR), skipping deploy."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${{ github.event_name }}" = "push" ]; then
|
||||
DEPLOY_BRANCH="master"
|
||||
else
|
||||
|
||||
@@ -176,8 +176,6 @@ jobs:
|
||||
env:
|
||||
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
|
||||
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`
|
||||
run: >-
|
||||
cargo test --workspace --all-features
|
||||
|
||||
@@ -51,8 +51,6 @@ jobs:
|
||||
with:
|
||||
# Cache on Cargo.lock file
|
||||
cache-on-failure: true
|
||||
# Saved only by master pushes, since a PR's saved cache is readable only by that PR yet counts toward the repo's size limit
|
||||
save-if: ${{ github.event_name == 'push' }}
|
||||
|
||||
- name: Install gungraun-runner and valgrind
|
||||
uses: gungraun/setup-gungraun@62591572561bb2f4ed2ae300b8a8bea99ea8ddaf # v1.1.3
|
||||
|
||||
@@ -64,12 +64,7 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
||||
run: exit 1
|
||||
|
||||
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
|
||||
- name: ⏭️ Pass for a newer run's review
|
||||
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
|
||||
run: echo "A newer run reviews the changed title"
|
||||
|
||||
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
|
||||
- name: 🔁 Fail without a verdict
|
||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
|
||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
|
||||
run: exit 1
|
||||
Generated
+7
-11
@@ -585,7 +585,6 @@ name = "blending-nodes"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
@@ -593,7 +592,6 @@ dependencies = [
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -2677,6 +2675,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -5438,11 +5437,9 @@ dependencies = [
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"interpreted-executor",
|
||||
"log",
|
||||
"node-macro",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5749,6 +5746,8 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
@@ -5773,14 +5772,12 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6024,7 +6021,6 @@ dependencies = [
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"kurbo",
|
||||
"linesweeper",
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
@@ -8079,6 +8075,7 @@ dependencies = [
|
||||
"log",
|
||||
"node-macro",
|
||||
"ollev",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -8086,7 +8083,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8101,7 +8098,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8115,7 +8112,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8586,7 +8583,6 @@ dependencies = [
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"svg-convert",
|
||||
"thiserror 2.0.21",
|
||||
"vello_gpu",
|
||||
"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
|
||||
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||
@@ -3,4 +3,3 @@
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
rename!("blending_nodes::filters::AddNoiseNode"@1 => "blending_nodes::filters::SpeckleNode"@2);
|
||||
@@ -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,8 +1,5 @@
|
||||
//! Migrations of the nodes in `graphene_core`.
|
||||
|
||||
mod fill_v1;
|
||||
mod passthrough_from_read_attribute_gradient_form_node;
|
||||
mod passthrough_from_footprint_value;
|
||||
mod passthrough_from_upload_texture_node;
|
||||
mod renames;
|
||||
mod vary_colors_from_assign_colors;
|
||||
@@ -1,37 +0,0 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
|
||||
/// 'Footprint Value' is gone with the footprint input of 'Rasterize', whose migration takes over the inputs of one feeding it. One read
|
||||
/// elsewhere passes on its empty primary input instead, since nothing else takes a footprint.
|
||||
#[migration("math_nodes::FootprintValueNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
||||
pub fn passthrough_from_footprint_value(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(3, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PassthroughFromFootprintValue, &contract());
|
||||
check_undo(&PassthroughFromFootprintValue, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_primary_input_and_drops_the_transform_and_resolution() {
|
||||
let (primary, transform, resolution) = (literal(()), literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PassthroughFromFootprintValue);
|
||||
let footprint_value = fixture.add(decl!("math_nodes::FootprintValueNode"@1), vec![primary.clone(), transform, resolution]);
|
||||
let migrated = fixture.migrate(&PassthroughFromFootprintValue).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, footprint_value), [primary]);
|
||||
}
|
||||
}
|
||||
-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,4 +1,3 @@
|
||||
//! Migrations of the nodes in `graphene_std`.
|
||||
|
||||
mod rasterize_v1;
|
||||
mod renames;
|
||||
@@ -1,276 +0,0 @@
|
||||
use migration_core::{Declaration, Graph, InputConnector, Inputs, MigrationError, NewNode, Node, NodeInput, OutputConnector, Upstream, decl, encode, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashSet;
|
||||
|
||||
const FOOTPRINT: u32 = 1;
|
||||
const RASTERIZE: Declaration = decl!("graphene_std::platform_application_io::RasterizeNode"@1);
|
||||
|
||||
/// Matched at any version, since naming one would order this migration after the one turning 'Footprint Value' into it, which must come after.
|
||||
const PASSTHROUGH: &str = "graphene_core::ops::PassthroughNode";
|
||||
|
||||
/// The default area, a square 1000 px across centered at (500, 500), and its resolution of one pixel per px.
|
||||
const DEFAULT_TRANSFORM: [f64; 6] = [1000., 0., 0., 1000., 500., 500.];
|
||||
const DEFAULT_RESOLUTION: [f64; 2] = [1000., 1000.];
|
||||
|
||||
/// A translation by half a unit, which moves a unit square anchored at its corner to one centered on the origin.
|
||||
const CORNER_TO_CENTER: [f64; 6] = [1., 0., 0., 1., 0.5, 0.5];
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
Footprint(Footprint),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the removed `Footprint` value, leaving out the render quality 'Rasterize' ignored.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct Footprint {
|
||||
transform: [f64; 6],
|
||||
resolution: [u32; 2],
|
||||
}
|
||||
|
||||
/// 'Rasterize' takes its footprint's area as a transform placing a unit square centered on its origin, rather than anchored at its corner,
|
||||
/// then its resolution. A 'Footprint Value' node feeding it, directly or through reroutes, hands over its own inputs and goes once nothing
|
||||
/// else reads it. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||
#[migration("graphene_std::platform_application_io::RasterizeNode"@1 => @2)]
|
||||
pub fn rasterize_v1(node: &Node, graph: &Graph, inputs: &mut Inputs, upstream: &mut Upstream) -> Result<(), MigrationError> {
|
||||
let Some(footprint) = node.inputs().get(FOOTPRINT as usize) else {
|
||||
return Err(MigrationError::invariant("Rasterize has a Footprint input"));
|
||||
};
|
||||
let footprint = through_reroutes(*graph, &footprint.input);
|
||||
|
||||
let (transform, resolution) = match footprint {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(footprint) {
|
||||
Some(Tagged::Footprint(footprint)) => (
|
||||
value(Tagged::DAffine2(centered(footprint.transform)), *exposed),
|
||||
value(Tagged::DVec2(footprint.resolution.map(f64::from)), *exposed),
|
||||
),
|
||||
_ => defaults(*exposed),
|
||||
},
|
||||
NodeInput::Node { id, index: 0 } if graph.declaration(*id) == Some(decl!("math_nodes::FootprintValueNode"@1)) => {
|
||||
let parameters = graph.node(*id).map(|footprint_value| footprint_value.inputs()).and_then(|slots| Some((slots.get(1)?, slots.get(2)?)));
|
||||
let Some((transform, resolution)) = parameters else {
|
||||
return Err(MigrationError::invariant("Footprint Value has Transform and Resolution inputs"));
|
||||
};
|
||||
|
||||
// Each Rasterize node it feeds takes over its inputs, so it's only needed by whatever else reads it
|
||||
let readers = graph.consumers(OutputConnector { node: *id, output: 0 });
|
||||
let only_feeds_rasterize = readers
|
||||
.iter()
|
||||
.all(|reader| matches!(reader, InputConnector::Node { node, input: FOOTPRINT } if graph.declaration(*node) == Some(RASTERIZE)));
|
||||
if only_feeds_rasterize {
|
||||
upstream.remove_node(*id);
|
||||
}
|
||||
|
||||
let multiply = decl!("math_nodes::MultiplyNode"@1);
|
||||
(centered_transform_input(&transform.input, multiply, upstream), resolution.input.clone())
|
||||
}
|
||||
_ => defaults(true),
|
||||
};
|
||||
|
||||
inputs.set(FOOTPRINT, transform);
|
||||
inputs.insert(FOOTPRINT + 1, resolution);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Where `input` reads from past any 'Passthrough' nodes rerouting it, which pass their content along unchanged.
|
||||
fn through_reroutes<'a>(graph: Graph<'a>, mut input: &'a NodeInput) -> &'a NodeInput {
|
||||
let mut visited = HashSet::new();
|
||||
|
||||
// A cycle of reroutes leads nowhere else, so revisiting one ends the walk
|
||||
while let NodeInput::Node { id, index: 0 } = input
|
||||
&& visited.insert(*id)
|
||||
&& graph.declaration(*id).is_some_and(|declaration| declaration.identifier == PASSTHROUGH)
|
||||
&& let Some(content) = graph.node(*id).and_then(|node| node.inputs().first())
|
||||
{
|
||||
input = &content.input;
|
||||
}
|
||||
|
||||
input
|
||||
}
|
||||
|
||||
/// The area transform from a 'Footprint Value' node's transform input, through a `multiply` node centering its unit square if it's wired.
|
||||
fn centered_transform_input(transform: &NodeInput, multiply: Declaration, upstream: &mut Upstream) -> NodeInput {
|
||||
match transform {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(transform) {
|
||||
Some(Tagged::DAffine2(transform)) => value(Tagged::DAffine2(centered(transform)), *exposed),
|
||||
_ => value(Tagged::DAffine2(DEFAULT_TRANSFORM), *exposed),
|
||||
},
|
||||
wire => {
|
||||
let multiply = upstream.add_node(NewNode {
|
||||
declaration: multiply,
|
||||
inputs: vec![wire.clone(), literal(Tagged::DAffine2(CORNER_TO_CENTER))],
|
||||
});
|
||||
NodeInput::Node { id: multiply, index: 0 }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The transform placing a unit square centered on its origin over the one `transform` places anchored at its corner, which is `transform`
|
||||
/// followed by a translation of half a unit, computed in the order a `DAffine2` product computes it.
|
||||
fn centered([x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]: [f64; 6]) -> [f64; 6] {
|
||||
[
|
||||
x_axis_x,
|
||||
x_axis_y,
|
||||
y_axis_x,
|
||||
y_axis_y,
|
||||
x_axis_x * 0.5 + y_axis_x * 0.5 + translation_x,
|
||||
x_axis_y * 0.5 + y_axis_y * 0.5 + translation_y,
|
||||
]
|
||||
}
|
||||
|
||||
fn defaults(exposed: bool) -> (NodeInput, NodeInput) {
|
||||
(value(Tagged::DAffine2(DEFAULT_TRANSFORM), exposed), value(Tagged::DVec2(DEFAULT_RESOLUTION), exposed))
|
||||
}
|
||||
|
||||
fn value(value: Tagged, exposed: bool) -> NodeInput {
|
||||
NodeInput::Value { value: encode(&value), exposed }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const FOOTPRINT_VALUE: Declaration = decl!("math_nodes::FootprintValueNode"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(3, |random, slot| match slot {
|
||||
1 => literal(Tagged::Footprint(Footprint {
|
||||
transform: [random.below(10) as f64, 0., 0., random.below(10) as f64, random.below(10) as f64, random.below(10) as f64],
|
||||
resolution: [random.below(10) as u32, random.below(10) as u32],
|
||||
})),
|
||||
_ => literal(random.below(10) as f64),
|
||||
})
|
||||
}
|
||||
|
||||
/// Rasterize's inputs with `footprint` between its artwork and its executor.
|
||||
fn rasterize_inputs(footprint: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(0.), footprint, NodeInput::Scope("wgpu-executor".into())]
|
||||
}
|
||||
|
||||
/// Rasterize's migrated inputs with `transform` and `resolution` between its artwork and its executor.
|
||||
fn migrated_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(0.), transform, resolution, NodeInput::Scope("wgpu-executor".into())]
|
||||
}
|
||||
|
||||
fn footprint_value_inputs(transform: NodeInput, resolution: NodeInput) -> Vec<NodeInput> {
|
||||
vec![literal(()), transform, resolution]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RasterizeV1, &contract());
|
||||
check_undo(&RasterizeV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_becomes_the_transform_centered_on_its_area_and_its_resolution() {
|
||||
// The 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||
let footprint = Footprint {
|
||||
transform: [500., 0., 0., 250., -20., 40.],
|
||||
resolution: [64, 32],
|
||||
};
|
||||
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([500., 0., 0., 250., 230., 165.])), literal(Tagged::DVec2([64., 32.])));
|
||||
assert_eq!(fixture.declaration_of(&migrated, rasterize), Some(decl!("graphene_std::platform_application_io::RasterizeNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_footprint_becomes_the_default_area_and_resolution() {
|
||||
let footprint = Footprint {
|
||||
transform: [1000., 0., 0., 1000., 0., 0.],
|
||||
resolution: [1000, 1000],
|
||||
};
|
||||
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(literal(Tagged::Footprint(footprint))));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let (transform, resolution) = defaults(false);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_hands_over_its_inputs_and_goes() {
|
||||
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let resolution_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let resolution = NodeInput::Node { id: resolution_source, index: 0 };
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||
let first = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let second = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||
assert_eq!(fixture.inputs(&migrated, first), expected);
|
||||
assert_eq!(fixture.inputs(&migrated, second), expected);
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), None, "nothing else reads the Footprint Value node");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_hands_over_its_inputs_through_reroutes() {
|
||||
let transform = literal(Tagged::DAffine2([300., 0., 0., 200., 10., 20.]));
|
||||
let resolution = literal(Tagged::DVec2([30., 20.]));
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(transform, resolution.clone()));
|
||||
let first_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@1), vec![NodeInput::Node { id: footprint_value, index: 0 }]);
|
||||
let second_reroute = fixture.add(decl!("graphene_core::ops::PassthroughNode"@2), vec![NodeInput::Node { id: first_reroute, index: 0 }]);
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: second_reroute, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let expected = migrated_inputs(literal(Tagged::DAffine2([300., 0., 0., 200., 160., 120.])), resolution);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), expected);
|
||||
assert_eq!(
|
||||
fixture.declaration_of(&migrated, footprint_value),
|
||||
Some(FOOTPRINT_VALUE),
|
||||
"the reroute still reads the Footprint Value node"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_footprint_value_transform_reaches_the_area_through_a_multiply_node() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let transform_source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let wire = NodeInput::Node { id: transform_source, index: 0 };
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(wire.clone(), literal(Tagged::DVec2([30., 20.]))));
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let inputs = fixture.inputs(&migrated, rasterize);
|
||||
let NodeInput::Node { id: multiply, index: 0 } = inputs[1] else {
|
||||
panic!("the area should be wired from a Multiply node");
|
||||
};
|
||||
assert_eq!(inputs, migrated_inputs(NodeInput::Node { id: multiply, index: 0 }, literal(Tagged::DVec2([30., 20.]))));
|
||||
assert_eq!(fixture.declaration_of(&migrated, multiply), Some(decl!("math_nodes::MultiplyNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, multiply), [wire, literal(Tagged::DAffine2(CORNER_TO_CENTER))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_footprint_value_node_read_elsewhere_stays() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let footprint_value = fixture.add(FOOTPRINT_VALUE, footprint_value_inputs(literal(Tagged::DAffine2(CORNER_TO_CENTER)), literal(Tagged::DVec2([1., 1.]))));
|
||||
fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: footprint_value, index: 0 }));
|
||||
fixture.export(NodeInput::Node { id: footprint_value, index: 0 });
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, footprint_value), Some(FOOTPRINT_VALUE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_other_wire_leaves_the_defaults_shown_in_the_graph() {
|
||||
let mut fixture = Fixture::new(&RasterizeV1);
|
||||
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let rasterize = fixture.add(RASTERIZE, rasterize_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||
let migrated = fixture.migrate(&RasterizeV1).unwrap();
|
||||
|
||||
let (transform, resolution) = defaults(true);
|
||||
assert_eq!(fixture.inputs(&migrated, rasterize), migrated_inputs(transform, resolution));
|
||||
}
|
||||
}
|
||||
@@ -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`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -6,6 +6,5 @@ mod mandelbrot_v2;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod noise_pattern_v2;
|
||||
mod passthrough_from_extend_image_to_bounds;
|
||||
mod pattern_square;
|
||||
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
|
||||
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,
|
||||
CutLayers,
|
||||
WriteItems { items: Vec<ApplicationDataItem> },
|
||||
Rendered { id: u64, svg: Result<Option<String>, String> },
|
||||
Rendered { id: u64, svg: Option<String> },
|
||||
Loaded { id: u64, content: DataTransfer },
|
||||
PasteItems { items: Vec<ApplicationDataItem> },
|
||||
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 {
|
||||
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);
|
||||
}
|
||||
ClipboardMessage::Loaded { id, content } => {
|
||||
@@ -674,212 +665,6 @@ mod test {
|
||||
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
|
||||
/// - assert that ellipse was copied
|
||||
#[tokio::test]
|
||||
|
||||
@@ -878,22 +878,6 @@ pub struct SliderMarker {
|
||||
/// Whether this marker follows its neighbors instead of bounding them, so they may drag past its drawn position.
|
||||
#[serde(rename = "betweenNeighbors")]
|
||||
between_neighbors: bool,
|
||||
/// How this marker and the next may pass each other.
|
||||
#[serde(rename = "overlapNext")]
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
/// How a slider marker and the next may pass each other, as split handles whose ranges may overlap.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum MarkerOverlap {
|
||||
/// Neither may pass the other.
|
||||
#[default]
|
||||
Never,
|
||||
/// Each may pass the other but not the marker beyond it, so split handles' inner halves can overlap while the handles can't pass each other.
|
||||
NextOnly,
|
||||
/// The markers up to this one and those after it don't bound each other, so split handles can pass each other entirely.
|
||||
Freely,
|
||||
}
|
||||
|
||||
impl SliderMarker {
|
||||
@@ -906,7 +890,6 @@ impl SliderMarker {
|
||||
paired_with_next: false,
|
||||
dashed_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -924,11 +907,6 @@ impl SliderMarker {
|
||||
self.dashed_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
|
||||
@@ -5,14 +5,10 @@ use crate::test_utils::gpu_executor;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::application_io::Texture;
|
||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math_nodes::{color_value, gradient_value};
|
||||
use graphene_std::raster_nodes::std_nodes::noise_pattern;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -140,111 +136,6 @@ fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
/// Endless content a layer can hold, which fills the whole canvas unless something clips it.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Endless {
|
||||
Color,
|
||||
Gradient,
|
||||
NoisePattern,
|
||||
}
|
||||
|
||||
/// A document viewed in the `render_mode` with a blue rectangle filling (50, 50) to (130, 130).
|
||||
async fn document_with_a_rectangle(render_mode: RenderMode) -> EditorTestUtils {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode }).await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
|
||||
editor
|
||||
}
|
||||
|
||||
/// Adds a new layer of `endless` content above the selected layer, clipped to it as by an Alt-click between them.
|
||||
async fn add_clipped_endless_layer(editor: &mut EditorTestUtils, endless: Endless) {
|
||||
editor.handle_message(DocumentMessage::CreateEmptyFolder).await;
|
||||
let layer = editor.get_selected_layer().await.expect("the new layer is selected");
|
||||
let node = match endless {
|
||||
Endless::Color => color_value::IDENTIFIER,
|
||||
Endless::Gradient => gradient_value::IDENTIFIER,
|
||||
Endless::NoisePattern => noise_pattern::IDENTIFIER,
|
||||
};
|
||||
let node_type = DefinitionIdentifier::ProtoNode(node);
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: layer.to_node() }).await;
|
||||
}
|
||||
|
||||
/// Evaluates the document for a viewport of `size` as the app does, returning what the frontend is sent and the frame the runtime presents.
|
||||
async fn evaluate_viewport(editor: &mut EditorTestUtils, size: UVec2) -> (Vec<FrontendMessage>, Option<Texture>) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
let document_id = portfolio.active_document_id.expect("a document is open");
|
||||
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
|
||||
let document = documents.get_mut(&document_id).expect("the active document exists");
|
||||
let submitted = executor
|
||||
.submit_node_graph_evaluation(document, document_id, size, 1., Default::default(), Vec::new(), true, DVec2::ZERO)
|
||||
.expect("the evaluation is submitted");
|
||||
|
||||
let mut messages = editor.dispatch(submitted);
|
||||
editor.runtime.update();
|
||||
let frame = editor.runtime.run().await;
|
||||
messages.extend(editor.dispatch(Message::Wake));
|
||||
|
||||
(messages, frame)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn endless_layers_clip_to_the_shape_beneath_them() {
|
||||
let size = UVec2::new(256, 256);
|
||||
|
||||
let frame_pixels = async |editor: &mut EditorTestUtils| {
|
||||
let (_, frame) = evaluate_viewport(editor, size).await;
|
||||
let frame = frame.expect("the viewport presents a frame");
|
||||
gpu_executor().read_texture_pixels(&frame).expect("the frame reads back")
|
||||
};
|
||||
let pixel = |pixels: &[u8], x: u32, y: u32| {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
for endless in [Endless::Color, Endless::Gradient, Endless::NoisePattern] {
|
||||
// In the viewport's Vello render, the endless content covers the rectangle but leaves the canvas past it as the rectangle alone left it
|
||||
let mut editor = document_with_a_rectangle(RenderMode::Normal).await;
|
||||
let rectangle_alone = frame_pixels(&mut editor).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let clipped = frame_pixels(&mut editor).await;
|
||||
|
||||
assert_ne!(pixel(&clipped, 90, 90), pixel(&rectangle_alone, 90, 90), "{endless:?}: the content shows within the rectangle");
|
||||
for (x, y) in [(20, 20), (200, 90), (90, 200), (230, 230)] {
|
||||
assert_eq!(
|
||||
pixel(&clipped, x, y),
|
||||
pixel(&rectangle_alone, x, y),
|
||||
"{endless:?}: the content is clipped away at ({x}, {y}), past the rectangle"
|
||||
);
|
||||
}
|
||||
|
||||
// In SVG Preview, the endless content is drawn only within the rectangle's mask
|
||||
let mut editor = document_with_a_rectangle(RenderMode::SvgPreview).await;
|
||||
add_clipped_endless_layer(&mut editor, endless).await;
|
||||
let (messages, _) = evaluate_viewport(&mut editor, size).await;
|
||||
let svg = messages
|
||||
.into_iter()
|
||||
.find_map(|message| match message {
|
||||
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the viewport's artwork is sent as SVG");
|
||||
|
||||
let (unmasked, masked) = svg.split_once(r#"mask="url(#mask-"#).unwrap_or_else(|| panic!("{endless:?}: the content is masked: {svg}"));
|
||||
let draws_endless_content = |markup: &str| ["<polyline", "<foreignObject"].iter().any(|tag| markup.contains(tag));
|
||||
assert!(
|
||||
!draws_endless_content(unmasked) && draws_endless_content(masked),
|
||||
"{endless:?}: the content is drawn within the mask: {svg}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||
|
||||
@@ -31,13 +31,12 @@ use graphene_std::vector::misc::{
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
||||
StrokeJoin,
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource,
|
||||
GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use kurbo::BezPath;
|
||||
@@ -409,6 +408,7 @@ macro_rules! inspectable_types {
|
||||
List<DVec2>,
|
||||
List<DAffine2>,
|
||||
List<BlendMode>,
|
||||
List<GradientForm>,
|
||||
List<GradientSpread>,
|
||||
List<GradientSpace>,
|
||||
List<GradientHueDirection>,
|
||||
@@ -469,7 +469,6 @@ macro_rules! inspectable_types {
|
||||
Item<DAffine2>,
|
||||
Item<BlendMode>,
|
||||
Item<GradientForm>,
|
||||
Item<GradientModel>,
|
||||
Item<GradientSpread>,
|
||||
Item<GradientSpace>,
|
||||
Item<GradientHueDirection>,
|
||||
@@ -1278,14 +1277,12 @@ impl_table_item_layout_for_choice_enum!(
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -1475,13 +1472,11 @@ macro_rules! known_item_types {
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
|
||||
@@ -4138,7 +4138,7 @@ impl DocumentMessageHandler {
|
||||
})
|
||||
.unwrap_or((None, None, None));
|
||||
|
||||
let blend_mode_menu_entries = BlendMode::list()
|
||||
let blend_mode_menu_entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|modes| {
|
||||
modes
|
||||
@@ -4155,7 +4155,7 @@ impl DocumentMessageHandler {
|
||||
|
||||
let widgets = vec![
|
||||
DropdownInput::new(blend_mode_menu_entries)
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list()).map(|index| index as u32))
|
||||
.selected_index(blend_mode.and_then(|blend_mode| blend_mode.index_in_list_svg_subset()).map(|index| index as u32))
|
||||
.disabled(disabled)
|
||||
.draw_icon(false)
|
||||
.sizing(WidgetSizing::default().grow(false))
|
||||
|
||||
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
|
||||
layer: LayerNodeIdentifier,
|
||||
#[serde(skip)]
|
||||
gradient: Gradient,
|
||||
/// The form whose curvatures the Fill takes, or `None` to keep its own.
|
||||
gradient_form: Option<GradientForm>,
|
||||
gradient_form: GradientForm,
|
||||
gradient_settings: GradientSettings,
|
||||
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
||||
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),
|
||||
..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) => {
|
||||
let gradient_transform = usvg_transform(radial.transform());
|
||||
@@ -1062,7 +1062,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
||||
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||
..Default::default()
|
||||
};
|
||||
modify_inputs.fill_gradient_set(gradient, 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"),
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||
use crate::messages::prelude::*;
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||
ReplaceablePaintChain, 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 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: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
|
||||
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
|
||||
return;
|
||||
@@ -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(
|
||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
||||
true,
|
||||
);
|
||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
|
||||
}
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
self.set_input_with_refresh(
|
||||
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
|
||||
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
|
||||
false,
|
||||
);
|
||||
|
||||
if existing_fill_node_id.is_none() {
|
||||
self.restore_default_stroke_order();
|
||||
@@ -773,28 +761,20 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
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
|
||||
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
||||
let Some(curvatures) = gradient_curvature_values(node) else { return };
|
||||
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
|
||||
return;
|
||||
}
|
||||
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
}
|
||||
|
||||
/// 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::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_ZOOM_SCALE_MIN, VIEWPORT_ZOOM_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
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_TO_FIT_PADDING_SCALE_FACTOR,
|
||||
};
|
||||
use crate::messages::frontend::utility_types::MouseCursorIcon;
|
||||
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::utility_types::misc::PTZ;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
@@ -34,8 +34,6 @@ pub struct NavigationMessageHandler {
|
||||
abortable_pan_start: Option<f64>,
|
||||
/// Whether the current drag navigates the artwork behind the open node graph, rather than the graph itself.
|
||||
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]
|
||||
@@ -101,10 +99,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
return;
|
||||
};
|
||||
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 } => {
|
||||
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::UpdateHints);
|
||||
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 } => {
|
||||
self.finish_operation_with_click = false;
|
||||
@@ -430,10 +417,6 @@ impl MessageHandler<NavigationMessage, NavigationMessageContext<'_>> for Navigat
|
||||
}
|
||||
}
|
||||
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 {
|
||||
NavigationOperation::None => {}
|
||||
NavigationOperation::Pan { .. } => {
|
||||
|
||||
@@ -5,19 +5,16 @@ use super::node_inspector::{self, ParameterWidgetsInfo, SliderRange};
|
||||
use super::utility_types::{FrontendNodeType, InputTypeConstraint};
|
||||
use crate::messages::frontend::IconName;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, Vec2InputSettings, WidgetOverride,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{NodeNetworkInterface, NodeTemplate, NodeTemplateImplementation};
|
||||
use crate::messages::portfolio::ingest::utility_types::TypeFilter;
|
||||
use crate::messages::prelude::{DocumentId, FontsMessage, FontsMessageHandler, Message, ResourceMessageHandler, Responses};
|
||||
use crate::node_graph_executor::NodeGraphExecutor;
|
||||
use glam::DVec2;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::concrete;
|
||||
use graph_craft::document::value::*;
|
||||
use graph_craft::document::*;
|
||||
use graph_craft::{concrete, list};
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, Color, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::raster::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, NoiseType};
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -40,6 +37,11 @@ impl NodeInspectorContext<'_> {
|
||||
let input_inspector_row = self.network_interface.persistent_input_metadata(node_id, index, self.selection_network_path)?;
|
||||
let widget_override = input_inspector_row.widget_override.clone()?;
|
||||
|
||||
// Older documents store number and Vec2 widget settings this way, but they come from the definition's parameter
|
||||
if matches!(widget_override.as_str(), "number" | "vec2") {
|
||||
return None;
|
||||
}
|
||||
|
||||
let Some(widget_override_lambda) = INPUT_OVERRIDES.get(&widget_override) else {
|
||||
log::error!("Could not get widget override '{widget_override}' lambda in call_widget_override");
|
||||
return None;
|
||||
@@ -51,11 +53,11 @@ impl NodeInspectorContext<'_> {
|
||||
}
|
||||
|
||||
/// Input position of the location parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = 2;
|
||||
pub const ARTBOARD_LOCATION_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
/// Input position of the dimensions parameter on the "Artboard" layer template, which follows the two layer-shaped inputs (stack and content) and maps through to the inner Create Artboard proto node.
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = 3;
|
||||
pub const ARTBOARD_DIMENSIONS_INPUT_INDEX: usize = graphene_std::subgraphs::artboard::DimensionsInput::INDEX;
|
||||
/// Input position of the control path parameter on the "Blend" network node template.
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = 4;
|
||||
pub const BLEND_PATH_INPUT_INDEX: usize = graphene_std::subgraphs::blend::PathInput::INDEX;
|
||||
|
||||
/// The key used to access definitions for a network node or proto node.
|
||||
/// For proto nodes, this is their [`ProtoNodeIdentifier`].
|
||||
@@ -107,8 +109,7 @@ pub struct DocumentNodeDefinition {
|
||||
/// Used to create the [`DefinitionIdentifier::Network`] identifier.
|
||||
pub identifier: &'static str,
|
||||
|
||||
/// The definition's position in its lineage. Bump it, with a `network` migration, when a change would load existing instances wrongly.
|
||||
/// Instances store it next to their reference. Proto-node definitions take theirs from the node macro.
|
||||
/// The definition's position in its lineage, from `version(N)` on its `#[node]` or `#[graph]`. Instances store it next to their reference.
|
||||
pub version: u32,
|
||||
|
||||
/// The default [`NodeTemplate`] this definition instantiates.
|
||||
@@ -136,529 +137,9 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
|
||||
/// Defines the "signature" or "header file"-like metadata for the document nodes, but not the implementation (which is defined in the node registry).
|
||||
/// The [`DocumentNode`] is the instance while these [`DocumentNodeDefinition`]s are the "classes" or "blueprints" from which the instances are built.
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
/// A proto node within a definition takes its input and output metadata from the node macro in NODE_METADATA, and its display name too unless the definition gives one.
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Graphic), true), NodeInput::type_default(list!(Graphic), true)],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of layers below this one, which the content is placed above.").into(),
|
||||
("Content", "The artwork this layer adds to the stack as a single item.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of layers with this layer's content placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Merges the provided content as a new item in the layer's compositing stack."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Artboard",
|
||||
version: 1,
|
||||
category: "Graphic",
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(artboard::create_artboard::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(Type::Fn(concrete!(Context).into(), generic!(T).into()), 1),
|
||||
NodeInput::import(item!(TaggedValue), 2),
|
||||
NodeInput::import(item!(TaggedValue), 3),
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Artboard), true),
|
||||
NodeInput::type_default(list!(Graphic), true),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::ZERO), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(1920., 1080.)), false),
|
||||
NodeInput::value(TaggedValue::Color(Color::WHITE), false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Base", "The stack of artboards below this one, which this artboard is placed above.").into(),
|
||||
("Content", "Graphics to include within the artboard.").into(),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Location",
|
||||
"Coordinate of the top-left corner of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "X".to_string(),
|
||||
y: "Y".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override(
|
||||
"Dimensions",
|
||||
"Width and height of the artboard within the document.",
|
||||
WidgetOverride::Vec2(Vec2InputSettings {
|
||||
x: "W".to_string(),
|
||||
y: "H".to_string(),
|
||||
unit: " px".to_string(),
|
||||
is_integer: true,
|
||||
..Default::default()
|
||||
}),
|
||||
),
|
||||
InputMetadata::with_name_description_override("Background", "Color of the artboard background.", WidgetOverride::Custom("artboard_background".to_string())),
|
||||
("Clip", "Whether to cut off the contained content that extends outside the artboard, or keep it visible.").into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The stack of artboards with this artboard placed on top.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::layer(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a new Artboard which can be used as a working surface."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Blend",
|
||||
version: 1,
|
||||
category: "Vector: Deform",
|
||||
icon: Some("NodeBlend"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(16), 0)],
|
||||
nodes: [
|
||||
// 0: Separate Paths (split the vector into its individual paths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::separate_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Count (number of subpaths)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::count::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Max (clamp subpath count to at least 1 for empty path case)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Number (the integer count enters the network's decimal math)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::as_number::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(item!(i64), 1)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Multiply (total_instances = count × subpath_count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Subtract (count - 1, open subpath denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::subtract::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Read Index (current repetition index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_index::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(2, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Divide (index / count)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 10)),
|
||||
..Default::default()
|
||||
},
|
||||
// 8: Floor (floor(index / count) = subpath index)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::floor::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(7), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 9: Modulo (index % count = local index within subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::modulo::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::node(NodeId(17), 0), NodeInput::value(TaggedValue::Bool(true), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(16, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 10: Path Is Closed (check if current subpath is closed)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_is_closed::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 4), NodeInput::node(NodeId(8), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
// 11: Switch (closed → count, open → max(count - 1, 1) as denominator)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::switch::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(10), 0), NodeInput::node(NodeId(17), 0), NodeInput::node(NodeId(18), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 12)),
|
||||
..Default::default()
|
||||
},
|
||||
// 12: Divide (local_index / denominator = within-subpath fraction)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::divide::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(9), 0), NodeInput::node(NodeId(11), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 13: Multiply (fraction × 0.9999999999 to avoid overflowing to the next subpath)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::multiply::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(12), 0), NodeInput::value(TaggedValue::Number(0.9999999999), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(30, 7)),
|
||||
..Default::default()
|
||||
},
|
||||
// 14: Add (subpath_index + clamped fraction = progression)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::add::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(8), 0), NodeInput::node(NodeId(13), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(37, 4)),
|
||||
..Default::default()
|
||||
},
|
||||
// 15: Morph (content, progression, reverse, distribution, path)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::morph::IDENTIFIER),
|
||||
inputs: vec![
|
||||
NodeInput::import(generic!(T), 0),
|
||||
NodeInput::node(NodeId(14), 0),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::import(item!(vector::misc::InterpolationDistribution), 3),
|
||||
NodeInput::import(item!(Vector), 4),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(44, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// 16: Repeat
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(repeat_nodes::repeat::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(15), 0), NodeInput::node(NodeId(4), 0), NodeInput::import(generic!(T), 2)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(51, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 17: Max (clamp count to at least 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(3), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(9, 13)),
|
||||
..Default::default()
|
||||
},
|
||||
// 18: Max (clamp open-path denominator to at least 1 to avoid division by zero when count = 1)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(math_nodes::max::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0), NodeInput::value(TaggedValue::Number(1.), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(23, 14)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(list!(Vector), true),
|
||||
NodeInput::value(TaggedValue::Integer(10), false),
|
||||
NodeInput::value(TaggedValue::Bool(Default::default()), false),
|
||||
NodeInput::value(TaggedValue::InterpolationDistribution(Default::default()), false),
|
||||
NodeInput::type_default(item!(Vector), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The vector objects to create intermediate shapes between.").into(),
|
||||
(
|
||||
"Count",
|
||||
"The number of shapes spanning from the first object to the last, repeated for each subpath of the control path.",
|
||||
)
|
||||
.into(),
|
||||
("Reverse", "Flip the stacking order of the shapes, so the ones nearest the first object are on top.").into(),
|
||||
("Distribution", "What changes evenly from one shape to the next, which sets how the intermediate shapes are spaced.").into(),
|
||||
(
|
||||
"Path",
|
||||
"An optional control path with one anchor point per object. Curved segments shape the trajectory of the blend instead of traveling straight.",
|
||||
)
|
||||
.into(),
|
||||
],
|
||||
output_names: vec!["Out".to_string()],
|
||||
output_descriptions: vec!["The blended shapes, from the first object to the last.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Creates a series of intermediate shapes that gradually transition between vector objects, optionally along a control path."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Origins to Polyline",
|
||||
version: 1,
|
||||
category: "Vector: Path",
|
||||
icon: Some("NodeOriginsToPolyline"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(7), 0)],
|
||||
nodes: [
|
||||
// 0: Read Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(context::read_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 1: Extract Transform
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::extract_transform::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 2: Decompose Translation
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(transform_nodes::decompose_translation::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(1), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 3: As Vector (auto-converts the decomposed translation into a single-anchor List<Vector>)
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::as_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(2), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 1)),
|
||||
..Default::default()
|
||||
},
|
||||
// 4: Flatten Vector
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic_nodes::graphic::flatten_vector::IDENTIFIER),
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(21, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 5: Map
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::map::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(4), 0), NodeInput::node(NodeId(3), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(28, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 6: Combine Paths
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::combine_paths::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(5), 0)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(35, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// 7: Points to Polyline
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::points_to_polyline::IDENTIFIER),
|
||||
inputs: vec![NodeInput::node(NodeId(6), 0), NodeInput::value(TaggedValue::Bool(false), false)],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(42, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::type_default(list!(Vector), true)],
|
||||
input_metadata: vec![("Vector", "The vector objects to connect in order by their origins.").into()],
|
||||
output_names: vec!["Vector".to_string()],
|
||||
output_descriptions: vec!["An open polyline with an anchor point at the origin of each object.".to_string()],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Connects the origins of vector objects in order with an open polyline, such as to make a control path for the **Blend** and **Morph** nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Load Image",
|
||||
version: 1,
|
||||
category: "Data: I/O",
|
||||
icon: Some("NodeLoadImage"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::import(item!(String), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::load_resource::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::bytes_to_image::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
|
||||
input_metadata: vec![
|
||||
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
|
||||
("URL", "The web address or local asset path of the image to load.").into(),
|
||||
],
|
||||
output_names: vec!["Image".to_string()],
|
||||
output_descriptions: vec!["The loaded image.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Loads an image from a given URL."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Regex Find",
|
||||
version: 1,
|
||||
category: "String: Regex",
|
||||
icon: Some("NodeRegexFind"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![
|
||||
// Primary output: the whole match (String)
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
// Secondary output: capture groups (List<String>), each item carries `start`/`end`/`name` attributes from `regex_find`
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
nodes: [
|
||||
// Node 0: regex_find proto node — returns List<String> of [whole_match, ...capture_groups]
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(item!(String), 0),
|
||||
NodeInput::import(item!(String), 1),
|
||||
NodeInput::import(item!(i64), 2),
|
||||
NodeInput::import(item!(bool), 3),
|
||||
NodeInput::import(item!(bool), 4),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(text_nodes::regex::regex_find::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 1: item_at_index at index 0, extracts the whole match as a bare String (drops the item's start/end/name attributes since the unwrapped String can't carry them)
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::item_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Node 2: remove_at_index at index 0, returns the capture group items as a List<String>, preserving each item's start/end/name attributes
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::value(TaggedValue::Integer(0), false)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::remove_at_index::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(8, 2)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::String(String::new()), true),
|
||||
NodeInput::value(TaggedValue::String(String::new()), false),
|
||||
NodeInput::value(TaggedValue::Integer(0), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
NodeInput::value(TaggedValue::Bool(false), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("String", "The string to search within.").into(),
|
||||
("Pattern", "The regular expression pattern to search for.").into(),
|
||||
(
|
||||
"Match Index",
|
||||
"Which non-overlapping occurrence of the pattern to return, starting from 0 for the first match. Negative indices count backwards from the last match.",
|
||||
)
|
||||
.into(),
|
||||
("Case Insensitive", "Match letters regardless of case.").into(),
|
||||
("Multiline", "Make `^` and `$` match the start and end of each line, not just the whole string.").into(),
|
||||
],
|
||||
output_names: vec!["Match".to_string(), "Captures".to_string()],
|
||||
output_descriptions: vec![
|
||||
"The whole portion of the string matching the pattern, or empty if there is no match.".to_string(),
|
||||
"The text matched by each capture group in the pattern, in order.".to_string(),
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed(
|
||||
r#"Finds a portion of the string matching a regular expression pattern. With "Match Index" at its default 0, it selects the first non-overlapping occurrence, but others may be selected. Capture groups, if any, are produced as a list in the "Captures" output."#,
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
document_node_derive::derive_definitions()
|
||||
}
|
||||
|
||||
type NodeInspector = HashMap<String, Box<dyn Fn(NodeId, &mut NodeInspectorContext) -> Vec<LayoutGroup> + Send + Sync>>;
|
||||
@@ -676,7 +157,6 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("hue_saturation_inspector".to_string(), Box::new(node_inspector::hue_saturation_inspector));
|
||||
map.insert("black_and_white_inspector".to_string(), Box::new(node_inspector::black_and_white_inspector));
|
||||
map.insert("threshold_inspector".to_string(), Box::new(node_inspector::threshold_inspector));
|
||||
map.insert("blend_if_inspector".to_string(), Box::new(node_inspector::blend_if_inspector));
|
||||
map.insert("vibrance_inspector".to_string(), Box::new(node_inspector::vibrance_inspector));
|
||||
map.insert("color_balance_inspector".to_string(), Box::new(node_inspector::color_balance_inspector));
|
||||
map.insert("fill_inspector".to_string(), Box::new(node_inspector::fill_inspector));
|
||||
@@ -686,7 +166,6 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
@@ -739,91 +218,10 @@ fn static_input_inspector() -> InputInspector {
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"number".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
if let Some(unit) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
{
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
if let Some(min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.min(min);
|
||||
}
|
||||
if let Some(max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.max(max);
|
||||
}
|
||||
if let Some(step) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "step", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.step(step);
|
||||
}
|
||||
if let Some(mode) = context.network_interface.input_data(&node_id, index, "mode", context.selection_network_path).map(|value| {
|
||||
let mode: NumberInputMode = serde_json::from_value(value.clone()).unwrap();
|
||||
mode
|
||||
}) {
|
||||
number_input = number_input.mode(mode);
|
||||
}
|
||||
if let Some(range_min) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_min(Some(range_min));
|
||||
}
|
||||
if let Some(range_max) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "range_max", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64())
|
||||
{
|
||||
number_input = number_input.range_max(Some(range_max));
|
||||
}
|
||||
if let Some(is_integer) = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
{
|
||||
number_input = number_input.is_integer(is_integer);
|
||||
}
|
||||
let blank_assist = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "blank_assist", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get blank assist when displaying number input for node {node_id}, index {index}");
|
||||
true
|
||||
});
|
||||
|
||||
Ok(vec![LayoutGroup::row(node_inspector::number_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context),
|
||||
number_input,
|
||||
))])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
// The custom number input settings are only available on proto nodes
|
||||
"optional_f64".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let mut number_input = NumberInput::default();
|
||||
// The field is cloned so the lock is released before building the row below, which locks the node metadata again
|
||||
if let Some(field) = context
|
||||
.network_interface
|
||||
.implementation(&node_id, context.selection_network_path)
|
||||
.and_then(|implementation| if let DocumentNodeImplementation::ProtoNode(id) = implementation { Some(id) } else { None })
|
||||
.and_then(|proto_node_identifier| registry::NODE_METADATA.lock().unwrap().get(proto_node_identifier)?.fields.get(index).cloned())
|
||||
{
|
||||
if let Some(field) = context.network_interface.field_metadata(&node_id, index, context.selection_network_path) {
|
||||
if let Some(unit) = field.unit {
|
||||
number_input = number_input.unit(unit);
|
||||
}
|
||||
@@ -954,57 +352,6 @@ fn static_input_inspector() -> InputInspector {
|
||||
"type_choice".to_string(),
|
||||
Box::new(|node_id, index, context| Ok(vec![node_inspector::type_choice_widget(ParameterWidgetsInfo::at_index(node_id, index, true, context))])),
|
||||
);
|
||||
map.insert(
|
||||
"vec2".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let x = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "x", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get x for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let y = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "y", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get y for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let unit = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "unit", context.selection_network_path)
|
||||
.and_then(|value| value.as_str())
|
||||
.unwrap_or_else(|| {
|
||||
log::error!("Could not get unit for vec2 input");
|
||||
""
|
||||
})
|
||||
.to_string();
|
||||
let min = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "min", context.selection_network_path)
|
||||
.and_then(|value| value.as_f64());
|
||||
let is_integer = context
|
||||
.network_interface
|
||||
.input_data(&node_id, index, "is_integer", context.selection_network_path)
|
||||
.and_then(|value| value.as_bool())
|
||||
.unwrap_or_default();
|
||||
|
||||
Ok(vec![node_inspector::vec2_widget(
|
||||
ParameterWidgetsInfo::at_index(node_id, index, true, context),
|
||||
&x,
|
||||
&y,
|
||||
&unit,
|
||||
min,
|
||||
is_integer,
|
||||
false,
|
||||
)])
|
||||
}),
|
||||
);
|
||||
map.insert(
|
||||
"noise_inspector_scale".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
@@ -1177,6 +524,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent >= 100.),
|
||||
)])
|
||||
@@ -1193,6 +541,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
"",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
mandelbrot_to_julia.is_some_and(|percent| percent <= 0.),
|
||||
)])
|
||||
@@ -1299,6 +648,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"Y",
|
||||
" px",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1314,6 +664,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"H",
|
||||
"x",
|
||||
None,
|
||||
None,
|
||||
false,
|
||||
false,
|
||||
)])
|
||||
@@ -1434,7 +785,7 @@ fn static_input_inspector() -> InputInspector {
|
||||
"vec2_uv".to_string(),
|
||||
Box::new(|node_id, index, context| {
|
||||
let parameter_widgets_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, false, false)])
|
||||
Ok(vec![node_inspector::vec2_widget(parameter_widgets_info, "U", "V", "", None, None, false, false)])
|
||||
}),
|
||||
);
|
||||
map
|
||||
@@ -1682,20 +1033,33 @@ mod test {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::document::NodeId;
|
||||
|
||||
// A `#[graph]` node with an inner node that has no definition is left out of the catalog with only a logged error
|
||||
#[test]
|
||||
fn every_registered_graph_has_a_definition() {
|
||||
// Released before resolving, since building the catalog locks the registry too
|
||||
let identifiers: Vec<&str> = graphene_std::registry::GRAPH_METADATA.lock().unwrap().iter().map(|graph| graph.identifier).collect();
|
||||
assert!(!identifiers.is_empty(), "the `#[graph]` nodes in `graphene_std::subgraphs` should be registered");
|
||||
|
||||
for identifier in identifiers {
|
||||
assert!(resolve_network_node_type(identifier).is_some(), "the '{identifier}' graph should have a definition");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rasterize_defaults_to_a_1000_px_square_at_full_resolution() {
|
||||
use glam::DAffine2;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
|
||||
let definition = super::resolve_proto_node_definition(&rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||
let transform = definition.node_template.input(rasterize::TransformInput).and_then(|input| input.as_value());
|
||||
let resolution = definition.node_template.input(rasterize::ResolutionInput).and_then(|input| input.as_value());
|
||||
let footprint = definition.node_template.input(rasterize::FootprintInput).and_then(|input| input.as_value());
|
||||
|
||||
// The square from (0, 0) to (1000, 1000)
|
||||
let expected_transform = DAffine2::from_scale_angle_translation(DVec2::splat(1000.), 0., DVec2::splat(500.));
|
||||
assert_eq!(transform, Some(&TaggedValue::DAffine2(expected_transform)));
|
||||
assert_eq!(resolution, Some(&TaggedValue::DVec2(DVec2::splat(1000.))));
|
||||
let expected = Footprint {
|
||||
transform: DAffine2::from_scale(DVec2::splat(1000.)),
|
||||
resolution: UVec2::splat(1000),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(footprint, Some(&TaggedValue::Footprint(expected)));
|
||||
}
|
||||
|
||||
// The executor input the compiler fills in has no type yet, which mustn't rule out every implementation
|
||||
@@ -1821,21 +1185,36 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn every_definition_default_value_satisfies_its_constraint() {
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
let name = &definition.node_template.display_name;
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(&definition.node_template, name);
|
||||
// Checks a node's inputs against what its implementations accept, then each node inside it, whose values a subgraph's author writes too
|
||||
fn check(node_template: &NodeTemplate, name: &str, violations: &mut Vec<String>) {
|
||||
let constraints = InputTypeConstraint::constraints_for_all_inputs(node_template, name);
|
||||
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&definition.node_template.inputs).enumerate() {
|
||||
for (index, (constraint, input)) in constraints.iter().zip(&node_template.inputs).enumerate() {
|
||||
if let Some(value) = input.as_value()
|
||||
&& !constraint.accepts_default_value(&value.ty())
|
||||
{
|
||||
violations.push(format!("{name} input {index}: {} does not satisfy {constraint:?}", value.ty()));
|
||||
}
|
||||
|
||||
let takes_nothing = matches!(constraint, InputTypeConstraint::Limited(types) if !types.is_empty() && types.iter().all(|ty| ty == "()"));
|
||||
if takes_nothing && matches!(input, NodeInput::Node { .. } | NodeInput::Import { .. }) {
|
||||
violations.push(format!("{name} input {index}: a wire feeds it, but it takes nothing"));
|
||||
}
|
||||
}
|
||||
|
||||
if let NodeTemplateImplementation::Network(network) = &node_template.implementation {
|
||||
for (node_id, inner) in &network.nodes {
|
||||
check(inner, &format!("{name}, node {node_id}"), violations);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Default values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
let mut violations = Vec::new();
|
||||
for definition in super::DOCUMENT_NODE_TYPES.values() {
|
||||
check(&definition.node_template, &definition.node_template.display_name, &mut violations);
|
||||
}
|
||||
|
||||
assert!(violations.is_empty(), "Values rejected by their input constraints:\n{}", violations.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1852,7 +1231,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(glam::DVec2)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(String)));
|
||||
@@ -1866,7 +1245,7 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn single_protonode2() {
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let node_type = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let constraint = InputTypeConstraint::constraints_for_all_inputs(&node_type.node_template, "name");
|
||||
all_satisifed(&constraint[0], [concrete!(f32), concrete!(f64), concrete!(String)]);
|
||||
assert!(!constraint[0].satisfies(&concrete!(glam::DVec2)));
|
||||
@@ -1875,8 +1254,8 @@ mod test_type_constraints {
|
||||
|
||||
#[test]
|
||||
fn network() {
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_dvec_2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f_32_f_64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_definition = resolve_proto_node_type(test_node_accept_f32_f64_dvec2::IDENTIFIER).expect("test node to exist");
|
||||
let min_definition = resolve_proto_node_type(test_node_accept_f32_f64_string::IDENTIFIER).expect("test node to exist");
|
||||
let atan_node = atan_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let min_node = min_definition.node_template_input_override([Some(NodeInput::import(generic!(X), 0))]);
|
||||
let inner_network = NodeNetworkTemplate {
|
||||
|
||||
+421
-30
@@ -1,11 +1,17 @@
|
||||
use super::DocumentNodeDefinition;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputMetadata, NodeTemplate, NodeTemplateImplementation, WidgetOverride};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
InputMetadata, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, WidgetOverride,
|
||||
};
|
||||
use glam::IVec2;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::registry::*;
|
||||
use graphene_std::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
/// Generates every definition, from the node macro's metadata for proto nodes and the graph macro's for built-in subgraphs.
|
||||
pub(super) fn derive_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let mut definitions_map = HashMap::new();
|
||||
|
||||
// Add the protonodes from the macro.
|
||||
@@ -75,16 +81,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
inputs,
|
||||
call_argument: input_type.clone(),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(id.clone()),
|
||||
// TODO: Store information for input overrides in the node macro
|
||||
input_metadata: fields
|
||||
.iter()
|
||||
.map(|f| match f.widget_override {
|
||||
RegistryWidgetOverride::None => (f.name, f.description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::String(str.to_string())),
|
||||
RegistryWidgetOverride::Custom(str) => InputMetadata::with_name_description_override(f.name, f.description, WidgetOverride::Custom(str.to_string())),
|
||||
})
|
||||
.collect(),
|
||||
input_metadata: input_metadata(fields),
|
||||
output_names,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -96,25 +93,242 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
);
|
||||
}
|
||||
|
||||
// Add the hand-written network nodes to the map and add the metadata for their internal protonodes
|
||||
for mut network_node in custom {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, &definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
definitions_map.insert(DefinitionIdentifier::Network(network_node.identifier.to_string()), network_node);
|
||||
}
|
||||
let graphs = GRAPH_METADATA.lock().unwrap().clone();
|
||||
add_graph_definitions(graphs, &mut definitions_map);
|
||||
|
||||
definitions_map
|
||||
}
|
||||
|
||||
/// Recursively fills each nested proto node's editor metadata from its definition, preserving only the authored position.
|
||||
/// The name, description, and any widget override of each parameter, for a proto node's fields or a graph's imports.
|
||||
/// The rest of a parameter's widget settings are read from its field when the Inspector draws it.
|
||||
fn input_metadata(fields: &[FieldMetadata]) -> Vec<InputMetadata> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|field| {
|
||||
let (name, description) = (field.name, field.description);
|
||||
match field.widget_override {
|
||||
RegistryWidgetOverride::None => (name, description).into(),
|
||||
RegistryWidgetOverride::Hidden => InputMetadata::with_name_description_override(name, description, WidgetOverride::Hidden),
|
||||
RegistryWidgetOverride::String(text) => InputMetadata::with_name_description_override(name, description, WidgetOverride::String(text.to_string())),
|
||||
RegistryWidgetOverride::Custom(key) => InputMetadata::with_name_description_override(name, description, WidgetOverride::Custom(key.to_string())),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Why a `#[graph]` node has no definition yet, or can't have one.
|
||||
enum GraphDefinitionError {
|
||||
/// A node inside it has no definition, which may be another graph not yet added.
|
||||
MissingNode(String),
|
||||
/// The graph's wiring is invalid, so it's left out of the catalog.
|
||||
Invalid(String),
|
||||
}
|
||||
|
||||
/// Adds the nodes defined as subgraphs by `#[graph]`, each once the definitions of the nodes inside it exist.
|
||||
fn add_graph_definitions(graphs: Vec<GraphMetadata>, definitions_map: &mut HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
// Every graph sharing an identifier is left out, so the catalog doesn't depend on registration order
|
||||
let mut identifier_counts = HashMap::new();
|
||||
for graph in &graphs {
|
||||
*identifier_counts.entry(graph.identifier).or_insert(0) += 1;
|
||||
}
|
||||
let mut rejected = HashSet::new();
|
||||
let mut pending_graphs: Vec<(GraphMetadata, String)> = graphs
|
||||
.into_iter()
|
||||
.filter(|graph| {
|
||||
let taken = identifier_counts[graph.identifier] > 1;
|
||||
if taken {
|
||||
log::error!("The '{}' graph has no definition, since another graph has the same identifier", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
}
|
||||
!taken
|
||||
})
|
||||
.map(|graph| (graph, String::new()))
|
||||
.collect();
|
||||
|
||||
loop {
|
||||
let pending_count = pending_graphs.len();
|
||||
|
||||
let mut ready = Vec::new();
|
||||
pending_graphs.retain_mut(|(graph, missing)| {
|
||||
// A graph built on a left-out graph is left out too, rather than embedding another definition of that name
|
||||
let rejected_inner_graph = graph.nodes.iter().find_map(|node| match node.implementation {
|
||||
GraphNodeImplementation::Graph(identifier) if rejected.contains(identifier) => Some(identifier),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(inner_graph) = rejected_inner_graph {
|
||||
log::error!("The '{}' graph has no definition, since the '{inner_graph}' graph inside it has none", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
return false;
|
||||
}
|
||||
|
||||
match graph_definition(graph, definitions_map) {
|
||||
Ok(definition) => {
|
||||
ready.push(definition);
|
||||
false
|
||||
}
|
||||
Err(GraphDefinitionError::MissingNode(missing_node)) => {
|
||||
*missing = missing_node;
|
||||
true
|
||||
}
|
||||
Err(GraphDefinitionError::Invalid(reason)) => {
|
||||
log::error!("The '{}' graph has no definition, since {reason}", graph.identifier);
|
||||
rejected.insert(graph.identifier);
|
||||
false
|
||||
}
|
||||
}
|
||||
});
|
||||
for definition in ready {
|
||||
let definition = prepare_network_definition(definition, definitions_map);
|
||||
definitions_map.insert(DefinitionIdentifier::Network(definition.identifier.to_string()), definition);
|
||||
}
|
||||
|
||||
if pending_graphs.is_empty() || pending_graphs.len() == pending_count {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for (graph, missing_node) in pending_graphs {
|
||||
log::error!("The '{}' graph has no definition, since the '{missing_node}' node inside it has none", graph.identifier);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills a network definition's nested proto node metadata and points its network at the definition.
|
||||
fn prepare_network_definition(mut network_node: DocumentNodeDefinition, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> DocumentNodeDefinition {
|
||||
fill_proto_node_metadata(&mut network_node.node_template, definitions_map);
|
||||
|
||||
// Set the reference to the node identifier
|
||||
if let NodeTemplateImplementation::Network(network_template) = &mut network_node.node_template.implementation {
|
||||
network_template.reference = Some(network_node.identifier.to_string());
|
||||
// If it is not a merge node, then set the display name to the identifier/reference
|
||||
if network_node.identifier != "Merge" {
|
||||
network_node.node_template.display_name = network_node.identifier.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
network_node
|
||||
}
|
||||
|
||||
/// Builds the catalog definition of a node defined as a subgraph by `#[graph]`.
|
||||
fn graph_definition(graph: &GraphMetadata, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) -> Result<DocumentNodeDefinition, GraphDefinitionError> {
|
||||
let mut nodes = HashMap::new();
|
||||
for (index, node) in graph.nodes.iter().enumerate() {
|
||||
// Start from the node's own definition, so each input the graph leaves out matches a new instance of it
|
||||
let (identifier, name) = match &node.implementation {
|
||||
GraphNodeImplementation::ProtoNode(identifier) => (DefinitionIdentifier::ProtoNode(identifier.clone()), identifier.as_str().to_string()),
|
||||
GraphNodeImplementation::Graph(identifier) => (DefinitionIdentifier::Network(identifier.to_string()), identifier.to_string()),
|
||||
};
|
||||
let Some(definition) = definitions_map.get(&identifier) else {
|
||||
return Err(GraphDefinitionError::MissingNode(name));
|
||||
};
|
||||
let mut template = definition.default_node_template();
|
||||
|
||||
if let Some(call_argument) = &node.call_argument {
|
||||
template.call_argument = call_argument.clone();
|
||||
}
|
||||
template.visible = !node.hidden;
|
||||
template.locked = node.locked;
|
||||
template.pinned = node.pinned;
|
||||
if let Some(display_name) = node.display_name {
|
||||
template.display_name = display_name.to_string();
|
||||
}
|
||||
|
||||
let position = node.position.map_or(IVec2::ZERO, |(x, y)| IVec2::new(x, y));
|
||||
template.node_type_metadata = if node.layer {
|
||||
NodeTypePersistentMetadata::layer(position)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(position)
|
||||
};
|
||||
|
||||
for (input_index, source) in &node.inputs {
|
||||
let Some(input) = template.inputs.get_mut(*input_index) else {
|
||||
return Err(GraphDefinitionError::Invalid(format!("its node {index}, '{name}', has no input {input_index} for it to set")));
|
||||
};
|
||||
|
||||
// An input the compiler fills in can't be set, which the macro already prevents for the graphs it builds
|
||||
if matches!(input, NodeInput::Scope(_) | NodeInput::Reflection(_)) {
|
||||
return Err(GraphDefinitionError::Invalid(format!(
|
||||
"it sets input {input_index} of its node {index}, '{name}', which the compiler fills in"
|
||||
)));
|
||||
}
|
||||
|
||||
*input = graph_input(source, input);
|
||||
}
|
||||
|
||||
nodes.insert(NodeId(index as u64), template);
|
||||
}
|
||||
|
||||
// Each import starts from its `#[default(...)]` or else its type, as a proto node's parameter does
|
||||
let inputs = preprocessor::node_inputs(&graph.imports, &NodeIOTypes::empty());
|
||||
|
||||
let exports = graph.exports.iter().map(|export| graph_input(&export.source, &NodeInput::value(TaggedValue::None, false))).collect();
|
||||
|
||||
Ok(DocumentNodeDefinition {
|
||||
identifier: graph.identifier,
|
||||
version: graph.version,
|
||||
category: graph.category,
|
||||
icon: graph.icon,
|
||||
description: Cow::Borrowed(graph.description),
|
||||
inspector: None,
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate { exports, nodes, ..Default::default() }),
|
||||
inputs,
|
||||
input_metadata: input_metadata(&graph.imports),
|
||||
output_names: graph.exports.iter().map(|export| export.name.to_string()).collect(),
|
||||
output_descriptions: graph.exports.iter().map(|export| export.description.to_string()).collect(),
|
||||
node_type_metadata: if graph.layer {
|
||||
NodeTypePersistentMetadata::layer(IVec2::ZERO)
|
||||
} else {
|
||||
NodeTypePersistentMetadata::node(IVec2::ZERO)
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// The input a graph definition writes, where `default` is what the node's own definition starts that input with.
|
||||
fn graph_input(source: &GraphInputSource, default: &NodeInput) -> NodeInput {
|
||||
match source {
|
||||
GraphInputSource::Node { node, output } => NodeInput::node(NodeId(*node as u64), *output),
|
||||
GraphInputSource::Import { index, ty } => NodeInput::import(ty.clone(), *index),
|
||||
GraphInputSource::Value { value, exposed } => {
|
||||
let ty = match default {
|
||||
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
|
||||
NodeInput::Import { import_type, .. } => import_type.clone(),
|
||||
_ => generic!(T),
|
||||
};
|
||||
NodeInput::value(graph_value(value, &ty), exposed.unwrap_or(default.is_exposed()))
|
||||
}
|
||||
GraphInputSource::Scope(key) => NodeInput::scope(*key),
|
||||
GraphInputSource::NodePath => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
GraphInputSource::SourceId => NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::SourceId),
|
||||
}
|
||||
}
|
||||
|
||||
/// The type of the elements a wire of this type carries, past any `Item`, `List`, or lazy wrapping.
|
||||
fn element_type(ty: &Type) -> &Type {
|
||||
let mut element = ty;
|
||||
while let Type::Item(inner) | Type::List(inner) | Type::Fn(_, inner) = element {
|
||||
element = inner;
|
||||
}
|
||||
element
|
||||
}
|
||||
|
||||
/// Converts a value written in a graph definition to the type of the input it feeds.
|
||||
fn graph_value(value: &GraphValue, ty: &Type) -> TaggedValue {
|
||||
// An integer literal feeds an integer input as an integer, and any other as a number
|
||||
let is_integer = *element_type(ty) == concrete!(i64);
|
||||
|
||||
match value {
|
||||
GraphValue::Integer(integer) if is_integer => TaggedValue::Integer(*integer),
|
||||
GraphValue::Integer(integer) => TaggedValue::Number(*integer as f64),
|
||||
GraphValue::Number(number) => TaggedValue::Number(*number),
|
||||
GraphValue::Bool(boolean) => TaggedValue::Bool(*boolean),
|
||||
GraphValue::String(string) => TaggedValue::String(string.clone()),
|
||||
GraphValue::Vec2(vec2) => TaggedValue::DVec2(*vec2),
|
||||
GraphValue::Color(color) => TaggedValue::Color(*color),
|
||||
}
|
||||
}
|
||||
|
||||
/// Recursively gives each nested proto node its definition's input and output metadata, and its display name if the network's author gave none.
|
||||
fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>) {
|
||||
match &mut node_template.implementation {
|
||||
NodeTemplateImplementation::Network(network_template) => {
|
||||
@@ -128,13 +342,190 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
|
||||
return;
|
||||
};
|
||||
|
||||
// A display name, lock, or pin the network's author gave the node is kept
|
||||
let definition_template = &definition.node_template;
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
if node_template.display_name.is_empty() {
|
||||
node_template.display_name = definition_template.display_name.clone();
|
||||
}
|
||||
node_template.input_metadata = definition_template.input_metadata.clone();
|
||||
node_template.output_names = definition_template.output_names.clone();
|
||||
node_template.locked = definition_template.locked;
|
||||
node_template.pinned = definition_template.pinned;
|
||||
node_template.locked |= definition_template.locked;
|
||||
node_template.pinned |= definition_template.pinned;
|
||||
}
|
||||
NodeTemplateImplementation::Definition(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_document_node_type;
|
||||
|
||||
fn number_import() -> FieldMetadata {
|
||||
FieldMetadata {
|
||||
name: "Value",
|
||||
description: "",
|
||||
internal: false,
|
||||
exposed: true,
|
||||
widget_override: RegistryWidgetOverride::None,
|
||||
value_source: RegistryValueSource::None,
|
||||
default_colors: None,
|
||||
default_type: Some(Type::Item(Box::new(concrete!(f64)))),
|
||||
number_soft_min: None,
|
||||
number_soft_max: None,
|
||||
number_hard_min: None,
|
||||
number_hard_max: None,
|
||||
number_mode_range: false,
|
||||
number_display_decimal_places: None,
|
||||
number_step: None,
|
||||
unit: None,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
constant: false,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// A graph exporting one node, which is fed by the given inputs.
|
||||
fn one_node_graph(identifier: &'static str, implementation: GraphNodeImplementation, inputs: Vec<(usize, GraphInputSource)>) -> GraphMetadata {
|
||||
GraphMetadata {
|
||||
identifier,
|
||||
category: "Test",
|
||||
icon: None,
|
||||
description: "",
|
||||
version: 1,
|
||||
layer: false,
|
||||
imports: vec![number_import()],
|
||||
exports: vec![GraphExportMetadata {
|
||||
name: "Out",
|
||||
description: "",
|
||||
source: GraphInputSource::Node { node: 0, output: 0 },
|
||||
}],
|
||||
nodes: vec![GraphNodeMetadata {
|
||||
implementation,
|
||||
inputs,
|
||||
position: None,
|
||||
layer: false,
|
||||
display_name: None,
|
||||
hidden: false,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
call_argument: None,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
fn from_import() -> Vec<(usize, GraphInputSource)> {
|
||||
let ty = Type::Item(Box::new(concrete!(f64)));
|
||||
vec![(0, GraphInputSource::Import { index: 0, ty })]
|
||||
}
|
||||
|
||||
/// The definitions a test graph builds on: only the As Number proto node.
|
||||
fn proto_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let identifier = DefinitionIdentifier::ProtoNode(math_nodes::as_number::IDENTIFIER);
|
||||
let definition = resolve_document_node_type(&identifier).expect("As Number should have a definition").clone();
|
||||
HashMap::from([(identifier, definition)])
|
||||
}
|
||||
|
||||
fn has_graph(definitions_map: &HashMap<DefinitionIdentifier, DocumentNodeDefinition>, identifier: &str) -> bool {
|
||||
definitions_map.contains_key(&DefinitionIdentifier::Network(identifier.to_string()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_resolves_when_registered_before_a_graph_inside_it() {
|
||||
let outer = one_node_graph("Test Outer", GraphNodeImplementation::Graph("Test Inner"), from_import());
|
||||
let inner = one_node_graph("Test Inner", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![outer, inner], &mut definitions_map);
|
||||
|
||||
assert!(has_graph(&definitions_map, "Test Inner"));
|
||||
assert!(has_graph(&definitions_map, "Test Outer"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_setting_an_input_its_node_lacks_is_left_out() {
|
||||
let mut inputs = from_import();
|
||||
inputs.push((
|
||||
100,
|
||||
GraphInputSource::Value {
|
||||
value: GraphValue::Number(1.),
|
||||
exposed: None,
|
||||
},
|
||||
));
|
||||
let graph = one_node_graph("Test Missing Input", math_nodes::as_number::IDENTIFIER.into(), inputs);
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Missing Input"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graphs_sharing_an_identifier_and_graphs_built_on_them_are_left_out() {
|
||||
let first = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let second = one_node_graph("Test Twin", math_nodes::as_number::IDENTIFIER.into(), from_import());
|
||||
let dependent = one_node_graph("Test Dependent", GraphNodeImplementation::Graph("Test Twin"), from_import());
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![first, second, dependent], &mut definitions_map);
|
||||
|
||||
assert!(!has_graph(&definitions_map, "Test Twin"));
|
||||
assert!(!has_graph(&definitions_map, "Test Dependent"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_integer_value_takes_the_type_of_the_input_it_feeds() {
|
||||
let integer = Type::Item(Box::new(concrete!(i64)));
|
||||
let number = Type::Item(Box::new(concrete!(f64)));
|
||||
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &integer), TaggedValue::Integer(3)));
|
||||
assert!(matches!(graph_value(&GraphValue::Integer(3), &number), TaggedValue::Number(value) if value == 3.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn imports_start_from_their_default_or_type() {
|
||||
let unit_primary = FieldMetadata {
|
||||
default_type: Some(concrete!(())),
|
||||
..number_import()
|
||||
};
|
||||
let with_default = FieldMetadata {
|
||||
value_source: RegistryValueSource::Default("2.5"),
|
||||
..number_import()
|
||||
};
|
||||
let graph = GraphMetadata {
|
||||
imports: vec![unit_primary, with_default],
|
||||
..one_node_graph("Test Defaults", math_nodes::as_number::IDENTIFIER.into(), from_import())
|
||||
};
|
||||
|
||||
let mut definitions_map = proto_definitions();
|
||||
add_graph_definitions(vec![graph], &mut definitions_map);
|
||||
let inputs = &definitions_map[&DefinitionIdentifier::Network("Test Defaults".to_string())].node_template.inputs;
|
||||
|
||||
// A `()` primary has nothing to connect, and an exposed parameter's default is parsed by its type
|
||||
assert!(!inputs[0].is_exposed());
|
||||
assert!(matches!(inputs[1].as_value(), Some(TaggedValue::Number(value)) if *value == 2.5));
|
||||
assert!(inputs[1].is_exposed());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_graph_nodes_widget_settings_come_from_its_import() {
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let artboard = resolve_document_node_type(&DefinitionIdentifier::Network("Artboard".into())).expect("Artboard should exist");
|
||||
document.network_interface.insert_node(node_id, artboard.default_node_template(), &[]);
|
||||
|
||||
let location = graphene_std::subgraphs::artboard::LocationInput::INDEX;
|
||||
let field = document
|
||||
.network_interface
|
||||
.field_metadata(&node_id, location, &[])
|
||||
.expect("the location input should have its import's settings");
|
||||
assert_eq!(field.labels, Some(("X", "Y")));
|
||||
assert!(field.integer);
|
||||
assert!(!document.network_interface.is_internal_input(&node_id, location, &[]));
|
||||
}
|
||||
}
|
||||
@@ -170,8 +170,6 @@ pub enum NodeGraphMessage {
|
||||
PointerOutsideViewport {
|
||||
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.
|
||||
WireHoverTick,
|
||||
/// Sends where everything gliding into place is drawn, along with the wires that follow it.
|
||||
@@ -439,7 +437,6 @@ impl NodeGraphMessage {
|
||||
| Self::PointerMove { .. }
|
||||
| Self::PointerUp
|
||||
| Self::PointerOutsideViewport { .. }
|
||||
| Self::MiddleClick
|
||||
| Self::WireHoverTick
|
||||
| Self::SendGlide
|
||||
| Self::GlideTick
|
||||
|
||||
@@ -1752,20 +1752,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
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 => {
|
||||
self.expand_wire_hovered_node_after_delay(ipp.time, ipp.mouse.position, network_interface, selection_network_path, responses);
|
||||
}
|
||||
|
||||
@@ -31,17 +31,17 @@ use graphene_std::raster_types::{CPU, GPU, Image, Raster};
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType, Transform};
|
||||
use graphene_std::vector::misc::BooleanOperation;
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
@@ -240,7 +240,7 @@ pub fn start_widgets(parameter_widgets_info: &ParameterWidgetsInfo) -> Vec<Widge
|
||||
}
|
||||
|
||||
/// The presentation of a parameter's widget, sourced from the node's field metadata: numeric bounds, widget modes, and unit of measure.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ParameterOptions {
|
||||
pub soft_min: Option<f64>,
|
||||
pub soft_max: Option<f64>,
|
||||
@@ -252,10 +252,34 @@ pub(crate) struct ParameterOptions {
|
||||
pub unit: Option<&'static str>,
|
||||
pub display_decimal_places: Option<u32>,
|
||||
pub step: Option<f64>,
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
pub integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
|
||||
fn from(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
impl Default for ParameterOptions {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
soft_min: None,
|
||||
soft_max: None,
|
||||
hard_min: None,
|
||||
hard_max: None,
|
||||
slider: false,
|
||||
multiline: false,
|
||||
progression: false,
|
||||
unit: None,
|
||||
display_decimal_places: None,
|
||||
step: None,
|
||||
labels: None,
|
||||
integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ParameterOptions {
|
||||
/// The options a proto node's field or a graph's import gives its widget.
|
||||
pub(crate) fn from_field(field: &graphene_std::registry::FieldMetadata) -> Self {
|
||||
Self {
|
||||
soft_min: field.number_soft_min,
|
||||
soft_max: field.number_soft_max,
|
||||
@@ -267,6 +291,9 @@ impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
|
||||
unit: field.unit,
|
||||
display_decimal_places: field.number_display_decimal_places,
|
||||
step: field.number_step,
|
||||
labels: field.labels,
|
||||
integer: field.integer,
|
||||
blank_assist: field.blank_assist,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -322,9 +349,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
unit,
|
||||
display_decimal_places,
|
||||
step,
|
||||
labels,
|
||||
integer,
|
||||
blank_assist,
|
||||
} = options;
|
||||
|
||||
let mut number_input = NumberInput::default();
|
||||
let mut number_input = NumberInput::default().is_integer(integer);
|
||||
if slider {
|
||||
number_input = number_input.mode_range();
|
||||
}
|
||||
@@ -367,7 +397,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
}
|
||||
};
|
||||
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, true, context);
|
||||
let default_info = ParameterWidgetsInfo::at_index(node_id, index, blank_assist, context);
|
||||
|
||||
// A type with no widget can only be supplied through the graph, labeled with a placeholder row
|
||||
let unsupported_widgets = |default_info: ParameterWidgetsInfo, type_label: String| {
|
||||
@@ -411,7 +441,10 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
true => text_area_widget(default_info).into(),
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DVec2>(x) => {
|
||||
let (x_label, y_label) = labels.unwrap_or(("X", "Y"));
|
||||
vec2_widget(default_info, x_label, y_label, unit.unwrap_or(""), hard_min, hard_max, integer, false)
|
||||
}
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
@@ -421,6 +454,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// ============
|
||||
Some(x) if id_is::<Font>(x) => font_widget(default_info),
|
||||
Some(x) if id_is::<TransferCurve>(x) => transfer_curve_widget(default_info),
|
||||
Some(x) if id_is::<Footprint>(x) => footprint_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Box<VectorModification>>(x) => vector_modification_widget(default_info).into(),
|
||||
Some(x) if id_is::<Image<Color>>(x) => image_data_widget(default_info).into(),
|
||||
Some(x) if id_is::<Resource>(x) => resource_widget(default_info, Vec::new()).into(),
|
||||
@@ -433,7 +467,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
// AUTO-GENERATED ENUM TYPES
|
||||
// =========================
|
||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||
@@ -481,7 +514,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BlendIfChannel>(x) => enum_choice::<BlendIfChannel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -676,6 +708,142 @@ pub fn image_data_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Vec<Wi
|
||||
widgets
|
||||
}
|
||||
|
||||
pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
|
||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut scale_widgets = vec![TextLabel::new("").widget_instance()];
|
||||
add_blank_assist(&mut scale_widgets);
|
||||
scale_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let mut resolution_widgets = vec![TextLabel::new("").widget_instance()];
|
||||
add_blank_assist(&mut resolution_widgets);
|
||||
resolution_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
|
||||
let Some(document_node) = document_node else { return LayoutGroup::default() };
|
||||
let Some(input) = document_node.inputs.get(index) else {
|
||||
log::warn!("A widget failed to be built because its node's input index is invalid.");
|
||||
return Vec::new().into();
|
||||
};
|
||||
|
||||
if let Some(&TaggedValue::Footprint(footprint)) = input.as_non_exposed_value() {
|
||||
let top_left = footprint.transform.transform_point2(DVec2::ZERO);
|
||||
let bounds = footprint.scale();
|
||||
let oversample = footprint.resolution.as_dvec2() / bounds;
|
||||
|
||||
location_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(top_left.x))
|
||||
.label("X")
|
||||
.unit(" px")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let (offset, scale) = {
|
||||
let diff = DVec2::new(top_left.x - x.value.unwrap_or_default(), 0.);
|
||||
(top_left - diff, bounds)
|
||||
};
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(top_left.y))
|
||||
.label("Y")
|
||||
.unit(" px")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let (offset, scale) = {
|
||||
let diff = DVec2::new(0., top_left.y - x.value.unwrap_or_default());
|
||||
(top_left - diff, bounds)
|
||||
};
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
scale_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(bounds.x))
|
||||
.label("W")
|
||||
.unit(" px")
|
||||
.on_update(update_value_at_index(
|
||||
move |x: &NumberInput| {
|
||||
let (offset, scale) = (top_left, DVec2::new(x.value.unwrap_or_default(), bounds.y));
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
},
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(bounds.y))
|
||||
.label("H")
|
||||
.unit(" px")
|
||||
.on_update(update_value_at_index(
|
||||
move |x: &NumberInput| {
|
||||
let (offset, scale) = (top_left, DVec2::new(bounds.x, x.value.unwrap_or_default()));
|
||||
|
||||
let footprint = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(scale, 0., offset),
|
||||
resolution: (oversample * scale).as_uvec2(),
|
||||
..footprint
|
||||
};
|
||||
|
||||
TaggedValue::Footprint(footprint)
|
||||
},
|
||||
node_id,
|
||||
index,
|
||||
))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
resolution_widgets.push(
|
||||
NumberInput::new(Some((footprint.resolution.as_dvec2() / bounds).x * 100.))
|
||||
.label("Resolution")
|
||||
.mode_range()
|
||||
.min(0.)
|
||||
.range_min(Some(1.))
|
||||
.range_max(Some(100.))
|
||||
.unit("%")
|
||||
.on_update(parameter_widgets_info.update_value(move |x: &NumberInput| {
|
||||
let resolution = (bounds * x.value.unwrap_or(100.) / 100.).as_uvec2().max((1, 1).into()).min((4000, 4000).into());
|
||||
|
||||
let footprint = Footprint { resolution, ..footprint };
|
||||
TaggedValue::Footprint(footprint)
|
||||
}))
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
let widgets = [LayoutGroup::row(location_widgets), LayoutGroup::row(scale_widgets), LayoutGroup::row(resolution_widgets)];
|
||||
let (last, rest) = widgets.split_last().expect("Footprint widget should return multiple rows");
|
||||
*extra_widgets = rest.to_vec();
|
||||
last.clone()
|
||||
}
|
||||
|
||||
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
@@ -786,7 +954,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit:
|
||||
}
|
||||
}
|
||||
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &str, unit: &str, min: Option<f64>, max: Option<f64>, is_integer: bool, disabled: bool) -> LayoutGroup {
|
||||
let mut widgets = start_widgets(¶meter_widgets_info);
|
||||
|
||||
let Some(input) = parameter_widgets_info.input() else {
|
||||
@@ -801,7 +969,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), dvec2.y))))
|
||||
@@ -812,7 +980,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(dvec2.x, input.value.unwrap()))))
|
||||
@@ -827,7 +995,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(x)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(input.value.unwrap(), value))))
|
||||
@@ -838,7 +1006,7 @@ pub fn vec2_widget(parameter_widgets_info: ParameterWidgetsInfo, x: &str, y: &st
|
||||
.label(y)
|
||||
.unit(unit)
|
||||
.min(min.unwrap_or(-((1_u64 << f64::MANTISSA_DIGITS) as f64)))
|
||||
.max((1_u64 << f64::MANTISSA_DIGITS) as f64)
|
||||
.max(max.unwrap_or((1_u64 << f64::MANTISSA_DIGITS) as f64))
|
||||
.is_integer(is_integer)
|
||||
.disabled(disabled)
|
||||
.on_update(parameter_widgets_info.update_value(move |input: &NumberInput| TaggedValue::DVec2(DVec2::new(value, input.value.unwrap()))))
|
||||
@@ -1218,7 +1386,7 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
return LayoutGroup::row(vec![]);
|
||||
};
|
||||
if let Some(&TaggedValue::BlendMode(blend_mode)) = input.as_non_exposed_value() {
|
||||
let entries = BlendMode::list()
|
||||
let entries = BlendMode::list_svg_subset()
|
||||
.iter()
|
||||
.map(|category| {
|
||||
category
|
||||
@@ -1235,7 +1403,9 @@ pub fn blend_mode_widget(parameter_widgets_info: ParameterWidgetsInfo) -> Layout
|
||||
|
||||
widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(entries).selected_index(blend_mode.index_in_list().map(|index| index as u32)).widget_instance(),
|
||||
DropdownInput::new(entries)
|
||||
.selected_index(blend_mode.index_in_list_svg_subset().map(|index| index as u32))
|
||||
.widget_instance(),
|
||||
]);
|
||||
}
|
||||
LayoutGroup::row(widgets).with_tooltip_description("Formula used for blending.")
|
||||
@@ -1796,8 +1966,6 @@ pub(crate) fn levels_inspector(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
enum MarkerScale {
|
||||
/// A 0..100 percentage, placed linearly.
|
||||
Percent,
|
||||
/// A 0..100 percentage of a channel's 256 levels, placed linearly and shown to a tenth, which tells neighboring levels apart.
|
||||
LevelPercent,
|
||||
/// A gamma of 0.01..9.99 running from 9.99 at the left to 0.01 at the right, logarithmic on each side of the 1 at its center.
|
||||
Gamma,
|
||||
/// A hue of 0..360 degrees, placed linearly on a track that wraps around.
|
||||
@@ -1807,7 +1975,7 @@ enum MarkerScale {
|
||||
impl MarkerScale {
|
||||
fn position(self, value: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent | Self::LevelPercent => value / 100.,
|
||||
Self::Percent => value / 100.,
|
||||
Self::Gamma if value >= 1. => 0.5 - 0.5 * value.log10() / 9.99_f64.log10(),
|
||||
Self::Gamma => 0.5 + 0.5 * value.log10() / 0.01_f64.log10(),
|
||||
Self::Degrees => {
|
||||
@@ -1821,7 +1989,7 @@ impl MarkerScale {
|
||||
|
||||
fn value(self, position: f64) -> f64 {
|
||||
match self {
|
||||
Self::Percent | Self::LevelPercent => (position * 100.).clamp(0., 100.),
|
||||
Self::Percent => (position * 100.).clamp(0., 100.),
|
||||
Self::Gamma if position <= 0.5 => 9.99_f64.powf(1. - 2. * position).clamp(1., 9.99),
|
||||
Self::Gamma => 0.01_f64.powf(2. * position - 1.).clamp(0.01, 1.),
|
||||
Self::Degrees => (position * 360.).clamp(0., 360.),
|
||||
@@ -1831,7 +1999,6 @@ impl MarkerScale {
|
||||
fn number_input(self) -> NumberInput {
|
||||
match self {
|
||||
Self::Percent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(0),
|
||||
Self::LevelPercent => NumberInput::default().mode_increment().unit("%").min(0.).max(100.).display_decimal_places(1),
|
||||
Self::Gamma => NumberInput::default().mode_increment().min(0.01).max(9.99).display_decimal_places(2),
|
||||
Self::Degrees => NumberInput::default().mode_increment().unit("°").min(0.).max(360.).display_decimal_places(0),
|
||||
}
|
||||
@@ -1856,8 +2023,6 @@ struct SliderSectionParam {
|
||||
dash_to_next: bool,
|
||||
/// Whether the marker takes its scale position within the span between its neighbors rather than the whole track, following them as they move.
|
||||
between_neighbors: bool,
|
||||
/// How the marker and the next parameter's marker may pass each other (see [`overlap_bounds`]).
|
||||
overlap_next: MarkerOverlap,
|
||||
}
|
||||
|
||||
impl SliderSectionParam {
|
||||
@@ -1870,7 +2035,6 @@ impl SliderSectionParam {
|
||||
pair_with_next: false,
|
||||
dash_to_next: false,
|
||||
between_neighbors: false,
|
||||
overlap_next: MarkerOverlap::Never,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1888,52 +2052,11 @@ impl SliderSectionParam {
|
||||
self.dash_to_next = true;
|
||||
self
|
||||
}
|
||||
|
||||
fn overlap_next(mut self, overlap: MarkerOverlap) -> Self {
|
||||
self.overlap_next = overlap;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The span the marker at `index` may move within where markers may overlap their next (see [`MarkerOverlap`]).
|
||||
fn overlap_bounds(positions: &[f64], overlaps_next: &[MarkerOverlap], index: usize) -> (f64, f64) {
|
||||
let overlap = |i: Option<usize>| i.and_then(|i| overlaps_next.get(i)).copied().unwrap_or_default();
|
||||
let position = |i: Option<usize>| i.and_then(|i| positions.get(i)).copied();
|
||||
let (previous, before_previous, next, after_next) = (index.checked_sub(1), index.checked_sub(2), Some(index + 1), Some(index + 2));
|
||||
let mut lower = 0_f64;
|
||||
let mut upper = 1_f64;
|
||||
|
||||
// A neighbor bounds the marker unless they overlap
|
||||
if overlap(previous) == MarkerOverlap::Never
|
||||
&& let Some(previous) = position(previous)
|
||||
{
|
||||
lower = lower.max(previous);
|
||||
}
|
||||
if overlap(Some(index)) == MarkerOverlap::Never
|
||||
&& let Some(next) = position(next)
|
||||
{
|
||||
upper = upper.min(next);
|
||||
}
|
||||
|
||||
// Past a neighbor overlapping only its next, the marker beyond bounds it too, unless either overlaps freely
|
||||
let bounds_beyond = |near: MarkerOverlap, far: MarkerOverlap| (near == MarkerOverlap::NextOnly || far == MarkerOverlap::NextOnly) && near != MarkerOverlap::Freely && far != MarkerOverlap::Freely;
|
||||
if bounds_beyond(overlap(previous), overlap(before_previous))
|
||||
&& let Some(before_previous) = position(before_previous)
|
||||
{
|
||||
lower = lower.max(before_previous);
|
||||
}
|
||||
if bounds_beyond(overlap(Some(index)), overlap(next))
|
||||
&& let Some(after_next) = position(after_next)
|
||||
{
|
||||
upper = upper.min(after_next);
|
||||
}
|
||||
|
||||
(lower, upper)
|
||||
}
|
||||
|
||||
/// Append a section of related parameters as rows: a shared slider over `track` (with one marker per non-exposed parameter) sits on the first non-exposed row
|
||||
/// alongside its 60px number input, and the remaining non-exposed rows show only their 60px number input. Exposed parameters render as the standard exposed-row display.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do, except where they may overlap.
|
||||
/// Marker positions are clamped to non-decreasing display order so they never visually cross even if the underlying values do.
|
||||
fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorContext, track: &Gradient, params: &[SliderSectionParam], layout: &mut Vec<LayoutGroup>) {
|
||||
// Snapshot exposure and values before the mutable-borrow loop
|
||||
let exposure_and_value: Vec<(bool, f64)> = match get_document_node(node_id, context) {
|
||||
@@ -1961,7 +2084,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let mut marker_scales = Vec::new();
|
||||
let mut marker_positions = Vec::new();
|
||||
let mut marker_between = Vec::new();
|
||||
let mut marker_overlaps = Vec::new();
|
||||
let mut marker_colors_and_links = Vec::new();
|
||||
for (i, param) in params.iter().enumerate() {
|
||||
let (exposed, value) = exposure_and_value[i];
|
||||
@@ -1974,21 +2096,13 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
marker_default_positions.push(param.scale.position(param.default_value));
|
||||
marker_scales.push(param.scale);
|
||||
marker_between.push(param.between_neighbors);
|
||||
marker_overlaps.push(if next_has_marker { param.overlap_next } else { MarkerOverlap::Never });
|
||||
marker_colors_and_links.push((param.handle_color, param.pair_with_next && next_has_marker, param.dash_to_next && next_has_marker));
|
||||
}
|
||||
|
||||
// Enforce non-decreasing order so markers never visually cross, matching the node's algorithm where shadows takes precedence.
|
||||
// A marker placed between its neighbors bounds nothing here and instead takes its scale position within their settled span.
|
||||
let cyclic = params.iter().any(|param| param.scale.cyclic());
|
||||
let overlapping = marker_overlaps.iter().any(|&overlap| overlap != MarkerOverlap::Never);
|
||||
if overlapping {
|
||||
// Markers allowed to overlap are held only past those they can't pass, each bounded by markers earlier in the list
|
||||
for i in 0..marker_positions.len() {
|
||||
let (lower, _) = overlap_bounds(&marker_positions, &marker_overlaps, i);
|
||||
marker_positions[i] = marker_positions[i].max(lower);
|
||||
}
|
||||
} else if !cyclic {
|
||||
if !cyclic {
|
||||
let mut floor = 0.;
|
||||
for (position, &between) in marker_positions.iter_mut().zip(&marker_between) {
|
||||
if between {
|
||||
@@ -2009,8 +2123,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let slider_markers: Vec<SliderMarker> = marker_positions
|
||||
.iter()
|
||||
.zip(&marker_colors_and_links)
|
||||
.zip(marker_between.iter().zip(&marker_overlaps))
|
||||
.map(|((&position, &(handle_color, paired, dashed)), (&between, &overlap))| {
|
||||
.zip(&marker_between)
|
||||
.map(|((&position, &(handle_color, paired, dashed)), &between)| {
|
||||
let mut marker = SliderMarker::new(position, 0.5, handle_color);
|
||||
if paired {
|
||||
marker = marker.pair_with_next();
|
||||
@@ -2021,7 +2135,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
if between {
|
||||
marker = marker.between_neighbors();
|
||||
}
|
||||
marker = marker.overlap_next(overlap);
|
||||
marker
|
||||
})
|
||||
.collect();
|
||||
@@ -2043,7 +2156,6 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
let marker_scales = marker_scales.clone();
|
||||
let marker_positions = marker_positions.clone();
|
||||
let marker_between = marker_between.clone();
|
||||
let marker_overlaps = marker_overlaps.clone();
|
||||
move |update: &SliderInputUpdate| {
|
||||
let i = match update {
|
||||
SliderInputUpdate::MoveMarker { index, .. } | SliderInputUpdate::ResetMarker { index } => *index as usize,
|
||||
@@ -2058,13 +2170,8 @@ fn build_shared_slider_section(node_id: NodeId, context: &mut NodeInspectorConte
|
||||
// The span the marker's scale maps onto: its neighbors' positions when placed between them, otherwise the track between the
|
||||
// nearest markers that bound it, which a marker placed between its neighbors never does
|
||||
let bounding = |j: usize| between || !marker_between[j];
|
||||
let (left, right) = if overlapping {
|
||||
overlap_bounds(&marker_positions, &marker_overlaps, i)
|
||||
} else {
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
(left, right)
|
||||
};
|
||||
let left = (0..i).rev().find(|&j| bounding(j)).map_or(0., |j| marker_positions[j]);
|
||||
let right = (i + 1..marker_positions.len()).find(|&j| bounding(j)).map_or(1., |j| marker_positions[j]);
|
||||
|
||||
let scale_position = match update {
|
||||
SliderInputUpdate::MoveMarker { position, .. } if between => {
|
||||
@@ -2489,105 +2596,6 @@ pub(crate) fn threshold_inspector(node_id: NodeId, context: &mut NodeInspectorCo
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn blend_if_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::blend_if::blend_if::*;
|
||||
|
||||
let channel = enum_choice::<BlendIfChannel>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, ChannelInput, true, context))
|
||||
.inspector_row();
|
||||
|
||||
let channel_value = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ChannelInput).cloned()) {
|
||||
Some(TaggedValue::BlendIfChannel(channel)) => channel,
|
||||
_ => BlendIfChannel::Gray,
|
||||
};
|
||||
let ([content, underlying], track_color): ([[ParameterRef; 4]; 2], Color) = match channel_value {
|
||||
BlendIfChannel::Gray => (
|
||||
[
|
||||
[
|
||||
ContentFalloffStartInput.into(),
|
||||
ContentRangeStartInput.into(),
|
||||
ContentRangeEndInput.into(),
|
||||
ContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
UnderlyingFalloffStartInput.into(),
|
||||
UnderlyingRangeStartInput.into(),
|
||||
UnderlyingRangeEndInput.into(),
|
||||
UnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::WHITE,
|
||||
),
|
||||
BlendIfChannel::Red => (
|
||||
[
|
||||
[
|
||||
RedContentFalloffStartInput.into(),
|
||||
RedContentRangeStartInput.into(),
|
||||
RedContentRangeEndInput.into(),
|
||||
RedContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
RedUnderlyingFalloffStartInput.into(),
|
||||
RedUnderlyingRangeStartInput.into(),
|
||||
RedUnderlyingRangeEndInput.into(),
|
||||
RedUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::RED,
|
||||
),
|
||||
BlendIfChannel::Green => (
|
||||
[
|
||||
[
|
||||
GreenContentFalloffStartInput.into(),
|
||||
GreenContentRangeStartInput.into(),
|
||||
GreenContentRangeEndInput.into(),
|
||||
GreenContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
GreenUnderlyingFalloffStartInput.into(),
|
||||
GreenUnderlyingRangeStartInput.into(),
|
||||
GreenUnderlyingRangeEndInput.into(),
|
||||
GreenUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::GREEN,
|
||||
),
|
||||
BlendIfChannel::Blue => (
|
||||
[
|
||||
[
|
||||
BlueContentFalloffStartInput.into(),
|
||||
BlueContentRangeStartInput.into(),
|
||||
BlueContentRangeEndInput.into(),
|
||||
BlueContentFalloffEndInput.into(),
|
||||
],
|
||||
[
|
||||
BlueUnderlyingFalloffStartInput.into(),
|
||||
BlueUnderlyingRangeStartInput.into(),
|
||||
BlueUnderlyingRangeEndInput.into(),
|
||||
BlueUnderlyingFalloffEndInput.into(),
|
||||
],
|
||||
],
|
||||
Color::BLUE,
|
||||
),
|
||||
};
|
||||
|
||||
// Each side's range runs along its channel's levels as a black split handle joined to a white one, with the fully shown range dashed between them
|
||||
let track = Gradient::from(vec![Color::BLACK, track_color]);
|
||||
let mut layout = vec![channel];
|
||||
for [falloff_start, range_start, range_end, falloff_end] in [content, underlying] {
|
||||
let params = [
|
||||
SliderSectionParam::new(falloff_start, Color::BLACK, 0., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(range_start, Color::BLACK, 0., MarkerScale::LevelPercent)
|
||||
.dash_to_next()
|
||||
.overlap_next(MarkerOverlap::Freely),
|
||||
SliderSectionParam::new(range_end, Color::WHITE, 100., MarkerScale::LevelPercent).pair_with_next(),
|
||||
SliderSectionParam::new(falloff_end, Color::WHITE, 100., MarkerScale::LevelPercent),
|
||||
];
|
||||
build_shared_slider_section(node_id, context, &track, ¶ms, &mut layout);
|
||||
}
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn vibrance_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::raster::vibrance::*;
|
||||
|
||||
@@ -2840,10 +2848,10 @@ pub(crate) fn grid_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
ParameterWidgetsInfo::new(node_id, SpacingInput, true, context),
|
||||
NumberInput::default().label("H").min(0.).unit(" px"),
|
||||
));
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, false, false);
|
||||
let angles = vec2_widget(ParameterWidgetsInfo::new(node_id, AnglesInput, true, context), "", "", "°", None, None, false, false);
|
||||
widgets.extend([spacing, angles]);
|
||||
} else {
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), false, false);
|
||||
let spacing = vec2_widget(ParameterWidgetsInfo::new(node_id, SpacingInput, true, context), "W", "H", " px", Some(0.), None, false, false);
|
||||
widgets.push(spacing);
|
||||
}
|
||||
}
|
||||
@@ -3167,80 +3175,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => graph_modification_utils::gradient_curvature_values(document_node),
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they make that form
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, gradient_form, tooltip) in [
|
||||
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
|
||||
(
|
||||
"Radial",
|
||||
GradientForm::Radial,
|
||||
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
|
||||
),
|
||||
] {
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the parameters would get without this panel
|
||||
let options = |index: usize| {
|
||||
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
|
||||
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
|
||||
field.map(ParameterOptions::from).unwrap_or_default()
|
||||
};
|
||||
let mut row = |index: usize, ty: Type| {
|
||||
context
|
||||
.call_widget_override(&node_id, index)
|
||||
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
|
||||
};
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
|
||||
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
@@ -3380,29 +3314,20 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
}
|
||||
|
||||
let row = context.call_widget_override(&node_id, input_index).unwrap_or_else(|| {
|
||||
let field = context.network_interface.field_metadata(&node_id, input_index, context.selection_network_path);
|
||||
let options = field.as_ref().map(ParameterOptions::from_field).unwrap_or_default();
|
||||
|
||||
let Some(implementation) = context.network_interface.implementation(&node_id, context.selection_network_path) else {
|
||||
log::error!("Could not get implementation for node {node_id}");
|
||||
return Vec::new();
|
||||
};
|
||||
|
||||
let mut options = ParameterOptions::default();
|
||||
let input_type = match implementation {
|
||||
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => 'early_return: {
|
||||
// Clone to end the `network_interface` borrow held via `implementation`, freeing the mutable borrow `input_type` needs below
|
||||
let proto_node_identifier = proto_node_identifier.clone();
|
||||
|
||||
let mut default_type = None;
|
||||
if let Some(field) = graphene_std::registry::NODE_METADATA
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(input_index))
|
||||
{
|
||||
options = ParameterOptions::from(field);
|
||||
default_type = field.default_type.clone();
|
||||
}
|
||||
|
||||
if let Some(default) = default_type {
|
||||
if let Some(default) = field.and_then(|field| field.default_type) {
|
||||
break 'early_return default;
|
||||
}
|
||||
|
||||
@@ -3418,12 +3343,21 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
let Some(input_type) = input_type else { return Vec::new() };
|
||||
input_type.clone()
|
||||
}
|
||||
_ => context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.unwrap_or(concrete!(())),
|
||||
_ => {
|
||||
// A graph import's declared type still picks its widget while its wire's type is unresolved, such as during an error inside the subgraph
|
||||
let declared_type = field.and_then(|field| field.default_type).map(|declared_type| match declared_type {
|
||||
Type::Item(element) => *element,
|
||||
declared_type => declared_type,
|
||||
});
|
||||
|
||||
context
|
||||
.network_interface
|
||||
.input_type(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
.compiled_nested_type()
|
||||
.cloned()
|
||||
.or(declared_type)
|
||||
.unwrap_or(concrete!(()))
|
||||
}
|
||||
};
|
||||
|
||||
inspector_row_from_type(node_id, input_index, &input_type, options, context).unwrap_or_else(|value| value)
|
||||
@@ -3787,25 +3721,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
let entries = [GradientForm::Linear, GradientForm::Radial]
|
||||
.iter()
|
||||
.map(|&gradient_form| {
|
||||
let [start, end] = gradient_form.curvatures();
|
||||
RadioEntryData::new(format!("{:?}", gradient_form))
|
||||
.label(gradient_form.to_string())
|
||||
.on_update(move |_| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
|
||||
.on_commit(commit_value)
|
||||
})
|
||||
.collect();
|
||||
@@ -3944,7 +3862,7 @@ pub(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorCon
|
||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, None, false, false));
|
||||
}
|
||||
|
||||
let edge_mode = enum_choice::<GradientSpread>()
|
||||
|
||||
@@ -37,7 +37,6 @@ impl FrontendGraphDataType {
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
"Pixels" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => 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 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);
|
||||
assert!(
|
||||
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 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");
|
||||
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"
|
||||
);
|
||||
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
|
||||
|
||||
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||
|
||||
@@ -59,7 +59,6 @@ use crate::messages::portfolio::document::utility_types::network_interface::reso
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils;
|
||||
use crate::messages::tool::tool_messages::tool_prelude::NumberInputMode;
|
||||
use deserialization::deserialize_node_persistent_metadata;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graph_craft::Type;
|
||||
@@ -74,7 +73,7 @@ use graphene_std::vector::click_target::{ClickTarget, ClickTargetType, FreePoint
|
||||
use graphene_std::vector::{Vector, VectorModificationType};
|
||||
use kurbo::BezPath;
|
||||
use memo_network::MemoNetwork;
|
||||
use serde_json::{Value, json};
|
||||
use serde_json::Value;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::hash::Hash;
|
||||
use std::ops::Deref;
|
||||
|
||||
+1
-58
@@ -2613,7 +2613,7 @@ async fn shaking_a_node_spliced_in_by_a_secondary_input_keeps_the_dot_on_its_wir
|
||||
// Numbers to Vec2 hides its primary input, so it takes the flow by its first exposed input instead
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
let shaken = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER), 10, 0)
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER), 10, 0)
|
||||
.await;
|
||||
let dot = editor.create_node_by_name_at(passthrough_definition(), 20, 0).await;
|
||||
let consumer = editor.create_node_by_name_at(fill_definition(), 30, 0).await;
|
||||
@@ -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]
|
||||
async fn shift_clicking_a_selected_node_in_the_graph_ends_its_press() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
use super::*;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
|
||||
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
/// Runs a query against a resolved [`NetworkView`], logging any error at this message-boundary wrapper and mapping it to None.
|
||||
pub(crate) fn query<'a, 'p, T>(&'a self, network_path: &'p [NodeId], caller: &str, query: impl FnOnce(NetworkView<'a, 'p>) -> Result<T, NetworkError>) -> Option<T> {
|
||||
@@ -829,17 +826,27 @@ impl NodeNetworkInterface {
|
||||
self.view(network_path).ok().and_then(|view| view.persistent_input_metadata(node_id, index).ok())
|
||||
}
|
||||
|
||||
/// Whether the input is internal state of its proto node (named with a leading `_`), which is never exposed to the graph.
|
||||
/// Whether the input is internal state of its node (named with a leading `_`), which is never exposed to the graph.
|
||||
pub fn is_internal_input(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> bool {
|
||||
let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) else {
|
||||
return false;
|
||||
};
|
||||
let Ok(node_metadata) = graphene_std::registry::NODE_METADATA.lock() else { return false };
|
||||
self.field_metadata(node_id, index, network_path).is_some_and(|field| field.internal)
|
||||
}
|
||||
|
||||
node_metadata
|
||||
.get(proto_node_identifier)
|
||||
.and_then(|metadata| metadata.fields.get(index))
|
||||
.is_some_and(|field| field.internal)
|
||||
/// The metadata the node macro records for a proto node's parameter, or the `#[graph]` macro for a graph node's import.
|
||||
/// A graph node's input has it only while it still has that import's name, since an edited subgraph can reorder its imports.
|
||||
pub fn field_metadata(&self, node_id: &NodeId, index: usize, network_path: &[NodeId]) -> Option<graphene_std::registry::FieldMetadata> {
|
||||
if let Some(DocumentNodeImplementation::ProtoNode(proto_node_identifier)) = self.implementation(node_id, network_path) {
|
||||
let node_metadata = graphene_std::registry::NODE_METADATA.lock().ok()?;
|
||||
return node_metadata.get(proto_node_identifier)?.fields.get(index).cloned();
|
||||
}
|
||||
|
||||
let Some(DefinitionIdentifier::Network(identifier)) = self.reference(node_id, network_path) else {
|
||||
return None;
|
||||
};
|
||||
let input_name = self.persistent_input_metadata(node_id, index, network_path)?.input_name.clone();
|
||||
|
||||
let graphs = graphene_std::registry::GRAPH_METADATA.lock().ok()?;
|
||||
let field = graphs.iter().find(|graph| graph.identifier == identifier)?.imports.get(index)?;
|
||||
(field.name == input_name).then(|| field.clone())
|
||||
}
|
||||
|
||||
/// The description stored for a node's output, or else for a proto node, the doc comment on its field in the struct a multi-output node returns.
|
||||
@@ -1079,7 +1086,7 @@ impl NodeNetworkInterface {
|
||||
/// Whether the artboard layer clips the content inside it to its bounds.
|
||||
fn artboard_clips_content(&self, artboard: LayerNodeIdentifier) -> bool {
|
||||
self.document_node(&artboard.to_node(), &[])
|
||||
.and_then(|artboard| artboard.inputs.get(ARTBOARD_CLIP_INPUT_INDEX))
|
||||
.and_then(|artboard| artboard.inputs.get(graphene_std::subgraphs::artboard::ClipInput::INDEX))
|
||||
.is_some_and(|clip_input| matches!(clip_input, NodeInput::Value { tagged_value, .. } if tagged_value.clone().deref() == &TaggedValue::Bool(true)))
|
||||
}
|
||||
|
||||
|
||||
@@ -773,51 +773,11 @@ impl PartialEq for DocumentNodeMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NumberInputSettings {
|
||||
pub unit: Option<String>,
|
||||
pub min: Option<f64>,
|
||||
pub max: Option<f64>,
|
||||
pub step: Option<f64>,
|
||||
pub mode: NumberInputMode,
|
||||
pub range_min: Option<f64>,
|
||||
pub range_max: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
impl Default for NumberInputSettings {
|
||||
fn default() -> Self {
|
||||
NumberInputSettings {
|
||||
unit: None,
|
||||
min: None,
|
||||
max: None,
|
||||
step: None,
|
||||
mode: NumberInputMode::default(),
|
||||
range_min: None,
|
||||
range_max: None,
|
||||
is_integer: false,
|
||||
blank_assist: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Vec2InputSettings {
|
||||
pub x: String,
|
||||
pub y: String,
|
||||
pub unit: String,
|
||||
pub min: Option<f64>,
|
||||
pub is_integer: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub enum WidgetOverride {
|
||||
None,
|
||||
Hidden,
|
||||
String(String),
|
||||
Number(NumberInputSettings),
|
||||
Vec2(Vec2InputSettings),
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
@@ -854,40 +814,6 @@ impl InputPersistentMetadata {
|
||||
self.input_data.insert("string_inspector".to_string(), Value::String(string_inspector));
|
||||
self.widget_override = Some("string".to_string());
|
||||
}
|
||||
WidgetOverride::Number(mut number_inspector) => {
|
||||
if let Some(unit) = number_inspector.unit.take() {
|
||||
self.input_data.insert("unit".to_string(), json!(unit));
|
||||
}
|
||||
if let Some(min) = number_inspector.min.take() {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
if let Some(max) = number_inspector.max.take() {
|
||||
self.input_data.insert("max".to_string(), json!(max));
|
||||
}
|
||||
if let Some(step) = number_inspector.step.take() {
|
||||
self.input_data.insert("step".to_string(), json!(step));
|
||||
}
|
||||
if let Some(range_min) = number_inspector.range_min.take() {
|
||||
self.input_data.insert("range_min".to_string(), json!(range_min));
|
||||
}
|
||||
if let Some(range_max) = number_inspector.range_max.take() {
|
||||
self.input_data.insert("range_max".to_string(), json!(range_max));
|
||||
}
|
||||
self.input_data.insert("mode".to_string(), json!(number_inspector.mode));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(number_inspector.is_integer));
|
||||
self.input_data.insert("blank_assist".to_string(), Value::Bool(number_inspector.blank_assist));
|
||||
self.widget_override = Some("number".to_string());
|
||||
}
|
||||
WidgetOverride::Vec2(vec2_inspector) => {
|
||||
self.input_data.insert("x".to_string(), json!(vec2_inspector.x));
|
||||
self.input_data.insert("y".to_string(), json!(vec2_inspector.y));
|
||||
self.input_data.insert("unit".to_string(), json!(vec2_inspector.unit));
|
||||
self.input_data.insert("is_integer".to_string(), Value::Bool(vec2_inspector.is_integer));
|
||||
if let Some(min) = vec2_inspector.min {
|
||||
self.input_data.insert("min".to_string(), json!(min));
|
||||
}
|
||||
self.widget_override = Some("vec2".to_string());
|
||||
}
|
||||
WidgetOverride::Custom(lambda_name) => {
|
||||
self.widget_override = Some(lambda_name);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::node_graph::document_node_definitions:
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, InputConnector, NodeTemplate, NodeTemplateImplementation, OutputConnector};
|
||||
use crate::messages::prelude::DocumentMessageHandler;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::application_io::resource::{DataSource, Resource, ResourceHash, ResourceId};
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeInput, value::TaggedValue};
|
||||
@@ -21,7 +21,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -121,10 +121,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_std::raster::SampleImageNode",
|
||||
"graphene_std::raster::SampleNode",
|
||||
"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 {
|
||||
@@ -185,6 +181,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphic_nodes::graphic::ExtractElementNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
||||
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
||||
@@ -297,6 +297,14 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::floor::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FloorNode", "graphene_core::ops::FloorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -464,9 +472,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
// The old 'Vec2 Value' node took separate X and Y inputs, a role now filled by 'Numbers to Vec2', while the new 'Vec2 Value' node takes a single vec2 input.
|
||||
// Old references (including these older aliases) are remapped here to `vec_2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
// Old references (including these older aliases) are remapped here to `vec2_value::IDENTIFIER` so the per-node migration in `migrate_node` can detect the leftover 3-input shape and convert it into a 'Numbers to Vec2' node.
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::vec_2_value::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::vec2_value::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_math_nodes::Vec2ValueNode",
|
||||
"graphene_core::ops::ConstructVector2",
|
||||
@@ -476,7 +484,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER,
|
||||
node: graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER,
|
||||
aliases: &["math_nodes::CombineVec2Node"],
|
||||
},
|
||||
// ================================
|
||||
@@ -545,13 +553,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
||||
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||
aliases: &[
|
||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||
"graphene_std::raster::CombineChannelsNode",
|
||||
@@ -569,6 +572,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"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 {
|
||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||
@@ -1565,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.
|
||||
// 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 = [
|
||||
("Split Vec2", 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 Vec2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Vector2", graphene_std::math_nodes::vec2_to_numbers::IDENTIFIER),
|
||||
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||
];
|
||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -1617,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.
|
||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||
@@ -1634,9 +1641,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let DocumentNodeImplementation::ProtoNode(protonode_id) = &node.implementation else { return None };
|
||||
let name = protonode_id.as_str().split('<').next().unwrap_or_default();
|
||||
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::vec2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||
} 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 {
|
||||
None
|
||||
}
|
||||
@@ -1682,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.
|
||||
// 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";
|
||||
@@ -1823,7 +1784,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
for (node_id, node, network_path) in &nodes {
|
||||
migrate_node(node_id, node, network_path, document, reset_node_definitions_on_open);
|
||||
}
|
||||
remove_footprint_value_nodes(document);
|
||||
create_layer_stacks(document);
|
||||
follow_segments_turned_on_load(document);
|
||||
|
||||
@@ -2182,100 +2142,6 @@ fn read_noise_through_gamma_correction(document: &mut DocumentMessageHandler, no
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Whether a node is a removed 'Footprint Value' node, under any identifier it had.
|
||||
fn is_footprint_value(node: &DocumentNode) -> bool {
|
||||
matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().ends_with("::FootprintValueNode"))
|
||||
}
|
||||
|
||||
/// Sets an upgraded Rasterize node's area transform and resolution from the footprint it took, stored or from a 'Footprint Value' node (even
|
||||
/// through reroutes) whose inputs it takes over. Any other wire can't be read before it runs, so it leaves the defaults, shown in the graph.
|
||||
fn set_rasterize_area_from_footprint(document: &mut DocumentMessageHandler, node_id: &NodeId, network_path: &[NodeId], footprint: &NodeInput) -> Option<()> {
|
||||
use graphene_std::math_nodes::multiply;
|
||||
|
||||
// A footprint's transform placed a unit square anchored at its corner, where the area's is centered on its origin
|
||||
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||
let (transform_connector, resolution_connector) = (InputConnector::node_at_index(*node_id, 1), InputConnector::node_at_index(*node_id, 2));
|
||||
|
||||
// Reroutes pass the footprint along unchanged, and a cycle of them leads nowhere else
|
||||
let mut footprint = footprint.clone();
|
||||
let mut visited = HashSet::new();
|
||||
while let NodeInput::Node { node_id: source, output_index: 0 } = footprint
|
||||
&& visited.insert(source)
|
||||
&& let Some(reroute) = document.network_interface.document_node(&source, network_path)
|
||||
&& matches!(&reroute.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER)
|
||||
&& let Some(content) = reroute.inputs.first()
|
||||
{
|
||||
footprint = content.clone();
|
||||
}
|
||||
|
||||
match &footprint {
|
||||
// A stored footprint loads as its transform's six numbers then its resolution's two
|
||||
NodeInput::Value { tagged_value, exposed } => {
|
||||
let TaggedValue::Numbers(numbers) = &**tagged_value else { return None };
|
||||
let &[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y, width, height] = numbers.as_slice() else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let transform = DAffine2::from_cols_array(&[x_axis_x, x_axis_y, y_axis_x, y_axis_y, translation_x, translation_y]) * corner_to_center;
|
||||
let resolution = DVec2::new(width, height);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&transform_connector, NodeInput::value(TaggedValue::DAffine2(transform), *exposed), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&resolution_connector, NodeInput::value(TaggedValue::DVec2(resolution), *exposed), network_path);
|
||||
}
|
||||
NodeInput::Node { node_id: source, output_index: 0 } if document.network_interface.document_node(source, network_path).is_some_and(is_footprint_value) => {
|
||||
let footprint_value = document.network_interface.document_node(source, network_path)?;
|
||||
let (transform, resolution) = (footprint_value.inputs.get(1)?.clone(), footprint_value.inputs.get(2)?.clone());
|
||||
document.network_interface.set_input(&resolution_connector, resolution, network_path);
|
||||
|
||||
match transform {
|
||||
NodeInput::Value { tagged_value, exposed } => {
|
||||
let &TaggedValue::DAffine2(transform) = &*tagged_value else { return None };
|
||||
let transform = NodeInput::value(TaggedValue::DAffine2(transform * corner_to_center), exposed);
|
||||
document.network_interface.set_input(&transform_connector, transform, network_path);
|
||||
}
|
||||
// A wired transform goes through a Multiply node moving its unit square's anchor to the center
|
||||
wire => {
|
||||
document.network_interface.set_input(&transform_connector, wire, network_path);
|
||||
|
||||
let multiply_id = NodeId::new();
|
||||
document
|
||||
.network_interface
|
||||
.insert_node(multiply_id, resolve_proto_node_type(multiply::IDENTIFIER)?.default_node_template(), network_path);
|
||||
let multiplicand = NodeInput::value(TaggedValue::DAffine2(corner_to_center), false);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(multiply_id, 1), multiplicand, network_path);
|
||||
document.network_interface.insert_node_before_input(&multiply_id, &transform_connector, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
for connector in [transform_connector, resolution_connector] {
|
||||
let default = document.network_interface.input_from_connector(&connector, network_path)?.as_value()?.clone();
|
||||
document.network_interface.set_input(&connector, NodeInput::value(default, true), network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Deletes every 'Footprint Value' node once the Rasterize nodes it fed have taken over its inputs, disconnecting whatever else it fed.
|
||||
fn remove_footprint_value_nodes(document: &mut DocumentMessageHandler) {
|
||||
let footprint_value_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(_, node, _)| is_footprint_value(node))
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in footprint_value_nodes {
|
||||
document.network_interface.delete_nodes(vec![node_id], false, &network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2628,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);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
// The 7-input shape's own gradient metadata defaults, which the steps after this one read until the legacy fill's values replace them below
|
||||
let metadata_defaults = [
|
||||
TaggedValue::GradientForm(GradientForm::Linear),
|
||||
TaggedValue::Bool(false),
|
||||
TaggedValue::DAffine2(glam::DAffine2::IDENTITY),
|
||||
];
|
||||
for (index, value) in (4..).zip(metadata_defaults) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
||||
}
|
||||
|
||||
// Content: no change
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||
|
||||
@@ -2783,11 +2637,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 7;
|
||||
}
|
||||
|
||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
|
||||
// so this era is told apart by its form at 4 or its spread at 5, either of which may be wired, where the modern shape holds curvatures.
|
||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
||||
let is_spread_method_fill = inputs_count == 8 && (matches!(value_at(4), Some(TaggedValue::GradientForm(_))) || matches!(value_at(5), Some(TaggedValue::GradientSpread(_))));
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && is_spread_method_fill {
|
||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
|
||||
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)?;
|
||||
|
||||
@@ -2810,36 +2661,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 7;
|
||||
}
|
||||
|
||||
// The Fill node gives its gradient paint the curvatures of a form in place of its `_gradient_form` input, and they stay shown in the graph where the form was
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
// Content, paint, and backups keep their places, and the transform inputs move past the second curvature
|
||||
for (index, input) in old_inputs.iter().enumerate().take(7) {
|
||||
let index = match index {
|
||||
4 => continue,
|
||||
5.. => index + 1,
|
||||
_ => index,
|
||||
};
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let form = old_inputs.get(4);
|
||||
let curvatures = match form.and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(form)) => form.curvatures(),
|
||||
_ => GradientForm::Linear.curvatures(),
|
||||
};
|
||||
let exposed = form.is_some_and(NodeInput::is_exposed);
|
||||
for (index, curvature) in (4..).zip(curvatures) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(TaggedValue::Number(curvature), exposed), network_path);
|
||||
}
|
||||
|
||||
inputs_count = 8;
|
||||
}
|
||||
|
||||
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3110,8 +2931,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// Convert the old 'Vec2 Value' node, identified by its leftover 3-input shape with separate X and Y inputs,
|
||||
// into the 'Numbers to Vec2' node which now fills that role (the new 'Vec2 Value' node instead takes a single vec2 input)
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec_2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec_2::IDENTIFIER);
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::vec2_value::IDENTIFIER) && inputs_count == 3 {
|
||||
let numbers_to_vec2_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::numbers_to_vec2::IDENTIFIER);
|
||||
let mut node_template = resolve_document_node_type(&numbers_to_vec2_reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
@@ -3256,16 +3077,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count = 2;
|
||||
}
|
||||
|
||||
// Rasterize, like the wrapper network collapsed into it above, took a footprint where it now takes an area transform and a resolution
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER) && matches!(inputs_count, 2 | 3) {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), node.inputs[0].clone(), network_path);
|
||||
set_rasterize_area_from_footprint(document, node_id, network_path, &node.inputs[1]);
|
||||
inputs_count = 4;
|
||||
}
|
||||
|
||||
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3353,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);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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
|
||||
@@ -4313,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
|
||||
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
||||
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
||||
@@ -4833,8 +4622,11 @@ mod tests {
|
||||
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
|
||||
// A footprint can't be written any more, so a placeholder value stands in for it until the document is serialized
|
||||
let placeholder = NodeInput::value(TaggedValue::String("footprint placeholder".into()), false);
|
||||
let footprint = Footprint {
|
||||
resolution: glam::UVec2::new(64, 32),
|
||||
..Default::default()
|
||||
};
|
||||
let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false);
|
||||
|
||||
// Save the node as the network that drew into a browser canvas, which took only the artwork and footprint
|
||||
let canvas_network = NodeNetworkTemplate {
|
||||
@@ -4852,111 +4644,27 @@ mod tests {
|
||||
..Default::default()
|
||||
};
|
||||
let mut legacy = NodeTemplate {
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), placeholder],
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), footprint_input.clone()],
|
||||
implementation: NodeTemplateImplementation::Network(canvas_network),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
|
||||
|
||||
// A 64 by 32 pixel footprint over the 500 by 250 px rectangle from (-20, 40)
|
||||
let placeholder = r#"{"String":"footprint placeholder"}"#;
|
||||
let footprint = r#"{"Footprint":{"transform":[500.0,0.0,0.0,250.0,-20.0,40.0],"resolution":[64,32],"quality":"Full"}}"#;
|
||||
let serialized = document.serialize_document();
|
||||
assert!(serialized.contains(placeholder), "the placeholder should be serialized as expected");
|
||||
let serialized = serialized.replace(placeholder, footprint);
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
|
||||
|
||||
// The area's unit square is centered on its origin, so its translation is the rectangle's center
|
||||
let area = DAffine2::from_scale_angle_translation(DVec2::new(500., 250.), 0., DVec2::new(230., 165.));
|
||||
let input = |index| interface.input_from_connector(&InputConnector::node_at_index(node_id, index), &[]).cloned();
|
||||
assert_eq!(input(1), Some(NodeInput::value(TaggedValue::DAffine2(area), false)), "the footprint should cover the same area");
|
||||
assert_eq!(
|
||||
input(2),
|
||||
Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(64., 32.)), false)),
|
||||
"the footprint should keep its resolution"
|
||||
interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]),
|
||||
Some(&footprint_input),
|
||||
"the footprint should carry over"
|
||||
);
|
||||
|
||||
let definition_inputs = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition").node_template.inputs.len();
|
||||
assert_eq!(interface.number_of_inputs(&node_id, &[]), definition_inputs, "the node should gain the inputs the compiler fills in");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_footprint_value_nodes_folds_them_into_the_rasterize_nodes_they_fed() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::platform_application_io::rasterize;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let literal_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
|
||||
let wired_rasterize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 10).await;
|
||||
let transform_source = editor
|
||||
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -20, 10)
|
||||
.await;
|
||||
let reroute = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), -5, 10).await;
|
||||
let document = editor.active_document_mut();
|
||||
|
||||
let footprint_transform = DAffine2::from_scale_angle_translation(DVec2::new(300., 200.), 0., DVec2::new(10., 20.));
|
||||
let footprint_value = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("math_nodes::FootprintValueNode")),
|
||||
inputs: vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::value(TaggedValue::DAffine2(footprint_transform), false),
|
||||
NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false),
|
||||
],
|
||||
..Default::default()
|
||||
};
|
||||
let (literal_footprint, wired_footprint) = (NodeId(1), NodeId(2));
|
||||
document.network_interface.insert_node(literal_footprint, footprint_value.clone(), &[]);
|
||||
document.network_interface.insert_node(wired_footprint, footprint_value, &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(wired_footprint, 1), NodeInput::node(transform_source, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(reroute, 0), NodeInput::node(wired_footprint, 0), &[]);
|
||||
|
||||
// Each Rasterize node as saved before its area and resolution, taking the artwork, the footprint, and the executor
|
||||
let definition = resolve_proto_node_type(rasterize::IDENTIFIER).expect("Rasterize should have a definition");
|
||||
let executor = definition.node_template.inputs.last().cloned().expect("Rasterize should take the executor");
|
||||
for (rasterize_node, footprint_node) in [(literal_rasterize, literal_footprint), (wired_rasterize, reroute)] {
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: vec![NodeInput::type_default(list!(graphic_types::Graphic), true), NodeInput::node(footprint_node, 0), executor.clone()],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&rasterize_node, &[], &mut old_inputs);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node, index| interface.input_from_connector(&InputConnector::node_at_index(node, index), &[]).cloned();
|
||||
|
||||
assert!(interface.document_node(&literal_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||
assert!(interface.document_node(&wired_footprint, &[]).is_none(), "the Footprint Value node should be removed");
|
||||
|
||||
let corner_to_center = DAffine2::from_translation(DVec2::splat(0.5));
|
||||
let resolution = Some(NodeInput::value(TaggedValue::DVec2(DVec2::new(30., 20.)), false));
|
||||
assert_eq!(
|
||||
input(literal_rasterize, 1),
|
||||
Some(NodeInput::value(TaggedValue::DAffine2(footprint_transform * corner_to_center), false))
|
||||
);
|
||||
assert_eq!(input(literal_rasterize, 2), resolution);
|
||||
|
||||
// The wired transform reaches the area through a Multiply node centering its unit square
|
||||
let Some(NodeInput::Node { node_id: multiply, output_index: 0 }) = input(wired_rasterize, 1) else {
|
||||
panic!("the wired transform should reach the area through a node");
|
||||
};
|
||||
assert_eq!(input(multiply, 0), Some(NodeInput::node(transform_source, 0)));
|
||||
assert_eq!(input(multiply, 1), Some(NodeInput::value(TaggedValue::DAffine2(corner_to_center), false)));
|
||||
assert_eq!(input(wired_rasterize, 2), resolution);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_a_document_with_the_removed_extract_node_turns_it_into_a_passthrough() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
@@ -5170,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
|
||||
#[test]
|
||||
fn every_into_group_alias_resets_the_merge_definition() {
|
||||
@@ -5556,7 +5230,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let count_conversion = network_template.nodes.get_mut(&NodeId(3)).expect("Blend should have a count conversion node");
|
||||
let (&count_conversion_id, count_conversion) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.inputs.iter().any(|input| matches!(input, NodeInput::Import { import_index: 1, .. })))
|
||||
.expect("Blend should have a count conversion node");
|
||||
count_conversion.implementation = NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::floor::IDENTIFIER);
|
||||
count_conversion.inputs = vec![NodeInput::import(item!(f64), 1)];
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
@@ -5573,7 +5251,7 @@ mod tests {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Blend", NodeId(3))].implementation,
|
||||
inner.nodes[&shipped_node_id("Blend", count_conversion_id)].implementation,
|
||||
DocumentNodeImplementation::ProtoNode(graphene_std::math_nodes::as_number::IDENTIFIER)
|
||||
);
|
||||
}
|
||||
@@ -5590,7 +5268,11 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Blend should be a network node")
|
||||
};
|
||||
let edited_subtract = network_template.nodes.get_mut(&NodeId(5)).expect("Blend should have an open-path denominator node");
|
||||
let (&edited_subtract_id, edited_subtract) = network_template
|
||||
.nodes
|
||||
.iter_mut()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::math_nodes::subtract::IDENTIFIER))
|
||||
.expect("Blend should have an open-path denominator node");
|
||||
edited_subtract.inputs[1] = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
@@ -5600,7 +5282,7 @@ mod tests {
|
||||
let (DocumentNodeImplementation::Definition(definition), Some(inner)) = (implementation, document.network_interface.document_network().implementation_network(implementation)) else {
|
||||
panic!("Blend should stay a network node")
|
||||
};
|
||||
let edited_subtract = derived_node_id(*definition, NodeId(5));
|
||||
let edited_subtract = derived_node_id(*definition, edited_subtract_id);
|
||||
assert_eq!(inner.nodes[&edited_subtract].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
|
||||
}
|
||||
|
||||
@@ -5682,8 +5364,15 @@ mod tests {
|
||||
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
|
||||
panic!("Regex Find should be a network node")
|
||||
};
|
||||
network_template.nodes.get_mut(&NodeId(0)).expect("Regex Find should have a find node").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&NodeId(1)).expect("Regex Find should have an item-at-index node").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
let inner_node_id = |identifier: graphene_std::ProtoNodeIdentifier| {
|
||||
let implementation = NodeTemplateImplementation::ProtoNode(identifier);
|
||||
network_template.nodes.iter().find(|(_, node)| node.implementation == implementation).map(|(&id, _)| id)
|
||||
};
|
||||
let find_id = inner_node_id(graphene_std::text_nodes::regex::regex_find::IDENTIFIER).expect("Regex Find should have a find node");
|
||||
let item_at_index_id = inner_node_id(graphene_std::graphic::item_at_index::IDENTIFIER).expect("Regex Find should have an item-at-index node");
|
||||
|
||||
network_template.nodes.get_mut(&find_id).expect("the find node should exist").inputs[2] = NodeInput::import(item!(f64), 2);
|
||||
network_template.nodes.get_mut(&item_at_index_id).expect("the item-at-index node should exist").inputs[1] = NodeInput::value(TaggedValue::Number(0.), false);
|
||||
document.network_interface.insert_node(node_id, node_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
@@ -5697,9 +5386,9 @@ mod tests {
|
||||
let Some(inner) = document.network_interface.document_network().implementation_network(&node.implementation) else {
|
||||
panic!("Regex Find should stay a network node")
|
||||
};
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", NodeId(0))].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(inner.nodes[&shipped_node_id("Regex Find", find_id)].inputs.get(2), Some(&NodeInput::import(item!(i64), 2)));
|
||||
assert_eq!(
|
||||
inner.nodes[&shipped_node_id("Regex Find", NodeId(1))].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
inner.nodes[&shipped_node_id("Regex Find", item_at_index_id)].inputs.get(1).and_then(|input| input.as_value()).cloned(),
|
||||
Some(TaggedValue::Integer(0))
|
||||
);
|
||||
}
|
||||
@@ -5766,204 +5455,6 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
|
||||
// Curvatures stay shown in the graph where an exposed form was
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, curvatures, exposed) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), exposed), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
assert_eq!(
|
||||
[1, 2].map(|index| node.inputs[index].is_exposed()),
|
||||
[exposed; 2],
|
||||
"{form:?} exposed {exposed} should leave its curvatures so"
|
||||
);
|
||||
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
|
||||
}
|
||||
}
|
||||
|
||||
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
|
||||
#[test]
|
||||
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use glam::DAffine2;
|
||||
|
||||
let (source_id, fill_id) = (NodeId(1), NodeId(2));
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
|
||||
let old_inputs = vec![
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
|
||||
ramp(),
|
||||
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
|
||||
NodeInput::value(TaggedValue::None, false),
|
||||
NodeInput::value(TaggedValue::Bool(true), false),
|
||||
NodeInput::value(TaggedValue::DAffine2(placement), false),
|
||||
];
|
||||
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let source = NodeTemplate {
|
||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(source_id, source, &[]);
|
||||
let fill = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
|
||||
inputs: old_inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(fill_id, fill, &[]);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&fill_id];
|
||||
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
|
||||
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
|
||||
assert_eq!(values, expected, "the form should become its curvatures before the placement");
|
||||
}
|
||||
|
||||
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
|
||||
#[tokio::test]
|
||||
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::vector::fill;
|
||||
use graphene_std::vector::style::Gradient;
|
||||
use graphene_std::vector_types::gradient_standard::GradientShape;
|
||||
use graphene_std::{Appearance, Cover, Graphic};
|
||||
|
||||
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
|
||||
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let layer = instrumented
|
||||
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
|
||||
.next()
|
||||
.expect("the layer is extended onto the root");
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
layer.element().render_svg(&mut render, &RenderParams::default());
|
||||
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
|
||||
let mut index = 0;
|
||||
while let Some(found) = markup.find(r#"id=""#) {
|
||||
let start = found + r#"id=""#.len();
|
||||
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
|
||||
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
|
||||
index += 1;
|
||||
}
|
||||
|
||||
let shape = match layer.element() {
|
||||
Graphic::VectorList(vectors) => match vectors
|
||||
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
|
||||
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
|
||||
{
|
||||
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
|
||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
|
||||
)),
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
(markup.replace(r#"ID=""#, r#"id=""#), shape)
|
||||
}
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(10., 20., 110., 70.).await;
|
||||
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
|
||||
gradient_form: Some(GradientForm::Radial),
|
||||
gradient_settings: Default::default(),
|
||||
transform: Some(placement),
|
||||
})
|
||||
.await;
|
||||
|
||||
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
|
||||
let (curved_svg, curved_shape) = painted(&mut editor).await;
|
||||
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
|
||||
assert_eq!(curved_shape, Some(GradientShape::Radial));
|
||||
|
||||
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
|
||||
let document = editor.active_document_mut();
|
||||
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
|
||||
.upstream_node_id_from_protonode(fill::IDENTIFIER)
|
||||
.expect("the layer has a Fill");
|
||||
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
|
||||
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
|
||||
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
|
||||
|
||||
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
|
||||
let mut old_inputs = NodeTemplate {
|
||||
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
|
||||
let serialized = document.serialize_document();
|
||||
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
|
||||
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
|
||||
|
||||
editor
|
||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
||||
document_name: Some("Migrated".into()),
|
||||
document_path: None,
|
||||
document_serialized_content: serialized,
|
||||
})
|
||||
.await;
|
||||
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
|
||||
assert_eq!(migrated_svg, curved_svg);
|
||||
assert_eq!(migrated_shape, curved_shape);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6513,35 +6004,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]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => match self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) {
|
||||
Some(document) => self.executor.submit_clipboard_svg(document, viewport.size().into_dvec2(), id),
|
||||
None => responses.add(ClipboardMessage::Rendered { id, svg: Ok(None) }),
|
||||
},
|
||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||
let layers = self.active_document().map(|document| {
|
||||
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 => {
|
||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||
responses.add(MenuBarMessage::SendLayout);
|
||||
|
||||
@@ -217,7 +217,7 @@ impl DrawingToolState {
|
||||
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: graphene_std::vector::Gradient::from(&ramp),
|
||||
gradient_form: None,
|
||||
gradient_form: Default::default(),
|
||||
gradient_settings: (&ramp).into(),
|
||||
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
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
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_positions::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())
|
||||
}
|
||||
|
||||
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
|
||||
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
||||
&TaggedValue::Number(value) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
|
||||
}
|
||||
|
||||
/// Get the gradient stops of a layer, if any.
|
||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||
// Try to find the gradient stops value that is created by a Fill node first
|
||||
@@ -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`).
|
||||
pub struct FillNodeGradient {
|
||||
pub stops: Gradient,
|
||||
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
|
||||
pub curvatures: Option<[f64; 2]>,
|
||||
/// The form its curvatures make, which is linear for any that make neither.
|
||||
pub gradient_form: GradientForm,
|
||||
pub settings: GradientSettings,
|
||||
pub transform: DAffine2,
|
||||
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
||||
};
|
||||
let settings = GradientSettings::from(ramp);
|
||||
let stops = Gradient::from(ramp);
|
||||
let curvatures = fill_node_curvatures(fill_node);
|
||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
||||
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
|
||||
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 transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||
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 {
|
||||
stops,
|
||||
curvatures,
|
||||
gradient_form,
|
||||
settings,
|
||||
transform,
|
||||
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
use graphene_std::vector::fill;
|
||||
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
|
||||
|
||||
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
|
||||
Some(TaggedValue::GradientForm(value)) => *value,
|
||||
_ => GradientForm::default(),
|
||||
};
|
||||
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
|
||||
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
|
||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: Gradient::from(ramp),
|
||||
gradient_form: None,
|
||||
gradient_form,
|
||||
gradient_settings: ramp.into(),
|
||||
transform: Some(transform),
|
||||
});
|
||||
|
||||
@@ -175,8 +175,6 @@ pub struct SnapSession {
|
||||
gesture: Option<Gesture>,
|
||||
/// The targets woken by resting the pointer on them, from the one woken longest ago to the latest.
|
||||
awake: Vec<Awake>,
|
||||
/// Those of them woken during the gesture under way, which go back to sleep when it ends.
|
||||
woken_in_gesture: Vec<Awake>,
|
||||
/// The layers each woken point of its own was found on, by its ID, which it goes back to sleep with.
|
||||
position_sources: HashMap<u64, Vec<LayerId>>,
|
||||
rest: Option<Rest>,
|
||||
@@ -497,17 +495,13 @@ impl SnapSession {
|
||||
landed
|
||||
}
|
||||
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to. What the gesture woke goes back to sleep with it.
|
||||
/// Ends a gesture, however it ended, and forgets what the pointer was snapped to.
|
||||
pub fn end_gesture(&mut self) {
|
||||
self.gesture = None;
|
||||
self.constructions = None;
|
||||
self.rest = None;
|
||||
self.crossings.clear();
|
||||
self.forget();
|
||||
|
||||
let woken_in_gesture = std::mem::take(&mut self.woken_in_gesture);
|
||||
self.awake.retain(|target| !woken_in_gesture.contains(target));
|
||||
self.forget_targets_gone_to_sleep();
|
||||
}
|
||||
|
||||
/// Forgets what the pointer was last snapped to, as when the pointer is no longer placing anything.
|
||||
@@ -551,14 +545,11 @@ impl SnapSession {
|
||||
if let Awake::Position { id, .. } = target {
|
||||
self.position_sources.insert(id, sources.clone());
|
||||
}
|
||||
if self.gesture.is_some() {
|
||||
self.woken_in_gesture.push(target);
|
||||
}
|
||||
self.awake.push(target);
|
||||
}
|
||||
let over_the_limit = self.awake.len().saturating_sub(AWAKE_LIMIT);
|
||||
self.awake.drain(..over_the_limit);
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
self.constructions = None;
|
||||
|
||||
true
|
||||
@@ -572,7 +563,6 @@ impl SnapSession {
|
||||
/// Puts every woken target back to sleep, and keeps the pointer from waking them again until it moves.
|
||||
pub fn sleep_all(&mut self) {
|
||||
self.awake.clear();
|
||||
self.woken_in_gesture.clear();
|
||||
self.position_sources.clear();
|
||||
self.constructions = None;
|
||||
|
||||
@@ -593,12 +583,10 @@ impl SnapSession {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Lets go of what is kept about woken targets that have since gone back to sleep.
|
||||
fn forget_targets_gone_to_sleep(&mut self) {
|
||||
fn forget_sources_of_sleeping_positions(&mut self) {
|
||||
let awake = &self.awake;
|
||||
self.position_sources
|
||||
.retain(|id, _| awake.iter().any(|target| matches!(target, Awake::Position { id: awake_id, .. } if awake_id == id)));
|
||||
self.woken_in_gesture.retain(|target| awake.contains(target));
|
||||
}
|
||||
|
||||
/// The woken targets, oldest first.
|
||||
@@ -733,7 +721,7 @@ impl SnapSession {
|
||||
Awake::Anchor { layer, .. } | Awake::Curve { layer, .. } | Awake::Box { layer } => !changed.contains(layer),
|
||||
Awake::Position { id, .. } => position_sources.get(id).is_none_or(|sources| !sources.iter().any(|layer| changed.contains(layer))),
|
||||
});
|
||||
self.forget_targets_gone_to_sleep();
|
||||
self.forget_sources_of_sleeping_positions();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1112,45 +1100,6 @@ mod tests {
|
||||
assert!(session.tick(1000 + WAKE_DWELL_IN_GESTURE));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_gesture_keeps_track_of_only_the_targets_it_woke_that_are_still_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
editor.draw_rect(500., 100., 700., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
|
||||
// Once the limit has put the first edge back to sleep, resting on it again wakes it a second time
|
||||
let along_edges = [(150., 100.), (300., 140.), (250., 240.), (100., 200.), (550., 100.), (700., 140.), (150., 100.)];
|
||||
for (index, position) in along_edges.into_iter().enumerate() {
|
||||
assert!(rest(&mut session, &editor, position.into(), index as u64 * 2000), "nothing woke at {position:?}");
|
||||
}
|
||||
assert_eq!(session.woken_in_gesture, session.awake);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn what_a_gesture_wakes_goes_back_to_sleep_when_it_ends_while_what_was_woken_before_it_stays_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(100., 100., 300., 240.).await;
|
||||
let mut session = SnapSession::default();
|
||||
|
||||
// The top edge is woken before the gesture, and the right edge during it
|
||||
assert!(rest(&mut session, &editor, DVec2::new(150., 100.), 0));
|
||||
let woken_before = session.awake.clone();
|
||||
|
||||
let input = InputPreprocessorMessageHandler::default();
|
||||
session.begin_gesture(SnapView::new(editor.active_document(), DOCUMENT, &input), Moving::default());
|
||||
snap_at_time(&mut session, &editor, DVec2::new(300., 140.), 2000);
|
||||
assert!(session.tick(2000 + WAKE_DWELL_IN_GESTURE));
|
||||
assert_eq!(session.awake.len(), 2);
|
||||
|
||||
session.end_gesture();
|
||||
assert_eq!(session.awake, woken_before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_the_latest_few_woken_targets_stay_awake() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
|
||||
@@ -29,8 +29,6 @@ pub struct GradientTool {
|
||||
#[derive(Default)]
|
||||
pub struct GradientOptions {
|
||||
gradient_form: GradientForm,
|
||||
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
@@ -94,16 +92,12 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
||||
GradientOptionsUpdate::Form(gradient_form) => {
|
||||
self.options.gradient_form = gradient_form;
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
apply_gradient_update(
|
||||
&mut self.data,
|
||||
context,
|
||||
responses,
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|
||||
|(_gradient, appearance)| {
|
||||
appearance.gradient_form = gradient_form;
|
||||
appearance.curvature_source = CurvatureSource::Form;
|
||||
},
|
||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|
||||
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|
||||
);
|
||||
responses.add(ToolMessage::UpdateHints);
|
||||
responses.add(ToolMessage::UpdateCursor);
|
||||
@@ -198,19 +192,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
||||
|
||||
let mut needs_refresh = false;
|
||||
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.curvature_source = appearance.curvature_source;
|
||||
needs_refresh = true;
|
||||
}
|
||||
if self.options.settings != appearance.settings {
|
||||
self.options.settings = appearance.settings;
|
||||
needs_refresh = true;
|
||||
}
|
||||
} else if self.options.curvature_source != CurvatureSource::Form {
|
||||
// With no gradient selected, the Form radio shows the form a new one gets
|
||||
self.options.curvature_source = CurvatureSource::Form;
|
||||
needs_refresh = true;
|
||||
}
|
||||
|
||||
let has_gradient = current_gradient.is_some();
|
||||
@@ -272,11 +261,7 @@ impl LayoutHolder for GradientTool {
|
||||
}
|
||||
.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(selected_form)
|
||||
.disabled(self.options.curvature_source == CurvatureSource::Graph)
|
||||
.widget_instance();
|
||||
let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
|
||||
|
||||
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||
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 gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
|
||||
|
||||
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
|
||||
return Some((
|
||||
gradient.stops,
|
||||
GradientAppearance {
|
||||
gradient_form,
|
||||
curvature_source,
|
||||
gradient_form: gradient.gradient_form,
|
||||
settings: gradient.settings,
|
||||
transform: gradient.transform,
|
||||
},
|
||||
@@ -421,48 +404,19 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
||||
struct GradientAppearance {
|
||||
transform: DAffine2,
|
||||
gradient_form: GradientForm,
|
||||
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
|
||||
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
|
||||
curvature_source: CurvatureSource,
|
||||
settings: GradientSettings,
|
||||
}
|
||||
|
||||
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum CurvatureSource {
|
||||
/// They make the form, or there's no node and the form's are implied.
|
||||
#[default]
|
||||
Form,
|
||||
/// They're values that make neither form.
|
||||
Custom,
|
||||
/// They're fed from the graph or exposed, so only the graph can change them.
|
||||
Graph,
|
||||
}
|
||||
|
||||
impl CurvatureSource {
|
||||
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
|
||||
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
|
||||
let form = curvatures.and_then(GradientForm::from_curvatures);
|
||||
let source = match (curvatures, form) {
|
||||
(None, _) => Self::Graph,
|
||||
(Some(_), None) => Self::Custom,
|
||||
(Some(_), Some(_)) => Self::Form,
|
||||
};
|
||||
(form.unwrap_or_default(), source)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
|
||||
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
||||
let target_input = gradient_chain_target_input(layer, network_interface);
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_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 gradient_form: Option<GradientForm> = None;
|
||||
let mut curvature_source = CurvatureSource::Form;
|
||||
|
||||
for node_id in network_interface
|
||||
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
||||
@@ -476,9 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
|
||||
(gradient_form, curvature_source) = (Some(form), source);
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -488,7 +444,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
GradientAppearance {
|
||||
transform: composed_transform,
|
||||
gradient_form: gradient_form.unwrap_or_default(),
|
||||
curvature_source,
|
||||
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -838,15 +793,12 @@ impl SelectedGradient {
|
||||
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
||||
if let Some(layer) = self.layer {
|
||||
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
|
||||
let write_form = self.dragging == GradientDragTarget::New;
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
|
||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
|
||||
} else {
|
||||
// Only a new gradient takes its form from the tool, as with a chain
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: self.gradient.clone(),
|
||||
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
|
||||
gradient_form: self.appearance.gradient_form,
|
||||
gradient_settings: self.appearance.settings,
|
||||
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.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque<Message>) {
|
||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||
responses.add(GraphOperationMessage::GradientCyclicSet {
|
||||
layer,
|
||||
gradient_cyclic: appearance.settings.cyclic,
|
||||
@@ -896,12 +848,10 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
|
||||
layer,
|
||||
transform: appearance.transform,
|
||||
});
|
||||
if write_form && appearance.curvature_source == CurvatureSource::Form {
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
}
|
||||
responses.add(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: appearance.gradient_form,
|
||||
});
|
||||
responses.add(GraphOperationMessage::GradientSpreadSet {
|
||||
layer,
|
||||
gradient_spread: appearance.settings.spread,
|
||||
@@ -1572,7 +1522,6 @@ impl Fsm for GradientToolFsmState {
|
||||
GradientAppearance {
|
||||
transform: DAffine2::IDENTITY,
|
||||
gradient_form: tool_options.gradient_form,
|
||||
curvature_source: CurvatureSource::Form,
|
||||
settings: tool_options.settings,
|
||||
},
|
||||
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
|
||||
@@ -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
|
||||
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, true, responses);
|
||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
|
||||
} else {
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient,
|
||||
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_settings: appearance.settings,
|
||||
transform: Some(appearance.transform),
|
||||
});
|
||||
@@ -2063,7 +2011,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
||||
responses.add(GraphOperationMessage::FillGradientSet {
|
||||
layer,
|
||||
gradient: new_gradient.clone(),
|
||||
gradient_form: None,
|
||||
gradient_form: appearance.gradient_form,
|
||||
gradient_settings: settings,
|
||||
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 crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
@@ -2168,8 +2115,8 @@ mod test_gradient {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use glam::DAffine2;
|
||||
use graph_craft::document::NodeInput;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeInput};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
||||
@@ -3419,7 +3366,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient 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.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3428,7 +3375,7 @@ mod test_gradient {
|
||||
})
|
||||
.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 network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3437,10 +3384,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.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");
|
||||
|
||||
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");
|
||||
}
|
||||
|
||||
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
|
||||
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
let dragged_end = end + offset;
|
||||
|
||||
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
|
||||
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
||||
editor
|
||||
.mouseup(
|
||||
EditorPointerState {
|
||||
editor_position: dragged_end,
|
||||
mouse_keys: MouseKeys::empty(),
|
||||
..Default::default()
|
||||
},
|
||||
ModifierKeys::empty(),
|
||||
)
|
||||
.await;
|
||||
|
||||
dragged_end
|
||||
}
|
||||
|
||||
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
|
||||
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
|
||||
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
let layer = create_gradient_list_layer(editor).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientTransformSet {
|
||||
layer,
|
||||
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
|
||||
})
|
||||
.await;
|
||||
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let curvature_node_id = network_interface
|
||||
.document_network()
|
||||
.nodes
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
|
||||
.expect("Gradient Curvature node should have been inserted");
|
||||
assert_eq!(
|
||||
curvature_inputs(editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"the inserted node should hold the radial form's curvatures"
|
||||
);
|
||||
|
||||
(layer, curvature_node_id)
|
||||
}
|
||||
|
||||
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
|
||||
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id: curvature_node_id,
|
||||
input_index,
|
||||
value: TaggedValue::Number(curvature).into(),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The start and end curvature inputs of a 'Gradient Curvature' node.
|
||||
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
}
|
||||
|
||||
/// The curvature inputs holding these values.
|
||||
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
|
||||
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
|
||||
}
|
||||
|
||||
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
|
||||
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
|
||||
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
|
||||
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
frontend_messages
|
||||
.iter()
|
||||
.rev()
|
||||
.filter_map(|message| match message {
|
||||
FrontendMessage::UpdateLayout {
|
||||
layout_target: LayoutTarget::ToolOptions,
|
||||
diff,
|
||||
} => Some(diff),
|
||||
_ => None,
|
||||
})
|
||||
.flat_map(|diff| diff.iter().rev())
|
||||
.find_map(|widget_diff| match &widget_diff.new_value {
|
||||
DiffUpdate::Widget(widget) => form_radio(widget),
|
||||
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
|
||||
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
|
||||
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
|
||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
||||
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
|
||||
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
editor
|
||||
.handle_message(GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding(GradientForm::Linear.curvatures()),
|
||||
"choosing the linear form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Linear.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
|
||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
||||
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
|
||||
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = document
|
||||
.network_interface
|
||||
.selected_nodes()
|
||||
.selected_layers(document.metadata())
|
||||
.next()
|
||||
.expect("the rectangle is selected");
|
||||
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
|
||||
let curvatures = |editor: &EditorTestUtils| {
|
||||
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
|
||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
||||
};
|
||||
|
||||
// Curvatures making neither form survive a drag of the gradient's end
|
||||
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
|
||||
let value = TaggedValue::Number(curvature).into();
|
||||
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
|
||||
}
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
|
||||
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
|
||||
|
||||
// Choosing a form in the control bar is what sets them
|
||||
let choose_form = |form| GradientToolMessage::UpdateOptions {
|
||||
options: super::GradientOptionsUpdate::Form(form),
|
||||
};
|
||||
editor.handle_message(choose_form(GradientForm::Radial)).await;
|
||||
assert_eq!(
|
||||
curvatures(&editor),
|
||||
inputs_holding(GradientForm::Radial.curvatures()),
|
||||
"choosing the radial form should set its curvatures"
|
||||
);
|
||||
|
||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
||||
editor.handle_message(choose_form(GradientForm::Linear)).await;
|
||||
let [start_input, end_input] = curvatures(&editor);
|
||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
||||
assert_eq!(
|
||||
end_input,
|
||||
inputs_holding(GradientForm::Radial.curvatures())[1],
|
||||
"the end curvature beside a wired one should stay as it was"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
|
||||
|
||||
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
|
||||
let document = editor.active_document();
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
||||
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
|
||||
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
||||
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
|
||||
editor.handle_message(GradientToolMessage::DoubleClick).await;
|
||||
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
|
||||
|
||||
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
|
||||
|
||||
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"recoloring the stop shouldn't reset the curvatures"
|
||||
);
|
||||
|
||||
editor.press(Key::Delete, ModifierKeys::empty()).await;
|
||||
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([0.5, 0.5]),
|
||||
"deleting the stop shouldn't reset the curvatures"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
|
||||
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
|
||||
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
|
||||
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
|
||||
|
||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"a drag shouldn't rewrite curvatures making the form"
|
||||
);
|
||||
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
||||
layer,
|
||||
gradient_form: GradientForm::Radial,
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
curvature_inputs(&editor, curvature_node_id),
|
||||
inputs_holding([1., 0.5]),
|
||||
"setting the form they make shouldn't rewrite them"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
||||
|
||||
// Reselecting the layer has the tool read its curvatures, which make neither form
|
||||
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
|
||||
|
||||
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((Some(GradientForm::Linear as u32), false)),
|
||||
"with nothing selected, the radio should show the linear form a new gradient gets"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
|
||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
||||
|
||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(number_node_id),
|
||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
||||
})
|
||||
.await;
|
||||
|
||||
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
assert_eq!(
|
||||
latest_form_radio(&frontend_messages),
|
||||
Some((None, true)),
|
||||
"a wired curvature should leave no form chosen and the radio disabled"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn drag_on_blank_layer_starts_gradient_chain() {
|
||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||
|
||||
@@ -12,7 +12,6 @@ use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::math::quad::Quad;
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
@@ -115,8 +114,7 @@ pub enum NodeGraphUpdate {
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
/// The SVG, `None` if the layers add nothing, or why it couldn't be rendered.
|
||||
svg: Result<Option<String>, String>,
|
||||
svg: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -231,28 +229,13 @@ impl NodeGraphExecutor {
|
||||
.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.
|
||||
/// The `viewport_size` is in viewport pixels.
|
||||
pub fn submit_clipboard_svg(&self, document: &DocumentMessageHandler, viewport_size: DVec2, id: u64) {
|
||||
let network_interface = &document.network_interface;
|
||||
let view = (document.metadata().document_to_viewport.inverse() * Quad::from_box([DVec2::ZERO, viewport_size])).bounding_box();
|
||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||
if document_id.is_none() || self.node_graph_document != document_id {
|
||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
||||
}
|
||||
|
||||
// Painted from the bottom up
|
||||
let selected = document.partition_selection().layers;
|
||||
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");
|
||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
||||
Message::NoOp
|
||||
}
|
||||
|
||||
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),
|
||||
}
|
||||
.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
|
||||
self.sender
|
||||
@@ -470,7 +474,7 @@ impl NodeGraphExecutor {
|
||||
ExecutionContext {
|
||||
export_config: Some(export_config),
|
||||
document_id,
|
||||
document_to_viewport: render_config.viewport.transform,
|
||||
document_to_viewport: viewport.transform,
|
||||
measure_fill: None,
|
||||
},
|
||||
));
|
||||
@@ -1196,28 +1200,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
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.
|
||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
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::runtime::AsyncRuntime;
|
||||
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::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 observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
@@ -52,8 +52,6 @@ pub struct NodeRuntime {
|
||||
pending_export: Option<ExecutionRequest>,
|
||||
pending_eyedropper: Option<ExecutionRequest>,
|
||||
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.
|
||||
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.
|
||||
@@ -61,6 +59,7 @@ pub struct NodeRuntime {
|
||||
async_runtime: Option<AsyncRuntime>,
|
||||
|
||||
editor_api: Arc<PlatformEditorApi>,
|
||||
resources: ResourceRegistry,
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
thumbnails: Thumbnails,
|
||||
@@ -108,39 +107,13 @@ pub enum GraphRuntimeRequest {
|
||||
key: ObservationKey,
|
||||
observation: Option<Observation>,
|
||||
},
|
||||
ClipboardSvg(ClipboardSvgRequest),
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
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,
|
||||
/// 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.
|
||||
output: OutputHandle,
|
||||
/// The compiled node giving what the copied layers add, whose bounds frame the SVG.
|
||||
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)]
|
||||
pub struct GraphUpdate {
|
||||
pub(super) network: NodeNetwork,
|
||||
@@ -185,9 +158,9 @@ impl NodeRuntime {
|
||||
pending_export: None,
|
||||
pending_eyedropper: None,
|
||||
pending_thumbnails: None,
|
||||
pending_clipboard: None,
|
||||
old_graph: None,
|
||||
compile_failed: false,
|
||||
resources: ResourceRegistry::default(),
|
||||
async_runtime: None,
|
||||
|
||||
editor_api: PlatformEditorApi {
|
||||
@@ -224,7 +197,6 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let mut graph = None;
|
||||
let mut clipboard = None;
|
||||
for request in self.receiver.try_iter() {
|
||||
match request {
|
||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
||||
@@ -251,8 +223,10 @@ impl NodeRuntime {
|
||||
self.observations_changed = true;
|
||||
}
|
||||
},
|
||||
// The clipboard waits only for its latest copy
|
||||
GraphRuntimeRequest::ClipboardSvg(request) => clipboard = Some(request),
|
||||
GraphRuntimeRequest::ClipboardSvg { id, layers } => {
|
||||
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) => {
|
||||
self.overlays = Some(context);
|
||||
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 {
|
||||
mut network,
|
||||
resources,
|
||||
@@ -279,8 +248,11 @@ impl NodeRuntime {
|
||||
apply_previews(&mut network, &previewed);
|
||||
write_layer_paths(&mut network, &layers);
|
||||
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();
|
||||
if result.is_ok() {
|
||||
self.thumbnails.update_sources(&layers, &network, &self.executor);
|
||||
@@ -333,10 +305,6 @@ impl NodeRuntime {
|
||||
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
|
||||
if self.overlays_stale {
|
||||
texture = self.composite_viewport_frame();
|
||||
@@ -430,70 +398,6 @@ impl NodeRuntime {
|
||||
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) {
|
||||
// Eyedropper should use the same time and pointer to not invalidate the cache
|
||||
if let Some(viewport) = self.pending {
|
||||
@@ -532,9 +436,9 @@ impl NodeRuntime {
|
||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||
Ok(Ok(Poll::Fallback(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())]))),
|
||||
Err(payload) => {
|
||||
let response = ExecutionResponse {
|
||||
@@ -602,121 +506,42 @@ impl NodeRuntime {
|
||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork, resources: &ResourceRegistry) -> 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)> {
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
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)) {
|
||||
return Err((e.to_string(), Vec::new()));
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
}
|
||||
|
||||
// We assume only one output
|
||||
assert_eq!(scoped_network.exports.len(), 1, "Graph with multiple outputs not yet handled");
|
||||
|
||||
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,
|
||||
Err(CompileError::Graph(errors)) => return Err((format!("{errors:?}"), errors)),
|
||||
Err(CompileError::Message(message)) => return Err((message, Vec::new())),
|
||||
Err(CompileError::Graph(errors)) => {
|
||||
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?");
|
||||
Ok(compiled_network)
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
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, output: NodeId, error: &NodeError) -> EvaluationErrors {
|
||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
||||
let source_map = self.executor.tree().source_map();
|
||||
let paths = |node: NodeId| -> NodePaths {
|
||||
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
||||
@@ -724,6 +549,7 @@ impl NodeRuntime {
|
||||
paths.into()
|
||||
};
|
||||
let mut errors = Vec::new();
|
||||
let output = self.output.node();
|
||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||
while let Some((mut trace, node, error)) = pending.pop() {
|
||||
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> {
|
||||
match poll {
|
||||
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}");
|
||||
}
|
||||
|
||||
#[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]
|
||||
async fn exporting_a_graph_that_fails_to_compile_says_it_failed() {
|
||||
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 atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
@@ -12,8 +12,8 @@ use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::Render;
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
@@ -276,11 +276,11 @@ impl ThumbnailContent {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area the content covers once rendered.
|
||||
fn content_bounds(&self) -> RenderBoundingBox {
|
||||
/// 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, maps_resolved: bool) -> RenderBoundingBox {
|
||||
match self {
|
||||
// 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
|
||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||
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.
|
||||
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,
|
||||
_ => [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.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
@@ -329,6 +361,25 @@ fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
||||
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
|
||||
/// so the input's extent is always preserved.
|
||||
fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
@@ -347,7 +398,8 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, shipped_node_id};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{FlowType, NodeTemplateImplementation, shipped_node_id};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
@@ -378,8 +430,20 @@ mod tests {
|
||||
editor.draw_rect(0., 0., 10., 10.).await;
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
// The node adding Merge's content to the stack
|
||||
let Some(NodeTemplateImplementation::Network(merge_network)) = resolve_network_node_type("Merge").map(|merge| &merge.node_template.implementation) else {
|
||||
panic!("Merge should be a network node")
|
||||
};
|
||||
let Some((&extend_id, _)) = merge_network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == NodeTemplateImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER))
|
||||
else {
|
||||
panic!("Merge should extend the stack with its content")
|
||||
};
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", extend_id))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -63,6 +63,7 @@ pub fn draw_atlas(scene: &mut VelloSceneBuilder, layout: &ThumbnailAtlasLayout,
|
||||
let render_params = RenderParams {
|
||||
footprint: Footprint::BOUNDLESS,
|
||||
render_output_type: RenderOutputType::Vello,
|
||||
thumbnail: true,
|
||||
..Default::default()
|
||||
};
|
||||
let cell_size = layout.cell_size.as_dvec2();
|
||||
|
||||
@@ -117,17 +117,10 @@ impl EditorTestUtils {
|
||||
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);
|
||||
for _ in 0..100 {
|
||||
self.runtime.update();
|
||||
self.runtime.run().await;
|
||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||
|
||||
if frontend_messages.iter().any(|message| matches!(message, FrontendMessage::TriggerClipboardWrite { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.runtime.update();
|
||||
self.runtime.run().await;
|
||||
frontend_messages.extend(self.dispatch(Message::Wake));
|
||||
|
||||
frontend_messages
|
||||
.into_iter()
|
||||
|
||||
@@ -2,8 +2,6 @@
|
||||
import { getContext, onMount, onDestroy } from "svelte";
|
||||
import LayoutCol from "/src/components/layout/LayoutCol.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 { createAutoScroller } from "/src/utility-functions/auto-scroll";
|
||||
import type { EditorWrapper } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
@@ -25,15 +23,7 @@
|
||||
let lastDragClientY = 0;
|
||||
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(() => {
|
||||
createDragToggleManager(dragToggleListener);
|
||||
|
||||
addEventListener("pointermove", draggingPointerMove);
|
||||
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
|
||||
@@ -46,8 +36,6 @@
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
destroyDragToggleManager(dragToggleListener);
|
||||
|
||||
removeEventListener("pointermove", draggingPointerMove);
|
||||
removeEventListener("pointerup", draggingPointerUp);
|
||||
removeEventListener("pointercancel", abortDrag);
|
||||
|
||||
@@ -331,7 +331,6 @@
|
||||
}
|
||||
|
||||
const dragToggleListener: DragToggleListener = {
|
||||
groups: ["layer-visibility", "layer-lock", "layer-chain-visibility"],
|
||||
activeGroupChanged: (group) => {
|
||||
activeDragToggleGroup = group;
|
||||
},
|
||||
@@ -343,15 +342,6 @@
|
||||
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) {
|
||||
editor.toggleLayerLock(id);
|
||||
}
|
||||
@@ -1204,7 +1194,6 @@
|
||||
on:pointerdown={(e) => layerPointerDown(e, listing)}
|
||||
on:click={(e) => selectLayerWithModifiers(e, listing)}
|
||||
on:dblclick={(e) => chainIconsDoubleClick(e, listing)}
|
||||
on:auxclick={(e) => chainIconsAuxClick(e, listing)}
|
||||
on:pointerenter={() => hoverRow(index)}
|
||||
on:pointerleave={() => (hoveredRowIndex = undefined)}
|
||||
>
|
||||
@@ -1354,8 +1343,6 @@
|
||||
data-chain-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
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}
|
||||
@@ -1372,17 +1359,12 @@
|
||||
: entry.chainExpanded
|
||||
? "Stop listing this layer's chain one node per row."
|
||||
: "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) => {
|
||||
// Without a chain to expand, a click selects the layer as it does elsewhere in the row
|
||||
if (entry.chainNodes.length === 0) return;
|
||||
e.stopPropagation();
|
||||
editor.toggleLayerChainExpanded(listing.id);
|
||||
}}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(listing.id);
|
||||
}}
|
||||
>
|
||||
<IconLabel
|
||||
icon={entry.iconName}
|
||||
@@ -1413,15 +1395,10 @@
|
||||
data-chain-row-node={slot.nodeIndex}
|
||||
data-chain-gap-before={slot.reorderablePosition}
|
||||
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) => {
|
||||
if (e.button === 0 && draggable) chainNodePointerDown(e, listing, chainNode);
|
||||
}}
|
||||
on:click={(e) => chainNodeClick(e, listing, chainNode.id)}
|
||||
on:auxclick={(e) => {
|
||||
if (e.button === 1) toggleNodeVisibilityLayerPanel(chainNode.id);
|
||||
}}
|
||||
on:dblclick={(e) => {
|
||||
// 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);
|
||||
|
||||
@@ -41,12 +41,6 @@
|
||||
const accel = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
|
||||
editor.toggleNodeInspectorSectionExpanded(widgetData.id, e.altKey || accel);
|
||||
}
|
||||
|
||||
function toggleVisibilityWithMiddleClick(e: MouseEvent) {
|
||||
if (e.button !== 1 || widgetData.disabled) return;
|
||||
|
||||
editor.toggleNodeVisibilityInspector(widgetData.id);
|
||||
}
|
||||
</script>
|
||||
|
||||
<!-- TODO: Implement collapsable sections with the Inspector system -->
|
||||
@@ -82,16 +76,7 @@
|
||||
{/if}
|
||||
{/each}
|
||||
{:else}
|
||||
<button
|
||||
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}
|
||||
>
|
||||
<button class="header" class:expanded class:expandable data-inspector-reorder-handle={reorderable ? "" : undefined} onclick={toggleExpandedWithModifiers}>
|
||||
<div
|
||||
class="icon-slot"
|
||||
data-tooltip-label={!expandable ? undefined : expanded ? "Collapse (All)" : "Expand (All)"}
|
||||
@@ -558,10 +543,9 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -140,9 +140,7 @@
|
||||
const reorder = allowReorder && allowSelect;
|
||||
let held = position;
|
||||
|
||||
if (!reorder && !allowWrap && markers.some((marker) => marker.overlapNext !== "Never")) {
|
||||
held = holdWithOverlaps(first, last, position);
|
||||
} else if (!reorder && !allowWrap) {
|
||||
if (!reorder && !allowWrap) {
|
||||
const lower = neighborBound(first, -1) ?? 0;
|
||||
const upper = (neighborBound(last, 1) ?? 1) - spacing;
|
||||
held = Math.max(lower, Math.min(upper, position));
|
||||
@@ -158,33 +156,6 @@
|
||||
return wrap ? held - Math.floor(held) : Math.max(0, Math.min(1 - spacing, held));
|
||||
}
|
||||
|
||||
// Holds markers `first..=last` moving to `position` within the track and each member's bounds from the markers outside the run, as the backend's `overlap_bounds` gives them
|
||||
function holdWithOverlaps(first: number, last: number, position: number): number {
|
||||
const outsideRun = (i: number) => i >= 0 && i < markers.length && (i < first || i > last);
|
||||
const overlap = (i: number) => (i >= 0 && i < markers.length ? markers[i].overlapNext : "Never");
|
||||
const boundsBeyond = (near: number, far: number) => (overlap(near) === "NextOnly" || overlap(far) === "NextOnly") && overlap(near) !== "Freely" && overlap(far) !== "Freely";
|
||||
|
||||
let lower = 0;
|
||||
let upper = 1;
|
||||
for (let k = first; k <= last; k += 1) {
|
||||
const offset = markers[k].position - markers[first].position;
|
||||
lower = Math.max(lower, -offset);
|
||||
upper = Math.min(upper, 1 - offset);
|
||||
|
||||
// A neighbor bounds the marker unless they overlap, and past a neighbor overlapping only its next, so does the marker beyond it
|
||||
const lowerBounds = [overlap(k - 1) === "Never" ? k - 1 : -1, boundsBeyond(k - 1, k - 2) ? k - 2 : -1];
|
||||
const upperBounds = [overlap(k) === "Never" ? k + 1 : -1, boundsBeyond(k, k + 1) ? k + 2 : -1];
|
||||
lowerBounds.filter(outsideRun).forEach((i) => {
|
||||
lower = Math.max(lower, markers[i].position - offset);
|
||||
});
|
||||
upperBounds.filter(outsideRun).forEach((i) => {
|
||||
upper = Math.min(upper, markers[i].position - offset);
|
||||
});
|
||||
}
|
||||
|
||||
return Math.max(lower, Math.min(upper, position));
|
||||
}
|
||||
|
||||
// The position of the nearest marker past `index` in the direction of `step` that bounds others, skipping any placed between its neighbors since those follow them instead
|
||||
function neighborBound(index: number, step: -1 | 1): number | undefined {
|
||||
for (let i = index + step; i >= 0 && i < markers.length; i += step) {
|
||||
@@ -686,10 +657,7 @@
|
||||
}
|
||||
$: midpointPositions = diamondPositions(markers, showMidpoints, trackCyclic, trackInterpolation);
|
||||
$: strips = markerSpans(markers, allowWrap, (marker) => marker.pairedWithNext);
|
||||
// A dashed link vanishes while the markers it joins have overlapped past each other, leaving no span between them
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext).filter(
|
||||
({ index }) => markers[index].overlapNext === "Never" || markers[index + 1].position >= markers[index].position,
|
||||
);
|
||||
$: dashes = markerSpans(markers, allowWrap, (marker) => marker.dashedToNext);
|
||||
|
||||
onMount(() => {
|
||||
document.addEventListener("keydown", deleteShortcut);
|
||||
|
||||
@@ -191,6 +191,7 @@ import NodeFlattenGradient from "/../branding/assets/16x16-nodes/node-flatten-gr
|
||||
import NodeFlattenRaster from "/../branding/assets/16x16-nodes/node-flatten-raster.svg";
|
||||
import NodeFlattenVector from "/../branding/assets/16x16-nodes/node-flatten-vector.svg";
|
||||
import NodeFloor from "/../branding/assets/16x16-nodes/node-floor.svg";
|
||||
import NodeFootprintValue from "/../branding/assets/16x16-nodes/node-footprint-value.svg";
|
||||
import NodeFormatJson from "/../branding/assets/16x16-nodes/node-format-json.svg";
|
||||
import NodeFormatNumber from "/../branding/assets/16x16-nodes/node-format-number.svg";
|
||||
import NodeGammaCorrection from "/../branding/assets/16x16-nodes/node-gamma-correction.svg";
|
||||
@@ -484,6 +485,7 @@ export const ICON_16X16_NODES = {
|
||||
NodeFlattenRaster: { svg: NodeFlattenRaster, size: 16 },
|
||||
NodeFlattenVector: { svg: NodeFlattenVector, size: 16 },
|
||||
NodeFloor: { svg: NodeFloor, size: 16 },
|
||||
NodeFootprintValue: { svg: NodeFootprintValue, size: 16 },
|
||||
NodeFormatJson: { svg: NodeFormatJson, size: 16 },
|
||||
NodeFormatNumber: { svg: NodeFormatNumber, size: 16 },
|
||||
NodeGammaCorrection: { svg: NodeGammaCorrection, size: 16 },
|
||||
|
||||
@@ -8,30 +8,21 @@
|
||||
// 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
|
||||
// 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 = {
|
||||
// The groups whose gestures this listener is told about
|
||||
groups: string[];
|
||||
// Given the group of the pressed button, and undefined once the press ends
|
||||
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
|
||||
engagedChanged?: (engaged: boolean) => void;
|
||||
};
|
||||
|
||||
const MIDDLE_BUTTON = 1;
|
||||
|
||||
const listeners = new Set<DragToggleListener>();
|
||||
let activeGroup: string | undefined = undefined;
|
||||
let middleButtonGesture = false;
|
||||
let source: HTMLElement | undefined = undefined;
|
||||
let startingState: string | undefined = undefined;
|
||||
let visited = new WeakSet<Element>();
|
||||
let engaged = false;
|
||||
let suppressNextClickFromSource: HTMLElement | undefined = undefined;
|
||||
let suppressNextAuxClick = false;
|
||||
|
||||
export function createDragToggleManager(listener: DragToggleListener) {
|
||||
listeners.add(listener);
|
||||
@@ -47,13 +38,12 @@ export function createDragToggleManager(listener: DragToggleListener) {
|
||||
window.addEventListener("blur", onPointerUp);
|
||||
// Capture phase on click suppresses the natural source-click before the button's handler runs
|
||||
window.addEventListener("click", onClickCapture, true);
|
||||
window.addEventListener("auxclick", onAuxClickCapture, true);
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyDragToggleManager(listener: DragToggleListener) {
|
||||
// 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);
|
||||
|
||||
// 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("blur", onPointerUp);
|
||||
window.removeEventListener("click", onClickCapture, true);
|
||||
window.removeEventListener("auxclick", onAuxClickCapture, true);
|
||||
|
||||
activeGroup = undefined;
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
}
|
||||
}
|
||||
|
||||
function listenersOfGroup(group: string): DragToggleListener[] {
|
||||
return Array.from(listeners).filter((listener) => listener.groups.includes(group));
|
||||
}
|
||||
|
||||
function notifyActiveGroupChange(group: string | undefined) {
|
||||
const previousGroup = activeGroup;
|
||||
activeGroup = group;
|
||||
|
||||
const notifiedGroup = group || previousGroup;
|
||||
if (notifiedGroup) listenersOfGroup(notifiedGroup).forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
listeners.forEach((listener) => listener.activeGroupChanged?.(group));
|
||||
}
|
||||
|
||||
function groupAttribute(middleButton: boolean): string {
|
||||
return middleButton ? "data-middle-drag-toggle-group" : "data-drag-toggle-group";
|
||||
}
|
||||
|
||||
function findMember(target: EventTarget | undefined, middleButton: boolean): HTMLElement | undefined {
|
||||
function findMember(target: EventTarget | undefined): HTMLElement | 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;
|
||||
}
|
||||
|
||||
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) {
|
||||
if (e.button !== 0 && e.button !== MIDDLE_BUTTON) return;
|
||||
if (e.button !== 0) return;
|
||||
suppressNextClickFromSource = undefined;
|
||||
suppressNextAuxClick = false;
|
||||
|
||||
const middleButton = e.button === MIDDLE_BUTTON;
|
||||
const found = findMember(e.target || undefined, middleButton);
|
||||
const found = findMember(e.target || undefined);
|
||||
if (!found) return;
|
||||
|
||||
// Stop the event so sibling drag/select handlers on ancestors don't also engage
|
||||
e.stopPropagation();
|
||||
|
||||
middleButtonGesture = middleButton;
|
||||
source = found;
|
||||
startingState = memberState(found);
|
||||
startingState = found.getAttribute("data-drag-toggle-state") || undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(found.getAttribute(groupAttribute(middleButton)) || undefined);
|
||||
|
||||
if (middleButton) engage();
|
||||
notifyActiveGroupChange(found.getAttribute("data-drag-toggle-group") || undefined);
|
||||
}
|
||||
|
||||
function onPointerMove(e: PointerEvent) {
|
||||
if (!activeGroup || !source) return;
|
||||
|
||||
const member = findMember(e.target || undefined, middleButtonGesture);
|
||||
if (!member || member.getAttribute(groupAttribute(middleButtonGesture)) !== activeGroup) return;
|
||||
const member = findMember(e.target || undefined);
|
||||
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
|
||||
if (member === source || visited.has(member)) return;
|
||||
|
||||
// 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
|
||||
if (memberState(member) !== startingState) return;
|
||||
if ((member.getAttribute("data-drag-toggle-state") || undefined) !== startingState) return;
|
||||
|
||||
visited.add(member);
|
||||
toggle(member);
|
||||
member.click();
|
||||
}
|
||||
|
||||
function onPointerUp(e: Event) {
|
||||
if (!activeGroup) return;
|
||||
const endedGroup = activeGroup;
|
||||
|
||||
// An engaged drag already toggled the source, so its release's click won't toggle it again
|
||||
if (engaged && source && e.type === "pointerup") {
|
||||
if (middleButtonGesture) suppressNextAuxClick = true;
|
||||
else suppressNextClickFromSource = source;
|
||||
}
|
||||
// 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") suppressNextClickFromSource = source;
|
||||
const wasEngaged = engaged;
|
||||
|
||||
middleButtonGesture = false;
|
||||
source = undefined;
|
||||
startingState = undefined;
|
||||
visited = new WeakSet();
|
||||
engaged = false;
|
||||
|
||||
notifyActiveGroupChange(undefined);
|
||||
if (wasEngaged) listenersOfGroup(endedGroup).forEach((listener) => listener.engagedChanged?.(false));
|
||||
if (wasEngaged) listeners.forEach((listener) => listener.engagedChanged?.(false));
|
||||
}
|
||||
|
||||
function onClickCapture(e: Event) {
|
||||
@@ -188,15 +141,6 @@ function onClickCapture(e: Event) {
|
||||
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
|
||||
import.meta.hot?.accept((newModule) => {
|
||||
const carried = Array.from(listeners);
|
||||
|
||||
+24
-2
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
None of these definitions are written by hand. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`. A built-in node made from a subgraph has its definition generated from the `graph` macro (see [Creating a node from a subgraph](#creating-a-node-from-a-subgraph)), keyed by its name.
|
||||
|
||||
## Inspector
|
||||
|
||||
@@ -127,7 +127,29 @@ fn opacity<T>(
|
||||
|
||||
## Additional Macro Options
|
||||
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `unit`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, while `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
The macro invocation can be extended with additional attributes. The currently supported attributes are (`name`, `path`, `skip_impl`, `category`). When using generics the `#[implementations()]` attribute can be used to automatically populate the node_registry for you. You can also use the `default`, `expose`, `soft`, `hard`, `range`, `step`, `display_decimal_places`, `unit`, `integer`, `labels`, `blank_assist`, `multiline`, and `progression` attributes to influence how the Inspector widgets are generated. The `#[unit("...")]` attribute appends a suffix like `%` or ` px` to a number's widget, `#[display_decimal_places(2)]` sets how many decimal places a number's widget shows, `#[integer]` makes a number or Vec2 widget take only integers, `#[labels("W", "H")]` names a Vec2 widget's two fields, and `#[blank_assist(false)]` drops the space a widget leaves for its assist area. `#[multiline]` gives a `String` the text area widget and `#[progression]` splits a number into its whole and fractional parts. The `#[soft(a..b)]` and `#[hard(a..b)]` attributes set the slider's suggested extent and its enforced clamp, respectively (either endpoint may be omitted, e.g. `0..` or `..100`; both endpoints are inclusive, so there is no `..=` form), and `#[range]` renders the input as a draggable slider. Values typed into the input may exceed the soft extent but are clamped to the hard bounds, so `#[soft]` is only meaningful together with `#[range]`.
|
||||
|
||||
## Creating a node from a subgraph
|
||||
|
||||
A node built from other nodes uses the `graph` macro, which registers the subgraph as a catalog definition. It takes `category`, `icon`, `name`, and `version` as `node` does, plus `layer` for a node that starts as a layer. Unlike a proto node's, a graph's name (or the title derived from its function name) is also its catalog identifier, which documents store. The function's parameters are the subgraph's imports, which are parsed like a proto node's parameters and take the same value and widget attributes. On an import, `#[hard]` bounds the Inspector widget without clamping a value wired into it. `out!(...)` names the exports. In the body, `>>` feeds its left side into the primary input of the node on its right, every other parameter is named in the call, and a bare name feeds the binding or import of that name into the parameter of the same name. State methods after a call, each written once, set the node's position in grid units (`.at(x, y)`), its display name (`.named("…")`), its flags (`.layer()`, `.hidden()`, `.locked()`, and `.pinned()`), and its call argument (`.call_argument::<Footprint>()`, or `impl Any` for a generic one). An output's name after the call or a binding, like `.captures`, wires from that output instead of the primary one, and goes after any state methods. The body ends with one value per export, as a final expression or with `return`. This is the Load Image node as it exists in `node-graph/nodes/gstd/src/subgraphs.rs`:
|
||||
|
||||
```rs
|
||||
/// Loads an image from a given URL.
|
||||
#[node_macro::graph(category("Data: I/O"), icon("NodeLoadImage"))]
|
||||
pub fn load_image(
|
||||
_: (),
|
||||
/// The web address or local asset path of the image to load.
|
||||
#[name("URL")]
|
||||
url: Item<String>,
|
||||
) -> out!(
|
||||
/// The loaded image.
|
||||
image,
|
||||
) {
|
||||
load_resource(url).at(0, 0) >> bytes_to_image().at(7, 0)
|
||||
}
|
||||
```
|
||||
|
||||
Each node, parameter, and output name resolves through the module the `node` or `graph` macro generates for that node, named after its function, so a misspelled one is reported where it's written. The module's `PARAMETER_COUNT` lets the macro reject `>>` into a node with no parameters. Proto nodes don't name their outputs in that module, so only a graph's outputs can be chosen by name. Every input a call leaves out keeps the default from the node's own definition.
|
||||
|
||||
## Executing a document `NodeNetwork`
|
||||
|
||||
|
||||
@@ -360,11 +360,15 @@ impl NodeNetwork {
|
||||
};
|
||||
let value_node_id = gen_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]],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if let Some(path) = &mut original_location.path {
|
||||
path.push(value_node_id);
|
||||
}
|
||||
collection.insert(
|
||||
merged_node_id,
|
||||
DocumentNode {
|
||||
|
||||
@@ -63,6 +63,7 @@ fn flatten_add_expected() -> NodeNetwork {
|
||||
inputs: vec![NodeInput::value(TaggedValue::Integer(2), false)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("core_types::value::ClonedNode")),
|
||||
original_location: OriginalLocation {
|
||||
path: Some(vec![NodeId(4)]),
|
||||
dependants: vec![vec![NodeId(10)]],
|
||||
..Default::default()
|
||||
},
|
||||
|
||||
@@ -5,13 +5,14 @@ use brush_nodes::{BrushCache, Stroke};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List, NodeIdPath};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use core_types::transform::Footprint;
|
||||
use core_types::{CacheHash, Color, ContextModification, MemoHash, Node, Poll, RuntimeHandle, SourceId, Type, TypeDescriptor};
|
||||
pub use dyn_any::StaticType;
|
||||
pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_application_io::resource::ResourceHash;
|
||||
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::style::DashPattern;
|
||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||
@@ -74,7 +75,7 @@ macro_rules! tagged_value {
|
||||
TypeDefault(Type),
|
||||
/// Stored compactly as a `Vec<f64>`, materializes as `List<f64>` at runtime via `to_dynany`/`to_any`. Aliases recover legacy on-disk shapes.
|
||||
#[serde(deserialize_with = "core_types::misc::migrate_to_numbers")] // TODO: Eventually remove this document upgrade code
|
||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4", alias = "Footprint")]
|
||||
#[serde(alias = "F64Array", alias = "F64Table", alias = "VecF64", alias = "VecF32", alias = "F64Array4")]
|
||||
Numbers(Vec<f64>),
|
||||
/// Stored compactly as a `Vec<f64>` of dash lengths, materializes as an `Item<DashPattern>` at runtime via `to_dynany`/`to_any`.
|
||||
DashPattern(Vec<f64>),
|
||||
@@ -399,11 +400,6 @@ macro_rules! tagged_value {
|
||||
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
|
||||
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 {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -420,9 +416,6 @@ macro_rules! tagged_value {
|
||||
if **element == concrete!(Stroke) {
|
||||
return Some(TaggedValue::Strokes(Vec::new()));
|
||||
}
|
||||
if **element == concrete!(Pixels) {
|
||||
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
||||
}
|
||||
macro_rules! check {
|
||||
($type_default:ty) => {
|
||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||
@@ -513,6 +506,7 @@ tagged_value! {
|
||||
#[serde(alias = "ColorTable", alias = "OptionalColor", alias = "ColorNotInTable")]
|
||||
Color(Color),
|
||||
Font(Font),
|
||||
Footprint(Footprint),
|
||||
VectorModification(Box<VectorModification>),
|
||||
ImageData(Image<Color>),
|
||||
Resource(ResourceId),
|
||||
@@ -557,7 +551,6 @@ tagged_value! {
|
||||
WarpStyle(graphic_types::WarpStyle),
|
||||
WaveType(graphic_types::WaveType),
|
||||
DisplaceMode(graphic_types::DisplaceMode),
|
||||
BlendIfChannel(graphic_types::BlendIfChannel),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -576,7 +569,6 @@ tagged_value! {
|
||||
StrokeAlign(vector::style::StrokeAlign),
|
||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||
GradientForm(vector::style::GradientForm),
|
||||
GradientModel(vector::style::GradientModel),
|
||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||
GradientSpread(vector::style::GradientSpread),
|
||||
GradientSpace(vector::style::GradientSpace),
|
||||
@@ -704,6 +696,17 @@ impl TaggedValue {
|
||||
Some(DAffine2::from_scale_angle_translation(DVec2::new(width, height), 0., DVec2::new(x, y)))
|
||||
}
|
||||
|
||||
// The Inspector's X, Y, W, H, rendered at 100% resolution
|
||||
fn to_footprint(input: &str) -> Option<Footprint> {
|
||||
let transform = to_daffine2(input)?;
|
||||
|
||||
Some(Footprint {
|
||||
transform,
|
||||
resolution: transform.matrix2.diagonal().as_uvec2(),
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
@@ -779,6 +782,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
||||
@@ -1134,6 +1138,20 @@ mod number_default_parsing {
|
||||
assert_eq!(TaggedValue::from_primitive_string("- 1., 2.", &item!(DVec2)), Some(TaggedValue::DVec2(DVec2::new(-1., 2.))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn footprint_defaults_parse_as_x_y_width_height() {
|
||||
let expected = Footprint {
|
||||
transform: DAffine2::from_scale_angle_translation(DVec2::new(10_000., 500.), 0., DVec2::new(-50., 20.)),
|
||||
resolution: glam::UVec2::new(10_000, 500),
|
||||
..Default::default()
|
||||
};
|
||||
assert_eq!(
|
||||
TaggedValue::from_primitive_string("- 50., 20., 10_000., 500.", &item!(Footprint)),
|
||||
Some(TaggedValue::Footprint(expected))
|
||||
);
|
||||
assert_eq!(TaggedValue::from_primitive_string("1., 2., 3.", &item!(Footprint)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_defaults_parse_as_x_y_width_height() {
|
||||
let expected = DAffine2::from_scale_angle_translation(DVec2::new(500., 400.), 0., DVec2::new(250., -20.));
|
||||
@@ -1275,29 +1293,3 @@ mod retired_numeric_variants {
|
||||
assert_ne!(load(serde_json::json!({ "F32": 2.2 })), TaggedValue::Number(2.2_f32 as f64));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
#[cfg(test)]
|
||||
mod retired_footprint_variant {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn a_footprint_reads_as_its_transform_then_its_resolution() {
|
||||
let payload = serde_json::json!({ "Footprint": { "transform": [500., 0., 0., 250., -20., 40.], "resolution": [64, 32], "quality": "Full" } });
|
||||
let expected = TaggedValue::Numbers(vec![500., 0., 0., 250., -20., 40., 64., 32.]);
|
||||
|
||||
let legacy = deserialize_tagged_value_with_legacy_migration(payload.clone()).expect("The footprint payload should deserialize");
|
||||
assert_eq!(*legacy.into_inner(), expected);
|
||||
|
||||
let stored: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||
assert_eq!(stored, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_in_a_footprint_transform_reads_as_zero() {
|
||||
let payload = serde_json::json!({ "Footprint": { "transform": [1., 0., 0., 1., null, 0.], "resolution": [64, 32], "quality": "Full" } });
|
||||
let loaded: TaggedValue = serde_json::from_value(payload).expect("The footprint payload should deserialize");
|
||||
|
||||
assert_eq!(loaded, TaggedValue::Numbers(vec![1., 0., 0., 1., 0., 0., 64., 32.]));
|
||||
}
|
||||
}
|
||||
@@ -65,23 +65,17 @@ impl DynamicExecutor {
|
||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||
#[cfg_attr(debug_assertions, inline(never))]
|
||||
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();
|
||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
||||
}
|
||||
|
||||
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() }))
|
||||
}
|
||||
|
||||
/// Adds the [`ProtoNetwork`] of an output held beside the one the editor shows, reusing nodes where possible.
|
||||
/// 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)> {
|
||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
||||
self.typing_context.update(&proto_network).map_err(|e| {
|
||||
// If there is an error then get types that have been resolved before the error
|
||||
let add = proto_network
|
||||
@@ -104,10 +98,7 @@ impl DynamicExecutor {
|
||||
})?;
|
||||
|
||||
let output = proto_network.output;
|
||||
let add = self
|
||||
.tree
|
||||
.update(proto_network, &self.typing_context, records_paths)
|
||||
.map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
||||
self.outputs.retain(|output| output.strong_count() > 0);
|
||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||
let output = held.unwrap_or_else(|| {
|
||||
@@ -301,22 +292,20 @@ impl BorrowTree {
|
||||
pub fn new(proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<BorrowTree, GraphErrors> {
|
||||
let mut nodes = BorrowTree::default();
|
||||
for (id, node) in proto_network.nodes {
|
||||
nodes.push_node(id, node, typing_context, true)?
|
||||
nodes.push_node(id, node, typing_context)?
|
||||
}
|
||||
Ok(nodes)
|
||||
}
|
||||
|
||||
/// Pushes new nodes into the tree, giving back the document paths whose entries in the source map changed, if it `records_paths`.
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext, records_paths: bool) -> Result<Vec<Path>, GraphErrors> {
|
||||
/// Pushes new nodes into the tree
|
||||
pub fn update(&mut self, proto_network: ProtoNetwork, typing_context: &TypingContext) -> Result<Vec<Path>, GraphErrors> {
|
||||
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.
|
||||
for (id, node) in proto_network.nodes {
|
||||
if !self.nodes.contains_key(&id) {
|
||||
if records_paths {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
}
|
||||
self.push_node(id, node, typing_context, records_paths)?;
|
||||
} else if records_paths && self.update_source_map(id, typing_context, &node) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
self.push_node(id, node, typing_context)?;
|
||||
} else if self.update_source_map(id, typing_context, &node) {
|
||||
new_nodes.push(node.original_location.path.clone().unwrap_or_default().into());
|
||||
}
|
||||
}
|
||||
@@ -523,16 +512,14 @@ impl BorrowTree {
|
||||
///
|
||||
/// # 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:
|
||||
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
|
||||
/// - `Nodes`: Constructs a node using other nodes as dependencies.
|
||||
/// - 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.
|
||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext, records_path: bool) -> Result<(), GraphErrors> {
|
||||
if records_path {
|
||||
self.update_source_map(id, typing_context, &proto_node);
|
||||
}
|
||||
fn push_node(&mut self, id: NodeId, proto_node: ProtoNode, typing_context: &TypingContext) -> Result<(), GraphErrors> {
|
||||
self.update_source_map(id, typing_context, &proto_node);
|
||||
self.context_features.insert(id, proto_node.upstream_context_features);
|
||||
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 val_1_protonode = ProtoNode::value(ConstructionArgs::Value(TaggedValue::Integer(2_i64).into()), vec![]);
|
||||
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 result: Option<Item<i64>> = tree.eval(NodeId(0), &());
|
||||
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.
|
||||
|
||||
use crate::node_registry::NODE_REGISTRY;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||
use graph_craft::{ProtoNodeIdentifier, Type, concrete, list};
|
||||
use graphene_std::graphic::{as_graphic, extend, write_layer_path};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::graphic::{extend, write_layer_path};
|
||||
use graphene_std::list::NodeIdPath;
|
||||
use graphene_std::{Artboard, Graphic, NodeParameter};
|
||||
use std::collections::HashMap;
|
||||
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.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CarriesLayerPath {
|
||||
@@ -342,6 +236,14 @@ mod tests {
|
||||
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 {
|
||||
DocumentNode {
|
||||
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");
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)));
|
||||
}
|
||||
}
|
||||
@@ -21,15 +21,15 @@ use graphene_std::render_node::RenderIntermediate;
|
||||
use graphene_std::text::{Font, TextAlign};
|
||||
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
|
||||
use graphene_std::transfer_curve::TransferCurve;
|
||||
use graphene_std::transform::{ReferencePoint, ScaleType};
|
||||
use graphene_std::transform::{Footprint, ReferencePoint, ScaleType};
|
||||
use graphene_std::vector::misc::{
|
||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||
WeldMethod,
|
||||
};
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use graphene_std::{DisplaceMode, RadialBlurMethod, WaveType};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
@@ -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<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientForm>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
||||
@@ -87,6 +88,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||
@@ -269,7 +271,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
GradientForm,
|
||||
GradientModel,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -302,7 +303,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
WarpStyle,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
BlendIfChannel,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -346,6 +346,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
DAffine2,
|
||||
bool,
|
||||
NodeIdPath,
|
||||
Footprint,
|
||||
Artboard,
|
||||
));
|
||||
node_types.extend(ranked_value_types!(rank_adapter_nodes));
|
||||
@@ -379,6 +380,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
DVec2,
|
||||
DAffine2,
|
||||
BlendMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
@@ -438,8 +440,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||
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
|
||||
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
|
||||
@@ -496,20 +496,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// 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: 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
|
||||
macro_rules! attribute_value_node {
|
||||
(Item<$element:ty>) => {
|
||||
@@ -529,7 +515,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(Item<Color>),
|
||||
attribute_value_node!(Item<BlendMode>),
|
||||
attribute_value_node!(Item<GradientForm>),
|
||||
attribute_value_node!(Item<GradientModel>),
|
||||
attribute_value_node!(Item<GradientSpread>),
|
||||
attribute_value_node!(Item<GradientSpace>),
|
||||
attribute_value_node!(Item<GradientHueDirection>),
|
||||
|
||||
@@ -72,32 +72,31 @@ impl BlendMode {
|
||||
]
|
||||
}
|
||||
|
||||
/// The subset of [`BlendMode::list()`] that is supported by SVG.
|
||||
pub fn list_svg_subset() -> [&'static [BlendMode]; 6] {
|
||||
use BlendMode::*;
|
||||
[
|
||||
// Normal group
|
||||
&[Normal],
|
||||
// Darken group
|
||||
&[Darken, Multiply, ColorBurn],
|
||||
// Lighten group
|
||||
&[Lighten, Screen, ColorDodge],
|
||||
// Contrast group
|
||||
&[Overlay, SoftLight, HardLight],
|
||||
// Inversion group
|
||||
&[Difference, Exclusion],
|
||||
// Component group
|
||||
&[Hue, Saturation, Color, Luminosity],
|
||||
]
|
||||
}
|
||||
|
||||
pub fn index_in_list(&self) -> Option<usize> {
|
||||
Self::list().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
}
|
||||
|
||||
/// Whether a layer in this mode reads what lies beneath it to blend, since neither SVG's `mix-blend-mode` nor Vello's layers have the mode.
|
||||
/// The alpha-only utility modes, hidden from the list, draw layers normally.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.to_svg_style_name().is_none() && !matches!(self, BlendMode::Erase | BlendMode::Restore | BlendMode::MultiplyAlpha)
|
||||
}
|
||||
|
||||
/// Whether a paint's strength (an effect's opacity, or a layer's fill) moves its color toward the mode's neutral color, which then blends at full strength, rather than fading the blend, for PSD interop.
|
||||
pub fn strength_moves_toward_neutral(&self) -> bool {
|
||||
use BlendMode::*;
|
||||
matches!(self, ColorDodge | LinearDodge | ColorBurn | LinearBurn | VividLight | LinearLight | HardMix)
|
||||
}
|
||||
|
||||
/// Whether a layer's fill moves its content toward the mode's neutral color (see [`Self::strength_moves_toward_neutral`]) rather than fading it, for PSD interop.
|
||||
/// The layer then reads what lies beneath it to blend (see [`Self::layer_reads_backdrop`]).
|
||||
pub fn fill_moves_layer_toward_neutral(&self) -> bool {
|
||||
self.strength_moves_toward_neutral()
|
||||
}
|
||||
|
||||
/// Whether a layer in this mode at this `fill` reads what lies beneath it to blend: in a mode neither SVG's `mix-blend-mode` nor Vello's layers have,
|
||||
/// or below a full fill moving it toward the mode's neutral color, which Color Dodge and Color Burn layers otherwise blend natively without.
|
||||
pub fn layer_reads_backdrop(&self, fill: f32) -> bool {
|
||||
self.reads_backdrop() || (fill < 1. && self.fill_moves_layer_toward_neutral())
|
||||
pub fn index_in_list_svg_subset(&self) -> Option<usize> {
|
||||
Self::list_svg_subset().iter().flat_map(|x| x.iter()).position(|&blend_mode| blend_mode == *self)
|
||||
}
|
||||
|
||||
/// Convert the enum to the CSS string for the blend mode.
|
||||
@@ -131,14 +130,11 @@ impl BlendMode {
|
||||
}
|
||||
|
||||
/// Renders the blend mode CSS style declaration.
|
||||
/// A mode CSS lacks, which layers read what lies beneath to blend by, draws normally where nothing beneath can be read, as for content without bounds.
|
||||
pub fn render(&self) -> String {
|
||||
format!(
|
||||
r#" mix-blend-mode: {};"#,
|
||||
self.to_svg_style_name().unwrap_or_else(|| {
|
||||
if !self.reads_backdrop() {
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
}
|
||||
log::warn!("Unsupported blend mode {self:?}");
|
||||
"normal"
|
||||
})
|
||||
)
|
||||
@@ -160,7 +156,7 @@ impl Display for BlendMode {
|
||||
BlendMode::Lighten => write!(f, "Lighten"),
|
||||
BlendMode::Screen => write!(f, "Screen"),
|
||||
BlendMode::ColorDodge => write!(f, "Color Dodge"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge (Add)"),
|
||||
BlendMode::LinearDodge => write!(f, "Linear Dodge"),
|
||||
BlendMode::LighterColor => write!(f, "Lighter Color"),
|
||||
// Contrast group
|
||||
BlendMode::Overlay => write!(f, "Overlay"),
|
||||
@@ -251,30 +247,6 @@ pub fn apply_blend_mode(foreground: Color, background: Color, blend_mode: BlendM
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly a layer whose fill moves it toward neutral (see [`BlendMode::fill_moves_layer_toward_neutral`]) shows over a backdrop of `backdrop_alpha`: fully over an opaque one,
|
||||
/// by its `fill` over nothing, and between, the harmonic mean of the two weighted by that alpha, which shows nothing at no fill.
|
||||
pub fn layer_fill_shown(backdrop_alpha: f32, fill: f32) -> f32 {
|
||||
let weighted = (1. - backdrop_alpha) + backdrop_alpha * fill;
|
||||
if weighted <= 0. { 0. } else { (fill / weighted).min(1.) }
|
||||
}
|
||||
|
||||
/// Like [`apply_blend_mode`], with the foreground at `strength` (from 0 to 1) moved toward the mode's neutral color where it does that (see [`BlendMode::strength_moves_toward_neutral`]),
|
||||
/// for the caller to composite at full strength. Other modes take the foreground as it is, for the caller to fade the blend by the strength.
|
||||
pub fn apply_blend_mode_at_strength(foreground: Color, background: Color, blend_mode: BlendMode, strength: f32) -> Color {
|
||||
let toward = |neutral: f32| {
|
||||
let moved = |channel: f32| neutral + strength * (channel - neutral);
|
||||
Color::from_rgbaf32_unchecked(moved(foreground.r()), moved(foreground.g()), moved(foreground.b()), foreground.a())
|
||||
};
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => apply_blend_mode(toward(0.), background, blend_mode),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => apply_blend_mode(toward(1.), background, blend_mode),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => apply_blend_mode(toward(0.5), background, blend_mode),
|
||||
BlendMode::HardMix => background.blend_rgb(foreground, |backdrop, source| Color::blend_hard_mix_at_strength(backdrop, source, strength)),
|
||||
_ => apply_blend_mode(foreground, background, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -289,13 +261,9 @@ mod tests {
|
||||
assert_eq!(Color::blend_color_burn(0.5, source), 0., "a source of {source}");
|
||||
}
|
||||
|
||||
// Color Dodge, like Divide, keeps a black backdrop black under any source, even white, and turns any other white under a white source.
|
||||
// Divide also turns any other white under a black source.
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(backdrop, 1.), 0., "a backdrop of {backdrop}");
|
||||
}
|
||||
// Color Dodge gives white for a white source, and Divide keeps a black backdrop black and turns any other white under a black source
|
||||
for source in [1., 1. - 1e-7, 1. + 2e-7] {
|
||||
assert_eq!(Color::blend_color_dodge(0.5, source), 1., "a source of {source}");
|
||||
assert_eq!(Color::blend_color_dodge(0., source), 1., "a source of {source}");
|
||||
}
|
||||
for backdrop in [0., 1e-7, -1e-7] {
|
||||
assert_eq!(Color::blend_divide(backdrop, 0.5), 0., "a backdrop of {backdrop}");
|
||||
@@ -371,65 +339,6 @@ mod tests {
|
||||
assert!((blended.a() - 1.).abs() < 1e-5, "alpha was {}", blended.a());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn darker_and_lighter_color_pick_the_whole_color_by_luma() {
|
||||
// Blue's luma (0.11) is below the gray's (0.3), though its mean channel (a third) is above it
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let gray = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 1.);
|
||||
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::DarkerColor), blue);
|
||||
assert_eq!(apply_blend_mode(gray, blue, BlendMode::LighterColor), gray);
|
||||
assert_eq!(apply_blend_mode(blue, gray, BlendMode::DarkerColor), blue);
|
||||
|
||||
// Where the lumas tie, the backdrop stays, with the paint's alpha
|
||||
let tied = Color::from_rgbaf32_unchecked(0.3, 0.3, 0.3, 0.5);
|
||||
assert_eq!(apply_blend_mode(tied, gray, BlendMode::DarkerColor), gray.with_alpha(0.5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_mix_ramps_steeper_with_strength_to_a_256th_wide_where_the_channels_sum_to_one() {
|
||||
let hard_mix = |backdrop: f32, source: f32, strength: f32| Color::blend_hard_mix_at_strength(backdrop, source, strength).clamp(0., 1.);
|
||||
|
||||
// At full strength, white past a sum of 1 and black short of it, even a level away
|
||||
assert_eq!(hard_mix(0.6, 0.5, 1.), 1.);
|
||||
assert_eq!(hard_mix(0.5, 0.49, 1.), 0.);
|
||||
assert_eq!(hard_mix(0.5, 0.51, 1.), 1.);
|
||||
|
||||
// For PSD interop, half a fill gives clamp(2b - 1 + s), and no strength leaves the backdrop as it is
|
||||
for (backdrop, source) in [(0.5, 0.3), (0.4, 0.4), (0.7, 0.1)] {
|
||||
let half = hard_mix(backdrop, source, 128. / 255.);
|
||||
assert!((half - (2. * backdrop - 1. + source).clamp(0., 1.)).abs() < 0.01, "{backdrop}, {source}: {half}");
|
||||
assert_eq!(hard_mix(backdrop, source, 0.), backdrop);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn strength_moves_a_paint_toward_the_modes_neutral_color() {
|
||||
let backdrop = Color::from_rgbaf32_unchecked(0.4, 0.4, 0.4, 1.);
|
||||
let paint = Color::from_rgbaf32_unchecked(0.8, 0.8, 0.8, 1.);
|
||||
let at_half = |blend_mode: BlendMode| apply_blend_mode_at_strength(paint, backdrop, blend_mode, 0.5).r();
|
||||
|
||||
// Half the paint added, the paint halfway to white burned in, and the paint halfway to middle gray lighting
|
||||
assert!((at_half(BlendMode::LinearDodge) - 0.8).abs() < 1e-6, "{}", at_half(BlendMode::LinearDodge));
|
||||
assert!((at_half(BlendMode::LinearBurn) - 0.3).abs() < 1e-6, "{}", at_half(BlendMode::LinearBurn));
|
||||
assert!((at_half(BlendMode::LinearLight) - 0.7).abs() < 1e-6, "{}", at_half(BlendMode::LinearLight));
|
||||
|
||||
// The modes whose strength fades their blend take the paint as it is
|
||||
assert_eq!(at_half(BlendMode::Subtract), apply_blend_mode(paint, backdrop, BlendMode::Subtract).r());
|
||||
|
||||
// Layers read what lies beneath for the ten modes CSS lacks, of which five move their content toward neutral by their fill
|
||||
let reading: Vec<BlendMode> = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop).collect();
|
||||
assert_eq!(reading.len(), 10);
|
||||
assert_eq!(reading.iter().filter(|blend_mode| blend_mode.fill_moves_layer_toward_neutral()).count(), 5);
|
||||
assert!(!BlendMode::Erase.reads_backdrop());
|
||||
|
||||
// Color Dodge and Color Burn do too below a full fill, which they otherwise blend natively at
|
||||
for blend_mode in [BlendMode::ColorDodge, BlendMode::ColorBurn] {
|
||||
assert!(!blend_mode.reads_backdrop() && !blend_mode.layer_reads_backdrop(1.) && blend_mode.layer_reads_backdrop(0.5) && blend_mode.layer_reads_backdrop(0.));
|
||||
}
|
||||
assert!(!BlendMode::Multiply.layer_reads_backdrop(0.5) && BlendMode::LinearBurn.layer_reads_backdrop(1.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_over_weights_straight_colors_by_alpha() {
|
||||
let over = Color::from_rgbaf32_unchecked(1., 0., 0., 0.5);
|
||||
|
||||
@@ -633,20 +633,14 @@ impl Color {
|
||||
c_b + c_s - 1.
|
||||
}
|
||||
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
/// Whole-color "Darker Color" blend: keeps whichever color has the lower mean RGB, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_darker_color(&self, other: Color) -> Color {
|
||||
let darker = if self.blend_luma() <= other.blend_luma() { *self } else { other };
|
||||
let darker = if self.average_rgb_channels() <= other.average_rgb_channels() { *self } else { other };
|
||||
|
||||
darker.with_alpha(other.alpha)
|
||||
}
|
||||
|
||||
/// The luma that Darker Color and Lighter Color compare, as the component blend modes measure it.
|
||||
#[inline(always)]
|
||||
fn blend_luma(&self) -> f32 {
|
||||
luma_rec_601_rounded(self.red, self.green, self.blue)
|
||||
}
|
||||
|
||||
/// Per-channel "Screen" blend.
|
||||
#[inline(always)]
|
||||
pub fn blend_screen(c_b: f32, c_s: f32) -> f32 {
|
||||
@@ -659,16 +653,10 @@ impl Color {
|
||||
c_s.max(c_b)
|
||||
}
|
||||
|
||||
/// Per-channel "Color Dodge" blend, where a black backdrop stays black and any other turns white under a white source, as the W3C formula orders them.
|
||||
/// Per-channel "Color Dodge" blend.
|
||||
#[inline(always)]
|
||||
pub fn blend_color_dodge(c_b: f32, c_s: f32) -> f32 {
|
||||
if c_b.abs() <= BLEND_EDGE_TOLERANCE {
|
||||
0.
|
||||
} else if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE {
|
||||
1.
|
||||
} else {
|
||||
(c_b / (1. - c_s)).min(1.)
|
||||
}
|
||||
if (c_s - 1.).abs() <= BLEND_EDGE_TOLERANCE { 1. } else { (c_b / (1. - c_s)).min(1.) }
|
||||
}
|
||||
|
||||
/// Per-channel "Linear Dodge" (Add) blend.
|
||||
@@ -677,10 +665,10 @@ impl Color {
|
||||
c_b + c_s
|
||||
}
|
||||
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher luma (0.3 R + 0.59 G + 0.11 B), this one where they tie, with `other`'s alpha.
|
||||
/// Whole-color "Lighter Color" blend: keeps whichever color has the higher mean RGB, with `other`'s alpha.
|
||||
#[inline(always)]
|
||||
pub fn blend_lighter_color(&self, other: Color) -> Color {
|
||||
let lighter = if self.blend_luma() >= other.blend_luma() { *self } else { other };
|
||||
let lighter = if self.average_rgb_channels() >= other.average_rgb_channels() { *self } else { other };
|
||||
|
||||
lighter.with_alpha(other.alpha)
|
||||
}
|
||||
@@ -736,15 +724,9 @@ impl Color {
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend: white where the channels sum to at least 1 and black below, along a ramp a 256th wide at full strength, for PSD interop.
|
||||
/// Per-channel "Hard Mix" blend: thresholds Linear Light at 0.5.
|
||||
pub fn blend_hard_mix(c_b: f32, c_s: f32) -> f32 {
|
||||
Color::blend_hard_mix_at_strength(c_b, c_s, 1.)
|
||||
}
|
||||
|
||||
/// Per-channel "Hard Mix" blend of a paint at `strength` (from 0 to 1), unclamped, whose ramp steepens from none (the backdrop as it is) to a 256th wide at full strength, for PSD interop.
|
||||
pub fn blend_hard_mix_at_strength(c_b: f32, c_s: f32, strength: f32) -> f32 {
|
||||
let steepness = 255. * strength / 256.;
|
||||
(c_b - steepness * (1. - c_s)) / (1. - steepness)
|
||||
if Color::blend_linear_light(c_b, c_s) < 0.5 { 0. } else { 1. }
|
||||
}
|
||||
|
||||
/// Per-channel "Difference" blend.
|
||||
|
||||
@@ -33,9 +33,9 @@ pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
|
||||
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||
ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
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
|
||||
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
|
||||
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
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, it's 0.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
|
||||
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
|
||||
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -1720,7 +1714,7 @@ impl<T: CacheHash> CacheHash for List<T> {
|
||||
self.element.as_slice().cache_hash(state);
|
||||
|
||||
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
|
||||
// (e.g., gradient_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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,18 +116,11 @@ pub fn migrate_to_numbers<'de, D: serde::Deserializer<'de>>(deserializer: D) ->
|
||||
enum NumbersFormat {
|
||||
Array(Vec<f64>),
|
||||
List(LegacyTable<f64>),
|
||||
/// The removed `Footprint` value, stored only by 'Rasterize', for its upgrade to split back into its transform's six numbers then its resolution's two.
|
||||
Footprint {
|
||||
transform: [Option<f64>; 6],
|
||||
resolution: [f64; 2],
|
||||
},
|
||||
}
|
||||
|
||||
Ok(match NumbersFormat::deserialize(deserializer)? {
|
||||
NumbersFormat::Array(values) => values,
|
||||
NumbersFormat::List(list) => list.element,
|
||||
// A `null` saved in place of a NaN or infinite number loads as 0, like elsewhere
|
||||
NumbersFormat::Footprint { transform, resolution } => transform.into_iter().map(Option::unwrap_or_default).chain(resolution).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -60,6 +60,12 @@ pub struct FieldMetadata {
|
||||
pub progression: bool,
|
||||
/// Whether the input must be fed by a value known at compile time, from `#[constant]`.
|
||||
pub constant: bool,
|
||||
/// The X and Y labels of a Vec2 parameter's widget, from `#[labels("W", "H")]`.
|
||||
pub labels: Option<(&'static str, &'static str)>,
|
||||
/// Whether a number or Vec2 parameter's widget only takes integers, from `#[integer]`. Integer types always do.
|
||||
pub integer: bool,
|
||||
/// Whether the widget leaves room for the assist area beside it, which `#[blank_assist(false)]` turns off.
|
||||
pub blank_assist: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -222,6 +228,167 @@ pub static NODE_REGISTRY: NodeRegistry = LazyLock::new(|| Mutex::new(HashMap::ne
|
||||
|
||||
pub static NODE_METADATA: LazyLock<Mutex<HashMap<ProtoNodeIdentifier, NodeMetadata>>> = LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
|
||||
/// Every node defined as a subgraph by the `#[graph]` macro, in registration order.
|
||||
pub static GRAPH_METADATA: LazyLock<Mutex<Vec<GraphMetadata>>> = LazyLock::new(|| Mutex::new(Vec::new()));
|
||||
|
||||
/// A node defined as a subgraph by `#[graph]`, which the editor turns into a catalog definition alongside the proto nodes.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphMetadata {
|
||||
/// The definition's identifier and display name.
|
||||
pub identifier: &'static str,
|
||||
pub category: &'static str,
|
||||
pub icon: Option<&'static str>,
|
||||
pub description: &'static str,
|
||||
/// The declaration version from `#[graph(version(N))]`, starting at 1.
|
||||
pub version: u32,
|
||||
/// Whether a new instance starts as a layer, from `#[graph(layer)]`.
|
||||
pub layer: bool,
|
||||
/// The subgraph's imports, which become the inputs of each instance, described like a proto node's parameters.
|
||||
/// Each one's `default_type` is the type it was declared with.
|
||||
pub imports: Vec<FieldMetadata>,
|
||||
pub exports: Vec<GraphExportMetadata>,
|
||||
/// The nodes inside the subgraph, where each node's position in this list is its ID.
|
||||
pub nodes: Vec<GraphNodeMetadata>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphExportMetadata {
|
||||
pub name: &'static str,
|
||||
pub description: &'static str,
|
||||
pub source: GraphInputSource,
|
||||
}
|
||||
|
||||
/// A node inside a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GraphNodeMetadata {
|
||||
pub implementation: GraphNodeImplementation,
|
||||
/// The inputs the definition sets, by index. Every other input keeps the default from the node's own definition.
|
||||
pub inputs: Vec<(usize, GraphInputSource)>,
|
||||
/// The absolute position in grid units, from `.at(x, y)`.
|
||||
pub position: Option<(i32, i32)>,
|
||||
/// From `.layer()`.
|
||||
pub layer: bool,
|
||||
/// From `.named("…")`.
|
||||
pub display_name: Option<&'static str>,
|
||||
/// From `.hidden()`.
|
||||
pub hidden: bool,
|
||||
/// From `.locked()`.
|
||||
pub locked: bool,
|
||||
/// From `.pinned()`.
|
||||
pub pinned: bool,
|
||||
/// From `.call_argument::<T>()`.
|
||||
pub call_argument: Option<Type>,
|
||||
}
|
||||
|
||||
/// What a node inside a subgraph is an instance of.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum GraphNodeImplementation {
|
||||
ProtoNode(ProtoNodeIdentifier),
|
||||
/// Another node defined by `#[graph]`, named by its identifier.
|
||||
Graph(&'static str),
|
||||
}
|
||||
|
||||
impl From<ProtoNodeIdentifier> for GraphNodeImplementation {
|
||||
fn from(identifier: ProtoNodeIdentifier) -> Self {
|
||||
Self::ProtoNode(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&'static str> for GraphNodeImplementation {
|
||||
fn from(identifier: &'static str) -> Self {
|
||||
Self::Graph(identifier)
|
||||
}
|
||||
}
|
||||
|
||||
/// What feeds an input, or an export, of a subgraph defined by `#[graph]`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum GraphInputSource {
|
||||
/// The output of another node in the subgraph, by its position in [`GraphMetadata::nodes`].
|
||||
Node { node: usize, output: usize },
|
||||
/// One of the subgraph's imports, with the type its wire records.
|
||||
Import { index: usize, ty: Type },
|
||||
/// A value. Without an exposure, the input keeps the one from the node's own definition.
|
||||
Value { value: GraphValue, exposed: Option<bool> },
|
||||
/// A scope input, from `scope("…")`.
|
||||
Scope(&'static str),
|
||||
/// The document path of the node, from `reflect(NodePath)`.
|
||||
NodePath,
|
||||
/// The source ID of the node, from `reflect(SourceId)`.
|
||||
SourceId,
|
||||
}
|
||||
|
||||
/// A value written in a subgraph definition. The editor converts it to the type of the input it feeds.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum GraphValue {
|
||||
/// A number written without a fractional part, which feeds an integer input as an integer and any other as a number.
|
||||
Integer(i64),
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
String(String),
|
||||
Vec2(glam::DVec2),
|
||||
Color(Color),
|
||||
}
|
||||
|
||||
impl GraphValue {
|
||||
pub fn vec2(x: f64, y: f64) -> Self {
|
||||
Self::Vec2(glam::DVec2::new(x, y))
|
||||
}
|
||||
|
||||
/// An opaque color from `rgb(0xRRGGBB)`.
|
||||
pub fn rgb(hex: u32) -> Self {
|
||||
let [_, red, green, blue] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, 255).into())
|
||||
}
|
||||
|
||||
/// A color with alpha from `rgba(0xRRGGBBAA)`.
|
||||
pub fn rgba(hex: u32) -> Self {
|
||||
let [red, green, blue, alpha] = hex.to_be_bytes();
|
||||
Self::Color(crate::color::SRGBA8::new(red, green, blue, alpha).into())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for GraphValue {
|
||||
fn from(value: &str) -> Self {
|
||||
Self::String(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<String> for GraphValue {
|
||||
fn from(value: String) -> Self {
|
||||
Self::String(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<bool> for GraphValue {
|
||||
fn from(value: bool) -> Self {
|
||||
Self::Bool(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<f64> for GraphValue {
|
||||
fn from(value: f64) -> Self {
|
||||
Self::Number(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<i64> for GraphValue {
|
||||
fn from(value: i64) -> Self {
|
||||
Self::Integer(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<glam::DVec2> for GraphValue {
|
||||
fn from(value: glam::DVec2) -> Self {
|
||||
Self::Vec2(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Color> for GraphValue {
|
||||
fn from(value: Color) -> Self {
|
||||
Self::Color(value)
|
||||
}
|
||||
}
|
||||
|
||||
/// All multi-output proto nodes (those returning a [`Destructure`] struct), keyed by their identifier.
|
||||
/// Snapshotted on first access, which must happen after startup registration of the node metadata completes.
|
||||
pub static MULTI_OUTPUT_NODES: LazyLock<HashMap<ProtoNodeIdentifier, DestructureMetadata>> = LazyLock::new(|| {
|
||||
|
||||
@@ -86,8 +86,6 @@ pub enum Adjustment {
|
||||
opacity: f64,
|
||||
},
|
||||
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 {
|
||||
@@ -114,17 +112,6 @@ impl Adjustment {
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
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);
|
||||
}
|
||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||
Self::Invert | Self::Solarize => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
@@ -313,7 +300,7 @@ impl Adjustment {
|
||||
pub enum DesaturateMethod {
|
||||
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
|
||||
///
|
||||
/// Accessibility contrast ratios use this.
|
||||
/// Accessibility contrast ratios and SVG luminance masks use this.
|
||||
#[default]
|
||||
#[label("Luminance (Rec. 709)")]
|
||||
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
|
||||
@@ -499,20 +486,6 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
||||
}
|
||||
|
||||
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) {
|
||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||
|
||||
@@ -1,361 +0,0 @@
|
||||
//! Blend If, shaped for PSD interop as its blending ranges: the content shows only where its own colors, and the colors of what lies beneath it, fall within a range of each channel's levels.
|
||||
//! The content's own range fades it like its fill does, leaving the shadows and glows cast from it as they are, and the range beneath fades everything the content draws like its opacity does.
|
||||
|
||||
use crate::effect_layers::is_pixel_filter;
|
||||
use crate::effects::EffectOperation;
|
||||
use crate::parameters::ParameterVisitor;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
|
||||
/// For PSD interop, the gray channel weighs the levels of the gamma-encoded red, green, and blue channels by these percentages.
|
||||
pub const GRAY_PERCENTAGES: [usize; 3] = [30, 59, 11];
|
||||
|
||||
/// How many levels each renderer reads a channel at before weighing it, the 8 bits browsers filter with, so every renderer cuts off the same pixels.
|
||||
pub const CHANNEL_LEVELS: usize = 256;
|
||||
|
||||
/// How near a cutoff a channel may lie, as a fraction of its full scale, and still count as reaching it: a quarter of a level, so a cutoff given in percent lands on the level it names.
|
||||
const CUTOFF_TOLERANCE: f64 = 1. / 1024.;
|
||||
|
||||
/// Which channel of the colors a Blend If range reads.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum BlendIfChannel {
|
||||
/// The lightness of the colors, weighing red, green, and blue by 30%, 59%, and 11%.
|
||||
#[default]
|
||||
Gray,
|
||||
Red,
|
||||
Green,
|
||||
Blue,
|
||||
}
|
||||
|
||||
/// A range of one channel's levels, in percent, which shows the content fully from its range start to its end and fades it out linearly to nothing at its falloff start and end.
|
||||
/// A falloff that meets its end of the range is a sharp cutoff, which shows the content at the level it lies on.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub struct BlendRange {
|
||||
pub falloff_start: f64,
|
||||
pub range_start: f64,
|
||||
pub range_end: f64,
|
||||
pub falloff_end: f64,
|
||||
}
|
||||
|
||||
impl Default for BlendRange {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
falloff_start: 0.,
|
||||
range_start: 0.,
|
||||
range_end: 100.,
|
||||
falloff_end: 100.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BlendRange {
|
||||
/// How strongly the content shows where the channel is `value`, from 0 to 1.
|
||||
pub fn weight(&self, value: f64) -> f64 {
|
||||
let value = value * 100.;
|
||||
let tolerance = CUTOFF_TOLERANCE * 100.;
|
||||
|
||||
// Each side rises (or falls) across its falloff, with its ends taken in either order
|
||||
let side = |falloff: f64, range: f64, rising: bool| {
|
||||
let (low, high) = (falloff.min(range), falloff.max(range));
|
||||
match (high - low > tolerance, rising) {
|
||||
(true, true) => ((value - low) / (high - low)).clamp(0., 1.),
|
||||
(true, false) => ((high - value) / (high - low)).clamp(0., 1.),
|
||||
(false, true) => f64::from(value >= low - tolerance),
|
||||
(false, false) => f64::from(value <= high + tolerance),
|
||||
}
|
||||
};
|
||||
|
||||
side(self.falloff_start, self.range_start, true) * side(self.falloff_end, self.range_end, false)
|
||||
}
|
||||
|
||||
/// Whether the range shows every level fully, so it changes nothing.
|
||||
pub fn shows_everything(&self) -> bool {
|
||||
// Rising then falling, it's full everywhere once it's full at both ends
|
||||
self.weight(0.) >= 1. && self.weight(1.) >= 1.
|
||||
}
|
||||
|
||||
/// The weight at each of the [`CHANNEL_LEVELS`] levels, from black to white.
|
||||
pub fn level_weights(&self) -> Vec<f64> {
|
||||
(0..CHANNEL_LEVELS).map(|level| self.weight(level as f64 / (CHANNEL_LEVELS - 1) as f64)).collect()
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||
let key = |parameter: &str| format!("{group}_{parameter}");
|
||||
visitor.parameter(&key("falloff_start"), &mut self.falloff_start, 0.);
|
||||
visitor.parameter(&key("range_start"), &mut self.range_start, 0.);
|
||||
visitor.parameter(&key("range_end"), &mut self.range_end, 100.);
|
||||
visitor.parameter(&key("falloff_end"), &mut self.falloff_end, 100.);
|
||||
}
|
||||
}
|
||||
|
||||
/// The ranges each channel's levels must fall within for the content to show, which multiply.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct ChannelRanges {
|
||||
pub gray: BlendRange,
|
||||
pub red: BlendRange,
|
||||
pub green: BlendRange,
|
||||
pub blue: BlendRange,
|
||||
}
|
||||
|
||||
impl ChannelRanges {
|
||||
/// Each channel with its range, in the order the GPU takes them.
|
||||
pub fn channels(&self) -> [(BlendIfChannel, &BlendRange); 4] {
|
||||
[
|
||||
(BlendIfChannel::Gray, &self.gray),
|
||||
(BlendIfChannel::Red, &self.red),
|
||||
(BlendIfChannel::Green, &self.green),
|
||||
(BlendIfChannel::Blue, &self.blue),
|
||||
]
|
||||
}
|
||||
|
||||
/// The channels with ranges that hide some levels.
|
||||
pub fn limiting(&self) -> impl Iterator<Item = (BlendIfChannel, &BlendRange)> {
|
||||
self.channels().into_iter().filter(|(_, range)| !range.shows_everything())
|
||||
}
|
||||
|
||||
/// Whether every channel's range shows every level fully, so they change nothing.
|
||||
pub fn show_everything(&self) -> bool {
|
||||
self.limiting().next().is_none()
|
||||
}
|
||||
|
||||
/// How strongly the content shows for a straight gamma-encoded `color`, each channel (and the gray from them) read at its nearest level.
|
||||
pub fn weight(&self, color: [f64; 3]) -> f64 {
|
||||
self.channel_weights(color).into_iter().product()
|
||||
}
|
||||
|
||||
/// The weight each channel's range gives a straight gamma-encoded `color`, in the order of [`Self::channels`], which multiply to its [`Self::weight`].
|
||||
pub fn channel_weights(&self, color: [f64; 3]) -> [f64; 4] {
|
||||
let levels = color.map(channel_level);
|
||||
let value = |level: usize| level as f64 / (CHANNEL_LEVELS - 1) as f64;
|
||||
let [red, green, blue] = levels.map(value);
|
||||
|
||||
[self.gray.weight(value(gray_level(levels))), self.red.weight(red), self.green.weight(green), self.blue.weight(blue)]
|
||||
}
|
||||
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, side: &str) {
|
||||
self.gray.visit_parameters(visitor, side);
|
||||
self.red.visit_parameters(visitor, &format!("red_{side}"));
|
||||
self.green.visit_parameters(visitor, &format!("green_{side}"));
|
||||
self.blue.visit_parameters(visitor, &format!("blue_{side}"));
|
||||
}
|
||||
}
|
||||
|
||||
/// The level from 0 to 255 nearest a channel's `value` from 0 to 1, with halves rounding up as the browsers' 8-bit filters round them.
|
||||
pub fn channel_level(value: f64) -> usize {
|
||||
((value.clamp(0., 1.) * (CHANNEL_LEVELS - 1) as f64 + 0.5).floor() as usize).min(CHANNEL_LEVELS - 1)
|
||||
}
|
||||
|
||||
/// The gray level of red, green, and blue levels, worked out in whole numbers so a gray exactly between two levels rounds up in every renderer.
|
||||
pub fn gray_level(levels: [usize; 3]) -> usize {
|
||||
let weighed: usize = levels.iter().zip(GRAY_PERCENTAGES).map(|(level, percentage)| level * percentage).sum();
|
||||
(weighed + 50) / 100
|
||||
}
|
||||
|
||||
/// The ranges of Blend If's two sides: those of the content's own colors, which fade the content like its fill, and those of what lies beneath it, which fade all it draws like its opacity.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct BlendIfRanges {
|
||||
pub content: ChannelRanges,
|
||||
pub underlying: ChannelRanges,
|
||||
}
|
||||
|
||||
impl BlendIfRanges {
|
||||
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
self.content.visit_parameters(visitor, "content");
|
||||
self.underlying.visit_parameters(visitor, "underlying");
|
||||
}
|
||||
}
|
||||
|
||||
/// How strongly all the content draws shows over a backdrop pixel with the straight gamma-encoded `color` and `alpha`, by the `underlying` ranges.
|
||||
/// Where nothing lies beneath, nothing is hidden, so the weight eases to full as the backdrop turns transparent.
|
||||
pub fn underlying_weight(underlying: &ChannelRanges, color: [f64; 3], alpha: f64) -> f64 {
|
||||
1. - alpha.clamp(0., 1.) * (1. - underlying.weight(color))
|
||||
}
|
||||
|
||||
/// The Blend If rows that act just before the row at `index` among `rows`: once `index` is the first row (or follows a pixel filter, like a blur or adjustment), those from it up to the next pixel filter.
|
||||
/// So each Blend If reads and fades the content as the pixel filters before it leave it, ahead of the shadows and glows around it, which are knocked out by the content as it then shows.
|
||||
pub fn blend_ifs_acting_before(rows: &[EffectOperation], index: usize) -> Vec<&BlendIfRanges> {
|
||||
let follows_pixel_filter = index.checked_sub(1).is_none_or(|previous| processes_pixels(&rows[previous]));
|
||||
if !follows_pixel_filter {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
(rows[index..].iter())
|
||||
.take_while(|operation| !processes_pixels(operation))
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) => Some(ranges.as_ref()),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Whether a solid paint overlay at `index` among `rows` may mix into the content's own colors ahead of the other effects.
|
||||
/// Not where a Blend If reading those colors acts in the same stretch between pixel filters, since it reads them before the overlay paints.
|
||||
pub fn paint_overlay_folds(rows: &[EffectOperation], index: usize) -> bool {
|
||||
let start = rows[..index].iter().rposition(processes_pixels).map_or(0, |previous| previous + 1);
|
||||
let end = rows[index..].iter().position(processes_pixels).map_or(rows.len(), |next| index + next);
|
||||
!fades_content(&rows[start..end])
|
||||
}
|
||||
|
||||
/// Whether a Blend If among the `operations` fades the content by its own colors, as a fill varying across it does.
|
||||
pub fn fades_content(operations: &[EffectOperation]) -> bool {
|
||||
operations
|
||||
.iter()
|
||||
.any(|operation| matches!(operation, EffectOperation::BlendIf(ranges) if !ranges.content.show_everything()))
|
||||
}
|
||||
|
||||
/// Whether a row processes the pixels of everything before it, as a pixel filter (like a blur or adjustment) that changes something does, which ends a stretch of rows that Blend Ifs act at the start of.
|
||||
fn processes_pixels(operation: &EffectOperation) -> bool {
|
||||
is_pixel_filter(operation) && !operation.changes_nothing()
|
||||
}
|
||||
|
||||
/// The ranges beneath of each Blend If row among the `operations` that hides anything by what lies beneath, which multiply.
|
||||
pub fn underlying_ranges<'a>(operations: impl IntoIterator<Item = &'a EffectOperation>) -> Vec<ChannelRanges> {
|
||||
(operations.into_iter())
|
||||
.filter_map(|operation| match operation {
|
||||
EffectOperation::BlendIf(ranges) if !ranges.underlying.show_everything() => Some(ranges.underlying),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn range(falloff_start: f64, range_start: f64, range_end: f64, falloff_end: f64) -> BlendRange {
|
||||
BlendRange {
|
||||
falloff_start,
|
||||
range_start,
|
||||
range_end,
|
||||
falloff_end,
|
||||
}
|
||||
}
|
||||
|
||||
/// A level from 0 to 255 as a channel value.
|
||||
fn level(level: f64) -> f64 {
|
||||
level / 255.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ranges_fade_linearly_across_their_falloffs() {
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let soft = range(percent(64.), percent(128.), percent(192.), percent(224.));
|
||||
|
||||
assert_eq!(soft.weight(level(32.)), 0.);
|
||||
assert!((soft.weight(level(96.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(160.)), 1.);
|
||||
assert!((soft.weight(level(208.)) - 0.5).abs() < 1e-12);
|
||||
assert_eq!(soft.weight(level(240.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsplit_cutoffs_keep_the_level_they_lie_on() {
|
||||
// For PSD interop, black at 64 keeps 64 and white at 192 keeps 192, given in percent as they'd be imported
|
||||
let percent = |level: f64| level / 255. * 100.;
|
||||
let hard = range(percent(64.), percent(64.), percent(192.), percent(192.));
|
||||
|
||||
assert_eq!(hard.weight(level(63.)), 0.);
|
||||
assert_eq!(hard.weight(level(64.)), 1.);
|
||||
assert_eq!(hard.weight(level(192.)), 1.);
|
||||
assert_eq!(hard.weight(level(193.)), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_default_range_shows_everything() {
|
||||
assert!(BlendRange::default().shows_everything());
|
||||
assert!(ChannelRanges::default().show_everything());
|
||||
assert!(!range(0., 10., 100., 100.).shows_everything());
|
||||
assert!(!range(0., 0., 100., 99.).shows_everything());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channels_multiply_with_gray_weighing_the_color() {
|
||||
let ranges = ChannelRanges {
|
||||
gray: range(0., 50., 100., 100.),
|
||||
red: range(0., 0., 50., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The gray of a light pink shows fully, but its red at full strength fades it to nothing
|
||||
assert_eq!(ranges.weight([1., 0.5, 0.5]), 0.);
|
||||
// A dark red's gray, read at its own level, lies partway up its falloff, while its red lies within its range
|
||||
let red = level(77.);
|
||||
let gray = gray_level([77, 0, 0]) as f64 / 255.;
|
||||
let expected = (gray * 100. / 50.) * ((100. - red * 100.) / 50.).min(1.);
|
||||
assert!((ranges.weight([red, 0., 0.]) - expected).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_beneath_hides_nothing() {
|
||||
let underlying = ChannelRanges {
|
||||
gray: range(50., 50., 100., 100.),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 0.), 1.);
|
||||
assert_eq!(underlying_weight(&underlying, [0.; 3], 1.), 0.);
|
||||
assert!((underlying_weight(&underlying, [0.; 3], 0.25) - 0.75).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_act_after_the_blurs_and_adjustments_before_them() {
|
||||
let blend_if = EffectOperation::BlendIf(Box::default());
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let shadow = EffectOperation::default_for(crate::EffectKind::DropShadow);
|
||||
let rows = [shadow.clone(), blend_if.clone(), blur, shadow, blend_if];
|
||||
|
||||
// The first acts ahead of the shadow before it, and the second just after the blur, ahead of the shadow between them
|
||||
let acting: Vec<usize> = (0..rows.len()).map(|index| blend_ifs_acting_before(&rows, index).len()).collect();
|
||||
assert_eq!(acting, [1, 0, 0, 1, 0]);
|
||||
|
||||
// A blur of no radius changes nothing, so it starts no stretch of its own
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let rows = [EffectOperation::default_for(crate::EffectKind::DropShadow), no_blur, EffectOperation::BlendIf(Box::default())];
|
||||
assert_eq!(blend_ifs_acting_before(&rows, 0).len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grays_between_two_levels_round_up() {
|
||||
// Blue at 250 weighs 27.5 levels of gray, and 249 weighs 27.39
|
||||
assert_eq!(gray_level([0, 0, 250]), 28);
|
||||
assert_eq!(gray_level([0, 0, 249]), 27);
|
||||
assert_eq!(gray_level([5, 0, 0]), 2);
|
||||
assert_eq!(gray_level([255, 255, 255]), 255);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_keep_their_strength_where_a_blend_if_reads_the_content_beside_them() {
|
||||
let overlay = EffectOperation::Adjustment(crate::Adjustment::ColorOverlay {
|
||||
color: core_types::Color::RED,
|
||||
blend_mode: core_types::blending::BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 40.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
assert!(!paint_overlay_folds(&[overlay.clone(), blend_if.clone(), blur.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[overlay.clone(), blur.clone(), blend_if.clone()], 0));
|
||||
assert!(paint_overlay_folds(&[blend_if, blur, overlay.clone()], 2));
|
||||
assert!(paint_overlay_folds(&[overlay, EffectOperation::BlendIf(Box::default())], 0));
|
||||
}
|
||||
}
|
||||
@@ -22,8 +22,6 @@ pub enum PiecePlace {
|
||||
IntoContent { over: bool },
|
||||
/// The part of an interior piece blending with what shows through the content's fill, in a layer of its mode beneath the content's, or with `over`, over it.
|
||||
Through { over: bool },
|
||||
/// What lies beneath the content, filtered and cut to its silhouette, at the bottom of the content's own layer.
|
||||
Backdrop,
|
||||
}
|
||||
|
||||
/// One coverage of an effect that draws as a piece of its own, named like the map of it.
|
||||
@@ -65,28 +63,20 @@ pub struct EffectLayers {
|
||||
/// How many of the effects, from the first, are carried out within the content's image.
|
||||
pub flattened: usize,
|
||||
pub layers: Vec<EffectLayer>,
|
||||
/// The rows from the first mask after every other effect to the end: masks, and Blend Ifs reading only what lies beneath, which fade each finished layer at each pixel like the item's opacity.
|
||||
/// Empty where those masks flatten what's before them instead.
|
||||
/// The rows from the first mask after every other effect to the end, which fade each finished layer at each pixel like the item's opacity. Empty where those masks flatten what's before them instead.
|
||||
pub trailing_masks: Range<usize>,
|
||||
/// Whether a Blend If fades every layer by the colors of what lies beneath.
|
||||
pub fades_by_underlying: bool,
|
||||
}
|
||||
|
||||
impl EffectLayers {
|
||||
/// The layers of content drawn with `blend_mode` and faded by `fill` through `effects`, or with every effect flattened if not `layered`, as for content clipped by a mask.
|
||||
/// Content in a mode CSS lacks reads what lies beneath to blend by it (see [`BlendMode::reads_backdrop`]), but the alpha-only utility modes are planned as normal.
|
||||
/// Content in a mode CSS lacks is drawn normally, so it's planned that way.
|
||||
pub fn plan(effects: &Effects, blend_mode: BlendMode, fill: f32, layered: bool) -> Self {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() || blend_mode.reads_backdrop() {
|
||||
blend_mode
|
||||
} else {
|
||||
BlendMode::Normal
|
||||
};
|
||||
let blend_mode = if blend_mode.to_svg_style_name().is_some() { blend_mode } else { BlendMode::Normal };
|
||||
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer.
|
||||
// A Blend If fading the content by its colors acts as a fill below full wherever it hides any.
|
||||
// Normal content at full fill hides what lies beneath its share, so its interior pieces blend with it alone, in any mode, within its own layer
|
||||
let shares_content = blend_mode == BlendMode::Normal;
|
||||
let blends_into_content = shares_content && fill >= 1. && !crate::blend_if::fades_content(&operations);
|
||||
let blends_into_content = shares_content && fill >= 1.;
|
||||
|
||||
// The masks after every other effect fade the layers rather than the content's image, so they flatten nothing before them
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -125,16 +115,10 @@ impl EffectLayers {
|
||||
.chain([(LayerPart::Content, blend_mode)])
|
||||
.collect();
|
||||
|
||||
// A blurred backdrop, or a shadow not knocked out (flattened or layered), in the content's layer would hide a part placed beneath that layer
|
||||
let backdrop: Vec<LayerPart> = pieces_from(0, operations.len())
|
||||
.into_iter()
|
||||
.filter(|(piece, _)| piece.place == PiecePlace::Backdrop)
|
||||
.map(|(piece, _)| LayerPart::Piece(piece))
|
||||
.collect();
|
||||
// A shadow not knocked out in the content's layer, flattened or layered, would hide a part placed beneath that layer
|
||||
let shows_through = |piece: &EffectPiece| piece.place == PiecePlace::Beneath && !piece.knocks_out;
|
||||
let mut content_run = parts.iter().rev().skip(1).take_while(|(_, mode)| *mode == BlendMode::Normal);
|
||||
let covered_beneath =
|
||||
!backdrop.is_empty() || content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
let covered_beneath = content_run.any(|(part, _)| matches!(part, LayerPart::Piece(piece) if shows_through(piece))) || unmerged.iter().any(|(piece, _)| shows_through(piece));
|
||||
|
||||
// Interior pieces of normal content blend within its share, in its layer. Below a full fill, a blended one splits off its part through the fill into a layer beneath
|
||||
// the content's, or over it when its mode isn't straight along what lies beneath or a shadow covers that, as every later piece then does to keep their order.
|
||||
@@ -182,10 +166,8 @@ impl EffectLayers {
|
||||
layers.splice(content_layer..content_layer, through);
|
||||
}
|
||||
|
||||
let fades_by_underlying = !crate::blend_if::underlying_ranges(&operations).is_empty();
|
||||
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes, unless it reads what lies beneath
|
||||
if blends_into_content && backdrop.is_empty() && !fades_by_underlying && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
// One normal layer at a full fill draws the same with all its effects flattened into the content's image, which takes fewer passes
|
||||
if blends_into_content && matches!(layers.as_slice(), [layer] if layer.blend_mode == BlendMode::Normal) {
|
||||
let content = EffectLayer {
|
||||
blend_mode: BlendMode::Normal,
|
||||
parts: vec![LayerPart::Content],
|
||||
@@ -194,21 +176,10 @@ impl EffectLayers {
|
||||
flattened: operations.len(),
|
||||
layers: vec![content],
|
||||
trailing_masks: no_rows,
|
||||
fades_by_underlying,
|
||||
};
|
||||
}
|
||||
|
||||
// What lies beneath, filtered, goes at the bottom of the content's own layer, which fades and blends it with the content, even from a row flattened into the content
|
||||
if let Some(content_layer) = layers.iter_mut().find(|layer| layer.holds_content()) {
|
||||
content_layer.parts.splice(0..0, backdrop);
|
||||
}
|
||||
|
||||
Self {
|
||||
flattened,
|
||||
layers,
|
||||
trailing_masks,
|
||||
fades_by_underlying,
|
||||
}
|
||||
Self { flattened, layers, trailing_masks }
|
||||
}
|
||||
|
||||
/// Like [`Self::plan`], for effects stamped in more than one space (see [`Effects::runs`]), as renderers draw them.
|
||||
@@ -230,27 +201,6 @@ impl EffectLayers {
|
||||
planned
|
||||
}
|
||||
|
||||
/// Whether a layered piece, a Blend If fading the layers, or a layer's blend mode reads what lies beneath the content.
|
||||
pub fn reads_backdrop(&self) -> bool {
|
||||
self.fades_by_underlying || self.reads_around_backdrop() || self.layers.iter().any(|layer| layer.blend_mode.reads_backdrop())
|
||||
}
|
||||
|
||||
/// Whether the content's layer reads what lies beneath it to blend at the content's `fill` (see [`BlendMode::layer_reads_backdrop`]).
|
||||
/// Color Dodge and Color Burn blend natively instead over a piece beneath the content it doesn't knock out, which what lies beneath the item leaves out.
|
||||
pub fn content_reads_backdrop(&self, fill: f32) -> bool {
|
||||
let Some(content_layer) = self.content_layer() else { return false };
|
||||
let blend_mode = self.layers[content_layer].blend_mode;
|
||||
|
||||
let shown_beneath = |part: &LayerPart| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Beneath && !piece.knocks_out);
|
||||
let pieces_show_beneath = self.layers[..content_layer].iter().flat_map(|layer| &layer.parts).any(shown_beneath);
|
||||
blend_mode.reads_backdrop() || (blend_mode.layer_reads_backdrop(fill) && !pieces_show_beneath)
|
||||
}
|
||||
|
||||
/// Whether a layered piece reads what lies around each pixel beneath the content, as a background blur does, where a Blend If reads only the pixel itself.
|
||||
pub fn reads_around_backdrop(&self) -> bool {
|
||||
(self.layers.iter().flat_map(|layer| &layer.parts)).any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::Backdrop))
|
||||
}
|
||||
|
||||
/// The index of the layer holding the content.
|
||||
pub fn content_layer(&self) -> Option<usize> {
|
||||
self.layers.iter().position(EffectLayer::holds_content)
|
||||
@@ -313,30 +263,11 @@ impl EffectLayers {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether any of the effects reads what lies beneath the content, like a background blur, or may, like a shadow in a mode CSS lacks.
|
||||
pub fn effects_read_backdrop(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| match &operation {
|
||||
EffectOperation::BackgroundBlur { .. } => !operation.changes_nothing(),
|
||||
EffectOperation::BlendIf(ranges) => !ranges.underlying.show_everything(),
|
||||
_ => {
|
||||
!operation.changes_nothing()
|
||||
&& pieces(0, &operation)
|
||||
.iter()
|
||||
.any(|(piece, blend_mode)| piece.place == PiecePlace::Beneath && blend_mode.reads_backdrop())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether an effect row can draw as layered pieces, rather than being carried out within the content's image.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them. A piece in a mode CSS lacks reads what lies beneath the item to blend, so only one beneath the content
|
||||
/// can, though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
/// Blurs, adjustments, masks, and feathers process the pixels of everything before them, and blend modes CSS lacks can't blend against the backdrop in SVG or a GPU layer,
|
||||
/// though interior pieces that `blend_into_content` blend with the content alone, which the renderers do themselves.
|
||||
fn can_be_layered(operation: &EffectOperation, blend_into_content: bool) -> bool {
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| match piece.place {
|
||||
_ if blend_mode.to_svg_style_name().is_some() => true,
|
||||
PiecePlace::Beneath => blend_mode.reads_backdrop(),
|
||||
PiecePlace::Within => blend_into_content,
|
||||
_ => false,
|
||||
};
|
||||
let layers_in = |(piece, blend_mode): (EffectPiece, BlendMode)| blend_mode.to_svg_style_name().is_some() || (blend_into_content && piece.place == PiecePlace::Within);
|
||||
!is_pixel_filter(operation) && pieces(0, operation).into_iter().all(layers_in)
|
||||
}
|
||||
|
||||
@@ -379,39 +310,31 @@ fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||
.map_or(0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it, leaving out each Blend If that reads only what lies beneath.
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
|
||||
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let trailing_masks = trailing_masks(&operations);
|
||||
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||
|
||||
// A Blend If reading only what lies beneath fades the finished layers wherever it sits, so it shapes no clip (and it's the only kind the trailing masks can hold)
|
||||
let kept: Vec<usize> = (0..merged).chain(trailing_masks).filter(|&index| !reads_only_beneath(&operations[index])).collect();
|
||||
if kept.len() == operations.len() {
|
||||
if merged == trailing_masks.start {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects(kept.into_iter().filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
/// A Blend If reading only what lies beneath is passed over, since it fades the finished layers as the masks do, but one reading the content's colors counts as another effect.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
let is_mask = |operation: &EffectOperation| matches!(operation, EffectOperation::Mask { .. });
|
||||
let is_other = |operation: &EffectOperation| !operation.changes_nothing() && !is_mask(operation) && !reads_only_beneath(operation);
|
||||
|
||||
let Some(last_other) = operations.iter().rposition(is_other) else { return no_rows };
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing() && is_mask(operation));
|
||||
let Some(last_other) = operations.iter().rposition(|operation| !operation.changes_nothing() && !is_mask(operation)) else {
|
||||
return no_rows;
|
||||
};
|
||||
let first_mask = operations[last_other + 1..].iter().position(|operation| !operation.changes_nothing());
|
||||
first_mask.map_or(no_rows, |offset| last_other + 1 + offset..operations.len())
|
||||
}
|
||||
|
||||
/// Whether the effect is a Blend If without ranges of the content's own colors, so it reads only what lies beneath (or changes nothing).
|
||||
fn reads_only_beneath(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::BlendIf(ranges) if ranges.content.show_everything())
|
||||
}
|
||||
|
||||
/// The pieces the effect at `index` draws, each with the mode it blends by, leaving out those painting no color.
|
||||
fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendMode)> {
|
||||
// Only a drop shadow can show through the content
|
||||
@@ -469,7 +392,6 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
inside.into_iter().chain(outside).flatten().collect()
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::BackgroundBlur { .. } => vec![piece(0, Backdrop, None, BlendMode::Normal)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
@@ -490,12 +412,10 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::BlendIf(_)
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
@@ -588,11 +508,9 @@ mod tests {
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Overlay, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Overlay, BlendMode::Screen, BlendMode::Normal]);
|
||||
|
||||
// Content in a mode CSS lacks reads what lies beneath to blend by it, and an interior piece blending within the content's layer may take one too
|
||||
// A mode CSS lacks is drawn normally, so it's planned that way, and an interior piece blending within the content's layer may take one too
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::LinearBurn, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::LinearBurn, BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_backdrop() && !layers.reads_around_backdrop());
|
||||
assert!(!EffectLayers::plan(&effects, BlendMode::Overlay, 1., true).reads_backdrop());
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
let linear_burn = Effects::from_operations([drop_shadow(red, BlendMode::Multiply), inner_shadow(red, BlendMode::LinearBurn)]);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 1., true).flattened, 0);
|
||||
assert_eq!(EffectLayers::plan(&linear_burn, BlendMode::Normal, 0.5, true).flattened, 2);
|
||||
@@ -650,11 +568,6 @@ mod tests {
|
||||
fn interior_pieces_go_over_the_content_where_its_layer_covers_what_lies_beneath_it() {
|
||||
let red = RED.with_alpha(0.75);
|
||||
let through_over = PiecePlace::Through { over: true };
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
let with_knockout = |knocks_out: bool| {
|
||||
let mut shadow = drop_shadow(Color::BLACK.with_alpha(0.75), BlendMode::Multiply);
|
||||
@@ -664,22 +577,23 @@ mod tests {
|
||||
shadow
|
||||
};
|
||||
|
||||
// A blurred backdrop, or a shadow not knocked out, beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
for beneath in [background_blur, with_knockout(false)] {
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([beneath.clone(), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen], "{beneath:?}");
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))], "{beneath:?}");
|
||||
}
|
||||
// A shadow not knocked out beneath the content in its layer would hide even a straight piece's part beneath that layer
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(false), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal, BlendMode::Screen]);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
|
||||
// A knocked-out shadow doesn't cover it there
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([with_knockout(true), inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(parts(&layers)[0], [Some((1, 0, PiecePlace::Through { over: false }))]);
|
||||
|
||||
// One flattened before an interior piece in a mode CSS lacks covers it too
|
||||
let flattening = [with_knockout(false), inner_shadow(red, BlendMode::LinearBurn), inner_shadow(red, BlendMode::Screen)];
|
||||
let layers = EffectLayers::plan(&Effects::from_operations(flattening), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers)[1], [Some((2, 0, through_over))]);
|
||||
// One flattened for a mode CSS lacks covers it too
|
||||
let mut flattened_shadow = with_knockout(false);
|
||||
if let EffectOperation::DropShadow { blend_mode, .. } = &mut flattened_shadow {
|
||||
*blend_mode = BlendMode::LinearBurn;
|
||||
}
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([flattened_shadow, inner_shadow(red, BlendMode::Screen)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 1);
|
||||
assert_eq!(parts(&layers)[1], [Some((1, 0, through_over))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -786,14 +700,9 @@ mod tests {
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (2, 2..2));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (5, 5..5));
|
||||
let unmerged = Effects::from_operations([
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
inner_shadow(RED, BlendMode::LinearBurn),
|
||||
drop_shadow(RED, BlendMode::Multiply),
|
||||
mask(),
|
||||
]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (4, 4..4));
|
||||
let unmerged = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply), mask()]);
|
||||
let layers = EffectLayers::plan(&unmerged, BlendMode::Normal, 1., true);
|
||||
assert_eq!((layers.flattened, layers.trailing_masks.clone()), (3, 3..3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -810,23 +719,19 @@ mod tests {
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
|
||||
// An interior piece in a mode CSS lacks, which would read the content beneath it, flattens what's before it, where one beneath the content takes a layer of its own
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), inner_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let effects = Effects::from_operations([inner_shadow(RED, BlendMode::Screen), drop_shadow(RED, BlendMode::LinearBurn), inner_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
let layers = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn)]), BlendMode::Normal, 0.5, true);
|
||||
assert_eq!((layers.flattened, modes(&layers)), (0, vec![BlendMode::LinearBurn, BlendMode::Normal]));
|
||||
assert!(layers.reads_backdrop());
|
||||
|
||||
// A flattened shadow left unmerged by a blur would cover the layered shadow after it, so everything flattens
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), inner_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), drop_shadow(RED, BlendMode::Multiply)]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(modes(&layers), [BlendMode::Normal]);
|
||||
|
||||
// Clipped content flattens everything
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, false);
|
||||
assert_eq!(layers.flattened, 3);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
@@ -853,95 +758,6 @@ mod tests {
|
||||
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_background_blur_lies_at_the_bottom_of_the_contents_layer() {
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let background_blur = EffectOperation::BackgroundBlur {
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// Even beside a blended shadow, and flattened by a later blur, it fades and blends with the content
|
||||
let effects = Effects::from_operations([drop_shadow(blue, BlendMode::Multiply), background_blur, blur]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Screen, 1., true);
|
||||
assert!(layers.reads_backdrop());
|
||||
let content_layer = layers.content_layer().unwrap();
|
||||
assert_eq!(layers.layers[content_layer].blend_mode, BlendMode::Screen);
|
||||
assert_eq!(parts(&layers)[content_layer], [Some((1, 0, PiecePlace::Backdrop)), None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_draw_no_pieces_and_read_the_backdrop_only_by_their_ranges_beneath() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let content_only = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&content_only, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers.len(), 1);
|
||||
assert!(!layers.reads_backdrop() && !effects_read_backdrop(&content_only));
|
||||
|
||||
ranges.underlying.blue.falloff_end = 50.;
|
||||
let beneath = Effects::from_operations([EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&beneath, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.layers[0].parts, [LayerPart::Content]);
|
||||
assert!(layers.reads_backdrop() && effects_read_backdrop(&beneath));
|
||||
|
||||
// Fading the content by its colors, it splits a blended interior piece as a partial fill does, even at a full fill
|
||||
let screen = Effects::from_operations([inner_shadow(RED.with_alpha(0.75), BlendMode::Screen), EffectOperation::BlendIf(Box::new(ranges))]);
|
||||
let layers = EffectLayers::plan(&screen, BlendMode::Normal, 1., true);
|
||||
assert_eq!(modes(&layers), [BlendMode::Screen, BlendMode::Normal]);
|
||||
assert!(layers.reads_through_share());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_after_trailing_masks_leave_them_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.underlying.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |effects: &Effects| -> Vec<EffectKind> { content_image_effects(effects).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// After the mask as before it, the shadow keeps its layer and mode while the mask fades each layer, and a clipping base takes the mask alone
|
||||
for operations in [
|
||||
[drop_shadow(RED, BlendMode::Multiply), mask(), blend_if.clone()],
|
||||
[drop_shadow(RED, BlendMode::Multiply), blend_if.clone(), mask()],
|
||||
] {
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 0, "{:?}", effects.operations().map(|operation| operation.kind()).collect::<Vec<_>>());
|
||||
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
|
||||
assert!(layers.fades_layers());
|
||||
assert_eq!(kinds(&effects), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
// With nothing else to trail, a clipping base still takes the mask alone in either order
|
||||
assert_eq!(kinds(&Effects::from_operations([blend_if.clone(), mask()])), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(&Effects::from_operations([mask(), blend_if])), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blend_ifs_reading_the_content_after_masks_keep_them_from_trailing() {
|
||||
let mut ranges = crate::blend_if::BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(ranges));
|
||||
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// The mask merges the shadow flattened before it into the content's image, which the Blend If then reads
|
||||
let effects = Effects::from_operations([drop_shadow(RED, BlendMode::LinearBurn), mask(), blend_if.clone()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
assert_eq!(layers.flattened, 2);
|
||||
assert!(!layers.fades_layers());
|
||||
|
||||
// A clipping base takes the mask alone, with the Blend If before it or after it
|
||||
assert_eq!(kinds(vec![blend_if.clone(), mask()]), [EffectKind::Mask]);
|
||||
assert_eq!(kinds(vec![mask(), blend_if]), [EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::blend_if::BlendIfRanges;
|
||||
use crate::filters::{Convolution, NoiseDistribution};
|
||||
use crate::masks::{MaskMode, mask_feather_sigma};
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
@@ -15,7 +14,7 @@ use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, 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 dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
@@ -60,14 +59,12 @@ pub enum EffectKind {
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
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.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
HighPass,
|
||||
/// Scatters random offsets across the colors, fixed in place on the content.
|
||||
Speckle,
|
||||
AddNoise,
|
||||
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
|
||||
Dissolve,
|
||||
/// Smears the content along a line, as if it moved while being captured.
|
||||
@@ -94,10 +91,6 @@ pub enum EffectKind {
|
||||
Pixelate,
|
||||
/// Prints each color channel of the content as dots on its own turned screen, as a press prints ink.
|
||||
ColorHalftone,
|
||||
/// Blurs what lies beneath the content within its silhouette, as if seen through frosted glass.
|
||||
BackgroundBlur,
|
||||
/// Shows the content only where its own colors, and those of what lies beneath it, fall within ranges of their channels.
|
||||
BlendIf,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -119,8 +112,6 @@ pub enum EffectKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -141,10 +132,9 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Median => "Median",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::Speckle => "Speckle",
|
||||
Self::AddNoise => "Add Noise",
|
||||
Self::Dissolve => "Dissolve",
|
||||
Self::MotionBlur => "Motion Blur",
|
||||
Self::RadialBlur => "Radial Blur",
|
||||
@@ -158,8 +148,6 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::Displace => "Displace",
|
||||
Self::Pixelate => "Pixelate",
|
||||
Self::ColorHalftone => "Color Halftone",
|
||||
Self::BackgroundBlur => "Background Blur",
|
||||
Self::BlendIf => "Blend If",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -180,7 +168,6 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
Self::AlphaToGray => "Alpha to Gray",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -224,9 +211,6 @@ pub enum MinimumMaximumMode {
|
||||
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.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -240,9 +224,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,
|
||||
/// 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 };
|
||||
|
||||
/// 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.
|
||||
@@ -332,10 +313,21 @@ pub fn bevel_lit(gradient: DVec2, light: DVec3) -> f64 {
|
||||
(-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,
|
||||
/// 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;
|
||||
|
||||
/// 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.
|
||||
/// 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 {
|
||||
@@ -368,6 +360,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`]).
|
||||
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
||||
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||
@@ -450,23 +447,12 @@ impl Effects {
|
||||
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.
|
||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, or a background blur among them reads what lies beneath, in the effect space of a run of them.
|
||||
/// How far past the content the effects together can paint, in the effect space of a run of them.
|
||||
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.painted_reach()).sum()
|
||||
@@ -482,30 +468,17 @@ impl Effects {
|
||||
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.
|
||||
/// 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.
|
||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||
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() {
|
||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||
let operation = effect.operation();
|
||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
||||
let changes_something = !effect.operation().changes_nothing();
|
||||
|
||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
||||
if let Some((transform, rows)) = runs.last_mut()
|
||||
&& shares_grid
|
||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||
{
|
||||
if changes_something && !run_changes_something {
|
||||
@@ -513,10 +486,9 @@ impl Effects {
|
||||
}
|
||||
rows.end = index + 1;
|
||||
run_changes_something |= changes_something;
|
||||
run_on_content_grid |= on_content_grid;
|
||||
} else {
|
||||
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
|
||||
@@ -856,14 +828,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.
|
||||
/// 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) {
|
||||
stamp_effect_on(item.attributes_mut(), effect);
|
||||
}
|
||||
|
||||
/// 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)
|
||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||
.0
|
||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
@@ -1113,11 +1079,6 @@ pub enum EffectOperation {
|
||||
radius: f64,
|
||||
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 {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
@@ -1125,13 +1086,13 @@ pub enum EffectOperation {
|
||||
radius: f64,
|
||||
/// On a scale of 0 to 255.
|
||||
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,
|
||||
},
|
||||
HighPass {
|
||||
radius: f64,
|
||||
},
|
||||
Speckle {
|
||||
AddNoise {
|
||||
/// Percent of full brightness.
|
||||
amount: f64,
|
||||
distribution: NoiseDistribution,
|
||||
@@ -1267,17 +1228,6 @@ pub enum EffectOperation {
|
||||
/// Percent of the spacing between dots that each screen's dots lie past the `offset` along both of its axes.
|
||||
phase: f64,
|
||||
},
|
||||
/// Blurs the backdrop beneath the content within the content's silhouette, beneath the content and its effects.
|
||||
BackgroundBlur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
/// Fades the content by how its own colors fall within ranges, as its fill does, and everything it draws by how the colors beneath fall within others, as its opacity does.
|
||||
BlendIf(Box<BlendIfRanges>),
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -1319,10 +1269,9 @@ impl EffectOperation {
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Median { .. } => EffectKind::Median,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::Speckle { .. } => EffectKind::Speckle,
|
||||
Self::AddNoise { .. } => EffectKind::AddNoise,
|
||||
Self::Dissolve { .. } => EffectKind::Dissolve,
|
||||
Self::MotionBlur { .. } => EffectKind::MotionBlur,
|
||||
Self::RadialBlur { .. } => EffectKind::RadialBlur,
|
||||
@@ -1336,8 +1285,6 @@ impl EffectOperation {
|
||||
Self::Displace { .. } => EffectKind::Displace,
|
||||
Self::Pixelate { .. } => EffectKind::Pixelate,
|
||||
Self::ColorHalftone { .. } => EffectKind::ColorHalftone,
|
||||
Self::BackgroundBlur { .. } => EffectKind::BackgroundBlur,
|
||||
Self::BlendIf(_) => EffectKind::BlendIf,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
@@ -1368,7 +1315,7 @@ impl EffectOperation {
|
||||
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
|
||||
pub fn changes_nothing(&self) -> bool {
|
||||
match self {
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => *radius <= 0.,
|
||||
Self::Blur { radius, .. } => *radius <= 0.,
|
||||
Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0.,
|
||||
Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)),
|
||||
Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()),
|
||||
@@ -1416,13 +1363,10 @@ impl EffectOperation {
|
||||
Self::Feather { distance } => *distance <= 0.,
|
||||
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
|
||||
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::Speckle { amount, .. } => *amount <= 0.,
|
||||
Self::AddNoise { amount, .. } => *amount <= 0.,
|
||||
// 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::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(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1431,16 +1375,6 @@ impl EffectOperation {
|
||||
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
|
||||
}
|
||||
|
||||
/// Whether this operation paints nothing past the content, whatever it reads there, like an inner shadow finding the edges it casts from.
|
||||
pub fn paints_only_within_content(&self) -> bool {
|
||||
match self {
|
||||
Self::InnerShadow { .. } | Self::InnerGlow { .. } | Self::Satin { .. } | Self::Mask { .. } | Self::Feather { .. } | Self::BackgroundBlur { .. } => true,
|
||||
Self::Outline { align, .. } => *align == StrokeAlign::Inside,
|
||||
Self::BevelAndEmboss { style, .. } => *style == BevelStyle::InnerBevel,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur or a warp, rather than casting from the content's shape or changing each pixel alone.
|
||||
pub fn reads_pixels_around(&self) -> bool {
|
||||
match self {
|
||||
@@ -1448,8 +1382,8 @@ impl EffectOperation {
|
||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||
true
|
||||
}
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | 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
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
| Self::OuterGlow { .. }
|
||||
@@ -1458,16 +1392,10 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::BackgroundBlur { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
let keeps_coverage = matches!(
|
||||
@@ -1481,8 +1409,6 @@ impl EffectOperation {
|
||||
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::HighPass { .. }
|
||||
);
|
||||
@@ -1503,9 +1429,8 @@ impl EffectOperation {
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
|
||||
Self::Blur { radius, box_blur: true, .. } | Self::BackgroundBlur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
// A background blur reads as far past the content as its Gaussian reaches
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => 3. * radius.max(0.),
|
||||
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
|
||||
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
|
||||
Self::DropShadow { distance, size, .. } | Self::InnerShadow { distance, size, .. } => distance.abs() + size.max(0.) + 1.,
|
||||
@@ -1525,7 +1450,6 @@ impl EffectOperation {
|
||||
// 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::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
|
||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||
@@ -1535,7 +1459,7 @@ impl EffectOperation {
|
||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => self.displacement_reach() + 1.,
|
||||
// Within the frame they paint the content's own cells or dots, reading a cell's or a dot's area around each point there, which `Effects::source_region` finds
|
||||
Self::Pixelate { .. } | Self::ColorHalftone { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::Speckle { .. } | Self::Dissolve { .. } | Self::BlendIf(_) | Self::Adjustment(_) => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1592,7 +1516,7 @@ impl EffectOperation {
|
||||
};
|
||||
|
||||
match &mut self {
|
||||
Self::Blur { radius, .. } | Self::BackgroundBlur { radius, .. } => finite(radius),
|
||||
Self::Blur { radius, .. } => finite(radius),
|
||||
Self::DropShadow { angle, distance, spread, size, .. }
|
||||
| Self::InnerShadow {
|
||||
angle, distance, choke: spread, size, ..
|
||||
@@ -1620,9 +1544,9 @@ impl EffectOperation {
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
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::Speckle { amount, .. } => finite(amount),
|
||||
Self::AddNoise { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
|
||||
Self::RadialBlur { amount, transform, .. } => {
|
||||
@@ -1670,7 +1594,7 @@ impl EffectOperation {
|
||||
offset,
|
||||
phase,
|
||||
} => [radius, red_angle, green_angle, blue_angle, &mut offset.x, &mut offset.y, phase].into_iter().for_each(finite),
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::BlendIf(_) | Self::Adjustment(_) => {}
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -1791,7 +1715,6 @@ impl EffectOperation {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Median => Self::Median { radius: 0. },
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
@@ -1799,7 +1722,7 @@ impl EffectOperation {
|
||||
edges_only: false,
|
||||
},
|
||||
EffectKind::HighPass => Self::HighPass { radius: 0. },
|
||||
EffectKind::Speckle => Self::Speckle {
|
||||
EffectKind::AddNoise => Self::AddNoise {
|
||||
amount: 0.,
|
||||
distribution: NoiseDistribution::default(),
|
||||
monochromatic: false,
|
||||
@@ -1878,12 +1801,6 @@ impl EffectOperation {
|
||||
offset: DVec2::ZERO,
|
||||
phase: 0.,
|
||||
},
|
||||
EffectKind::BackgroundBlur => Self::BackgroundBlur {
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::BlendIf => Self::BlendIf(Box::default()),
|
||||
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
|
||||
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
|
||||
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
|
||||
@@ -1920,7 +1837,6 @@ impl EffectOperation {
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1937,11 +1853,6 @@ impl EffectOperation {
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::BackgroundBlur { radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 10.);
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::DropShadow {
|
||||
color,
|
||||
blend_mode,
|
||||
@@ -2134,7 +2045,6 @@ impl EffectOperation {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
@@ -2147,7 +2057,7 @@ impl EffectOperation {
|
||||
visitor.parameter("edges_only", edges_only, false);
|
||||
}
|
||||
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
|
||||
Self::Speckle {
|
||||
Self::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
@@ -2273,7 +2183,6 @@ impl EffectOperation {
|
||||
visitor.parameter("offset", offset, DVec2::ZERO);
|
||||
visitor.parameter("phase", phase, 0.);
|
||||
}
|
||||
Self::BlendIf(ranges) => ranges.visit_parameters(visitor),
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
@@ -2284,23 +2193,6 @@ mod tests {
|
||||
use super::*;
|
||||
use vector_types::{Gradient, GradientStop};
|
||||
|
||||
#[test]
|
||||
fn box_blurs_reach_their_half_width_and_a_pixel_while_gaussians_reach_three_radii() {
|
||||
let blur = |box_blur| EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 6.,
|
||||
box_blur,
|
||||
gamma: false,
|
||||
};
|
||||
let background_blur = |box_blur| EffectOperation::BackgroundBlur { radius: 6., box_blur, gamma: false };
|
||||
|
||||
// Whether it blurs the content or what lies beneath it, a blur reaches as far as its kernel reads
|
||||
for (box_blur, reach) in [(true, 7.), (false, 18.)] {
|
||||
assert_eq!(blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
assert_eq!(background_blur(box_blur).reach(), reach, "box: {box_blur}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
@@ -2437,7 +2329,6 @@ mod tests {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
@@ -2452,7 +2343,7 @@ mod tests {
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
EffectOperation::Speckle {
|
||||
EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Gaussian,
|
||||
monochromatic: true,
|
||||
@@ -2545,16 +2436,10 @@ mod tests {
|
||||
offset: DVec2::new(-4., 6.),
|
||||
phase: 25.,
|
||||
},
|
||||
EffectOperation::BlendIf(Box::new({
|
||||
let mut ranges = BlendIfRanges::default();
|
||||
ranges.content.gray.range_start = 25.;
|
||||
ranges.underlying.red.falloff_end = 80.;
|
||||
ranges
|
||||
})),
|
||||
];
|
||||
|
||||
for operation in &operations {
|
||||
assert_eq!(Effect::new(operation).operation(), *operation);
|
||||
for operation in operations {
|
||||
assert_eq!(Effect::new(&operation).operation(), operation);
|
||||
}
|
||||
|
||||
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
|
||||
@@ -2576,13 +2461,6 @@ mod tests {
|
||||
|
||||
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
|
||||
// Blend If's ranges ride attributes named like its node's inputs
|
||||
let blend_if = operations.iter().find(|operation| operation.kind() == EffectKind::BlendIf).unwrap();
|
||||
let row = Effect::new(blend_if);
|
||||
assert_eq!(row.0.attribute::<f64>("content_range_start"), Some(&25.));
|
||||
assert_eq!(row.0.attribute::<f64>("red_underlying_falloff_end"), Some(&80.));
|
||||
assert_eq!(row.0.attributes().iter_any().count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -2902,16 +2780,6 @@ mod tests {
|
||||
assert_eq!(runs, vec![0..3, 3..4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effects_painting_only_within_the_content_paint_nothing_past_it() {
|
||||
// An inner shadow reads past the content to find the edges it casts from, but paints only within it
|
||||
let (inner_shadow, drop_shadow) = (EffectOperation::default_for(EffectKind::InnerShadow), EffectOperation::default_for(EffectKind::DropShadow));
|
||||
let painted = |effects: Effects| effects.reach_around_by(DAffine2::IDENTITY, [DVec2::ZERO; 2], 0., |operation| !operation.paints_only_within_content());
|
||||
assert!(Effects::from_operations([inner_shadow.clone()]).reach() > 0.);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow.clone()])), DVec2::ZERO);
|
||||
assert_eq!(painted(Effects::from_operations([inner_shadow, drop_shadow.clone()])), DVec2::splat(drop_shadow.reach()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
|
||||
use EffectKind::*;
|
||||
@@ -2936,7 +2804,6 @@ mod tests {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -3036,7 +2903,6 @@ mod tests {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Median { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
@@ -3060,28 +2926,6 @@ mod tests {
|
||||
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]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||
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 dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||
@@ -164,10 +164,9 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Median { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::Speckle { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
)
|
||||
}
|
||||
@@ -179,7 +178,13 @@ pub fn reads_neighbors(operation: &EffectOperation) -> bool {
|
||||
|
||||
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
|
||||
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||
matches!(operation, EffectOperation::AddNoise { .. } | 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.
|
||||
@@ -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.
|
||||
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.
|
||||
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
||||
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.
|
||||
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.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum UnsharpBlur {
|
||||
/// A Gaussian blur with this standard deviation in document pixels.
|
||||
Gaussian(f64),
|
||||
/// 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,
|
||||
}
|
||||
|
||||
@@ -256,7 +277,7 @@ pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
|
||||
shifts
|
||||
}
|
||||
|
||||
/// How the random offsets Speckle gives the colors are spread.
|
||||
/// How the random offsets Add Noise gives the colors are spread.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
@@ -275,7 +296,7 @@ pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RandomField {
|
||||
/// Speckle's offset for each color, or for Gaussian noise its first uniform value.
|
||||
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value.
|
||||
NoiseOffsets,
|
||||
/// Gaussian noise's second uniform value for each color, its angle.
|
||||
NoiseAngles,
|
||||
@@ -299,7 +320,7 @@ impl RandomField {
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest offset Speckle of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
|
||||
let deviations = match distribution {
|
||||
NoiseDistribution::Uniform => 1.,
|
||||
@@ -350,6 +371,24 @@ impl FieldSampling {
|
||||
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)]
|
||||
|
||||
@@ -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 core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
|
||||
@@ -9,17 +9,13 @@ use core_types::math::quad::Quad;
|
||||
use core_types::none;
|
||||
use core_types::ops::FromAnchorPosition;
|
||||
use core_types::transform::Transform;
|
||||
use core_types::{
|
||||
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
|
||||
Color,
|
||||
};
|
||||
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
pub use vector_types::Vector;
|
||||
use vector_types::gradient_standard::GradientShape;
|
||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::{Gradient, 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.
|
||||
#[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, inherited_appearance: Option<&Appearance>) -> bool {
|
||||
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => {
|
||||
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
||||
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)
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||
&& 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| {
|
||||
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
||||
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)
|
||||
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.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
}),
|
||||
_ => false,
|
||||
}
|
||||
@@ -649,22 +644,16 @@ impl Graphic {
|
||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||
match self {
|
||||
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
|
||||
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => {
|
||||
!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) => {
|
||||
!item_effects_may_change_alpha(item)
|
||||
&& vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
)
|
||||
}
|
||||
// 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.element().is_guaranteed_fully_opaque(),
|
||||
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
||||
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
Graphic::VectorList(list) => {
|
||||
!list.is_empty()
|
||||
&& !list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_opaque(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
@@ -676,23 +665,19 @@ impl Graphic {
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => 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::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()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
Graphic::Gradient(item) => {
|
||||
item_opacity_is_full(item)
|
||||
&& !item_effects_may_change_alpha(item)
|
||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
||||
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||
}
|
||||
Graphic::GradientList(list) => {
|
||||
!list.is_empty()
|
||||
&& every_item_has_full_opacity(list)
|
||||
&& !list_effects_may_change_alpha(list)
|
||||
&& (0..list.len()).all(|index| {
|
||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
||||
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
||||
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
|
||||
})
|
||||
}
|
||||
@@ -702,41 +687,27 @@ impl Graphic {
|
||||
}
|
||||
|
||||
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 {
|
||||
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::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::Vector(item) => {
|
||||
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_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
item.attribute::<Effects>(ATTR_EFFECTS),
|
||||
))
|
||||
}
|
||||
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(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
||||
)
|
||||
}))
|
||||
}
|
||||
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_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().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) => vector_is_guaranteed_fully_transparent(
|
||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||
),
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
vector_is_guaranteed_fully_transparent(
|
||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||
)
|
||||
}),
|
||||
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
||||
Graphic::ColorList(list) => every_item_has_zero_opacity(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
|
||||
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::GradientList(list) => {
|
||||
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.)))
|
||||
}
|
||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||
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.)),
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(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.
|
||||
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 {
|
||||
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 && effects.is_none_or(Effects::change_nothing))
|
||||
let fills_invisible = opacity_fill <= f64::EPSILON
|
||||
|| appearance.is_none_or(|appearance| {
|
||||
appearance
|
||||
.covers_with_paints()
|
||||
@@ -853,16 +823,6 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
||||
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.
|
||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||
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)
|
||||
}
|
||||
|
||||
/// Whether a gradient with the attributes the `attribute` lookup gives paints every point, which curved contours leaving gaps unfilled don't.
|
||||
fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>) -> bool {
|
||||
fn read<'a, T: 'static>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>, key: &str) -> Option<&'a T> {
|
||||
attribute(key).and_then(|value| value.downcast_ref::<T>())
|
||||
}
|
||||
|
||||
GradientShape::new(
|
||||
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
|
||||
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
|
||||
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
|
||||
)
|
||||
.paints_everywhere()
|
||||
}
|
||||
|
||||
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
|
||||
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
|
||||
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
|
||||
@@ -1342,64 +1287,4 @@ mod graphic_is_opaque_tests {
|
||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod blend_if;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod filters;
|
||||
@@ -21,10 +20,9 @@ pub use vector_types;
|
||||
pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use 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 generator::Generator;
|
||||
|
||||
@@ -7,45 +7,26 @@ use dyn_any::DynAny;
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
#[widget(Radio)]
|
||||
pub enum MaskMode {
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it. Brightness is judged by weighting the gamma-encoded RGB channels by `0.3, 0.59, 0.11`.
|
||||
///
|
||||
/// This matches the Luminosity family of blend modes.
|
||||
/// White shows the content and black hides it, with transparent areas also hiding it.
|
||||
#[default]
|
||||
Luminance,
|
||||
/// Like Luminance, but brightness is judged by weighting the gamma-encoded RGB channels by `0.2125, 0.7154, 0.0721`, so greens show more of the content, and reds and blues less.
|
||||
///
|
||||
/// SVG luminance masks use this, so masks brought in from SVG keep their look.
|
||||
#[label("Luminance (SVG)")]
|
||||
LuminanceSvg,
|
||||
/// Opaque areas show the content and transparent areas hide it, whatever their colors.
|
||||
Alpha,
|
||||
}
|
||||
|
||||
/// The weights of the red, green, and blue channels in the luminance of a mask in the `Luminance` mode, taken on gamma-encoded channels, those the Luminosity family of blend modes uses.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.3, 0.59, 0.11];
|
||||
|
||||
/// The weights of the red, green, and blue channels in SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
/// They weigh the luminance of a mask in the `LuminanceSvg` mode and of the maps that vary other effects, which SVG reads by `luminanceToAlpha`.
|
||||
pub const SVG_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
impl MaskMode {
|
||||
/// The weights of a mask graphic's premultiplied gamma-encoded red, green, blue, and alpha channels that sum to how much it shows the content.
|
||||
pub fn channel_weights(self) -> [f32; 4] {
|
||||
let ([red, green, blue], alpha) = match self {
|
||||
Self::Luminance => (MASK_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::LuminanceSvg => (SVG_LUMINANCE_WEIGHTS, 0.),
|
||||
Self::Alpha => ([0.; 3], 1.),
|
||||
};
|
||||
[red, green, blue, alpha]
|
||||
}
|
||||
}
|
||||
/// The weights of the red, green, and blue channels in a mask's luminance, those of SVG's `luminanceToAlpha`, taken on gamma-encoded channels as an SVG mask does.
|
||||
pub const MASK_LUMINANCE_WEIGHTS: [f32; 3] = [0.2125, 0.7154, 0.0721];
|
||||
|
||||
/// How much a pixel of the mask graphic, given as premultiplied gamma-encoded channels, shows the content, from 0 to 1.
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in every mode.
|
||||
pub fn mask_coverage(channels: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let coverage: f32 = channels.into_iter().zip(mode.channel_weights()).map(|(channel, weight)| channel * weight).sum();
|
||||
/// The luminance of premultiplied channels is that of the straight color times its alpha, so transparent areas hide the content in either mode.
|
||||
pub fn mask_coverage([red, green, blue, alpha]: [f32; 4], mode: MaskMode) -> f32 {
|
||||
let [red_weight, green_weight, blue_weight] = MASK_LUMINANCE_WEIGHTS;
|
||||
let coverage = match mode {
|
||||
MaskMode::Luminance => red * red_weight + green * green_weight + blue * blue_weight,
|
||||
MaskMode::Alpha => alpha,
|
||||
};
|
||||
coverage.clamp(0., 1.)
|
||||
}
|
||||
|
||||
@@ -65,9 +46,12 @@ pub fn mask_feather_sigma(feather: f64) -> f64 {
|
||||
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.
|
||||
///
|
||||
/// 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.
|
||||
/// 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.
|
||||
@@ -103,6 +87,11 @@ pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64
|
||||
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::Luminance) * 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.
|
||||
///
|
||||
/// 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.
|
||||
@@ -131,21 +120,3 @@ pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn luminance_modes_weigh_pure_red_green_and_blue_by_their_own_weights() {
|
||||
let level = |channels: [f32; 4], mode| (mask_coverage(channels, mode) * 255.).round() as u8;
|
||||
let primaries = [[1., 0., 0., 1.], [0., 1., 0., 1.], [0., 0., 1., 1.]];
|
||||
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Luminance)), [77, 150, 28]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::LuminanceSvg)), [54, 182, 18]);
|
||||
assert_eq!(primaries.map(|primary| level(primary, MaskMode::Alpha)), [255; 3]);
|
||||
|
||||
// Premultiplied channels count the color by its alpha
|
||||
assert_eq!(level([0., 0.5, 0., 0.5], MaskMode::Luminance), 75);
|
||||
}
|
||||
}
|
||||
@@ -1076,10 +1076,10 @@ pub enum DisplaceMode {
|
||||
/// For PSD interop, the 8-bit level of a displacement map's luminance that moves nothing, which black lies the farthest from.
|
||||
pub const DISPLACEMENT_NEUTRAL_LEVEL: f64 = 128.;
|
||||
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as an SVG luminance mask reads it:
|
||||
/// The share of its distance that a displacement map's premultiplied gamma-encoded `color` moves the content, by its luminance as a mask reads it:
|
||||
/// -1 at black, none at the neutral level, and 127/128 at white. Where the map is translucent it's seen over the neutral level.
|
||||
pub fn displacement_amount(color: [f32; 4]) -> f64 {
|
||||
let luminance = mask_coverage(color, MaskMode::LuminanceSvg) as f64;
|
||||
let luminance = mask_coverage(color, MaskMode::Luminance) as f64;
|
||||
let level = luminance * 255. + DISPLACEMENT_NEUTRAL_LEVEL * (1. - color[3] as f64);
|
||||
(level - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL
|
||||
}
|
||||
@@ -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.
|
||||
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.
|
||||
pub fn disc_in_cell_area(radius: f64, side: f64) -> f64 {
|
||||
let half = side / 2.;
|
||||
@@ -1709,10 +1715,10 @@ impl EffectOperation {
|
||||
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 {
|
||||
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::Pinch { .. }
|
||||
| Self::Spherize { .. }
|
||||
@@ -1737,10 +1743,8 @@ impl EffectOperation {
|
||||
| Self::MinimumMaximum { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
| Self::Speckle { .. }
|
||||
| Self::AddNoise { .. }
|
||||
| Self::Dissolve { .. }
|
||||
| Self::BackgroundBlur { .. }
|
||||
| Self::BlendIf(_)
|
||||
| Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -2845,7 +2849,7 @@ mod tests {
|
||||
assert!((displacement_amount([0., 0., 0., 1.]) + 1.).abs() < 1e-5);
|
||||
assert_eq!(displacement_amount([0., 0., 0., 0.]), 0.);
|
||||
|
||||
// A color moves the content by its luminance, as an SVG luminance mask reads it, and a pixel reads from the opposite way
|
||||
// A color moves the content by its luminance, as a mask reads it, and a pixel reads from the opposite way
|
||||
let red = displacement_amount([1., 0., 0., 1.]);
|
||||
assert!((red - (0.2125 * 255. - DISPLACEMENT_NEUTRAL_LEVEL) / DISPLACEMENT_NEUTRAL_LEVEL).abs() < 1e-5);
|
||||
assert_eq!(map_displacement([1., 0., 0., 1.], DVec2::new(10., -4.)), DVec2::new(10., -4.) * -red);
|
||||
|
||||
@@ -25,4 +25,6 @@ vector-types = { workspace = true }
|
||||
# Workspace dependencies
|
||||
fastnoise-lite = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -30,12 +30,11 @@ pub enum StepKind {
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 22] = [
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -57,7 +56,6 @@ impl StepKind {
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
StepKind::AlphaToGray,
|
||||
];
|
||||
|
||||
/// 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.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
Adjustment::AlphaToGray,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ use core_types::transfer_curve::TransferCurveEvaluator;
|
||||
use glam::Vec3;
|
||||
use graphic_types::adjustment::{self as settings, Adjustment, DesaturateMethod, RelativeAbsolute};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{CPU, Raster};
|
||||
use std::iter::once;
|
||||
use std::sync::Arc;
|
||||
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));
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn adjust_color(adjustment: &Adjustment, color: Color) -> Color {
|
||||
struct AdjustColor(Color);
|
||||
@@ -241,7 +226,6 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_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 {
|
||||
min_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.);
|
||||
}
|
||||
}
|
||||
|
||||
#[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::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => add_noise(&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 add_noise(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 = add_noise(&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 = add_noise(&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 = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||
let reseeded = add_noise(&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| add_noise(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 glam::{DVec2, IVec2};
|
||||
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.
|
||||
pub fn thumbnail_area(pattern: &GeneratorPattern) -> Option<[DVec2; 2]> {
|
||||
@@ -143,6 +177,35 @@ fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
mod tests {
|
||||
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]
|
||||
fn pattern_values_show_as_the_gray_at_that_level() {
|
||||
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
|
||||
let sample = pattern_sampler(&white_noise(3));
|
||||
let coarse: Vec<Color> = centers(4).map(&sample).collect();
|
||||
for (index, point) in centers(16).enumerate() {
|
||||
let (x, y) = (index % 16, index / 16);
|
||||
assert_eq!(sample(point), coarse[(y / 4) * 4 + x / 4]);
|
||||
let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap();
|
||||
let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap();
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
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
|
||||
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_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,26 +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.
|
||||
//! The modes CSS lacks, which layers read what lies beneath to blend by, take the formulas the effects share (see [`crate::blending::blend_gamma`]).
|
||||
//! 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 blend normally, since layers only ever take the others.
|
||||
|
||||
use core_types::Color;
|
||||
use core_types::blending::{BlendMode, apply_blend_mode_at_strength, layer_fill_shown};
|
||||
use core_types::color::BLEND_EDGE_TOLERANCE;
|
||||
use crate::effect_kernels::Plane;
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
/// 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.
|
||||
pub fn blend_pixel(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode) -> [f32; 4] {
|
||||
blend_pixel_at_strength(source, backdrop, blend_mode, 1.)
|
||||
}
|
||||
|
||||
/// One premultiplied pixel of a layer's full-strength content blended onto another by the mode, faded by the layer's `fill`, or over the backdrop
|
||||
/// in a mode whose fill moves the content toward its neutral color (see [`BlendMode::fill_moves_layer_toward_neutral`]), moved there by it.
|
||||
pub fn blend_layer_pixel(content: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, fill: f32) -> [f32; 4] {
|
||||
match blend_mode.fill_moves_layer_toward_neutral() {
|
||||
true => blend_pixel_at_strength(content, backdrop, blend_mode, fill),
|
||||
false => blend_pixel(content.map(|channel| channel * fill), backdrop, blend_mode),
|
||||
}
|
||||
}
|
||||
|
||||
/// [`blend_pixel`] with the source at `strength`, which moves it toward the mode's neutral color where it blends, and shows it as strongly as [`layer_fill_shown`] gives.
|
||||
fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: BlendMode, strength: f32) -> [f32; 4] {
|
||||
let (source_alpha, backdrop_alpha) = (source[3], backdrop[3]);
|
||||
if source_alpha <= 0. {
|
||||
return backdrop;
|
||||
@@ -31,18 +21,14 @@ fn blend_pixel_at_strength(source: [f32; 4], backdrop: [f32; 4], blend_mode: Ble
|
||||
false => [0.; 3],
|
||||
};
|
||||
let (source_color, backdrop_color) = (straight(source), straight(backdrop));
|
||||
let blended = match strength < 1. {
|
||||
true => blend_at_strength(backdrop_color, source_color, blend_mode, strength),
|
||||
false => blend(backdrop_color, source_color, blend_mode),
|
||||
};
|
||||
let blended = blend(backdrop_color, source_color, blend_mode);
|
||||
|
||||
let shown = source_alpha * layer_fill_shown(backdrop_alpha, strength);
|
||||
let mut result = [0.; 4];
|
||||
for channel in 0..3 {
|
||||
let mixed = (1. - backdrop_alpha) * source_color[channel] + backdrop_alpha * blended[channel];
|
||||
result[channel] = shown * mixed + (1. - shown) * backdrop[channel];
|
||||
result[channel] = source_alpha * mixed + (1. - source_alpha) * backdrop[channel];
|
||||
}
|
||||
result[3] = shown + backdrop_alpha * (1. - shown);
|
||||
result[3] = source_alpha + backdrop_alpha * (1. - source_alpha);
|
||||
result
|
||||
}
|
||||
|
||||
@@ -53,22 +39,10 @@ fn blend(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode) -> [f32; 3
|
||||
BlendMode::Saturation => set_luminosity(set_saturation(backdrop, saturation(source)), luminosity(backdrop)),
|
||||
BlendMode::Color => set_luminosity(source, luminosity(backdrop)),
|
||||
BlendMode::Luminosity => set_luminosity(backdrop, luminosity(source)),
|
||||
blend_mode if blend_mode.reads_backdrop() => crate::blending::blend_gamma(backdrop, source, blend_mode),
|
||||
_ => [0, 1, 2].map(|channel| blend_channel(backdrop[channel], source[channel], blend_mode)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The blend of straight `backdrop` and `source` colors with the source at `strength`, moved toward the mode's neutral color (see [`apply_blend_mode_at_strength`]).
|
||||
fn blend_at_strength(backdrop: [f32; 3], source: [f32; 3], blend_mode: BlendMode, strength: f32) -> [f32; 3] {
|
||||
if !blend_mode.strength_moves_toward_neutral() {
|
||||
return blend(backdrop, source, blend_mode);
|
||||
}
|
||||
|
||||
let color = |[red, green, blue]: [f32; 3]| Color::from_rgbaf32_unchecked(red, green, blue, 1.);
|
||||
let blended = apply_blend_mode_at_strength(color(source), color(backdrop), blend_mode, strength);
|
||||
[blended.r(), blended.g(), blended.b()]
|
||||
}
|
||||
|
||||
/// The mode's blend of one channel of the backdrop and source, for the modes that blend each channel on its own.
|
||||
fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
let hard_light = |backdrop: f32, source: f32| match source <= 0.5 {
|
||||
@@ -82,8 +56,8 @@ fn blend_channel(backdrop: f32, source: f32, blend_mode: BlendMode) -> f32 {
|
||||
BlendMode::Overlay => hard_light(source, backdrop),
|
||||
BlendMode::Darken => backdrop.min(source),
|
||||
BlendMode::Lighten => backdrop.max(source),
|
||||
BlendMode::ColorDodge if backdrop <= BLEND_EDGE_TOLERANCE => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. - BLEND_EDGE_TOLERANCE => 1.,
|
||||
BlendMode::ColorDodge if backdrop <= 0. => 0.,
|
||||
BlendMode::ColorDodge if source >= 1. => 1.,
|
||||
BlendMode::ColorDodge => (backdrop / (1. - source)).min(1.),
|
||||
BlendMode::ColorBurn if backdrop >= 1. => 1.,
|
||||
BlendMode::ColorBurn if source <= 0. => 0.,
|
||||
@@ -168,195 +142,6 @@ mod tests {
|
||||
assert!((screened[0] - (0.5 * 0.75 + 0.5 * 0.5)).abs() < 1e-6);
|
||||
}
|
||||
|
||||
/// The reference formulas, for PSD interop, for the modes CSS lacks and for Color Burn and Color Dodge, at full strength, on a channel of straight gamma-encoded `backdrop` and `source` colors.
|
||||
fn reference_formula(blend_mode: BlendMode, backdrop: [f32; 3], source: [f32; 3]) -> [f32; 3] {
|
||||
let luma = |color: [f32; 3]| 0.3 * color[0] + 0.59 * color[1] + 0.11 * color[2];
|
||||
let color_burn = |b: f32, s: f32| {
|
||||
if b >= 1. {
|
||||
1.
|
||||
} else if s <= 0. {
|
||||
0.
|
||||
} else {
|
||||
1. - ((1. - b) / s).min(1.)
|
||||
}
|
||||
};
|
||||
let color_dodge = |b: f32, s: f32| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s >= 1. {
|
||||
1.
|
||||
} else {
|
||||
(b / (1. - s)).min(1.)
|
||||
}
|
||||
};
|
||||
let channels = |formula: &dyn Fn(f32, f32) -> f32| [0, 1, 2].map(|channel| formula(backdrop[channel], source[channel]).clamp(0., 1.));
|
||||
|
||||
match blend_mode {
|
||||
BlendMode::ColorBurn => channels(&color_burn),
|
||||
BlendMode::ColorDodge => channels(&color_dodge),
|
||||
BlendMode::LinearBurn => channels(&|b, s| b + s - 1.),
|
||||
BlendMode::LinearDodge => channels(&|b, s| b + s),
|
||||
BlendMode::VividLight => channels(&|b, s| if s <= 0.5 { color_burn(b, 2. * s) } else { color_dodge(b, 2. * s - 1.) }),
|
||||
BlendMode::LinearLight => channels(&|b, s| b + 2. * s - 1.),
|
||||
BlendMode::PinLight => channels(&|b, s| if s <= 0.5 { b.min(2. * s) } else { b.max(2. * s - 1.) }),
|
||||
BlendMode::HardMix => channels(&|b, s| 256. * b - 255. * (1. - s)),
|
||||
BlendMode::Subtract => channels(&|b, s| b - s),
|
||||
BlendMode::Divide => channels(&|b, s| {
|
||||
if b <= 0. {
|
||||
0.
|
||||
} else if s <= 0. {
|
||||
1.
|
||||
} else {
|
||||
b / s
|
||||
}
|
||||
}),
|
||||
BlendMode::DarkerColor => {
|
||||
if luma(source) < luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
BlendMode::LighterColor => {
|
||||
if luma(source) > luma(backdrop) {
|
||||
source
|
||||
} else {
|
||||
backdrop
|
||||
}
|
||||
}
|
||||
_ => panic!("{blend_mode} blends natively"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Pairs of a backdrop and a source color, away from Hard Mix's ramp and the lumas' ties.
|
||||
const PAIRS: [([f32; 3], [f32; 3]); 4] = [
|
||||
([0.2, 0.6, 0.45], [0.85, 0.3, 0.6]),
|
||||
([0.9, 0.1, 0.5], [0.3, 0.7, 0.2]),
|
||||
([0.55, 0.55, 0.55], [0.05, 0.95, 0.35]),
|
||||
([0., 1., 0.3], [0.6, 0.15, 0.8]),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn modes_css_lacks_take_the_reference_formulas_over_any_backdrop() {
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let expected = reference_formula(blend_mode, backdrop, source);
|
||||
let opaque = |[red, green, blue]: [f32; 3]| [red, green, blue, 1.];
|
||||
|
||||
// Over an opaque backdrop, the source takes the formula
|
||||
let blended = blend_pixel(opaque(source), opaque(backdrop), blend_mode);
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
|
||||
// Over one of half alpha, its color mixes halfway from its own to the formula's, as the 16 native modes do
|
||||
let half = [backdrop[0] * 0.5, backdrop[1] * 0.5, backdrop[2] * 0.5, 0.5];
|
||||
let blended = blend_pixel(opaque(source), half, blend_mode);
|
||||
for channel in 0..3 {
|
||||
let mixed = 0.5 * source[channel] + 0.5 * expected[channel];
|
||||
assert!((blended[channel] - mixed).abs() < 1e-5, "{blend_mode} over half alpha: {blended:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_move_the_content_toward_neutral_in_seven_modes_and_fade_it_in_the_others() {
|
||||
let fill = 0.5;
|
||||
let reading = BlendMode::list().into_iter().flatten().copied().filter(BlendMode::reads_backdrop);
|
||||
for blend_mode in reading.chain([BlendMode::ColorDodge, BlendMode::ColorBurn]) {
|
||||
for (backdrop, source) in PAIRS {
|
||||
let blended = blend_layer_pixel([source[0], source[1], source[2], 1.], [backdrop[0], backdrop[1], backdrop[2], 1.], blend_mode, fill);
|
||||
|
||||
let expected = match blend_mode {
|
||||
// The paint at full strength once moved halfway toward black, white, or middle gray
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => reference_formula(blend_mode, backdrop, source.map(|channel| fill * channel)),
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => reference_formula(blend_mode, backdrop, source.map(|channel| 1. - fill * (1. - channel))),
|
||||
BlendMode::VividLight | BlendMode::LinearLight => reference_formula(blend_mode, backdrop, source.map(|channel| 0.5 + fill * (channel - 0.5))),
|
||||
// A ramp a fill of half makes `clamp(2b - 1 + s)`
|
||||
BlendMode::HardMix => [0, 1, 2].map(|channel| Color::blend_hard_mix_at_strength(backdrop[channel], source[channel], fill).clamp(0., 1.)),
|
||||
// Halfway from the backdrop to the blend
|
||||
_ => {
|
||||
let full = reference_formula(blend_mode, backdrop, source);
|
||||
[0, 1, 2].map(|channel| backdrop[channel] + (full[channel] - backdrop[channel]) * fill)
|
||||
}
|
||||
};
|
||||
assert!(
|
||||
(0..3).all(|channel| (blended[channel] - expected[channel]).abs() < 1e-5),
|
||||
"{blend_mode}: {blended:?} rather than {expected:?}"
|
||||
);
|
||||
assert!((blended[3] - 1.).abs() < 1e-6, "{blend_mode} covers the opaque backdrop");
|
||||
}
|
||||
}
|
||||
|
||||
// Where nothing lies beneath, the fill fades the content as it is, as a fill fades content in the other modes
|
||||
let faded = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.; 4], BlendMode::LinearDodge, fill);
|
||||
assert!(faded.iter().zip([0.4, 0.2, 0.1, 0.5]).all(|(channel, expected)| (channel - expected).abs() < 1e-6), "{faded:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fills_moving_layers_toward_neutral_blend_their_share_at_full_strength_over_opaque_backdrops_and_change_nothing_at_no_fill() {
|
||||
let close = |ours: [f32; 4], expected: [f32; 4]| ours.iter().zip(expected).all(|(ours, expected)| (ours - expected).abs() < 1e-5);
|
||||
let premultiplied = |[red, green, blue]: [f32; 3], alpha: f32| [red * alpha, green * alpha, blue * alpha, alpha];
|
||||
let pushed = |blend_mode: BlendMode, source: [f32; 3], fill: f32| {
|
||||
source.map(|channel| match blend_mode {
|
||||
BlendMode::ColorDodge | BlendMode::LinearDodge => fill * channel,
|
||||
BlendMode::ColorBurn | BlendMode::LinearBurn => 1. - fill * (1. - channel),
|
||||
_ => 0.5 + fill * (channel - 0.5),
|
||||
})
|
||||
};
|
||||
|
||||
let modes = [
|
||||
BlendMode::ColorDodge,
|
||||
BlendMode::ColorBurn,
|
||||
BlendMode::LinearDodge,
|
||||
BlendMode::LinearBurn,
|
||||
BlendMode::VividLight,
|
||||
BlendMode::LinearLight,
|
||||
];
|
||||
for blend_mode in modes {
|
||||
for (backdrop, source) in PAIRS {
|
||||
for alpha in [1., 0.5] {
|
||||
for fill in [0., 0.3, 1.] {
|
||||
// Over an opaque backdrop, the content's share blends the paint moved toward neutral at full strength, the rest showing the backdrop, for PSD interop
|
||||
let full = reference_formula(blend_mode, backdrop, pushed(blend_mode, source, fill));
|
||||
let expected = [0, 1, 2].map(|channel| alpha * full[channel] + (1. - alpha) * backdrop[channel]);
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), premultiplied(backdrop, 1.), blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(expected, 1.)), "{blend_mode} at fill {fill}, alpha {alpha}: {blended:?}");
|
||||
|
||||
// Over nothing, the fill fades the content as it is
|
||||
let blended = blend_layer_pixel(premultiplied(source, alpha), [0.; 4], blend_mode, fill);
|
||||
assert!(close(blended, premultiplied(source, alpha * fill)), "{blend_mode} at fill {fill} over nothing: {blended:?}");
|
||||
}
|
||||
|
||||
for backdrop_alpha in [0.25, 0.5, 0.75] {
|
||||
let beneath = premultiplied(backdrop, backdrop_alpha);
|
||||
|
||||
// No fill leaves a partly covering backdrop as it is, alpha included
|
||||
let unfilled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 0.);
|
||||
assert!(close(unfilled, beneath), "{blend_mode} at no fill over alpha {backdrop_alpha}: {unfilled:?}");
|
||||
|
||||
// A full fill blends by the W3C's general formula, mixing toward the blend as far as the backdrop covers
|
||||
let blend = reference_formula(blend_mode, backdrop, source);
|
||||
let mixed = [0, 1, 2].map(|channel| (1. - backdrop_alpha) * source[channel] + backdrop_alpha * blend[channel]);
|
||||
let expected = [0, 1, 2]
|
||||
.map(|channel| alpha * mixed[channel] + (1. - alpha) * beneath[channel])
|
||||
.into_iter()
|
||||
.chain([alpha + (1. - alpha) * backdrop_alpha])
|
||||
.collect::<Vec<f32>>();
|
||||
let filled = blend_layer_pixel(premultiplied(source, alpha), beneath, blend_mode, 1.);
|
||||
assert!(close(filled, expected.try_into().unwrap()), "{blend_mode} at full fill over alpha {backdrop_alpha}: {filled:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// An opaque layer at no fill over half alpha leaves that alpha
|
||||
let unfilled = blend_layer_pixel([0.8, 0.4, 0.2, 1.], [0.25, 0.25, 0.25, 0.5], BlendMode::LinearDodge, 0.);
|
||||
assert!((unfilled[3] - 0.5).abs() < 1e-6, "{unfilled:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_luminosity_of_black_over_any_gray_is_black() {
|
||||
for level in 0..=255 {
|
||||
|
||||
@@ -4,12 +4,18 @@ pub mod adjustment_steps;
|
||||
pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_planning;
|
||||
pub mod effect_kernels;
|
||||
pub mod filter_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod layer_blending;
|
||||
pub mod mandelbrot;
|
||||
pub mod masks;
|
||||
pub mod raster_effects;
|
||||
pub mod resample_kernels;
|
||||
pub mod value_effects;
|
||||
pub mod warp_kernels;
|
||||
|
||||
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::Luminance).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,9 +5,8 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
||||
use crate::blending::overlay_paint;
|
||||
use core_types::Color;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, 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::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||
use graphic_types::effects::{EffectOperation, Effects};
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
@@ -30,47 +29,6 @@ pub fn adjustments(effects: &Effects) -> Vec<Adjustment> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A step a value's Blend Ifs take among its adjustments (see [`content_blend_ifs`]).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum BlendIfStep {
|
||||
/// A Blend If reads the value's colors and fades the value by these content ranges, as a fill does.
|
||||
Fade(ChannelRanges),
|
||||
/// An effect run after the first starts (see [`Effects::runs`]), taking the value as the runs before it leave it as its content at full strength.
|
||||
NextRun,
|
||||
}
|
||||
|
||||
/// Where each Blend If among the effects that fades a value by its own colors reads it, after how many of the [`adjustments`], with where each effect run after the first starts.
|
||||
/// Empty if no Blend If fades the value.
|
||||
pub fn content_blend_ifs(effects: &Effects) -> Vec<(usize, BlendIfStep)> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
if !fades_content(&operations) {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
// Each run's Blend Ifs act from its own start, as the renderers draw each run's effects on the result of those before it
|
||||
let mut adjustments_before = 0;
|
||||
let mut steps = Vec::new();
|
||||
for (run_index, (_, rows)) in effects.runs().into_iter().enumerate() {
|
||||
if run_index > 0 {
|
||||
steps.push((adjustments_before, BlendIfStep::NextRun));
|
||||
}
|
||||
|
||||
let run = &operations[rows];
|
||||
for (row, operation) in run.iter().enumerate() {
|
||||
let acting = blend_ifs_acting_before(run, row).into_iter().filter(|ranges| !ranges.content.show_everything());
|
||||
steps.extend(acting.map(|ranges| (adjustments_before, BlendIfStep::Fade(ranges.content))));
|
||||
|
||||
adjustments_before += usize::from(matches!(operation, EffectOperation::Adjustment(_)));
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// Whether a Blend If fades a value with effects in more than one run, so later runs read and paint within the result of those before them.
|
||||
pub fn blend_ifs_span_runs(effects: &Effects) -> bool {
|
||||
content_blend_ifs(effects).iter().any(|(_, step)| *step == BlendIfStep::NextRun)
|
||||
}
|
||||
|
||||
/// The color with `adjustments` carried out on it in order.
|
||||
pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
adjustments.iter().fold(color, |color, adjustment| adjust_color(adjustment, color))
|
||||
@@ -79,60 +37,19 @@ pub fn adjusted_color(color: Color, adjustments: &[Adjustment]) -> Color {
|
||||
/// The color an endless paint of `color` shows with `adjustments` carried out over it and its `fill` fading it, though not the paint overlays painted over it.
|
||||
/// Without edges, each paint overlay blends with the paint itself, which is exact where the paint is opaque.
|
||||
pub fn filled_color(color: Color, adjustments: &[Adjustment], fill: f32) -> Color {
|
||||
filled_color_with_blend_ifs(color, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Like [`filled_color`], with the steps of the `blend_ifs` (see [`content_blend_ifs`]) also fading the paint by each one's content ranges where it reads the paint's colors.
|
||||
pub fn filled_color_with_blend_ifs(color: Color, adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Color {
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
if fill >= 1. {
|
||||
return adjusted_color(color, adjustments);
|
||||
}
|
||||
fill_through(color, adjustments, blend_ifs, fill, |index, color| adjust_color(&adjustments[index], color), ChannelRanges::weight)
|
||||
fill_through(color, adjustments, fill, |index, color| adjust_color(&adjustments[index], color))
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` and the `blend_ifs` as [`filled_color_with_blend_ifs`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
/// `weigh` gives how strongly a Blend If's ranges show the gamma-encoded channels it reads.
|
||||
fn fill_through(
|
||||
color: Color,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
adjust: impl Fn(usize, Color) -> Color,
|
||||
mut weigh: impl FnMut(&ChannelRanges, [f64; 3]) -> f64,
|
||||
) -> Color {
|
||||
// Each Blend If fades the faded color by how strongly it shows the full-strength one, which each later run resets to the faded color
|
||||
let mut steps = blend_ifs.iter().peekable();
|
||||
let mut take_steps = |full: &mut Color, filled: &mut Color, adjusted_count: usize| {
|
||||
let mut weight = 1.;
|
||||
let mut faded = false;
|
||||
while let Some((_, step)) = steps.next_if(|(before, _)| *before <= adjusted_count) {
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
let [red, green, blue, _] = full.to_gamma_srgb_channels();
|
||||
weight *= weigh(ranges, [red, green, blue].map(f64::from));
|
||||
faded = true;
|
||||
}
|
||||
BlendIfStep::NextRun => {
|
||||
*filled = filled.with_alpha(filled.a() * std::mem::replace(&mut weight, 1.) as f32);
|
||||
*full = *filled;
|
||||
}
|
||||
}
|
||||
}
|
||||
*filled = filled.with_alpha(filled.a() * weight as f32);
|
||||
faded
|
||||
};
|
||||
|
||||
/// Carries out `adjustments` over a paint faded by `fill` as [`filled_color`] does, with `adjust` carrying out each one besides a paint overlay, given its index.
|
||||
fn fill_through(color: Color, adjustments: &[Adjustment], fill: f32, adjust: impl Fn(usize, Color) -> Color) -> Color {
|
||||
// The color at full strength, which each paint overlay blends with, and the color the fill fades, which it paints over at full strength
|
||||
let (mut full, mut filled) = (color, color.with_alpha(color.a() * fill));
|
||||
|
||||
// Once a Blend If fades them, adjustments keep the colors empty where they're empty, as the renderers keep empty pixels
|
||||
let mut faded = false;
|
||||
for (index, adjustment) in adjustments.iter().enumerate() {
|
||||
faded |= take_steps(&mut full, &mut filled, index);
|
||||
|
||||
let Adjustment::ColorOverlay { color: paint, blend_mode, opacity } = *adjustment else {
|
||||
let adjusted = |color: Color| if !faded || color.a() > 0. { adjust(index, color) } else { color };
|
||||
(full, filled) = (adjusted(full), adjusted(filled));
|
||||
(full, filled) = (adjust(index, full), adjust(index, filled));
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -147,39 +64,18 @@ fn fill_through(
|
||||
filled = Color::from_gamma_srgb_channels(mix(red, under_red), mix(green, under_green), mix(blue, under_blue), alpha);
|
||||
full = overlay_paint(full, paint, blend_mode, (opacity / 100.) as f32);
|
||||
}
|
||||
take_steps(&mut full, &mut filled, adjustments.len());
|
||||
filled
|
||||
}
|
||||
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` and the `blend_ifs` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
/// Carries out `adjustments` in order on any number of colors with the `fill` fading them, with each one's kernel prepared once.
|
||||
fn prepared(adjustments: &[Adjustment], fill: f32) -> Box<dyn Fn(Color) -> Color> {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
if fill >= 1. && blend_ifs.is_empty() {
|
||||
if fill >= 1. {
|
||||
return Box::new(move |color| kernels.iter().fold(color, |color, kernel| kernel.adjust(color)));
|
||||
}
|
||||
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
Box::new(move |color| fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), ChannelRanges::weight))
|
||||
}
|
||||
|
||||
/// Tells apart the colors each channel's range of each of the `blend_ifs` shows fully, partly, or not at all, as it reads them where [`fill_through`] fades by it.
|
||||
fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep)], fill: f32) -> impl Fn(Color) -> u64 {
|
||||
let kernels: Vec<PreparedAdjustment> = adjustments.iter().map(PreparedAdjustment::new).collect();
|
||||
let (adjustments, blend_ifs) = (adjustments.to_vec(), blend_ifs.to_vec());
|
||||
|
||||
// Each channel's state (hidden, partly shown, or shown) is a digit in base 3, so up to ten Blend Ifs stay apart exactly
|
||||
move |color| {
|
||||
let mut region = 0_u64;
|
||||
let weigh = |ranges: &ChannelRanges, channels: [f64; 3]| {
|
||||
for weight in ranges.channel_weights(channels) {
|
||||
let state = u64::from(weight > 0.) + u64::from(weight >= 1.);
|
||||
region = region.wrapping_mul(3).wrapping_add(state);
|
||||
}
|
||||
ranges.weight(channels)
|
||||
};
|
||||
fill_through(color, &adjustments, &blend_ifs, fill, |index, color| kernels[index].adjust(color), weigh);
|
||||
region
|
||||
}
|
||||
let adjustments = adjustments.to_vec();
|
||||
Box::new(move |color| fill_through(color, &adjustments, fill, |index, color| kernels[index].adjust(color)))
|
||||
}
|
||||
|
||||
/// The gradient with `adjustments` carried out along its ramp, with the settings to read the result with, or `None` if there are no adjustments.
|
||||
@@ -187,28 +83,17 @@ fn blend_if_regions(adjustments: &[Adjustment], blend_ifs: &[(usize, BlendIfStep
|
||||
/// A stepped ramp holds each stop's color, so adjusting the stops is exact. Elsewhere an adjustment can bend the ramp between stops,
|
||||
/// so the adjusted ramp is resampled into stops that interpolate linearly in gamma.
|
||||
pub fn adjusted_gradient(gradient: &Gradient, settings: GradientSettings, adjustments: &[Adjustment], fill: f32) -> Option<(Gradient, GradientSettings)> {
|
||||
adjusted_gradient_with_blend_ifs(gradient, settings, adjustments, &[], fill)
|
||||
}
|
||||
|
||||
/// Like [`adjusted_gradient`], with the `blend_ifs` also fading the ramp as [`filled_color_with_blend_ifs`] fades a color, or `None` if there are neither adjustments nor Blend Ifs.
|
||||
pub fn adjusted_gradient_with_blend_ifs(
|
||||
gradient: &Gradient,
|
||||
settings: GradientSettings,
|
||||
adjustments: &[Adjustment],
|
||||
blend_ifs: &[(usize, BlendIfStep)],
|
||||
fill: f32,
|
||||
) -> Option<(Gradient, GradientSettings)> {
|
||||
if adjustments.is_empty() && blend_ifs.is_empty() {
|
||||
if adjustments.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// A gradient without stops reads as black, so its adjusted ramp is one stop of the adjusted black
|
||||
if gradient.is_empty() {
|
||||
return Some((Gradient::from(vec![prepared(adjustments, blend_ifs, fill)(Color::BLACK)]), settings));
|
||||
return Some((Gradient::from(vec![prepared(adjustments, fill)(Color::BLACK)]), settings));
|
||||
}
|
||||
|
||||
if settings.interpolation == GradientInterpolation::Stepped {
|
||||
let adjust = prepared(adjustments, blend_ifs, fill);
|
||||
let adjust = prepared(adjustments, fill);
|
||||
return Some((gradient.map_colors(|color| adjust(*color)), settings));
|
||||
}
|
||||
|
||||
@@ -217,16 +102,6 @@ pub fn adjusted_gradient_with_blend_ifs(
|
||||
gradient.cache_hash(&mut hasher);
|
||||
settings.cache_hash(&mut hasher);
|
||||
adjustments.iter().for_each(|adjustment| adjustment.cache_hash(&mut hasher));
|
||||
for (before, step) in blend_ifs {
|
||||
hasher.write_usize(*before);
|
||||
match step {
|
||||
BlendIfStep::Fade(ranges) => {
|
||||
hasher.write_u8(0);
|
||||
ranges.cache_hash(&mut hasher);
|
||||
}
|
||||
BlendIfStep::NextRun => hasher.write_u8(1),
|
||||
}
|
||||
}
|
||||
hasher.write_u32(fill.to_bits());
|
||||
let key = hasher.finish();
|
||||
|
||||
@@ -239,11 +114,7 @@ pub fn adjusted_gradient_with_blend_ifs(
|
||||
return Some(result);
|
||||
}
|
||||
|
||||
// A Blend If cuts the ramp off wherever the colors it reads cross its ranges, which may lie between the resampling's probes
|
||||
let resampled = match blend_ifs.is_empty() {
|
||||
true => gradient.map_ramp(settings, prepared(adjustments, blend_ifs, fill)),
|
||||
false => gradient.map_ramp_by_regions(settings, prepared(adjustments, blend_ifs, fill), blend_if_regions(adjustments, blend_ifs, fill)),
|
||||
};
|
||||
let resampled = gradient.map_ramp(settings, prepared(adjustments, fill));
|
||||
let resampled_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
@@ -258,84 +129,29 @@ pub fn adjusted_gradient_with_blend_ifs(
|
||||
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.
|
||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||
filled_color_after_effects(color, 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.
|
||||
pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> Color> {
|
||||
prepared(&adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||
}
|
||||
|
||||
/// 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)> {
|
||||
filled_gradient_after_effects(gradient, settings, 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.
|
||||
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`]).
|
||||
/// The color with the adjustments among its effects carried out and the effects consumed, for nodes that read the color.
|
||||
/// A color without the effects attribute is returned as it is.
|
||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
|
||||
let mut item = item;
|
||||
*item.element_mut() = color;
|
||||
*item.element_mut() = adjusted_color(*item.element(), &adjustments);
|
||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
||||
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 the adjustments among its effects carried out along its ramp and the effects consumed, for nodes that read its colors.
|
||||
/// A gradient without the effects attribute is returned as it is.
|
||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||
let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) else { return item };
|
||||
let Some(adjustments) = item.attribute::<Effects>(ATTR_EFFECTS).map(adjustments) else {
|
||||
return item;
|
||||
};
|
||||
let settings = GradientSettings::from_item_attributes(&item);
|
||||
let adjusted = gradient_after_effects(item.element(), settings, effects);
|
||||
|
||||
let mut item = item;
|
||||
let settings = match adjusted {
|
||||
let settings = match adjusted_gradient(item.element(), settings, &adjustments, 1.) {
|
||||
Some((gradient, adjusted_settings)) => {
|
||||
*item.element_mut() = gradient;
|
||||
adjusted_settings
|
||||
@@ -364,16 +180,6 @@ mod tests {
|
||||
actual.iter().zip(expected).all(|(actual, expected)| (actual - expected).abs() < 1e-4)
|
||||
}
|
||||
|
||||
/// The `element` with each row stamped on it while it's placed by the row's scale, so a row stamped at a new scale starts a run of its own.
|
||||
fn stamped<T>(element: T, rows: &[(EffectOperation, f64)]) -> Item<T> {
|
||||
let mut item = Item::new_from_element(element);
|
||||
for (operation, scale) in rows {
|
||||
item.set_attribute(core_types::ATTR_TRANSFORM, glam::DAffine2::from_scale(glam::DVec2::splat(*scale)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(operation));
|
||||
}
|
||||
item
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn paint_overlays_mix_in_gamma_unfaded_by_the_fill() {
|
||||
let half_white = [Adjustment::ColorOverlay {
|
||||
@@ -392,168 +198,6 @@ mod tests {
|
||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let unfilled = Item::new_from_element(Color::BLACK)
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
|
||||
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
||||
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
|
||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let invert = EffectOperation::Adjustment(Adjustment::Invert);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
});
|
||||
let black_through = |operations: Vec<EffectOperation>| evaluate_color_effects(Item::new_from_element(Color::BLACK).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations)));
|
||||
|
||||
// Black is hidden, whether inverted after the Blend If reads it or not, but shows once inverted before
|
||||
assert_eq!(black_through(vec![blend_if.clone()]).element().a(), 0.);
|
||||
assert_eq!(black_through(vec![blend_if.clone(), invert.clone()]).element().a(), 0.);
|
||||
assert!(close(gamma(*black_through(vec![invert, blend_if.clone()]).element()), [1.; 4]));
|
||||
|
||||
// An overlay after it paints over the hidden color at full strength, as over a fill of none, and the effects are consumed
|
||||
let overlaid = black_through(vec![blend_if.clone(), red]);
|
||||
assert!(close(gamma(*overlaid.element()), [1., 0., 0., 1.]));
|
||||
assert!(overlaid.attribute::<Effects>(ATTR_EFFECTS).is_none());
|
||||
|
||||
// A gradient's dark start is hidden and its light end shown
|
||||
let gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_EFFECTS, Effects::from_operations([blend_if]));
|
||||
let evaluated = evaluate_gradient_effects(gradient);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
assert!(evaluated.element().evaluate(0., settings).a() < 1e-6);
|
||||
assert!(close(gamma(evaluated.element().evaluate(1., settings)), [1.; 4]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consumed_values_fade_by_blend_ifs_reading_each_effect_run_as_the_runs_before_it_leave_it() {
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let overlay = |color: Color| {
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color,
|
||||
blend_mode: BlendMode::Normal,
|
||||
opacity: 100.,
|
||||
})
|
||||
};
|
||||
|
||||
// White painted blue is read as blue by a Blend If after a scale, which hides it, but in the same run the Blend If reads the white beneath the overlay
|
||||
let color_through = |color: Color, rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(color, rows)).element();
|
||||
assert_eq!(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::WHITE, &[(overlay(Color::BLUE), 1.), (blend_if.clone(), 1.)])), [0., 0., 1., 1.]));
|
||||
|
||||
// Black hidden before a scale leaves nothing for an overlay after it to paint within
|
||||
assert_eq!(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 2.)]).a(), 0.);
|
||||
assert!(close(gamma(color_through(Color::BLACK, &[(blend_if.clone(), 1.), (overlay(Color::RED), 1.)])), [1., 0., 0., 1.]));
|
||||
|
||||
// A ramp painted blue is hidden all along by a Blend If after a scale
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(overlay(Color::BLUE), 1.), (blend_if, 2.)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for t in [0., 0.25, 0.75, 1.] {
|
||||
let shown = evaluated.element().evaluate(t, settings);
|
||||
assert!(shown.a() < 1e-6, "hidden at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_a_blend_if_hides_stay_hidden_through_adjustments_raising_alpha_as_rasters_do() {
|
||||
use graphic_types::EffectKind;
|
||||
use graphic_types::blend_if::BlendIfRanges;
|
||||
|
||||
// Shown only where the gray is at least half
|
||||
let mut hides_darks = BlendIfRanges::default();
|
||||
hides_darks.content.gray.falloff_start = 50.;
|
||||
hides_darks.content.gray.range_start = 50.;
|
||||
let blend_if = EffectOperation::BlendIf(Box::new(hides_darks));
|
||||
let make_opaque = EffectOperation::default_for(EffectKind::MakeOpaque);
|
||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::RED,
|
||||
blend_mode: BlendMode::Normal,
|
||||
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)
|
||||
let black_through = |rows: &[(EffectOperation, f64)]| *evaluate_color_effects(stamped(Color::BLACK, rows)).element();
|
||||
|
||||
// Hidden black stays hidden when made opaque, in its run or the next, where an overlay finds nothing to paint within either
|
||||
let hidden = [
|
||||
("made opaque", vec![(blend_if.clone(), 1.), (make_opaque.clone(), 1.)]),
|
||||
("made opaque in the next run", vec![(blend_if.clone(), 1.), (make_opaque.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 {
|
||||
assert_eq!(black_through(&rows).a(), 0., "black {name}");
|
||||
}
|
||||
|
||||
// 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.)]);
|
||||
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
|
||||
for scale in [1., 2.] {
|
||||
let ramp = stamped(Gradient::from(vec![Color::BLACK, Color::WHITE]), &[(blend_if.clone(), 1.), (make_opaque.clone(), scale)]);
|
||||
let evaluated = evaluate_gradient_effects(ramp);
|
||||
let settings = GradientSettings::from_item_attributes(&evaluated);
|
||||
for (t, alpha) in [(0., 0.), (0.25, 0.), (0.75, 1.), (1., 1.)] {
|
||||
let shown = evaluated.element().evaluate(t, settings).a();
|
||||
assert!((shown - alpha).abs() < 1e-6, "the alpha at {t} with the scale {scale} is {shown}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ramp_keeps_the_band_a_blend_if_shows_between_where_resampling_probes_it() {
|
||||
use graphic_types::blend_if::{BlendIfRanges, BlendRange};
|
||||
|
||||
// Shown only where the gray lies from 30% to 40%, which neither end of the ramp nor any of its quarter points lands within
|
||||
let mut band = BlendIfRanges::default();
|
||||
band.content.gray = BlendRange {
|
||||
falloff_start: 30.,
|
||||
range_start: 30.,
|
||||
range_end: 40.,
|
||||
falloff_end: 40.,
|
||||
};
|
||||
let effects = Effects::from_operations([EffectOperation::BlendIf(Box::new(band))]);
|
||||
let gamma_settings = GradientSettings {
|
||||
space: GradientSpace::RgbGamma,
|
||||
interpolation: GradientInterpolation::Linear,
|
||||
..Default::default()
|
||||
};
|
||||
let (resampled, settings) = gradient_after_effects(&Gradient::from(vec![Color::BLACK, Color::WHITE]), gamma_settings, &effects).expect("the Blend If fades the ramp");
|
||||
|
||||
// The band shows its own grays from level 77 to 102, which lie from 30% to just past 40% along the ramp, with sharp edges
|
||||
for t in [0.301, 0.35, 0.4] {
|
||||
let shown = resampled.evaluate(t, settings);
|
||||
assert!(close(gamma(shown), [t as f32, t as f32, t as f32, 1.]), "the band shows at {t}: {:?}", gamma(shown));
|
||||
}
|
||||
for t in [0., 0.25, 0.299, 0.403, 0.5, 0.75, 1.] {
|
||||
assert!(resampled.evaluate(t, settings).a() < 1e-6, "hidden at {t}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gradient_without_stops_adjusts_the_black_it_reads_as() {
|
||||
let empty = Gradient::from(Vec::<Color>::new());
|
||||
|
||||
@@ -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;
|
||||
#[cfg(feature = "wgpu")]
|
||||
pub use gpu::{Texture, TextureWeakRef};
|
||||
|
||||
@@ -34,7 +34,6 @@ log = { workspace = true }
|
||||
num-traits = { workspace = true }
|
||||
usvg = { workspace = true }
|
||||
kurbo = { workspace = true }
|
||||
linesweeper = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
raster-kernels = { workspace = true }
|
||||
|
||||
@@ -1,23 +1,19 @@
|
||||
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
|
||||
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
|
||||
//! Content with an effect no filter can carry out or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
|
||||
//! are drawn as images in place of markup. Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||
//! Content with an effect no filter can carry out at all is drawn as an image of it in place of its markup.
|
||||
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
|
||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::raster_types::{CPU, Raster};
|
||||
use kurbo::{Affine, BezPath};
|
||||
use std::sync::Arc;
|
||||
use vello_gpu::peniko::Fill;
|
||||
|
||||
/// The most pixels across or down a map or image may have.
|
||||
pub const MAX_DEFERRED_IMAGE_PIXELS: u32 = 8192;
|
||||
@@ -187,12 +183,13 @@ pub fn substitute_effect_map(svg: &mut String, placement: &EffectMapPlacement, m
|
||||
svg.replace_range(span, &image);
|
||||
}
|
||||
|
||||
/// Content an SVG draws as an image the GPU renders of it, since SVG can't carry it out as markup.
|
||||
/// One item of content an SVG draws as an image the GPU renders of it, since its effects hold one SVG filters can't carry out.
|
||||
#[derive(Clone)]
|
||||
pub struct DeferredImage {
|
||||
/// Names the markers around the content's own markup in the SVG, which the image replaces.
|
||||
pub id: u64,
|
||||
pub content: DeferredContent,
|
||||
/// The item with its effects, but without its opacity and blend mode, which the image takes instead.
|
||||
pub content: Graphic,
|
||||
pub render_params: RenderParams,
|
||||
/// Maps the user space the markers sit in into the document.
|
||||
pub user_to_document: DAffine2,
|
||||
@@ -202,69 +199,6 @@ pub struct DeferredImage {
|
||||
pub margin: f64,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
/// The reference for the mask fading the image by Blend If's ranges of what lies beneath, if any.
|
||||
pub mask: Option<String>,
|
||||
}
|
||||
|
||||
/// What the GPU renders an image of for an SVG.
|
||||
#[derive(Clone)]
|
||||
pub enum DeferredContent {
|
||||
/// An item with effects SVG filters can't carry out or a paint SVG only approximates, but without its opacity and blend mode, which the image takes instead.
|
||||
Item(Graphic),
|
||||
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
||||
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
|
||||
Beneath { clip: Option<BezPath>, drawn: Vec<DrawnContent> },
|
||||
}
|
||||
|
||||
/// Content an SVG draws, which the GPU draws again into images of what lies beneath content drawn after it.
|
||||
#[derive(Clone)]
|
||||
pub struct DrawnContent {
|
||||
items: Arc<dyn DrawnItems>,
|
||||
/// How many of the items are drawn, since content drawn among them lies over only those before it.
|
||||
pub(crate) count: usize,
|
||||
/// Maps the user space the items are drawn in into the document.
|
||||
user_to_document: DAffine2,
|
||||
render_params: RenderParams,
|
||||
}
|
||||
|
||||
impl DrawnContent {
|
||||
/// The `items` drawn in a user space that `user_to_document` maps into the document, none of them drawn yet.
|
||||
pub(crate) fn new(items: Arc<dyn DrawnItems>, user_to_document: DAffine2, render_params: &RenderParams) -> Self {
|
||||
Self {
|
||||
items,
|
||||
count: 0,
|
||||
user_to_document,
|
||||
render_params: render_params.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A list of graphical content, or one item of it, whose first items the GPU can draw.
|
||||
pub(crate) trait DrawnItems: Send + Sync {
|
||||
/// Draws the first `count` items into a scene of the document, from the user space that `transform` maps into it.
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams);
|
||||
}
|
||||
|
||||
impl<T: Clone + Send + Sync + 'static> DrawnItems for List<T>
|
||||
where
|
||||
List<T>: Render,
|
||||
{
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count >= self.len() {
|
||||
return self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
|
||||
let first: List<T> = (0..count).filter_map(|index| self.clone_item(index)).collect();
|
||||
first.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
|
||||
impl DrawnItems for Graphic {
|
||||
fn draw_first(&self, count: usize, scene: &mut VelloSceneBuilder, transform: DAffine2, render_params: &RenderParams) {
|
||||
if count > 0 {
|
||||
self.render_to_vello(scene, transform, render_params);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an SVG draws the image the GPU rendered of an item of deferred content.
|
||||
@@ -278,7 +212,6 @@ pub struct DeferredImagePlacement {
|
||||
pub user_to_document: DAffine2,
|
||||
pub opacity: f32,
|
||||
pub blend_mode: BlendMode,
|
||||
pub mask: Option<String>,
|
||||
/// Whether the image is drawn to a canvas rather than embedded in the SVG.
|
||||
pub to_canvas: bool,
|
||||
/// Screen pixels per document unit, which sizes an image drawn to a canvas.
|
||||
@@ -292,22 +225,9 @@ pub struct DeferredImageLayout {
|
||||
pub size: UVec2,
|
||||
}
|
||||
|
||||
/// The starts of the markers around the markup standing in for an item of deferred content, which its ID and `-->` follow.
|
||||
pub(crate) const DEFERRED_IMAGE_OPENING: &str = "<!--deferred-image-";
|
||||
pub(crate) const DEFERRED_IMAGE_CLOSING: &str = "<!--/deferred-image-";
|
||||
|
||||
/// The starts of the markers around a copy of that markup in a Blend If mask, which can't draw the canvas of its image, followed by its ID, a hyphen and the key color's hex (for the opening), and `-->`.
|
||||
pub(crate) const DEFERRED_COVER_OPENING: &str = "<!--deferred-cover-";
|
||||
pub(crate) const DEFERRED_COVER_CLOSING: &str = "<!--/deferred-cover-";
|
||||
|
||||
/// The markers that open and close the markup standing in for the item of deferred content `id` names.
|
||||
pub(crate) fn image_markers(id: u64) -> (String, String) {
|
||||
(format!("{DEFERRED_IMAGE_OPENING}{id}-->"), format!("{DEFERRED_IMAGE_CLOSING}{id}-->"))
|
||||
}
|
||||
|
||||
/// Whether the `markup` holds markers of markup standing in for an item of deferred content.
|
||||
pub(crate) fn holds_image_markers(markup: &str) -> bool {
|
||||
markup.contains(DEFERRED_IMAGE_OPENING)
|
||||
(format!("<!--deferred-image-{id}-->"), format!("<!--/deferred-image-{id}-->"))
|
||||
}
|
||||
|
||||
impl DeferredImage {
|
||||
@@ -322,7 +242,6 @@ impl DeferredImage {
|
||||
user_to_document: self.user_to_document,
|
||||
opacity: self.opacity,
|
||||
blend_mode: self.blend_mode,
|
||||
mask: self.mask.clone(),
|
||||
to_canvas: self.render_params.to_canvas(),
|
||||
canvas_image_scale: self.render_params.canvas_image_scale,
|
||||
},
|
||||
@@ -333,25 +252,8 @@ impl DeferredImage {
|
||||
|
||||
/// Draws the content with its effects into a scene of the document, which the `layout` places in the image's pixels.
|
||||
pub fn draw(&self, scene: &mut VelloSceneBuilder, layout: &DeferredImageLayout) {
|
||||
let image_params = |render_params: &RenderParams| image_render_params(render_params, layout.document_to_pixels, layout.size);
|
||||
|
||||
match &self.content {
|
||||
DeferredContent::Item(content) => content.render_to_vello(scene, self.user_to_document, &image_params(&self.render_params)),
|
||||
DeferredContent::Beneath { clip, drawn } => {
|
||||
// A clip rather than a layer, within which content reading what lies beneath it would find nothing
|
||||
if let Some(clip) = clip {
|
||||
scene.push_clip_layer(Fill::NonZero, Affine::IDENTITY, clip);
|
||||
}
|
||||
|
||||
for drawn in drawn {
|
||||
drawn.items.draw_first(drawn.count, scene, drawn.user_to_document, &image_params(&drawn.render_params));
|
||||
}
|
||||
|
||||
if clip.is_some() {
|
||||
scene.pop_layer();
|
||||
}
|
||||
}
|
||||
}
|
||||
self.content
|
||||
.render_to_vello(scene, self.user_to_document, &image_render_params(&self.render_params, layout.document_to_pixels, layout.size));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -370,41 +272,11 @@ pub fn substitute_deferred_image(svg: &mut String, image_data: &mut Vec<(u64, Ca
|
||||
canvas_image_scale: placement.canvas_image_scale,
|
||||
..Default::default()
|
||||
};
|
||||
let opacity = if placement.opacity < 1. { format!(r#" opacity="{}""#, placement.opacity) } else { String::new() };
|
||||
let style = if placement.blend_mode != BlendMode::Normal {
|
||||
format!(r#" style="{}""#, placement.blend_mode.render())
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
|
||||
// A mask goes on a group taking the image's opacity and blend mode, which still blends with what lies beneath
|
||||
let markup = match &placement.mask {
|
||||
Some(mask) => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, 1., BlendMode::Normal, &mut render, &render_params);
|
||||
format!(r#"<g mask="{mask}"{opacity}{style}>{}</g>"#, render.svg.to_svg_string())
|
||||
}
|
||||
None => {
|
||||
render_raster_cpu_image_svg(image, placement.transform, placement.opacity, placement.blend_mode, &mut render, &render_params);
|
||||
render.svg.to_svg_string()
|
||||
}
|
||||
};
|
||||
let markup = render.svg.to_svg_string();
|
||||
while let Some(span) = marked_span(svg, &opening, &closing) {
|
||||
svg.replace_range(span, &markup);
|
||||
}
|
||||
image_data.extend(render.image_data);
|
||||
|
||||
// A Blend If mask can't draw the canvas in its copy of what lies beneath, so a rectangle of the color its ranges show in full covers the image there
|
||||
if placement.to_canvas {
|
||||
let (opening, closing) = (format!("{DEFERRED_COVER_OPENING}{}-", placement.id), format!("{DEFERRED_COVER_CLOSING}{}-->", placement.id));
|
||||
let transform = format_transform_matrix(placement.transform);
|
||||
while let Some(start) = svg.find(&opening) {
|
||||
let key_start = start + opening.len();
|
||||
let Some(key_end) = svg[key_start..].find("-->").map(|offset| key_start + offset) else { break };
|
||||
let Some(end) = svg[key_end..].find(&closing).map(|offset| key_end + offset + closing.len()) else {
|
||||
break;
|
||||
};
|
||||
let cover = format!(r##"<rect width="1" height="1" transform="{transform}" fill="#{}"{opacity}{style} />"##, &svg[key_start..key_end]);
|
||||
svg.replace_range(start..end, &cover);
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user