mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e2c7abcd | ||
|
|
f6804d9443 | ||
|
|
5471774764 | ||
|
|
f1ca7e7ab2 | ||
|
|
07ddc86fc2 | ||
|
|
3134753d07 | ||
|
|
cece2e9957 | ||
|
|
620f8d992b | ||
|
|
db2d8625a6 | ||
|
|
c6686a65c3 | ||
|
|
455008de2e | ||
|
|
48cf345355 | ||
|
|
a102519e39 | ||
|
|
508d67f5b3 | ||
|
|
fd9da9d56c | ||
|
|
4b62b39c74 | ||
|
|
b822b64e96 | ||
|
|
617ce90276 | ||
|
|
7b2715146c | ||
|
|
cf1f7dec80 | ||
|
|
48ff126082 |
No files matched your search
@@ -20,6 +20,9 @@ on:
|
||||
linux:
|
||||
description: "Linux"
|
||||
type: boolean
|
||||
flatpak:
|
||||
description: "Flatpak (with the Linux build)"
|
||||
type: boolean
|
||||
debug:
|
||||
description: "Debug build"
|
||||
type: boolean
|
||||
@@ -33,6 +36,8 @@ on:
|
||||
type: boolean
|
||||
linux:
|
||||
type: boolean
|
||||
flatpak:
|
||||
type: boolean
|
||||
debug:
|
||||
type: boolean
|
||||
checkout_repo:
|
||||
@@ -815,7 +820,7 @@ jobs:
|
||||
path: target/artifacts
|
||||
|
||||
linux:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux || inputs.flatpak
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -892,12 +897,14 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: 🔧 Install Flatpak tooling
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y flatpak flatpak-builder
|
||||
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 🏗 Build Flatpak
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
|
||||
|
||||
@@ -914,6 +921,7 @@ jobs:
|
||||
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 📦 Upload Flatpak package
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-flatpak
|
||||
@@ -921,7 +929,7 @@ jobs:
|
||||
compression-level: 0
|
||||
|
||||
- name: 💬 Update PR comment with Flatpak artifact link
|
||||
if: github.event_name != 'push' && steps.linux-comment.outputs.comment_id
|
||||
if: inputs.flatpak && steps.linux-comment.outputs.comment_id
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# USAGE:
|
||||
# After reviewing the code, core team members may comment on a PR with `!build` followed by optional `<target>` and `<profile>` arguments.
|
||||
# This matches the syntax of the `cargo run build` CLI command, but allows platforms to be specified.
|
||||
# This extends the syntax of the `cargo run build` CLI command, allowing several targets and specific platforms to be built at once.
|
||||
#
|
||||
# `<target>`: `web` (default), `desktop` (all platforms), or `desktop:<platforms>` (subset of `windows+mac+linux`)
|
||||
# `<target>`: any of `web`, `desktop` (all platforms), `desktop:<platforms>`, or a bare platform (`windows`, `mac`, `linux`), joined by spaces or `+` (default: `web`)
|
||||
# `flatpak` additionally packages the Linux build as a Flatpak, which `desktop` and `linux` leave out
|
||||
# `<profile>`: `release` (default) or `debug`
|
||||
#
|
||||
# Only the comment's first line is parsed, so notes may follow on the lines below it.
|
||||
#
|
||||
# Examples:
|
||||
# - !build
|
||||
# - !build debug
|
||||
# - !build desktop
|
||||
# - !build web desktop
|
||||
# - !build linux
|
||||
# - !build linux+flatpak
|
||||
# - !build desktop:windows+mac
|
||||
# - !build desktop:linux debug
|
||||
# - !build web+desktop:linux debug
|
||||
name: "!build PR Command"
|
||||
|
||||
on:
|
||||
@@ -37,6 +43,7 @@ jobs:
|
||||
windows: ${{ steps.pr_info.outputs.windows }}
|
||||
mac: ${{ steps.pr_info.outputs.mac }}
|
||||
linux: ${{ steps.pr_info.outputs.linux }}
|
||||
flatpak: ${{ steps.pr_info.outputs.flatpak }}
|
||||
debug: ${{ steps.pr_info.outputs.debug }}
|
||||
|
||||
steps:
|
||||
@@ -46,8 +53,8 @@ jobs:
|
||||
# Passed through the environment so the comment text can't inject shell syntax
|
||||
COMMENT: ${{ github.event.comment.body }}
|
||||
run: |
|
||||
# Split into space-separated words
|
||||
read -ra WORDS <<< "$COMMENT"
|
||||
# Split the first line into space-separated words (comments posted from the web UI have CRLF line endings)
|
||||
read -ra WORDS <<< "${COMMENT%%$'\r'*}"
|
||||
|
||||
# First word must be "!build"
|
||||
if [[ "${WORDS[0]}" != "!build" ]]; then
|
||||
@@ -55,49 +62,47 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Initialize build flags (web defaults to true, matching the CLI default target)
|
||||
WEB="true"
|
||||
# Initialize build flags
|
||||
WEB="false"
|
||||
WINDOWS="false"
|
||||
MAC="false"
|
||||
LINUX="false"
|
||||
FLATPAK="false"
|
||||
DEBUG="false"
|
||||
PROFILE=""
|
||||
|
||||
# Parse target (optional, defaults to `web` if omitted)
|
||||
IDX=1
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
# Target: `web` enables just the web build (already the default, but accepted explicitly)
|
||||
"web")
|
||||
((IDX++)) ;;
|
||||
# Target: `desktop` enables all three desktop platforms
|
||||
"desktop")
|
||||
WEB="false"; WINDOWS="true"; MAC="true"; LINUX="true"; ((IDX++)) ;;
|
||||
# Target: `desktop:<platforms>` enables a subset of desktop platforms, split by `+`
|
||||
desktop:*)
|
||||
WEB="false"
|
||||
PLATFORMS="${WORDS[$IDX]#desktop:}"
|
||||
IFS='+' read -ra PARTS <<< "$PLATFORMS"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
case "$PART" in
|
||||
"windows") WINDOWS="true" ;;
|
||||
"mac") MAC="true" ;;
|
||||
"linux") LINUX="true" ;;
|
||||
*) echo "::error::Unrecognized platform: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
((IDX++))
|
||||
;;
|
||||
esac
|
||||
# Every remaining word is either the profile or a `+`-separated list of targets
|
||||
for WORD in "${WORDS[@]:1}"; do
|
||||
case "$WORD" in
|
||||
"debug" | "release")
|
||||
if [[ -n "$PROFILE" ]]; then
|
||||
echo "::error::Profile given more than once: $WORD"
|
||||
exit 1
|
||||
fi
|
||||
PROFILE="$WORD"
|
||||
if [[ "$WORD" == "debug" ]]; then DEBUG="true"; fi
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
# Parse profile (optional, defaults to `release` if omitted)
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
"debug") DEBUG="true"; ((IDX++)) ;;
|
||||
"release") ((IDX++)) ;;
|
||||
esac
|
||||
IFS='+' read -ra PARTS <<< "$WORD"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
# In `desktop:<platforms>`, the prefix only matters on the first platform since the others are split off as bare platforms
|
||||
case "$PART" in
|
||||
"web") WEB="true" ;;
|
||||
"desktop") WINDOWS="true"; MAC="true"; LINUX="true" ;;
|
||||
"windows" | "desktop:windows") WINDOWS="true" ;;
|
||||
"mac" | "desktop:mac") MAC="true" ;;
|
||||
"linux" | "desktop:linux") LINUX="true" ;;
|
||||
"flatpak" | "desktop:flatpak") LINUX="true"; FLATPAK="true" ;;
|
||||
*) echo "::error::Unrecognized argument: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
done
|
||||
|
||||
# Reject any unexpected trailing words
|
||||
if [[ $IDX -lt ${#WORDS[@]} ]]; then
|
||||
echo "::error::Unexpected argument: ${WORDS[$IDX]}"
|
||||
exit 1
|
||||
# Without any target, build for web to match the CLI default target
|
||||
if [[ "$WEB$WINDOWS$MAC$LINUX" != *true* ]]; then
|
||||
WEB="true"
|
||||
fi
|
||||
|
||||
# Write parsed build flags to job outputs
|
||||
@@ -105,6 +110,7 @@ jobs:
|
||||
echo "windows=$WINDOWS" >> $GITHUB_OUTPUT
|
||||
echo "mac=$MAC" >> $GITHUB_OUTPUT
|
||||
echo "linux=$LINUX" >> $GITHUB_OUTPUT
|
||||
echo "flatpak=$FLATPAK" >> $GITHUB_OUTPUT
|
||||
echo "debug=$DEBUG" >> $GITHUB_OUTPUT
|
||||
|
||||
# Fetch the PR's head branch and repo (needed for forked PRs where the code lives in another repo)
|
||||
@@ -139,6 +145,7 @@ jobs:
|
||||
windows: ${{ needs.setup.outputs.windows == 'true' }}
|
||||
mac: ${{ needs.setup.outputs.mac == 'true' }}
|
||||
linux: ${{ needs.setup.outputs.linux == 'true' }}
|
||||
flatpak: ${{ needs.setup.outputs.flatpak == 'true' }}
|
||||
debug: ${{ needs.setup.outputs.debug == 'true' }}
|
||||
checkout_repo: ${{ needs.setup.outputs.repo }}
|
||||
checkout_ref: ${{ needs.setup.outputs.ref }}
|
||||
|
||||
Generated
+31
-7
@@ -588,6 +588,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -2664,6 +2665,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -2695,6 +2697,7 @@ dependencies = [
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2710,10 +2713,12 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -4161,6 +4166,7 @@ dependencies = [
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -5719,6 +5725,20 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-kernels"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"fastnoise-lite",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
@@ -5727,18 +5747,16 @@ dependencies = [
|
||||
"color",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"image",
|
||||
"ndarray",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5991,12 +6009,14 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7974,6 +7994,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"qrcodegen",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
@@ -8034,7 +8055,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8049,7 +8070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8063,7 +8084,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8524,8 +8545,11 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+4
-3
@@ -95,6 +95,7 @@ core-types = { path = "node-graph/libraries/core-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
@@ -310,6 +311,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
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
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -252,16 +252,19 @@ impl<L: Layout> Gdd<L> {
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
if flat.is_none() && has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
let named = flat.registry().resources.values().filter_map(|entry| entry.hash);
|
||||
for hash in named.filter(|hash| working_copy_hashes.contains(hash)) {
|
||||
entries.insert(self.layout.resource_path(&hash), None);
|
||||
}
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Finds the path of every layer in a runtime network, once for each instance of the networks holding it.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::NodeMetadataEntry;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
|
||||
/// The path of every node its metadata marks as a layer.
|
||||
pub fn layer_paths(network: &NodeNetwork, node_metadata: &[NodeMetadataEntry]) -> Vec<Vec<NodeId>> {
|
||||
let layers: HashSet<(NetworkLocation, NodeId)> = node_metadata.iter().filter(|node| node.is_layer).map(|node| (node.network, node.local_id)).collect();
|
||||
|
||||
let mut layer_paths = Vec::new();
|
||||
for_each_network_instance(network, |network_path, nested| {
|
||||
let Some(location) = network.locate(network_path) else { return };
|
||||
let nested_layers = nested.nodes.keys().filter(|node_id| layers.contains(&(location, **node_id)));
|
||||
layer_paths.extend(nested_layers.map(|node_id| [network_path, &[*node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// Visits every network with its path, once for each instance of it.
|
||||
/// A definition is not entered again from inside itself.
|
||||
pub fn for_each_network_instance(network: &NodeNetwork, mut visit: impl FnMut(&[NodeId], &NodeNetwork)) {
|
||||
let mut stack = vec![(Vec::new(), Vec::new())];
|
||||
while let Some((network_path, enclosing_definitions)) = stack.pop() {
|
||||
let Some(nested) = network.nested_network(&network_path) else { continue };
|
||||
visit(&network_path, nested);
|
||||
|
||||
for (node_id, node) in &nested.nodes {
|
||||
let mut enclosing_definitions = enclosing_definitions.clone();
|
||||
match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) if enclosing_definitions.contains(&id) => continue,
|
||||
DocumentNodeImplementation::Definition(id) => enclosing_definitions.push(id),
|
||||
DocumentNodeImplementation::Network(_) => {}
|
||||
_ => continue,
|
||||
}
|
||||
stack.push(([network_path.as_slice(), &[*node_id]].concat(), enclosing_definitions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
const DEFINITION: NetworkId = NetworkId(9);
|
||||
|
||||
fn node_metadata(network: NetworkLocation, local_id: u64, is_layer: bool) -> NodeMetadataEntry {
|
||||
NodeMetadataEntry {
|
||||
network,
|
||||
local_id: NodeId(local_id),
|
||||
position: None,
|
||||
is_layer,
|
||||
display_name: None,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
input_metadata: Vec::new(),
|
||||
output_names: Vec::new(),
|
||||
output_descriptions: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let instance = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let definition = NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), instance.clone())).into_iter().collect(),
|
||||
definitions: [(DEFINITION, definition)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let metadata = [(None, 1, true), (None, 2, false), (Some(DEFINITION), 3, true), (Some(DEFINITION), 4, false)];
|
||||
let metadata: Vec<_> = metadata.into_iter().map(|(location, local_id, is_layer)| node_metadata(location, local_id, is_layer)).collect();
|
||||
|
||||
let mut layer_paths = layer_paths(&network, &metadata);
|
||||
layer_paths.sort();
|
||||
|
||||
assert_eq!(layer_paths, vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_holding_itself_is_entered_once() {
|
||||
let recursive = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), recursive.clone())].into_iter().collect(),
|
||||
definitions: [(
|
||||
DEFINITION,
|
||||
NodeNetwork {
|
||||
nodes: [(NodeId(2), recursive)].into_iter().collect(),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut network_paths = Vec::new();
|
||||
for_each_network_instance(&network, |network_path, _| network_paths.push(network_path.to_vec()));
|
||||
|
||||
assert_eq!(network_paths, vec![vec![], vec![NodeId(1)]]);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub mod codec;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod io;
|
||||
#[cfg(feature = "conversion")]
|
||||
pub mod layers;
|
||||
pub mod layout;
|
||||
mod load;
|
||||
pub mod manifest;
|
||||
|
||||
@@ -578,6 +578,50 @@ fn export_with_history_carries_history_only_resources() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history leaves behind the working copy's bytes of a resource only history still names.
|
||||
#[test]
|
||||
fn export_without_history_drops_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let byte_store = empty_byte_store();
|
||||
|
||||
let removed_payload = b"bytes of a removed resource";
|
||||
let removed_hash = ResourceHash::from(&removed_payload[..]);
|
||||
gdd.add_resource(ResourceId::new(), removed_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let kept_payload = b"bytes of a kept resource";
|
||||
let kept_hash = ResourceHash::from(&kept_payload[..]);
|
||||
let kept_id = ResourceId::new();
|
||||
gdd.add_resource(kept_id, kept_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
resources.push_source_back(&kept_id, DataSource::Embedded);
|
||||
resources.resolve(&kept_id, kept_hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(kept_id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(gdd.has_resource(&removed_hash).await, "the working copy should still hold the removed resource's bytes");
|
||||
|
||||
let options = ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, options, &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&kept_hash).await, "bytes the registry names should travel with the export");
|
||||
assert!(!reopened.has_resource(&removed_hash).await, "history-only bytes should stay behind");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
pub mod node {
|
||||
pub const CALL_ARGUMENT: &str = "call_argument";
|
||||
pub const VISIBLE: &str = "visible";
|
||||
pub const SKIP_DEDUPLICATION: &str = "skip_deduplication";
|
||||
pub const REFLECTION_METADATA: &str = "reflection_metadata";
|
||||
|
||||
pub mod input {
|
||||
|
||||
@@ -382,9 +382,6 @@ fn convert_node<M: NodeMetadataSource + ?Sized>(
|
||||
attributes
|
||||
.set_if_not_default(node::VISIBLE, &doc_node.visible, &true, timestamp)
|
||||
.map_err(map_serialization_error(node::VISIBLE))?;
|
||||
attributes
|
||||
.set_if_not_default(node::SKIP_DEDUPLICATION, &doc_node.skip_deduplication, &false, timestamp)
|
||||
.map_err(map_serialization_error(node::SKIP_DEDUPLICATION))?;
|
||||
|
||||
write_ui_attributes(&mut attributes, ctx.metadata, network, runtime_node_id, timestamp)?;
|
||||
|
||||
|
||||
@@ -260,8 +260,7 @@ fn test_metadata_preservation() {
|
||||
inputs: vec![NodeInput::import(concrete!(f64), 0), NodeInput::import(Type::Generic(Cow::Borrowed("T")), 1)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new("test::NodeWithMetadata")),
|
||||
call_argument: concrete!(String),
|
||||
visible: false, // Non-default value
|
||||
skip_deduplication: true, // Non-default value
|
||||
visible: false, // Non-default value
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
@@ -296,9 +295,6 @@ fn test_metadata_preservation() {
|
||||
// Verify visible is preserved
|
||||
assert_eq!(orig_node_0.visible, conv_node_0.visible, "visible should be preserved");
|
||||
|
||||
// Verify skip_deduplication is preserved
|
||||
assert_eq!(orig_node_0.skip_deduplication, conv_node_0.skip_deduplication, "skip_deduplication should be preserved");
|
||||
|
||||
// Verify import_type is preserved for Import inputs
|
||||
match (&orig_node_0.inputs[0], &conv_node_0.inputs[0]) {
|
||||
(NodeInput::Import { import_type: orig_type, .. }, NodeInput::Import { import_type: conv_type, .. }) => {
|
||||
@@ -354,11 +350,6 @@ fn test_demo_artwork_round_trip() {
|
||||
artwork_name, node_id
|
||||
);
|
||||
assert_eq!(orig_node.visible, conv_node.visible, "{}: visible should be preserved for node {:?}", artwork_name, node_id);
|
||||
assert_eq!(
|
||||
orig_node.skip_deduplication, conv_node.skip_deduplication,
|
||||
"{}: skip_deduplication should be preserved for node {:?}",
|
||||
artwork_name, node_id
|
||||
);
|
||||
|
||||
// Check input count
|
||||
assert_eq!(
|
||||
|
||||
@@ -457,7 +457,6 @@ fn convert_node(context: &ConversionContext, node: &crate::Node) -> Result<Docum
|
||||
call_argument: node.attributes.get_or(node::CALL_ARGUMENT, concrete!(core_types::Context)),
|
||||
implementation: convert_implementation(context, &node.implementation)?,
|
||||
visible: node.attributes.get_or(node::VISIBLE, true),
|
||||
skip_deduplication: node.attributes.get_or(node::SKIP_DEDUPLICATION, false),
|
||||
// Regenerated during compilation; not stored.
|
||||
compile_metadata: None,
|
||||
original_location: Default::default(),
|
||||
|
||||
@@ -5,7 +5,7 @@ use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
@@ -97,10 +97,12 @@ impl LiveDocument {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
/// The document's runtime network, with the path of every layer in it.
|
||||
pub async fn network_with_layers(&self) -> Result<(NodeNetwork, Vec<Vec<NodeId>>), LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
Ok(network)
|
||||
let (network, node_metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &node_metadata);
|
||||
Ok((network, layers))
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
|
||||
+115
-4
@@ -5,7 +5,8 @@ use document_container::archive::ArchiveFormat;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -17,6 +18,8 @@ use migration_nodes as _;
|
||||
/// A document's runtime network, with the file it was opened from.
|
||||
pub struct LoadedDocument {
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`, once for each instance of the networks holding it.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
pub origin: DocumentOrigin,
|
||||
}
|
||||
|
||||
@@ -58,9 +61,13 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let named_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
|
||||
if !named_gdd && ArchiveFormat::detect(&bytes).is_none() {
|
||||
let document_string = String::from_utf8(bytes).map_err(|error| format!("Document {} is neither a .gdd archive nor text: {error}", path.display()))?;
|
||||
let network = legacy_network(&document_string).map_err(|error| format!("Failed to parse legacy document {}: {error}", path.display()))?;
|
||||
let parse_error = |error| format!("Failed to parse legacy document {}: {error}", path.display());
|
||||
let document: serde_json::Value = serde_json::from_str(&document_string).map_err(parse_error)?;
|
||||
let network = legacy_network(&document).map_err(parse_error)?;
|
||||
let layers = legacy_layer_paths(&network, &document);
|
||||
return Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Legacy(document_string),
|
||||
});
|
||||
}
|
||||
@@ -68,14 +75,118 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let gdd = open_gdd(&bytes).await?;
|
||||
let declarations = gdd.declarations(&gdd).await;
|
||||
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &nodes);
|
||||
Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Gdd { gdd: Box::new(gdd), nodes, networks },
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_network(document_string: &str) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let document: serde_json::Value = serde_json::from_str(document_string)?;
|
||||
fn legacy_network(document: &serde_json::Value) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let network = document["network_interface"]["network"].to_string();
|
||||
serde_json::from_str(&network)
|
||||
}
|
||||
|
||||
/// The path of every node a legacy document's metadata marks as a layer.
|
||||
fn legacy_layer_paths(network: &NodeNetwork, document: &serde_json::Value) -> Vec<Vec<NodeId>> {
|
||||
let mut layer_paths = Vec::new();
|
||||
document_format::layers::for_each_network_instance(network, |network_path, _| {
|
||||
let Some(network_metadata) = legacy_network_metadata(network, document, network_path) else {
|
||||
return;
|
||||
};
|
||||
let is_layer = |node_metadata: &serde_json::Value| node_metadata["node_type_metadata"]["Layer"].is_object();
|
||||
let layers = legacy_node_metadata(network_metadata).into_iter().filter(|(_, node_metadata)| is_layer(node_metadata));
|
||||
layer_paths.extend(layers.map(|(node_id, _)| [network_path, &[node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// The metadata of the network at this path in a legacy document.
|
||||
/// Older documents keep a held network's metadata inside its node's metadata, newer ones keep a definition's in a table.
|
||||
fn legacy_network_metadata<'a>(network: &NodeNetwork, document: &'a serde_json::Value, network_path: &[NodeId]) -> Option<&'a serde_json::Value> {
|
||||
let document_network_metadata = &document["network_interface"]["network_metadata"];
|
||||
let definitions = &document_network_metadata["persistent_metadata"]["definitions"];
|
||||
|
||||
let mut current = network;
|
||||
let mut network_metadata = document_network_metadata;
|
||||
for node_id in network_path {
|
||||
let node = current.nodes.get(node_id)?;
|
||||
network_metadata = match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => &definitions[id.0.to_string()],
|
||||
DocumentNodeImplementation::Network(_) => &legacy_node_metadata(network_metadata).remove(node_id)?["network_metadata"],
|
||||
_ => return None,
|
||||
};
|
||||
current = network.implementation_network(&node.implementation)?;
|
||||
}
|
||||
|
||||
Some(network_metadata)
|
||||
}
|
||||
|
||||
/// The metadata of each node in a legacy network, by ID.
|
||||
fn legacy_node_metadata(network_metadata: &serde_json::Value) -> HashMap<NodeId, &serde_json::Value> {
|
||||
let entries = network_metadata["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten();
|
||||
entries.filter_map(|entry| Some((NodeId(entry[0].as_u64()?), &entry[1]["persistent_metadata"]))).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
fn node(implementation: DocumentNodeImplementation) -> DocumentNode {
|
||||
DocumentNode { implementation, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A network holding the nodes 3 and 4.
|
||||
fn inner_network() -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_legacy_layer_paths(network: &NodeNetwork, document: &str) -> Vec<Vec<NodeId>> {
|
||||
let document = serde_json::from_str(document).expect("The test document should be valid JSON");
|
||||
let mut layer_paths = legacy_layer_paths(network, &document);
|
||||
layer_paths.sort();
|
||||
layer_paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let definition = NetworkId(9);
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), node(DocumentNodeImplementation::Definition(definition)))).into_iter().collect(),
|
||||
definitions: [(definition, inner_network())].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [2, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]],
|
||||
"definitions": { "9": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} } }
|
||||
} } } }"#;
|
||||
|
||||
let expected = vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]];
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_held_network_is_found() {
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), node(DocumentNodeImplementation::Network(inner_network())))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": {
|
||||
"node_type_metadata": { "Layer": {} },
|
||||
"network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} }
|
||||
} }]]
|
||||
} } } }"#;
|
||||
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)]]);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::{Compiler, Declaration, DeclarationResolver, InputConnector, MigrationError, NewNode, OutputConnector, encode};
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use document_graph_storage::{Implementation, InputSlot, NetworkId, NodeId, NodeInput, Registry, TimeStamp, Value};
|
||||
use serde::Serialize;
|
||||
use std::ops::Deref;
|
||||
@@ -390,6 +391,16 @@ impl Inputs {
|
||||
self.origins.push(None);
|
||||
}
|
||||
|
||||
/// Add a slot the compiler fills in with what `metadata` names, a frozen mirror value such as the node's path.
|
||||
pub fn push_reflection<T: Serialize>(&mut self, metadata: T) {
|
||||
let mut slot = new_slot(NodeInput::Reflection);
|
||||
slot.attributes.set(REFLECTION_METADATA, encode(&metadata), TimeStamp::ORIGIN);
|
||||
|
||||
self.edited = true;
|
||||
self.slots.push(slot);
|
||||
self.origins.push(None);
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, index: u32) {
|
||||
if !self.check(index, self.slots.len()) {
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[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};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
@@ -4,3 +4,5 @@ use migration_core::rename;
|
||||
|
||||
// Version 2 is where old Upload Texture nodes join the lineage, and stored Passthrough nodes already have its layout
|
||||
rename!("graphene_core::ops::PassthroughNode"@1 => @2);
|
||||
// The removed Monitor node passes its one input on, as a Passthrough does
|
||||
rename!("graphene_core::memo::MonitorNode"@1 => "graphene_core::ops::PassthroughNode"@2);
|
||||
@@ -1,6 +1,8 @@
|
||||
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
mod vector_nodes;
|
||||
@@ -0,0 +1,99 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
const FORM: u32 = 1;
|
||||
|
||||
/// 'Gradient Form' became 'Gradient Curvature', whose start and end curvatures take the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for
|
||||
/// radial. A wired form becomes linear, 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.],
|
||||
};
|
||||
|
||||
inputs.set(FORM, literal(Tagged::Number(start)));
|
||||
inputs.push(literal(Tagged::Number(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::{NodeInput, decl};
|
||||
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());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let gradient = literal(Tagged::Number(0.));
|
||||
for (old_form, [start, end]) in [
|
||||
(form(GradientForm::Linear), [0., 0.]),
|
||||
(form(GradientForm::Radial), [1., 0.5]),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.]),
|
||||
] {
|
||||
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(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,104 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, Node, decl, literal, migration};
|
||||
|
||||
/// The pattern fills the plane rather than being cut off at the unit square, so it's read through that square filled with it, and the node gained a
|
||||
/// primary input.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@1 => @2)]
|
||||
pub fn mandelbrot_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
inputs.insert(0, literal(Tagged::None));
|
||||
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 1.);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::{ROOT_NETWORK, TimeStamp};
|
||||
use migration_core::attr::node::ui::{IS_LAYER, POSITION};
|
||||
use migration_core::{NodeInput, Position};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(0, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV1, &contract());
|
||||
check_undo(&MandelbrotV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_reads_a_unit_square_filled_with_the_pattern() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
fixture.export(NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), [literal(Tagged::None)]);
|
||||
|
||||
let Some(NodeInput::Node { id: placement, .. }) = migrated.networks[&ROOT_NETWORK].exports[0].target else {
|
||||
panic!("the export should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, placement), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([0.5, 0.5])));
|
||||
}
|
||||
|
||||
/// The positions of the pattern, its paint, the rectangle, the fill, and the placement after migrating a pattern at `position`.
|
||||
fn placed_square(position: Position, layer: Option<[i32; 2]>) -> [Option<Position>; 5] {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
let place = |fixture: &mut Fixture, node, position: Position| {
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
||||
};
|
||||
place(&mut fixture, mandelbrot, position);
|
||||
|
||||
let reader = match layer {
|
||||
Some(layer_position) => {
|
||||
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::None), NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
place(&mut fixture, layer, Position::Absolute(layer_position));
|
||||
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
||||
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
||||
layer
|
||||
}
|
||||
None => fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]),
|
||||
};
|
||||
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(reader, if layer.is_some() { 1 } else { 0 });
|
||||
let fill = reads(placement, 0);
|
||||
let (rectangle, paint) = (reads(fill, 0), reads(fill, 1));
|
||||
|
||||
[mandelbrot, paint, rectangle, fill, placement].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chained_pattern_gives_its_place_to_the_filled_rectangle() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Chain, Some([30, 10]));
|
||||
|
||||
assert_eq!([rectangle, fill, placement], [Some(Position::Chain); 3]);
|
||||
assert_eq!(pattern, Some(Position::Absolute([0, 0])));
|
||||
assert_eq!(paint, Some(Position::Absolute([7, 0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_pattern_gets_its_square_to_the_right() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Absolute([5, 5]), None);
|
||||
|
||||
assert_eq!(pattern, Some(Position::Absolute([5, 5])));
|
||||
assert_eq!(paint, Some(Position::Absolute([12, 5])));
|
||||
assert_eq!(rectangle, Some(Position::Absolute([12, 2])));
|
||||
assert_eq!(fill, Some(Position::Absolute([19, 5])));
|
||||
assert_eq!(placement, Some(Position::Absolute([26, 5])));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,97 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, MigrationError, Node, decl, literal_of, migration};
|
||||
|
||||
const CLIP: u32 = 1;
|
||||
|
||||
/// The pattern fills the plane, so the Clip toggle that cut it off at a 100-unit square is gone, and a clipped pattern is read through that square
|
||||
/// filled with it. A wired toggle counts as clipped.
|
||||
#[migration("raster_nodes::std_nodes::NoisePatternNode"@1 => @2)]
|
||||
pub fn noise_pattern_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let Some(clip) = node.inputs().get(CLIP as usize) else {
|
||||
return Err(MigrationError::invariant("Noise Pattern has a Clip input"));
|
||||
};
|
||||
let clipped = !matches!(literal_of::<Tagged>(&clip.input), Some(Tagged::Bool(false)));
|
||||
|
||||
inputs.remove(CLIP);
|
||||
|
||||
if clipped {
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 100.);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@1);
|
||||
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
// The toggle a clipped pattern's readers move off of can't be reading that pattern, since its own migration removes it
|
||||
reads_own_output: |slot| slot != CLIP as usize,
|
||||
..SourceContract::new(16, |random, slot| match slot {
|
||||
1 => literal(Tagged::Bool(random.below(2) == 0)),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn noise_inputs(clip: bool) -> Vec<NodeInput> {
|
||||
let mut inputs: Vec<NodeInput> = (0..16).map(|slot| literal(Tagged::Number(slot as f64))).collect();
|
||||
inputs[CLIP as usize] = literal(Tagged::Bool(clip));
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&NoisePatternV1, &contract());
|
||||
check_undo(&NoisePatternV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_pattern_is_read_through_a_square_filled_with_it() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(true));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
// The settings after the removed toggle move down a slot
|
||||
let inputs = fixture.inputs(&migrated, noise);
|
||||
assert_eq!(inputs.len(), 15);
|
||||
assert_eq!(inputs[CLIP as usize], literal(Tagged::Number(2.)));
|
||||
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(consumer, 0);
|
||||
let fill = reads(placement, 0);
|
||||
let paint = reads(fill, 1);
|
||||
assert_eq!(reads(paint, 0), noise);
|
||||
assert_eq!(fixture.declaration_of(&migrated, reads(fill, 0)), Some(decl!("vector_nodes::generator_nodes::RectangleNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([50., 50.])));
|
||||
assert_eq!(fixture.inputs(&migrated, paint)[1], literal(Tagged::DVec2([-50., -50.])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclipped_pattern_keeps_its_readers() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(false));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, noise).len(), 15);
|
||||
assert_eq!(fixture.inputs(&migrated, consumer), [NodeInput::Node { id: noise, index: 0 }]);
|
||||
assert_eq!(migrated.node_instances.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! The square that Noise Pattern and Mandelbrot were cut off at before their patterns filled the plane, which their migrations keep.
|
||||
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, Declaration, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, literal};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants these migrations use.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
BoxCorners(Vec<f64>),
|
||||
Color(Color),
|
||||
GradientRamp(GradientRamp),
|
||||
GradientForm(GradientForm),
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
blue: f32,
|
||||
alpha: f32,
|
||||
linear: bool,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
|
||||
Self {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
linear: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientRamp {
|
||||
stops: GradientStops,
|
||||
gradient_space: GradientSpace,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientStops {
|
||||
color: Vec<Color>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientSpace {
|
||||
OkLab,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientForm {
|
||||
Linear,
|
||||
}
|
||||
|
||||
/// The declarations the square is built from, which each migration names itself so the runner orders it against them.
|
||||
pub(super) struct SquareNodes {
|
||||
pub rectangle: Declaration,
|
||||
pub fill: Declaration,
|
||||
pub transform: Declaration,
|
||||
}
|
||||
|
||||
/// Makes everything reading the pattern read a rectangle filled with it instead, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
pub(super) fn fill_square_with_pattern(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes, nodes: SquareNodes, size: f64) {
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let number = |number| literal(Tagged::Number(number));
|
||||
let pair = |value| literal(Tagged::DVec2([value, value]));
|
||||
let wire = |id| NodeInput::Node { id, index: 0 };
|
||||
let transform = |content, translation| vec![content, pair(translation), number(0.), pair(1.), pair(0.)];
|
||||
|
||||
let rectangle = downstream.add_node(NewNode {
|
||||
declaration: nodes.rectangle,
|
||||
inputs: vec![
|
||||
literal(Tagged::None),
|
||||
number(size),
|
||||
number(size),
|
||||
literal(Tagged::BoxCorners(Vec::new())),
|
||||
literal(Tagged::Bool(true)),
|
||||
literal(Tagged::Bool(false)),
|
||||
],
|
||||
});
|
||||
let paint = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(node.id()), -size / 2.),
|
||||
},
|
||||
"paint",
|
||||
);
|
||||
|
||||
// Past the rectangle and its paint, the Fill holds the defaults its definition gives a new node
|
||||
let backup_gradient = GradientRamp {
|
||||
stops: GradientStops {
|
||||
color: vec![Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)],
|
||||
},
|
||||
gradient_space: GradientSpace::OkLab,
|
||||
};
|
||||
let fill = downstream.add_node(NewNode {
|
||||
declaration: nodes.fill,
|
||||
inputs: vec![
|
||||
wire(rectangle),
|
||||
wire(paint),
|
||||
literal(Tagged::Color(Color::new(0., 0., 0., 0.))),
|
||||
literal(Tagged::GradientRamp(backup_gradient)),
|
||||
literal(Tagged::GradientForm(GradientForm::Linear)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||
],
|
||||
});
|
||||
|
||||
let placement = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(fill), size / 2.),
|
||||
},
|
||||
"placement",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: placement, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// In a layer's chain, the filled rectangle takes the pattern's place. The pattern and its paint leave the chain with no coordinates to go by,
|
||||
// so they start at the graph's origin. Elsewhere the square sits to the pattern's right.
|
||||
let stored = node.attributes().get_typed::<Position>(POSITION);
|
||||
if stored == Some(Position::Chain) {
|
||||
for id in [placement, fill, rectangle] {
|
||||
attributes.set(id, POSITION, &Position::Chain);
|
||||
}
|
||||
|
||||
attributes.set(node.id(), POSITION, &Position::Absolute([0, 0]));
|
||||
attributes.set(paint, POSITION, &Position::Absolute([7, 0]));
|
||||
} else {
|
||||
let [x, y] = match stored {
|
||||
Some(Position::Absolute(coordinates)) => coordinates,
|
||||
_ => [0, 0],
|
||||
};
|
||||
for (id, [x_offset, y_offset]) in [(paint, [7, 0]), (rectangle, [7, -3]), (fill, [14, 0]), (placement, [21, 0])] {
|
||||
attributes.set(id, POSITION, &Position::Absolute([x + x_offset, y + y_offset]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `vector_nodes`.
|
||||
|
||||
mod path_from_path_network;
|
||||
mod renames;
|
||||
@@ -0,0 +1,49 @@
|
||||
use migration_core::{Inputs, migration};
|
||||
use serde::Serialize;
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant this migration uses.
|
||||
#[derive(Serialize)]
|
||||
enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// The Path subgraph became the node it held, which takes the instance's inputs and is given its own path as that node was.
|
||||
#[migration(network "Path"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2)]
|
||||
pub fn path_from_path_network(inputs: &mut Inputs) {
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::NodeInput;
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
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(&PathFromPathNetwork, &contract());
|
||||
check_undo(&PathFromPathNetwork, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapses_into_the_node_and_gives_it_its_path() {
|
||||
let (content, modification) = (literal(1.), literal(2.));
|
||||
|
||||
let mut fixture = Fixture::new(&PathFromPathNetwork);
|
||||
let (path, network) = fixture.add_network(decl!(network "Path"@1), vec![content.clone(), modification.clone()]);
|
||||
let migrated = fixture.migrate(&PathFromPathNetwork).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, path), Some(decl!("vector_nodes::vector_modification_nodes::PathNode"@2)));
|
||||
assert!(!migrated.networks.contains_key(&network));
|
||||
assert_eq!(fixture.inputs(&migrated, path), [content, modification, NodeInput::Reflection]);
|
||||
|
||||
let own_path = &migrated.node_instances[&path].inputs()[2];
|
||||
assert_eq!(own_path.attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier, or changed version with stored nodes staying as they are.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("vector_nodes::vector_modification_nodes::PathModifyNode"@1 => "vector_nodes::vector_modification_nodes::PathNode"@2);
|
||||
@@ -33,6 +33,18 @@ pub fn opacity_toggles(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Number(100.)));
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `DocumentNodeMetadata` variant the migration below uses.
|
||||
#[derive(Serialize)]
|
||||
pub enum Reflected {
|
||||
DocumentNodePath,
|
||||
}
|
||||
|
||||
/// Gives the node its own path.
|
||||
#[migration("vector_nodes::bounding_box"@1 => @2)]
|
||||
pub fn bounding_box_own_path(inputs: &mut Inputs) {
|
||||
inputs.push_reflection(Reflected::DocumentNodePath);
|
||||
}
|
||||
|
||||
pub const ROTATION: u32 = 2;
|
||||
|
||||
/// Rotation is now stored in degrees.
|
||||
|
||||
@@ -6,8 +6,9 @@ mod networks;
|
||||
mod registration;
|
||||
mod rewrite;
|
||||
|
||||
use document_graph_storage::attributes::attr::node::REFLECTION_METADATA;
|
||||
use document_graph_storage::{NodeId, NodeInput, ROOT_NETWORK, Registry};
|
||||
use examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
|
||||
use examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, ROTATION, Tagged, TransformDegrees};
|
||||
use migration_core::{decl, literal, literal_of};
|
||||
use migration_runner::RunnerError;
|
||||
use migration_runner::testing::{Fixture, registered};
|
||||
@@ -58,6 +59,19 @@ fn opacity_toggles_build_the_target_layout() {
|
||||
assert_eq!(fixture.declaration_of(&migrated, opacity), Some(decl!("blending_nodes::opacity"@2)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reflection_input_stores_what_it_reflects() {
|
||||
let mut fixture = Fixture::new(&BoundingBoxOwnPath);
|
||||
let bounding_box = fixture.add(decl!("vector_nodes::bounding_box"@1), vec![literal(Tagged::Number(1.))]);
|
||||
|
||||
let migrated = fixture.migrate(&BoundingBoxOwnPath).unwrap();
|
||||
|
||||
let slots = migrated.node_instances[&bounding_box].inputs();
|
||||
assert_eq!(slots.len(), 2);
|
||||
assert_eq!(slots[1].input, NodeInput::Reflection);
|
||||
assert_eq!(slots[1].attributes.get_typed::<String>(REFLECTION_METADATA).as_deref(), Some("DocumentNodePath"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_converts_a_literal_rotation() {
|
||||
let mut fixture = Fixture::new(&TransformDegrees);
|
||||
|
||||
@@ -33,6 +33,7 @@ fn every_migration_registers_once() {
|
||||
decl!("order::static_late"@1),
|
||||
decl!("transform_nodes::transform"@1),
|
||||
decl!("vector_nodes::angle_between"@1),
|
||||
decl!("vector_nodes::bounding_box"@1),
|
||||
decl!("vector_nodes::extract_xy"@1),
|
||||
decl!("vector_nodes::split_vec2"@2),
|
||||
];
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The history properties of `migration_runner::testing` on the examples.
|
||||
|
||||
use crate::examples::{AngleBetweenDegrees, Axis, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
|
||||
use crate::examples::{AngleBetweenDegrees, Axis, BoundingBoxOwnPath, ExtractXyToSplit, OpacityToggles, Tagged, TransformDegrees};
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Random, SourceContract, check_commutation, check_undo, registered};
|
||||
|
||||
@@ -18,6 +18,11 @@ fn opacity_toggles_commute() {
|
||||
check_commutation(&OpacityToggles, &numbers(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounding_box_own_path_commutes() {
|
||||
check_commutation(&BoundingBoxOwnPath, &numbers(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transform_degrees_commutes() {
|
||||
check_commutation(&TransformDegrees, &numbers(3));
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(crate) struct NodeSource {
|
||||
pub version: u32,
|
||||
pub function: String,
|
||||
pub file: PathBuf,
|
||||
/// The parameters and output as written, without their attributes. 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.
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
@@ -131,7 +131,10 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
}
|
||||
|
||||
let function_name = function.sig.ident.to_string();
|
||||
let parameters = function.sig.inputs.iter().map(|parameter| match parameter {
|
||||
|
||||
// A `#[data]` field is the node's own state rather than a stored input, so documents don't notice it changing
|
||||
let is_data_field = |parameter: &&syn::FnArg| matches!(parameter, syn::FnArg::Typed(typed) if typed.attrs.iter().any(|attribute| attribute.path().is_ident("data")));
|
||||
let parameters = function.sig.inputs.iter().filter(|parameter| !is_data_field(parameter)).map(|parameter| match parameter {
|
||||
syn::FnArg::Typed(typed) => {
|
||||
let (pattern, ty) = (&typed.pat, &typed.ty);
|
||||
quote::quote!(#pattern: #ty).to_string()
|
||||
@@ -149,3 +152,23 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_fields_are_left_out_of_the_signature() {
|
||||
let function: syn::ItemFn = syn::parse_quote! {
|
||||
#[node_macro::node(category("Raster"))]
|
||||
fn lookup(_: impl Ctx, image: Item<Color>, #[data] cache: Cache) -> Item<Color> {
|
||||
image
|
||||
}
|
||||
};
|
||||
let node = node_source(&function, Path::new("lib.rs"), &["raster_nodes".to_string()]).expect("the function is a node");
|
||||
|
||||
assert_eq!(node.identifier, "raster_nodes::LookupNode");
|
||||
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
||||
assert!(node.signature.contains("image"), "{}", node.signature);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate.
|
||||
|
||||
use crate::lineage::{MigrationStep, find_migrations};
|
||||
use crate::lineage::{MigrationStep, find_all_migrations};
|
||||
use crate::nodes::{NodeSource, find_nodes};
|
||||
use convert_case::{Case, Casing};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +18,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
|
||||
match (command, arguments) {
|
||||
("new", []) => {
|
||||
let steps = missing_steps(&nodes, &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(&nodes, &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
println!("Every node version already has a migration leading to it");
|
||||
return Ok(());
|
||||
@@ -35,7 +35,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
));
|
||||
}
|
||||
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
return Err(format!("migrations up to `{}`@{} already exist", node.identifier, node.version));
|
||||
}
|
||||
@@ -242,6 +242,7 @@ fn declare_module(file: &Path, module: &str) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lineage::find_migrations;
|
||||
|
||||
/// A workspace with one node crate and an empty `migration-nodes`, removed on drop.
|
||||
struct Workspace(PathBuf);
|
||||
@@ -329,6 +330,22 @@ mod tests {
|
||||
assert!(missing_steps(&nodes, &found).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_reached_from_a_compiled_migration_needs_no_step() {
|
||||
let workspace = Workspace::new("compiled");
|
||||
let compiled = workspace.0.join("document/migrations/compiled/src");
|
||||
std::fs::create_dir_all(&compiled).unwrap();
|
||||
std::fs::write(
|
||||
compiled.join("lib.rs"),
|
||||
"#[migration(\"old::Node\"@1 => \"blending_nodes::OpacityNode\"@2)]\npub fn opacity_from_node(inputs: &mut Inputs) {}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
scaffold(&workspace.0, "new", &[]).unwrap();
|
||||
assert!(!workspace.0.join(MIGRATIONS).join("blending_nodes/opacity_v1.rs").exists());
|
||||
assert!(workspace.read("legacy/brighten_v1.rs").contains("\"legacy::adjust::BrightenNode\"@1 => @2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_no_module_declares_is_no_migration() {
|
||||
let workspace = Workspace::new("undeclared");
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::consts::DEFAULT_STROKE_WIDTH;
|
||||
use crate::messages::portfolio::document::SelectionParts;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface;
|
||||
use crate::messages::portfolio::document::utility_types::nodes::SelectedNodes;
|
||||
@@ -429,7 +429,7 @@ impl MessageHandler<ClipboardMessage, ClipboardMessageContext<'_>> for Clipboard
|
||||
let mut layers = Vec::new();
|
||||
|
||||
for (_, new_vector, transform) in paths {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
|
||||
error!("Path node does not exist");
|
||||
continue;
|
||||
};
|
||||
@@ -987,17 +987,17 @@ mod test {
|
||||
.iter()
|
||||
.find_map(|(id, node)| (node.implementation == graph_craft::document::DocumentNodeImplementation::Definition(entry)).then_some(*id))
|
||||
.expect("the pasted layer");
|
||||
let (inner, input_index) = interface.document_network().definitions[&entry]
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface.document_network().definitions[&entry]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the entry should have a value input");
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("the entry should have an Extend node");
|
||||
let before = interface.document_network().definitions[&entry].clone();
|
||||
let NodeInput::Value { tagged_value, exposed } = &before.nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[layer]);
|
||||
|
||||
// Leaving out the stack below keeps the entry a working layer
|
||||
let no_base = NodeInput::type_default(graphene_std::list!(graphene_std::Graphic), false);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), no_base, &[layer]);
|
||||
assert_ne!(interface.document_network().definitions[&entry], before, "the edit should change the pasted entry");
|
||||
|
||||
editor.paste_from_clipboard(clipboard.clone()).await;
|
||||
|
||||
@@ -64,6 +64,9 @@ pub struct DropdownInput {
|
||||
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
|
||||
#[serde(rename = "selectedIndex")]
|
||||
pub selected_index: Option<u32>,
|
||||
// Shown while no entry is selected
|
||||
#[derivative(Default(value = "\"-\".to_string()"))]
|
||||
pub placeholder: String,
|
||||
#[serde(rename = "drawIcon")]
|
||||
pub draw_icon: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -32,7 +33,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -65,9 +66,9 @@ const DEFAULT_ROWS_IN_VIEW: Range<usize> = 0..100;
|
||||
impl MessageHandler<DataPanelMessage, DataPanelMessageContext<'_>> for DataPanelMessageHandler {
|
||||
fn process_message(&mut self, message: DataPanelMessage, responses: &mut VecDeque<Message>, context: DataPanelMessageContext) {
|
||||
match message {
|
||||
DataPanelMessage::UpdateLayout { mut inspect_result } => {
|
||||
self.introspected_data = inspect_result.take_data();
|
||||
self.introspected_node_path = inspect_result.inspect_node_path;
|
||||
DataPanelMessage::UpdateLayout { inspect_result } => {
|
||||
self.introspected_data = inspect_result.data;
|
||||
self.introspected_node_path = inspect_result.node_path;
|
||||
self.context = inspect_result.context;
|
||||
self.update_layout(responses, context);
|
||||
}
|
||||
@@ -394,6 +395,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -450,6 +452,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -792,6 +795,45 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -857,6 +899,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -865,6 +908,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -882,6 +926,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -890,6 +935,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1213,6 +1259,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1359,9 +1410,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -1383,6 +1436,12 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -262,9 +262,6 @@ fn diff_document_node(out: &mut String, expected: &graph_craft::document::Docume
|
||||
if expected.visible != actual.visible {
|
||||
let _ = writeln!(out, " visible: expected={} actual={}", expected.visible, actual.visible);
|
||||
}
|
||||
if expected.skip_deduplication != actual.skip_deduplication {
|
||||
let _ = writeln!(out, " skip_deduplication: expected={} actual={}", expected.skip_deduplication, actual.skip_deduplication);
|
||||
}
|
||||
if expected.compile_metadata != actual.compile_metadata {
|
||||
let _ = writeln!(out, " compile_metadata: expected={:?} actual={:?}", expected.compile_metadata, actual.compile_metadata);
|
||||
}
|
||||
|
||||
@@ -325,6 +325,9 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1915,6 +1915,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
@@ -4894,7 +4902,7 @@ mod document_message_handler_tests {
|
||||
}
|
||||
|
||||
// Merging nodes whose output isn't wired downstream produces an encapsulating subnetwork with no exports.
|
||||
// Inspecting it via the Data panel (which splices in a monitor node) must not leave a dangling reference that crashes compilation.
|
||||
// Inspecting it via the Data panel must not leave a dangling reference that crashes compilation.
|
||||
#[tokio::test]
|
||||
async fn merge_selected_nodes_while_inspecting_does_not_crash() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
@@ -4909,7 +4917,7 @@ mod document_message_handler_tests {
|
||||
let merged = editor.active_document().network_interface.selected_nodes_in_nested_network(&[]).unwrap().0.clone();
|
||||
assert_eq!(merged.len(), 1, "merge should leave one encapsulating node selected");
|
||||
|
||||
// Simulate the Data panel inspecting the merged node, which compiles the graph with a monitor node spliced in
|
||||
// Simulate the Data panel inspecting the merged node
|
||||
let portfolio = &mut editor.editor.dispatcher.message_handlers.portfolio_message_handler;
|
||||
let document_id = portfolio.active_document_id.unwrap();
|
||||
let document = portfolio.documents.get_mut(&document_id).unwrap();
|
||||
@@ -5069,15 +5077,11 @@ mod document_message_handler_tests {
|
||||
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
|
||||
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
|
||||
|
||||
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
|
||||
let news: Vec<graphene_std::list::Item<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<graphene_std::Graphic>>(&editor.runtime)
|
||||
.collect();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
|
||||
let phantom_count = news
|
||||
.iter()
|
||||
.flat_map(|new| new.iter_element_values())
|
||||
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
|
||||
.count();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element");
|
||||
let phantom_count = news.iter().filter(|new| matches!(new.element(), graphene_std::Graphic::None(_))).count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
|
||||
|
||||
@@ -137,7 +137,9 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.network_interface.move_node_to_chain_start(&smooth_anchors_id, layer, &[], self.import);
|
||||
|
||||
// Add Path node to chain start (closest to the Merge node)
|
||||
let path = resolve_network_node_type("Path").expect("Path node does not exist").default_node_template();
|
||||
let path = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
|
||||
.expect("Path node does not exist")
|
||||
.default_node_template();
|
||||
let path_id = NodeId::new();
|
||||
self.network_interface.insert_node(path_id, path, &[]);
|
||||
self.network_interface.move_node_to_chain_start(&path_id, layer, &[], self.import);
|
||||
@@ -150,7 +152,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
let (vector, paths) = Vector::from_bezpath(&bezpath);
|
||||
let modification = Box::new(VectorModification::create_from_vector(&vector, &paths));
|
||||
|
||||
let shape = resolve_network_node_type("Path")
|
||||
let shape = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
|
||||
.expect("Path node does not exist")
|
||||
.node_template_input_override([None, Some(NodeInput::value(TaggedValue::VectorModification(modification), false))]);
|
||||
let shape_id = NodeId::new();
|
||||
@@ -410,7 +412,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
|
||||
// If inserting a 'Path' node, insert a 'Combine Paths' node if the type is `Graphic`.
|
||||
// TODO: Allow the 'Path' node to operate on `List` data by utilizing the reference (index or ID?) for each item.
|
||||
if node_definition.identifier == "Path" {
|
||||
if *reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
|
||||
let layer_input_type = self.network_interface.input_type(&InputConnector::layer_secondary_input(output_layer.to_node()), &[]);
|
||||
if layer_input_type.compiled_element_name().as_deref() == Some("Graphic") {
|
||||
let Some(combine_paths_definition) = resolve_proto_node_type(graphene_std::vector_nodes::combine_paths::IDENTIFIER) else {
|
||||
@@ -759,20 +761,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
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.
|
||||
@@ -994,7 +1002,7 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
}
|
||||
|
||||
pub fn vector_modify(&mut self, modification_type: VectorModificationType) {
|
||||
let Some(path_node_id) = self.existing_network_node_id("Path", true) else {
|
||||
let Some(path_node_id) = self.existing_proto_node_id(graphene_std::vector::path::IDENTIFIER, true) else {
|
||||
return;
|
||||
};
|
||||
self.network_interface.vector_modify(&path_node_id, modification_type);
|
||||
|
||||
@@ -175,44 +175,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -2)),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(3), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
@@ -244,7 +225,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(3), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
@@ -256,32 +237,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
@@ -769,56 +731,6 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Path",
|
||||
version: 1,
|
||||
category: "Vector: Geometry",
|
||||
icon: Some("NodePath"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
|
||||
call_argument: generic!(T),
|
||||
skip_deduplication: true,
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::import(concrete!(graphene_std::vector::VectorModification), 1),
|
||||
NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath),
|
||||
],
|
||||
call_argument: generic!(T),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(vector::path_modify::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(id, node)| (NodeId(id as u64), node))
|
||||
.collect(),
|
||||
..Default::default()
|
||||
}),
|
||||
inputs: vec![
|
||||
NodeInput::type_default(item!(Vector), true),
|
||||
NodeInput::value(TaggedValue::VectorModification(Default::default()), false),
|
||||
],
|
||||
input_metadata: vec![
|
||||
("Content", "The original shape that edits made with the Pen and Path tools are applied to.").into(),
|
||||
("Modification", "The edits made with the Pen and Path tools, stored as changes to points and segments.").into(),
|
||||
],
|
||||
output_names: vec!["Modified".to_string()],
|
||||
output_descriptions: vec!["The shape with the Pen and Path tool edits applied.".to_string()],
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("Holds the edits made with the Pen and Path tools, applying them to the incoming shape."),
|
||||
inspector: None,
|
||||
},
|
||||
];
|
||||
|
||||
document_node_derive::post_process_nodes(custom)
|
||||
@@ -848,14 +760,11 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("exposure_inspector".to_string(), Box::new(node_inspector::exposure_inspector));
|
||||
map.insert("format_number_inspector".to_string(), Box::new(node_inspector::format_number_inspector));
|
||||
map.insert("string_capitalization_inspector".to_string(), Box::new(node_inspector::string_capitalization_inspector));
|
||||
map.insert("gradient_curvature_inspector".to_string(), Box::new(node_inspector::gradient_curvature_inspector));
|
||||
map.insert("rectangle_inspector".to_string(), Box::new(node_inspector::rectangle_inspector));
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||
map.insert(
|
||||
"monitor_inspector".to_string(),
|
||||
Box::new(|_node_id, _context| node_inspector::string_inspector("Used internally by the editor to read the data passing through it.")),
|
||||
);
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ pub(super) fn post_process_nodes(custom: Vec<DocumentNodeDefinition>) -> HashMap
|
||||
|
||||
// Add the rest of the protonodes from the macro.
|
||||
// Typed nodes are registered in `core_types::NODE_REGISTRY` via the macro's auto-generated `register_node` codegen.
|
||||
// `skip_impl` nodes (e.g. Cache, Monitor) bypass that registration but are wired up manually in
|
||||
// `skip_impl` nodes (e.g. Cache) bypass that registration but are wired up manually in
|
||||
// `interpreted_executor::node_registry::NODE_REGISTRY` via `async_node!`. We consult that extended registry as a
|
||||
// fallback when deriving `call_argument` so it reflects the impls actually registered, which will usually be `Context`.
|
||||
let extended_node_registry = &*interpreted_executor::node_registry::NODE_REGISTRY;
|
||||
|
||||
@@ -183,7 +183,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
NodeGraphMessage::AddPathNode => {
|
||||
if let Some(layer) = make_path_editable_is_allowed(network_interface) {
|
||||
responses.add(NodeGraphMessage::CreateNodeInLayerWithTransaction {
|
||||
node_type: DefinitionIdentifier::Network("Path".into()),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER),
|
||||
layer,
|
||||
});
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -1001,7 +1005,12 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
}
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo {
|
||||
blank_assist: false,
|
||||
..parameter_widgets_info
|
||||
};
|
||||
let ParameterWidgetsInfo {
|
||||
document_id,
|
||||
document_node,
|
||||
node_id,
|
||||
index,
|
||||
@@ -1025,8 +1034,27 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
Some(TaggedValue::TypeDefault(_)) => Font::default(),
|
||||
_ => return (first_widgets, second_widgets),
|
||||
};
|
||||
|
||||
let filters = vec![TypeFilter::font()];
|
||||
let file_drop_action = IngestAction::resource_input(document_id, node_id, index, &filters);
|
||||
let load_button = IconButton::new("FileImport", 24)
|
||||
.tooltip_label("Load Font File")
|
||||
.tooltip_description("Use a font that isn't in the list by loading its .ttf or .otf file. The font is saved with the document.")
|
||||
.on_update(move |_| {
|
||||
IngestMessage::SetResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index: index,
|
||||
filters: filters.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance();
|
||||
|
||||
{
|
||||
first_widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
load_button,
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(vec![
|
||||
fonts
|
||||
@@ -1050,7 +1078,15 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
.collect::<Vec<_>>(),
|
||||
])
|
||||
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
|
||||
.placeholder(font.font_family.clone())
|
||||
.virtual_scrolling(true)
|
||||
.on_file_drop(move |file| {
|
||||
IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file(PathBuf::from(&file.name), Some(file.mime_type.as_str()).filter(|mime| !mime.is_empty()), file.data.clone()).into(),
|
||||
action: file_drop_action.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
@@ -1094,6 +1130,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
})
|
||||
.map(|i| i as u32),
|
||||
)
|
||||
.placeholder(font.font_style.clone())
|
||||
.widget_instance(),
|
||||
]);
|
||||
second_widgets = Some(second_row);
|
||||
@@ -3013,6 +3050,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// 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) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
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're exactly those
|
||||
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, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.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 curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
@@ -3143,8 +3253,8 @@ pub(crate) fn generate_node_inspector(node_id: NodeId, context: &mut NodeInspect
|
||||
} else {
|
||||
let number_of_inputs = context.network_interface.number_of_inputs(&node_id, context.selection_network_path);
|
||||
for input_index in 1..number_of_inputs {
|
||||
// Hide inputs that are connected to a scope
|
||||
if let Some(NodeInput::Scope(_)) = context
|
||||
// Hide inputs that are connected to a scope or filled in by the compiler
|
||||
if let Some(NodeInput::Scope(_) | NodeInput::Reflection(_)) = context
|
||||
.network_interface
|
||||
.input_from_connector(&InputConnector::node_at_index(node_id, input_index), context.selection_network_path)
|
||||
{
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder,
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::sync::Arc;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ResourceMessage {
|
||||
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
|
||||
StoreFont { resource_id: ResourceId, font: Font, data: Arc<[u8]> },
|
||||
AddFont { resource_id: ResourceId, font: Font },
|
||||
ResolveAll,
|
||||
Resolve { resource_id: ResourceId },
|
||||
|
||||
@@ -35,6 +35,20 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
}
|
||||
ResourceMessage::StoreFont { resource_id, font, data } => {
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
self.registry.push_source_back(&resource_id, DataSource::Embedded);
|
||||
self.registry.push_source_back(
|
||||
&resource_id,
|
||||
DataSource::Font {
|
||||
family: font.font_family.clone(),
|
||||
style: Some(font.font_style.clone()),
|
||||
},
|
||||
);
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
responses.add(FontsMessage::ResourceResolved { font, hash });
|
||||
}
|
||||
ResourceMessage::AddFont { resource_id, font } => {
|
||||
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
|
||||
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
|
||||
|
||||
@@ -872,7 +872,7 @@ async fn demo_artwork_vector_modifications_still_apply() {
|
||||
|
||||
let document = editor.active_document();
|
||||
let network = &document.network_interface;
|
||||
let path_definition = DefinitionIdentifier::Network("Path".into());
|
||||
let path_definition = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
|
||||
let mut path_layers = 0;
|
||||
let mut any_curve = false;
|
||||
|
||||
|
||||
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
|
||||
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
|
||||
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -131,7 +133,7 @@ impl DocumentMetadata {
|
||||
|
||||
let mut use_local = true;
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, network_interface);
|
||||
let identifier = DefinitionIdentifier::Network("Path".into());
|
||||
let identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
|
||||
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&identifier)
|
||||
&& let Some(&source) = self.first_element_source_ids.get(&layer.to_node())
|
||||
&& !network_interface
|
||||
@@ -347,9 +349,9 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style. Only the first item of a layer's vector data
|
||||
/// is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
let stroke = self
|
||||
.layer_appearance_attributes
|
||||
@@ -359,8 +361,10 @@ impl DocumentMetadata {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
}
|
||||
|
||||
/// Get the bounding box of the click target of the specified layer in viewport space
|
||||
@@ -732,7 +736,7 @@ mod tests {
|
||||
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
|
||||
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
|
||||
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
|
||||
+13
-13
@@ -1216,9 +1216,9 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
|
||||
let path = vec![merge];
|
||||
editor.enter_editable_network(merge).await;
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Origins to Polyline".into()), 0, 0).await;
|
||||
let path = vec![subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
let import_count = editor.active_document().network_interface.number_of_imports(&path);
|
||||
|
||||
// With a primary, the only one is past the last import
|
||||
@@ -1226,20 +1226,20 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let empty_connectors = network_interface.empty_import_export_connectors(true, &path);
|
||||
assert_eq!(empty_connectors.iter().map(|(index, _)| *index).collect::<Vec<_>>(), vec![import_count]);
|
||||
|
||||
// The attribute name given to Merge's interior Write Attribute node
|
||||
let write_attribute = network_interface
|
||||
// The closed setting given to the subgraph's interior Points to Polyline node
|
||||
let points_to_polyline = network_interface
|
||||
.nested_network(&path)
|
||||
.and_then(|network| {
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::graphic::write_attribute::IDENTIFIER))
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::vector::points_to_polyline::IDENTIFIER))
|
||||
})
|
||||
.map(|(node_id, _)| *node_id)
|
||||
.expect("Merge should contain a Write Attribute node");
|
||||
let value_input = InputConnector::node_at_index(write_attribute, 1);
|
||||
.expect("Origins to Polyline should contain a Points to Polyline node");
|
||||
let value_input = InputConnector::node_at_index(points_to_polyline, 1);
|
||||
let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&value_input, &path) else {
|
||||
panic!("Merge's Write Attribute node should be given its attribute name as a value");
|
||||
panic!("The Points to Polyline node should be given its closed setting as a value");
|
||||
};
|
||||
let displaced_value = (**tagged_value).clone();
|
||||
|
||||
@@ -1257,7 +1257,7 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
"the new import should be wired to the input"
|
||||
);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(merge, import_count), &[]);
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(subgraph, import_count), &[]);
|
||||
assert!(
|
||||
matches!(new_input, Some(NodeInput::Value { tagged_value, exposed: true }) if **tagged_value == displaced_value),
|
||||
"the new import should take over the value its wire displaced, found {new_input:?}"
|
||||
@@ -1273,11 +1273,11 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.empty_import_export_connectors(true, &path).iter().any(|(index, _)| *index == 0));
|
||||
|
||||
// The content given to Merge's interior Write Attribute node by its Into Group node
|
||||
let wired_input = InputConnector::node_at_index(write_attribute, 0);
|
||||
// The points given to the subgraph's interior Points to Polyline node by its Combine Paths node
|
||||
let wired_input = InputConnector::node_at_index(points_to_polyline, 0);
|
||||
assert!(
|
||||
matches!(network_interface.input_from_connector(&wired_input, &path), Some(NodeInput::Node { .. })),
|
||||
"Merge's Write Attribute node should be wired its content from another node"
|
||||
"The Points to Polyline node should have its points wired from another node"
|
||||
);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::AddImportAndConnect {
|
||||
|
||||
+14
-16
@@ -864,14 +864,15 @@ async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[group]);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let (inner, index) = interface
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
|
||||
.expect("a node with a value input inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("an Extend node inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), NodeInput::value(TaggedValue::None, false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -1064,13 +1065,14 @@ fn table_layer(editor: &EditorTestUtils) -> (NodeId, graph_craft::document::Netw
|
||||
.expect("a committed layer should name a table entry")
|
||||
}
|
||||
|
||||
/// A node inside the table entry `definition`, and the index of one of its value inputs.
|
||||
fn value_input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
/// The Extend node inside the layer's table entry `definition`, and the index of its base input.
|
||||
fn input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
editor.active_document().network_interface.document_network().definitions[&definition]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the layer's network should have a node with a value input")
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some((*id, 0)))
|
||||
.expect("the layer's network should have an Extend node")
|
||||
}
|
||||
|
||||
/// The network location `deltas` recorded for a write to an input of `node_id`.
|
||||
@@ -1119,7 +1121,7 @@ async fn an_edit_inside_a_table_entry_constructs_the_diff() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
@@ -1174,7 +1176,7 @@ async fn a_write_keeps_its_network_when_the_instance_changes_implementation() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.discard_deltas();
|
||||
|
||||
@@ -1387,14 +1389,10 @@ async fn making_an_instance_unique_forks_its_network() {
|
||||
assert_ne!(forked, definition);
|
||||
assert!(!interface.is_shared(©, &[]) && !interface.is_shared(&layer, &[]));
|
||||
|
||||
let (inner, input_index) = value_input_inside(&editor, forked);
|
||||
let (inner, input_index) = input_inside(&editor, forked);
|
||||
let original = editor.active_document().network_interface.document_network().definitions[&definition].clone();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let NodeInput::Value { tagged_value, exposed } = &interface.document_network().definitions[&forked].nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[copy]);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), NodeInput::value(TaggedValue::None, false), &[copy]);
|
||||
|
||||
assert_ne!(interface.document_network().definitions[&forked], original, "the edit should change the copy's network");
|
||||
assert_eq!(interface.document_network().definitions[&definition], original, "the original's network should be untouched");
|
||||
|
||||
@@ -62,6 +62,19 @@ impl NodeNetworkInterface {
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// The path of every node in the document's networks made from the definition.
|
||||
pub fn node_paths_with_reference(&self, reference: &DefinitionIdentifier) -> Vec<Vec<NodeId>> {
|
||||
let mut node_paths = Vec::new();
|
||||
self.for_each_network(&mut |network_path, network_metadata| {
|
||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||
if self.reference(node_id, network_path).as_ref() == Some(reference) {
|
||||
node_paths.push([network_path, &[*node_id]].concat());
|
||||
}
|
||||
}
|
||||
});
|
||||
node_paths
|
||||
}
|
||||
|
||||
fn for_each_layer(&self, visit: &mut impl FnMut(&[NodeId], NodeId)) {
|
||||
self.for_each_network(&mut |network_path, network_metadata| {
|
||||
for (node_id, node_metadata) in &network_metadata.persistent_metadata.node_metadata {
|
||||
@@ -1050,11 +1063,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1071,17 +1084,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
@@ -1209,7 +1222,6 @@ impl NodeNetworkInterface {
|
||||
node.inputs = old_node.inputs;
|
||||
node.call_argument = old_node.manual_composition.unwrap_or_default();
|
||||
node.visible = old_node.visible;
|
||||
node.skip_deduplication = old_node.skip_deduplication;
|
||||
node.original_location = old_node.original_location;
|
||||
node_metadata.persistent_metadata.display_name = old_node.alias;
|
||||
node_metadata.persistent_metadata.locked = old_node.locked;
|
||||
|
||||
@@ -221,7 +221,7 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
|
||||
let deltas = if current.implementation == target.implementation && current.skip_deduplication == target.skip_deduplication {
|
||||
let deltas = if current.implementation == target.implementation {
|
||||
field_deltas(location, local_id, (current, current_metadata), (&target, &target_metadata))
|
||||
} else {
|
||||
vec![
|
||||
|
||||
+37
-14
@@ -61,7 +61,7 @@ static INPUT_CONVERSIONS: Lazy<HashMap<ProtoNodeIdentifier, Vec<Option<&'static
|
||||
.collect()
|
||||
});
|
||||
|
||||
/// Proto nodes whose every implementation returns its one input's type unchanged (like Monitor and Memoize), so a wire through one is constrained by what it feeds.
|
||||
/// Proto nodes whose every implementation returns its one input's type unchanged (like Memoize), so a wire through one is constrained by what it feeds.
|
||||
static TYPE_PRESERVING_NODES: Lazy<HashSet<ProtoNodeIdentifier>> = Lazy::new(|| {
|
||||
NODE_REGISTRY
|
||||
.iter()
|
||||
@@ -420,7 +420,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// A check of which wire types an input accepts, built once so testing many types searches the node's matching implementations only once.
|
||||
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Monitor) also needs the inputs it feeds to accept the type.
|
||||
/// Unlike [`Self::input_accepts_type`], a node passing its input's type through unchanged (like Memoize) also needs the inputs it feeds to accept the type.
|
||||
fn type_acceptor(&self, input_connector: &InputConnector, network_path: &[NodeId]) -> Box<dyn Fn(&Type) -> bool> {
|
||||
let accepts_here: Box<dyn Fn(&Type) -> bool> = match input_connector {
|
||||
InputConnector::Export(export_index) => match network_path.split_last() {
|
||||
@@ -768,25 +768,48 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn subgraph_inputs_look_through_type_preserving_nodes() {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let path_node_id = editor.create_node_by_name(DefinitionIdentifier::Network("Path".into())).await;
|
||||
let merge = editor.create_node_by_name_at(DefinitionIdentifier::Network("Merge".into()), 0, 0).await;
|
||||
|
||||
// The Path subgraph's content goes through a Monitor node, which accepts most types, before the node that needs a vector
|
||||
let content_types = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.potential_valid_input_types(&InputConnector::node_at_index(path_node_id, 0), &[])
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>();
|
||||
assert!(content_types.iter().any(|ty| ty == "Vector"), "Path's content should accept a vector, found {content_types:?}");
|
||||
// A new import feeding a Memoize, which accepts most types, before a Path that needs a vector
|
||||
editor.enter_editable_network(merge).await;
|
||||
let memoize = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::memo::memoize::IDENTIFIER), -20, 10).await;
|
||||
let path = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), -10, 10).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(memoize, 0),
|
||||
input_connector: InputConnector::node_at_index(path, 0),
|
||||
})
|
||||
.await;
|
||||
let import_index = editor.active_document().network_interface.number_of_imports(&[merge]);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::AddImportAndConnect {
|
||||
import_index,
|
||||
input_connector: InputConnector::node_at_index(memoize, 0),
|
||||
})
|
||||
.await;
|
||||
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let type_names = |input_connector: &InputConnector, network_path: &[super::NodeId]| {
|
||||
network_interface
|
||||
.potential_valid_input_types(input_connector, network_path)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
let memoize_types = type_names(&InputConnector::node_at_index(memoize, 0), &[merge]);
|
||||
assert!(memoize_types.iter().any(|ty| ty == "Color"), "Memoize itself should accept a color, found {memoize_types:?}");
|
||||
|
||||
let content_types = type_names(&InputConnector::node_at_index(merge, import_index), &[]);
|
||||
assert!(content_types.iter().any(|ty| ty == "Vector"), "the input should accept a vector, found {content_types:?}");
|
||||
assert!(
|
||||
!content_types.iter().any(|ty| ty == "Color"),
|
||||
"Path's content should not accept a color just because its Monitor does, found {content_types:?}"
|
||||
"the input should not accept a color just because its Memoize does, found {content_types:?}"
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ impl NodeNetworkInterface {
|
||||
pub fn compute_modified_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
|
||||
|
||||
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))
|
||||
if let Some(path_node) = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
|
||||
&& let Some(geometry) = self.document_metadata.vector_modify.get(&path_node)
|
||||
{
|
||||
let mut modified = geometry.clone();
|
||||
@@ -28,7 +28,7 @@ impl NodeNetworkInterface {
|
||||
/// (e.g. the pre-solidified centerline for a Solidify Stroke layer) and otherwise do nothing.
|
||||
pub fn upstream_path_node_vector(&self, layer: LayerNodeIdentifier) -> Option<VectorGeometry> {
|
||||
let graph_layer = graph_modification_utils::NodeGraphLayer::new(layer, self);
|
||||
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
|
||||
graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
|
||||
self.compute_modified_vector(layer)
|
||||
}
|
||||
|
||||
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
|
||||
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
}
|
||||
}
|
||||
@@ -21,8 +21,6 @@ pub struct NodeTemplate {
|
||||
pub implementation: NodeTemplateImplementation,
|
||||
/// Represents the eye icon for hiding/showing the node in the graph UI.
|
||||
pub visible: bool,
|
||||
/// Prevents identical proto nodes from being deduplicated during compilation, e.g. for monitor nodes.
|
||||
pub skip_deduplication: bool,
|
||||
/// A name chosen by the user for this instance of the node. Empty indicates no given name, in which case the implementation name is displayed in italics.
|
||||
pub display_name: String,
|
||||
/// Metadata to override the Inspector widgets for each input. Kept the same length as `inputs`.
|
||||
@@ -57,7 +55,6 @@ impl Default for NodeTemplate {
|
||||
call_argument: concrete!(Context),
|
||||
implementation: NodeTemplateImplementation::default(),
|
||||
visible: true,
|
||||
skip_deduplication: false,
|
||||
display_name: String::new(),
|
||||
input_metadata: Vec::new(),
|
||||
output_names: Vec::new(),
|
||||
@@ -110,7 +107,6 @@ impl NodeTemplate {
|
||||
call_argument,
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
compile_metadata: _,
|
||||
original_location: _,
|
||||
} = document_node;
|
||||
@@ -161,7 +157,6 @@ impl NodeTemplate {
|
||||
call_argument,
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
display_name,
|
||||
input_metadata,
|
||||
output_names,
|
||||
@@ -179,7 +174,6 @@ impl NodeTemplate {
|
||||
call_argument,
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
display_name,
|
||||
mut input_metadata,
|
||||
mut output_names,
|
||||
@@ -211,7 +205,6 @@ impl NodeTemplate {
|
||||
call_argument,
|
||||
implementation,
|
||||
visible,
|
||||
skip_deduplication,
|
||||
compile_metadata: None,
|
||||
original_location: Default::default(),
|
||||
};
|
||||
|
||||
@@ -20,7 +20,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
|
||||
use graphene_std::transform::ScaleType;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use graphene_std::vector::graphic_types;
|
||||
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::f64::consts::PI;
|
||||
use std::ops::Range;
|
||||
@@ -117,10 +117,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"raster_nodes::std_nodes::SampleImageNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::memo::monitor::IDENTIFIER,
|
||||
aliases: &["graphene_core::memo::MonitorNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::memo::memoize::IDENTIFIER,
|
||||
aliases: &["graphene_core::memo::MemoNode", "graphene_core::memo::ImpureMemoNode"],
|
||||
@@ -299,10 +295,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -516,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
|
||||
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
node: graphene_std::blending_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -537,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -546,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::adjustments::ColorOverlayNode",
|
||||
"raster_nodes::generate_curves::ColorOverlayNode",
|
||||
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
"raster_nodes::blending_nodes::ColorOverlayNode",
|
||||
],
|
||||
},
|
||||
NodeReplacement {
|
||||
@@ -944,8 +938,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
aliases: &["graphene_core::vector::PathLengthNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::vector::path_modify::IDENTIFIER,
|
||||
node: graphene_std::vector::path::IDENTIFIER,
|
||||
aliases: &[
|
||||
"vector_nodes::vector_modification_nodes::PathModifyNode",
|
||||
"graphene_core::vector::vector_modification_nodes::PathModifyNode",
|
||||
"graphene_core::vector::vector_data::modification::PathModifyNode",
|
||||
"graphene_core::vector::vector_modification::PathModifyNode",
|
||||
@@ -1162,6 +1157,14 @@ pub fn document_migration_replace_resources_referenced_by_hash(document_serializ
|
||||
(out, hash_to_id)
|
||||
}
|
||||
|
||||
/// The removed Monitor node, which old documents still hold.
|
||||
const MONITOR_IDENTIFIER: ProtoNodeIdentifier = ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode");
|
||||
|
||||
/// Whether the implementation is the removed Monitor node, with or without the type arguments it was once stored with.
|
||||
fn is_monitor(implementation: &DocumentNodeImplementation) -> bool {
|
||||
matches!(implementation, DocumentNodeImplementation::ProtoNode(identifier) if identifier.as_str().split('<').next() == Some(MONITOR_IDENTIFIER.as_str()))
|
||||
}
|
||||
|
||||
/// Whether the node is a subgraph that feeds its first input through a Monitor into a Transform proto node and forwards the other four inputs unchanged, making it equivalent to a bare Transform node.
|
||||
fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph_craft::document::NodeNetwork) -> bool {
|
||||
let Some(network) = document_network.implementation_network(&node.implementation) else {
|
||||
@@ -1177,7 +1180,7 @@ fn is_monitored_transform_subgraph(node: &DocumentNode, document_network: &graph
|
||||
_ => false,
|
||||
})
|
||||
};
|
||||
let Some((monitor_id, monitor)) = find_proto_node(&graphene_std::memo::monitor::IDENTIFIER) else {
|
||||
let Some((monitor_id, monitor)) = find_proto_node(&MONITOR_IDENTIFIER) else {
|
||||
return false;
|
||||
};
|
||||
let Some((transform_id, transform)) = find_proto_node(&graphene_std::transform_nodes::transform::IDENTIFIER) else {
|
||||
@@ -1274,6 +1277,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1370,9 +1377,31 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves.
|
||||
// The "Path" wrapper network was replaced with the `path` proto node directly. Convert old `Network("Path")` instances to the proto node, forwarding the Content and Modification inputs.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: replacing the outer Path's network impl orphans its child paths.
|
||||
let path_wrappers: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, _, path)| (document.network_interface.reference(node_id, &path) == Some(DefinitionIdentifier::Network("Path".into()))).then_some((*node_id, path)))
|
||||
.collect();
|
||||
for (node_id, network_path) in &path_wrappers {
|
||||
let new_reference = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
|
||||
let Some(definition) = resolve_document_node_type(&new_reference) 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;
|
||||
};
|
||||
|
||||
for (index, input) in old_inputs.into_iter().take(2).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Merge and Artboard networks no longer hold a Monitor node or write the layer's path onto their content, since the editor finds thumbnails and writes the paths itself.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths.
|
||||
let monitored_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
let outdated_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
@@ -1381,17 +1410,37 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let is_merge_or_artboard = [DefinitionIdentifier::Network("Merge".into()), DefinitionIdentifier::Network("Artboard".into())].contains(&reference);
|
||||
|
||||
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
|
||||
let has_monitor = network.nodes.values().any(|inner_node| inner_node.implementation == monitor);
|
||||
let path_of_subgraph = DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER);
|
||||
let has_removed_node = network
|
||||
.nodes
|
||||
.values()
|
||||
.any(|inner_node| is_monitor(&inner_node.implementation) || inner_node.implementation == path_of_subgraph);
|
||||
|
||||
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
|
||||
(is_merge_or_artboard && has_removed_node).then_some((*node_id, path, reference))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, reference) in &monitored_layers {
|
||||
for (node_id, network_path, reference) in &outdated_layers {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
|
||||
}
|
||||
|
||||
// Any Monitor still left becomes a Passthrough of its content, once the passes above have used it to recognize old networks
|
||||
let monitors: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(_, node, _)| is_monitor(&node.implementation))
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
for (node_id, network_path) in &monitors {
|
||||
let mut passthrough = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut passthrough);
|
||||
document.network_interface.set_call_argument(node_id, network_path, passthrough.call_argument);
|
||||
}
|
||||
|
||||
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math Function"
|
||||
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math Formula", which reads the pair as `a` and `b`.
|
||||
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
|
||||
@@ -1637,6 +1686,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take 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)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1815,6 +1907,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && node.inputs.is_empty() {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) 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;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1874,6 +2012,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2405,7 +2613,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2726,20 +2933,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
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), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -3463,7 +3656,7 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
|
||||
// SVG-import legacy Path nodes baked their geometry at non-exposed input 0; move it to input 1 (the modern slot for VectorModification).
|
||||
// For exposed input 0, any baked value is unused at runtime, so just reset it.
|
||||
if reference == DefinitionIdentifier::Network("Path".into()) {
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER) {
|
||||
let input_0 = node.inputs.first()?;
|
||||
if let NodeInput::Value { tagged_value, exposed } = input_0
|
||||
&& let TaggedValue::VectorModification(modification) = &**tagged_value
|
||||
@@ -4918,7 +5111,7 @@ mod tests {
|
||||
let content = std::mem::replace(&mut extend.inputs[1], NodeInput::node(monitor_id, 0));
|
||||
let monitor_template = NodeTemplate {
|
||||
inputs: vec![content],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
|
||||
implementation: NodeTemplateImplementation::ProtoNode(MONITOR_IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
network_template.nodes.insert(monitor_id, monitor_template);
|
||||
@@ -4933,14 +5126,34 @@ mod tests {
|
||||
else {
|
||||
panic!("{name} should stay a network node")
|
||||
};
|
||||
let monitor = DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER);
|
||||
assert!(
|
||||
network.nodes.values().all(|inner_node| inner_node.implementation != monitor),
|
||||
"{name} should no longer have a Monitor node"
|
||||
);
|
||||
// A Monitor left in place would become a Passthrough, so only the rebuilt network has the definition's node count
|
||||
let NodeTemplateImplementation::Network(shipped) = resolve_network_node_type(name).expect("The definition should exist").default_node_template().implementation else {
|
||||
panic!("{name} should be a network node")
|
||||
};
|
||||
assert_eq!(network.nodes.len(), shipped.nodes.len(), "{name} should be rebuilt from its definition, without the Monitor node");
|
||||
}
|
||||
}
|
||||
|
||||
// The removed Monitor node keeps passing on its content wherever it's left
|
||||
#[test]
|
||||
fn a_monitor_node_becomes_a_passthrough() {
|
||||
let node_id = NodeId(1);
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let content = NodeInput::value(TaggedValue::Number(42.), false);
|
||||
let monitor_template = NodeTemplate {
|
||||
inputs: vec![content.clone()],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new("graphene_core::memo::MonitorNode<_, _, _>")),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(node_id, monitor_template, &[]);
|
||||
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&node_id];
|
||||
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
|
||||
assert_eq!(node.inputs, [content]);
|
||||
}
|
||||
|
||||
// Regex Find's Match Index is now an integer, so an old instance rounds its stored F64 index and rebuilds the subgraph
|
||||
// that fed the decimal index to its two item-at-index nodes
|
||||
#[test]
|
||||
@@ -5038,6 +5251,54 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
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), false), &[]);
|
||||
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)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -5987,4 +6248,79 @@ mod tests {
|
||||
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction};
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let data = std::fs::read("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.dispatch(IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file("marbled-mandelbrot.graphite".into(), None, data).into(),
|
||||
action: IngestAction::Open,
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster_nodes::color_lookup_table::{Lut, LutParseError};
|
||||
use graphene_std::text::Font;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct IngestMessageContext {
|
||||
@@ -66,7 +67,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
let preferred = items.into_iter().min_by_key(|item| match item.data {
|
||||
TransferData::Svg(_) => 0,
|
||||
TransferData::Raster { .. } => 1,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Text(_) => 3,
|
||||
TransferData::ApplicationData(_) => 4,
|
||||
});
|
||||
@@ -103,11 +104,17 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
return;
|
||||
}
|
||||
|
||||
// The file goes to the document that asked for it, which may no longer be active or open once the dialog closes
|
||||
let resource_id = ResourceId::new();
|
||||
|
||||
let font = if data_type == DataType::Font { Font::from_data(&data) } else { None };
|
||||
let resource_store_message = match font {
|
||||
Some(font) => ResourceMessage::StoreFont { resource_id, font, data: data.into() },
|
||||
None => ResourceMessage::StoreEmbedded { resource_id, data: data.into() },
|
||||
};
|
||||
|
||||
let messages = [
|
||||
DocumentMessage::AddTransaction,
|
||||
DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, data: data.into() }),
|
||||
resource_store_message.into(),
|
||||
DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: input_index as usize,
|
||||
@@ -172,7 +179,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
};
|
||||
(insert, None)
|
||||
}
|
||||
TransferData::Lut(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
};
|
||||
|
||||
if !place_at_origin {
|
||||
@@ -209,7 +216,7 @@ fn unsupported(responses: &mut VecDeque<Message>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image or LUT only if it fully parses.
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image, LUT, or font only if it parses.
|
||||
fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> Option<&'static str> {
|
||||
const WRONG_TYPE: &str = "This input does not accept the format of the chosen file.";
|
||||
|
||||
@@ -233,6 +240,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
|
||||
}
|
||||
LutParseError::Unreadable => "This file could not be read as a LUT. It may be corrupted or an unsupported format variant.",
|
||||
}),
|
||||
DataType::Font => Font::from_data(data).is_none().then_some("This file could not be read as a font."),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -442,6 +450,27 @@ mod tests {
|
||||
assert!(!stores(IDENTITY_CUBE, TypeFilter::raster()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_stores_a_font_file_under_the_name_it_carries() {
|
||||
let font_file: &[u8] = crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE.as_ref();
|
||||
let stored_font = |data: &[u8]| {
|
||||
let responses = ingest_named(data, Some("custom.ttf"), resource_input(TypeFilter::font().types), true);
|
||||
responses.into_iter().find_map(|message| match message {
|
||||
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
message: DocumentMessage::Resource(ResourceMessage::StoreFont { font, .. }),
|
||||
}) => Some(font),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
|
||||
assert_eq!(stored_font(font_file), Some(Font::new("Source Sans Pro".to_string(), "Regular (400)".to_string())));
|
||||
|
||||
// A file cut off after its intact signature, and an image named as a font
|
||||
assert_eq!(stored_font(&font_file[..40]), None);
|
||||
assert_eq!(stored_font(&Image::new(8, 8, Color::WHITE).to_png()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_table_outside_a_node_input_only_shows_a_dialog() {
|
||||
let responses = ingest_named(IDENTITY_CUBE, Some("grade.cube"), IngestAction::Import, true);
|
||||
|
||||
@@ -23,6 +23,9 @@ const TEXT_MIME: &str = "text/plain";
|
||||
const GRAPHITE_PREFIX: &str = "graphite: ";
|
||||
const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
|
||||
const FONT_FILE_EXTENSIONS: &[&str] = &["ttf", "otf"];
|
||||
const FONT_FILE_SIGNATURES: [&[u8]; 3] = [&[0, 1, 0, 0], b"OTTO", b"true"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
pub enum IngestAction {
|
||||
@@ -65,6 +68,7 @@ pub enum DataType {
|
||||
Gdd,
|
||||
Svg,
|
||||
Raster(ImageFormat),
|
||||
Font,
|
||||
Lut,
|
||||
Text,
|
||||
#[default]
|
||||
@@ -98,6 +102,7 @@ impl DataType {
|
||||
GDD_FILE_EXTENSION => Self::Gdd,
|
||||
"svg" => Self::Svg,
|
||||
extension if LUT_FILE_EXTENSIONS.contains(&extension) => Self::Lut,
|
||||
extension if FONT_FILE_EXTENSIONS.contains(&extension) => Self::Font,
|
||||
extension => ImageFormat::from_extension(extension).map_or(Self::Unknown, Self::Raster),
|
||||
}
|
||||
}
|
||||
@@ -113,6 +118,9 @@ impl DataType {
|
||||
if let Ok(format) = image::guess_format(data) {
|
||||
return Self::Raster(format);
|
||||
}
|
||||
if FONT_FILE_SIGNATURES.iter().any(|signature| data.starts_with(signature)) {
|
||||
return Self::Font;
|
||||
}
|
||||
|
||||
// Only the head is read as text, where a character split by the cut is the one invalid sequence tolerated
|
||||
let head = &data[..data.len().min(SNIFFED_TEXT_LENGTH)];
|
||||
@@ -139,8 +147,7 @@ impl DataType {
|
||||
Self::Svg => SVG_MIME,
|
||||
Self::Raster(format) => format.to_mime_type(),
|
||||
Self::Text => TEXT_MIME,
|
||||
// The LUT formats share no MIME type
|
||||
Self::Lut | Self::Unknown => return None,
|
||||
Self::Lut | Self::Font | Self::Unknown => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,6 +158,7 @@ impl DataType {
|
||||
Self::Svg => &["svg"],
|
||||
Self::Raster(format) => format.extensions_str(),
|
||||
Self::Lut => LUT_FILE_EXTENSIONS,
|
||||
Self::Font => FONT_FILE_EXTENSIONS,
|
||||
Self::Text | Self::Unknown => &[],
|
||||
}
|
||||
}
|
||||
@@ -189,6 +197,13 @@ impl TypeFilter {
|
||||
types: vec![DataType::Lut],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn font() -> Self {
|
||||
Self {
|
||||
name: "Font".into(),
|
||||
types: vec![DataType::Font],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TypeFilter> for FileFilter {
|
||||
@@ -221,6 +236,7 @@ pub enum TransferData {
|
||||
Document(Vec<u8>),
|
||||
LegacyDocument(String),
|
||||
Lut(Vec<u8>),
|
||||
Font(Vec<u8>),
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
@@ -232,6 +248,7 @@ impl TransferData {
|
||||
Self::Document(_) => DataType::Gdd,
|
||||
Self::LegacyDocument(_) => DataType::GraphiteLegacy,
|
||||
Self::Lut(_) => DataType::Lut,
|
||||
Self::Font(_) => DataType::Font,
|
||||
Self::Text(_) | Self::ApplicationData(_) => DataType::Text,
|
||||
Self::Other(_) => DataType::Unknown,
|
||||
}
|
||||
@@ -240,7 +257,7 @@ impl TransferData {
|
||||
pub fn into_bytes(self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Text(text) | Self::Svg(text) | Self::LegacyDocument(text) => text.into_bytes(),
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Other(data) => data,
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Font(data) | Self::Other(data) => data,
|
||||
Self::ApplicationData(_) => DataTransferItem::from(self).into_raw().map(|(_, data)| data.into_bytes()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -295,6 +312,7 @@ impl DataTransferItem {
|
||||
DataType::Svg => text(data, TransferData::Svg),
|
||||
DataType::Raster(format) => TransferData::Raster { format, data },
|
||||
DataType::Lut => TransferData::Lut(data),
|
||||
DataType::Font => TransferData::Font(data),
|
||||
DataType::Text | DataType::Unknown => TransferData::Other(data),
|
||||
};
|
||||
Self { data, path: Some(path) }
|
||||
@@ -312,7 +330,7 @@ impl DataTransferItem {
|
||||
},
|
||||
TransferData::Svg(svg) => Some((DataType::Svg, RawData::Text(svg))),
|
||||
TransferData::Raster { format, data } => Some((DataType::Raster(format), RawData::Bytes(data))),
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => None,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,6 +422,7 @@ mod tests {
|
||||
DataType::from_content("\u{feff}<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_bytes()),
|
||||
DataType::Svg
|
||||
);
|
||||
assert_eq!(DataType::from_content(b"OTTO\0\x0c"), DataType::Font);
|
||||
assert_eq!(DataType::from_content(b"just text"), DataType::Unknown);
|
||||
assert_eq!(DataType::from_content(&[0xff, 0xfe, 0x00]), DataType::Unknown);
|
||||
}
|
||||
@@ -426,6 +445,7 @@ mod tests {
|
||||
assert_eq!(detect(Some("application/graphite+json"), ""), DataType::GraphiteLegacy);
|
||||
assert_eq!(detect(Some("image/png"), "document.gdd"), DataType::Raster(ImageFormat::Png));
|
||||
assert_eq!(detect(None, "grade.CUBE"), DataType::Lut);
|
||||
assert_eq!(detect(None, "Custom.TTF"), DataType::Font);
|
||||
assert_eq!(detect(Some("application/vnd.iccprofile"), "profile.icm"), DataType::Lut);
|
||||
assert_eq!(detect(Some("text/csv"), "table.csv"), DataType::Unknown);
|
||||
assert_eq!(DataType::detect(&[], None, None), DataType::Unknown);
|
||||
|
||||
@@ -78,7 +78,7 @@ impl EditTarget {
|
||||
|
||||
/// The Path node, which vector edits insert beside a layer with vector content when it's missing.
|
||||
pub fn path() -> Self {
|
||||
Self::network_node("Path", Insertion::BesideVectorLayer)
|
||||
Self::proto_node(graphene_std::vector::path::IDENTIFIER, Insertion::BesideVectorLayer)
|
||||
}
|
||||
|
||||
/// The Fill node, which paint edits insert under any Stroke node beside a layer with vector content when it's missing.
|
||||
|
||||
@@ -23,7 +23,11 @@ pub fn find_spline(document: &DocumentMessageHandler, layer: LayerNodeIdentifier
|
||||
.network_interface
|
||||
.upstream_flow_back_from_nodes([layer.to_node()].to_vec(), &[], FlowType::HorizontalFlow)
|
||||
.map(|node_id| (document.network_interface.reference(&node_id, &[]), node_id))
|
||||
.take_while(|(reference, _)| reference.as_ref().is_some_and(|node_ref| node_ref != &DefinitionIdentifier::Network("Path".into())))
|
||||
.take_while(|(reference, _)| {
|
||||
reference
|
||||
.as_ref()
|
||||
.is_some_and(|node_ref| node_ref != &DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))
|
||||
})
|
||||
.find(|(reference, _)| {
|
||||
reference
|
||||
.as_ref()
|
||||
@@ -115,7 +119,7 @@ pub fn merge_layers(document: &DocumentMessageHandler, first_layer: LayerNodeIde
|
||||
|
||||
// Add a path node after the combine paths node
|
||||
let path_node_id = NodeId::new();
|
||||
let path_node = document_node_definitions::resolve_network_node_type("Path")
|
||||
let path_node = document_node_definitions::resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER)
|
||||
.expect("Failed to create path node")
|
||||
.default_node_template();
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
@@ -342,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
|
||||
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
|
||||
|
||||
@@ -76,8 +76,8 @@ mod test_ellipse {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
let ellipse_node = node_graph_layer.upstream_node_id_from_protonode(ellipse::IDENTIFIER)?;
|
||||
Some(ResolvedEllipse {
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&vec![ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_x: instrumented.grab_ranked_input::<ellipse::RadiusXInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
|
||||
radius_y: instrumented.grab_ranked_input::<ellipse::RadiusYInput, f64>(&[ellipse_node], &editor.runtime).unwrap(),
|
||||
transform: document.metadata().transform_to_document(layer),
|
||||
})
|
||||
})
|
||||
|
||||
@@ -635,7 +635,8 @@ pub fn make_path_editable_is_allowed(network_interface: &mut NodeNetworkInterfac
|
||||
|
||||
// Must not already have an existing Path node, in the right-most part of the layer chain, which has an empty set of modifications
|
||||
// (otherwise users could repeatedly keep running this command and stacking up empty Path nodes)
|
||||
if let Some(TaggedValue::VectorModification(modifications)) = NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::Network("Path".into()), 1)
|
||||
if let Some(TaggedValue::VectorModification(modifications)) =
|
||||
NodeGraphLayer::new(first_layer, network_interface).find_input(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER), 1)
|
||||
&& modifications.is_empty()
|
||||
{
|
||||
return None;
|
||||
|
||||
@@ -698,8 +698,7 @@ mod test_artboard {
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
|
||||
.flatten()
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<Artboard>>(&editor.runtime)
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -280,18 +280,25 @@ fn whole_expanse_rect(layer: LayerNodeIdentifier, document: &DocumentMessageHand
|
||||
#[cfg(test)]
|
||||
mod test_fill {
|
||||
pub use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::Graphic;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::vector::fill;
|
||||
|
||||
// The Fill tool writes solid colors, whose stored values the input monitor records as `Item<Color>` wires
|
||||
// The Fill tool writes solid colors, which reach the paint input embedded as `Graphic` items
|
||||
async fn get_fills(editor: &mut EditorTestUtils) -> Vec<Item<Color>> {
|
||||
let instrumented = match editor.eval_graph_until_finished().await {
|
||||
Ok(instrumented) => instrumented,
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
|
||||
instrumented.grab_all_input::<fill::PaintInput, Item<Color>>(&editor.runtime).collect()
|
||||
instrumented
|
||||
.grab_all_input::<fill::PaintInput, Item<Graphic>>(&editor.runtime)
|
||||
.filter_map(|paint| match paint.into_element() {
|
||||
Graphic::Color(color) => Some(color),
|
||||
_ => None,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::SNAP_POINT_TOLERANCE;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -312,7 +312,7 @@ impl Fsm for FreehandToolFsmState {
|
||||
|
||||
let parent = document.new_layer_bounding_artboard(input, viewport);
|
||||
|
||||
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
|
||||
let node = node_type.default_node_template();
|
||||
let nodes = vec![(NodeId(0), node)];
|
||||
|
||||
@@ -454,7 +454,7 @@ mod test_freehand {
|
||||
.filter_map(|layer| {
|
||||
let graph_layer = NodeGraphLayer::new(layer, &document.network_interface);
|
||||
// Only get layers with path nodes
|
||||
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::Network("Path".into()))?;
|
||||
let _ = graph_layer.upstream_visible_node_id_from_name_in_layer(&DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER))?;
|
||||
|
||||
let vector = document.network_interface.compute_modified_vector(layer)?;
|
||||
let transform = document.metadata().transform_to_viewport(layer);
|
||||
|
||||
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
|
||||
|
||||
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
|
||||
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
|
||||
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
|
||||
let mut gradient_form: Option<GradientForm> = None;
|
||||
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
|
||||
|
||||
if reference == transform_reference {
|
||||
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
|
||||
} else if reference == gradient_form_reference
|
||||
&& gradient_form.is_none()
|
||||
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
|
||||
{
|
||||
gradient_form = Some(*value);
|
||||
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
|
||||
// Curvatures other than the radial form's are drawn with the linear form's controls
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
|
||||
Some(&TaggedValue::Number(value)) => value,
|
||||
_ => 0.,
|
||||
};
|
||||
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
|
||||
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3366,7 +3369,7 @@ mod test_gradient {
|
||||
.await;
|
||||
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
|
||||
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
|
||||
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
|
||||
editor.select_tool(ToolType::Gradient).await;
|
||||
editor
|
||||
@@ -3375,7 +3378,7 @@ mod test_gradient {
|
||||
})
|
||||
.await;
|
||||
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
|
||||
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
|
||||
let form_node_id = {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
network_interface
|
||||
@@ -3384,10 +3387,10 @@ mod test_gradient {
|
||||
.keys()
|
||||
.copied()
|
||||
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
|
||||
.expect("Gradient Form node should have been inserted")
|
||||
.expect("Gradient Curvature node should have been inserted")
|
||||
};
|
||||
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
|
||||
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
|
||||
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
|
||||
|
||||
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
|
||||
|
||||
@@ -6,7 +6,7 @@ use crate::consts::{
|
||||
};
|
||||
use crate::messages::input_mapper::utility_types::macros::action_shortcut_manual;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::TransformIn;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::{path_overlays, selected_segments};
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::{DocumentMetadata, LayerNodeIdentifier};
|
||||
@@ -2859,7 +2859,7 @@ impl Fsm for PathToolFsmState {
|
||||
let layer = if shape_editor.selected_shape_state.contains_key(&layer) {
|
||||
layer
|
||||
} else {
|
||||
let Some(node_type) = resolve_network_node_type("Path") else {
|
||||
let Some(node_type) = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER) else {
|
||||
error!("Could not resolve node type for Path");
|
||||
continue;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{COLOR_OVERLAY_BLUE, COLOR_OVERLAY_BLUE_05, HIDE_HANDLE_DISTANCE, SEGMENT_OVERLAY_SIZE};
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_network_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::path_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::{DrawHandles, OverlayContext};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -1434,7 +1434,7 @@ impl PenToolData {
|
||||
}
|
||||
|
||||
// New path layer
|
||||
let node_type = resolve_network_node_type("Path").expect("Path node does not exist");
|
||||
let node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
|
||||
let nodes = vec![(NodeId(0), node_type.default_node_template())];
|
||||
|
||||
let parent = document.new_layer_bounding_artboard(input, viewport);
|
||||
@@ -2526,7 +2526,7 @@ mod test_pen_tool {
|
||||
/// The single Pen-drawn path layer and its vector, or `None` once the layer has been undone away.
|
||||
fn drawn_path(editor: &EditorTestUtils) -> Option<(LayerNodeIdentifier, VectorGeometry)> {
|
||||
let document = editor.active_document();
|
||||
let path_identifier = DefinitionIdentifier::Network("Path".into());
|
||||
let path_identifier = DefinitionIdentifier::ProtoNode(graphene_std::vector::path::IDENTIFIER);
|
||||
let mut path_layers = document
|
||||
.metadata()
|
||||
.all_layers()
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::tool_prelude::*;
|
||||
use crate::consts::{DRAG_THRESHOLD, PATH_JOIN_THRESHOLD, SNAP_POINT_TOLERANCE};
|
||||
use crate::messages::input_mapper::utility_types::pointer::MouseKeys;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{resolve_network_node_type, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::overlays::utility_functions::open_path_endpoint_overlays;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlayContext;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
@@ -442,7 +442,7 @@ impl Fsm for SplineToolFsmState {
|
||||
|
||||
let parent = document.new_layer_bounding_artboard(input, viewport);
|
||||
|
||||
let path_node_type = resolve_network_node_type("Path").expect("Path node does not exist");
|
||||
let path_node_type = resolve_proto_node_type(graphene_std::vector::path::IDENTIFIER).expect("Path node does not exist");
|
||||
let path_node = path_node_type.default_node_template();
|
||||
let spline_node_type = resolve_proto_node_type(graphene_std::vector::spline::IDENTIFIER).expect("Spline node does not exist");
|
||||
let spline_node = spline_node_type.node_template_input_override([Some(NodeInput::node(NodeId(1), 0))]);
|
||||
|
||||
+168
-118
@@ -1,7 +1,8 @@
|
||||
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::utility_types::NodeEvaluationError;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, NodeNetworkInterface};
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
@@ -10,12 +11,12 @@ use graph_craft::proto::GraphErrors;
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig, TimingInformation};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::list::List;
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::raster::{CPU, Raster};
|
||||
use graphene_std::renderer::{RenderMetadata, graphic_list_bounding_box};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, graphic_types, no_paths, paths_from_list_row_attributes};
|
||||
use graphene_std::{ATTR_TRANSFORM, Graphic};
|
||||
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 interpreted_executor::dynamic_executor::ResolvedDocumentNodeTypesDelta;
|
||||
use std::any::Any;
|
||||
use std::sync::Arc;
|
||||
@@ -38,9 +39,20 @@ pub struct ExecutionResponse {
|
||||
responses: VecDeque<FrontendMessage>,
|
||||
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
|
||||
dropped_thumbnails: Vec<NodeId>,
|
||||
vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
/// The resulting value from the temporary inspected during execution
|
||||
inspect_result: Option<InspectResult>,
|
||||
/// The latest result of each observation.
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservationKey {
|
||||
/// The node the Data panel inspects.
|
||||
DataPanel,
|
||||
/// The content of a 'Path' node, which is the geometry the Pen and Path tools edit.
|
||||
PathContent(NodeId),
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// The "Fill" node whose geometry a gradient migration measures.
|
||||
FillMeasurement,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -81,9 +93,16 @@ pub enum NodeGraphUpdate {
|
||||
ExecutionResponse(Box<ExecutionResponse>),
|
||||
CompilationResponse(CompilationResponse),
|
||||
EyedropperPreview(Raster<CPU>),
|
||||
Thumbnails { responses: VecDeque<FrontendMessage>, document_id: DocumentId },
|
||||
InspectResult(Box<InspectResult>),
|
||||
ClipboardSvg { id: u64, svg: Option<String> },
|
||||
Thumbnails {
|
||||
responses: VecDeque<FrontendMessage>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// The latest result of each observation, sent outside an execution after one of them changed.
|
||||
Observations(HashMap<ObservationKey, InspectResult>),
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
svg: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -98,6 +117,8 @@ pub struct NodeGraphExecutor {
|
||||
node_graph_document: Option<DocumentId>,
|
||||
/// Full path from the root document network to the node currently being inspected by the Data panel, or empty if nothing is selected.
|
||||
previous_node_to_inspect: Vec<NodeId>,
|
||||
/// The context overrides the Data panel evaluates its inspected node with, reset when another node is inspected.
|
||||
inspect_context_overrides: ContextOverrides,
|
||||
/// The canvas images the frontend holds, so a render sends only those it lacks.
|
||||
canvas_images_sent: HashSet<u64>,
|
||||
/// Evaluation errors of the last evaluation, used in tests
|
||||
@@ -152,6 +173,7 @@ impl NodeGraphExecutor {
|
||||
node_graph_hash: 0,
|
||||
node_graph_document: None,
|
||||
previous_node_to_inspect: Vec::new(),
|
||||
inspect_context_overrides: ContextOverrides::default(),
|
||||
canvas_images_sent: HashSet::new(),
|
||||
#[cfg(test)]
|
||||
evaluation_errors: None,
|
||||
@@ -188,8 +210,16 @@ impl NodeGraphExecutor {
|
||||
execution_id
|
||||
}
|
||||
|
||||
pub fn submit_inspect_context_overrides(&self, overrides: graphene_std::ContextOverrides) {
|
||||
self.sender.send(GraphRuntimeRequest::InspectContextOverrides(overrides)).expect("Failed to send the context overrides");
|
||||
pub fn submit_inspect_context_overrides(&mut self, overrides: ContextOverrides) {
|
||||
self.inspect_context_overrides = overrides;
|
||||
let Some(observation) = self.data_panel_observation() else { return };
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::Observe {
|
||||
key: ObservationKey::DataPanel,
|
||||
observation: Some(observation),
|
||||
})
|
||||
.expect("Failed to send the context overrides");
|
||||
}
|
||||
|
||||
pub fn submit_clipboard_svg(&self, document_id: Option<DocumentId>, id: u64, layers: Vec<NodeId>) -> Message {
|
||||
@@ -213,14 +243,14 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
/// Updates the network to monitor all inputs. Useful for the testing.
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&mut network);
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
@@ -228,9 +258,9 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
node_to_inspect: Vec::new(),
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
@@ -238,12 +268,17 @@ impl NodeGraphExecutor {
|
||||
|
||||
/// Update the cached network if necessary.
|
||||
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
|
||||
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
|
||||
if inspected_node_changed {
|
||||
self.previous_node_to_inspect = node_to_inspect;
|
||||
self.inspect_context_overrides = ContextOverrides::default();
|
||||
}
|
||||
|
||||
let network_hash = document.network_interface.network_hash();
|
||||
if network_hash != self.node_graph_hash || self.node_graph_document != Some(document_id) || ignore_hash {
|
||||
let network = document.network_interface.document_network().clone();
|
||||
let previewed = document.network_interface.previewed_nodes();
|
||||
let layers = document.network_interface.layer_paths();
|
||||
self.previous_node_to_inspect.clone_from(&node_to_inspect);
|
||||
self.node_graph_hash = network_hash;
|
||||
self.node_graph_document = Some(document_id);
|
||||
|
||||
@@ -253,19 +288,39 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
node_to_inspect,
|
||||
previewed,
|
||||
layers,
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
} else if self.previous_node_to_inspect != node_to_inspect {
|
||||
self.previous_node_to_inspect.clone_from(&node_to_inspect);
|
||||
self.sender.send(GraphRuntimeRequest::Inspect(node_to_inspect)).map_err(|e| e.to_string())?;
|
||||
} else if inspected_node_changed {
|
||||
let observation = self.data_panel_observation();
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::Observe {
|
||||
key: ObservationKey::DataPanel,
|
||||
observation,
|
||||
})
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// What the Data panel reads back, if it inspects a node.
|
||||
fn data_panel_observation(&self) -> Option<Observation> {
|
||||
(!self.previous_node_to_inspect.is_empty()).then(|| Observation {
|
||||
node_path: self.previous_node_to_inspect.clone(),
|
||||
connector: ObservedConnector::Output,
|
||||
overrides: self.inspect_context_overrides.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Every observation a graph update of the document starts with.
|
||||
fn observations(&self, network_interface: &NodeNetworkInterface) -> HashMap<ObservationKey, Observation> {
|
||||
let data_panel = self.data_panel_observation().map(|observation| (ObservationKey::DataPanel, observation));
|
||||
data_panel.into_iter().chain(path_content_observations(network_interface)).collect()
|
||||
}
|
||||
|
||||
/// Adds an evaluate request for whatever current network is cached.
|
||||
pub(crate) fn submit_current_node_graph_evaluation(
|
||||
&mut self,
|
||||
@@ -393,11 +448,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -429,9 +484,9 @@ impl NodeGraphExecutor {
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
node_to_inspect: Vec::new(),
|
||||
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);
|
||||
@@ -466,8 +521,7 @@ impl NodeGraphExecutor {
|
||||
result,
|
||||
responses: existing_responses,
|
||||
dropped_thumbnails,
|
||||
vector_modify,
|
||||
inspect_result,
|
||||
mut observations,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -503,7 +557,8 @@ impl NodeGraphExecutor {
|
||||
// Apply only to the active document's in-progress migration, dropping responses left over from a document switch.
|
||||
if let Some(bake_target) = execution_context.measure_fill {
|
||||
if execution_context.document_id == document_id && self.gradient_migration.as_ref().is_some_and(|migration| migration.document_id == document_id) {
|
||||
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(inspect_result).flatten();
|
||||
let measured = observations.remove(&ObservationKey::FillMeasurement);
|
||||
let inspect_result = matches!(result, ExecutionResult::Value(_) | ExecutionResult::Fallback(..)).then_some(measured).flatten();
|
||||
self.handle_gradient_measurement(document, document_id, bake_target, inspect_result, responses);
|
||||
}
|
||||
continue;
|
||||
@@ -592,7 +647,7 @@ impl NodeGraphExecutor {
|
||||
None => responses.add(response),
|
||||
}
|
||||
}
|
||||
document.network_interface.update_vector_modify(vector_modify);
|
||||
document.network_interface.update_vector_modify(path_contents(&observations));
|
||||
|
||||
match (node_graph_output, execution_context.export_config) {
|
||||
(Some(node_graph_output), Some(export_config)) => self.process_export(node_graph_output, export_config, document, responses),
|
||||
@@ -605,6 +660,7 @@ impl NodeGraphExecutor {
|
||||
});
|
||||
|
||||
// Update the Data panel on the frontend using the value of the inspect result.
|
||||
let inspect_result = observations.remove(&ObservationKey::DataPanel);
|
||||
if let Some(inspect_result) = (!self.previous_node_to_inspect.is_empty()).then_some(inspect_result).flatten() {
|
||||
responses.add(DataPanelMessage::UpdateLayout {
|
||||
inspect_result: Box::new(inspect_result),
|
||||
@@ -661,9 +717,13 @@ impl NodeGraphExecutor {
|
||||
let (data, width, height) = raster.to_flat_u8();
|
||||
responses.add(EyedropperToolMessage::PreviewImage { data, width, height });
|
||||
}
|
||||
NodeGraphUpdate::InspectResult(inspect_result) => {
|
||||
if inspect_result.inspect_node_path == self.previous_node_to_inspect {
|
||||
responses.add(DataPanelMessage::UpdateLayout { inspect_result });
|
||||
NodeGraphUpdate::Observations(mut observations) => {
|
||||
if let Some(inspect_result) = observations.remove(&ObservationKey::DataPanel)
|
||||
&& inspect_result.node_path == self.previous_node_to_inspect
|
||||
{
|
||||
responses.add(DataPanelMessage::UpdateLayout {
|
||||
inspect_result: Box::new(inspect_result),
|
||||
});
|
||||
}
|
||||
}
|
||||
NodeGraphUpdate::Thumbnails {
|
||||
@@ -789,14 +849,19 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
let fill_measurement = Observation {
|
||||
node_path: full_path,
|
||||
connector: ObservedConnector::Output,
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
if self
|
||||
.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
node_to_inspect: full_path.clone(),
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: HashMap::from([(ObservationKey::FillMeasurement, fill_measurement)]),
|
||||
}))
|
||||
.is_err()
|
||||
{
|
||||
@@ -807,7 +872,6 @@ impl NodeGraphExecutor {
|
||||
|
||||
// Force the next normal render to recompile and re-send the real, non-redirected network
|
||||
self.node_graph_hash = 0;
|
||||
self.previous_node_to_inspect = full_path;
|
||||
|
||||
let viewport = Footprint {
|
||||
transform: document.metadata().document_to_viewport,
|
||||
@@ -858,7 +922,7 @@ impl NodeGraphExecutor {
|
||||
return;
|
||||
}
|
||||
|
||||
match inspect_result.and_then(|mut result| result.take_data()).and_then(|data| measure_fill_geometry(&data)) {
|
||||
match inspect_result.and_then(|result| result.data).and_then(|data| measure_fill_geometry(&data)) {
|
||||
Some((bounding_box, item_transform)) => {
|
||||
// Skip the bake if the user already placed this gradient themselves, but drop the now-superseded entry either way
|
||||
if fill_transform_unbaked(document, &network_path, fill_node_id) {
|
||||
@@ -904,10 +968,9 @@ impl NodeGraphExecutor {
|
||||
}
|
||||
|
||||
// TODO: Eventually remove this document upgrade code
|
||||
/// Tear down the in-progress migration and clear the stale inspect target and hash so the next normal render recompiles the real network.
|
||||
/// Tear down the in-progress migration and clear the hash so the next normal render recompiles the real network.
|
||||
fn cancel_gradient_migration(&mut self) {
|
||||
self.gradient_migration = None;
|
||||
self.previous_node_to_inspect = Vec::new();
|
||||
self.node_graph_hash = 0;
|
||||
}
|
||||
|
||||
@@ -971,6 +1034,7 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -987,6 +1051,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -1118,125 +1183,110 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
path_nodes.into_iter().filter_map(|node_path| {
|
||||
let key = ObservationKey::PathContent(*node_path.last()?);
|
||||
let observation = Observation {
|
||||
node_path,
|
||||
connector: ObservedConnector::Input(path::ContentInput::INDEX),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
Some((key, observation))
|
||||
})
|
||||
}
|
||||
|
||||
/// The incoming geometry of each 'Path' node, read from its observed content.
|
||||
fn path_contents(observations: &HashMap<ObservationKey, InspectResult>) -> HashMap<NodeId, VectorGeometry> {
|
||||
observations
|
||||
.iter()
|
||||
.filter_map(|(key, result)| {
|
||||
let ObservationKey::PathContent(path_node) = *key else { return None };
|
||||
let value = result.data.as_ref()?;
|
||||
|
||||
let geometry = match value.downcast_ref::<List<Vector>>() {
|
||||
Some(list) => VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default()),
|
||||
None => VectorGeometry::from_item(value.downcast_ref::<Item<Vector>>()?),
|
||||
};
|
||||
Some((path_node, geometry))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Re-export for usage by tests in other modules
|
||||
#[cfg(test)]
|
||||
pub use test::Instrumented;
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkInterface;
|
||||
use crate::test_utils::test_prelude::{self, NodeGraphLayer};
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::{DocumentNode, NodeNetwork};
|
||||
use graphene_std::Context;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::list::Item;
|
||||
use graphene_std::memo::IORecord;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
/// Stores all of the monitor nodes that have been attached to a graph
|
||||
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<Vec<NodeId>>>>,
|
||||
protonodes_by_path: HashMap<Vec<NodeId>, Vec<Vec<NodeId>>>,
|
||||
protonodes_by_name: HashMap<ProtoNodeIdentifier, Vec<Vec<NodeId>>>,
|
||||
}
|
||||
|
||||
impl Instrumented {
|
||||
/// Adds montior nodes to the network
|
||||
fn add(&mut self, network: &mut NodeNetwork, path: &mut Vec<NodeId>) {
|
||||
// Required to do seperately to satiate the borrow checker.
|
||||
let mut monitor_nodes = Vec::new();
|
||||
for (id, node) in network.nodes.iter_mut() {
|
||||
// Recursively instrument
|
||||
if let DocumentNodeImplementation::Network(nested) = &mut node.implementation {
|
||||
path.push(*id);
|
||||
self.add(nested, path);
|
||||
path.pop();
|
||||
/// Records the path of each proto node in the network and the networks nested in it.
|
||||
fn add(&mut self, network: &NodeNetwork, path: &mut Vec<NodeId>) {
|
||||
for (id, node) in &network.nodes {
|
||||
path.push(*id);
|
||||
match &node.implementation {
|
||||
DocumentNodeImplementation::Network(nested) => self.add(nested, path),
|
||||
DocumentNodeImplementation::ProtoNode(identifier) => self.protonodes_by_name.entry(identifier.clone()).or_default().push(path.clone()),
|
||||
_ => {}
|
||||
}
|
||||
let mut monitor_node_ids = Vec::with_capacity(node.inputs.len());
|
||||
for input in &mut node.inputs {
|
||||
let node_id = NodeId::new();
|
||||
path.push(node_id);
|
||||
monitor_node_ids.push(path.clone());
|
||||
path.pop();
|
||||
|
||||
// A None value is a unit wire with nothing to record and no Monitor row, so its slot stays a dead path that introspects as absent
|
||||
if matches!(input, NodeInput::Value { tagged_value, .. } if matches!(&**tagged_value, graph_craft::document::value::TaggedValue::None)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let old_input = std::mem::replace(input, NodeInput::node(node_id, 0));
|
||||
monitor_nodes.push((old_input, node_id));
|
||||
}
|
||||
if let DocumentNodeImplementation::ProtoNode(identifier) = &mut node.implementation {
|
||||
path.push(*id);
|
||||
self.protonodes_by_name.entry(identifier.clone()).or_default().push(monitor_node_ids.clone());
|
||||
self.protonodes_by_path.insert(path.clone(), monitor_node_ids);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
for (input, monitor_id) in monitor_nodes {
|
||||
let monitor_node = DocumentNode {
|
||||
inputs: vec![input],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::memo::monitor::IDENTIFIER),
|
||||
call_argument: graph_craft::generic!(T),
|
||||
skip_deduplication: true,
|
||||
..Default::default()
|
||||
};
|
||||
network.nodes.insert(monitor_id, monitor_node);
|
||||
path.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/// Instrument a graph and return a new [Instrumented] state.
|
||||
pub fn new(network: &mut NodeNetwork) -> Self {
|
||||
pub fn new(network: &NodeNetwork) -> Self {
|
||||
let mut instrumented = Self::default();
|
||||
instrumented.add(network, &mut Vec::new());
|
||||
instrumented
|
||||
}
|
||||
|
||||
/// Pulls a concrete output type out of a monitor record, tolerating the three context shapes the executor records against.
|
||||
fn downcast_record<Output: Send + Sync + Clone + 'static>(dynamic: Arc<dyn std::any::Any + Send + Sync>) -> Option<Output> {
|
||||
if let Some(x) = dynamic.downcast_ref::<IORecord<(), Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else if let Some(x) = dynamic.downcast_ref::<IORecord<Footprint, Output>>() {
|
||||
Some(x.output.clone())
|
||||
} else {
|
||||
dynamic.downcast_ref::<IORecord<Context, Output>>().map(|x| x.output.clone())
|
||||
}
|
||||
/// Reads the value an input of the proto node at this path received, if it has the `Output` type.
|
||||
/// Only the value types the Data panel can show come through.
|
||||
fn grab_input<Output: Clone + 'static>(path: &[NodeId], input_index: usize, runtime: &NodeRuntime) -> Option<Output> {
|
||||
let observation = Observation {
|
||||
node_path: path.to_vec(),
|
||||
connector: ObservedConnector::Input(input_index),
|
||||
overrides: ContextOverrides::default(),
|
||||
};
|
||||
runtime.observe(observation)?.downcast_ref::<Output>().cloned()
|
||||
}
|
||||
|
||||
/// Grab all of the values of the input every time it occurs in the graph, downcast to the recorded `Output` type.
|
||||
/// A record whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
|
||||
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Send + Sync + Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
|
||||
/// Grab all of the values of the input every time it occurs in the graph, downcast to the received `Output` type.
|
||||
/// A value whose type does not match `Output` is skipped, so a wrong `Output` yields an empty iterator rather than an error.
|
||||
pub fn grab_all_input<'a, Input: NodeParameter + 'a, Output: Clone + 'static>(&'a self, runtime: &'a NodeRuntime) -> impl Iterator<Item = Output> + 'a {
|
||||
self.protonodes_by_name
|
||||
.get(&Input::NODE_IDENTIFIER)
|
||||
.map_or([].as_slice(), |x| x.as_slice())
|
||||
.map_or([].as_slice(), |paths| paths.as_slice())
|
||||
.iter()
|
||||
.filter_map(|inputs| inputs.get(Input::INDEX))
|
||||
.filter_map(|input_monitor_node| runtime.executor.introspect(input_monitor_node).ok())
|
||||
.filter_map(Instrumented::downcast_record::<Output>)
|
||||
.filter_map(|path| Self::grab_input::<Output>(path, Input::INDEX, runtime))
|
||||
}
|
||||
|
||||
pub fn grab_protonode_input<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Output> {
|
||||
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
|
||||
|
||||
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
|
||||
|
||||
Self::downcast_record::<Output>(dynamic)
|
||||
pub fn grab_protonode_input<Input: NodeParameter, Output: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Output> {
|
||||
Self::grab_input::<Output>(path, Input::INDEX, runtime)
|
||||
}
|
||||
|
||||
/// Grabs a ranked input's recorded value as its bare element `Element`.
|
||||
/// A stored value materializes as an `Item<Element>` wire, so the monitor records the whole cell and this unwraps its element.
|
||||
pub fn grab_ranked_input<Input: NodeParameter, Element: Send + Sync + Clone + 'static>(&self, path: &Vec<NodeId>, runtime: &NodeRuntime) -> Option<Element> {
|
||||
let input_monitor_node = self.protonodes_by_path.get(path)?.get(Input::INDEX)?;
|
||||
let dynamic = runtime.executor.introspect(input_monitor_node).ok()?;
|
||||
Self::downcast_record::<Item<Element>>(dynamic).map(|item| item.into_element())
|
||||
/// Grabs a ranked input's received value as its bare element `Element`.
|
||||
/// A stored value materializes as an `Item<Element>` wire, so the input receives the whole cell and this unwraps its element.
|
||||
pub fn grab_ranked_input<Input: NodeParameter, Element: Clone + 'static>(&self, path: &[NodeId], runtime: &NodeRuntime) -> Option<Element> {
|
||||
Self::grab_input::<Item<Element>>(path, Input::INDEX, runtime).map(Item::into_element)
|
||||
}
|
||||
|
||||
pub fn grab_input_from_layer<Input: NodeParameter, Output: Send + Sync + Clone + 'static>(
|
||||
pub fn grab_input_from_layer<Input: NodeParameter, Output: Clone + 'static>(
|
||||
&self,
|
||||
layer: LayerNodeIdentifier,
|
||||
network_interface: &NodeNetworkInterface,
|
||||
@@ -1244,7 +1294,7 @@ mod test {
|
||||
) -> Option<Output> {
|
||||
let node_graph_layer = NodeGraphLayer::new(layer, network_interface);
|
||||
let node = node_graph_layer.upstream_node_id_from_protonode(Input::NODE_IDENTIFIER)?;
|
||||
self.grab_protonode_input::<Input, Output>(&vec![node], runtime)
|
||||
self.grab_protonode_input::<Input, Output>(&[node], runtime)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,7 @@ async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
}
|
||||
|
||||
/// The proto node IDs compiled for the document node paths that pass `keep`. The executor keeps the nodes an update drops
|
||||
/// for one more update, so a first update clears those of the test harness's instrumented graph.
|
||||
/// for one more update, so a first update clears those of the graph before it.
|
||||
async fn compiled_ids(editor: &mut EditorTestUtils, keep: impl Fn(&[NodeId]) -> bool) -> HashSet<NodeId> {
|
||||
compile_and_run(editor).await;
|
||||
compile_and_run(editor).await;
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::*;
|
||||
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
|
||||
use crate::task::{Spawn, Spawner, Task};
|
||||
use glam::{DVec2, UVec2};
|
||||
use glam::UVec2;
|
||||
use graph_craft::application_io::resource::ResourceRegistry;
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
@@ -11,23 +11,26 @@ use graph_craft::graphene_compiler::{CompileError, CompiledNetwork, Compiler};
|
||||
use graph_craft::proto::GraphErrors;
|
||||
use graphene_hash::CacheHash;
|
||||
use graphene_std::application_io::{ApplicationIo, ExportFormat, Texture};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::memo::IORecord;
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasSurface, CanvasSurfaceHandle};
|
||||
use graphene_std::raster_types::Raster;
|
||||
use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::vector::{Vector, VectorGeometry, paths_from_list_row_attributes};
|
||||
use graphene_std::{Context, ContextFeatures, ContextOverrides, NodeError, OwnedContextImpl, Poll};
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use thumbnails::Thumbnails;
|
||||
|
||||
#[cfg(test)]
|
||||
mod layer_path_tests;
|
||||
mod observer;
|
||||
mod thumbnails;
|
||||
|
||||
/// Persistent data between graph executions. It's updated via message passing from the editor thread with [`GraphRuntimeRequest`]`.
|
||||
@@ -54,17 +57,13 @@ pub struct NodeRuntime {
|
||||
resources: ResourceRegistry,
|
||||
node_graph_errors: GraphErrors,
|
||||
node_graph_warnings: GraphErrors,
|
||||
monitor_nodes: Vec<(Vec<NodeId>, NodeId)>,
|
||||
thumbnails: Thumbnails,
|
||||
|
||||
/// The node the Data panel inspects.
|
||||
inspect_state: Option<InspectState>,
|
||||
observer: Observer<ObservationKey>,
|
||||
/// Whether an observation changed since its results were last sent.
|
||||
observations_changed: bool,
|
||||
|
||||
preprocessor: preprocessor::Preprocessor,
|
||||
|
||||
vector_modify: HashMap<NodeId, VectorGeometry>,
|
||||
vector_evaluations: HashMap<NodeId, (NodeId, u64)>,
|
||||
|
||||
/// Cached surface for Wasm viewport rendering (reused across frames)
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu", feature = "wasm"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle,
|
||||
@@ -78,22 +77,31 @@ pub struct NodeRuntime {
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
ThumbnailsInView { layers: HashSet<NodeId>, document_id: DocumentId },
|
||||
Inspect(Vec<NodeId>),
|
||||
InspectContextOverrides(ContextOverrides),
|
||||
ClipboardSvg { id: u64, layers: Vec<NodeId> },
|
||||
ThumbnailsInView {
|
||||
layers: HashSet<NodeId>,
|
||||
document_id: DocumentId,
|
||||
},
|
||||
/// Starts, changes, or with `None` stops one observation without a graph update.
|
||||
Observe {
|
||||
key: ObservationKey,
|
||||
observation: Option<Observation>,
|
||||
},
|
||||
ClipboardSvg {
|
||||
id: u64,
|
||||
layers: Vec<NodeId>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub struct GraphUpdate {
|
||||
pub(super) network: NodeNetwork,
|
||||
pub(super) resources: ResourceRegistry,
|
||||
/// Full path from the root network to the node the Data panel inspects.
|
||||
pub(super) node_to_inspect: Vec<NodeId>,
|
||||
/// The node each network renders in place of its export, paired with that network's path.
|
||||
pub(super) previewed: Vec<(Vec<NodeId>, RootNode)>,
|
||||
/// Full path from the root network to every layer, 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.
|
||||
pub(super) observations: HashMap<ObservationKey, Observation>,
|
||||
}
|
||||
|
||||
/// Replaces each network's primary export with its previewed node.
|
||||
@@ -143,14 +151,12 @@ impl NodeRuntime {
|
||||
|
||||
node_graph_errors: Vec::new(),
|
||||
node_graph_warnings: Vec::new(),
|
||||
monitor_nodes: Vec::new(),
|
||||
thumbnails: Thumbnails::new(),
|
||||
observer: Observer::default(),
|
||||
observations_changed: false,
|
||||
|
||||
preprocessor: preprocessor::Preprocessor::new(),
|
||||
|
||||
vector_modify: Default::default(),
|
||||
vector_evaluations: Default::default(),
|
||||
inspect_state: None,
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu"))]
|
||||
wasm_canvas_cache: CanvasSurfaceHandle::new(),
|
||||
#[cfg(all(target_family = "wasm", feature = "gpu"))]
|
||||
@@ -181,17 +187,15 @@ impl NodeRuntime {
|
||||
self.thumbnails.set_in_view(layers);
|
||||
self.pending_thumbnails = Some(document_id);
|
||||
}
|
||||
// A graph update applied after this loop would otherwise inspect what was selected before
|
||||
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
|
||||
Some(update) => update.node_to_inspect = node_to_inspect,
|
||||
None => self.inspect_state = InspectState::new(node_to_inspect),
|
||||
},
|
||||
GraphRuntimeRequest::InspectContextOverrides(overrides) => {
|
||||
if let Some(inspect_state) = &mut self.inspect_state {
|
||||
inspect_state.overrides = overrides;
|
||||
inspect_state.overrides_changed = true;
|
||||
// A graph update applied after this loop would otherwise replace this with what it observed before
|
||||
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.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");
|
||||
@@ -202,21 +206,17 @@ impl NodeRuntime {
|
||||
let Some(GraphUpdate {
|
||||
mut network,
|
||||
resources,
|
||||
node_to_inspect,
|
||||
previewed,
|
||||
layers,
|
||||
observations,
|
||||
}) = graph
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
apply_previews(&mut network, &previewed);
|
||||
|
||||
match &mut self.inspect_state {
|
||||
Some(inspect_state) if inspect_state.inspect_node_path == node_to_inspect => inspect_state.last_evaluation = None,
|
||||
_ => self.inspect_state = InspectState::new(node_to_inspect),
|
||||
}
|
||||
|
||||
write_layer_paths(&mut network, &layers);
|
||||
self.observer.replace_all(observations);
|
||||
self.resources = resources;
|
||||
|
||||
self.node_graph_errors.clear();
|
||||
@@ -259,12 +259,9 @@ impl NodeRuntime {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(inspect_state) = &mut self.inspect_state
|
||||
&& std::mem::take(&mut inspect_state.overrides_changed)
|
||||
&& viewport.is_none()
|
||||
{
|
||||
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
|
||||
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
|
||||
if std::mem::take(&mut self.observations_changed) && viewport.is_none() {
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.sender.send(NodeGraphUpdate::Observations(observations)).expect("Failed to send response");
|
||||
}
|
||||
|
||||
if let Some(eyedropper) = self.pending_eyedropper.take() {
|
||||
@@ -373,8 +370,7 @@ impl NodeRuntime {
|
||||
result: ExecutionResult::Panic(payload),
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
vector_modify: HashMap::new(),
|
||||
inspect_result: None,
|
||||
observations: HashMap::new(),
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
@@ -385,20 +381,27 @@ impl NodeRuntime {
|
||||
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult) {
|
||||
let mut responses = VecDeque::new();
|
||||
let dropped_thumbnails = self.process_monitor_nodes(&mut responses).await;
|
||||
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
|
||||
let dropped_thumbnails = self.update_thumbnails(&mut responses).await;
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
result,
|
||||
responses,
|
||||
dropped_thumbnails,
|
||||
vector_modify: self.vector_modify.clone(),
|
||||
inspect_result,
|
||||
observations,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
|
||||
/// Reads one observation from the last evaluation, apart from the observations the runtime keeps.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn observe(&self, observation: Observation) -> Option<ObservedValue> {
|
||||
let mut observer = Observer::default();
|
||||
observer.set((), Some(observation));
|
||||
observer.evaluate(&self.executor, self.old_graph.as_ref()).remove(&())?.data
|
||||
}
|
||||
|
||||
async fn read_back(&self, texture: Texture) -> Raster<CPU> {
|
||||
let application_io = self.editor_api.application_io.as_ref().unwrap();
|
||||
let executor = application_io.gpu_executor().expect("GPU executor should be available when we receive a texture");
|
||||
@@ -426,12 +429,6 @@ impl NodeRuntime {
|
||||
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
|
||||
};
|
||||
self.node_graph_warnings = warnings;
|
||||
self.monitor_nodes = proto_network
|
||||
.nodes
|
||||
.iter()
|
||||
.filter(|(_, node)| node.identifier == graphene_std::memo::monitor::IDENTIFIER)
|
||||
.map(|(id, node)| (node.original_location.path.clone().unwrap_or_default(), *id))
|
||||
.collect();
|
||||
|
||||
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
|
||||
let result = self.executor.update(proto_network).map_err(|(types, e)| {
|
||||
@@ -462,41 +459,9 @@ impl NodeRuntime {
|
||||
EvaluationErrors(errors.into())
|
||||
}
|
||||
|
||||
/// Updates state data, giving back the layers whose thumbnails were dropped because they no longer have content to show.
|
||||
async fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
|
||||
/// Renders the stale thumbnails, giving back the layers whose thumbnails were dropped because they no longer have content to show.
|
||||
async fn update_thumbnails(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
|
||||
let dropped_thumbnails = self.thumbnails.drop_sourceless();
|
||||
|
||||
for (monitor_node_path, _) in &self.monitor_nodes {
|
||||
let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else {
|
||||
warn!("Monitor node has invalid node id");
|
||||
continue;
|
||||
};
|
||||
|
||||
if !records_vector(&self.executor, monitor_node_path) {
|
||||
continue;
|
||||
}
|
||||
let tree = self.executor.tree();
|
||||
let Ok(content_node) = tree.input_node(monitor_node_path, 0) else { continue };
|
||||
let Ok(Some(context)) = tree.last_context(content_node) else { continue };
|
||||
let context_hash = context_hash(&context);
|
||||
if self.vector_evaluations.get(&parent_network_node_id) == Some(&(content_node, context_hash)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(output) = tree.evaluate(content_node, &context).ok().and_then(evaluated_output) else {
|
||||
continue;
|
||||
};
|
||||
let geometry = if let Some(list) = output.downcast_ref::<List<Vector>>() {
|
||||
VectorGeometry::new(list.element(0).cloned().unwrap_or_default(), paths_from_list_row_attributes(list, 0).cloned().unwrap_or_default())
|
||||
} else if let Some(item) = output.downcast_ref::<Item<Vector>>() {
|
||||
VectorGeometry::from_item(item)
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
self.vector_modify.insert(parent_network_node_id, geometry);
|
||||
self.vector_evaluations.insert(parent_network_node_id, (content_node, context_hash));
|
||||
}
|
||||
|
||||
self.thumbnails.render_stale(&self.executor, &self.editor_api, responses).await;
|
||||
|
||||
dropped_thumbnails
|
||||
@@ -511,35 +476,6 @@ impl ExecutionResult {
|
||||
}
|
||||
}
|
||||
|
||||
/// The layer a monitor node belongs to, since monitor nodes sit within the network of the document node they monitor.
|
||||
fn monitor_parent_node(monitor_node_path: &[NodeId]) -> Option<NodeId> {
|
||||
monitor_node_path.len().checked_sub(2).and_then(|index| monitor_node_path.get(index)).copied()
|
||||
}
|
||||
|
||||
fn records_vector(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> bool {
|
||||
// TODO: Tell this from the monitor node's type once the types the borrow tree records can be compared with concrete ones
|
||||
executor
|
||||
.introspect(monitor_node_path)
|
||||
.is_ok_and(|data| data.is::<IORecord<Context, List<Vector>>>() || data.is::<IORecord<Context, Item<Vector>>>())
|
||||
}
|
||||
|
||||
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
|
||||
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
|
||||
|
||||
InspectedContext {
|
||||
features: ContextOverrides {
|
||||
footprint: context.try_footprint().copied(),
|
||||
real_time: context.try_real_time(),
|
||||
animation_time: context.try_animation_time(),
|
||||
pointer_position: context.try_pointer_position(),
|
||||
index: context.try_index().map(|index| index.collect()),
|
||||
},
|
||||
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
|
||||
variables: context.varargs_len().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn evaluated_output(poll: Poll<graphene_std::registry::Any>) -> Option<graphene_std::registry::Any> {
|
||||
match poll {
|
||||
Poll::Final(output) | Poll::Partial(output) => Some(output),
|
||||
@@ -594,112 +530,11 @@ impl Spawn for NodeTaskExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/// The node the Data panel inspects, which is evaluated again from the context it was last evaluated with.
|
||||
struct InspectState {
|
||||
inspect_node_path: Vec<NodeId>,
|
||||
overrides: ContextOverrides,
|
||||
last_evaluation: Option<(NodeId, u64, Option<InspectedData>)>,
|
||||
overrides_changed: bool,
|
||||
}
|
||||
|
||||
type InspectedData = Arc<dyn std::any::Any + Send + Sync + 'static>;
|
||||
|
||||
/// The resulting value from the temporary inspected during execution
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InspectResult {
|
||||
introspected_data: Option<Arc<dyn std::any::Any + Send + Sync + 'static>>,
|
||||
/// Full path from the root network to the inspected node, with the node itself as the last element.
|
||||
/// The parent slice (`split_last().1`) is the network the node lives in, which downstream consumers
|
||||
/// (e.g. the Data panel) need when looking the node up via `network_interface.is_layer(...)` etc.
|
||||
pub inspect_node_path: Vec<NodeId>,
|
||||
pub context: InspectedContext,
|
||||
}
|
||||
|
||||
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct InspectedContext {
|
||||
pub features: ContextOverrides,
|
||||
/// The positions the context carries, from the outermost level in.
|
||||
pub positions: Vec<DVec2>,
|
||||
pub variables: usize,
|
||||
pub overrides: ContextOverrides,
|
||||
pub dependencies: ContextFeatures,
|
||||
}
|
||||
|
||||
impl InspectResult {
|
||||
pub fn take_data(&mut self) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
|
||||
self.introspected_data.clone()
|
||||
}
|
||||
}
|
||||
|
||||
// This is very ugly but is required to be inside a message
|
||||
impl PartialEq for InspectResult {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.inspect_node_path == other.inspect_node_path
|
||||
}
|
||||
}
|
||||
|
||||
impl InspectState {
|
||||
fn new(inspect_node_path: Vec<NodeId>) -> Option<Self> {
|
||||
(!inspect_node_path.is_empty()).then_some(Self {
|
||||
inspect_node_path,
|
||||
overrides: ContextOverrides::default(),
|
||||
last_evaluation: None,
|
||||
overrides_changed: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn access(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> InspectResult {
|
||||
let node = network.and_then(|network| executor.tree().output_node(network, &self.inspect_node_path));
|
||||
let context = node.and_then(|node| executor.tree().last_context(node).ok().flatten()).map(|context| self.with_overrides(context));
|
||||
|
||||
let introspected_data = node.zip(context.clone()).and_then(|(node, context)| self.evaluate(executor, node, context));
|
||||
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
|
||||
let context = InspectedContext {
|
||||
overrides: self.overrides.clone(),
|
||||
dependencies: node.map(|node| executor.tree().context_features(node)).unwrap_or_default(),
|
||||
..features
|
||||
};
|
||||
|
||||
InspectResult {
|
||||
introspected_data,
|
||||
inspect_node_path: self.inspect_node_path.clone(),
|
||||
context,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_overrides(&self, context: Context<'static>) -> Context<'static> {
|
||||
if self.overrides.is_empty() {
|
||||
return context;
|
||||
}
|
||||
let context = context
|
||||
.as_deref()
|
||||
.map(|context| context.with_overrides(&self.overrides))
|
||||
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(&self.overrides));
|
||||
Some(Arc::new(context))
|
||||
}
|
||||
|
||||
/// Evaluates the node with the context, reusing the last result if neither changed.
|
||||
fn evaluate(&mut self, executor: &DynamicExecutor, node: NodeId, context: Context<'static>) -> Option<Arc<dyn std::any::Any + Send + Sync + 'static>> {
|
||||
let context_hash = context_hash(&context);
|
||||
if let Some((last_node, last_context_hash, data)) = &self.last_evaluation
|
||||
&& (*last_node, *last_context_hash) == (node, context_hash)
|
||||
{
|
||||
return data.clone();
|
||||
}
|
||||
|
||||
let output = evaluated_output(executor.tree().evaluate(node, &context).ok()?)?;
|
||||
// Output the Data panel can't show is remembered too, so it isn't evaluated again for nothing
|
||||
let data = crate::messages::portfolio::document::data_panel::shareable_inspect_output(output);
|
||||
self.last_evaluation = Some((node, context_hash, data.clone()));
|
||||
data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::EditorTestUtils;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::DocumentNode;
|
||||
use graphene_std::SourceId;
|
||||
use graphene_std::runtime::Runtime;
|
||||
@@ -753,31 +588,48 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
|
||||
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
|
||||
let mut noise = Image::new(64, 64, Color::BLACK);
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for pixel in &mut noise.data {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let gray = (state % 256) as f32 / 255.;
|
||||
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
|
||||
}
|
||||
editor.create_raster_image(noise, None).await;
|
||||
|
||||
// Trace the image between the layer and the nodes feeding it
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let mut create = |node_type| {
|
||||
let node_id = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(node_id),
|
||||
node_type,
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
node_id
|
||||
};
|
||||
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
|
||||
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
|
||||
let content = InputConnector::node_at_index(layer.to_node(), 1);
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.upstream_output_connector(&content, &[])
|
||||
.expect("the image layer has content");
|
||||
|
||||
let vectorize = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(vectorize),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(noise),
|
||||
output_connector: image,
|
||||
input_connector: InputConnector::node_at_index(vectorize, 0),
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
input_connector: content,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -824,8 +676,7 @@ mod tests {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
vectorize_layer(&mut editor);
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
|
||||
send_export(&mut editor);
|
||||
editor.runtime.update();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::graphic::extend;
|
||||
|
||||
fn rectangle() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
|
||||
}
|
||||
|
||||
// A layer without an Extend node gets its path written onto its whole output
|
||||
#[tokio::test]
|
||||
async fn a_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let rectangle = editor.create_node_by_name_at(rectangle(), 0, 0).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
assert!(editor.active_document().metadata().click_targets.is_empty(), "A node not shown as a layer should have no click targets");
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: rectangle, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(rectangle, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"A node shown as a layer should have click targets"
|
||||
);
|
||||
}
|
||||
|
||||
// A layer that is an Extend node gets its path written onto what it adds
|
||||
#[tokio::test]
|
||||
async fn an_extend_node_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let extend = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(extend::IDENTIFIER), 0, 0).await;
|
||||
let (below, added) = (editor.create_node_by_name_at(rectangle(), -10, 0).await, editor.create_node_by_name_at(rectangle(), -10, 4).await);
|
||||
for (rectangle, input) in [(below, InputConnector::node(extend, extend::BaseInput)), (added, InputConnector::node(extend, extend::NewInput))] {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: input,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(extend, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: extend, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(extend, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"An Extend node shown as a layer should have click targets for what it adds"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
use super::{context_hash, evaluated_output};
|
||||
use crate::messages::portfolio::document::data_panel::shareable_inspect_output;
|
||||
use glam::DVec2;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graphene_std::{Context, ContextFeatures, ContextOverrides, OwnedContextImpl};
|
||||
use interpreted_executor::dynamic_executor::{BorrowTree, DynamicExecutor};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub type ObservedValue = Arc<dyn std::any::Any + Send + Sync + 'static>;
|
||||
|
||||
/// A connector of a document node whose value the editor reads back after each evaluation.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Observation {
|
||||
pub node_path: Vec<NodeId>,
|
||||
pub connector: ObservedConnector,
|
||||
/// Replaces parts of the context the value is evaluated with.
|
||||
pub overrides: ContextOverrides,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ObservedConnector {
|
||||
Input(usize),
|
||||
Output,
|
||||
}
|
||||
|
||||
/// The value an observation read, with the context it was evaluated with.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct InspectResult {
|
||||
pub data: Option<ObservedValue>,
|
||||
pub node_path: Vec<NodeId>,
|
||||
pub context: InspectedContext,
|
||||
}
|
||||
|
||||
/// The features of the context an inspected node was evaluated with, after the overrides replaced some of them.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct InspectedContext {
|
||||
pub features: ContextOverrides,
|
||||
pub positions: Vec<DVec2>,
|
||||
pub variables: usize,
|
||||
pub overrides: ContextOverrides,
|
||||
pub dependencies: ContextFeatures,
|
||||
}
|
||||
|
||||
// This is very ugly but is required to be inside a message
|
||||
impl PartialEq for InspectResult {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.node_path == other.node_path
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates each observed connector again from the context its node was last evaluated with.
|
||||
pub struct Observer<Key> {
|
||||
observations: HashMap<Key, ObservationState>,
|
||||
}
|
||||
|
||||
struct ObservationState {
|
||||
observation: Observation,
|
||||
last_evaluation: Option<Evaluation>,
|
||||
}
|
||||
|
||||
struct Evaluation {
|
||||
source: NodeId,
|
||||
context_hash: u64,
|
||||
value: Option<ObservedValue>,
|
||||
}
|
||||
|
||||
impl<Key> Default for Observer<Key> {
|
||||
fn default() -> Self {
|
||||
Self { observations: HashMap::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl<Key: Clone + Eq + Hash> Observer<Key> {
|
||||
/// Replaces every observation, keeping the last evaluation of those that stayed the same.
|
||||
pub fn replace_all(&mut self, observations: HashMap<Key, Observation>) {
|
||||
let mut previous = std::mem::take(&mut self.observations);
|
||||
self.observations = observations
|
||||
.into_iter()
|
||||
.map(|(key, observation)| {
|
||||
let state = ObservationState::new(observation, previous.remove(&key));
|
||||
(key, state)
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
/// Starts, changes, or with `None` stops the observation under this key.
|
||||
pub fn set(&mut self, key: Key, observation: Option<Observation>) {
|
||||
let previous = self.observations.remove(&key);
|
||||
let Some(observation) = observation else { return };
|
||||
|
||||
self.observations.insert(key, ObservationState::new(observation, previous));
|
||||
}
|
||||
|
||||
/// Evaluates the observations whose source or context changed, giving back the latest result of each.
|
||||
pub fn evaluate(&mut self, executor: &DynamicExecutor, network: Option<&NodeNetwork>) -> HashMap<Key, InspectResult> {
|
||||
let tree = executor.tree();
|
||||
|
||||
self.observations.iter_mut().map(|(key, state)| (key.clone(), state.evaluate(tree, network))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl ObservationState {
|
||||
fn new(observation: Observation, previous: Option<ObservationState>) -> Self {
|
||||
let last_evaluation = previous.filter(|previous| previous.observation == observation).and_then(|previous| previous.last_evaluation);
|
||||
Self { observation, last_evaluation }
|
||||
}
|
||||
|
||||
fn evaluate(&mut self, tree: &BorrowTree, network: Option<&NodeNetwork>) -> InspectResult {
|
||||
let Observation { node_path, connector, overrides } = &self.observation;
|
||||
|
||||
let source = match connector {
|
||||
ObservedConnector::Input(index) => tree.input_node(node_path, *index).ok(),
|
||||
ObservedConnector::Output => network.and_then(|network| tree.output_node(network, node_path)),
|
||||
};
|
||||
let context = source.and_then(|source| tree.last_context(source).ok().flatten()).map(|context| with_overrides(context, overrides));
|
||||
|
||||
let introspected_data = source
|
||||
.zip(context.clone())
|
||||
.and_then(|(source, context)| evaluate_value(&mut self.last_evaluation, tree, source, context));
|
||||
|
||||
let features = context.as_ref().and_then(|context| context.as_deref()).map(context_features).unwrap_or_default();
|
||||
let context = InspectedContext {
|
||||
overrides: overrides.clone(),
|
||||
dependencies: source.map(|source| tree.context_features(source)).unwrap_or_default(),
|
||||
..features
|
||||
};
|
||||
|
||||
InspectResult {
|
||||
data: introspected_data,
|
||||
node_path: node_path.clone(),
|
||||
context,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluates the node with the context, reusing the last result if neither changed.
|
||||
fn evaluate_value(last_evaluation: &mut Option<Evaluation>, tree: &BorrowTree, source: NodeId, context: Context<'static>) -> Option<ObservedValue> {
|
||||
let context_hash = context_hash(&context);
|
||||
if let Some(evaluation) = last_evaluation
|
||||
&& (evaluation.source, evaluation.context_hash) == (source, context_hash)
|
||||
{
|
||||
return evaluation.value.clone();
|
||||
}
|
||||
|
||||
let output = evaluated_output(tree.evaluate(source, &context).ok()?)?;
|
||||
// Output that can't be shared is remembered too, so it isn't evaluated again for nothing
|
||||
let value = shareable_inspect_output(output);
|
||||
*last_evaluation = Some(Evaluation {
|
||||
source,
|
||||
context_hash,
|
||||
value: value.clone(),
|
||||
});
|
||||
value
|
||||
}
|
||||
|
||||
fn with_overrides(context: Context<'static>, overrides: &ContextOverrides) -> Context<'static> {
|
||||
if overrides.is_empty() {
|
||||
return context;
|
||||
}
|
||||
|
||||
let context = context
|
||||
.as_deref()
|
||||
.map(|context| context.with_overrides(overrides))
|
||||
.unwrap_or_else(|| OwnedContextImpl::empty().with_overrides(overrides));
|
||||
Some(Arc::new(context))
|
||||
}
|
||||
|
||||
fn context_features(context: &OwnedContextImpl) -> InspectedContext {
|
||||
use graphene_std::{ExtractAnimationTime, ExtractFootprint, ExtractIndex, ExtractPointerPosition, ExtractPosition, ExtractRealTime, ExtractVarArgs};
|
||||
|
||||
InspectedContext {
|
||||
features: ContextOverrides {
|
||||
footprint: context.try_footprint().copied(),
|
||||
real_time: context.try_real_time(),
|
||||
animation_time: context.try_animation_time(),
|
||||
pointer_position: context.try_pointer_position(),
|
||||
index: context.try_index().map(|index| index.collect()),
|
||||
},
|
||||
positions: context.try_position().map(|positions| positions.collect()).unwrap_or_default(),
|
||||
variables: context.varargs_len().unwrap_or_default(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -4,12 +4,11 @@ use crate::messages::frontend::FrontendMessage;
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::{Item, List};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -19,8 +18,9 @@ use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic, NodeParameter};
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::layer_content;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -399,20 +399,7 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
|
||||
|
||||
/// 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 output = network.output_source(layer_path, 0)?;
|
||||
|
||||
// A hidden layer, or one passing through what's below it, has nothing of its own to show
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
let source = if node.implementation == DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
network.input_source(network_path, node.inputs.get(extend::NewInput::INDEX)?)?
|
||||
} else {
|
||||
output
|
||||
};
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
@@ -484,6 +471,7 @@ mod tests {
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::application_io::TimingInformation;
|
||||
use interpreted_executor::layer_paths::layer_path_writer_id;
|
||||
|
||||
async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
@@ -510,7 +498,7 @@ mod tests {
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, shipped_node_id("Merge", NodeId(3))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -8,27 +8,13 @@
|
||||
import { widgetSizingStyles } from "/src/utility-functions/widgets";
|
||||
import type { MenuListEntry, ActionShortcut, WidgetSizing } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const DASH_ENTRY: MenuListEntry = {
|
||||
value: "",
|
||||
label: "-",
|
||||
icon: undefined,
|
||||
annotation: "",
|
||||
disabled: false,
|
||||
children: [],
|
||||
childrenHash: 0n,
|
||||
font: undefined,
|
||||
tooltipLabel: "",
|
||||
tooltipDescription: "",
|
||||
tooltipShortcut: undefined,
|
||||
tooltipCode: "",
|
||||
};
|
||||
|
||||
const dispatch = createEventDispatcher<{ selectedIndex: number; previewIndex: number; fileDrop: File }>();
|
||||
|
||||
let self: LayoutRow | undefined;
|
||||
|
||||
// Content
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, a dash is displayed
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, the placeholder is displayed
|
||||
export let placeholder = "-";
|
||||
export let drawIcon = false;
|
||||
export let disabled = false;
|
||||
// Children
|
||||
@@ -132,13 +118,13 @@
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function makeActiveEntry(): MenuListEntry {
|
||||
function makeActiveEntry(): MenuListEntry | undefined {
|
||||
const allEntries = entries.flat();
|
||||
|
||||
if (selectedIndex !== undefined && selectedIndex >= 0 && selectedIndex < allEntries.length) {
|
||||
return allEntries[selectedIndex];
|
||||
}
|
||||
return DASH_ENTRY;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function takesDraggedFile(e: DragEvent): boolean {
|
||||
@@ -187,10 +173,10 @@
|
||||
data-dropdown-input
|
||||
>
|
||||
<LayoutRow class="dropdown-box" classes={{ disabled, open }} {tooltipLabel} {tooltipDescription} {tooltipShortcut} on:click={() => !disabled && (open = true)} data-floating-menu-spawner>
|
||||
{#if activeEntry.icon}
|
||||
{#if activeEntry?.icon}
|
||||
<IconLabel class="dropdown-icon" icon={activeEntry.icon} />
|
||||
{/if}
|
||||
<TextLabel class="dropdown-label">{activeEntry.label}</TextLabel>
|
||||
<TextLabel class="dropdown-label">{activeEntry?.label ?? placeholder}</TextLabel>
|
||||
<IconLabel class="dropdown-arrow" icon="DropdownArrow" />
|
||||
</LayoutRow>
|
||||
<MenuList
|
||||
@@ -200,7 +186,7 @@
|
||||
on:activeEntry={({ detail }) => commitEntry(detail)}
|
||||
on:open={({ detail }) => (open = detail)}
|
||||
{open}
|
||||
activeEntry={activeEntry === DASH_ENTRY ? undefined : activeEntry}
|
||||
{activeEntry}
|
||||
{entries}
|
||||
entriesHash={entriesHash || 0n}
|
||||
{drawIcon}
|
||||
|
||||
@@ -14,7 +14,6 @@ pub struct DocumentNode {
|
||||
pub call_argument: Type,
|
||||
pub implementation: DocumentNodeImplementation,
|
||||
pub visible: bool,
|
||||
pub skip_deduplication: bool,
|
||||
pub compile_metadata: Option<NodeCompileMetadata>,
|
||||
pub original_location: OriginalLocation,
|
||||
}
|
||||
@@ -139,7 +138,7 @@ When the document graph is executed, the following steps occur:
|
||||
- The constructor functions are run with the `ConstructionArgs` enum. Constructors generally evaluate the result of these inputs, e.g. if you have a `Pi` node that is used as the second input to an `Add` node, the `Add` node's constructor will evaluate the `Pi` node. This is visible if you place a log statement in the `Pi` node's implementation.
|
||||
- The resolved functions are stored in a `BorrowTree`, which allows previous proto-nodes to be referenced as inputs by later nodes. The `BorrowTree` ensures nodes can't be removed while being referenced by other nodes.
|
||||
|
||||
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize and monitor nodes.
|
||||
The registry rows for a node declared with the `node` macro are generated by it, one per `#[implementations(...)]` pairing. The rows written by hand in `node_registry.rs` are for the adapters that convert between wire types and for executor-internal nodes such as the memoize nodes.
|
||||
|
||||
## Debugging
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ impl DocumentNode {
|
||||
}
|
||||
|
||||
impl NodeNetwork {
|
||||
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and finding monitor nodes.
|
||||
/// Populate the [`DocumentNode::path`], which stores the location of the document node to allow for matching the resulting proto nodes to the document node for the purposes of typing and observing node values.
|
||||
///
|
||||
/// Table entries are not visited, since each instance gets its paths when [`Self::flatten`] copies the entry.
|
||||
pub fn generate_node_paths(&mut self, prefix: &[NodeId]) {
|
||||
|
||||
@@ -28,7 +28,6 @@ impl DocumentNode {
|
||||
call_argument: self.call_argument,
|
||||
construction_args,
|
||||
original_location: self.original_location,
|
||||
skip_deduplication: self.skip_deduplication,
|
||||
compile_metadata: self.compile_metadata.unwrap_or_default(),
|
||||
upstream_context_features: Default::default(),
|
||||
}
|
||||
|
||||
@@ -44,11 +44,6 @@ pub struct DocumentNode {
|
||||
/// Represents the eye icon for hiding/showing the node in the graph UI. When hidden, a node gets replaced with a passthrough node during the graph flattening step.
|
||||
#[serde(default = "return_true")]
|
||||
pub visible: bool,
|
||||
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
|
||||
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
|
||||
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
|
||||
#[serde(default)]
|
||||
pub skip_deduplication: bool,
|
||||
#[serde(skip)]
|
||||
pub compile_metadata: Option<NodeCompileMetadata>,
|
||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||
@@ -82,7 +77,6 @@ impl Default for DocumentNode {
|
||||
call_argument: concrete!(Context),
|
||||
implementation: Default::default(),
|
||||
visible: true,
|
||||
skip_deduplication: Default::default(),
|
||||
original_location: OriginalLocation::default(),
|
||||
compile_metadata: Default::default(),
|
||||
}
|
||||
@@ -817,7 +811,6 @@ impl core_types::graphene_hash::CacheHash for DocumentNode {
|
||||
self.call_argument.cache_hash(state);
|
||||
self.implementation.cache_hash(state);
|
||||
self.visible.cache_hash(state);
|
||||
self.skip_deduplication.cache_hash(state);
|
||||
self.compile_metadata.cache_hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,11 +88,6 @@ pub struct OldDocumentNode {
|
||||
pub locked: bool,
|
||||
/// Metadata about the node including its position in the graph UI. Ensure the click target in the encapsulating network is updated when the node moves by using network.update_click_target(node_id).
|
||||
pub metadata: OldDocumentNodeMetadata,
|
||||
/// When two different proto nodes hash to the same value (e.g. two value nodes each containing `2_u32` or two multiply nodes that have the same node IDs as input), the duplicates are removed.
|
||||
/// See [`ProtoNetwork::generate_stable_node_ids`] for details.
|
||||
/// However sometimes this is not desirable, for example in the case of a [`graphene_core::memo::MonitorNode`] that needs to be accessed outside of the graph.
|
||||
#[serde(default)]
|
||||
pub skip_deduplication: bool,
|
||||
/// The path to this node and its inputs and outputs as of when [`NodeNetwork::generate_node_paths`] was called.
|
||||
#[serde(skip)]
|
||||
pub original_location: OriginalLocation,
|
||||
|
||||
@@ -577,6 +577,9 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -711,6 +714,25 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -729,6 +751,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -124,7 +124,6 @@ pub struct ProtoNode {
|
||||
pub call_argument: Type,
|
||||
pub identifier: ProtoNodeIdentifier,
|
||||
pub original_location: OriginalLocation,
|
||||
pub skip_deduplication: bool,
|
||||
pub(crate) compile_metadata: NodeCompileMetadata,
|
||||
/// The context features read by this node and everything upstream of it.
|
||||
pub upstream_context_features: ContextFeatures,
|
||||
@@ -137,7 +136,6 @@ impl Default for ProtoNode {
|
||||
construction_args: ConstructionArgs::Value(value::TaggedValue::Integer(0).into()),
|
||||
call_argument: concrete!(()),
|
||||
original_location: OriginalLocation::default(),
|
||||
skip_deduplication: false,
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
}
|
||||
@@ -146,16 +144,12 @@ impl Default for ProtoNode {
|
||||
|
||||
impl ProtoNode {
|
||||
/// A stable node ID is a hash of a node that should stay constant. This is used in order to remove duplicates from the graph.
|
||||
/// In the case of `skip_deduplication`, the `document_node_path` is also hashed in order to avoid duplicate monitor nodes from being removed (which would make it impossible to load thumbnails).
|
||||
pub fn stable_node_id(&self) -> Option<NodeId> {
|
||||
use std::hash::Hasher;
|
||||
let mut hasher = rustc_hash::FxHasher::default();
|
||||
|
||||
self.identifier.as_str().hash(&mut hasher);
|
||||
self.construction_args.cache_hash(&mut hasher);
|
||||
if self.skip_deduplication {
|
||||
self.original_location.path.hash(&mut hasher);
|
||||
}
|
||||
|
||||
std::mem::discriminant(&self.call_argument).hash(&mut hasher);
|
||||
self.call_argument.hash(&mut hasher);
|
||||
@@ -173,7 +167,6 @@ impl ProtoNode {
|
||||
path: Some(path),
|
||||
..Default::default()
|
||||
},
|
||||
skip_deduplication: false,
|
||||
compile_metadata: Default::default(),
|
||||
upstream_context_features: ContextFeatures::empty(),
|
||||
}
|
||||
@@ -355,7 +348,6 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
|
||||
@@ -387,7 +379,6 @@ impl ProtoNetwork {
|
||||
},
|
||||
compile_metadata: forwarding,
|
||||
upstream_context_features: features,
|
||||
..Default::default()
|
||||
},
|
||||
));
|
||||
nullification_node_id
|
||||
|
||||
@@ -2,6 +2,7 @@ use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
use graphene_std::graphic::write_layer_path;
|
||||
use graphene_std::simplify_identifier_name;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::error::Error;
|
||||
@@ -57,6 +58,7 @@ enum Kind {
|
||||
Nullify,
|
||||
Expand,
|
||||
Scope,
|
||||
LayerPath,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -68,6 +70,7 @@ impl Kind {
|
||||
Kind::Nullify => "+nullify",
|
||||
Kind::Expand => "+expand",
|
||||
Kind::Scope => "+scope",
|
||||
Kind::LayerPath => "+layer-path",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,6 +237,7 @@ fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind {
|
||||
_ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify,
|
||||
_ if proto.original_location.auto_convert_index.is_some() => Kind::Convert,
|
||||
ConstructionArgs::Value(_) => Kind::Value,
|
||||
_ if proto.identifier == write_layer_path::IDENTIFIER => Kind::LayerPath,
|
||||
_ if origin.is_empty() => Kind::Scope,
|
||||
_ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document,
|
||||
_ => Kind::Expand,
|
||||
|
||||
@@ -13,6 +13,7 @@ use graph_craft::proto::ProtoNetwork;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
@@ -24,13 +25,15 @@ use std::sync::{Arc, Mutex};
|
||||
pub struct OpenedDocument {
|
||||
pub gdd: Option<GddV1>,
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
/// What `dump` shows for each node and network, when asked for.
|
||||
pub names: Option<HashMap<Vec<NodeId>, String>>,
|
||||
}
|
||||
|
||||
/// Open `path` with [`document_loader::open_document`]. `with_names` also collects its display names.
|
||||
pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocument, Box<dyn Error>> {
|
||||
let LoadedDocument { network, origin } = document_loader::open_document(path).await?;
|
||||
let LoadedDocument { network, layers, origin } = document_loader::open_document(path).await?;
|
||||
|
||||
let (gdd, names) = match origin {
|
||||
DocumentOrigin::Legacy(document_string) => (None, with_names.then(|| dump::legacy_names(&document_string))),
|
||||
@@ -43,7 +46,7 @@ pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocume
|
||||
(Some(*gdd), names)
|
||||
}
|
||||
};
|
||||
Ok(OpenedDocument { gdd, network, names })
|
||||
Ok(OpenedDocument { gdd, network, layers, names })
|
||||
}
|
||||
|
||||
/// The name of each node, keyed by the path the dump visits it at.
|
||||
@@ -89,7 +92,9 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
(application_io, editor_api)
|
||||
}
|
||||
|
||||
pub fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
write_layer_paths(&mut network, layers);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
@@ -117,7 +122,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_network = compile_graph(document.network, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
let proto_network = compile_graph(document.network, &document.layers, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
Ok(CompiledDocument {
|
||||
proto_network,
|
||||
|
||||
@@ -124,11 +124,11 @@ impl Viewer {
|
||||
}
|
||||
|
||||
fn recompile(&mut self) {
|
||||
let network = match self.runtime.block_on(self.live.network()) {
|
||||
Ok(network) => network,
|
||||
let (network, layers) = match self.runtime.block_on(self.live.network_with_layers()) {
|
||||
Ok(network_with_layers) => network_with_layers,
|
||||
Err(error) => return log::error!("Failed to build the runtime network: {error}"),
|
||||
};
|
||||
let proto = match compile_graph(network, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
let proto = match compile_graph(network, &layers, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
Ok(proto) => proto,
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
|
||||
@@ -113,11 +113,6 @@ impl DynamicExecutor {
|
||||
Ok(ResolvedDocumentNodeTypesDelta { add, remove })
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
self.tree.introspect(node_path)
|
||||
}
|
||||
|
||||
pub fn input_type(&self) -> Option<Type> {
|
||||
self.typing_context.type_of(self.output).map(|node_io| node_io.call_argument.clone())
|
||||
}
|
||||
@@ -311,13 +306,6 @@ impl BorrowTree {
|
||||
self.nodes.insert(id, (node, path, inputs));
|
||||
}
|
||||
|
||||
/// Calls the `Node::serialize` for that specific node, returning for example the cached value for a monitor node. The node path must match the document node path.
|
||||
pub fn introspect(&self, node_path: &[NodeId]) -> Result<Arc<dyn std::any::Any + Send + Sync + 'static>, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (node, _path, _) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
node.node().serialize().ok_or(IntrospectError::NoData)
|
||||
}
|
||||
|
||||
pub fn get(&self, id: NodeId) -> Option<SharedNodeContainer> {
|
||||
self.nodes.get(&id).map(|(node, _, _)| node.clone() as SharedNodeContainer)
|
||||
}
|
||||
@@ -333,10 +321,19 @@ impl BorrowTree {
|
||||
self.context_features.get(&id).copied().unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The node feeding an input of the proto node at this path, looking past the nodes wrapping it under the same path such as 'Memoize'.
|
||||
pub fn input_node(&self, node_path: &[NodeId], input_index: usize) -> Result<NodeId, IntrospectError> {
|
||||
let (id, _) = self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
let (_, _, inputs) = self.nodes.get(id).ok_or(IntrospectError::ProtoNodeNotFound(*id))?;
|
||||
inputs.get(input_index).copied().ok_or(IntrospectError::NoData)
|
||||
let (mut id, _) = *self.source_map.get(node_path).ok_or_else(|| IntrospectError::PathNotFound(node_path.to_vec()))?;
|
||||
|
||||
loop {
|
||||
let (_, _, inputs) = self.nodes.get(&id).ok_or(IntrospectError::ProtoNodeNotFound(id))?;
|
||||
let wrapped = inputs.first().filter(|first| self.nodes.get(first).is_some_and(|(_, path, _)| **path == *node_path));
|
||||
|
||||
match wrapped {
|
||||
Some(&wrapped) => id = wrapped,
|
||||
None => return inputs.get(input_index).copied().ok_or(IntrospectError::NoData),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The context this node was last evaluated with in the graph.
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
||||
|
||||
use crate::node_registry::NODE_REGISTRY;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::graphic::{extend, write_layer_path};
|
||||
use graphene_std::list::NodeIdPath;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
/// What a layer adds to the document, which is what its thumbnail shows and what its path is written onto.
|
||||
pub enum LayerContent {
|
||||
/// What the Extend node the layer ends in is given to add, with the path of the network the node is in.
|
||||
Added { network_path: Vec<NodeId>, extend: NodeId },
|
||||
/// Everything the layer outputs, from the node at this path.
|
||||
Output(Vec<NodeId>),
|
||||
}
|
||||
|
||||
/// The content of the layer at this path, unless it's hidden or passes through what's below it and so has none of its own.
|
||||
pub fn layer_content(layer_path: &[NodeId], network: &NodeNetwork) -> Option<LayerContent> {
|
||||
let output = network.output_source(layer_path, 0)?;
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
if node.implementation != DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
return Some(LayerContent::Output(output));
|
||||
}
|
||||
|
||||
Some(LayerContent::Added {
|
||||
network_path: network_path.to_vec(),
|
||||
extend: *node_id,
|
||||
})
|
||||
}
|
||||
|
||||
impl LayerContent {
|
||||
/// The path of the node producing the content once compiled.
|
||||
pub fn source(&self, network: &NodeNetwork) -> Option<Vec<NodeId>> {
|
||||
match self {
|
||||
Self::Added { network_path, extend } => {
|
||||
let added = network.nested_network(network_path)?.nodes.get(extend)?.inputs.get(extend::NewInput::INDEX)?;
|
||||
network.input_source(network_path, added)
|
||||
}
|
||||
Self::Output(output) => Some(output.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a node after each layer's content that writes the layer's path onto it.
|
||||
/// A layer has none if its content may be of a type that can't carry the path.
|
||||
pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>]) {
|
||||
let mut carries_layer_path = HashMap::new();
|
||||
|
||||
// O(layers * depth)
|
||||
for layer_path in layer_paths {
|
||||
let Some((layer, parent_path)) = layer_path.split_last() else { continue };
|
||||
let Some(content) = layer_content(layer_path, network) else { continue };
|
||||
|
||||
// An Extend node nested deeper than the layer may be in a network that other layers share.
|
||||
// So the writer goes after the layer's output, and the Extend node only decides if the content can carry the path.
|
||||
let content = match content {
|
||||
LayerContent::Added { network_path, extend } if network_path.len() > layer_path.len() => LayerContent::Output([network_path.as_slice(), &[extend]].concat()),
|
||||
content => content,
|
||||
};
|
||||
|
||||
let Some(source) = content.source(network) else { continue };
|
||||
if !source_can_carry_layer_path(source, network, &mut carries_layer_path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match content {
|
||||
// The writer goes between the Extend node and what it's given to add, inside the layer or beside it if the layer is that node
|
||||
LayerContent::Added { network_path, extend } => {
|
||||
let writer = layer_path_writer_id(extend);
|
||||
let layer_beside = if network_path.len() == layer_path.len() { Vec::new() } else { vec![*layer] };
|
||||
let Some(holder) = network_mut(network, &network_path) else { continue };
|
||||
let Some(added) = holder.nodes.get_mut(&extend).and_then(|node| node.inputs.get_mut(extend::NewInput::INDEX)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Every layer made from the same network shares the writer
|
||||
if *added == NodeInput::node(writer, 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = std::mem::replace(added, NodeInput::node(writer, 0));
|
||||
holder.nodes.insert(writer, layer_path_writer(content, layer_beside));
|
||||
}
|
||||
// The writer goes beside the layer, taking over everything its output feeds
|
||||
LayerContent::Output(_) => {
|
||||
let writer = layer_path_writer_id(*layer);
|
||||
let Some(holder) = network_mut(network, parent_path) else { continue };
|
||||
if holder.nodes.contains_key(&writer) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (output, written) = (NodeInput::node(*layer, 0), NodeInput::node(writer, 0));
|
||||
let inputs = holder.nodes.values_mut().flat_map(|node| &mut node.inputs).chain(&mut holder.exports);
|
||||
inputs.filter(|input| **input == output).for_each(|input| *input = written.clone());
|
||||
|
||||
holder.nodes.insert(writer, layer_path_writer(output, vec![*layer]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the layer path writer fares with what a proto node outputs.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CarriesLayerPath {
|
||||
Always,
|
||||
/// The node outputs the type its one input is given, so that decides it.
|
||||
AsItsInput,
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Whether the layer path writer can take everything the proto node at this path may output.
|
||||
fn source_can_carry_layer_path(mut source: Vec<NodeId>, network: &NodeNetwork, carries_layer_path: &mut HashMap<ProtoNodeIdentifier, CarriesLayerPath>) -> bool {
|
||||
loop {
|
||||
let Some((node_id, network_path)) = source.split_last() else { return false };
|
||||
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
|
||||
return false;
|
||||
};
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
|
||||
|
||||
match *carries_layer_path.entry(identifier.clone()).or_insert_with(|| output_can_carry_layer_path(identifier)) {
|
||||
CarriesLayerPath::Always => return true,
|
||||
CarriesLayerPath::Never => return false,
|
||||
CarriesLayerPath::AsItsInput => {
|
||||
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
|
||||
return false;
|
||||
};
|
||||
source = input_source;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn output_can_carry_layer_path(identifier: &ProtoNodeIdentifier) -> CarriesLayerPath {
|
||||
let (Some(outputs), Some(writers)) = (NODE_REGISTRY.get(identifier), NODE_REGISTRY.get(&write_layer_path::IDENTIFIER)) else {
|
||||
return CarriesLayerPath::Never;
|
||||
};
|
||||
|
||||
let writes_type = |output: &graph_craft::Type| {
|
||||
let content = |writer: &graphene_std::NodeIOTypes| writer.inputs.get(write_layer_path::ContentInput::INDEX).is_some_and(|content| content.nested_type() == output);
|
||||
writers.keys().any(content)
|
||||
};
|
||||
if outputs.keys().all(|output| writes_type(output.return_value.nested_type())) {
|
||||
return CarriesLayerPath::Always;
|
||||
}
|
||||
|
||||
let as_its_input = |output: &graphene_std::NodeIOTypes| matches!(output.inputs.as_slice(), [input] if input.nested_type() == output.return_value.nested_type());
|
||||
if outputs.keys().all(as_its_input) {
|
||||
CarriesLayerPath::AsItsInput
|
||||
} else {
|
||||
CarriesLayerPath::Never
|
||||
}
|
||||
}
|
||||
|
||||
/// The network at this path, which is either an entry of the definitions table or held by its node.
|
||||
fn network_mut<'a>(network: &'a mut NodeNetwork, path: &[NodeId]) -> Option<&'a mut NodeNetwork> {
|
||||
// The last table entry along the path, which holds any networks after it
|
||||
let mut table_entry = None;
|
||||
let mut current = &*network;
|
||||
for (index, node_id) in path.iter().enumerate() {
|
||||
current = match ¤t.nodes.get(node_id)?.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => {
|
||||
table_entry = Some((*id, index + 1));
|
||||
network.definitions.get(id)?
|
||||
}
|
||||
DocumentNodeImplementation::Network(held) => held,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
|
||||
let (mut current, held_path) = match table_entry {
|
||||
Some((id, held_from)) => (network.definitions.get_mut(&id)?, &path[held_from..]),
|
||||
None => (network, path),
|
||||
};
|
||||
for node_id in held_path {
|
||||
let DocumentNodeImplementation::Network(held) = &mut current.nodes.get_mut(node_id)?.implementation else {
|
||||
return None;
|
||||
};
|
||||
current = held;
|
||||
}
|
||||
|
||||
Some(current)
|
||||
}
|
||||
|
||||
/// The ID of the node writing the layer path onto what the node with this ID outputs or is given, which stays the same between compilations.
|
||||
pub fn layer_path_writer_id(node_id: NodeId) -> NodeId {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
"layer path writer".hash(&mut hasher);
|
||||
node_id.hash(&mut hasher);
|
||||
NodeId(hasher.finish())
|
||||
}
|
||||
|
||||
fn layer_path_writer(content: NodeInput, layer_beside: Vec<NodeId>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
content,
|
||||
// The writer is directly inside the layer or beside it, so removing only its own ID gives the path
|
||||
NodeInput::value(TaggedValue::Integer(1), false),
|
||||
NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false),
|
||||
NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(write_layer_path::IDENTIFIER),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::NetworkId;
|
||||
|
||||
#[test]
|
||||
fn content_that_cannot_carry_a_layer_path_is_left_alone() {
|
||||
let path_node = DocumentNode {
|
||||
inputs: vec![NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), path_node)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(1)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
|
||||
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn definition_node(id: NetworkId) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(id),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A network shaped like 'Merge', where an Extend node adds what the node beside it gives.
|
||||
fn merge_like(added: DocumentNode) -> NodeNetwork {
|
||||
let extend = proto_node(extend::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(2), 0)]);
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), extend), (NodeId(2), added)].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// One network is shared by a layer at the root and by a layer inside another layer, so the one writer inside it has to suit both
|
||||
#[test]
|
||||
fn a_network_shared_by_layers_at_different_depths_writes_each_layer_path() {
|
||||
let (merge, group) = (NetworkId(1), NetworkId(2));
|
||||
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||
let group_network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(30), 0)],
|
||||
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(group))].into_iter().collect(),
|
||||
definitions: [(merge, merge_like(rectangle)), (group, group_network)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The outer layer comes first in one order and last in the other
|
||||
let orders = [
|
||||
[vec![NodeId(20)], vec![NodeId(10)], vec![NodeId(20), NodeId(30)]],
|
||||
[vec![NodeId(10)], vec![NodeId(20), NodeId(30)], vec![NodeId(20)]],
|
||||
];
|
||||
let written = orders.map(|layer_paths| {
|
||||
let mut network = network.clone();
|
||||
write_layer_paths(&mut network, &layer_paths);
|
||||
network
|
||||
});
|
||||
assert_eq!(written[0], written[1], "The order the layers are given in should not change what's written");
|
||||
|
||||
// The writer writes the path of the layer holding its network, whichever layer that is
|
||||
let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))];
|
||||
let (levels_up, layer_beside) = (writer.input(write_layer_path::LevelsUpInput), writer.input(write_layer_path::LayerBesideInput));
|
||||
assert_eq!(levels_up, Some(&NodeInput::value(TaggedValue::Integer(1), false)));
|
||||
assert_eq!(layer_beside, Some(&NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)));
|
||||
}
|
||||
|
||||
// Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer
|
||||
#[test]
|
||||
fn a_network_writing_its_own_layer_path_is_left_alone() {
|
||||
let write_attribute = proto_node(graphene_std::graphic::write_attribute::IDENTIFIER, Vec::new());
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(NetworkId(1)))].into_iter().collect(),
|
||||
definitions: [(NetworkId(1), merge_like(write_attribute))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(10)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod dynamic_executor;
|
||||
pub mod layer_paths;
|
||||
pub mod node_registry;
|
||||
pub mod util;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -27,6 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -34,50 +36,6 @@ use std::sync::Arc;
|
||||
// TODO: turn into hashmap
|
||||
fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> {
|
||||
let mut node_types: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
// =============
|
||||
// MONITOR NODES
|
||||
// =============
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Vector>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Artboard>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Graphic>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Vector>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Footprint>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DVec2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<bool>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<DAffine2>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<BlendMode>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientForm>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpread>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientSpace>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientHueDirection>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<GradientInterpolation>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<AttributeValueDyn>]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => ListDyn]),
|
||||
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => List<graphene_std::brush::Stroke>]),
|
||||
// Context nullification
|
||||
#[cfg(feature = "gpu")]
|
||||
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Arc<PlatformEditorApi>>, Context => Item<graphene_std::ContextModification>]),
|
||||
@@ -100,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -120,6 +79,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -298,8 +258,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
}};
|
||||
}
|
||||
// The single list of value/enum element types that ride ranked wires as framable node parameters.
|
||||
// Each needs both a rank promotion adapter and a cache chain (memoize/monitor/context),
|
||||
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up monitorable but not promotable, or vice versa.
|
||||
// Each needs both a rank promotion adapter and a cache chain (memoize/context),
|
||||
// so both registrations below are driven from here by callback, which is what keeps a value type from ending up cacheable but not promotable, or vice versa.
|
||||
macro_rules! ranked_value_types {
|
||||
($register:ident) => {
|
||||
$register!(
|
||||
@@ -329,6 +289,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -354,7 +317,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
)
|
||||
};
|
||||
}
|
||||
// Primary element types (graphical data and scalars) get promotion adapters here; their monitor/memoize rows are the
|
||||
// Primary element types (graphical data and scalars) get promotion adapters here; their memoize rows are the
|
||||
// explicit ones near the top of the registry, so they are deliberately absent from the shared value-type list above
|
||||
node_types.extend(rank_adapter_nodes!(
|
||||
Vector,
|
||||
@@ -362,6 +325,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -394,6 +358,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -434,18 +399,17 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
node_types.extend(bundle_adapter_nodes!(Raster<GPU>));
|
||||
// The memoize + monitor + context-nullification triple for each value type in the shared list above: the compiler wraps
|
||||
// a ranked connector's broadcast sibling in a Memoize + context-nullification pair, and test instrumentation monitors any wire.
|
||||
// The memoize + context-nullification pair the compiler wraps a ranked connector's broadcast sibling in, for each value type in the shared list above.
|
||||
// Node identifiers are passed explicitly since `stringify!` would mangle the path's whitespace through this nested macro.
|
||||
macro_rules! cache_chain_nodes {
|
||||
(each: $value:ty) => {{
|
||||
let entries: Vec<(ProtoNodeIdentifier, NodeConstructor, NodeIOTypes)> = vec![
|
||||
async_node!(identifier: graphene_core::memo::memoize::IDENTIFIER, graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => $value]),
|
||||
async_node!(identifier: graphene_core::memo::monitor::IDENTIFIER, graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => $value]),
|
||||
async_node!(identifier: graphene_core::context_modification::context_modification::IDENTIFIER, graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => $value, Context => Item<graphene_std::ContextModification>]),
|
||||
];
|
||||
entries
|
||||
@@ -487,6 +451,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -544,6 +509,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -572,6 +538,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_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_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
@@ -55,11 +56,6 @@ pub trait Node<Input: ?Sized> {
|
||||
fn node_name(&self) -> &'static str {
|
||||
std::any::type_name::<Self>()
|
||||
}
|
||||
/// Serialize the node which is used for the `introspect` function which can retrieve values from monitor nodes.
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
log::warn!("Node::serialize not implemented for {}", std::any::type_name::<Self>());
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
mod types;
|
||||
@@ -107,9 +103,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for &N {
|
||||
fn node_name(&self) -> &'static str {
|
||||
(**self).node_name()
|
||||
}
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
}
|
||||
impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for Box<N> {
|
||||
type Output = N::Output;
|
||||
@@ -120,9 +113,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for Box<N> {
|
||||
fn node_name(&self) -> &'static str {
|
||||
(**self).node_name()
|
||||
}
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
}
|
||||
impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for std::sync::Arc<N> {
|
||||
type Output = N::Output;
|
||||
@@ -133,9 +123,6 @@ impl<I: ?Sized, N: Node<I> + ?Sized> Node<I> for std::sync::Arc<N> {
|
||||
fn node_name(&self) -> &'static str {
|
||||
(**self).node_name()
|
||||
}
|
||||
fn serialize(&self) -> Option<std::sync::Arc<dyn std::any::Any + Send + Sync>> {
|
||||
(**self).serialize()
|
||||
}
|
||||
}
|
||||
|
||||
/// A compile-time symbol naming one parameter of one proto node.
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial 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 `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -4,13 +4,6 @@ use std::hash::{Hash, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Stores both what a node was called with and what it returned.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct IORecord<I, O> {
|
||||
pub input: I,
|
||||
pub output: O,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MemoHash<T: CacheHash> {
|
||||
hash: u64,
|
||||
|
||||
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user