Compare commits

..
Author SHA1 Message Date
Timon 709d8c0c67 Desktop: Register supported mimetypes on Linux 2026-10-28 21:38:34 +00:00
326 changed files with 8437 additions and 25734 deletions

No files matched your search

+2 -2
View File
@@ -1,2 +1,2 @@
https://github.com/Keavon/graphite-branded-assets/archive/60d4f11cdd8b483f65c1c9f6d4fb1344b878e9b0.tar.gz
4ac444388551feef482f469a2c4e86de2a39bfd4a859b144e51a6c1a1be5fd60
https://github.com/Keavon/graphite-branded-assets/archive/f6a8460b0e85d05bb93a9536dc3d6ed6cc331178.tar.gz
6e8ea35b8fe9f7a371c5c2570259c0e0be8a52cbdfa747551874724b0c58a576
+11 -26
View File
@@ -47,24 +47,20 @@ on:
jobs:
web:
if: github.event_name == 'push' || inputs.web
# Fork code always runs on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
runs-on: [self-hosted, target/wasm]
permissions:
contents: write
deployments: write
pull-requests: write
env:
CARGO_TERM_COLOR: always
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
RUSTC_WRAPPER: sccache
SCCACHE_GHA_ENABLED: "true"
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
# NOTICE: keep these tool versions in sync with the other jobs in this file, `check.yml` (sccache), `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
SCCACHE_VERSION: "v0.19.0"
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend and Binaryen
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
# NOTICE: keep these tool versions in sync with the other jobs in this file, `.devcontainer/devcontainer.json`, `.nix/dev.nix` and `.nix/pkgs/graphite.nix` (wasm-bindgen-cli), `tools/cargo-run/src/requirements.rs` (wasm-bindgen-cli, cargo-about), `tools/cargo-run/src/requirements/wasm_opt.rs` (Binaryen), and the `wasm-bindgen` crate in `Cargo.toml`
WASM_BINDGEN_CLI_VERSION: "0.2.127"
BINARYEN_VERSION: "130"
CARGO_ABOUT_VERSION: "0.9.2"
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -86,12 +82,7 @@ jobs:
rustflags: ""
target: wasm32-unknown-unknown
- name: 📦 Install sccache
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
with:
version: ${{ env.SCCACHE_VERSION }}
- name: 🚧 Install wasm-bindgen-cli, Binaryen wasm-opt, and cargo-about
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
run: |
# Extracts into a temporary folder first so a cancelled download can't leave a truncated binary that later runs mistake for a finished install
install_release_archive() {
@@ -116,12 +107,6 @@ jobs:
fi
echo "$BINARYEN_DIR/bin" >> "$GITHUB_PATH"
CARGO_ABOUT_DIR="$HOME/.cache/cargo-about-$CARGO_ABOUT_VERSION"
if [ ! -x "$CARGO_ABOUT_DIR/cargo-about" ]; then
install_release_archive "https://github.com/EmbarkStudios/cargo-about/releases/download/$CARGO_ABOUT_VERSION/cargo-about-$CARGO_ABOUT_VERSION-x86_64-unknown-linux-musl.tar.gz" "$CARGO_ABOUT_DIR"
fi
echo "$CARGO_ABOUT_DIR" >> "$GITHUB_PATH"
- name: 🔀 Choose production deployment environment and insert template
id: production-env
if: github.event_name == 'push'
@@ -142,7 +127,7 @@ jobs:
NODE_ENV: production
# Split the Wasm binary to fit Cloudflare Pages' file size limit (see `wasmSplitting` in `frontend/vite.config.ts`)
SPLIT_WASM: "1"
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
run: mold -run cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false
@@ -314,7 +299,7 @@ jobs:
cd frontend
npm run check
# A job of its own so its native compile doesn't delay the web build and deploy
# Runs on a GitHub-hosted runner to keep the self-hosted one free for web builds
code-docs:
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
runs-on: ubuntu-latest
@@ -340,7 +325,7 @@ jobs:
windows:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.windows
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'windows-latest' || vars.WINDOWS_RUNNER || 'windows-latest' }}
runs-on: windows-latest
permissions:
contents: read
id-token: write
@@ -550,7 +535,7 @@ jobs:
mac:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.mac
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'macos-latest' || vars.MACOS_RUNNER || 'macos-latest' }}
runs-on: macos-latest
permissions:
contents: read
pull-requests: write
@@ -756,7 +741,7 @@ jobs:
linux:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
+9 -23
View File
@@ -3,14 +3,10 @@ name: "Check"
on:
pull_request: {}
merge_group: {}
# Checking each master commit also fills the compilation cache, which only master pushes may write to
push:
branches:
- master
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
# Cancel a PR's in-progress checks once a newer commit is pushed to it (merge queue refs are unique per entry, so those never cancel each other)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
env:
@@ -115,8 +111,7 @@ jobs:
needs: skip-check
# Always called with the skip decision passed in, since a skipped caller job reports only as `build` and leaves the required `build / web` check missing.
# Like the jobs below, the checks still run if `skip-check` itself fails, since a skipped job counts as passing for required checks.
# Master pushes are left out because `build.yml` builds and deploys those itself.
if: ${{ !cancelled() && github.event_name != 'push' }}
if: ${{ !cancelled() }}
uses: ./.github/workflows/build.yml
# The called workflow's jobs can only narrow these, so this grants the union of what they request
permissions:
@@ -130,22 +125,18 @@ jobs:
web: ${{ needs.skip-check.outputs.skip != 'true' }}
merge_queue: ${{ github.event_name == 'merge_group' }}
# Run the Rust tests
# Run the Rust tests on the self-hosted native runner
test:
needs: skip-check
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
# Fork PRs always run on GitHub's own runners, while the `LINUX_RUNNER` repo variable can point the rest at another provider
runs-on: ${{ github.event.pull_request.head.repo.fork && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
runs-on: [self-hosted, target/native]
permissions:
contents: read
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 0
RUSTC_WRAPPER: sccache
SCCACHE_GHA_ENABLED: "true"
# Only master pushes write to the compilation cache, so unmerged code can't plant entries that later master builds reuse
SCCACHE_GHA_RW_MODE: ${{ (github.event_name == 'push' && github.ref == 'refs/heads/master') && 'READ_WRITE' || 'READ_ONLY' }}
# NOTICE: keep in sync with the web job in `build.yml`
SCCACHE_VERSION: "v0.19.0"
# sccache deletes the oldest files in its folder once past its size cap, so it gets a folder apart from rust-gpu's codegen backend
SCCACHE_DIR: /var/lib/github-actions/.cache/sccache
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -158,11 +149,6 @@ jobs:
cache: false
rustflags: ""
- name: 📦 Install sccache
uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
with:
version: ${{ env.SCCACHE_VERSION }}
- name: 🦀 Fetch Rust dependencies
run: cargo fetch --locked
@@ -170,7 +156,7 @@ jobs:
env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: cargo test --all-features
run: mold -run cargo test --all-features
# Rust format check on GitHub runner
rust-fmt:
+45
View File
@@ -0,0 +1,45 @@
name: "Provide Shaders"
on:
push:
branches:
- master
workflow_dispatch: {}
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
- name: ❄ Install Nix
uses: DeterminateSystems/nix-installer-action@3138316df39ed29be04236d7ffc686fa525866aa # v23
with:
extra-conf: |
extra-substituters = https://graphite.cachix.org https://graphite-dev.cachix.org
extra-trusted-public-keys = graphite.cachix.org-1:B7Il1yMpkquN/dXM+5GRmz+4Xmu2aaCS1GcWNfFhsOo= graphite-dev.cachix.org-1:RppXYpiV1qO2TYKTkXXGHsAEQDOB5G51b3VlrN9QmbI=
- name: 🏗 Build graphene raster nodes shaders
run: nix build .#graphite-raster-nodes-shaders && cp result raster_nodes_shaders_entrypoint.wgsl
- name: 📤 Upload graphene raster nodes shaders to artifacts repository
run: |
bash .github/workflows/scripts/artifact-upload.bash \
${{ vars.ARTIFACTS_REPO_OWNER }} \
${{ vars.ARTIFACTS_REPO_NAME }} \
${{ vars.ARTIFACTS_REPO_BRANCH }} \
rev/${{ github.sha }}/raster_nodes_shaders_entrypoint.wgsl \
raster_nodes_shaders_entrypoint.wgsl \
"${{ github.sha }} raster_nodes_shaders_entrypoint.wgsl" \
${{ secrets.ARTIFACTS_REPO_TOKEN }}
- name: 📤 Push shaders to dev Nix cache
env:
NIX_CACHE_AUTH_TOKEN: ${{ secrets.NIX_CACHE_AUTH_TOKEN_DEV }}
NIX_CACHE_NAME: graphite-dev
run: |
nix run nixpkgs#cachix -- authtoken $NIX_CACHE_AUTH_TOKEN
nix build .#graphite-raster-nodes-shaders --no-link --print-out-paths | nix run nixpkgs#cachix -- push $NIX_CACHE_NAME
@@ -0,0 +1,89 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
cat <<EOF
Usage: $0 <owner> <repo> <branch> <target-path> <artifact-file> <commit-message> <github-token>
Arguments:
owner : GitHub user or organization of the target repo
repo : Target repo name
branch : Branch name (e.g. main)
target-path : Full path (including folders + filename) in the target repo where to upload
artifact-file : Local file path to upload
commit-message : Commit message for creating/updating the file
github-token : GitHub token (PAT or equivalent) with write access to the target repo
This will perform a GitHub API PUT to /repos/{owner}/{repo}/contents/{target-path}.
If a file already exists at that path, it will auto-detect the SHA and update; otherwise it will create a new one.
EOF
exit 1
}
if [ $# -ne 7 ]; then
usage
fi
OWNER="$1"
REPO="$2"
BRANCH="$3"
TARGET_PATH="$4"
ARTIFACT_PATH="$5"
COMMIT_MSG="$6"
TOKEN="$7"
if [ ! -f "$ARTIFACT_PATH" ]; then
echo "Error: artifact file not found: $ARTIFACT_PATH" >&2
exit 1
fi
LOCAL_SHA=$(git hash-object "$ARTIFACT_PATH")
echo "Local blob SHA: $LOCAL_SHA"
GET_URL="https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}?ref=${BRANCH}"
GET_RESPONSE=$(curl -s -H "Authorization: token ${TOKEN}" "$GET_URL")
REMOTE_SHA=$(echo "$GET_RESPONSE" | jq -r .sha 2>/dev/null || echo "")
if [ "$REMOTE_SHA" != "null" ] && [ -n "$REMOTE_SHA" ]; then
echo "Remote blob SHA: $REMOTE_SHA"
if [ "$LOCAL_SHA" = "$REMOTE_SHA" ]; then
echo "The remote file is identical. Skipping upload."
exit 0
else
echo "Remote file differs. Preparing to upload."
fi
else
echo "No existing remote file or no SHA found. Creating."
fi
CONTENT_TMP_BASE64=$(mktemp)
if base64 --help 2>&1 | grep -q -- "-w"; then
base64 -w 0 "$ARTIFACT_PATH" > "$CONTENT_TMP_BASE64"
else
base64 "$ARTIFACT_PATH" | tr -d '\n' > "$CONTENT_TMP_BASE64"
fi
PAYLOAD_TMP=$(mktemp)
jq -n \
--arg message "$COMMIT_MSG" \
--arg branch "$BRANCH" \
--arg sha "$REMOTE_SHA" \
--rawfile content "$CONTENT_TMP_BASE64" \
'{
message: $message,
content: $content,
branch: $branch
} + (if ($sha != "" and $sha != "null") then { sha: $sha } else {} end)' \
> "$PAYLOAD_TMP"
UPLOAD_RESPONSE=$(curl -s -X PUT \
-H "Authorization: token ${TOKEN}" \
-H "Content-Type: application/json" \
-d @"$PAYLOAD_TMP" \
"https://api.github.com/repos/${OWNER}/${REPO}/contents/${TARGET_PATH}")
echo "Upload Response:"
echo "$UPLOAD_RESPONSE"
rm -f "$CONTENT_TMP_BASE64" "$PAYLOAD_TMP"
+2 -1
View File
@@ -31,7 +31,7 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
cargoAbout = lib.call ./deps/cargo-about.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
};
args = {
@@ -56,6 +56,7 @@ in
default = graphite;
graphite = (lib.call ./pkgs/graphite.nix) { };
graphite-dev = (lib.call ./pkgs/graphite.nix) { dev = true; };
graphite-raster-nodes-shaders = lib.call ./pkgs/graphite-raster-nodes-shaders.nix;
graphite-branding = lib.call ./pkgs/graphite-branding.nix;
graphite-bundle = (lib.call ./pkgs/graphite-bundle.nix) { };
graphite-bundle-dev = (lib.call ./pkgs/graphite-bundle.nix) { graphite = graphite-dev; };
-18
View File
@@ -1,18 +0,0 @@
# TODO: Remove once nixpkgs ships cargo-about >= 0.9.3, and switch back to `pkgs.cargo-about`
{ pkgs, ... }:
pkgs.cargo-about.overrideAttrs (
finalAttrs: _: {
version = "0.9.3";
src = pkgs.fetchFromGitHub {
owner = "EmbarkStudios";
repo = "cargo-about";
tag = finalAttrs.version;
hash = "sha256-Jlr4TYNZkzYo5V77n0YYrx1e8m17ELN/1+ZcR/Bl0K4=";
};
cargoDeps = pkgs.rustPlatform.fetchCargoVendor {
inherit (finalAttrs) pname version src;
hash = "sha256-kNGfQQumgvtDPhiQcqc9K2ohhEsTzuySeisHcNcmig8=";
};
}
)
+55
View File
@@ -0,0 +1,55 @@
{ pkgs, ... }:
let
toolchain = pkgs.rust-bin.nightly."2026-07-03".default.override {
extensions = [
"rust-src"
"rust-analyzer"
"clippy"
"cargo"
"rustc-dev"
"llvm-tools"
];
};
cargo = pkgs.writeShellScriptBin "cargo" ''
#!${pkgs.lib.getExe pkgs.bash}
filtered_args=()
for arg in "$@"; do
case "$arg" in
+nightly|+nightly-*) ;;
*) filtered_args+=("$arg") ;;
esac
done
exec ${toolchain}/bin/cargo ${"\${filtered_args[@]}"}
'';
rustc_codegen_spirv =
(pkgs.makeRustPlatform {
cargo = toolchain;
rustc = toolchain;
}).buildRustPackage
(finalAttrs: {
pname = "rustc_codegen_spirv";
version = "0.10.0";
src = pkgs.fetchCrate {
inherit (finalAttrs) pname version;
sha256 = "sha256-QluNI2TdJI0j2CBOeAbB9DfOv+8LqzWk7siZyT1WWLU=";
};
cargoHash = "sha256-vvviUccnip+j60Ml1vqLNJ49KyEF40VLUoV1TMALHMs=";
cargoBuildFlags = [
"-p"
"rustc_codegen_spirv"
"--features=use-compiled-tools"
"--no-default-features"
];
doCheck = false;
});
in
{
toolchain = toolchain;
env = {
RUST_GPU_PATH_OVERRIDE = "${cargo}/bin:${toolchain}/bin";
RUSTC_CODEGEN_SPIRV_PATH = "${rustc_codegen_spirv}/lib/librustc_codegen_spirv.so";
};
}
+3 -7
View File
@@ -23,7 +23,7 @@ let
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.cargo-about
pkgs.rustc
pkgs.cargo
@@ -47,17 +47,13 @@ let
# Plotting tools
pkgs.graphviz
];
libs = [
pkgs.vulkan-loader
];
env = {
VK_ADD_DRIVER_FILES = "${pkgs.mesa}/share/vulkan/icd.d/lvp_icd.${pkgs.stdenv.hostPlatform.uname.processor}.json";
};
}
deps.rustGPU
(lib.optionalAttrs desktop (
{
libs = [
pkgs.wayland
pkgs.vulkan-loader
pkgs.libGL
pkgs.libxkbcommon
self.packages.${system}.graphite-cef
@@ -0,0 +1,28 @@
{
info,
deps,
self,
system,
...
}:
(deps.crane.lib.overrideToolchain (_: deps.rustGPU.toolchain)).buildPackage {
pname = "graphite-raster-nodes-shaders";
inherit (info) version src;
inherit (self.packages.${system}.graphite) cargoVendorDir cargoArtifacts;
strictDeps = true;
env = deps.rustGPU.env;
buildPhase = ''
cargo build -r -p raster-nodes-shaders
'';
installPhase = ''
cp target/spirv-builder/spirv-unknown-naga-wgsl/release/deps/raster_nodes_shaders_entrypoint.wgsl $out
'';
doCheck = false;
}
+3 -1
View File
@@ -35,6 +35,7 @@ let
inherit (deps.crane.lib.findCargoFiles (deps.crane.lib.cleanCargoSource info.src)) cargoConfigs;
cargoLockList = [
"${info.src}/Cargo.lock"
"${deps.rustGPU.toolchain.availableComponents.rust-src}/lib/rustlib/src/rust/library/Cargo.lock"
];
}
);
@@ -84,7 +85,7 @@ deps.crane.lib.buildPackage (
pkgs.nodejs
pkgs.binaryen
pkgs.wasm-bindgen-cli_0_2_127
deps.cargoAbout
pkgs.cargo-about
pkgs.removeReferencesTo
pkgs.importNpmLock.npmConfigHook
];
@@ -96,6 +97,7 @@ deps.crane.lib.buildPackage (
makeCacheWritable = true;
env = {
RASTER_NODES_SHADER_PATH = self.packages.${system}.graphite-raster-nodes-shaders;
GRAPHITE_GIT_COMMIT_HASH = self.rev or "unknown";
GRAPHITE_GIT_COMMIT_DATE = self.lastModified or "unknown";
CEF_PATH = "${self.packages.${system}.graphite-cef}/lib";
Generated
+407 -81
View File
File diff suppressed because it is too large. Load diff
+16 -5
View File
@@ -22,6 +22,8 @@ members = [
"node-graph/libraries/graphene-hash",
"node-graph/libraries/*",
"node-graph/nodes/*",
"node-graph/nodes/raster/shaders",
"node-graph/nodes/raster/shaders/entrypoint",
"node-graph/graph-craft",
"node-graph/graphene-cli",
"node-graph/nodes/gstd",
@@ -81,10 +83,10 @@ graphene-application-io = { path = "node-graph/libraries/application-io" }
graphene-resource = { path = "node-graph/libraries/resources" }
graphene-animation = { path = "node-graph/libraries/animation" }
core-types = { path = "node-graph/libraries/core-types" }
no-std-types = { path = "node-graph/libraries/no-std-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" }
@@ -153,6 +155,7 @@ wgpu = { version = "30.0", default-features = false, features = [
"webgl",
# We don't have wgpu on multiple threads (yet) https://github.com/gfx-rs/wgpu/blob/trunk/CHANGELOG.md#wgpu-types-now-send-sync-on-wasm
"fragile-send-sync-non-atomic-wasm",
"spirv",
"strict_asserts",
] }
once_cell = "1.13" # Remove and replace with `core::cell::LazyCell` (<https://doc.rust-lang.org/core/cell/struct.LazyCell.html>)
@@ -242,6 +245,7 @@ tinyvec = { version = "1", features = ["std"] }
criterion = { version = "0.7", features = ["html_reports"] }
gungraun = { version = "0.18" }
ndarray = "0.16"
strum = { version = "0.27", features = ["derive"] }
dirs = "6.0"
cef = "156"
cef-dll-sys = "156"
@@ -252,6 +256,11 @@ rfd = "0.17"
open = "5.3"
spin = "0.10"
clap = "4.5"
# Ensure these are kept in sync with .nix/deps/rust-gpu.nix
spirv-std = { version = "0.10.0", features = ["bytemuck"] }
cargo-gpu-install = { version = "0.10.0", default-features = false }
qrcodegen = "1.8"
lzma-rust2 = { version = "0.16", default-features = false, features = ["std", "encoder", "optimization", "xz"] }
scraper = "0.25"
@@ -259,12 +268,14 @@ linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints]
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[profile.dev]
opt-level = 1
[profile.dev.package]
no-std-types = { opt-level = 1 }
core-types= { opt-level = 1 }
interpreted-executor = { opt-level = 1 } # This is a mitigation for https://github.com/rustwasm/wasm-pack/issues/981 which is needed because the node_registry function is too large
graphite-proc-macros = { opt-level = 1 }
@@ -281,6 +292,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 = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "7306bb4f206d956a8989173237c406b1d7798b35" }
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[1789832635968548900,{"inputs":[{"Node":{"node_id":1924303400883620400,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.9822506,"green":0.20507872,"blue":0.012983031,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.25,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":3143874172491239000,"output_index":0}}],"nodes":[[26023588519449590,{"inputs":[{"Node":{"node_id":4002029424845293600,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.94750905,"green":0.5567761,"blue":0.06654528,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true},{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[0.0,-92.53735521402166,92.53735521402166,0.0,9.606221358397944,-69.72678572415595]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[213744308682803360,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":10463288500489480000,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[366962978353611840,{"inputs":[{"Node":{"node_id":8366826746721323000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[799182088624980700,{"inputs":[{"Node":{"node_id":7386572856931342000,"output_index":0}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"math_nodes::DivideNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1250460246919467000,{"inputs":[{"Node":{"node_id":4742778578215475000,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Union"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplicationLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[322234583139821148,{"inputs":[{"Node":{"node_id":6589978257209505606,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[-261.2435565297001,-70.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"trLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":15709488322180832347,"output_index":0}}],"nodes":[[57904581517036791,{"inputs":[{"Node":{"node_id":9393309733761233513,"output_index":0}},{"Node":{"node_id":15300421479077882117,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[70804263053697201,{"inputs":[{"Node":{"node_id":13942787566051910019,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[3.410605131648481e-13,3.410605131648481e-13]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1268.999999999999,634.9999999999992]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[194878846429432339,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4],"remove":[],"delta":[[1,[671.7691453623979,420.00000000000006]],[2,[559.8076211353317,450.0000000000001]],[3,[410.5255888325765,410.0]],[4,[522.4871130596428,380.00000000000006]]]},"segments":{"add":[1,2,3,4],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4]],"end_point":[[1,2],[2,3],[3,4],[4,1]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplicLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false}],[4388711862172196665,{"inputs":[{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}},{"Scope":"raster_nodes::raster_kernel::RasterKernelPipelineNode"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}]Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":12241147352993594415,"output_index":0}}],"nodes":[[80924370013313595,{"inputs":[{"Node":{"node_id":6029481207635803402,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.06469504,"green":0.0,"blue":0.0755814,"alpha":1.0,"linear":true},{"red":0.016644126,"green":0.13212071,"blue":0.62523156,"alpha":1.0,"linear":true},{"red":1.0,"green":0.8708812,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.30054384,"green":0.8468733,"blue":0.8468733,"alpha":0.01,"linear":true}],"position":[0.0,0.12704918032786883,0.5,1.0],"midpoint":[0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3606681156406984991,{"inputs":[{"Node":{"node_id":6323350524796370485,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":0.04631017,"green":0.0,"blue":0.0076861563,"alpha":1.0,"linear":true},{"red":0.83939683,"green":0.7249875,"blue":0.27055356,"alpha":1.0,"linear":true},{"red":0.025397457,"green":0.3485102,"blue":0.3485102,"alpha":1.0,"linear":true},{"red":0.01102731,"green":0.09231063,"blue":0.09231063,"alpha":1.0,"linear":true}],"position":[0.0,0.3237704918032787,0.5655737704918032,0.8155737704918032,1.0],"midpoint":[0.5,0.5,0.5,0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::adjustments::GradientMapNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4388711862172196665,{"inputs":[],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::MandelbrotNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6029481207635803402,{"inputs":[{"Node":{"node_id":4388711862172196665,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1000.0,1000.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[6323350524796370485,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"Integer":0},"exposed":false}},{"Value":{"tagged_value":{"Number":35.0},"exposed":false}},{"Value":{"tagged_value":{"NoiseType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"DomainWarpType":"OpenSimplex2"},"exposed":false}},{"Value":{"tagged_value":{"Number":100.0},"exposed":false}},{"Value":{"tagged_value":{"FractalType":"PingPong"},"exposed":false}},{"Value":{"tagged_value":{"Integer":3},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"Number":0.5},"exposed":false}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"Number":2.0},"exposed":false}},{"Value":{"tagged_value":{"CellularDistanceFunction":"Hybrid"},"exposed":false}},{"Value":{"tagged_value":{"CellularReturnType":"CellValue"},"exposed":false}},{"Value":{"tagged_value":{"Number":1.0},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"raster_nodes::std_nodes::NoisePatternNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"FOOTPRINT","inject":""}}],[6565638614909771142,{"inputs":[{"Node":{"node_id":7624113397561636853,"output_index":0}},{"Node":{"node_id":80924370013313595,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"GeLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}]},"import_index":0}},{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_dedLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":392274448837115448,"output_index":0}}],"nodes":[[57390435731316553,{"inputs":[{"Node":{"node_id":8460565235419043665,"output_index":0}},{"Node":{"node_id":13838011362258067867,"output_index":0}},{"Value":{"tagged_value":{"Number":0.0},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1.0,1.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"transform_nodes::transform_nodes::TransformNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[140396870212231820,{"inputs":[{"Node":{"node_id":18095952297474762348,"output_index":0}},{"Value":{"tagged_value":{"BooleanOperation":"Intersect"},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"path_bool_nodes::BooleanOperationNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[294265135510952894,{"inputs":[{"Node":{"node_id":11264395591110193456,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.83076996,"green":0.32314324,"blue":0.027320892,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.6938719,"green":0.048171822,"blue":0.028426038,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[20.0,0.0,0.0,20.0,-10.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[392274448837115448,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::artboard::Artboard"}}}},"exposed":true}},{"Node":{"node_id":6787585796949551500,"output_index":0}},{"Value":{"tagged_value":{"DVec2":[0.0,0.0]},"exposed":false}},{"Value":{"tagged_value":{"DVec2":[1536.0,768.0]},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.8549927,"green":0.71569365,"blue":0.48514998,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":4,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"Generic":"T"}]},"import_index":1}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":2}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":3}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":4}},{"Import":{"import_type":{"Item":{"Concrete":{"name":"graph_craft::document::value::TaggedValue"}}},"import_index":5}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::artboard::CreateArtboardNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":1,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Import":{"import_type":{"Fn":[{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},{"List":{"Concrete":{"nameLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[2288754089236120499,{"inputs":[{"Node":{"node_id":14158287945315818946,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"core_types::vector::SplineNode"}},"visible":true,"skip_deduplication":false}],[7828034197076821310,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":3}}],"call_argument":{"Concrete":{"name":"core::option::Option<Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":4445985685181725042,"output_index":0}}],"nodes":[[239716716021064150,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"List":{"Concrete":{"name":"graphic_types::graphic::Graphic"}}}},"exposed":true}},{"Node":{"node_id":7711570794020903773,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1801066723091712434,{"inputs":[{"Value":{"tagged_value":"None","exposed":true}},{"Value":{"tagged_value":{"Color":{"red":0.036889445,"green":0.038204364,"blue":0.043735027,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Number":1744.31393592},"exposed":false}},{"Value":{"tagged_value":{"Number":63.0},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":2288754089236120499,"output_index":0}}],"nodes":[[640915213983348287,{"inputs":[{"Value":{"tagged_value":"None","exposed":false}},{"Value":{"tagged_value":{"Number":4000.0},"exposed":false}},{"Value":{"tagged_value":{"Number":500.0},"exposed":false}},{"Value":{"tagged_value":{"BoxCorners":[0.0]},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"vector_nodes::generator_nodes::RectangleNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1791308547102433540,{"inputs":[{"Node":{"node_id":640915213983348287,"output_index":0}},{"Import":{"import_type":{"Generic":"T"},"import_index":1}},{"Value":{"tagged_value":{"Color":{"red":0.9911022,"green":0.6514057,"blue":0.39157256,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":false},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[1.0,0.0,0.0,1.0,0.0,0.0]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2288754089236120499,{"inputs":[{"Node":{"node_id":1415828794531Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":14972365039974885000,"output_index":0}}],"nodes":[[169695252050218443,{"inputs":[{"Node":{"node_id":13907401402762847509,"output_index":0}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.75,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.7734375,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":0.01,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Radial"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[31.55635094002563,-2.7755575615628914e-17,2.7755575615628914e-17,31.55635094002563,-0.225779263556106,34.981204988590605]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[183562335973647870,{"inputs":[{"Node":{"node_id":4248875763694880300,"output_index":0}},{"Node":{"node_id":2181148486404191200,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[655907162126315400,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5,6,7,8,9,10,11],"remove":[],"delta":[[1,[416.0,270.9999999999999]],[2,[587.0,291.9999999999999]],[3,[373.0,372.9999999999999]],[4,[484.0,446.9999999999999]],[5,[639.0,438.9999999999999]],[6,[495.0,533.9999999999999]],[7,[304.0,611.9999999999999]],[8,[475.0,671.9999999999999]],[9,[750.0,703.9999999999999]],[10,[455.0,824.9999999999999]],[11,[186.0,824.9999999999999]]]},"segments":{"add":[1,2,3,4,5,6,7,8,9,10],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5],[6,6],[7,7],[8,8],[9,9],[10,10]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,6],[6,7],[7,8],[8,9],[9,10],[10,11]],"handle_primary":[[1,[0.0,0.0]],[2,[0.0,0.0]],[3,[0.0,0.0]],[4,[0.0,0.0]],[5,[0.0,0.0]],[6,[0.0,0.0]],[7,[0.0,0.0]],[8,[0.0,0.0]],[9,[0.0,0.0]],[10,[0.0,0.0]]],"handle_end":Line truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[],"path_breaks":[1]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>Line truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":2394762731964337494,"output_index":0}}],"nodes":[[1378578509112405,{"inputs":[{"Value":{"tagged_value":{"TypeDefault":{"Item":{"Concrete":{"name":"vector_types::vector::vector_types::Vector"}}}},"exposed":true}},{"Value":{"tagged_value":{"VectorModification":{"points":{"add":[1,2,3,4,5],"remove":[],"delta":[[1,[602.6886145404666,50.91906721536352]],[2,[599.5281207133061,50.3923182441701]],[3,[590.4855967078191,66.80932784636488]],[4,[594.6410608139003,75.57872275567746]],[5,[593.3924706599604,60.59564090839812]]]},"segments":{"add":[1,2,3,4,5],"remove":[],"start_point":[[1,1],[2,2],[3,3],[4,4],[5,5]],"end_point":[[1,2],[2,3],[3,4],[4,5],[5,1]],"handle_primary":[[1,[0.0,0.0]],[2,[-1.843621399176982,0.5267489711934203]],[3,[1.9314128943758533,7.3257125438195345]],[4,[0.0,0.0]],[5,[1.248590153939972,-3.9798811156835896]]],"handle_end":[[1,[1.843621399176982,-0.5267489711934203]],[2,[-2.7532629181224593,-10.4429315732828]],[3,[0.0,0.0]],[4,[-1.704168058538812,5.432035686592322]],[5,[-4.379820149367788,0.9754610577655498]]]},"add_g1_continuous":[],"remove_g1_continuous":[]}},"exposed":false}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":1,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Import":{"import_type":{"Concrete":{"name":"vector_types::vector::vector_modification::VectorModification"}},"import_index":1}},{"Reflection":"DocumentNodePath"}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"vector_nodes::vector_modification_nodes::PathModifyNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[172538270105470471,{"inputs":[{"Node":{"node_id":9276497172451351253,"output_index":0}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"Color":{"red":0.78353786,"green":0.6038274,"blue":0.33245158,"alpha":1.0,"linear":true}},"exposed":false}},{"Value":{"tagged_value":{"GradientRamp":{"stops":{"color":[{"red":0.0,"green":0.0,"blue":0.0,"alpha":1.0,"linear":true},{"red":1.0,"green":1.0,"blue":1.0,"alpha":1.0,"linear":true}],"position":[0.0,1.0],"midpoint":[0.5,0.5]},"gradient_space":"RgbGamma"}},"exposed":false}},{"Value":{"tagged_value":{"GradientForm":"Linear"},"exposed":false}},{"Value":{"tagged_value":{"Bool":true},"exposed":false}},{"Value":{"tagged_value":{"DAffine2":[2.170365521878466,0.0,0.0,2.170365521878466,604.9565968314213,108.54930650815425]},"exposed":false}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::vector::FillNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[314278016428495768,{"inputs":[{"Node":{"node_id":6282972142629473139,"output_index":0}},{"Node":{"node_id":5020096817747898028,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpLine truncated
+1 -1
View File
@@ -1 +1 @@
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false}],[76,{"inputs":[{"Node":{"node_id":77,"output_index":0}},{"Node":{"node_id":16164610528699022118,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_dedupLine truncated
{"network_interface":{"network":{"exports":[{"Node":{"node_id":16815500381887058038,"output_index":0}}],"nodes":[[74,{"inputs":[{"Node":{"node_id":75,"output_index":0}},{"Node":{"node_id":81,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_injections":[]}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[75,{"inputs":[{"Node":{"node_id":76,"output_index":0}},{"Node":{"node_id":161,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"Network":{"exports":[{"Node":{"node_id":5,"output_index":0}}],"nodes":[[0,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::AsGraphicNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[1,{"inputs":[{"Import":{"import_type":{"Generic":"T"},"import_index":1}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::IntoGroupNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[2,{"inputs":[{"Reflection":"DocumentNodePath"}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::PathOfSubgraphNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[3,{"inputs":[{"Node":{"node_id":1,"output_index":0}},{"Value":{"tagged_value":{"String":"editor:layer_path"},"exposed":false}},{"Node":{"node_id":2,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::WriteAttributeNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}],[4,{"inputs":[{"Node":{"node_id":3,"output_index":0}}],"call_argument":{"Concrete":{"name":"core::option::Option<alloc::sync::Arc<core_types::context::OwnedContextImpl>>"}},"implementation":{"ProtoNode":{"name":"graphene_core::memo::MonitorNode"}},"visible":true,"skip_deduplication":true,"context_features":{"extract":"","inject":""}}],[5,{"inputs":[{"Node":{"node_id":0,"output_index":0}},{"Node":{"node_id":4,"output_index":0}}],"call_argument":{"Generic":"T"},"implementation":{"ProtoNode":{"name":"graphic_nodes::graphic::ExtendNode"}},"visible":true,"skip_deduplication":false,"context_features":{"extract":"","inject":""}}]],"scope_Line truncated
+1 -1
View File
@@ -187,7 +187,7 @@ allow-git = []
[sources.allow-org]
# 1 or more github.com organizations to allow git sources for
github = ["linebender"]
github = ["linebender", "Rust-GPU"]
# 1 or more gitlab.com organizations to allow git sources for
#gitlab = [""]
# 1 or more bitbucket.org organizations to allow git sources for
+2 -1
View File
@@ -2,10 +2,11 @@
Name=Graphite
GenericName=Vector & Raster Graphics Editor
Comment=Open-source vector & raster graphics editor. Featuring node based procedural nondestructive editing workflow.
Exec=graphite
Exec=graphite %F
Terminal=false
Type=Application
Icon=art.graphite.Graphite
Categories=Graphics;VectorGraphics;RasterGraphics;
MimeType=application/graphite+json;application/vnd.graphite.document;image/svg+xml;image/png;image/jpeg;image/gif;image/webp;image/bmp;image/tiff;
Keywords=graphite;editor;vector;raster;procedural;design;
StartupWMClass=art.graphite.Graphite
+1 -4
View File
@@ -111,10 +111,7 @@ impl App {
loop {
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let timeout = node_runtime.until_next_frame().unwrap_or(Duration::from_millis(10));
if start_render_receiver.recv_timeout(timeout).is_err() {
node_runtime.begin_frame();
}
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
if exiting_clone.load(Ordering::Relaxed) {
break;
}
+1 -1
View File
@@ -1,7 +1,7 @@
#[derive(clap::Parser)]
#[clap(name = "graphite", version)]
pub struct Cli {
#[arg(help = "Files to open on startup", value_parser = |path: &str| std::path::absolute(path))]
#[arg(help = "Files to open on startup")]
pub files: Vec<std::path::PathBuf>,
#[arg(long, action = clap::ArgAction::SetTrue, help = "Disable hardware accelerated UI rendering")]
+2 -2
View File
@@ -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<'static>>,
overlays_scene: Option<VelloSceneBuilder>,
#[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<'static>) {
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
self.surface_outdated = true;
self.overlays_scene = Some(scene);
}
+2 -1
View File
@@ -15,12 +15,13 @@ publish.workspace = true
workspace = true
[features]
gpu = ["graphite-editor/gpu"]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
[dependencies]
# Local dependencies
graphite-editor = { workspace = true }
graphite-wasm-wrapper = { path = "../../frontend/wrapper", default-features = false, features = ["editor"] }
graphene-std = { workspace = true }
graph-craft = { workspace = true }
wgpu-executor = { workspace = true }
+1 -2
View File
@@ -8,7 +8,6 @@ use graphite_editor::node_graph_executor::NodeRuntime;
use message_dispatcher::DesktopWrapperMessageDispatcher;
use messages::{DesktopFrontendMessage, DesktopWrapperMessage};
use std::sync::Arc;
use std::time::Instant;
pub use graph_craft::application_io::resource::MmapResourceStorage;
pub use graphite_editor::consts::{DOUBLE_CLICK_MILLISECONDS, FILE_EXTENSION};
@@ -64,7 +63,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_spawner(spawner)
.with_random_seed(random_seed)
.build();
+1 -1
View File
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
WindowUpdateDirectInput {
enabled: bool,
},
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
PersistenceUpdatePreferences {
preferences: Preferences,
},
+1 -9
View File
@@ -11,7 +11,7 @@ use graphene_resource::{LoadResource, Resource, ResourceHash};
use crate::error::Error;
use crate::layout::Layout;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
@@ -158,14 +158,6 @@ impl<L: Layout> Gdd<L> {
network_view_settings: self.network_view_settings.clone(),
};
sink.write_entry(&io::path_for(self.layout.session_basename(), codecs.session), &codecs.session.write_single(&session_state)?)?;
// The facts name revs, so a copy without the history carries none.
if options.include_history && !self.metadata.is_empty() {
let mut lines = Vec::new();
for fact in self.metadata.facts() {
METADATA_CODEC.append(&mut lines, fact)?;
}
sink.write_entry(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &lines)?;
}
let working_copy_hashes: std::collections::HashSet<ResourceHash> = self.resource_hashes().await?.into_iter().collect();
-9
View File
@@ -35,15 +35,6 @@ pub async fn iter<T: DeserializeOwned>(container: &AnyContainer, basename: &str,
Ok(codec.iter::<T>(bytes.as_slice()).collect::<Result<Vec<_>, _>>()?)
}
/// Same as [`iter`] but skips the values that fail to decode.
pub async fn iter_lenient<T: DeserializeOwned>(container: &AnyContainer, basename: &str, codec: Codec) -> Result<Vec<T>, ReadError> {
let bytes = read_bytes(container, basename, codec).await?;
let values = codec
.iter::<T>(bytes.as_slice())
.filter_map(|value| value.inspect_err(|error| log::warn!("Skipping an unreadable entry of {basename}: {error}")).ok());
Ok(values.collect())
}
/// Whether `{basename}.{ext}` exists for the given codec.
pub async fn exists(container: &AnyContainer, basename: &str, codec: Codec) -> bool {
container.exists(&path_for(basename, codec)).await
-4
View File
@@ -12,7 +12,6 @@ pub trait Layout {
fn registry_basename(&self) -> &str;
fn history_basename(&self) -> &str;
fn hot_log_basename(&self) -> &str;
fn metadata_basename(&self) -> &str;
fn resources_dir(&self) -> &str;
fn resource_path(&self, hash: &ResourceHash) -> String;
/// The embedded legacy `.graphite` document, stored verbatim during the dual-write soak so the
@@ -40,9 +39,6 @@ impl Layout for GddV1Layout {
fn hot_log_basename(&self) -> &str {
"hot-log"
}
fn metadata_basename(&self) -> &str {
"metadata"
}
fn resources_dir(&self) -> &str {
"resources"
}
+1 -11
View File
@@ -16,7 +16,7 @@ use document_container::backends::folder::FolderBackend;
use document_container::{AnyContainer, AsyncContainer, ByteHolder};
#[cfg(feature = "conversion")]
use document_graph_storage::{CommitError, NodeMetadataSource};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -52,8 +52,6 @@ pub const MANIFEST_CODEC: Codec = Codec::Json;
/// want a diffable on-disk representation. Recorded in the manifest at create time and read back on
/// open (see [`manifest::PayloadCodecs`]), so the persist path never probes the filesystem.
pub const DEFAULT_SESSION_CODEC: Codec = Codec::Json;
/// One fact per line, so recording one only appends.
pub const METADATA_CODEC: Codec = Codec::JsonLines;
pub const DEFAULT_REGISTRY_CODEC: Codec = Codec::Postcard;
pub const DEFAULT_HISTORY_CODEC: Codec = Codec::PostcardFrames;
pub const DEFAULT_HOT_LOG_CODEC: Codec = Codec::PostcardFrames;
@@ -77,8 +75,6 @@ pub struct Gdd<L: Layout = GddV1Layout> {
/// per-payload codecs so the persist path never probes the filesystem, keeping it fully read-free
/// and synchronous.
pub(crate) manifest: Manifest,
/// See [`HistoryMetadata`].
pub(crate) metadata: HistoryMetadata,
/// Per-peer view settings (PTZ, rulers, etc.), persisted in `session.json` not the registry, so
/// they stay out of the CRDT/history. Opaque to the storage layer; the editor owns the keys/values.
pub(crate) view_settings: std::collections::BTreeMap<String, document_graph_storage::Value>,
@@ -140,10 +136,6 @@ impl<L: Layout> Gdd<L> {
true => io::read_single(&working, layout.session_basename(), codecs.session).await?,
false => SessionState::default(),
};
let metadata = match io::exists(&working, layout.metadata_basename(), METADATA_CODEC).await {
true => HistoryMetadata::fold(io::iter_lenient(&working, layout.metadata_basename(), METADATA_CODEC).await?),
false => HistoryMetadata::default(),
};
let has_registry = io::exists(&working, layout.registry_basename(), codecs.registry).await;
let has_history = io::exists(&working, layout.history_basename(), codecs.history).await;
@@ -181,7 +173,6 @@ impl<L: Layout> Gdd<L> {
layout,
manifest,
view_settings: session_state.view_settings,
metadata,
network_view_settings: session_state.network_view_settings,
})
}
@@ -208,7 +199,6 @@ impl<L: Layout> Gdd<L> {
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
metadata: HistoryMetadata::default(),
network_view_settings: std::collections::BTreeMap::new(),
})
}
+2 -21
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HistoryMetadata, HotOp, Rev, Subject, TimeStamp, Value, WallStamp};
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
#[cfg(feature = "conversion")]
use graphene_resource::ResourceStorage;
@@ -14,7 +14,7 @@ use crate::error::Error;
use crate::layout::Layout;
use crate::manifest::Manifest;
use crate::session_state::SessionState;
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
use crate::{Gdd, MANIFEST_CODEC, io};
impl<L: Layout> Gdd<L> {
/// Move the undo cursor back one commit (silent-zone reflog undo) and persist the new cursor. Returns
@@ -182,25 +182,6 @@ impl<L: Layout> Gdd<L> {
Ok(())
}
pub fn metadata(&self) -> &HistoryMetadata {
&self.metadata
}
/// State a fact at wall time `wall_ms`, taken on only once it is on disk. Returns whether it changed anything.
pub fn record(&mut self, subject: Subject, key: &str, value: serde_json::Value, wall_ms: f64) -> Result<bool, Error> {
let stamp = WallStamp {
ms: wall_ms as u64,
peer: self.session.peer(),
};
let Some(fact) = self.metadata.statement(subject, key, value, stamp) else { return Ok(false) };
// The leading newline keeps the fact off a tail a crash left unterminated. Reading skips the blank lines this leaves.
let mut line = vec![b'\n'];
METADATA_CODEC.append(&mut line, &fact)?;
self.working.append_non_blocking(&io::path_for(self.layout.metadata_basename(), METADATA_CODEC), &line)?;
self.metadata.absorb(fact);
Ok(true)
}
/// Rewrite the entire history file from the in-memory session. `history()` yields deltas in
/// topological (append) order, which is a valid replay order, so no separate sort is needed.
fn rewrite_history(&mut self) -> Result<(), Error> {
-62
View File
@@ -1,62 +0,0 @@
use document_container::backends::memory::MemoryBackend;
use document_container::{AnyContainer, AsyncContainer};
use document_format::{GddV1, GddV1Layout, Layout};
use document_graph_storage::{PeerId, Rev, Subject, UserId, rev_attr, user_attr};
const NOW_MS: f64 = 1_700_000_000_000.;
const ADA: Subject = Subject::User(UserId(10));
fn document_naming_ada() -> GddV1 {
let mut gdd = GddV1::create_in(AnyContainer::Memory(MemoryBackend::new()), GddV1Layout, PeerId(1), 1, "editor".into(), "stdlib".into()).expect("create");
assert!(gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS).expect("record"));
gdd
}
#[test]
fn recorded_facts_survive_a_reopen() {
futures::executor::block_on(async {
let mut gdd = document_naming_ada();
assert!(!gdd.record(ADA, user_attr::NAME, "Ada".into(), NOW_MS + 1.).expect("record"), "the same name is no change");
let step = Rev::new(7).expect("non-zero");
gdd.record(Subject::Rev(step), rev_attr::LABEL, "Fixed the eye".into(), NOW_MS).expect("record");
let (working, layout) = gdd.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
assert_eq!(reopened.metadata().rev_label(step), Some("Fixed the eye"));
});
}
#[cfg(all(feature = "conversion", feature = "zip"))]
#[test]
fn an_export_carries_the_metadata_only_with_the_history() {
futures::executor::block_on(async {
let gdd = document_naming_ada();
let byte_store = graph_craft::application_io::resource::HashMapResourceStorage::new();
for include_history in [true, false] {
let options = document_format::ExportOptions {
include_history,
..Default::default()
};
let archive = gdd.export_to_bytes(document_format::ExportFormat::Zip, options, &byte_store, None).await.expect("export");
let reopened = GddV1::open_from_archive(&archive, AnyContainer::Memory(MemoryBackend::new()), GddV1Layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), include_history.then_some("Ada"));
}
});
}
#[test]
fn a_torn_tail_is_skipped_and_the_next_fact_is_not_joined_to_it() {
futures::executor::block_on(async {
let (working, layout) = document_naming_ada().into_storage();
let path = document_format::io::path_for(layout.metadata_basename(), document_format::METADATA_CODEC);
working.append_non_blocking(&path, b"{\"subject\":{\"User\":").expect("append");
let mut reopened = GddV1::open_in(working, layout).await.expect("open");
reopened.record(Subject::User(UserId(11)), user_attr::NAME, "Bea".into(), NOW_MS).expect("record");
let (working, layout) = reopened.into_storage();
let reopened = GddV1::open_in(working, layout).await.expect("open");
assert_eq!(reopened.metadata().user_name(UserId(10)), Some("Ada"));
assert_eq!(reopened.metadata().user_name(UserId(11)), Some("Bea"));
});
}
+8 -17
View File
@@ -3,7 +3,7 @@ use std::hash::Hash;
use crate::{
Attributes, CrdtError, Delta, ExportSlot, History, HotOp, HotSequence, Implementation, InputSlot, LamportClock, MAX_EXPORT_SLOTS, MAX_INPUT_SLOTS, Network, NetworkId, Node, NodeId, NodeInput,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, Touched, UserId,
PeerId, PeerRegistration, Registry, RegistryDelta, ResourceEntry, ResourceId, RetiredMarks, Rev, SourceValue, TimeStamp, Tombstone, UserId,
};
#[derive(Clone, Debug)]
@@ -112,8 +112,8 @@ impl Document {
Ok(())
}
/// Take on a peer's marks as well as this peer's. Returns what the dropped ops named.
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
/// Take on a peer's marks as well as this peer's. Returns whether a hot op was dropped.
pub(crate) fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> bool {
self.retired.absorb(remote);
self.drop_retired_hot_ops()
}
@@ -134,19 +134,16 @@ impl Document {
}
/// Drop retired hot ops and re-derive working without them: their effect returns with their deltas.
fn drop_retired_hot_ops(&mut self) -> Touched {
fn drop_retired_hot_ops(&mut self) -> bool {
let before = self.hot_log.len();
let retired = &self.retired;
let mut touched = Touched::default();
let mut dropped = false;
for hot_op in self.hot_log.extract_if(.., |hot_op| retired.covers(hot_op.id())) {
touched.record(&hot_op.op);
dropped = true;
}
self.hot_log.retain(|hot_op| !retired.covers(hot_op.id()));
let dropped = self.hot_log.len() != before;
if dropped {
self.resync_hot_timestamps();
self.rebuild_working();
}
touched
dropped
}
/// Apply a retired commit and record it in history.
@@ -187,12 +184,6 @@ impl Document {
self.apply_op_with(RegistryTarget::Working, op, timestamp, ApplyMode::Idempotent)
}
/// A retired op from a peer, against both the retired and the working registry.
pub(crate) fn apply_retired_op_idempotent(&mut self, op: RegistryDelta, timestamp: TimeStamp) -> Result<(), CrdtError> {
self.apply_op_with(RegistryTarget::Retired, op.clone(), timestamp, ApplyMode::Idempotent)?;
self.apply_op_idempotent(op, timestamp)
}
/// Applies one op. Every field, existence included, is last-writer-wins on a timestamp, so ops fold alike in any order:
/// an addition writes every field, a removal keeps the content as a tombstone, a newer write or reference revives an
/// older removal, and a write to an entity never seen lands on a placeholder until its addition arrives.
+3 -1
View File
@@ -625,6 +625,8 @@ fn convert_input<M: NodeMetadataSource + ?Sized>(input: &GraphCraftNodeInput, pa
index: (*import_index).try_into().map_err(|_| ConversionError::IndexOverflow(*import_index))?,
},
GraphCraftNodeInput::Reflection(_) => NodeInput::Reflection,
// GPU-specific; not modeled in the Registry format.
GraphCraftNodeInput::Inline(_) => return Err(ConversionError::UnsupportedImplementation),
})
}
@@ -696,7 +698,7 @@ fn convert_implementation<M: NodeMetadataSource + ?Sized>(
Implementation::Network(nested_network_id)
}
// TODO: Support Extract in the Registry format.
DocumentNodeImplementation::Extract | DocumentNodeImplementation::Definition(_) => return Err(ConversionError::UnsupportedImplementation),
DocumentNodeImplementation::Extract => return Err(ConversionError::UnsupportedImplementation),
})
}
+12 -45
View File
@@ -37,10 +37,6 @@ impl History {
history
}
pub(crate) fn position(&self, rev: Rev) -> Option<usize> {
self.index.get(&rev).copied()
}
pub fn get(&self, rev: Rev) -> Option<&Delta> {
self.index.get(&rev).map(|&position| &self.deltas[position])
}
@@ -54,14 +50,6 @@ impl History {
&self.resource_hashes
}
/// Whether the deltas from `from` on form a single-parent chain off the delta before them, so are already sorted.
pub(crate) fn extends_canonically(&self, from: usize) -> bool {
(from..self.deltas.len()).all(|position| {
let delta = &self.deltas[position];
delta.parent == position.checked_sub(1).map(|previous| self.deltas[previous].id) && !matches!(delta.kind, RegistryDelta::Merge { .. })
})
}
pub fn len(&self) -> usize {
self.deltas.len()
}
@@ -102,14 +90,22 @@ impl History {
self.deltas.iter()
}
pub(crate) fn at(&self, position: usize) -> Option<&Delta> {
self.deltas.get(position)
/// Absorb `incoming` (dedup by `Rev`) and canonically re-sort the whole combined history.
///
/// The sort is deterministic (topological, ties broken by `Rev`), so two peers that absorb the same
/// delta set produce byte-identical history, not merely two different valid orderings. This is the
/// history-convergence mechanism: arrival order is erased. Callers update the registry separately
/// (LWW apply is commutative, so the registry converges regardless of order).
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) {
for delta in incoming {
self.push(delta);
}
self.canonical_sort();
}
/// Re-order `deltas` into the canonical topological order and rebuild the index: parents precede
/// children, and among deltas whose parents are all emitted the lowest `Rev` goes first. O(V + E).
/// Peers holding the same deltas thus hold byte-identical history.
pub(crate) fn canonical_sort(&mut self) {
fn canonical_sort(&mut self) {
// Unsatisfied in-history parent count per delta, plus reverse edges to decrement as parents emit.
let mut pending_parents: HashMap<Rev, usize> = HashMap::with_capacity(self.deltas.len());
let mut children: HashMap<Rev, Vec<Rev>> = HashMap::new();
@@ -163,35 +159,6 @@ impl History {
seen
}
pub(crate) fn is_ancestor(&self, ancestor: Rev, descendant: Rev) -> bool {
self.ancestors([descendant]).contains(&ancestor)
}
/// `tip`, its first-parent ancestors at distance 1, 2, 4, 8, ..., and the root.
pub(crate) fn sample_chain(&self, tip: Rev) -> Vec<Rev> {
let mut samples = vec![tip];
let mut current = tip;
let mut distance = 0_usize;
while let Some(parent) = self.get(current).and_then(|delta| delta.parent) {
current = parent;
distance += 1;
if distance.is_power_of_two() {
samples.push(current);
}
}
// Copies of one document share the root, which tells a diverged copy from an unrelated document.
if samples.last() != Some(&current) {
samples.push(current);
}
samples
}
/// Every delta not reachable from `known`, in topological order.
pub(crate) fn deltas_unknown_to(&self, known: impl IntoIterator<Item = Rev>) -> Vec<&Delta> {
let known = self.ancestors(known);
self.deltas.iter().filter(|delta| !known.contains(&delta.id)).collect()
}
/// The current tips: revs that no other delta lists as a parent (the divergent heads). A linear
/// history has exactly one tip; concurrent branches have several. Sorted ascending for determinism.
pub fn tips(&self) -> Vec<Rev> {
@@ -1,164 +0,0 @@
//! What people say about a document's history, kept beside it rather than in it: user names, step labels
//! and tags. None of it is folded into the document, so moving the head never changes it and stating it
//! never rewrites a delta.
use crate::ids::{PeerId, Rev, UserId};
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// When a fact was stated and by whom: milliseconds since the Unix epoch, the peer breaking ties.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct WallStamp {
pub ms: u64,
pub peer: PeerId,
}
/// What a fact is about. A rev stands for the interaction it closes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum Subject {
User(UserId),
Rev(Rev),
}
/// One statement about a subject, and one line of the metadata file.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetadataFact {
pub subject: Subject,
pub key: String,
pub value: serde_json::Value,
pub stamp: WallStamp,
}
/// The attribute keys the editor writes for a user.
pub mod user_attr {
/// The display name the user chose. Absent or empty means unnamed.
pub const NAME: &str = "name";
}
/// The attribute keys the editor writes for a rev.
pub mod rev_attr {
/// The name a person gave the interaction. Absent or empty means unnamed.
pub const LABEL: &str = "label";
/// Prefixes each tag's name to form its key. The value is `true` while the tag stands and `false` once removed.
pub const TAG_PREFIX: &str = "tag:";
}
/// The standing fact for each subject and key. Folding the same facts in any order gives the same record.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct HistoryMetadata {
facts: BTreeMap<Subject, BTreeMap<String, MetadataFact>>,
}
impl HistoryMetadata {
pub fn is_empty(&self) -> bool {
self.facts.is_empty()
}
pub fn fold(facts: impl IntoIterator<Item = MetadataFact>) -> Self {
let mut record = Self::default();
for fact in facts {
record.absorb(fact);
}
record
}
pub fn facts(&self) -> impl Iterator<Item = &MetadataFact> {
self.facts.values().flat_map(BTreeMap::values)
}
fn standing(&self, subject: Subject, key: &str) -> Option<&MetadataFact> {
self.facts.get(&subject)?.get(key)
}
fn text(&self, subject: Subject, key: &str) -> Option<&str> {
self.standing(subject, key)?.value.as_str().filter(|text| !text.is_empty())
}
pub fn user_name(&self, user: UserId) -> Option<&str> {
self.text(Subject::User(user), user_attr::NAME)
}
pub fn rev_label(&self, rev: Rev) -> Option<&str> {
self.text(Subject::Rev(rev), rev_attr::LABEL)
}
/// The tags standing on `rev`, in name order.
pub fn rev_tags(&self, rev: Rev) -> Vec<&str> {
let Some(attributes) = self.facts.get(&Subject::Rev(rev)) else { return Vec::new() };
attributes
.values()
.filter(|fact| fact.value == true)
.filter_map(|fact| fact.key.strip_prefix(rev_attr::TAG_PREFIX))
.collect()
}
/// The fact that would state `value`, stamped after the one it replaces so a clock behind a peer's still wins.
/// `None` when the value already stands, or when the standing stamp is at the end of time and can't be outdone.
pub fn statement(&self, subject: Subject, key: &str, value: serde_json::Value, mut stamp: WallStamp) -> Option<MetadataFact> {
if let Some(standing) = self.standing(subject, key) {
if standing.value == value {
return None;
}
if stamp <= standing.stamp {
stamp.ms = standing.stamp.ms.checked_add(1)?;
}
}
let key = key.to_string();
Some(MetadataFact { subject, key, value, stamp })
}
/// Take on a fact unless the standing one has a later stamp, or the same stamp and a value that encodes no lower.
pub fn absorb(&mut self, fact: MetadataFact) {
let attributes = self.facts.entry(fact.subject).or_default();
let stands = |mine: &MetadataFact| mine.stamp.cmp(&fact.stamp).then_with(|| mine.value.to_string().cmp(&fact.value.to_string())).is_ge();
if !attributes.get(&fact.key).is_some_and(stands) {
attributes.insert(fact.key.clone(), fact);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
const ADA: Subject = Subject::User(UserId(1));
fn stamp(ms: u64) -> WallStamp {
WallStamp { ms, peer: PeerId(1) }
}
fn fact(subject: Subject, key: &str, value: impl Into<serde_json::Value>, ms: u64) -> MetadataFact {
MetadataFact {
subject,
key: key.into(),
value: value.into(),
stamp: stamp(ms),
}
}
#[test]
fn facts_settle_alike_whatever_order_they_meet_in() {
let name = |value, ms| fact(ADA, user_attr::NAME, value, ms);
let later = HistoryMetadata::fold([name("Bea", 20), name("Ada", 10)]);
assert_eq!(later, HistoryMetadata::fold([name("Ada", 10), name("Bea", 20)]));
assert_eq!(later.user_name(UserId(1)), Some("Bea"));
assert_eq!(HistoryMetadata::fold([name("Ada", 10), name("Bea", 10)]), HistoryMetadata::fold([name("Bea", 10), name("Ada", 10)]));
}
#[test]
fn a_clock_behind_a_peers_still_gets_its_say() {
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "Ada", 100)]);
let stated = record.statement(ADA, user_attr::NAME, "Countess".into(), stamp(5)).expect("a change");
assert_eq!(stated.stamp.ms, 101);
assert!(record.statement(ADA, user_attr::NAME, "Ada".into(), stamp(500)).is_none(), "the same value is no change");
}
#[test]
fn empty_names_and_removed_tags_do_not_read_back() {
let step = Rev::new(7).expect("non-zero");
let subject = Subject::Rev(step);
let record = HistoryMetadata::fold([fact(ADA, user_attr::NAME, "", 1), fact(subject, "tag:v1", true, 1), fact(subject, "tag:draft", false, 1)]);
assert_eq!(record.user_name(UserId(1)), None);
assert_eq!(record.rev_tags(step), vec!["v1"]);
}
}
+1 -7
View File
@@ -5,14 +5,12 @@ pub mod crdt;
pub mod delta;
pub mod document;
pub mod history;
mod history_metadata;
pub mod ids;
pub mod model;
mod prior;
pub mod registry;
pub mod resources;
pub mod session;
mod touched;
pub mod value;
#[cfg(any(feature = "conversion", test))]
@@ -26,14 +24,12 @@ pub use attributes::*;
pub use crdt::*;
pub use document::*;
pub use history::History;
pub use history_metadata::{HistoryMetadata, MetadataFact, Subject, WallStamp, rev_attr, user_attr};
pub use ids::*;
pub use model::*;
pub use prior::{NetworkField, NodeField, Prior};
pub use registry::*;
pub use resources::*;
pub use session::*;
pub use touched::Touched;
pub use value::{Value, ValueError, from_value, to_value};
#[cfg(any(feature = "conversion", test))]
@@ -44,13 +40,11 @@ pub use from_runtime::{
#[cfg(any(feature = "conversion", test))]
pub use metadata_source::{InputMetadataEntry, NetworkMetadataEntry, NoMetadata, NodeMetadataEntry, NodeMetadataSource, Position};
#[cfg(any(feature = "conversion", test))]
pub use to_runtime::{Declarations, ProjectedNetwork, ProjectedNode, RuntimeProjection};
pub use to_runtime::Declarations;
#[cfg(test)]
mod tests {
mod bookkeeping;
mod crdt;
mod projection;
mod round_trip;
mod sessions;
}
+38 -307
View File
@@ -3,8 +3,8 @@ use crate::NodeMetadataSource;
#[cfg(any(feature = "conversion", test))]
use crate::from_runtime;
use crate::{
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, Touched, UserId,
Value, to_value,
ApplyMode, Attributes, Delta, Document, History, Implementation, LamportClock, NetworkId, NodeId, PeerId, Registry, RegistryDelta, RegistryTarget, ResourceEntry, Rev, TimeStamp, UserId, Value,
to_value,
};
use graphene_resource::{ResourceHash, ResourceId};
use serde::{Deserialize, Serialize};
@@ -288,99 +288,14 @@ impl Session {
Ok(session)
}
/// Move the shared head back to its ancestor `target`, leaving the line since as a branch. Returns the move to
/// broadcast and what the steps left behind named. Only the retirer does this; a guest asks it to.
pub fn move_head_to(&mut self, target: Rev) -> Result<(HeadMove, Touched), CrdtError> {
let from = self.document.head;
if from == Some(target) {
return Err(CrdtError::NothingToUndo);
}
let touched = self.touched_since(Some(target))?;
let snapshot = self.fold_at(Some(target))?;
self.document.head = Some(target);
self.document.retired_snapshot = snapshot;
self.document.redo_stack.clear();
self.document.rebuild_working();
self.publish_up_to(target);
Ok((
HeadMove {
from,
head: Some(target),
copies: Vec::new(),
},
touched,
))
}
/// Follow a peer's [`HeadMove`], returning what the walked-over ops named. Changes nothing when the head is not
/// where the move started, since this peer has then diverged, or when the copies don't chain from an ancestor of
/// the head to the move's head.
pub fn apply_head_move(&mut self, moved: &HeadMove) -> Result<Touched, CrdtError> {
if self.document.head != moved.from {
return Err(CrdtError::CursorMismatch {
expected: moved.from,
found: self.document.head,
});
}
let base = moved.copies.first().map_or(moved.head, |copy| copy.parent);
let touched = self.touched_since(base)?;
let mut tip = base;
for copy in &moved.copies {
if copy.parent != tip || matches!(copy.kind, RegistryDelta::Merge { .. }) {
return Err(CrdtError::MalformedHeadMove);
}
tip = Some(copy.id);
}
if tip != moved.head {
return Err(CrdtError::MalformedHeadMove);
}
// Like `follow`, a failed fold leaves only the copies behind in history.
for copy in &moved.copies {
self.document.clock.observe(copy.timestamp);
self.document.history.push(copy.clone());
}
let snapshot = self.fold_at(moved.head)?;
self.document.head = moved.head;
self.document.retired_snapshot = snapshot;
if !moved.copies.is_empty() {
self.document.history.canonical_sort();
}
self.document.redo_stack.clear();
self.document.rebuild_working();
if let Some(head) = moved.head {
self.publish_up_to(head);
}
Ok(touched)
}
/// What the deltas on the head's line but not on `base`'s named, merged branches included. Fails unless `base` is
/// on the head's line.
fn touched_since(&self, base: Option<Rev>) -> Result<Touched, CrdtError> {
let history = &self.document.history;
let line = history.ancestors(self.document.head);
if let Some(base) = base
&& !line.contains(&base)
{
return Err(CrdtError::NotAncestor(base));
}
let kept = history.ancestors(base);
let mut touched = Touched::default();
for delta in history.iter().filter(|delta| line.contains(&delta.id) && !kept.contains(&delta.id)) {
touched.record(&delta.kind);
}
Ok(touched)
}
/// Which hot ops are done with, for a peer catching up and for persisting. See [`RetiredMarks`].
pub fn retired_marks(&self) -> &RetiredMarks {
&self.document.retired
}
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover. Returns what those named.
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) -> Touched {
self.document.absorb_retired_marks(remote)
/// Take on a peer's marks, or this peer's persisted ones, dropping the hot ops they cover.
pub fn absorb_retired_marks(&mut self, remote: &RetiredMarks) {
self.document.absorb_retired_marks(remote);
}
/// Replay a persisted hot op. Idempotent on structural ops, suitable for crash recovery
@@ -389,13 +304,41 @@ impl Session {
self.document.replay_hot_op(hot_op)
}
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
self.fold_at(self.document.head)
/// Integrate `incoming` retired deltas from another branch and emit a [`RegistryDelta::Merge`]
/// joining the resulting tips, returning the new merge `Rev` (or `None` if `incoming` adds nothing).
/// Applies each incoming op to the registry, then hands the set to [`History::merge`]. Incoming
/// deltas must arrive in causal order.
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<Option<Rev>, CrdtError> {
let mut absorbed: Vec<Delta> = Vec::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
self.document.apply_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed.push(delta);
}
if absorbed.is_empty() {
return Ok(None);
}
self.document.history.merge(absorbed);
let tips = self.document.history.tips();
let timestamp = self.document.clock.tick();
let merge = Delta::merge(tips, self.document.peer, timestamp);
let merge_rev = merge.id;
// The merge's parents are the current tips, so it sorts last: `push` preserves the canonical
// order without re-sorting the whole history.
self.document.history.push(merge);
self.document.head = Some(merge_rev);
// Merge runs with an empty hot log; keep the retired snapshot in step with the working registry.
self.document.retired_snapshot = self.document.working_registry.clone();
Ok(Some(merge_rev))
}
fn fold_at(&self, head: Option<Rev>) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(head);
/// The retired snapshot as history alone gives it: the fold of `head`'s ancestry, leaving out undone deltas kept for redo.
pub fn snapshot_from_history(&self) -> Result<Registry, CrdtError> {
let reachable = self.document.history.ancestors(self.document.head);
let mut scratch = Document::empty(self.document.peer, self.document.user);
for delta in self.document.history.iter().filter(|delta| reachable.contains(&delta.id)) {
scratch.apply_op_with(RegistryTarget::Working, delta.kind.clone(), delta.timestamp, ApplyMode::Idempotent)?;
@@ -461,162 +404,6 @@ impl Session {
closed
}
/// Takes a retirer's deltas and moves the head to `head` (by default the batch's last delta) without minting a
/// merge. A batch not extending this head refolds the snapshot, leaving the old tip as a branch.
pub fn follow(&mut self, incoming: Vec<Delta>, head: Option<Rev>) -> Result<MergeOutcome, CrdtError> {
let before = self.document.head;
let length_before = self.document.history.len();
let named = head.is_some();
let head = head.or_else(|| incoming.last().map(|delta| delta.id)).or(before);
if let Some(head) = head
&& !self.document.history.contains(head)
&& !incoming.iter().any(|delta| delta.id == head)
{
return Err(CrdtError::NotFoundInHistory(head));
}
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
if let Some(parent) = delta.all_parents().find(|&parent| !self.document.history.contains(parent)) {
return Err(CrdtError::NotFoundInHistory(parent));
}
self.document.history.push(delta);
}
// A late copy of a line this head is already past changes nothing unless the head is named.
let stale = |head: Rev| !named && before.is_some_and(|before| self.document.history.is_ancestor(head, before));
if self.document.history.len() == length_before && (head == before || head.is_some_and(stale)) {
return Ok(MergeOutcome::NoOp);
}
let mut chain = Vec::new();
let mut current = head;
let extends = loop {
if current == before {
break true;
}
let Some(rev) = current else { break false };
let Some(delta) = self.document.history.get(rev) else { break false };
if self.document.history.position(rev).is_some_and(|position| position < length_before) {
break false;
}
// A merge may join a branch abandoned here, so the snapshot is refolded from the whole ancestry.
if delta.all_parents().count() > 1 {
break false;
}
chain.push(delta.clone());
current = delta.parent;
};
self.document.head = head;
if extends {
for delta in chain.into_iter().rev() {
self.document.apply_retired_op_idempotent(delta.kind, delta.timestamp)?;
}
} else {
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
}
if !self.document.history.extends_canonically(length_before) {
self.document.history.canonical_sort();
}
self.document.redo_stack.clear();
if let Some(head) = head {
self.publish_up_to(head);
}
Ok(head.map_or(MergeOutcome::NoOp, MergeOutcome::FastForward))
}
/// Integrates another peer's retired deltas, in causal order: fast-forwards when they extend `head`, otherwise
/// joins `head` and the incoming tips with a [`RegistryDelta::Merge`].
pub fn merge(&mut self, incoming: impl IntoIterator<Item = Delta>) -> Result<MergeOutcome, CrdtError> {
let length_before = self.document.history.len();
let head_before = self.document.head;
// Applied to both registries, since working is the snapshot plus the hot log.
let mut absorbed_ids = HashSet::new();
for delta in incoming {
if self.document.history.contains(delta.id) {
continue;
}
self.document.apply_retired_op_idempotent(delta.kind.clone(), delta.timestamp)?;
absorbed_ids.insert(delta.id);
self.document.history.push(delta);
}
if absorbed_ids.is_empty() {
return Ok(MergeOutcome::NoOp);
}
let extends = self.document.history.extends_canonically(length_before);
if !extends {
self.document.history.canonical_sort();
}
let history = &self.document.history;
let last_before = length_before.checked_sub(1).and_then(|position| history.at(position)).map(|delta| delta.id);
let parents: Vec<Rev> = if extends && self.document.head == last_before {
// The chain hangs off `head`, so its end is the only tip.
vec![history.at(history.len() - 1).expect("the batch is non-empty").id]
} else {
let mut candidates: Vec<Rev> = history.tips().into_iter().filter(|tip| absorbed_ids.contains(tip)).collect();
candidates.extend(self.document.head);
let is_dominated = |candidate: Rev| candidates.iter().any(|&other| other != candidate && history.is_ancestor(candidate, other));
candidates.iter().copied().filter(|&candidate| !is_dominated(candidate)).collect()
};
let outcome = match parents.as_slice() {
[tip] => MergeOutcome::FastForward(*tip),
_ => {
let timestamp = self.document.clock.tick();
let merge = Delta::merge(parents, self.document.peer, timestamp);
let merge_rev = merge.id;
// Its parents are tips, so `push` keeps the canonical order without a re-sort.
self.document.history.push(merge);
MergeOutcome::Merged(merge_rev)
}
};
self.document.head = outcome.head();
// The line moved past what was undone, and a peer holds everything up to here.
self.document.redo_stack.clear();
if let Some(head) = self.document.head {
self.publish_up_to(head);
}
// A merge, or a batch sorted in ahead of the tail, may bring in effects that applying it did not.
let mut refold = !extends || matches!(outcome, MergeOutcome::Merged(_));
if !refold && let MergeOutcome::FastForward(tip) = outcome {
refold = !self.fold_in_skipped(tip, head_before, &absorbed_ids)?;
}
if refold {
self.document.retired_snapshot = self.snapshot_from_history()?;
self.document.rebuild_working();
}
Ok(outcome)
}
/// Folds in the deltas between `from` and `tip` that the batch did not bring, such as steps undone here. `false`
/// when the walk meets a merge or misses `from`.
fn fold_in_skipped(&mut self, tip: Rev, from: Option<Rev>, absorbed: &HashSet<Rev>) -> Result<bool, CrdtError> {
let mut skipped = Vec::new();
let mut current = Some(tip);
while current != from {
let Some(delta) = current.and_then(|rev| self.document.history.get(rev)) else { return Ok(false) };
if matches!(delta.kind, RegistryDelta::Merge { .. }) {
return Ok(false);
}
if !absorbed.contains(&delta.id) {
skipped.push(delta.clone());
}
current = delta.parent;
}
for delta in skipped.into_iter().rev() {
self.document.apply_retired_op_idempotent(delta.kind, delta.timestamp)?;
}
Ok(true)
}
/// The hot ops stamped at or before `up_to`, which [`retire`](Self::retire) drains.
pub fn hot_ops_up_to(&self, up_to: TimeStamp) -> Vec<HotOpId> {
self.document.hot_log.iter().filter(|hot_op| hot_op.timestamp <= up_to).map(HotOp::id).collect()
@@ -758,29 +545,6 @@ impl Session {
self.document.history.iter()
}
/// A sample of `head`'s ancestry, for a peer to work out what this session lacks.
pub fn known_revs(&self) -> Vec<Rev> {
self.document.head.map(|head| self.document.history.sample_chain(head)).unwrap_or_default()
}
/// The deltas on `head`'s ancestry not reachable from `known`. Abandoned branches stay local, since merging one
/// would bring an undone step back. The head counts as published from then on.
pub fn deltas_unknown_to(&mut self, known: impl IntoIterator<Item = Rev>) -> Vec<Delta> {
let reachable = self.document.history.ancestors(self.document.head);
let deltas: Vec<Delta> = self
.document
.history
.deltas_unknown_to(known)
.into_iter()
.filter(|delta| reachable.contains(&delta.id))
.cloned()
.collect();
if let Some(head) = self.document.head.filter(|_| !deltas.is_empty()) {
self.publish_up_to(head);
}
deltas
}
/// The retired delta for `rev`, or `None` if it isn't in history. O(1) lookup, for callers that
/// already hold the revs they want (e.g. persisting a freshly-retired batch) and don't need a scan.
pub fn delta(&self, rev: Rev) -> Option<&Delta> {
@@ -1070,12 +834,6 @@ pub enum CrdtError {
NothingToUndo,
#[error("Nothing to redo")]
NothingToRedo,
#[error("Cursor is at {found:?}, the move expected {expected:?}")]
CursorMismatch { expected: Option<Rev>, found: Option<Rev> },
#[error("Delta {0} is not on the head's line")]
NotAncestor(Rev),
#[error("Head move copies do not chain from its base to its head")]
MalformedHeadMove,
#[error("Node {0} already exists")]
NodeAlreadyExists(NodeId),
#[error("Network {0} already exists")]
@@ -1083,30 +841,3 @@ pub enum CrdtError {
#[error("Delta stored under {stored} hashes to {expected}")]
RevMismatch { stored: Rev, expected: Rev },
}
/// A shared head move, as [`Session::move_head_to`] produces it and [`Session::apply_head_move`] follows it.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct HeadMove {
pub from: Option<Rev>,
pub head: Option<Rev>,
/// Steps minted again on top of the line's new end.
pub copies: Vec<Delta>,
}
/// How [`Session::merge`] or [`Session::follow`] moved the head.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MergeOutcome {
NoOp,
FastForward(Rev),
Merged(Rev),
}
impl MergeOutcome {
/// `None` when nothing changed.
pub fn head(self) -> Option<Rev> {
match self {
Self::NoOp => None,
Self::FastForward(rev) | Self::Merged(rev) => Some(rev),
}
}
}
@@ -1,6 +1,6 @@
use crate::{AttributeDelta, CrdtError, HotOpId, Implementation, Network, NetworkId, Node, NodeId, NodeInput, PeerId, RegistryDelta, Session, UserId, Value};
pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
fn set_attribute(key: &str, value: u32) -> RegistryDelta {
RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta {
key: key.to_string(),
@@ -9,7 +9,7 @@ pub(super) fn set_attribute(key: &str, value: u32) -> RegistryDelta {
}
}
pub(super) fn add_network(id: u64) -> RegistryDelta {
fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork {
id: NetworkId(id),
network: Network::default(),
+69 -2
View File
@@ -170,6 +170,73 @@ fn set_document_attribute(key: &str, value: u32) -> RegistryDelta {
}
}
/// Two peers that each integrate the other's concurrent branch converge to byte-identical history:
/// the merge commit is parent-set-addressed (same `Rev` on both) and the canonical sort erases the
/// arrival-order difference. Exercises `Session::merge`, the `Merge` variant, and `canonical_sort`.
#[test]
fn merge_converges_to_identical_history() {
// Shared base commit, then a concurrent edit on each peer's own clone of that base.
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
session_b.commit_op_for_test(set_document_attribute("compute::b", 2)).expect("B edit");
// Cross-merge: feed each peer the other's full delta set. The shared base dedups by `Rev`.
let deltas_a = session_a.cloned_deltas();
let deltas_b = session_b.cloned_deltas();
let merge_a = session_a.merge(deltas_b).expect("merge into A failed").expect("A produced a merge");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed").expect("B produced a merge");
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
let order_a: Vec<crate::Rev> = session_a.history().map(|d| d.id).collect();
let order_b: Vec<crate::Rev> = session_b.history().map(|d| d.id).collect();
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
}
/// Resurrection must reach into a merged-in branch: a network added then removed on the other peer's
/// branch lives only under the merge's secondary parent, so a `SetNetworkExport` targeting it after
/// the merge can only restore it by traversing all ancestors (not the primary-parent chain).
#[test]
fn resurrection_reaches_across_a_merge() {
let network_id = NetworkId(7);
// Shared base, then peer B adds and removes network 7 on its own branch.
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_document_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
session_a.commit_op_for_test(set_document_attribute("compute::a", 1)).expect("A edit");
session_b
.commit_op_for_test(RegistryDelta::AddNetwork {
id: network_id,
network: Network::default(),
})
.expect("B AddNetwork");
session_b
.commit_op_for_test(RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: Network::default(),
})
.expect("B RemoveNetwork");
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
// A SetNetworkExport on 7 must resurrect it by walking into the merged-in branch. Before the
// all-ancestors fix this failed with NetworkNotInHistory (the primary-parent walk missed B's branch).
session_a
.commit_op_for_test(RegistryDelta::SetNetworkExport {
id: network_id,
index: 0,
export: None,
})
.expect("resurrection must find the AddNetwork on the merged-in branch");
}
/// Committing the same NodeNetwork twice must produce zero history entries on the second commit.
/// Without value-only diffing in compute_deltas, the second commit would emit spurious
/// ChangeNodeInput / ChangeNodeAttribute ops because self.registry has real timestamps while the
@@ -884,7 +951,7 @@ fn add_node_rev_is_independent_of_attribute_insertion_order() {
}
/// Commit a retired delta and mirror it onto the working registry, which `commit_op_for_test` leaves alone.
pub(super) fn commit_retired(session: &mut Session, op: RegistryDelta) {
fn commit_retired(session: &mut Session, op: RegistryDelta) {
let before = session.history().count();
session.commit_op_for_test(op).expect("commit failed");
@@ -898,7 +965,7 @@ fn add_network(id: u64) -> RegistryDelta {
RegistryDelta::AddNetwork { id: NetworkId(id), network }
}
pub(super) fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
fn change_node_attribute(id: NodeId, key: &str, value: serde_json::Value) -> RegistryDelta {
let delta = crate::AttributeDelta {
key: key.into(),
value: Some(Value::from(value)),
@@ -1,173 +0,0 @@
use std::collections::BTreeSet;
use core_types::uuid::NodeId as RuntimeNodeId;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::concrete;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use crate::to_runtime::ConversionError;
use crate::{Declarations, Network, NetworkId, NoMetadata, Node, NodeId, PeerId, ROOT_NETWORK, Registry};
fn proto(identifier: &'static str, inputs: Vec<NodeInput>) -> DocumentNode {
DocumentNode {
inputs,
implementation: DocumentNodeImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
..Default::default()
}
}
/// A root network holding a proto node and a group, with another proto node and a nested group inside
/// the group, so projection is exercised two networks deep.
fn nested_network() -> NodeNetwork {
let inner = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(30), 0)],
nodes: [(RuntimeNodeId(30), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::import(concrete!(u32), 0)]))]
.into_iter()
.collect(),
..Default::default()
};
let group = NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(20), 0)],
nodes: [
(RuntimeNodeId(20), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(21), 0)])),
(
RuntimeNodeId(21),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(3), false)],
implementation: DocumentNodeImplementation::Network(inner),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
};
NodeNetwork {
exports: vec![NodeInput::node(RuntimeNodeId(1), 0)],
nodes: [
(RuntimeNodeId(1), proto("graphene_core::ops::identity::IdentityNode", vec![NodeInput::node(RuntimeNodeId(2), 0)])),
(
RuntimeNodeId(2),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Integer(7), true)],
implementation: DocumentNodeImplementation::Network(group),
..Default::default()
},
),
]
.into_iter()
.collect(),
..Default::default()
}
}
/// A node projected alone must match the whole-document conversion, metadata included, since a mirror
/// patched from projections has to match one rebuilt whole.
#[test]
fn projecting_a_node_matches_the_whole_conversion() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, node_entries, network_entries) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
for &id in registry.node_instances.keys() {
let projected = projection.node(id).expect("every stored node projects");
let (path, local_id) = projection.node_address(id).expect("every stored node has an address");
assert_eq!((path.as_slice(), local_id), (projected.network_path.as_slice(), projected.local_id));
assert_eq!(
whole.nested_network(&path).and_then(|network| network.nodes.get(&local_id)),
Some(&projected.node),
"node {id} projected differently than the whole conversion converts it"
);
let own_entry = node_entries.iter().find(|entry| entry.storage_id == id).expect("the whole conversion emits an entry per node");
assert_eq!(projected.node_entries.first(), Some(own_entry), "the node's own entry comes first");
let nested_prefix: Vec<RuntimeNodeId> = [path.as_slice(), &[local_id]].concat();
let expected_nested: BTreeSet<_> = node_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.storage_id)
.collect();
let projected_nested: BTreeSet<_> = projected.node_entries.iter().skip(1).map(|entry| entry.storage_id).collect();
assert_eq!(projected_nested, expected_nested, "nested node entries under {id}");
let expected_networks: BTreeSet<_> = network_entries
.iter()
.filter(|entry| entry.network_path.starts_with(&nested_prefix))
.map(|entry| entry.network_id)
.collect();
let projected_networks: BTreeSet<_> = projected.network_entries.iter().map(|entry| entry.network_id).collect();
assert_eq!(projected_networks, expected_networks, "nested network entries under {id}");
}
}
#[test]
fn a_network_entry_projects_its_dense_exports_and_path() {
let resources = graphene_resource::ResourceRegistry::new();
let conversion = Registry::convert_from_runtime(&nested_network(), &NoMetadata, &resources, PeerId(1)).expect("conversion");
let registry = &conversion.registry;
let (whole, _, _) = registry.to_runtime_with_full_metadata(&conversion.declarations).expect("whole conversion");
let projection = registry.runtime_projection(&conversion.declarations);
let root = projection.network_entry(ROOT_NETWORK).expect("root");
assert!(root.network_path.is_empty());
assert_eq!(root.exports, whole.exports);
for &network_id in registry.networks.keys() {
let entry = projection.network_entry(network_id).expect("every stored network projects");
let nested = whole.nested_network(&entry.network_path).expect("the projected path exists in the whole conversion");
assert_eq!(entry.exports, nested.exports, "exports of the network at {:?}", entry.network_path);
assert_eq!(entry.scope_injections, nested.scope_injections);
if let Some(owner) = projection.owner(network_id) {
let (owner_path, owner_local) = projection.node_address(owner).expect("owner address");
assert_eq!(
entry.network_path,
[owner_path.as_slice(), &[owner_local]].concat(),
"a network's path ends in the node implementing it"
);
}
}
}
/// A network no node implements is not in the runtime, so nothing inside it has an address.
#[test]
fn an_unreachable_network_has_no_address() {
let mut registry = Registry::default();
registry.networks.insert(NetworkId(5), Network::default());
let mut node = Node::dummy();
node.network = NetworkId(5);
registry.node_instances.insert(NodeId(9), node);
let declarations = Declarations::new();
let projection = registry.runtime_projection(&declarations);
assert_eq!(projection.network_path(NetworkId(5)), None);
assert_eq!(projection.node_address(NodeId(9)), None);
assert!(matches!(projection.node(NodeId(9)), Err(ConversionError::NetworkNotFound(_))));
}
/// The runtime holds a copy of a network under each node implementing it, so one several nodes implement has no single
/// address, and the root, which a node may name too, has no owner.
#[test]
fn a_network_several_nodes_implement_has_no_owner_and_neither_has_the_root() {
let mut registry = Registry::default();
registry.networks.insert(ROOT_NETWORK, Network::default());
registry.networks.insert(NetworkId(5), Network::default());
for (id, implemented) in [(1, NetworkId(5)), (2, NetworkId(5)), (3, ROOT_NETWORK)] {
let mut node = Node::dummy();
node.network = ROOT_NETWORK;
node.implementation = crate::Implementation::Network(implemented);
registry.node_instances.insert(NodeId(id), node);
}
let declarations = Declarations::new();
let projection = registry.runtime_projection(&declarations);
assert_eq!(projection.owner(NetworkId(5)), None);
assert_eq!(projection.network_path(NetworkId(5)), None);
assert_eq!(projection.owner(ROOT_NETWORK), None);
assert_eq!(projection.network_path(ROOT_NETWORK), Some(Vec::new()));
}
@@ -1,541 +0,0 @@
//! Peers exchanging retired history: syncing, following and merging lines, moving the shared head, and undo against what
//! other peers hold.
use crate::{CrdtError, Delta, History, Implementation, MergeOutcome, Network, NetworkId, Node, NodeId, PeerId, RegistryDelta, ResourceEntry, ResourceHash, ResourceId, Rev, Session, UserId, Value};
use std::collections::HashSet;
use super::bookkeeping::{add_network, set_attribute};
use super::crdt::{change_node_attribute, commit_retired};
/// Commits `op` as one interaction, with nothing hot.
fn step(session: &mut Session, op: RegistryDelta) -> Rev {
session.commit_op_for_test(op).expect("commit");
session.document.working_registry = session.document.retired_snapshot.clone();
let rev = session.head_rev().expect("committed");
session.mark_interaction_end(rev);
rev
}
fn sync(from: &mut Session, to: &mut Session) -> MergeOutcome {
let deltas = from.deltas_unknown_to(to.known_revs());
to.merge(deltas).expect("merge")
}
fn document_attribute(session: &Session, key: &str) -> Option<Value> {
session.retired_registry().attributes.get(key).filter(|value| !value.deleted).map(|value| value.value.clone())
}
#[test]
fn an_own_step_after_a_merge_further_back_can_be_undone() {
let mut a = Session::with_peer(PeerId(1));
step(&mut a, set_attribute("base", 0));
step(&mut a, set_attribute("a0", 0));
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
step(&mut a, set_attribute("a", 1));
step(&mut b, set_attribute("b", 1));
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::Merged(_)));
step(&mut a, set_attribute("mine", 1));
assert!(a.can_undo(), "the head interaction is this user's own single step; the merge is further back");
a.undo().expect("undo");
assert_eq!(document_attribute(&a, "mine"), None);
assert!(document_attribute(&a, "b").is_some(), "undo stopped at the merge");
assert_eq!(a.retired_registry(), &a.snapshot_from_history().unwrap());
}
#[test]
fn an_own_step_after_a_fast_forward_onto_unmarked_remote_deltas_can_be_undone() {
let mut a = Session::with_peer(PeerId(1));
step(&mut a, set_attribute("base", 0));
step(&mut a, set_attribute("a0", 0));
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
for i in 0..3 {
let staged = b.stage_ops([set_attribute("remote", i)]).unwrap();
b.retire(staged.last().unwrap().timestamp).unwrap();
}
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(_)));
step(&mut a, set_attribute("mine", 1));
assert!(a.can_undo(), "the head interaction is this user's own single step");
}
#[test]
fn a_step_handed_to_a_peer_is_published() {
let mut a = Session::with_peer(PeerId(1));
step(&mut a, set_attribute("base", 0));
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
step(&mut b, set_attribute("b", 1));
step(&mut b, set_attribute("b", 2));
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(_)));
assert!(!b.can_undo(), "A holds the step, so it is published");
sync(&mut a, &mut b);
sync(&mut b, &mut a);
assert_eq!(a.retired_registry(), b.retired_registry());
}
/// The tips as a scan finds them, for checking the maintained set against.
fn scanned_tips(history: &History) -> Vec<Rev> {
let referenced: HashSet<Rev> = history.iter().flat_map(|delta| delta.all_parents()).collect();
let mut tips: Vec<Rev> = history.iter().map(|delta| delta.id).filter(|rev| !referenced.contains(rev)).collect();
tips.sort_unstable();
tips
}
/// Two peers that branch from a shared base, so their histories hold two tips until merged.
fn branched_pair() -> (Session, Session) {
let mut a = Session::with_peer(PeerId(1));
a.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut b = a.clone();
b.document.peer = PeerId(2);
b.document.clock = crate::LamportClock::new(PeerId(2));
a.commit_op_for_test(set_attribute("a", 1)).expect("a edit");
b.commit_op_for_test(set_attribute("b", 2)).expect("b edit");
(a, b)
}
#[test]
fn history_indexes_follow_pushes_merges_and_reloads() {
let (mut a, b) = branched_pair();
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
a.merge(b.cloned_deltas()).expect("merge");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
assert_eq!(a.document.history.tips().len(), 1, "the merge delta is the one tip");
let (id, hash) = (ResourceId::new(), ResourceHash::from(b"bytes".as_slice()));
let entry = ResourceEntry::embedded(hash, PeerId(1), crate::TimeStamp::ORIGIN);
a.commit_op_for_test(RegistryDelta::AddResource { id, entry }).expect("add");
assert_eq!(a.document.history.tips(), scanned_tips(&a.document.history));
let snapshot = a.retired_registry().resources[&id].clone();
a.commit_op_for_test(RegistryDelta::RemoveResource { id, snapshot }).expect("remove");
assert!(a.all_referenced_resource_hashes().contains(&hash), "a removed resource's hash is still referenced from history");
let reloaded = History::from_ordered(a.cloned_deltas());
assert_eq!(reloaded.tips(), a.document.history.tips());
assert!(reloaded.resource_hashes().contains(&hash));
assert!(a.history().all(|delta| reloaded.contains(delta.id)));
}
#[test]
fn a_merge_appends_a_chain_and_sorts_a_branch_into_place() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("base", 0)).expect("base");
let mut guest = host.clone();
guest.document.peer = PeerId(2);
for op in [set_attribute("x", 1), add_network(5), set_attribute("y", 2)] {
host.commit_op_for_test(op).expect("host step");
}
let (a, b) = branched_pair();
let ids = |history: &History| history.iter().map(|delta| delta.id).collect::<Vec<_>>();
for (mut receiver, mut sender, missing, fast_forward) in [(guest, host, 3, true), (a, b, 1, false)] {
let before = receiver.history_len();
let incoming: Vec<Delta> = sender.deltas_unknown_to(receiver.known_revs());
assert_eq!(incoming.len(), missing, "only what the receiver lacks is sent");
let outcome = receiver.merge(incoming).expect("merge");
let mut sorted = receiver.document.history.clone();
sorted.canonical_sort();
assert_eq!(ids(&sorted), ids(&receiver.document.history));
assert_eq!(receiver.document.history.extends_canonically(before), fast_forward);
assert_eq!(receiver.document.history.tips(), scanned_tips(&receiver.document.history));
if fast_forward {
assert_eq!(outcome, MergeOutcome::FastForward(sender.head_rev().expect("head")));
assert_eq!(ids(&receiver.document.history), ids(&sender.document.history), "no merge delta");
assert!(receiver.retired_registry().value_equal(sender.retired_registry()));
assert_eq!(sender.merge(receiver.cloned_deltas()).expect("merge back"), MergeOutcome::NoOp);
} else {
assert!(matches!(outcome, MergeOutcome::Merged(_)), "{outcome:?}");
}
}
}
#[test]
fn an_undone_branch_is_kept_to_itself() {
let mut author = Session::with_peer(PeerId(1));
author.commit_op_for_test(set_attribute("base", 0)).expect("base");
let base = author.head_rev().expect("base rev");
author.mark_interaction_end(base);
let mut peer = author.clone();
peer.document.peer = PeerId(2);
author.commit_op_for_test(set_attribute("undone", 1)).expect("the step to undo");
let undone = author.head_rev().expect("rev");
author.mark_interaction_end(undone);
author.undo().expect("undo");
assert_eq!(author.head_rev(), Some(base));
author.commit_op_for_test(set_attribute("kept", 2)).expect("a new branch");
let kept = author.head_rev().expect("rev");
let sent: Vec<Rev> = author.deltas_unknown_to(peer.known_revs()).into_iter().map(|delta| delta.id).collect();
assert_eq!(sent, vec![kept], "only the branch the cursor is on goes out, not the undone step");
assert!(author.delta(undone).is_some(), "the undone step stays in the author's DAG for a history panel");
let incoming: Vec<Delta> = sent.iter().filter_map(|&rev| author.delta(rev).cloned()).collect();
let outcome = peer.merge(incoming).expect("merge");
assert!(matches!(outcome, MergeOutcome::FastForward(rev) if rev == kept), "{outcome:?}");
assert!(peer.retired_registry().attributes.get("kept").is_some_and(|value| !value.deleted));
assert!(!peer.retired_registry().attributes.contains_key("undone"), "the undone step never reached the peer");
}
#[test]
fn following_a_merge_refolds_the_branch_it_joins() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(1)).expect("root");
let mut guest = Session::with_peer(PeerId(2));
let root: Vec<Delta> = host.history().cloned().collect();
guest.follow(root, host.head_rev()).expect("follow the root");
// The guest retires a step of its own while apart, then follows the host's line, which leaves it behind.
guest.commit_op_for_test(add_network(2)).expect("own step");
let own: Vec<Delta> = guest.history().filter(|delta| delta.author == PeerId(2)).cloned().collect();
host.commit_op_for_test(add_network(3)).expect("host step");
let line: Vec<Delta> = host.history().cloned().collect();
guest.follow(line, host.head_rev()).expect("follow the host");
assert!(!guest.retired_registry().networks.contains_key(&NetworkId(2)), "the guest's own step is off the line");
// The host merges the guest's step and the guest follows to the joined head.
host.merge(own).expect("merge");
let merged: Vec<Delta> = host.history().cloned().collect();
guest.follow(merged, host.head_rev()).expect("follow the merge");
let fold = guest.snapshot_from_history().expect("fold");
assert_eq!(guest.retired_registry(), &fold, "the snapshot is the fold of the joined head's ancestry");
assert!(guest.retired_registry().networks.contains_key(&NetworkId(2)), "the branch is back on the line");
assert_eq!(guest.retired_registry(), host.retired_registry());
assert!(guest.registry().value_equal(guest.retired_registry()));
}
#[test]
fn a_late_copy_of_a_followed_line_leaves_the_head_but_a_known_step_ahead_moves_it() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("a", 1)).unwrap();
host.commit_op_for_test(set_attribute("b", 1)).unwrap();
let deltas = host.cloned_deltas();
let (first, second) = (deltas[0].id, deltas[1].id);
let mut guest = Session::with_peer(PeerId(2));
guest.follow(deltas.clone(), None).unwrap();
assert_eq!(guest.head_rev(), Some(second));
// The first step again, as a broadcast delayed past the second arrives.
assert!(matches!(guest.follow(vec![deltas[0].clone()], None).unwrap(), MergeOutcome::NoOp));
assert_eq!(guest.head_rev(), Some(second));
// The host moves back and then restores the step, which mints the same delta again.
guest.follow(Vec::new(), Some(first)).unwrap();
assert_eq!(guest.head_rev(), Some(first));
guest.follow(vec![deltas[1].clone()], None).unwrap();
assert_eq!(guest.head_rev(), Some(second));
assert!(guest.retired_registry().value_equal(&host.snapshot_from_history().unwrap()));
}
#[test]
fn following_to_an_unknown_head_is_rejected_and_changes_nothing() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("a", 1)).unwrap();
let mut guest = Session::with_peer(PeerId(2));
guest.follow(host.cloned_deltas(), None).unwrap();
let (head, registry) = (guest.head_rev(), guest.retired_registry().clone());
host.commit_op_for_test(set_attribute("b", 1)).unwrap();
let unknown = host.head_rev().unwrap();
assert!(matches!(guest.follow(Vec::new(), Some(unknown)), Err(crate::CrdtError::NotFoundInHistory(rev)) if rev == unknown));
assert_eq!(guest.head_rev(), head);
assert_eq!(guest.retired_registry(), &registry);
}
#[test]
fn an_undone_step_leaves_no_stamp_behind_for_a_concurrent_write_to_lose_to() {
let mut a = Session::with_peer(PeerId(3));
step(&mut a, set_attribute("base", 1));
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
let concurrent = b.stage_ops([set_attribute("k", 20)]).unwrap().last().unwrap().timestamp;
step(&mut a, set_attribute("k", 10));
a.undo().unwrap();
step(&mut a, set_attribute("other", 1));
sync(&mut a, &mut b);
b.retire(concurrent).unwrap();
sync(&mut b, &mut a);
assert_eq!(document_attribute(&a, "k"), document_attribute(&b, "k"));
assert_eq!(a.retired_registry(), &a.snapshot_from_history().unwrap());
}
#[test]
fn a_fast_forward_onto_an_undone_step_folds_it_back_in() {
let mut a = Session::with_peer(PeerId(1));
let first = step(&mut a, set_attribute("first", 1));
step(&mut a, set_attribute("second", 2));
// A copy that left without being recorded, as when a crash comes between sending it and persisting the frontier.
let mut b = Session::with_peer(PeerId(2));
sync(&mut a.clone(), &mut b);
a.undo().unwrap();
assert_eq!(a.head_rev(), Some(first));
let third = step(&mut b, set_attribute("third", 3));
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::FastForward(rev) if rev == third));
assert!(document_attribute(&a, "second").is_some());
assert!(a.retired_registry().value_equal(&a.snapshot_from_history().unwrap()));
assert!(!a.can_redo(), "the undone step is on the line again");
}
#[test]
fn undo_takes_only_this_users_own_steps_and_stops_at_a_merge() {
let mut a = Session::with_peer(PeerId(1));
step(&mut a, set_attribute("first", 1));
step(&mut a, set_attribute("second", 2));
let mut b = Session::with_peer(PeerId(2));
sync(&mut a, &mut b);
assert!(!b.can_undo(), "the steps are the other user's");
assert!(matches!(b.undo(), Err(crate::CrdtError::NothingToUndo)));
step(&mut a, set_attribute("a", 1));
step(&mut b, set_attribute("b", 1));
assert!(matches!(sync(&mut b, &mut a), MergeOutcome::Merged(_)));
assert!(!a.can_undo(), "the head is a merge");
}
#[test]
fn merge_converges_to_identical_history() {
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
session_a.commit_op_for_test(set_attribute("compute::a", 1)).expect("A edit");
session_b.commit_op_for_test(set_attribute("compute::b", 2)).expect("B edit");
let deltas_a = session_a.cloned_deltas();
let deltas_b = session_b.cloned_deltas();
let merge_a = session_a.merge(deltas_b).expect("merge into A failed");
let merge_b = session_b.merge(deltas_a).expect("merge into B failed");
assert!(matches!(merge_a, MergeOutcome::Merged(_)), "divergent branches must produce a merge delta");
assert_eq!(merge_a, merge_b, "same tips must mint the identical parent-set-addressed merge commit");
let order_a: Vec<Rev> = session_a.history().map(|d| d.id).collect();
let order_b: Vec<Rev> = session_b.history().map(|d| d.id).collect();
assert_eq!(order_a, order_b, "both peers must converge to byte-identical history order");
assert_eq!(session_a.head_rev(), session_b.head_rev(), "both peers land on the same merge head");
}
#[test]
fn a_write_revives_a_network_removed_on_a_merged_branch() {
let network_id = NetworkId(7);
// Shared base, then peer B adds and removes network 7 on its own branch.
let mut session_a = Session::with_peer(PeerId(1));
session_a.commit_op_for_test(set_attribute("compute::base", 0)).expect("base commit");
let mut session_b = session_a.clone();
session_a.commit_op_for_test(set_attribute("compute::a", 1)).expect("A edit");
session_b.commit_op_for_test(add_network(network_id.0)).expect("B AddNetwork");
session_b
.commit_op_for_test(RegistryDelta::RemoveNetwork {
id: network_id,
snapshot: Network::default(),
})
.expect("B RemoveNetwork");
// A merges B's branch: 7's AddNetwork now lives only under the merge's secondary parent.
session_a.merge(session_b.cloned_deltas()).expect("merge failed");
// A SetNetworkExport on 7 is newer than its removal, so it brings 7 back from its tombstone.
session_a
.commit_op_for_test(RegistryDelta::SetNetworkExport {
id: network_id,
index: 0,
export: None,
})
.expect("a write newer than the removal revives the network");
assert!(session_a.retired_registry().networks.contains_key(&network_id));
}
#[test]
fn a_concurrent_remove_and_attribute_change_commute() {
let node = Node::new(NetworkId(5), Implementation::Network(NetworkId(5)), 0);
let mut base = Session::with_peer(PeerId(1));
commit_retired(&mut base, add_network(5));
commit_retired(&mut base, RegistryDelta::AddNode { id: NodeId(7), node: node.clone() });
let mut remover = base.clone();
commit_retired(&mut remover, RegistryDelta::RemoveNode { id: NodeId(7), snapshot: node });
let mut changer = Session::with_peer(PeerId(2));
changer.merge(base.cloned_deltas()).expect("changer adopts the base");
commit_retired(&mut changer, change_node_attribute(NodeId(7), "tint", serde_json::json!(75)));
// One delta from each branch, neither an ancestor of the other.
let removal = remover.cloned_deltas().pop().expect("removal delta");
let change = changer.cloned_deltas().pop().expect("change delta");
let merged = |order: [&Delta; 2]| {
let mut session = base.clone();
session.merge(order.map(Delta::clone).to_vec()).expect("merge failed");
session.retired_registry().clone()
};
assert_eq!(merged([&removal, &change]), merged([&change, &removal]));
}
/// The retirer moves the head back: the line since stays as a branch, and a follower folds to the same state.
#[test]
fn moving_the_head_back_leaves_the_line_since_as_a_branch_everyone_follows() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
let [first, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
host.commit_op_for_test(set_attribute(key, value)).expect("step");
let rev = host.head_rev().expect("rev");
host.mark_interaction_end(rev);
rev
});
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let (moved, touched) = host.move_head_to(first).expect("move");
assert_eq!(moved.from, Some(third));
assert_eq!(moved.head, Some(first));
assert!(moved.copies.is_empty(), "nothing is minted: the line since is left behind");
assert!(touched.is_empty(), "document attributes name no graph entity");
let snapshot = host.retired_registry();
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the second step's write is gone");
assert!(snapshot.attributes.get("c").is_none_or(|value| value.deleted), "the third step's write is gone");
assert_eq!(snapshot.attributes.get("a").map(|value| &value.value), Some(&Value::from(serde_json::json!(1))));
assert!(host.delta(second).is_some() && host.delta(third).is_some(), "the steps left behind stay as a branch");
assert!(host.registry().value_equal(host.retired_registry()));
guest.apply_head_move(&moved).expect("follow");
assert_eq!(guest.head_rev(), Some(first));
assert!(guest.retired_registry().value_equal(host.retired_registry()), "the follower folds to the same state");
}
/// A move only applies from the head it started at: a peer elsewhere has diverged and is left as it was.
#[test]
fn a_head_move_from_another_head_is_rejected_and_changes_nothing() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
let first = host.head_rev().expect("rev");
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
let (moved, _) = host.move_head_to(first).expect("move");
let registry = guest.retired_registry().clone();
assert!(matches!(guest.apply_head_move(&moved), Err(CrdtError::CursorMismatch { found, .. }) if found == Some(first)));
assert_eq!(guest.head_rev(), Some(first));
assert_eq!(guest.retired_registry(), &registry);
}
/// Across a merge the move drops both merged branches, reports what each named, and takes either side as its target.
#[test]
fn a_head_move_back_across_a_merge_drops_both_branches() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(add_network(1)).expect("base");
let base = host.head_rev().expect("rev");
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
host.commit_op_for_test(add_network(2)).expect("host step");
let host_step = host.head_rev().expect("rev");
guest.commit_op_for_test(add_network(3)).expect("guest step");
let guest_step = guest.head_rev().expect("rev");
assert!(matches!(host.merge(guest.cloned_deltas()).expect("merge"), MergeOutcome::Merged(_)));
let mut moved_to_base = host.clone();
let (_, touched) = moved_to_base.move_head_to(base).expect("move to the base");
assert!(touched.networks.is_superset(&[NetworkId(2), NetworkId(3)].into()), "both branches are left behind: {touched:?}");
assert!(!moved_to_base.retired_registry().networks.contains_key(&NetworkId(2)));
assert!(!moved_to_base.retired_registry().networks.contains_key(&NetworkId(3)));
for (target, kept, dropped) in [(host_step, 2, 3), (guest_step, 3, 2)] {
let mut moved = host.clone();
moved.move_head_to(target).expect("either side of the merge is an ancestor");
assert!(moved.retired_registry().networks.contains_key(&NetworkId(kept)));
assert!(!moved.retired_registry().networks.contains_key(&NetworkId(dropped)));
let sibling = if target == host_step { guest_step } else { host_step };
assert!(matches!(moved.move_head_to(sibling), Err(CrdtError::NotAncestor(rev)) if rev == sibling));
}
}
/// A follower takes on the copies a move minted on top of its base and folds to the line they end.
#[test]
fn a_head_move_with_copies_is_followed_onto_them() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
let first = host.head_rev().expect("rev");
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
let second = host.head_rev().expect("rev");
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let copy = Delta::new(Some(first), PeerId(1), crate::TimeStamp { counter: 50, peer: PeerId(1) }, set_attribute("c", 3), Vec::new());
let moved = crate::HeadMove {
from: Some(second),
head: Some(copy.id),
copies: vec![copy.clone()],
};
let touched = guest.apply_head_move(&moved).expect("follow");
assert!(touched.is_empty(), "the walked-over step wrote a document attribute");
assert_eq!(guest.head_rev(), Some(copy.id));
assert!(guest.clock_counter() >= 50, "a later edit here outdates the copy");
assert!(guest.delta(copy.id).is_some() && guest.delta(second).is_some(), "the copy joins history and the old step stays");
let snapshot = guest.retired_registry();
assert!(snapshot.attributes.get("b").is_none_or(|value| value.deleted), "the step walked over is gone");
assert_eq!(snapshot.attributes.get("c").map(|value| &value.value), Some(&Value::from(serde_json::json!(3))));
assert!(guest.registry().value_equal(guest.retired_registry()));
assert!(snapshot.value_equal(&guest.snapshot_from_history().expect("fold")));
}
/// Copies that don't chain from the base to the move's head are refused before anything changes.
#[test]
fn a_malformed_head_move_changes_nothing() {
let mut host = Session::with_peer(PeerId(1));
host.commit_op_for_test(set_attribute("a", 1)).expect("step");
let first = host.head_rev().expect("rev");
host.commit_op_for_test(set_attribute("b", 2)).expect("step");
let second = host.head_rev().expect("rev");
let mut guest = Session::load(PeerId(2), UserId(2), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
let (history_len, registry) = (guest.history_len(), guest.retired_registry().clone());
let copy = |counter, parent| Delta::new(parent, PeerId(1), crate::TimeStamp { counter, peer: PeerId(1) }, set_attribute("c", counter as u32), Vec::new());
let off_first = copy(50, Some(first));
let off_base_again = copy(51, Some(first));
for moved in [
// The copies end somewhere other than the move's head.
crate::HeadMove {
from: Some(second),
head: Some(second),
copies: vec![off_first.clone()],
},
// The second copy hangs off the base instead of the first copy.
crate::HeadMove {
from: Some(second),
head: Some(off_base_again.id),
copies: vec![off_first.clone(), off_base_again.clone()],
},
] {
assert!(matches!(guest.apply_head_move(&moved), Err(CrdtError::MalformedHeadMove)));
assert_eq!(guest.head_rev(), Some(second));
assert_eq!(guest.history_len(), history_len);
assert_eq!(guest.retired_registry(), &registry);
assert!(guest.registry().value_equal(guest.retired_registry()));
}
}
/// Peers hold the line up to where the head moved, so a silent undo must not reach behind it.
#[test]
fn a_head_move_publishes_the_new_head() {
let mut host = Session::with_identity(PeerId(1), UserId(1));
let [_, second, third] = [("a", 1), ("b", 2), ("c", 3)].map(|(key, value)| {
host.commit_op_for_test(set_attribute(key, value)).expect("step");
let rev = host.head_rev().expect("rev");
host.mark_interaction_end(rev);
rev
});
host.publish_up_to(third);
let mut guest = Session::load(PeerId(2), UserId(1), host.retired_registry().clone(), host.cloned_deltas(), host.head_rev(), Vec::new(), 0);
guest.publish_up_to(third);
let (moved, _) = host.move_head_to(second).expect("move");
assert!(!host.can_undo(), "the step the room holds stays put");
guest.apply_head_move(&moved).expect("follow");
assert!(!guest.can_undo(), "the follower holds the same line");
}
+9 -126
View File
@@ -112,118 +112,6 @@ fn runtime_node_id(global_id: NodeId, node: &Node) -> RuntimeNodeId {
RuntimeNodeId(node.attributes.get_typed(node::ORIGINAL_NODE_ID).unwrap_or(global_id.0))
}
/// A node in runtime form with the metadata entries for it and everything nested under it, paths absolute.
pub struct ProjectedNode {
/// The runtime path of the network the node sits in.
pub network_path: Vec<RuntimeNodeId>,
pub local_id: RuntimeNodeId,
pub node: DocumentNode,
/// The node's own entry first, then one per nested node.
pub node_entries: Vec<NodeMetadataEntry>,
/// One per network the node's implementation nests, outermost first.
pub network_entries: Vec<NetworkMetadataEntry>,
}
/// A network's own runtime form without its nodes, as [`RuntimeProjection::network_entry`] produces it.
pub struct ProjectedNetwork {
pub network_path: Vec<RuntimeNodeId>,
pub exports: Vec<GraphCraftNodeInput>,
pub scope_injections: FxHashMap<String, (RuntimeNodeId, Type)>,
pub metadata: NetworkMetadataEntry,
}
/// Converts single registry entities to runtime form, for keeping a runtime mirror in step without
/// rebuilding it.
pub struct RuntimeProjection<'a> {
context: ConversionContext<'a>,
/// The node whose implementation each nested network is, or `None` where several nodes implement it.
owners: FxHashMap<NetworkId, Option<NodeId>>,
}
impl Registry {
pub fn runtime_projection<'a>(&'a self, declarations: &'a Declarations) -> RuntimeProjection<'a> {
let mut owners = FxHashMap::default();
for (&id, node) in &self.node_instances {
if let Implementation::Network(network) = node.implementation
&& network != ROOT_NETWORK
{
owners.entry(network).and_modify(|owner| *owner = None).or_insert(Some(id));
}
}
RuntimeProjection {
context: ConversionContext::new(self, declarations),
owners,
}
}
}
impl RuntimeProjection<'_> {
/// The node implementing `network`, or `None` for the root, for a network no node implements, and for one several
/// nodes implement, which the runtime holds a copy of under each and no single path addresses.
pub fn owner(&self, network: NetworkId) -> Option<NodeId> {
self.owners.get(&network).copied().flatten()
}
/// The runtime path of `network`: the nodes implementing it and its ancestors, outermost first.
/// `None` for a network the root does not reach, which the runtime does not hold.
pub fn network_path(&self, network: NetworkId) -> Option<Vec<RuntimeNodeId>> {
let mut chain: Vec<(NodeId, &Node)> = Vec::new();
let mut current = network;
while current != ROOT_NETWORK {
let owner = self.owner(current)?;
// Owners can form a cycle through concurrent implementation swaps, which the runtime rejects.
if chain.iter().any(|&(id, _)| id == owner) {
return None;
}
let node = self.context.registry.node_instances.get(&owner)?;
chain.push((owner, node));
current = node.network;
}
Some(chain.into_iter().rev().map(|(id, node)| runtime_node_id(id, node)).collect())
}
/// Where the node sits in the runtime: the path of its network, and its id within that network.
pub fn node_address(&self, id: NodeId) -> Option<(Vec<RuntimeNodeId>, RuntimeNodeId)> {
let node = self.context.registry.node_instances.get(&id)?;
Some((self.network_path(node.network)?, runtime_node_id(id, node)))
}
/// The node and everything nested under it, converted as a whole-document conversion would.
pub fn node(&self, id: NodeId) -> Result<ProjectedNode, ConversionError> {
let node = self.context.registry.node_instances.get(&id).ok_or(ConversionError::NodeNotFound(id))?;
let network_path = self.network_path(node.network).ok_or(ConversionError::NetworkNotFound(node.network))?;
let local_id = runtime_node_id(id, node);
if let Implementation::Network(nested) = node.implementation {
detect_network_cycle(&self.context, nested)?;
}
let mut node_entries = Some(vec![extract_ui_metadata(node, id, &network_path, local_id)]);
let mut network_entries = Some(Vec::new());
Ok(ProjectedNode {
node: convert_node(&self.context, node, &network_path, local_id, &mut node_entries, &mut network_entries)?,
network_path,
local_id,
node_entries: node_entries.expect("seeded above"),
network_entries: network_entries.expect("seeded above"),
})
}
/// The network's exports, scope injections and metadata, without its nodes.
pub fn network_entry(&self, id: NetworkId) -> Result<ProjectedNetwork, ConversionError> {
let registry = self.context.registry;
let network = registry.network_or_removed(id).ok_or(ConversionError::NetworkNotFound(id))?;
let network_path = self.network_path(id).ok_or(ConversionError::NetworkNotFound(id))?;
Ok(ProjectedNetwork {
metadata: extract_network_metadata(registry, &network.attributes, &network_path, id),
scope_injections: read_scope_injections(registry, id, &network.attributes)?,
exports: convert_exports(registry, id, network)?,
network_path,
})
}
}
/// Converts a single network. Recurses through `Implementation::Network` owning nodes.
///
/// **ID remapping:** Registry uses globally hashed IDs; runtime networks need local IDs. We pull
@@ -313,30 +201,25 @@ fn convert_network(
}
}
let exports = convert_exports(context.registry, network_id, network)?;
// Input attributes aren't round-tripped for exports — Reflection/Import inputs don't appear there.
let empty_attrs = crate::Attributes::new();
let exports: Vec<GraphCraftNodeInput> = network
.exports
.iter()
.filter_map(|slot| slot.target.as_ref())
.map(|input| convert_input(context.registry, network_id, input, &empty_attrs))
.collect::<Result<Vec<_>, _>>()?;
let scope_injections = read_scope_injections(context.registry, network_id, &network.attributes)?;
Ok(NodeNetwork {
exports,
nodes,
scope_injections,
definitions: FxHashMap::default(),
generated: false,
})
}
/// The network's exports, compacted into the runtime's dense list.
fn convert_exports(registry: &Registry, network_id: NetworkId, network: &crate::Network) -> Result<Vec<GraphCraftNodeInput>, ConversionError> {
// Input attributes aren't round-tripped for exports — Reflection/Import inputs don't appear there.
let empty_attrs = crate::Attributes::new();
network
.exports
.iter()
.filter_map(|slot| slot.target.as_ref())
.map(|input| convert_input(registry, network_id, input, &empty_attrs))
.collect()
}
/// Rebuild a network's `scope_injections` from its serialized attribute blob, resolving each stored
/// storage node ID back to its runtime-local ID. Mirrors `from_runtime::write_scope_injections`.
fn read_scope_injections(registry: &Registry, network_id: NetworkId, attributes: &crate::Attributes) -> Result<FxHashMap<String, (RuntimeNodeId, Type)>, ConversionError> {
-173
View File
@@ -1,173 +0,0 @@
//! Which entities a run of ops named, so a runtime mirror of the registry can be brought back into line
//! without a full rebuild.
//!
//! Over-approximate on purpose: an op is recorded whether or not it changed anything, and the mirror
//! settles the outcome by comparing each entity's stored and mirrored forms. That is cheaper than having
//! every apply arm report its outcome, and stays correct when an op revives an entity it only references.
use std::collections::BTreeSet;
use crate::{Implementation, NetworkId, NodeId, NodeInput, RegistryDelta};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Touched {
pub nodes: BTreeSet<NodeId>,
pub networks: BTreeSet<NetworkId>,
/// Some resource entry changed. Resources are mirrored as one registry rather than per entity.
pub resources: bool,
}
impl Touched {
/// Records every entity `op` names: its target and whatever it references.
pub fn record(&mut self, op: &RegistryDelta) {
match op {
RegistryDelta::AddNode { id, node } => {
self.nodes.insert(*id);
self.networks.insert(node.network);
if let Implementation::Network(network) = node.implementation {
self.networks.insert(network);
}
self.reference_inputs(node.inputs().iter().map(|slot| &slot.input));
}
RegistryDelta::SetNodeImplementation { id, implementation } => {
self.nodes.insert(*id);
if let Implementation::Network(network) = implementation {
self.networks.insert(*network);
}
}
RegistryDelta::RemoveNode { id, .. } | RegistryDelta::ChangeNodeAttribute { id, .. } | RegistryDelta::ChangeNodeInputAttribute { id, .. } => {
self.nodes.insert(*id);
}
RegistryDelta::ChangeNodeInput { id, new_input, .. } => {
self.nodes.insert(*id);
self.reference_inputs([new_input]);
}
RegistryDelta::SetNodeInputs { id, inputs } => {
self.nodes.insert(*id);
self.reference_inputs(inputs.iter().map(|slot| &slot.input));
}
RegistryDelta::SetNetworkExport { id, export, .. } => {
self.networks.insert(*id);
self.reference_inputs(export);
}
RegistryDelta::ChangeNetworkAttribute { id, .. } | RegistryDelta::AddNetwork { id, .. } | RegistryDelta::RemoveNetwork { id, .. } => {
self.networks.insert(*id);
}
RegistryDelta::AddResource { .. } | RegistryDelta::SetResourceHash { .. } | RegistryDelta::RemoveResource { .. } | RegistryDelta::AddSource { .. } | RegistryDelta::RemoveSource { .. } => {
self.resources = true;
}
RegistryDelta::RegisterPeer { .. } | RegistryDelta::ChangeDocumentAttribute { .. } | RegistryDelta::Merge { .. } | RegistryDelta::Meta | RegistryDelta::Other(_) => {}
}
}
pub fn extend(&mut self, other: Touched) {
self.nodes.extend(other.nodes);
self.networks.extend(other.networks);
self.resources |= other.resources;
}
pub fn is_empty(&self) -> bool {
self.nodes.is_empty() && self.networks.is_empty() && !self.resources
}
fn reference_inputs<'a>(&mut self, inputs: impl IntoIterator<Item = &'a NodeInput>) {
for input in inputs {
if let NodeInput::Node { id, .. } = input {
self.nodes.insert(*id);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AttributeDelta, Network, Node};
#[test]
fn an_input_write_touches_the_node_it_references_as_well_as_its_target() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeNodeInput {
id: NodeId(1),
index: 0,
new_input: NodeInput::Node { id: NodeId(2), index: 0 },
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1), NodeId(2)]));
assert!(touched.networks.is_empty());
assert!(!touched.resources);
}
#[test]
fn an_export_touches_the_network_and_the_node_it_targets() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::SetNetworkExport {
id: NetworkId(3),
index: 0,
export: Some(NodeInput::Node { id: NodeId(4), index: 0 }),
});
assert_eq!(touched.networks, BTreeSet::from([NetworkId(3)]));
assert_eq!(touched.nodes, BTreeSet::from([NodeId(4)]));
}
#[test]
fn ops_outside_the_graph_touch_nothing_or_only_the_resource_flag() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::ChangeDocumentAttribute {
delta: AttributeDelta { key: "key".into(), value: None },
});
touched.record(&RegistryDelta::Merge { extra_parents: Vec::new() });
assert!(touched.is_empty());
touched.record(&RegistryDelta::SetResourceHash {
id: crate::ResourceId::new(),
hash: None,
});
assert!(touched.resources);
assert!(touched.nodes.is_empty());
}
#[test]
fn a_node_add_touches_the_node_its_network_and_what_its_inputs_reference() {
let mut node = Node::dummy();
let network = node.network;
node.inputs.push(crate::InputSlot {
input: NodeInput::Node { id: NodeId(9), index: 0 },
timestamp: crate::TimeStamp::ORIGIN,
attributes: Default::default(),
});
let mut touched = Touched::default();
touched.record(&RegistryDelta::AddNode { id: NodeId(8), node });
touched.record(&RegistryDelta::AddNetwork {
id: NetworkId(5),
network: Network::default(),
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(8), NodeId(9)]));
assert_eq!(touched.networks, BTreeSet::from([network, NetworkId(5)]));
}
#[test]
fn implementing_a_node_by_a_network_touches_both() {
let mut touched = Touched::default();
touched.record(&RegistryDelta::SetNodeImplementation {
id: NodeId(1),
implementation: Implementation::Network(NetworkId(2)),
});
assert_eq!(touched.nodes, BTreeSet::from([NodeId(1)]));
assert_eq!(touched.networks, BTreeSet::from([NetworkId(2)]));
}
#[test]
fn adding_a_node_implemented_by_a_network_touches_that_network_too() {
let mut node = Node::dummy();
let network = node.network;
node.implementation = Implementation::Network(NetworkId(2));
let mut touched = Touched::default();
touched.record(&RegistryDelta::AddNode { id: NodeId(1), node });
assert_eq!(touched.networks, BTreeSet::from([network, NetworkId(2)]));
}
}
+11 -28
View File
@@ -2,7 +2,7 @@ use crate::application::{Editor, Environment};
use crate::dispatcher::Dispatcher;
use crate::messages::prelude::*;
use crate::node_graph_executor::{NodeGraphExecutor, NodeRuntime};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use crate::task::{Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,8 +96,6 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
let RuntimeBuilder {
wake: runtime_wake,
mut application_io,
scheduling,
clock,
} = runtime;
graphene_std::uuid::set_uuid_seed(random_seed);
@@ -109,8 +107,7 @@ impl Builder<ReadyEditorBuilder, ReadyRuntimeBuilder, Spawner, u64> {
application_io.inject_resource_proxy(dispatcher.message_handlers.resource_storage_message_handler.resources());
node_runtime.replace_application_io(application_io);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
node_runtime.replace_task_executor(spawner, runtime_wake);
(Editor { dispatcher }, node_runtime)
}
@@ -187,18 +184,17 @@ impl<W, E, R> EditorBuilder<W, E, R, ()> {
pub struct RuntimeBuilder<W = (), A = ()> {
wake: W,
application_io: A,
clock: Arc<dyn Clock>,
scheduling: Scheduling,
}
impl RuntimeBuilder {
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
pub fn new() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
}
}
@@ -208,25 +204,12 @@ impl<A> RuntimeBuilder<(), A> {
RuntimeBuilder {
wake: Arc::new(wake),
application_io: self.application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W> RuntimeBuilder<W, ()> {
pub fn with_application_io(self, application_io: PlatformApplicationIo) -> RuntimeBuilder<W, PlatformApplicationIo> {
RuntimeBuilder {
wake: self.wake,
application_io,
clock: self.clock,
scheduling: self.scheduling,
}
}
}
impl<W, A> RuntimeBuilder<W, A> {
pub fn with_scheduling(self, scheduling: Scheduling) -> Self {
Self { scheduling, ..self }
RuntimeBuilder { wake: self.wake, application_io }
}
}
@@ -3,6 +3,7 @@ use crate::messages::layout::utility_types::widget_prelude::*;
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use graph_craft::application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesDialogMessageContext<'a> {
@@ -361,10 +362,44 @@ impl PreferencesDialogMessageHandler {
// =============
{
let is_desktop = cfg!(not(target_family = "wasm"));
if is_desktop {
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
rows.push(header);
let header = vec![TextLabel::new("Compatibility").italic(true).widget_instance()];
let render_tile_resolution_description = "
Maximum X or Y resolution per render tile. Larger tiles may improve performance but can cause flickering or missing content in complex artwork if set too high.\n\
\n\
*Default: 1280 px.*
"
.trim();
let render_tile_resolution_label = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
TextLabel::new("Render Tile Resolution")
.tooltip_label("Render Tile Resolution")
.tooltip_description(render_tile_resolution_description)
.widget_instance(),
];
let render_tile_resolution = vec![
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
NumberInput::new(Some(preferences.max_render_region_size as f64))
.tooltip_label("Render Tile Resolution")
.tooltip_description(render_tile_resolution_description)
.mode_range()
.int()
.min(256.)
.max(4096.)
.increment_step(256.)
.unit(" px")
.on_update(|number_input: &NumberInput| {
let size = number_input.value.unwrap_or(EditorPreferences::default().max_render_region_size as f64) as u32;
PreferencesMessage::MaxRenderRegionSize { size }.into()
})
.widget_instance(),
];
rows.extend_from_slice(&[header, render_tile_resolution_label, render_tile_resolution]);
if is_desktop {
let ui_acceleration_description = "
Use the CPU to draw the Graphite user interface (areas outside of the canvas) instead of the GPU. This does not affect the rendering of artwork in the canvas, which remains hardware accelerated.\n\
\n\
@@ -263,11 +263,8 @@ pub enum FrontendMessage {
UpdateRenderStatus {
status: RenderStatus,
},
/// Gives the frontend the canvas images it lacks, and names every canvas the latest render uses so it can drop the rest.
UpdateImageData {
image_data: Vec<RasterizedImage>,
#[serde(rename = "canvasIdsInUse")]
canvas_ids_in_use: Vec<u64>,
},
UpdateDocumentLayerDetails {
data: LayerPanelEntry,
@@ -197,7 +197,7 @@ mod tests {
for file_type in [FileType::Png, FileType::Jpg, FileType::Webp, FileType::Tiff, FileType::Bmp, FileType::Tga, FileType::Ico] {
let encoded = file_type.encode(2, 1, pixels.clone()).unwrap_or_else(|error| panic!("{file_type:?}: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|error| panic!("{file_type:?} should read back: {error}"));
let decoded = Image::from_encoded(&encoded).unwrap_or_else(|| panic!("{file_type:?} should read back"));
assert_eq!((decoded.width, decoded.height), (2, 1), "{file_type:?}");
// Only JPG lacks transparency, so it lands on white
+23 -11
View File
@@ -1,17 +1,29 @@
use graph_craft::application_io::http;
use reqwest::IntoUrl;
#[derive(Debug, Clone, Default)]
pub struct Client;
#[derive(Debug, Clone)]
pub struct Client {
inner: Option<reqwest::Client>,
}
impl Default for Client {
fn default() -> Self {
Self {
#[cfg(not(target_family = "wasm"))]
inner: reqwest::Client::builder().timeout(std::time::Duration::from_secs(100)).build().ok(),
#[cfg(target_family = "wasm")]
inner: reqwest::Client::builder().build().ok(),
}
}
}
impl Client {
pub async fn fetch(&self, url: &str) -> Option<Box<[u8]>> {
let url = url.parse().map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
let mut request = reqwest::Request::new(reqwest::Method::GET, url);
if cfg!(not(target_family = "wasm")) {
*request.timeout_mut() = Some(std::time::Duration::from_secs(100));
}
let response = http::send(request).await.map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
let response = response.error_for_status().map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
pub async fn fetch<U: IntoUrl>(&self, url: U) -> Option<Box<[u8]>> {
let Some(client) = &self.inner else {
log::error!("HTTP client failed to initialize, cannot fetch");
return None;
};
let response = client.get(url).send().await;
let response = response.and_then(|r| r.error_for_status()).map_err(|err| log::error!("failed to fetch: {err}")).ok()?;
let bytes = response.bytes().await.map_err(|err| log::error!("failed to read response body: {err}")).ok()?;
Some(bytes.to_vec().into_boxed_slice())
}
@@ -11,7 +11,6 @@ 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;
@@ -19,7 +18,7 @@ use graphene_std::raster::{
AdjustmentChannel, CellularDistanceFunction, CellularReturnType, DesaturateMethod, DomainWarpType, FractalType, HueSaturationRange, NoiseType, RedGreenBlue, RelativeAbsolute,
SelectiveColorChoice, TonalRange,
};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -33,7 +32,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, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
use kurbo::BezPath;
use std::any::Any;
use std::sync::Arc;
@@ -378,7 +377,6 @@ macro_rules! inspectable_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
List<i64>,
@@ -435,7 +433,6 @@ macro_rules! inspectable_types {
Item<Raster<GPU>>,
Item<Color>,
Item<Gradient>,
Item<Generator>,
Item<String>,
Item<f64>,
Item<i64>,
@@ -779,45 +776,6 @@ 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"
@@ -883,7 +841,6 @@ 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(),
@@ -892,7 +849,6 @@ 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(),
}
@@ -910,7 +866,6 @@ 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),
@@ -919,7 +874,6 @@ 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),
}
@@ -980,7 +934,18 @@ impl TableItemLayout for Raster<CPU> {
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![ImageLabel::new(self.png_data_url().to_string()).widget_instance()];
let base64_string = raster.base64_string.clone().unwrap_or_else(|| {
use base64::Engine;
let output = raster.to_png();
let preamble = "data:image/png;base64,";
let mut base64_string = String::with_capacity(preamble.len() + output.len() * 4);
base64_string.push_str(preamble);
base64::engine::general_purpose::STANDARD.encode_string(output, &mut base64_string);
base64_string
});
let widgets = vec![ImageLabel::new(base64_string).widget_instance()];
vec![LayoutGroup::row(widgets)]
}
}
@@ -990,15 +955,9 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
format!("Raster ({} x {})", self.data().width(), self.data().height())
}
fn value_page(&self, _data: &mut LayoutData) -> Vec<LayoutGroup> {
if self.is_empty() {
let widgets = vec![TextLabel::new("Image has no area").widget_instance()];
return vec![LayoutGroup::row(widgets)];
}
let widgets = vec![TextLabel::new("This raster data is a texture on the GPU. It currently cannot be displayed here.").widget_instance()];
vec![LayoutGroup::row(widgets)]
}
@@ -1249,11 +1208,6 @@ 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,
@@ -1400,11 +1354,9 @@ macro_rules! known_item_types {
List<Raster<GPU>>,
List<Color>,
List<Gradient>,
List<Generator>,
List<String>,
List<f64>,
Gradient,
Generator,
Color,
NodeId,
DAffine2,
@@ -1426,12 +1378,6 @@ macro_rules! known_item_types {
Appearance,
Coverage,
Cover,
Effects,
Effect,
EffectKind,
GlowSource,
BevelStyle,
BevelDirection,
DashPattern,
BoxCorners,
TransferCurve,
@@ -315,9 +315,6 @@ pub enum DocumentMessage {
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
},
UpdateEffectsReach {
effects_reach: HashMap<NodeId, f64>,
},
Undo,
UngroupSelectedLayers,
UngroupLayer {
@@ -1877,14 +1877,6 @@ 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;
@@ -759,26 +759,20 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
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 [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);
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -169,27 +169,27 @@ 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(5), 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(-21, -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)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -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)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 0)),
..Default::default()
},
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
@@ -201,12 +201,20 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::node(NodeId(2), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
..Default::default()
},
// The monitor node is used to display a thumbnail in the UI
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(3), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
skip_deduplication: true,
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(4), 0)],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
..Default::default()
@@ -237,7 +245,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(4), 0)],
nodes: [
NodeTemplate {
call_argument: generic!(T),
@@ -249,14 +257,14 @@ 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)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, -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)),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-21, 3)),
..Default::default()
},
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
@@ -268,13 +276,22 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
NodeInput::node(NodeId(1), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
..Default::default()
},
// The monitor node is used to display a thumbnail in the UI.
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(2), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::monitor::IDENTIFIER),
call_argument: generic!(T),
skip_deduplication: true,
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(3), 0),
],
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
@@ -623,25 +640,53 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
.collect(),
..Default::default()
}),
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String(String::new()), false)],
inputs: vec![NodeInput::value(TaggedValue::None, false), NodeInput::value(TaggedValue::String("graphite:null".to_string()), false)],
input_metadata: vec![
("Empty", "Has no effect, since the image is loaded from the URL.").into(),
("URL", "The web address or local asset path of the image to load.").into(),
],
output_names: vec!["Image".to_string()],
output_descriptions: vec!["The loaded image.".to_string()],
output_descriptions: vec!["The loaded image, which is empty if it fails to load or decode.".to_string()],
..Default::default()
},
description: Cow::Borrowed("Loads an image from a given URL."),
inspector: None,
},
#[cfg(feature = "gpu")]
#[cfg(all(feature = "gpu", target_family = "wasm"))]
DocumentNodeDefinition {
identifier: "Rasterize",
category: "Raster",
icon: Some("NodeRasterize"),
node_template: NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(2), 0)],
nodes: [
NodeTemplate {
inputs: vec![],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::create_canvas::IDENTIFIER),
skip_deduplication: true,
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, 2)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: NodeTemplateImplementation::ProtoNode(memo::memoize::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(7, 2)),
..Default::default()
},
NodeTemplate {
inputs: vec![NodeInput::import(generic!(T), 0), NodeInput::import(item!(Footprint), 1), NodeInput::node(NodeId(1), 0)],
implementation: NodeTemplateImplementation::ProtoNode(platform_application_io::rasterize::IDENTIFIER),
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(14, 0)),
..Default::default()
},
]
.into_iter()
.enumerate()
.map(|(id, node)| (NodeId(id as u64), node))
.collect(),
..Default::default()
}),
inputs: vec![
NodeInput::type_default(list!(Vector), true),
NodeInput::value(
@@ -834,14 +879,13 @@ 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.")),
Box::new(|_node_id, _context| node_inspector::string_inspector("Used internally by the editor to obtain a layer thumbnail.")),
);
map
}
@@ -1549,10 +1593,6 @@ impl InputTypeConstraint {
warn!("Input types for extract node {name} not supported");
Self::All
}
NodeTemplateImplementation::Definition(_) => {
warn!("Input types for definition node {name} not supported");
Self::All
}
}
}
@@ -149,6 +149,6 @@ fn fill_proto_node_metadata(node_template: &mut NodeTemplate, definitions_map: &
node_template.locked = definition_template.locked;
node_template.pinned = definition_template.pinned;
}
NodeTemplateImplementation::Definition(_) | NodeTemplateImplementation::Extract => {}
NodeTemplateImplementation::Extract => {}
}
}
@@ -2,7 +2,7 @@ use super::utility_types::{Direction, NodeEvaluationError};
use crate::messages::input_mapper::utility_types::keyboard::Key;
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::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector};
use crate::messages::portfolio::document::utility_types::network_interface::{ChainInsertionPoint, ChainNodeCopy, ImportOrExport, InputConnector, NodeTemplate, OutputConnector, RootNode};
use crate::messages::prelude::*;
use glam::IVec2;
use graph_craft::document::value::TaggedValue;
@@ -75,6 +75,10 @@ pub enum NodeGraphMessage {
DisconnectImportExport {
index: ImportOrExport,
},
DisconnectRootNode,
SetRootNodeToRestore {
root_node_to_restore: RootNode,
},
EnterNestedNetwork,
DuplicateSelectedNodes,
ExposeInput {
@@ -11,7 +11,7 @@ use crate::messages::portfolio::document::utility_types::document_metadata::Laye
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
use crate::messages::portfolio::document::utility_types::network_interface::{
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionCheckpoint,
};
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
@@ -471,6 +471,10 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
ImportOrExport::Import(import_index) => {
network_interface.disconnect_import_wires(import_index, breadcrumb_network_path);
}
// While previewing, drop the wire the preview would restore, as dragging it off does
ImportOrExport::Export(0) if matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { root_node_to_restore: Some(_) }) => {
network_interface.start_previewing_without_restore(breadcrumb_network_path);
}
ImportOrExport::Export(export_index) => network_interface.disconnect_input(&InputConnector::Export(export_index), breadcrumb_network_path),
}
network_interface.remove_orphaned_dots(breadcrumb_network_path);
@@ -478,6 +482,12 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::SendGraph);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
NodeGraphMessage::DisconnectRootNode => {
network_interface.start_previewing_without_restore(selection_network_path);
}
NodeGraphMessage::SetRootNodeToRestore { root_node_to_restore } => {
network_interface.set_root_node_to_restore(root_node_to_restore, selection_network_path);
}
// Duplicates in the flow like everywhere else
NodeGraphMessage::DuplicateSelectedNodes => responses.add(DocumentMessage::DuplicateSelectedLayers),
NodeGraphMessage::EnterNestedNetwork => {
@@ -514,7 +524,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
responses.add(NodeGraphMessage::BeginEditLayerName { node_id: layer_id });
return;
}
if let Some(DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_)) = network_interface.implementation(&node_id, selection_network_path) {
if let Some(DocumentNodeImplementation::Network(_)) = network_interface.implementation(&node_id, selection_network_path) {
responses.add(DocumentMessage::EnterNestedNetwork { node_id });
}
}
@@ -1386,7 +1396,18 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
self.wire_in_progress_to_connector = Some(point);
// Disconnect if the wire was previously connected to an input
if let Some(disconnecting) = &self.disconnecting {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
let mut disconnect_root_node = false;
if let Previewing::Yes { root_node_to_restore } = network_interface.previewing(selection_network_path)
&& root_node_to_restore.is_some()
&& *disconnecting == InputConnector::Export(0)
{
disconnect_root_node = true;
}
if disconnect_root_node {
responses.add(NodeGraphMessage::DisconnectRootNode);
} else {
responses.add(NodeGraphMessage::DisconnectInput { input_connector: *disconnecting });
}
// Picking up a wire from the end of a dot leaves that dot with nothing to redirect
responses.add(NodeGraphMessage::RemoveOrphanedDots);
// Update the frontend that the node is disconnected
@@ -1802,6 +1823,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
.into_iter()
.collect::<HashSet<_>>();
let previewing = network_interface.previewing(selection_network_path);
for selected_node in &all_selected_nodes {
// Handle inputs of selected node
for input_index in 0..network_interface.number_of_inputs(selected_node, selection_network_path) {
@@ -1828,6 +1850,17 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
first_deselected_upstream_output = upstream_of(&node_id);
}
// While previewing, the export's eventual return to this node is a connection too, so it moves upstream as well
if let Some(OutputConnector::Node { node_id, output_index }) = first_deselected_upstream_output
&& let Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
} = previewing && root_node_to_restore.to_connector() == OutputConnector::primary_output(*selected_node)
{
responses.add(NodeGraphMessage::SetRootNodeToRestore {
root_node_to_restore: RootNode { node_id, output_index },
});
}
let number_of_outputs = network_interface.number_of_outputs(selected_node, selection_network_path);
let Some(outward_wires) = network_interface.outward_wires(selection_network_path) else {
log::error!("Could not get output wires in shake input");
@@ -3062,7 +3095,7 @@ impl NodeGraphMessageHandler {
.filter(|input| network_interface.input_from_connector(input, network_path).is_some_and(|input| input.is_exposed()))
.filter_map(|input| network_interface.wire_update_from_input(input, wire_style, glide_offsets, network_path))
.collect::<Vec<_>>();
wires.extend(network_interface.wire_to_preview(wire_style, glide_offsets, network_path));
wires.extend(network_interface.wire_to_root(wire_style, glide_offsets, network_path));
wires
}
@@ -3382,7 +3415,14 @@ impl NodeGraphMessageHandler {
warn!("No network in update_selection_action_buttons");
return;
};
let previewing = network_interface.previewing(breadcrumb_network_path).previewed().map(|previewed| previewed.node_id);
let previewing = if matches!(network_interface.previewing(breadcrumb_network_path), Previewing::Yes { .. }) {
network.exports.iter().find_map(|export| {
let NodeInput::Node { node_id, .. } = export else { return None };
Some(*node_id)
})
} else {
None
};
// If only one node is selected then show the preview or stop previewing button
if let Some(node_id) = previewing {
@@ -3670,8 +3710,8 @@ impl NodeGraphMessageHandler {
wire_path_update: None,
}));
if let Some(wire_to_preview) = network_interface.wire_to_preview(graph_wire_style, &GlideOffsets::default(), breadcrumb_network_path) {
added_wires.push(wire_to_preview);
if let Some(wire_to_root) = network_interface.wire_to_root(graph_wire_style, &GlideOffsets::default(), breadcrumb_network_path) {
added_wires.push(wire_to_root);
} else {
added_wires.push(WirePathUpdate {
id: NodeId(u64::MAX),
@@ -3722,7 +3762,11 @@ impl NodeGraphMessageHandler {
log::error!("Could not get position for node: {node_id}");
continue;
};
let previewed = network_interface.previewing(breadcrumb_network_path).previews(node_id);
let is_export = network_interface
.input_from_connector(&InputConnector::Export(0), breadcrumb_network_path)
.is_some_and(|export| export.as_node().is_some_and(|export_node_id| node_id == export_node_id));
let is_root_node = network_interface.root_node(breadcrumb_network_path).is_some_and(|root_node| root_node.node_id == node_id);
let previewed = is_export && !is_root_node;
let locked = network_interface.is_locked(&node_id, breadcrumb_network_path);
@@ -3758,7 +3802,7 @@ impl NodeGraphMessageHandler {
let mut subgraph_names = vec!["Document".to_string()];
for node_id in breadcrumb_network_path {
let node = current_network.nodes.get(node_id)?;
if let Some(network) = network_interface.document_network().implementation_network(&node.implementation) {
if let Some(network) = node.implementation.get_network() {
current_network = network;
};
subgraph_names.push(network_interface.display_name(node_id, &current_network_path));
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -388,7 +388,6 @@ 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
// ============
@@ -439,9 +438,6 @@ 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(),
@@ -1372,8 +1368,8 @@ fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<GPU>),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
@@ -3001,79 +2997,6 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
}
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
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::*;
@@ -34,8 +34,6 @@ 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<'static> {
pub fn take_scene(self) -> VelloSceneBuilder {
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<'static>,
scene: VelloSceneBuilder,
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<'static> {
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
const MAX_TEXTURE_SIZE: u32 = 2048;
@@ -638,7 +638,7 @@ impl OverlayContextInternal {
let inner_circle = kurbo::Circle::new((position.x, position.y), MANIPULATOR_GROUP_MARKER_SIZE / 2.);
let color_fill = if selected { COLOR_OVERLAY_BLUE } else { COLOR_OVERLAY_WHITE };
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &inner_circle);
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &circle);
self.scene.stroke(&kurbo::Stroke::new(1.), transform, Self::parse_color(COLOR_OVERLAY_BLUE), None, &inner_circle);
}
@@ -775,41 +775,19 @@ impl OverlayContextInternal {
#[allow(clippy::too_many_arguments)]
fn dashed_ellipse(
&mut self,
center: DVec2,
radius_x: f64,
radius_y: f64,
rotation: Option<f64>,
start_angle: Option<f64>,
end_angle: Option<f64>,
counterclockwise: Option<bool>,
color_fill: Option<&str>,
color_stroke: Option<&str>,
dash_width: Option<f64>,
dash_gap_width: Option<f64>,
dash_offset: Option<f64>,
_center: DVec2,
_radius_x: f64,
_radius_y: f64,
_rotation: Option<f64>,
_start_angle: Option<f64>,
_end_angle: Option<f64>,
_counterclockwise: Option<bool>,
_color_fill: Option<&str>,
_color_stroke: Option<&str>,
_dash_width: Option<f64>,
_dash_gap_width: Option<f64>,
_dash_offset: Option<f64>,
) {
let transform = self.get_transform();
let center = self.snap_to_physical_pixel(center);
let start_angle = start_angle.unwrap_or_default();
let end_angle = end_angle.unwrap_or(TAU);
let sweep_angle = match counterclockwise.unwrap_or_default() {
false if end_angle - start_angle >= TAU => TAU,
false => (end_angle - start_angle).rem_euclid(TAU),
true if start_angle - end_angle >= TAU => -TAU,
true => -(start_angle - end_angle).rem_euclid(TAU),
};
let arc = kurbo::Arc::new((center.x, center.y), (radius_x, radius_y), start_angle, sweep_angle, rotation.unwrap_or_default());
if let Some(color_fill) = color_fill {
self.scene.fill(peniko::Fill::NonZero, transform, Self::parse_color(color_fill), None, &arc);
}
let mut stroke = kurbo::Stroke::new(1.);
if let Some(dash_width) = dash_width {
stroke = stroke.with_dashes(dash_offset.unwrap_or(0.), [dash_width, dash_gap_width.unwrap_or(1.)]);
}
self.scene.stroke(&stroke, transform, Self::parse_color(color_stroke.unwrap_or(COLOR_OVERLAY_BLUE)), None, &arc);
}
fn draw_arc(&mut self, center: DVec2, radius: f64, start_from: f64, end_at: f64) {
@@ -1179,7 +1157,7 @@ impl OverlayContextInternal {
// Lay out the text once, taking its dimensions and vector paths from the same thread-local context pass
let (text_size, text_list) = TextContext::with_thread_local(|text_context| {
let text_size = text_context.bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false).unwrap_or_default();
let text_list = text_context.to_path(text, &FALLBACK_FONT_RESOURCE, typesetting, false);
(text_size, text_list)
});
let text_width = text_size.x;
@@ -93,7 +93,7 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
.collect::<Vec<(DataSource, Option<ResourceHash>)>>();
async fn resolve_to_message(document_id: DocumentId, resource_id: ResourceId, source: DataSource, url: Url, client: &Client) -> Option<Message> {
let result = client.fetch(url.as_str()).await;
let result = client.fetch(url.clone()).await;
match result {
Some(data) => {
let hash = ResourceHash::from(data.as_ref());
@@ -51,8 +51,6 @@ 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.
@@ -349,22 +347,21 @@ 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, 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| {
/// stroke geometry when the layer is a vector with a stroke style. Falls back to the click-target-based
/// bounds for non-vector layers (groups, raster, text, color, gradient).
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
if let Some(item) = self.layer_vector_data.get(&layer) {
let stroke = self
.layer_appearance_attributes
.get(&layer)
.and_then(|appearance| appearance.first_coverage_of(graphene_std::Cover::Stroke))
.map(graphene_std::Coverage::stroke_params);
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)?;
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
Some([min - reach, max + reach])
if let Some(bounds) = item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref()) {
return Some(bounds);
}
}
self.bounding_box_document(layer)
}
/// Get the bounding box of the click target of the specified layer in viewport space
@@ -720,26 +717,6 @@ pub struct NodeRelations {
mod tests {
use super::*;
#[test]
fn stroked_bounds_include_the_items_after_the_first() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
let line = |from: f64, to: f64| {
let mut path = BezPath::new();
path.move_to((from, 0.));
path.line_to((to, 0.));
path
};
// Only the first item is recorded as vector data, while click targets cover every item
let mut metadata = DocumentMetadata::default();
metadata.layer_vector_data.insert(layer, Arc::new(Vector::item_from_bezpath(&line(0., 10.))));
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_and_effects(layer).unwrap();
assert_eq!((min.x, max.x), (0., 110.));
}
#[test]
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
@@ -164,7 +164,6 @@ impl Default for PathSnapping {
#[derive(Clone, Copy, Debug, serde::Serialize, serde::Deserialize, PartialEq)]
pub enum GridType {
// TODO: Eventually remove this alias document upgrade code
#[serde(alias = "Rectangle")]
Rectangular {
spacing: DVec2,
@@ -50,7 +50,7 @@ use glam::{DAffine2, DVec2, IVec2};
use graph_craft::Type;
use graph_craft::application_io::resource::ResourceId;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NetworkId, NetworkLocation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork, OldDocumentNodeImplementation, OldNodeNetwork};
use graphene_std::Appearance;
use graphene_std::math::quad::Quad;
use graphene_std::registry::MULTI_OUTPUT_NODES;
@@ -129,20 +129,15 @@ impl PartialEq for NodeNetworkInterface {
}
impl NodeNetworkInterface {
// TODO: Eventually remove this document upgrade code
/// Normalizes the stored types of every node at every nesting level, for an older document whose stored types predate the current form.
pub fn normalize_stored_types(&mut self) {
self.migrate_graph(NodeNetwork::normalize_stored_types);
}
// TODO: Eventually remove this document upgrade code
/// Add DocumentNodePath input to the PathModifyNode protonode
pub fn migrate_path_modify_node(&mut self) {
self.migrate_graph(fix_network);
fn fix_network(network: &mut NodeNetwork) {
for definition in network.definitions.values_mut() {
fix_network(definition);
}
for node in network.nodes.values_mut() {
if let Some(network) = node.implementation.get_network_mut() {
fix_network(network);
@@ -190,67 +185,4 @@ mod network_interface_tests {
"duplicated node should exist\nother nodes: {nodes:#?}\noriginal {original:#?}"
);
}
#[test]
fn instance_paths_resolve_through_the_definitions_table() {
use super::*;
let definition = NetworkId(1);
let instance = |implementation| DocumentNode { implementation, ..Default::default() };
let instances = [NodeId(10), NodeId(11)];
let network = NodeNetwork {
nodes: instances.iter().map(|&id| (id, instance(DocumentNodeImplementation::Definition(definition)))).collect(),
definitions: [(definition, NodeNetwork::value_network(instance(DocumentNodeImplementation::default())))].into_iter().collect(),
..Default::default()
};
let mut definition_metadata = NodeNetworkMetadata::default();
definition_metadata.persistent_metadata.reference = Some("Artboard".into());
definition_metadata.persistent_metadata.node_metadata.insert(NodeId(0), DocumentNodeMetadata::default());
let mut network_metadata = NodeNetworkMetadata::default();
let mut instance_metadata = DocumentNodeMetadata::default();
instance_metadata.persistent_metadata.output_names = vec![String::new()];
for id in instances {
network_metadata.persistent_metadata.node_metadata.insert(id, instance_metadata.clone());
}
network_metadata.persistent_metadata.definitions.insert(definition, definition_metadata);
let interface = NodeNetworkInterface::from_trees(network.clone(), network_metadata.clone());
let paths = instances.map(|id| [id]);
let views = paths.each_ref().map(|path| interface.view(path).unwrap());
assert!(std::ptr::eq(views[0].network, views[1].network));
assert!(std::ptr::eq(views[0].metadata, views[1].metadata));
assert!(views[0].node_metadata(&NodeId(0)).is_ok());
let document_view = interface.view(&[]).unwrap();
assert_eq!(document_view.reference(&NodeId(10)), Ok(Some(DefinitionIdentifier::Network("Artboard".into()))));
assert_eq!(document_view.number_of_outputs(&NodeId(10)), Ok(1));
assert_eq!(interface.validate_invariants(), Vec::<String>::new());
let unused = NetworkId(2);
let mut network_with_unused = network.clone();
network_with_unused
.definitions
.insert(unused, NodeNetwork::value_network(instance(DocumentNodeImplementation::default())));
let mut metadata_with_unused = network_metadata.clone();
metadata_with_unused.persistent_metadata.definitions.insert(unused, NodeNetworkMetadata::default());
let with_unused = NodeNetworkInterface::from_trees(network_with_unused, metadata_with_unused);
assert_eq!(with_unused.validate_invariants(), vec!["Node 0 in network [] has no metadata entry".to_string()]);
let mut mismatched_network = network;
mismatched_network.nodes.get_mut(&NodeId(11)).unwrap().inputs.push(NodeInput::value(TaggedValue::None, false));
network_metadata
.persistent_metadata
.node_metadata
.get_mut(&NodeId(11))
.unwrap()
.persistent_metadata
.input_metadata
.push(InputMetadata::default());
let mismatched = NodeNetworkInterface::from_trees(mismatched_network, network_metadata);
assert_eq!(mismatched.validate_invariants().len(), 1);
}
}
@@ -676,7 +676,9 @@ impl NodeNetworkInterface {
/// The wire into the input as the frontend draws it, with its ends following anything drawn gliding into place.
pub fn wire_update_from_input(&self, input: &InputConnector, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let wire = self.wire_path_from_input(input, graph_wire_style, false, glide_offsets, network_path)?;
// While previewing, the export's wire leads to the temporarily previewed node
let dashed = *input == InputConnector::Export(0) && matches!(self.previewing(network_path), Previewing::Yes { .. });
let wire = self.wire_path_from_input(input, graph_wire_style, dashed, glide_offsets, network_path)?;
let (id, input_index) = match input {
InputConnector::Node { node_id, input_index } => (*node_id, *input_index),
InputConnector::Export(export_index) => (NodeId(u64::MAX), *export_index),
@@ -753,23 +755,27 @@ impl NodeNetworkInterface {
network_metadata.transient_metadata.wires.borrow_mut().remove(input);
}
/// The dashed wire from the previewed node to the export, drawn alongside the export's own wire.
pub fn wire_to_preview(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
/// When previewing, there may be a second path to the root node.
pub fn wire_to_root(&self, graph_wire_style: GraphWireStyle, glide_offsets: &GlideOffsets, network_path: &[NodeId]) -> Option<WirePathUpdate> {
let input = InputConnector::Export(0);
let current_export = self.upstream_output_connector(&input, network_path)?;
let Previewing::Yes { previewed } = self.previewing(network_path) else { return None };
let root_node = match self.previewing(network_path) {
Previewing::Yes { root_node_to_restore } => root_node_to_restore,
Previewing::No => None,
}?;
if self.upstream_output_connector(&input, network_path) == Some(previewed.to_connector()) {
if Some(root_node.node_id) == current_export.node_id() {
return None;
}
let Some(input_position) = self.get_input_center(&input, network_path) else {
log::error!("Could not get input position for wire end in preview: {input:?}");
log::error!("Could not get input position for wire end in root node: {input:?}");
return None;
};
let input_position = input_position + glide_offsets.input(&input);
let upstream_output = OutputConnector::node(previewed.node_id, previewed.output_index);
let upstream_output = OutputConnector::node(root_node.node_id, root_node.output_index);
let Some(output_position) = self.get_output_center(&upstream_output, network_path) else {
log::error!("Could not get output position for wire start in preview: {upstream_output:?}");
log::error!("Could not get output position for wire start in root node: {upstream_output:?}");
return None;
};
let output_position = output_position + glide_offsets.output(&upstream_output);
@@ -781,6 +787,7 @@ impl NodeNetworkInterface {
let path_string = vector_wire.to_svg();
let center_path_string = center_line.to_svg();
// Styled by the root node's own output, since the export it leads to is connected to the previewed node instead
let output_type = self.output_type(&upstream_output, network_path);
let data_type = output_type.displayed_type();
let is_list = output_type.is_list();
@@ -788,7 +795,7 @@ impl NodeNetworkInterface {
path_string,
data_type,
thick,
dashed: true,
dashed: false,
is_list,
center_path_string,
});
@@ -20,13 +20,6 @@ fn rectangle_definition() -> DefinitionIdentifier {
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
}
/// The graph the runtime compiles: the document network with its previews applied.
fn evaluated_network(network_interface: &NodeNetworkInterface) -> graph_craft::document::NodeNetwork {
let mut network = network_interface.document_network().clone();
crate::node_graph_executor::apply_previews(&mut network, &network_interface.previewed_nodes());
network
}
fn new_artboard_message(id: NodeId) -> GraphOperationMessage {
GraphOperationMessage::NewArtboard {
id,
@@ -185,6 +178,31 @@ async fn connecting_an_export_is_never_cyclic() {
assert_invariants(&editor, "after connecting the export");
}
#[tokio::test]
async fn toggling_preview_on_a_disconnected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node = editor.create_node_by_name(rectangle_definition()).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.disconnect_input(&InputConnector::Export(0), &[]);
// Previewing a node while the export is disconnected is a preview with nothing to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::Yes { root_node_to_restore: None });
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert_eq!(export.and_then(|input| input.as_node()), Some(node), "The previewed node should be wired to the export");
// Ending the preview restores the disconnected export
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
let export = network_interface.input_from_connector(&InputConnector::Export(0), &[]);
assert!(export.is_some_and(|input| input.as_node().is_none()), "Ending the preview should disconnect the export again");
assert_invariants(&editor, "after toggling preview twice");
}
#[tokio::test]
async fn artboard_identity_is_independent_of_scene_connectivity() {
let mut editor = EditorTestUtils::create();
@@ -1348,7 +1366,7 @@ async fn showing_a_secondary_import_in_the_inspector_keeps_its_wires_in_the_subg
}
#[tokio::test]
async fn previewing_leaves_the_export_alone() {
async fn toggle_preview_transitions_with_a_connected_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -1360,31 +1378,31 @@ async fn previewing_leaves_the_export_alone() {
let export_node = |network_interface: &super::NodeNetworkInterface| network_interface.input_from_connector(&InputConnector::Export(0), &[]).and_then(|input| input.as_node());
assert_eq!(export_node(network_interface), Some(artboard));
// Previewing a node names it without touching the export
// Previewing a node remembers the artboard as the connection to restore
network_interface.toggle_preview(node, &[]);
assert_eq!(export_node(network_interface), Some(node));
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: node, output_index: 0 }
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 })
}
);
assert_eq!(export_node(network_interface), Some(artboard), "Previewing must not rewire the export");
// Toggling the previewed node again ends the preview, leaving the export as it always was
// Toggling the previewed node again restores the artboard connection
network_interface.toggle_preview(node, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the node feeding the export while previewing ends the preview
// Toggling the restore node while previewing ends the preview by restoring it
network_interface.toggle_preview(node, &[]);
network_interface.toggle_preview(artboard, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
// Toggling the node already feeding the export changes nothing
network_interface.toggle_preview(artboard, &[]);
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_eq!(export_node(network_interface), Some(artboard));
assert_eq!(network_interface.previewing(&[]), Previewing::No);
assert_invariants(&editor, "after cycling through the preview states");
}
@@ -2823,7 +2841,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
}
#[tokio::test]
async fn previewing_keeps_the_dot_on_the_export_wire_and_outlasts_removing_other_dots() {
async fn previewing_keeps_the_dot_it_will_restore_the_export_to_and_outlasts_removing_other_dots() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
@@ -2853,7 +2871,7 @@ async fn previewing_keeps_the_dot_on_the_export_wire_and_outlasts_removing_other
network_interface.remove_orphaned_dots(&[]);
assert!(!exists(&editor, other_dot), "the dot left with nothing to feed should be removed");
assert!(exists(&editor, export_dot), "the dot on the export's wire should stay while previewing");
assert!(exists(&editor, export_dot), "the dot the preview will restore the export to should stay");
assert!(
matches!(editor.active_document().network_interface.previewing(&[]), Previewing::Yes { .. }),
"removing a dot outside the preview should leave it running"
@@ -2863,7 +2881,7 @@ async fn previewing_keeps_the_dot_on_the_export_wire_and_outlasts_removing_other
assert_eq!(
editor.active_document().network_interface.upstream_output_connector(&InputConnector::Export(0), &[]),
Some(OutputConnector::node(export_dot, 0)),
"ending the preview should leave the export wired through the dot"
"ending the preview should restore the export to the dot"
);
assert_invariants(&editor, "after previewing past a dot on the export's wire");
}
@@ -3323,189 +3341,3 @@ async fn resting_a_wire_on_an_exposed_input_reveals_nothing_that_would_move_it_f
);
assert!(!exposed(&editor, translation) && !exposed(&editor, scale), "the unused revealed inputs should hide again");
}
#[tokio::test]
async fn the_evaluated_network_renders_the_previewed_node() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let evaluated = evaluated_network(network_interface);
assert_eq!(
evaluated.exports.first().and_then(|export| export.as_node()),
Some(node),
"The network being evaluated should export the previewed node"
);
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The document itself should be unchanged"
);
}
#[test]
fn a_preview_written_by_the_rewiring_version_still_deserializes() {
let stored = r#"{"Yes":{"root_node_to_restore":{"node_id":7,"output_index":1}}}"#;
let previewing: Previewing = serde_json::from_str(stored).expect("a preview written by the rewiring version should deserialize");
assert_eq!(
previewing,
Previewing::LegacyRewired {
root_node_to_restore: Some(RootNode { node_id: NodeId(7), output_index: 1 })
},
"The stored preview should be read as one needing migration"
);
}
#[test]
fn the_current_preview_shape_round_trips() {
let previewing = Previewing::Yes {
previewed: RootNode { node_id: NodeId(7), output_index: 1 },
};
let stored = serde_json::to_string(&previewing).expect("previewing should serialize");
assert_eq!(serde_json::from_str::<Previewing>(&stored).expect("previewing should deserialize"), previewing);
}
#[tokio::test]
async fn migrating_a_rewired_preview_restores_the_export() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
// What the rewiring version saved: the export wired to the previewed node, and the artboard recorded to restore
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::Export(0), &[]);
let Some(mut network) = network_interface.network_mut(&[]) else {
panic!("the document network should resolve")
};
network.set_previewing(Previewing::LegacyRewired {
root_node_to_restore: Some(RootNode { node_id: artboard, output_index: 0 }),
});
network_interface.migrate_rewired_previews();
assert_eq!(
network_interface.document_network().exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The export should be back to what the document recorded to restore"
);
assert_eq!(
network_interface.previewing(&[]),
Previewing::Yes {
previewed: RootNode { node_id: node, output_index: 0 }
},
"The node the export had been moved to should become the preview"
);
assert_eq!(
evaluated_network(network_interface).exports.first().and_then(|export| export.as_node()),
Some(node),
"What is evaluated should still be the previewed node, so the user sees what they saved"
);
}
#[tokio::test]
async fn toggling_a_preview_changes_the_network_hash() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
let before = network_interface.network_hash();
network_interface.toggle_preview(node, &[]);
let previewing = network_interface.network_hash();
assert_ne!(before, previewing, "Starting a preview should change the hash, since it changes what is evaluated");
network_interface.toggle_preview(node, &[]);
assert_eq!(before, network_interface.network_hash(), "Ending the preview should return the hash to what it was");
}
#[tokio::test]
async fn toggling_a_node_to_a_layer_changes_the_network_hash() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
let before = network_interface.network_hash();
network_interface.set_to_node_or_layer(&node, &[], true);
assert_ne!(
before,
network_interface.network_hash(),
"A new layer should change the hash, since it gives the runtime another thumbnail to render"
);
network_interface.set_to_node_or_layer(&node, &[], false);
assert_eq!(before, network_interface.network_hash(), "Returning to a node should return the hash to what it was");
}
#[tokio::test]
async fn the_network_hash_is_stable_while_previewing() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let hash = network_interface.network_hash();
for _ in 0..8 {
assert_eq!(hash, network_interface.network_hash(), "Re-reading the hash of an unchanged document should give the same value");
}
}
#[tokio::test]
async fn a_session_preview_of_a_removed_node_is_dropped() {
use super::storage_metadata::{apply_network_view_settings, collect_network_view_settings};
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let artboard = NodeId::new();
editor.handle_message(new_artboard_message(artboard)).await;
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 20).await;
let network_interface = &mut editor.active_document_mut().network_interface;
network_interface.toggle_preview(node, &[]);
let network_ids = HashMap::from([(Vec::new(), document_graph_storage::NetworkId(0))]);
let stored = collect_network_view_settings(network_interface, &network_ids);
// As if another peer had removed the previewed node
network_interface.delete_nodes(vec![node], false, &[]);
apply_network_view_settings(network_interface, &network_ids, &stored);
assert_eq!(
network_interface.previewing(&[]),
Previewing::No,
"A preview naming a node the document no longer has should be dropped rather than restored"
);
assert_eq!(
evaluated_network(network_interface).exports.first().and_then(|export| export.as_node()),
Some(artboard),
"The evaluated network should fall back to the document's own export"
);
}
@@ -1,7 +1,3 @@
// TODO: Eventually remove this document upgrade code
// This file holds the older serialized shapes of the network metadata, read once when a document is
// opened and converted to the current form.
use crate::messages::portfolio::document::utility_types::network_interface::{DocumentNodePersistentMetadata, InputMetadata, InputPersistentMetadata, NodeNetworkMetadata, NodeTypePersistentMetadata};
use serde_json::Value;
use std::collections::HashMap;
@@ -25,11 +25,9 @@ impl NodeNetworkInterface {
self.unload_import_export_ports(network_path);
}
/// Unloads what a node's name or lock state feeds: a layer's width, the geometry sized from it, and
/// the network bounds that geometry contributes to.
/// Unloads what a node's name or lock state feeds: a layer's width, and the geometry sized from it.
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
self.try_unload_layer_width(node_id, network_path);
self.unload_node_click_targets(node_id, network_path);
self.unload_all_nodes_bounding_box(network_path);
}
}
@@ -902,7 +902,7 @@ impl NodeNetworkInterface {
let layer_output = NodeInput::node(layer.to_node(), 0);
match post_node_input {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
// First child in the stack: wire layer output to the post_node input
self.set_input_for_import(&post_node, layer_output, network_path);
}
@@ -956,6 +956,7 @@ impl NodeNetworkInterface {
}
// Disconnect layer to move
self.stop_previewing(network_path);
self.remove_references_from_network(&layer.to_node(), network_path);
let post_node = self.post_node_with_index(parent, insert_index, network_path);
@@ -1031,7 +1032,7 @@ impl NodeNetworkInterface {
if !inserting_into_stack {
match post_node_input {
// Create a new stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
self.create_wire(&OutputConnector::primary_output(layer.to_node()), &post_node, network_path);
let final_layer_position = after_move_post_layer_position + IVec2::new(-LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP);
@@ -1057,7 +1058,7 @@ impl NodeNetworkInterface {
} else {
match post_node_input {
// Move to the bottom of the stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
let offset = after_move_post_layer_position - previous_layer_position + IVec2::new(0, STACK_VERTICAL_GAP + height_above_layer);
self.shift_absolute_node_position(&layer.to_node(), offset, network_path);
self.create_wire(&OutputConnector::primary_output(layer.to_node()), &post_node, network_path);
@@ -19,9 +19,13 @@ impl NodeNetworkInterface {
let other_persistent = &other_network_metadata.persistent_metadata;
*view.navigation = other_persistent.navigation_metadata.clone();
*view.previewing = match other_persistent.previewing.previewed() {
Some(previewed) if !view.nodes.contains_key(&previewed.node_id) => Previewing::No,
_ => other_persistent.previewing,
// The live preview root may name a node that the rebuilt-from-storage network no longer contains
// (e.g. after a storage undo), so only carry it over when the root still exists; otherwise drop it.
*view.previewing = match other_persistent.previewing {
Previewing::Yes {
root_node_to_restore: Some(root_node),
} if !view.nodes.contains_key(&root_node.node_id) => Previewing::No,
previewing => previewing,
};
*view.selection.undo = other_persistent.selection_undo_history.clone();
@@ -447,9 +451,7 @@ impl NodeNetworkInterface {
// When opening an old document to ensure the output names match the number of exports
pub fn validate_output_names(&mut self, node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId]) {
let Some(network) = self.document_network().implementation_network(&node.implementation) else {
return;
};
let DocumentNodeImplementation::Network(network) = &node.implementation else { return };
let number_of_exports = network.exports.len();
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
@@ -623,10 +625,7 @@ impl NodeNetworkInterface {
self.unload_all_nodes_bounding_box(network_path);
// A nested network draws its interior ports from the encapsulating node's inputs
if matches!(
self.implementation(node_id, network_path),
Some(DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_))
) {
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Network(_))) {
let nested_path = [network_path, &[*node_id]].concat();
self.invalidate_import_export(&nested_path);
}
@@ -659,13 +658,13 @@ impl NodeNetworkInterface {
}
// A wire to or from the imports changed
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. }) => {
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
self.unload_wire(input_connector, network_path);
}
// A node was disconnected
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }) => {
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }) => {
self.unload_wire(input_connector, network_path);
if let Some((old_upstream_node_id, previous_position)) = disconnected_upstream
@@ -914,6 +913,15 @@ impl NodeNetworkInterface {
return;
}
// Removing a dot the preview shows or restores the export to ends the preview, as deleting any node does
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
let previewed = self.upstream_output_connector(&InputConnector::Export(0), network_path).and_then(|output| output.node_id());
let restored = root_node_to_restore.map(|root_node| root_node.node_id);
if orphans.iter().any(|dot| Some(*dot) == previewed || Some(*dot) == restored) {
self.stop_previewing(network_path);
}
}
self.delete_nodes_leaving_dots(orphans.iter().copied().collect(), false, network_path);
// A dot that failed to be deleted isn't judged again, so this always comes to an end
@@ -936,13 +944,14 @@ impl NodeNetworkInterface {
match side {
DotSide::Incoming => self.upstream_output_connector(&InputConnector::primary_input(*node_id), network_path).is_none(),
DotSide::Outgoing => {
let previewed = self.previewing(network_path).previews(*node_id);
// The export a preview will restore to the dot still counts as taking its output
let restored_by_preview = matches!(self.previewing(network_path), Previewing::Yes { root_node_to_restore: Some(root_node) } if root_node.node_id == *node_id);
let consumed = self
.with_outward_wires(network_path, |outward_wires| {
outward_wires.get(&OutputConnector::primary_output(*node_id)).is_some_and(|inputs| !inputs.is_empty())
})
.unwrap_or_default();
!previewed && !consumed
!restored_by_preview && !consumed
}
}
}
@@ -950,6 +959,9 @@ impl NodeNetworkInterface {
/// Deletes the nodes and any sole dependents in the horizontal chain if the node to delete is a layer node,
/// along with any redirect dots left without a wire once they're gone.
pub fn delete_nodes(&mut self, nodes_to_delete: Vec<NodeId>, delete_children: bool, network_path: &[NodeId]) {
// TODO: Add more logic to support retaining preview when removing references. Since there are so many edge cases/possible crashes, for now the preview is ended.
self.stop_previewing(network_path);
self.delete_nodes_leaving_dots(nodes_to_delete, delete_children, network_path);
self.remove_orphaned_dots(network_path);
}
@@ -1078,10 +1090,6 @@ impl NodeNetworkInterface {
/// Removes all references to the node with the given id from the network, and reconnects the input to the node below.
pub fn remove_references_from_network(&mut self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
if self.previewing(network_path).previews(*node_id) {
self.set_previewing(Previewing::No, network_path);
}
// The wire the downstream inputs reconnect to, which is the first exposed input of the node being removed
let reconnect_to_input = self.document_node(node_id, network_path).and_then(|node| {
node.inputs
@@ -1155,6 +1163,58 @@ impl NodeNetworkInterface {
true
}
pub fn start_previewing_without_restore(&mut self, network_path: &[NodeId]) {
// Some logic will have to be performed to prevent the graph positions from being completely changed when the export changes to some previewed node
self.set_previewing_state(Previewing::Yes { root_node_to_restore: None }, network_path);
}
/// While previewing, changes which node output the export is reconnected to once the preview ends.
pub fn set_root_node_to_restore(&mut self, root_node_to_restore: RootNode, network_path: &[NodeId]) {
if let Previewing::Yes { .. } = self.previewing(network_path) {
self.set_previewing_state(
Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
},
network_path,
);
}
}
pub(super) fn stop_previewing(&mut self, network_path: &[NodeId]) {
if let Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
} = self.previewing(network_path)
{
self.set_input(
&InputConnector::Export(0),
NodeInput::node(root_node_to_restore.node_id, root_node_to_restore.output_index),
network_path,
);
}
self.set_previewing_state(Previewing::No, network_path);
}
fn set_previewing_state(&mut self, previewing: Previewing, network_path: &[NodeId]) {
// A dot the preview was to restore the export to may be left with nothing taking its output
if let Previewing::Yes {
root_node_to_restore: Some(root_node),
} = self.previewing(network_path)
&& self.is_redirect_dot(&root_node.node_id, network_path)
{
self.dots_that_lost_a_wire.entry(network_path.to_vec()).or_default().insert((root_node.node_id, DotSide::Outgoing));
}
let Some(mut network) = self.network_mut(network_path) else {
log::error!("Could not get nested network_metadata in set_previewing_state");
return;
};
network.set_previewing(previewing);
// The export's wire is dashed only while previewing
self.unload_wire(&InputConnector::Export(0), network_path);
}
pub fn set_display_name(&mut self, node_id: &NodeId, display_name: String, network_path: &[NodeId]) {
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
log::error!("Could not get node {node_id} in set_display_name");
@@ -1379,34 +1439,91 @@ impl NodeNetworkInterface {
self.load_structure();
}
/// Renders `toggle_id` in place of the network's export, or stops doing so if it already is.
pub fn toggle_preview(&mut self, toggle_id: NodeId, network_path: &[NodeId]) {
let primary_output = RootNode { node_id: toggle_id, output_index: 0 };
let previewing = if self.previewing(network_path).previews(toggle_id) || self.root_node(network_path) == Some(primary_output) {
Previewing::No
} else {
Previewing::Yes { previewed: primary_output }
let Some(network) = self.nested_network(network_path) else {
return;
};
self.set_previewing(previewing, network_path);
}
// If new_export is None then disconnect
let mut new_export = None;
let mut new_previewing_state = Previewing::No;
if let Some(export) = network.exports.first() {
// If there currently an export
if let NodeInput::Node { node_id, output_index, .. } = export {
let previous_export_id = *node_id;
let previous_output_index = *output_index;
fn set_previewing(&mut self, previewing: Previewing, network_path: &[NodeId]) {
if let Some(mut network) = self.network_mut(network_path) {
network.set_previewing(previewing);
}
}
// The export is clicked
if *node_id == toggle_id {
// If the current export is clicked and is being previewed end the preview and set either export back to root node or disconnect
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
new_export = root_node_to_restore.map(|root_node| root_node.to_connector());
new_previewing_state = Previewing::No;
}
// The export is clicked and there is no preview, so it already shows the primary output a preview would
else if previous_output_index == 0 {
return;
}
// The export is clicked and there is no preview, but it comes from another output, so preview the primary one and restore that afterward
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
// The export is not clicked
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
// TODO: Eventually remove this document upgrade code
/// Converts previews written by versions that previewed by rewiring the export, putting the export back.
pub fn migrate_rewired_previews(&mut self) {
for (network_path, root_node_to_restore) in self.legacy_rewired_previews() {
let previewing = self.root_node(&network_path).map_or(Previewing::No, |previewed| Previewing::Yes { previewed });
match root_node_to_restore {
Some(root_node) => self.create_wire(&root_node.to_connector(), &InputConnector::Export(0), &network_path),
None => self.disconnect_input(&InputConnector::Export(0), &network_path),
// There is currently a dashed line being drawn
if let Previewing::Yes { root_node_to_restore } = self.previewing(network_path) {
// There is also a solid line being drawn
if let Some(root_node_to_restore) = root_node_to_restore {
// If the node with the solid line is clicked, then end the preview by restoring it
if root_node_to_restore.node_id == toggle_id {
new_export = Some(root_node_to_restore.to_connector());
new_previewing_state = Previewing::No;
} else {
// Root node to restore does not change
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(root_node_to_restore),
};
}
}
// There is a dashed line without a solid line.
else {
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
}
// Not previewing, there is no dashed line being drawn
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes {
root_node_to_restore: Some(RootNode {
node_id: previous_export_id,
output_index: previous_output_index,
}),
};
}
}
}
// The primary export is disconnected, so preview the node with nothing to restore, which disconnects the export again when the preview ends
else {
new_export = Some(OutputConnector::primary_output(toggle_id));
new_previewing_state = Previewing::Yes { root_node_to_restore: None };
}
self.set_previewing(previewing, &network_path);
}
match new_export {
Some(new_export) => {
self.create_wire(&new_export, &InputConnector::Export(0), network_path);
}
None => {
self.disconnect_input(&InputConnector::Export(0), network_path);
}
}
self.set_previewing_state(new_previewing_state, network_path);
}
}
@@ -1,5 +1,4 @@
use super::*;
use std::hash::{Hash, Hasher};
/// Index of the Artboard definition's Clip input, which must match the input order authored in document_node_definitions.rs.
pub(crate) const ARTBOARD_CLIP_INPUT_INDEX: usize = 5;
@@ -23,69 +22,6 @@ impl NodeNetworkInterface {
pub fn document_network(&self) -> &NodeNetwork {
self.network.network()
}
/// The node each network previews in place of its export, paired with that network's path and sorted by it.
pub fn previewed_nodes(&self) -> Vec<(Vec<NodeId>, RootNode)> {
let mut previewed = Vec::new();
self.for_each_network(&mut |network_path, network_metadata| {
let Some(root_node) = network_metadata.persistent_metadata.previewing.previewed() else { return };
let replaces_export = self
.document_network()
.nested_network(network_path)
.is_some_and(|network| !network.exports.is_empty() && network.nodes.contains_key(&root_node.node_id));
if replaces_export {
previewed.push((network_path.to_vec(), root_node));
}
});
previewed.sort_by(|(left, _), (right, _)| left.cmp(right));
previewed
}
// TODO: Eventually remove this document upgrade code
/// Each network whose preview was written by a version that rewired the export, paired with what that version would restore.
pub(crate) fn legacy_rewired_previews(&self) -> Vec<(Vec<NodeId>, Option<RootNode>)> {
let mut legacy = Vec::new();
self.for_each_network(&mut |network_path, network_metadata| {
if let Previewing::LegacyRewired { root_node_to_restore } = network_metadata.persistent_metadata.previewing {
legacy.push((network_path.to_vec(), root_node_to_restore));
}
});
legacy
}
/// The path of every layer in the document's networks.
pub fn layer_paths(&self) -> Vec<Vec<NodeId>> {
let mut layer_paths = Vec::new();
self.for_each_layer(&mut |network_path, layer| layer_paths.push([network_path, &[layer]].concat()));
layer_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 {
if node_metadata.persistent_metadata.is_layer() {
visit(network_path, *node_id);
}
}
});
}
fn for_each_network(&self, visit: &mut impl FnMut(&[NodeId], &NodeNetworkMetadata)) {
fn walk(network_path: &mut Vec<NodeId>, network_metadata: &NodeNetworkMetadata, visit: &mut impl FnMut(&[NodeId], &NodeNetworkMetadata)) {
visit(network_path, network_metadata);
for (node_id, node_metadata) in &network_metadata.persistent_metadata.node_metadata {
let Some(nested) = &node_metadata.persistent_metadata.network_metadata else { continue };
network_path.push(*node_id);
walk(network_path, nested, visit);
network_path.pop();
}
}
walk(&mut Vec::new(), &self.network_metadata, visit);
}
/// Gets the nested network based on network_path
pub fn nested_network(&self, network_path: &[NodeId]) -> Option<&NodeNetwork> {
let Some(network) = self.document_network().nested_network(network_path) else {
@@ -95,23 +31,8 @@ impl NodeNetworkInterface {
Some(network)
}
pub fn locate<'p>(&self, network_path: &'p [NodeId]) -> Option<NetworkLocation<'p>> {
self.document_network().locate(network_path)
}
/// Identifies the graph that would be evaluated, previews included.
pub fn network_hash(&self) -> u64 {
// Layers get thumbnails, so they're hashed too, summed since the order isn't stable. O(nodes) on every render, without allocating.
let mut layers_hash = 0_u64;
self.for_each_layer(&mut |network_path, layer| {
let mut hasher = std::hash::DefaultHasher::new();
(network_path, layer).hash(&mut hasher);
layers_hash = layers_hash.wrapping_add(hasher.finish());
});
let mut hasher = std::hash::DefaultHasher::new();
(self.network.current_hash(), self.previewed_nodes(), layers_hash).hash(&mut hasher);
hasher.finish()
self.network.current_hash()
}
/// Get the specified document node in the nested network based on node_id and network_path
@@ -127,13 +48,9 @@ impl NodeNetworkInterface {
&self.network_metadata
}
pub(crate) fn nested_metadata(&self, network_path: &[NodeId]) -> Option<&NodeNetworkMetadata> {
self.network_metadata.nested_metadata(self.locate(network_path)?)
}
/// The network metadata should always exist for the current network
pub fn network_metadata(&self, network_path: &[NodeId]) -> Option<&NodeNetworkMetadata> {
let Some(network_metadata) = self.nested_metadata(network_path) else {
let Some(network_metadata) = self.network_metadata.nested_metadata(network_path) else {
log::error!("Could not get nested network_metadata with path {network_path:?}");
return None;
};
@@ -970,11 +887,11 @@ impl NodeNetworkInterface {
Some(transformed.bounding_box())
}
/// 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]> {
/// 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]> {
self.document_metadata.document_bounds(include_artboards, true, || {
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
})
}
@@ -991,17 +908,17 @@ impl NodeNetworkInterface {
.reduce(Quad::combine_bounds)
}
/// 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]> {
/// 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]> {
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_and_effects");
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
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_and_effects(layer))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
.reduce(Quad::combine_bounds)
}
@@ -1107,17 +1024,13 @@ impl NodeNetworkInterface {
let mut network_metadata = NodeNetworkMetadata::default();
let mut stack = vec![(Vec::new(), old_network)];
while let Some((network_path, old_network)) = stack.pop() {
let Some(location) = node_network.locate(&network_path) else {
log::error!("Could not locate nested network in from_old_network");
continue;
};
let Some(nested_network) = node_network.located_network_mut(location) else {
let Some(nested_network) = node_network.nested_network_mut(&network_path) else {
log::error!("Could not get nested network in from_old_network");
continue;
};
nested_network.exports = old_network.exports;
nested_network.scope_injections = old_network.scope_injections.into_iter().collect();
let Some(nested_network_metadata) = network_metadata.nested_metadata_mut(location) else {
let Some(nested_network_metadata) = network_metadata.nested_metadata_mut(&network_path) else {
log::error!("Could not get nested network in from_old_network");
continue;
};
@@ -1,7 +1,7 @@
use std::collections::{HashMap, HashSet};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, NodeInput};
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors, Promotion};
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use graphene_std::NodeIOTypes;
@@ -212,7 +212,7 @@ impl NodeNetworkInterface {
};
let node_path = [network_path, &[*node_id]].concat();
match implementation {
DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_) => {
DocumentNodeImplementation::Network(_) => {
let outward_wires = self.with_outward_wires(&node_path, |map| map.get(&OutputConnector::Import(*input_index)).cloned()).flatten();
let Some(outward_wires) = outward_wires else { return false };
outward_wires.iter().any(|connector| match connector {
@@ -257,6 +257,7 @@ impl NodeNetworkInterface {
}
NodeInput::Scope(_) => TypeSource::Compiled(concrete!(())),
NodeInput::Reflection(document_node_metadata) => TypeSource::Compiled(document_node_metadata.ty()),
NodeInput::Inline(_) => TypeSource::Compiled(concrete!(InlineRust)),
}
}
@@ -353,7 +354,7 @@ impl NodeNetworkInterface {
return Vec::new();
};
match implementation {
DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_) => {
DocumentNodeImplementation::Network(_) => {
let nested_path = [network_path, &[*node_id]].concat();
let inputs_from_import = self
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
@@ -390,7 +391,7 @@ impl NodeNetworkInterface {
.any(|connector| type_feeds_input(source_type, connector, conversions))
}
// The wire reaches every interior input fed by the import, so each of them has to accept it
Some(DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_)) => {
Some(DocumentNodeImplementation::Network(_)) => {
let nested_path = [network_path, &[*node_id]].concat();
let interior_inputs = self
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
@@ -434,7 +435,7 @@ impl NodeNetworkInterface {
Box::new(move |source_type| connectors.iter().any(|connector| type_feeds_input(source_type, connector, conversions)))
}
// The wire reaches every interior input fed by the import, so each of them has to accept it
Some(DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_)) => {
Some(DocumentNodeImplementation::Network(_)) => {
let nested_path = [network_path, &[*node_id]].concat();
let interior_inputs = self
.with_outward_wires(&nested_path, |outward_wires| outward_wires.get(&OutputConnector::Import(*input_index)).cloned())
@@ -522,7 +523,7 @@ impl NodeNetworkInterface {
.map(|node_io| node_io.return_value.nested_type().clone())
.collect(),
// A subgraph's output carries whatever feeds its export
Some(DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_)) => {
Some(DocumentNodeImplementation::Network(_)) => {
let nested_path = [network_path, &[*node_id]].concat();
let export = InputConnector::Export(*output_index);
match self.upstream_output_connector(&export, &nested_path) {
@@ -582,9 +583,7 @@ impl NodeNetworkInterface {
return Vec::new();
};
match implementation {
DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_) => {
self.valid_output_types(&OutputConnector::Import(input_connector.input_index()), &[network_path, &[*node_id]].concat())
}
DocumentNodeImplementation::Network(_) => self.valid_output_types(&OutputConnector::Import(input_connector.input_index()), &[network_path, &[*node_id]].concat()),
DocumentNodeImplementation::ProtoNode(proto_node_identifier) => {
let Some(implementations) = NODE_REGISTRY.get(proto_node_identifier) else {
log::error!("Protonode {proto_node_identifier:?} not found in registry in complete_valid_input_types");
@@ -657,9 +656,7 @@ impl NodeNetworkInterface {
return TypeSource::Error("Could not get implementation");
};
match implementation {
DocumentNodeImplementation::Network(_) | DocumentNodeImplementation::Definition(_) => {
self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat())
}
DocumentNodeImplementation::Network(_) => self.input_type(&InputConnector::Export(*output_index), &[network_path, &[*node_id]].concat()),
// The compiler removes passthrough nodes so they resolve no type of their own, but their output carries their primary input's type
DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::ops::passthrough::IDENTIFIER => {
self.input_type(&InputConnector::primary_input(*node_id), network_path)
@@ -737,22 +734,6 @@ mod tests {
assert!(!type_feeds_input(&item!(f64), &item!(Graphic), paint_conversions), "a number has no conversion into a graphic");
}
#[test]
fn a_cpu_raster_feeds_an_input_that_only_takes_gpu_rasters() {
use graphene_std::raster_nodes::dehaze::dehaze::ImageFrameInput;
use graphene_std::raster_types::{CPU, GPU, Raster};
let dehaze_image = input_conversions(&ImageFrameInput::NODE_IDENTIFIER).get(ImageFrameInput::INDEX).copied().flatten();
assert!(
type_feeds_input(&item!(Raster<CPU>), &item!(Raster<GPU>), dehaze_image),
"a CPU raster should upload through the input adapter"
);
assert!(type_feeds_input(&list!(Raster<CPU>), &list!(Raster<GPU>), dehaze_image), "a list of CPU rasters should too");
assert!(type_feeds_input(&item!(Raster<GPU>), &item!(Raster<GPU>), dehaze_image), "a GPU raster should pass through");
assert!(!type_feeds_input(&item!(Raster<GPU>), &item!(Raster<CPU>), None), "nothing downloads a GPU raster implicitly");
}
#[test]
fn items_promote_onto_list_inputs() {
let paint_conversions = input_conversions(&PaintInput::NODE_IDENTIFIER).get(PaintInput::INDEX).copied().flatten();
@@ -114,12 +114,13 @@ impl NodeMetadataSource for StorageMetadataView<'_> {
self.persistent(network_path, local_id)?.storage_id.map(document_graph_storage::NodeId)
}
fn reference(&self, network_path: &[NodeId]) -> Option<&str> {
let network_metadata = self.interface.nested_metadata(network_path)?;
let network_metadata = self.interface.network_metadata.nested_metadata(network_path)?;
network_metadata.persistent_metadata.reference.as_deref()
}
fn pinned_order(&self, network_path: &[NodeId]) -> Vec<NodeId> {
self.interface
.network_metadata
.nested_metadata(network_path)
.map(|network_metadata| network_metadata.persistent_metadata.pinned_node_order.clone())
.unwrap_or_default()
@@ -188,7 +189,7 @@ pub fn build_interface_from_storage(network: NodeNetwork, node_entries: Vec<Node
let mut network_metadata = NodeNetworkMetadata::default();
seed_metadata_tree(&network, &mut network_metadata);
apply_entries_into_tree(&network, &mut network_metadata, node_entries)?;
apply_network_entries_into_tree(&network, &mut network_metadata, network_entries);
apply_network_entries_into_tree(&mut network_metadata, network_entries);
Ok(NodeNetworkInterface::from_trees(network, network_metadata))
}
@@ -210,7 +211,7 @@ pub fn collect_network_view_settings(
let mut out = BTreeMap::new();
for (network_path, &network_id) in network_ids {
let Some(network_metadata) = interface.nested_metadata(network_path) else {
let Some(network_metadata) = interface.network_metadata.nested_metadata(network_path) else {
continue;
};
let navigation = &network_metadata.persistent_metadata.navigation_metadata;
@@ -283,28 +284,17 @@ pub fn apply_network_view_settings(
if let Some(value) = settings.get(session::network::PREVIEWING)
&& let Ok(previewing) = from_value::<Previewing>(value)
&& let Some(mut network) = interface.network_mut(network_path)
{
let previewing = match previewing.previewed() {
Some(previewed) if !network_contains(interface, network_path, previewed.node_id) => Previewing::No,
_ => previewing,
};
if let Some(mut network) = interface.network_mut(network_path) {
network.set_previewing(previewing);
}
network.set_previewing(previewing);
}
}
}
/// Whether the network at `network_path` contains `node_id`, without logging when it doesn't.
fn network_contains(interface: &NodeNetworkInterface, network_path: &[NodeId], node_id: NodeId) -> bool {
interface.document_network().nested_network(network_path).is_some_and(|network| network.nodes.contains_key(&node_id))
}
/// Entries whose `network_path` doesn't resolve are skipped with a warning (per-network drift is more often a stale path than corruption).
fn apply_network_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMetadata, entries: Vec<NetworkMetadataEntry>) {
fn apply_network_entries_into_tree(metadata: &mut NodeNetworkMetadata, entries: Vec<NetworkMetadataEntry>) {
for entry in entries {
let Some(network_metadata) = network.locate(&entry.network_path).and_then(|location| metadata.nested_metadata_mut(location)) else {
let Some(network_metadata) = metadata.nested_metadata_mut(&entry.network_path) else {
log::warn!("apply_network_entries_into_tree: nested network at {:?} not found, skipping", entry.network_path);
continue;
};
@@ -339,10 +329,9 @@ fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMeta
}
for (path, entries) in by_path {
let location = network.locate(&path);
let nested_network = location.and_then(|location| network.located_network(location));
let nested_network = nested_network_at(network, &path);
let Some(network_metadata) = location.and_then(|location| metadata.nested_metadata_mut(location)) else {
let Some(network_metadata) = metadata.nested_metadata_mut(&path) else {
log::warn!("apply_entries_into_tree: nested network at {path:?} not found, skipping {} entries", entries.len());
continue;
};
@@ -400,6 +389,17 @@ fn apply_entries_into_tree(network: &NodeNetwork, metadata: &mut NodeNetworkMeta
Ok(())
}
/// `None` when the path is invalid; callers treat that as "skip silently" since the surrounding `nested_metadata_mut` already warns.
fn nested_network_at<'a>(root: &'a NodeNetwork, path: &[NodeId]) -> Option<&'a NodeNetwork> {
let mut current = root;
for segment in path {
let node = current.nodes.get(segment)?;
let DocumentNodeImplementation::Network(nested) = &node.implementation else { return None };
current = nested;
}
Some(current)
}
/// Storage-side `None` restores as `""` (the runtime's "unset" sentinel for `input_name` / `input_description`).
fn input_metadata_entry_to_runtime(entry: InputMetadataEntry) -> InputMetadata {
InputMetadata {
@@ -23,8 +23,7 @@ impl NodeNetworkInterface {
/// The metadata tree at `network_path`.
fn network_metadata_mut(&mut self, network_path: &[NodeId]) -> Option<&mut NodeNetworkMetadata> {
let location = self.locate(network_path)?;
self.network_metadata.get_mut().nested_metadata_mut(location)
self.network_metadata.get_mut().nested_metadata_mut(network_path)
}
/// The metadata of the node that encapsulates the network at `network_path`, or `None` for the
@@ -35,7 +34,6 @@ impl NodeNetworkInterface {
self.network_metadata_mut(&encapsulating_path)?.persistent_metadata.node_metadata.get_mut(&encapsulating_node_id)
}
// TODO: Eventually remove this document upgrade code, along with the migrations that call it
/// Rewrites the whole graph in place, for a document arriving in an older shape than the current one.
///
/// Nothing is recorded: a migration produces the document the peer should have had rather than
@@ -48,19 +46,17 @@ impl NodeNetworkInterface {
/// The persistent metadata of a network, or `None` if the network is missing.
pub(crate) fn network_mut<'a>(&'a mut self, network_path: &'a [NodeId]) -> Option<NetworkMut<'a>> {
let location = self.locate(network_path)?;
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(location)?.persistent_metadata;
let metadata = &mut self.network_metadata.get_mut().nested_metadata_mut(network_path)?.persistent_metadata;
Some(NetworkMut::new(metadata, &mut self.deltas, network_path))
}
/// Both halves of a node, or `None` if either is missing.
pub(crate) fn node_mut<'a>(&'a mut self, locator: NodeLocator<'a>) -> Option<NodeMut<'a>> {
let location = self.locate(locator.network_path)?;
let node = self.network.get_mut().network_mut().located_network_mut(location)?.nodes.get_mut(&locator.node_id)?;
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.get_mut(&locator.node_id)?;
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(location)?
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.get_mut(&locator.node_id)?;
@@ -357,7 +357,6 @@ impl NodeMut<'_> {
/// Appends input metadata until there is one entry per input, filling from `defaults` where it has an
/// entry for the added index. Restores the parallel-array invariant for an older document.
/// Entries past the last input are kept, since they can hold user-authored names and overrides.
pub(crate) fn pad_input_metadata(&mut self, number_of_inputs: usize, defaults: impl Fn(usize) -> Option<InputMetadata>) {
if self.metadata.input_metadata.len() >= number_of_inputs {
return;
@@ -274,9 +274,14 @@ impl NodeNetworkInterface {
let node = Box::new(document_node.clone());
let metadata = Box::new(persistent_metadata.clone());
let location = self.locate(locator.network_path)?;
let previous_node = self.network.get_mut().network_mut().located_network_mut(location)?.nodes.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(location)?.persistent_metadata.node_metadata.insert(
let previous_node = self
.network
.get_mut()
.network_mut()
.nested_network_mut(locator.network_path)?
.nodes
.insert(locator.node_id, document_node);
let previous_metadata = self.network_metadata.get_mut().nested_metadata_mut(locator.network_path)?.persistent_metadata.node_metadata.insert(
locator.node_id,
DocumentNodeMetadata {
persistent_metadata,
@@ -314,12 +319,11 @@ impl NodeNetworkInterface {
return None;
}
let location = self.locate(locator.network_path)?;
let node = self.network.get_mut().network_mut().located_network_mut(location)?.nodes.remove(&locator.node_id);
let node = self.network.get_mut().network_mut().nested_network_mut(locator.network_path)?.nodes.remove(&locator.node_id);
let metadata = self
.network_metadata
.get_mut()
.nested_metadata_mut(location)?
.nested_metadata_mut(locator.network_path)?
.persistent_metadata
.node_metadata
.remove(&locator.node_id);
@@ -337,8 +341,7 @@ impl NodeNetworkInterface {
/// Whether both trees hold the network, checked before a write so a missing one cannot leave the two
/// halves out of step.
fn network_pair_exists(&self, network_path: &[NodeId]) -> bool {
self.locate(network_path)
.is_some_and(|location| self.network.network().located_network(location).is_some() && self.network_metadata.nested_metadata(location).is_some())
self.network.network().nested_network(network_path).is_some() && self.network_metadata.nested_metadata(network_path).is_some()
}
/// Takes what the writes since the last drain changed, in write order, leaving the buffer empty
@@ -200,9 +200,4 @@ 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;
}
}
@@ -75,7 +75,6 @@ impl Default for NodeTemplate {
#[derive(Debug, Clone, PartialEq)]
pub enum NodeTemplateImplementation {
Network(NodeNetworkTemplate),
Definition(NetworkId),
ProtoNode(ProtoNodeIdentifier),
Extract,
}
@@ -151,7 +150,6 @@ impl NodeTemplate {
navigation_metadata: nested_persistent.navigation_metadata,
})
}
DocumentNodeImplementation::Definition(id) => NodeTemplateImplementation::Definition(id),
DocumentNodeImplementation::ProtoNode(identifier) => NodeTemplateImplementation::ProtoNode(identifier),
DocumentNodeImplementation::Extract => NodeTemplateImplementation::Extract,
};
@@ -228,7 +226,6 @@ impl NodeTemplate {
}
}
// TODO: Eventually remove this document upgrade code
/// Normalizes the stored types at every nesting level via [`DocumentNode::normalize_stored_types`], round-tripping through the split halves to reuse its logic.
pub fn normalize_stored_types(&mut self) {
let (mut document_node, persistent_node_metadata) = std::mem::take(self).into_parts();
@@ -280,13 +277,11 @@ impl NodeTemplateImplementation {
navigation_metadata,
selection_undo_history: Default::default(),
selection_redo_history: Default::default(),
definitions: Default::default(),
},
transient_metadata: Default::default(),
};
(DocumentNodeImplementation::Network(network), Some(network_metadata))
}
NodeTemplateImplementation::Definition(id) => (DocumentNodeImplementation::Definition(id), None),
NodeTemplateImplementation::ProtoNode(identifier) => (DocumentNodeImplementation::ProtoNode(identifier), None),
NodeTemplateImplementation::Extract => (DocumentNodeImplementation::Extract, None),
}
@@ -450,60 +450,15 @@ impl RootNode {
}
}
/// Which node the node graph renders in place of the network's export, as per-peer view state that leaves the export untouched.
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize)]
#[derive(PartialEq, Debug, Clone, Copy, Hash, Default, serde::Serialize, serde::Deserialize)]
pub enum Previewing {
Yes {
previewed: RootNode,
},
// TODO: Eventually remove this document upgrade code
/// Written by versions that previewed by rewiring the export, and converted to `Yes` when the document is opened.
LegacyRewired {
root_node_to_restore: Option<RootNode>,
},
/// If there is a node to restore the connection to the export for, then it is stored in the option.
/// Otherwise, nothing gets restored and the primary export is disconnected.
Yes { root_node_to_restore: Option<RootNode> },
#[default]
No,
}
impl Previewing {
pub fn previewed(&self) -> Option<RootNode> {
match self {
Previewing::Yes { previewed } => Some(*previewed),
_ => None,
}
}
pub fn previews(&self, node_id: NodeId) -> bool {
self.previewed().is_some_and(|previewed| previewed.node_id == node_id)
}
}
// TODO: Eventually remove this document upgrade code, restoring the derived `Deserialize`
impl<'de> serde::Deserialize<'de> for Previewing {
/// Also accepts the shape written by versions that previewed by rewiring the export.
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(serde::Deserialize)]
enum Stored {
Yes(YesFields),
LegacyRewired { root_node_to_restore: Option<RootNode> },
No,
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum YesFields {
Current { previewed: RootNode },
Rewired { root_node_to_restore: Option<RootNode> },
}
Ok(match Stored::deserialize(deserializer)? {
Stored::Yes(YesFields::Current { previewed }) => Previewing::Yes { previewed },
Stored::Yes(YesFields::Rewired { root_node_to_restore }) | Stored::LegacyRewired { root_node_to_restore } => Previewing::LegacyRewired { root_node_to_restore },
Stored::No => Previewing::No,
})
}
}
/// All fields in NetworkMetadata should automatically be updated by using the network interface API. If a field is none then it should be calculated based on the network state.
#[derive(Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct NodeNetworkMetadata {
@@ -528,29 +483,27 @@ impl PartialEq for NodeNetworkMetadata {
}
impl NodeNetworkMetadata {
pub fn nested_metadata(&self, location: NetworkLocation) -> Option<&Self> {
let mut network_metadata = match location.definition {
Some(id) => self.persistent_metadata.definitions.get(&id)?,
None => self,
};
pub fn nested_metadata(&self, nested_path: &[NodeId]) -> Option<&Self> {
let mut network_metadata = Some(self);
for segment in location.inline_path {
network_metadata = network_metadata.persistent_metadata.node_metadata.get(segment)?.persistent_metadata.network_metadata.as_ref()?;
for segment in nested_path {
network_metadata = network_metadata
.and_then(|network| network.persistent_metadata.node_metadata.get(segment))
.and_then(|node| node.persistent_metadata.network_metadata.as_ref());
}
Some(network_metadata)
network_metadata
}
/// Get the mutable nested network given by the path of node ids
pub fn nested_metadata_mut(&mut self, location: NetworkLocation) -> Option<&mut Self> {
let mut network_metadata = match location.definition {
Some(id) => self.persistent_metadata.definitions.get_mut(&id)?,
None => self,
};
pub fn nested_metadata_mut(&mut self, nested_path: &[NodeId]) -> Option<&mut Self> {
let mut network_metadata = Some(self);
for segment in location.inline_path {
network_metadata = network_metadata.persistent_metadata.node_metadata.get_mut(segment)?.persistent_metadata.network_metadata.as_mut()?;
for segment in nested_path {
network_metadata = network_metadata
.and_then(|network: &mut NodeNetworkMetadata| network.persistent_metadata.node_metadata.get_mut(segment))
.and_then(|node| node.persistent_metadata.network_metadata.as_mut());
}
Some(network_metadata)
network_metadata
}
}
@@ -579,8 +532,6 @@ pub struct NodeNetworkPersistentMetadata {
/// Stack of selection snapshots for future history states.
#[serde(skip)]
pub selection_redo_history: VecDeque<SelectedNodes>,
#[serde(default, skip_serializing_if = "HashMap::is_empty")]
pub definitions: HashMap<NetworkId, NodeNetworkMetadata>,
}
/// A lazily computed cache slot whose load and read paths work through &self, with interior mutability guarding the stored value.
@@ -1137,9 +1088,6 @@ pub(crate) fn visit_network_resources(network: &NodeNetwork, visit: &mut impl Fn
for node in network.nodes.values() {
visit_node_resources(node, visit);
}
for definition in network.definitions.values() {
visit_network_resources(definition, visit);
}
}
pub(crate) fn visit_node_resources(node: &DocumentNode, visit: &mut impl FnMut(ResourceId)) {
@@ -1195,37 +1143,6 @@ mod tests {
assert_eq!(visits.len(), 4);
}
#[test]
fn resource_visits_reach_each_definition_once() {
let definition = NetworkId(1);
let used = ResourceId::from(1);
let instance = || DocumentNode {
implementation: DocumentNodeImplementation::Definition(definition),
..Default::default()
};
let body = NodeNetwork {
nodes: [(
NodeId(0),
DocumentNode {
inputs: vec![NodeInput::value(TaggedValue::Resource(used), false)],
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let network = NodeNetwork {
nodes: [(NodeId(1), instance()), (NodeId(2), instance())].into_iter().collect(),
definitions: [(definition, body)].into_iter().collect(),
..Default::default()
};
let mut visits = Vec::new();
visit_network_resources(&network, &mut |id| visits.push(id));
assert_eq!(visits, vec![used]);
}
#[test]
fn port_click_targets_reach_around_the_connector_where_wires_attach() {
let center = DVec2::new(100., 50.);
@@ -1,5 +1,5 @@
use super::{InputConnector, NodeNetworkInterface, NodeNetworkMetadata};
use graph_craft::document::{DocumentNodeImplementation, NetworkId, NodeId, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use std::collections::{HashMap, HashSet};
impl NodeNetworkInterface {
@@ -9,44 +9,12 @@ impl NodeNetworkInterface {
// O(nodes + wires) summed across all nesting levels, plus an acyclicity walk per network
pub fn validate_invariants(&self) -> Vec<String> {
let mut violations = Vec::new();
self.validate_definition_tables(&mut violations);
let mut root = DocumentRoot {
network: self.document_network(),
metadata: &self.network_metadata,
definition_import_counts: HashMap::new(),
};
validate_network(&mut root, self.document_network(), &self.network_metadata, &mut Vec::new(), Some(0), &mut violations);
for (id, definition) in &self.document_network().definitions {
if root.definition_import_counts.contains_key(id) {
continue;
}
let Some(definition_metadata) = self.network_metadata.persistent_metadata.definitions.get(id) else {
continue;
};
root.definition_import_counts.insert(*id, None);
validate_network(&mut root, definition, definition_metadata, &mut Vec::new(), None, &mut violations);
}
self.validate_outward_wires(&mut Vec::new(), &mut HashSet::new(), &mut violations);
validate_network(self.document_network(), &self.network_metadata, &mut Vec::new(), 0, &mut violations);
self.validate_outward_wires(&mut Vec::new(), &mut violations);
self.validate_dots_stay_on_wires(&mut violations);
violations
}
/// The definitions table and its metadata table must contain exactly the same definitions.
fn validate_definition_tables(&self, violations: &mut Vec<String>) {
let definitions = &self.document_network().definitions;
let definition_metadata = &self.network_metadata.persistent_metadata.definitions;
for id in definitions.keys().filter(|id| !definition_metadata.contains_key(id)) {
violations.push(format!("Definition {id:?} has no metadata entry"));
}
for id in definition_metadata.keys().filter(|id| !definitions.contains_key(id)) {
violations.push(format!("Metadata entry for definition {id:?} has no corresponding definition"));
}
}
/// A redirect dot an edit took a wire from must be gone by the time the edit is done if that left it orphaned.
fn validate_dots_stay_on_wires(&self, violations: &mut Vec<String>) {
for (network_path, lost_wires) in &self.dots_that_lost_a_wire {
@@ -57,7 +25,7 @@ impl NodeNetworkInterface {
}
/// A loaded outward wire cache must match a fresh computation from the network.
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, validated_definitions: &mut HashSet<NetworkId>, violations: &mut Vec<String>) {
fn validate_outward_wires(&self, path: &mut Vec<NodeId>, violations: &mut Vec<String>) {
let Some(network) = self.nested_network(path) else { return };
if let Some(computed) = self.compute_outward_wires(path)
@@ -77,14 +45,9 @@ impl NodeNetworkInterface {
}
for (node_id, node) in &network.nodes {
let descend = match node.implementation {
DocumentNodeImplementation::Network(_) => true,
DocumentNodeImplementation::Definition(id) => validated_definitions.insert(id),
_ => false,
};
if descend {
if matches!(node.implementation, DocumentNodeImplementation::Network(_)) {
path.push(*node_id);
self.validate_outward_wires(path, validated_definitions, violations);
self.validate_outward_wires(path, violations);
path.pop();
}
}
@@ -100,15 +63,7 @@ fn wire_counts(inputs: &[InputConnector]) -> HashMap<InputConnector, usize> {
counts
}
struct DocumentRoot<'a> {
network: &'a NodeNetwork,
metadata: &'a NodeNetworkMetadata,
definition_import_counts: HashMap<NetworkId, Option<usize>>,
}
fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: Option<usize>, violations: &mut Vec<String>) {
let (document_network, document_metadata) = (root.network, root.metadata);
fn validate_network(network: &NodeNetwork, network_metadata: &NodeNetworkMetadata, path: &mut Vec<NodeId>, import_count: usize, violations: &mut Vec<String>) {
let node_metadata = &network_metadata.persistent_metadata.node_metadata;
// The network and its metadata tree must contain exactly the same set of nodes
@@ -134,17 +89,13 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
let validate_input = |input: &NodeInput, location: &str, violations: &mut Vec<String>| match input {
NodeInput::Node { node_id, output_index, .. } => match network.nodes.get(node_id) {
None => violations.push(format!("{location} in network {path:?} references nonexistent node {node_id}")),
Some(target) if *output_index >= document_network.implementation_output_count(&target.implementation) => {
Some(target) if *output_index >= target.implementation.output_count() => {
violations.push(format!("{location} in network {path:?} references nonexistent output {output_index} of node {node_id}"));
}
_ => {}
},
NodeInput::Import { import_index, .. } => {
if let Some(import_count) = import_count
&& *import_index >= import_count
{
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
}
NodeInput::Import { import_index, .. } if *import_index >= import_count => {
violations.push(format!("{location} in network {path:?} references nonexistent import {import_index} of {import_count}"));
}
_ => {}
};
@@ -175,22 +126,19 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
));
}
let validate_output_names = |export_count: usize, violations: &mut Vec<String>| {
if persistent.output_names.len() != export_count {
violations.push(format!(
"Node {node_id} in network {path:?} has {export_count} exports but {} output names",
persistent.output_names.len()
));
}
};
// Nested network metadata must exist exactly for nodes implemented as networks
match (&node.implementation, &persistent.network_metadata) {
(DocumentNodeImplementation::Network(nested_network), Some(nested_metadata)) => {
validate_output_names(nested_network.exports.len(), violations);
if persistent.output_names.len() != nested_network.exports.len() {
violations.push(format!(
"Node {node_id} in network {path:?} has {} exports but {} output names",
nested_network.exports.len(),
persistent.output_names.len()
));
}
path.push(*node_id);
validate_network(root, nested_network, nested_metadata, path, Some(node.inputs.len()), violations);
validate_network(nested_network, nested_metadata, path, node.inputs.len(), violations);
path.pop();
}
(DocumentNodeImplementation::Network(_), None) => {
@@ -199,31 +147,6 @@ fn validate_network(root: &mut DocumentRoot, network: &NodeNetwork, network_meta
(_, Some(_)) => {
violations.push(format!("Non-network node {node_id} in network {path:?} has nested network metadata"));
}
(DocumentNodeImplementation::Definition(id), None) => {
let Some(definition) = document_network.definitions.get(id) else {
violations.push(format!("Node {node_id} in network {path:?} references nonexistent definition {id:?}"));
continue;
};
validate_output_names(definition.exports.len(), violations);
match root.definition_import_counts.get(id) {
Some(&Some(validated_import_count)) if validated_import_count != node.inputs.len() => violations.push(format!(
"Node {node_id} in network {path:?} has {} inputs but another instance of definition {id:?} has {validated_import_count}",
node.inputs.len()
)),
Some(_) => {}
None => {
root.definition_import_counts.insert(*id, Some(node.inputs.len()));
let Some(definition_metadata) = document_metadata.persistent_metadata.definitions.get(id) else {
continue;
};
path.push(*node_id);
validate_network(root, definition, definition_metadata, path, Some(node.inputs.len()), violations);
path.pop();
}
}
}
(_, None) => {}
}
}
@@ -30,10 +30,14 @@ pub struct NetworkView<'a, 'p> {
impl NodeNetworkInterface {
/// Resolves a read cursor for the network at `network_path`, walking the nested network and metadata trees once.
pub fn view<'a, 'p>(&'a self, network_path: &'p [NodeId]) -> Result<NetworkView<'a, 'p>, NetworkError> {
let not_found = || NetworkError::NetworkNotFound { path: network_path.to_vec() };
let location = self.locate(network_path).ok_or_else(not_found)?;
let network = self.document_network().located_network(location).ok_or_else(not_found)?;
let metadata = self.document_network_metadata().nested_metadata(location).ok_or_else(not_found)?;
let network = self
.document_network()
.nested_network(network_path)
.ok_or_else(|| NetworkError::NetworkNotFound { path: network_path.to_vec() })?;
let metadata = self
.document_network_metadata()
.nested_metadata(network_path)
.ok_or_else(|| NetworkError::NetworkNotFound { path: network_path.to_vec() })?;
Ok(NetworkView {
interface: self,
@@ -92,14 +96,19 @@ impl<'a, 'p> NetworkView<'a, 'p> {
}
pub fn reference(&self, node_id: &NodeId) -> Result<Option<DefinitionIdentifier>, NetworkError> {
let network_metadata = match self.implementation(node_id)? {
DocumentNodeImplementation::Network(_) => self.node_metadata(node_id)?.persistent_metadata.network_metadata.as_ref(),
DocumentNodeImplementation::Definition(id) => self.interface.network_metadata.persistent_metadata.definitions.get(id),
DocumentNodeImplementation::ProtoNode(protonode_id) => return Ok(Some(DefinitionIdentifier::ProtoNode(protonode_id.clone()))),
DocumentNodeImplementation::Extract => return Ok(None),
};
let network_metadata = network_metadata.ok_or(NetworkError::NestedMetadataNotFound { node_id: *node_id })?;
Ok(network_metadata.persistent_metadata.reference.clone().map(DefinitionIdentifier::Network))
match self.implementation(node_id)? {
DocumentNodeImplementation::Network(_) => {
let node_metadata = self.node_metadata(node_id)?;
let network_metadata = node_metadata
.persistent_metadata
.network_metadata
.as_ref()
.ok_or(NetworkError::NestedMetadataNotFound { node_id: *node_id })?;
Ok(network_metadata.persistent_metadata.reference.clone().map(DefinitionIdentifier::Network))
}
DocumentNodeImplementation::ProtoNode(protonode_id) => Ok(Some(DefinitionIdentifier::ProtoNode(protonode_id.clone()))),
_ => Ok(None),
}
}
pub fn is_layer(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
@@ -242,17 +251,9 @@ impl<'a, 'p> NetworkView<'a, 'p> {
Ok(self.input_row_count(node_id)?.max(self.number_of_outputs(node_id)?).max(1))
}
pub fn implementation_network(&self, node_id: &NodeId) -> Result<Option<&'a NodeNetwork>, NetworkError> {
let implementation = self.implementation(node_id)?;
Ok(self.interface.document_network().implementation_network(implementation))
}
pub fn number_of_outputs(&self, node_id: &NodeId) -> Result<usize, NetworkError> {
if let Some(nested_network) = self.implementation_network(node_id)? {
return Ok(nested_network.exports.len());
}
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(nested_network) => nested_network.exports.len(),
// A multi-output proto node has an output for each field of the struct it returns
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).map_or(1, |metadata| metadata.number_of_outputs()),
_ => 1,
@@ -273,11 +274,8 @@ impl<'a, 'p> NetworkView<'a, 'p> {
}
pub fn hidden_primary_output(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
if let Some(network) = self.implementation_network(node_id)? {
return Ok(network.exports.first().is_none_or(|input| !input.is_exposed()));
}
Ok(match self.implementation(node_id)? {
DocumentNodeImplementation::Network(network) => network.exports.first().is_none_or(|input| !input.is_exposed()),
DocumentNodeImplementation::ProtoNode(identifier) => MULTI_OUTPUT_NODES.get(identifier).is_some_and(|metadata| metadata.hidden_primary_output()),
_ => false,
})
@@ -296,14 +294,20 @@ impl<'a, 'p> NetworkView<'a, 'p> {
self.metadata.persistent_metadata.previewing
}
/// The node output wired to the primary export, if any.
/// The root node (the node that the solid line is connected to), or None if no nodes are connected to the output.
pub fn root_node(&self) -> Option<RootNode> {
match self.network.exports.first() {
Some(NodeInput::Node { node_id, output_index, .. }) => Some(RootNode {
node_id: *node_id,
output_index: *output_index,
match &self.metadata.persistent_metadata.previewing {
Previewing::Yes { root_node_to_restore } => *root_node_to_restore,
Previewing::No => self.network.exports.first().and_then(|export| {
if let NodeInput::Node { node_id, output_index, .. } = export {
Some(RootNode {
node_id: *node_id,
output_index: *output_index,
})
} else {
None
}
}),
_ => None,
}
}
@@ -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::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -299,6 +299,10 @@ 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"],
@@ -496,7 +500,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::mix_colors::IDENTIFIER,
node: graphene_std::raster_nodes::blending_nodes::mix::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::BlendNode",
"raster_nodes::adjustments::BlendNode",
@@ -504,12 +508,11 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::BlendNode",
"graphene_raster_nodes::blending_nodes::BlendNode",
"raster_nodes::blending_nodes::BlendNode",
"raster_nodes::blending_nodes::MixNode",
],
},
NodeReplacement {
node: graphene_std::raster_nodes::effects::blur::IDENTIFIER,
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
@@ -518,7 +521,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::BrightnessContrastNode",
"graphene_raster_nodes::adjustments::brightness_contrast_classic",
"graphene_raster_nodes::adjustments::BrightnessContrastClassicNode",
"raster_nodes::adjustments::BrightnessContrastClassicNode",
],
},
NodeReplacement {
@@ -529,9 +531,8 @@ 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::effects::paint_overlay::IDENTIFIER,
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -539,7 +540,6 @@ 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 {
@@ -1195,49 +1195,10 @@ fn is_monitored_transform_subgraph(node: &DocumentNode) -> bool {
monitor_reads_first_import && transform_reads_monitor_and_other_imports && exports_transform
}
/// The CPU node a removed GPU twin was generated from, as named in its era, like `raster_nodes::adjustments::InvertNode` for `raster_nodes::adjustments::invert_shader_node::InvertShaderNodeNode`.
fn cpu_node_of_gpu_twin(identifier: &str) -> Option<String> {
let identifier = identifier.split('<').next()?;
let (module_path, struct_name) = identifier.rsplit_once("::")?;
let (parent_module_path, twin_module) = module_path.rsplit_once("::")?;
let cpu_struct_name = struct_name.strip_suffix("ShaderNodeNode")?;
twin_module.ends_with("_shader_node").then(|| format!("{parent_module_path}::{cpu_struct_name}Node"))
}
pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_node_definitions_on_open: bool) {
document.network_interface.migrate_path_modify_node();
document.network_interface.migrate_rewired_previews();
document.network_interface.normalize_stored_types();
// The removed GPU twins become their CPU nodes minus the trailing executor input, so the renames below carry them forward like their era's CPU nodes
let gpu_twins = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
let kept_input_count = node.inputs.len().saturating_sub(1);
Some((*node_id, path, cpu_node_of_gpu_twin(identifier.as_str())?, node.inputs[..kept_input_count].to_vec()))
})
.collect::<Vec<_>>();
for (node_id, network_path, cpu_identifier, inputs) in gpu_twins {
let input_metadata = document
.network_interface
.node_metadata(&node_id, &network_path)
.map(|metadata| metadata.persistent_metadata.input_metadata.iter().take(inputs.len()).cloned().collect())
.unwrap_or_default();
let mut node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::with_owned_string(cpu_identifier)),
inputs,
input_metadata,
..Default::default()
};
document.network_interface.replace_implementation(&node_id, &network_path, &mut node_template);
document.network_interface.replace_inputs(&node_id, &network_path, &mut node_template);
}
let network = document.network_interface.document_network().clone();
// Apply string and node replacements to each node
@@ -1262,18 +1223,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
};
document.network_interface.replace_implementation(node_id, &network_path, &mut default_template);
document.network_interface.set_call_argument(node_id, &network_path, default_template.call_argument);
// 'Mix Colors' takes the under color first, like a 'Merge' takes its stack, where 'Mix' and 'Blend' before it took the over color first
if *new == graphene_std::raster_nodes::blending_nodes::mix_colors::IDENTIFIER
&& let [over, under, ..] = node.inputs.as_slice()
{
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), under.clone(), &network_path);
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), over.clone(), &network_path);
}
if *new == graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER {
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
}
}
}
}
@@ -1369,28 +1318,6 @@ 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.
// 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
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::Network(network) = &node.implementation else { return None };
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);
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
})
.collect();
for (node_id, network_path, reference) in &monitored_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());
}
// The old "Math" node evaluated an expression over "A" and "B". A lexable static expression not reading a wired `B` becomes "Math f(x)"
// with `A` as `x` and a constant `B` inlined. Anything else becomes "Extend" feeding "Math f(…)", which reads the pair as `a` and `b`.
let math_nodes: Vec<(NodeId, Vec<NodeId>, Vec<NodeInput>)> = document
@@ -1636,49 +1563,6 @@ 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";
@@ -1857,56 +1741,6 @@ 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.
const NOISE_SETTINGS: usize = 14;
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)));
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER);
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() {
// Also with the pipeline input these nodes took when they rendered on the GPU themselves
17 if node.inputs.last() == Some(&pipeline) => 1,
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() || node.inputs == [pipeline]) {
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).take(NOISE_SETTINGS).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
@@ -1960,76 +1794,6 @@ 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 };
@@ -2560,6 +2324,7 @@ 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()) {
@@ -2880,6 +2645,20 @@ 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();
@@ -3636,18 +3415,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1), old_inputs[2].clone(), network_path);
}
// Load Image's URL is empty until set, it used to be `graphite:null`
if reference == DefinitionIdentifier::Network("Load Image".into())
&& let Some(url) = node.inputs.get(1)
&& matches!(url.as_value(), Some(TaggedValue::String(url)) if url == "graphite:null")
{
document.network_interface.set_input(
&InputConnector::node_at_index(*node_id, 1),
NodeInput::value(TaggedValue::String(String::new()), url.is_exposed()),
network_path,
);
}
// `wgpu-executor` scope was removed, change to the auto injected scope node `graphene_std::platform_application_io::wgpu_executor`
for (i, input) in node.inputs.iter().enumerate() {
if let NodeInput::Scope(name) = input
@@ -3661,52 +3428,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
}
}
let raster_kernel_pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
let raster_kernel_nodes = {
use graphene_std::raster_nodes::adjustments::*;
[
desaturate::IDENTIFIER,
gamma_correction::IDENTIFIER,
make_opaque::IDENTIFIER,
brightness_contrast::IDENTIFIER,
levels::IDENTIFIER,
curves::IDENTIFIER,
black_and_white::IDENTIFIER,
hue_saturation::IDENTIFIER,
invert::IDENTIFIER,
threshold::IDENTIFIER,
gradient_map::IDENTIFIER,
vibrance::IDENTIFIER,
channel_mixer::IDENTIFIER,
selective_color::IDENTIFIER,
posterize::IDENTIFIER,
exposure::IDENTIFIER,
color_balance::IDENTIFIER,
photo_filter::IDENTIFIER,
color_lookup::IDENTIFIER,
image_to_channels::IDENTIFIER,
graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mask::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::extend_image_to_bounds::IDENTIFIER,
graphene_std::raster_nodes::filter::median_filter::IDENTIFIER,
graphene_std::raster_nodes::effects::blur::IDENTIFIER,
graphene_std::raster_nodes::image_color_palette::image_color_palette::IDENTIFIER,
graphene_std::raster_nodes::dehaze::dehaze::IDENTIFIER,
graphene_std::platform_application_io::image_to_bytes::IDENTIFIER,
graphene_std::platform_application_io::rasterize::IDENTIFIER,
]
};
if raster_kernel_nodes.iter().any(|identifier| reference == DefinitionIdentifier::ProtoNode(identifier.clone())) && !node.inputs.contains(&raster_kernel_pipeline) {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
let value_inputs = node_template.inputs.iter().position(|input| *input == raster_kernel_pipeline)?;
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.into_iter().take(value_inputs).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
}
}
// A value input stored as a List-form TypeDefault adopts the definition's current default when the connector's declared default has since changed (e.g. the connector was ranked down to Item).
// The red-slash no-paint choice shares that stored form but is a deliberate value, not a stale disconnect default, so it is exempt.
if let Some(definition) = resolve_document_node_type(&reference) {
@@ -3812,11 +3533,11 @@ fn modifications_following_turned_segments(network: &graph_craft::document::Node
};
// Where the output comes from: the node itself, or the nodes a network node exports
let sources: Vec<Location> = match network.implementation_network(&origin_node.implementation) {
Some(nested) => (0..nested.exports.len())
let sources: Vec<Location> = match &origin_node.implementation {
DocumentNodeImplementation::Network(nested) => (0..nested.exports.len())
.filter_map(|output| producing_node(network, origin_path, &NodeInput::node(*origin_id, output), 0))
.collect(),
None => vec![origin.clone()],
_ => vec![origin.clone()],
};
let mut reached = HashSet::new();
@@ -3874,9 +3595,9 @@ fn producing_node(network: &graph_craft::document::NodeNetwork, network_path: &[
match input {
NodeInput::Node { node_id, output_index } => {
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
match network.implementation_network(&node.implementation) {
Some(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
None => Some((network_path.to_vec(), *node_id)),
match &node.implementation {
DocumentNodeImplementation::Network(nested) => producing_node(network, &[network_path, &[*node_id]].concat(), nested.exports.get(*output_index)?, depth + 1),
_ => Some((network_path.to_vec(), *node_id)),
}
}
NodeInput::Import { import_index, .. } => {
@@ -3991,20 +3712,6 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// Collapse the legacy "Rasterize" wrapper network, which drew into a browser canvas, into the standalone Vello `rasterize` proto node
#[cfg(feature = "gpu")]
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Rasterize"
&& node.inputs.len() == 2
{
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::rasterize::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
for (index, input) in old_inputs.iter().take(2).enumerate() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input.clone(), network_path);
}
}
// The removed Attach Attribute node degrades to a passthrough of its
// content: its eager whole-list source input cannot be mechanically rewired as Write Attribute's lazy per-item value producer.
if let Some(DefinitionIdentifier::ProtoNode(identifier)) = document.network_interface.reference(node_id, network_path)
@@ -4018,14 +3725,11 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// The removed Upload Texture node, in its proto node or older wrapper network form, degrades to a passthrough of its content
let is_upload_texture = match document.network_interface.reference(node_id, network_path) {
Some(DefinitionIdentifier::Network(name)) => name == "Upload Texture",
Some(DefinitionIdentifier::ProtoNode(identifier)) => identifier.as_str().ends_with("::UploadTextureNode"),
None => false,
};
if is_upload_texture {
let mut node_template = resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER)?.default_node_template();
// The Upload Texture node's old wrapper-network form maps onto its proto node form, which draws the executor from scope
if let Some(DefinitionIdentifier::Network(name)) = document.network_interface.reference(node_id, network_path)
&& name == "Upload Texture"
{
let mut node_template = resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
if let Some(content) = old_inputs.first() {
@@ -4134,79 +3838,6 @@ mod tests {
assert_eq!(chain_layout(&opened, layer), expected, "the migration should leave the layer's chain intact");
}
#[cfg(feature = "gpu")]
#[tokio::test]
async fn opening_a_canvas_rasterize_network_upgrades_it_to_the_vello_node() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeNetworkTemplate;
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use crate::test_utils::test_prelude::*;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::platform_application_io::rasterize;
use graphene_std::transform::Footprint;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let node_id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER), 0, 0).await;
let document = editor.active_document_mut();
let footprint = Footprint {
resolution: glam::UVec2::new(64, 32),
..Default::default()
};
let footprint_input = NodeInput::value(TaggedValue::Footprint(footprint), false);
document.network_interface.set_input(&InputConnector::node_at_index(node_id, 1), footprint_input.clone(), &[]);
// Save the node as the network that drew into a browser canvas
let canvas_network = NodeNetworkTemplate {
exports: vec![NodeInput::node(NodeId(0), 0)],
nodes: [(
NodeId(0),
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(rasterize::IDENTIFIER),
inputs: vec![NodeInput::import(list!(graphic_types::Graphic), 0), NodeInput::import(item!(Footprint), 1)],
..Default::default()
},
)]
.into_iter()
.collect(),
..Default::default()
};
let mut legacy = NodeTemplate {
implementation: NodeTemplateImplementation::Network(canvas_network),
..Default::default()
};
document.network_interface.replace_implementation(&node_id, &[], &mut legacy);
document.network_interface.set_reference(&node_id, &[], Some("Rasterize".into()));
let serialized = document.serialize_document();
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
let interface = &opened.network_interface;
assert_eq!(interface.reference(&node_id, &[]), Some(DefinitionIdentifier::ProtoNode(rasterize::IDENTIFIER)));
assert_eq!(
interface.input_from_connector(&InputConnector::node_at_index(node_id, 1), &[]),
Some(&footprint_input),
"the footprint should carry over"
);
}
#[cfg(feature = "gpu")]
#[tokio::test]
async fn a_rasterize_node_on_the_export_compiles() {
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
editor.new_document().await;
let rasterize = editor
.create_node_by_name_at(DefinitionIdentifier::ProtoNode(graphene_std::platform_application_io::rasterize::IDENTIFIER), 0, 0)
.await;
editor
.active_document_mut()
.network_interface
.create_wire(&OutputConnector::primary_output(rasterize), &InputConnector::Export(0), &[]);
editor.handle_message(NodeGraphMessage::RunDocumentGraph).await;
}
#[test]
fn null_floats_load_as_zero() {
use crate::messages::portfolio::document::utility_types::misc::PTZ;
@@ -4242,88 +3873,7 @@ mod tests {
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
}
#[test]
fn gpu_twins_name_the_cpu_nodes_they_came_from() {
assert_eq!(
cpu_node_of_gpu_twin("raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode").as_deref(),
Some(graphene_std::raster_nodes::adjustments::desaturate::IDENTIFIER.as_str())
);
assert_eq!(
cpu_node_of_gpu_twin("graphene_raster_nodes::blending_nodes::color_overlay_shader_node::ColorOverlayShaderNodeNode").as_deref(),
Some("graphene_raster_nodes::blending_nodes::ColorOverlayNode")
);
assert_eq!(cpu_node_of_gpu_twin(graphene_std::raster_nodes::adjustments::invert::IDENTIFIER.as_str()), None);
}
// Upload Texture opens as a passthrough, and GPU twins open as the CPU nodes they were generated from, keeping their wires but not their executor input
#[test]
fn gpu_twins_and_upload_texture_open_as_cpu_nodes() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::desaturate;
let executor = || NodeInput::scope("graphene_std::platform_application_io::WgpuExecutorNode");
let legacy_node = |identifier: &'static str, inputs: Vec<NodeInput>| NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
input_metadata: inputs.iter().map(|_| ("Value", "").into()).collect(),
inputs,
..Default::default()
};
let desaturate_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(desaturate::IDENTIFIER))
.expect("the Desaturate definition should exist")
.default_node_template();
let content = NodeInput::value(TaggedValue::Color(Color::RED), false);
let method = desaturate_template.inputs[1].clone();
let brightness = NodeInput::value(TaggedValue::Number(25.), false);
let contrast = NodeInput::value(TaggedValue::Number(-10.), false);
// Uploaded content feeds a Desaturate GPU twin, which feeds a Brightness/Contrast Classic GPU twin saved under the `raster_nodes` crate name
let saved_nodes = [
legacy_node("graphene_std::platform_application_io::UploadTextureNode", vec![content.clone(), executor()]),
legacy_node(
"raster_nodes::adjustments::desaturate_shader_node::DesaturateShaderNodeNode",
vec![NodeInput::node(NodeId(0), 0), method.clone(), executor()],
),
legacy_node(
"raster_nodes::adjustments::brightness_contrast_classic_shader_node::BrightnessContrastClassicShaderNodeNode",
vec![NodeInput::node(NodeId(1), 0), brightness.clone(), contrast.clone(), executor()],
),
];
let nodes = saved_nodes
.into_iter()
.enumerate()
.map(|(index, node_template)| (NodeId(index as u64), node_template))
.collect::<Vec<_>>();
let unchanged_ids = nodes.iter().map(|(node_id, _)| (*node_id, *node_id)).collect();
let mut document = DocumentMessageHandler::default();
document.network_interface.insert_node_group(nodes, unchanged_ids, &[]);
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let node = |index: u64| opened.network_interface.document_node(&NodeId(index), &[]).expect("the node should still exist");
let upload_texture = node(0);
assert_eq!(upload_texture.implementation, DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER));
assert_eq!(upload_texture.inputs, [content]);
let desaturate_node = node(1);
assert_eq!(desaturate_node.implementation, DocumentNodeImplementation::ProtoNode(desaturate::IDENTIFIER));
let pipeline = NodeInput::scope(graphene_std::raster_nodes::raster_kernel::raster_kernel_pipeline::IDENTIFIER.as_str().to_string());
assert_eq!(desaturate_node.inputs, [NodeInput::node(NodeId(0), 0), method, pipeline]);
let brightness_contrast = node(2);
assert_eq!(
brightness_contrast.implementation,
DocumentNodeImplementation::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER)
);
assert_eq!(brightness_contrast.inputs[..3], [NodeInput::node(NodeId(1), 0), brightness, contrast]);
assert_eq!(
brightness_contrast.inputs[3],
NodeInput::value(TaggedValue::Bool(true), false),
"the Classic twin should turn on the Use Classic toggle"
);
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::IDENTIFIER).is_some());
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -4688,47 +4238,6 @@ mod tests {
assert_eq!(inner.nodes[&NodeId(5)].inputs.get(1).and_then(|input| input.as_value()).cloned(), Some(TaggedValue::Number(42.)));
}
// Merge and Artboard networks once passed their content through a Monitor node for thumbnails, so their rebuilt networks drop it
#[test]
fn merge_and_artboard_networks_drop_their_monitor_node() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
for name in ["Merge", "Artboard"] {
let node_id = NodeId(1);
let mut document = DocumentMessageHandler::default();
let mut node_template = resolve_network_node_type(name).expect("The definition should exist").default_node_template();
let NodeTemplateImplementation::Network(network_template) = &mut node_template.implementation else {
panic!("{name} should be a network node")
};
// Splice a Monitor node into the content entering the exported Extend node, where the old network had it
let Some(NodeInput::Node { node_id: extend_id, .. }) = network_template.exports.first().cloned() else {
panic!("{name} should export a node")
};
let monitor_id = NodeId(100);
let extend = network_template.nodes.get_mut(&extend_id).expect("The exported node should exist");
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),
..Default::default()
};
network_template.nodes.insert(monitor_id, monitor_template);
document.network_interface.insert_node(node_id, node_template, &[]);
migrate(&mut document);
let DocumentNodeImplementation::Network(network) = &document.network_interface.document_network().nodes[&node_id].implementation 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"
);
}
}
// 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]
@@ -4823,54 +4332,6 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
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();
@@ -5285,43 +4746,6 @@ mod tests {
}
}
#[test]
fn mix_and_blend_nodes_open_as_mix_colors_with_the_under_color_first() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::blending_nodes::mix_colors;
let (over, under) = (Color::RED, Color::BLUE);
let color_input = |color| NodeInput::value(TaggedValue::Color(color), false);
// Old Mix and Blend nodes list the over color first, while a node already saved as Mix Colors lists the under color first
let saved_nodes = [
(ProtoNodeIdentifier::new("raster_nodes::blending_nodes::MixNode"), [over, under]),
(ProtoNodeIdentifier::new("raster_nodes::blending_nodes::BlendNode"), [over, under]),
(mix_colors::IDENTIFIER, [under, over]),
];
let mut document = DocumentMessageHandler::default();
for (index, (identifier, colors)) in saved_nodes.iter().enumerate() {
let mut node_template = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(mix_colors::IDENTIFIER))
.expect("the Mix Colors definition should exist")
.default_node_template();
node_template.implementation = NodeTemplateImplementation::ProtoNode(identifier.clone());
node_template.inputs[0] = color_input(colors[0]);
node_template.inputs[1] = color_input(colors[1]);
document.network_interface.insert_node(NodeId(index as u64), node_template, &[]);
}
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
for (index, (identifier, _)) in saved_nodes.iter().enumerate() {
let node = opened.network_interface.document_node(&NodeId(index as u64), &[]).expect("the node should still exist");
assert_eq!(node.implementation, DocumentNodeImplementation::ProtoNode(mix_colors::IDENTIFIER), "{}", identifier.as_str());
assert_eq!(node.inputs[0], color_input(under), "{} should take the under color first", identifier.as_str());
assert_eq!(node.inputs[1], color_input(over), "{} should take the over color second", identifier.as_str());
}
}
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
#[test]
fn removed_nodes_open_as_their_stand_ins() {
@@ -5420,81 +4844,4 @@ mod tests {
assert_eq!(interface.display_name(&node_id, &[]), "Image", "node {node_id}");
}
}
// 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::IngestAction;
use crate::messages::prelude::IngestMessage;
use crate::test_utils::test_prelude::*;
let mut editor = EditorTestUtils::create();
let content = std::fs::read_to_string("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
editor.editor.handle_message(IngestMessage::Ingest {
data: content.into_bytes(),
action: IngestAction::Open,
mime_type: String::new(),
path: Some("marbled-mandelbrot.graphite".into()),
});
if let Err(error) = editor.eval_graph_until_finished().await {
panic!("The migrated demo failed to render: {error}");
}
}
}
@@ -280,7 +280,6 @@ async fn build_document_from_storage(gdd: GddV1, byte_store: &ResourcesHandle, d
}
};
apply_network_view_settings(&mut interface, &network_ids, gdd.network_view_settings());
// TODO: Run document upgrades here once this format has a versioned migration
let mut document = DocumentMessageHandler::from_storage(interface, gdd, declarations, String::new(), None);
document.finalize_storage_load();
@@ -47,6 +47,7 @@ pub enum PortfolioMessage {
document_id: DocumentId,
},
DestroyAllDocuments,
EditorPreferences,
GarbageCollectResources,
ResolveResources,
ResolveDocumentResources {
@@ -141,8 +141,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
// Messages
PortfolioMessage::Init => {
self.executor.forget_canvas_images();
// Tell frontend to load persistent preferences
responses.add(FrontendMessage::TriggerLoadPreferences);
@@ -352,6 +350,7 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
responses.add(MenuBarMessage::SendLayout);
responses.add(PersistentStateMessage::WriteState);
}
PortfolioMessage::EditorPreferences => self.executor.update_editor_preferences(preferences.editor_preferences()),
PortfolioMessage::GarbageCollectResources => {
// The resources of documents that are not loaded yet are unknown, so GC waits for every load and for a successful store listing.
if !self.persistent_state.loaded() || self.pending_opens > 0 || !self.loading_documents.is_empty() || self.store_unavailable {
@@ -514,14 +513,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_path,
document_serialized_content,
} => {
if let Some(path) = &document_path
&& let Some(&document_id) = self.document_ids.iter().find(|&&id| self.document_details(id).is_some_and(|info| info.path.as_ref() == Some(path)))
{
responses.add(PortfolioMessage::SelectDocument { document_id });
responses.add(AppWindowMessage::Focus);
return;
}
let mut document = match load_legacy_document(document_serialized_content, &resource_storage.resources_mut(), reset_node_definitions_on_open) {
Ok(document) => document,
Err(error) => {
@@ -545,14 +536,6 @@ impl MessageHandler<PortfolioMessage, PortfolioMessageContext<'_>> for Portfolio
document_path,
content,
} => {
if let Some(path) = &document_path
&& let Some(&document_id) = self.document_ids.iter().find(|&&id| self.document_details(id).is_some_and(|info| info.path.as_ref() == Some(path)))
{
responses.add(PortfolioMessage::SelectDocument { document_id });
responses.add(AppWindowMessage::Focus);
return;
}
let document_id = DocumentId(generate_uuid());
// Suppress resource GC until the open completes
@@ -30,6 +30,9 @@ pub enum PreferencesMessage {
UIScale {
scale: f64,
},
MaxRenderRegionSize {
size: u32,
},
DisableUIAcceleration {
disable_ui_acceleration: bool,
},
@@ -4,6 +4,7 @@ use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
use crate::messages::preferences::SelectionMode;
use crate::messages::prelude::*;
use crate::messages::tool::utility_types::ToolType;
use graph_craft::application_io::EditorPreferences;
#[derive(ExtractField)]
pub struct PreferencesMessageContext<'a> {
@@ -20,6 +21,7 @@ pub struct PreferencesMessageHandler {
pub graph_wire_style: GraphWireStyle,
pub viewport_zoom_wheel_rate: f64,
pub ui_scale: f64,
pub max_render_region_size: u32,
pub disable_ui_acceleration: bool,
pub validate_storage_round_trip: bool,
pub save_as_gdd: bool,
@@ -39,6 +41,12 @@ impl PreferencesMessageHandler {
pub fn get_selection_mode(&self) -> SelectionMode {
self.selection_mode
}
pub fn editor_preferences(&self) -> EditorPreferences {
EditorPreferences {
max_render_region_size: self.max_render_region_size,
}
}
}
impl Default for PreferencesMessageHandler {
@@ -50,6 +58,7 @@ impl Default for PreferencesMessageHandler {
graph_wire_style: GraphWireStyle::default(),
viewport_zoom_wheel_rate: VIEWPORT_ZOOM_WHEEL_RATE,
ui_scale: UI_SCALE_DEFAULT,
max_render_region_size: EditorPreferences::default().max_render_region_size,
disable_ui_acceleration: true, // TODO: Set this back to false once we have ui acceleration working more reliably
validate_storage_round_trip: false,
save_as_gdd: false,
@@ -70,6 +79,7 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
PreferencesMessage::Load { preferences } => {
*self = preferences;
responses.add(PortfolioMessage::EditorPreferences);
responses.add(PreferencesMessage::ModifyLayout {
zoom_with_scroll: self.zoom_with_scroll,
});
@@ -113,6 +123,11 @@ impl MessageHandler<PreferencesMessage, PreferencesMessageContext<'_>> for Prefe
self.ui_scale = scale;
responses.add(FrontendMessage::UpdateUIScale { scale: self.ui_scale });
}
PreferencesMessage::MaxRenderRegionSize { size } => {
self.max_render_region_size = size;
responses.add(PortfolioMessage::EditorPreferences);
responses.add(NodeGraphMessage::RunDocumentGraph);
}
PreferencesMessage::DisableUIAcceleration { disable_ui_acceleration } => {
self.disable_ui_acceleration = disable_ui_acceleration;
}
@@ -342,7 +342,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
// A generator discards its primary input, so the chain ends at whichever one is reached
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
let setters = [
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_form::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -480,8 +480,7 @@ pub fn star_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMessa
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let Ok(star) = star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star)];
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(star_polygon_bezpath(DVec2::ZERO, points, radius1, radius2))];
overlay_context.outline(targets.iter(), viewport, None);
}
@@ -496,8 +495,7 @@ pub fn polygon_outline(layer: Option<LayerNodeIdentifier>, document: &DocumentMe
let viewport = document.metadata().transform_to_viewport(layer);
let points = sides as u64;
let Ok(polygon) = regular_polygon_bezpath(DVec2::ZERO, points, radius) else { return };
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(polygon)];
let targets: Vec<ClickTargetType> = vec![ClickTargetType::Path(regular_polygon_bezpath(DVec2::ZERO, points, radius))];
overlay_context.outline(targets.iter(), viewport, None);
}
@@ -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_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
@@ -430,14 +430,11 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
// 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 });
} 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);
}
}
@@ -3369,7 +3366,7 @@ mod test_gradient {
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3378,7 +3375,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3387,10 +3384,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Curvature node should have been inserted")
.expect("Gradient Form node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
+29 -175
View File
@@ -4,6 +4,7 @@ use crate::messages::portfolio::document::utility_types::layers_in_view::LayersI
use crate::messages::portfolio::document::utility_types::network_interface::InputConnector;
use crate::messages::prelude::*;
use glam::{DAffine2, DVec2, UVec2};
use graph_craft::application_io::EditorPreferences;
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
use graph_craft::proto::GraphErrors;
@@ -36,7 +37,7 @@ pub struct ExecutionResponse {
execution_id: u64,
result: ExecutionResult,
responses: VecDeque<FrontendMessage>,
/// The layers whose thumbnails the runtime let go of, which it renders anew if they have content to show again.
/// The layers whose thumbnails the runtime let go of, which it renders anew if they're monitored again.
dropped_thumbnails: Vec<NodeId>,
vector_modify: HashMap<NodeId, VectorGeometry>,
/// The resulting value from the temporary inspected during execution
@@ -58,7 +59,7 @@ pub type NodeErrorTrace = Box<[NodePaths]>;
pub type NodePaths = Box<[Box<[NodeId]>]>;
impl EvaluationErrors {
pub(crate) fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync + 'static), &NodeErrorTrace)> {
fn iter(&self) -> impl Iterator<Item = (&(dyn std::error::Error + Send + Sync), &NodeErrorTrace)> {
self.0.iter().map(|(error, trace)| (&**error, trace))
}
}
@@ -97,11 +98,6 @@ 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 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
#[cfg(test)]
evaluation_errors: Option<EvaluationErrors>,
// TODO: Eventually remove this document upgrade code
/// In-progress one-time pre-pass that converts legacy bounding-box-relative gradients to absolute space, if any.
gradient_migration: Option<GradientMigration>,
@@ -143,40 +139,26 @@ impl NodeGraphExecutor {
let node_runtime = NodeRuntime::new(request_receiver, response_sender, editor_wake);
let node_executor = Self {
futures: Default::default(),
sender: request_sender,
receiver: response_receiver,
futures: Default::default(),
pending: None,
current_execution_id: 0,
node_graph_hash: 0,
node_graph_document: None,
current_execution_id: 0,
previous_node_to_inspect: Vec::new(),
canvas_images_sent: HashSet::new(),
#[cfg(test)]
evaluation_errors: None,
gradient_migration: None,
gradient_migration_attempted: HashSet::new(),
pending: None,
};
(node_executor, node_runtime)
}
/// Forgets which canvas images the frontend holds, for a frontend that started over without them.
pub fn forget_canvas_images(&mut self) {
self.canvas_images_sent.clear();
}
/// Allows the test runner to see if any more executions have been queued.
#[cfg(test)]
pub fn current_execution_id(&self) -> u64 {
self.current_execution_id
}
/// Allows the test runner to access last executions evaluation errors.
#[cfg(test)]
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
self.evaluation_errors.take()
}
/// Execute the network by flattening it and creating a borrow stack.
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
let execution_id = self.current_execution_id;
@@ -203,13 +185,18 @@ impl NodeGraphExecutor {
.expect("Failed to send the thumbnails in view");
}
pub fn update_editor_preferences(&self, editor_preferences: EditorPreferences) {
self.sender
.send(GraphRuntimeRequest::EditorPreferencesUpdate(editor_preferences))
.expect("Failed to send editor preferences");
}
/// Updates the network to monitor all inputs. Useful for the testing.
#[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 resources = document.resources.registry.clone();
@@ -219,8 +206,6 @@ impl NodeGraphExecutor {
network,
resources,
node_to_inspect: Vec::new(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
}))
.map_err(|e| e.to_string())?;
Ok(instrumented)
@@ -231,8 +216,6 @@ impl NodeGraphExecutor {
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);
@@ -240,13 +223,7 @@ impl NodeGraphExecutor {
let resources = document.resources.registry.clone();
self.sender
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
network,
resources,
node_to_inspect,
previewed,
layers,
}))
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, node_to_inspect }))
.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);
@@ -373,7 +350,6 @@ impl NodeGraphExecutor {
/// Evaluates a node graph for export
pub fn submit_document_export(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, mut export_config: ExportConfig) -> Result<(), String> {
let network = document.network_interface.document_network().clone();
let previewed = document.network_interface.previewed_nodes();
let resources = document.resources.registry.clone();
let export_format = if export_config.file_type == FileType::Svg {
@@ -383,11 +359,11 @@ impl NodeGraphExecutor {
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
// `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.
// `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.
let bounds = match export_config.bounds {
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::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -420,8 +396,6 @@ impl NodeGraphExecutor {
network,
resources,
node_to_inspect: Vec::new(),
previewed,
layers: document.network_interface.layer_paths(),
}))
.map_err(|e| e.to_string())?;
let execution_id = self.queue_execution(render_config);
@@ -505,10 +479,7 @@ impl NodeGraphExecutor {
if execution_context.export_config.is_none() && !matches!(result, ExecutionResult::Pending) {
let errors = match &result {
ExecutionResult::Fallback(_, errors) | ExecutionResult::Error(errors) => {
let in_document = |path: &&[NodeId]| {
path.split_last()
.is_some_and(|(node, network)| document.network_interface.view(network).and_then(|view| view.node(node)).is_ok())
};
let in_document = |path: &&[NodeId]| path.split_last().is_some_and(|(node, network)| document.network_interface.document_node(node, network).is_some());
errors
.iter()
.flat_map(|(error, trace)| {
@@ -530,28 +501,10 @@ impl NodeGraphExecutor {
responses.add(NodeGraphMessage::UpdateEvaluationErrors { errors });
}
#[cfg(test)]
{
self.evaluation_errors = None;
}
let node_graph_output = match result {
ExecutionResult::Pending => Ok(None),
ExecutionResult::Value(value) => Ok(Some(value)),
ExecutionResult::Fallback(value, _errors) => {
#[cfg(test)]
{
self.evaluation_errors = Some(_errors);
}
Ok(Some(value))
}
ExecutionResult::Error(errors) => {
let message = errors.to_string();
#[cfg(test)]
{
self.evaluation_errors = Some(errors);
}
Err(message)
}
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Ok(Some(value)),
ExecutionResult::Error(errors) => Err(errors.to_string()),
ExecutionResult::Panic(payload) => {
let message = payload.downcast_ref::<&str>().copied().or_else(|| payload.downcast_ref::<String>().map(String::as_str));
Err(format!("Panicked: {}", message.unwrap_or("no message")))
@@ -762,12 +715,6 @@ impl NodeGraphExecutor {
// On this throwaway clone, redirect each level's export down to the Fill, un-hiding the Fill and its enclosing subnetworks so it's measured as a real Fill rather than a passthrough.
// But upstream generators keep their visibility, so a hidden one intentionally contributes no geometry.
let full_path: Vec<NodeId> = network_path.iter().copied().chain(std::iter::once(fill_node_id)).collect();
if let Err(error) = network.inline_definitions() {
log::error!("Gradient migration: could not inline the document's network definitions: {error}; dropping the pending gradient bake of fill node {fill_node_id:?}");
remove_pending_gradient_bake(document, &network_path, fill_node_id);
self.advance_gradient_migration(document, document_id, responses);
return;
}
if !redirect_export_chain(&mut network, &full_path) {
// The fill was deleted or is otherwise unreachable, so drop its stale entry instead of retrying it on every open
log::warn!("Gradient migration: could not redirect the document network's export chain to fill node {fill_node_id:?}; dropping its pending gradient bake");
@@ -783,8 +730,6 @@ impl NodeGraphExecutor {
network,
resources,
node_to_inspect: full_path.clone(),
previewed: Vec::new(),
layers: document.network_interface.layer_paths(),
}))
.is_err()
{
@@ -908,28 +853,18 @@ impl NodeGraphExecutor {
match render_output.data {
RenderOutputType::Svg { svg, image_data } => {
// The frontend keeps the canvases it was sent until a render stops using them, so only the images it lacks are sent
let canvas_ids_in_use: Vec<u64> = image_data.iter().map(|(id, _)| *id).collect();
let in_use: HashSet<u64> = canvas_ids_in_use.iter().copied().collect();
self.canvas_images_sent.retain(|id| in_use.contains(id));
// Convert each linear-light image, at its display resolution, into gamma sRGB bytes (the DOM boundary form)
// Convert each linear-light `Image<Color>` into gamma sRGB bytes (the DOM boundary form) before dispatching.
let rgba8_bytes = |&color: &_| <[u8; 4]>::from(SRGBA8::from(color));
let image_data = image_data
.into_iter()
.filter(|(id, _)| self.canvas_images_sent.insert(*id))
.map(|(id, canvas_image)| {
let image = canvas_image.raster.halved(canvas_image.halvings);
RasterizedImage {
id,
width: image.width,
height: image.height,
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
}
.map(|(id, image)| RasterizedImage {
id,
width: image.width,
height: image.height,
pixels: image.data.iter().flat_map(rgba8_bytes).collect::<Vec<u8>>().into(),
})
.collect();
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
responses.add(FrontendMessage::UpdateImageData { image_data });
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
#[cfg(target_family = "wasm")]
@@ -941,8 +876,8 @@ impl NodeGraphExecutor {
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
}
RenderOutputType::Texture { .. } => {}
RenderOutputType::Buffer { width, height, .. } => {
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
_ => {
log::error!("Invalid node graph output type: {:#?}", render_output.data);
responses.add(FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error });
return;
}
@@ -959,7 +894,6 @@ impl NodeGraphExecutor {
clip_targets,
vector_data,
appearance_attributes,
effects_reach,
backgrounds: _,
} = render_output.metadata;
@@ -976,7 +910,6 @@ 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);
@@ -1238,82 +1171,3 @@ mod test {
}
}
}
#[cfg(test)]
mod raster_input_adapter_tests {
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
use crate::test_utils::test_prelude::*;
use graph_craft::ProtoNodeIdentifier;
use graph_craft::document::{DocumentNodeImplementation, NodeId};
use graphene_std::Effects;
use graphene_std::list::{ATTR_EFFECTS, Item};
use graphene_std::ops::ConvertAsync;
use graphene_std::raster_nodes::adjustments::invert;
use graphene_std::raster_nodes::dehaze::dehaze;
use graphene_std::raster_nodes::filter::median_filter;
use graphene_std::raster_types::{CPU, GPU, Raster};
use graphene_std::transform::Footprint;
/// A document whose image feeds `nodes` in turn, ending in the export, with each node's ID.
async fn image_through(editor: &mut EditorTestUtils, color: Color, nodes: &[ProtoNodeIdentifier]) -> Vec<NodeId> {
editor.new_document().await;
editor.create_raster_image(Image::new(4, 4, color), None).await;
let image = editor
.active_document()
.network_interface
.document_network()
.nodes
.iter()
.find(|(_, node)| matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::raster_nodes::std_nodes::image::IDENTIFIER))
.map(|(id, _)| *id)
.expect("the pasted image should be an Image node");
let mut ids = Vec::new();
let mut previous = OutputConnector::node(image, 0);
for (index, identifier) in nodes.iter().enumerate() {
let id = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(identifier.clone()), (index as i32 + 1) * 10, 0).await;
let input = InputConnector::node_at_index(id, 0);
editor.active_document_mut().network_interface.create_wire(&previous, &input, &[]);
previous = OutputConnector::node(id, 0);
ids.push(id);
}
editor.active_document_mut().network_interface.create_wire(&previous, &InputConnector::Export(0), &[]);
ids
}
async fn read(editor: &EditorTestUtils, raster: Raster<GPU>) -> Raster<CPU> {
let executor = editor.gpu_executor();
raster.convert(Footprint::DEFAULT, executor).await
}
#[tokio::test]
async fn an_images_stamped_effects_are_carried_out_before_the_gpu_only_node_it_feeds() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::WHITE, &[invert::IDENTIFIER, median_filter::IDENTIFIER, invert::IDENTIFIER]).await;
let instrumented = editor.eval_graph_until_finished().await.expect("the CPU raster should reach Median through its input adapter");
let reached_median: Item<Raster<CPU>> = instrumented
.grab_all_input::<median_filter::ImageFrameInput, Item<Raster<CPU>>>(&editor.runtime)
.next()
.expect("the image should arrive at Median as a CPU raster");
assert!(reached_median.attribute::<Effects>(ATTR_EFFECTS).is_some(), "the first Invert should only stamp the image");
// Median at its default radius passes its input through, so its output shows what the adapter gave it
let output = instrumented
.grab_all_input::<invert::InputInput, Item<Raster<GPU>>>(&editor.runtime)
.next()
.expect("Median should output a GPU raster");
assert!(output.attribute::<Effects>(ATTR_EFFECTS).is_none(), "no stamp should be left to apply after Median");
let raster = read(&editor, output.into_element()).await;
assert!(raster.data[0].r() < 0.01, "the white image should be black by the time Median reads it, not {:?}", raster.data[0]);
}
#[tokio::test]
async fn an_image_feeding_dehaze_compiles_and_renders_without_a_migration() {
let mut editor = EditorTestUtils::create();
image_through(&mut editor, Color::from_rgbaf32_unchecked(0.5, 0.6, 0.7, 1.), &[dehaze::IDENTIFIER]).await;
// A compile error or a failed render fails this
editor.eval_graph_uninstrumented().await.expect("the image should reach Dehaze through its input adapter");
}
}
+52 -182
View File
@@ -1,7 +1,6 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Scheduling, Spawn, Spawner, Task};
use crate::task::{Spawn, Spawner, Task};
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
@@ -18,15 +17,15 @@ 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, Clock};
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 interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
use interpreted_executor::util::wrap_network_in_scope;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{Receiver, Sender};
use std::time::Duration;
use thumbnails::Thumbnails;
mod thumbnails;
@@ -42,15 +41,12 @@ pub struct NodeRuntime {
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
/// A re-evaluation waiting for the next frame, or for the end of an export.
rerun: bool,
dirty: Arc<AtomicBool>,
pending: Option<ExecutionRequest>,
pending_export: Option<ExecutionRequest>,
/// The network the executor last compiled successfully, with previews applied.
editor_preferences: EditorPreferences,
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
scheduling: Scheduling,
frame_start: Duration,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -80,6 +76,7 @@ pub struct NodeRuntime {
pub enum GraphRuntimeRequest {
GraphUpdate(GraphUpdate),
ExecutionRequest(ExecutionRequest),
EditorPreferencesUpdate(EditorPreferences),
ThumbnailsInView {
layers: HashSet<NodeId>,
document_id: DocumentId,
@@ -95,19 +92,6 @@ pub struct GraphUpdate {
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>>,
}
/// Replaces each network's primary export with its previewed node.
pub(crate) fn apply_previews(network: &mut NodeNetwork, previewed: &[(Vec<NodeId>, RootNode)]) {
for (network_path, previewed) in previewed {
let Some(nested) = network.nested_network_mut(network_path) else { continue };
let Some(export) = nested.exports.first_mut() else { continue };
*export = NodeInput::node(previewed.node_id, previewed.output_index);
}
}
#[derive(Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
@@ -128,16 +112,17 @@ impl NodeRuntime {
receiver,
sender,
editor_wake,
rerun: false,
dirty: Default::default(),
pending: None,
pending_export: None,
editor_preferences: EditorPreferences::default(),
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
scheduling: Scheduling::default(),
frame_start: Duration::ZERO,
editor_api: PlatformEditorApi {
editor_preferences: Box::new(EditorPreferences::default()),
#[cfg(not(test))]
application_io: None,
@@ -170,6 +155,7 @@ impl NodeRuntime {
}
async fn handle_requests(&mut self) -> Option<Texture> {
let mut preferences = None;
let mut graph = None;
let mut eyedropper = None;
let mut execution = None;
@@ -194,6 +180,7 @@ impl NodeRuntime {
break;
}
}
GraphRuntimeRequest::EditorPreferencesUpdate(_) => preferences = Some(request),
GraphRuntimeRequest::ThumbnailsInView { layers, document_id } => thumbnails_in_view = Some((layers, document_id)),
// A graph update applied after this loop would otherwise inspect what was selected before
GraphRuntimeRequest::Inspect(node_to_inspect) => match &mut graph {
@@ -221,13 +208,8 @@ impl NodeRuntime {
}
}
let rerun = std::mem::take(&mut self.rerun) | self.async_runtime().take_bumped();
if rerun && execution.is_none() {
if self.frame_has_budget() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
} else {
self.rerun = true;
}
if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
}
// Eydropper should use the same time and pointer to not invalidate the cache
@@ -238,34 +220,35 @@ impl NodeRuntime {
eyedropper.render_config.pointer = execution.render_config.pointer;
}
let requests = [graph, eyedropper, execution].into_iter().flatten();
let requests = [preferences, graph, eyedropper, execution].into_iter().flatten();
for request in requests {
match request {
GraphRuntimeRequest::ThumbnailsInView { .. } | GraphRuntimeRequest::Inspect(_) | GraphRuntimeRequest::InspectContextOverrides(_) => {}
GraphRuntimeRequest::GraphUpdate(GraphUpdate {
mut network,
resources,
node_to_inspect,
previewed,
layers,
}) => {
apply_previews(&mut network, &previewed);
GraphRuntimeRequest::EditorPreferencesUpdate(preferences) => {
self.editor_preferences = preferences.clone();
self.editor_api = PlatformEditorApi {
application_io: self.editor_api.application_io.clone(),
editor_preferences: Box::new(preferences),
}
.into();
if let Some(graph) = self.old_graph.clone() {
// We ignore this result as compilation errors should have been reported in an earlier iteration
let _ = self.update_network(graph);
}
}
GraphRuntimeRequest::GraphUpdate(GraphUpdate { network, resources, node_to_inspect }) => {
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),
}
self.old_graph = Some(network.clone());
self.resources = resources;
self.node_graph_errors.clear();
self.node_graph_warnings.clear();
let result = self.update_network(network.clone());
if result.is_ok() {
self.thumbnails.update_sources(&layers, &network, &self.executor);
self.old_graph = Some(network);
}
let result = self.update_network(network);
let node_graph_errors = self.node_graph_errors.clone();
let node_graph_warnings = self.node_graph_warnings.clone();
@@ -279,7 +262,7 @@ impl NodeRuntime {
}
GraphRuntimeRequest::ExecutionRequest(request @ ExecutionRequest { execution_id, mut render_config, .. }) => {
if !render_config.for_export && !render_config.for_eyedropper {
self.thumbnails.set_scale(render_config.scale);
self.thumbnails.set_scale(render_config.scale, &self.monitor_nodes);
self.pending = Some(request);
}
if render_config.for_export {
@@ -322,7 +305,7 @@ impl NodeRuntime {
self.pending_export = Some(request);
return None;
}
(true, _) => self.rerun = true,
(true, _) => self.dirty.store(true, Ordering::Release),
_ => {}
}
@@ -333,7 +316,7 @@ impl NodeRuntime {
Vec::new()
};
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor, self.old_graph.as_ref()));
let inspect_result = self.inspect_state.as_mut().map(|state| state.access(&self.executor));
let output = match &mut result {
ExecutionResult::Value(value) | ExecutionResult::Fallback(value, _) => Some(value),
@@ -408,7 +391,7 @@ impl NodeRuntime {
// Without an execution to send it along with, the inspected node is evaluated again with its new overrides once the graph is up to date
if inspect_again && let Some(inspect_state) = &mut self.inspect_state {
let inspect_result = inspect_state.access(&self.executor, self.old_graph.as_ref());
let inspect_result = inspect_state.access(&self.executor);
self.sender.send(NodeGraphUpdate::InspectResult(Box::new(inspect_result))).expect("Failed to send response");
}
@@ -436,12 +419,14 @@ impl NodeRuntime {
Err(CompileError::Message(message)) => return Err((ResolvedDocumentNodeTypesDelta::default(), message)),
};
self.node_graph_warnings = warnings;
let previous_monitor_ids: HashMap<Vec<NodeId>, NodeId> = std::mem::take(&mut self.monitor_nodes).into_iter().collect();
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();
self.thumbnails.update_monitors(&previous_monitor_ids, &self.monitor_nodes);
assert_ne!(proto_network.nodes.len(), 0, "No proto nodes exist?");
let result = self.executor.update(proto_network).map_err(|(types, e)| {
@@ -485,9 +470,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.
/// Updates state data, giving back the layers whose thumbnails were dropped because they're no longer monitored.
async fn process_monitor_nodes(&mut self, responses: &mut VecDeque<FrontendMessage>) -> Vec<NodeId> {
let dropped_thumbnails = self.thumbnails.drop_sourceless();
let dropped_thumbnails = self.thumbnails.drop_unmonitored(&self.monitor_nodes);
for (monitor_node_path, _) in &self.monitor_nodes {
let Some(parent_network_node_id) = monitor_parent_node(monitor_node_path) else {
@@ -573,58 +558,38 @@ impl NodeRuntime {
pub(crate) fn replace_application_io(&mut self, application_io: PlatformApplicationIo) {
self.editor_api = PlatformEditorApi {
application_io: Some(application_io.into()),
editor_preferences: Box::new(self.editor_preferences.clone()),
}
.into();
}
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake, clock: Arc<dyn Clock>) {
self.async_runtime = Some(AsyncRuntime::new(Arc::new(NodeTaskExecutor { spawner, wake }), clock));
self.begin_frame();
pub(crate) fn replace_task_executor(&mut self, spawner: Spawner, wake: Wake) {
let spawn = NodeTaskExecutor {
spawner,
dirty: self.dirty.clone(),
wake,
};
self.async_runtime = Some(AsyncRuntime::new(Arc::new(spawn)));
}
pub fn set_scheduling(&mut self, scheduling: Scheduling) {
self.scheduling = scheduling;
}
/// Called by the host once the previous output was presented.
pub fn begin_frame(&mut self) {
self.frame_start = self.async_runtime().clock().now();
}
/// How long a deferred re-evaluation waits for the next frame.
pub fn until_next_frame(&self) -> Option<Duration> {
let budget = self.frame_budget()?;
let elapsed = self.frame_elapsed().as_nanos() % budget.as_nanos();
self.rerun.then(|| budget - Duration::from_nanos(elapsed as u64))
}
fn frame_elapsed(&self) -> Duration {
self.async_runtime().clock().now().saturating_sub(self.frame_start)
}
fn frame_budget(&self) -> Option<Duration> {
self.scheduling.frame_budget.filter(|budget| !budget.is_zero())
}
fn frame_has_budget(&self) -> bool {
self.frame_budget().is_none_or(|budget| self.frame_elapsed() < budget)
}
pub(crate) fn async_runtime(&self) -> &AsyncRuntime {
fn async_runtime(&self) -> &AsyncRuntime {
self.async_runtime.as_ref().expect("the task executor is installed before the first graph update")
}
}
struct NodeTaskExecutor {
spawner: Spawner,
dirty: Arc<AtomicBool>,
wake: Wake,
}
impl Spawn for NodeTaskExecutor {
fn spawn(&self, task: Task) {
let dirty = self.dirty.clone();
let wake = self.wake.clone();
self.spawner.spawn(Box::pin(async move {
task.await;
dirty.store(true, Ordering::Release);
wake();
}));
}
@@ -683,8 +648,8 @@ impl InspectState {
})
}
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));
fn access(&mut self, executor: &DynamicExecutor) -> InspectResult {
let node = executor.tree().output_node(&self.inspect_node_path, executor.output());
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));
@@ -729,98 +694,3 @@ impl InspectState {
data
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::{EditorTestUtils, FakeClock};
use graph_craft::document::DocumentNode;
use graphene_std::SourceId;
use graphene_std::runtime::Runtime;
#[test]
fn a_preview_replaces_the_export_of_the_graph_being_compiled() {
let previewed_node = NodeId(1);
let exported_node = NodeId(2);
let mut network = NodeNetwork {
exports: vec![NodeInput::node(exported_node, 0)],
nodes: [(previewed_node, DocumentNode::default()), (exported_node, DocumentNode::default())].into_iter().collect(),
..Default::default()
};
apply_previews(
&mut network,
&[(
Vec::new(),
RootNode {
node_id: previewed_node,
output_index: 0,
},
)],
);
assert_eq!(network.exports.first().and_then(|export| export.as_node()), Some(previewed_node));
}
const SOURCE: SourceId = SourceId(1);
async fn editor(clock: &Arc<FakeClock>) -> EditorTestUtils {
let mut editor = EditorTestUtils::create_with(Scheduling::default(), clock.clone());
editor.new_document().await;
// SVG Preview renders through the SVG pipeline, which sends each evaluation's artwork to the frontend where it can be seen
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
editor.draw_rect(0., 0., 100., 100.).await;
editor.runtime.async_runtime().retain_sources(&[SOURCE]);
editor.runtime.begin_frame();
editor
}
fn finish_task(editor: &EditorTestUtils) {
editor.runtime.async_runtime().spawn(SOURCE, Box::pin(async {}));
}
async fn evaluates(editor: &mut EditorTestUtils) -> bool {
editor.runtime.run().await;
let messages = editor.editor.handle_message(Message::Wake);
messages.iter().any(|message| matches!(message, FrontendMessage::UpdateDocumentArtwork { .. }))
}
#[tokio::test]
async fn reevaluations_past_the_frame_budget_wait_for_the_next_frame() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
finish_task(&editor);
finish_task(&editor);
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "two finished tasks re-evaluated twice");
clock.advance(Duration::from_millis(20));
finish_task(&editor);
assert!(!evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), Some(Duration::from_millis(12)));
editor.runtime.begin_frame();
assert!(evaluates(&mut editor).await);
assert_eq!(editor.runtime.until_next_frame(), None);
}
#[tokio::test]
async fn explicit_requests_ignore_the_frame_budget() {
let clock = Arc::new(FakeClock::default());
let mut editor = editor(&clock).await;
clock.advance(Duration::from_millis(100));
finish_task(&editor);
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();
portfolio
.executor
.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO)
.unwrap();
assert!(evaluates(&mut editor).await);
assert!(!evaluates(&mut editor).await, "the finished task re-evaluated after the explicit request");
}
}
@@ -1,25 +1,23 @@
use super::evaluated_output;
use super::{evaluated_output, monitor_parent_node, records_vector};
use crate::messages::frontend::FrontendMessage;
#[cfg(feature = "gpu")]
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;
#[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;
#[cfg(all(target_family = "wasm", feature = "wasm"))]
use graphene_std::platform_application_io::canvas_utils::{Canvas, CanvasHandle};
use graphene_std::raster_types::{CPU, GPU, Raster};
#[cfg(feature = "gpu")]
use graphene_std::raster_types::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, Context, ContextFeatures, Graphic};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::Arc;
@@ -42,13 +40,11 @@ fn cell_size(scale: f64) -> UVec2 {
(CELL_SIZE * scale).round().as_uvec2().max(UVec2::ONE)
}
/// The thumbnails of the layers, rendered from their content when it changes while they're in view.
/// The thumbnails of the layers, rendered from the content their monitor nodes watch when it changes while they're in view.
#[derive(Default)]
pub struct Thumbnails {
/// The proto node giving the content each layer's thumbnail shows.
sources: HashMap<NodeId, NodeId>,
/// The layers whose content changed since their thumbnail was last rendered.
stale: HashSet<NodeId>,
/// The monitor nodes whose content changed since their layer's thumbnail was last rendered.
stale: HashSet<Vec<NodeId>>,
/// The layers whose thumbnails the frontend shows, the only ones rendered.
in_view: HashSet<NodeId>,
/// The device pixel ratio thumbnails are rendered at.
@@ -77,45 +73,39 @@ impl Thumbnails {
}
/// Thumbnails rendered at another device pixel ratio are rendered again.
pub fn set_scale(&mut self, scale: f64) {
pub fn set_scale(&mut self, scale: f64, monitor_nodes: &[(Vec<NodeId>, NodeId)]) {
if scale != self.scale {
self.stale.extend(self.sources.keys().copied());
self.stale.extend(monitor_nodes.iter().map(|(path, _)| path.clone()));
}
self.scale = scale;
}
/// Finds the proto node giving each layer's content in the newly compiled graph, marking the layers whose proto node changed as stale.
pub fn update_sources(&mut self, layer_paths: &[Vec<NodeId>], network: &NodeNetwork, executor: &DynamicExecutor) {
// O(layers * depth)
let sources: HashMap<NodeId, NodeId> = layer_paths
.iter()
.filter_map(|layer_path| Some((*layer_path.last()?, thumbnail_source(layer_path, network, executor)?)))
.collect();
/// Marks the thumbnails of the monitor nodes whose proto node ID changed as stale.
pub fn update_monitors(&mut self, previous_monitor_ids: &HashMap<Vec<NodeId>, NodeId>, monitor_nodes: &[(Vec<NodeId>, NodeId)]) {
// A proto node's ID hashes everything upstream of it, so a monitor node whose ID stayed the same records the same output
let changed_monitors = monitor_nodes.iter().filter(|(path, id)| previous_monitor_ids.get(path) != Some(id));
self.stale.extend(changed_monitors.map(|(path, _)| path.clone()));
// A proto node's ID hashes everything upstream of it, so a layer whose source kept its ID shows the same content
let changed = sources.iter().filter(|(layer, source)| self.sources.get(layer) != Some(source));
self.stale.extend(changed.map(|(layer, _)| *layer));
self.stale.retain(|layer| sources.contains_key(layer));
self.sources = sources;
let current_monitors: HashSet<&Vec<NodeId>> = monitor_nodes.iter().map(|(path, _)| path).collect();
self.stale.retain(|path| current_monitors.contains(path));
}
/// Forgets the thumbnails of the layers with no content to show anymore, giving them back so the frontend can clear them.
pub fn drop_sourceless(&mut self) -> Vec<NodeId> {
/// Forgets the thumbnails of the layers no longer monitored, giving them back so the frontend can clear them.
pub fn drop_unmonitored(&mut self, monitor_nodes: &[(Vec<NodeId>, NodeId)]) -> Vec<NodeId> {
// TODO: Consider optimizing this since it's currently O(m*n^2), with a sort it could be made O(m * n*log(n))
let mut dropped = Vec::new();
let sources = &self.sources;
let mut keep_sourced = |layer: &NodeId| {
let sourced = sources.contains_key(layer);
if !sourced {
dropped.push(*layer);
let mut keep_monitored = |id: &NodeId| {
let monitored = monitor_nodes.iter().any(|(monitor_node_path, _)| monitor_node_path.contains(id));
if !monitored && !dropped.contains(id) {
dropped.push(*id);
}
sourced
monitored
};
#[cfg(all(target_family = "wasm", feature = "wasm"))]
self.canvases.retain(|layer, _| keep_sourced(layer));
self.canvases.retain(|id, _| keep_monitored(id));
#[cfg(not(all(target_family = "wasm", feature = "wasm")))]
self.sent.retain(|layer| keep_sourced(layer));
self.sent.retain(|id| keep_monitored(id));
dropped
}
@@ -123,16 +113,19 @@ impl Thumbnails {
/// Renders the thumbnails of the layers in view whose content changed since they were last rendered, keeping the others stale until they come into view.
pub async fn render_stale(&mut self, executor: &DynamicExecutor, editor_api: &PlatformEditorApi, responses: &mut VecDeque<FrontendMessage>) {
let mut contents = HashMap::new();
for layer in std::mem::take(&mut self.stale) {
let Some(&source) = self.sources.get(&layer) else { continue };
for monitor_node_path in std::mem::take(&mut self.stale) {
let Some(layer) = monitor_parent_node(&monitor_node_path) else { continue };
if records_vector(executor, &monitor_node_path) {
continue;
}
if !self.in_view.contains(&layer) {
self.stale.insert(layer);
self.stale.insert(monitor_node_path);
continue;
}
let Some(content) = ThumbnailContent::evaluate(executor, source) else {
self.stale.insert(layer);
let Some(content) = ThumbnailContent::evaluate(executor, &monitor_node_path) else {
self.stale.insert(monitor_node_path);
continue;
};
contents.insert(layer, content);
@@ -164,7 +157,10 @@ impl Thumbnails {
for layers in layers.chunks(cells_per_atlas) {
let layout = ThumbnailAtlasLayout::new(layers.to_vec(), self.scale);
let texture = executor.render_vello(layout.size(), DAffine2::IDENTITY, &mut |scene| atlas::draw_atlas(scene, &layout, contents));
let texture = executor.vello_scene(layout.size(), DAffine2::IDENTITY).and_then(|mut scene| {
atlas::draw_atlas(&mut scene, &layout, contents);
executor.render_vello_scene(scene)
});
let texture = match texture {
Ok(texture) => texture,
Err(error) => {
@@ -305,9 +301,10 @@ enum ThumbnailContent {
}
impl ThumbnailContent {
/// Evaluates the content node again from its last context, normalized so thumbnails don't depend on the view or playhead.
fn evaluate(executor: &DynamicExecutor, content_node: NodeId) -> Option<Self> {
/// Evaluates the content a monitor node watches again from its last context, normalized so thumbnails don't depend on the view or playhead.
fn evaluate(executor: &DynamicExecutor, monitor_node_path: &[NodeId]) -> Option<Self> {
let tree = executor.tree();
let content_node = tree.input_node(monitor_node_path, 0).ok()?;
let context = tree.last_context(content_node).ok()??;
// Replacing a feature the content doesn't read would only miss its caches
@@ -330,8 +327,8 @@ impl ThumbnailContent {
} else if output.is::<Item<String>>() {
Self::Text(List::new_from_item(*output.downcast().ok()?))
} else {
// Any layer can show other graphical content as a group of its own, and shows nothing for content that isn't graphical
Self::Graphics(into_graphic(output).map(List::new_from_element).unwrap_or_default())
log::warn!("Failed to downcast the content of monitor node {monitor_node_path:?} for its thumbnail");
return None;
};
Some(content)
}
@@ -362,51 +359,6 @@ impl ThumbnailContent {
}
}
/// 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
};
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
}
/// Converts the other kinds of graphical content into a graphic.
fn into_graphic(output: graphene_std::registry::Any) -> Option<Graphic> {
macro_rules! downcast_into_graphic {
($($content:ty),*) => {$(
if output.is::<$content>() {
return output.downcast::<$content>().ok().map(|content| Graphic::from(*content));
}
)*};
}
downcast_into_graphic!(
List<Vector>,
Item<Vector>,
List<Raster<CPU>>,
Item<Raster<CPU>>,
List<Raster<GPU>>,
Item<Raster<GPU>>,
List<Color>,
Item<Color>,
List<Gradient>,
Item<Gradient>
);
None
}
/// Returns the union of the artboards' clipping rectangles, used as the thumbnail bounds for an artboard layer so the
/// framing matches what's actually visible after clipping rather than the unclipped content extents.
fn artboard_clip_bounds(artboards: &List<Artboard>) -> RenderBoundingBox {
@@ -441,58 +393,3 @@ fn expand_to_thumbnail_aspect(bounds: [DVec2; 2]) -> [DVec2; 2] {
let half = DVec2::new(width, height) / 2.;
[center - half, center + half]
}
#[cfg(test)]
mod tests {
use crate::messages::portfolio::document::utility_types::network_interface::FlowType;
use crate::test_utils::test_prelude::*;
use glam::UVec2;
use graph_craft::document::NodeId;
use graphene_std::application_io::TimingInformation;
async fn compile_and_run(editor: &mut EditorTestUtils) {
let portfolio = editor.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
executor
.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., TimingInformation::default(), Vec::new(), true, DVec2::ZERO)
.unwrap();
editor.runtime.run().await;
editor.dispatch(Message::Wake);
}
fn compiled_id(editor: &EditorTestUtils, path: &[NodeId]) -> Option<NodeId> {
editor.runtime.executor.tree().source_map().get(path).map(|(id, _)| *id)
}
#[tokio::test]
async fn a_merge_layer_shows_its_content_and_another_layer_its_output() {
let mut editor = EditorTestUtils::create();
editor.new_document().await;
editor.draw_rect(0., 0., 10., 10.).await;
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, NodeId(3)]);
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
assert_eq!(
editor.runtime.thumbnails.sources.get(&layer).copied(),
merge_content,
"A Merge layer shows only the content it adds to the stack"
);
// The node feeding the layer's content, shown as a layer itself
let network_interface = &mut editor.active_document_mut().network_interface;
let content_node = network_interface
.upstream_flow_back_from_nodes(vec![layer], &[], FlowType::HorizontalFlow)
.nth(1)
.expect("The layer should have a content chain");
network_interface.set_to_node_or_layer(&content_node, &[], true);
compile_and_run(&mut editor).await;
let content_output = compiled_id(&editor, &[content_node]);
assert!(content_output.is_some(), "The content node should be compiled");
assert_eq!(editor.runtime.thumbnails.sources.get(&content_node).copied(), content_output, "Any other layer shows its output");
}
}
+1 -1
View File
@@ -1,4 +1,4 @@
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
pub use graphene_std::runtime::{Spawn, Task};
use std::sync::Arc;
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
+13 -100
View File
@@ -9,19 +9,17 @@ use crate::messages::prelude::*;
use crate::messages::tool::tool_messages::tool_prelude::Key;
use crate::messages::tool::utility_types::ToolType;
use crate::node_graph_executor::Instrumented;
use crate::node_graph_executor::{EvaluationErrors, NodeRuntime};
use crate::task::{Scheduling, Spawn, Task};
use crate::node_graph_executor::NodeRuntime;
use crate::task::{Spawn, Task};
use crate::test_utils::test_prelude::LayerNodeIdentifier;
use document_container::store::MemoryStore;
use glam::{DVec2, UVec2};
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graph_craft::application_io::{ApplicationIo, PlatformApplicationIo};
use graphene_std::raster::color::Color;
use graphene_std::runtime::Clock;
use graphene_std::uuid::NodeId;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, LazyLock, Mutex, PoisonError};
use std::time::Duration;
/// A set of utility functions to make the writing of editor test more declarative
pub struct EditorTestUtils {
@@ -32,10 +30,6 @@ pub struct EditorTestUtils {
impl EditorTestUtils {
pub fn create() -> Self {
Self::create_with(Scheduling::UNLIMITED, Arc::new(FakeClock::default()))
}
pub fn create_with(scheduling: Scheduling, clock: Arc<dyn Clock>) -> Self {
init_test_logger();
let woken = Arc::new(AtomicBool::new(false));
@@ -48,7 +42,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default()))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -63,11 +57,6 @@ impl EditorTestUtils {
editor
}
/// The GPU executor the graph runs on.
pub fn gpu_executor(&self) -> <PlatformApplicationIo as ApplicationIo>::Executor {
gpu_application_io().gpu_executor().cloned().expect("tests render on the GPU")
}
pub fn dispatch(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
let mut responses = self.editor.handle_message(message);
while self.woken.swap(false, Ordering::Relaxed) {
@@ -79,7 +68,7 @@ impl EditorTestUtils {
/// Submit an evaluation to the executor, run the runtime, and process the results.
///
/// If a deferred message triggers a second graph run, this will not occur. See [`Self::eval_graph_until_finished`] for this behaviour.
async fn eval_graph_once(&mut self) -> Result<Instrumented, TestGraphError> {
async fn eval_graph_once(&mut self) -> Result<Instrumented, String> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
@@ -87,23 +76,17 @@ impl EditorTestUtils {
let instrumented = match executor.update_node_graph_instrumented(document) {
Ok(instrumented) => instrumented,
Err(e) => return Err(TestGraphError::Other(format!("update_node_graph_instrumented failed\n\n{e}"))),
Err(e) => return Err(format!("update_node_graph_instrumented failed\n\n{e}")),
};
if let Err(e) = executor.submit_current_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), DVec2::ZERO) {
return Err(TestGraphError::Other(format!("submit_current_node_graph_evaluation failed\n\n{e}")));
return Err(format!("submit_current_node_graph_evaluation failed\n\n{e}"));
}
self.runtime.run().await;
let frontend_messages = self.dispatch(Message::Wake);
let evaluation_errors = self.portfolio_message_handler_mut().executor.take_evaluation_errors();
if evaluation_errors.is_none() && frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err(TestGraphError::Render);
}
#[cfg(feature = "gpu")]
let evaluation_errors = evaluation_errors.filter(|errors| !errors.iter().all(|(error, _)| error.is::<wgpu_executor::NoGpuError>()));
if let Some(errors) = evaluation_errors {
return Err(TestGraphError::Evaluation(errors));
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err("Graph should render".to_string());
}
for message in frontend_messages {
@@ -113,35 +96,8 @@ impl EditorTestUtils {
Ok(instrumented)
}
/// Compiles and runs the graph without the monitors of [`Instrumented`], which can't wrap the runtime handle that asynchronous nodes take.
pub async fn eval_graph_uninstrumented(&mut self) -> Result<(), String> {
let portfolio = &mut self.portfolio_message_handler_mut();
let document_id = portfolio.active_document_id.unwrap();
let (executor, documents) = (&mut portfolio.executor, &mut portfolio.documents);
let document = documents.get_mut(&document_id).unwrap();
if let Err(e) = executor.submit_node_graph_evaluation(document, document_id, UVec2::ONE, 1., Default::default(), Vec::new(), true, Default::default()) {
return Err(format!("submit_node_graph_evaluation failed\n\n{e}"));
}
self.finish_evaluation().await
}
/// Waits for the submitted evaluation and processes its results, failing if the graph didn't render.
async fn finish_evaluation(&mut self) -> Result<(), String> {
self.runtime.run().await;
let frontend_messages = self.dispatch(Message::Wake);
if frontend_messages.contains(&FrontendMessage::UpdateRenderStatus { status: RenderStatus::Error }) {
return Err("Graph should render".to_string());
}
for message in frontend_messages {
message.check_node_graph_error();
}
Ok(())
}
/// Repeatedly calls [`Self::eval_graph_once`] until no more runs are triggered by deferred messages.
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, TestGraphError> {
pub async fn eval_graph_until_finished(&mut self) -> Result<Instrumented, String> {
const MAX_ITERATIONS: usize = 16;
for _iteration in 0..MAX_ITERATIONS {
let execution_id = self.portfolio_message_handler().executor.current_execution_id();
@@ -151,7 +107,7 @@ impl EditorTestUtils {
return Ok(result);
}
}
return Err(TestGraphError::Other(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping")));
return Err(format!("eval_graph_until_finished exceeded {MAX_ITERATIONS} graph executions; stopping"));
}
pub async fn handle_message(&mut self, message: impl Into<Message>) -> Vec<FrontendMessage> {
@@ -460,23 +416,6 @@ impl FrontendMessageTestUtils for FrontendMessage {
}
}
#[derive(Debug)]
pub enum TestGraphError {
Evaluation(EvaluationErrors),
Render,
Other(String),
}
impl std::fmt::Display for TestGraphError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Evaluation(errors) => write!(f, "Graph evaluation failed:\n{errors}"),
Self::Render => write!(f, "Graph should render"),
Self::Other(message) => write!(f, "{message}"),
}
}
}
thread_local! {
static CAPTURED_ERRORS: std::cell::RefCell<Option<Vec<String>>> = const { std::cell::RefCell::new(None) };
}
@@ -520,16 +459,6 @@ fn init_test_logger() {
});
}
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
/// Panics if no adapter is found, since tests render on the GPU like the app does.
fn gpu_application_io() -> PlatformApplicationIo {
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
let executor = GPU_EXECUTOR.clone().expect(
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
);
PlatformApplicationIo::new_with_executor(executor)
}
/// Runs `operation`, returning its result along with the errors it logged.
pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String>) {
init_test_logger();
@@ -541,22 +470,6 @@ pub fn capture_logged_errors<T>(operation: impl FnOnce() -> T) -> (T, Vec<String
(result, errors)
}
/// A clock that only moves when advanced.
#[derive(Debug, Default)]
pub struct FakeClock(Mutex<Duration>);
impl FakeClock {
pub fn advance(&self, by: Duration) {
*self.0.lock().unwrap_or_else(PoisonError::into_inner) += by;
}
}
impl Clock for FakeClock {
fn now(&self) -> Duration {
*self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
struct BlockingSpawner;
impl Spawn for BlockingSpawner {
fn spawn(&self, task: Task) {
@@ -578,7 +491,7 @@ pub mod test_prelude {
pub use crate::messages::tool::common_functionality::graph_modification_utils::{NodeGraphLayer, is_layer_fed_by_node_of_name};
pub use crate::messages::tool::utility_types::ToolType;
pub use crate::node_graph_executor::NodeRuntime;
pub use crate::test_utils::{EditorTestUtils, TestGraphError};
pub use crate::test_utils::EditorTestUtils;
pub use core::f64;
pub use glam::{DVec2, IVec2};
pub use graph_craft::document::DocumentNode;
Generated
+9 -9
View File
@@ -2,11 +2,11 @@
"nodes": {
"crane": {
"locked": {
"lastModified": 1792350552,
"narHash": "sha256-292lvpvxTGKryKxh3/3tcIVi85CwYGdl4oOi113Sob8=",
"lastModified": 1789760033,
"narHash": "sha256-jtT4yxZpR8seYnlCMMWSSPlFN92zO6ICuZ8pJrmi86k=",
"owner": "ipetkov",
"repo": "crane",
"rev": "e675a36b7377bebe41d548388a2501cbb16d380d",
"rev": "73b980519cefc727a5f6cc8e5c0947a2f9be6edd",
"type": "github"
},
"original": {
@@ -17,11 +17,11 @@
},
"nixpkgs": {
"locked": {
"lastModified": 1792773339,
"narHash": "sha256-rZLrzrC6i+jnTAlvPZHogKDulY7WWDEv9hJeHieO7Zw=",
"lastModified": 1790578696,
"narHash": "sha256-ZoxIApko70jCdbH3l20HWXOBaT2HZd87orzd2yJ9dVE=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "3ec636362e1816bc2f0888fa0fa2c69f1bc9e504",
"rev": "7a0f122f5090cf4c2ade2a13a0e229d4e19ba71f",
"type": "github"
},
"original": {
@@ -45,11 +45,11 @@
]
},
"locked": {
"lastModified": 1793086596,
"narHash": "sha256-ObKS44vw4IIVpQ69YJzUGjZ0IwnpWoUlwjJSY7gefdo=",
"lastModified": 1790756160,
"narHash": "sha256-NPs4nNLxCpho3Ctj8O7t/bzmX0zR8r0zndKghAFEz5U=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "c7e9d512653a35ef4d5879c3df4d44d7b78d0e6d",
"rev": "ed3a19fd0439ed618ec5fe1e12f0ba69a8be38b5",
"type": "github"
},
"original": {
@@ -192,7 +192,6 @@
if (!canvasName) return;
// Get the canvas element from the global storage
let canvas = window.imageCanvases[canvasName];
if (!canvas) return;
// Get logical dimensions from foreignObject parent (set by backend)
const foreignObject = placeholder.parentElement;
Loaded 100 of 326 files, more files were not shown because too many files have changed in this diff. Show more