mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-06 08:13:40 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13bb1687b9 | ||
|
|
674221fbc3 | ||
|
|
1300b4f92a | ||
|
|
c0778752ab | ||
|
|
27cded81af | ||
|
|
d5fdb12320 |
No files matched your search
@@ -29,8 +29,6 @@ const DAILY_LIMIT_PER_CONTRIBUTOR = 40;
|
|||||||
const MAX_RUN_PAGES = 10;
|
const MAX_RUN_PAGES = 10;
|
||||||
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
|
// The workflow step that fails only when a run reached a verdict against its title, by the end of its name
|
||||||
const VERDICT_STEP_NAME = "Fail for the title's verdict";
|
const VERDICT_STEP_NAME = "Fail for the title's verdict";
|
||||||
// The workflow step that passes a run whose title changed while it ran, without a verdict, by the end of its name
|
|
||||||
const SUPERSEDED_STEP_NAME = "Pass for a newer run's review";
|
|
||||||
const MAX_VERDICT_LOOKUPS = 5;
|
const MAX_VERDICT_LOOKUPS = 5;
|
||||||
|
|
||||||
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
// How much of the PR's changes accompany the title, which keeps the message under about 20,000 tokens
|
||||||
@@ -177,15 +175,14 @@ async function listBranchRuns(workflowId: number, before?: number): Promise<Work
|
|||||||
return newestFirst(runs);
|
return newestFirst(runs);
|
||||||
}
|
}
|
||||||
|
|
||||||
// The newest finished run that reached a verdict on its title, skipping those that didn't (as when a service was unreachable or the title changed mid-run)
|
// The newest of the finished runs that reached a verdict on its title, skipping failures that didn't (such as when GitHub or the review service couldn't be reached)
|
||||||
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
|
async function latestVerdictRun(finishedRunsNewestFirst: WorkflowRun[]): Promise<WorkflowRun | undefined> {
|
||||||
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
for (let i = 0; i < Math.min(finishedRunsNewestFirst.length, MAX_VERDICT_LOOKUPS); i++) {
|
||||||
const run = finishedRunsNewestFirst[i];
|
const run = finishedRunsNewestFirst[i];
|
||||||
|
if (run.conclusion === "success") return run;
|
||||||
|
|
||||||
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
|
const { jobs } = await github<{ jobs: { steps?: { name: string; conclusion: string | null }[] }[] }>("GET", `/repos/${repository}/actions/runs/${run.id}/jobs`);
|
||||||
const steps = jobs.flatMap((job) => job.steps || []);
|
const steps = jobs.flatMap((job) => job.steps || []);
|
||||||
if (steps.some((step) => step.name.endsWith(SUPERSEDED_STEP_NAME) && step.conclusion === "success")) continue;
|
|
||||||
if (run.conclusion === "success") return run;
|
|
||||||
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
|
if (steps.some((step) => step.name.endsWith(VERDICT_STEP_NAME) && step.conclusion === "failure")) return run;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ const pullRequestNumber = readEvent().pull_request.number;
|
|||||||
const decision = readDecision();
|
const decision = readDecision();
|
||||||
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
const retried = RETRIED_OUTCOMES.includes(decision.outcome);
|
||||||
const passed = PASSING_OUTCOMES.includes(decision.outcome);
|
const passed = PASSING_OUTCOMES.includes(decision.outcome);
|
||||||
const superseded = decision.outcome === "superseded";
|
|
||||||
|
|
||||||
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
|
// New feedback replaces earlier comments so the latest is at the bottom of the conversation, while carried-over and retried outcomes leave them be
|
||||||
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
|
if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" && !retried) {
|
||||||
@@ -48,10 +47,10 @@ if (decision.outcome !== "unchanged" && decision.outcome !== "still_approved" &&
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`::${passed || superseded ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
console.log(`::${passed ? "notice" : "error"}::${ANNOTATIONS[decision.outcome]}`);
|
||||||
|
|
||||||
// Later runs tell verdicts, retries, and superseded runs apart by which of the workflow's last steps each one ran
|
// The workflow fails a different step for a verdict against the title than for an outcome to retry, which later runs read back to tell them apart
|
||||||
const result = passed ? "approved" : superseded ? "superseded" : retried ? "retry" : "verdict";
|
const result = passed ? "approved" : retried ? "retry" : "verdict";
|
||||||
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
fs.appendFileSync(requireEnvironment("GITHUB_OUTPUT"), `result=${result}\n`);
|
||||||
|
|
||||||
function readDecision(): Decision {
|
function readDecision(): Decision {
|
||||||
|
|||||||
@@ -64,12 +64,7 @@ jobs:
|
|||||||
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
if: ${{ !cancelled() && steps.report.outputs.result == 'verdict' }}
|
||||||
run: exit 1
|
run: exit 1
|
||||||
|
|
||||||
# A run whose title changed mid-run passes and leaves the check to the newer run, which skips it by this name (see `SUPERSEDED_STEP_NAME` in `gather.ts`)
|
|
||||||
- name: ⏭️ Pass for a newer run's review
|
|
||||||
if: ${{ !cancelled() && steps.report.outputs.result == 'superseded' }}
|
|
||||||
run: echo "A newer run reviews the changed title"
|
|
||||||
|
|
||||||
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
|
# Later runs review the title again after this failure, as they do when a step above fails unexpectedly
|
||||||
- name: 🔁 Fail without a verdict
|
- name: 🔁 Fail without a verdict
|
||||||
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' && steps.report.outputs.result != 'superseded' }}
|
if: ${{ !cancelled() && steps.report.outputs.result != 'verdict' && steps.report.outputs.result != 'approved' }}
|
||||||
run: exit 1
|
run: exit 1
|
||||||
Generated
+44
-7
@@ -2498,6 +2498,7 @@ dependencies = [
|
|||||||
"futures",
|
"futures",
|
||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
|
"graph-ui-types",
|
||||||
"graphene-animation",
|
"graphene-animation",
|
||||||
"graphene-application-io",
|
"graphene-application-io",
|
||||||
"graphene-canvas-utils",
|
"graphene-canvas-utils",
|
||||||
@@ -2535,6 +2536,44 @@ dependencies = [
|
|||||||
"smallvec",
|
"smallvec",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "graph-ui"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"core-types",
|
||||||
|
"glam",
|
||||||
|
"graph-craft",
|
||||||
|
"graph-ui-icons",
|
||||||
|
"graph-ui-types",
|
||||||
|
"graphene-std",
|
||||||
|
"graphic-types",
|
||||||
|
"node-macro",
|
||||||
|
"rendering",
|
||||||
|
"svg-convert",
|
||||||
|
"text-nodes",
|
||||||
|
"vector-types",
|
||||||
|
"vello_gpu",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "graph-ui-icons"
|
||||||
|
version = "0.0.0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "graph-ui-types"
|
||||||
|
version = "0.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"core-types",
|
||||||
|
"dyn-any",
|
||||||
|
"glam",
|
||||||
|
"graph-layout",
|
||||||
|
"graphene-hash",
|
||||||
|
"graphic-types",
|
||||||
|
"serde",
|
||||||
|
"tsify",
|
||||||
|
"wasm-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "graphene-animation"
|
name = "graphene-animation"
|
||||||
version = "0.0.0"
|
version = "0.0.0"
|
||||||
@@ -2675,6 +2714,7 @@ dependencies = [
|
|||||||
"math-nodes",
|
"math-nodes",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"path-bool-nodes",
|
"path-bool-nodes",
|
||||||
|
"raster-kernels",
|
||||||
"raster-nodes",
|
"raster-nodes",
|
||||||
"rendering",
|
"rendering",
|
||||||
"repeat-nodes",
|
"repeat-nodes",
|
||||||
@@ -5436,11 +5476,9 @@ dependencies = [
|
|||||||
"glam",
|
"glam",
|
||||||
"graph-craft",
|
"graph-craft",
|
||||||
"graphene-std",
|
"graphene-std",
|
||||||
"graphic-types",
|
|
||||||
"interpreted-executor",
|
"interpreted-executor",
|
||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"wgpu-executor",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -5773,14 +5811,12 @@ dependencies = [
|
|||||||
"node-macro",
|
"node-macro",
|
||||||
"raster-kernels",
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"rendering",
|
|
||||||
"serde",
|
"serde",
|
||||||
"thiserror 2.0.21",
|
"thiserror 2.0.21",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tsify",
|
"tsify",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
"wgpu-executor",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -8079,6 +8115,7 @@ dependencies = [
|
|||||||
"log",
|
"log",
|
||||||
"node-macro",
|
"node-macro",
|
||||||
"ollev",
|
"ollev",
|
||||||
|
"raster-kernels",
|
||||||
"raster-types",
|
"raster-types",
|
||||||
"vector-types",
|
"vector-types",
|
||||||
]
|
]
|
||||||
@@ -8086,7 +8123,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_common"
|
name = "vello_common"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"fearless_simd",
|
"fearless_simd",
|
||||||
@@ -8101,7 +8138,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_gpu"
|
name = "vello_gpu"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytemuck",
|
"bytemuck",
|
||||||
"hashbrown 0.17.1",
|
"hashbrown 0.17.1",
|
||||||
@@ -8115,7 +8152,7 @@ dependencies = [
|
|||||||
[[package]]
|
[[package]]
|
||||||
name = "vello_gpu_shaders"
|
name = "vello_gpu_shaders"
|
||||||
version = "0.3.0"
|
version = "0.3.0"
|
||||||
source = "git+https://github.com/Keavon/vello.git?rev=a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c#a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c"
|
source = "git+https://github.com/Keavon/vello.git?rev=9d032e642c1480c92e45889524db69a7b6a3dc07#9d032e642c1480c92e45889524db69a7b6a3dc07"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"naga",
|
"naga",
|
||||||
"wesl",
|
"wesl",
|
||||||
|
|||||||
+9
-3
@@ -34,6 +34,9 @@ members = [
|
|||||||
"node-graph/libraries/*",
|
"node-graph/libraries/*",
|
||||||
"node-graph/nodes/*",
|
"node-graph/nodes/*",
|
||||||
"node-graph/graph-craft",
|
"node-graph/graph-craft",
|
||||||
|
"node-graph/graph-ui",
|
||||||
|
"node-graph/graph-ui/icons",
|
||||||
|
"node-graph/graph-ui/types",
|
||||||
"node-graph/graphene-cli",
|
"node-graph/graphene-cli",
|
||||||
"node-graph/nodes/gstd",
|
"node-graph/nodes/gstd",
|
||||||
"node-graph/interpreted-executor",
|
"node-graph/interpreted-executor",
|
||||||
@@ -112,6 +115,9 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
|||||||
math-nodes = { path = "node-graph/nodes/math" }
|
math-nodes = { path = "node-graph/nodes/math" }
|
||||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||||
graph-craft = { path = "node-graph/graph-craft" }
|
graph-craft = { path = "node-graph/graph-craft" }
|
||||||
|
graph-ui = { path = "node-graph/graph-ui" }
|
||||||
|
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
|
||||||
|
graph-ui-types = { path = "node-graph/graph-ui/types" }
|
||||||
document-format = { path = "document/format" }
|
document-format = { path = "document/format" }
|
||||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||||
document-container = { path = "document/container" }
|
document-container = { path = "document/container" }
|
||||||
@@ -315,6 +321,6 @@ debug = true
|
|||||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||||
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
|
fastnoise-lite = { git = "https://github.com/Keavon/FastNoiseLite.git", rev = "26c1ac62e124d68ff970c2423dcda2ef24344060" } # TODO: Remove this once the WGSL port is upstreamed and released in version 1.2
|
||||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "a1ba4a9512b65015d16cb81b0ae0f1dc651b5f1c" }
|
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "9d032e642c1480c92e45889524db69a7b6a3dc07" }
|
||||||
@@ -234,7 +234,11 @@ impl RenderState {
|
|||||||
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
WgpuCurrentSurfaceTexture::Suboptimal(t) => (t, true),
|
||||||
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
|
WgpuCurrentSurfaceTexture::Occluded => return Ok(()),
|
||||||
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
WgpuCurrentSurfaceTexture::Lost => return Err(RenderError::SurfaceLost),
|
||||||
WgpuCurrentSurfaceTexture::Outdated => return Err(RenderError::SurfaceOutdated),
|
WgpuCurrentSurfaceTexture::Outdated => {
|
||||||
|
self.surface.configure(&self.executor.context().device, &self.config);
|
||||||
|
window.request_redraw();
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
WgpuCurrentSurfaceTexture::Timeout => return Err(RenderError::SurfaceTimeout),
|
||||||
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
WgpuCurrentSurfaceTexture::Validation => return Err(RenderError::SurfaceValidation),
|
||||||
};
|
};
|
||||||
@@ -327,7 +331,6 @@ impl RenderState {
|
|||||||
pub(crate) enum RenderError {
|
pub(crate) enum RenderError {
|
||||||
OutdatedUITextureError,
|
OutdatedUITextureError,
|
||||||
SurfaceLost,
|
SurfaceLost,
|
||||||
SurfaceOutdated,
|
|
||||||
SurfaceTimeout,
|
SurfaceTimeout,
|
||||||
SurfaceValidation,
|
SurfaceValidation,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,8 @@ pub enum ConversionError {
|
|||||||
IndexOverflow(usize),
|
IndexOverflow(usize),
|
||||||
#[error("Node ID {0} is used by more than one node in the document")]
|
#[error("Node ID {0} is used by more than one node in the document")]
|
||||||
DuplicateNodeId(u64),
|
DuplicateNodeId(u64),
|
||||||
|
#[error("The transient node {0} cannot be saved")]
|
||||||
|
TransientNode(String),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
|
/// Graph-only conversion (no editor metadata). Use [`Registry::from_runtime_with_metadata`] for
|
||||||
@@ -559,7 +561,11 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Nodes the binary doesn't register, such as in tests, are at their first version
|
// Nodes the binary doesn't register, such as in tests, are at their first version
|
||||||
let version = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|metadata| metadata.version)).unwrap_or(1);
|
let registered = NODE_METADATA.lock().ok().and_then(|metadata| metadata.get(identifier).map(|node| (node.version, node.flags)));
|
||||||
|
let (version, flags) = registered.unwrap_or((1, Default::default()));
|
||||||
|
if flags.transient {
|
||||||
|
return Err(ConversionError::TransientNode(identifier_str));
|
||||||
|
}
|
||||||
let EncodedDeclaration { id, hash, bytes, proto } =
|
let EncodedDeclaration { id, hash, bytes, proto } =
|
||||||
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
|
EncodedDeclaration::new(identifier_str.clone(), version).map_err(|error| ConversionError::SerializationError(format!("proto-node {identifier_str}: {error}")))?;
|
||||||
|
|
||||||
|
|||||||
@@ -657,6 +657,41 @@ fn a_node_id_used_in_two_networks_is_rejected() {
|
|||||||
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
|
assert!(matches!(result, Err(crate::from_runtime::ConversionError::DuplicateNodeId(_))), "a reused node ID must not be stored");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_transient_node_is_rejected() {
|
||||||
|
use core_types::registry::{NODE_METADATA, NodeFlags, NodeMetadata};
|
||||||
|
|
||||||
|
let identifier = ProtoNodeIdentifier::new("test::TransientNode");
|
||||||
|
let metadata = NodeMetadata {
|
||||||
|
display_name: "Transient",
|
||||||
|
category: "",
|
||||||
|
icon: None,
|
||||||
|
fields: Vec::new(),
|
||||||
|
description: "",
|
||||||
|
inspector: None,
|
||||||
|
context_features: Vec::new(),
|
||||||
|
flags: NodeFlags {
|
||||||
|
transient: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
version: 1,
|
||||||
|
output_fields: None,
|
||||||
|
};
|
||||||
|
NODE_METADATA.lock().unwrap().insert(identifier.clone(), metadata);
|
||||||
|
|
||||||
|
let mut network = create_simple_network();
|
||||||
|
network.nodes.insert(
|
||||||
|
NodeId(100),
|
||||||
|
DocumentNode {
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let result = Registry::convert_from_runtime(&network, &crate::NoMetadata, &Default::default(), PeerId(0));
|
||||||
|
assert!(matches!(result, Err(crate::from_runtime::ConversionError::TransientNode(_))));
|
||||||
|
}
|
||||||
|
|
||||||
/// A node input referencing a node in a different network can't be remapped to a valid local runtime
|
/// A node input referencing a node in a different network can't be remapped to a valid local runtime
|
||||||
/// ID, so conversion must reject it rather than emit a dangling reference.
|
/// ID, so conversion must reject it rather than emit a dangling reference.
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1,111 +0,0 @@
|
|||||||
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
const GRADIENT_FORM: u32 = 4;
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
#[serde(alias = "GradientType")]
|
|
||||||
GradientForm(GradientForm),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum GradientForm {
|
|
||||||
Linear,
|
|
||||||
Radial,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 'Fill' gives the gradient it paints the curvatures of a form, rather than the form: 0 and 0 for linear, and -1 and 0.5 for radial.
|
|
||||||
/// A wired form becomes linear, and the curvatures stay shown in the graph where the form was.
|
|
||||||
#[migration("graphene_core::vector::FillNode"@1 => @2)]
|
|
||||||
pub fn fill_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
|
||||||
let Some(form) = node.inputs().get(GRADIENT_FORM as usize) else {
|
|
||||||
return Err(MigrationError::invariant("Fill has a gradient form input"));
|
|
||||||
};
|
|
||||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
|
||||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
|
|
||||||
_ => [0., 0.],
|
|
||||||
};
|
|
||||||
|
|
||||||
let exposed = match form.input {
|
|
||||||
NodeInput::Value { exposed, .. } => exposed,
|
|
||||||
_ => true,
|
|
||||||
};
|
|
||||||
let curvature = |curvature: f64| NodeInput::Value {
|
|
||||||
value: encode(&Tagged::Number(curvature)),
|
|
||||||
exposed,
|
|
||||||
};
|
|
||||||
|
|
||||||
inputs.set(GRADIENT_FORM, curvature(start));
|
|
||||||
inputs.insert(GRADIENT_FORM + 1, curvature(end));
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
const FORM_SLOT: usize = GRADIENT_FORM as usize;
|
|
||||||
|
|
||||||
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
|
|
||||||
#[derive(Serialize)]
|
|
||||||
enum LegacyTagged {
|
|
||||||
GradientType(GradientForm),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn form(form: GradientForm) -> NodeInput {
|
|
||||||
literal(Tagged::GradientForm(form))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(7, |random, slot| match slot {
|
|
||||||
FORM_SLOT if random.below(2) == 0 => form(GradientForm::Radial),
|
|
||||||
FORM_SLOT => form(GradientForm::Linear),
|
|
||||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&FillV1, &contract());
|
|
||||||
check_undo(&FillV1, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn forms_become_their_curvature_presets() {
|
|
||||||
let other_inputs: Vec<NodeInput> = (0..7).map(|index| literal(Tagged::Number(index as f64))).collect();
|
|
||||||
let shown_radial = NodeInput::Value {
|
|
||||||
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
|
|
||||||
exposed: true,
|
|
||||||
};
|
|
||||||
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
|
|
||||||
value: encode(&Tagged::Number(curvature)),
|
|
||||||
exposed,
|
|
||||||
};
|
|
||||||
|
|
||||||
// The curvatures stay shown in the graph where an exposed or wired form was, and the inputs after them keep their values
|
|
||||||
for (old_form, [start, end], exposed) in [
|
|
||||||
(form(GradientForm::Linear), [0., 0.], false),
|
|
||||||
(form(GradientForm::Radial), [-1., 0.5], false),
|
|
||||||
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
|
|
||||||
(shown_radial, [-1., 0.5], true),
|
|
||||||
(NodeInput::Import { index: 0 }, [0., 0.], true),
|
|
||||||
] {
|
|
||||||
let mut old_inputs = other_inputs.clone();
|
|
||||||
old_inputs[FORM_SLOT] = old_form;
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&FillV1);
|
|
||||||
let fill = fixture.add(decl!("graphene_core::vector::FillNode"@1), old_inputs);
|
|
||||||
let migrated = fixture.migrate(&FillV1).unwrap();
|
|
||||||
|
|
||||||
let mut expected = other_inputs.clone();
|
|
||||||
expected.splice(FORM_SLOT..=FORM_SLOT, [curvature(start, exposed), curvature(end, exposed)]);
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, fill), Some(decl!("graphene_core::vector::FillNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, fill), expected);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,7 +1,5 @@
|
|||||||
//! Migrations of the nodes in `graphene_core`.
|
//! Migrations of the nodes in `graphene_core`.
|
||||||
|
|
||||||
mod fill_v1;
|
|
||||||
mod passthrough_from_read_attribute_gradient_form_node;
|
|
||||||
mod passthrough_from_upload_texture_node;
|
mod passthrough_from_upload_texture_node;
|
||||||
mod renames;
|
mod renames;
|
||||||
mod vary_colors_from_assign_colors;
|
mod vary_colors_from_assign_colors;
|
||||||
-36
@@ -1,36 +0,0 @@
|
|||||||
use migration_core::{Inputs, migration};
|
|
||||||
|
|
||||||
/// 'Read Attribute Gradient Form' is gone since no node writes that attribute anymore, so it passes its content on and drops the attribute name.
|
|
||||||
#[migration("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
|
||||||
pub fn passthrough_from_read_attribute_gradient_form_node(inputs: &mut Inputs) {
|
|
||||||
inputs.truncate(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&PassthroughFromReadAttributeGradientFormNode, &contract());
|
|
||||||
check_undo(&PassthroughFromReadAttributeGradientFormNode, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_content_and_drops_the_name() {
|
|
||||||
let (content, name) = (literal(1.), literal("gradient_form".to_string()));
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&PassthroughFromReadAttributeGradientFormNode);
|
|
||||||
let read_attribute = fixture.add(decl!("graphic_nodes::graphic::ReadAttributeGradientFormNode"@1), vec![content.clone(), name]);
|
|
||||||
let migrated = fixture.migrate(&PassthroughFromReadAttributeGradientFormNode).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, read_attribute), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, read_attribute), [content]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +1 @@
|
|||||||
//! Migrations of the nodes in `graphene_std`.
|
//! Migrations of the nodes in `graphene_std`.
|
||||||
|
|
||||||
mod renames;
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
|
||||||
|
|
||||||
use migration_core::rename;
|
|
||||||
|
|
||||||
// Version 2 moves these nodes' parameters ahead of their scope inputs, and only the compiler inserts them, so no stored node has version 1's order
|
|
||||||
rename!("graphene_std::platform_application_io::ResourceNode"@1 => @2);
|
|
||||||
rename!("graphene_std::render_background::RenderBackgroundNode"@1 => @2);
|
|
||||||
rename!("graphene_std::render_cache::RenderOutputCacheNode"@1 => @2);
|
|
||||||
rename!("graphene_std::render_node::RenderNode"@1 => @2);
|
|
||||||
rename!("graphene_std::render_pixel_preview::RenderPixelPreviewNode"@1 => @2);
|
|
||||||
|
|
||||||
// Version 3 adds the scope and source ID inputs the render node spawns its readbacks with, which the compiler inserts along with the node
|
|
||||||
rename!("graphene_std::render_node::RenderNode"@2 => @3);
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
|
||||||
use migration_core::{Attributes, Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum Tagged {
|
|
||||||
Number(f64),
|
|
||||||
#[serde(alias = "GradientType")]
|
|
||||||
GradientForm(GradientForm),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize)]
|
|
||||||
enum GradientForm {
|
|
||||||
Linear,
|
|
||||||
Radial,
|
|
||||||
}
|
|
||||||
|
|
||||||
const FORM: u32 = 1;
|
|
||||||
|
|
||||||
/// 'Gradient Form' became 'Gradient Curvature', with start and end curvatures taking the presets of the form it set: 0 and 0 for linear, -1 and 0.5 for
|
|
||||||
/// radial. A wired form becomes linear, the curvatures stay shown in the graph where the form was, and a name it stored as its default is cleared.
|
|
||||||
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
|
|
||||||
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
|
||||||
let [_, form] = node.inputs() else {
|
|
||||||
return Err(MigrationError::invariant("Gradient Form has two inputs"));
|
|
||||||
};
|
|
||||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
|
||||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [-1., 0.5],
|
|
||||||
_ => [0., 0.],
|
|
||||||
};
|
|
||||||
|
|
||||||
let exposed = match form.input {
|
|
||||||
NodeInput::Value { exposed, .. } => exposed,
|
|
||||||
_ => true,
|
|
||||||
};
|
|
||||||
let curvature = |curvature: f64| NodeInput::Value {
|
|
||||||
value: encode(&Tagged::Number(curvature)),
|
|
||||||
exposed,
|
|
||||||
};
|
|
||||||
|
|
||||||
inputs.set(FORM, curvature(start));
|
|
||||||
inputs.push(curvature(end));
|
|
||||||
|
|
||||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
|
|
||||||
attributes.remove(node.id(), DISPLAY_NAME);
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use document_graph_storage::TimeStamp;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn form(form: GradientForm) -> NodeInput {
|
|
||||||
literal(Tagged::GradientForm(form))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract {
|
|
||||||
display_names: &["Gradient Form"],
|
|
||||||
..SourceContract::new(2, |random, slot| match slot {
|
|
||||||
1 if random.below(2) == 0 => form(GradientForm::Radial),
|
|
||||||
1 => form(GradientForm::Linear),
|
|
||||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&GradientCurvatureFromGradientForm, &contract());
|
|
||||||
check_undo(&GradientCurvatureFromGradientForm, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A form stored under its name from before 'Gradient Type' became 'Gradient Form'.
|
|
||||||
#[derive(Serialize)]
|
|
||||||
enum LegacyTagged {
|
|
||||||
GradientType(GradientForm),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn forms_become_their_curvature_presets() {
|
|
||||||
let gradient = literal(Tagged::Number(0.));
|
|
||||||
let shown_radial = NodeInput::Value {
|
|
||||||
value: encode(&Tagged::GradientForm(GradientForm::Radial)),
|
|
||||||
exposed: true,
|
|
||||||
};
|
|
||||||
let curvature = |curvature: f64, exposed: bool| NodeInput::Value {
|
|
||||||
value: encode(&Tagged::Number(curvature)),
|
|
||||||
exposed,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Curvatures stay shown in the graph where an exposed or wired form was
|
|
||||||
for (old_form, [start, end], exposed) in [
|
|
||||||
(form(GradientForm::Linear), [0., 0.], false),
|
|
||||||
(form(GradientForm::Radial), [-1., 0.5], false),
|
|
||||||
(literal(LegacyTagged::GradientType(GradientForm::Radial)), [-1., 0.5], false),
|
|
||||||
(shown_radial, [-1., 0.5], true),
|
|
||||||
(NodeInput::Import { index: 0 }, [0., 0.], true),
|
|
||||||
] {
|
|
||||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
|
||||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
|
|
||||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), curvature(start, exposed), curvature(end, exposed)]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn only_the_old_default_name_is_cleared() {
|
|
||||||
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
|
|
||||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
|
||||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
|
|
||||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
|
||||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
|
||||||
|
|
||||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,4 @@
|
|||||||
//! Migrations of the nodes in `math_nodes`.
|
//! Migrations of the nodes in `math_nodes`.
|
||||||
|
|
||||||
mod gradient_curvature_from_gradient_form;
|
|
||||||
mod math_formula_from_math_f;
|
mod math_formula_from_math_f;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -6,6 +6,5 @@ mod mandelbrot_v2;
|
|||||||
mod mix_colors_from_mix_node;
|
mod mix_colors_from_mix_node;
|
||||||
mod noise_pattern_v1;
|
mod noise_pattern_v1;
|
||||||
mod noise_pattern_v2;
|
mod noise_pattern_v2;
|
||||||
mod passthrough_from_extend_image_to_bounds;
|
|
||||||
mod pattern_square;
|
mod pattern_square;
|
||||||
mod renames;
|
mod renames;
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
use migration_core::{Inputs, migration};
|
|
||||||
|
|
||||||
/// 'Extend Image to Bounds' is gone, and the transparent pixels it padded an image with drew nothing, so it passes its image on and drops its bounds.
|
|
||||||
#[migration("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1 => "graphene_core::ops::PassthroughNode"@2)]
|
|
||||||
pub fn passthrough_from_extend_image_to_bounds(inputs: &mut Inputs) {
|
|
||||||
inputs.truncate(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
use migration_core::{decl, literal};
|
|
||||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
|
||||||
|
|
||||||
fn contract() -> SourceContract {
|
|
||||||
SourceContract::new(2, |random, _slot| literal(random.below(10) as f64))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_history() {
|
|
||||||
check_commutation(&PassthroughFromExtendImageToBounds, &contract());
|
|
||||||
check_undo(&PassthroughFromExtendImageToBounds, &contract());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keeps_the_image_and_drops_the_bounds() {
|
|
||||||
let (image, bounds) = (literal(1.), literal(2.));
|
|
||||||
|
|
||||||
let mut fixture = Fixture::new(&PassthroughFromExtendImageToBounds);
|
|
||||||
let extend = fixture.add(decl!("raster_nodes::std_nodes::ExtendImageToBoundsNode"@1), vec![image.clone(), bounds]);
|
|
||||||
let migrated = fixture.migrate(&PassthroughFromExtendImageToBounds).unwrap();
|
|
||||||
|
|
||||||
assert_eq!(fixture.declaration_of(&migrated, extend), Some(decl!("graphene_core::ops::PassthroughNode"@2)));
|
|
||||||
assert_eq!(fixture.inputs(&migrated, extend), [image]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,12 +4,3 @@ use migration_core::rename;
|
|||||||
|
|
||||||
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
// Version 2 is where old Mix nodes join the lineage, and stored Mix Colors nodes already have its layout
|
||||||
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2);
|
||||||
|
|
||||||
// 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places
|
|
||||||
rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2);
|
|
||||||
|
|
||||||
// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places
|
|
||||||
rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2);
|
|
||||||
|
|
||||||
// 'Median Filter' became an effect taking any graphic, whose stored image and radius keep their places
|
|
||||||
rename!("raster_nodes::filter::MedianFilterNode"@1 => @2);
|
|
||||||
@@ -16,7 +16,7 @@ pub(crate) fn check_against(workspace: &Path, baseline: &str) -> Result<(), Stri
|
|||||||
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
|
let baseline_nodes = extract_baseline(workspace, baseline, &directory).and_then(|()| find_nodes(&directory.join(NODE_CRATES)));
|
||||||
// Removal failing only leaves a temporary directory behind
|
// Removal failing only leaves a temporary directory behind
|
||||||
let _ = std::fs::remove_dir_all(&directory);
|
let _ = std::fs::remove_dir_all(&directory);
|
||||||
let baseline_nodes = baseline_nodes?;
|
let baseline_nodes: Vec<NodeSource> = baseline_nodes?.into_iter().filter(|node| !node.transient).collect();
|
||||||
|
|
||||||
let problems = api_problems(&baseline_nodes, ¤t, &migrations);
|
let problems = api_problems(&baseline_nodes, ¤t, &migrations);
|
||||||
if !problems.is_empty() {
|
if !problems.is_empty() {
|
||||||
@@ -71,7 +71,7 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
|
|||||||
// Moving a module keeps the function and its API, which is what a rename looks like
|
// Moving a module keeps the function and its API, which is what a rename looks like
|
||||||
let moved = current
|
let moved = current
|
||||||
.iter()
|
.iter()
|
||||||
.find(|new| !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
.find(|new| !new.transient && !baseline_identifiers.contains(&new.identifier.as_str()) && new.function == old.function && new.signature == old.signature);
|
||||||
problems.push(match moved {
|
problems.push(match moved {
|
||||||
Some(new) => format!(
|
Some(new) => format!(
|
||||||
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
|
"`{identifier}`@{version} disappeared and looks moved to `{}`. Set `version({})` on it and run `cargo run migration rename {identifier}@{version} {}`",
|
||||||
@@ -83,6 +83,9 @@ fn api_problems(baseline: &[NodeSource], current: &[NodeSource], migrations: &[M
|
|||||||
});
|
});
|
||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
if new.transient {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if new.version < version {
|
if new.version < version {
|
||||||
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
|
problems.push(format!("`{identifier}` went back from version {version} to {}", new.version));
|
||||||
@@ -123,6 +126,7 @@ mod tests {
|
|||||||
NodeSource {
|
NodeSource {
|
||||||
identifier: identifier.to_string(),
|
identifier: identifier.to_string(),
|
||||||
version,
|
version,
|
||||||
|
transient: false,
|
||||||
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
|
function: identifier.rsplit("::").next().unwrap_or(identifier).to_string(),
|
||||||
file: PathBuf::from("lib.rs"),
|
file: PathBuf::from("lib.rs"),
|
||||||
signature: signature.to_string(),
|
signature: signature.to_string(),
|
||||||
@@ -168,6 +172,15 @@ mod tests {
|
|||||||
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
|
assert!(problems[0].contains("disappeared without a migration"), "{}", problems[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_node_turned_transient_needs_no_migration() {
|
||||||
|
let transient = NodeSource {
|
||||||
|
transient: true,
|
||||||
|
..node("a::b", 1, "(x: f64, y: f64)")
|
||||||
|
};
|
||||||
|
assert!(api_problems(&[node("a::b", 2, "(x: f64)")], &[transient], &[]).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_bump_needs_a_migration_from_the_baseline_version() {
|
fn a_bump_needs_a_migration_from_the_baseline_version() {
|
||||||
let bumped = [node("a::b", 3, "(x: f64)")];
|
let bumped = [node("a::b", 3, "(x: f64)")];
|
||||||
|
|||||||
@@ -117,6 +117,7 @@ fn check(workspace: &Path) -> Result<(), String> {
|
|||||||
|
|
||||||
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
|
let nodes: Vec<lineage::Declaration> = nodes::find_nodes(&workspace.join(scaffold::NODE_CRATES))?
|
||||||
.into_iter()
|
.into_iter()
|
||||||
|
.filter(|node| !node.transient)
|
||||||
.map(|node| (node.identifier, node.version))
|
.map(|node| (node.identifier, node.version))
|
||||||
.collect();
|
.collect();
|
||||||
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
|
let migrations = lineage::find_all_migrations(workspace, &scaffold::MIGRATION_CRATES)?;
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ pub(crate) struct NodeSource {
|
|||||||
/// function name with a `Node` suffix.
|
/// function name with a `Node` suffix.
|
||||||
pub identifier: String,
|
pub identifier: String,
|
||||||
pub version: u32,
|
pub version: u32,
|
||||||
|
pub transient: bool,
|
||||||
pub function: String,
|
pub function: String,
|
||||||
pub file: PathBuf,
|
pub file: PathBuf,
|
||||||
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
|
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
|
||||||
@@ -119,7 +120,9 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
|||||||
|
|
||||||
let mut path = module_path.join("::");
|
let mut path = module_path.join("::");
|
||||||
let mut version = 1;
|
let mut version = 1;
|
||||||
|
let mut transient = false;
|
||||||
for argument in arguments {
|
for argument in arguments {
|
||||||
|
transient |= argument.path().is_ident("transient");
|
||||||
let syn::Meta::List(list) = argument else { continue };
|
let syn::Meta::List(list) = argument else { continue };
|
||||||
if list.path.is_ident("path") {
|
if list.path.is_ident("path") {
|
||||||
path = list.tokens.to_string().replace(' ', "");
|
path = list.tokens.to_string().replace(' ', "");
|
||||||
@@ -147,6 +150,7 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
|||||||
Some(NodeSource {
|
Some(NodeSource {
|
||||||
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
|
identifier: format!("{path}::{}Node", function_name.to_case(Case::Pascal)),
|
||||||
version,
|
version,
|
||||||
|
transient,
|
||||||
function: function_name,
|
function: function_name,
|
||||||
file: file.to_path_buf(),
|
file: file.to_path_buf(),
|
||||||
signature,
|
signature,
|
||||||
@@ -171,4 +175,24 @@ mod tests {
|
|||||||
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
||||||
assert!(node.signature.contains("image"), "{}", node.signature);
|
assert!(node.signature.contains("image"), "{}", node.signature);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_transient_attribute_is_read() {
|
||||||
|
let transient: syn::ItemFn = syn::parse_quote! {
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw(_: impl Ctx) -> List<Vector> {
|
||||||
|
List::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let saved: syn::ItemFn = syn::parse_quote! {
|
||||||
|
#[node_macro::node(category(""), memoize)]
|
||||||
|
fn draw(_: impl Ctx) -> List<Vector> {
|
||||||
|
List::new()
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let node = |function| node_source(function, Path::new("lib.rs"), &["drawing".to_string()]).expect("the function is a node");
|
||||||
|
|
||||||
|
assert!(node(&transient).transient);
|
||||||
|
assert!(!node(&saved).transient);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -13,7 +13,7 @@ pub(crate) const MIGRATION_CRATES: [&str; 2] = [MIGRATIONS, "document/migrations
|
|||||||
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
|
/// `new` scaffolds every step missing between a node's newest migration and its version, `new <identifier>` does so for one node,
|
||||||
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
|
/// `new <old>@<version> <identifier>` replaces a node by another, and `rename <old>@<version> <identifier>` registers a finished rename.
|
||||||
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
|
pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) -> Result<(), String> {
|
||||||
let nodes = find_nodes(&workspace.join(NODE_CRATES))?;
|
let nodes: Vec<NodeSource> = find_nodes(&workspace.join(NODE_CRATES))?.into_iter().filter(|node| !node.transient).collect();
|
||||||
let migrations = workspace.join(MIGRATIONS);
|
let migrations = workspace.join(MIGRATIONS);
|
||||||
|
|
||||||
match (command, arguments) {
|
match (command, arguments) {
|
||||||
|
|||||||
@@ -665,6 +665,18 @@ mod test {
|
|||||||
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
assert!(rectangle < polygon && polygon < ellipse, "The first drawn layer should be painted first: {svg}");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(miri, ignore)]
|
||||||
|
#[tokio::test]
|
||||||
|
async fn copied_svg_leaves_out_the_layers_that_are_not_copied() {
|
||||||
|
let mut editor = create_editor_with_three_layers().await;
|
||||||
|
let top = editor.active_document().metadata().all_layers().next().expect("the document has layers").to_node();
|
||||||
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![top] }).await;
|
||||||
|
|
||||||
|
let clipboard = copy_layers_to_clipboard(&mut editor).await;
|
||||||
|
let svg = copied_svg(&clipboard).expect("the copied layer should render an SVG");
|
||||||
|
assert_eq!(svg.matches("<path").count(), 1, "only the copied layer should be drawn: {svg}");
|
||||||
|
}
|
||||||
|
|
||||||
/// - paste
|
/// - paste
|
||||||
/// - assert that ellipse was copied
|
/// - assert that ellipse was copied
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -31,8 +31,7 @@ use graphene_std::vector::misc::{
|
|||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap,
|
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||||
StrokeJoin,
|
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||||
use graphene_std::{
|
use graphene_std::{
|
||||||
@@ -409,6 +408,7 @@ macro_rules! inspectable_types {
|
|||||||
List<DVec2>,
|
List<DVec2>,
|
||||||
List<DAffine2>,
|
List<DAffine2>,
|
||||||
List<BlendMode>,
|
List<BlendMode>,
|
||||||
|
List<GradientForm>,
|
||||||
List<GradientSpread>,
|
List<GradientSpread>,
|
||||||
List<GradientSpace>,
|
List<GradientSpace>,
|
||||||
List<GradientHueDirection>,
|
List<GradientHueDirection>,
|
||||||
@@ -469,7 +469,6 @@ macro_rules! inspectable_types {
|
|||||||
Item<DAffine2>,
|
Item<DAffine2>,
|
||||||
Item<BlendMode>,
|
Item<BlendMode>,
|
||||||
Item<GradientForm>,
|
Item<GradientForm>,
|
||||||
Item<GradientModel>,
|
|
||||||
Item<GradientSpread>,
|
Item<GradientSpread>,
|
||||||
Item<GradientSpace>,
|
Item<GradientSpace>,
|
||||||
Item<GradientHueDirection>,
|
Item<GradientHueDirection>,
|
||||||
@@ -1285,7 +1284,6 @@ impl_table_item_layout_for_choice_enum!(
|
|||||||
MaskMode,
|
MaskMode,
|
||||||
MinimumMaximumMode,
|
MinimumMaximumMode,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -1481,7 +1479,6 @@ macro_rules! known_item_types {
|
|||||||
TransferCurve,
|
TransferCurve,
|
||||||
BlendMode,
|
BlendMode,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
|
|||||||
@@ -26,8 +26,7 @@ pub enum GraphOperationMessage {
|
|||||||
layer: LayerNodeIdentifier,
|
layer: LayerNodeIdentifier,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
gradient: Gradient,
|
gradient: Gradient,
|
||||||
/// The form whose curvatures the Fill takes, or `None` to keep its own.
|
gradient_form: GradientForm,
|
||||||
gradient_form: Option<GradientForm>,
|
|
||||||
gradient_settings: GradientSettings,
|
gradient_settings: GradientSettings,
|
||||||
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
/// `None` lets the gradient cover the layer's bounding box, following it as the layer changes.
|
||||||
transform: Option<DAffine2>,
|
transform: Option<DAffine2>,
|
||||||
|
|||||||
+2
-2
@@ -1034,7 +1034,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
|||||||
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
space: gradient_info.spaces.get(linear.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||||
}
|
}
|
||||||
usvg::Paint::RadialGradient(radial) => {
|
usvg::Paint::RadialGradient(radial) => {
|
||||||
let gradient_transform = usvg_transform(radial.transform());
|
let gradient_transform = usvg_transform(radial.transform());
|
||||||
@@ -1062,7 +1062,7 @@ fn apply_usvg_fill(fill: &usvg::Fill, modify_inputs: &mut ModifyInputsContext, g
|
|||||||
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
space: gradient_info.spaces.get(radial.id()).copied().unwrap_or(GradientSpace::RgbGamma),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
modify_inputs.fill_gradient_set(gradient, Some(gradient_form), settings, Some(transform));
|
modify_inputs.fill_gradient_set(gradient, gradient_form, settings, Some(transform));
|
||||||
}
|
}
|
||||||
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
|
usvg::Paint::Pattern(_) => warn!("SVG patterns are not currently supported"),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
|
|||||||
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{self, FlowType, InputConnector, NodeNetworkInterface, OutputConnector};
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
use crate::messages::tool::common_functionality::graph_modification_utils::{
|
||||||
ReplaceablePaintChain, fill_node_curvatures, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, gradient_curvature_values, replaceable_paint_chain,
|
ReplaceablePaintChain, get_fill_input_node_id, get_upstream_gradient_value_node_id, gradient_chain_target_input, replaceable_paint_chain,
|
||||||
};
|
};
|
||||||
use glam::{DAffine2, DVec2, IVec2};
|
use glam::{DAffine2, DVec2, IVec2};
|
||||||
use graph_craft::application_io::resource::ResourceId;
|
use graph_craft::application_io::resource::ResourceId;
|
||||||
@@ -450,8 +450,7 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Paints the layer's Fill with `gradient`, giving its curvatures those of `gradient_form` if that's given, unless the graph feeds them.
|
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: GradientForm, settings: GradientSettings, transform: Option<DAffine2>) {
|
||||||
pub fn fill_gradient_set(&mut self, gradient: Gradient, gradient_form: Option<GradientForm>, settings: GradientSettings, transform: Option<DAffine2>) {
|
|
||||||
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
|
let existing_fill_node_id = self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, false);
|
||||||
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
|
let Some(fill_node_id) = existing_fill_node_id.or_else(|| self.existing_chain_hosted_node_id(graphene_std::vector_nodes::fill::IDENTIFIER, true)) else {
|
||||||
return;
|
return;
|
||||||
@@ -491,22 +490,11 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only a chosen form sets the curvatures, leaving any the graph feeds or that already make it
|
|
||||||
let curvatures = self.network_interface.document_network().nodes.get(&fill_node_id).and_then(fill_node_curvatures);
|
|
||||||
if let Some(gradient_form) = gradient_form
|
|
||||||
&& curvatures.is_some_and(|curvatures| GradientForm::from_curvatures(curvatures) != Some(gradient_form))
|
|
||||||
{
|
|
||||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
let [start_curvature, end_curvature] = gradient_form.curvatures();
|
|
||||||
self.set_input_with_refresh(
|
self.set_input_with_refresh(
|
||||||
InputConnector::node(fill_node_id, StartCurvatureInput),
|
InputConnector::node(fill_node_id, graphene_std::vector::fill::GradientFormInput),
|
||||||
NodeInput::value(TaggedValue::Number(start_curvature), false),
|
NodeInput::value(TaggedValue::GradientForm(gradient_form), false),
|
||||||
true,
|
false,
|
||||||
);
|
);
|
||||||
self.set_input_with_refresh(InputConnector::node(fill_node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end_curvature), false), true);
|
|
||||||
}
|
|
||||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
|
||||||
|
|
||||||
if existing_fill_node_id.is_none() {
|
if existing_fill_node_id.is_none() {
|
||||||
self.restore_default_stroke_order();
|
self.restore_default_stroke_order();
|
||||||
@@ -773,28 +761,20 @@ impl<'a> ModifyInputsContext<'a> {
|
|||||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||||
/// from the default (`Linear`). Curvatures fed from the graph (procedural authorship) or already making the form are left untouched.
|
/// from the default (`Linear`).
|
||||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
|
||||||
|
|
||||||
let Some(output_layer) = self.get_output_layer() else { return };
|
let Some(output_layer) = self.get_output_layer() else { return };
|
||||||
|
|
||||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||||
|
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
|
|
||||||
let Some(node) = self.network_interface.document_network().nodes.get(&node_id) else { return };
|
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||||
let Some(curvatures) = gradient_curvature_values(node) else { return };
|
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||||
if GradientForm::from_curvatures(curvatures) == Some(gradient_form) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
let [start, end] = gradient_form.curvatures();
|
|
||||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), true);
|
|
||||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||||
|
|||||||
@@ -686,7 +686,6 @@ fn static_node_inspector() -> NodeInspector {
|
|||||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
|
||||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||||
|
|||||||
@@ -37,8 +37,8 @@ use graphene_std::vector::misc::{
|
|||||||
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
ArcType, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod, WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{
|
use graphene_std::vector::style::{
|
||||||
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign,
|
FillChoice, Gradient, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, GradientStops, StrokeAlign, StrokeCap, StrokeJoin,
|
||||||
StrokeCap, StrokeJoin, build_transform_with_y_preservation,
|
build_transform_with_y_preservation,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||||
@@ -254,23 +254,6 @@ pub(crate) struct ParameterOptions {
|
|||||||
pub step: Option<f64>,
|
pub step: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<&graphene_std::registry::FieldMetadata> for ParameterOptions {
|
|
||||||
fn from(field: &graphene_std::registry::FieldMetadata) -> Self {
|
|
||||||
Self {
|
|
||||||
soft_min: field.number_soft_min,
|
|
||||||
soft_max: field.number_soft_max,
|
|
||||||
hard_min: field.number_hard_min,
|
|
||||||
hard_max: field.number_hard_max,
|
|
||||||
slider: field.number_mode_range,
|
|
||||||
multiline: field.multiline,
|
|
||||||
progression: field.progression,
|
|
||||||
unit: field.unit,
|
|
||||||
display_decimal_places: field.number_display_decimal_places,
|
|
||||||
step: field.number_step,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
/// The values a range slider's two ends map to linearly and the one its double-click restores, if known.
|
||||||
#[derive(Clone, Copy)]
|
#[derive(Clone, Copy)]
|
||||||
pub struct SliderRange {
|
pub struct SliderRange {
|
||||||
@@ -434,7 +417,6 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
|||||||
// AUTO-GENERATED ENUM TYPES
|
// AUTO-GENERATED ENUM TYPES
|
||||||
// =========================
|
// =========================
|
||||||
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GradientForm>(x) => enum_choice::<GradientForm>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<GradientModel>(x) => enum_choice::<GradientModel>().for_socket(default_info).inspector_row(),
|
|
||||||
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GradientSpread>(x) => enum_choice::<GradientSpread>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GradientSpace>(x) => enum_choice::<GradientSpace>().for_socket(default_info).inspector_row(),
|
||||||
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
Some(x) if id_is::<GradientHueDirection>(x) => enum_choice::<GradientHueDirection>().for_socket(default_info).inspector_row(),
|
||||||
@@ -3304,80 +3286,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
|||||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::*;
|
|
||||||
|
|
||||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
|
||||||
let curvatures = match get_document_node(node_id, context) {
|
|
||||||
Ok(document_node) => graph_modification_utils::gradient_curvature_values(document_node),
|
|
||||||
Err(err) => {
|
|
||||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// Each form's button sets both curvatures to the form's own, and stands out while they make that form
|
|
||||||
let mut form = vec![
|
|
||||||
TextLabel::new("Form")
|
|
||||||
.tooltip_label("Form")
|
|
||||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
|
||||||
.widget_instance(),
|
|
||||||
];
|
|
||||||
add_blank_assist(&mut form);
|
|
||||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
|
||||||
for (label, gradient_form, tooltip) in [
|
|
||||||
("Linear", GradientForm::Linear, "Sets both curvatures to 0, making straight contours."),
|
|
||||||
(
|
|
||||||
"Radial",
|
|
||||||
GradientForm::Radial,
|
|
||||||
"Sets the start curvature to -1 and the end curvature to 0.5, making circles around the start.",
|
|
||||||
),
|
|
||||||
] {
|
|
||||||
let [start, end] = gradient_form.curvatures();
|
|
||||||
form.push(
|
|
||||||
TextButton::new(label)
|
|
||||||
.tooltip_description(tooltip)
|
|
||||||
.emphasized(curvatures.and_then(GradientForm::from_curvatures) == Some(gradient_form))
|
|
||||||
.disabled(curvatures.is_none())
|
|
||||||
.on_update(move |_: &TextButton| Message::Batched {
|
|
||||||
messages: Box::new([
|
|
||||||
NodeGraphMessage::SetInputValue {
|
|
||||||
node_id,
|
|
||||||
input_index: StartCurvatureInput::INDEX,
|
|
||||||
value: TaggedValue::Number(start).into(),
|
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
NodeGraphMessage::SetInputValue {
|
|
||||||
node_id,
|
|
||||||
input_index: EndCurvatureInput::INDEX,
|
|
||||||
value: TaggedValue::Number(end).into(),
|
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
]),
|
|
||||||
})
|
|
||||||
.on_commit(commit_value)
|
|
||||||
.widget_instance(),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// The same sliders the parameters would get without this panel
|
|
||||||
let options = |index: usize| {
|
|
||||||
let registry = graphene_std::registry::NODE_METADATA.lock().ok();
|
|
||||||
let field = registry.as_ref().and_then(|registry| registry.get(&IDENTIFIER)).and_then(|metadata| metadata.fields.get(index));
|
|
||||||
field.map(ParameterOptions::from).unwrap_or_default()
|
|
||||||
};
|
|
||||||
let mut row = |index: usize, ty: Type| {
|
|
||||||
context
|
|
||||||
.call_widget_override(&node_id, index)
|
|
||||||
.unwrap_or_else(|| inspector_row_from_type(node_id, index, &ty, options(index), context).unwrap_or_else(|rows| rows))
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut layout = vec![LayoutGroup::row(form)];
|
|
||||||
layout.extend(row(StartCurvatureInput::INDEX, concrete!(f64)));
|
|
||||||
layout.extend(row(EndCurvatureInput::INDEX, concrete!(f64)));
|
|
||||||
layout
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||||
|
|
||||||
@@ -3535,7 +3443,18 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
|||||||
.get(&proto_node_identifier)
|
.get(&proto_node_identifier)
|
||||||
.and_then(|metadata| metadata.fields.get(input_index))
|
.and_then(|metadata| metadata.fields.get(input_index))
|
||||||
{
|
{
|
||||||
options = ParameterOptions::from(field);
|
options = ParameterOptions {
|
||||||
|
soft_min: field.number_soft_min,
|
||||||
|
soft_max: field.number_soft_max,
|
||||||
|
hard_min: field.number_hard_min,
|
||||||
|
hard_max: field.number_hard_max,
|
||||||
|
slider: field.number_mode_range,
|
||||||
|
multiline: field.multiline,
|
||||||
|
progression: field.progression,
|
||||||
|
unit: field.unit,
|
||||||
|
display_decimal_places: field.number_display_decimal_places,
|
||||||
|
step: field.number_step,
|
||||||
|
};
|
||||||
default_type = field.default_type.clone();
|
default_type = field.default_type.clone();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3924,25 +3843,9 @@ pub(crate) fn fill_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
|||||||
let entries = [GradientForm::Linear, GradientForm::Radial]
|
let entries = [GradientForm::Linear, GradientForm::Radial]
|
||||||
.iter()
|
.iter()
|
||||||
.map(|&gradient_form| {
|
.map(|&gradient_form| {
|
||||||
let [start, end] = gradient_form.curvatures();
|
|
||||||
RadioEntryData::new(format!("{:?}", gradient_form))
|
RadioEntryData::new(format!("{:?}", gradient_form))
|
||||||
.label(gradient_form.to_string())
|
.label(gradient_form.to_string())
|
||||||
.on_update(move |_| Message::Batched {
|
.on_update(update_value(move |_| TaggedValue::GradientForm(gradient_form), node_id, GradientFormInput))
|
||||||
messages: Box::new([
|
|
||||||
NodeGraphMessage::SetInputValue {
|
|
||||||
node_id,
|
|
||||||
input_index: StartCurvatureInput::INDEX,
|
|
||||||
value: TaggedValue::Number(start).into(),
|
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
NodeGraphMessage::SetInputValue {
|
|
||||||
node_id,
|
|
||||||
input_index: EndCurvatureInput::INDEX,
|
|
||||||
value: TaggedValue::Number(end).into(),
|
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
]),
|
|
||||||
})
|
|
||||||
.on_commit(commit_value)
|
.on_commit(commit_value)
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
|
|||||||
@@ -37,7 +37,6 @@ impl FrontendGraphDataType {
|
|||||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||||
// A generator draws pixels like an image, at whatever resolution is needed
|
// A generator draws pixels like an image, at whatever resolution is needed
|
||||||
"Generator" => Self::Raster,
|
"Generator" => Self::Raster,
|
||||||
"Pixels" => Self::Raster,
|
|
||||||
raster if raster.starts_with("Raster") => Self::Raster,
|
raster if raster.starts_with("Raster") => Self::Raster,
|
||||||
_ => Self::General,
|
_ => Self::General,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -975,7 +975,7 @@ async fn legacy_four_input_fill_migrates_to_the_split_transform_shape() {
|
|||||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||||
let fill_node = &network.nodes[&node_id];
|
let fill_node = &network.nodes[&node_id];
|
||||||
|
|
||||||
assert_eq!(fill_node.inputs.len(), 8, "the legacy Fill should upgrade to the 8-input shape");
|
assert_eq!(fill_node.inputs.len(), 7, "the legacy Fill should upgrade to the 7-input shape");
|
||||||
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
let paint = fill_node.input(graphene_std::vector::fill::PaintInput);
|
||||||
assert!(
|
assert!(
|
||||||
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
matches!(paint, Some(graph_craft::document::NodeInput::Node { .. })),
|
||||||
@@ -1033,13 +1033,7 @@ async fn eight_input_fill_migrates_the_spread_input_into_the_ramp() {
|
|||||||
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
let network = document.network_interface.nested_network(&network_path).expect("the found network path should resolve");
|
||||||
let fill_node = &network.nodes[&node_id];
|
let fill_node = &network.nodes[&node_id];
|
||||||
|
|
||||||
assert_eq!(fill_node.inputs.len(), 8, "the eight-input Fill should come out in the modern shape, which also has eight inputs");
|
assert_eq!(fill_node.inputs.len(), 7, "the eight-input Fill should fold down to the 7-input shape");
|
||||||
let curvatures = [graphene_std::vector::fill::StartCurvatureInput::INDEX, graphene_std::vector::fill::EndCurvatureInput::INDEX].map(|index| fill_node.inputs[index].as_value().cloned());
|
|
||||||
assert_eq!(
|
|
||||||
curvatures,
|
|
||||||
[0., 0.].map(|curvature| Some(TaggedValue::Number(curvature))),
|
|
||||||
"the linear form should become its curvatures"
|
|
||||||
);
|
|
||||||
|
|
||||||
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
let paint = fill_node.input_value(graphene_std::vector::fill::PaintInput);
|
||||||
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
let Some(TaggedValue::GradientRamp(ramp)) = paint else {
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
|||||||
use graphene_std::transform::ScaleType;
|
use graphene_std::transform::ScaleType;
|
||||||
use graphene_std::uuid::NodeId;
|
use graphene_std::uuid::NodeId;
|
||||||
use graphene_std::vector::graphic_types;
|
use graphene_std::vector::graphic_types;
|
||||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use std::f64::consts::PI;
|
use std::f64::consts::PI;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
@@ -121,10 +121,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_std::raster::SampleImageNode",
|
"graphene_std::raster::SampleImageNode",
|
||||||
"graphene_std::raster::SampleNode",
|
"graphene_std::raster::SampleNode",
|
||||||
"raster_nodes::std_nodes::SampleImageNode",
|
"raster_nodes::std_nodes::SampleImageNode",
|
||||||
// The deleted Extend Image to Bounds passes its image through, since the transparent pixels it padded with drew nothing
|
|
||||||
"graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
|
||||||
"graphene_std::raster::ExtendImageToBoundsNode",
|
|
||||||
"raster_nodes::std_nodes::ExtendImageToBoundsNode",
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
@@ -185,6 +181,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphic_nodes::graphic::ExtractElementNode",
|
"graphic_nodes::graphic::ExtractElementNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::graphic::read_attribute_gradient_form::IDENTIFIER,
|
||||||
|
aliases: &["graphic_nodes::graphic::ReadAttributeGradientTypeNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
node: graphene_std::graphic::read_attribute_gradient_spread::IDENTIFIER,
|
||||||
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
aliases: &["graphic_nodes::graphic::ReadAttributeSpreadMethodNode"],
|
||||||
@@ -301,6 +301,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||||
|
aliases: &["math_nodes::GradientTypeNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||||
aliases: &["math_nodes::SpreadMethodNode"],
|
aliases: &["math_nodes::SpreadMethodNode"],
|
||||||
@@ -549,13 +553,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::channels::into_channels::IDENTIFIER,
|
node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
|
||||||
aliases: &["raster_nodes::adjustments::ImageToChannelsNode"],
|
|
||||||
},
|
|
||||||
NodeReplacement {
|
|
||||||
node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER,
|
|
||||||
aliases: &[
|
aliases: &[
|
||||||
"raster_nodes::std_nodes::ChannelsToImageNode",
|
|
||||||
"raster_nodes::std_nodes::CombineChannelsNode",
|
"raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
"graphene_raster_nodes::std_nodes::CombineChannelsNode",
|
||||||
"graphene_std::raster::CombineChannelsNode",
|
"graphene_std::raster::CombineChannelsNode",
|
||||||
@@ -573,6 +572,10 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
|||||||
"graphene_core::raster::ExposureNode",
|
"graphene_core::raster::ExposureNode",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
NodeReplacement {
|
||||||
|
node: graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
|
||||||
|
aliases: &["graphene_raster_nodes::std_nodes::ExtendImageToBoundsNode", "graphene_std::raster::ExtendImageToBoundsNode"],
|
||||||
|
},
|
||||||
NodeReplacement {
|
NodeReplacement {
|
||||||
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
node: graphene_std::raster_nodes::adjustments::gamma_correction::IDENTIFIER,
|
||||||
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
aliases: &["graphene_raster_nodes::adjustments::GammaCorrectionNode", "graphene_core::raster::adjustments::GammaCorrectionNode"],
|
||||||
@@ -1569,13 +1572,13 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `into_channels` proto nodes.
|
// The "Split Vec2", "Split Vector2", and "Split Channels" wrapper networks became the multi-output `vec2_to_numbers` and `image_to_channels` proto nodes.
|
||||||
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
// A wrapper saved before these gained a hidden primary output had each field one output lower, so its wires shift up by one.
|
||||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer network impl orphans its child paths.
|
||||||
let split_wrapper_replacements = [
|
let split_wrapper_replacements = [
|
||||||
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vec2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
("Split Vector2", graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER),
|
||||||
("Split Channels", graphene_std::raster_nodes::channels::into_channels::IDENTIFIER),
|
("Split Channels", graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER),
|
||||||
];
|
];
|
||||||
for (old_reference, new_identifier) in split_wrapper_replacements {
|
for (old_reference, new_identifier) in split_wrapper_replacements {
|
||||||
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
let split_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||||
@@ -1621,7 +1624,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Into Channels" nodes.
|
// The standalone "Extract XY" and "Extract Channel" nodes were removed in favor of the multi-output "Vec2 to Numbers" and "Image to Channels" nodes.
|
||||||
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
// Convert each to its replacement, moving its downstream wires to the field output for the axis or channel it extracted.
|
||||||
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
const EXTRACT_XY: [&str; 2] = ["graphene_core::extract_xy::ExtractXyNode", "graphene_core::ops::ExtractXyNode"];
|
||||||
const EXTRACT_CHANNEL: [&str; 4] = [
|
const EXTRACT_CHANNEL: [&str; 4] = [
|
||||||
@@ -1640,7 +1643,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
if EXTRACT_XY.contains(&name) {
|
if EXTRACT_XY.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
Some((*node_id, path, graphene_std::math_nodes::vec_2_to_numbers::IDENTIFIER, "Extract XY"))
|
||||||
} else if EXTRACT_CHANNEL.contains(&name) {
|
} else if EXTRACT_CHANNEL.contains(&name) {
|
||||||
Some((*node_id, path, graphene_std::raster_nodes::channels::into_channels::IDENTIFIER, "Extract Channel"))
|
Some((*node_id, path, graphene_std::raster_nodes::adjustments::image_to_channels::IDENTIFIER, "Extract Channel"))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
@@ -1686,52 +1689,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The "Gradient Form" node was replaced by "Gradient Curvature", with its two curvatures taking the presets of the form it set
|
|
||||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
|
||||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
|
||||||
.network_interface
|
|
||||||
.document_network()
|
|
||||||
.recursive_nodes()
|
|
||||||
.filter_map(|(node_id, node, path)| {
|
|
||||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
|
||||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
for (node_id, network_path) in &gradient_form_nodes {
|
|
||||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let mut node_template = definition.default_node_template();
|
|
||||||
|
|
||||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
|
||||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
|
||||||
|
|
||||||
if let Some(input) = old_inputs.first() {
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
|
||||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => GradientForm::Radial.curvatures(),
|
|
||||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => GradientForm::Linear.curvatures(),
|
|
||||||
_ => {
|
|
||||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
|
||||||
GradientForm::Linear.curvatures()
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
// The curvatures stay shown in the graph where an exposed or wired form was
|
|
||||||
let exposed = old_inputs.get(1).is_some_and(NodeInput::is_exposed);
|
|
||||||
document
|
|
||||||
.network_interface
|
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), exposed), network_path);
|
|
||||||
document
|
|
||||||
.network_interface
|
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), exposed), network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||||
@@ -2537,18 +2494,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
// The 7-input shape's own gradient metadata defaults, which the steps after this one read until the legacy fill's values replace them below
|
|
||||||
let metadata_defaults = [
|
|
||||||
TaggedValue::GradientForm(GradientForm::Linear),
|
|
||||||
TaggedValue::Bool(false),
|
|
||||||
TaggedValue::DAffine2(glam::DAffine2::IDENTITY),
|
|
||||||
];
|
|
||||||
for (index, value) in (4..).zip(metadata_defaults) {
|
|
||||||
document
|
|
||||||
.network_interface
|
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Content: no change
|
// Content: no change
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
||||||
|
|
||||||
@@ -2692,11 +2637,8 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 7;
|
inputs_count = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field. The modern shape is also 8 inputs,
|
// The Fill node's `_spread_method` input moved into the `GradientRamp` value's own `gradient_spread` field
|
||||||
// so this era is told apart by its form at 4 or its spread at 5, either of which may be wired, where the modern shape holds curvatures.
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 8 {
|
||||||
let value_at = |index: usize| node.inputs.get(index).and_then(|input| input.as_value());
|
|
||||||
let is_spread_method_fill = inputs_count == 8 && (matches!(value_at(4), Some(TaggedValue::GradientForm(_))) || matches!(value_at(5), Some(TaggedValue::GradientSpread(_))));
|
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && is_spread_method_fill {
|
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||||
|
|
||||||
@@ -2719,36 +2661,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
inputs_count = 7;
|
inputs_count = 7;
|
||||||
}
|
}
|
||||||
|
|
||||||
// The Fill node gives its gradient paint the curvatures of a form in place of its `_gradient_form` input, and they stay shown in the graph where the form was
|
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::fill::IDENTIFIER) && inputs_count == 7 {
|
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
|
||||||
|
|
||||||
// Content, paint, and backups keep their places, and the transform inputs move past the second curvature
|
|
||||||
for (index, input) in old_inputs.iter().enumerate().take(7) {
|
|
||||||
let index = match index {
|
|
||||||
4 => continue,
|
|
||||||
5.. => index + 1,
|
|
||||||
_ => index,
|
|
||||||
};
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
let form = old_inputs.get(4);
|
|
||||||
let curvatures = match form.and_then(|input| input.as_value()) {
|
|
||||||
Some(TaggedValue::GradientForm(form)) => form.curvatures(),
|
|
||||||
_ => GradientForm::Linear.curvatures(),
|
|
||||||
};
|
|
||||||
let exposed = form.is_some_and(NodeInput::is_exposed);
|
|
||||||
for (index, curvature) in (4..).zip(curvatures) {
|
|
||||||
document
|
|
||||||
.network_interface
|
|
||||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(TaggedValue::Number(curvature), exposed), network_path);
|
|
||||||
}
|
|
||||||
|
|
||||||
inputs_count = 8;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
|
// Upgrade Stroke node to reorder parameters and add "Align" (#2644)
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::stroke::IDENTIFIER) && inputs_count == 8 {
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||||
@@ -3252,17 +3164,9 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
|||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[1].clone(), network_path);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Sample Image and Extend Image to Bounds nodes, now passthroughs, drop their old titles and any inputs past the first, like Extend Image to Bounds's bounds
|
// Sample Image nodes, now passthroughs, drop their old title
|
||||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
if reference == DefinitionIdentifier::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER) {
|
||||||
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
reset_default_display_name(document, node_id, network_path, "Sample Image");
|
||||||
reset_default_display_name(document, node_id, network_path, "Extend Image to Bounds");
|
|
||||||
|
|
||||||
if inputs_count > 1 {
|
|
||||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
|
||||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
// Serialize became As String, whose input converts a wired value to text, while a stored value keeps the JSON text Serialize made of it
|
||||||
@@ -4212,20 +4116,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// The removed Read Attribute Gradient Form node, under either of its names, degrades to a passthrough of its content
|
|
||||||
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
|
|
||||||
&& ["::ReadAttributeGradientFormNode", "::ReadAttributeGradientTypeNode"]
|
|
||||||
.iter()
|
|
||||||
.any(|name| identifier.as_str().ends_with(name))
|
|
||||||
{
|
|
||||||
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
|
|
||||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
|
||||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
|
||||||
if let Some(content) = old_inputs.first() {
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), content.clone(), network_path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
|
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
|
||||||
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
|
||||||
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
|
||||||
@@ -4988,40 +4878,6 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Read Attribute Gradient Form, under either of its names, opens as a passthrough of its content
|
|
||||||
#[test]
|
|
||||||
fn read_attribute_gradient_form_opens_as_a_passthrough() {
|
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
|
||||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
|
||||||
|
|
||||||
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
|
|
||||||
let name = NodeInput::value(TaggedValue::String("gradient_form".into()), false);
|
|
||||||
let identifiers = ["graphic_nodes::graphic::ReadAttributeGradientFormNode", "graphic_nodes::graphic::ReadAttributeGradientTypeNode"];
|
|
||||||
|
|
||||||
let nodes = identifiers
|
|
||||||
.iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(index, &identifier)| {
|
|
||||||
let node_template = NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
|
||||||
inputs: vec![content.clone(), name.clone()],
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
(NodeId(index as u64), node_template)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
|
|
||||||
|
|
||||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
|
||||||
for (index, identifier) in identifiers.iter().enumerate() {
|
|
||||||
let node = opened.network_interface.document_node(&NodeId(index as u64), &[]).expect("the node should still exist");
|
|
||||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER), "{identifier}");
|
|
||||||
assert_eq!(node.inputs, [content.clone()], "{identifier}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
|
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
|
||||||
#[test]
|
#[test]
|
||||||
fn every_into_group_alias_resets_the_merge_definition() {
|
fn every_into_group_alias_resets_the_merge_definition() {
|
||||||
@@ -5584,204 +5440,6 @@ mod tests {
|
|||||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
|
||||||
|
|
||||||
// Curvatures stay shown in the graph where an exposed form was
|
|
||||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
|
||||||
for (identifier, form, curvatures, exposed) in [
|
|
||||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], false),
|
|
||||||
("math_nodes::GradientTypeNode", GradientForm::Linear, [0., 0.], false),
|
|
||||||
("math_nodes::GradientFormNode", GradientForm::Radial, [-1., 0.5], true),
|
|
||||||
] {
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
|
||||||
document.network_interface.insert_node(
|
|
||||||
source_id,
|
|
||||||
NodeTemplate {
|
|
||||||
inputs: vec![placeholder()],
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
document.network_interface.insert_node(
|
|
||||||
form_id,
|
|
||||||
NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
|
||||||
inputs: vec![placeholder(); 2],
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
|
||||||
document
|
|
||||||
.network_interface
|
|
||||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), exposed), &[]);
|
|
||||||
migrate(&mut document);
|
|
||||||
|
|
||||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
|
||||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
|
||||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
|
||||||
|
|
||||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
|
||||||
assert_eq!(
|
|
||||||
[curvature(1), curvature(2)],
|
|
||||||
curvatures.map(|curvature| Some(TaggedValue::Number(curvature))),
|
|
||||||
"{form:?} should become its curvature presets"
|
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
[1, 2].map(|index| node.inputs[index].is_exposed()),
|
|
||||||
[exposed; 2],
|
|
||||||
"{form:?} exposed {exposed} should leave its curvatures so"
|
|
||||||
);
|
|
||||||
assert_eq!(node.inputs.len(), 3, "{form:?} should take the curvature node's gradient and two curvatures");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// An eight-input Fill from when the spread was an input of its own, here wired, opens with its form's curvatures and keeps its placement
|
|
||||||
#[test]
|
|
||||||
fn eight_input_fills_with_a_wired_spread_take_their_form_as_curvatures() {
|
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
|
||||||
use glam::DAffine2;
|
|
||||||
|
|
||||||
let (source_id, fill_id) = (NodeId(1), NodeId(2));
|
|
||||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
|
||||||
let ramp = || NodeInput::value(TaggedValue::GradientRamp(GradientRamp::default()), false);
|
|
||||||
let old_inputs = vec![
|
|
||||||
NodeInput::value(TaggedValue::None, false),
|
|
||||||
ramp(),
|
|
||||||
NodeInput::value(TaggedValue::Color(Color::BLACK), false),
|
|
||||||
ramp(),
|
|
||||||
NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false),
|
|
||||||
NodeInput::value(TaggedValue::None, false),
|
|
||||||
NodeInput::value(TaggedValue::Bool(true), false),
|
|
||||||
NodeInput::value(TaggedValue::DAffine2(placement), false),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
let source = NodeTemplate {
|
|
||||||
inputs: vec![NodeInput::value(TaggedValue::None, false)],
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
document.network_interface.insert_node(source_id, source, &[]);
|
|
||||||
let fill = NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::vector::fill::IDENTIFIER),
|
|
||||||
inputs: old_inputs,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
document.network_interface.insert_node(fill_id, fill, &[]);
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(fill_id, 5), NodeInput::node(source_id, 0), &[]);
|
|
||||||
migrate(&mut document);
|
|
||||||
|
|
||||||
let node = &document.network_interface.document_network().nodes[&fill_id];
|
|
||||||
let values: Vec<_> = node.inputs[4..].iter().map(|input| input.as_value().cloned()).collect();
|
|
||||||
let expected = [TaggedValue::Number(-1.), TaggedValue::Number(0.5), TaggedValue::Bool(true), TaggedValue::DAffine2(placement)].map(Some);
|
|
||||||
assert_eq!(values, expected, "the form should become its curvatures before the placement");
|
|
||||||
}
|
|
||||||
|
|
||||||
// A Fill that held the radial form in its input before the transform ones opens with that form's curvatures, painting as a Fill given the form now does
|
|
||||||
#[tokio::test]
|
|
||||||
async fn fills_of_the_radial_form_paint_the_same_once_migrated() {
|
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::NodeGraphLayer;
|
|
||||||
use crate::test_utils::test_prelude::*;
|
|
||||||
use glam::DAffine2;
|
|
||||||
use graphene_std::graphic::extend;
|
|
||||||
use graphene_std::list::Item;
|
|
||||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
|
||||||
use graphene_std::vector::fill;
|
|
||||||
use graphene_std::vector::style::Gradient;
|
|
||||||
use graphene_std::vector_types::gradient_standard::GradientShape;
|
|
||||||
use graphene_std::{Appearance, Cover, Graphic};
|
|
||||||
|
|
||||||
// The SVG of the document's one layer, its IDs numbered by their order of appearance, and the shape the CPU samples its fill's gradient as
|
|
||||||
async fn painted(editor: &mut EditorTestUtils) -> (String, Option<GradientShape>) {
|
|
||||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
|
||||||
let layer = instrumented
|
|
||||||
.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime)
|
|
||||||
.next()
|
|
||||||
.expect("the layer is extended onto the root");
|
|
||||||
|
|
||||||
let mut render = SvgRender::new();
|
|
||||||
layer.element().render_svg(&mut render, &RenderParams::default());
|
|
||||||
let mut markup = format!("{}{}", render.svg_defs, render.svg.to_svg_string());
|
|
||||||
let mut index = 0;
|
|
||||||
while let Some(found) = markup.find(r#"id=""#) {
|
|
||||||
let start = found + r#"id=""#.len();
|
|
||||||
let id = markup[start..start + markup[start..].find('"').unwrap_or_default()].to_string();
|
|
||||||
markup = markup.replace(&format!(r#"id="{id}""#), &format!(r#"ID="{index}""#)).replace(&format!("#{id}"), &format!("#{index}"));
|
|
||||||
index += 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
let shape = match layer.element() {
|
|
||||||
Graphic::VectorList(vectors) => match vectors
|
|
||||||
.attribute::<Appearance>(graphene_std::list::ATTR_APPEARANCE, 0)
|
|
||||||
.and_then(|appearance| appearance.first_paint_of(Cover::Fill))
|
|
||||||
{
|
|
||||||
Some(Graphic::Gradient(gradient)) => Some(GradientShape::new(
|
|
||||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_START_CURVATURE),
|
|
||||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_END_CURVATURE),
|
|
||||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_GRADIENT_MODEL),
|
|
||||||
gradient.attribute_cloned_or_default(graphene_std::ATTR_TRANSFORM),
|
|
||||||
)),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
(markup.replace(r#"ID=""#, r#"id=""#), shape)
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.draw_rect(10., 20., 110., 70.).await;
|
|
||||||
let layer = editor.active_document().metadata().all_layers().next().expect("the rectangle is a layer");
|
|
||||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(40., 25.), 0.3, DVec2::new(60., 45.));
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::FillGradientSet {
|
|
||||||
layer,
|
|
||||||
gradient: Gradient::from(vec![Color::BLACK, Color::WHITE]),
|
|
||||||
gradient_form: Some(GradientForm::Radial),
|
|
||||||
gradient_settings: Default::default(),
|
|
||||||
transform: Some(placement),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
// The radial form's curvatures draw the unit circle it always drew, and the CPU samples it as the form
|
|
||||||
let (curved_svg, curved_shape) = painted(&mut editor).await;
|
|
||||||
assert!(curved_svg.contains(r#"gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1""#), "{curved_svg}");
|
|
||||||
assert_eq!(curved_shape, Some(GradientShape::Radial));
|
|
||||||
|
|
||||||
// The same document saved with the form, under the name it had before 'Gradient Type' became 'Gradient Form', in place of the curvatures
|
|
||||||
let document = editor.active_document_mut();
|
|
||||||
let fill_id = NodeGraphLayer::new(layer, &document.network_interface)
|
|
||||||
.upstream_node_id_from_protonode(fill::IDENTIFIER)
|
|
||||||
.expect("the layer has a Fill");
|
|
||||||
let inputs = document.network_interface.document_network().nodes[&fill_id].inputs.clone();
|
|
||||||
let curvatures = [4, 5].map(|index| inputs[index].as_value().cloned());
|
|
||||||
assert_eq!(curvatures, GradientForm::Radial.curvatures().map(|curvature| Some(TaggedValue::Number(curvature))));
|
|
||||||
|
|
||||||
let form = NodeInput::value(TaggedValue::GradientForm(GradientForm::Radial), false);
|
|
||||||
let mut old_inputs = NodeTemplate {
|
|
||||||
inputs: [&inputs[..4], &[form], &inputs[6..]].concat(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
document.network_interface.replace_inputs(&fill_id, &[], &mut old_inputs);
|
|
||||||
let serialized = document.serialize_document();
|
|
||||||
assert_eq!(serialized.matches(r#"{"GradientForm":"Radial"}"#).count(), 1, "the form should be saved once");
|
|
||||||
let serialized = serialized.replace(r#"{"GradientForm":"Radial"}"#, r#"{"GradientType":"Radial"}"#);
|
|
||||||
|
|
||||||
editor
|
|
||||||
.handle_message(PortfolioMessage::OpenLegacyDocumentFile {
|
|
||||||
document_name: Some("Migrated".into()),
|
|
||||||
document_path: None,
|
|
||||||
document_serialized_content: serialized,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let (migrated_svg, migrated_shape) = painted(&mut editor).await;
|
|
||||||
assert_eq!(migrated_svg, curved_svg);
|
|
||||||
assert_eq!(migrated_shape, curved_shape);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_no_duplicate_node_replacements() {
|
fn test_no_duplicate_node_replacements() {
|
||||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||||
@@ -6331,35 +5989,6 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn extend_image_to_bounds_opens_as_a_passthrough_of_its_image() {
|
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
|
||||||
use glam::DAffine2;
|
|
||||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
|
||||||
|
|
||||||
let (image, extend) = (NodeId(1), NodeId(2));
|
|
||||||
let image_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
|
|
||||||
.expect("the Image definition should exist")
|
|
||||||
.default_node_template();
|
|
||||||
let extend_template = NodeTemplate {
|
|
||||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("raster_nodes::std_nodes::ExtendImageToBoundsNode")),
|
|
||||||
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::DAffine2(DAffine2::IDENTITY), false)],
|
|
||||||
display_name: "Extend Image to Bounds".to_string(),
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
let mut document = DocumentMessageHandler::default();
|
|
||||||
document.network_interface.insert_node(image, image_template, &[]);
|
|
||||||
document.network_interface.insert_node(extend, extend_template, &[]);
|
|
||||||
document.network_interface.set_input(&InputConnector::node_at_index(extend, 0), NodeInput::node(image, 0), &[]);
|
|
||||||
|
|
||||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
|
||||||
let node = opened.network_interface.document_node(&extend, &[]).expect("the node should still exist");
|
|
||||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
|
||||||
assert!(matches!(node.inputs[..], [NodeInput::Node { node_id, output_index: 0, .. }] if node_id == image), "{:?}", node.inputs);
|
|
||||||
assert_ne!(opened.network_interface.display_name(&extend, &[]), "Extend Image to Bounds");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||||
|
|||||||
@@ -997,7 +997,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
|||||||
artboard_name,
|
artboard_name,
|
||||||
artboard_count,
|
artboard_count,
|
||||||
};
|
};
|
||||||
let result = self.executor.submit_document_export(document, document_id, export_config);
|
let result = self.executor.submit_document_export(document, export_config);
|
||||||
|
|
||||||
if let Err(description) = result {
|
if let Err(description) = result {
|
||||||
responses.add(DialogMessage::DisplayDialogError {
|
responses.add(DialogMessage::DisplayDialogError {
|
||||||
@@ -1124,18 +1124,14 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
PortfolioMessage::SubmitClipboardSvg { id } => {
|
PortfolioMessage::SubmitClipboardSvg { id } => {
|
||||||
let layers = self.active_document().map(|document| {
|
let Some(document) = self.active_document_id.and_then(|document_id| self.documents.get(&document_id)) else {
|
||||||
|
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||||
|
return;
|
||||||
|
};
|
||||||
let selected = document.partition_selection().layers;
|
let selected = document.partition_selection().layers;
|
||||||
let mut layers = document
|
let mut layers = document.metadata().all_layers().filter(|layer| selected.contains(layer)).collect::<Vec<_>>();
|
||||||
.metadata()
|
|
||||||
.all_layers()
|
|
||||||
.filter(|layer| selected.contains(layer))
|
|
||||||
.map(|layer| layer.to_node())
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
layers.reverse();
|
layers.reverse();
|
||||||
layers
|
responses.add(self.executor.submit_clipboard_svg(document, id, &layers));
|
||||||
});
|
|
||||||
responses.add(self.executor.submit_clipboard_svg(self.active_document_id, id, layers.unwrap_or_default()));
|
|
||||||
}
|
}
|
||||||
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
PortfolioMessage::ToggleResetNodesToDefinitionsOnOpen => {
|
||||||
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
self.reset_node_definitions_on_open = !self.reset_node_definitions_on_open;
|
||||||
|
|||||||
@@ -217,7 +217,7 @@ impl DrawingToolState {
|
|||||||
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
Some(FillChoice::Gradient(ramp)) => responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: graphene_std::vector::Gradient::from(&ramp),
|
gradient: graphene_std::vector::Gradient::from(&ramp),
|
||||||
gradient_form: None,
|
gradient_form: Default::default(),
|
||||||
gradient_settings: (&ramp).into(),
|
gradient_settings: (&ramp).into(),
|
||||||
transform: None,
|
transform: None,
|
||||||
}),
|
}),
|
||||||
|
|||||||
@@ -346,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
|||||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||||
let setters = [
|
let setters = [
|
||||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||||
@@ -428,17 +428,6 @@ pub fn get_chain_source_gradient_settings(layer: LayerNodeIdentifier, network_in
|
|||||||
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
|
Some(get_chain_source_gradient_ramp(layer, network_interface)?.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The start and end curvatures a 'Gradient Curvature' node holds as values, or `None` when either is fed from the graph or exposed.
|
|
||||||
pub fn gradient_curvature_values(node: &DocumentNode) -> Option<[f64; 2]> {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
|
||||||
&TaggedValue::Number(value) => Some(value),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
Some([value(node.input(StartCurvatureInput))?, value(node.input(EndCurvatureInput))?])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Get the gradient stops of a layer, if any.
|
/// Get the gradient stops of a layer, if any.
|
||||||
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
pub fn get_gradient_stops(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> Option<Gradient> {
|
||||||
// Try to find the gradient stops value that is created by a Fill node first
|
// Try to find the gradient stops value that is created by a Fill node first
|
||||||
@@ -841,23 +830,9 @@ pub fn set_stroke_weight_for_selected_layers(weight: f64, document: &DocumentMes
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A Fill node's curvatures, unless the graph feeds either or exposes it, read like [`gradient_curvature_values`] reads a 'Gradient Curvature' node's.
|
|
||||||
pub fn fill_node_curvatures(fill_node: &DocumentNode) -> Option<[f64; 2]> {
|
|
||||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
let value = |input: Option<&NodeInput>| match input?.as_non_exposed_value()? {
|
|
||||||
&TaggedValue::Number(value) => Some(value),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
Some([value(fill_node.input(StartCurvatureInput))?, value(fill_node.input(EndCurvatureInput))?])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
/// A Fill node's decoded gradient inputs, with the transform kept in its raw form (not yet baked into `start`/`end`).
|
||||||
pub struct FillNodeGradient {
|
pub struct FillNodeGradient {
|
||||||
pub stops: Gradient,
|
pub stops: Gradient,
|
||||||
/// Its curvatures, unless the graph feeds them, as [`fill_node_curvatures`] reads them.
|
|
||||||
pub curvatures: Option<[f64; 2]>,
|
|
||||||
/// The form its curvatures make, which is linear for any that make neither.
|
|
||||||
pub gradient_form: GradientForm,
|
pub gradient_form: GradientForm,
|
||||||
pub settings: GradientSettings,
|
pub settings: GradientSettings,
|
||||||
pub transform: DAffine2,
|
pub transform: DAffine2,
|
||||||
@@ -874,8 +849,10 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
|||||||
};
|
};
|
||||||
let settings = GradientSettings::from(ramp);
|
let settings = GradientSettings::from(ramp);
|
||||||
let stops = Gradient::from(ramp);
|
let stops = Gradient::from(ramp);
|
||||||
let curvatures = fill_node_curvatures(fill_node);
|
let gradient_form = match fill_node.input(fill::GradientFormInput).and_then(|input| input.as_value()) {
|
||||||
let gradient_form = curvatures.and_then(GradientForm::from_curvatures).unwrap_or_default();
|
Some(&TaggedValue::GradientForm(value)) => value,
|
||||||
|
_ => GradientForm::default(),
|
||||||
|
};
|
||||||
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
let has_transform = matches!(fill_node.input(fill::HasTransformInput).and_then(|input| input.as_value()), Some(&TaggedValue::Bool(true)));
|
||||||
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
let transform_input = fill_node.input(fill::TransformInput).and_then(|input| input.as_value());
|
||||||
let transform = match (has_transform, transform_input) {
|
let transform = match (has_transform, transform_input) {
|
||||||
@@ -886,7 +863,6 @@ pub fn read_fill_node_gradient(fill_node: &DocumentNode, bounding_box: impl FnOn
|
|||||||
|
|
||||||
Some(FillNodeGradient {
|
Some(FillNodeGradient {
|
||||||
stops,
|
stops,
|
||||||
curvatures,
|
|
||||||
gradient_form,
|
gradient_form,
|
||||||
settings,
|
settings,
|
||||||
transform,
|
transform,
|
||||||
@@ -1029,6 +1005,10 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
|||||||
use graphene_std::vector::fill;
|
use graphene_std::vector::fill;
|
||||||
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
|
let fill_parameters = NodeGraphLayer::new(layer, &document.network_interface).find_node_parameters(fill::IDENTIFIER);
|
||||||
|
|
||||||
|
let gradient_form = match fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::GradientFormInput)) {
|
||||||
|
Some(TaggedValue::GradientForm(value)) => *value,
|
||||||
|
_ => GradientForm::default(),
|
||||||
|
};
|
||||||
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
|
let has_transform = matches!(fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::HasTransformInput)), Some(TaggedValue::Bool(true)));
|
||||||
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
|
let transform = match (has_transform, fill_parameters.as_ref().and_then(|parameters| parameters.value(fill::TransformInput))) {
|
||||||
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
(true, Some(TaggedValue::DAffine2(value))) => *value,
|
||||||
@@ -1039,7 +1019,7 @@ pub fn set_fill_for_selected_layers(fill_choice: FillChoice, document: &Document
|
|||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: Gradient::from(ramp),
|
gradient: Gradient::from(ramp),
|
||||||
gradient_form: None,
|
gradient_form,
|
||||||
gradient_settings: ramp.into(),
|
gradient_settings: ramp.into(),
|
||||||
transform: Some(transform),
|
transform: Some(transform),
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,8 +29,6 @@ pub struct GradientTool {
|
|||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct GradientOptions {
|
pub struct GradientOptions {
|
||||||
gradient_form: GradientForm,
|
gradient_form: GradientForm,
|
||||||
/// Where the selected gradient's curvatures come from. Unless they make its form, neither form is shown as chosen.
|
|
||||||
curvature_source: CurvatureSource,
|
|
||||||
settings: GradientSettings,
|
settings: GradientSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,16 +92,12 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
|||||||
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
ToolMessage::Gradient(GradientToolMessage::UpdateOptions { options }) => match options {
|
||||||
GradientOptionsUpdate::Form(gradient_form) => {
|
GradientOptionsUpdate::Form(gradient_form) => {
|
||||||
self.options.gradient_form = gradient_form;
|
self.options.gradient_form = gradient_form;
|
||||||
self.options.curvature_source = CurvatureSource::Form;
|
|
||||||
apply_gradient_update(
|
apply_gradient_update(
|
||||||
&mut self.data,
|
&mut self.data,
|
||||||
context,
|
context,
|
||||||
responses,
|
responses,
|
||||||
|(_gradient, appearance)| appearance.gradient_form != gradient_form || appearance.curvature_source != CurvatureSource::Form,
|
|(_gradient, appearance)| appearance.gradient_form != gradient_form,
|
||||||
|(_gradient, appearance)| {
|
|(_gradient, appearance)| appearance.gradient_form = gradient_form,
|
||||||
appearance.gradient_form = gradient_form;
|
|
||||||
appearance.curvature_source = CurvatureSource::Form;
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
responses.add(ToolMessage::UpdateHints);
|
responses.add(ToolMessage::UpdateHints);
|
||||||
responses.add(ToolMessage::UpdateCursor);
|
responses.add(ToolMessage::UpdateCursor);
|
||||||
@@ -198,19 +192,14 @@ impl<'a> MessageHandler<ToolMessage, &mut ToolActionMessageContext<'a>> for Grad
|
|||||||
|
|
||||||
let mut needs_refresh = false;
|
let mut needs_refresh = false;
|
||||||
if let Some((_gradient, appearance)) = ¤t_gradient {
|
if let Some((_gradient, appearance)) = ¤t_gradient {
|
||||||
if self.options.gradient_form != appearance.gradient_form || self.options.curvature_source != appearance.curvature_source {
|
if self.options.gradient_form != appearance.gradient_form {
|
||||||
self.options.gradient_form = appearance.gradient_form;
|
self.options.gradient_form = appearance.gradient_form;
|
||||||
self.options.curvature_source = appearance.curvature_source;
|
|
||||||
needs_refresh = true;
|
needs_refresh = true;
|
||||||
}
|
}
|
||||||
if self.options.settings != appearance.settings {
|
if self.options.settings != appearance.settings {
|
||||||
self.options.settings = appearance.settings;
|
self.options.settings = appearance.settings;
|
||||||
needs_refresh = true;
|
needs_refresh = true;
|
||||||
}
|
}
|
||||||
} else if self.options.curvature_source != CurvatureSource::Form {
|
|
||||||
// With no gradient selected, the Form radio shows the form a new one gets
|
|
||||||
self.options.curvature_source = CurvatureSource::Form;
|
|
||||||
needs_refresh = true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let has_gradient = current_gradient.is_some();
|
let has_gradient = current_gradient.is_some();
|
||||||
@@ -272,11 +261,7 @@ impl LayoutHolder for GradientTool {
|
|||||||
}
|
}
|
||||||
.into()
|
.into()
|
||||||
});
|
});
|
||||||
let selected_form = (self.options.curvature_source == CurvatureSource::Form).then_some(self.options.gradient_form as u32);
|
let gradient_form = RadioInput::new(gradient_form_entries).selected_index(Some(self.options.gradient_form as u32)).widget_instance();
|
||||||
let gradient_form = RadioInput::new(gradient_form_entries)
|
|
||||||
.selected_index(selected_form)
|
|
||||||
.disabled(self.options.curvature_source == CurvatureSource::Graph)
|
|
||||||
.widget_instance();
|
|
||||||
|
|
||||||
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
// Display priority: the selected layer's stops, then any user-customized tool default, then the working colors
|
||||||
let stops_value = self
|
let stops_value = self
|
||||||
@@ -396,12 +381,10 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
|||||||
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
|
let fill_node = network_interface.document_network().nodes.get(&fill_id)?;
|
||||||
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
|
let gradient = graph_modification_utils::read_fill_node_gradient(fill_node, || network_interface.document_metadata().nonzero_bounding_box(layer))?;
|
||||||
|
|
||||||
let (gradient_form, curvature_source) = CurvatureSource::of(gradient.curvatures);
|
|
||||||
return Some((
|
return Some((
|
||||||
gradient.stops,
|
gradient.stops,
|
||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
gradient_form,
|
gradient_form: gradient.gradient_form,
|
||||||
curvature_source,
|
|
||||||
settings: gradient.settings,
|
settings: gradient.settings,
|
||||||
transform: gradient.transform,
|
transform: gradient.transform,
|
||||||
},
|
},
|
||||||
@@ -421,48 +404,19 @@ fn resolve_gradient(layer: LayerNodeIdentifier, network_interface: &NodeNetworkI
|
|||||||
struct GradientAppearance {
|
struct GradientAppearance {
|
||||||
transform: DAffine2,
|
transform: DAffine2,
|
||||||
gradient_form: GradientForm,
|
gradient_form: GradientForm,
|
||||||
/// Where the chain's curvatures come from. Unless they make `gradient_form`, the tool draws the linear form's controls.
|
|
||||||
// TODO: Draw the stops and midpoints of custom curvatures where their contours cross the line, since the ramp can then span just part of it
|
|
||||||
curvature_source: CurvatureSource,
|
|
||||||
settings: GradientSettings,
|
settings: GradientSettings,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where a gradient's curvatures come from, as told by its 'Gradient Curvature' node or the Fill node holding it.
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
||||||
enum CurvatureSource {
|
|
||||||
/// They make the form, or there's no node and the form's are implied.
|
|
||||||
#[default]
|
|
||||||
Form,
|
|
||||||
/// They're values that make neither form.
|
|
||||||
Custom,
|
|
||||||
/// They're fed from the graph or exposed, so only the graph can change them.
|
|
||||||
Graph,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CurvatureSource {
|
|
||||||
/// The form some curvatures make (linear if neither) and where they come from, given them unless the graph feeds them.
|
|
||||||
fn of(curvatures: Option<[f64; 2]>) -> (GradientForm, Self) {
|
|
||||||
let form = curvatures.and_then(GradientForm::from_curvatures);
|
|
||||||
let source = match (curvatures, form) {
|
|
||||||
(None, _) => Self::Graph,
|
|
||||||
(Some(_), None) => Self::Custom,
|
|
||||||
(Some(_), Some(_)) => Self::Form,
|
|
||||||
};
|
|
||||||
(form.unwrap_or_default(), source)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
|
/// Resolve the gradient transform, form, and spread by walking the chain feeding the layer.
|
||||||
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &NodeNetworkInterface) -> GradientAppearance {
|
||||||
let target_input = gradient_chain_target_input(layer, network_interface);
|
let target_input = gradient_chain_target_input(layer, network_interface);
|
||||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||||
|
|
||||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||||
|
|
||||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||||
let mut gradient_form: Option<GradientForm> = None;
|
let mut gradient_form: Option<GradientForm> = None;
|
||||||
let mut curvature_source = CurvatureSource::Form;
|
|
||||||
|
|
||||||
for node_id in network_interface
|
for node_id in network_interface
|
||||||
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
.upstream_flow_back_from_nodes(vec![walk_from], &[], FlowType::HorizontalFlow)
|
||||||
@@ -476,9 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
|||||||
|
|
||||||
if reference == transform_reference {
|
if reference == transform_reference {
|
||||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
} else if reference == gradient_form_reference
|
||||||
let (form, source) = CurvatureSource::of(graph_modification_utils::gradient_curvature_values(document_node));
|
&& gradient_form.is_none()
|
||||||
(gradient_form, curvature_source) = (Some(form), source);
|
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||||
|
{
|
||||||
|
gradient_form = Some(*value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -488,7 +444,6 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
|||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
transform: composed_transform,
|
transform: composed_transform,
|
||||||
gradient_form: gradient_form.unwrap_or_default(),
|
gradient_form: gradient_form.unwrap_or_default(),
|
||||||
curvature_source,
|
|
||||||
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
settings: get_chain_source_gradient_settings(layer, network_interface).unwrap_or_default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -838,15 +793,12 @@ impl SelectedGradient {
|
|||||||
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
pub fn render_gradient(&mut self, responses: &mut VecDeque<Message>) {
|
||||||
if let Some(layer) = self.layer {
|
if let Some(layer) = self.layer {
|
||||||
if self.is_gradient_chain {
|
if self.is_gradient_chain {
|
||||||
// Only a new gradient takes its form from the tool, as the Properties panel may have adjusted an existing one after it was selected
|
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, responses);
|
||||||
let write_form = self.dragging == GradientDragTarget::New;
|
|
||||||
dispatch_gradient_chain_writes(layer, &self.gradient, self.appearance, write_form, responses);
|
|
||||||
} else {
|
} else {
|
||||||
// Only a new gradient takes its form from the tool, as with a chain
|
|
||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: self.gradient.clone(),
|
gradient: self.gradient.clone(),
|
||||||
gradient_form: (self.dragging == GradientDragTarget::New).then_some(self.appearance.gradient_form),
|
gradient_form: self.appearance.gradient_form,
|
||||||
gradient_settings: self.appearance.settings,
|
gradient_settings: self.appearance.settings,
|
||||||
transform: Some(self.appearance.transform),
|
transform: Some(self.appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -877,8 +829,8 @@ impl SelectedGradient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer, including its form's curvatures if `write_form` is set.
|
/// Send the per-attribute graph operations that mirror the in-memory `Gradient` onto the chain feeding the layer.
|
||||||
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, write_form: bool, responses: &mut VecDeque<Message>) {
|
fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradient, appearance: GradientAppearance, responses: &mut VecDeque<Message>) {
|
||||||
responses.add(GraphOperationMessage::GradientCyclicSet {
|
responses.add(GraphOperationMessage::GradientCyclicSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_cyclic: appearance.settings.cyclic,
|
gradient_cyclic: appearance.settings.cyclic,
|
||||||
@@ -896,12 +848,10 @@ fn dispatch_gradient_chain_writes(layer: LayerNodeIdentifier, gradient: &Gradien
|
|||||||
layer,
|
layer,
|
||||||
transform: appearance.transform,
|
transform: appearance.transform,
|
||||||
});
|
});
|
||||||
if write_form && appearance.curvature_source == CurvatureSource::Form {
|
|
||||||
responses.add(GraphOperationMessage::GradientFormSet {
|
responses.add(GraphOperationMessage::GradientFormSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_form: appearance.gradient_form,
|
gradient_form: appearance.gradient_form,
|
||||||
});
|
});
|
||||||
}
|
|
||||||
responses.add(GraphOperationMessage::GradientSpreadSet {
|
responses.add(GraphOperationMessage::GradientSpreadSet {
|
||||||
layer,
|
layer,
|
||||||
gradient_spread: appearance.settings.spread,
|
gradient_spread: appearance.settings.spread,
|
||||||
@@ -1572,7 +1522,6 @@ impl Fsm for GradientToolFsmState {
|
|||||||
GradientAppearance {
|
GradientAppearance {
|
||||||
transform: DAffine2::IDENTITY,
|
transform: DAffine2::IDENTITY,
|
||||||
gradient_form: tool_options.gradient_form,
|
gradient_form: tool_options.gradient_form,
|
||||||
curvature_source: CurvatureSource::Form,
|
|
||||||
settings: tool_options.settings,
|
settings: tool_options.settings,
|
||||||
},
|
},
|
||||||
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
|
// A blank layer, or one holding only the other tool's paint, starts a whole-expanse gradient chain; a layer with content gets its Fill painted
|
||||||
@@ -1991,13 +1940,12 @@ fn apply_gradient_update(
|
|||||||
|
|
||||||
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
|
// Only check for the gradient list once we know we'll write back, since this is a graph traversal per layer
|
||||||
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
|
if get_upstream_gradient_value_node_id(layer, &context.document.network_interface).is_some() {
|
||||||
// Read fresh from the layer, so its form's curvatures change only if the update chose another form
|
dispatch_gradient_chain_writes(layer, &gradient, appearance, responses);
|
||||||
dispatch_gradient_chain_writes(layer, &gradient, appearance, true, responses);
|
|
||||||
} else {
|
} else {
|
||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient,
|
gradient,
|
||||||
gradient_form: (appearance.curvature_source == CurvatureSource::Form).then_some(appearance.gradient_form),
|
gradient_form: appearance.gradient_form,
|
||||||
gradient_settings: appearance.settings,
|
gradient_settings: appearance.settings,
|
||||||
transform: Some(appearance.transform),
|
transform: Some(appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -2063,7 +2011,7 @@ fn apply_stops_update(data: &mut GradientToolData, context: &mut ToolActionMessa
|
|||||||
responses.add(GraphOperationMessage::FillGradientSet {
|
responses.add(GraphOperationMessage::FillGradientSet {
|
||||||
layer,
|
layer,
|
||||||
gradient: new_gradient.clone(),
|
gradient: new_gradient.clone(),
|
||||||
gradient_form: None,
|
gradient_form: appearance.gradient_form,
|
||||||
gradient_settings: settings,
|
gradient_settings: settings,
|
||||||
transform: Some(appearance.transform),
|
transform: Some(appearance.transform),
|
||||||
});
|
});
|
||||||
@@ -2160,7 +2108,6 @@ mod test_gradient {
|
|||||||
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
use super::{GradientHoverTarget, detect_hover_target, gradient_to_viewport_transform, midpoint_diamonds, midpoint_ratio_at};
|
||||||
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
use crate::consts::{GRADIENT_MIDPOINT_MAX, GRADIENT_MIDPOINT_MIN};
|
||||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||||
use crate::messages::layout::utility_types::layout_widget::{DiffUpdate, Layout, LayoutTarget, Widget, WidgetInstance};
|
|
||||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||||
@@ -2168,8 +2115,8 @@ mod test_gradient {
|
|||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_upstream_gradient_value_node_id;
|
||||||
pub use crate::test_utils::test_prelude::*;
|
pub use crate::test_utils::test_prelude::*;
|
||||||
use glam::DAffine2;
|
use glam::DAffine2;
|
||||||
|
use graph_craft::document::NodeInput;
|
||||||
use graph_craft::document::value::TaggedValue;
|
use graph_craft::document::value::TaggedValue;
|
||||||
use graph_craft::document::{NodeId, NodeInput};
|
|
||||||
use graphene_std::NodeParameter;
|
use graphene_std::NodeParameter;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
use graphene_std::vector::style::{GradientForm, GradientSpread, build_transform_with_y_preservation};
|
||||||
@@ -3419,7 +3366,7 @@ mod test_gradient {
|
|||||||
.await;
|
.await;
|
||||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||||
|
|
||||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||||
editor.select_tool(ToolType::Gradient).await;
|
editor.select_tool(ToolType::Gradient).await;
|
||||||
editor
|
editor
|
||||||
@@ -3428,7 +3375,7 @@ mod test_gradient {
|
|||||||
})
|
})
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||||
let form_node_id = {
|
let form_node_id = {
|
||||||
let network_interface = &editor.active_document().network_interface;
|
let network_interface = &editor.active_document().network_interface;
|
||||||
network_interface
|
network_interface
|
||||||
@@ -3437,10 +3384,10 @@ mod test_gradient {
|
|||||||
.keys()
|
.keys()
|
||||||
.copied()
|
.copied()
|
||||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||||
.expect("Gradient Curvature node should have been inserted")
|
.expect("Gradient Form node should have been inserted")
|
||||||
};
|
};
|
||||||
|
|
||||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||||
|
|
||||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||||
@@ -3585,347 +3532,6 @@ mod test_gradient {
|
|||||||
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
|
assert!(matches!(positions_input, NodeInput::Node { .. }), "the wired positions input must survive the baked write");
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drags the end of a layer's gradient by `offset` in the viewport with the Gradient tool, returning where the end was dragged to.
|
|
||||||
async fn drag_gradient_end(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, offset: DVec2) -> DVec2 {
|
|
||||||
let document = editor.active_document();
|
|
||||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
|
||||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
|
||||||
let dragged_end = end + offset;
|
|
||||||
|
|
||||||
editor.move_mouse(end.x, end.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
|
||||||
editor.left_mousedown(end.x, end.y, ModifierKeys::empty()).await;
|
|
||||||
editor.move_mouse(dragged_end.x, dragged_end.y, ModifierKeys::empty(), MouseKeys::LEFT).await;
|
|
||||||
editor
|
|
||||||
.mouseup(
|
|
||||||
EditorPointerState {
|
|
||||||
editor_position: dragged_end,
|
|
||||||
mouse_keys: MouseKeys::empty(),
|
|
||||||
..Default::default()
|
|
||||||
},
|
|
||||||
ModifierKeys::empty(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
dragged_end
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Makes a layer drawing a gradient list along the line from (10, 50) to (200, 50) and selects it with the Gradient tool, then chooses
|
|
||||||
/// the radial form, which inserts a 'Gradient Curvature' node. Returns the layer and that node.
|
|
||||||
async fn radial_gradient_list_layer(editor: &mut EditorTestUtils) -> (LayerNodeIdentifier, NodeId) {
|
|
||||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
|
||||||
let layer = create_gradient_list_layer(editor).await;
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::GradientTransformSet {
|
|
||||||
layer,
|
|
||||||
transform: transform_from_line(DVec2::new(10., 50.), DVec2::new(200., 50.)),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
|
||||||
editor.select_tool(ToolType::Gradient).await;
|
|
||||||
|
|
||||||
editor
|
|
||||||
.handle_message(GradientToolMessage::UpdateOptions {
|
|
||||||
options: super::GradientOptionsUpdate::Form(GradientForm::Radial),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
|
||||||
let network_interface = &editor.active_document().network_interface;
|
|
||||||
let curvature_node_id = network_interface
|
|
||||||
.document_network()
|
|
||||||
.nodes
|
|
||||||
.keys()
|
|
||||||
.copied()
|
|
||||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&curvature_reference))
|
|
||||||
.expect("Gradient Curvature node should have been inserted");
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(editor, curvature_node_id),
|
|
||||||
inputs_holding(GradientForm::Radial.curvatures()),
|
|
||||||
"the inserted node should hold the radial form's curvatures"
|
|
||||||
);
|
|
||||||
|
|
||||||
(layer, curvature_node_id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets both curvatures of a 'Gradient Curvature' node, as its sliders in the Properties panel do.
|
|
||||||
async fn set_curvatures(editor: &mut EditorTestUtils, curvature_node_id: NodeId, curvatures: [f64; 2]) {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
for (input_index, curvature) in [StartCurvatureInput::INDEX, EndCurvatureInput::INDEX].into_iter().zip(curvatures) {
|
|
||||||
editor
|
|
||||||
.handle_message(NodeGraphMessage::SetInputValue {
|
|
||||||
node_id: curvature_node_id,
|
|
||||||
input_index,
|
|
||||||
value: TaggedValue::Number(curvature).into(),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The start and end curvature inputs of a 'Gradient Curvature' node.
|
|
||||||
fn curvature_inputs(editor: &EditorTestUtils, curvature_node_id: NodeId) -> [Option<NodeInput>; 2] {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
let node = &editor.active_document().network_interface.document_network().nodes[&curvature_node_id];
|
|
||||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The curvature inputs holding these values.
|
|
||||||
fn inputs_holding(curvatures: [f64; 2]) -> [Option<NodeInput>; 2] {
|
|
||||||
curvatures.map(|curvature| Some(NodeInput::value(TaggedValue::Number(curvature), false)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Form radio's chosen entry and whether it's disabled, as last sent to the control bar among these frontend messages.
|
|
||||||
fn latest_form_radio(frontend_messages: &[FrontendMessage]) -> Option<(Option<u32>, bool)> {
|
|
||||||
let form_radio = |widget: &WidgetInstance| match &*widget.widget {
|
|
||||||
Widget::RadioInput(radio_input) => Some((radio_input.selected_index, radio_input.disabled)),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
frontend_messages
|
|
||||||
.iter()
|
|
||||||
.rev()
|
|
||||||
.filter_map(|message| match message {
|
|
||||||
FrontendMessage::UpdateLayout {
|
|
||||||
layout_target: LayoutTarget::ToolOptions,
|
|
||||||
diff,
|
|
||||||
} => Some(diff),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.flat_map(|diff| diff.iter().rev())
|
|
||||||
.find_map(|widget_diff| match &widget_diff.new_value {
|
|
||||||
DiffUpdate::Widget(widget) => form_radio(widget),
|
|
||||||
DiffUpdate::Layout(layout) => layout.iter().find_map(form_radio),
|
|
||||||
DiffUpdate::LayoutGroup(group) => Layout(vec![group.clone()]).iter().find_map(form_radio),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn tool_edits_keep_custom_curvatures_until_a_form_is_chosen() {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
|
||||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
|
||||||
|
|
||||||
// Dragging the end writes every attribute the tool manages, but leaves the curvatures as they are
|
|
||||||
let dragged_end = drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
|
||||||
let document = editor.active_document();
|
|
||||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the gradient should survive the drag");
|
|
||||||
let end = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::X);
|
|
||||||
assert!(end.abs_diff_eq(dragged_end, 1.), "the drag should move the end to {dragged_end:?}, not {end:?}");
|
|
||||||
assert_eq!(curvature_inputs(&editor, curvature_node_id), inputs_holding([0.5, 0.25]), "a drag shouldn't reset custom curvatures");
|
|
||||||
|
|
||||||
// Choosing a form in the control bar is what sets them
|
|
||||||
editor
|
|
||||||
.handle_message(GradientToolMessage::UpdateOptions {
|
|
||||||
options: super::GradientOptionsUpdate::Form(GradientForm::Linear),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(&editor, curvature_node_id),
|
|
||||||
inputs_holding(GradientForm::Linear.curvatures()),
|
|
||||||
"choosing the linear form should set its curvatures"
|
|
||||||
);
|
|
||||||
|
|
||||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
|
||||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
|
||||||
editor
|
|
||||||
.handle_message(NodeGraphMessage::CreateWire {
|
|
||||||
output_connector: OutputConnector::primary_output(number_node_id),
|
|
||||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
|
||||||
layer,
|
|
||||||
gradient_form: GradientForm::Radial,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let [start_input, end_input] = curvature_inputs(&editor, curvature_node_id);
|
|
||||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
|
||||||
assert_eq!(
|
|
||||||
end_input,
|
|
||||||
inputs_holding(GradientForm::Linear.curvatures())[1],
|
|
||||||
"the end curvature beside a wired one should stay as it was"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn edits_of_a_fill_gradient_keep_its_curvatures_until_a_form_is_chosen() {
|
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_fill_node_id_with_direct_fill_input;
|
|
||||||
use graphene_std::vector::fill::{EndCurvatureInput, StartCurvatureInput};
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
editor.active_document_mut().snapping_state.snapping_enabled = false;
|
|
||||||
editor.drag_tool(ToolType::Rectangle, -5., -3., 100., 100., ModifierKeys::empty()).await;
|
|
||||||
editor.drag_tool(ToolType::Gradient, 0., 0., 100., 0., ModifierKeys::empty()).await;
|
|
||||||
|
|
||||||
let document = editor.active_document();
|
|
||||||
let layer = document
|
|
||||||
.network_interface
|
|
||||||
.selected_nodes()
|
|
||||||
.selected_layers(document.metadata())
|
|
||||||
.next()
|
|
||||||
.expect("the rectangle is selected");
|
|
||||||
let fill_id = get_fill_node_id_with_direct_fill_input(layer, &document.network_interface).expect("the gradient is held by the Fill");
|
|
||||||
let curvatures = |editor: &EditorTestUtils| {
|
|
||||||
let node = &editor.active_document().network_interface.document_network().nodes[&fill_id];
|
|
||||||
[node.input(StartCurvatureInput).cloned(), node.input(EndCurvatureInput).cloned()]
|
|
||||||
};
|
|
||||||
|
|
||||||
// Curvatures making neither form survive a drag of the gradient's end
|
|
||||||
for (input_index, curvature) in [(StartCurvatureInput::INDEX, 0.3), (EndCurvatureInput::INDEX, 0.2)] {
|
|
||||||
let value = TaggedValue::Number(curvature).into();
|
|
||||||
editor.handle_message(NodeGraphMessage::SetInputValue { node_id: fill_id, input_index, value }).await;
|
|
||||||
}
|
|
||||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 20.)).await;
|
|
||||||
assert_eq!(curvatures(&editor), inputs_holding([0.3, 0.2]), "a drag shouldn't reset custom curvatures");
|
|
||||||
|
|
||||||
// Choosing a form in the control bar is what sets them
|
|
||||||
let choose_form = |form| GradientToolMessage::UpdateOptions {
|
|
||||||
options: super::GradientOptionsUpdate::Form(form),
|
|
||||||
};
|
|
||||||
editor.handle_message(choose_form(GradientForm::Radial)).await;
|
|
||||||
assert_eq!(
|
|
||||||
curvatures(&editor),
|
|
||||||
inputs_holding(GradientForm::Radial.curvatures()),
|
|
||||||
"choosing the radial form should set its curvatures"
|
|
||||||
);
|
|
||||||
|
|
||||||
// A curvature fed by a wire is procedural authorship, which neither a drag nor a form's write may replace with a value
|
|
||||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
|
||||||
editor
|
|
||||||
.handle_message(NodeGraphMessage::CreateWire {
|
|
||||||
output_connector: OutputConnector::primary_output(number_node_id),
|
|
||||||
input_connector: InputConnector::node(fill_id, StartCurvatureInput),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., -20.)).await;
|
|
||||||
editor.handle_message(choose_form(GradientForm::Linear)).await;
|
|
||||||
let [start_input, end_input] = curvatures(&editor);
|
|
||||||
assert!(matches!(start_input, Some(NodeInput::Node { .. })), "the wired start curvature should stay wired, not {start_input:?}");
|
|
||||||
assert_eq!(
|
|
||||||
end_input,
|
|
||||||
inputs_holding(GradientForm::Radial.curvatures())[1],
|
|
||||||
"the end curvature beside a wired one should stay as it was"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn stop_edits_keep_curvatures_set_while_the_stop_was_selected() {
|
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
|
||||||
let stop_count = |editor: &EditorTestUtils| get_gradient_stops(layer, &editor.active_document().network_interface).map(|stops| stops.len());
|
|
||||||
|
|
||||||
// Clicking the line inserts a stop and selects it, and a double-click opens its color picker
|
|
||||||
let document = editor.active_document();
|
|
||||||
let (_, appearance, _) = super::resolve_gradient(layer, &document.network_interface).expect("the layer should have a gradient");
|
|
||||||
let stop = (gradient_to_viewport_transform(layer, document) * appearance.transform).transform_point2(DVec2::new(0.3, 0.));
|
|
||||||
editor.move_mouse(stop.x, stop.y, ModifierKeys::empty(), MouseKeys::empty()).await;
|
|
||||||
editor.left_mousedown(stop.x, stop.y, ModifierKeys::empty()).await;
|
|
||||||
editor.left_mouseup(stop.x, stop.y, ModifierKeys::empty()).await;
|
|
||||||
editor.handle_message(GradientToolMessage::DoubleClick).await;
|
|
||||||
assert_eq!(stop_count(&editor), Some(3), "the click should insert a stop");
|
|
||||||
|
|
||||||
// The Properties panel then adjusts curvatures of neither form while the stop stays selected
|
|
||||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.5]).await;
|
|
||||||
|
|
||||||
editor.handle_message(GradientToolMessage::UpdateStopColor { color: Color::GREEN }).await;
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(&editor, curvature_node_id),
|
|
||||||
inputs_holding([0.5, 0.5]),
|
|
||||||
"recoloring the stop shouldn't reset the curvatures"
|
|
||||||
);
|
|
||||||
|
|
||||||
editor.press(Key::Delete, ModifierKeys::empty()).await;
|
|
||||||
assert_eq!(stop_count(&editor), Some(2), "Delete should remove the selected stop");
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(&editor, curvature_node_id),
|
|
||||||
inputs_holding([0.5, 0.5]),
|
|
||||||
"deleting the stop shouldn't reset the curvatures"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn curvatures_already_making_a_form_are_kept_by_writes_of_that_form() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
|
||||||
|
|
||||||
// The start curvature's slider maximum is the same point as -1, so the tool draws these curvatures as the radial form
|
|
||||||
set_curvatures(&mut editor, curvature_node_id, [1., 0.5]).await;
|
|
||||||
let (_, appearance, _) = super::resolve_gradient(layer, &editor.active_document().network_interface).expect("the layer should have a gradient");
|
|
||||||
assert_eq!((appearance.gradient_form, appearance.curvature_source), (GradientForm::Radial, super::CurvatureSource::Form));
|
|
||||||
|
|
||||||
drag_gradient_end(&mut editor, layer, DVec2::new(0., 40.)).await;
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(&editor, curvature_node_id),
|
|
||||||
inputs_holding([1., 0.5]),
|
|
||||||
"a drag shouldn't rewrite curvatures making the form"
|
|
||||||
);
|
|
||||||
|
|
||||||
editor
|
|
||||||
.handle_message(GraphOperationMessage::GradientFormSet {
|
|
||||||
layer,
|
|
||||||
gradient_form: GradientForm::Radial,
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
assert_eq!(
|
|
||||||
curvature_inputs(&editor, curvature_node_id),
|
|
||||||
inputs_holding([1., 0.5]),
|
|
||||||
"setting the form they make shouldn't rewrite them"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn the_form_radio_shows_what_a_new_gradient_gets_once_a_custom_one_is_deselected() {
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
|
||||||
set_curvatures(&mut editor, curvature_node_id, [0.5, 0.25]).await;
|
|
||||||
|
|
||||||
// Reselecting the layer has the tool read its curvatures, which make neither form
|
|
||||||
let mut frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
|
||||||
assert_eq!(latest_form_radio(&frontend_messages), Some((None, false)), "custom curvatures should show neither form as chosen");
|
|
||||||
|
|
||||||
frontend_messages.extend(editor.handle_message(DocumentMessage::DeselectAllLayers).await);
|
|
||||||
assert_eq!(
|
|
||||||
latest_form_radio(&frontend_messages),
|
|
||||||
Some((Some(GradientForm::Linear as u32), false)),
|
|
||||||
"with nothing selected, the radio should show the linear form a new gradient gets"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn the_form_radio_is_disabled_for_curvatures_fed_from_the_graph() {
|
|
||||||
use graphene_std::math_nodes::gradient_curvature::StartCurvatureInput;
|
|
||||||
|
|
||||||
let mut editor = EditorTestUtils::create();
|
|
||||||
editor.new_document().await;
|
|
||||||
let (layer, curvature_node_id) = radial_gradient_list_layer(&mut editor).await;
|
|
||||||
|
|
||||||
let number_node_id = editor.create_node_by_name(DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::number_value::IDENTIFIER)).await;
|
|
||||||
editor
|
|
||||||
.handle_message(NodeGraphMessage::CreateWire {
|
|
||||||
output_connector: OutputConnector::primary_output(number_node_id),
|
|
||||||
input_connector: InputConnector::node(curvature_node_id, StartCurvatureInput),
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let frontend_messages = editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
|
||||||
assert_eq!(
|
|
||||||
latest_form_radio(&frontend_messages),
|
|
||||||
Some((None, true)),
|
|
||||||
"a wired curvature should leave no form chosen and the radio disabled"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn drag_on_blank_layer_starts_gradient_chain() {
|
async fn drag_on_blank_layer_starts_gradient_chain() {
|
||||||
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
use crate::messages::tool::common_functionality::graph_modification_utils::get_gradient_stops;
|
||||||
|
|||||||
+195
-120
@@ -1,23 +1,28 @@
|
|||||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
use crate::messages::frontend::utility_types::{ExportBounds, FileType, RasterizedImage, RenderStatus};
|
||||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
use crate::messages::portfolio::document::node_graph::utility_types::NodeEvaluationError;
|
||||||
|
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface, RootNode};
|
||||||
use crate::messages::prelude::*;
|
use crate::messages::prelude::*;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
|
use graph_craft::application_io::resource::ResourceRegistry;
|
||||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||||
|
use graph_craft::list;
|
||||||
use graph_craft::proto::GraphErrors;
|
use graph_craft::proto::GraphErrors;
|
||||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::color::SRGBA8;
|
use graphene_std::color::SRGBA8;
|
||||||
use graphene_std::list::{Item, List};
|
use graphene_std::list::{Item, List};
|
||||||
|
use graphene_std::math::quad::Quad;
|
||||||
use graphene_std::raster::{CPU, Raster};
|
use graphene_std::raster::{CPU, Raster};
|
||||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||||
use graphene_std::transform::Footprint;
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, path, paths_from_list_row_attributes};
|
||||||
use graphene_std::{ATTR_TRANSFORM, ContextOverrides, Graphic, NodeParameter};
|
use graphene_std::{ATTR_TRANSFORM, Artboard, ContextOverrides, Graphic, NodeParameter};
|
||||||
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
use interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||||
|
use interpreted_executor::layer_paths::{layer_content, write_layer_paths};
|
||||||
use std::any::Any;
|
use std::any::Any;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::mpsc::{Receiver, Sender};
|
use std::sync::mpsc::{Receiver, Sender};
|
||||||
@@ -97,7 +102,8 @@ impl std::fmt::Display for EvaluationErrors {
|
|||||||
|
|
||||||
#[derive(serde::Serialize, serde::Deserialize)]
|
#[derive(serde::Serialize, serde::Deserialize)]
|
||||||
pub struct CompilationResponse {
|
pub struct CompilationResponse {
|
||||||
result: Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)>,
|
result: Result<(), String>,
|
||||||
|
resolved_types: ResolvedDocumentNodeTypesDelta,
|
||||||
node_graph_errors: GraphErrors,
|
node_graph_errors: GraphErrors,
|
||||||
node_graph_warnings: GraphErrors,
|
node_graph_warnings: GraphErrors,
|
||||||
}
|
}
|
||||||
@@ -112,19 +118,24 @@ pub enum NodeGraphUpdate {
|
|||||||
},
|
},
|
||||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||||
Observations(HashMap<ObservationKey, InspectResult>),
|
Observations(HashMap<ObservationKey, InspectResult>),
|
||||||
ClipboardSvg {
|
Export {
|
||||||
id: u64,
|
id: u64,
|
||||||
svg: Option<String>,
|
result: Box<ExecutionResult>,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct NodeGraphExecutor {
|
pub struct NodeGraphExecutor {
|
||||||
sender: Sender<GraphRuntimeRequest>,
|
sender: Sender<GraphRuntimeRequest>,
|
||||||
|
|
||||||
receiver: Receiver<NodeGraphUpdate>,
|
receiver: Receiver<NodeGraphUpdate>,
|
||||||
current_execution_id: u64,
|
current_execution_id: u64,
|
||||||
futures: VecDeque<(u64, ExecutionContext)>,
|
futures: VecDeque<(u64, ExecutionContext)>,
|
||||||
pending: Option<(u64, ExecutionContext)>,
|
pending: Option<(u64, ExecutionContext)>,
|
||||||
|
|
||||||
|
current_export_id: u64,
|
||||||
|
exports: HashMap<u64, ExportTarget>,
|
||||||
|
|
||||||
node_graph_hash: u64,
|
node_graph_hash: u64,
|
||||||
/// The document whose network the graph runtime was last sent.
|
/// The document whose network the graph runtime was last sent.
|
||||||
node_graph_document: Option<DocumentId>,
|
node_graph_document: Option<DocumentId>,
|
||||||
@@ -146,9 +157,14 @@ pub struct NodeGraphExecutor {
|
|||||||
gradient_migration_attempted: HashSet<DocumentId>,
|
gradient_migration_attempted: HashSet<DocumentId>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum ExportTarget {
|
||||||
|
File(ExportConfig),
|
||||||
|
Clipboard(u64),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
struct ExecutionContext {
|
struct ExecutionContext {
|
||||||
export_config: Option<ExportConfig>,
|
|
||||||
document_id: DocumentId,
|
document_id: DocumentId,
|
||||||
/// The view the render was asked for, which the footprints it reports back are measured in.
|
/// The view the render was asked for, which the footprints it reports back are measured in.
|
||||||
document_to_viewport: DAffine2,
|
document_to_viewport: DAffine2,
|
||||||
@@ -183,6 +199,8 @@ impl NodeGraphExecutor {
|
|||||||
futures: Default::default(),
|
futures: Default::default(),
|
||||||
pending: None,
|
pending: None,
|
||||||
current_execution_id: 0,
|
current_execution_id: 0,
|
||||||
|
current_export_id: 0,
|
||||||
|
exports: HashMap::new(),
|
||||||
node_graph_hash: 0,
|
node_graph_hash: 0,
|
||||||
node_graph_document: None,
|
node_graph_document: None,
|
||||||
previous_node_to_inspect: Vec::new(),
|
previous_node_to_inspect: Vec::new(),
|
||||||
@@ -211,6 +229,21 @@ impl NodeGraphExecutor {
|
|||||||
execution_id
|
execution_id
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn queue_export(&mut self, network: NodeNetwork, resources: ResourceRegistry, render_config: RenderConfig, target: ExportTarget) -> Result<(), String> {
|
||||||
|
let id = self.current_export_id;
|
||||||
|
self.current_export_id += 1;
|
||||||
|
let request = GraphRuntimeRequest::Export {
|
||||||
|
id,
|
||||||
|
render_config,
|
||||||
|
network,
|
||||||
|
resources,
|
||||||
|
};
|
||||||
|
self.sender.send(request).map_err(|e| e.to_string())?;
|
||||||
|
self.exports.insert(id, target);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
pub fn submit_overlays(&self, context: crate::messages::portfolio::document::overlays::utility_types::OverlayContext) {
|
||||||
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
if let Err(error) = self.sender.send(GraphRuntimeRequest::RenderOverlays(context)) {
|
||||||
log::error!("Failed to send the overlays: {error}");
|
log::error!("Failed to send the overlays: {error}");
|
||||||
@@ -229,13 +262,29 @@ impl NodeGraphExecutor {
|
|||||||
.expect("Failed to send the context overrides");
|
.expect("Failed to send the context overrides");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
pub fn submit_clipboard_svg(&mut self, document: &DocumentMessageHandler, id: u64, layers: &[LayerNodeIdentifier]) -> Message {
|
||||||
if document_id.is_none() || self.node_graph_document != document_id {
|
let no_svg = ClipboardMessage::Rendered { id, svg: None }.into();
|
||||||
return ClipboardMessage::Rendered { id, svg: None }.into();
|
let Some((network, [min, max])) = copied_layers(&document.network_interface, layers) else {
|
||||||
}
|
return no_svg;
|
||||||
|
};
|
||||||
|
|
||||||
self.sender.send(GraphRuntimeRequest::ClipboardSvg { id, layers }).expect("Failed to send runtime request");
|
let viewport = Footprint {
|
||||||
Message::NoOp
|
resolution: (max - min).round().as_uvec2(),
|
||||||
|
transform: DAffine2::from_translation(-min),
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
let render_config = RenderConfig {
|
||||||
|
viewport,
|
||||||
|
scale: 1.,
|
||||||
|
export_format: ExportFormat::Svg,
|
||||||
|
for_export: true,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
|
||||||
|
match self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::Clipboard(id)) {
|
||||||
|
Ok(()) => Message::NoOp,
|
||||||
|
Err(_) => no_svg,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
pub fn submit_thumbnails_in_view(&self, document: &DocumentMessageHandler, document_id: DocumentId) {
|
||||||
@@ -260,9 +309,11 @@ impl NodeGraphExecutor {
|
|||||||
|
|
||||||
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
|
let graph_hash = document.network_interface.network_hash().wrapping_add(document.resources.resolved_hash());
|
||||||
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
|
if graph_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
|
||||||
let network = document.network_interface.document_network().clone();
|
let mut network = document.network_interface.document_network().clone();
|
||||||
let previewed = document.network_interface.previewed_nodes();
|
let previewed = document.network_interface.previewed_nodes();
|
||||||
let layers = document.network_interface.layer_paths();
|
let layers = document.network_interface.layer_paths();
|
||||||
|
prepare_network(&mut network, &previewed, &layers);
|
||||||
|
let thumbnails = thumbnail_sources(&network, &layers);
|
||||||
self.node_graph_hash = graph_hash;
|
self.node_graph_hash = graph_hash;
|
||||||
self.node_graph_document = Some(document_id);
|
self.node_graph_document = Some(document_id);
|
||||||
|
|
||||||
@@ -272,8 +323,7 @@ impl NodeGraphExecutor {
|
|||||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
network,
|
network,
|
||||||
resources,
|
resources,
|
||||||
previewed,
|
thumbnails,
|
||||||
layers,
|
|
||||||
observations: self.observations(&document.network_interface),
|
observations: self.observations(&document.network_interface),
|
||||||
}))
|
}))
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
@@ -337,7 +387,6 @@ impl NodeGraphExecutor {
|
|||||||
self.futures.push_back((
|
self.futures.push_back((
|
||||||
execution_id,
|
execution_id,
|
||||||
ExecutionContext {
|
ExecutionContext {
|
||||||
export_config: None,
|
|
||||||
document_id,
|
document_id,
|
||||||
document_to_viewport: viewport.transform,
|
document_to_viewport: viewport.transform,
|
||||||
measure_fill: None,
|
measure_fill: None,
|
||||||
@@ -404,7 +453,6 @@ impl NodeGraphExecutor {
|
|||||||
self.futures.push_back((
|
self.futures.push_back((
|
||||||
execution_id,
|
execution_id,
|
||||||
ExecutionContext {
|
ExecutionContext {
|
||||||
export_config: None,
|
|
||||||
document_id,
|
document_id,
|
||||||
document_to_viewport: viewport.transform,
|
document_to_viewport: viewport.transform,
|
||||||
measure_fill: None,
|
measure_fill: None,
|
||||||
@@ -415,10 +463,9 @@ impl NodeGraphExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Evaluates a node graph for export
|
/// Evaluates a node graph for export
|
||||||
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, export_config: ExportConfig) -> Result<(), String> {
|
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, export_config: ExportConfig) -> Result<(), String> {
|
||||||
let network = document.network_interface.document_network().clone();
|
let mut network = document.network_interface.document_network().clone();
|
||||||
let previewed = document.network_interface.previewed_nodes();
|
prepare_network(&mut network, &document.network_interface.previewed_nodes(), &document.network_interface.layer_paths());
|
||||||
let resources = document.resources.registry.clone();
|
|
||||||
|
|
||||||
let export_format = if export_config.file_type == FileType::Svg {
|
let export_format = if export_config.file_type == FileType::Svg {
|
||||||
graphene_std::application_io::ExportFormat::Svg
|
graphene_std::application_io::ExportFormat::Svg
|
||||||
@@ -452,34 +499,12 @@ impl NodeGraphExecutor {
|
|||||||
time: Default::default(),
|
time: Default::default(),
|
||||||
pointer: DVec2::ZERO,
|
pointer: DVec2::ZERO,
|
||||||
export_format,
|
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,
|
render_mode: graphene_std::vector::style::RenderMode::Normal,
|
||||||
for_export: true,
|
for_export: true,
|
||||||
for_eyedropper: false,
|
for_eyedropper: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Execute the node graph
|
self.queue_export(network, document.resources.registry.clone(), render_config, ExportTarget::File(export_config))
|
||||||
self.sender
|
|
||||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
|
||||||
network,
|
|
||||||
resources,
|
|
||||||
previewed,
|
|
||||||
layers: document.network_interface.layer_paths(),
|
|
||||||
observations: self.observations(&document.network_interface),
|
|
||||||
}))
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
let execution_id = self.queue_execution(render_config);
|
|
||||||
self.futures.push_back((
|
|
||||||
execution_id,
|
|
||||||
ExecutionContext {
|
|
||||||
export_config: Some(export_config),
|
|
||||||
document_id,
|
|
||||||
document_to_viewport: viewport.transform,
|
|
||||||
measure_fill: None,
|
|
||||||
},
|
|
||||||
));
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
/// Applies the graph runtime's responses to the active document, giving back the layers whose thumbnails the runtime dropped meanwhile.
|
||||||
@@ -491,8 +516,8 @@ impl NodeGraphExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut all_dropped_thumbnails = Vec::new();
|
let mut all_dropped_thumbnails = Vec::new();
|
||||||
let mut results = self.receiver.try_iter().collect::<Vec<_>>().into_iter();
|
let results = self.receiver.try_iter().collect::<Vec<_>>();
|
||||||
for response in results.by_ref() {
|
for response in results {
|
||||||
match response {
|
match response {
|
||||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
||||||
let ExecutionResponse {
|
let ExecutionResponse {
|
||||||
@@ -516,7 +541,7 @@ impl NodeGraphExecutor {
|
|||||||
|
|
||||||
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
let execution_context = if self.futures.front().is_some_and(|&(queued_execution_id, _)| queued_execution_id == execution_id) {
|
||||||
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
|
let (_, execution_context) = self.futures.pop_front().expect("the front was just checked");
|
||||||
if execution_context.export_config.is_none() && execution_context.measure_fill.is_none() {
|
if execution_context.measure_fill.is_none() {
|
||||||
self.pending = Some((execution_id, execution_context.clone()));
|
self.pending = Some((execution_id, execution_context.clone()));
|
||||||
}
|
}
|
||||||
execution_context
|
execution_context
|
||||||
@@ -571,7 +596,7 @@ impl NodeGraphExecutor {
|
|||||||
responses.add(OverlaysMessage::Draw);
|
responses.add(OverlaysMessage::Draw);
|
||||||
|
|
||||||
// A pending graph keeps the last frame, and the errors shown with it
|
// A pending graph keeps the last frame, and the errors shown with it
|
||||||
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
|
if !matches!(result, ExecutionResult::Pending) {
|
||||||
let errors = match &result {
|
let errors = match &result {
|
||||||
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
|
||||||
let in_document = |path: &&[NodeId]| {
|
let in_document = |path: &&[NodeId]| {
|
||||||
@@ -644,11 +669,8 @@ impl NodeGraphExecutor {
|
|||||||
log::error!("Node graph evaluation failed:\n{message}");
|
log::error!("Node graph evaluation failed:\n{message}");
|
||||||
}
|
}
|
||||||
|
|
||||||
if execution_context.export_config.is_some() {
|
|
||||||
responses.add(export_failure_dialog(message));
|
|
||||||
}
|
|
||||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||||
break;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -666,10 +688,8 @@ impl NodeGraphExecutor {
|
|||||||
}
|
}
|
||||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||||
|
|
||||||
match (node_graph_output, execution_context.export_config) {
|
if let Some(node_graph_output) = node_graph_output {
|
||||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses);
|
||||||
(Some(node_graph_output), None) => self.process_node_graph_output(node_graph_output, execution_context.document_to_viewport, render_status, responses),
|
|
||||||
(None, _) => {}
|
|
||||||
}
|
}
|
||||||
responses.add(DeferMessage::TriggerGraphRun {
|
responses.add(DeferMessage::TriggerGraphRun {
|
||||||
execution_id,
|
execution_id,
|
||||||
@@ -691,19 +711,19 @@ impl NodeGraphExecutor {
|
|||||||
node_graph_errors,
|
node_graph_errors,
|
||||||
node_graph_warnings,
|
node_graph_warnings,
|
||||||
result,
|
result,
|
||||||
|
resolved_types,
|
||||||
} = execution_response;
|
} = execution_response;
|
||||||
|
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
|
// The migration's temporary redirected-export compilations must not push types or a graph view to the frontend
|
||||||
if self.gradient_migration.is_some() {
|
if self.gradient_migration.is_some() {
|
||||||
if let Err((_, e)) = &result {
|
if let Err(e) = &result {
|
||||||
log::trace!("Gradient migration measurement compile: {e}");
|
log::trace!("Gradient migration measurement compile: {e}");
|
||||||
}
|
}
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
let type_delta = match result {
|
if let Err(e) = &result {
|
||||||
Err((incomplete_delta, e)) => {
|
|
||||||
// Clear the click targets while the graph is in an un-renderable state
|
// Clear the click targets while the graph is in an un-renderable state
|
||||||
|
|
||||||
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
document.network_interface.update_click_targets(HashMap::new(), HashSet::new());
|
||||||
@@ -716,24 +736,17 @@ impl NodeGraphExecutor {
|
|||||||
} else {
|
} else {
|
||||||
log::trace!("{e}");
|
log::trace!("{e}");
|
||||||
}
|
}
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::UpdateTypes {
|
|
||||||
resolved_types: incomplete_delta,
|
|
||||||
node_graph_errors,
|
|
||||||
node_graph_warnings,
|
|
||||||
});
|
|
||||||
|
|
||||||
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
Ok(result) => result,
|
|
||||||
};
|
|
||||||
|
|
||||||
responses.add(NodeGraphMessage::UpdateTypes {
|
responses.add(NodeGraphMessage::UpdateTypes {
|
||||||
resolved_types: type_delta,
|
resolved_types,
|
||||||
node_graph_errors,
|
node_graph_errors,
|
||||||
node_graph_warnings,
|
node_graph_warnings,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if result.is_err() {
|
||||||
|
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
NodeGraphUpdate::EyedropperPreview(raster) => {
|
NodeGraphUpdate::EyedropperPreview(raster) => {
|
||||||
let (data, width, height) = raster.to_flat_u8();
|
let (data, width, height) = raster.to_flat_u8();
|
||||||
@@ -756,33 +769,7 @@ impl NodeGraphExecutor {
|
|||||||
Self::receive_thumbnails(document, thumbnails, responses);
|
Self::receive_thumbnails(document, thumbnails, responses);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
NodeGraphUpdate::Export { id: export_id, result } => self.receive_export(export_id, *result, document, responses),
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// An error leaves the later responses unapplied, but the runtime still dropped and rendered their thumbnails
|
|
||||||
for response in results {
|
|
||||||
match response {
|
|
||||||
NodeGraphUpdate::ExecutionResponse(execution_response) => {
|
|
||||||
let execution_context = self.execution_context(execution_response.execution_id);
|
|
||||||
|
|
||||||
if execution_context.is_some_and(|context| context.document_id == document_id) {
|
|
||||||
document.layers_in_view.forget_thumbnails(&execution_response.dropped_thumbnails, responses);
|
|
||||||
}
|
|
||||||
if matches!(execution_response.result, ExecutionResult::Uncompiled) && execution_context.is_some_and(|context| context.export_config.is_some()) {
|
|
||||||
responses.add(export_failure_dialog(None));
|
|
||||||
}
|
|
||||||
|
|
||||||
all_dropped_thumbnails.extend(execution_response.dropped_thumbnails);
|
|
||||||
}
|
|
||||||
NodeGraphUpdate::Thumbnails {
|
|
||||||
responses: thumbnails,
|
|
||||||
document_id: thumbnails_document,
|
|
||||||
} if thumbnails_document == document_id => {
|
|
||||||
Self::receive_thumbnails(document, thumbnails, responses);
|
|
||||||
}
|
|
||||||
NodeGraphUpdate::ClipboardSvg { id, svg } => responses.add(ClipboardMessage::Rendered { id, svg }),
|
|
||||||
_ => {}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -798,15 +785,6 @@ impl NodeGraphExecutor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What an execution was submitted for, while it's still queued or pending.
|
|
||||||
fn execution_context(&self, execution_id: u64) -> Option<&ExecutionContext> {
|
|
||||||
self.futures
|
|
||||||
.iter()
|
|
||||||
.chain(&self.pending)
|
|
||||||
.find(|(queued_execution_id, _)| *queued_execution_id == execution_id)
|
|
||||||
.map(|(_, execution_context)| execution_context)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
|
/// Kick off the one-time pre-pass converting legacy bounding-box gradients to absolute space, or no-op if already running.
|
||||||
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
|
/// Returns false when the render should proceed normally instead: the pass already ran this session, so any entries still
|
||||||
@@ -876,6 +854,10 @@ impl NodeGraphExecutor {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let layers = document.network_interface.layer_paths();
|
||||||
|
prepare_network(&mut network, &[], &layers);
|
||||||
|
let thumbnails = thumbnail_sources(&network, &layers);
|
||||||
|
|
||||||
let resources = document.resources.registry.clone();
|
let resources = document.resources.registry.clone();
|
||||||
let fill_measurement = Observation {
|
let fill_measurement = Observation {
|
||||||
node_path: full_path,
|
node_path: full_path,
|
||||||
@@ -887,8 +869,7 @@ impl NodeGraphExecutor {
|
|||||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
network,
|
network,
|
||||||
resources,
|
resources,
|
||||||
previewed: Vec::new(),
|
thumbnails,
|
||||||
layers: document.network_interface.layer_paths(),
|
|
||||||
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
||||||
}))
|
}))
|
||||||
.is_err()
|
.is_err()
|
||||||
@@ -920,7 +901,6 @@ impl NodeGraphExecutor {
|
|||||||
self.futures.push_back((
|
self.futures.push_back((
|
||||||
execution_id,
|
execution_id,
|
||||||
ExecutionContext {
|
ExecutionContext {
|
||||||
export_config: None,
|
|
||||||
document_id,
|
document_id,
|
||||||
document_to_viewport: viewport.transform,
|
document_to_viewport: viewport.transform,
|
||||||
measure_fill: Some((network_path, fill_node_id, gradient)),
|
measure_fill: Some((network_path, fill_node_id, gradient)),
|
||||||
@@ -1080,6 +1060,51 @@ impl NodeGraphExecutor {
|
|||||||
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
responses.add(FrontendMessage::UpdateRenderStatus { status: render_status });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn receive_export(&mut self, export_id: u64, result: ExecutionResult, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||||
|
let Some(target) = self.exports.remove(&export_id) else { return };
|
||||||
|
|
||||||
|
let failure = match (result, &target) {
|
||||||
|
(ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _), _) => {
|
||||||
|
return match target {
|
||||||
|
ExportTarget::File(export_config) => self.process_export(value, export_config, document, responses),
|
||||||
|
ExportTarget::Clipboard(id) => {
|
||||||
|
let svg = match value {
|
||||||
|
TaggedValue::RenderOutput(RenderOutput {
|
||||||
|
data: RenderOutputType::Svg { svg, .. },
|
||||||
|
..
|
||||||
|
}) => Some(svg),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
responses.add(ClipboardMessage::Rendered { id, svg });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
(ExecutionResult::Error(errors), _) => Some(errors.to_string()),
|
||||||
|
(ExecutionResult::Panic(payload), _) => {
|
||||||
|
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
|
||||||
|
Some(format!("Panicked: {}", message.unwrap_or("no message")))
|
||||||
|
}
|
||||||
|
(ExecutionResult::Pending | ExecutionResult::Partial(_) | ExecutionResult::Uncompiled, _) => None,
|
||||||
|
};
|
||||||
|
if let Some(message) = &failure {
|
||||||
|
log::error!("Node graph evaluation failed:\n{message}");
|
||||||
|
}
|
||||||
|
|
||||||
|
match target {
|
||||||
|
ExportTarget::File(_) => responses.add(DialogMessage::DisplayDialogError {
|
||||||
|
title: "Unable to export document".to_string(),
|
||||||
|
description: failure.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
||||||
|
}),
|
||||||
|
ExportTarget::Clipboard(id) => {
|
||||||
|
responses.add(ClipboardMessage::Rendered { id, svg: None });
|
||||||
|
if let Some(description) = failure {
|
||||||
|
let title = "Unable to copy as SVG".to_string();
|
||||||
|
responses.add(DialogMessage::DisplayDialogError { title, description });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
fn process_export(&self, node_graph_output: TaggedValue, export_config: ExportConfig, document: &DocumentMessageHandler, responses: &mut VecDeque<Message>) {
|
||||||
let ExportConfig {
|
let ExportConfig {
|
||||||
file_type,
|
file_type,
|
||||||
@@ -1179,6 +1204,61 @@ pub(crate) fn redirect_export_chain(network: &mut NodeNetwork, full_path: &[Node
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn prepare_network(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)], layers: &[Vec<NodeId>]) {
|
||||||
|
apply_previews(network, previewed);
|
||||||
|
write_layer_paths(network, layers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Replaces each network's primary export with its previewed node.
|
||||||
|
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
|
||||||
|
for (network_path, previewed) in previewed {
|
||||||
|
let Some(nested) = network.nested_network_mut(network_path) else { continue };
|
||||||
|
let Some(export) = nested.exports.first_mut() else { continue };
|
||||||
|
*export = NodeInput::node(previewed.node_id, previewed.output_index);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node giving the content each layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||||
|
fn thumbnail_sources(network: &NodeNetwork, layers: &[Vec<NodeId>]) -> Vec<(NodeId, Vec<NodeId>)> {
|
||||||
|
// O(layers * depth)
|
||||||
|
let source = |layer: &Vec<NodeId>| Some((*layer.last()?, layer_content(layer, network)?.source(network)?));
|
||||||
|
|
||||||
|
layers.iter().filter_map(source).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn copied_layers(interface: &NodeNetworkInterface, layers: &[LayerNodeIdentifier]) -> Option<(NodeNetwork, [DVec2; 2])> {
|
||||||
|
let metadata = interface.document_metadata();
|
||||||
|
let is_artboard = |layer: &LayerNodeIdentifier| interface.is_artboard(&layer.to_node(), &[]);
|
||||||
|
let stack = match layers.iter().filter(|layer| is_artboard(layer)).count() {
|
||||||
|
0 if layers.iter().all(|layer| interface.is_merge(&layer.to_node(), &[])) => list!(Graphic),
|
||||||
|
artboards if artboards == layers.len() => list!(Artboard),
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut network = interface.document_network().clone();
|
||||||
|
prepare_network(&mut network, &interface.previewed_nodes(), &interface.layer_paths());
|
||||||
|
let mut below = NodeInput::type_default(stack, true);
|
||||||
|
let mut bounds = None;
|
||||||
|
for &layer in layers {
|
||||||
|
let mut node = network.nodes.get(&layer.to_node())?.clone();
|
||||||
|
*node.inputs.first_mut()? = below;
|
||||||
|
let copy = NodeId::new();
|
||||||
|
network.nodes.insert(copy, node);
|
||||||
|
below = NodeInput::node(copy, 0);
|
||||||
|
|
||||||
|
let from_document = match metadata.upstream_footprints.contains_key(&layer.to_node()) {
|
||||||
|
true => metadata.downstream_transform_to_document(layer).inverse(),
|
||||||
|
false => DAffine2::IDENTITY,
|
||||||
|
};
|
||||||
|
let in_document = metadata.bounding_box_document_with_stroke_and_effects(layer);
|
||||||
|
let own = in_document.map(|bounds| (from_document * Quad::from_box(bounds)).bounding_box());
|
||||||
|
bounds = [bounds, own].into_iter().flatten().reduce(Quad::combine_bounds);
|
||||||
|
}
|
||||||
|
network.exports = vec![below];
|
||||||
|
|
||||||
|
Some((network, bounds?))
|
||||||
|
}
|
||||||
|
|
||||||
// TODO: Eventually remove this document upgrade code
|
// TODO: Eventually remove this document upgrade code
|
||||||
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
|
/// Turn a measured fill node's evaluated geometry into a `[0,1]² -> bounding box` affine plus the geometry's item transform.
|
||||||
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2, DAffine2)> {
|
||||||
@@ -1200,14 +1280,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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 {
|
|
||||||
title: "Unable to export document".to_string(),
|
|
||||||
description: evaluation_error.unwrap_or_else(|| "The node graph has errors that prevent it from rendering.".to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
fn path_content_observations(network_interface: &NodeNetworkInterface) -> impl Iterator<Item = (ObservationKey, Observation)> {
|
||||||
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
let path_nodes = network_interface.node_paths_with_reference(&DefinitionIdentifier::ProtoNode(path::IDENTIFIER));
|
||||||
|
|
||||||
@@ -1273,14 +1345,17 @@ mod test {
|
|||||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||||
let instrumented = Instrumented::new(&network);
|
let instrumented = Instrumented::new(&network);
|
||||||
|
|
||||||
|
let layers = document.network_interface.layer_paths();
|
||||||
|
prepare_network(&mut network, &[], &layers);
|
||||||
|
let thumbnails = thumbnail_sources(&network, &layers);
|
||||||
|
|
||||||
let resources = document.resources.registry.clone();
|
let resources = document.resources.registry.clone();
|
||||||
|
|
||||||
self.sender
|
self.sender
|
||||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
network,
|
network,
|
||||||
resources,
|
resources,
|
||||||
previewed: Vec::new(),
|
thumbnails,
|
||||||
layers: document.network_interface.layer_paths(),
|
|
||||||
observations: self.observations(&document.network_interface),
|
observations: self.observations(&document.network_interface),
|
||||||
}))
|
}))
|
||||||
.map_err(|e| e.to_string())?;
|
.map_err(|e| e.to_string())?;
|
||||||
|
|||||||
@@ -18,8 +18,8 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
|
|||||||
editor.dispatch(Message::Wake);
|
editor.dispatch(Message::Wake);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
|
/// The proto node IDs compiled for the document node paths that pass `keep`. The runtime keeps the output of the network
|
||||||
/// for one more update, so a first update clears those of the graph before it.
|
/// an update replaces for one more update, so a first update clears the nodes of the graph before it.
|
||||||
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
|
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
|
||||||
compile_and_run(editor).await;
|
compile_and_run(editor).await;
|
||||||
compile_and_run(editor).await;
|
compile_and_run(editor).await;
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||||
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
|
use crate::messages::portfolio::document::overlays::utility_types::{OverlayContext, RenderedLayers};
|
||||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
|
||||||
use crate::task::{Spawn, Spawner, Task};
|
use crate::task::{Spawn, Spawner, Task};
|
||||||
use graph_craft::application_io::resource::ResourceRegistry;
|
use graph_craft::application_io::resource::ResourceRegistry;
|
||||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||||
@@ -18,8 +17,7 @@ use graphene_std::raster_types::Raster;
|
|||||||
use graphene_std::runtime::AsyncRuntime;
|
use graphene_std::runtime::AsyncRuntime;
|
||||||
use graphene_std::vector::style::RenderMode;
|
use graphene_std::vector::style::RenderMode;
|
||||||
use graphene_std::{Context, NodeError, Poll};
|
use graphene_std::{Context, NodeError, Poll};
|
||||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||||
use interpreted_executor::layer_paths::write_layer_paths;
|
|
||||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||||
use observer::Observer;
|
use observer::Observer;
|
||||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||||
@@ -43,25 +41,34 @@ pub struct NodeRuntime {
|
|||||||
pub(super) executor: DynamicExecutor,
|
pub(super) executor: DynamicExecutor,
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
executor: DynamicExecutor,
|
executor: DynamicExecutor,
|
||||||
output: OutputHandle,
|
|
||||||
receiver: Receiver<GraphRuntimeRequest>,
|
receiver: Receiver<GraphRuntimeRequest>,
|
||||||
sender: Sender<NodeGraphUpdate>,
|
sender: Sender<NodeGraphUpdate>,
|
||||||
|
|
||||||
editor_wake: Wake,
|
editor_wake: Wake,
|
||||||
dirty: Arc<AtomicBool>,
|
dirty: Arc<AtomicBool>,
|
||||||
|
|
||||||
|
output: Option<OutputHandle>,
|
||||||
|
previous: Option<OutputHandle>,
|
||||||
|
|
||||||
pending: Option<ExecutionRequest>,
|
pending: Option<ExecutionRequest>,
|
||||||
pending_export: Option<ExecutionRequest>,
|
|
||||||
pending_eyedropper: Option<ExecutionRequest>,
|
pending_eyedropper: Option<ExecutionRequest>,
|
||||||
pending_thumbnails: Option<DocumentId>,
|
pending_thumbnails: Option<DocumentId>,
|
||||||
|
|
||||||
|
viewport_artwork: Option<ViewportArtwork>,
|
||||||
|
|
||||||
|
exports: Vec<(u64, RenderConfig, OutputHandle)>,
|
||||||
|
|
||||||
/// The network the executor last compiled successfully, with previews applied.
|
/// The network the executor last compiled successfully, with previews applied.
|
||||||
old_graph: Option<NodeNetwork>,
|
old_graph: Option<NodeNetwork>,
|
||||||
/// Whether the latest network failed to compile, leaving the executor with an older one that mustn't be shown in its place.
|
|
||||||
compile_failed: bool,
|
|
||||||
async_runtime: Option<AsyncRuntime>,
|
|
||||||
|
|
||||||
|
async_runtime: Option<AsyncRuntime>,
|
||||||
editor_api: Arc<PlatformEditorApi>,
|
editor_api: Arc<PlatformEditorApi>,
|
||||||
resources: ResourceRegistry,
|
resources: ResourceRegistry,
|
||||||
|
|
||||||
node_graph_errors: GraphErrors,
|
node_graph_errors: GraphErrors,
|
||||||
node_graph_warnings: GraphErrors,
|
node_graph_warnings: GraphErrors,
|
||||||
|
|
||||||
thumbnails: Thumbnails,
|
thumbnails: Thumbnails,
|
||||||
observer: Observer<ObservationKey>,
|
observer: Observer<ObservationKey>,
|
||||||
/// Whether an observation changed since its results were last sent.
|
/// Whether an observation changed since its results were last sent.
|
||||||
@@ -69,13 +76,9 @@ pub struct NodeRuntime {
|
|||||||
|
|
||||||
preprocessor: preprocessor::Preprocessor,
|
preprocessor: preprocessor::Preprocessor,
|
||||||
|
|
||||||
/// Cached surface for Wasm viewport rendering (reused across frames)
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
|
||||||
wasm_canvas_cache: CanvasSurfaceHandle,
|
|
||||||
/// The viewport's latest artwork.
|
|
||||||
viewport_artwork: Option<ViewportArtwork>,
|
|
||||||
/// The layers from the render of the viewport's latest artwork.
|
/// The layers from the render of the viewport's latest artwork.
|
||||||
rendered_layers: RenderedLayers,
|
rendered_layers: RenderedLayers,
|
||||||
|
|
||||||
/// The latest overlays, rendered again over each new artwork.
|
/// The latest overlays, rendered again over each new artwork.
|
||||||
overlays: Option<OverlayContext>,
|
overlays: Option<OverlayContext>,
|
||||||
/// Whether the overlays or the artwork changed since the overlays were last rendered.
|
/// Whether the overlays or the artwork changed since the overlays were last rendered.
|
||||||
@@ -83,6 +86,10 @@ pub struct NodeRuntime {
|
|||||||
overlays_canvas: VelloCanvas,
|
overlays_canvas: VelloCanvas,
|
||||||
/// The latest rendered overlays.
|
/// The latest rendered overlays.
|
||||||
overlays_texture: Option<Texture>,
|
overlays_texture: Option<Texture>,
|
||||||
|
|
||||||
|
/// Cached surface for Wasm viewport rendering (reused across frames)
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
wasm_canvas_cache: CanvasSurfaceHandle,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the viewport shows beneath its overlays.
|
/// What the viewport shows beneath its overlays.
|
||||||
@@ -98,43 +105,32 @@ enum ViewportArtwork {
|
|||||||
pub enum GraphRuntimeRequest {
|
pub enum GraphRuntimeRequest {
|
||||||
GraphUpdate(GraphUpdate),
|
GraphUpdate(GraphUpdate),
|
||||||
ExecutionRequest(ExecutionRequest),
|
ExecutionRequest(ExecutionRequest),
|
||||||
|
Export {
|
||||||
|
id: u64,
|
||||||
|
render_config: RenderConfig,
|
||||||
|
network: NodeNetwork,
|
||||||
|
resources: ResourceRegistry,
|
||||||
|
},
|
||||||
ThumbnailsInView {
|
ThumbnailsInView {
|
||||||
layers: HashSet<NodeId>,
|
layers: HashSet<NodeId>,
|
||||||
document_id: DocumentId,
|
document_id: DocumentId,
|
||||||
},
|
},
|
||||||
/// Starts, changes, or with `None` stops one observation without a graph update.
|
RenderOverlays(OverlayContext),
|
||||||
Observe {
|
Observe {
|
||||||
key: ObservationKey,
|
key: ObservationKey,
|
||||||
observation: Option<Observation>,
|
observation: Option<Observation>,
|
||||||
},
|
},
|
||||||
ClipboardSvg {
|
|
||||||
id: u64,
|
|
||||||
layers: Vec<NodeId>,
|
|
||||||
},
|
|
||||||
RenderOverlays(OverlayContext),
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct GraphUpdate {
|
pub struct GraphUpdate {
|
||||||
pub(super) network: NodeNetwork,
|
pub(super) network: NodeNetwork,
|
||||||
pub(super) resources: ResourceRegistry,
|
pub(super) resources: ResourceRegistry,
|
||||||
/// The node each network renders in place of its export, paired with that network's path.
|
pub(super) thumbnails: Vec<(NodeId, Vec<NodeId>)>,
|
||||||
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
|
|
||||||
/// Full path from the root network to every layer, which are the nodes with thumbnails.
|
|
||||||
pub(super) layers: Vec<Vec<NodeId>>,
|
|
||||||
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
|
/// The connectors whose values are sent back after each evaluation, replacing those observed before.
|
||||||
pub(super) observations: HashMap<ObservationKey, Observation>,
|
pub(super) observations: HashMap<ObservationKey, Observation>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Replaces each network's primary export with its previewed node.
|
|
||||||
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
|
|
||||||
for (network_path, previewed) in previewed {
|
|
||||||
let Some(nested) = network.nested_network_mut(network_path) else { continue };
|
|
||||||
let Some(export) = nested.exports.first_mut() else { continue };
|
|
||||||
*export = NodeInput::node(previewed.node_id, previewed.output_index);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||||
pub struct ExportConfig {
|
pub struct ExportConfig {
|
||||||
pub name: String,
|
pub name: String,
|
||||||
@@ -149,20 +145,27 @@ impl NodeRuntime {
|
|||||||
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
|
pub fn new(receiver: Receiver<GraphRuntimeRequest>, sender: Sender<NodeGraphUpdate>, editor_wake: Wake) -> Self {
|
||||||
Self {
|
Self {
|
||||||
executor: DynamicExecutor::default(),
|
executor: DynamicExecutor::default(),
|
||||||
output: OutputHandle::default(),
|
|
||||||
receiver,
|
receiver,
|
||||||
sender,
|
sender,
|
||||||
|
|
||||||
editor_wake,
|
editor_wake,
|
||||||
dirty: Default::default(),
|
dirty: Default::default(),
|
||||||
|
|
||||||
|
output: None,
|
||||||
|
previous: None,
|
||||||
|
|
||||||
pending: None,
|
pending: None,
|
||||||
pending_export: None,
|
|
||||||
pending_eyedropper: None,
|
pending_eyedropper: None,
|
||||||
pending_thumbnails: None,
|
pending_thumbnails: None,
|
||||||
old_graph: None,
|
|
||||||
compile_failed: false,
|
|
||||||
resources: ResourceRegistry::default(),
|
|
||||||
async_runtime: None,
|
|
||||||
|
|
||||||
|
viewport_artwork: None,
|
||||||
|
|
||||||
|
exports: Vec::new(),
|
||||||
|
|
||||||
|
old_graph: None,
|
||||||
|
|
||||||
|
async_runtime: None,
|
||||||
editor_api: PlatformEditorApi {
|
editor_api: PlatformEditorApi {
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
application_io: None,
|
application_io: None,
|
||||||
@@ -171,119 +174,117 @@ impl NodeRuntime {
|
|||||||
application_io: Some(PlatformApplicationIo::default().into()),
|
application_io: Some(PlatformApplicationIo::default().into()),
|
||||||
}
|
}
|
||||||
.into(),
|
.into(),
|
||||||
|
resources: ResourceRegistry::default(),
|
||||||
|
|
||||||
node_graph_errors: Vec::new(),
|
node_graph_errors: Vec::new(),
|
||||||
node_graph_warnings: Vec::new(),
|
node_graph_warnings: Vec::new(),
|
||||||
|
|
||||||
thumbnails: Thumbnails::new(),
|
thumbnails: Thumbnails::new(),
|
||||||
observer: Observer::default(),
|
observer: Observer::default(),
|
||||||
observations_changed: false,
|
observations_changed: false,
|
||||||
|
|
||||||
preprocessor: preprocessor::Preprocessor::new(),
|
preprocessor: preprocessor::Preprocessor::new(),
|
||||||
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
|
||||||
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
|
||||||
viewport_artwork: None,
|
|
||||||
rendered_layers: RenderedLayers::default(),
|
rendered_layers: RenderedLayers::default(),
|
||||||
|
|
||||||
overlays: None,
|
overlays: None,
|
||||||
overlays_stale: false,
|
overlays_stale: false,
|
||||||
overlays_canvas: VelloCanvas::default(),
|
overlays_canvas: VelloCanvas::default(),
|
||||||
overlays_texture: None,
|
overlays_texture: None,
|
||||||
|
|
||||||
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
|
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(&mut self) {
|
pub fn update(&mut self) {
|
||||||
if self.pending_export.is_some() {
|
while let Ok(request) = self.receiver.try_recv() {
|
||||||
return;
|
match request {
|
||||||
|
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||||
|
network,
|
||||||
|
resources,
|
||||||
|
thumbnails,
|
||||||
|
observations,
|
||||||
|
}) => {
|
||||||
|
self.observer.replace_all(observations);
|
||||||
|
self.resources = resources;
|
||||||
|
|
||||||
|
self.node_graph_errors.clear();
|
||||||
|
self.node_graph_warnings.clear();
|
||||||
|
let result = self.update_network(network.clone());
|
||||||
|
if result.is_ok() {
|
||||||
|
self.thumbnails.update_sources(&thumbnails, &self.executor);
|
||||||
|
self.old_graph = Some(network);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut graph = None;
|
let node_graph_errors = self.node_graph_errors.clone();
|
||||||
for request in self.receiver.try_iter() {
|
let node_graph_warnings = self.node_graph_warnings.clone();
|
||||||
match request {
|
let resolved_types = self.executor.take_type_deltas().unwrap_or_default();
|
||||||
GraphRuntimeRequest::GraphUpdate(update) => graph = Some(update),
|
|
||||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
self.sender
|
||||||
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_export => {
|
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
|
||||||
self.pending_export = Some(request);
|
result,
|
||||||
self.dirty.store(true, Ordering::Release);
|
resolved_types,
|
||||||
break;
|
node_graph_errors,
|
||||||
|
node_graph_warnings,
|
||||||
|
}))
|
||||||
|
.expect("Failed to send response");
|
||||||
}
|
}
|
||||||
|
GraphRuntimeRequest::ExecutionRequest(request) if request.render_config.for_eyedropper => self.pending_eyedropper = Some(request),
|
||||||
GraphRuntimeRequest::ExecutionRequest(request) => {
|
GraphRuntimeRequest::ExecutionRequest(request) => {
|
||||||
self.pending = Some(request);
|
self.pending = Some(request);
|
||||||
self.dirty.store(true, Ordering::Release);
|
self.dirty.store(true, Ordering::Release);
|
||||||
}
|
}
|
||||||
|
GraphRuntimeRequest::Export {
|
||||||
|
id,
|
||||||
|
render_config,
|
||||||
|
network,
|
||||||
|
resources,
|
||||||
|
} => {
|
||||||
|
let mut scoped_network = wrap_network_with_render_node_in_scope(network, self.editor_api.clone(), self.async_runtime().handle());
|
||||||
|
let preprocessed = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| resources.hash(&resource_id)).ok();
|
||||||
|
let compiled = preprocessed.and_then(|_| Compiler {}.compile_single(scoped_network).ok());
|
||||||
|
let inserted = compiled.and_then(|compiled| self.executor.insert(compiled.network).ok());
|
||||||
|
self.async_runtime().update_sources(self.executor.sources());
|
||||||
|
match inserted {
|
||||||
|
Some(output) => {
|
||||||
|
self.exports.push((id, render_config, output));
|
||||||
|
self.dirty.store(true, Ordering::Release);
|
||||||
|
}
|
||||||
|
None => self.send_export(id, ExecutionResult::Uncompiled),
|
||||||
|
}
|
||||||
|
}
|
||||||
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => {
|
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => {
|
||||||
self.thumbnails.set_in_view(layers);
|
self.thumbnails.set_in_view(layers);
|
||||||
self.pending_thumbnails = Some(document_id);
|
self.pending_thumbnails = Some(document_id);
|
||||||
}
|
}
|
||||||
// A graph update applied after this loop would otherwise replace this with what it observed before
|
GraphRuntimeRequest::Observe { key, observation } => {
|
||||||
GraphRuntimeRequest::Observe { key, observation } => match (&mut graph, observation) {
|
|
||||||
(Some(update), Some(observation)) => _ = update.observations.insert(key, observation),
|
|
||||||
(Some(update), None) => _ = update.observations.remove(&key),
|
|
||||||
(None, observation) => {
|
|
||||||
self.observer.set(key, observation);
|
self.observer.set(key, observation);
|
||||||
self.observations_changed = true;
|
self.observations_changed = true;
|
||||||
}
|
}
|
||||||
},
|
|
||||||
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) => {
|
GraphRuntimeRequest::RenderOverlays(context) => {
|
||||||
self.overlays = Some(context);
|
self.overlays = Some(context);
|
||||||
self.overlays_stale = true;
|
self.overlays_stale = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let Some(GraphUpdate {
|
|
||||||
mut network,
|
|
||||||
resources,
|
|
||||||
previewed,
|
|
||||||
layers,
|
|
||||||
observations,
|
|
||||||
}) = graph
|
|
||||||
else {
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
|
|
||||||
apply_previews(&mut network, &previewed);
|
|
||||||
write_layer_paths(&mut network, &layers);
|
|
||||||
self.observer.replace_all(observations);
|
|
||||||
self.resources = 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);
|
|
||||||
self.old_graph = Some(network);
|
|
||||||
}
|
|
||||||
let node_graph_errors = self.node_graph_errors.clone();
|
|
||||||
let node_graph_warnings = self.node_graph_warnings.clone();
|
|
||||||
|
|
||||||
self.sender
|
|
||||||
.send(NodeGraphUpdate::CompilationResponse(CompilationResponse {
|
|
||||||
result,
|
|
||||||
node_graph_errors,
|
|
||||||
node_graph_warnings,
|
|
||||||
}))
|
|
||||||
.expect("Failed to send response");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn run(&mut self) -> Option<Texture> {
|
pub async fn run(&mut self) -> Option<Texture> {
|
||||||
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
let dirty = self.dirty.swap(false, Ordering::Acquire);
|
||||||
let mut texture = None;
|
let mut texture = None;
|
||||||
|
|
||||||
if let Some(export) = self.pending_export {
|
|
||||||
if dirty {
|
if dirty {
|
||||||
self.run_export(export).await;
|
for (id, render_config, output) in std::mem::take(&mut self.exports) {
|
||||||
|
self.run_export(id, render_config, output).await;
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
|
||||||
let viewport = if dirty { self.pending } else { None };
|
let viewport = if dirty { self.pending } else { None };
|
||||||
|
|
||||||
if let Some(document_id) = self.pending_thumbnails.take()
|
if let Some(document_id) = self.pending_thumbnails.take()
|
||||||
&& viewport.is_none()
|
&& viewport.is_none()
|
||||||
&& !self.compile_failed
|
&& self.output.is_some()
|
||||||
{
|
{
|
||||||
let mut responses = VecDeque::new();
|
let mut responses = VecDeque::new();
|
||||||
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
|
self.thumbnails.render_stale(&self.executor, &self.editor_api, &mut responses).await;
|
||||||
@@ -309,7 +310,6 @@ impl NodeRuntime {
|
|||||||
if self.overlays_stale {
|
if self.overlays_stale {
|
||||||
texture = self.composite_viewport_frame();
|
texture = self.composite_viewport_frame();
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
(self.editor_wake)();
|
(self.editor_wake)();
|
||||||
texture
|
texture
|
||||||
@@ -318,7 +318,11 @@ impl NodeRuntime {
|
|||||||
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||||
self.thumbnails.set_scale(request.render_config.scale);
|
self.thumbnails.set_scale(request.render_config.scale);
|
||||||
|
|
||||||
let Some(mut result) = self.evaluate(request) else { return };
|
let result = match self.output.clone() {
|
||||||
|
Some(output) => self.evaluate(&output, request),
|
||||||
|
None => Some(ExecutionResult::Uncompiled),
|
||||||
|
};
|
||||||
|
let Some(mut result) = result else { return };
|
||||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||||
|
|
||||||
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||||
@@ -378,24 +382,20 @@ impl NodeRuntime {
|
|||||||
Some(frame)
|
Some(frame)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_export(&mut self, request: ExecutionRequest) {
|
async fn run_export(&mut self, id: u64, render_config: RenderConfig, output: OutputHandle) {
|
||||||
let result = self.evaluate(request);
|
let mut result = self.execute(&output, render_config);
|
||||||
if matches!(result, Some(ExecutionResult::Pending)) {
|
if matches!(result, ExecutionResult::Pending | ExecutionResult::Partial(_)) {
|
||||||
|
self.exports.push((id, render_config, output));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.pending_export = None;
|
|
||||||
let Some(mut result) = result else { return };
|
|
||||||
self.dirty.store(true, Ordering::Release);
|
|
||||||
|
|
||||||
if let Some(RenderOutput { data, .. }) = result.render_output()
|
if let Some(RenderOutput { data, .. }) = result.render_output()
|
||||||
&& let RenderOutputType::Texture(texture) = data
|
&& let RenderOutputType::Texture(texture) = data
|
||||||
{
|
{
|
||||||
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
let (buffer, width, height) = self.read_back(texture.clone()).await.to_flat_u8();
|
||||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||||
}
|
}
|
||||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
self.send_export(id, result);
|
||||||
self.respond(request, result, observations).await;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||||
@@ -405,7 +405,8 @@ impl NodeRuntime {
|
|||||||
request.render_config.pointer = viewport.render_config.pointer;
|
request.render_config.pointer = viewport.render_config.pointer;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(mut result) = self.evaluate(request)
|
if let Some(output) = self.output.clone()
|
||||||
|
&& let Some(mut result) = self.evaluate(&output, request)
|
||||||
&& let Some(RenderOutput {
|
&& let Some(RenderOutput {
|
||||||
data: RenderOutputType::Texture(texture),
|
data: RenderOutputType::Texture(texture),
|
||||||
..
|
..
|
||||||
@@ -416,11 +417,7 @@ impl NodeRuntime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn evaluate(&mut self, request: ExecutionRequest) -> Option<ExecutionResult> {
|
fn evaluate(&mut self, output: &OutputHandle, request: ExecutionRequest) -> Option<ExecutionResult> {
|
||||||
if self.compile_failed {
|
|
||||||
return Some(ExecutionResult::Uncompiled);
|
|
||||||
}
|
|
||||||
|
|
||||||
let ExecutionRequest { execution_id, mut render_config } = request;
|
let ExecutionRequest { execution_id, mut render_config } = request;
|
||||||
|
|
||||||
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active
|
// Render via the SVG pipeline even though raster was requested if SVG Preview render mode is active
|
||||||
@@ -428,22 +425,35 @@ impl NodeRuntime {
|
|||||||
render_config.export_format = ExportFormat::Svg;
|
render_config.export_format = ExportFormat::Svg;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
match self.execute(output, render_config) {
|
||||||
|
ExecutionResult::Panic(payload) => {
|
||||||
|
self.send_result(execution_id, ExecutionResult::Panic(payload));
|
||||||
|
None
|
||||||
|
}
|
||||||
|
result => Some(result),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn execute(&mut self, output: &OutputHandle, render_config: RenderConfig) -> ExecutionResult {
|
||||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(output, context))) {
|
||||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
|
||||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||||
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
Ok(Ok(Poll::Final(value))) => ExecutionResult::Value(value),
|
||||||
Ok(Ok(Poll::Fallback(boxed))) => {
|
Ok(Ok(Poll::Fallback(boxed))) => {
|
||||||
let (value, error) = *boxed;
|
let (value, error) = *boxed;
|
||||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
ExecutionResult::Fallback(value, self.resolve_errors(output, &error))
|
||||||
}
|
}
|
||||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(output, &error)),
|
||||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||||
Err(payload) => {
|
Err(payload) => ExecutionResult::Panic(payload),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_result(&self, execution_id: u64, result: ExecutionResult) {
|
||||||
let response = ExecutionResponse {
|
let response = ExecutionResponse {
|
||||||
execution_id,
|
execution_id,
|
||||||
result: ExecutionResult::Panic(payload),
|
result,
|
||||||
responses: VecDeque::new(),
|
responses: VecDeque::new(),
|
||||||
dropped_thumbnails: Vec::new(),
|
dropped_thumbnails: Vec::new(),
|
||||||
observations: HashMap::new(),
|
observations: HashMap::new(),
|
||||||
@@ -451,17 +461,17 @@ impl NodeRuntime {
|
|||||||
viewport_canvas_info: None,
|
viewport_canvas_info: None,
|
||||||
};
|
};
|
||||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||||
return None;
|
|
||||||
}
|
}
|
||||||
};
|
|
||||||
Some(result)
|
fn send_export(&self, id: u64, result: ExecutionResult) {
|
||||||
|
self.sender.send(NodeGraphUpdate::Export { id, result: Box::new(result) }).expect("Failed to send response");
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||||
let mut responses = VecDeque::new();
|
let mut responses = VecDeque::new();
|
||||||
|
|
||||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
let dropped_thumbnails = if self.output.is_none() { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||||
|
|
||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
let mut result = result;
|
let mut result = result;
|
||||||
@@ -506,11 +516,15 @@ impl NodeRuntime {
|
|||||||
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
Raster::new_gpu(texture).convert(Footprint::BOUNDLESS, executor.clone()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
fn update_network(&mut self, graph: NodeNetwork) -> Result<(), String> {
|
||||||
|
if let Some(output) = self.output.take() {
|
||||||
|
self.previous = Some(output);
|
||||||
|
}
|
||||||
|
|
||||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||||
|
|
||||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
return Err(e.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
// We assume only one output
|
// We assume only one output
|
||||||
@@ -522,26 +536,25 @@ impl NodeRuntime {
|
|||||||
Err(CompileError::Graph(errors)) => {
|
Err(CompileError::Graph(errors)) => {
|
||||||
let message = format!("{errors:?}");
|
let message = format!("{errors:?}");
|
||||||
self.node_graph_errors = errors;
|
self.node_graph_errors = errors;
|
||||||
return Err((ResolvedDocumentNodeTypesDelta::default(), message));
|
return Err(message);
|
||||||
}
|
}
|
||||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
Err(CompileError::Message(message)) => return Err(message),
|
||||||
};
|
};
|
||||||
self.node_graph_warnings = warnings;
|
self.node_graph_warnings = warnings;
|
||||||
|
|
||||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||||
let updated = self.executor.update(proto_network).map(|(output, types)| {
|
let updated = self.executor.insert(proto_network).map(|output| {
|
||||||
self.output = output;
|
self.output = Some(output);
|
||||||
types
|
|
||||||
});
|
});
|
||||||
let result = updated.map_err(|(types, e)| {
|
let result = updated.map_err(|e| {
|
||||||
self.node_graph_errors.clone_from(&e);
|
self.node_graph_errors.clone_from(&e);
|
||||||
(types, format!("{e:?}"))
|
format!("{e:?}")
|
||||||
});
|
});
|
||||||
self.async_runtime().update_sources(self.executor.sources());
|
self.async_runtime().update_sources(self.executor.sources());
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
fn resolve_errors(&self, error: &NodeError) -> EvaluationErrors {
|
fn resolve_errors(&self, output: &OutputHandle, error: &NodeError) -> EvaluationErrors {
|
||||||
let source_map = self.executor.tree().source_map();
|
let source_map = self.executor.tree().source_map();
|
||||||
let paths = |node: NodeId| -> NodePaths {
|
let paths = |node: NodeId| -> NodePaths {
|
||||||
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
let mut paths: Vec<_> = source_map.iter().filter(|(_, (id, _))| *id == node).map(|(path, _)| path.clone()).collect();
|
||||||
@@ -549,7 +562,7 @@ impl NodeRuntime {
|
|||||||
paths.into()
|
paths.into()
|
||||||
};
|
};
|
||||||
let mut errors = Vec::new();
|
let mut errors = Vec::new();
|
||||||
let output = self.output.node();
|
let output = output.node();
|
||||||
let mut pending = vec![(vec![paths(output)], output, error)];
|
let mut pending = vec![(vec![paths(output)], output, error)];
|
||||||
while let Some((mut trace, node, error)) = pending.pop() {
|
while let Some((mut trace, node, error)) = pending.pop() {
|
||||||
let passed = self.executor.trace_error(node, error);
|
let passed = self.executor.trace_error(node, error);
|
||||||
@@ -673,7 +686,7 @@ mod tests {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Sends a network update and a request to export it, as the editor does for an export.
|
/// Sends a request to export the document, as the editor does for an export.
|
||||||
fn send_export(editor: &mut EditorTestUtils, file_type: FileType) {
|
fn send_export(editor: &mut EditorTestUtils, file_type: FileType) {
|
||||||
let portfolio = editor.portfolio_message_handler_mut();
|
let portfolio = editor.portfolio_message_handler_mut();
|
||||||
let document_id = portfolio.active_document_id.unwrap();
|
let document_id = portfolio.active_document_id.unwrap();
|
||||||
@@ -686,7 +699,7 @@ mod tests {
|
|||||||
bounds: ExportBounds::AllArtwork,
|
bounds: ExportBounds::AllArtwork,
|
||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
executor.submit_document_export(document, document_id, export_config).unwrap();
|
executor.submit_document_export(document, export_config).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the runtime evaluated the graph since this was last called.
|
/// Whether the runtime evaluated the graph since this was last called.
|
||||||
@@ -744,11 +757,60 @@ mod tests {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn send_request(editor: &mut EditorTestUtils) {
|
||||||
|
let portfolio = editor.portfolio_message_handler_mut();
|
||||||
|
let document_id = portfolio.active_document_id.unwrap();
|
||||||
|
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||||
|
portfolio
|
||||||
|
.executor
|
||||||
|
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
|
||||||
|
.unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run(editor: &mut EditorTestUtils) -> Option<Texture> {
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await
|
||||||
|
}
|
||||||
|
|
||||||
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
/// The ID of the viewport request the runtime evaluates, which only changes once it has read a newer one.
|
||||||
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
fn last_request(editor: &EditorTestUtils) -> Option<u64> {
|
||||||
editor.runtime.pending.map(|request| request.execution_id)
|
editor.runtime.pending.map(|request| request.execution_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn respond_to_last_request(editor: &mut EditorTestUtils, result: ExecutionResult) -> Vec<FrontendMessage> {
|
||||||
|
let response = ExecutionResponse {
|
||||||
|
execution_id: last_request(editor).unwrap(),
|
||||||
|
result,
|
||||||
|
responses: VecDeque::new(),
|
||||||
|
dropped_thumbnails: Vec::new(),
|
||||||
|
observations: HashMap::new(),
|
||||||
|
};
|
||||||
|
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).unwrap();
|
||||||
|
editor.dispatch(Message::Wake)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn failed(messages: &[FrontendMessage]) -> bool {
|
||||||
|
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drawn_in(messages: &[FrontendMessage]) -> Option<&str> {
|
||||||
|
messages.iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::UpdateDocumentArtwork { svg } => Some(svg.as_str()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn empty_svg() -> RenderOutputType {
|
||||||
|
RenderOutputType::Svg {
|
||||||
|
svg: String::new(),
|
||||||
|
image_data: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rendered(data: RenderOutputType) -> TaggedValue {
|
||||||
|
TaggedValue::RenderOutput(RenderOutput { data, metadata: Default::default() })
|
||||||
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn only_update_reads_the_channel() {
|
async fn only_update_reads_the_channel() {
|
||||||
let mut editor = editor().await;
|
let mut editor = editor().await;
|
||||||
@@ -1032,28 +1094,167 @@ mod tests {
|
|||||||
assert!(shows_dialog, "the export should show why it saved nothing");
|
assert!(shows_dialog, "the export should show why it saved nothing");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
fn rectangle_node(editor: &EditorTestUtils) -> NodeId {
|
||||||
async fn an_export_goes_ahead_of_what_was_sent_after_it() {
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||||
let mut editor = editor().await;
|
use graphene_std::vector::generator_nodes::rectangle;
|
||||||
let last = last_request(&editor);
|
|
||||||
send_export(&mut editor, FileType::Svg);
|
|
||||||
send_update(&mut editor);
|
|
||||||
|
|
||||||
editor.runtime.update();
|
let interface = &editor.active_document().network_interface;
|
||||||
assert!(editor.runtime.pending_export.is_some());
|
let nodes = interface.document_network().nodes.keys().copied();
|
||||||
assert_eq!(last_request(&editor), last, "the request sent after the export was read ahead of it");
|
let reference = Some(DefinitionIdentifier::ProtoNode(rectangle::IDENTIFIER));
|
||||||
|
nodes.into_iter().find(|node_id| interface.reference(node_id, &[]) == reference).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
editor.runtime.run().await;
|
fn set_layer_visible(editor: &mut EditorTestUtils, visible: bool) {
|
||||||
assert!(exported(&mut editor));
|
let layer = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
||||||
|
editor.active_document_mut().network_interface.set_visibility(&layer, &[], visible);
|
||||||
|
}
|
||||||
|
|
||||||
editor.runtime.update();
|
fn compiled_nodes(editor: &EditorTestUtils) -> HashMap<Vec<NodeId>, NodeId> {
|
||||||
assert_ne!(last_request(&editor), last);
|
let document = &editor.active_document().network_interface.document_network().nodes;
|
||||||
editor.runtime.run().await;
|
let source_map = editor.runtime.executor.tree().source_map();
|
||||||
assert!(evaluated(&mut editor), "the request sent after the export was lost");
|
let of_the_document = source_map.iter().filter(|(path, _)| path.first().is_some_and(|node| document.contains_key(node)));
|
||||||
|
of_the_document.map(|(path, (node, _))| (path.to_vec(), *node)).collect()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn a_parked_export_holds_back_everything_sent_after_it() {
|
async fn an_export_shows_the_network_it_was_sent_with_whatever_was_sent_after_it() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
|
||||||
|
set_layer_visible(&mut editor, false);
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
set_layer_visible(&mut editor, true);
|
||||||
|
send_update(&mut editor);
|
||||||
|
|
||||||
|
editor.runtime.update();
|
||||||
|
editor.runtime.run().await;
|
||||||
|
let messages = editor.dispatch(Message::Wake);
|
||||||
|
let exported = messages.iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
assert!(exported.is_some_and(|svg| !svg.contains("<path")), "the export should leave out the rectangle hidden when it was sent");
|
||||||
|
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the update sent after the export should be drawn");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_export_leaves_what_the_viewport_shows_as_it_is() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
set_layer_visible(&mut editor, false);
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
send_request(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
let messages = editor.dispatch(Message::Wake);
|
||||||
|
let exported = messages.iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.clone().into_vec()).unwrap()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
assert!(exported.is_some_and(|svg| !svg.contains("<path")), "the export should show the document as the editor has it");
|
||||||
|
assert!(drawn_in(&messages).is_some_and(|svg| svg.contains("<path")), "the export changed the network the viewport shows");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_export_shows_the_node_previewed_in_the_document() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
let below = editor.active_document().metadata().all_layers().next().unwrap().to_node();
|
||||||
|
editor.draw_ellipse(0., 0., 100., 100.).await;
|
||||||
|
editor.active_document_mut().network_interface.toggle_preview(below, &[]);
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
run(&mut editor).await;
|
||||||
|
let exported = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerSaveFile { content, .. } => Some(String::from_utf8(content.into_vec()).unwrap()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
assert!(
|
||||||
|
exported.is_some_and(|svg| svg.matches("<path").count() == 1),
|
||||||
|
"the export should show the previewed layer without the one above it"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_export_runs_the_nodes_the_viewport_runs_for_the_same_document() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
let compiled = compiled_nodes(&editor);
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
editor.runtime.update();
|
||||||
|
assert!(!editor.runtime.exports.is_empty(), "the export's network should be inserted");
|
||||||
|
assert_eq!(compiled_nodes(&editor), compiled, "the export compiled a node of the document anew");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_node_an_export_inserted_before_its_network_update_still_gets_its_types() {
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||||
|
use graphene_std::vector::bounding_box;
|
||||||
|
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
let rectangle = rectangle_node(&editor);
|
||||||
|
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
|
||||||
|
let node = NodeId::new();
|
||||||
|
let template = resolve_proto_node_type(bounding_box::IDENTIFIER).unwrap().default_node_template();
|
||||||
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
network_interface.insert_node(node, template, &[]);
|
||||||
|
network_interface.set_input(&InputConnector::node_at_index(node, 0), NodeInput::node(rectangle, 0), &[]);
|
||||||
|
network_interface.set_input(&content, NodeInput::node(node, 0), &[]);
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
assert!(editor.active_document().network_interface.resolved_types.types.contains_key([node].as_slice()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_copied_group_runs_the_nodes_the_viewport_runs_for_the_layers_in_it() {
|
||||||
|
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||||
|
|
||||||
|
let mut editor = editor().await;
|
||||||
|
let group_folder_type = GroupFolderType::Layer;
|
||||||
|
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
let compiled = compiled_nodes(&editor);
|
||||||
|
|
||||||
|
editor.dispatch(ClipboardMessage::CopyLayers);
|
||||||
|
editor.runtime.update();
|
||||||
|
assert!(!editor.runtime.exports.is_empty(), "the group's network should be inserted");
|
||||||
|
let copied = compiled_nodes(&editor);
|
||||||
|
assert!(compiled.iter().all(|(path, node)| copied.get(path) == Some(node)), "the copy compiled a node of the document anew");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_parked_export_holds_back_nothing_sent_after_it() {
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||||
|
add_traced_noise_layer(&mut editor).await;
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
|
||||||
|
|
||||||
|
let last = last_request(&editor);
|
||||||
|
set_layer_visible(&mut editor, false);
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
assert_ne!(last_request(&editor), last, "the parked export held back the request sent after it");
|
||||||
|
assert!(evaluated(&mut editor), "the request sent after the parked export was not evaluated");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_export_that_finishes_after_what_was_sent_after_it_is_still_saved() {
|
||||||
let mut editor = EditorTestUtils::create();
|
let mut editor = EditorTestUtils::create();
|
||||||
editor.new_document().await;
|
editor.new_document().await;
|
||||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||||
@@ -1062,24 +1263,190 @@ mod tests {
|
|||||||
send_export(&mut editor, FileType::Svg);
|
send_export(&mut editor, FileType::Svg);
|
||||||
editor.runtime.update();
|
editor.runtime.update();
|
||||||
editor.runtime.run().await;
|
editor.runtime.run().await;
|
||||||
assert!(editor.runtime.pending_export.is_some(), "the export took a single evaluation");
|
assert!(!editor.runtime.exports.is_empty(), "the export took a single evaluation");
|
||||||
|
|
||||||
let last = last_request(&editor);
|
|
||||||
send_update(&mut editor);
|
send_update(&mut editor);
|
||||||
|
let mut saved = false;
|
||||||
let mut runs = 0;
|
let mut runs = 0;
|
||||||
while editor.runtime.pending_export.is_some() {
|
while !editor.runtime.exports.is_empty() {
|
||||||
editor.runtime.update();
|
editor.runtime.update();
|
||||||
assert_eq!(last_request(&editor), last, "a request got ahead of the parked export");
|
|
||||||
editor.runtime.run().await;
|
editor.runtime.run().await;
|
||||||
|
saved |= exported(&mut editor);
|
||||||
runs += 1;
|
runs += 1;
|
||||||
assert!(runs < 100_000, "the export never finished");
|
assert!(runs < 100_000, "the export never finished");
|
||||||
}
|
}
|
||||||
assert!(exported(&mut editor));
|
assert!(saved, "the export was lost");
|
||||||
|
}
|
||||||
|
|
||||||
editor.runtime.update();
|
#[tokio::test]
|
||||||
assert_ne!(last_request(&editor), last);
|
async fn two_exports_sent_together_are_both_saved() {
|
||||||
editor.runtime.run().await;
|
let mut editor = editor().await;
|
||||||
assert!(evaluated(&mut editor), "the request sent after the export was lost");
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
run(&mut editor).await;
|
||||||
|
|
||||||
|
let messages = editor.dispatch(Message::Wake);
|
||||||
|
let saved = messages.iter().filter(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
|
||||||
|
assert_eq!(saved.count(), 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_failed_export_leaves_the_frame_that_follows_it_shown() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap();
|
||||||
|
let result = Box::new(ExecutionResult::Error(EvaluationErrors(Box::new([]))));
|
||||||
|
editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap();
|
||||||
|
let messages = respond_to_last_request(&mut editor, ExecutionResult::Value(rendered(empty_svg())));
|
||||||
|
let shows_dialog = messages.iter().any(|message| matches!(message, FrontendMessage::DisplayDialog { .. }));
|
||||||
|
assert!(shows_dialog, "the export should say it failed");
|
||||||
|
assert!(!failed(&messages), "the failed export marked the viewport's render as failed");
|
||||||
|
assert!(drawn_in(&messages).is_some(), "the frame that followed the failed export was dropped");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn an_export_answered_behind_a_failed_frame_is_still_saved() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
|
||||||
|
send_export(&mut editor, FileType::Svg);
|
||||||
|
let failed_frame = ExecutionResponse {
|
||||||
|
execution_id: last_request(&editor).unwrap(),
|
||||||
|
result: ExecutionResult::Error(EvaluationErrors(Box::new([]))),
|
||||||
|
responses: VecDeque::new(),
|
||||||
|
dropped_thumbnails: Vec::new(),
|
||||||
|
observations: HashMap::new(),
|
||||||
|
};
|
||||||
|
editor.runtime.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(failed_frame))).unwrap();
|
||||||
|
let id = *editor.portfolio_message_handler().executor.exports.keys().next().unwrap();
|
||||||
|
let result = Box::new(ExecutionResult::Value(rendered(empty_svg())));
|
||||||
|
editor.runtime.sender.send(NodeGraphUpdate::Export { id, result }).unwrap();
|
||||||
|
|
||||||
|
let messages = editor.dispatch(Message::Wake);
|
||||||
|
let saved = messages.iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }));
|
||||||
|
assert!(failed(&messages), "the frame should be reported as failed");
|
||||||
|
assert!(saved, "the export answered behind the failed frame was dropped");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn cutting_a_layer_still_being_traced_writes_its_svg_once_the_trace_is_done() {
|
||||||
|
use crate::messages::portfolio::ingest::utility_types::TransferData;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
add_traced_noise_layer(&mut editor).await;
|
||||||
|
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||||
|
send_update(&mut editor);
|
||||||
|
let mut runs = 0;
|
||||||
|
while editor.active_document().metadata().bounding_box_document(layer).is_none() {
|
||||||
|
run(&mut editor).await;
|
||||||
|
editor.dispatch(Message::Wake);
|
||||||
|
runs += 1;
|
||||||
|
assert!(runs < 100_000, "the trace never drew a shape");
|
||||||
|
}
|
||||||
|
|
||||||
|
editor.dispatch(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] });
|
||||||
|
editor.dispatch(ClipboardMessage::CutLayers);
|
||||||
|
assert_eq!(editor.active_document().metadata().all_layers().count(), 0, "the layer should be cut");
|
||||||
|
run(&mut editor).await;
|
||||||
|
assert!(!editor.runtime.exports.is_empty(), "the copy took a single evaluation");
|
||||||
|
|
||||||
|
let mut written = None;
|
||||||
|
runs = 0;
|
||||||
|
while written.is_none() {
|
||||||
|
run(&mut editor).await;
|
||||||
|
written = editor.dispatch(Message::Wake).into_iter().find_map(|message| match message {
|
||||||
|
FrontendMessage::TriggerClipboardWrite { content } => Some(content),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
runs += 1;
|
||||||
|
assert!(runs < 100_000, "the cut layer never reached the clipboard");
|
||||||
|
}
|
||||||
|
let svg = written.iter().flat_map(|content| &content.0).find_map(|item| match &item.data {
|
||||||
|
TransferData::Svg(svg) => Some(svg.as_str()),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
assert!(svg.is_some_and(|svg| svg.contains("<path")), "the SVG should hold the shapes traced from the cut layer");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_layer_copied_out_of_an_artboard_is_framed_in_the_space_the_artboard_gives_it() {
|
||||||
|
use crate::messages::input_mapper::utility_types::keyboard::ModifierKeys;
|
||||||
|
use crate::messages::tool::utility_types::ToolType;
|
||||||
|
|
||||||
|
let mut editor = EditorTestUtils::create();
|
||||||
|
editor.new_document().await;
|
||||||
|
editor.drag_tool(ToolType::Artboard, 100., 50., 300., 250., ModifierKeys::empty()).await;
|
||||||
|
editor.draw_rect(120., 80., 160., 130.).await;
|
||||||
|
let layer = editor.get_selected_layer().await.expect("the drawn rectangle should be selected");
|
||||||
|
|
||||||
|
let document = editor.active_document();
|
||||||
|
let metadata = document.metadata();
|
||||||
|
let artboard = layer.parent(metadata).expect("the rectangle should be in the artboard");
|
||||||
|
assert!(document.network_interface.is_artboard(&artboard.to_node(), &[]));
|
||||||
|
let [artboard_min, _] = metadata.bounding_box_document(artboard).expect("the artboard has bounds");
|
||||||
|
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).expect("the rectangle has bounds");
|
||||||
|
assert!(artboard_min.length() > 1., "the artboard should be away from the origin");
|
||||||
|
|
||||||
|
let (_, [framed_min, framed_max]) = copied_layers(&document.network_interface, &[layer]).expect("the rectangle should be copied");
|
||||||
|
assert!(framed_min.abs_diff_eq(min - artboard_min, 1e-6), "{framed_min} should leave out where the artboard is");
|
||||||
|
assert!(framed_max.abs_diff_eq(max - artboard_min, 1e-6), "{framed_max} should leave out where the artboard is");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Feeds the rectangle into an 'Add' node, which takes numbers, so the graph compiles but fails to type check.
|
||||||
|
fn break_type_check(editor: &mut EditorTestUtils) {
|
||||||
|
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||||
|
use graphene_std::math_nodes::add;
|
||||||
|
|
||||||
|
let rectangle = rectangle_node(editor);
|
||||||
|
let content = InputConnector::node_at_index(editor.active_document().metadata().all_layers().next().unwrap().to_node(), 1);
|
||||||
|
let add_node = NodeId::new();
|
||||||
|
let template = resolve_proto_node_type(add::IDENTIFIER).unwrap().default_node_template();
|
||||||
|
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||||
|
network_interface.insert_node(add_node, template, &[]);
|
||||||
|
network_interface.set_input(&InputConnector::node_at_index(add_node, 0), NodeInput::node(rectangle, 0), &[]);
|
||||||
|
network_interface.set_input(&content, NodeInput::node(add_node, 0), &[]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_network_that_fails_to_type_check_leaves_no_output_and_keeps_the_last_one_that_did() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
let output = editor.runtime.output.as_ref().expect("the network should compile").node();
|
||||||
|
|
||||||
|
break_type_check(&mut editor);
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
assert!(editor.runtime.output.is_none(), "a rectangle should not type check as a number");
|
||||||
|
assert_eq!(editor.runtime.previous.as_ref().map(OutputHandle::node), Some(output));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn a_layer_hidden_and_shown_again_finds_its_nodes_again() {
|
||||||
|
let mut editor = editor().await;
|
||||||
|
let rectangle = rectangle_node(&editor);
|
||||||
|
let compiled = |editor: &EditorTestUtils| {
|
||||||
|
let tree = editor.runtime.executor.tree();
|
||||||
|
tree.source_map().get([rectangle].as_slice()).and_then(|(node, _)| tree.get(*node))
|
||||||
|
};
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
let before = compiled(&editor).expect("the rectangle should be compiled");
|
||||||
|
|
||||||
|
for visible in [false, true] {
|
||||||
|
set_layer_visible(&mut editor, visible);
|
||||||
|
send_update(&mut editor);
|
||||||
|
run(&mut editor).await;
|
||||||
|
}
|
||||||
|
let after = compiled(&editor).expect("the rectangle should be compiled again");
|
||||||
|
assert!(Arc::ptr_eq(&before, &after), "the rectangle was built again");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use crate::messages::frontend::FrontendMessage;
|
|||||||
use atlas::ThumbnailAtlasLayout;
|
use atlas::ThumbnailAtlasLayout;
|
||||||
use glam::{DAffine2, DVec2, UVec2};
|
use glam::{DAffine2, DVec2, UVec2};
|
||||||
use graph_craft::application_io::PlatformEditorApi;
|
use graph_craft::application_io::PlatformEditorApi;
|
||||||
use graph_craft::document::{NodeId, NodeNetwork};
|
use graph_craft::document::NodeId;
|
||||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||||
use graphene_std::bounds::RenderBoundingBox;
|
use graphene_std::bounds::RenderBoundingBox;
|
||||||
use graphene_std::gradient::Gradient;
|
use graphene_std::gradient::Gradient;
|
||||||
@@ -12,12 +12,11 @@ use graphene_std::ops::ConvertAsync;
|
|||||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
|
||||||
use graphene_std::raster_types::{CPU, GPU, Raster};
|
use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
use graphene_std::renderer::Render;
|
||||||
use graphene_std::transform::{Footprint, RenderQuality};
|
use graphene_std::transform::Footprint;
|
||||||
use graphene_std::vector::Vector;
|
use graphene_std::vector::Vector;
|
||||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||||
use interpreted_executor::layer_paths::layer_content;
|
|
||||||
use std::collections::{HashMap, HashSet, VecDeque};
|
use std::collections::{HashMap, HashSet, VecDeque};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -83,12 +82,9 @@ impl Thumbnails {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
|
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
|
||||||
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
|
pub fn update_sources(&mut self, layers: &[(NodeId, Vec<NodeId>)], executor: &DynamicExecutor) {
|
||||||
// O(layers * depth)
|
let source_map = executor.tree().source_map();
|
||||||
let sources: HashMap<NodeId, NodeId> = layer_paths
|
let sources: HashMap<NodeId, NodeId> = layers.iter().filter_map(|(layer, source)| Some((*layer, source_map.get(source.as_slice())?.0))).collect();
|
||||||
.iter()
|
|
||||||
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
|
||||||
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
|
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
|
||||||
@@ -276,11 +272,11 @@ impl ThumbnailContent {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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.
|
/// The area the content covers once rendered, counting the effects drawn through maps and images.
|
||||||
fn content_bounds(&self, maps_resolved: bool) -> RenderBoundingBox {
|
fn content_bounds(&self) -> RenderBoundingBox {
|
||||||
match self {
|
match self {
|
||||||
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
// Text-aware bounds, which the `BoundingBox` trait can't give `Graphic::TextList` content, with the effects' reach
|
||||||
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, maps_resolved),
|
Self::Graphics(graphics) => graphene_std::renderer::graphic_list_painted_bounds(graphics, true),
|
||||||
// The clipping rectangles rather than the content, since the renderer clips content to them
|
// The clipping rectangles rather than the content, since the renderer clips content to them
|
||||||
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
Self::Artboards(artboards) => artboard_clip_bounds(artboards),
|
||||||
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
Self::Text(text) => graphene_std::renderer::text_list_bounding_box(text, DAffine2::IDENTITY),
|
||||||
@@ -289,7 +285,7 @@ impl ThumbnailContent {
|
|||||||
|
|
||||||
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
/// The area the thumbnail shows, centered on the content at the thumbnail's aspect ratio.
|
||||||
fn bounds(&self) -> [DVec2; 2] {
|
fn bounds(&self) -> [DVec2; 2] {
|
||||||
let bounds = match self.content_bounds(true) {
|
let bounds = match self.content_bounds() {
|
||||||
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
RenderBoundingBox::Rectangle(bounds) if (bounds[1] - bounds[0]) != DVec2::ZERO => bounds,
|
||||||
_ => [DVec2::ZERO, DVec2::ONE],
|
_ => [DVec2::ZERO, DVec2::ONE],
|
||||||
};
|
};
|
||||||
@@ -297,45 +293,6 @@ 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)?;
|
|
||||||
|
|
||||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Converts the other kinds of graphical content into a graphic.
|
/// Converts the other kinds of graphical content into a graphic.
|
||||||
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
|
||||||
macro_rules! downcast_into_graphic {
|
macro_rules! downcast_into_graphic {
|
||||||
|
|||||||
@@ -558,10 +558,9 @@
|
|||||||
margin-left: 8px;
|
margin-left: 8px;
|
||||||
}
|
}
|
||||||
|
|
||||||
// A label with no expose button before it lines up with the parameter names that follow one
|
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||||
> .text-label:first-child {
|
> .text-label:only-child {
|
||||||
margin-left: calc(20px + 8px + 8px);
|
margin-left: calc(20px + 8px + 8px);
|
||||||
--wire-indent: 20px;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
> .separator.horizontal.unrelated {
|
> .separator.horizontal.unrelated {
|
||||||
|
|||||||
@@ -41,6 +41,7 @@ raster-nodes = { workspace = true, features = ["serde"] }
|
|||||||
vector-nodes = { workspace = true, features = ["serde"] }
|
vector-nodes = { workspace = true, features = ["serde"] }
|
||||||
graphic-types = { workspace = true, features = ["serde"] }
|
graphic-types = { workspace = true, features = ["serde"] }
|
||||||
text-nodes = { workspace = true, features = ["serde"] }
|
text-nodes = { workspace = true, features = ["serde"] }
|
||||||
|
graph-ui-types = { workspace = true }
|
||||||
|
|
||||||
# Workspace dependencies
|
# Workspace dependencies
|
||||||
log = { workspace = true }
|
log = { workspace = true }
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
|
|||||||
use graphene_animation::AnimationCurve;
|
use graphene_animation::AnimationCurve;
|
||||||
use graphene_application_io::resource::ResourceHash;
|
use graphene_application_io::resource::ResourceHash;
|
||||||
use graphene_application_io::resource::ResourceId;
|
use graphene_application_io::resource::ResourceId;
|
||||||
use graphic_types::raster_types::{CPU, Image, Pixels, Raster};
|
use graphic_types::raster_types::{CPU, Image, Raster};
|
||||||
use graphic_types::vector_types::vector::misc::BoxCorners;
|
use graphic_types::vector_types::vector::misc::BoxCorners;
|
||||||
use graphic_types::vector_types::vector::style::DashPattern;
|
use graphic_types::vector_types::vector::style::DashPattern;
|
||||||
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
|
||||||
@@ -110,6 +110,8 @@ macro_rules! tagged_value {
|
|||||||
Runtime(RuntimeHandle),
|
Runtime(RuntimeHandle),
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
EditorApi(Arc<PlatformEditorApi>),
|
EditorApi(Arc<PlatformEditorApi>),
|
||||||
|
#[serde(skip)]
|
||||||
|
GraphUi(graph_ui_types::TaggedGraphUiValue),
|
||||||
/// Only used by the `resource` node, should never be serialized
|
/// Only used by the `resource` node, should never be serialized
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
ResourceHash(ResourceHash),
|
ResourceHash(ResourceHash),
|
||||||
@@ -144,6 +146,7 @@ macro_rules! tagged_value {
|
|||||||
Self::Runtime(runtime) => runtime.cache_hash(state),
|
Self::Runtime(runtime) => runtime.cache_hash(state),
|
||||||
Self::RenderOutput(x) => x.cache_hash(state),
|
Self::RenderOutput(x) => x.cache_hash(state),
|
||||||
Self::EditorApi(x) => x.cache_hash(state),
|
Self::EditorApi(x) => x.cache_hash(state),
|
||||||
|
Self::GraphUi(x) => x.cache_hash(state),
|
||||||
Self::ResourceHash(x) => x.cache_hash(state),
|
Self::ResourceHash(x) => x.cache_hash(state),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -208,6 +211,7 @@ macro_rules! tagged_value {
|
|||||||
Self::SourceId(source) => Box::new(Item::new_from_element(source)),
|
Self::SourceId(source) => Box::new(Item::new_from_element(source)),
|
||||||
Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)),
|
Self::Runtime(runtime) => Box::new(Item::new_from_element(runtime)),
|
||||||
Self::EditorApi(x) => Box::new(Item::new_from_element(x)),
|
Self::EditorApi(x) => Box::new(Item::new_from_element(x)),
|
||||||
|
Self::GraphUi(x) => x.to_dynany(),
|
||||||
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
|
Self::ResourceHash(x) => Box::new(Item::new_from_element(x)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -268,6 +272,7 @@ macro_rules! tagged_value {
|
|||||||
Self::SourceId(source) => Arc::new(Item::new_from_element(source)),
|
Self::SourceId(source) => Arc::new(Item::new_from_element(source)),
|
||||||
Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)),
|
Self::Runtime(runtime) => Arc::new(Item::new_from_element(runtime)),
|
||||||
Self::EditorApi(x) => Arc::new(Item::new_from_element(x)),
|
Self::EditorApi(x) => Arc::new(Item::new_from_element(x)),
|
||||||
|
Self::GraphUi(x) => x.to_any(),
|
||||||
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
|
Self::ResourceHash(x) => Arc::new(Item::new_from_element(x)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -300,6 +305,7 @@ macro_rules! tagged_value {
|
|||||||
Self::SourceId(_) => item!(SourceId),
|
Self::SourceId(_) => item!(SourceId),
|
||||||
Self::Runtime(_) => item!(RuntimeHandle),
|
Self::Runtime(_) => item!(RuntimeHandle),
|
||||||
Self::EditorApi(_) => item!(Arc<PlatformEditorApi>),
|
Self::EditorApi(_) => item!(Arc<PlatformEditorApi>),
|
||||||
|
Self::GraphUi(x) => x.ty(),
|
||||||
Self::ResourceHash(_) => item!(ResourceHash),
|
Self::ResourceHash(_) => item!(ResourceHash),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -400,11 +406,6 @@ macro_rules! tagged_value {
|
|||||||
Type::Fn(_, output) => TaggedValue::from_type(output),
|
Type::Fn(_, output) => TaggedValue::from_type(output),
|
||||||
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
// Element types with a dedicated variant use it directly (the variant's value is a rank-0 cell); the rest store the structural type
|
||||||
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
Type::Item(element) => TaggedValue::from_type(element).or_else(|| {
|
||||||
// Pixels are read back from an image, so a `Pixels` input holds the empty image
|
|
||||||
if **element == concrete!(Pixels) {
|
|
||||||
return Some(TaggedValue::TypeDefault(item!(Raster<CPU>)));
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
@@ -421,9 +422,6 @@ macro_rules! tagged_value {
|
|||||||
if **element == concrete!(Stroke) {
|
if **element == concrete!(Stroke) {
|
||||||
return Some(TaggedValue::Strokes(Vec::new()));
|
return Some(TaggedValue::Strokes(Vec::new()));
|
||||||
}
|
}
|
||||||
if **element == concrete!(Pixels) {
|
|
||||||
return Some(TaggedValue::TypeDefault(list!(Raster<CPU>)));
|
|
||||||
}
|
|
||||||
macro_rules! check {
|
macro_rules! check {
|
||||||
($type_default:ty) => {
|
($type_default:ty) => {
|
||||||
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
if **element == concrete!($type_default) { return Some(TaggedValue::TypeDefault(input.clone())); }
|
||||||
@@ -466,6 +464,7 @@ macro_rules! tagged_value {
|
|||||||
Self::SourceId(source) => format!("SourceId({source:?})"),
|
Self::SourceId(source) => format!("SourceId({source:?})"),
|
||||||
Self::Runtime(_) => "Runtime".to_string(),
|
Self::Runtime(_) => "Runtime".to_string(),
|
||||||
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
Self::EditorApi(_) => "PlatformEditorApi".to_string(),
|
||||||
|
Self::GraphUi(_) => "GraphUi".to_string(),
|
||||||
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
Self::ResourceHash(hash) => format!("ResourceHash({hash:?})"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -578,7 +577,6 @@ tagged_value! {
|
|||||||
StrokeAlign(vector::style::StrokeAlign),
|
StrokeAlign(vector::style::StrokeAlign),
|
||||||
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
#[serde(alias = "GradientType")] // TODO: Eventually remove this document upgrade code
|
||||||
GradientForm(vector::style::GradientForm),
|
GradientForm(vector::style::GradientForm),
|
||||||
GradientModel(vector::style::GradientModel),
|
|
||||||
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
#[serde(alias = "GradientSpreadMethod")] // TODO: Eventually remove this document upgrade code
|
||||||
GradientSpread(vector::style::GradientSpread),
|
GradientSpread(vector::style::GradientSpread),
|
||||||
GradientSpace(vector::style::GradientSpace),
|
GradientSpace(vector::style::GradientSpace),
|
||||||
|
|||||||
@@ -0,0 +1,36 @@
|
|||||||
|
[package]
|
||||||
|
name = "graph-ui"
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = ["graph-ui-types/serde"]
|
||||||
|
wasm = ["graph-ui-types/wasm"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# Local dependencies
|
||||||
|
core-types = { workspace = true }
|
||||||
|
graph-craft = { workspace = true }
|
||||||
|
graph-ui-icons = { workspace = true }
|
||||||
|
graph-ui-types = { workspace = true }
|
||||||
|
graphene-std = { workspace = true }
|
||||||
|
graphic-types = { workspace = true }
|
||||||
|
node-macro = { workspace = true }
|
||||||
|
rendering = { workspace = true }
|
||||||
|
svg-convert = { workspace = true }
|
||||||
|
text-nodes = { workspace = true }
|
||||||
|
vector-types = { workspace = true }
|
||||||
|
|
||||||
|
# Workspace dependencies
|
||||||
|
glam = { workspace = true }
|
||||||
|
vello_gpu = { workspace = true }
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
[package]
|
||||||
|
name = "graph-ui-icons"
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
// TODO(Timon): Replace with generalized icon crate
|
||||||
|
|
||||||
|
use std::fmt::Write;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"];
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../..");
|
||||||
|
let assets = root.join("branding/assets");
|
||||||
|
|
||||||
|
let mut sources = Vec::new();
|
||||||
|
println!("cargo:rerun-if-changed={}", assets.display());
|
||||||
|
if assets.is_dir() {
|
||||||
|
for folder in FOLDERS {
|
||||||
|
for entry in std::fs::read_dir(assets.join(folder)).unwrap() {
|
||||||
|
let path = entry.unwrap().path();
|
||||||
|
if path.extension().is_some_and(|extension| extension == "svg") {
|
||||||
|
sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
println!("cargo:warning=No branding folder, icons will be missing");
|
||||||
|
}
|
||||||
|
sources.sort();
|
||||||
|
|
||||||
|
let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n");
|
||||||
|
for (name, path) in &sources {
|
||||||
|
writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap();
|
||||||
|
}
|
||||||
|
table.push_str("];\n");
|
||||||
|
std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn icon_name(file_stem: &str) -> String {
|
||||||
|
let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..];
|
||||||
|
file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect()
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
// TODO(Timon): Replace with generalized icon crate
|
||||||
|
|
||||||
|
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||||
|
|
||||||
|
pub fn svg(name: &str) -> Option<&'static str> {
|
||||||
|
let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?;
|
||||||
|
Some(SOURCES[index].1)
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
use crate::metrics::{BORDER_DASHES, BORDER_WIDTH};
|
||||||
|
use glam::DVec2;
|
||||||
|
use std::f64::consts::{FRAC_PI_2, PI};
|
||||||
|
use std::ops::Range;
|
||||||
|
use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
|
||||||
|
|
||||||
|
const MEASURE_TOLERANCE: f64 = 0.5;
|
||||||
|
const MEASURE_DEPTH: u32 = 20;
|
||||||
|
const ARC_TOLERANCE: f64 = 0.1;
|
||||||
|
|
||||||
|
struct Measured {
|
||||||
|
distance: f64,
|
||||||
|
segment: usize,
|
||||||
|
t: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath {
|
||||||
|
let mut dashes = BezPath::new();
|
||||||
|
for contour in contours(path) {
|
||||||
|
let measured = measure(&contour);
|
||||||
|
let Some(length) = measured.last().map(|last| last.distance) else { continue };
|
||||||
|
let mut distance = 0.;
|
||||||
|
for (index, interval) in [dash, gap].into_iter().cycle().enumerate() {
|
||||||
|
if distance >= length {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if index % 2 == 0 {
|
||||||
|
piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes);
|
||||||
|
}
|
||||||
|
distance += interval;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dashes
|
||||||
|
}
|
||||||
|
|
||||||
|
fn contours(path: &BezPath) -> Vec<Vec<PathSeg>> {
|
||||||
|
let mut contours: Vec<Vec<PathSeg>> = Vec::new();
|
||||||
|
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||||
|
for element in path.elements() {
|
||||||
|
let segment = match *element {
|
||||||
|
PathEl::MoveTo(point) => {
|
||||||
|
contours.push(Vec::new());
|
||||||
|
(start, last) = (point, point);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)),
|
||||||
|
PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()),
|
||||||
|
PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)),
|
||||||
|
PathEl::ClosePath => PathSeg::Line(Line::new(last, start)),
|
||||||
|
};
|
||||||
|
last = segment.end();
|
||||||
|
if let Some(contour) = contours.last_mut() {
|
||||||
|
contour.push(segment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
contours
|
||||||
|
}
|
||||||
|
|
||||||
|
fn measure(contour: &[PathSeg]) -> Vec<Measured> {
|
||||||
|
let mut measured = Vec::new();
|
||||||
|
let mut distance = 0.;
|
||||||
|
for (segment, piece) in contour.iter().enumerate() {
|
||||||
|
distance = match piece {
|
||||||
|
PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured),
|
||||||
|
_ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
measured
|
||||||
|
}
|
||||||
|
|
||||||
|
fn measure_cubic(cubic: CubicBez, distance: f64, range: Range<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> f64 {
|
||||||
|
let strays = |control: Point, fraction: f64| {
|
||||||
|
let on_chord = cubic.p0.lerp(cubic.p3, fraction);
|
||||||
|
(control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE
|
||||||
|
};
|
||||||
|
if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) {
|
||||||
|
return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured);
|
||||||
|
}
|
||||||
|
let (first, second) = cubic.subdivide();
|
||||||
|
let middle = (range.start + range.end) / 2.;
|
||||||
|
let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured);
|
||||||
|
measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec<Measured>) -> f64 {
|
||||||
|
let next = distance + from.distance(to);
|
||||||
|
if next > distance {
|
||||||
|
measured.push(Measured { distance: next, segment, t });
|
||||||
|
}
|
||||||
|
next
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(measured: &[Measured], distance: f64) -> (usize, f64) {
|
||||||
|
let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1);
|
||||||
|
let entry = &measured[index];
|
||||||
|
let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) {
|
||||||
|
Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t),
|
||||||
|
Some(previous) => (previous.distance, 0.),
|
||||||
|
None => (0., 0.),
|
||||||
|
};
|
||||||
|
(entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn piece(contour: &[PathSeg], measured: &[Measured], range: Range<f64>, dashes: &mut BezPath) {
|
||||||
|
let (start_segment, start_t) = at(measured, range.start);
|
||||||
|
let (end_segment, end_t) = at(measured, range.end);
|
||||||
|
dashes.move_to(contour[start_segment].eval(start_t));
|
||||||
|
let mut push = |segment: usize, range: Range<f64>| match contour[segment].subsegment(range) {
|
||||||
|
PathSeg::Line(line) => dashes.line_to(line.p1),
|
||||||
|
PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2),
|
||||||
|
PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3),
|
||||||
|
};
|
||||||
|
if start_segment == end_segment {
|
||||||
|
push(start_segment, start_t..end_t);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
push(start_segment, start_t..1.);
|
||||||
|
for segment in start_segment + 1..end_segment {
|
||||||
|
push(segment, 0. ..1.);
|
||||||
|
}
|
||||||
|
push(end_segment, 0. ..end_t);
|
||||||
|
}
|
||||||
|
|
||||||
|
enum BorderPart {
|
||||||
|
Line(DVec2, DVec2),
|
||||||
|
Corner(DVec2, f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath {
|
||||||
|
let inset = BORDER_WIDTH / 2.;
|
||||||
|
let arc_radius = radius - inset;
|
||||||
|
let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]);
|
||||||
|
let [left, top] = (min + inset).to_array();
|
||||||
|
let [right, bottom] = (max - inset).to_array();
|
||||||
|
let parts = [
|
||||||
|
BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)),
|
||||||
|
BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2),
|
||||||
|
BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)),
|
||||||
|
BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.),
|
||||||
|
BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)),
|
||||||
|
BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2),
|
||||||
|
BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)),
|
||||||
|
BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI),
|
||||||
|
];
|
||||||
|
let length = |part: &BorderPart| match part {
|
||||||
|
BorderPart::Line(from, to) => from.distance(*to),
|
||||||
|
BorderPart::Corner(..) => corner_length,
|
||||||
|
};
|
||||||
|
let point = |part: &BorderPart, fraction: f64| match *part {
|
||||||
|
BorderPart::Line(from, to) => from.lerp(to, fraction),
|
||||||
|
BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2),
|
||||||
|
};
|
||||||
|
let starts: Vec<f64> = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect();
|
||||||
|
let perimeter: f64 = parts.iter().map(length).sum();
|
||||||
|
|
||||||
|
let mut left_out: Vec<[f64; 2]> = parts
|
||||||
|
.iter()
|
||||||
|
.zip(&starts)
|
||||||
|
.flat_map(|(part, &start)| {
|
||||||
|
let straight = matches!(part, BorderPart::Line(..));
|
||||||
|
let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap));
|
||||||
|
inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)])
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
left_out.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||||
|
|
||||||
|
let shown = if dashed {
|
||||||
|
let [dash, gap] = BORDER_DASHES;
|
||||||
|
let length = perimeter.floor();
|
||||||
|
let fewer = (length / (dash + gap)).floor();
|
||||||
|
let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count);
|
||||||
|
let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() {
|
||||||
|
(fewer + 1., gaps[1])
|
||||||
|
} else {
|
||||||
|
(fewer, gaps[0])
|
||||||
|
};
|
||||||
|
(0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect()
|
||||||
|
} else {
|
||||||
|
vec![[0., perimeter]]
|
||||||
|
};
|
||||||
|
let visible = shown.into_iter().flat_map(|[mut from, to]| {
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
for &[gap_from, gap_to] in &left_out {
|
||||||
|
if gap_from < to && gap_to > from {
|
||||||
|
pieces.extend((gap_from > from).then_some([from, gap_from]));
|
||||||
|
from = from.max(gap_to);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pieces.extend((from < to).then_some([from, to]));
|
||||||
|
pieces
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut border = BezPath::new();
|
||||||
|
for [from, to] in visible {
|
||||||
|
let mut started = false;
|
||||||
|
for (part, start) in parts.iter().zip(&starts) {
|
||||||
|
if length(part) == 0. {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.));
|
||||||
|
if b <= a {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if !started {
|
||||||
|
border.move_to(<(f64, f64)>::from(point(part, a)));
|
||||||
|
started = true;
|
||||||
|
}
|
||||||
|
match *part {
|
||||||
|
BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))),
|
||||||
|
BorderPart::Corner(center, start_angle) => {
|
||||||
|
border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
border
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 {
|
||||||
|
let point = |angle: f64| radius * DVec2::from_angle(angle);
|
||||||
|
let middle = (from + to) / 2.;
|
||||||
|
let bulge = point(middle) - (point(from) + point(to)) / 2.;
|
||||||
|
if bulge.abs().max_element() > MEASURE_TOLERANCE {
|
||||||
|
flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to])
|
||||||
|
} else {
|
||||||
|
point(from).distance(point(to))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> {
|
||||||
|
let mut range = [0_f64, 1_f64];
|
||||||
|
for axis in 0..2 {
|
||||||
|
let value = |fraction: f64| point(fraction)[axis];
|
||||||
|
let [start, end] = [value(0.), value(1.)];
|
||||||
|
if start.min(end) > high[axis] || start.max(end) < low[axis] {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if start == end {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let fraction_at = |bound: f64| {
|
||||||
|
if (bound - start) * (end - start) <= 0. {
|
||||||
|
return 0.;
|
||||||
|
}
|
||||||
|
if (bound - end) * (end - start) >= 0. {
|
||||||
|
return 1.;
|
||||||
|
}
|
||||||
|
if straight {
|
||||||
|
return (bound - start) / (end - start);
|
||||||
|
}
|
||||||
|
let [mut before, mut after] = [0_f64, 1_f64];
|
||||||
|
for _ in 0..f64::MANTISSA_DIGITS {
|
||||||
|
let middle = (before + after) / 2.;
|
||||||
|
if (value(middle) - bound) * (end - start) < 0. {
|
||||||
|
before = middle;
|
||||||
|
} else {
|
||||||
|
after = middle;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
after
|
||||||
|
};
|
||||||
|
let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])];
|
||||||
|
range = [range[0].max(a.min(b)), range[1].min(a.max(b))];
|
||||||
|
}
|
||||||
|
(range[0] < range[1]).then_some(range)
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
// TODO(Timon): Replace with generalized icon crate
|
||||||
|
|
||||||
|
use crate::card::DataType;
|
||||||
|
use crate::look::data_type_colors;
|
||||||
|
use crate::metrics::ICON_SIZE;
|
||||||
|
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||||
|
use core_types::color::SRGBA8;
|
||||||
|
use core_types::list::List;
|
||||||
|
use glam::DAffine2;
|
||||||
|
use graphic_types::{IntoGraphicList, Vector};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::Write;
|
||||||
|
use std::sync::{LazyLock, Mutex};
|
||||||
|
use svg_convert::Options;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Icon {
|
||||||
|
pub(crate) shapes: List<Vector>,
|
||||||
|
pub(crate) overflows: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
|
||||||
|
|
||||||
|
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
|
||||||
|
|
||||||
|
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
|
||||||
|
let mut converted = CONVERTED.lock().unwrap();
|
||||||
|
let converted = converted.entry(current).or_default();
|
||||||
|
if let Some(icon) = converted.get(name) {
|
||||||
|
return icon.clone();
|
||||||
|
}
|
||||||
|
let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current));
|
||||||
|
converted.insert(name.to_string(), icon.clone());
|
||||||
|
icon
|
||||||
|
}
|
||||||
|
|
||||||
|
fn convert(svg: &str, current: SRGBA8) -> Option<Icon> {
|
||||||
|
let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current));
|
||||||
|
for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) {
|
||||||
|
write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap();
|
||||||
|
}
|
||||||
|
let options = Options {
|
||||||
|
style_sheet: Some(style_sheet),
|
||||||
|
..Options::default()
|
||||||
|
};
|
||||||
|
let shapes: List<Vector> = svg_convert::convert(svg, &options).ok()?.into_flattened_list();
|
||||||
|
|
||||||
|
let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) {
|
||||||
|
RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE,
|
||||||
|
RenderBoundingBox::Infinite => true,
|
||||||
|
RenderBoundingBox::None => false,
|
||||||
|
};
|
||||||
|
Some(Icon { shapes, overflows })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_color(color: SRGBA8) -> String {
|
||||||
|
format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn class_color(class: &str) -> Option<SRGBA8> {
|
||||||
|
let token = class.strip_prefix("color-")?;
|
||||||
|
let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) };
|
||||||
|
let (pair, percent) = mix.rsplit_once('-')?;
|
||||||
|
let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?;
|
||||||
|
let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?;
|
||||||
|
let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8;
|
||||||
|
Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn token_color(token: &str) -> Option<SRGBA8> {
|
||||||
|
if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) {
|
||||||
|
let value = u8::from_str_radix(digit, 16).ok()? * 0x11;
|
||||||
|
return Some(SRGBA8::new_opaque(value, value, value));
|
||||||
|
}
|
||||||
|
let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true));
|
||||||
|
let data_type = match name {
|
||||||
|
"general" => DataType::General,
|
||||||
|
"number" => DataType::Number,
|
||||||
|
"artboard" => DataType::Artboard,
|
||||||
|
"graphic" => DataType::Graphic,
|
||||||
|
"raster" => DataType::Raster,
|
||||||
|
"vector" => DataType::Vector,
|
||||||
|
"color" => DataType::Color,
|
||||||
|
"gradient" => DataType::Gradient,
|
||||||
|
"typography" => DataType::Typography,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
let [bright, dimmed] = data_type_colors(data_type);
|
||||||
|
Some(if dim { dimmed } else { bright })
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
use graph_ui_types::inputs;
|
||||||
|
pub use graph_ui_types::{GraphUiConfig, card, dot, error_badge, geometry, highlights, layer, metrics, network_connector, placed, replicated_map, scene, wire};
|
||||||
|
pub use network::{network, render_config};
|
||||||
|
pub use text::{error_text_size, label_width};
|
||||||
|
|
||||||
|
mod dashes;
|
||||||
|
pub mod icons;
|
||||||
|
mod look;
|
||||||
|
mod network;
|
||||||
|
pub mod nodes;
|
||||||
|
pub mod router;
|
||||||
|
mod text;
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
use crate::card::{Connector, DataType};
|
||||||
|
use crate::highlights::Highlight;
|
||||||
|
use crate::icons;
|
||||||
|
use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE};
|
||||||
|
use core_types::Color;
|
||||||
|
use core_types::color::SRGBA8;
|
||||||
|
use core_types::list::{Item, List};
|
||||||
|
use core_types::transform::ApplyTransform;
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath;
|
||||||
|
use vector_types::vector::style::{Stroke, StrokeJoin};
|
||||||
|
use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape};
|
||||||
|
|
||||||
|
pub(crate) const CARD_OPACITY: f32 = 0.33;
|
||||||
|
pub(crate) const GRID_DOT_OPACITY: f32 = 0.2;
|
||||||
|
pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||||
|
pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5;
|
||||||
|
pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||||
|
pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||||
|
pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||||
|
pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||||
|
pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66);
|
||||||
|
pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||||
|
pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa);
|
||||||
|
pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||||
|
pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||||
|
pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||||
|
pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff);
|
||||||
|
pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05;
|
||||||
|
pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e);
|
||||||
|
pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||||
|
pub(crate) const ERROR_OPACITY: f64 = 0.5;
|
||||||
|
pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||||
|
pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||||
|
const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff);
|
||||||
|
const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc);
|
||||||
|
pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3;
|
||||||
|
|
||||||
|
pub(crate) static CONNECTOR_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z"));
|
||||||
|
pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z"));
|
||||||
|
pub(crate) static STACK_INPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z"));
|
||||||
|
pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||||
|
parsed(
|
||||||
|
"M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\
|
||||||
|
M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
pub(crate) static STACK_INPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||||
|
parsed(
|
||||||
|
"M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\
|
||||||
|
M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z",
|
||||||
|
)
|
||||||
|
});
|
||||||
|
|
||||||
|
fn parsed(path_data: &str) -> BezPath {
|
||||||
|
BezPath::from_svg(path_data).expect("A connector outline is valid path data")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] {
|
||||||
|
let colors = match data_type {
|
||||||
|
DataType::General => [0xcfcfcf, 0x8a8a8a],
|
||||||
|
DataType::Number => [0xc9a699, 0x886b60],
|
||||||
|
DataType::Artboard => [0xfbf9eb, 0xb9b9a9],
|
||||||
|
DataType::Graphic => [0x68c587, 0x37754c],
|
||||||
|
DataType::Raster => [0xe4bb72, 0x9a7b43],
|
||||||
|
DataType::Vector => [0x65bbe5, 0x417892],
|
||||||
|
DataType::Color => [0xce6ea7, 0x924071],
|
||||||
|
DataType::Gradient => [0xaf81eb, 0x6c489b],
|
||||||
|
DataType::Typography => [0xeea7a7, 0x955252],
|
||||||
|
DataType::Invalid => [0xd6536e, 0xa7324a],
|
||||||
|
};
|
||||||
|
colors.map(|color| {
|
||||||
|
let [_, red, green, blue] = u32::to_be_bytes(color);
|
||||||
|
SRGBA8::new_opaque(red, green, blue)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector, highlight: Highlight) -> List<Vector> {
|
||||||
|
drawn_connector(outline, top_left, connector.data_type, connector.connected, highlight)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List<Vector> {
|
||||||
|
let [bright, dim] = data_type_colors(data_type);
|
||||||
|
match highlight {
|
||||||
|
Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })),
|
||||||
|
Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)),
|
||||||
|
Highlight::Hovered | Highlight::WireTarget => {
|
||||||
|
let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone();
|
||||||
|
let grown = Vector::item_from_bezpath(&grown);
|
||||||
|
let ring = Stroke {
|
||||||
|
join: StrokeJoin::Round,
|
||||||
|
..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE)
|
||||||
|
};
|
||||||
|
List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item<Vector> {
|
||||||
|
let mut outline = Vector::item_from_bezpath(outline);
|
||||||
|
outline.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||||
|
painted(outline, Coverage::new_fill(), color.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item<Vector> {
|
||||||
|
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
|
||||||
|
let Some(icon) = icons::icon(name, current) else { return List::new() };
|
||||||
|
let mut graphic = icon.shapes;
|
||||||
|
if icon.overflows {
|
||||||
|
let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]);
|
||||||
|
stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above);
|
||||||
|
graphic = List::new_from_item(clip);
|
||||||
|
}
|
||||||
|
graphic.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn text(outline: &List<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
|
||||||
|
let glyphs = outline.clone().into_iter();
|
||||||
|
let mut glyphs: List<Vector> = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect();
|
||||||
|
glyphs.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||||
|
glyphs
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List<Vector> {
|
||||||
|
let mut dark = BezPath::new();
|
||||||
|
let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2();
|
||||||
|
for (column, row) in (0..cells.y)
|
||||||
|
.flat_map(|row| (0..cells.x).map(move |column| (column, row)))
|
||||||
|
.filter(|(column, row)| (column + row) % 2 == 1)
|
||||||
|
{
|
||||||
|
let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL;
|
||||||
|
let cell_max = (cell_min + CHECKER_CELL).min(max);
|
||||||
|
dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.));
|
||||||
|
}
|
||||||
|
let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into());
|
||||||
|
List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn painted(mut item: Item<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
|
||||||
|
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
|
||||||
|
item
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn image(content: Graphic, unit_square_to_place: DAffine2) -> Item<Vector> {
|
||||||
|
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
|
||||||
|
image.left_apply_transform(&unit_square_to_place);
|
||||||
|
stamp_coverage(&mut image, Coverage::new_fill(), content, CoverPlacement::Above);
|
||||||
|
image
|
||||||
|
}
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
use crate::GraphUiConfig;
|
||||||
|
use crate::inputs::{self, TaggedGraphUiValue, Thumbnails};
|
||||||
|
use crate::nodes::{
|
||||||
|
draw_backdrop, draw_box_selection, draw_cards, draw_dots, draw_errors, draw_grid, draw_highlights, draw_layers, draw_loose_wires, draw_moving, draw_network_connectors, draw_raised,
|
||||||
|
draw_reorder_bar, draw_thick_wires, draw_thumbnails, draw_wires, texture_layer,
|
||||||
|
};
|
||||||
|
use crate::scene::GraphUiScene;
|
||||||
|
use core_types::registry::{FieldMetadata, NODE_METADATA, RegistryValueSource};
|
||||||
|
use core_types::transform::Footprint;
|
||||||
|
use core_types::{ContextFeatures, NodeCompileMetadata, ProtoNodeIdentifier};
|
||||||
|
use glam::DAffine2;
|
||||||
|
use graph_craft::document::value::TaggedValue;
|
||||||
|
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||||
|
use graphene_std::application_io::{ExportFormat, RenderConfig};
|
||||||
|
use graphene_std::graphic::extend;
|
||||||
|
use graphene_std::ops::passthrough;
|
||||||
|
use graphene_std::platform_application_io::wgpu_executor;
|
||||||
|
use graphene_std::render_cache::render_output_cache;
|
||||||
|
use graphene_std::render_node::{create_context, render, render_intermediate};
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub fn network(scene: &GraphUiScene, config: &GraphUiConfig, thumbnails: &Thumbnails) -> NodeNetwork {
|
||||||
|
let layers = scene.settled().layers.iter().chain(&scene.moving().layers);
|
||||||
|
let layer_thumbnails = layers.filter_map(|layer| Some((layer.look.key, thumbnails.get(&layer.look.key)?.clone())));
|
||||||
|
let values = [
|
||||||
|
(inputs::SETTLED, TaggedGraphUiValue::Rows(scene.settled().clone())),
|
||||||
|
(inputs::MOVING, TaggedGraphUiValue::Rows(scene.moving().clone())),
|
||||||
|
(inputs::NETWORK_CONNECTORS, TaggedGraphUiValue::NetworkConnectors(scene.network_connectors().clone())),
|
||||||
|
(inputs::ERRORS, TaggedGraphUiValue::Errors(scene.errors().clone())),
|
||||||
|
(inputs::THUMBNAILS, TaggedGraphUiValue::Thumbnails(Arc::new(layer_thumbnails.collect()))),
|
||||||
|
(inputs::WIRE_IN_PROGRESS, TaggedGraphUiValue::WireInProgress(config.wire_in_progress)),
|
||||||
|
(inputs::REORDER_BAR, TaggedGraphUiValue::ReorderBar(config.reorder_bar)),
|
||||||
|
(inputs::BOX_SELECTION, TaggedGraphUiValue::BoxSelection(config.box_selection)),
|
||||||
|
(inputs::FADE_ARTWORK, TaggedGraphUiValue::FadeArtwork(config.fade_artwork)),
|
||||||
|
(inputs::WIRE_STYLE, TaggedGraphUiValue::WireStyle(config.wire_style)),
|
||||||
|
(inputs::HIGHLIGHTS, TaggedGraphUiValue::Highlights(config.highlights)),
|
||||||
|
];
|
||||||
|
|
||||||
|
let mut network = NodeNetwork::default();
|
||||||
|
for (scope, value) in values {
|
||||||
|
let ty = value.ty();
|
||||||
|
let id = add(&mut network, node(passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::GraphUi(value), false)]));
|
||||||
|
network.scope_injections.insert(scope.as_str().to_string(), (id, ty));
|
||||||
|
}
|
||||||
|
|
||||||
|
let [backdrop, above @ ..] = [
|
||||||
|
drawn(&mut network, draw_backdrop::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_grid::IDENTIFIER),
|
||||||
|
tiled(&mut network, draw_thick_wires::IDENTIFIER, [draw_layers::IDENTIFIER]),
|
||||||
|
drawn(&mut network, draw_thumbnails::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_loose_wires::IDENTIFIER),
|
||||||
|
tiled(&mut network, draw_wires::IDENTIFIER, [draw_cards::IDENTIFIER, draw_dots::IDENTIFIER, draw_raised::IDENTIFIER]),
|
||||||
|
drawn(&mut network, draw_moving::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_errors::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_network_connectors::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_highlights::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_reorder_bar::IDENTIFIER),
|
||||||
|
drawn(&mut network, draw_box_selection::IDENTIFIER),
|
||||||
|
];
|
||||||
|
let stack = stacked(&mut network, backdrop, above);
|
||||||
|
let frame = rendered(&mut network, stack);
|
||||||
|
// INDEX is never read; it forces a nullification and cache pair onto the render's wire, so its memo keys on the footprint and the render params only
|
||||||
|
let compile_metadata = Some(NodeCompileMetadata {
|
||||||
|
extract: ContextFeatures::VARARGS | ContextFeatures::INDEX,
|
||||||
|
inject: ContextFeatures::REAL_TIME | ContextFeatures::ANIMATION_TIME | ContextFeatures::POINTER_POSITION | ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let create_context = DocumentNode {
|
||||||
|
compile_metadata,
|
||||||
|
..node(create_context::IDENTIFIER, vec![NodeInput::node(frame, 0)])
|
||||||
|
};
|
||||||
|
let output = add(&mut network, create_context);
|
||||||
|
network.exports.push(NodeInput::node(output, 0));
|
||||||
|
network
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render_config(view: DAffine2, request: RenderConfig) -> RenderConfig {
|
||||||
|
let translation = (view.translation * request.scale).round() / request.scale;
|
||||||
|
let viewport = Footprint {
|
||||||
|
transform: DAffine2 { translation, ..view },
|
||||||
|
resolution: request.viewport.resolution,
|
||||||
|
..Default::default()
|
||||||
|
};
|
||||||
|
RenderConfig {
|
||||||
|
viewport,
|
||||||
|
scale: request.scale,
|
||||||
|
time: request.time,
|
||||||
|
export_format: ExportFormat::Raster,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||||
|
DocumentNode {
|
||||||
|
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||||
|
inputs,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add(network: &mut NodeNetwork, node: DocumentNode) -> NodeId {
|
||||||
|
let id = NodeId(u64::MAX - network.nodes.len() as u64);
|
||||||
|
network.nodes.insert(id, node);
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drawn(network: &mut NodeNetwork, identifier: ProtoNodeIdentifier) -> NodeId {
|
||||||
|
let scope = |field: &FieldMetadata| match &field.value_source {
|
||||||
|
RegistryValueSource::Scope(scope) => Ok(NodeInput::scope(*scope)),
|
||||||
|
source => Err(format!("The parameter {} of the drawing node {identifier} of the node graph reads {source:?}, not a scope", field.name)),
|
||||||
|
};
|
||||||
|
let scopes = NODE_METADATA
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get(&identifier)
|
||||||
|
.map(|metadata| metadata.fields.iter().map(scope).collect::<Result<Vec<_>, _>>());
|
||||||
|
let scopes = scopes.unwrap_or_else(|| panic!("The drawing node {identifier} of the node graph is not registered"));
|
||||||
|
let scopes = scopes.unwrap_or_else(|not_a_scope| panic!("{not_a_scope}"));
|
||||||
|
add(network, node(identifier, scopes))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stacked(network: &mut NodeNetwork, bottom: NodeId, above: impl IntoIterator<Item = NodeId>) -> NodeId {
|
||||||
|
let over = |below, layer| add(network, node(extend::IDENTIFIER, vec![NodeInput::node(below, 0), NodeInput::node(layer, 0)]));
|
||||||
|
above.into_iter().fold(bottom, over)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rendered(network: &mut NodeNetwork, content: NodeId) -> NodeId {
|
||||||
|
let intermediate = add(network, node(render_intermediate::IDENTIFIER, vec![NodeInput::node(content, 0)]));
|
||||||
|
let inputs = vec![
|
||||||
|
NodeInput::node(intermediate, 0),
|
||||||
|
NodeInput::scope(wgpu_executor::IDENTIFIER),
|
||||||
|
NodeInput::scope("runtime"),
|
||||||
|
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
|
||||||
|
];
|
||||||
|
add(network, node(render::IDENTIFIER, inputs))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tiled(network: &mut NodeNetwork, first: ProtoNodeIdentifier, rest: impl IntoIterator<Item = ProtoNodeIdentifier>) -> NodeId {
|
||||||
|
let bottom = drawn(network, first);
|
||||||
|
let above: Vec<NodeId> = rest.into_iter().map(|identifier| drawn(network, identifier)).collect();
|
||||||
|
let bands = stacked(network, bottom, above);
|
||||||
|
let region = rendered(network, bands);
|
||||||
|
// The cache's signature names the time and the pointer, which would put both into its key; it reads only the footprint and the render params
|
||||||
|
let compile_metadata = Some(NodeCompileMetadata {
|
||||||
|
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
|
||||||
|
inject: ContextFeatures::VARARGS,
|
||||||
|
..Default::default()
|
||||||
|
});
|
||||||
|
let cache = DocumentNode {
|
||||||
|
compile_metadata,
|
||||||
|
..node(render_output_cache::IDENTIFIER, vec![NodeInput::node(region, 0), NodeInput::scope(wgpu_executor::IDENTIFIER)])
|
||||||
|
};
|
||||||
|
let cached = add(network, cache);
|
||||||
|
add(network, node(texture_layer::IDENTIFIER, vec![NodeInput::node(cached, 0)]))
|
||||||
|
}
|
||||||
@@ -0,0 +1,627 @@
|
|||||||
|
use crate::card::{Card, Connector, DataType, Selection};
|
||||||
|
use crate::dashes::{border, dashed};
|
||||||
|
use crate::dot::Dot;
|
||||||
|
use crate::error_badge::{self, ErrorBadge};
|
||||||
|
use crate::geometry::{WireEnd, is_thick_wire, node_geometry, wire_ends};
|
||||||
|
use crate::highlights::{ConnectorKey, Highlight, Highlights};
|
||||||
|
use crate::inputs::{self, Thumbnails};
|
||||||
|
use crate::layer::{Layer, LayerButton};
|
||||||
|
use crate::look::{
|
||||||
|
BACKDROP, BORDER, BOX_SELECTION, BOX_SELECTION_FILL_OPACITY, CARD_OPACITY, CIRCLE_TOLERANCE, CONNECTOR_OUTLINE, DISABLED_ICON, ERROR_OPACITY, ERROR_RED, ERROR_TEXT, GRID_DOT_OPACITY, HIDDEN_CARD,
|
||||||
|
HIDDEN_TEXT, HOVERED_BUTTON, LAYER_IN_ACTIVE_SELECTION, LAYER_IN_INACTIVE_SELECTION, PREVIEWED_BORDER, SELECTED_DOT_RING_OPACITY, SEPARATOR, STACK_INPUT_OUTLINE, STACK_INPUT_WIRE_END,
|
||||||
|
STACK_OUTPUT_OUTLINE, STACK_OUTPUT_WIRE_END, TEXT, THUMBNAIL_BACKGROUND, WIRE_SPLIT, checkerboard, connector, data_type_colors, drawn_connector, icon, image, outlined, painted, rounded_rect,
|
||||||
|
text,
|
||||||
|
};
|
||||||
|
use crate::metrics::{
|
||||||
|
BORDER_WIDTH, CARD_ICON_LEFT, CARD_NAME_LEFT, CARD_NAME_MAX_WIDTH, CARD_RADIUS, CARD_ROW_PADDING, CONNECTOR_GAP, CONNECTOR_SIZE, DOT_HOVERED_RING, DOT_OUTPUT_ARROW, DOT_PREVIEWED_RING_OFFSET,
|
||||||
|
DOT_RADIUS, DOT_SELECTED_RING, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_RADIUS, GRID_COLLAPSE_SPACING, GRID_SIZE, HOVERED_CONNECTOR_SCALE, ICON_SIZE, LAYER_BUTTON_RADIUS, LAYER_BUTTON_SIZE,
|
||||||
|
LAYER_GRIP_DOT_COUNT, LAYER_GRIP_DOT_RADIUS, LAYER_GRIP_DOT_SPACING, LAYER_GRIP_DOTS, LAYER_RADIUS, LAYER_THUMBNAIL_GAP, LAYER_THUMBNAIL_RADIUS, LIST_WIRE_WIDTH, THICK_WIRE_WIDTH, WIRE_DASHES,
|
||||||
|
WIRE_WIDTH,
|
||||||
|
};
|
||||||
|
use crate::network_connector::{self, NetworkConnector, NetworkConnectorKey, NetworkConnectorKind};
|
||||||
|
use crate::placed::Placed;
|
||||||
|
use crate::replicated_map::ReplicatedMap;
|
||||||
|
use crate::router::{build_thick_wire_center_line, route};
|
||||||
|
use crate::scene::Rows;
|
||||||
|
use crate::text::{Labels, error_text_size, paragraph_outline};
|
||||||
|
use crate::wire::{InputKey, OutputKey, Wire, WireInProgress, WireKey, WireStyle};
|
||||||
|
use core_types::color::SRGBA8;
|
||||||
|
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List};
|
||||||
|
use core_types::transform::ApplyTransform;
|
||||||
|
use core_types::{Color, Ctx, ExtractFootprint, ExtractVarArgs, Poll};
|
||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||||
|
use graphic_types::raster_types::Raster;
|
||||||
|
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||||
|
use rendering::RenderParams;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
use text_nodes::TextToVectorError;
|
||||||
|
use vector_types::vector::style::Stroke;
|
||||||
|
use vector_types::{Gradient, GradientInterpolation, GradientSpread, GradientStop};
|
||||||
|
use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten};
|
||||||
|
|
||||||
|
const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.;
|
||||||
|
const WIRE_FLATTENING_TOLERANCE: f64 = 0.02;
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn draw_backdrop(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::FADE_ARTWORK)] fade_artwork: Item<f64>) -> List<Vector> {
|
||||||
|
let (view, scale) = view_and_device_scale(&ctx);
|
||||||
|
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
|
||||||
|
let opacity = fade_artwork.into_element() as f32;
|
||||||
|
let mut backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
|
||||||
|
backdrop.left_apply_transform(&view.inverse());
|
||||||
|
List::new_from_item(backdrop)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn view_and_device_scale(ctx: &(impl ExtractFootprint + ExtractVarArgs)) -> (DAffine2, f64) {
|
||||||
|
let render_params: Option<&RenderParams> = ctx.vararg(0).ok().and_then(|render_params| render_params.downcast_ref());
|
||||||
|
let scale = render_params.expect("The render params are the first vararg").scale;
|
||||||
|
(DAffine2::from_scale(DVec2::splat(1. / scale)) * ctx.footprint().transform, scale)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn draw_grid(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs) -> List<Vector> {
|
||||||
|
let (view, scale) = view_and_device_scale(&ctx);
|
||||||
|
let viewport_size = ctx.footprint().resolution.as_dvec2() / scale;
|
||||||
|
let mut dots = grid_dots(view, viewport_size, scale);
|
||||||
|
dots.left_apply_transform(&view.inverse());
|
||||||
|
dots
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List<Vector> {
|
||||||
|
let zoom = view.matrix2.x_axis.length();
|
||||||
|
let mut spacing = zoom * GRID_SIZE;
|
||||||
|
if !spacing.is_finite() || spacing <= 0. {
|
||||||
|
return List::new();
|
||||||
|
}
|
||||||
|
while spacing < GRID_COLLAPSE_SPACING {
|
||||||
|
spacing *= 2.;
|
||||||
|
}
|
||||||
|
let radius = ((1. + (zoom - 0.5 + 0.001).floor() / 2.) * scale).ceil() as u32;
|
||||||
|
let period = spacing * scale;
|
||||||
|
let origin = (view.translation * scale - radius as f64).rem_euclid(DVec2::splat(period)) - period - GRID_DOT_ROUNDING_BIAS;
|
||||||
|
|
||||||
|
let dot_color = Color::WHITE.with_alpha(GRID_DOT_OPACITY);
|
||||||
|
let stop = |column: u32, color| GradientStop {
|
||||||
|
position: column as f64 / period,
|
||||||
|
midpoint: 0.5,
|
||||||
|
color,
|
||||||
|
};
|
||||||
|
let mut dots = List::new();
|
||||||
|
for ([top, bottom], runs) in disc_columns(radius) {
|
||||||
|
let mut bands = BezPath::new();
|
||||||
|
for row in 0..=((viewport_size.y * scale - origin.y) / period).ceil() as u32 {
|
||||||
|
let y = (origin.y + row as f64 * period).round();
|
||||||
|
bands.extend(Rect::new(0., (y + top as f64) / scale, viewport_size.x, (y + bottom as f64) / scale).path_elements(0.));
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = runs[0][0];
|
||||||
|
let stops = runs.iter().flat_map(|&[left, right]| [stop(left - start, dot_color), stop(right - start, Color::TRANSPARENT)]);
|
||||||
|
let mut columns = Item::new_from_element(Gradient::new(stops));
|
||||||
|
columns.set_attribute(ATTR_GRADIENT_SPREAD, GradientSpread::Repeat);
|
||||||
|
columns.set_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped);
|
||||||
|
columns.left_apply_transform(&DAffine2::from_scale_angle_translation(DVec2::splat(spacing), 0., DVec2::new((origin.x + start as f64) / scale, 0.)));
|
||||||
|
|
||||||
|
let mut group = Vector::item_from_bezpath(&bands);
|
||||||
|
stamp_coverage(&mut group, Coverage::new_fill(), Graphic::Gradient(columns), CoverPlacement::Above);
|
||||||
|
dots.push(group);
|
||||||
|
}
|
||||||
|
dots
|
||||||
|
}
|
||||||
|
|
||||||
|
fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> {
|
||||||
|
let lit = |column: u32, row: u32| (DVec2::new(column as f64, row as f64) + 0.5 - radius as f64).length() < radius as f64;
|
||||||
|
let mut runs_by_rows = BTreeMap::<[u32; 2], Vec<[u32; 2]>>::new();
|
||||||
|
for column in 0..2 * radius {
|
||||||
|
let top = (0..radius).take_while(|&row| !lit(column, row)).count() as u32;
|
||||||
|
let runs = runs_by_rows.entry([top, 2 * radius - top]).or_default();
|
||||||
|
match runs.last_mut() {
|
||||||
|
Some(run) if run[1] == column => run[1] += 1,
|
||||||
|
_ => runs.push([column, column + 1]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
runs_by_rows
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_layers(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
layers(rows.element())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layers(rows: &Rows) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut labels = Labels::default();
|
||||||
|
let mut graphic = List::new();
|
||||||
|
for layer in &rows.layers {
|
||||||
|
graphic.extend(draw_layer(layer, &mut labels)?);
|
||||||
|
}
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_layer(layer: &Placed<Layer>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut graphic = List::new();
|
||||||
|
let [min, max] = layer.body();
|
||||||
|
let fill = match (layer.look.selection, layer.look.visible) {
|
||||||
|
(Selection::Active, _) => LAYER_IN_ACTIVE_SELECTION.into(),
|
||||||
|
(Selection::Inactive, _) => LAYER_IN_INACTIVE_SELECTION.into(),
|
||||||
|
(Selection::None, true) => Color::BLACK,
|
||||||
|
(Selection::None, false) => HIDDEN_CARD.into(),
|
||||||
|
};
|
||||||
|
graphic.push(painted(rounded_rect(min, max, [LAYER_RADIUS; 4]), Coverage::new_fill(), fill.with_alpha(CARD_OPACITY)));
|
||||||
|
|
||||||
|
if !layer.look.renaming {
|
||||||
|
let [name, name_end] = layer.name_box();
|
||||||
|
let text_color = if layer.look.visible { TEXT } else { HIDDEN_TEXT };
|
||||||
|
graphic.extend(text(&labels.label(&layer.look.name, name_end.x - name.x)?.outline, name, text_color));
|
||||||
|
}
|
||||||
|
|
||||||
|
let [thumbnail_min, thumbnail_max] = layer.thumbnail();
|
||||||
|
let thumbnail = rounded_rect(thumbnail_min, thumbnail_max, [LAYER_THUMBNAIL_RADIUS; 4]);
|
||||||
|
graphic.push(painted(thumbnail, Coverage::new_fill(), THUMBNAIL_BACKGROUND.into()));
|
||||||
|
let thumbnail_border = Vector::item_from_bezpath(&border(thumbnail_min, thumbnail_max, LAYER_THUMBNAIL_RADIUS, &[], false));
|
||||||
|
graphic.push(painted(thumbnail_border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BORDER.into()));
|
||||||
|
let [image_min, image_max] = layer.thumbnail_image();
|
||||||
|
graphic.extend(checkerboard(image_min, image_max));
|
||||||
|
|
||||||
|
if let Some(output) = &layer.look.primary_output {
|
||||||
|
graphic.extend(stack_output(layer, output, Highlight::None));
|
||||||
|
}
|
||||||
|
match &layer.look.primary_input {
|
||||||
|
Some(input) => graphic.extend(stack_input(layer, input, Highlight::None)),
|
||||||
|
None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])),
|
||||||
|
}
|
||||||
|
|
||||||
|
let [block_min, block_max] = layer.thumbnail_block();
|
||||||
|
let mut gaps = vec![[block_min - LAYER_THUMBNAIL_GAP, block_max + LAYER_THUMBNAIL_GAP], layer.visibility()];
|
||||||
|
gaps.extend(layer.left_input_wire().map(|wire| [wire - CONNECTOR_GAP / 2., wire + CONNECTOR_GAP / 2.]));
|
||||||
|
let border = Vector::item_from_bezpath(&border(min, max, LAYER_RADIUS, &gaps, layer.look.previewed));
|
||||||
|
let border_color = if layer.look.previewed { PREVIEWED_BORDER } else { BORDER };
|
||||||
|
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stack_output(layer: &Placed<Layer>, output: &Connector, highlight: Highlight) -> List<Vector> {
|
||||||
|
let mut graphic = connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output, highlight);
|
||||||
|
if output.connected && layer.look.primary_output_connected_to_layer && highlight != Highlight::WireSource {
|
||||||
|
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
|
||||||
|
}
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stack_input(layer: &Placed<Layer>, input: &Connector, highlight: Highlight) -> List<Vector> {
|
||||||
|
let mut graphic = connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input, highlight);
|
||||||
|
if input.connected && layer.look.primary_input_connected_to_layer && highlight != Highlight::WireSource {
|
||||||
|
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
|
||||||
|
}
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn draw_thumbnails(_: impl Ctx, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
|
||||||
|
layer_thumbnails(thumbnails.element(), rows.element())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_thumbnails(thumbnails: &Thumbnails, rows: &Rows) -> List<Vector> {
|
||||||
|
let thumbnails = thumbnails.iter().filter_map(|(key, thumbnail)| Some((rows.layers.get(key)?, thumbnail)));
|
||||||
|
thumbnails
|
||||||
|
.map(|(layer, thumbnail)| {
|
||||||
|
let [min, max] = layer.thumbnail_image();
|
||||||
|
image(thumbnail.clone(), DAffine2::from_scale_angle_translation(max - min, 0., min))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn texture_layer(ctx: impl Ctx + ExtractFootprint, rendered: Item<RenderOutput>) -> Poll<List<Vector>> {
|
||||||
|
let RenderOutputType::Texture(texture) = rendered.into_element().data else {
|
||||||
|
return Poll::error("A layer of the node graph was not rendered into a texture");
|
||||||
|
};
|
||||||
|
let footprint = ctx.footprint();
|
||||||
|
let viewport = footprint.transform.inverse() * DAffine2::from_scale(footprint.resolution.as_dvec2());
|
||||||
|
let texture = Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)));
|
||||||
|
Poll::Final(List::new_from_item(image(texture, viewport)))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_raised(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
|
||||||
|
raised(rows.element())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn raised(rows: &Rows) -> List<Vector> {
|
||||||
|
let raised_parts_of_layers = rows.layers.iter().flat_map(draw_raised_parts_of_layer);
|
||||||
|
raised_parts_of_layers.chain(rows.cards.iter().flat_map(draw_connectors_of_card)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_raised_parts_of_layer(layer: &Placed<Layer>) -> List<Vector> {
|
||||||
|
let mut graphic = List::new();
|
||||||
|
if let Some(input) = &layer.look.secondary_input {
|
||||||
|
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, Highlight::None));
|
||||||
|
}
|
||||||
|
graphic.extend(grip(layer, false));
|
||||||
|
for (_, place, icons) in layer_buttons(layer) {
|
||||||
|
graphic.extend(layer_button(layer, place, icons, false, false));
|
||||||
|
}
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grip(layer: &Placed<Layer>, hovered: bool) -> List<Vector> {
|
||||||
|
let grip_color = match (hovered, layer.look.selection != Selection::None) {
|
||||||
|
(true, _) => Some(Color::WHITE),
|
||||||
|
(false, true) => Some(TEXT.into()),
|
||||||
|
(false, false) => None,
|
||||||
|
};
|
||||||
|
let Some(grip_color) = grip_color else { return List::new() };
|
||||||
|
let [grip, _] = layer.grip();
|
||||||
|
let mut dots = BezPath::new();
|
||||||
|
let [columns, rows] = LAYER_GRIP_DOT_COUNT;
|
||||||
|
for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) {
|
||||||
|
let center = grip + LAYER_GRIP_DOTS + DVec2::new(column as f64, row as f64) * LAYER_GRIP_DOT_SPACING;
|
||||||
|
dots.extend(Circle::new((center.x, center.y), LAYER_GRIP_DOT_RADIUS).path_elements(CIRCLE_TOLERANCE));
|
||||||
|
}
|
||||||
|
List::new_from_item(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_buttons(layer: &Placed<Layer>) -> impl Iterator<Item = (LayerButton, [DVec2; 2], [&'static str; 2])> {
|
||||||
|
let lock = layer.lock().map(|lock| (LayerButton::Lock, lock, ["PadlockLocked", "PadlockUnlocked"]));
|
||||||
|
let eye = if layer.look.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
|
||||||
|
lock.into_iter().chain([(LayerButton::Visibility, layer.visibility(), eye)])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_button(layer: &Placed<Layer>, [min, max]: [DVec2; 2], [resting, hover]: [&str; 2], hovered: bool, clicked: bool) -> List<Vector> {
|
||||||
|
let mut graphic = List::new();
|
||||||
|
if hovered {
|
||||||
|
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
|
||||||
|
}
|
||||||
|
let name = if hovered && !clicked { hover } else { resting };
|
||||||
|
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.look.read_only { DISABLED_ICON } else { TEXT }));
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_connectors_of_card(card: &Placed<Card>) -> List<Vector> {
|
||||||
|
card.inputs()
|
||||||
|
.chain(card.outputs())
|
||||||
|
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output, Highlight::None))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_thick_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
|
||||||
|
settled_wires(rows.element(), wire_style.into_element(), true)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_wires(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>, #[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>) -> List<Vector> {
|
||||||
|
settled_wires(rows.element(), wire_style.into_element(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn settled_wires(rows: &Rows, wire_style: WireStyle, thick: bool) -> List<Vector> {
|
||||||
|
let settled = [rows];
|
||||||
|
let no_imports_or_exports = ReplicatedMap::default();
|
||||||
|
let wires = wires_with_ends(&rows.wires, &settled, &no_imports_or_exports).filter(|(_, ends)| is_thick_wire(*ends) == thick);
|
||||||
|
wires.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_loose_wires(
|
||||||
|
_: impl Ctx,
|
||||||
|
#[scope(inputs::MOVING)] moving: Item<Rows>,
|
||||||
|
#[scope(inputs::SETTLED)] settled: Item<Rows>,
|
||||||
|
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
|
||||||
|
#[scope(inputs::WIRE_IN_PROGRESS)] wire_in_progress: Item<Option<WireInProgress>>,
|
||||||
|
#[scope(inputs::WIRE_STYLE)] wire_style: Item<WireStyle>,
|
||||||
|
) -> List<Vector> {
|
||||||
|
let wire_style = wire_style.into_element();
|
||||||
|
let rows = [moving.element(), settled.element()];
|
||||||
|
let loose = wires_with_ends(&moving.element().wires, &rows, network_connectors.element());
|
||||||
|
let mut graphic = wire_in_progress.into_element().map_or_else(List::new, draw_wire_in_progress);
|
||||||
|
graphic.extend(loose.flat_map(|(wire, ends)| draw_wire(wire, ends, wire_style)).collect());
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wires_with_ends<'a>(wires: &'a ReplicatedMap<Wire>, rows: &'a [&'a Rows], network_connectors: &'a ReplicatedMap<NetworkConnector>) -> impl Iterator<Item = (&'a Wire, [WireEnd; 2])> {
|
||||||
|
wires.iter().filter_map(move |wire| Some((wire, wire_ends(wire, rows, network_connectors)?)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_wire(wire: &Wire, ends: [WireEnd; 2], wire_style: WireStyle) -> List<Vector> {
|
||||||
|
let [bright, dim] = data_type_colors(wire.data_type);
|
||||||
|
let previewed = wire.key == WireKey::Preview;
|
||||||
|
let color = if previewed || wire.insertion_target { bright } else { dim };
|
||||||
|
let stroke = |path: &BezPath, width: f64, color: SRGBA8| painted(Vector::item_from_bezpath(path), Coverage::new_stroke(&Stroke::new(width)), color.into());
|
||||||
|
let drawn = |path: &BezPath| if previewed { flattened(&dashed(path, WIRE_DASHES)) } else { flattened(path) };
|
||||||
|
let path = drawn(&route(ends, wire_style));
|
||||||
|
if is_thick_wire(ends) {
|
||||||
|
let center_line = build_thick_wire_center_line(ends, wire_style);
|
||||||
|
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(¢er_line), WIRE_WIDTH, WIRE_SPLIT)])
|
||||||
|
} else if wire.list {
|
||||||
|
List::from_iter([stroke(&path, LIST_WIRE_WIDTH, color), stroke(&path, WIRE_WIDTH, WIRE_SPLIT)])
|
||||||
|
} else {
|
||||||
|
List::new_from_item(stroke(&path, WIRE_WIDTH, color))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_wire_in_progress(wire: WireInProgress) -> List<Vector> {
|
||||||
|
let path = route(wire.ends, WireStyle::Direct);
|
||||||
|
if path.elements().len() != 4 {
|
||||||
|
return List::new();
|
||||||
|
}
|
||||||
|
let [_, dim] = data_type_colors(wire.data_type);
|
||||||
|
let path = flattened(&path);
|
||||||
|
List::new_from_item(painted(Vector::item_from_bezpath(&path), Coverage::new_stroke(&Stroke::new(WIRE_WIDTH)), dim.into()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flattened(path: &BezPath) -> BezPath {
|
||||||
|
let mut lines = BezPath::new();
|
||||||
|
flatten(path, WIRE_FLATTENING_TOLERANCE, |element| lines.push(element));
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_cards(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
cards(rows.element())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cards(rows: &Rows) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut labels = Labels::default();
|
||||||
|
let mut graphic = List::new();
|
||||||
|
for card in &rows.cards {
|
||||||
|
graphic.extend(draw_card(card, &mut labels)?);
|
||||||
|
}
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_card(card: &Placed<Card>, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut graphic = List::new();
|
||||||
|
let [min, max] = card.body();
|
||||||
|
|
||||||
|
let (card_color, text_color) = if card.look.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
|
||||||
|
let body = rounded_rect(min, max, [CARD_RADIUS; 4]);
|
||||||
|
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
|
||||||
|
|
||||||
|
let (header_tint, rows_tint) = match card.look.selection {
|
||||||
|
Selection::None => (0.05, 0.),
|
||||||
|
Selection::Inactive => (0.15, 0.1),
|
||||||
|
Selection::Active => (0.2, 0.15),
|
||||||
|
};
|
||||||
|
let header_bottom = if card.rows() == 1 { CARD_RADIUS } else { 0. };
|
||||||
|
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [CARD_RADIUS, CARD_RADIUS, header_bottom, header_bottom]);
|
||||||
|
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
|
||||||
|
if card.look.selection != Selection::None && card.rows() > 1 {
|
||||||
|
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., CARD_RADIUS, CARD_RADIUS]);
|
||||||
|
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
|
||||||
|
}
|
||||||
|
graphic.extend(icon(card.look.icon, min + DVec2::new(CARD_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
|
||||||
|
let name = labels.label(&card.look.name, CARD_NAME_MAX_WIDTH)?;
|
||||||
|
graphic.extend(text(&name.outline, min + DVec2::new(CARD_NAME_LEFT, 0.), text_color));
|
||||||
|
|
||||||
|
let width = max.x - min.x;
|
||||||
|
for row in 1..card.rows() as usize {
|
||||||
|
let (input, output) = (card.look.secondary_inputs.get(row - 1), card.look.secondary_outputs.get(row - 1));
|
||||||
|
let Some(connector) = input.or(output) else { continue };
|
||||||
|
let name = labels.label(&connector.name, width - 2. * CARD_ROW_PADDING)?;
|
||||||
|
let left = if input.is_some() { CARD_ROW_PADDING } else { width - CARD_ROW_PADDING - name.width };
|
||||||
|
graphic.extend(text(&name.outline, min + DVec2::new(left, row as f64 * GRID_SIZE), text_color));
|
||||||
|
}
|
||||||
|
|
||||||
|
let border_color = if card.look.previewed { PREVIEWED_BORDER } else { BORDER };
|
||||||
|
let gap = |edge: f64, (top_left, _): (DVec2, &Connector)| {
|
||||||
|
let center = DVec2::new(edge, top_left.y + CONNECTOR_SIZE / 2.);
|
||||||
|
[center - CONNECTOR_GAP / 2., center + CONNECTOR_GAP / 2.]
|
||||||
|
};
|
||||||
|
let gaps: Vec<[DVec2; 2]> = card.inputs().map(|input| gap(min.x, input)).chain(card.outputs().map(|output| gap(max.x, output))).collect();
|
||||||
|
let border = Vector::item_from_bezpath(&border(min, max, CARD_RADIUS, &gaps, card.look.previewed));
|
||||||
|
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_dots(_: impl Ctx, #[scope(inputs::SETTLED)] rows: Item<Rows>) -> List<Vector> {
|
||||||
|
dots(rows.element())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dots(rows: &Rows) -> List<Vector> {
|
||||||
|
rows.dots.iter().flat_map(|dot| draw_dot(dot, [Highlight::None; 2])).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_moving(_: impl Ctx, #[scope(inputs::MOVING)] moving: Item<Rows>, #[scope(inputs::THUMBNAILS)] thumbnails: Item<Thumbnails>) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let moving = moving.element();
|
||||||
|
let mut graphic = layers(moving)?;
|
||||||
|
graphic.extend(layer_thumbnails(thumbnails.element(), moving));
|
||||||
|
graphic.extend(cards(moving)?);
|
||||||
|
graphic.extend(dots(moving));
|
||||||
|
graphic.extend(raised(moving));
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_dot(dot: &Placed<Dot>, [highlight, output_highlight]: [Highlight; 2]) -> List<Vector> {
|
||||||
|
let [wired, unwired] = data_type_colors(dot.look.data_type);
|
||||||
|
let center = dot.center();
|
||||||
|
let grown = matches!(highlight, Highlight::Hovered | Highlight::WireTarget);
|
||||||
|
let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. };
|
||||||
|
let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE));
|
||||||
|
let output_shown = output_highlight != Highlight::None;
|
||||||
|
let fill = if dot.look.wired && !output_shown { wired } else { unwired };
|
||||||
|
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
|
||||||
|
let resting = [highlight, output_highlight] == [Highlight::None; 2];
|
||||||
|
|
||||||
|
if grown {
|
||||||
|
let offset = if dot.look.previewed { DOT_PREVIEWED_RING_OFFSET } else { 0. };
|
||||||
|
let ring = circle(DOT_RADIUS + offset + DOT_HOVERED_RING / 2.);
|
||||||
|
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_HOVERED_RING * scale)), unwired.into()));
|
||||||
|
} else if resting && dot.look.previewed {
|
||||||
|
let radius = DOT_RADIUS + DOT_PREVIEWED_RING_OFFSET + BORDER_WIDTH;
|
||||||
|
let ring = Vector::item_from_bezpath(&border(center - radius, center + radius, radius, &[], true));
|
||||||
|
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), wired.into()));
|
||||||
|
} else if resting && dot.look.selected {
|
||||||
|
let ring = circle(DOT_RADIUS + DOT_SELECTED_RING / 2.);
|
||||||
|
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_SELECTED_RING)), Color::WHITE.with_alpha(SELECTED_DOT_RING_OPACITY)));
|
||||||
|
}
|
||||||
|
|
||||||
|
if output_shown {
|
||||||
|
graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.look.data_type, true, output_highlight));
|
||||||
|
}
|
||||||
|
graphic
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_errors(
|
||||||
|
_: impl Ctx,
|
||||||
|
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
|
||||||
|
#[scope(inputs::MOVING)] moving: Item<Rows>,
|
||||||
|
#[scope(inputs::SETTLED)] settled: Item<Rows>,
|
||||||
|
) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let rows = [moving.element(), settled.element()];
|
||||||
|
badges_with_anchors(errors.element().iter(), rows).map(|(error, anchor)| draw_error(error, anchor, false)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn badges_with_anchors<'a>(errors: impl Iterator<Item = &'a ErrorBadge>, rows: [&'a Rows; 2]) -> impl Iterator<Item = (&'a ErrorBadge, DVec2)> {
|
||||||
|
errors.filter_map(move |error| Some((error, node_geometry(&rows, &error.key)?.error_badge_anchor())))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_error(error: &ErrorBadge, anchor: DVec2, hovered: bool) -> Result<Item<Vector>, TextToVectorError> {
|
||||||
|
let text_size = error_text_size(&error.text);
|
||||||
|
let [min, max] = error_badge::body(anchor, text_size);
|
||||||
|
let mut badge = List::new_from_item(painted(rounded_rect(min, max, [ERROR_RADIUS; 4]), Coverage::new_fill(), ERROR_RED.into()));
|
||||||
|
let corners = error_badge::tail(anchor);
|
||||||
|
let mut tail = BezPath::new();
|
||||||
|
tail.move_to((corners[0].x, corners[0].y));
|
||||||
|
for corner in &corners[1..] {
|
||||||
|
tail.line_to((corner.x, corner.y));
|
||||||
|
}
|
||||||
|
tail.close_path();
|
||||||
|
badge.push(painted(Vector::item_from_bezpath(&tail), Coverage::new_fill(), ERROR_RED.into()));
|
||||||
|
|
||||||
|
let outline = paragraph_outline(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
|
||||||
|
badge.extend(text(&outline, error_badge::text_top_left(anchor, text_size), ERROR_TEXT));
|
||||||
|
|
||||||
|
let mut grouped = rounded_rect(min, corners.into_iter().fold(max, DVec2::max), [0.; 4]);
|
||||||
|
stamp_coverage(&mut grouped, Coverage::new_fill(), Graphic::VectorList(badge), CoverPlacement::Above);
|
||||||
|
if !hovered {
|
||||||
|
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
|
||||||
|
}
|
||||||
|
Ok(grouped)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_network_connectors(_: impl Ctx, #[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut labels = Labels::default();
|
||||||
|
let mut graphic = List::new();
|
||||||
|
for row in network_connectors.element() {
|
||||||
|
graphic.extend(draw_network_connector(row, &mut labels)?);
|
||||||
|
}
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let mut graphic = row_connector(row, Highlight::None);
|
||||||
|
let Some(entry) = &row.connector else { return Ok(graphic) };
|
||||||
|
let name = labels.label(&entry.name, f64::INFINITY)?;
|
||||||
|
if !row.renaming {
|
||||||
|
let [top_left, _] = row.name_box(name.width);
|
||||||
|
graphic.extend(text(&name.outline, top_left, TEXT));
|
||||||
|
}
|
||||||
|
if row.editable && row.key.index() < 2 {
|
||||||
|
let [min, max] = row.separator(name.width);
|
||||||
|
graphic.push(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), SEPARATOR.into()));
|
||||||
|
}
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_connector(row: &NetworkConnector, highlight: Highlight) -> List<Vector> {
|
||||||
|
match &row.connector {
|
||||||
|
Some(entry) => connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry, highlight),
|
||||||
|
None => drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, highlight),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient, memoize)]
|
||||||
|
fn draw_highlights(
|
||||||
|
_: impl Ctx,
|
||||||
|
#[scope(inputs::HIGHLIGHTS)] highlights: Item<Highlights>,
|
||||||
|
#[scope(inputs::MOVING)] moving: Item<Rows>,
|
||||||
|
#[scope(inputs::SETTLED)] settled: Item<Rows>,
|
||||||
|
#[scope(inputs::NETWORK_CONNECTORS)] network_connectors: Item<ReplicatedMap<NetworkConnector>>,
|
||||||
|
#[scope(inputs::ERRORS)] errors: Item<ReplicatedMap<ErrorBadge>>,
|
||||||
|
) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
let highlights = highlights.into_element();
|
||||||
|
let rows = [moving.element(), settled.element()];
|
||||||
|
let mut graphic = List::new();
|
||||||
|
for dot in rows.iter().flat_map(|rows| &rows.dots) {
|
||||||
|
let looks = highlights.dot(dot.look.key);
|
||||||
|
if looks != [Highlight::None; 2] {
|
||||||
|
graphic.extend(draw_dot(dot, looks));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let connectors: BTreeSet<ConnectorKey> = highlights.connectors().collect();
|
||||||
|
for key in connectors {
|
||||||
|
if let Some(drawn) = highlighted_connector(key, highlights.connector(key), rows, network_connectors.element()) {
|
||||||
|
graphic.extend(drawn);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for layer in rows.iter().flat_map(|rows| &rows.layers) {
|
||||||
|
match highlights.layer_button(layer.look.key) {
|
||||||
|
Some(LayerButton::Grip) => graphic.extend(grip(layer, true)),
|
||||||
|
Some(hovered) if !layer.look.read_only => {
|
||||||
|
for (_, place, icons) in layer_buttons(layer).filter(|(button, ..)| *button == hovered) {
|
||||||
|
graphic.extend(layer_button(layer, place, icons, true, highlights.clicked));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let hovered = errors.element().iter().filter(|error| highlights.badge_hovered(error.key));
|
||||||
|
for (error, anchor) in badges_with_anchors(hovered, rows) {
|
||||||
|
graphic.push(draw_error(error, anchor, true)?);
|
||||||
|
}
|
||||||
|
Ok(graphic)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn highlighted_connector(key: ConnectorKey, highlight: Highlight, rows: [&Rows; 2], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<List<Vector>> {
|
||||||
|
let card = |node| rows.into_iter().find_map(|rows| rows.cards.get(&node));
|
||||||
|
let layer = |node| rows.into_iter().find_map(|rows| rows.layers.get(&node));
|
||||||
|
let indexed = |index: usize| move |found: &&Connector| found.index as usize == index;
|
||||||
|
let on_card = |(top_left, found): (DVec2, &Connector)| connector(&CONNECTOR_OUTLINE, top_left, found, highlight);
|
||||||
|
match key {
|
||||||
|
ConnectorKey::Input(InputKey::Node { node, index }) => {
|
||||||
|
if let Some(card) = card(node) {
|
||||||
|
return card.inputs().find(|(_, input)| indexed(index)(input)).map(on_card);
|
||||||
|
}
|
||||||
|
let layer = layer(node)?;
|
||||||
|
if let Some(input) = layer.look.primary_input.as_ref().filter(indexed(index)) {
|
||||||
|
return Some(stack_input(layer, input, highlight));
|
||||||
|
}
|
||||||
|
let input = layer.look.secondary_input.as_ref().filter(indexed(index))?;
|
||||||
|
Some(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input, highlight))
|
||||||
|
}
|
||||||
|
ConnectorKey::Output(OutputKey::Node { node, index }) => {
|
||||||
|
if let Some(card) = card(node) {
|
||||||
|
return card.outputs().find(|(_, output)| indexed(index)(output)).map(on_card);
|
||||||
|
}
|
||||||
|
let layer = layer(node)?;
|
||||||
|
layer.look.primary_output.as_ref().filter(indexed(index)).map(|output| stack_output(layer, output, highlight))
|
||||||
|
}
|
||||||
|
ConnectorKey::Input(InputKey::Export(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Export(index))?, highlight)),
|
||||||
|
ConnectorKey::Output(OutputKey::Import(index)) => Some(row_connector(network_connectors.get(&NetworkConnectorKey::Import(index))?, highlight)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn draw_reorder_bar(_: impl Ctx, #[scope(inputs::REORDER_BAR)] reorder_bar: Item<Option<(NetworkConnectorKind, DVec2)>>) -> List<Vector> {
|
||||||
|
let Some((kind, anchor)) = reorder_bar.into_element() else { return List::new() };
|
||||||
|
let [min, max] = network_connector::reorder_bar(kind, anchor);
|
||||||
|
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[node_macro::node(transient)]
|
||||||
|
fn draw_box_selection(ctx: impl Ctx + ExtractFootprint + ExtractVarArgs, #[scope(inputs::BOX_SELECTION)] box_selection: Item<Option<[DVec2; 2]>>) -> List<Vector> {
|
||||||
|
let Some([start, end]) = box_selection.into_element() else { return List::new() };
|
||||||
|
let min = start.min(end);
|
||||||
|
let max = min + (end - start).abs() + 2. * BORDER_WIDTH;
|
||||||
|
let fill = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::from(BOX_SELECTION).with_alpha(BOX_SELECTION_FILL_OPACITY));
|
||||||
|
let [inner_min, inner_max] = [min + BORDER_WIDTH / 2., max - BORDER_WIDTH / 2.];
|
||||||
|
let outline = Rect::new(inner_min.x, inner_min.y, inner_max.x, inner_max.y).to_path(0.);
|
||||||
|
let border = painted(Vector::item_from_bezpath(&outline), Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BOX_SELECTION.into());
|
||||||
|
let (view, _) = view_and_device_scale(&ctx);
|
||||||
|
let mut selection = List::from_iter([fill, border]);
|
||||||
|
selection.left_apply_transform(&view.inverse());
|
||||||
|
selection
|
||||||
|
}
|
||||||
@@ -0,0 +1,521 @@
|
|||||||
|
use crate::geometry::{WireEnd, is_thick_wire};
|
||||||
|
use crate::metrics::GRID_SIZE;
|
||||||
|
use crate::wire::WireStyle;
|
||||||
|
use glam::{DVec2, IVec2};
|
||||||
|
use graphene_std::vector::misc::dvec2_to_point;
|
||||||
|
use vello_gpu::kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||||
|
|
||||||
|
pub fn route(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
|
||||||
|
let [output_position, input_position] = ends.map(|end| end.position);
|
||||||
|
let [vertical_out, vertical_in] = ends.map(|end| end.vertical);
|
||||||
|
|
||||||
|
let (output_position, input_position) = if is_thick_wire(ends) {
|
||||||
|
if thick_wire_spans_single_cell(output_position, input_position) {
|
||||||
|
return BezPath::new();
|
||||||
|
}
|
||||||
|
let trim = 3. * (input_position.y - output_position.y).signum();
|
||||||
|
(output_position + DVec2::new(0., trim), input_position - DVec2::new(0., trim))
|
||||||
|
} else {
|
||||||
|
(output_position, input_position)
|
||||||
|
};
|
||||||
|
|
||||||
|
match wire_style {
|
||||||
|
WireStyle::Direct => {
|
||||||
|
let horizontal_gap = (output_position.x - input_position.x).abs();
|
||||||
|
let vertical_gap = (output_position.y - input_position.y).abs();
|
||||||
|
|
||||||
|
let curve_length = GRID_SIZE;
|
||||||
|
let curve_falloff_rate = curve_length * std::f64::consts::TAU;
|
||||||
|
|
||||||
|
let horizontal_curve_amount = -(2_f64.powf((-10. * horizontal_gap) / curve_falloff_rate)) + 1.;
|
||||||
|
let vertical_curve_amount = -(2_f64.powf((-10. * vertical_gap) / curve_falloff_rate)) + 1.;
|
||||||
|
let horizontal_curve = horizontal_curve_amount * curve_length;
|
||||||
|
let vertical_curve = vertical_curve_amount * curve_length;
|
||||||
|
|
||||||
|
let locations = [
|
||||||
|
output_position,
|
||||||
|
DVec2::new(
|
||||||
|
if vertical_out { output_position.x } else { output_position.x + horizontal_curve },
|
||||||
|
if vertical_out { output_position.y - vertical_curve } else { output_position.y },
|
||||||
|
),
|
||||||
|
DVec2::new(
|
||||||
|
if vertical_in { input_position.x } else { input_position.x - horizontal_curve },
|
||||||
|
if vertical_in { input_position.y + vertical_curve } else { input_position.y },
|
||||||
|
),
|
||||||
|
DVec2::new(input_position.x, input_position.y),
|
||||||
|
];
|
||||||
|
|
||||||
|
let smoothing = 0.5;
|
||||||
|
let delta01 = DVec2::new((locations[1].x - locations[0].x) * smoothing, (locations[1].y - locations[0].y) * smoothing);
|
||||||
|
let delta23 = DVec2::new((locations[3].x - locations[2].x) * smoothing, (locations[3].y - locations[2].y) * smoothing);
|
||||||
|
|
||||||
|
let mut wire = BezPath::new();
|
||||||
|
wire.move_to(dvec2_to_point(locations[0]));
|
||||||
|
wire.line_to(dvec2_to_point(locations[1]));
|
||||||
|
wire.curve_to(dvec2_to_point(locations[1] + delta01), dvec2_to_point(locations[2] - delta23), dvec2_to_point(locations[2]));
|
||||||
|
wire.line_to(dvec2_to_point(locations[3]));
|
||||||
|
wire
|
||||||
|
}
|
||||||
|
WireStyle::GridAligned => {
|
||||||
|
let locations = straight_wire_path(output_position, input_position, vertical_out, vertical_in);
|
||||||
|
straight_wire_to_bezpath(locations)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -> bool {
|
||||||
|
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= GRID_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
|
||||||
|
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots.
|
||||||
|
pub(crate) fn build_thick_wire_center_line(ends: [WireEnd; 2], wire_style: WireStyle) -> BezPath {
|
||||||
|
let [output_position, input_position] = ends.map(|end| end.position);
|
||||||
|
if thick_wire_spans_single_cell(output_position, input_position) {
|
||||||
|
return BezPath::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let wire = route(ends, wire_style);
|
||||||
|
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
|
||||||
|
return BezPath::new();
|
||||||
|
};
|
||||||
|
|
||||||
|
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||||
|
let sign = (input_position.y - output_position.y).signum();
|
||||||
|
let mut center_line = BezPath::new();
|
||||||
|
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||||
|
center_line.line_to(start);
|
||||||
|
for element in wire.elements().iter().skip(1) {
|
||||||
|
center_line.push(*element);
|
||||||
|
}
|
||||||
|
center_line.line_to(end + Vec2::new(0., 2. * sign));
|
||||||
|
center_line
|
||||||
|
}
|
||||||
|
|
||||||
|
fn straight_wire_path(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> Vec<IVec2> {
|
||||||
|
let grid_spacing = GRID_SIZE as i32;
|
||||||
|
let line_width = 2;
|
||||||
|
|
||||||
|
let in_x = input_position.x.floor() as i32;
|
||||||
|
let in_y = input_position.y.floor() as i32;
|
||||||
|
let out_x = output_position.x.floor() as i32;
|
||||||
|
let out_y = output_position.y.floor() as i32;
|
||||||
|
|
||||||
|
let mid_x = (in_x + out_x).div_euclid(2) + (in_x + out_x).div_euclid(2).rem_euclid(grid_spacing);
|
||||||
|
let mid_y = (in_y + out_y).div_euclid(2) + (in_y + out_y).div_euclid(2).rem_euclid(grid_spacing);
|
||||||
|
let mid_y_alternate = in_y - in_y.rem_euclid(grid_spacing);
|
||||||
|
|
||||||
|
let x1 = out_x;
|
||||||
|
let x2 = out_x + grid_spacing;
|
||||||
|
let x3 = in_x - 2 * grid_spacing;
|
||||||
|
let x4 = in_x;
|
||||||
|
let x5 = in_x - 2 * grid_spacing + line_width;
|
||||||
|
let x6 = out_x + grid_spacing + line_width;
|
||||||
|
let x7 = out_x + 2 * grid_spacing + line_width;
|
||||||
|
let x8 = in_x + line_width;
|
||||||
|
let x9 = out_x + 2 * grid_spacing;
|
||||||
|
let x10 = mid_x + line_width;
|
||||||
|
let x11 = out_x - grid_spacing;
|
||||||
|
let x12 = out_x - 4 * grid_spacing;
|
||||||
|
let x13 = mid_x;
|
||||||
|
let x14 = in_x + grid_spacing;
|
||||||
|
let x15 = in_x - 4 * grid_spacing;
|
||||||
|
let x16 = in_x + 8 * grid_spacing;
|
||||||
|
let x17 = mid_x - 2 * line_width;
|
||||||
|
let x18 = out_x + grid_spacing - 2 * line_width;
|
||||||
|
let x19 = out_x - 2 * line_width;
|
||||||
|
let x20 = mid_x - line_width;
|
||||||
|
|
||||||
|
let y1 = out_y;
|
||||||
|
let y2 = out_y - grid_spacing;
|
||||||
|
let y3 = in_y;
|
||||||
|
let y4 = out_y - grid_spacing + 5 * line_width + 1;
|
||||||
|
let y5 = in_y - 2 * grid_spacing;
|
||||||
|
let y6 = out_y + 4 * line_width;
|
||||||
|
let y7 = out_y + 5 * line_width;
|
||||||
|
let y8 = out_y - 2 * grid_spacing + 5 * line_width + 1;
|
||||||
|
let y9 = out_y + 6 * line_width;
|
||||||
|
let y10 = in_y + 2 * grid_spacing;
|
||||||
|
let y111 = in_y + grid_spacing + 6 * line_width + 1;
|
||||||
|
let y12 = in_y + grid_spacing - 5 * line_width + 1;
|
||||||
|
let y13 = in_y - grid_spacing;
|
||||||
|
let y14 = in_y + grid_spacing;
|
||||||
|
let y15 = mid_y;
|
||||||
|
let y16 = mid_y_alternate;
|
||||||
|
|
||||||
|
let wire1 = vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x5, y4), IVec2::new(x5, y3), IVec2::new(x4, y3)];
|
||||||
|
|
||||||
|
let wire2 = vec![IVec2::new(x1, y1), IVec2::new(x1, y16), IVec2::new(x3, y16), IVec2::new(x3, y3), IVec2::new(x4, y3)];
|
||||||
|
|
||||||
|
let wire3 = vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y4),
|
||||||
|
IVec2::new(x12, y4),
|
||||||
|
IVec2::new(x12, y10),
|
||||||
|
IVec2::new(x3, y10),
|
||||||
|
IVec2::new(x3, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
|
||||||
|
let wire4 = vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y4),
|
||||||
|
IVec2::new(x13, y4),
|
||||||
|
IVec2::new(x13, y10),
|
||||||
|
IVec2::new(x3, y10),
|
||||||
|
IVec2::new(x3, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
|
||||||
|
// `outConnector` point and `inConnector` point lying on the same horizontal grid line and `outConnector` point lies to the right of `inConnector` point
|
||||||
|
if out_y == in_y && out_x > in_x && (vertical_out || !vertical_in) {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x3, y2), IVec2::new(x3, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle straight lines
|
||||||
|
if out_y == in_y || (out_x == in_x && vertical_out) {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle standard right-angle paths
|
||||||
|
// Start vertical, then horizontal
|
||||||
|
|
||||||
|
// `outConnector` point lies to the left of `inConnector` point
|
||||||
|
if vertical_out && in_x > out_x {
|
||||||
|
// `outConnector` point lies above `inConnector` point
|
||||||
|
if out_y < in_y {
|
||||||
|
// `outConnector` point lies on the vertical grid line 4 units to the left of `inConnector` point point
|
||||||
|
if -4 * grid_spacing <= out_x - in_x && out_x - in_x < -3 * grid_spacing {
|
||||||
|
return wire1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// `outConnector` point lying on vertical grid lines 3 and 2 units to the left of `inConnector` point
|
||||||
|
if -3 * grid_spacing <= out_x - in_x && out_x - in_x <= -grid_spacing {
|
||||||
|
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x1, y2), IVec2::new(x2, y2), IVec2::new(x2, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x6, y4), IVec2::new(x6, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y4),
|
||||||
|
IVec2::new(x7, y4),
|
||||||
|
IVec2::new(x7, y5),
|
||||||
|
IVec2::new(x3, y5),
|
||||||
|
IVec2::new(x3, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point lying on vertical grid line 1 units to the left of `inConnector` point
|
||||||
|
if -grid_spacing < out_x - in_x && out_x - in_x <= 0 {
|
||||||
|
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
|
||||||
|
if -2 * grid_spacing <= out_y - in_y && out_y - in_y <= -grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y6), IVec2::new(x2, y6), IVec2::new(x8, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
|
||||||
|
if -grid_spacing <= out_y - in_y && out_y - in_y <= 0 {
|
||||||
|
return vec![IVec2::new(x1, y7), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y2),
|
||||||
|
IVec2::new(x9, y2),
|
||||||
|
IVec2::new(x9, y5),
|
||||||
|
IVec2::new(x3, y5),
|
||||||
|
IVec2::new(x3, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x1, y4), IVec2::new(x10, y4), IVec2::new(x10, y3), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point lies below `inConnector` point
|
||||||
|
// `outConnector` point lying on vertical grid line 1 unit to the left of `inConnector` point
|
||||||
|
if -grid_spacing <= out_x - in_x && out_x - in_x <= 0 {
|
||||||
|
// `outConnector` point lying on the horizontal grid lines 1 and 2 units below the `inConnector` point
|
||||||
|
if 0 <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y6), IVec2::new(x11, y6), IVec2::new(x11, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
return wire2;
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x1, y3), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point lies to the right of `inConnector` point
|
||||||
|
if vertical_out && in_x <= out_x {
|
||||||
|
// `outConnector` point lying on any horizontal grid line above `inConnector` point
|
||||||
|
if out_y < in_y {
|
||||||
|
// `outConnector` point lying on horizontal grid line 1 unit above `inConnector` point
|
||||||
|
if -2 * grid_spacing < out_y - in_y && out_y - in_y <= -grid_spacing {
|
||||||
|
return wire1;
|
||||||
|
};
|
||||||
|
|
||||||
|
// `outConnector` point lying on the same horizontal grid line as `inConnector` point
|
||||||
|
if -grid_spacing < out_y - in_y && out_y - in_y <= 0 {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x1, y8), IVec2::new(x5, y8), IVec2::new(x5, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// `outConnector` point lying on vertical grid lines 1 and 2 units to the right of `inConnector` point
|
||||||
|
if grid_spacing <= out_x - in_x && out_x - in_x <= 3 * grid_spacing {
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y4),
|
||||||
|
IVec2::new(x9, y4),
|
||||||
|
IVec2::new(x9, y5),
|
||||||
|
IVec2::new(x3, y5),
|
||||||
|
IVec2::new(x3, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x1, y4),
|
||||||
|
IVec2::new(x10, y4),
|
||||||
|
IVec2::new(x10, y5),
|
||||||
|
IVec2::new(x5, y5),
|
||||||
|
IVec2::new(x5, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point lies below `inConnector` point
|
||||||
|
if out_y - in_y <= grid_spacing {
|
||||||
|
// `outConnector` point lies on the horizontal grid line 1 unit below the `inConnector` Point
|
||||||
|
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y9), IVec2::new(x3, y9), IVec2::new(x3, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
|
||||||
|
return wire3;
|
||||||
|
};
|
||||||
|
|
||||||
|
return wire4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point lies on the horizontal grid line 2 units below `outConnector` point
|
||||||
|
if grid_spacing <= out_y - in_y && out_y - in_y <= 2 * grid_spacing {
|
||||||
|
if 0 <= out_x - in_x && out_x - in_x <= 13 * grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y7), IVec2::new(x5, y7), IVec2::new(x5, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
if 13 < out_x - in_x && out_x - in_x <= 18 * grid_spacing {
|
||||||
|
return wire3;
|
||||||
|
};
|
||||||
|
|
||||||
|
return wire4;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 0 to 4 units below the `outConnector` Point
|
||||||
|
if out_y - in_y <= 4 * grid_spacing {
|
||||||
|
return wire1;
|
||||||
|
};
|
||||||
|
|
||||||
|
return wire2;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start horizontal, then vertical
|
||||||
|
if vertical_in {
|
||||||
|
// when `outConnector` lies below `inConnector`
|
||||||
|
if out_y > in_y {
|
||||||
|
// `out_x` lies to the left of `in_x`
|
||||||
|
if out_x < in_x {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x4, y1), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// `out_x` lies to the right of `in_x`
|
||||||
|
if out_y - in_y <= grid_spacing {
|
||||||
|
// `outConnector` point directly below `inConnector` point
|
||||||
|
if 0 <= out_x - in_x && out_x - in_x <= grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x14, y1), IVec2::new(x14, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// `outConnector` point lies below `inConnector` point and strictly to the right of `inConnector` point
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y111), IVec2::new(x4, y111), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y2), IVec2::new(x4, y2), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `out_y` lies on or above the `in_y` point
|
||||||
|
if -6 * grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
|
||||||
|
// edge case: `outConnector` point lying on vertical grid lines ranging from 4 units to left to 5 units to right of `inConnector` point
|
||||||
|
if -grid_spacing < in_x - out_x && in_x - out_x < 4 * grid_spacing {
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x2, y1),
|
||||||
|
IVec2::new(x2, y2),
|
||||||
|
IVec2::new(x15, y2),
|
||||||
|
IVec2::new(x15, y12),
|
||||||
|
IVec2::new(x4, y12),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x16, y1), IVec2::new(x16, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// left of edge case: `outConnector` point lying on vertical grid lines more than 4 units to left of `inConnector` point
|
||||||
|
if 4 * grid_spacing < in_x - out_x {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x17, y1), IVec2::new(x17, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// right of edge case: `outConnector` point lying on the vertical grid lines more than 5 units to right of `inConnector` point
|
||||||
|
if 6 * grid_spacing > in_x - out_x {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y12), IVec2::new(x4, y12), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Both horizontal - use horizontal middle point
|
||||||
|
// When `inConnector` point is one of the two closest diagonally opposite points
|
||||||
|
if 0 <= in_x - out_x && in_x - out_x <= grid_spacing && in_y - out_y >= -grid_spacing && in_y - out_y <= grid_spacing {
|
||||||
|
return vec![IVec2::new(x19, y1), IVec2::new(x19, y3), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// When `inConnector` point lies on the horizontal line 1 unit above and below the `outConnector` point
|
||||||
|
if -grid_spacing <= out_y - in_y && out_y - in_y <= grid_spacing && out_x > in_x {
|
||||||
|
// Horizontal line above `out_y`
|
||||||
|
if in_y < out_y {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y13), IVec2::new(x3, y13), IVec2::new(x3, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Horizontal line below `out_y`
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x2, y1), IVec2::new(x2, y14), IVec2::new(x3, y14), IVec2::new(x3, y3), IVec2::new(x4, y3)];
|
||||||
|
}
|
||||||
|
|
||||||
|
// `outConnector` point to the right of `inConnector` point
|
||||||
|
if out_x > in_x - grid_spacing {
|
||||||
|
return vec![
|
||||||
|
IVec2::new(x1, y1),
|
||||||
|
IVec2::new(x18, y1),
|
||||||
|
IVec2::new(x18, y15),
|
||||||
|
IVec2::new(x5, y15),
|
||||||
|
IVec2::new(x5, y3),
|
||||||
|
IVec2::new(x4, y3),
|
||||||
|
];
|
||||||
|
};
|
||||||
|
|
||||||
|
// When `inConnector` point lies on the vertical grid line two units to the right of `outConnector` point
|
||||||
|
if grid_spacing <= in_x - out_x && in_x - out_x <= 2 * grid_spacing {
|
||||||
|
return vec![IVec2::new(x1, y1), IVec2::new(x18, y1), IVec2::new(x18, y3), IVec2::new(x4, y3)];
|
||||||
|
};
|
||||||
|
|
||||||
|
vec![IVec2::new(x1, y1), IVec2::new(x20, y1), IVec2::new(x20, y3), IVec2::new(x4, y3)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||||
|
if locations.is_empty() {
|
||||||
|
return BezPath::new();
|
||||||
|
}
|
||||||
|
|
||||||
|
let to_point = |location: IVec2| Point::new(location.x as f64, location.y as f64);
|
||||||
|
|
||||||
|
if locations.len() == 2 {
|
||||||
|
let p1 = to_point(locations[0]);
|
||||||
|
let p2 = to_point(locations[1]);
|
||||||
|
return Line::new(p1, p2).to_path(DEFAULT_ACCURACY);
|
||||||
|
}
|
||||||
|
|
||||||
|
let corner_radius = 10;
|
||||||
|
|
||||||
|
// Create path with rounded corners
|
||||||
|
let mut path = BezPath::new();
|
||||||
|
path.move_to(to_point(locations[0]));
|
||||||
|
|
||||||
|
for i in 1..(locations.len() - 1) {
|
||||||
|
let prev = locations[i - 1];
|
||||||
|
let curr = locations[i];
|
||||||
|
let next = locations[i + 1];
|
||||||
|
|
||||||
|
let corner_start = IVec2::new(
|
||||||
|
curr.x
|
||||||
|
+ if curr.x == prev.x {
|
||||||
|
0
|
||||||
|
} else if prev.x > curr.x {
|
||||||
|
corner_radius
|
||||||
|
} else {
|
||||||
|
-corner_radius
|
||||||
|
},
|
||||||
|
curr.y
|
||||||
|
+ if curr.y == prev.y {
|
||||||
|
0
|
||||||
|
} else if prev.y > curr.y {
|
||||||
|
corner_radius
|
||||||
|
} else {
|
||||||
|
-corner_radius
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let corner_start_mid = IVec2::new(
|
||||||
|
curr.x
|
||||||
|
+ if curr.x == prev.x {
|
||||||
|
0
|
||||||
|
} else if prev.x > curr.x {
|
||||||
|
corner_radius / 2
|
||||||
|
} else {
|
||||||
|
-corner_radius / 2
|
||||||
|
},
|
||||||
|
curr.y
|
||||||
|
+ if curr.y == prev.y {
|
||||||
|
0
|
||||||
|
} else {
|
||||||
|
match prev.y > curr.y {
|
||||||
|
true => corner_radius / 2,
|
||||||
|
false => -corner_radius / 2,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let corner_end = IVec2::new(
|
||||||
|
curr.x
|
||||||
|
+ if curr.x == next.x {
|
||||||
|
0
|
||||||
|
} else if next.x > curr.x {
|
||||||
|
corner_radius
|
||||||
|
} else {
|
||||||
|
-corner_radius
|
||||||
|
},
|
||||||
|
curr.y
|
||||||
|
+ if curr.y == next.y {
|
||||||
|
0
|
||||||
|
} else if next.y > curr.y {
|
||||||
|
corner_radius
|
||||||
|
} else {
|
||||||
|
-corner_radius
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let corner_end_mid = IVec2::new(
|
||||||
|
curr.x
|
||||||
|
+ if curr.x == next.x {
|
||||||
|
0
|
||||||
|
} else if next.x > curr.x {
|
||||||
|
corner_radius / 2
|
||||||
|
} else {
|
||||||
|
-corner_radius / 2
|
||||||
|
},
|
||||||
|
curr.y
|
||||||
|
+ if curr.y == next.y {
|
||||||
|
0
|
||||||
|
} else if next.y > curr.y {
|
||||||
|
10 / 2
|
||||||
|
} else {
|
||||||
|
-corner_radius / 2
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
path.line_to(to_point(corner_start));
|
||||||
|
path.curve_to(to_point(corner_start_mid), to_point(corner_end_mid), to_point(corner_end));
|
||||||
|
}
|
||||||
|
path.line_to(to_point(*locations.last().unwrap()));
|
||||||
|
path
|
||||||
|
}
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, GRID_SIZE, TEXT_SIZE};
|
||||||
|
use core_types::list::{ATTR_GEOMETRY_CACHE, List};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphic_types::Vector;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::collections::hash_map::Entry;
|
||||||
|
use text_nodes::{FALLBACK_FONT_RESOURCE, TextToVectorError, TypesettingConfig};
|
||||||
|
use vector_types::vector::GeometryCache;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Label {
|
||||||
|
pub outline: List<Vector>,
|
||||||
|
pub width: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Labels(HashMap<(String, u64), Label>);
|
||||||
|
|
||||||
|
impl Labels {
|
||||||
|
pub fn label(&mut self, text: &str, max_width: f64) -> Result<&Label, TextToVectorError> {
|
||||||
|
match self.0.entry((text.to_string(), max_width.to_bits())) {
|
||||||
|
Entry::Occupied(label) => Ok(label.into_mut()),
|
||||||
|
Entry::Vacant(label) => {
|
||||||
|
let text = ellipsized(text, max_width);
|
||||||
|
let (outline, width) = (outline(&text)?, label_width(&text));
|
||||||
|
Ok(label.insert(Label { outline, width }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn label_width(text: &str) -> f64 {
|
||||||
|
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ellipsized(text: &str, max_width: f64) -> String {
|
||||||
|
if label_width(text) <= max_width {
|
||||||
|
return text.to_string();
|
||||||
|
}
|
||||||
|
let cut = |end: usize| format!("{}…", &text[..end]);
|
||||||
|
let ends: Vec<usize> = text.char_indices().map(|(end, _)| end).collect();
|
||||||
|
let fitting = ends.partition_point(|&end| label_width(&cut(end)) <= max_width);
|
||||||
|
cut(ends[fitting.saturating_sub(1)])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn outline(text: &str) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn with_geometry_caches(mut outline: List<Vector>) -> List<Vector> {
|
||||||
|
for index in 0..outline.len() {
|
||||||
|
outline.set_attribute(ATTR_GEOMETRY_CACHE, index, GeometryCache::default());
|
||||||
|
}
|
||||||
|
outline
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paragraph_size(text: &str, line_height: f64, max_width: f64) -> DVec2 {
|
||||||
|
let unwrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, None), true);
|
||||||
|
let wrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), true);
|
||||||
|
DVec2::new(unwrapped.x.min(max_width), wrapped.y)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error_text_size(text: &str) -> DVec2 {
|
||||||
|
paragraph_size(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result<List<Vector>, TextToVectorError> {
|
||||||
|
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), false).map(with_geometry_caches)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn typesetting() -> TypesettingConfig {
|
||||||
|
TypesettingConfig {
|
||||||
|
font_size: TEXT_SIZE,
|
||||||
|
line_height_ratio: GRID_SIZE / TEXT_SIZE,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paragraph_typesetting(line_height: f64, max_width: Option<f64>) -> TypesettingConfig {
|
||||||
|
TypesettingConfig {
|
||||||
|
font_size: TEXT_SIZE,
|
||||||
|
line_height_ratio: line_height / TEXT_SIZE,
|
||||||
|
max_width,
|
||||||
|
..Default::default()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
[package]
|
||||||
|
name = "graph-ui-types"
|
||||||
|
description = "The rows, scene and metrics of the node graph UI"
|
||||||
|
version.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
authors.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
repository.workspace = true
|
||||||
|
readme.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
publish.workspace = true
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
serde = ["dep:serde"]
|
||||||
|
wasm = ["dep:tsify", "dep:wasm-bindgen"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# Local dependencies
|
||||||
|
core-types = { workspace = true }
|
||||||
|
dyn-any = { workspace = true }
|
||||||
|
graph-layout = { workspace = true }
|
||||||
|
graphene-hash = { workspace = true }
|
||||||
|
graphic-types = { workspace = true }
|
||||||
|
|
||||||
|
# Workspace dependencies
|
||||||
|
glam = { workspace = true }
|
||||||
|
serde = { workspace = true, optional = true }
|
||||||
|
tsify = { workspace = true, optional = true }
|
||||||
|
wasm-bindgen = { workspace = true, optional = true }
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
use crate::geometry::NodeShape;
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Card {
|
||||||
|
pub key: NodeId,
|
||||||
|
pub shape: NodeShape,
|
||||||
|
pub name: String,
|
||||||
|
pub icon: &'static str,
|
||||||
|
pub primary_input: Option<Connector>,
|
||||||
|
pub primary_output: Option<Connector>,
|
||||||
|
pub secondary_inputs: Vec<Connector>,
|
||||||
|
pub secondary_outputs: Vec<Connector>,
|
||||||
|
pub selection: Selection,
|
||||||
|
pub visible: bool,
|
||||||
|
pub previewed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||||
|
pub enum Selection {
|
||||||
|
None,
|
||||||
|
Inactive,
|
||||||
|
Active,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Connector {
|
||||||
|
pub index: u32,
|
||||||
|
pub name: String,
|
||||||
|
pub data_type: DataType,
|
||||||
|
pub connected: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||||
|
pub enum DataType {
|
||||||
|
General,
|
||||||
|
Number,
|
||||||
|
Artboard,
|
||||||
|
Graphic,
|
||||||
|
Raster,
|
||||||
|
Vector,
|
||||||
|
Color,
|
||||||
|
Gradient,
|
||||||
|
Typography,
|
||||||
|
Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for Card {
|
||||||
|
type Key = NodeId;
|
||||||
|
|
||||||
|
fn key(&self) -> NodeId {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
use crate::card::DataType;
|
||||||
|
use crate::geometry::NodeShape;
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Dot {
|
||||||
|
pub key: NodeId,
|
||||||
|
pub shape: NodeShape,
|
||||||
|
pub data_type: DataType,
|
||||||
|
pub wired: bool,
|
||||||
|
pub selected: bool,
|
||||||
|
pub previewed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for Dot {
|
||||||
|
type Key = NodeId;
|
||||||
|
|
||||||
|
fn key(&self) -> NodeId {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
use crate::metrics::{ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE};
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct ErrorBadge {
|
||||||
|
pub key: NodeId,
|
||||||
|
pub text: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for ErrorBadge {
|
||||||
|
type Key = NodeId;
|
||||||
|
|
||||||
|
fn key(&self) -> NodeId {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body(anchor: DVec2, text_size: DVec2) -> [DVec2; 2] {
|
||||||
|
let size = text_size + 2. * ERROR_PADDING;
|
||||||
|
[anchor - DVec2::Y * size.y, anchor + DVec2::X * size.x]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn text_top_left(anchor: DVec2, text_size: DVec2) -> DVec2 {
|
||||||
|
let [top_left, _] = body(anchor, text_size);
|
||||||
|
top_left + ERROR_PADDING
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tail(anchor: DVec2) -> [DVec2; 3] {
|
||||||
|
let top_left = anchor + DVec2::X * ERROR_TAIL_LEFT;
|
||||||
|
[top_left, top_left + DVec2::X * ERROR_TAIL_SIZE.x, top_left + DVec2::new(ERROR_TAIL_SIZE.x / 2., ERROR_TAIL_SIZE.y)]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn covers(anchor: DVec2, text_size: DVec2, point: DVec2) -> bool {
|
||||||
|
let [tail, ..] = tail(anchor);
|
||||||
|
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
|
||||||
|
within(body(anchor, text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
|
||||||
|
}
|
||||||
@@ -0,0 +1,493 @@
|
|||||||
|
use crate::card::{Card, Connector};
|
||||||
|
use crate::dot::Dot;
|
||||||
|
use crate::layer::Layer;
|
||||||
|
use crate::metrics::{
|
||||||
|
CLICK_RADIUS, GRID_SIZE, INPUT_CONNECTOR_OFFSET, LAYER_BUTTON_SIZE, LAYER_CLICK_RADIUS, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
|
||||||
|
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, OUTPUT_CONNECTOR_OFFSET, PORT_CLICK_RADIUS, SIDE_PORT_HALF_HEIGHT, SIDE_PORT_INWARD_REACH, SIDE_PORT_OUTWARD_REACH, STACK_ANCHOR_DISTANCE,
|
||||||
|
STACK_CONNECTOR_SIZE, STACK_PORT_HALF_SIZE, WAYPOINT_GUTTER_OFFSET, WAYPOINT_GUTTER_RADIUS, WAYPOINT_HALF_SIZE,
|
||||||
|
};
|
||||||
|
use crate::network_connector::{NetworkConnector, NetworkConnectorKey};
|
||||||
|
use crate::placed::Placed;
|
||||||
|
use crate::replicated_map::ReplicatedMap;
|
||||||
|
use crate::scene::Rows;
|
||||||
|
use crate::wire::{InputKey, OutputKey, Wire};
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use glam::{DVec2, IVec2, UVec2};
|
||||||
|
use graph_layout::{CHAIN_WIDTH, NodeKind};
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
use std::ops::Range;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||||
|
pub struct NodeShape {
|
||||||
|
pub size: UVec2,
|
||||||
|
pub exposed_inputs: Arc<[usize]>,
|
||||||
|
pub outputs: u32,
|
||||||
|
pub primary_output_hidden: bool,
|
||||||
|
pub name_width: f64,
|
||||||
|
pub locked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeShape {
|
||||||
|
fn inputs(&self) -> u32 {
|
||||||
|
self.exposed_inputs.len() as u32
|
||||||
|
}
|
||||||
|
|
||||||
|
fn primary_input_hidden(&self) -> bool {
|
||||||
|
self.exposed_inputs.first().is_some_and(|first| *first != 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Part {
|
||||||
|
Body,
|
||||||
|
Input(u32),
|
||||||
|
Output(u32),
|
||||||
|
Visibility,
|
||||||
|
Lock,
|
||||||
|
Grip,
|
||||||
|
Name,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct PartTarget {
|
||||||
|
pub min: DVec2,
|
||||||
|
pub max: DVec2,
|
||||||
|
pub corner_radius: f64,
|
||||||
|
pub part: Part,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartTarget {
|
||||||
|
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - half_size,
|
||||||
|
max: center + half_size,
|
||||||
|
corner_radius,
|
||||||
|
part,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn over([min, max]: [DVec2; 2], corner_radius: f64, part: Part) -> Self {
|
||||||
|
Self { min, max, corner_radius, part }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input_port(center: DVec2, input: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
corner_radius: PORT_CLICK_RADIUS,
|
||||||
|
part: Part::Input(input),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output_port(center: DVec2, output: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||||
|
corner_radius: PORT_CLICK_RADIUS,
|
||||||
|
part: Part::Output(output),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
|
||||||
|
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let radius = self.clamped_radius();
|
||||||
|
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
|
||||||
|
gap == DVec2::ZERO || gap.length_squared() < radius * radius
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn contains(&self, point: DVec2) -> bool {
|
||||||
|
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let radius = self.clamped_radius();
|
||||||
|
let inner = point.clamp(self.min + radius, self.max - radius);
|
||||||
|
point.distance_squared(inner) <= radius * radius
|
||||||
|
}
|
||||||
|
|
||||||
|
fn clamped_radius(&self) -> f64 {
|
||||||
|
self.corner_radius.min((self.max - self.min).min_element() / 2.)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct WireEnd {
|
||||||
|
pub position: DVec2,
|
||||||
|
pub vertical: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_thick_wire([from, to]: [WireEnd; 2]) -> bool {
|
||||||
|
from.vertical && to.vertical
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct NodeGeometry {
|
||||||
|
pub cell: IVec2,
|
||||||
|
pub kind: NodeKind,
|
||||||
|
pub chain_length: u32,
|
||||||
|
pub shape: NodeShape,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeGeometry {
|
||||||
|
pub fn body(&self) -> PartTarget {
|
||||||
|
match self.kind {
|
||||||
|
NodeKind::Waypoint => PartTarget::around(self.dot_center(), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
|
||||||
|
NodeKind::Layer => PartTarget {
|
||||||
|
min: self.top_left() - DVec2::new(self.chain_width(), 0.),
|
||||||
|
max: self.top_left() + self.size(),
|
||||||
|
corner_radius: LAYER_CLICK_RADIUS,
|
||||||
|
part: Part::Body,
|
||||||
|
},
|
||||||
|
NodeKind::Node => PartTarget::over(self.card_body(), CLICK_RADIUS, Part::Body),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
|
||||||
|
match self.kind {
|
||||||
|
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
|
||||||
|
NodeKind::Layer => self.layer_parts(&mut visit),
|
||||||
|
NodeKind::Node => self.node_ports(&mut visit),
|
||||||
|
}
|
||||||
|
visit(self.body());
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input_end(&self, index: usize) -> Option<WireEnd> {
|
||||||
|
let position = self.input_anchor(self.place_of_input(index)?)?;
|
||||||
|
let vertical = self.kind == NodeKind::Layer && index == 0;
|
||||||
|
Some(WireEnd { position, vertical })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn output_end(&self, index: usize) -> Option<WireEnd> {
|
||||||
|
let position = self.output_anchor(u32::try_from(index).ok()?)?;
|
||||||
|
let vertical = self.kind == NodeKind::Layer;
|
||||||
|
Some(WireEnd { position, vertical })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn input_at(&self, place: u32) -> Option<usize> {
|
||||||
|
match self.kind {
|
||||||
|
NodeKind::Node => {
|
||||||
|
let row = place.checked_sub(self.input_rows().start)?;
|
||||||
|
self.shape.exposed_inputs.get(row as usize).copied()
|
||||||
|
}
|
||||||
|
NodeKind::Layer | NodeKind::Waypoint => Some(place as usize),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn error_badge_anchor(&self) -> DVec2 {
|
||||||
|
let offset = if self.kind == NodeKind::Layer {
|
||||||
|
DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.)
|
||||||
|
} else {
|
||||||
|
DVec2::ZERO
|
||||||
|
};
|
||||||
|
self.top_left() + offset
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place_of_input(&self, index: usize) -> Option<u32> {
|
||||||
|
let place = match self.kind {
|
||||||
|
NodeKind::Node => {
|
||||||
|
let row = self.shape.exposed_inputs.iter().position(|exposed| *exposed == index)?;
|
||||||
|
self.input_rows().start as usize + row
|
||||||
|
}
|
||||||
|
NodeKind::Layer | NodeKind::Waypoint => index,
|
||||||
|
};
|
||||||
|
u32::try_from(place).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input_anchor(&self, place: u32) -> Option<DVec2> {
|
||||||
|
match (self.kind, place) {
|
||||||
|
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
|
||||||
|
(NodeKind::Layer, 0) => Some(self.stack_input_anchor()),
|
||||||
|
(NodeKind::Layer, 1) if self.has_side_input() => Some(self.side_input_anchor()),
|
||||||
|
(NodeKind::Node, row) if self.input_rows().contains(&row) => Some(self.row_input_anchor(row)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_anchor(&self, place: u32) -> Option<DVec2> {
|
||||||
|
match (self.kind, place) {
|
||||||
|
(NodeKind::Waypoint, 0) => Some(self.dot_center()),
|
||||||
|
(NodeKind::Layer, 0) => Some(self.stack_output_anchor()),
|
||||||
|
(NodeKind::Node, row) if self.output_rows().contains(&row) => Some(self.row_output_anchor(row)),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn card_body(&self) -> [DVec2; 2] {
|
||||||
|
let top_left = self.top_left() + DVec2::new(0., GRID_SIZE / 2.);
|
||||||
|
[top_left, top_left + self.size() - DVec2::new(0., GRID_SIZE)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_body(&self) -> [DVec2; 2] {
|
||||||
|
let top_left = self.top_left();
|
||||||
|
let chain_width = self.chain_width();
|
||||||
|
let left = if chain_width > 0. { -chain_width } else { LAYER_LEFT_MARGIN };
|
||||||
|
[top_left + DVec2::X * left, top_left + self.size()]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn thumbnail_block(&self) -> [DVec2; 2] {
|
||||||
|
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
|
||||||
|
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, self.size().y)]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn visibility(&self) -> [DVec2; 2] {
|
||||||
|
let [_, max] = self.layer_body();
|
||||||
|
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.middle() - LAYER_BUTTON_SIZE / 2.);
|
||||||
|
[top_left, top_left + LAYER_BUTTON_SIZE]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn grip(&self) -> [DVec2; 2] {
|
||||||
|
let [right_of_grip, _] = self.lock().unwrap_or(self.visibility());
|
||||||
|
[right_of_grip - DVec2::X * LAYER_GRIP_WIDTH, right_of_grip + DVec2::Y * LAYER_BUTTON_SIZE]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock(&self) -> Option<[DVec2; 2]> {
|
||||||
|
let [min, max] = self.visibility();
|
||||||
|
self.shape.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dot_center(&self) -> DVec2 {
|
||||||
|
self.top_left() + DVec2::new(0., GRID_SIZE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
let center = self.dot_center();
|
||||||
|
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
|
||||||
|
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
|
||||||
|
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
for row in self.input_rows() {
|
||||||
|
visit(PartTarget::input_port(self.row_input_anchor(row), row));
|
||||||
|
}
|
||||||
|
for row in self.output_rows() {
|
||||||
|
visit(PartTarget::output_port(self.row_output_anchor(row), row));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||||
|
visit(PartTarget::around(self.stack_input_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Input(0)));
|
||||||
|
if self.has_side_input() {
|
||||||
|
visit(PartTarget::input_port(self.side_input_anchor(), 1));
|
||||||
|
}
|
||||||
|
visit(PartTarget::around(self.stack_output_anchor(), STACK_PORT_HALF_SIZE, PORT_CLICK_RADIUS, Part::Output(0)));
|
||||||
|
|
||||||
|
visit(PartTarget::over(self.visibility(), CLICK_RADIUS, Part::Visibility));
|
||||||
|
if let Some(lock) = self.lock() {
|
||||||
|
visit(PartTarget::over(lock, CLICK_RADIUS, Part::Lock));
|
||||||
|
}
|
||||||
|
|
||||||
|
let [grip_min, grip_max] = self.grip();
|
||||||
|
visit(PartTarget::over([grip_min, grip_max], 0., Part::Grip));
|
||||||
|
|
||||||
|
let name_left = self.top_left().x + LAYER_NAME_LEFT;
|
||||||
|
let name_right = (name_left + self.shape.name_width).min(grip_min.x);
|
||||||
|
if name_right > name_left {
|
||||||
|
visit(PartTarget {
|
||||||
|
min: DVec2::new(name_left, grip_min.y),
|
||||||
|
max: DVec2::new(name_right, grip_max.y),
|
||||||
|
corner_radius: CLICK_RADIUS,
|
||||||
|
part: Part::Name,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn top_left(&self) -> DVec2 {
|
||||||
|
self.cell.as_dvec2() * GRID_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size(&self) -> DVec2 {
|
||||||
|
self.shape.size.as_dvec2() * GRID_SIZE
|
||||||
|
}
|
||||||
|
|
||||||
|
fn middle(&self) -> f64 {
|
||||||
|
self.top_left().y + self.size().y / 2.
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input_rows(&self) -> Range<u32> {
|
||||||
|
let first = u32::from(self.shape.primary_input_hidden());
|
||||||
|
first..first + self.shape.inputs()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_rows(&self) -> Range<u32> {
|
||||||
|
u32::from(self.shape.primary_output_hidden)..self.shape.outputs
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_input_anchor(&self, row: u32) -> DVec2 {
|
||||||
|
self.top_left() + DVec2::new(0., GRID_SIZE * (row as f64 + 1.))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_output_anchor(&self, row: u32) -> DVec2 {
|
||||||
|
self.top_left() + DVec2::new(self.size().x, GRID_SIZE * (row as f64 + 1.))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stack_input_anchor(&self) -> DVec2 {
|
||||||
|
let [min, max] = self.thumbnail_block();
|
||||||
|
DVec2::new((min.x + max.x) / 2., max.y + STACK_ANCHOR_DISTANCE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stack_output_anchor(&self) -> DVec2 {
|
||||||
|
let [min, max] = self.thumbnail_block();
|
||||||
|
DVec2::new((min.x + max.x) / 2., min.y - STACK_ANCHOR_DISTANCE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn side_input_anchor(&self) -> DVec2 {
|
||||||
|
DVec2::new(self.top_left().x, self.middle())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn has_side_input(&self) -> bool {
|
||||||
|
self.shape.inputs() > 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn chain_width(&self) -> f64 {
|
||||||
|
if self.has_side_input() {
|
||||||
|
(self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID_SIZE
|
||||||
|
} else {
|
||||||
|
0.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placed<Card> {
|
||||||
|
fn geometry(&self) -> NodeGeometry {
|
||||||
|
NodeGeometry {
|
||||||
|
cell: self.cell,
|
||||||
|
kind: NodeKind::Node,
|
||||||
|
chain_length: 0,
|
||||||
|
shape: self.look.shape.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body(&self) -> [DVec2; 2] {
|
||||||
|
self.geometry().card_body()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rows(&self) -> u32 {
|
||||||
|
self.look.shape.size.y.saturating_sub(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||||
|
let geometry = self.geometry();
|
||||||
|
rows(&self.look.primary_input, &self.look.secondary_inputs).map(move |(row, input)| (geometry.row_input_anchor(row) + INPUT_CONNECTOR_OFFSET, input))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||||
|
let geometry = self.geometry();
|
||||||
|
rows(&self.look.primary_output, &self.look.secondary_outputs).map(move |(row, output)| (geometry.row_output_anchor(row) + OUTPUT_CONNECTOR_OFFSET, output))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rows<'a>(primary: &'a Option<Connector>, secondary: &'a [Connector]) -> impl Iterator<Item = (u32, &'a Connector)> {
|
||||||
|
primary.iter().map(|connector| (0, connector)).chain((1..).zip(secondary))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placed<Layer> {
|
||||||
|
fn geometry(&self) -> NodeGeometry {
|
||||||
|
NodeGeometry {
|
||||||
|
cell: self.cell,
|
||||||
|
kind: NodeKind::Layer,
|
||||||
|
chain_length: self.look.chain_length,
|
||||||
|
shape: self.look.shape.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn body(&self) -> [DVec2; 2] {
|
||||||
|
self.geometry().layer_body()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn left_input_wire(&self) -> Option<DVec2> {
|
||||||
|
let geometry = self.geometry();
|
||||||
|
let [min, _] = geometry.layer_body();
|
||||||
|
(self.look.has_left_input_wire && geometry.chain_width() > 0.).then(|| DVec2::new(min.x, geometry.middle()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn thumbnail_block(&self) -> [DVec2; 2] {
|
||||||
|
self.geometry().thumbnail_block()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn thumbnail(&self) -> [DVec2; 2] {
|
||||||
|
let [min, max] = self.thumbnail_block();
|
||||||
|
[min + DVec2::X * LAYER_THUMBNAIL_MARGIN, max - DVec2::X * LAYER_THUMBNAIL_MARGIN]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn thumbnail_image(&self) -> [DVec2; 2] {
|
||||||
|
let [min, max] = self.thumbnail();
|
||||||
|
[min + LAYER_THUMBNAIL_IMAGE_INSET, max - LAYER_THUMBNAIL_IMAGE_INSET]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stack_output(&self) -> DVec2 {
|
||||||
|
let [min, max] = self.thumbnail_block();
|
||||||
|
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., min.y - STACK_CONNECTOR_SIZE.y)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn stack_input(&self) -> DVec2 {
|
||||||
|
let [min, max] = self.thumbnail_block();
|
||||||
|
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., max.y)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn secondary_input_connector(&self) -> DVec2 {
|
||||||
|
self.geometry().side_input_anchor() + INPUT_CONNECTOR_OFFSET
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name_box(&self) -> [DVec2; 2] {
|
||||||
|
let geometry = self.geometry();
|
||||||
|
let top_left = DVec2::new(geometry.top_left().x + LAYER_NAME_LEFT, geometry.middle() - GRID_SIZE / 2.);
|
||||||
|
[top_left, top_left + DVec2::new(geometry.size().x - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN, GRID_SIZE)]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn visibility(&self) -> [DVec2; 2] {
|
||||||
|
self.geometry().visibility()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn grip(&self) -> [DVec2; 2] {
|
||||||
|
self.geometry().grip()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn lock(&self) -> Option<[DVec2; 2]> {
|
||||||
|
self.geometry().lock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Placed<Dot> {
|
||||||
|
fn geometry(&self) -> NodeGeometry {
|
||||||
|
NodeGeometry {
|
||||||
|
cell: self.cell,
|
||||||
|
kind: NodeKind::Waypoint,
|
||||||
|
chain_length: 0,
|
||||||
|
shape: self.look.shape.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn center(&self) -> DVec2 {
|
||||||
|
self.geometry().dot_center()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rows {
|
||||||
|
fn geometry(&self, node: &NodeId) -> Option<NodeGeometry> {
|
||||||
|
let card = || self.cards.get(node).map(Placed::<Card>::geometry);
|
||||||
|
let layer = || self.layers.get(node).map(Placed::<Layer>::geometry);
|
||||||
|
let dot = || self.dots.get(node).map(Placed::<Dot>::geometry);
|
||||||
|
card().or_else(layer).or_else(dot)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn node_geometry(rows: &[&Rows], node: &NodeId) -> Option<NodeGeometry> {
|
||||||
|
rows.iter().find_map(|rows| rows.geometry(node))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn wire_ends(wire: &Wire, rows: &[&Rows], network_connectors: &ReplicatedMap<NetworkConnector>) -> Option<[WireEnd; 2]> {
|
||||||
|
let from = match wire.from {
|
||||||
|
OutputKey::Node { node, index } => node_geometry(rows, &node)?.output_end(index)?,
|
||||||
|
OutputKey::Import(index) => network_connectors.get(&NetworkConnectorKey::Import(index))?.wire_end()?,
|
||||||
|
};
|
||||||
|
let to = match wire.to {
|
||||||
|
InputKey::Node { node, index } => node_geometry(rows, &node)?.input_end(index)?,
|
||||||
|
InputKey::Export(index) => network_connectors.get(&NetworkConnectorKey::Export(index))?.wire_end()?,
|
||||||
|
};
|
||||||
|
Some([from, to])
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
use crate::layer::LayerButton;
|
||||||
|
use crate::wire::{InputKey, OutputKey};
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||||
|
pub enum Highlight {
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
Hovered,
|
||||||
|
WireSource,
|
||||||
|
WireTarget,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||||
|
pub enum ConnectorKey {
|
||||||
|
Input(InputKey),
|
||||||
|
Output(OutputKey),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, CacheHash)]
|
||||||
|
pub enum NodePart {
|
||||||
|
Dot(NodeId),
|
||||||
|
DotOutput(NodeId),
|
||||||
|
Visibility(NodeId),
|
||||||
|
Lock(NodeId),
|
||||||
|
Grip(NodeId),
|
||||||
|
ErrorBadge(NodeId),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash, DynAny)]
|
||||||
|
pub struct Highlights {
|
||||||
|
pub hovered_connector: Option<ConnectorKey>,
|
||||||
|
pub dragged_from: Option<ConnectorKey>,
|
||||||
|
pub snapped_to: Option<ConnectorKey>,
|
||||||
|
pub hovered_part: Option<NodePart>,
|
||||||
|
pub pressed_part: Option<NodePart>,
|
||||||
|
pub clicked: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Highlights {
|
||||||
|
pub fn dot(&self, dot: NodeId) -> [Highlight; 2] {
|
||||||
|
let ends = [
|
||||||
|
ConnectorKey::Input(InputKey::Node { node: dot, index: 0 }),
|
||||||
|
ConnectorKey::Output(OutputKey::Node { node: dot, index: 0 }),
|
||||||
|
];
|
||||||
|
let body = if self.snapped_to.is_some_and(|key| ends.contains(&key)) {
|
||||||
|
Highlight::WireTarget
|
||||||
|
} else if [self.hovered_part, self.pressed_part].contains(&Some(NodePart::Dot(dot))) {
|
||||||
|
Highlight::Hovered
|
||||||
|
} else {
|
||||||
|
Highlight::None
|
||||||
|
};
|
||||||
|
let output = if self.dragged_from.is_some_and(|key| ends.contains(&key)) {
|
||||||
|
Highlight::WireSource
|
||||||
|
} else if self.hovered_part == Some(NodePart::DotOutput(dot)) {
|
||||||
|
Highlight::Hovered
|
||||||
|
} else {
|
||||||
|
Highlight::None
|
||||||
|
};
|
||||||
|
[body, output]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layer_button(&self, layer: NodeId) -> Option<LayerButton> {
|
||||||
|
match self.hovered_part? {
|
||||||
|
NodePart::Visibility(node) if node == layer => Some(LayerButton::Visibility),
|
||||||
|
NodePart::Lock(node) if node == layer => Some(LayerButton::Lock),
|
||||||
|
NodePart::Grip(node) if node == layer => Some(LayerButton::Grip),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connector(&self, key: ConnectorKey) -> Highlight {
|
||||||
|
let key = Some(key);
|
||||||
|
if key == self.snapped_to {
|
||||||
|
Highlight::WireTarget
|
||||||
|
} else if key == self.hovered_connector {
|
||||||
|
Highlight::Hovered
|
||||||
|
} else if key == self.dragged_from {
|
||||||
|
Highlight::WireSource
|
||||||
|
} else {
|
||||||
|
Highlight::None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connectors(&self) -> impl Iterator<Item = ConnectorKey> {
|
||||||
|
[self.hovered_connector, self.dragged_from, self.snapped_to].into_iter().flatten()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn badge_hovered(&self, badge: NodeId) -> bool {
|
||||||
|
self.hovered_part == Some(NodePart::ErrorBadge(badge))
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
use crate::error_badge::ErrorBadge;
|
||||||
|
use crate::highlights::Highlights;
|
||||||
|
use crate::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||||
|
use crate::replicated_map::ReplicatedMap;
|
||||||
|
use crate::scene::Rows;
|
||||||
|
use crate::wire::{WireInProgress, WireStyle};
|
||||||
|
use core_types::list::Item;
|
||||||
|
use core_types::registry::Any;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use core_types::{ProtoNodeIdentifier, Type, item};
|
||||||
|
use glam::DVec2;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
use graphic_types::Graphic;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
pub const SETTLED: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-settled");
|
||||||
|
pub const MOVING: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-moving");
|
||||||
|
pub const NETWORK_CONNECTORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-network-connectors");
|
||||||
|
pub const ERRORS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-errors");
|
||||||
|
pub const THUMBNAILS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-thumbnails");
|
||||||
|
pub const WIRE_IN_PROGRESS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-in-progress");
|
||||||
|
pub const REORDER_BAR: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-reorder-bar");
|
||||||
|
pub const BOX_SELECTION: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-box-selection");
|
||||||
|
pub const FADE_ARTWORK: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-fade-artwork");
|
||||||
|
pub const WIRE_STYLE: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-wire-style");
|
||||||
|
pub const HIGHLIGHTS: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graph-ui-highlights");
|
||||||
|
|
||||||
|
pub type Thumbnails = Arc<BTreeMap<NodeId, Graphic>>;
|
||||||
|
|
||||||
|
macro_rules! tagged_graph_ui_value {
|
||||||
|
($($identifier:ident($ty:ty)),* $(,)?) => {
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub enum TaggedGraphUiValue {
|
||||||
|
$($identifier($ty),)*
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TaggedGraphUiValue {
|
||||||
|
pub fn to_dynany(self) -> Any {
|
||||||
|
match self {
|
||||||
|
$(Self::$identifier(x) => Box::new(Item::new_from_element(x)),)*
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_any(self) -> Arc<dyn std::any::Any + Send + Sync> {
|
||||||
|
match self {
|
||||||
|
$(Self::$identifier(x) => Arc::new(Item::new_from_element(x)),)*
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn ty(&self) -> Type {
|
||||||
|
match self {
|
||||||
|
$(Self::$identifier(_) => item!($ty),)*
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
tagged_graph_ui_value! {
|
||||||
|
Rows(Rows),
|
||||||
|
NetworkConnectors(ReplicatedMap<NetworkConnector>),
|
||||||
|
Errors(ReplicatedMap<ErrorBadge>),
|
||||||
|
Thumbnails(Thumbnails),
|
||||||
|
WireInProgress(Option<WireInProgress>),
|
||||||
|
ReorderBar(Option<(NetworkConnectorKind, DVec2)>),
|
||||||
|
BoxSelection(Option<[DVec2; 2]>),
|
||||||
|
FadeArtwork(f64),
|
||||||
|
WireStyle(WireStyle),
|
||||||
|
Highlights(Highlights),
|
||||||
|
}
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
use crate::card::{Connector, Selection};
|
||||||
|
use crate::geometry::NodeShape;
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Layer {
|
||||||
|
pub key: NodeId,
|
||||||
|
pub shape: NodeShape,
|
||||||
|
pub chain_length: u32,
|
||||||
|
pub name: String,
|
||||||
|
pub renaming: bool,
|
||||||
|
pub has_left_input_wire: bool,
|
||||||
|
pub primary_input: Option<Connector>,
|
||||||
|
pub primary_output: Option<Connector>,
|
||||||
|
pub secondary_input: Option<Connector>,
|
||||||
|
pub primary_input_connected_to_layer: bool,
|
||||||
|
pub primary_output_connected_to_layer: bool,
|
||||||
|
pub visible: bool,
|
||||||
|
pub read_only: bool,
|
||||||
|
pub selection: Selection,
|
||||||
|
pub previewed: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||||
|
pub enum LayerButton {
|
||||||
|
Visibility,
|
||||||
|
Lock,
|
||||||
|
Grip,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for Layer {
|
||||||
|
type Key = NodeId;
|
||||||
|
|
||||||
|
fn key(&self) -> NodeId {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
use glam::{DAffine2, DVec2};
|
||||||
|
use highlights::Highlights;
|
||||||
|
use network_connector::NetworkConnectorKind;
|
||||||
|
use wire::{WireInProgress, WireStyle};
|
||||||
|
|
||||||
|
pub use inputs::TaggedGraphUiValue;
|
||||||
|
|
||||||
|
pub mod card;
|
||||||
|
pub mod dot;
|
||||||
|
pub mod error_badge;
|
||||||
|
pub mod geometry;
|
||||||
|
pub mod highlights;
|
||||||
|
pub mod inputs;
|
||||||
|
pub mod layer;
|
||||||
|
pub mod metrics;
|
||||||
|
pub mod network_connector;
|
||||||
|
pub mod placed;
|
||||||
|
pub mod replicated_map;
|
||||||
|
pub mod scene;
|
||||||
|
pub mod wire;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct GraphUiConfig {
|
||||||
|
pub view: DAffine2,
|
||||||
|
pub fade_artwork: f64,
|
||||||
|
pub wire_in_progress: Option<WireInProgress>,
|
||||||
|
pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>,
|
||||||
|
pub box_selection: Option<[DVec2; 2]>,
|
||||||
|
pub highlights: Highlights,
|
||||||
|
pub wire_style: WireStyle,
|
||||||
|
}
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
use glam::DVec2;
|
||||||
|
|
||||||
|
pub const GRID_SIZE: f64 = 24.;
|
||||||
|
pub const GRID_COLLAPSE_SPACING: f64 = 10.;
|
||||||
|
pub const TEXT_SIZE: f64 = 14.;
|
||||||
|
pub const BORDER_WIDTH: f64 = 1.;
|
||||||
|
pub const BORDER_DASHES: [f64; 2] = [3., 2.];
|
||||||
|
pub const ICON_SIZE: f64 = 16.;
|
||||||
|
|
||||||
|
pub const CARD_GRID_WIDTH: u32 = 5;
|
||||||
|
pub const CARD_RADIUS: f64 = 2.;
|
||||||
|
pub const CARD_ICON_LEFT: f64 = 8.;
|
||||||
|
pub const CARD_NAME_LEFT: f64 = 32.;
|
||||||
|
pub const CARD_NAME_MAX_WIDTH: f64 = 84.;
|
||||||
|
pub const CARD_ROW_PADDING: f64 = 8.;
|
||||||
|
|
||||||
|
pub const CONNECTOR_SIZE: f64 = 8.;
|
||||||
|
pub const INPUT_CONNECTOR_LEFT: f64 = -3.;
|
||||||
|
pub const OUTPUT_CONNECTOR_RIGHT: f64 = 5.;
|
||||||
|
pub const INPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.);
|
||||||
|
pub const OUTPUT_CONNECTOR_OFFSET: DVec2 = DVec2::new(OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE, -CONNECTOR_SIZE / 2.);
|
||||||
|
pub const CONNECTOR_GAP: f64 = 16.;
|
||||||
|
pub const HOVERED_CONNECTOR_SCALE: f64 = 1.3;
|
||||||
|
pub const HOVERED_CONNECTOR_RING: f64 = 4.;
|
||||||
|
pub const STACK_CONNECTOR_SIZE: DVec2 = DVec2::new(CONNECTOR_SIZE, 12.);
|
||||||
|
|
||||||
|
pub const IMPORT_NAME_INSET: f64 = 8.;
|
||||||
|
pub const EXPORT_NAME_INSET: f64 = 9.;
|
||||||
|
pub const NETWORK_CONNECTOR_NAME_RAISE: f64 = 1.;
|
||||||
|
pub const NETWORK_CONNECTOR_SEPARATOR_OVERHANG: f64 = 4.;
|
||||||
|
pub const REORDER_BAR_SIZE: DVec2 = DVec2::new(50., 2.);
|
||||||
|
|
||||||
|
pub const ERROR_PADDING: f64 = 8.;
|
||||||
|
pub const ERROR_LINE_HEIGHT: f64 = 18.;
|
||||||
|
pub const ERROR_MAX_WIDTH: f64 = 600.;
|
||||||
|
pub const ERROR_RADIUS: f64 = 4.;
|
||||||
|
pub const ERROR_TAIL_LEFT: f64 = 6.;
|
||||||
|
pub const ERROR_TAIL_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||||
|
|
||||||
|
pub const WIRE_WIDTH: f64 = 2.;
|
||||||
|
pub const LIST_WIRE_WIDTH: f64 = 4.;
|
||||||
|
pub const WIRE_DASHES: [f64; 2] = [3., 2.];
|
||||||
|
pub const THICK_WIRE_WIDTH: f64 = 8.;
|
||||||
|
|
||||||
|
pub const DOT_RADIUS: f64 = 5.;
|
||||||
|
pub const DOT_SELECTED_RING: f64 = 2.;
|
||||||
|
pub const DOT_PREVIEWED_RING_OFFSET: f64 = 2.;
|
||||||
|
pub const DOT_HOVERED_RING: f64 = 2.;
|
||||||
|
pub const DOT_OUTPUT_ARROW: DVec2 = DVec2::new(WAYPOINT_GUTTER_OFFSET - CONNECTOR_SIZE / 2., -CONNECTOR_SIZE / 2.);
|
||||||
|
|
||||||
|
pub const LAYER_RADIUS: f64 = 8.;
|
||||||
|
pub const LAYER_LEFT_MARGIN: f64 = GRID_SIZE / 2.;
|
||||||
|
pub const LAYER_THUMBNAIL_WIDTH: f64 = 3. * GRID_SIZE;
|
||||||
|
pub const LAYER_THUMBNAIL_MARGIN: f64 = 1.;
|
||||||
|
pub const LAYER_THUMBNAIL_RADIUS: f64 = 2.;
|
||||||
|
pub const LAYER_THUMBNAIL_IMAGE_INSET: f64 = 2.;
|
||||||
|
pub const LAYER_DETAILS_MARGIN: f64 = 8.;
|
||||||
|
pub const LAYER_NAME_LEFT: f64 = LAYER_LEFT_MARGIN + LAYER_THUMBNAIL_WIDTH + LAYER_DETAILS_MARGIN;
|
||||||
|
pub const LAYER_BUTTON_SIZE: f64 = GRID_SIZE;
|
||||||
|
pub const LAYER_BUTTON_RADIUS: f64 = 2.;
|
||||||
|
pub const LAYER_GRIP_WIDTH: f64 = 8.;
|
||||||
|
pub const LAYER_GRIP_DOTS: DVec2 = DVec2::new(2.5, 9.5);
|
||||||
|
pub const LAYER_GRIP_DOT_COUNT: [u32; 2] = [2, 3];
|
||||||
|
pub const LAYER_GRIP_DOT_SPACING: f64 = 3.;
|
||||||
|
pub const LAYER_GRIP_DOT_RADIUS: f64 = 0.5;
|
||||||
|
pub const LAYER_THUMBNAIL_GAP: DVec2 = DVec2::new(8., 2.);
|
||||||
|
|
||||||
|
pub const CHECKER_CELL: f64 = 8.;
|
||||||
|
pub const CLICK_RADIUS: f64 = 3.;
|
||||||
|
pub const LAYER_CLICK_RADIUS: f64 = 10.;
|
||||||
|
pub const PORT_CLICK_RADIUS: f64 = 4.;
|
||||||
|
pub const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
|
||||||
|
pub const SIDE_PORT_INWARD_REACH: f64 = 8.;
|
||||||
|
pub const SIDE_PORT_HALF_HEIGHT: f64 = GRID_SIZE / 2.;
|
||||||
|
pub const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||||
|
pub const STACK_ANCHOR_DISTANCE: f64 = 8.;
|
||||||
|
|
||||||
|
pub const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
|
||||||
|
pub const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
|
||||||
|
pub const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
use crate::card::Connector;
|
||||||
|
use crate::geometry::WireEnd;
|
||||||
|
use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_NAME_INSET, INPUT_CONNECTOR_OFFSET, NETWORK_CONNECTOR_NAME_RAISE, NETWORK_CONNECTOR_SEPARATOR_OVERHANG, REORDER_BAR_SIZE};
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use glam::{DVec2, IVec2};
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash, DynAny)]
|
||||||
|
pub enum NetworkConnectorKind {
|
||||||
|
Import,
|
||||||
|
Export,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
pub enum NetworkConnectorKey {
|
||||||
|
Import(usize),
|
||||||
|
Export(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NetworkConnectorKey {
|
||||||
|
pub fn new(kind: NetworkConnectorKind, index: usize) -> Self {
|
||||||
|
match kind {
|
||||||
|
NetworkConnectorKind::Import => Self::Import(index),
|
||||||
|
NetworkConnectorKind::Export => Self::Export(index),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn kind(self) -> NetworkConnectorKind {
|
||||||
|
match self {
|
||||||
|
Self::Import(_) => NetworkConnectorKind::Import,
|
||||||
|
Self::Export(_) => NetworkConnectorKind::Export,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn index(self) -> usize {
|
||||||
|
match self {
|
||||||
|
Self::Import(index) | Self::Export(index) => index,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct NetworkConnector {
|
||||||
|
pub key: NetworkConnectorKey,
|
||||||
|
pub position: IVec2,
|
||||||
|
pub connector: Option<Connector>,
|
||||||
|
pub editable: bool,
|
||||||
|
pub renaming: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for NetworkConnector {
|
||||||
|
type Key = NetworkConnectorKey;
|
||||||
|
|
||||||
|
fn key(&self) -> NetworkConnectorKey {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NetworkConnector {
|
||||||
|
pub fn anchor(&self) -> DVec2 {
|
||||||
|
self.position.as_dvec2()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn wire_end(&self) -> Option<WireEnd> {
|
||||||
|
let position = self.anchor();
|
||||||
|
self.connector.is_some().then_some(WireEnd { position, vertical: false })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn connector_top_left(&self) -> DVec2 {
|
||||||
|
self.anchor() + INPUT_CONNECTOR_OFFSET
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn name_box(&self, width: f64) -> [DVec2; 2] {
|
||||||
|
network_connector_name_box(self.key.kind(), self.anchor(), width).map(|corner| corner - DVec2::Y * NETWORK_CONNECTOR_NAME_RAISE)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn separator(&self, name_width: f64) -> [DVec2; 2] {
|
||||||
|
let [name_min, name_max] = self.name_box(name_width);
|
||||||
|
let toward_the_line = if self.key.index() == 0 { GRID_SIZE } else { -GRID_SIZE };
|
||||||
|
let top = self.anchor().y + toward_the_line - BORDER_WIDTH;
|
||||||
|
[
|
||||||
|
DVec2::new(name_min.x - NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top),
|
||||||
|
DVec2::new(name_max.x + NETWORK_CONNECTOR_SEPARATOR_OVERHANG, top + BORDER_WIDTH),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reorder_bar(kind: NetworkConnectorKind, anchor: DVec2) -> [DVec2; 2] {
|
||||||
|
let left = match kind {
|
||||||
|
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - REORDER_BAR_SIZE.x,
|
||||||
|
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||||
|
};
|
||||||
|
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
|
||||||
|
[top_left, top_left + REORDER_BAR_SIZE]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn network_connector_name_box(kind: NetworkConnectorKind, anchor: DVec2, width: f64) -> [DVec2; 2] {
|
||||||
|
let left = match kind {
|
||||||
|
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - width,
|
||||||
|
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||||
|
};
|
||||||
|
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
|
||||||
|
[top_left, top_left + DVec2::new(width, GRID_SIZE)]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn network_connector_row_offset(index: usize) -> f64 {
|
||||||
|
let rows = if index == 0 { 0 } else { index + 1 };
|
||||||
|
rows as f64 * GRID_SIZE
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use glam::IVec2;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Placed<T> {
|
||||||
|
pub cell: IVec2,
|
||||||
|
pub look: T,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed> Keyed for Placed<T> {
|
||||||
|
type Key = T::Key;
|
||||||
|
|
||||||
|
fn key(&self) -> T::Key {
|
||||||
|
self.look.key()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
use dyn_any::StaticType;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::hash::{DefaultHasher, Hasher};
|
||||||
|
use std::ops::Deref;
|
||||||
|
use std::sync::{Arc, OnceLock};
|
||||||
|
|
||||||
|
pub trait Keyed: Clone {
|
||||||
|
type Key: Ord + Clone + Debug;
|
||||||
|
|
||||||
|
fn key(&self) -> Self::Key;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct ReplicatedMap<T: Keyed> {
|
||||||
|
items: Arc<Vec<T>>,
|
||||||
|
hash: Arc<OnceLock<u64>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed> Default for ReplicatedMap<T> {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
items: Arc::default(),
|
||||||
|
hash: Arc::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed + PartialEq> PartialEq for ReplicatedMap<T> {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.items == other.items
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe impl<T: Keyed + 'static> StaticType for ReplicatedMap<T> {
|
||||||
|
type Static = Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed + CacheHash> CacheHash for ReplicatedMap<T> {
|
||||||
|
fn cache_hash<H: Hasher>(&self, state: &mut H) {
|
||||||
|
let hash = self.hash.get_or_init(|| {
|
||||||
|
let mut hasher = DefaultHasher::new();
|
||||||
|
self.items.cache_hash(&mut hasher);
|
||||||
|
hasher.finish()
|
||||||
|
});
|
||||||
|
state.write_u64(*hash);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed> ReplicatedMap<T> {
|
||||||
|
pub fn get(&self, key: &T::Key) -> Option<&T> {
|
||||||
|
self.position(key).ok().map(|index| &self.items[index])
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn iter(&self) -> std::slice::Iter<'_, T> {
|
||||||
|
self.items.iter()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.items.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.items.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn edit(self) -> ReplicatedMapEdit<T> {
|
||||||
|
ReplicatedMapEdit { map: self, deltas: Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply(&mut self, deltas: impl IntoIterator<Item = ReplicatedMapDelta<T>>) {
|
||||||
|
for delta in deltas {
|
||||||
|
match delta {
|
||||||
|
ReplicatedMapDelta::Put(item) => self.put(item),
|
||||||
|
ReplicatedMapDelta::Remove(key) => {
|
||||||
|
let removed = self.remove(&key);
|
||||||
|
debug_assert!(removed, "a delta removes an item that its map never held");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn position(&self, key: &T::Key) -> Result<usize, usize> {
|
||||||
|
self.items.binary_search_by(|item| item.key().cmp(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn items_mut(&mut self) -> &mut Vec<T> {
|
||||||
|
self.hash = Arc::default();
|
||||||
|
Arc::make_mut(&mut self.items)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(&mut self, item: T) {
|
||||||
|
match self.position(&item.key()) {
|
||||||
|
Ok(index) => self.items_mut()[index] = item,
|
||||||
|
Err(index) => self.items_mut().insert(index, item),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&mut self, key: &T::Key) -> bool {
|
||||||
|
let position = self.position(key);
|
||||||
|
if let Ok(index) = position {
|
||||||
|
self.items_mut().remove(index);
|
||||||
|
}
|
||||||
|
position.is_ok()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a, T: Keyed> IntoIterator for &'a ReplicatedMap<T> {
|
||||||
|
type Item = &'a T;
|
||||||
|
type IntoIter = std::slice::Iter<'a, T>;
|
||||||
|
|
||||||
|
fn into_iter(self) -> Self::IntoIter {
|
||||||
|
self.iter()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum ReplicatedMapDelta<T: Keyed> {
|
||||||
|
Put(T),
|
||||||
|
Remove(T::Key),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ReplicatedMapEdit<T: Keyed> {
|
||||||
|
map: ReplicatedMap<T>,
|
||||||
|
deltas: Vec<ReplicatedMapDelta<T>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed> Deref for ReplicatedMapEdit<T> {
|
||||||
|
type Target = ReplicatedMap<T>;
|
||||||
|
|
||||||
|
fn deref(&self) -> &Self::Target {
|
||||||
|
&self.map
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<T: Keyed> ReplicatedMapEdit<T> {
|
||||||
|
pub fn put(&mut self, item: T)
|
||||||
|
where
|
||||||
|
T: PartialEq,
|
||||||
|
{
|
||||||
|
if self.map.get(&item.key()) == Some(&item) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.map.put(item.clone());
|
||||||
|
self.deltas.push(ReplicatedMapDelta::Put(item));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update(&mut self, key: &T::Key, change: impl FnOnce(&mut T)) -> bool {
|
||||||
|
let Ok(index) = self.map.position(key) else { return false };
|
||||||
|
let item = &mut self.map.items_mut()[index];
|
||||||
|
change(item);
|
||||||
|
debug_assert!(item.key() == *key, "an update must not change the key of its item");
|
||||||
|
self.deltas.push(ReplicatedMapDelta::Put(item.clone()));
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&mut self, key: &T::Key) -> bool {
|
||||||
|
let removed = self.map.remove(key);
|
||||||
|
if removed {
|
||||||
|
self.deltas.push(ReplicatedMapDelta::Remove(key.clone()));
|
||||||
|
}
|
||||||
|
removed
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn replace_all(&mut self, items: impl IntoIterator<Item = T>)
|
||||||
|
where
|
||||||
|
T: PartialEq,
|
||||||
|
{
|
||||||
|
let mut items: Vec<T> = items.into_iter().collect();
|
||||||
|
items.sort_by_key(T::key);
|
||||||
|
debug_assert!(items.windows(2).all(|pair| pair[0].key() != pair[1].key()), "two items of a map share a key");
|
||||||
|
|
||||||
|
let removed = self.map.iter().rev().map(T::key).filter(|key| items.binary_search_by(|item| item.key().cmp(key)).is_err());
|
||||||
|
self.deltas.extend(removed.map(ReplicatedMapDelta::Remove));
|
||||||
|
let put = items.iter().filter(|item| self.map.get(&item.key()) != Some(item));
|
||||||
|
self.deltas.extend(put.cloned().map(ReplicatedMapDelta::Put));
|
||||||
|
|
||||||
|
*self.map.items_mut() = items;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn finish(self) -> (ReplicatedMap<T>, Vec<ReplicatedMapDelta<T>>) {
|
||||||
|
(self.map, self.deltas)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,161 @@
|
|||||||
|
use crate::card::Card;
|
||||||
|
use crate::dot::Dot;
|
||||||
|
use crate::error_badge::ErrorBadge;
|
||||||
|
use crate::layer::Layer;
|
||||||
|
use crate::network_connector::NetworkConnector;
|
||||||
|
use crate::placed::Placed;
|
||||||
|
use crate::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit};
|
||||||
|
use crate::wire::Wire;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, CacheHash, DynAny)]
|
||||||
|
pub struct Rows {
|
||||||
|
pub cards: ReplicatedMap<Placed<Card>>,
|
||||||
|
pub layers: ReplicatedMap<Placed<Layer>>,
|
||||||
|
pub dots: ReplicatedMap<Placed<Dot>>,
|
||||||
|
pub wires: ReplicatedMap<Wire>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rows {
|
||||||
|
fn edit(self) -> RowsEdit {
|
||||||
|
RowsEdit {
|
||||||
|
cards: self.cards.edit(),
|
||||||
|
layers: self.layers.edit(),
|
||||||
|
dots: self.dots.edit(),
|
||||||
|
wires: self.wires.edit(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn apply(&mut self, delta: RowsDelta) {
|
||||||
|
self.cards.apply(delta.cards);
|
||||||
|
self.layers.apply(delta.layers);
|
||||||
|
self.dots.apply(delta.dots);
|
||||||
|
self.wires.apply(delta.wires);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct GraphUiScene {
|
||||||
|
settled: Rows,
|
||||||
|
moving: Rows,
|
||||||
|
network_connectors: ReplicatedMap<NetworkConnector>,
|
||||||
|
errors: ReplicatedMap<ErrorBadge>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphUiScene {
|
||||||
|
pub fn settled(&self) -> &Rows {
|
||||||
|
&self.settled
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn moving(&self) -> &Rows {
|
||||||
|
&self.moving
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn network_connectors(&self) -> &ReplicatedMap<NetworkConnector> {
|
||||||
|
&self.network_connectors
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn errors(&self) -> &ReplicatedMap<ErrorBadge> {
|
||||||
|
&self.errors
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn edit(self) -> GraphUiSceneEdit {
|
||||||
|
GraphUiSceneEdit {
|
||||||
|
settled: self.settled.edit(),
|
||||||
|
moving: self.moving.edit(),
|
||||||
|
network_connectors: self.network_connectors.edit(),
|
||||||
|
errors: self.errors.edit(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply(&mut self, delta: GraphUiSceneDelta) {
|
||||||
|
self.settled.apply(delta.settled);
|
||||||
|
self.moving.apply(delta.moving);
|
||||||
|
self.network_connectors.apply(delta.network_connectors);
|
||||||
|
self.errors.apply(delta.errors);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct RowsEdit {
|
||||||
|
pub cards: ReplicatedMapEdit<Placed<Card>>,
|
||||||
|
pub layers: ReplicatedMapEdit<Placed<Layer>>,
|
||||||
|
pub dots: ReplicatedMapEdit<Placed<Dot>>,
|
||||||
|
pub wires: ReplicatedMapEdit<Wire>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RowsEdit {
|
||||||
|
fn finish(self) -> (Rows, RowsDelta) {
|
||||||
|
let (cards, card_deltas) = self.cards.finish();
|
||||||
|
let (layers, layer_deltas) = self.layers.finish();
|
||||||
|
let (dots, dot_deltas) = self.dots.finish();
|
||||||
|
let (wires, wire_deltas) = self.wires.finish();
|
||||||
|
(
|
||||||
|
Rows { cards, layers, dots, wires },
|
||||||
|
RowsDelta {
|
||||||
|
cards: card_deltas,
|
||||||
|
layers: layer_deltas,
|
||||||
|
dots: dot_deltas,
|
||||||
|
wires: wire_deltas,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct GraphUiSceneEdit {
|
||||||
|
pub settled: RowsEdit,
|
||||||
|
pub moving: RowsEdit,
|
||||||
|
pub network_connectors: ReplicatedMapEdit<NetworkConnector>,
|
||||||
|
pub errors: ReplicatedMapEdit<ErrorBadge>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphUiSceneEdit {
|
||||||
|
pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) {
|
||||||
|
let (settled, settled_delta) = self.settled.finish();
|
||||||
|
let (moving, moving_delta) = self.moving.finish();
|
||||||
|
let (network_connectors, network_connector_deltas) = self.network_connectors.finish();
|
||||||
|
let (errors, error_deltas) = self.errors.finish();
|
||||||
|
(
|
||||||
|
GraphUiScene {
|
||||||
|
settled,
|
||||||
|
moving,
|
||||||
|
network_connectors,
|
||||||
|
errors,
|
||||||
|
},
|
||||||
|
GraphUiSceneDelta {
|
||||||
|
settled: settled_delta,
|
||||||
|
moving: moving_delta,
|
||||||
|
network_connectors: network_connector_deltas,
|
||||||
|
errors: error_deltas,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct RowsDelta {
|
||||||
|
cards: Vec<ReplicatedMapDelta<Placed<Card>>>,
|
||||||
|
layers: Vec<ReplicatedMapDelta<Placed<Layer>>>,
|
||||||
|
dots: Vec<ReplicatedMapDelta<Placed<Dot>>>,
|
||||||
|
wires: Vec<ReplicatedMapDelta<Wire>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RowsDelta {
|
||||||
|
fn is_empty(&self) -> bool {
|
||||||
|
self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct GraphUiSceneDelta {
|
||||||
|
settled: RowsDelta,
|
||||||
|
moving: RowsDelta,
|
||||||
|
network_connectors: Vec<ReplicatedMapDelta<NetworkConnector>>,
|
||||||
|
errors: Vec<ReplicatedMapDelta<ErrorBadge>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphUiSceneDelta {
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.settled.is_empty() && self.moving.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
use crate::card::DataType;
|
||||||
|
use crate::geometry::WireEnd;
|
||||||
|
use crate::replicated_map::Keyed;
|
||||||
|
use core_types::uuid::NodeId;
|
||||||
|
use dyn_any::DynAny;
|
||||||
|
use graphene_hash::CacheHash;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||||
|
pub struct Wire {
|
||||||
|
pub key: WireKey,
|
||||||
|
pub from: OutputKey,
|
||||||
|
pub to: InputKey,
|
||||||
|
pub data_type: DataType,
|
||||||
|
pub list: bool,
|
||||||
|
pub insertion_target: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||||
|
pub enum WireKey {
|
||||||
|
Input(InputKey),
|
||||||
|
Preview,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||||
|
pub enum OutputKey {
|
||||||
|
Node { node: NodeId, index: usize },
|
||||||
|
Import(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||||
|
pub enum InputKey {
|
||||||
|
Node { node: NodeId, index: usize },
|
||||||
|
Export(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Keyed for Wire {
|
||||||
|
type Key = WireKey;
|
||||||
|
|
||||||
|
fn key(&self) -> WireKey {
|
||||||
|
self.key
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, CacheHash, DynAny)]
|
||||||
|
pub struct WireInProgress {
|
||||||
|
pub ends: [WireEnd; 2],
|
||||||
|
pub data_type: DataType,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||||
|
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||||
|
#[derive(Copy, Clone, Debug, PartialEq, Default, CacheHash, DynAny)]
|
||||||
|
pub enum WireStyle {
|
||||||
|
#[default]
|
||||||
|
Direct = 0,
|
||||||
|
GridAligned = 1,
|
||||||
|
}
|
||||||
@@ -128,7 +128,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
|||||||
impl CompiledDocument {
|
impl CompiledDocument {
|
||||||
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
pub fn into_renderer(self) -> Result<Renderer, Box<dyn Error>> {
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(self.proto_network).map_err(|(_, errors)| {
|
let output = executor.insert(self.proto_network).map_err(|errors| {
|
||||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||||
messages.join("\n")
|
messages.join("\n")
|
||||||
})?;
|
})?;
|
||||||
|
|||||||
@@ -133,13 +133,13 @@ impl Viewer {
|
|||||||
Err(error) => return log::error!("Compile failed: {error}"),
|
Err(error) => return log::error!("Compile failed: {error}"),
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
match executor.update(proto) {
|
match executor.insert(proto) {
|
||||||
Ok((output, _)) => {
|
Ok(output) => {
|
||||||
self.graph_runtime.update_sources(executor.sources());
|
self.graph_runtime.update_sources(executor.sources());
|
||||||
log::info!("Document compiled");
|
log::info!("Document compiled");
|
||||||
self.executor = Some((executor, output));
|
self.executor = Some((executor, output));
|
||||||
}
|
}
|
||||||
Err((_, errors)) => {
|
Err(errors) => {
|
||||||
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
let messages: Vec<String> = errors.iter().map(|error| format!("{error:?}")).collect();
|
||||||
log::error!("Executor creation failed: {}", messages.join("\n"));
|
log::error!("Executor creation failed: {}", messages.join("\n"));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,7 +18,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
|||||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||||
let proto_network = compile(network);
|
let proto_network = compile(network);
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(proto_network.clone()).unwrap();
|
let output = executor.insert(proto_network.clone()).unwrap();
|
||||||
(executor, output, proto_network)
|
(executor, output, proto_network)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ impl Session {
|
|||||||
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
self.output = self.executor.insert(proto_network).expect("Failed to update the executor");
|
||||||
|
|
||||||
let render_config = RenderConfig {
|
let render_config = RenderConfig {
|
||||||
viewport: Footprint {
|
viewport: Footprint {
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ fn update_executor<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
|||||||
c.bench_function(name, |b| {
|
c.bench_function(name, |b| {
|
||||||
b.iter_batched(
|
b.iter_batched(
|
||||||
|| (executor.clone(), proto_network.clone()),
|
|| (executor.clone(), proto_network.clone()),
|
||||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
|
||||||
criterion::BatchSize::SmallInput,
|
criterion::BatchSize::SmallInput,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
@@ -36,7 +36,7 @@ fn run_once<M: Measurement>(name: &str, c: &mut BenchmarkGroup<M>) {
|
|||||||
let proto_network = compile(network);
|
let proto_network = compile(network);
|
||||||
|
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(proto_network).unwrap();
|
let output = executor.insert(proto_network).unwrap();
|
||||||
let footprint = Footprint::default();
|
let footprint = Footprint::default();
|
||||||
|
|
||||||
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
|
c.bench_function(name, |b| b.iter(|| executor.execute(&output, footprint)));
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ fn update_executor(c: &mut Criterion) {
|
|||||||
let (_, _, proto_network) = setup_network(name);
|
let (_, _, proto_network) = setup_network(name);
|
||||||
(DynamicExecutor::default(), proto_network)
|
(DynamicExecutor::default(), proto_network)
|
||||||
},
|
},
|
||||||
|(mut executor, network)| executor.update(std::hint::black_box(network)),
|
|(mut executor, network)| executor.insert(std::hint::black_box(network)),
|
||||||
criterion::BatchSize::SmallInput,
|
criterion::BatchSize::SmallInput,
|
||||||
)
|
)
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ fn setup_update_executor(name: &str) -> (DynamicExecutor, ProtoNetwork) {
|
|||||||
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
#[benches::with_setup(args = ["isometric-fountain", "painted-dreams", "procedural-string-lights", "parametric-dunescape", "red-dress", "valley-of-spires"], setup = setup_update_executor)]
|
||||||
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
pub fn update_executor(setup: (DynamicExecutor, ProtoNetwork)) -> DynamicExecutor {
|
||||||
let (mut executor, network) = setup;
|
let (mut executor, network) = setup;
|
||||||
let _ = black_box(executor.update(black_box(network)));
|
let _ = black_box(executor.insert(black_box(network)));
|
||||||
|
|
||||||
// Return the executor so its teardown happens outside the measured section
|
// Return the executor so its teardown happens outside the measured section
|
||||||
executor
|
executor
|
||||||
|
|||||||
@@ -19,8 +19,7 @@ pub struct DynamicExecutor {
|
|||||||
typing_context: TypingContext,
|
typing_context: TypingContext,
|
||||||
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
|
/// The outputs of the networks, kept alive by the executor as long as there are handles to them.
|
||||||
outputs: Vec<Weak<NodeId>>,
|
outputs: Vec<Weak<NodeId>>,
|
||||||
// Kept for one more update, so a node that comes back is reused
|
type_deltas: TypeDeltaCollector,
|
||||||
orphaned_nodes: HashSet<NodeId>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default)]
|
#[derive(Clone, Debug, Default)]
|
||||||
@@ -38,7 +37,7 @@ impl Default for DynamicExecutor {
|
|||||||
tree: Default::default(),
|
tree: Default::default(),
|
||||||
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
typing_context: TypingContext::new(&node_registry::NODE_REGISTRY),
|
||||||
outputs: Vec::new(),
|
outputs: Vec::new(),
|
||||||
orphaned_nodes: HashSet::new(),
|
type_deltas: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -64,19 +63,37 @@ impl DynamicExecutor {
|
|||||||
|
|
||||||
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
/// Adds the [`ProtoNetwork`] to the existing [`BorrowTree`], reusing nodes where possible.
|
||||||
#[cfg_attr(debug_assertions, inline(never))]
|
#[cfg_attr(debug_assertions, inline(never))]
|
||||||
pub fn update(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn insert(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||||
let (output, add) = self.insert_nodes(proto_network)?;
|
let output = self.insert_nodes(proto_network)?;
|
||||||
let remove = self.free_orphaned_nodes();
|
self.free_orphaned_nodes();
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove }))
|
Ok(output)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update_without_freeing(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, ResolvedDocumentNodeTypesDelta), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn replace(&mut self, output: OutputHandle, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||||
let (output, add) = self.insert_nodes(proto_network)?;
|
let inserted = self.insert_nodes(proto_network)?;
|
||||||
Ok((output, ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }))
|
let Some(replaced) = Arc::into_inner(output.0) else { return Ok(inserted) };
|
||||||
|
let live: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
||||||
|
let mut pending = vec![replaced];
|
||||||
|
while let Some(node) = pending.pop() {
|
||||||
|
let Some((container, _, inputs)) = self.tree.nodes.get(&node) else { continue };
|
||||||
|
if Arc::strong_count(container) > 1 || live.contains(&node) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
pending.extend(inputs.iter());
|
||||||
|
if let Some(path) = self.tree.free_node(node) {
|
||||||
|
self.type_deltas.remove(path);
|
||||||
|
}
|
||||||
|
self.typing_context.remove_inference(node);
|
||||||
|
}
|
||||||
|
Ok(inserted)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<(OutputHandle, Vec<(Path, NodeTypes)>), (ResolvedDocumentNodeTypesDelta, GraphErrors)> {
|
pub fn take_type_deltas(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
|
||||||
self.typing_context.update(&proto_network).map_err(|e| {
|
self.type_deltas.take()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn insert_nodes(&mut self, proto_network: ProtoNetwork) -> Result<OutputHandle, GraphErrors> {
|
||||||
|
self.typing_context.update(&proto_network).inspect_err(|_| {
|
||||||
// If there is an error then get types that have been resolved before the error
|
// If there is an error then get types that have been resolved before the error
|
||||||
let add = proto_network
|
let add = proto_network
|
||||||
.nodes
|
.nodes
|
||||||
@@ -94,11 +111,13 @@ impl DynamicExecutor {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
.collect::<Vec<_>>();
|
.collect::<Vec<_>>();
|
||||||
(ResolvedDocumentNodeTypesDelta { add, remove: Vec::new() }, e)
|
self.type_deltas.add(add);
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
let output = proto_network.output;
|
let output = proto_network.output;
|
||||||
let add = self.tree.update(proto_network, &self.typing_context).map_err(|e| (ResolvedDocumentNodeTypesDelta::default(), e))?;
|
|
||||||
|
let add = self.tree.update(proto_network, &self.typing_context)?;
|
||||||
|
|
||||||
self.outputs.retain(|output| output.strong_count() > 0);
|
self.outputs.retain(|output| output.strong_count() > 0);
|
||||||
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
let held = self.outputs.iter().filter_map(Weak::upgrade).find(|held| **held == output);
|
||||||
let output = held.unwrap_or_else(|| {
|
let output = held.unwrap_or_else(|| {
|
||||||
@@ -107,11 +126,11 @@ impl DynamicExecutor {
|
|||||||
output
|
output
|
||||||
});
|
});
|
||||||
|
|
||||||
let add = self.document_node_types(add.into_iter()).collect();
|
self.type_deltas.add(self.tree.node_types(add.into_iter()));
|
||||||
Ok((OutputHandle(output), add))
|
Ok(OutputHandle(output))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn free_orphaned_nodes(&mut self) -> Vec<Path> {
|
fn free_orphaned_nodes(&mut self) {
|
||||||
let mut kept = HashSet::new();
|
let mut kept = HashSet::new();
|
||||||
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
let mut pending: Vec<NodeId> = self.outputs.iter().filter_map(Weak::upgrade).map(|output| *output).collect();
|
||||||
while let Some(node) = pending.pop() {
|
while let Some(node) = pending.pop() {
|
||||||
@@ -121,20 +140,15 @@ impl DynamicExecutor {
|
|||||||
pending.extend(inputs.iter());
|
pending.extend(inputs.iter());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let orphaned = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
let orphaned: Vec<NodeId> = self.tree.nodes.keys().filter(|node| !kept.contains(node)).copied().collect();
|
||||||
let old_to_remove = core::mem::replace(&mut self.orphaned_nodes, orphaned);
|
for node_id in orphaned {
|
||||||
let mut remove = Vec::with_capacity(old_to_remove.len() - self.orphaned_nodes.len().min(old_to_remove.len()));
|
|
||||||
for node_id in old_to_remove {
|
|
||||||
if self.orphaned_nodes.contains(&node_id) {
|
|
||||||
let path = self.tree.free_node(node_id);
|
let path = self.tree.free_node(node_id);
|
||||||
self.typing_context.remove_inference(node_id);
|
self.typing_context.remove_inference(node_id);
|
||||||
if let Some(path) = path {
|
if let Some(path) = path {
|
||||||
remove.push(path);
|
self.type_deltas.remove(path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
remove
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
|
pub fn execute<I: 'static + WasmNotSend>(&self, output: &OutputHandle, input: I) -> Result<Poll<TaggedValue>, Box<dyn Error>> {
|
||||||
self.tree.eval_tagged_value(output.node(), &input).map_err(|error| error.into())
|
self.tree.eval_tagged_value(output.node(), &input).map_err(|error| error.into())
|
||||||
@@ -153,7 +167,7 @@ impl DynamicExecutor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
pub fn document_node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
||||||
nodes.flat_map(|id| self.tree.source_map().get(&id).map(|(_, b)| (id, b.clone())))
|
self.tree.node_types(nodes)
|
||||||
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
|
// TODO: https://github.com/GraphiteEditor/Graphite/issues/1767
|
||||||
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
|
// TODO: Non exposed inputs are not added to the inputs_source_map, so they are not included in the resolved_document_node_types. The type is still available in the typing_context. This only affects the UI-only "Import" node.
|
||||||
}
|
}
|
||||||
@@ -559,6 +573,39 @@ impl BorrowTree {
|
|||||||
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
pub fn source_map(&self) -> &HashMap<Path, (NodeId, NodeTypes)> {
|
||||||
&self.source_map
|
&self.source_map
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn node_types<'a>(&'a self, nodes: impl Iterator<Item = Path> + 'a) -> impl Iterator<Item = (Path, NodeTypes)> + 'a {
|
||||||
|
nodes.flat_map(|id| self.source_map().get(&id).map(|(_, b)| (id, b.clone())))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct TypeDeltaCollector {
|
||||||
|
changes: HashMap<Path, Option<NodeTypes>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TypeDeltaCollector {
|
||||||
|
fn add(&mut self, types: impl IntoIterator<Item = (Path, NodeTypes)>) {
|
||||||
|
self.changes.extend(types.into_iter().map(|(path, types)| (path, Some(types))));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn remove(&mut self, path: Path) {
|
||||||
|
self.changes.insert(path, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn take(&mut self) -> Option<ResolvedDocumentNodeTypesDelta> {
|
||||||
|
if self.changes.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut delta = ResolvedDocumentNodeTypesDelta::default();
|
||||||
|
for (path, types) in self.changes.drain() {
|
||||||
|
match types {
|
||||||
|
Some(types) => delta.add.push((path, types)),
|
||||||
|
None => delta.remove.push(path),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(delta)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -876,7 +876,7 @@ fn error_traced_through(indices: &[usize]) -> NodeError {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_trace_leads_to_the_node_that_raised_the_error() {
|
fn a_trace_leads_to_the_node_that_raised_the_error() {
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||||
|
|
||||||
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
|
assert!(executor.trace_error(output.node(), &error_traced_through(&[])).is_empty());
|
||||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
|
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0])), [NodeId(0)]);
|
||||||
@@ -899,7 +899,7 @@ fn a_trace_steps_over_the_index_of_a_promotion_adapter() {
|
|||||||
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
|
nodes: vec![(NodeId(0), value_node), (NodeId(1), box_corners_node)],
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(network).unwrap();
|
let output = executor.insert(network).unwrap();
|
||||||
|
|
||||||
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
|
assert_eq!(*executor.trace_error(output.node(), &error_traced_through(&[0, 0])), [NodeId(0)]);
|
||||||
}
|
}
|
||||||
@@ -936,7 +936,7 @@ fn chained_fallbacks_both_reach_the_root() {
|
|||||||
.concat(),
|
.concat(),
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(network).unwrap();
|
let output = executor.insert(network).unwrap();
|
||||||
|
|
||||||
let context: Context = None;
|
let context: Context = None;
|
||||||
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
|
let Ok(Poll::Fallback(boxed)) = executor.execute(&output, context) else {
|
||||||
@@ -966,7 +966,7 @@ fn an_error_after_a_fallback_keeps_both() {
|
|||||||
.concat(),
|
.concat(),
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(network).unwrap();
|
let output = executor.insert(network).unwrap();
|
||||||
|
|
||||||
let context: Context = None;
|
let context: Context = None;
|
||||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||||
@@ -995,7 +995,7 @@ fn a_node_error_names_the_node_that_raised_it() {
|
|||||||
.concat(),
|
.concat(),
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(network).expect("The Throw Error nodes should resolve");
|
let output = executor.insert(network).expect("The Throw Error nodes should resolve");
|
||||||
|
|
||||||
let context: Context = None;
|
let context: Context = None;
|
||||||
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
let Ok(Poll::Error(error)) = executor.execute(&output, context) else {
|
||||||
@@ -1050,7 +1050,7 @@ fn handled_error_network(handler: ProtoNodeIdentifier, handler_inputs: &[u64], k
|
|||||||
.concat(),
|
.concat(),
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(network).expect("The error handling nodes should resolve");
|
let output = executor.insert(network).expect("The error handling nodes should resolve");
|
||||||
(executor, output)
|
(executor, output)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1190,16 +1190,6 @@ fn source_network(node: u64) -> ProtoNetwork {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn update_without_freeing_keeps_the_nodes_the_network_leaves_out() {
|
|
||||||
let mut executor = DynamicExecutor::default();
|
|
||||||
executor.update(source_network(0)).unwrap();
|
|
||||||
|
|
||||||
executor.update_without_freeing(source_network(1)).unwrap();
|
|
||||||
executor.update_without_freeing(source_network(1)).unwrap();
|
|
||||||
assert!(executor.tree().get(NodeId(0)).is_some());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn networks_are_executed_side_by_side_by_their_handles() {
|
fn networks_are_executed_side_by_side_by_their_handles() {
|
||||||
let network = |node: u64| ProtoNetwork {
|
let network = |node: u64| ProtoNetwork {
|
||||||
@@ -1208,8 +1198,8 @@ fn networks_are_executed_side_by_side_by_their_handles() {
|
|||||||
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
|
nodes: vec![value_node(node, TaggedValue::Number(node as f64))],
|
||||||
};
|
};
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (first, _) = executor.update(network(0)).unwrap();
|
let first = executor.insert(network(0)).unwrap();
|
||||||
let (second, _) = executor.update(network(1)).unwrap();
|
let second = executor.insert(network(1)).unwrap();
|
||||||
|
|
||||||
let context: Context = None;
|
let context: Context = None;
|
||||||
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
|
assert_eq!(executor.execute(&first, context.clone()).unwrap(), Poll::Final(TaggedValue::Number(0.)));
|
||||||
@@ -1219,9 +1209,9 @@ fn networks_are_executed_side_by_side_by_their_handles() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn an_output_that_is_already_held_shares_its_handle() {
|
fn an_output_that_is_already_held_shares_its_handle() {
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (first, _) = executor.update(source_network(0)).unwrap();
|
let first = executor.insert(source_network(0)).unwrap();
|
||||||
let (second, _) = executor.update(source_network(0)).unwrap();
|
let second = executor.insert(source_network(0)).unwrap();
|
||||||
let (other, _) = executor.update(source_network(1)).unwrap();
|
let other = executor.insert(source_network(1)).unwrap();
|
||||||
|
|
||||||
assert!(Arc::ptr_eq(&first.0, &second.0));
|
assert!(Arc::ptr_eq(&first.0, &second.0));
|
||||||
assert!(!Arc::ptr_eq(&first.0, &other.0));
|
assert!(!Arc::ptr_eq(&first.0, &other.0));
|
||||||
@@ -1230,28 +1220,123 @@ fn an_output_that_is_already_held_shares_its_handle() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
|
fn a_handle_keeps_its_output_and_the_nodes_that_feed_it() {
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
let (output, _) = executor.update(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
let output = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||||
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
|
let kept = |executor: &DynamicExecutor| [0, 1].map(|node| executor.tree().get(NodeId(node)).is_some());
|
||||||
|
|
||||||
for _ in 0..3 {
|
for _ in 0..3 {
|
||||||
executor.update(source_network(2)).unwrap();
|
executor.insert(source_network(2)).unwrap();
|
||||||
}
|
}
|
||||||
assert_eq!(kept(&executor), [true; 2]);
|
assert_eq!(kept(&executor), [true; 2]);
|
||||||
|
|
||||||
drop(output);
|
drop(output);
|
||||||
executor.update(source_network(2)).unwrap();
|
executor.insert(source_network(2)).unwrap();
|
||||||
assert_eq!(kept(&executor), [true; 2], "orphaned for one more update");
|
|
||||||
executor.update(source_network(2)).unwrap();
|
|
||||||
assert_eq!(kept(&executor), [false; 2]);
|
assert_eq!(kept(&executor), [false; 2]);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn a_source_is_listed_for_as_long_as_its_node_lives() {
|
fn a_source_is_listed_for_as_long_as_its_node_lives() {
|
||||||
let mut executor = DynamicExecutor::default();
|
let mut executor = DynamicExecutor::default();
|
||||||
executor.update(source_network(0)).unwrap();
|
let output = executor.insert(source_network(0)).unwrap();
|
||||||
|
let listed = |executor: &DynamicExecutor| executor.sources().any(|source| *source == SourceId(0));
|
||||||
|
|
||||||
for _ in 0..3 {
|
executor.insert(source_network(1)).unwrap();
|
||||||
executor.update(source_network(1)).unwrap();
|
assert!(listed(&executor));
|
||||||
assert_eq!(executor.sources().any(|source| *source == SourceId(0)), executor.tree().get(NodeId(0)).is_some());
|
|
||||||
|
drop(output);
|
||||||
|
executor.insert(source_network(1)).unwrap();
|
||||||
|
assert!(!listed(&executor));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn changed_paths(executor: &mut DynamicExecutor) -> Option<[Vec<u64>; 2]> {
|
||||||
|
let changes = executor.take_type_deltas()?;
|
||||||
|
let added = changes.add.iter().map(|(path, _)| path[0].0);
|
||||||
|
let removed = changes.remove.iter().map(|path| path[0].0);
|
||||||
|
let mut paths = [added.collect::<Vec<_>>(), removed.collect()];
|
||||||
|
paths.iter_mut().for_each(|paths| paths.sort_unstable());
|
||||||
|
Some(paths)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn take_type_deltas_gives_the_paths_inserted_and_freed_since_the_last_take() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let held = [executor.insert(source_network(0)).unwrap(), executor.insert(source_network(1)).unwrap()];
|
||||||
|
assert_eq!(changed_paths(&mut executor), Some([vec![0, 1], vec![]]));
|
||||||
|
assert_eq!(changed_paths(&mut executor), None);
|
||||||
|
|
||||||
|
drop(held);
|
||||||
|
executor.insert(source_network(2)).unwrap();
|
||||||
|
assert_eq!(changed_paths(&mut executor), Some([vec![2], vec![0, 1]]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_path_freed_and_inserted_again_between_two_takes_is_given_with_its_types() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
executor.insert(source_network(0)).unwrap();
|
||||||
|
executor.take_type_deltas();
|
||||||
|
|
||||||
|
executor.insert(source_network(1)).unwrap();
|
||||||
|
executor.insert(source_network(0)).unwrap();
|
||||||
|
let path: Path = [NodeId(0)].into();
|
||||||
|
let types = executor.tree().source_map()[&path].1.clone();
|
||||||
|
assert_eq!(executor.take_type_deltas().unwrap().add, [(path, types)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_path_typed_before_a_type_error_is_given() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
executor.insert(bounding_box_network(TaggedValue::Number(1.))).unwrap_err();
|
||||||
|
assert_eq!(changed_paths(&mut executor), Some([vec![0], vec![]]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replace_frees_what_only_the_replaced_output_reached() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let replaced = executor.insert(bounding_box_network(TaggedValue::TypeDefault(item!(Vector)))).unwrap();
|
||||||
|
|
||||||
|
executor.replace(replaced, source_network(2)).unwrap();
|
||||||
|
for node in [NodeId(0), NodeId(1)] {
|
||||||
|
assert!(executor.tree().get(node).is_none());
|
||||||
|
assert!(executor.typing_context.type_of(node).is_none());
|
||||||
|
}
|
||||||
|
let delta = executor.take_type_deltas().unwrap();
|
||||||
|
let mut removed: Vec<_> = delta.remove.iter().map(|path| path.to_vec()).collect();
|
||||||
|
removed.sort();
|
||||||
|
assert_eq!(removed, [vec![NodeId(0)], vec![NodeId(1)]]);
|
||||||
|
assert_eq!(executor.tree().source_map().keys().map(|path| path.to_vec()).collect::<Vec<_>>(), [vec![NodeId(2)]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replace_keeps_what_the_new_network_or_another_output_still_reaches() {
|
||||||
|
let content = TaggedValue::TypeDefault(item!(Vector));
|
||||||
|
let value_network = |(output, node)| ProtoNetwork {
|
||||||
|
inputs: vec![],
|
||||||
|
output,
|
||||||
|
nodes: vec![(output, node)],
|
||||||
|
};
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let _document = executor.insert(value_network(value_node(0, content.clone()))).unwrap();
|
||||||
|
let replaced = executor.insert(offset_points_network(content)).unwrap();
|
||||||
|
|
||||||
|
executor.replace(replaced, value_network(value_node(1, TaggedValue::Number(10.)))).unwrap();
|
||||||
|
assert_eq!([0, 1, 2, 3].map(|node| executor.tree().get(NodeId(node)).is_some()), [true, true, false, false]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replace_frees_nothing_while_the_replaced_handle_is_held_elsewhere() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let held = executor.insert(source_network(0)).unwrap();
|
||||||
|
|
||||||
|
executor.replace(held.clone(), source_network(1)).unwrap();
|
||||||
|
assert!(executor.tree().get(NodeId(0)).is_some());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn repeated_replacing_keeps_the_node_count_and_the_source_map_size_constant() {
|
||||||
|
let mut executor = DynamicExecutor::default();
|
||||||
|
let mut output = executor.insert(source_network(0)).unwrap();
|
||||||
|
|
||||||
|
for node in 1..=4 {
|
||||||
|
output = executor.replace(output, source_network(node)).unwrap();
|
||||||
|
assert_eq!([executor.tree().nodes.len(), executor.tree().source_map().len()], [1, 1]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -49,6 +49,6 @@ mod tests {
|
|||||||
let compiler = Compiler {};
|
let compiler = Compiler {};
|
||||||
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
|
let protograph = compiler.compile_single(network).expect("Graph should be generated").network;
|
||||||
|
|
||||||
let _exec = DynamicExecutor::default().update(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
let _exec = DynamicExecutor::default().insert(protograph).map(|_e| panic!("The network should not type check ")).unwrap_err();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -26,7 +26,7 @@ use graphene_std::vector::misc::{
|
|||||||
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
ArcType, BooleanOperation, BoxCorners, CentroidType, ExtrudeJoiningAlgorithm, GridTopology, GridType, InterpolationDistribution, PointSpacingType, RowsOrColumns, SpiralType, UnweldMethod,
|
||||||
WeldMethod,
|
WeldMethod,
|
||||||
};
|
};
|
||||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientModel, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, BlendIfChannel, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||||
@@ -68,6 +68,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||||
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientForm>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
|
||||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
||||||
@@ -154,14 +155,24 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
)
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
// Keeps an adapter row under the identifier the preprocessor names it by and repeats it under the adapter node's own identifier,
|
||||||
|
// which the new compiler selects by signature
|
||||||
|
macro_rules! also_under_own_identifier {
|
||||||
|
($module:ident, $row:expr) => {{
|
||||||
|
let row: (ProtoNodeIdentifier, NodeConstructor, NodeIOTypes) = $row;
|
||||||
|
let own = (graphene_core::ops::$module::IDENTIFIER, row.1, row.2.clone());
|
||||||
|
[row, own]
|
||||||
|
}};
|
||||||
|
}
|
||||||
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
// A conversion row registered under the same `input_adapter<$element>` identifier so a convertible-but-not-identical
|
||||||
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
// ranked wire can feed an `Item<$element>` connector, converting each element via `Into`
|
||||||
macro_rules! input_adapter_row {
|
macro_rules! input_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(into_item, input_adapter_row!(node: IntoItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(into_list, input_adapter_row!(node: IntoListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
(node: $node:ident, from: $from:ty, to: $to:ty, element: $element:ty) => {
|
||||||
@@ -253,7 +264,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.extend(input_adapter_node!(element: $element));
|
entries.extend(input_adapter_node!(element: $element));
|
||||||
entries.push(item_to_list_node!(element: $element));
|
entries.extend(also_under_own_identifier!(item_to_list, item_to_list_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -270,7 +281,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
StrokeAlign,
|
StrokeAlign,
|
||||||
StrokeCap,
|
StrokeCap,
|
||||||
GradientForm,
|
GradientForm,
|
||||||
GradientModel,
|
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -359,9 +369,10 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
|
||||||
macro_rules! list_dyn_rows {
|
macro_rules! list_dyn_rows {
|
||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
$(input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn),)*
|
$(also_under_own_identifier!(into, input_adapter_node!(name: "input_adapter", from: List<$element>, to: ListDyn, element: ListDyn)),)*
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -381,6 +392,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
DVec2,
|
DVec2,
|
||||||
DAffine2,
|
DAffine2,
|
||||||
BlendMode,
|
BlendMode,
|
||||||
|
GradientForm,
|
||||||
GradientSpread,
|
GradientSpread,
|
||||||
GradientSpace,
|
GradientSpace,
|
||||||
GradientHueDirection,
|
GradientHueDirection,
|
||||||
@@ -393,8 +405,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
($($element:ty),* $(,)?) => {{
|
($($element:ty),* $(,)?) => {{
|
||||||
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
let mut entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = Vec::new();
|
||||||
$(
|
$(
|
||||||
entries.push(bundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(bundle, bundle_node!(element: $element)));
|
||||||
entries.push(unbundle_node!(element: $element));
|
entries.extend(also_under_own_identifier!(unbundle, unbundle_node!(element: $element)));
|
||||||
)*
|
)*
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
@@ -440,8 +452,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
node_types.extend(ranked_value_types!(cache_chain_nodes));
|
||||||
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
// The direct counterpart to `Box<VectorModification>`'s promotion adapter above (see that note)
|
||||||
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
node_types.extend(cache_chain_nodes!(Box<VectorModification>));
|
||||||
// Context nullification can wrap the read-back adapter's output
|
|
||||||
node_types.extend(cache_chain_nodes!(Pixels));
|
|
||||||
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
// A position wire may feed a ranked vector connector, each position becoming a single-anchor vector
|
||||||
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
node_types.extend(input_adapter_row!(from_element: DVec2, element: Vector));
|
||||||
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
// A string wire may feed the ranked `Item<DashPattern>` dash connector by parsing each element into a dash pattern
|
||||||
@@ -456,10 +466,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
// Each item moves inside its matching variant, attributes and all, rather than mapping only its element.
|
||||||
macro_rules! embed_adapter_row {
|
macro_rules! embed_adapter_row {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(embed_item, input_adapter_row!(node: EmbedItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(embed_list, input_adapter_row!(node: EmbedListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -476,10 +487,11 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
// The `Convert`-based counterpart of `input_adapter_row!`, for casts the std `Into` trait cannot express
|
||||||
macro_rules! convert_adapter_node {
|
macro_rules! convert_adapter_node {
|
||||||
(from_element: $from:ty, element: $element:ty) => {{
|
(from_element: $from:ty, element: $element:ty) => {{
|
||||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element),
|
also_under_own_identifier!(convert_item, input_adapter_row!(node: ConvertItemNode, from: Item<$from>, to: Item<$element>, element: $element)),
|
||||||
input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element),
|
also_under_own_identifier!(convert_list, input_adapter_row!(node: ConvertListNode, from: List<$from>, to: List<$element>, element: $element)),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
entries
|
entries
|
||||||
}};
|
}};
|
||||||
}
|
}
|
||||||
@@ -498,30 +510,22 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
// Position and transform wires may feed a ranked `String` connector by formatting each element as text
|
||||||
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DVec2, element: String));
|
||||||
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
node_types.extend(convert_adapter_node!(from_element: DAffine2, element: String));
|
||||||
// An image wire feeds a `Pixels` connector through its GPU readback, an async node taking the executor, runtime, and source ID after the wire.
|
|
||||||
// These rows have no one-input passthrough siblings, which type resolution would match by their first input alone.
|
|
||||||
macro_rules! read_back_node {
|
|
||||||
($node:ty, wire: $wire:ty) => {
|
|
||||||
async_node!(
|
|
||||||
identifier: graphene_std::read_back::INPUT_ADAPTER,
|
|
||||||
$node,
|
|
||||||
input: Context,
|
|
||||||
fn_params: [Context => $wire, Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::SourceId>]
|
|
||||||
)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackNode<_, _, _, _>, wire: Item<Raster<CPU>>));
|
|
||||||
node_types.push(read_back_node!(graphene_std::read_back::ReadBackListNode<_, _, _, _>, wire: List<Raster<CPU>>));
|
|
||||||
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
// The sanctioned attribute value conversions: an Item wire's elements box per cell, while a List wire boxes whole as one value
|
||||||
macro_rules! attribute_value_node {
|
macro_rules! attribute_value_node {
|
||||||
(Item<$element:ty>) => {
|
(Item<$element:ty>) => {
|
||||||
|
also_under_own_identifier!(
|
||||||
|
item_to_attribute_value,
|
||||||
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
input_adapter_row!(node: ItemToAttributeValueNode, from: Item<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
(List<$element:ty>) => {
|
(List<$element:ty>) => {
|
||||||
|
also_under_own_identifier!(
|
||||||
|
list_to_attribute_value,
|
||||||
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
input_adapter_row!(node: ListToAttributeValueNode, from: List<$element>, to: Item<AttributeValueDyn>, element: AttributeValueDyn)
|
||||||
|
)
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
let attribute_value_rows: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = [
|
||||||
attribute_value_node!(Item<f64>),
|
attribute_value_node!(Item<f64>),
|
||||||
attribute_value_node!(Item<i64>),
|
attribute_value_node!(Item<i64>),
|
||||||
attribute_value_node!(Item<bool>),
|
attribute_value_node!(Item<bool>),
|
||||||
@@ -531,7 +535,6 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
attribute_value_node!(Item<Color>),
|
attribute_value_node!(Item<Color>),
|
||||||
attribute_value_node!(Item<BlendMode>),
|
attribute_value_node!(Item<BlendMode>),
|
||||||
attribute_value_node!(Item<GradientForm>),
|
attribute_value_node!(Item<GradientForm>),
|
||||||
attribute_value_node!(Item<GradientModel>),
|
|
||||||
attribute_value_node!(Item<GradientSpread>),
|
attribute_value_node!(Item<GradientSpread>),
|
||||||
attribute_value_node!(Item<GradientSpace>),
|
attribute_value_node!(Item<GradientSpace>),
|
||||||
attribute_value_node!(Item<GradientHueDirection>),
|
attribute_value_node!(Item<GradientHueDirection>),
|
||||||
@@ -547,7 +550,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
|||||||
attribute_value_node!(List<Raster<GPU>>),
|
attribute_value_node!(List<Raster<GPU>>),
|
||||||
attribute_value_node!(List<Graphic>),
|
attribute_value_node!(List<Graphic>),
|
||||||
attribute_value_node!(List<Artboard>),
|
attribute_value_node!(List<Artboard>),
|
||||||
];
|
]
|
||||||
|
.concat();
|
||||||
node_types.extend(attribute_value_rows);
|
node_types.extend(attribute_value_rows);
|
||||||
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
// Whole-List Transform companion rows: a rank-1 content wire composes the matrix onto every item
|
||||||
macro_rules! transform_list_node {
|
macro_rules! transform_list_node {
|
||||||
|
|||||||
@@ -33,9 +33,9 @@ pub use graphene_hash;
|
|||||||
pub use graphene_hash::CacheHash;
|
pub use graphene_hash::CacheHash;
|
||||||
pub use list::{
|
pub use list::{
|
||||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_MODEL,
|
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD,
|
||||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM,
|
||||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
ATTR_TYPE,
|
||||||
};
|
};
|
||||||
pub use memo::MemoHash;
|
pub use memo::MemoHash;
|
||||||
pub use num_traits;
|
pub use num_traits;
|
||||||
|
|||||||
@@ -59,14 +59,8 @@ pub const ATTR_CLIP: &str = "clip";
|
|||||||
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
|
// TODO: Consider adding "gradient_spread_left" and "gradient_spread_right" override attributes to allow setting different gradient spreads on each side of a gradient
|
||||||
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
|
/// Gradient's `GradientSpread` (`Pad`, `Reflect`, `Repeat`, or `Clear`).
|
||||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||||
/// Gradient's `f64` curvature for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, it's 0.
|
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
|
||||||
/// Gradient's `f64` curvature for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
|
||||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
|
||||||
/// Gradient's `GradientModel` (`Standard` or `Apollonian`), how the contours between its curved ends are laid out: as SVG 2's cone
|
|
||||||
/// between the end circles, or as the family of circles the ends span. Absent, it's `Standard`.
|
|
||||||
pub const ATTR_GRADIENT_MODEL: &str = "gradient_model";
|
|
||||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||||
@@ -1720,7 +1714,7 @@ impl<T: CacheHash> CacheHash for List<T> {
|
|||||||
self.element.as_slice().cache_hash(state);
|
self.element.as_slice().cache_hash(state);
|
||||||
|
|
||||||
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
|
// Hash every attribute (key + values) rather than just the well-known ones, so changes to user-defined keys
|
||||||
// (e.g., gradient_spread) invalidate downstream graph caches as expected
|
// (e.g., gradient_form, gradient_spread) invalidate downstream graph caches as expected
|
||||||
self.attributes.cache_hash_entries(state);
|
self.attributes.cache_hash_entries(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,18 @@ pub struct NodeFlags {
|
|||||||
pub forwards_input: bool,
|
pub forwards_input: bool,
|
||||||
pub inject_scope: bool,
|
pub inject_scope: bool,
|
||||||
pub asynchronous: bool,
|
pub asynchronous: bool,
|
||||||
|
/// Whether type resolution may insert this node on an edge, from `#[node_macro::node(adapter(...))]`.
|
||||||
|
pub adapter: Option<AdapterKind>,
|
||||||
|
pub transient: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How an adapter node changes the wire it is inserted on.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum AdapterKind {
|
||||||
|
/// Converts the wire's element into another element type.
|
||||||
|
Conversion,
|
||||||
|
/// Changes the wire's rank, like raising an `Item` onto a `List`.
|
||||||
|
Rank,
|
||||||
}
|
}
|
||||||
|
|
||||||
// Translation struct between macro and definition
|
// Translation struct between macro and definition
|
||||||
|
|||||||
@@ -86,8 +86,6 @@ pub enum Adjustment {
|
|||||||
opacity: f64,
|
opacity: f64,
|
||||||
},
|
},
|
||||||
Solarize,
|
Solarize,
|
||||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Adjustment {
|
impl Adjustment {
|
||||||
@@ -114,17 +112,6 @@ impl Adjustment {
|
|||||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||||
Self::Solarize => EffectKind::Solarize,
|
Self::Solarize => EffectKind::Solarize,
|
||||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
|
|
||||||
pub fn may_change_alpha(&self) -> bool {
|
|
||||||
match self {
|
|
||||||
Self::MakeOpaque { .. } => true,
|
|
||||||
Self::Levels(settings) => !settings.alpha.is_identity(),
|
|
||||||
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
|
|
||||||
_ => false,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -154,7 +141,7 @@ impl Adjustment {
|
|||||||
visitor.parameter("inverse", inverse, false);
|
visitor.parameter("inverse", inverse, false);
|
||||||
}
|
}
|
||||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
Self::Invert | Self::Solarize => {}
|
||||||
Self::BrightnessContrast {
|
Self::BrightnessContrast {
|
||||||
brightness,
|
brightness,
|
||||||
contrast,
|
contrast,
|
||||||
@@ -499,20 +486,6 @@ fn grouped_key(group: &str, parameter: &str) -> String {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl LevelsRecord {
|
impl LevelsRecord {
|
||||||
/// The record leaving every value as it is, as its node's defaults do.
|
|
||||||
pub const IDENTITY: Self = Self {
|
|
||||||
shadows: 0.,
|
|
||||||
midtones: 1.,
|
|
||||||
highlights: 100.,
|
|
||||||
output_minimums: 0.,
|
|
||||||
output_maximums: 100.,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Whether the record leaves every value as it is.
|
|
||||||
pub fn is_identity(&self) -> bool {
|
|
||||||
*self == Self::IDENTITY
|
|
||||||
}
|
|
||||||
|
|
||||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
|
||||||
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
|
||||||
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
|
||||||
|
|||||||
@@ -490,7 +490,6 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
| EffectOperation::Median { .. }
|
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use core_types::Color;
|
|||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||||
@@ -60,8 +60,6 @@ pub enum EffectKind {
|
|||||||
FindEdges,
|
FindEdges,
|
||||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||||
MinimumMaximum,
|
MinimumMaximum,
|
||||||
/// Gives each pixel the middle value of each channel among those around it, removing specks while keeping edges.
|
|
||||||
Median,
|
|
||||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||||
Sharpen,
|
Sharpen,
|
||||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||||
@@ -119,8 +117,6 @@ pub enum EffectKind {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for EffectKind {
|
impl std::fmt::Display for EffectKind {
|
||||||
@@ -141,7 +137,6 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::Emboss => "Emboss",
|
Self::Emboss => "Emboss",
|
||||||
Self::FindEdges => "Find Edges",
|
Self::FindEdges => "Find Edges",
|
||||||
Self::MinimumMaximum => "Minimum/Maximum",
|
Self::MinimumMaximum => "Minimum/Maximum",
|
||||||
Self::Median => "Median",
|
|
||||||
Self::Sharpen => "Sharpen",
|
Self::Sharpen => "Sharpen",
|
||||||
Self::HighPass => "High Pass",
|
Self::HighPass => "High Pass",
|
||||||
Self::Speckle => "Speckle",
|
Self::Speckle => "Speckle",
|
||||||
@@ -180,7 +175,6 @@ impl std::fmt::Display for EffectKind {
|
|||||||
Self::PhotoFilter => "Photo Filter",
|
Self::PhotoFilter => "Photo Filter",
|
||||||
Self::ColorLookup => "Color Lookup",
|
Self::ColorLookup => "Color Lookup",
|
||||||
Self::Solarize => "Solarize",
|
Self::Solarize => "Solarize",
|
||||||
Self::AlphaToGray => "Alpha to Gray",
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,9 +218,6 @@ pub enum MinimumMaximumMode {
|
|||||||
Maximum,
|
Maximum,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The most pixels a median's square reaches out from its center on its grid, whose cost grows with the square's area. Past it, the grid coarsens instead.
|
|
||||||
pub const MAX_MEDIAN_GRID_RADIUS: f64 = 16.;
|
|
||||||
|
|
||||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub struct EffectCapture {
|
pub struct EffectCapture {
|
||||||
@@ -463,17 +454,6 @@ impl Effects {
|
|||||||
self.operations().all(|operation| operation.changes_nothing())
|
self.operations().all(|operation| operation.changes_nothing())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
|
|
||||||
pub fn may_change_alpha(&self) -> bool {
|
|
||||||
self.operations().any(|operation| {
|
|
||||||
!operation.changes_nothing()
|
|
||||||
&& match &operation {
|
|
||||||
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
|
|
||||||
_ => true,
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The effects of the given range of rows decoded into operations, in order.
|
/// The effects of the given range of rows decoded into operations, in order.
|
||||||
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
|
||||||
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
|
||||||
@@ -495,30 +475,17 @@ impl Effects {
|
|||||||
self.operations().map(|operation| operation.required_reach()).sum()
|
self.operations().map(|operation| operation.required_reach()).sum()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How many pixels per unit of their effect space a run of these effects renders at, at most, if any of them works on the content's own grid (see [`EffectOperation::works_on_content_grid`]).
|
|
||||||
/// It's one, except that a median reaching past [`MAX_MEDIAN_GRID_RADIUS`] whole units coarsens the grid to bound its cost.
|
|
||||||
pub fn content_grid_resolution(&self) -> Option<f64> {
|
|
||||||
let grid_resolution = |operation: EffectOperation| match operation {
|
|
||||||
EffectOperation::Median { radius } => (MAX_MEDIAN_GRID_RADIUS / radius.floor()).min(1.),
|
|
||||||
_ => 1.,
|
|
||||||
};
|
|
||||||
self.operations().filter(EffectOperation::works_on_content_grid).map(grid_resolution).reduce(f64::min)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||||
/// A transform applied between two effects, or an effect on the content's own grid (which runs alone at its grid's resolution), starts a new run around the result of those before it.
|
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||||
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
pub fn runs(&self) -> Vec<(DAffine2, Range<usize>)> {
|
||||||
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
let mut runs: Vec<(DAffine2, Range<usize>)> = Vec::new();
|
||||||
let (mut run_changes_something, mut run_on_content_grid) = (false, false);
|
let mut run_changes_something = false;
|
||||||
for (index, effect) in self.effects().enumerate() {
|
for (index, effect) in self.effects().enumerate() {
|
||||||
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
let stamped_transform: DAffine2 = self.0.attribute_cloned_or_default(ATTR_TRANSFORM, index);
|
||||||
let operation = effect.operation();
|
let changes_something = !effect.operation().changes_nothing();
|
||||||
let (changes_something, on_content_grid) = (!operation.changes_nothing(), operation.works_on_content_grid());
|
|
||||||
|
|
||||||
let shares_grid = !(on_content_grid && run_changes_something) && !(run_on_content_grid && changes_something);
|
|
||||||
if let Some((transform, rows)) = runs.last_mut()
|
if let Some((transform, rows)) = runs.last_mut()
|
||||||
&& shares_grid
|
|
||||||
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
&& (!changes_something || !run_changes_something || same_linear_part(transform.matrix2, stamped_transform.matrix2))
|
||||||
{
|
{
|
||||||
if changes_something && !run_changes_something {
|
if changes_something && !run_changes_something {
|
||||||
@@ -526,10 +493,9 @@ impl Effects {
|
|||||||
}
|
}
|
||||||
rows.end = index + 1;
|
rows.end = index + 1;
|
||||||
run_changes_something |= changes_something;
|
run_changes_something |= changes_something;
|
||||||
run_on_content_grid |= on_content_grid;
|
|
||||||
} else {
|
} else {
|
||||||
runs.push((stamped_transform, index..index + 1));
|
runs.push((stamped_transform, index..index + 1));
|
||||||
(run_changes_something, run_on_content_grid) = (changes_something, on_content_grid);
|
run_changes_something = changes_something;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
runs
|
runs
|
||||||
@@ -869,14 +835,8 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
|||||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||||
stamp_effect_on(item.attributes_mut(), effect);
|
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||||
}
|
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||||
|
|
||||||
/// Like [`stamp_effect`], given the item's attributes.
|
|
||||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
|
||||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
|
||||||
attributes
|
|
||||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
|
||||||
.0
|
.0
|
||||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||||
}
|
}
|
||||||
@@ -1126,11 +1086,6 @@ pub enum EffectOperation {
|
|||||||
radius: f64,
|
radius: f64,
|
||||||
mode: MinimumMaximumMode,
|
mode: MinimumMaximumMode,
|
||||||
},
|
},
|
||||||
/// Carried out on the content's own grid of pixels (see [`Self::works_on_content_grid`]), then resampled to the view.
|
|
||||||
Median {
|
|
||||||
/// How many pixels the square neighborhood reaches out from its center, of which the whole pixels count.
|
|
||||||
radius: f64,
|
|
||||||
},
|
|
||||||
Sharpen {
|
Sharpen {
|
||||||
/// Percent.
|
/// Percent.
|
||||||
amount: f64,
|
amount: f64,
|
||||||
@@ -1332,7 +1287,6 @@ impl EffectOperation {
|
|||||||
Self::Emboss { .. } => EffectKind::Emboss,
|
Self::Emboss { .. } => EffectKind::Emboss,
|
||||||
Self::FindEdges => EffectKind::FindEdges,
|
Self::FindEdges => EffectKind::FindEdges,
|
||||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||||
Self::Median { .. } => EffectKind::Median,
|
|
||||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||||
Self::HighPass { .. } => EffectKind::HighPass,
|
Self::HighPass { .. } => EffectKind::HighPass,
|
||||||
Self::Speckle { .. } => EffectKind::Speckle,
|
Self::Speckle { .. } => EffectKind::Speckle,
|
||||||
@@ -1433,8 +1387,6 @@ impl EffectOperation {
|
|||||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||||
// Only whole pixels count, so one of less than a pixel reads the pixel alone
|
|
||||||
Self::Median { radius } => *radius < 1.,
|
|
||||||
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
Self::BlendIf(ranges) => ranges.content.show_everything() && ranges.underlying.show_everything(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1461,7 +1413,7 @@ impl EffectOperation {
|
|||||||
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
Self::Twirl { .. } | Self::Pinch { .. } | Self::Spherize { .. } | Self::PolarCoordinates { .. } | Self::Warp { .. } | Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } => {
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Median { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||||
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
// Cast from the content's shape, reading a mask's or the backdrop's own image or a feather's map, or changing each pixel alone
|
||||||
Self::DropShadow { .. }
|
Self::DropShadow { .. }
|
||||||
| Self::InnerShadow { .. }
|
| Self::InnerShadow { .. }
|
||||||
@@ -1475,12 +1427,6 @@ impl EffectOperation {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this operation is carried out on the content's own grid of pixels, one to each unit of its effect space, and the result resampled to the view, since it doesn't commute with resampling.
|
|
||||||
/// So it looks the same at every zoom, and on an image at its own size when stamped, it reads the image's pixels.
|
|
||||||
pub fn works_on_content_grid(&self) -> bool {
|
|
||||||
matches!(self, Self::Median { .. }) && !self.changes_nothing()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||||
pub fn painted_reach(&self) -> f64 {
|
pub fn painted_reach(&self) -> f64 {
|
||||||
let keeps_coverage = matches!(
|
let keeps_coverage = matches!(
|
||||||
@@ -1494,8 +1440,6 @@ impl EffectOperation {
|
|||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
..
|
..
|
||||||
}
|
}
|
||||||
// Its coverage is the window's middle one, which past the content's bounds comes from a window at least half beyond them
|
|
||||||
| Self::Median { .. }
|
|
||||||
| Self::Sharpen { .. }
|
| Self::Sharpen { .. }
|
||||||
| Self::HighPass { .. }
|
| Self::HighPass { .. }
|
||||||
);
|
);
|
||||||
@@ -1538,7 +1482,6 @@ impl EffectOperation {
|
|||||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||||
Self::Median { radius } => radius.max(0.).floor() + 1.,
|
|
||||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||||
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
Self::MotionBlur { distance, .. } => distance.abs() / 2. + 3.,
|
||||||
// They reach as far as `Effects::reach_around` measures from where the content lies
|
// They reach as far as `Effects::reach_around` measures from where the content lies
|
||||||
@@ -1633,7 +1576,7 @@ impl EffectOperation {
|
|||||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||||
Self::Feather { distance } => finite(distance),
|
Self::Feather { distance } => finite(distance),
|
||||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||||
Self::MinimumMaximum { radius, .. } | Self::Median { radius } | Self::HighPass { radius } => finite(radius),
|
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||||
Self::Speckle { amount, .. } => finite(amount),
|
Self::Speckle { amount, .. } => finite(amount),
|
||||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||||
@@ -1804,7 +1747,6 @@ impl EffectOperation {
|
|||||||
radius: 0.,
|
radius: 0.,
|
||||||
mode: MinimumMaximumMode::default(),
|
mode: MinimumMaximumMode::default(),
|
||||||
},
|
},
|
||||||
EffectKind::Median => Self::Median { radius: 0. },
|
|
||||||
EffectKind::Sharpen => Self::Sharpen {
|
EffectKind::Sharpen => Self::Sharpen {
|
||||||
amount: 0.,
|
amount: 0.,
|
||||||
radius: 0.,
|
radius: 0.,
|
||||||
@@ -1933,7 +1875,6 @@ impl EffectOperation {
|
|||||||
}),
|
}),
|
||||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2147,7 +2088,6 @@ impl EffectOperation {
|
|||||||
visitor.parameter("radius", radius, 1.);
|
visitor.parameter("radius", radius, 1.);
|
||||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||||
}
|
}
|
||||||
Self::Median { radius } => visitor.parameter("radius", radius, 0.),
|
|
||||||
Self::Sharpen {
|
Self::Sharpen {
|
||||||
amount,
|
amount,
|
||||||
radius,
|
radius,
|
||||||
@@ -2450,7 +2390,6 @@ mod tests {
|
|||||||
radius: 7.,
|
radius: 7.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
EffectOperation::Median { radius: 3.5 },
|
|
||||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 180.,
|
amount: 180.,
|
||||||
@@ -2949,7 +2888,6 @@ mod tests {
|
|||||||
PhotoFilter,
|
PhotoFilter,
|
||||||
ColorLookup,
|
ColorLookup,
|
||||||
Solarize,
|
Solarize,
|
||||||
AlphaToGray,
|
|
||||||
PaintOverlay,
|
PaintOverlay,
|
||||||
];
|
];
|
||||||
for kind in kinds {
|
for kind in kinds {
|
||||||
@@ -3049,7 +2987,6 @@ mod tests {
|
|||||||
radius: 3.,
|
radius: 3.,
|
||||||
mode: MinimumMaximumMode::Maximum,
|
mode: MinimumMaximumMode::Maximum,
|
||||||
},
|
},
|
||||||
EffectOperation::Median { radius: 3.5 },
|
|
||||||
EffectOperation::Sharpen {
|
EffectOperation::Sharpen {
|
||||||
amount: 100.,
|
amount: 100.,
|
||||||
radius: 3.,
|
radius: 3.,
|
||||||
@@ -3073,28 +3010,6 @@ mod tests {
|
|||||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_median_works_on_the_content_grid_coarsened_past_its_largest_radius() {
|
|
||||||
let median = |radius| Effects::from_operations([EffectOperation::Median { radius }]);
|
|
||||||
assert_eq!(median(0.5).content_grid_resolution(), None, "less than a whole pixel changes nothing");
|
|
||||||
assert_eq!(median(5.9).content_grid_resolution(), Some(1.));
|
|
||||||
assert_eq!(median(64.).content_grid_resolution(), Some(MAX_MEDIAN_GRID_RADIUS / 64.));
|
|
||||||
assert_eq!(Effects::from_operations([EffectOperation::FindEdges]).content_grid_resolution(), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_median_runs_alone_at_its_own_grid_resolution() {
|
|
||||||
let median = |radius| EffectOperation::Median { radius };
|
|
||||||
let nothing = median(0.);
|
|
||||||
let effects = Effects::from_operations([nothing.clone(), median(1.), median(64.), nothing, EffectOperation::FindEdges, median(2.)]);
|
|
||||||
|
|
||||||
// Effects changing nothing join a median's run, but nothing else does
|
|
||||||
let runs: Vec<_> = effects.runs().into_iter().map(|(_, rows)| rows).collect();
|
|
||||||
assert_eq!(runs, vec![0..2, 2..4, 4..5, 5..6]);
|
|
||||||
let resolutions: Vec<_> = runs.into_iter().map(|rows| effects.run(rows).content_grid_resolution()).collect();
|
|
||||||
assert_eq!(resolutions, [Some(1.), Some(MAX_MEDIAN_GRID_RADIUS / 64.), None, Some(1.)]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
fn baking_the_content_placement_into_its_geometry_keeps_its_mask_in_place() {
|
||||||
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
fn nested_placement(graphic: &Graphic) -> DAffine2 {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||||
|
|
||||||
use crate::effects::EffectOperation;
|
use crate::effects::{EffectOperation, Effects};
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||||
@@ -164,7 +164,6 @@ pub fn is_filter(operation: &EffectOperation) -> bool {
|
|||||||
| EffectOperation::Emboss { .. }
|
| EffectOperation::Emboss { .. }
|
||||||
| EffectOperation::FindEdges
|
| EffectOperation::FindEdges
|
||||||
| EffectOperation::MinimumMaximum { .. }
|
| EffectOperation::MinimumMaximum { .. }
|
||||||
| EffectOperation::Median { .. }
|
|
||||||
| EffectOperation::Sharpen { .. }
|
| EffectOperation::Sharpen { .. }
|
||||||
| EffectOperation::HighPass { .. }
|
| EffectOperation::HighPass { .. }
|
||||||
| EffectOperation::Speckle { .. }
|
| EffectOperation::Speckle { .. }
|
||||||
@@ -182,6 +181,12 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
|||||||
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||||
|
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||||
|
pub fn has_filters(effects: &Effects) -> bool {
|
||||||
|
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||||
|
}
|
||||||
|
|
||||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||||
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||||
(DVec2::new(-1., -1.), [-1., -1.]),
|
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||||
|
|||||||
@@ -9,17 +9,13 @@ use core_types::math::quad::Quad;
|
|||||||
use core_types::none;
|
use core_types::none;
|
||||||
use core_types::ops::FromAnchorPosition;
|
use core_types::ops::FromAnchorPosition;
|
||||||
use core_types::transform::Transform;
|
use core_types::transform::Transform;
|
||||||
use core_types::{
|
use core_types::{ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
ATTR_CLIPPING_MASK, ATTR_EDITOR_LAYER_PATH, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM,
|
|
||||||
Color,
|
|
||||||
};
|
|
||||||
use dyn_any::DynAny;
|
use dyn_any::DynAny;
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use raster_types::{CPU, GPU, Raster};
|
use raster_types::{CPU, GPU, Raster};
|
||||||
pub use vector_types::Vector;
|
pub use vector_types::Vector;
|
||||||
use vector_types::gradient_standard::GradientShape;
|
|
||||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||||
use vector_types::{Gradient, GradientModel, GradientSpread};
|
use vector_types::{Gradient, GradientSpread};
|
||||||
|
|
||||||
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
||||||
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
#[derive(Clone, Debug, CacheHash, PartialEq, DynAny)]
|
||||||
@@ -630,17 +626,16 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
|
pub fn can_reduce_to_clip_path(&self) -> bool {
|
||||||
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
|
|
||||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||||
match self {
|
match self {
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => {
|
||||||
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
|
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
|
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||||
}
|
}
|
||||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
|
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
|
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||||
}),
|
}),
|
||||||
_ => false,
|
_ => false,
|
||||||
}
|
}
|
||||||
@@ -649,22 +644,16 @@ impl Graphic {
|
|||||||
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
pub fn is_guaranteed_fully_opaque(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => false,
|
Graphic::None(_) | Graphic::NoneList(_) => false,
|
||||||
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
|
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
|
||||||
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
|
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
|
||||||
Graphic::GraphicList(list) => {
|
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
|
||||||
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
|
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
|
||||||
}
|
|
||||||
Graphic::Vector(item) => {
|
|
||||||
!item_effects_may_change_alpha(item)
|
|
||||||
&& vector_is_guaranteed_fully_opaque(
|
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
)
|
),
|
||||||
}
|
|
||||||
Graphic::VectorList(list) => {
|
Graphic::VectorList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
&& !list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
vector_is_guaranteed_fully_opaque(
|
vector_is_guaranteed_fully_opaque(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
@@ -676,23 +665,19 @@ impl Graphic {
|
|||||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||||
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
|
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||||
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
|
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||||
Graphic::Gradient(item) => {
|
Graphic::Gradient(item) => {
|
||||||
item_opacity_is_full(item)
|
item_opacity_is_full(item)
|
||||||
&& !item_effects_may_change_alpha(item)
|
|
||||||
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
|
||||||
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
|
|
||||||
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
&& item.element().iter().all(|stop| stop.color.is_opaque())
|
||||||
}
|
}
|
||||||
Graphic::GradientList(list) => {
|
Graphic::GradientList(list) => {
|
||||||
!list.is_empty()
|
!list.is_empty()
|
||||||
&& every_item_has_full_opacity(list)
|
&& every_item_has_full_opacity(list)
|
||||||
&& !list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
&& (0..list.len()).all(|index| {
|
||||||
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
|
||||||
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
|
|
||||||
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
|
&& list.element(index).is_some_and(|stops| stops.iter().all(|stop| stop.color.is_opaque()))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -702,41 +687,27 @@ impl Graphic {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
pub fn is_guaranteed_fully_transparent(&self) -> bool {
|
||||||
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||||
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
|
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
|
||||||
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
|
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
|
||||||
Graphic::Vector(item) => {
|
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
|
||||||
item_opacity_is_zero(item)
|
|
||||||
|| (!item_effects_may_change_alpha(item)
|
|
||||||
&& vector_is_guaranteed_fully_transparent(
|
|
||||||
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY, 1.),
|
||||||
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
|
||||||
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
item.attribute::<Appearance>(ATTR_APPEARANCE),
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS),
|
),
|
||||||
))
|
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||||
}
|
|
||||||
Graphic::VectorList(list) => {
|
|
||||||
every_item_has_zero_opacity(list)
|
|
||||||
|| (!list_effects_may_change_alpha(list)
|
|
||||||
&& (0..list.len()).all(|index| {
|
|
||||||
vector_is_guaranteed_fully_transparent(
|
vector_is_guaranteed_fully_transparent(
|
||||||
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
|
||||||
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
|
||||||
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
|
||||||
list.attribute::<Effects>(ATTR_EFFECTS, index),
|
|
||||||
)
|
)
|
||||||
}))
|
}),
|
||||||
}
|
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
|
||||||
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
|
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
|
||||||
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
|
|
||||||
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
|
||||||
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
|
||||||
Graphic::GradientList(list) => {
|
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
|
||||||
every_item_has_zero_opacity(list)
|
|
||||||
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
|
|
||||||
}
|
|
||||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||||
@@ -829,13 +800,12 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
|
||||||
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
|
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
|
||||||
if opacity <= f64::EPSILON {
|
if opacity <= f64::EPSILON {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
|
let fills_invisible = opacity_fill <= f64::EPSILON
|
||||||
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|
|
||||||
|| appearance.is_none_or(|appearance| {
|
|| appearance.is_none_or(|appearance| {
|
||||||
appearance
|
appearance
|
||||||
.covers_with_paints()
|
.covers_with_paints()
|
||||||
@@ -853,16 +823,6 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
|
|||||||
fills_invisible && strokes_invisible
|
fills_invisible && strokes_invisible
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
|
|
||||||
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
|
|
||||||
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
|
|
||||||
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
|
|
||||||
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
|
||||||
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
|
||||||
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
|
||||||
@@ -883,21 +843,6 @@ fn every_item_has_full_opacity<T>(list: &List<T>) -> bool {
|
|||||||
(0..list.len()).all(|index| list.attribute_cloned_or::<f64>(ATTR_OPACITY, index, 1.) >= 1. - f64::EPSILON && list.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, index, 1.) >= 1. - f64::EPSILON)
|
(0..list.len()).all(|index| list.attribute_cloned_or::<f64>(ATTR_OPACITY, index, 1.) >= 1. - f64::EPSILON && list.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, index, 1.) >= 1. - f64::EPSILON)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether a gradient with the attributes the `attribute` lookup gives paints every point, which curved contours leaving gaps unfilled don't.
|
|
||||||
fn gradient_paints_everywhere<'a>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>) -> bool {
|
|
||||||
fn read<'a, T: 'static>(attribute: &dyn Fn(&str) -> Option<&'a dyn std::any::Any>, key: &str) -> Option<&'a T> {
|
|
||||||
attribute(key).and_then(|value| value.downcast_ref::<T>())
|
|
||||||
}
|
|
||||||
|
|
||||||
GradientShape::new(
|
|
||||||
read::<f64>(attribute, ATTR_GRADIENT_START_CURVATURE).copied().unwrap_or_default(),
|
|
||||||
read::<f64>(attribute, ATTR_GRADIENT_END_CURVATURE).copied().unwrap_or_default(),
|
|
||||||
read::<GradientModel>(attribute, ATTR_GRADIENT_MODEL).copied().unwrap_or_default(),
|
|
||||||
read::<DAffine2>(attribute, ATTR_TRANSFORM).copied().unwrap_or_default(),
|
|
||||||
)
|
|
||||||
.paints_everywhere()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
|
/// Bounding box of one vector, inflated by its appearance's stroke when `include_stroke` is true.
|
||||||
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
|
/// Paths and stroke parameters live on the holder's attributes, out of reach of the element-level impl.
|
||||||
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
|
fn vector_bounding_box(vector: &Vector, paths: Option<&List<Path>>, composed_transform: DAffine2, appearance: Option<&Appearance>, include_stroke: bool) -> Option<[DVec2; 2]> {
|
||||||
@@ -1342,64 +1287,4 @@ mod graphic_is_opaque_tests {
|
|||||||
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
|
||||||
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
|
|
||||||
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
|
|
||||||
use crate::effects::EffectOperation;
|
|
||||||
use crate::vector_types::vector::style::Stroke;
|
|
||||||
|
|
||||||
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
|
|
||||||
let colors = |alpha: f64, operation: EffectOperation| {
|
|
||||||
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
|
|
||||||
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
|
|
||||||
};
|
|
||||||
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
|
|
||||||
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
|
|
||||||
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
|
|
||||||
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
|
|
||||||
composite: record,
|
|
||||||
red: LevelsRecord::IDENTITY,
|
|
||||||
green: LevelsRecord::IDENTITY,
|
|
||||||
blue: LevelsRecord::IDENTITY,
|
|
||||||
alpha,
|
|
||||||
})))
|
|
||||||
};
|
|
||||||
let identity = LevelsRecord::IDENTITY;
|
|
||||||
let darkened = LevelsRecord { output_maximums: 50., ..identity };
|
|
||||||
|
|
||||||
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
|
|
||||||
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
|
|
||||||
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
|
|
||||||
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
|
|
||||||
|
|
||||||
// Effects that might fade a paint, or show a transparent one, leave it unknown
|
|
||||||
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
|
|
||||||
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
|
|
||||||
|
|
||||||
// A group's own effects act on all it wraps, though its zero opacity still hides it
|
|
||||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
|
|
||||||
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
|
|
||||||
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
|
|
||||||
|
|
||||||
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
|
|
||||||
let mut shape = Item::new_from_element(Vector::default());
|
|
||||||
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
|
|
||||||
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
|
|
||||||
let shadowed = shape
|
|
||||||
.clone()
|
|
||||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
|
|
||||||
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
|
|
||||||
|
|
||||||
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
|
|
||||||
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
|
|
||||||
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
|
|
||||||
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
|
|
||||||
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
|
|
||||||
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
|
|
||||||
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
|
|
||||||
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
|||||||
pub use blend_if::BlendIfChannel;
|
pub use blend_if::BlendIfChannel;
|
||||||
pub use effects::{
|
pub use effects::{
|
||||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||||
stamp_effect, stamp_effect_on, stamped_transform,
|
stamp_effect, stamped_transform,
|
||||||
};
|
};
|
||||||
pub use filters::NoiseDistribution;
|
pub use filters::NoiseDistribution;
|
||||||
pub use generator::Generator;
|
pub use generator::Generator;
|
||||||
|
|||||||
@@ -1715,10 +1715,10 @@ impl EffectOperation {
|
|||||||
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
FrameWarp::of(self).is_some() || warp_of(self).is_some()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether this operation takes the content's frame, which displacements and lattices measure from and a median reads within, unless it changes nothing.
|
/// Whether this operation takes the content's frame, which displacements and lattices measure from, unless it changes nothing.
|
||||||
pub fn takes_frame(&self) -> bool {
|
pub fn takes_frame(&self) -> bool {
|
||||||
match self {
|
match self {
|
||||||
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } | Self::Median { .. } => !self.changes_nothing(),
|
Self::Ripple { .. } | Self::Wave { .. } | Self::Displace { .. } | Self::Pixelate { .. } | Self::ColorHalftone { .. } => !self.changes_nothing(),
|
||||||
Self::Twirl { .. }
|
Self::Twirl { .. }
|
||||||
| Self::Pinch { .. }
|
| Self::Pinch { .. }
|
||||||
| Self::Spherize { .. }
|
| Self::Spherize { .. }
|
||||||
|
|||||||
@@ -30,12 +30,11 @@ pub enum StepKind {
|
|||||||
ColorLookup,
|
ColorLookup,
|
||||||
ColorOverlay,
|
ColorOverlay,
|
||||||
Solarize,
|
Solarize,
|
||||||
AlphaToGray,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl StepKind {
|
impl StepKind {
|
||||||
/// Every kind, in the order of their codes.
|
/// Every kind, in the order of their codes.
|
||||||
pub const ALL: [StepKind; 22] = [
|
pub const ALL: [StepKind; 21] = [
|
||||||
StepKind::Desaturate,
|
StepKind::Desaturate,
|
||||||
StepKind::GammaCorrection,
|
StepKind::GammaCorrection,
|
||||||
StepKind::MakeOpaque,
|
StepKind::MakeOpaque,
|
||||||
@@ -57,7 +56,6 @@ impl StepKind {
|
|||||||
StepKind::ColorLookup,
|
StepKind::ColorLookup,
|
||||||
StepKind::ColorOverlay,
|
StepKind::ColorOverlay,
|
||||||
StepKind::Solarize,
|
StepKind::Solarize,
|
||||||
StepKind::AlphaToGray,
|
|
||||||
];
|
];
|
||||||
|
|
||||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||||
@@ -271,7 +269,6 @@ mod tests {
|
|||||||
opacity: 50.,
|
opacity: 50.,
|
||||||
},
|
},
|
||||||
Adjustment::Solarize,
|
Adjustment::Solarize,
|
||||||
Adjustment::AlphaToGray,
|
|
||||||
];
|
];
|
||||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||||
|
|
||||||
|
|||||||
@@ -226,7 +226,6 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
|||||||
}
|
}
|
||||||
Adjustment::Invert => visitor.visit(Invert),
|
Adjustment::Invert => visitor.visit(Invert),
|
||||||
Adjustment::Solarize => visitor.visit(Solarize),
|
Adjustment::Solarize => visitor.visit(Solarize),
|
||||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
|
||||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||||
min_luminance: (min_luminance / 100.) as f32,
|
min_luminance: (min_luminance / 100.) as f32,
|
||||||
max_luminance: (max_luminance / 100.) as f32,
|
max_luminance: (max_luminance / 100.) as f32,
|
||||||
@@ -1122,20 +1121,6 @@ impl MapColor for Solarize {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
|
||||||
struct AlphaToGray;
|
|
||||||
|
|
||||||
impl MapColor for AlphaToGray {
|
|
||||||
fn map_cpu(&self, color: Color) -> Color {
|
|
||||||
let gray = srgb_to_linear(color.a());
|
|
||||||
color.map_rgb(|_| gray)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
|
||||||
steps.push(StepKind::AlphaToGray, []);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Threshold {
|
struct Threshold {
|
||||||
min_luminance: f32,
|
min_luminance: f32,
|
||||||
max_luminance: f32,
|
max_luminance: f32,
|
||||||
@@ -2022,69 +2007,4 @@ mod tests {
|
|||||||
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
|
|
||||||
use core_types::transfer_curve::TransferCurve;
|
|
||||||
use glam::DVec2;
|
|
||||||
use graphic_types::effects::{EffectKind, EffectOperation};
|
|
||||||
|
|
||||||
let kinds = [
|
|
||||||
EffectKind::Desaturate,
|
|
||||||
EffectKind::GammaCorrection,
|
|
||||||
EffectKind::MakeOpaque,
|
|
||||||
EffectKind::BrightnessContrast,
|
|
||||||
EffectKind::Levels,
|
|
||||||
EffectKind::Curves,
|
|
||||||
EffectKind::BlackAndWhite,
|
|
||||||
EffectKind::HueSaturation,
|
|
||||||
EffectKind::Invert,
|
|
||||||
EffectKind::Threshold,
|
|
||||||
EffectKind::GradientMap,
|
|
||||||
EffectKind::Vibrance,
|
|
||||||
EffectKind::ChannelMixer,
|
|
||||||
EffectKind::SelectiveColor,
|
|
||||||
EffectKind::Posterize,
|
|
||||||
EffectKind::Exposure,
|
|
||||||
EffectKind::ColorBalance,
|
|
||||||
EffectKind::PhotoFilter,
|
|
||||||
EffectKind::ColorLookup,
|
|
||||||
EffectKind::Solarize,
|
|
||||||
];
|
|
||||||
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
|
|
||||||
EffectOperation::Adjustment(adjustment) => adjustment,
|
|
||||||
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
|
|
||||||
let identity = settings::LevelsRecord::IDENTITY;
|
|
||||||
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
|
|
||||||
let levels = |composite, alpha| {
|
|
||||||
Adjustment::Levels(Box::new(settings::LevelsSettings {
|
|
||||||
composite,
|
|
||||||
red: identity,
|
|
||||||
green: identity,
|
|
||||||
blue: identity,
|
|
||||||
alpha,
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
|
|
||||||
let curves = |composite: TransferCurve, alpha: TransferCurve| {
|
|
||||||
Adjustment::Curves(Box::new(settings::CurvesSettings {
|
|
||||||
composite,
|
|
||||||
alpha,
|
|
||||||
..Default::default()
|
|
||||||
}))
|
|
||||||
};
|
|
||||||
let settings = [
|
|
||||||
levels(darkened, identity),
|
|
||||||
levels(identity, darkened),
|
|
||||||
curves(curve.clone(), TransferCurve::default()),
|
|
||||||
curves(TransferCurve::default(), curve),
|
|
||||||
];
|
|
||||||
|
|
||||||
for adjustment in defaults.iter().chain(&settings) {
|
|
||||||
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
//! 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 crate::effect_kernels::{BlurKernel, Plane};
|
||||||
use crate::resample_kernels::sample_bilinear;
|
|
||||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||||
use graphic_types::effects::{MAX_MEDIAN_GRID_RADIUS, spans_along_axes};
|
use graphic_types::effects::spans_along_axes;
|
||||||
use graphic_types::filters::{
|
use graphic_types::filters::{
|
||||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
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,
|
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||||
@@ -11,7 +10,6 @@ use graphic_types::filters::{
|
|||||||
use graphic_types::generator::pcg3d;
|
use graphic_types::generator::pcg3d;
|
||||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||||
use raster_types::parallel_rows::fill_rows;
|
use raster_types::parallel_rows::fill_rows;
|
||||||
use std::ops::Range;
|
|
||||||
|
|
||||||
/// 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.
|
/// 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.
|
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||||
@@ -477,105 +475,6 @@ fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize,
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The GPU's median of `radius` whole effect-space units, which `pixels_per_length` makes pixels along each axis, on a grid of a pixel to each unit coarsened past [`MAX_MEDIAN_GRID_RADIUS`] as the GPU's is.
|
|
||||||
/// The `image` is the range of pixels along each axis holding the image, whose own pixels read only each other, and `origin` its corner, where the coarse grid starts.
|
|
||||||
pub fn median_on_content_grid(plane: &Plane<[f32; 4]>, radius: f64, pixels_per_length: DVec2, origin: DVec2, image: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
|
||||||
let whole = radius.max(0.).floor();
|
|
||||||
let coarsening = (MAX_MEDIAN_GRID_RADIUS / whole).min(1.);
|
|
||||||
if coarsening >= 1. {
|
|
||||||
let radii = (pixels_per_length * whole).round().min(DVec2::new(plane.width as f64, plane.height as f64));
|
|
||||||
return match radii == DVec2::ZERO {
|
|
||||||
true => plane.clone(),
|
|
||||||
false => median(plane, [radii.x as usize, radii.y as usize], image),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// The coarse grid's texels, each spanning this many pixels, lie on a lattice from the image's corner, as the GPU's lattice lies from the content's origin
|
|
||||||
let texel = pixels_per_length / coarsening;
|
|
||||||
let first = ((DVec2::ZERO - origin) / texel).floor();
|
|
||||||
let end = ((DVec2::new(plane.width as f64, plane.height as f64) - origin) / texel).ceil();
|
|
||||||
let size = (end - first).max(DVec2::ONE);
|
|
||||||
let texel_center = |index: DVec2| origin + (first + index + 0.5) * texel;
|
|
||||||
|
|
||||||
// The content drawn onto the coarse grid by sampling it at each texel's center, as the GPU draws it
|
|
||||||
let (coarse_width, coarse_height) = (size.x as usize, size.y as usize);
|
|
||||||
let mut coarse = Plane::new(coarse_width, coarse_height);
|
|
||||||
fill_rows(&mut coarse.data, coarse_width, |y, row| {
|
|
||||||
for (x, texel) in row.iter_mut().enumerate() {
|
|
||||||
*texel = sample_bilinear(plane, texel_center(DVec2::new(x as f64, y as f64)));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// The texels whose centers lie within the image, and the median over a window of the radius in texels, then resampled back onto the pixels
|
|
||||||
let within = |axis: usize, count: usize| {
|
|
||||||
let inside = |index: usize| image[axis].contains(&(texel_center(DVec2::splat(index as f64))[axis].floor().max(0.) as usize));
|
|
||||||
let start = (0..count).find(|&index| inside(index)).unwrap_or(count);
|
|
||||||
let end = (start..count).find(|&index| !inside(index)).unwrap_or(count);
|
|
||||||
start..end
|
|
||||||
};
|
|
||||||
let radius_in_texels = (coarsening * whole).round() as usize;
|
|
||||||
let medians = median(&coarse, [radius_in_texels; 2], [within(0, coarse_width), within(1, coarse_height)]);
|
|
||||||
|
|
||||||
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 center = DVec2::new(x as f64, y as f64) + 0.5;
|
|
||||||
*pixel = sample_bilinear(&medians, (center - origin) / texel - first);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The median of each pixel's window reaching `across` and `down` pixels, as the GPU's median finds it: the alpha's among the window's pixels, with those past the plane's edges transparent,
|
|
||||||
/// and each straight color's among those with coverage, taking the upper median of an even count. A pixel within the `within` range along each axis reads only pixels within it. O(width × height × across × down).
|
|
||||||
pub fn median(plane: &Plane<[f32; 4]>, [across, down]: [usize; 2], within: [Range<usize>; 2]) -> Plane<[f32; 4]> {
|
|
||||||
let inside = |x: isize, y: isize| x >= 0 && y >= 0 && within[0].contains(&(x as usize)) && within[1].contains(&(y as usize));
|
|
||||||
let upper_median = |values: &mut [f32]| *values.select_nth_unstable_by(values.len() / 2, f32::total_cmp).1;
|
|
||||||
let window_capacity = (2 * across + 1) * (2 * down + 1);
|
|
||||||
|
|
||||||
let mut result = Plane::new(plane.width, plane.height);
|
|
||||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
|
||||||
// Allocated once for the row and reused for each of its pixels
|
|
||||||
let mut alphas: Vec<f32> = Vec::with_capacity(window_capacity);
|
|
||||||
let mut colors: [Vec<f32>; 3] = std::array::from_fn(|_| Vec::with_capacity(window_capacity));
|
|
||||||
|
|
||||||
let y = y as isize;
|
|
||||||
for (x, pixel) in row.iter_mut().enumerate() {
|
|
||||||
let x = x as isize;
|
|
||||||
alphas.clear();
|
|
||||||
colors.iter_mut().for_each(Vec::clear);
|
|
||||||
|
|
||||||
let clips = inside(x, y);
|
|
||||||
for read_y in y - down as isize..=y + down as isize {
|
|
||||||
for read_x in x - across as isize..=x + across as isize {
|
|
||||||
if clips && !inside(read_x, read_y) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
let on_plane = read_x >= 0 && read_y >= 0 && (read_x as usize) < plane.width && (read_y as usize) < plane.height;
|
|
||||||
let [red, green, blue, alpha] = if on_plane { plane.data[read_y as usize * plane.width + read_x as usize] } else { [0.; 4] };
|
|
||||||
alphas.push(alpha.min(1.));
|
|
||||||
if alpha > 0. {
|
|
||||||
// Kept within the finite range of the GPU's half floats
|
|
||||||
let straight = |channel: f32| (channel / alpha).max(0.).min(65504.);
|
|
||||||
colors.iter_mut().zip([red, green, blue]).for_each(|(values, channel)| values.push(straight(channel)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let alpha = upper_median(&mut alphas);
|
|
||||||
*pixel = match colors[0].is_empty() || !(alpha > 0.) {
|
|
||||||
true => [0.; 4],
|
|
||||||
false => {
|
|
||||||
let [red, green, blue] = colors.each_mut().map(|values| upper_median(values));
|
|
||||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
});
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
/// 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.
|
/// 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 {
|
fn unit_interval(hash: u32) -> f32 {
|
||||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||||
|
|||||||
@@ -18,4 +18,4 @@ pub mod warp_kernels;
|
|||||||
|
|
||||||
pub use kernel::*;
|
pub use kernel::*;
|
||||||
pub use raster_effects::evaluate_raster_effects;
|
pub use raster_effects::evaluate_raster_effects;
|
||||||
pub use value_effects::{evaluate_color_effects, evaluate_color_parameter, evaluate_gradient_effects};
|
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||||
@@ -13,7 +13,7 @@ use crate::warp_kernels::WarpRasterizer;
|
|||||||
use core_types::FallibleVec2Operations;
|
use core_types::FallibleVec2Operations;
|
||||||
use core_types::blending::BlendMode;
|
use core_types::blending::BlendMode;
|
||||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_MODEL, ATTR_GRADIENT_START_CURVATURE, Item, List};
|
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_FORM, Item, List};
|
||||||
use core_types::transfer_curve::TransferCurve;
|
use core_types::transfer_curve::TransferCurve;
|
||||||
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
use core_types::{ATTR_BLEND_MODE, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color};
|
||||||
use glam::{DAffine2, DMat2, DVec2};
|
use glam::{DAffine2, DMat2, DVec2};
|
||||||
@@ -33,8 +33,7 @@ use raster_types::parallel_rows::fill_rows;
|
|||||||
use raster_types::{CPU, Image, Raster};
|
use raster_types::{CPU, Image, Raster};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::ops::Range;
|
use std::ops::Range;
|
||||||
use vector_types::gradient::{Gradient, GradientSettings, GradientSpread};
|
use vector_types::gradient::{Gradient, GradientForm, GradientSettings, GradientSpread};
|
||||||
use vector_types::gradient_standard::GradientShape;
|
|
||||||
|
|
||||||
mod styles;
|
mod styles;
|
||||||
|
|
||||||
@@ -550,16 +549,6 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
|||||||
}
|
}
|
||||||
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
// An image of its own has nothing beneath it to blur, or for Blend If to read, which fades the content where it acts
|
||||||
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
EffectOperation::BackgroundBlur { .. } | EffectOperation::BlendIf(_) => {}
|
||||||
EffectOperation::Median { radius } => {
|
|
||||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
|
||||||
let origin = DVec2::new(margin_x as f64, margin_y as f64);
|
|
||||||
let median = |plane: &Plane<[f32; 4]>| {
|
|
||||||
let image = [margin_x..margin_x + width, margin_y..margin_y + height];
|
|
||||||
crate::filter_kernels::median_on_content_grid(plane, radius, pixels_per_length, origin, image)
|
|
||||||
};
|
|
||||||
full = median(&full);
|
|
||||||
filled = filled.map(|filled| median(&filled));
|
|
||||||
}
|
|
||||||
// A solid paint overlay paints within the content alone, like any other paint overlay
|
// A solid paint overlay paints within the content alone, like any other paint overlay
|
||||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, opacity }) => {
|
||||||
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
let painted = premultiplied_gamma_channels(color.with_alpha(color.a() * (opacity / 100.) as f32));
|
||||||
@@ -1240,7 +1229,7 @@ fn drawn_paint_colors(operation: &EffectOperation, transform: DAffine2, size: DV
|
|||||||
Some(colors)
|
Some(colors)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, gradients, and those nested in a placement of their own.
|
/// Samples the paint's color at points in the space its placement maps into, faded by its opacity, for the paints the CPU can draw: colors, images, generators, linear or radial gradients, and those nested in a placement of their own.
|
||||||
/// The paint's own adjustments are carried out first, and an image's own effects too.
|
/// The paint's own adjustments are carried out first, and an image's own effects too.
|
||||||
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
|
fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync + '_>> {
|
||||||
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
let inverse = |placement: DAffine2| (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
||||||
@@ -1271,11 +1260,7 @@ fn paint_sampler(paint: &Graphic) -> Option<Box<dyn Fn(DVec2) -> Color + Sync +
|
|||||||
let item = evaluate_gradient_effects(item.clone());
|
let item = evaluate_gradient_effects(item.clone());
|
||||||
let position = gradient_position(&item)?;
|
let position = gradient_position(&item)?;
|
||||||
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(&item));
|
let evaluator = item.element().evaluator(GradientSettings::from_item_attributes(&item));
|
||||||
let spread = evaluator.settings().spread;
|
Some(Box::new(move |point| faded(evaluator.evaluate(position(point)), opacity)))
|
||||||
Some(Box::new(move |point| {
|
|
||||||
let color = position(point).map_or(Color::TRANSPARENT, |position| evaluator.evaluate(spread_position(position, spread)));
|
|
||||||
faded(color, opacity)
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
Graphic::Graphic(item) => nested_sampler(item.element(), &|key| item.attributes().get_any(key)),
|
Graphic::Graphic(item) => nested_sampler(item.element(), &|key| item.attributes().get_any(key)),
|
||||||
Graphic::GraphicList(list) => {
|
Graphic::GraphicList(list) => {
|
||||||
@@ -1423,9 +1408,7 @@ fn displacement_map_sampler(map: &Graphic) -> Option<Box<dyn Fn(DVec2) -> [f32;
|
|||||||
let samples = gradient.interpolated_samples(settings);
|
let samples = gradient.interpolated_samples(settings);
|
||||||
|
|
||||||
Some(Box::new(move |point| {
|
Some(Box::new(move |point| {
|
||||||
let color = position(point).map_or(Color::TRANSPARENT, |position| {
|
let color = drawn_gradient_color(&samples, settings.spread, position(point));
|
||||||
drawn_gradient_color(&samples, settings.spread, spread_position(position, settings.spread))
|
|
||||||
});
|
|
||||||
premultiplied_gamma_channels(color).map(|channel| channel * opacity)
|
premultiplied_gamma_channels(color).map(|channel| channel * opacity)
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
@@ -1512,49 +1495,22 @@ fn drawn_gradient_color(samples: &[(f64, Color, Option<f64>)], spread: GradientS
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// How far along the gradient each point lies, or `None` where it's unpainted, or no function where its placement collapses a form.
|
/// How far along the gradient each point lies, or `None` where its placement collapses it.
|
||||||
/// A solid end stop's color is that end's infinite position, which [`spread_position`] keeps on that end under every spread.
|
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> f64 + Sync>> {
|
||||||
fn gradient_position(item: &Item<Gradient>) -> Option<Box<dyn Fn(DVec2) -> Option<f64> + Sync>> {
|
|
||||||
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let placement: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
let shape = GradientShape::new(
|
|
||||||
item.attribute_cloned_or_default(ATTR_GRADIENT_START_CURVATURE),
|
|
||||||
item.attribute_cloned_or_default(ATTR_GRADIENT_END_CURVATURE),
|
|
||||||
item.attribute_cloned_or_default(ATTR_GRADIENT_MODEL),
|
|
||||||
placement,
|
|
||||||
);
|
|
||||||
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse());
|
|
||||||
|
|
||||||
match shape {
|
match item.attribute_cloned_or_default::<GradientForm>(ATTR_GRADIENT_FORM) {
|
||||||
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
|
// Measured along the line across the bands, which stay parallel to the placement's sheared y axis as the renderers draw them
|
||||||
GradientShape::Linear => {
|
GradientForm::Linear => {
|
||||||
let axis = placement.matrix2.x_axis;
|
let axis = placement.matrix2.x_axis;
|
||||||
let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis);
|
let line = axis.try_project_onto(placement.matrix2.y_axis.perp()).unwrap_or(axis);
|
||||||
let origin = placement.translation;
|
let origin = placement.translation;
|
||||||
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| Some((point - origin).dot(line) / line.length_squared())) as Box<dyn Fn(DVec2) -> Option<f64> + Sync>)
|
(line.length_squared() > 0.).then(|| Box::new(move |point: DVec2| (point - origin).dot(line) / line.length_squared()) as Box<dyn Fn(DVec2) -> f64 + Sync>)
|
||||||
}
|
}
|
||||||
GradientShape::Radial => {
|
GradientForm::Radial => {
|
||||||
let to_unit = to_unit?;
|
let to_unit = (placement.matrix2.determinant() != 0.).then(|| placement.inverse())?;
|
||||||
Some(Box::new(move |point| Some(to_unit.transform_point2(point).length())))
|
Some(Box::new(move |point| to_unit.transform_point2(point).length()))
|
||||||
}
|
}
|
||||||
// Any other curvatures draw in the gradient space the full placement maps from, which a collapsed placement leaves a solid color needing none
|
|
||||||
GradientShape::Standard(gradient) => {
|
|
||||||
let to_unit = to_unit.unwrap_or_default();
|
|
||||||
Some(Box::new(move |point| gradient.t(to_unit.transform_point2(point))))
|
|
||||||
}
|
|
||||||
// Apollonian circles paint every point, and a collapsed placement takes the Standard model's solid color instead
|
|
||||||
GradientShape::Apollonian(parameters) => {
|
|
||||||
let to_unit = to_unit?;
|
|
||||||
Some(Box::new(move |point| Some(parameters.t(to_unit.transform_point2(point)))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The position a `spread` reads along the ramp for one of a gradient's positions, which keeps an infinite one (a solid end stop) on that end's color under every spread but Clear.
|
|
||||||
fn spread_position(position: f64, spread: GradientSpread) -> f64 {
|
|
||||||
match (position.is_infinite(), spread) {
|
|
||||||
(true, GradientSpread::Repeat | GradientSpread::Reflect) if position > 0. => 1. - f64::EPSILON,
|
|
||||||
(true, GradientSpread::Repeat | GradientSpread::Reflect) => 0.,
|
|
||||||
_ => position,
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1921,7 +1877,9 @@ mod tests {
|
|||||||
|
|
||||||
// A ramp from black to white across far more than the content, which lights flat ground wherever it reaches
|
// A ramp from black to white across far more than the content, which lights flat ground wherever it reaches
|
||||||
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||||
let ramp = Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)));
|
let ramp = Item::new_from_element(Gradient::new(stops))
|
||||||
|
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(-100.)) * DAffine2::from_scale(DVec2::splat(300.)))
|
||||||
|
.with_attribute(ATTR_GRADIENT_FORM, GradientForm::Linear);
|
||||||
|
|
||||||
let mut emboss = EffectOperation::default_for(graphic_types::EffectKind::BevelAndEmboss);
|
let mut emboss = EffectOperation::default_for(graphic_types::EffectKind::BevelAndEmboss);
|
||||||
if let EffectOperation::BevelAndEmboss { style, size, texture, .. } = &mut emboss {
|
if let EffectOperation::BevelAndEmboss { style, size, texture, .. } = &mut emboss {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::adjustments::{PreparedAdjustment, adjust_color};
|
|||||||
use crate::blending::overlay_paint;
|
use crate::blending::overlay_paint;
|
||||||
use core_types::Color;
|
use core_types::Color;
|
||||||
use core_types::graphene_hash::CacheHash;
|
use core_types::graphene_hash::CacheHash;
|
||||||
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_OPACITY, ATTR_OPACITY_FILL, Item};
|
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, Item};
|
||||||
use graphic_types::adjustment::Adjustment;
|
use graphic_types::adjustment::Adjustment;
|
||||||
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
use graphic_types::blend_if::{ChannelRanges, blend_ifs_acting_before, fades_content};
|
||||||
use graphic_types::effects::{EffectOperation, Effects};
|
use graphic_types::effects::{EffectOperation, Effects};
|
||||||
@@ -258,24 +258,9 @@ pub fn adjusted_gradient_with_blend_ifs(
|
|||||||
Some((resampled, resampled_settings))
|
Some((resampled, resampled_settings))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
|
|
||||||
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
|
|
||||||
pub fn carries_out_every_effect(effects: &Effects) -> bool {
|
|
||||||
effects.operations().all(|operation| match operation {
|
|
||||||
EffectOperation::Adjustment(_) => true,
|
|
||||||
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
|
|
||||||
_ => operation.changes_nothing(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
|
||||||
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
|
||||||
filled_color_after_effects(color, effects, 1.)
|
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||||
}
|
|
||||||
|
|
||||||
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
|
|
||||||
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
|
|
||||||
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
|
||||||
@@ -285,15 +270,10 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
|
|||||||
|
|
||||||
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
|
||||||
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
|
||||||
filled_gradient_after_effects(gradient, settings, effects, 1.)
|
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
|
/// The color with its effects carried out as [`color_after_effects`] does and consumed, for nodes that read the color.
|
||||||
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
|
|
||||||
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
|
|
||||||
/// A color without the effects attribute is returned as it is.
|
/// A color without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
||||||
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
let Some(color) = item.attribute::<Effects>(ATTR_EFFECTS).map(|effects| color_after_effects(*item.element(), effects)) else {
|
||||||
@@ -306,27 +286,6 @@ pub fn evaluate_color_effects(item: Item<Color>) -> Item<Color> {
|
|||||||
item
|
item
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The color as the renderers show it, for a node reading it as a parameter: its effects carried out over it faded by its fill, then its opacity fading it all, each consumed.
|
|
||||||
/// Every node reading one color goes through this, so those attributes mean the same to all of them.
|
|
||||||
pub fn evaluate_color_parameter(item: Item<Color>) -> Item<Color> {
|
|
||||||
let fill = item.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) as f32;
|
|
||||||
let opacity = item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32;
|
|
||||||
let (adjustments, blend_ifs) = item
|
|
||||||
.attribute::<Effects>(ATTR_EFFECTS)
|
|
||||||
.map(|effects| (adjustments(effects), content_blend_ifs(effects)))
|
|
||||||
.unwrap_or_default();
|
|
||||||
|
|
||||||
let shown = filled_color_with_blend_ifs(*item.element(), &adjustments, &blend_ifs, fill);
|
|
||||||
let mut item = item;
|
|
||||||
*item.element_mut() = shown.with_alpha(shown.a() * opacity);
|
|
||||||
|
|
||||||
// Consumed so a node passing the item on doesn't get them carried out twice where it's drawn
|
|
||||||
item.remove_attribute::<Effects>(ATTR_EFFECTS);
|
|
||||||
item.remove_attribute::<f64>(ATTR_OPACITY);
|
|
||||||
item.remove_attribute::<f64>(ATTR_OPACITY_FILL);
|
|
||||||
item
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
/// The gradient with its effects carried out along its ramp as [`gradient_after_effects`] does and consumed, for nodes that read its colors.
|
||||||
/// A gradient without the effects attribute is returned as it is.
|
/// A gradient without the effects attribute is returned as it is.
|
||||||
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
pub fn evaluate_gradient_effects(item: Item<Gradient>) -> Item<Gradient> {
|
||||||
@@ -392,21 +351,6 @@ mod tests {
|
|||||||
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
assert!(close(gamma(filled_color(Color::BLACK, &half_white, 0.5)), [2. / 3., 2. / 3., 2. / 3., 0.75]));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_color_parameters_fill_fades_it_beneath_its_paint_overlays_and_its_opacity_over_them() {
|
|
||||||
let red = EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
|
||||||
color: Color::RED,
|
|
||||||
blend_mode: BlendMode::Normal,
|
|
||||||
opacity: 100.,
|
|
||||||
});
|
|
||||||
let unfilled = Item::new_from_element(Color::BLACK)
|
|
||||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([red]))
|
|
||||||
.with_attribute(ATTR_OPACITY_FILL, 0_f64);
|
|
||||||
|
|
||||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.clone()).element()), [1., 0., 0., 1.]));
|
|
||||||
assert!(close(gamma(*evaluate_color_parameter(unfilled.with_attribute(ATTR_OPACITY, 0.5_f64)).element()), [1., 0., 0., 0.5]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
fn consumed_effects_fade_values_by_their_blend_ifs_where_they_read_the_colors() {
|
||||||
use graphic_types::blend_if::BlendIfRanges;
|
use graphic_types::blend_if::BlendIfRanges;
|
||||||
|
|||||||
@@ -312,29 +312,6 @@ mod cpu {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// An image's pixels as it's drawn, with its effects and fill carried out on its own pixel grid.
|
|
||||||
/// A node input of this type has the compiler read them back from the image wired into it, which carries its effects as attributes until then.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, DynAny, core_types::CacheHash)]
|
|
||||||
pub struct Pixels(Raster<CPU>);
|
|
||||||
|
|
||||||
impl Pixels {
|
|
||||||
pub fn new(raster: Raster<CPU>) -> Self {
|
|
||||||
Self(raster)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn into_raster(self) -> Raster<CPU> {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Deref for Pixels {
|
|
||||||
type Target = Image<Color>;
|
|
||||||
|
|
||||||
fn deref(&self) -> &Self::Target {
|
|
||||||
self.0.data()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub use gpu::GPU;
|
pub use gpu::GPU;
|
||||||
#[cfg(feature = "wgpu")]
|
#[cfg(feature = "wgpu")]
|
||||||
pub use gpu::{Texture, TextureWeakRef};
|
pub use gpu::{Texture, TextureWeakRef};
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
|
//! What SVG can't express, which the GPU renders as images for an SVG to take, once the SVG is drawn.
|
||||||
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
|
//! An effect whose coverage SVG filters can't work out, like the shadows and glows shaped for PSD interop, goes in its filter as a map of that coverage, while the content keeps its own markup.
|
||||||
//! Content with an effect no filter can carry out or a paint SVG only approximates (like a gradient of Apollonian circles), and a backdrop whose copy in markup would nest,
|
//! Content with an effect no filter can carry out, and a backdrop whose copy in markup would nest, are drawn as images in place of markup.
|
||||||
//! are drawn as images in place of markup. Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
//! Placeholders stand in for each until it's resolved, leaving an SVG that never is short of those effects.
|
||||||
|
|
||||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
|
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, format_transform_matrix, render_raster_cpu_image_svg};
|
||||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||||
@@ -209,7 +209,7 @@ pub struct DeferredImage {
|
|||||||
/// What the GPU renders an image of for an SVG.
|
/// What the GPU renders an image of for an SVG.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub enum DeferredContent {
|
pub enum DeferredContent {
|
||||||
/// An item with effects SVG filters can't carry out or a paint SVG only approximates, but without its opacity and blend mode, which the image takes instead.
|
/// An item with effects SVG filters can't carry out, but without its opacity and blend mode, which the image takes instead.
|
||||||
Item(Graphic),
|
Item(Graphic),
|
||||||
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
/// What lies beneath content reading its backdrop, drawn in order, for which the markers stand around no markup.
|
||||||
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
|
/// The outline of the backdrop root's `clip`, a path in the document filled by the nonzero rule, cuts it as it's drawn, as it cuts what a copy of it would hold.
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
use crate::renderer::{
|
use crate::renderer::{
|
||||||
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
|
ItemRef, RenderParams, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, painted_gradient, spread_adjusted_samples, transform_is_invertible,
|
||||||
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
|
|
||||||
};
|
};
|
||||||
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
use crate::{Render, RenderSvgSegmentList, SvgRender};
|
||||||
use core_types::color::SRGBA8;
|
use core_types::color::SRGBA8;
|
||||||
use core_types::list::List;
|
use core_types::list::List;
|
||||||
use core_types::uuid::generate_uuid;
|
use core_types::uuid::generate_uuid;
|
||||||
use core_types::{ATTR_TRANSFORM, Color};
|
use core_types::{ATTR_GRADIENT_FORM, ATTR_TRANSFORM, Color};
|
||||||
use glam::{DAffine2, DVec2};
|
use glam::{DAffine2, DVec2};
|
||||||
use graphic_types::Graphic;
|
use graphic_types::Graphic;
|
||||||
|
use graphic_types::vector_types::gradient::GradientForm;
|
||||||
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign, StrokeCap, StrokeJoin};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
use vector_types::Gradient;
|
use vector_types::Gradient;
|
||||||
@@ -86,35 +86,26 @@ impl RenderExt for List<Color> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
|
/// Adds one gradient item's def into `svg_defs` and returns the gradient ID, or `None` when the item is absent.
|
||||||
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
|
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
|
||||||
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
|
fn render_gradient_paint(item: Option<ItemRef<'_, Gradient>>, svg_defs: &mut String, item_transform: DAffine2, element_transform: DAffine2, for_mask: bool) -> Option<u64> {
|
||||||
fn render_gradient_paint(
|
|
||||||
item: Option<ItemRef<'_, Gradient>>,
|
|
||||||
svg_defs: &mut String,
|
|
||||||
item_transform: DAffine2,
|
|
||||||
element_transform: DAffine2,
|
|
||||||
stroke_transform: DAffine2,
|
|
||||||
bounds: DAffine2,
|
|
||||||
for_mask: bool,
|
|
||||||
) -> Option<u64> {
|
|
||||||
let mut stop = String::new();
|
let mut stop = String::new();
|
||||||
|
|
||||||
let item = item?;
|
let item = item?;
|
||||||
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
|
let (stops, settings) = painted_gradient(item)?;
|
||||||
let shape = gradient_shape(item);
|
let gradient_form: GradientForm = item.attribute_cloned_or_default(ATTR_GRADIENT_FORM);
|
||||||
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||||
|
|
||||||
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
|
let mut samples = spread_adjusted_samples(&stops, settings, gradient_form);
|
||||||
with_two_stops_at_least(shape, &mut samples);
|
|
||||||
|
|
||||||
|
let paint_opacity = item.paint_opacity(for_mask);
|
||||||
if paint_opacity < 1. {
|
if paint_opacity < 1. {
|
||||||
for (_, color, _) in &mut samples {
|
for (_, color, _) in &mut samples {
|
||||||
*color = color.with_alpha(color.a() * paint_opacity);
|
*color = color.with_alpha(color.a() * paint_opacity);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for &(position, color, original_midpoint) in &samples {
|
for (position, color, original_midpoint) in samples {
|
||||||
stop.push_str("<stop");
|
stop.push_str("<stop");
|
||||||
if position != 0. {
|
if position != 0. {
|
||||||
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
let _ = write!(stop, r#" offset="{}""#, (position * 1_000_000.).round() / 1_000_000.);
|
||||||
@@ -147,7 +138,13 @@ fn render_gradient_paint(
|
|||||||
|
|
||||||
let document_transform = item_transform * local_gradient_transform;
|
let document_transform = item_transform * local_gradient_transform;
|
||||||
|
|
||||||
let gradient_transform = element_transform_inverse * gradient_placement(document_transform, shape);
|
let placement = gradient_placement(document_transform, gradient_form);
|
||||||
|
let gradient_transform = format_transform_matrix(element_transform_inverse * placement);
|
||||||
|
let gradient_transform = if gradient_transform.is_empty() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
format!(r#" gradientTransform="{gradient_transform}""#)
|
||||||
|
};
|
||||||
|
|
||||||
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
|
let gradient_spread = if matches!(settings.spread, GradientSpread::Pad | GradientSpread::Clear) {
|
||||||
String::new()
|
String::new()
|
||||||
@@ -155,45 +152,26 @@ fn render_gradient_paint(
|
|||||||
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
|
format!(r#" spreadMethod="{}""#, settings.spread.svg_name())
|
||||||
};
|
};
|
||||||
|
|
||||||
// A paint drawn through a mask fills a pattern of the box around the painted area, which the masks are drawn over
|
let gradient_id = generate_uuid();
|
||||||
let masked = svg_gradient_standard(shape).is_some_and(|gradient| gradient.is_masked());
|
|
||||||
let pattern_area = if masked {
|
|
||||||
let inverse = |length: f64| if length > 0. { 1. / length } else { 0. };
|
|
||||||
let inflate = DVec2::new(inverse(item_transform.matrix2.x_axis.length()), inverse(item_transform.matrix2.y_axis.length()));
|
|
||||||
let (local_min, local_max) = (bounds.transform_point2(DVec2::ZERO) - inflate, bounds.transform_point2(DVec2::ONE) + inflate);
|
|
||||||
|
|
||||||
let corners = [local_min, DVec2::new(local_max.x, local_min.y), DVec2::new(local_min.x, local_max.y), local_max].map(|corner| stroke_transform.transform_point2(corner));
|
match gradient_form {
|
||||||
let min = corners.into_iter().reduce(DVec2::min)?;
|
GradientForm::Linear => {
|
||||||
let size = corners.into_iter().reduce(DVec2::max)? - min;
|
|
||||||
if !(size.x > 0. && size.y > 0. && size.is_finite() && min.is_finite()) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
Some((min, size))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
let area = pattern_area.map_or(String::new(), |(min, size)| format!(r#"rect x="{}" y="{}" width="{}" height="{}""#, min.x, min.y, size.x, size.y));
|
|
||||||
|
|
||||||
let layers = write_svg_gradient_paint(svg_defs, shape, &samples, &stop, &gradient_spread, gradient_transform, &area);
|
|
||||||
if let [SvgGradientLayer { paint, mask: None }] = layers.as_slice() {
|
|
||||||
return Some(*paint);
|
|
||||||
}
|
|
||||||
|
|
||||||
let (min, size) = pattern_area?;
|
|
||||||
let pattern_id = generate_uuid();
|
|
||||||
let _ = write!(
|
let _ = write!(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
r#"<pattern id="{pattern_id}" patternUnits="userSpaceOnUse" x="{}" y="{}" width="{}" height="{}" viewBox="{} {} {} {}">"#,
|
r#"<linearGradient id="{}" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="1" y2="0"{gradient_spread}{gradient_transform}>{}</linearGradient>"#,
|
||||||
min.x, min.y, size.x, size.y, min.x, min.y, size.x, size.y
|
gradient_id, stop
|
||||||
);
|
);
|
||||||
for SvgGradientLayer { paint, mask } in layers {
|
|
||||||
let mask = mask.map(|mask| format!(r#" mask="url(#{mask})""#)).unwrap_or_default();
|
|
||||||
let _ = write!(svg_defs, r#"<{area} fill="url(#{paint})"{mask} />"#);
|
|
||||||
}
|
}
|
||||||
svg_defs.push_str("</pattern>");
|
GradientForm::Radial => {
|
||||||
|
let _ = write!(
|
||||||
|
svg_defs,
|
||||||
|
r#"<radialGradient id="{}" gradientUnits="userSpaceOnUse" cx="0" cy="0" r="1"{gradient_spread}{gradient_transform}>{}</radialGradient>"#,
|
||||||
|
gradient_id, stop
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Some(pattern_id)
|
Some(gradient_id)
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RenderExt for List<Gradient> {
|
impl RenderExt for List<Gradient> {
|
||||||
@@ -207,8 +185,8 @@ impl RenderExt for List<Gradient> {
|
|||||||
_paint_reach: f64,
|
_paint_reach: f64,
|
||||||
item_transform: DAffine2,
|
item_transform: DAffine2,
|
||||||
element_transform: DAffine2,
|
element_transform: DAffine2,
|
||||||
stroke_transform: DAffine2,
|
_stroke_transform: DAffine2,
|
||||||
bounds: DAffine2,
|
_bounds: DAffine2,
|
||||||
render_params: &RenderParams,
|
render_params: &RenderParams,
|
||||||
_target: PaintTarget,
|
_target: PaintTarget,
|
||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
@@ -217,8 +195,6 @@ impl RenderExt for List<Gradient> {
|
|||||||
svg_defs,
|
svg_defs,
|
||||||
item_transform,
|
item_transform,
|
||||||
element_transform,
|
element_transform,
|
||||||
stroke_transform,
|
|
||||||
bounds,
|
|
||||||
render_params.for_mask,
|
render_params.for_mask,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -302,11 +278,10 @@ impl RenderExt for Graphic {
|
|||||||
target: PaintTarget,
|
target: PaintTarget,
|
||||||
) -> Self::Output {
|
) -> Self::Output {
|
||||||
let paint_attr = target.paint_attr();
|
let paint_attr = target.paint_attr();
|
||||||
let by_colors = paint_draws_by_its_colors(self);
|
|
||||||
|
|
||||||
match self {
|
match self {
|
||||||
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
|
||||||
Graphic::ColorList(color_list) if by_colors => color_list.render(
|
Graphic::ColorList(color_list) => color_list.render(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
user_to_document,
|
user_to_document,
|
||||||
paint_reach,
|
paint_reach,
|
||||||
@@ -317,11 +292,11 @@ impl RenderExt for Graphic {
|
|||||||
render_params,
|
render_params,
|
||||||
target,
|
target,
|
||||||
),
|
),
|
||||||
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
|
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, render_params.for_mask)
|
||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
|
||||||
Graphic::GradientList(gradient_list) if by_colors => gradient_list
|
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
|
||||||
.render(
|
.render(
|
||||||
svg_defs,
|
svg_defs,
|
||||||
user_to_document,
|
user_to_document,
|
||||||
@@ -336,10 +311,7 @@ impl RenderExt for Graphic {
|
|||||||
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
|
||||||
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
|
||||||
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
|
||||||
Graphic::Color(_)
|
Graphic::Graphic(_)
|
||||||
| Graphic::ColorList(_)
|
|
||||||
| Graphic::Gradient(_)
|
|
||||||
| Graphic::Graphic(_)
|
|
||||||
| Graphic::Vector(_)
|
| Graphic::Vector(_)
|
||||||
| Graphic::RasterCPU(_)
|
| Graphic::RasterCPU(_)
|
||||||
| Graphic::RasterGPU(_)
|
| Graphic::RasterGPU(_)
|
||||||
|
|||||||
Loaded 100 of 157 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user