Compare commits

..
Author SHA1 Message Date
Dennis Kobert 6b8040dab5 Remove no_std leftovers 2026-10-31 09:01:43 +00:00
Dennis Kobert 4b90f41d69 Remove the unused parallel rows helper 2026-10-31 09:01:27 +00:00
Dennis Kobert 892ad740e3 Report a raster kernel's GPU failures and oversized outputs rather than saying a GPU is required 2026-10-31 09:01:27 +00:00
Dennis Kobert 0d4f64d326 Test that a footprint-dependent raster warns at Dehaze and feeds Median without one 2026-10-30 20:22:17 -07:00
Dennis Kobert 3e58246c0b Wait for a readback's map callback when another thread's poll is running it 2026-10-30 20:22:17 -07:00
Keavon Chambers 6264e7396a Add curvature dials to gradients, rendered as a pencil of circles on Vello GPU 2026-10-30 20:22:17 -07:00
Keavon Chambers 9bf8f2469d Replace Color Overlay with a Paint Overlay effect that paints with any graphic 2026-10-30 20:22:17 -07:00
Dennis Kobert e6cb938ff9 Load images into CPU rasters by default again 2026-10-30 20:22:17 -07:00
Dennis Kobert 95e9c2852e Upload a CPU raster wire feeding a GPU-only input through its input adapter 2026-10-30 20:22:17 -07:00
Keavon Chambers 06d83843fa Speed up adjusted solid vector paints by folding the adjustments into the paint 2026-10-30 20:22:05 -07:00
Keavon Chambers 28e0112504 Speed up an image's leading adjustments by running them on a copy of its texture 2026-10-30 20:22:05 -07:00
Dennis Kobert 11d097f103 Give GPU rasters drawn smaller than their pixels mipmaps 2026-10-30 20:22:05 -07:00
Keavon Chambers 78e3166d22 Extend adjustments to images, colors, and gradients, stamped on images and carried out at once on colors and gradients 2026-10-30 20:22:05 -07:00
Keavon Chambers 661f37fa17 Allow adjustments on any graphic, carried out on the GPU by their kernels 2026-10-30 20:22:05 -07:00
Keavon Chambers aa7ebfc18c Add a Bevel & Emboss effect lighting the inner, outer, emboss, and pillow slopes 2026-10-30 20:22:05 -07:00
Keavon Chambers 2be0d1889b Add Inner Glow, Satin, and Outline effects to any graphic 2026-10-30 20:22:05 -07:00
Dennis Kobert 3b7d46836d Add an Eager node that uploads a raster and carries out its effects 2026-10-30 20:22:05 -07:00
Keavon Chambers 8f0ef2da8b Add Blur, Drop Shadow, Inner Shadow, and Outer Glow effects to any graphic 2026-10-30 20:22:05 -07:00
Keavon Chambers b88eee543a Move the noise and Mandelbrot kernels into a generator module rendering any area 2026-10-30 20:22:05 -07:00
Keavon Chambers e01f602b13 Upload images with mipmaps so they average their pixels when zoomed out 2026-10-30 20:22:05 -07:00
Keavon Chambers 8fd36852c1 Gather each adjustment's settings into plain data run by its kernel 2026-10-30 20:22:05 -07:00
Dennis Kobert 1bfbd8f4f8 Mark the Dehaze node as footprint invariant 2026-10-30 20:22:05 -07:00
Dennis Kobert c698fb157d Give content that nodes move or copy a footprint covering everywhere it lands 2026-10-30 20:22:05 -07:00
Dennis Kobert 48ee95a802 Keep a GPU raster's logical placement separate from the region its pixels cover 2026-10-30 20:22:05 -07:00
Dennis Kobert f3edba1603 Fall back to half-float rasters where the GPU can't render full floats 2026-10-30 20:22:05 -07:00
Dennis Kobert 7bb28460cc Merge no-std-types into core-types 2026-10-30 20:22:05 -07:00
Dennis Kobert f8c3984b6c Render the Rasterize node with Vello 2026-10-30 20:22:05 -07:00
Dennis Kobert 9ca321fdcf Remove CPU raster paths from raster nodes 2026-10-30 20:22:05 -07:00
Dennis Kobert d53c990f72 Run raster consumers on GPU rasters 2026-10-30 20:22:05 -07:00
Dennis Kobert ecaa5bb906 Load images into GPU rasters 2026-10-30 20:22:05 -07:00
Dennis Kobert fc488dd91f Embed GPU rasters in SVG output by downloading them first 2026-10-30 20:22:05 -07:00
Dennis Kobert a12cbea9fb Shade the Mandelbrot set by smooth escape time 2026-10-30 20:22:05 -07:00
Dennis Kobert 7b0298fe96 Run headless editor tests on a software GPU 2026-10-30 20:22:05 -07:00
Dennis Kobert ceb39a2c5b Give GPU rasters an empty default 2026-10-30 20:22:04 -07:00
Dennis Kobert b9e0df685f Run Dehaze and Image Color Palette on GPU rasters 2026-10-30 20:22:04 -07:00
Dennis Kobert 135b05bacf Run raster nodes on GPU rasters through hand-written WGSL kernels 2026-10-30 20:22:04 -07:00
Keavon Chambers 43316436c2 Port FastNoise Lite to WGSL 2026-10-30 20:22:04 -07:00
Keavon Chambers d555a4b3f1 Move CI from the self-hosted runners to GitHub's, with runners selectable through repo variables (#4874) 2026-10-30 19:37:39 -07:00
Keavon Chambers b39ec01d7d Retire Rust GPU, the 'Upload Texture' node, and the "GPU"-suffixed adjustment node twins (#4873)
* Retire the rust-gpu twins of the adjustment nodes, leaving rust-gpu dormant

* Remove the dormant rust-gpu shader crate and everything that supported it
2026-10-30 17:52:29 -07:00
Keavon Chambers 09099bf033 Speed up raster nodes with threads and caching (#4859) 2026-10-30 14:23:43 -07:00
Dennis Kobert ef3b45ae79 Limit number of instant graph reevaluations (#4758)
* Defer re-evaluations triggered by finished tasks to the next frame once the frame budget is spent, and abort the tasks of removed sources

* Clean up the frame budget change: share the Instant clock, drop redundant scheduling calls and comments

* Treat a zero frame budget as unlimited, let render signals cut the deferred-frame wait short, and fix the RFC's Runtime::spawn signature
2026-10-30 17:20:36 +01:00
Dennis Kobert b574a6c9f3 Keep a history metadata log external to the actual history (#4849)
Keep a history metadata log: facts about users and revs in an append-only file beside the history
2026-10-30 17:18:42 +01:00
235 changed files with 17444 additions and 6555 deletions

No files matched your search

+26 -11
View File
@@ -47,20 +47,24 @@ on:
jobs:
web:
if: github.event_name == 'push' || inputs.web
runs-on: [self-hosted, target/wasm]
# 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' }}
permissions:
contents: write
deployments: write
pull-requests: write
env:
CARGO_TERM_COLOR: always
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 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`
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"
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
@@ -82,7 +86,12 @@ jobs:
rustflags: ""
target: wasm32-unknown-unknown
- name: 🚧 Install wasm-bindgen-cli and Binaryen wasm-opt
- 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
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() {
@@ -107,6 +116,12 @@ 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'
@@ -127,7 +142,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: mold -run cargo run build web${{ inputs.debug && ' debug' || '' }}
run: cargo run build web${{ inputs.debug && ' debug' || '' }}
- name: 📤 Publish to Cloudflare Pages
if: inputs.merge_queue == false
@@ -299,7 +314,7 @@ jobs:
cd frontend
npm run check
# Runs on a GitHub-hosted runner to keep the self-hosted one free for web builds
# A job of its own so its native compile doesn't delay the web build and deploy
code-docs:
if: github.event_name == 'push' && github.ref != 'refs/tags/latest-stable'
runs-on: ubuntu-latest
@@ -325,7 +340,7 @@ jobs:
windows:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.windows
runs-on: windows-latest
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'windows-latest' || vars.WINDOWS_RUNNER || 'windows-latest' }}
permissions:
contents: read
id-token: write
@@ -535,7 +550,7 @@ jobs:
mac:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.mac
runs-on: macos-latest
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'macos-latest' || vars.MACOS_RUNNER || 'macos-latest' }}
permissions:
contents: read
pull-requests: write
@@ -741,7 +756,7 @@ jobs:
linux:
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
runs-on: ubuntu-latest
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
permissions:
contents: read
pull-requests: write
+23 -9
View File
@@ -3,10 +3,14 @@ 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 (merge queue refs are unique per entry, so those never cancel each other)
# 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)
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}
group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.sha }}
cancel-in-progress: true
env:
@@ -111,7 +115,8 @@ 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.
if: ${{ !cancelled() }}
# Master pushes are left out because `build.yml` builds and deploys those itself.
if: ${{ !cancelled() && github.event_name != 'push' }}
uses: ./.github/workflows/build.yml
# The called workflow's jobs can only narrow these, so this grants the union of what they request
permissions:
@@ -125,18 +130,22 @@ jobs:
web: ${{ needs.skip-check.outputs.skip != 'true' }}
merge_queue: ${{ github.event_name == 'merge_group' }}
# Run the Rust tests on the self-hosted native runner
# Run the Rust tests
test:
needs: skip-check
if: ${{ !cancelled() && needs.skip-check.outputs.skip != 'true' }}
runs-on: [self-hosted, target/native]
# 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' }}
permissions:
contents: read
env:
RUSTC_WRAPPER: /usr/bin/sccache
CARGO_INCREMENTAL: 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
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"
steps:
- name: 📥 Clone repository
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
@@ -149,6 +158,11 @@ 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
@@ -156,7 +170,7 @@ jobs:
env:
# `--cfg=web_sys_unstable_apis` mirrors the `[build]` section of `.cargo/config.toml`
RUSTFLAGS: "-Dwarnings --cfg=web_sys_unstable_apis"
run: mold -run cargo test --all-features
run: cargo test --all-features
# Rust format check on GitHub runner
rust-fmt:
-45
View File
@@ -1,45 +0,0 @@
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
@@ -1,89 +0,0 @@
#!/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
View File
@@ -31,7 +31,6 @@ let
deps = {
crane = lib.call ./deps/crane.nix;
rustGPU = lib.call ./deps/rust-gpu.nix;
cargoAbout = lib.call ./deps/cargo-about.nix;
};
@@ -57,7 +56,6 @@ 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; };
-55
View File
@@ -1,55 +0,0 @@
{ 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";
};
}
+6 -2
View File
@@ -47,13 +47,17 @@ 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
@@ -1,28 +0,0 @@
{
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;
}
-2
View File
@@ -35,7 +35,6 @@ 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"
];
}
);
@@ -97,7 +96,6 @@ 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
+66 -406
View File
@@ -313,7 +313,6 @@ version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
dependencies = [
"bytemuck",
"serde_core",
]
@@ -336,7 +335,7 @@ name = "blending-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam 0.33.10",
"glam",
"graphic-types",
"node-macro",
"serde",
@@ -378,7 +377,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"graphic-types",
"half",
@@ -396,7 +395,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"serde",
]
@@ -488,29 +487,6 @@ dependencies = [
"serde",
]
[[package]]
name = "cargo-gpu-install"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "668b4bd1b59810c4f907eeb36bb0f0a450c824219b2e599b9b8ef2b3ae056e94"
dependencies = [
"anyhow",
"cargo_metadata 0.21.0",
"directories",
"log",
"serde",
"spirv-builder",
]
[[package]]
name = "cargo-platform"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "84982c6c0ae343635a3a4ee6dedef965513735c8b183caa7289fa6e27399ebd4"
dependencies = [
"serde",
]
[[package]]
name = "cargo-platform"
version = "0.3.3"
@@ -550,37 +526,6 @@ dependencies = [
"notify-debouncer-full",
]
[[package]]
name = "cargo-util-schemas"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7dc1a6f7b5651af85774ae5a34b4e8be397d9cf4bc063b7e6dbd99a841837830"
dependencies = [
"semver",
"serde",
"serde-untagged",
"serde-value",
"thiserror 2.0.18",
"toml 0.8.23",
"unicode-xid",
"url",
]
[[package]]
name = "cargo_metadata"
version = "0.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5cfca2aaa699835ba88faf58a06342a314a950d2b9686165e038286c30316868"
dependencies = [
"camino",
"cargo-platform 0.2.0",
"cargo-util-schemas",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "cargo_metadata"
version = "0.23.1"
@@ -588,7 +533,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef987d17b0a113becdd19d3d0022d04d7ef41f9efe4f3fb63ac44ba61df3ade9"
dependencies = [
"camino",
"cargo-platform 0.3.3",
"cargo-platform",
"semver",
"serde",
"serde_json",
@@ -619,7 +564,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb823e721b3ea203f4635e71532db2b010696c074518eb4f6154fd7f47fc6fcb"
dependencies = [
"anyhow",
"cargo_metadata 0.23.1",
"cargo_metadata",
"cef-dll-sys",
"clap",
"libloading 0.9.0",
@@ -781,8 +726,6 @@ version = "0.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681"
dependencies = [
"serde",
"termcolor",
"unicode-width",
]
@@ -859,7 +802,7 @@ checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b"
name = "control-protocol"
version = "0.0.0"
dependencies = [
"glam 0.33.10",
"glam",
"serde",
"serde_json",
]
@@ -948,17 +891,19 @@ dependencies = [
"ctor",
"dyn-any",
"futures",
"glam 0.33.10",
"glam",
"graphene-hash",
"half",
"image",
"kurbo",
"log",
"lyon_geom",
"no-std-types",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"parley",
"petgraph 0.7.1",
"petgraph",
"polycool",
"rand",
"rand_chacha",
@@ -966,7 +911,6 @@ dependencies = [
"serde",
"serde_json",
"skrifa",
"thiserror 2.0.18",
"tinyvec",
"tsify",
"wasm-bindgen",
@@ -1227,15 +1171,6 @@ dependencies = [
"crypto-common",
]
[[package]]
name = "directories"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "16f5094c54661b38d03bd7e50df373292118db60b585c08a411c6d840017fe7d"
dependencies = [
"dirs-sys",
]
[[package]]
name = "dirs"
version = "6.0.0"
@@ -1428,7 +1363,7 @@ name = "dyn-any"
version = "0.3.1"
dependencies = [
"dyn-any-derive",
"glam 0.33.10",
"glam",
"reqwest",
]
@@ -1526,16 +1461,6 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "erased-serde"
version = "0.4.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e004d887f51fcb9fef17317a2f3525c887d8aa3f4f50fed920816a688284a5b7"
dependencies = [
"serde",
"typeid",
]
[[package]]
name = "errno"
version = "0.3.13"
@@ -1581,15 +1506,6 @@ dependencies = [
"regex-syntax 0.8.6",
]
[[package]]
name = "fastnoise-lite"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3e5f3c3cc9081e5d0e18bcd50e80cd33cba47fc22f88a9da9c33ecd1c87ea5c0"
dependencies = [
"num-traits",
]
[[package]]
name = "fastrand"
version = "2.3.0"
@@ -1977,36 +1893,6 @@ dependencies = [
"xml-rs",
]
[[package]]
name = "glam"
version = "0.30.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19fc433e8437a212d1b6f1e68c7824af3aed907da60afa994e7f542d18d12aa9"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.31.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "556f6b2ea90b8d15a74e0e7bb41671c9bdf38cd9f78c284d750b9ce58a2b5be7"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.32.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f70749695b063ecbf6b62949ccccde2e733ec3ecbbd71d467dca4e5c6c97cca0"
dependencies = [
"bytemuck",
"libm",
]
[[package]]
name = "glam"
version = "0.33.10"
@@ -2014,7 +1900,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "928452f9c953e142b2f0973e4bd5f34445fcaa8069556ea97a3c9d34d15a4cf8"
dependencies = [
"bytemuck",
"libm",
"serde_core",
]
@@ -2067,7 +1952,7 @@ dependencies = [
"core-types",
"criterion",
"dyn-any",
"glam 0.33.10",
"glam",
"graph-craft",
"graphene-animation",
"graphene-application-io",
@@ -2102,7 +1987,7 @@ name = "graphene-animation"
version = "0.0.0"
dependencies = [
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"kurbo",
"serde",
@@ -2115,7 +2000,7 @@ dependencies = [
"blake3",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"graphene-resource",
"log",
@@ -2132,7 +2017,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-application-io",
"log",
"serde",
@@ -2170,7 +2055,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-animation",
"graphene-hash",
"graphic-types",
@@ -2187,7 +2072,7 @@ dependencies = [
name = "graphene-hash"
version = "0.0.0"
dependencies = [
"glam 0.33.10",
"glam",
"graphene-hash-derive",
"kurbo",
]
@@ -2222,7 +2107,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graph-craft",
"graphene-application-io",
"graphene-canvas-utils",
@@ -2260,7 +2145,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphic-types",
"node-macro",
"rand",
@@ -2277,12 +2162,15 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"graphene-resource",
"node-macro",
"num_enum",
"raster-types",
"serde",
"serde_json",
"tsify",
"vector-types",
"wasm-bindgen",
]
@@ -2298,7 +2186,7 @@ dependencies = [
"dirs",
"fd-lock",
"futures",
"glam 0.33.10",
"glam",
"graphite-desktop-ui",
"graphite-desktop-wrapper",
"interprocess",
@@ -2395,7 +2283,6 @@ dependencies = [
"base64",
"dirs",
"graph-craft",
"graphene-std",
"graphite-editor",
"graphite-wasm-wrapper",
"image",
@@ -2423,7 +2310,7 @@ dependencies = [
"dyn-any",
"env_logger",
"futures",
"glam 0.33.10",
"glam",
"graph-craft",
"graphene-hash",
"graphene-std",
@@ -3027,7 +2914,7 @@ dependencies = [
"criterion",
"dyn-any",
"futures",
"glam 0.33.10",
"glam",
"graph-craft",
"graphene-animation",
"graphene-core",
@@ -3305,7 +3192,7 @@ dependencies = [
"ena",
"itertools 0.14.0",
"lalrpop-util",
"petgraph 0.7.1",
"petgraph",
"regex",
"regex-syntax 0.8.6",
"sha3",
@@ -3614,7 +3501,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-core",
"graphic-types",
"math-parser",
@@ -3635,16 +3522,6 @@ dependencies = [
"unicode-ident",
]
[[package]]
name = "matrixmultiply"
version = "0.3.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08"
dependencies = [
"autocfg",
"rawpointer",
]
[[package]]
name = "memchr"
version = "2.7.5"
@@ -3750,7 +3627,6 @@ dependencies = [
"naga-types",
"num-traits",
"once_cell",
"petgraph 0.8.2",
"rustc-hash 1.1.0",
"spirv",
"thiserror 2.0.18",
@@ -3769,21 +3645,6 @@ dependencies = [
"thiserror 2.0.18",
]
[[package]]
name = "ndarray"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841"
dependencies = [
"matrixmultiply",
"num-complex",
"num-integer",
"num-traits",
"portable-atomic",
"portable-atomic-util",
"rawpointer",
]
[[package]]
name = "ndk"
version = "0.9.0"
@@ -3832,27 +3693,6 @@ dependencies = [
"libc",
]
[[package]]
name = "no-std-types"
version = "0.0.0"
dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"graphene-hash",
"half",
"log",
"node-macro",
"num-derive",
"num-traits",
"num_enum",
"serde",
"spirv-std",
"tsify",
"wasm-bindgen",
]
[[package]]
name = "node-docs"
version = "0.0.0"
@@ -3872,12 +3712,10 @@ dependencies = [
"convert_case 0.12.0",
"core-types",
"indoc",
"no-std-types",
"proc-macro-crate",
"proc-macro-error2",
"proc-macro2",
"quote",
"strum",
"syn 2.0.106",
]
@@ -3956,15 +3794,6 @@ dependencies = [
"syn 2.0.106",
]
[[package]]
name = "num-integer"
version = "0.1.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
dependencies = [
"num-traits",
]
[[package]]
name = "num-traits"
version = "0.2.19"
@@ -4187,15 +4016,6 @@ dependencies = [
"libredox",
]
[[package]]
name = "ordered-float"
version = "2.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68f19d67e5a2795c94e73e0bb1cc1a7edeb2e28efd39e2e1c9b7a40c1108b11c"
dependencies = [
"num-traits",
]
[[package]]
name = "ordered-float"
version = "4.6.0"
@@ -4285,7 +4105,7 @@ name = "path-bool-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam 0.33.10",
"glam",
"graphic-types",
"linesweeper",
"log",
@@ -4331,17 +4151,6 @@ dependencies = [
"indexmap",
]
[[package]]
name = "petgraph"
version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54acf3a685220b533e437e264e4d932cfbdc4cc7ec0cd232ed73c08d03b8a7ca"
dependencies = [
"fixedbitset",
"hashbrown 0.15.5",
"indexmap",
]
[[package]]
name = "phf"
version = "0.13.1"
@@ -4602,7 +4411,7 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam 0.33.10",
"glam",
"graph-craft",
"graphene-std",
"interpreted-executor",
@@ -4814,6 +4623,18 @@ version = "0.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c3d6831663a5098ea164f89cff59c6284e95f4e3c76ce9848d4529f5ccca9bde"
[[package]]
name = "raster-kernels"
version = "0.0.0"
dependencies = [
"core-types",
"glam",
"graphene-resource",
"graphic-types",
"thiserror 2.0.18",
"vector-types",
]
[[package]]
name = "raster-nodes"
version = "0.0.0"
@@ -4822,25 +4643,17 @@ dependencies = [
"color",
"core-types",
"dyn-any",
"fastnoise-lite",
"futures",
"glam 0.33.10",
"glam",
"graphene-core",
"graphene-hash",
"graphene-resource",
"image",
"kurbo",
"ndarray",
"no-std-types",
"graphic-types",
"node-macro",
"num-traits",
"num_enum",
"rand",
"rand_chacha",
"raster-nodes-shaders",
"raster-kernels",
"raster-types",
"serde",
"spirv-std",
"thiserror 2.0.18",
"tokio",
"tsify",
@@ -4849,22 +4662,6 @@ dependencies = [
"wgpu-executor",
]
[[package]]
name = "raster-nodes-shaders"
version = "0.0.0"
dependencies = [
"cargo-gpu-install",
"env_logger",
"log",
]
[[package]]
name = "raster-nodes-shaders-entrypoint"
version = "0.0.0"
dependencies = [
"raster-nodes",
]
[[package]]
name = "raster-types"
version = "0.0.0"
@@ -4873,7 +4670,7 @@ dependencies = [
"bytemuck",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"image",
"node-macro",
@@ -4885,12 +4682,6 @@ dependencies = [
"wgpu",
]
[[package]]
name = "raw-string"
version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e0501e134c6905fee1f10fed25b0a7e1261bf676cffac9543a7d0730dec01af2"
[[package]]
name = "raw-window-handle"
version = "0.6.2"
@@ -4909,12 +4700,6 @@ dependencies = [
"objc2-quartz-core",
]
[[package]]
name = "rawpointer"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3"
[[package]]
name = "rayon"
version = "1.11.0"
@@ -5051,7 +4836,7 @@ dependencies = [
"brush-types",
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-hash",
"graphene-resource",
"graphic-types",
@@ -5059,6 +4844,7 @@ dependencies = [
"log",
"num-traits",
"parley",
"raster-kernels",
"serde",
"skrifa",
"text-nodes",
@@ -5073,7 +4859,7 @@ version = "0.0.0"
dependencies = [
"core-types",
"dyn-any",
"glam 0.33.10",
"glam",
"graphene-core",
"graphic-types",
"kurbo",
@@ -5203,16 +4989,6 @@ dependencies = [
"memchr",
]
[[package]]
name = "rspirv"
version = "0.13.0+sdk-1.4.341.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "091dca2e1d6fd3098417b5ec88e77e80d1ba5945750943419dc976858082c296"
dependencies = [
"rustc-hash 1.1.0",
"spirv",
]
[[package]]
name = "rustc-demangle"
version = "0.1.26"
@@ -5231,20 +5007,6 @@ version = "2.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d"
[[package]]
name = "rustc_codegen_spirv-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d703f5624720c5b6012f4b88d6e6766f43ed50d80144eaffd6791c3270754cdc"
dependencies = [
"rspirv",
"semver",
"serde",
"serde_json",
"spirv",
"thiserror 2.0.18",
]
[[package]]
name = "rustc_version"
version = "0.4.1"
@@ -5502,27 +5264,6 @@ dependencies = [
"serde_derive",
]
[[package]]
name = "serde-untagged"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34836a629bcbc6f1afdf0907a744870039b1e14c0561cb26094fa683b158eff3"
dependencies = [
"erased-serde",
"serde",
"typeid",
]
[[package]]
name = "serde-value"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3a1a3341211875ef120e117ea7fd5228530ae7e7036a779fdc9117be6b3282c"
dependencies = [
"ordered-float 2.10.1",
"serde",
]
[[package]]
name = "serde-wasm-bindgen"
version = "0.6.5"
@@ -5790,7 +5531,7 @@ name = "snapping"
version = "0.0.0"
dependencies = [
"criterion",
"glam 0.33.10",
"glam",
"kurbo",
]
@@ -5831,62 +5572,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f"
dependencies = [
"bitflags 2.13.2",
"serde",
]
[[package]]
name = "spirv-builder"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "57fa119866f0311546e5309b18770b72141c25d185452c11a812be2c7b9d84e9"
dependencies = [
"cargo_metadata 0.21.0",
"log",
"memchr",
"raw-string",
"rustc_codegen_spirv-types",
"semver",
"serde",
"serde_json",
"thiserror 2.0.18",
]
[[package]]
name = "spirv-std"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1d98471765e294d4dd6289350e3633b5c5ba57bb382c3287d83e69ee737179e0"
dependencies = [
"bitflags 2.13.2",
"bytemuck",
"glam 0.30.10",
"glam 0.31.1",
"glam 0.32.1",
"glam 0.33.10",
"libm",
"num-traits",
"spirv-std-macros",
"spirv-std-types",
]
[[package]]
name = "spirv-std-macros"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13a6a0d063d4dd003e43818135b7aa4a30c41c48b5d0efe2cac02220448d4f19"
dependencies = [
"proc-macro2",
"quote",
"spirv-std-types",
"syn 3.0.6",
]
[[package]]
name = "spirv-std-types"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "655632248eaaa205cea4656bc73c8285cbd8109fc784010b24ea6bd0bab79ac1"
[[package]]
name = "stable_deref_trait"
version = "1.2.0"
@@ -5950,27 +5637,6 @@ version = "0.11.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "strum"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
dependencies = [
"strum_macros",
]
[[package]]
name = "strum_macros"
version = "0.27.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn 2.0.106",
]
[[package]]
name = "subtle"
version = "2.6.1"
@@ -6105,15 +5771,6 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "termcolor"
version = "1.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
dependencies = [
"winapi-util",
]
[[package]]
name = "text-nodes"
version = "0.0.0"
@@ -6122,7 +5779,7 @@ dependencies = [
"core-types",
"dyn-any",
"fancy-regex",
"glam 0.33.10",
"glam",
"graphene-hash",
"graphene-resource",
"ipsum",
@@ -6527,7 +6184,7 @@ name = "transform-nodes"
version = "0.0.0"
dependencies = [
"core-types",
"glam 0.33.10",
"glam",
"graphic-types",
"node-macro",
"rand",
@@ -6782,7 +6439,7 @@ dependencies = [
"delaunator",
"dyn-any",
"futures",
"glam 0.33.10",
"glam",
"graphene-core",
"graphene-hash",
"graphic-types",
@@ -6811,14 +6468,14 @@ dependencies = [
"core-types",
"dyn-any",
"fixedbitset",
"glam 0.33.10",
"glam",
"graphene-hash",
"kurbo",
"log",
"lyon_geom",
"node-macro",
"num-traits",
"petgraph 0.7.1",
"petgraph",
"polycool",
"robust",
"rustc-hash 2.1.1",
@@ -6833,7 +6490,7 @@ dependencies = [
[[package]]
name = "vello_common"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"fearless_simd",
@@ -6848,7 +6505,7 @@ dependencies = [
[[package]]
name = "vello_gpu"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"bytemuck",
"hashbrown 0.17.1",
@@ -6862,7 +6519,7 @@ dependencies = [
[[package]]
name = "vello_gpu_shaders"
version = "0.3.0"
source = "git+https://github.com/Keavon/vello.git?rev=f20a8dde35de04c44d05e88b33864f27ad7d6f70#f20a8dde35de04c44d05e88b33864f27ad7d6f70"
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
dependencies = [
"naga",
"wesl",
@@ -7109,7 +6766,7 @@ dependencies = [
"clap",
"control-protocol",
"getrandom 0.3.3",
"glam 0.33.10",
"glam",
"image",
"interprocess",
"serde",
@@ -7217,7 +6874,6 @@ dependencies = [
"hashbrown 0.17.1",
"js-sys",
"log",
"naga",
"parking_lot",
"portable-atomic",
"profiling",
@@ -7312,10 +6968,14 @@ dependencies = [
"core-types",
"dyn-any",
"futures",
"glam 0.33.10",
"glam",
"graphene-application-io",
"graphene-resource",
"graphic-types",
"half",
"log",
"node-macro",
"raster-kernels",
"raster-types",
"rendering",
"thiserror 2.0.18",
@@ -7359,7 +7019,7 @@ dependencies = [
"objc2-metal",
"objc2-quartz-core",
"once_cell",
"ordered-float 4.6.0",
"ordered-float",
"parking_lot",
"portable-atomic",
"portable-atomic-util",
+7 -18
View File
@@ -22,8 +22,6 @@ 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",
@@ -83,10 +81,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" }
@@ -155,7 +153,6 @@ 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>)
@@ -197,7 +194,7 @@ color = "0.3"
rand = { version = "0.9", default-features = false, features = ["std_rng"] }
rand_chacha = "0.9"
glam = { version = "0.33", default-features = false, features = [
"nostd-libm",
"std",
"scalar-math",
"bytemuck",
"debug-glam-assert",
@@ -223,7 +220,7 @@ pretty_assertions = "1.4"
fern = { version = "0.7", features = ["colored"] }
num_enum = { version = "0.7", default-features = false }
num-derive = "0.4"
num-traits = { version = "0.2", default-features = false, features = ["libm"] }
num-traits = "0.2"
tsify = { version = "0.5", default-features = false, features = ["js"] }
syn = { version = "2.0", default-features = false, features = [
"full",
@@ -245,7 +242,6 @@ 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"
@@ -256,11 +252,6 @@ 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"
@@ -268,14 +259,12 @@ linesweeper = "0.4"
smallvec = "1.13.2"
zip = { version = "8", default-features = false }
[workspace.lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(target_arch, values("spirv"))'] }
[workspace.lints]
[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 }
@@ -292,6 +281,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 = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "f20a8dde35de04c44d05e88b33864f27ad7d6f70" }
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" }
+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,"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
{"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
+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}}],"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
{"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
+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,"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
{"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
+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,"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
{"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
+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,"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
{"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
+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":[]}},"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
{"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
+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,"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
{"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
+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", "Rust-GPU"]
github = ["linebender"]
# 1 or more gitlab.com organizations to allow git sources for
#gitlab = [""]
# 1 or more bitbucket.org organizations to allow git sources for
+4 -1
View File
@@ -111,7 +111,10 @@ impl App {
loop {
let texture = async_runtime.block_on(node_runtime.run());
rendering_app_event_scheduler.schedule(AppEvent::ViewportTexture(texture));
let _ = start_render_receiver.recv_timeout(Duration::from_millis(10));
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();
}
if exiting_clone.load(Ordering::Relaxed) {
break;
}
+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>,
overlays_scene: Option<VelloSceneBuilder<'static>>,
#[derivative(Debug = "ignore")]
overlays_canvas: VelloCanvas,
surface_outdated: bool,
@@ -220,7 +220,7 @@ impl RenderState {
self.viewport_offset = offset;
}
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
self.surface_outdated = true;
self.overlays_scene = Some(scene);
}
+1 -2
View File
@@ -15,13 +15,12 @@ publish.workspace = true
workspace = true
[features]
gpu = ["graphite-editor/gpu", "graphene-std/shader-nodes"]
gpu = ["graphite-editor/gpu"]
[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 }
+2 -1
View File
@@ -8,6 +8,7 @@ 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};
@@ -63,7 +64,7 @@ impl DesktopWrapper {
.with_resource_storage(resource_storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new().with_wake(runtime_wake).with_application_io(application_io))
.with_runtime(RuntimeBuilder::new(Arc::new(Instant::now())).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>),
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
PersistenceUpdatePreferences {
preferences: Preferences,
},
+9 -1
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, io};
use crate::{Gdd, MANIFEST_CODEC, METADATA_CODEC, io};
/// Export wrapping. Payloads keep the working copy's recorded per-payload codecs (see
/// [`crate::manifest::PayloadCodecs`]); export does not re-encode.
@@ -158,6 +158,14 @@ 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,6 +35,15 @@ 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,6 +12,7 @@ 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
@@ -39,6 +40,9 @@ impl Layout for GddV1Layout {
fn hot_log_basename(&self) -> &str {
"hot-log"
}
fn metadata_basename(&self) -> &str {
"metadata"
}
fn resources_dir(&self) -> &str {
"resources"
}
+11 -1
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, HotOp, PeerId, Registry, Session, UserId};
use document_graph_storage::{Delta, HistoryMetadata, HotOp, PeerId, Registry, Session, UserId};
#[cfg(feature = "conversion")]
use graphene_resource::LoadResource;
use graphene_resource::ResourceHash;
@@ -52,6 +52,8 @@ 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;
@@ -75,6 +77,8 @@ 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>,
@@ -136,6 +140,10 @@ 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;
@@ -173,6 +181,7 @@ impl<L: Layout> Gdd<L> {
layout,
manifest,
view_settings: session_state.view_settings,
metadata,
network_view_settings: session_state.network_view_settings,
})
}
@@ -199,6 +208,7 @@ impl<L: Layout> Gdd<L> {
layout,
manifest,
view_settings: std::collections::BTreeMap::new(),
metadata: HistoryMetadata::default(),
network_view_settings: std::collections::BTreeMap::new(),
})
}
+21 -2
View File
@@ -6,7 +6,7 @@
use document_container::AsyncContainer;
#[cfg(feature = "conversion")]
use document_graph_storage::NodeMetadataSource;
use document_graph_storage::{HotOp, Rev, TimeStamp, Value};
use document_graph_storage::{HistoryMetadata, HotOp, Rev, Subject, TimeStamp, Value, WallStamp};
#[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, io};
use crate::{Gdd, MANIFEST_CODEC, METADATA_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,6 +182,25 @@ 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
@@ -0,0 +1,62 @@
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"));
});
}
@@ -625,8 +625,6 @@ 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),
})
}
@@ -0,0 +1,164 @@
//! 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"]);
}
}
+2
View File
@@ -5,6 +5,7 @@ pub mod crdt;
pub mod delta;
pub mod document;
pub mod history;
mod history_metadata;
pub mod ids;
pub mod model;
mod prior;
@@ -25,6 +26,7 @@ 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};
+28 -11
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::{Spawn, Spawner};
use crate::task::{Clock, Scheduling, Spawn, Spawner};
use document_container::store::DocumentStore;
use graph_craft::application_io::PlatformApplicationIo;
use graph_craft::application_io::resource::ResourceStorage;
@@ -96,6 +96,8 @@ 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);
@@ -107,7 +109,8 @@ 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);
node_runtime.replace_task_executor(spawner, runtime_wake, clock);
node_runtime.set_scheduling(scheduling);
(Editor { dispatcher }, node_runtime)
}
@@ -184,17 +187,18 @@ 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() -> Self {
Self { wake: (), application_io: () }
}
}
impl Default for RuntimeBuilder {
fn default() -> Self {
Self::new()
pub fn new(clock: Arc<dyn Clock>) -> Self {
Self {
wake: (),
application_io: (),
clock,
scheduling: Scheduling::default(),
}
}
}
@@ -204,12 +208,25 @@ 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 }
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 }
}
}
@@ -18,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};
use graphene_std::raster_types::{CPU, GPU, Raster, Storage};
use graphene_std::text::TextAlign;
use graphene_std::text_nodes::{StringCapitalization, TextDenomination};
use graphene_std::transfer_curve::TransferCurve;
@@ -32,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, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
use kurbo::BezPath;
use std::any::Any;
use std::sync::Arc;
@@ -776,6 +776,45 @@ impl TableItemLayout for Coverage {
}
}
impl TableItemLayout for Effects {
fn type_name() -> &'static str {
"Effects"
}
fn identifier(&self) -> String {
"Effects".to_string()
}
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for Effect {
fn type_name() -> &'static str {
"Effect"
}
fn identifier(&self) -> String {
"Effect".to_string()
}
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.value_page(data)
}
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
self.0.value_widgets(target, data)
}
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
self.0.layout_with_breadcrumb(data)
}
}
impl TableItemLayout for TransferCurve {
fn type_name() -> &'static str {
"TransferCurve"
@@ -944,9 +983,15 @@ impl TableItemLayout for Raster<GPU> {
"Raster"
}
fn identifier(&self) -> String {
format!("Raster ({} x {})", self.data().width(), self.data().height())
let size = self.size();
format!("Raster ({} x {})", size.x, size.y)
}
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)]
}
@@ -1197,6 +1242,10 @@ macro_rules! impl_table_item_layout_for_choice_enum {
impl_table_item_layout_for_choice_enum!(
BlendMode,
Cover,
BevelDirection,
BevelStyle,
EffectKind,
GlowSource,
GradientForm,
GradientSpread,
GradientSpace,
@@ -1367,6 +1416,12 @@ macro_rules! known_item_types {
Appearance,
Coverage,
Cover,
Effects,
Effect,
EffectKind,
GlowSource,
BevelStyle,
BevelDirection,
DashPattern,
BoxCorners,
TransferCurve,
@@ -315,6 +315,9 @@ pub enum DocumentMessage {
UpdateAppearanceAttributes {
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
},
UpdateEffectsReach {
effects_reach: HashMap<NodeId, f64>,
},
Undo,
UngroupSelectedLayers,
UngroupLayer {
@@ -1877,6 +1877,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
.collect();
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
}
DocumentMessage::UpdateEffectsReach { effects_reach } => {
let layer_effects_reach = effects_reach
.into_iter()
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
.collect();
self.network_interface.update_effects_reach(layer_effects_reach);
}
DocumentMessage::Undo => {
if self.network_interface.transaction_status() != TransactionStatus::Finished {
return;
@@ -759,20 +759,26 @@ impl<'a> ModifyInputsContext<'a> {
self.responses.add(NodeGraphMessage::RunDocumentGraph);
}
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
/// from the default (`Linear`).
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let Some(output_layer) = self.get_output_layer() else { return };
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
let create_if_nonexistent = gradient_form != GradientForm::default();
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
return;
};
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
let [start, end] = match gradient_form {
GradientForm::Linear => LINEAR_DIALS,
GradientForm::Radial => RADIAL_DIALS,
};
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
}
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
@@ -834,6 +834,7 @@ 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));
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
build_transform_with_y_preservation,
};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
use graphene_std::{Artboard, Graphic, Vector};
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
use graphene_std::{NodeParameter, ParameterRef};
use math_parser::parser::{MessagePart, ParseError};
use std::path::PathBuf;
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
// ============
// STRUCT TYPES
// ============
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
@@ -1368,8 +1372,8 @@ fn type_choice_sections(offered: &[Type]) -> Vec<Vec<Type>> {
vec![
concrete!(Graphic),
concrete!(Vector),
concrete!(Raster<CPU>),
concrete!(Raster<GPU>),
concrete!(Raster<CPU>),
concrete!(Color),
concrete!(Gradient),
concrete!(String),
@@ -2997,6 +3001,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
}
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::math_nodes::gradient_curvature::*;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
let curvatures = match get_document_node(node_id, context) {
Ok(document_node) => {
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
Some(&TaggedValue::Number(value)) => Some(value),
_ => None,
};
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
}
Err(err) => {
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
return Vec::new();
}
};
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
let mut form = vec![
TextLabel::new("Form")
.tooltip_label("Form")
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
.widget_instance(),
];
add_blank_assist(&mut form);
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
for (label, [start, end], tooltip) in [
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
] {
form.push(
TextButton::new(label)
.tooltip_description(tooltip)
.emphasized(curvatures == Some([start, end]))
.disabled(curvatures.is_none())
.on_update(move |_: &TextButton| Message::Batched {
messages: Box::new([
NodeGraphMessage::SetInputValue {
node_id,
input_index: StartCurvatureInput::INDEX,
value: TaggedValue::Number(start).into(),
}
.into(),
NodeGraphMessage::SetInputValue {
node_id,
input_index: EndCurvatureInput::INDEX,
value: TaggedValue::Number(end).into(),
}
.into(),
]),
})
.on_commit(commit_value)
.widget_instance(),
);
}
// The same sliders the curvatures would get without this panel
let options = ParameterOptions {
soft_min: Some(-1.),
soft_max: Some(1.),
slider: true,
..Default::default()
};
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
let mut layout = vec![LayoutGroup::row(form)];
layout.extend(curvature(StartCurvatureInput::INDEX));
layout.extend(curvature(EndCurvatureInput::INDEX));
layout
}
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
use graphene_std::vector::generator_nodes::rectangle::*;
@@ -270,7 +270,7 @@ impl OverlayContext {
}
}
pub fn take_scene(self) -> VelloSceneBuilder {
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
let empty_scene = overlay_scene(&internal.viewport);
std::mem::replace(&mut internal.scene, empty_scene)
@@ -486,13 +486,13 @@ pub enum DrawHandles {
}
pub(super) struct OverlayContextInternal {
scene: VelloSceneBuilder,
scene: VelloSceneBuilder<'static>,
viewport: ViewportMessageHandler,
visibility_settings: OverlaysVisibilitySettings,
}
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
const MAX_TEXTURE_SIZE: u32 = 2048;
@@ -51,6 +51,8 @@ pub struct DocumentMetadata {
pub layer_vector_data: HashMap<LayerNodeIdentifier, Arc<Item<Vector>>>,
/// Per-layer `ATTR_APPEARANCE` attribute, exposed so message handlers can read paint information that lives on the list.
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
/// Transform from document space to viewport space.
pub document_to_viewport: DAffine2,
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
@@ -347,9 +349,9 @@ impl DocumentMetadata {
}
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
/// stroke geometry when the layer is a vector with a stroke style. Only the first item of a layer's vector data
/// is recorded, so the others count through the click-target-based bounds, without their strokes.
pub fn bounding_box_document_with_stroke(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
let stroke = self
.layer_appearance_attributes
@@ -359,8 +361,10 @@ impl DocumentMetadata {
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
});
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
[stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
Some([min - reach, max + reach])
}
/// Get the bounding box of the click target of the specified layer in viewport space
@@ -732,7 +736,7 @@ mod tests {
let later_item = ClickTarget::new_with_path(line(100., 110.), 0.);
metadata.click_targets.insert(layer, vec![Arc::new(later_item)]);
let [min, max] = metadata.bounding_box_document_with_stroke(layer).unwrap();
let [min, max] = metadata.bounding_box_document_with_stroke_and_effects(layer).unwrap();
assert_eq!((min.x, max.x), (0., 110.));
}
@@ -902,7 +902,7 @@ impl NodeNetworkInterface {
let layer_output = NodeInput::node(layer.to_node(), 0);
match post_node_input {
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | 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);
}
@@ -1031,7 +1031,7 @@ impl NodeNetworkInterface {
if !inserting_into_stack {
match post_node_input {
// Create a new stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | 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 +1057,7 @@ impl NodeNetworkInterface {
} else {
match post_node_input {
// Move to the bottom of the stack
NodeInput::Value { .. } | NodeInput::Scope(_) | NodeInput::Inline(_) | NodeInput::Reflection(_) => {
NodeInput::Value { .. } | NodeInput::Scope(_) | 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);
@@ -659,13 +659,13 @@ impl NodeNetworkInterface {
}
// A wire to or from the imports changed
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. }) => {
(NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }, NodeInput::Import { .. })
| (NodeInput::Import { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. }) => {
self.unload_wire(input_connector, network_path);
}
// A node was disconnected
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Inline { .. } | NodeInput::Import { .. }) => {
(NodeInput::Node { .. }, NodeInput::Value { .. } | NodeInput::Scope { .. } | NodeInput::Import { .. }) => {
self.unload_wire(input_connector, network_path);
if let Some((old_upstream_node_id, previous_position)) = disconnected_upstream
@@ -970,11 +970,11 @@ impl NodeNetworkInterface {
Some(transformed.bounding_box())
}
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
self.document_metadata.document_bounds(include_artboards, true, || {
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
})
}
@@ -991,17 +991,17 @@ impl NodeNetworkInterface {
.reduce(Quad::combine_bounds)
}
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
return None;
};
selected_nodes
.selected_layers(&self.document_metadata)
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
.reduce(Quad::combine_bounds)
}
@@ -1,7 +1,7 @@
use std::collections::{HashMap, HashSet};
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNodeImplementation, InlineRust, NodeInput};
use graph_craft::document::{DocumentNodeImplementation, NodeInput};
use graph_craft::proto::{GraphErrorType, GraphErrors, Promotion};
use graph_craft::{ProtoNodeIdentifier, Type, concrete};
use graphene_std::NodeIOTypes;
@@ -257,7 +257,6 @@ impl NodeNetworkInterface {
}
NodeInput::Scope(_) => TypeSource::Compiled(concrete!(())),
NodeInput::Reflection(document_node_metadata) => TypeSource::Compiled(document_node_metadata.ty()),
NodeInput::Inline(_) => TypeSource::Compiled(concrete!(InlineRust)),
}
}
@@ -738,6 +737,22 @@ 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();
@@ -200,4 +200,9 @@ impl NodeNetworkInterface {
pub fn update_appearance_attributes(&mut self, new_layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>) {
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
}
/// Update how far each layer's effects paint past its content.
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
}
}
@@ -20,7 +20,7 @@ use graphene_std::text::{TextAlign, TypesettingConfig};
use graphene_std::transform::ScaleType;
use graphene_std::uuid::NodeId;
use graphene_std::vector::graphic_types;
use graphene_std::vector::style::{GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use graphene_std::vector::style::{GradientForm, GradientRamp, GradientSpread, PaintOrder, StrokeAlign};
use std::collections::{HashMap, HashSet};
use std::f64::consts::PI;
use std::ops::Range;
@@ -299,10 +299,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
aliases: &["math_nodes::GradientTypeNode"],
},
NodeReplacement {
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
aliases: &["math_nodes::SpreadMethodNode"],
@@ -512,8 +508,8 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
],
},
NodeReplacement {
node: graphene_std::raster_nodes::filter::blur::IDENTIFIER,
aliases: &["graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
node: graphene_std::raster_nodes::effects::blur::IDENTIFIER,
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
},
NodeReplacement {
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
@@ -522,6 +518,7 @@ 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 {
@@ -532,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::ChannelMixerNode",
],
},
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
NodeReplacement {
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
node: graphene_std::raster_nodes::effects::paint_overlay::IDENTIFIER,
aliases: &[
"graphene_raster_nodes::adjustments::ColorOverlayNode",
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
@@ -541,6 +539,7 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
"graphene_core::raster::adjustments::ColorOverlayNode",
"raster_nodes::generate_curves::ColorOverlayNode",
"graphene_raster_nodes::blending_nodes::ColorOverlayNode",
"raster_nodes::blending_nodes::ColorOverlayNode",
],
},
NodeReplacement {
@@ -1196,11 +1195,49 @@ 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
@@ -1233,6 +1270,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
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");
}
}
}
}
@@ -1595,6 +1636,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
}
}
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
.network_interface
.document_network()
.recursive_nodes()
.filter_map(|(node_id, node, path)| {
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
})
.collect();
for (node_id, network_path) in &gradient_form_nodes {
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
continue;
};
let mut node_template = definition.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
continue;
};
reset_default_display_name(document, node_id, network_path, "Gradient Form");
if let Some(input) = old_inputs.first() {
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
}
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
_ => {
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
graphene_std::renderer::dial_gradient::LINEAR_DIALS
}
};
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
}
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
@@ -2356,7 +2440,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
];
for (parameter, fallback) in conversions {
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
@@ -3472,6 +3555,54 @@ 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::std_nodes::noise_pattern::IDENTIFIER,
graphene_std::raster_nodes::std_nodes::mandelbrot::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) {
@@ -3783,11 +3914,14 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
}
}
// 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();
// 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();
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() {
@@ -4004,7 +4138,88 @@ mod tests {
#[test]
fn removed_definition_swap_targets_resolve() {
assert!(resolve_proto_node_type(graphene_std::ops::passthrough::IDENTIFIER).is_some());
assert!(resolve_proto_node_type(graphene_std::platform_application_io::upload_texture::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"
);
}
// Migrating a Merge network's coercion nodes by alias would leave a reducer in the primary slot, so every alias must reset instead
@@ -4504,6 +4719,54 @@ mod tests {
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
}
#[test]
fn gradient_form_nodes_become_gradient_curvature_presets() {
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
let (source_id, form_id) = (NodeId(1), NodeId(2));
for (identifier, form, dials) in [
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
] {
let mut document = DocumentMessageHandler::default();
let placeholder = || NodeInput::value(TaggedValue::None, false);
document.network_interface.insert_node(
source_id,
NodeTemplate {
inputs: vec![placeholder()],
..Default::default()
},
&[],
);
document.network_interface.insert_node(
form_id,
NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
inputs: vec![placeholder(); 2],
..Default::default()
},
&[],
);
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
document
.network_interface
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
migrate(&mut document);
let node = &document.network_interface.document_network().nodes[&form_id];
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
assert_eq!(
[curvature(1), curvature(2)],
dials.map(|dial| Some(TaggedValue::Number(dial))),
"{form:?} should become its curvature presets"
);
}
}
#[test]
fn test_no_duplicate_node_replacements() {
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
@@ -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_form::IDENTIFIER,
graphene_std::math_nodes::gradient_curvature::IDENTIFIER,
graphene_std::math_nodes::gradient_spread::IDENTIFIER,
graphene_std::math_nodes::gradient_positions::IDENTIFIER,
graphene_std::math_nodes::gradient_midpoints::IDENTIFIER,
@@ -413,7 +413,7 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
let walk_from = network_interface.upstream_output_connector(&target_input, &[]).and_then(|out| out.node_id()).unwrap_or(layer.to_node());
let transform_reference = DefinitionIdentifier::ProtoNode(graphene_std::transform_nodes::transform::IDENTIFIER);
let gradient_form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let gradient_curvature_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let mut transforms_downstream_to_upstream: Vec<DAffine2> = Vec::new();
let mut gradient_form: Option<GradientForm> = None;
@@ -430,11 +430,14 @@ fn read_gradient_chain_state(layer: LayerNodeIdentifier, network_interface: &Nod
if reference == transform_reference {
transforms_downstream_to_upstream.push(read_transform_node_value(&document_node.inputs));
} else if reference == gradient_form_reference
&& gradient_form.is_none()
&& let Some(TaggedValue::GradientForm(value)) = document_node.inputs.get(1).and_then(|input| input.as_value())
{
gradient_form = Some(*value);
} else if reference == gradient_curvature_reference && gradient_form.is_none() {
// Curvatures other than the radial form's are drawn with the linear form's controls
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_value()) {
Some(&TaggedValue::Number(value)) => value,
_ => 0.,
};
let is_radial = [curvature(1), curvature(2)] == graphene_std::renderer::dial_gradient::RADIAL_DIALS;
gradient_form = Some(if is_radial { GradientForm::Radial } else { GradientForm::Linear });
}
}
@@ -3366,7 +3369,7 @@ mod test_gradient {
.await;
let feeder_position = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position");
// Set the gradient form through the tool, which splices a 'Gradient Form' node onto the Fill's fill input wire.
// Set the gradient form through the tool, which splices a 'Gradient Curvature' node onto the Fill's fill input wire.
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![layer.to_node()] }).await;
editor.select_tool(ToolType::Gradient).await;
editor
@@ -3375,7 +3378,7 @@ mod test_gradient {
})
.await;
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_form::IDENTIFIER);
let form_reference = DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER);
let form_node_id = {
let network_interface = &editor.active_document().network_interface;
network_interface
@@ -3384,10 +3387,10 @@ mod test_gradient {
.keys()
.copied()
.find(|node_id| network_interface.reference(node_id, &[]).as_ref() == Some(&form_reference))
.expect("Gradient Form node should have been inserted")
.expect("Gradient Curvature node should have been inserted")
};
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Form position");
let form_position = editor.active_document_mut().network_interface.position(&form_node_id, &[]).expect("Gradient Curvature position");
let feeder_position_after = editor.active_document_mut().network_interface.position(&gradient_value_id, &[]).expect("Gradient Value position after");
assert_eq!(form_position, feeder_position, "the inserted node should occupy the feeder's former slot, not the graph origin");
+85 -4
View File
@@ -383,11 +383,11 @@ impl NodeGraphExecutor {
};
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
let bounds = match export_config.bounds {
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
}
.ok_or_else(|| "No bounding box".to_string())?;
@@ -959,6 +959,7 @@ impl NodeGraphExecutor {
clip_targets,
vector_data,
appearance_attributes,
effects_reach,
backgrounds: _,
} = render_output.metadata;
@@ -975,6 +976,7 @@ impl NodeGraphExecutor {
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
responses.add(DocumentMessage::UpdateVectorData { vector_data });
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
responses.add(DocumentMessage::RenderScrollbars);
responses.add(DocumentMessage::RenderRulers);
responses.add(OverlaysMessage::Draw);
@@ -1236,3 +1238,82 @@ 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");
}
}
+115 -19
View File
@@ -1,7 +1,7 @@
use super::*;
use crate::messages::frontend::utility_types::{ExportBounds, FileType};
use crate::messages::portfolio::document::utility_types::network_interface::RootNode;
use crate::task::{Spawn, Spawner, Task};
use crate::task::{Scheduling, Spawn, Spawner, Task};
use glam::{DVec2, UVec2};
use graph_craft::application_io::resource::ResourceRegistry;
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
@@ -18,15 +18,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;
use graphene_std::runtime::{AsyncRuntime, Clock};
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,12 +42,15 @@ pub struct NodeRuntime {
receiver: Receiver<GraphRuntimeRequest>,
sender: Sender<NodeGraphUpdate>,
editor_wake: Wake,
dirty: Arc<AtomicBool>,
/// A re-evaluation waiting for the next frame, or for the end of an export.
rerun: bool,
pending: Option<ExecutionRequest>,
pending_export: Option<ExecutionRequest>,
/// The network the executor last compiled successfully, with previews applied.
old_graph: Option<NodeNetwork>,
async_runtime: Option<AsyncRuntime>,
scheduling: Scheduling,
frame_start: Duration,
editor_api: Arc<PlatformEditorApi>,
resources: ResourceRegistry,
@@ -125,12 +128,14 @@ impl NodeRuntime {
receiver,
sender,
editor_wake,
dirty: Default::default(),
rerun: false,
pending: None,
pending_export: None,
old_graph: None,
resources: ResourceRegistry::default(),
async_runtime: None,
scheduling: Scheduling::default(),
frame_start: Duration::ZERO,
editor_api: PlatformEditorApi {
#[cfg(not(test))]
@@ -216,8 +221,13 @@ impl NodeRuntime {
}
}
if self.dirty.swap(false, Ordering::Acquire) && execution.is_none() {
execution = self.pending_export.or(self.pending).map(GraphRuntimeRequest::ExecutionRequest);
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;
}
}
// Eydropper should use the same time and pointer to not invalidate the cache
@@ -312,7 +322,7 @@ impl NodeRuntime {
self.pending_export = Some(request);
return None;
}
(true, _) => self.dirty.store(true, Ordering::Release),
(true, _) => self.rerun = true,
_ => {}
}
@@ -567,33 +577,54 @@ impl NodeRuntime {
.into();
}
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(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();
}
fn async_runtime(&self) -> &AsyncRuntime {
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 {
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();
}));
}
@@ -702,7 +733,10 @@ impl InspectState {
#[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() {
@@ -727,4 +761,66 @@ mod tests {
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 -1
View File
@@ -1,4 +1,4 @@
pub use graphene_std::runtime::{Spawn, Task};
pub use graphene_std::runtime::{Clock, Scheduling, Spawn, Task};
use std::sync::Arc;
pub type Spawner = Arc<dyn Spawn + Send + Sync>;
+68 -4
View File
@@ -10,16 +10,18 @@ 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::{Spawn, Task};
use crate::task::{Scheduling, 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 {
@@ -30,6 +32,10 @@ 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));
@@ -42,7 +48,7 @@ impl EditorTestUtils {
.with_resource_storage(Arc::new(HashMapResourceStorage::new()))
.with_document_store(Arc::new(MemoryStore::default())),
)
.with_runtime(RuntimeBuilder::new().with_wake(|| {}).with_application_io(PlatformApplicationIo::default()))
.with_runtime(RuntimeBuilder::new(clock).with_wake(|| {}).with_application_io(gpu_application_io()).with_scheduling(scheduling))
.with_spawner(BlockingSpawner)
.with_random_seed(0)
.build();
@@ -57,6 +63,11 @@ 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) {
@@ -102,6 +113,33 @@ 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> {
const MAX_ITERATIONS: usize = 16;
@@ -482,6 +520,16 @@ 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();
@@ -493,6 +541,22 @@ 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) {
@@ -540,9 +540,10 @@
margin-left: 8px;
}
// A label alone in its row lines up with the parameter names that follow their expose buttons
> .text-label:only-child {
// A label with no expose button before it lines up with the parameter names that follow one
> .text-label:first-child {
margin-left: calc(20px + 8px + 8px);
--wire-indent: 20px;
}
> .separator.horizontal.unrelated {
+2 -3
View File
@@ -11,11 +11,10 @@ publish.workspace = true
readme = "./README.md"
[features]
default = ["gpu", "shader-nodes", "web"]
default = ["gpu", "web"]
web = ["editor", "editor?/wasm"]
editor = ["dep:editor", "dep:graphene-std", "dep:graph-craft", "dep:spin", "dep:wgpu"]
gpu = ["editor?/gpu"]
shader-nodes = ["graphene-std?/shader-nodes", "gpu"]
native = []
[lib]
@@ -37,7 +36,7 @@ serde-wasm-bindgen = { workspace = true }
js-sys = { workspace = true }
wasm-bindgen-futures = { workspace = true }
wgpu = { workspace = true, optional = true }
web-sys = { workspace = true }
web-sys = { workspace = true, features = ["Performance"] }
serde_json = { workspace = true }
spin = { workspace = true, optional = true }
tsify = { workspace = true }
+13 -2
View File
@@ -81,7 +81,11 @@ impl EditorWrapper {
.with_resource_storage(storage)
.with_document_store(document_store),
)
.with_runtime(RuntimeBuilder::new().with_wake(crate::helpers::wake_runtime).with_application_io(application_io))
.with_runtime(
RuntimeBuilder::new(std::sync::Arc::new(crate::helpers::PerformanceClock))
.with_wake(crate::helpers::wake_runtime)
.with_application_io(application_io),
)
.with_spawner(crate::helpers::WasmSpawner)
.with_random_seed(uuid_random_seed)
.build();
@@ -193,7 +197,14 @@ impl EditorWrapper {
*g.borrow_mut() = Some(Closure::new(move |_timestamp| {
#[cfg(not(feature = "native"))]
wasm_bindgen_futures::spawn_local(run_node_runtime());
{
if let Some(mut runtime) = crate::NODE_RUNTIME.try_lock()
&& let Some(runtime) = runtime.as_mut()
{
runtime.begin_frame();
}
wasm_bindgen_futures::spawn_local(run_node_runtime());
}
#[cfg(any(not(feature = "native"), target_family = "wasm"))]
wrapper(|wrapper| {
+11 -1
View File
@@ -7,7 +7,7 @@ use editor::messages::input_mapper::utility_types::keyboard::Key;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::messages::prelude::*;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
use editor::task::{Spawn, Task};
use editor::task::{Clock, Spawn, Task};
use js_sys::{Object, Reflect};
use std::cell::RefCell;
use std::collections::HashSet;
@@ -70,6 +70,16 @@ impl Spawn for WasmSpawner {
}
}
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) struct PerformanceClock;
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
impl Clock for PerformanceClock {
fn now(&self) -> Duration {
let performance = window().and_then(|window| window.performance()).expect("the editor runs in a window with `performance`");
Duration::from_secs_f64(performance.now() / 1000.)
}
}
/// Web editor wake: queues a microtask that dispatches [`Message::Wake`].
#[cfg(all(not(feature = "native"), target_family = "wasm"))]
pub(crate) fn wake_editor() {
+3 -28
View File
@@ -145,11 +145,7 @@ impl DocumentNode {
let mut construction_args = ConstructionArgs::Nodes(vec![]);
// If we have one input of the type inline, set it as the construction args
if let &[NodeInput::Inline(ref inline)] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Inline(inline.clone());
}
// If we have one input of the type inline, set it as the construction args
// If we have one input of the type value, set it as the construction args
if let &[NodeInput::Value { ref tagged_value, .. }] = self.inputs.as_slice() {
construction_args = ConstructionArgs::Value(tagged_value.clone());
}
@@ -195,22 +191,6 @@ pub enum NodeInput {
/// Input that is replaced at graph compilation with introspective metadata about this node's location.
Reflection(DocumentNodeMetadata),
/// A Rust source code string. Allows us to insert literal Rust code. Only used for GPU compilation.
/// We can use this whenever we spin up Rustc. Sort of like inline assembly, but because our language is Rust, it acts as inline Rust.
Inline(InlineRust),
}
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
pub struct InlineRust {
pub expr: String,
pub ty: Type,
}
impl InlineRust {
pub fn new(expr: String, ty: Type) -> Self {
Self { expr, ty }
}
}
#[derive(Debug, Clone, PartialEq, Hash, core_types::CacheHash, DynAny, serde::Serialize, serde::Deserialize)]
@@ -263,7 +243,6 @@ impl NodeInput {
NodeInput::Node { .. } => true,
NodeInput::Value { exposed, .. } => *exposed,
NodeInput::Import { .. } => true,
NodeInput::Inline(_) => false,
NodeInput::Scope(_) => false,
NodeInput::Reflection(_) => false,
}
@@ -275,7 +254,6 @@ impl NodeInput {
NodeInput::Value { tagged_value, .. } => tagged_value.ty(),
// Stored import types are normalized to their structural form once at document migration
NodeInput::Import { import_type, .. } => import_type.clone(),
NodeInput::Inline(_) => panic!("ty() called on NodeInput::Inline"),
NodeInput::Scope(_) => panic!("ty() called on NodeInput::Scope"),
NodeInput::Reflection(_) => concrete!(Metadata),
}
@@ -335,13 +313,11 @@ pub enum DocumentNodeImplementation {
///
/// This is explained in more detail here: <https://www.youtube.com/watch?v=72KJa3jQClo>
///
/// Currently we use it for GPU execution, where a node has to get "extracted" to its source code representation and stored as a value that can be given to the GpuCompiler node at runtime
/// (to become a compute shader). Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
/// Future use could involve the addition of an InjectNode to convert the source code form back into an executable node, enabling metaprogramming in the node graph.
/// We would use an assortment of nodes that operate on Graphene source code (just data, no different from any other data flowing through the graph) to make graph transformations.
///
/// We use this for dealing with macros in a syntactic way of modifying the node graph from within the graph itself. Just like we often deal with lambdas to represent a whole group of
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, because we need to pass the GPU SPIR-V compiler the source code for a lambda,
/// not the executable logic of a lambda.
/// operations/code/logic, this allows us to basically deal with a lambda at a meta/source-code level, rather than its executable logic.
///
/// This is analogous to how Rust macros operate at the level of source code, not executable code. When we speak of source code, that represents Graphene's source code in the form of a
/// DocumentNode network, not the text form of Rust's source code. (Analogous to the token stream/AST of a Rust macro.)
@@ -1202,7 +1178,6 @@ impl NodeNetwork {
*import_index = parent_input_index;
}
NodeInput::Value { .. } => unreachable!("Value inputs should have been replaced with value nodes"),
NodeInput::Inline(_) => (),
NodeInput::Scope(_) => unreachable!("Scope inputs should have been resolved by resolve_scope_inputs_recursive before flattening"),
NodeInput::Reflection(_) => unreachable!("Reflection inputs should have been replaced with value nodes"),
}
+26 -1
View File
@@ -13,7 +13,7 @@ pub use glam::{DAffine2, DVec2, IVec2, UVec2};
use graphene_animation::AnimationCurve;
use graphene_application_io::resource::ResourceHash;
use graphene_application_io::resource::ResourceId;
use graphic_types::raster_types::{CPU, Image, Raster};
use graphic_types::raster_types::{CPU, GPU, Image, Raster};
use graphic_types::vector_types::vector::misc::BoxCorners;
use graphic_types::vector_types::vector::style::DashPattern;
use graphic_types::vector_types::vector::style::{Gradient, GradientRamp};
@@ -36,6 +36,7 @@ macro_rules! for_each_item_type_default {
$action!(Vector);
$action!(f64);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Graphic);
$action!(Color);
$action!(Gradient);
@@ -52,6 +53,7 @@ macro_rules! for_each_list_type_default {
$action!(Graphic);
$action!(Artboard);
$action!(Raster<CPU>);
$action!(Raster<GPU>);
$action!(Vector);
$action!(String);
$action!(Color);
@@ -577,6 +579,9 @@ tagged_value! {
TonalRange(raster_nodes::adjustments::TonalRange),
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
GlowSource(graphic_types::GlowSource),
BevelStyle(graphic_types::BevelStyle),
BevelDirection(graphic_types::BevelDirection),
GridType(vector::misc::GridType),
GridTopology(vector::misc::GridTopology),
ArcType(vector::misc::ArcType),
@@ -706,6 +711,25 @@ impl TaggedValue {
None
}
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
let mut choices = input.split("::");
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
if first == "StrokeAlign" {
return Some(match second {
"Center" => vector::style::StrokeAlign::Center,
"Inside" => vector::style::StrokeAlign::Inside,
"Outside" => vector::style::StrokeAlign::Outside,
_ => {
log::error!("Invalid StrokeAlign default type variant: {input}");
return None;
}
});
}
log::error!("Invalid StrokeAlign default type: {input}");
None
}
match ty {
Type::Generic(_) => None,
Type::Concrete(concrete_type) => {
@@ -724,6 +748,7 @@ impl TaggedValue {
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
_ => return None,
+2 -11
View File
@@ -1,5 +1,5 @@
use crate::document::value;
use crate::document::value::TaggedValue;
use crate::document::{InlineRust, value};
use crate::document::{NodeId, OriginalLocation};
pub use core_types::registry::*;
use core_types::*;
@@ -51,10 +51,6 @@ impl core::fmt::Display for ProtoNetwork {
write_node(f, network, *id, indent + 1)?;
}
}
ConstructionArgs::Inline(inline) => {
f.write_str(&"\t".repeat(indent + 1))?;
f.write_fmt(format_args!("Inline construction argument: {inline:?}"))?
}
}
f.write_str(&"\t".repeat(indent))?;
f.write_str("}\n")?;
@@ -75,8 +71,6 @@ pub enum ConstructionArgs {
/// The bool indicates whether to treat the node as lambda node.
// TODO: use a struct for clearer naming.
Nodes(Vec<NodeId>),
/// Used for GPU computation to work around the limitations of rust-gpu.
Inline(InlineRust),
}
impl Eq for ConstructionArgs {}
@@ -109,7 +103,6 @@ impl CacheHash for ConstructionArgs {
}
}
Self::Value(value) => value.cache_hash(state),
Self::Inline(inline) => inline.hash(state),
}
}
}
@@ -119,7 +112,6 @@ impl ConstructionArgs {
match self {
ConstructionArgs::Nodes(nodes) => nodes.iter().map(|n| format!("n{:0x}", n.0)).collect(),
ConstructionArgs::Value(value) => vec![value.to_primitive_string()],
ConstructionArgs::Inline(inline) => vec![inline.expr.clone()],
}
}
}
@@ -440,7 +432,7 @@ impl ProtoNetwork {
Some(id),
);
}
ConstructionArgs::Value(_) | ConstructionArgs::Inline(_) => return (dependencies.extract.into(), Some(id)),
ConstructionArgs::Value(_) => return (dependencies.extract.into(), Some(id)),
};
// Compute the dependencies for each branch and combine all of them
@@ -877,7 +869,6 @@ impl TypingContext {
.map(|node| node.ty())
})
.collect::<Result<Vec<Type>, GraphErrors>>()?,
ConstructionArgs::Inline(ref inline) => vec![inline.ty.clone()],
};
// Get the node input type from the proto node declaration
-2
View File
@@ -152,7 +152,6 @@ pub fn print(network: &ProtoNetwork, document: &Document, format: Format, upstre
let arguments = match &node.proto.construction_args {
ConstructionArgs::Nodes(_) => format!("({})", node.inputs.iter().map(|&input| id(input)).collect::<Vec<_>>().join(", ")),
ConstructionArgs::Value(value) => format!("{{{}}}", summary(value, 80)),
ConstructionArgs::Inline(inline) => format!("{{{}}}", inline.expr),
};
let shared = if node.origins.len() > 1 { "(shared)" } else { "" };
let provenance = [node.kind.tag(), &location(node.origins[0]), shared]
@@ -246,7 +245,6 @@ fn constant<'a>(nodes: &[Node<'a>], mut n: usize) -> Option<&'a TaggedValue> {
match &nodes[n].proto.construction_args {
ConstructionArgs::Value(value) => return Some(&**value),
ConstructionArgs::Nodes(_) => n = *nodes[n].inputs.first()?,
ConstructionArgs::Inline(_) => return None,
}
}
}
+1 -1
View File
@@ -190,7 +190,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
application_io: Some(application_io_for_api),
});
let spawner = Arc::new(TokioSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(std::time::Instant::now()));
let proto_graph = compile_graph(node_network, editor_api, gdd.as_ref(), runtime.handle())?;
match app.command {
@@ -3,14 +3,14 @@ use criterion::measurement::Measurement;
use graph_craft::proto::ProtoNetwork;
use graph_craft::util::{DEMO_ART, compile, load_from_name};
use graphene_std::application_io::EditorApi;
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
use graphene_std::runtime::{AsyncRuntime, Clock, Spawn, Task};
use interpreted_executor::dynamic_executor::DynamicExecutor;
use interpreted_executor::util::wrap_network_in_scope;
pub fn setup_network(name: &str) -> (DynamicExecutor, ProtoNetwork) {
let network = load_from_name(name);
let editor_api = std::sync::Arc::new(EditorApi::default());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner), std::sync::Arc::new(NoClock)).handle());
let preprocessor = preprocessor::Preprocessor::new();
preprocessor.preprocess(&mut network, &|_| None).unwrap();
let proto_network = compile(network);
@@ -33,3 +33,10 @@ struct DummySpawner;
impl Spawn for DummySpawner {
fn spawn(&self, _task: Task) {}
}
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> std::time::Duration {
std::time::Duration::ZERO
}
}
@@ -503,7 +503,6 @@ impl BorrowTree {
/// - Updates the source map using [`update_source_map`](BorrowTree::update_source_map) before inserting the node.
/// - Handles different types of construction arguments:
/// - `Value`: Creates a node from a `TaggedValue`, with special handling for `EditorApi` values.
/// - `Inline`: Currently unimplemented. Only used for `rust-gpu` support.
/// - `Nodes`: Constructs a node using other nodes as dependencies.
/// - Uses the constructor function from the `typing_context` for `Nodes` construction arguments.
/// - Returns an error if no constructor is found for the given node ID.
@@ -518,7 +517,6 @@ impl BorrowTree {
let node = ObservedNode::new(Box::new(upcasted) as TypeErasedBox<'_>);
self.store_node(node, id, path.into(), Box::default());
}
ConstructionArgs::Inline(_) => unimplemented!("Inline nodes are not supported yet"),
ConstructionArgs::Nodes(ids) => {
let ids = ids.to_vec();
let mut construction_nodes = self.node_deps(&ids);
@@ -27,6 +27,7 @@ use graphene_std::vector::misc::{
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
use node_registry_macros::async_node;
use std::collections::HashMap;
use std::sync::Arc;
@@ -51,6 +52,8 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<CPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
#[cfg(feature = "gpu")]
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Color>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<Gradient>]),
async_node!(graphene_core::memo::MonitorNode<_, _, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
@@ -90,6 +93,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::RuntimeHandle>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<graphene_std::SourceId>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>, Context => Item<graphene_std::ContextModification>]),
async_node!(graphene_core::context_modification::ContextModificationNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>, Context => Item<graphene_std::ContextModification>]),
// ==========
// MEMO NODES
@@ -142,6 +146,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<graphene_std::brush::Stroke>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<RenderIntermediate>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuExecutor>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Option<wgpu_executor::WgpuExecutor>>]),
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<wgpu_executor::WgpuPipelineCache>]),
];
// The per-connector input adapter, registered per element type: an `Item` or `List` wire passes through unchanged.
@@ -329,6 +334,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
TonalRange,
AdjustmentChannel,
HueSaturationRange,
GlowSource,
BevelStyle,
BevelDirection,
Stroke,
ScaleType,
ReferencePoint,
@@ -375,8 +383,28 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
// The nested-generic `Box<VectorModification>` registers directly rather than through the shared callback, since the
// extra macro layer mangles the `stringify!` whitespace in its adapter identifier; its cache chain is likewise direct below
node_types.extend(rank_adapter_nodes!(Box<VectorModification>));
// A GPU raster's input adapter also takes the pipeline to upload a CPU raster wire with, so its rows don't come from `rank_adapter_nodes`
#[cfg(feature = "gpu")]
node_types.extend(rank_adapter_nodes!(Raster<GPU>));
{
use graphene_std::raster_nodes::effects::{PassRasterNode, UploadItemNode, UploadListNode};
use wgpu_executor::WgpuPipelineCache;
macro_rules! gpu_raster_input_adapter {
($path:ty, $from:ty) => {
async_node!(
identifier: ProtoNodeIdentifier::new("input_adapter<Raster<GPU>>"),
$path,
input: Context,
fn_params: [Context => $from, Context => Item<WgpuPipelineCache>]
)
};
}
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, Item<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(PassRasterNode<_, _>, List<Raster<GPU>>));
node_types.push(gpu_raster_input_adapter!(UploadItemNode<_, _>, Item<Raster<CPU>>));
node_types.push(gpu_raster_input_adapter!(UploadListNode<_, _>, List<Raster<CPU>>));
node_types.push(item_to_list_node!(element: Raster<GPU>));
}
// Type-erased rows for the `ListDyn` connectors (`Read Attribute`, `Count`): any `List` wire erases its element type
macro_rules! list_dyn_rows {
($($element:ty),* $(,)?) => {{
+23 -7
View File
@@ -1,6 +1,6 @@
use graph_craft::application_io::PlatformEditorApi;
use graph_craft::document::value::TaggedValue;
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeInput, NodeNetwork};
use graph_craft::generic;
use graph_craft::{concrete, item};
use graphene_std::Context;
@@ -27,7 +27,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
let render_node = DocumentNode {
inputs: vec![NodeInput::node(NodeId(0), 0)],
implementation: DocumentNodeImplementation::Network(NodeNetwork {
exports: vec![NodeInput::node(NodeId(5), 0)],
exports: vec![NodeInput::node(NodeId(6), 0)],
nodes: [
DocumentNode {
call_argument: concrete!(Context),
@@ -42,7 +42,23 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(0), 0)],
inputs: vec![
NodeInput::scope(graphene_std::platform_application_io::try_wgpu_executor::IDENTIFIER),
NodeInput::node(NodeId(0), 0),
NodeInput::scope("runtime"),
NodeInput::Reflection(DocumentNodeMetadata::SourceId),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::download_gpu_rasters::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::VARARGS,
inject: ContextFeatures::empty(),
..Default::default()
}),
..Default::default()
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::render::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -53,7 +69,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(1), 0)],
inputs: vec![NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_cache::render_output_cache::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -64,7 +80,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(2), 0)],
inputs: vec![NodeInput::scope(graphene_std::render_pixel_preview::pixel_preview_pipeline::IDENTIFIER), NodeInput::node(NodeId(3), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_pixel_preview::render_pixel_preview::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
extract: ContextFeatures::FOOTPRINT | ContextFeatures::VARARGS,
@@ -77,7 +93,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
call_argument: concrete!(Context),
inputs: vec![
NodeInput::scope(graphene_std::render_background::composite_background_pipeline::IDENTIFIER),
NodeInput::node(NodeId(3), 0),
NodeInput::node(NodeId(4), 0),
],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_background::render_background::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
@@ -89,7 +105,7 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
},
DocumentNode {
call_argument: concrete!(Context),
inputs: vec![NodeInput::node(NodeId(4), 0)],
inputs: vec![NodeInput::node(NodeId(5), 0)],
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::render_node::create_context::IDENTIFIER),
compile_metadata: Some(graphene_std::NodeCompileMetadata {
// INDEX is never read; it forces a nullification and cache pair onto the `data` parameter's wire so the render cache keys on a stable context
+5 -5
View File
@@ -16,15 +16,13 @@ workspace = true
[features]
default = ["serde"]
serde = ["dep:serde"]
nightly = []
serde = ["dep:serde", "glam/serde", "half/serde"]
type_id_logging = []
dealloc_nodes = []
wasm = ["tsify", "wasm-bindgen", "no-std-types/wasm"]
wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
no-std-types = { workspace = true, features = ["std"] }
graphene-hash = { workspace = true, features = ["derive"] }
# Workspace dependencies
@@ -33,6 +31,9 @@ bitflags = { workspace = true }
bytemuck = { workspace = true }
node-macro = { workspace = true }
num-traits = { workspace = true }
num-derive = { workspace = true }
num_enum = { workspace = true, features = ["std"] }
half = { workspace = true, features = ["std"] }
rand = { workspace = true }
glam = { workspace = true }
serde_json = { workspace = true }
@@ -51,7 +52,6 @@ log = { workspace = true }
base64 = { workspace = true }
polycool = { workspace = true }
futures = { workspace = true }
thiserror = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
@@ -1,13 +1,11 @@
use crate::color::Color;
use core::fmt::Display;
use node_macro::BufferStruct;
use num_enum::{FromPrimitive, IntoPrimitive};
#[repr(i32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, BufferStruct, FromPrimitive, IntoPrimitive)]
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, Eq, PartialEq, Hash, FromPrimitive, IntoPrimitive)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum BlendMode {
// Basic group
#[default]
@@ -132,7 +130,6 @@ impl BlendMode {
}
/// Renders the blend mode CSS style declaration.
#[cfg(feature = "std")]
pub fn render(&self) -> String {
format!(
r#" mix-blend-mode: {};"#,
@@ -3,8 +3,6 @@ use bytemuck::{Pod, Zeroable};
use core::fmt::Debug;
use glam::DVec2;
use num_derive::*;
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
pub trait Linear {
fn from_f32(x: f32) -> Self;
@@ -88,7 +86,6 @@ pub trait SRGB: Rec709Primaries {}
// TODO: Come up with a better name for this trait
pub trait Pixel: Clone + Pod + Zeroable + Default {
#[cfg(feature = "std")]
fn to_bytes(&self) -> Vec<u8> {
bytemuck::bytes_of(self).to_vec()
}
@@ -5,16 +5,10 @@ use bytemuck::{Pod, Zeroable};
use core::fmt::Debug;
use glam::Vec4;
use half::f16;
use node_macro::BufferStruct;
#[cfg(not(feature = "std"))]
use num_traits::Euclid;
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
#[repr(C)]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(not(target_arch = "spirv"), derive(Debug))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[derive(Default, Clone, Copy, PartialEq, Pod, Zeroable, Debug, dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct RGBA16F {
red: f16,
green: f16,
@@ -22,14 +16,6 @@ pub struct RGBA16F {
alpha: f16,
}
/// hack around half still masking out impl Debug for f16 on spirv
#[cfg(target_arch = "spirv")]
impl core::fmt::Debug for RGBA16F {
fn fmt(&self, _f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
Ok(())
}
}
impl From<Color> for RGBA16F {
#[inline(always)]
fn from(c: Color) -> Self {
@@ -96,9 +82,8 @@ impl Pixel for RGBA16F {}
/// the linear-light [`Color`] type. Convert via [`From<SRGBA8> for Color`] and [`From<Color> for SRGBA8`].
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify), tsify(from_wasm_abi))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)]
#[derive(dyn_any::DynAny, graphene_hash::CacheHash, Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct SRGBA8 {
pub red: u8,
pub green: u8,
@@ -125,7 +110,6 @@ impl SRGBA8 {
/// Parse `RRGGBB` or `RRGGBBAA` (with or without a leading `#`). Returns `None` for any other format.
/// For full CSS Color 4 parsing (named colors, shorthand hex, `rgb(...)`, `hsl(...)`), parse in the caller and construct via [`Self::new`].
#[cfg(feature = "std")]
pub fn from_hex_str(hex: &str) -> Option<Self> {
let hex = hex.trim().trim_start_matches('#');
if hex.len() != 6 && hex.len() != 8 {
@@ -141,19 +125,16 @@ impl SRGBA8 {
}
/// `rrggbb` (lowercase, no `#` prefix, alpha discarded). Use where alpha is specified separately, e.g. SVG `fill="#..." fill-opacity="..."`.
#[cfg(feature = "std")]
pub fn to_rgb_hex(self) -> String {
format!("{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
}
/// `rrggbbaa` (lowercase, no `#` prefix).
#[cfg(feature = "std")]
pub fn to_rgba_hex(self) -> String {
format!("{:02x}{:02x}{:02x}{:02x}", self.red, self.green, self.blue, self.alpha)
}
/// `#rrggbb` if fully opaque, `#rrggbbaa` otherwise. Suitable for direct insertion into a CSS property or SVG attribute.
#[cfg(feature = "std")]
pub fn to_css_hex(self) -> String {
if self.alpha == 255 {
format!("#{}", self.to_rgb_hex())
@@ -223,8 +204,8 @@ impl From<SRGBA8> for Color {
#[repr(C)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny, serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[derive(dyn_any::DynAny, Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Luma(pub f32);
impl Luminance for Luma {
@@ -259,9 +240,7 @@ impl Pixel for Luma {}
///
/// Anything crossing the Wasm/JS boundary must go through [`SRGBA8`] instead.
#[repr(C)]
#[cfg_attr(feature = "std", derive(dyn_any::DynAny))]
#[cfg_attr(feature = "std", derive(graphene_hash::CacheHash))]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, BufferStruct)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Pod, Zeroable, dyn_any::DynAny, graphene_hash::CacheHash)]
pub struct Color {
red: f32,
green: f32,
@@ -273,7 +252,7 @@ pub struct Color {
impl Eq for Color {}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "std")]
#[cfg(feature = "serde")]
impl serde::Serialize for Color {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
@@ -290,7 +269,7 @@ impl serde::Serialize for Color {
}
// TODO: Eventually remove this document upgrade code
#[cfg(feature = "std")]
#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Color {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
// Documents from before the linear-storage migration lack the `linear` marker and stored gamma-encoded floats; convert them on load.
@@ -351,7 +330,6 @@ impl AlphaMut for Color {
}
impl Pixel for Color {
#[cfg(feature = "std")]
fn to_bytes(&self) -> Vec<u8> {
let SRGBA8 { red, green, blue, alpha } = (*self).into();
[red, green, blue, alpha].to_vec()
@@ -444,10 +422,7 @@ impl Color {
lightness + saturation - lightness * saturation
};
let temp2 = 2. * lightness - temp1;
#[cfg(feature = "std")]
let rem = |x: f32| x.rem_euclid(1.);
#[cfg(not(feature = "std"))]
let rem = |x: f32| x.rem_euclid(&1.);
let mut red = rem(hue + 1. / 3.);
let mut green = rem(hue);
@@ -823,10 +798,7 @@ impl Color {
/// Convert this color to HSV coordinates (all between 0 and 1).
/// HSV is defined on sRGB display values, so this color's linear RGB is gamma-encoded before the HSV math.
pub fn to_hsva(&self) -> [f32; 4] {
#[cfg(feature = "std")]
let rem = |x: f32, m: f32| x.rem_euclid(m);
#[cfg(not(feature = "std"))]
let rem = |x: f32, m: f32| x.rem_euclid(&m);
let [red, green, blue, alpha] = self.to_gamma_srgb_channels();
let max = red.max(green).max(blue);
@@ -873,10 +845,7 @@ impl Color {
} else {
4. + (red - green) / (max_channel - min_channel)
} / 6.;
#[cfg(feature = "std")]
let hue = hue.rem_euclid(1.);
#[cfg(not(feature = "std"))]
let hue = hue.rem_euclid(&1.);
[hue, saturation, lightness, alpha]
}
@@ -3,9 +3,6 @@
//! These work in `f32` at full precision. For round-trip-exact `u8` ⇄ `f32` conversion at the
//! display byte boundary, use the lookup tables in [`super::discrete_srgb`] instead.
#[cfg(not(feature = "std"))]
use num_traits::float::Float;
/// Decode an sRGB gamma-encoded channel value to linear-light.
#[inline(always)]
pub fn srgb_to_linear(channel: f32) -> f32 {
+24 -2
View File
@@ -1,7 +1,6 @@
use crate::runtime::{Generations, SourceId};
use crate::transform::Footprint;
use glam::DVec2;
pub use no_std_types::context::{ArcCtx, Ctx};
use glam::{DAffine2, DVec2};
use std::any::Any;
use std::borrow::Borrow;
use std::collections::BTreeSet;
@@ -9,6 +8,15 @@ use std::hash::{Hash, Hasher};
use std::panic::Location;
use std::sync::Arc;
pub trait Ctx: Clone + Send {}
impl<T: Ctx> Ctx for Option<T> {}
impl<T: Ctx + Sync> Ctx for &T {}
impl Ctx for () {}
pub trait ArcCtx: Send + Sync {}
impl<T: ArcCtx> Ctx for Arc<T> {}
// ==============
// EXTRACT TRAITS
// ==============
@@ -764,6 +772,20 @@ impl OwnedContextImpl {
self.footprint = Some(footprint);
self
}
/// Replaces any footprint with [`Footprint::for_instances`] for content placed once per transform in `instance_transforms`.
pub fn with_instances_footprint(mut self, instance_transforms: impl IntoIterator<Item = DAffine2>) -> Self {
if let Some(footprint) = &self.footprint {
self.footprint = Some(footprint.for_instances(instance_transforms));
}
self
}
/// Replaces any footprint with its [`Footprint::probe`].
pub fn with_probe_footprint(mut self) -> Self {
if let Some(footprint) = &self.footprint {
self.footprint = Some(footprint.probe());
}
self
}
pub fn with_real_time(mut self, real_time: f64) -> Self {
self.real_time = Some(real_time);
self
+16 -8
View File
@@ -1,6 +1,9 @@
extern crate log;
pub mod blending;
pub mod bounds;
pub mod choice_type;
pub mod color;
pub mod consts;
pub mod context;
pub mod generic;
@@ -29,16 +32,12 @@ pub use glam_ext::FallibleVec2Operations;
pub use graphene_hash;
pub use graphene_hash::CacheHash;
pub use list::{
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
};
pub use memo::MemoHash;
pub use no_std_types::AsU32;
pub use no_std_types::blending;
pub use no_std_types::choice_type;
pub use no_std_types::color;
pub use no_std_types::shaders;
pub use num_traits;
pub use poll::{Finality, Interrupt, LazyInput, NodeError, Poll, PollInput, Status};
pub use runtime::{Generations, RuntimeHandle, SourceId};
@@ -166,3 +165,12 @@ impl<P: NodeParameter> From<P> for ParameterRef {
}
}
}
pub trait AsU32 {
fn as_u32(&self) -> u32;
}
impl AsU32 for u32 {
fn as_u32(&self) -> u32 {
*self
}
}
+52 -182
View File
@@ -1,4 +1,3 @@
use crate::TypeDescriptor;
use crate::bounds::{BoundingBox, RenderBoundingBox};
use crate::math::quad::Quad;
use crate::transform::ApplyTransform;
@@ -62,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
/// Gradient's `GradientForm` (`Linear` or `Radial`).
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
@@ -81,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
pub const ATTR_MIDPOINT: &str = "midpoint";
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
pub const ATTR_APPEARANCE: &str = "appearance";
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
/// Unlike the appearance, it doesn't cascade to descendants.
pub const ATTR_EFFECTS: &str = "effects";
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
/// `List<Coverage>` inside an `Appearance`.
@@ -204,12 +211,6 @@ fn implicit_default_value(key: &str) -> Option<Box<dyn AnyAttributeValue>> {
}
}
/// What pushing and extending lists pad a missing `key` attribute with: `key`'s implicit default if it has type `T`, otherwise
/// `T::default()`.
pub fn implicit_default<T: Clone + Default + 'static>(key: &str) -> T {
implicit_default_value(key).and_then(|default| default.as_any().downcast_ref::<T>().cloned()).unwrap_or_default()
}
/// Appends `count` copies of `key`'s implicit default to `attribute` (see [`implicit_default_value`]).
fn pad_with_implicit_default(key: &str, attribute: &mut dyn AnyAttribute, count: usize) {
match implicit_default_value(key) {
@@ -405,8 +406,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Converts the shared attribute into one that can be downcast to its concrete type.
fn into_any_arc(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync>;
/// Pushes a scalar attribute value onto the end of this attribute, or a default if it has another type, which returns `false`.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool;
/// Pushes a scalar attribute value onto the end of this attribute.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>);
/// Pushes a default value onto the end of this attribute.
fn push_default(&mut self);
@@ -416,8 +417,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
fn push_repeated(&mut self, value: &dyn AnyAttributeValue, count: usize);
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Hands the value back if it has another type.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>>;
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>);
/// Creates a new attribute of the same type filled with `count` number of default values.
fn new_with_defaults(&self, count: usize) -> Arc<dyn AnyAttribute>;
@@ -430,8 +431,8 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
self.len() == 0
}
/// Appends all values from another attribute of the same type, or defaults for them if it has another type, which returns `false` unless it is empty.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool;
/// Appends all values from another attribute of the same type.
fn extend(&mut self, other: Arc<dyn AnyAttribute>);
/// Returns a shared reference to the value at the requested index.
fn get_any(&self, index: usize) -> Option<&dyn std::any::Any>;
@@ -451,9 +452,6 @@ pub trait AnyAttribute: std::any::Any + Send + Sync {
/// Compares this attribute to another for value-by-value equality (object-safe wrapper around `PartialEq`).
/// Returns `false` if the underlying types differ.
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool;
/// The type of this attribute's values.
fn value_type(&self) -> TypeDescriptor;
}
/// Adapts a `&mut dyn Hasher` so generic `CacheHash::cache_hash<H>` calls (which require `H: Sized + Hasher`) can
@@ -552,11 +550,9 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Pushes an attribute value onto the end of this attribute's list, downcasting it to `T`.
/// Falls back to a default value if the type doesn't match, to maintain the attribute-length invariant.
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) -> bool {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone);
let matches = value.is_ok();
self.0.push(value.unwrap_or_default());
matches
fn push(&mut self, value: Arc<dyn AnyAttributeValue>) {
let value = value.into_any_arc().downcast::<T>().map(Arc::unwrap_or_clone).unwrap_or_default();
self.0.push(value);
}
/// Pushes a default `T` value onto the end of this attribute list.
@@ -571,11 +567,8 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
}
/// Sets the value at the given index, padding with defaults if the attribute is shorter than `index`.
/// Hands the value back if it isn't a `T`.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) -> Result<(), Box<dyn AnyAttributeValue>> {
if !value.as_any().is::<T>() {
return Err(value);
}
/// Falls back to a default if the value's type doesn't match.
fn set_at(&mut self, index: usize, value: Box<dyn AnyAttributeValue>) {
while self.0.len() < index {
self.0.push(T::default());
}
@@ -585,7 +578,6 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
} else {
self.0[index] = value;
}
Ok(())
}
/// Creates a new attribute filled with `count` default `T` values.
@@ -601,18 +593,14 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
/// Appends all values from another attribute, downcasting it to the same `Attribute<T>` type.
/// Falls back to padding with defaults if the type doesn't match, to maintain the attribute-length invariant.
fn extend(&mut self, other: Arc<dyn AnyAttribute>) -> bool {
fn extend(&mut self, other: Arc<dyn AnyAttribute>) {
let other_len = other.len();
match other.into_any_arc().downcast::<Self>().map(Arc::try_unwrap) {
Ok(Ok(other)) => self.0.extend(other.0),
Ok(Err(shared)) => self.0.extend_from_slice(&shared.0),
Err(_) => {
self.0.extend(std::iter::repeat_with(T::default).take(other_len));
return other_len == 0;
}
Err(_) => self.0.extend(std::iter::repeat_with(T::default).take(other_len)),
}
true
}
/// Returns a shared reference to the value at the given index as a type-erased `Any`.
@@ -649,10 +637,6 @@ impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static>
fn eq_dyn(&self, other: &dyn AnyAttribute) -> bool {
other.as_any().downcast_ref::<Self>().is_some_and(|other| self.0 == other.0)
}
fn value_type(&self) -> TypeDescriptor {
crate::descriptor!(T)
}
}
// ==================
@@ -724,11 +708,6 @@ impl ListDyn {
pub fn attribute<U: 'static>(&self, key: &str, index: usize) -> Option<&U> {
self.attributes.get_value(key, index)
}
/// Returns the type of the values the attribute for the given key holds, or `None` if absent.
pub fn attribute_type(&self, key: &str) -> Option<TypeDescriptor> {
self.attributes.value_type(key)
}
}
impl<T> From<List<T>> for ListDyn {
@@ -1110,31 +1089,23 @@ impl Attributes {
/// Pushes an item's scalar attributes into this attribute store.
/// Existing attributes that the item lacks receive a default value.
/// New attribute keys create a new attribute padded with defaults for all prior items.
/// Returns the first attribute that holds another type than the item's value for it, which gets the default instead.
fn push_item(&mut self, item: ItemAttributeValues) -> Option<AttributeTypeConflictError> {
fn push_item(&mut self, item: ItemAttributeValues) {
let len = self.len;
self.len += 1;
if self.attributes.is_empty() && item.0.is_none() {
return None;
return;
}
let mut item_entries = item.into_entries();
let mut conflict = None;
// Push values into existing attributes, or the implicit default if the item lacks that attribute
for (attribute_key, attribute) in self.attributes.as_mut_slice() {
let attribute = unshared(attribute);
match item_entries.iter().position(|(key, _)| key == attribute_key) {
// An attribute without values holds no type to keep
Some(position) if len == 0 => *attribute = item_entries.swap_remove(position).1.into_attribute(attribute_key.as_str(), 0),
Some(position) => {
if !unshared(attribute).push(item_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError {
name: attribute_key.as_str().to_string(),
});
}
}
None => pad_with_implicit_default(attribute_key.as_str(), unshared(attribute), 1),
Some(position) => attribute.push(item_entries.swap_remove(position).1),
None => pad_with_implicit_default(attribute_key.as_str(), attribute, 1),
}
}
@@ -1143,41 +1114,33 @@ impl Attributes {
let attribute = value.into_attribute(key.as_str(), len);
self.attributes.push((key, attribute));
}
conflict
}
/// Appends all attribute data from another attribute store into this one.
/// Attributes present in only one side are padded with defaults for the other side's items.
/// Returns the first attribute both stores hold with values of different types, where the other store's items get the default.
fn extend(&mut self, other: Attributes) -> Option<AttributeTypeConflictError> {
fn extend(&mut self, other: Attributes) {
let (len, other_len) = (self.len, other.len);
self.len += other_len;
// An empty store takes on the other's attributes whole, sharing them
if len == 0 && self.entries().is_empty() {
self.attributes = other.attributes;
return None;
return;
}
// Nothing to add or pad, so self's attributes can stay shared
if other.attributes.is_empty() && (other_len == 0 || self.attributes.is_empty()) {
return None;
return;
}
let mut other_entries = other.attributes.into_vec();
let mut conflict = None;
// Extend matching attributes, or pad self's attributes with implicit defaults for the other's item count
for (key, self_attribute) in self.attributes.as_mut_slice() {
let self_attribute = unshared(self_attribute);
match other_entries.iter().position(|(other_key, _)| other_key == key) {
// An attribute without values holds no type to keep
Some(position) if len == 0 => *self_attribute = other_entries.swap_remove(position).1,
Some(position) => {
if !unshared(self_attribute).extend(other_entries.swap_remove(position).1) {
conflict.get_or_insert_with(|| AttributeTypeConflictError { name: key.as_str().to_string() });
}
}
None => pad_with_implicit_default(key.as_str(), unshared(self_attribute), other_len),
Some(position) => self_attribute.extend(other_entries.swap_remove(position).1),
None => pad_with_implicit_default(key.as_str(), self_attribute, other_len),
}
}
@@ -1190,13 +1153,6 @@ impl Attributes {
self.attributes.push((key, combined));
}
conflict
}
/// The type of the values the attribute for the given key holds, if present.
fn value_type(&self, key: &str) -> Option<TypeDescriptor> {
self.entries().iter().find(|(k, _)| k.is(key)).map(|(_, attribute)| attribute.value_type())
}
/// Gets a reference to the value at the given index from the attribute for the given key.
@@ -1273,24 +1229,18 @@ impl Attributes {
}
/// Sets a single type-erased value at the given index of a list of `item_count` items, creating the attribute from the
/// value's type if the key holds none. An attribute of another type is replaced, padded with implicit defaults.
fn set_value_dyn(&mut self, key: &str, index: usize, mut value: Box<dyn AnyAttributeValue>, item_count: usize) {
if let Some(position) = self.position(key)
&& let Some((_, attribute)) = self.attributes.as_mut_slice().get_mut(position)
{
match unshared(attribute).set_at(index, value) {
Ok(()) => return,
Err(mistyped) => {
self.attributes.remove(position);
value = mistyped;
}
}
}
/// value's type if the key holds none.
fn set_value_dyn(&mut self, key: &str, index: usize, value: Box<dyn AnyAttributeValue>, item_count: usize) {
let position = self.position(key);
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
if let Some((_, attribute)) = position.and_then(|position| self.attributes.as_mut_slice().get_mut(position)) {
unshared(attribute).set_at(index, value);
} else {
let mut new_attribute = Arc::<dyn AnyAttributeValue>::from(value).into_attribute(key, index);
let trailing_defaults = item_count.saturating_sub(new_attribute.len());
pad_with_implicit_default(key, unshared(&mut new_attribute), trailing_defaults);
self.attributes.push((AttributeKey::new(key), new_attribute));
}
}
/// Returns a debug-formatted string for the value at the given index in the attribute for the given key.
@@ -1385,12 +1335,6 @@ impl Attributes {
}
}
#[derive(Clone, Debug, PartialEq, thiserror::Error)]
#[error("The \"{name}\" attribute holds different types of values in the lists being combined")]
pub struct AttributeTypeConflictError {
pub name: String,
}
// =======
// List<T>
// =======
@@ -1552,7 +1496,7 @@ impl<T> List<T> {
}
/// Sets a single type-erased attribute value at the given index, creating the attribute from the value's underlying type if it doesn't exist (padded with defaults to match the list's length).
/// An existing attribute of another type is replaced the same way.
/// Falls back to default if the value's type doesn't match an existing attribute.
pub fn set_attribute_value_dyn(&mut self, key: impl AsRef<str>, index: usize, value: AttributeValueDyn) {
self.attributes.set_value_dyn(key.as_ref(), index, value.0, self.element.len());
}
@@ -1609,16 +1553,14 @@ impl<T: Clone> List<T> {
Arc::make_mut(&mut self.element)
}
/// Appends an item to the end of this list, returning the first attribute the list holds with another type than the item's value for it.
/// The list keeps its type for it, giving the item its default.
pub fn push(&mut self, item: Item<T>) -> Option<AttributeTypeConflictError> {
/// Appends an item to the end of this list.
pub fn push(&mut self, item: Item<T>) {
self.elements_mut().push(item.element);
self.attributes.push_item(item.attributes)
self.attributes.push_item(item.attributes);
}
/// Appends all items from another list into this one, returning the first attribute both lists have with values of different types.
/// This list keeps its type for it, giving the other list's items its default.
pub fn extend(&mut self, list: List<T>) -> Option<AttributeTypeConflictError> {
/// Appends all items from another list into this one.
pub fn extend(&mut self, list: List<T>) {
// An empty list adopts the other's elements without copying them
if self.element.is_empty() {
self.element = list.element;
@@ -1629,7 +1571,7 @@ impl<T: Clone> List<T> {
Err(shared) => elements.extend_from_slice(&shared),
}
}
self.attributes.extend(list.attributes)
self.attributes.extend(list.attributes);
}
/// Returns an iterator over mutable references to all element values.
@@ -2245,78 +2187,6 @@ mod tests {
assert_eq!(starts(&rebuilt), [11, 21, 10, 20, 0]);
}
// Combining lists keeps only the first type of an attribute both have, and reports the attribute whose values were lost
#[test]
fn combining_lists_reports_attribute_type_conflicts() {
let mut base = List::new_from_elements(vec![1_u32, 2]);
base.set_attribute_values(ATTR_START, vec![10_u64, 20]);
base.set_attribute_values(ATTR_NAME, vec![String::from("a"), String::from("b")]);
let mut matching = List::new_from_elements(vec![3_u32]);
matching.set_attribute_values(ATTR_START, vec![30_u64]);
matching.set_attribute_values(ATTR_END, vec![1.5_f64]);
assert_eq!(base.extend(matching), None);
let mut empty = List::new();
empty.set_attribute_values(ATTR_NAME, Vec::<i64>::new());
assert_eq!(base.extend(empty), None, "an empty list loses no values");
let mut mistyped = List::new_from_elements(vec![4_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let conflict = AttributeTypeConflictError { name: ATTR_NAME.to_string() };
assert_eq!(base.extend(mistyped), Some(conflict.clone()));
assert_eq!(conflict.to_string(), "The \"name\" attribute holds different types of values in the lists being combined");
assert_eq!(base.attribute::<String>(ATTR_NAME, 3), Some(&String::new()));
assert_eq!(base.push(Item::new_from_element(5).with_attribute(ATTR_START, 50_u64)), None);
let mistyped_item = Item::new_from_element(6).with_attribute(ATTR_START, 60_f64);
assert_eq!(base.push(mistyped_item), Some(AttributeTypeConflictError { name: ATTR_START.to_string() }));
assert_eq!(base.attribute::<u64>(ATTR_START, 5), Some(&0));
}
#[test]
fn an_attribute_without_values_takes_the_type_of_the_values_added_to_it() {
let mut mistyped = List::new_from_elements(vec![1_u32]);
mistyped.set_attribute_values(ATTR_NAME, vec![7_i64]);
let mut extended = List::<u32>::new();
extended.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(extended.extend(mistyped), None);
assert_eq!(extended.attribute::<i64>(ATTR_NAME, 0), Some(&7));
let mut pushed = List::<u32>::new();
pushed.set_attribute_values(ATTR_NAME, Vec::<String>::new());
assert_eq!(pushed.push(Item::new_from_element(1).with_attribute(ATTR_NAME, 7_i64)), None);
assert_eq!(pushed.attribute::<i64>(ATTR_NAME, 0), Some(&7));
}
// An attribute's type reads back from a list's type-erased view, and a missing value reads as what padding fills in
#[test]
fn attribute_types_and_implicit_defaults_read_back() {
let mut list = List::new_from_elements(vec![1_u32]);
list.set_attribute(ATTR_OPACITY, 0, 0.5_f64);
let list = ListDyn::from(list);
assert_eq!(list.attribute_type(ATTR_OPACITY), Some(crate::descriptor!(f64)));
assert_eq!(list.attribute_type(ATTR_OPACITY).map(|value_type| value_type.to_string()), Some("Number".to_string()));
assert_eq!(list.attribute_type(ATTR_START), None);
assert_eq!(implicit_default::<f64>(ATTR_OPACITY), 1.);
assert_eq!(implicit_default::<f64>(ATTR_START), 0.);
assert_eq!(implicit_default::<i64>(ATTR_OPACITY), 0);
}
// A type-erased value of another type replaces the attribute, as a typed one does, instead of becoming the old type's default
#[test]
fn setting_a_value_of_another_type_replaces_the_attribute() {
let mut list = List::new_from_elements(vec![1_u32, 2]);
list.set_attribute_values(ATTR_OPACITY, vec![0.5_f64, 0.25]);
list.set_attribute_value_dyn(ATTR_OPACITY, 1, AttributeValueDyn(Box::new(3_i64)));
assert_eq!(list.iter_attribute_values::<i64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0, 3]));
list.set_attribute_value_dyn(ATTR_OPACITY, 0, AttributeValueDyn(Box::new(0.75_f64)));
assert_eq!(list.iter_attribute_values::<f64>(ATTR_OPACITY).map(|values| values.copied().collect::<Vec<_>>()), Some(vec![0.75, 1.]));
}
// Keys are stored inline up to a length limit and shared beyond it, which reads the same either way
#[test]
fn attribute_keys_of_any_length_read_back() {
+2 -2
View File
@@ -90,8 +90,8 @@ struct LegacyTable<T> {
}
// TODO: Eventually remove this document upgrade code
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<no_std_types::color::Color, D::Error> {
use no_std_types::color::Color;
pub fn migrate_to_color<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<crate::color::Color, D::Error> {
use crate::color::Color;
use serde::Deserialize;
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
+145 -32
View File
@@ -1,13 +1,16 @@
use crate::poll::Poll;
use crate::uuid::NodeId;
use dyn_any::WasmNotSend;
use futures::future::{AbortHandle, Abortable};
pub use futures::future::AbortHandle;
use futures::future::Abortable;
use std::collections::HashMap;
use std::future::Future;
use std::hash::{Hash, Hasher};
use std::pin::Pin;
use std::sync::{Arc, Mutex, PoisonError};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::task::{Context, Waker};
use std::time::Duration;
#[cfg(not(target_family = "wasm"))]
pub type Task = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
@@ -18,6 +21,36 @@ pub trait Spawn {
fn spawn(&self, task: Task);
}
/// Monotonic time since an arbitrary origin.
pub trait Clock: Send + Sync {
fn now(&self) -> Duration;
}
#[cfg(not(target_family = "wasm"))]
impl Clock for std::time::Instant {
fn now(&self) -> Duration {
self.elapsed()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scheduling {
/// How far into a frame a re-evaluation caused by finished tasks may start. `None` never defers it.
pub frame_budget: Option<Duration>,
}
impl Scheduling {
pub const UNLIMITED: Self = Self { frame_budget: None };
}
impl Default for Scheduling {
fn default() -> Self {
Self {
frame_budget: Some(Duration::from_millis(16)),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, graphene_hash::CacheHash, dyn_any::DynAny)]
pub struct SourceId(pub u64);
@@ -33,15 +66,22 @@ impl SourceId {
pub type Generations = Arc<[(SourceId, u64)]>;
pub trait Runtime {
fn spawn(&self, source: SourceId, task: Task);
/// Bumps the generation of `source` once `task` finishes, unless it was aborted or the source was removed first.
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle;
}
#[derive(Clone, dyn_any::DynAny)]
pub struct RuntimeHandle(Arc<RuntimeInner>);
impl RuntimeHandle {
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
}
impl Runtime for RuntimeHandle {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
}
}
@@ -64,28 +104,43 @@ impl graphene_hash::CacheHash for RuntimeHandle {
pub struct AsyncRuntime(Arc<RuntimeInner>);
impl AsyncRuntime {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>) -> Self {
pub fn new(spawner: Arc<dyn Spawn + Send + Sync>, clock: Arc<dyn Clock>) -> Self {
Self(Arc::new(RuntimeInner {
generations: Mutex::default(),
sources: Mutex::default(),
next_task: AtomicU64::new(0),
bumped: AtomicBool::new(false),
spawner,
clock,
}))
}
/// Aborts the unfinished tasks of removed sources.
pub fn retain_sources(&self, live: &[SourceId]) {
let mut generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
generations.retain(|source, _| live.contains(source));
let mut sources = self.0.lock();
for (_, state) in sources.extract_if(|source, _| !live.contains(source)) {
state.tasks.values().for_each(AbortHandle::abort);
}
for source in live {
generations.entry(*source).or_insert(0);
sources.entry(*source).or_default();
}
}
pub fn snapshot(&self) -> Generations {
let generations = self.0.generations.lock().unwrap_or_else(PoisonError::into_inner);
let mut snapshot: Vec<_> = generations.iter().map(|(source, generation)| (*source, *generation)).collect();
let sources = self.0.lock();
let mut snapshot: Vec<_> = sources.iter().map(|(source, state)| (*source, state.generation)).collect();
snapshot.sort_unstable();
snapshot.into()
}
/// Whether any generation was bumped since the last call.
pub fn take_bumped(&self) -> bool {
self.0.bumped.swap(false, Ordering::AcqRel)
}
pub fn clock(&self) -> &dyn Clock {
&*self.0.clock
}
#[must_use]
pub fn handle(&self) -> RuntimeHandle {
RuntimeHandle(Arc::clone(&self.0))
@@ -93,25 +148,50 @@ impl AsyncRuntime {
}
impl Runtime for AsyncRuntime {
fn spawn(&self, source: SourceId, task: Task) {
self.0.spawn(source, task);
fn spawn(&self, source: SourceId, task: Task) -> AbortHandle {
self.0.spawn(source, task)
}
}
/// A live source's generation and its unfinished tasks.
#[derive(Default)]
struct SourceState {
generation: u64,
tasks: HashMap<u64, AbortHandle>,
}
struct RuntimeInner {
generations: Mutex<HashMap<SourceId, u64>>,
sources: Mutex<HashMap<SourceId, SourceState>>,
next_task: AtomicU64,
bumped: AtomicBool,
spawner: Arc<dyn Spawn + Send + Sync>,
clock: Arc<dyn Clock>,
}
impl RuntimeInner {
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) {
fn lock(&self) -> MutexGuard<'_, HashMap<SourceId, SourceState>> {
self.sources.lock().unwrap_or_else(PoisonError::into_inner)
}
fn spawn(self: &Arc<Self>, source: SourceId, task: Task) -> AbortHandle {
let (handle, registration) = AbortHandle::new_pair();
let id = self.next_task.fetch_add(1, Ordering::Relaxed);
if let Some(state) = self.lock().get_mut(&source) {
state.tasks.insert(id, handle.clone());
}
let inner = Arc::clone(self);
self.spawner.spawn(Box::pin(async move {
task.await;
if let Some(generation) = inner.generations.lock().unwrap_or_else(PoisonError::into_inner).get_mut(&source) {
*generation += 1;
let finished = Abortable::new(task, registration).await.is_ok();
if let Some(state) = inner.lock().get_mut(&source)
&& state.tasks.remove(&id).is_some()
&& finished
{
state.generation += 1;
inner.bumped.store(true, Ordering::Release);
}
}));
handle
}
}
@@ -167,14 +247,12 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
return state;
}
let (handle, registration) = AbortHandle::new_pair();
let slots = Arc::downgrade(&self.0);
runtime.spawn(
let handle = runtime.spawn(
source,
Box::pin(async move {
if let Ok(state) = Abortable::new(future, registration).await
&& let Some(slots) = slots.upgrade()
{
let state = future.await;
if let Some(slots) = slots.upgrade() {
slots.lock().unwrap_or_else(PoisonError::into_inner).insert(key, Slot::Ready(state));
}
}),
@@ -193,7 +271,14 @@ impl<T: Clone + WasmNotSend + 'static> Slots<T> {
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
struct NoClock;
impl Clock for NoClock {
fn now(&self) -> Duration {
Duration::ZERO
}
}
fn poll_once(task: &mut Task) -> bool {
task.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_ready()
@@ -246,7 +331,7 @@ mod tests {
#[test]
fn a_completion_bumps_its_generation() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.handle().spawn(SOURCE, Box::pin(YieldOnce(false)));
@@ -259,7 +344,7 @@ mod tests {
#[test]
fn retaining_sources_keeps_live_generations() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
spawner.drain();
@@ -274,7 +359,7 @@ mod tests {
#[test]
fn an_inline_completion_and_a_dropped_source_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
@@ -291,7 +376,7 @@ mod tests {
#[test]
fn a_slot_serves_the_placeholder_until_the_response_lands() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
@@ -308,7 +393,7 @@ mod tests {
#[test]
fn a_blocking_spawner_lands_the_slot_in_the_same_resolve() {
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner));
let runtime = AsyncRuntime::new(Arc::new(BlockingSpawner), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
let slots = Slots::default();
let fetch = || async {
@@ -323,7 +408,7 @@ mod tests {
#[test]
fn a_clone_keeps_the_task_running() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let slots = Slots::default();
let fetch = || async {
YieldOnce(false).await;
@@ -340,7 +425,7 @@ mod tests {
#[test]
fn dropping_the_last_clone_aborts_the_task() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
let slots = Slots::default();
let finished = Arc::new(AtomicBool::new(false));
let fetch = || {
@@ -357,4 +442,32 @@ mod tests {
assert_eq!(spawner.drain(), 1);
assert!(!finished.load(Ordering::Relaxed));
}
#[test]
fn finished_tasks_bump_once() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE]);
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
runtime.spawn(SOURCE, Box::pin(YieldOnce(false)));
assert_eq!(spawner.drain(), 2);
assert!(runtime.take_bumped());
assert!(!runtime.take_bumped());
}
#[test]
fn aborted_tasks_bump_nothing() {
let spawner = Arc::new(CollectSpawner::default());
let runtime = AsyncRuntime::new(spawner.clone(), Arc::new(NoClock));
runtime.retain_sources(&[SOURCE, SourceId(9)]);
runtime.spawn(SOURCE, Box::pin(std::future::pending())).abort();
let removed = runtime.spawn(SourceId(9), Box::pin(std::future::pending()));
runtime.retain_sources(&[SOURCE]);
assert!(removed.is_aborted());
assert_eq!(spawner.drain(), 2);
assert_eq!(&*runtime.snapshot(), &[(SOURCE, 0)]);
assert!(!runtime.take_bumped());
}
}
@@ -179,6 +179,8 @@ impl Footprint {
quality: RenderQuality::Full,
};
pub const MAX_UNION_RESOLUTION: u32 = 8192;
pub const BOUNDLESS: Self = Self {
transform: DAffine2 {
matrix2: DMat2::from_diagonal(DVec2::splat(f64::INFINITY)),
@@ -205,6 +207,61 @@ impl Footprint {
}
}
/// The same view squeezed into a single pixel, for evaluating content only to learn where it's placed. A boundless footprint stays boundless.
pub fn probe(&self) -> Footprint {
if !self.transform.is_finite() {
return *self;
}
Footprint {
transform: DAffine2::from_scale(1. / self.resolution.max(UVec2::ONE).as_dvec2()) * self.transform,
resolution: UVec2::ONE,
..*self
}
}
/// The footprint for content shown once per transform in `instance_transforms`, covering what every instance shows of it. A boundless footprint stays boundless.
pub fn for_instances(&self, instance_transforms: impl IntoIterator<Item = DAffine2>) -> Footprint {
if !self.transform.is_finite() {
return *self;
}
let views = instance_transforms.into_iter().map(|instance_transform| Footprint {
transform: self.transform * instance_transform,
..*self
});
Self::union(views).unwrap_or(*self)
}
/// The footprint covering everything each of `views` shows of the content, axis-aligned in the content's space at the finest pixel density any of them needs.
/// Its density is lowered to keep each side within [`Self::MAX_UNION_RESOLUTION`]. `None` when no view has an invertible transform.
pub fn union(views: impl IntoIterator<Item = Footprint>) -> Option<Footprint> {
let mut bounds: Option<AxisAlignedBbox> = None;
let mut density = 0_f64;
let mut quality = RenderQuality::Full;
for view in views {
if view.transform.matrix2.determinant() == 0. {
continue;
}
let view_bounds = view.viewport_bounds_in_local_space();
bounds = Some(bounds.map_or(view_bounds.clone(), |bounds| bounds.union(&view_bounds)));
density = density.max(view.scale().max_element());
quality = view.quality;
}
let bounds = bounds?;
let size = bounds.size();
let density = density.min(Self::MAX_UNION_RESOLUTION as f64 / size.max_element());
let resolution = (size * density).ceil().as_uvec2().max(UVec2::ONE);
Some(Footprint {
transform: DAffine2::from_scale(DVec2::splat(density)) * DAffine2::from_translation(-bounds.start),
resolution,
quality,
})
}
pub fn scale(&self) -> DVec2 {
self.transform.scale_magnitudes()
}
@@ -257,3 +314,59 @@ impl ApplyTransform for DVec2 {
*self = modification.transform_point2(*self);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn view(width: u32, height: u32) -> Footprint {
Footprint {
resolution: UVec2::new(width, height),
..Footprint::DEFAULT
}
}
#[test]
fn instances_footprint_covers_every_instance() {
let footprint = view(100, 100).for_instances([DAffine2::IDENTITY, DAffine2::from_translation(DVec2::new(200., 0.))]);
let bounds = footprint.viewport_bounds_in_local_space();
assert!(bounds.start.abs_diff_eq(DVec2::new(-200., 0.), 1e-9), "{bounds:?}");
assert!(bounds.end.abs_diff_eq(DVec2::new(100., 100.), 1e-9), "{bounds:?}");
assert_eq!(footprint.resolution, UVec2::new(300, 100));
}
#[test]
fn instances_footprint_takes_the_finest_density() {
let footprint = view(100, 100).for_instances([DAffine2::IDENTITY, DAffine2::from_scale(DVec2::splat(4.))]);
assert!((footprint.scale().x - 4.).abs() < 1e-9);
assert_eq!(footprint.resolution, UVec2::new(400, 400));
}
#[test]
fn instances_footprint_caps_its_resolution() {
let footprint = view(1000, 1000).for_instances([DAffine2::IDENTITY, DAffine2::from_translation(DVec2::new(1e6, 0.))]);
assert!(footprint.resolution.max_element() <= Footprint::MAX_UNION_RESOLUTION);
}
#[test]
fn boundless_footprint_stays_boundless() {
assert_eq!(Footprint::BOUNDLESS.for_instances([DAffine2::from_translation(DVec2::ONE)]), Footprint::BOUNDLESS);
assert_eq!(Footprint::BOUNDLESS.probe(), Footprint::BOUNDLESS);
}
#[test]
fn probe_covers_the_same_view_in_one_pixel() {
let footprint = Footprint {
transform: DAffine2::from_scale(DVec2::splat(2.)),
..view(100, 50)
};
let probe = footprint.probe();
assert_eq!(probe.resolution, UVec2::ONE);
let (bounds, probe_bounds) = (footprint.viewport_bounds_in_local_space(), probe.viewport_bounds_in_local_space());
assert!(bounds.start.abs_diff_eq(probe_bounds.start, 1e-9) && bounds.end.abs_diff_eq(probe_bounds.end, 1e-9));
}
}
@@ -15,11 +15,9 @@ publish.workspace = true
workspace = true
[features]
default = ["std"]
std = ["dep:kurbo"]
derive = ["graphene-hash-derive"]
[dependencies]
graphene-hash-derive = { path = "derive", optional = true }
glam = { workspace = true }
kurbo = { workspace = true, optional = true }
kurbo = { workspace = true }
@@ -1,8 +1,3 @@
#![cfg_attr(not(feature = "std"), no_std)]
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "derive")]
pub use graphene_hash_derive::CacheHash;
@@ -66,7 +61,6 @@ impl_via_hash! {
glam::BVec2, glam::BVec3, glam::BVec4,
}
#[cfg(feature = "std")]
impl_via_hash! {
String,
}
@@ -154,7 +148,6 @@ impl_glam_array! {
}
// kurbo path types: hash each element's verb and point coordinates via to_bits().
#[cfg(feature = "std")]
impl CacheHash for kurbo::Point {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -163,7 +156,6 @@ impl CacheHash for kurbo::Point {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::PathEl {
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
core::hash::Hash::hash(&core::mem::discriminant(self), state);
@@ -183,7 +175,6 @@ impl CacheHash for kurbo::PathEl {
}
}
#[cfg(feature = "std")]
impl CacheHash for kurbo::BezPath {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -224,7 +215,6 @@ impl<T: CacheHash, const N: usize> CacheHash for [T; N] {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for Vec<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -232,7 +222,6 @@ impl<T: CacheHash> CacheHash for Vec<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -243,7 +232,6 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -251,7 +239,6 @@ impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
}
}
#[cfg(feature = "std")]
impl<T: CacheHash + ?Sized> CacheHash for std::sync::Arc<T> {
#[inline]
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
@@ -21,6 +21,7 @@ wasm = [
"core-types/wasm",
"vector-types/wasm",
"raster-types/wasm",
"tsify",
"wasm-bindgen",
]
@@ -28,6 +29,7 @@ wasm = [
# Local dependencies
core-types = { workspace = true }
graphene-hash = { workspace = true }
graphene-resource = { workspace = true }
brush-types = { workspace = true }
raster-types = { workspace = true, features = ["wgpu"] }
vector-types = { workspace = true }
@@ -36,8 +38,10 @@ node-macro = { workspace = true }
# Workspace dependencies
dyn-any = { workspace = true }
glam = { workspace = true }
num_enum = { workspace = true }
serde_json = { workspace = true }
# Optional workspace dependencies
serde = { workspace = true, optional = true }
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
@@ -0,0 +1,557 @@
//! Color adjustments as plain data holding their nodes' settings in the nodes' own units, decoded from effect rows, carried out by the kernels of the `raster-kernels` crate.
use crate::Graphic;
use crate::effects::{EffectKind, ParameterVisitor};
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::Item;
use core_types::transfer_curve::TransferCurve;
use graphene_resource::Resource;
use num_enum::{FromPrimitive, IntoPrimitive};
use vector_types::Gradient;
/// A color adjustment applied to each color on its own, with no regard for its neighbors.
#[derive(Clone, Debug, PartialEq, CacheHash)]
pub enum Adjustment {
Desaturate {
method: DesaturateMethod,
},
GammaCorrection {
gamma: f64,
inverse: bool,
},
MakeOpaque,
BrightnessContrast {
/// Percent.
brightness: f64,
/// Percent.
contrast: f64,
use_classic: bool,
/// On a scale of 0 to 255.
classic_pivot: f64,
},
Levels(Box<LevelsSettings>),
Curves(Box<CurvesSettings>),
BlackAndWhite(BlackAndWhiteSettings),
HueSaturation(Box<HueSaturationSettings>),
Invert,
Threshold {
/// Percent.
min_luminance: f64,
/// Percent.
max_luminance: f64,
},
GradientMap {
/// The gradient, with its whole-ramp settings as its attributes.
gradient: Item<Gradient>,
reverse: bool,
},
Vibrance {
/// Percent.
vibrance: f64,
/// Percent.
saturation: f64,
},
ChannelMixer(Box<ChannelMixerSettings>),
SelectiveColor(Box<SelectiveColorSettings>),
Posterize {
levels: i64,
},
Exposure {
exposure: f64,
offset: f64,
gamma_correction: f64,
},
ColorBalance(ColorBalanceSettings),
PhotoFilter {
color: Color,
/// Percent.
density: f64,
preserve_luminosity: bool,
},
ColorLookup {
/// The file the lookup table is read from.
lut_file: Resource,
},
ColorOverlay {
color: Color,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
}
impl Adjustment {
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
pub fn is_per_channel(&self) -> bool {
matches!(
self,
Self::GammaCorrection { .. }
| Self::MakeOpaque
| Self::BrightnessContrast { .. }
| Self::Levels(_)
| Self::Curves(_)
| Self::Invert
| Self::Posterize { .. }
| Self::Exposure { .. }
| Self::ColorBalance(_)
)
}
pub fn kind(&self) -> EffectKind {
match self {
Self::Desaturate { .. } => EffectKind::Desaturate,
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
Self::MakeOpaque => EffectKind::MakeOpaque,
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
Self::Levels(_) => EffectKind::Levels,
Self::Curves(_) => EffectKind::Curves,
Self::BlackAndWhite(_) => EffectKind::BlackAndWhite,
Self::HueSaturation(_) => EffectKind::HueSaturation,
Self::Invert => EffectKind::Invert,
Self::Threshold { .. } => EffectKind::Threshold,
Self::GradientMap { .. } => EffectKind::GradientMap,
Self::Vibrance { .. } => EffectKind::Vibrance,
Self::ChannelMixer(_) => EffectKind::ChannelMixer,
Self::SelectiveColor(_) => EffectKind::SelectiveColor,
Self::Posterize { .. } => EffectKind::Posterize,
Self::Exposure { .. } => EffectKind::Exposure,
Self::ColorBalance(_) => EffectKind::ColorBalance,
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
Self::ColorLookup { .. } => EffectKind::ColorLookup,
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
}
}
/// Visits each parameter with the attribute it rides, named after the node's parameter, and its implicit default, which is the node's.
pub(crate) fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
match self {
Self::Desaturate { method } => visitor.parameter("method", method, DesaturateMethod::default()),
Self::GammaCorrection { gamma, inverse } => {
visitor.parameter("gamma", gamma, 2.2);
visitor.parameter("inverse", inverse, false);
}
Self::MakeOpaque | Self::Invert => {}
Self::BrightnessContrast {
brightness,
contrast,
use_classic,
classic_pivot,
} => {
visitor.parameter("brightness", brightness, 0.);
visitor.parameter("contrast", contrast, 0.);
visitor.parameter("use_classic", use_classic, false);
visitor.parameter("classic_pivot", classic_pivot, 127.);
}
Self::Levels(settings) => {
let LevelsSettings { composite, red, green, blue, alpha } = settings.as_mut();
composite.visit_parameters(visitor, "");
red.visit_parameters(visitor, "red");
green.visit_parameters(visitor, "green");
blue.visit_parameters(visitor, "blue");
alpha.visit_parameters(visitor, "alpha");
}
Self::Curves(settings) => {
let CurvesSettings { composite, red, green, blue, alpha } = settings.as_mut();
visitor.parameter("curve", composite, TransferCurve::default());
visitor.parameter("red_curve", red, TransferCurve::default());
visitor.parameter("green_curve", green, TransferCurve::default());
visitor.parameter("blue_curve", blue, TransferCurve::default());
visitor.parameter("alpha_curve", alpha, TransferCurve::default());
}
Self::BlackAndWhite(settings) => {
visitor.parameter("use_tint", &mut settings.use_tint, false);
visitor.parameter("tint", &mut settings.tint, Color::from(SRGBA8::new(0xe1, 0xd3, 0xb3, 0xff)));
visitor.parameter("reds", &mut settings.reds, 40.);
visitor.parameter("yellows", &mut settings.yellows, 60.);
visitor.parameter("greens", &mut settings.greens, 40.);
visitor.parameter("cyans", &mut settings.cyans, 60.);
visitor.parameter("blues", &mut settings.blues, 20.);
visitor.parameter("magentas", &mut settings.magentas, 80.);
}
Self::HueSaturation(settings) => {
let HueSaturationSettings {
master,
colorize,
colorize_sliders,
reds,
yellows,
greens,
cyans,
blues,
magentas,
} = settings.as_mut();
master.visit_parameters(visitor, "", [0., 0., 0.]);
visitor.parameter("colorize", colorize, false);
colorize_sliders.visit_parameters(visitor, "colorize", [24., 25., 0.]);
reds.visit_parameters(visitor, "reds", [315., 345., 15., 45.]);
yellows.visit_parameters(visitor, "yellows", [15., 45., 75., 105.]);
greens.visit_parameters(visitor, "greens", [75., 105., 135., 165.]);
cyans.visit_parameters(visitor, "cyans", [135., 165., 195., 225.]);
blues.visit_parameters(visitor, "blues", [195., 225., 255., 285.]);
magentas.visit_parameters(visitor, "magentas", [255., 285., 315., 345.]);
}
Self::Threshold { min_luminance, max_luminance } => {
visitor.parameter("min_luminance", min_luminance, 50.);
visitor.parameter("max_luminance", max_luminance, 100.);
}
Self::GradientMap { gradient, reverse } => {
visitor.parameter("gradient", gradient, Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])));
visitor.parameter("reverse", reverse, false);
}
Self::Vibrance { vibrance, saturation } => {
visitor.parameter("vibrance", vibrance, 0.);
visitor.parameter("saturation", saturation, 0.);
}
Self::ChannelMixer(settings) => {
let ChannelMixerSettings {
monochrome,
monochrome_mix,
red,
green,
blue,
} = settings.as_mut();
visitor.parameter("monochrome", monochrome, false);
monochrome_mix.visit_parameters(visitor, "monochrome", [40., 40., 20., 0.]);
red.visit_parameters(visitor, "red", [100., 0., 0., 0.]);
green.visit_parameters(visitor, "green", [0., 100., 0., 0.]);
blue.visit_parameters(visitor, "blue", [0., 0., 100., 0.]);
}
Self::SelectiveColor(settings) => {
let SelectiveColorSettings {
mode,
reds,
yellows,
greens,
cyans,
blues,
magentas,
whites,
neutrals,
blacks,
} = settings.as_mut();
visitor.parameter("mode", mode, RelativeAbsolute::default());
let groups = [
("reds", reds),
("yellows", yellows),
("greens", greens),
("cyans", cyans),
("blues", blues),
("magentas", magentas),
("whites", whites),
("neutrals", neutrals),
("blacks", blacks),
];
for (name, inks) in groups {
inks.visit_parameters(visitor, name);
}
}
Self::Posterize { levels } => visitor.parameter("levels", levels, 4),
Self::Exposure { exposure, offset, gamma_correction } => {
visitor.parameter("exposure", exposure, 0.);
visitor.parameter("offset", offset, 0.);
visitor.parameter("gamma_correction", gamma_correction, 1.);
}
Self::ColorBalance(settings) => {
settings.shadows.visit_parameters(visitor, "shadows");
settings.midtones.visit_parameters(visitor, "midtones");
settings.highlights.visit_parameters(visitor, "highlights");
visitor.parameter("preserve_luminosity", &mut settings.preserve_luminosity, true);
}
Self::PhotoFilter { color, density, preserve_luminosity } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xec, 0x8a, 0x00, 0xff)));
visitor.parameter("density", density, 25.);
visitor.parameter("preserve_luminosity", preserve_luminosity, true);
}
Self::ColorLookup { lut_file } => visitor.parameter("lut_file", lut_file, Resource::default()),
Self::ColorOverlay { color, blend_mode, opacity } => {
// Rides the row as the paint of the Paint Overlay node, which stamps it
let mut paint = Graphic::from(*color);
visitor.parameter("paint", &mut paint, Graphic::from(Color::BLACK));
if let Graphic::Color(paint) = paint {
*color = *paint.element();
}
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
}
}
}
/// Conversion from a color to grayscale.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
#[widget(Dropdown)]
#[repr(u32)]
pub enum DesaturateMethod {
/// Light level of the color, the Y (luminance) of Rec. 709, which weights the linear-light RGB channels by `0.2126, 0.7152, 0.0722`.
///
/// Accessibility contrast ratios and SVG luminance masks use this.
#[default]
#[label("Luminance (Rec. 709)")]
#[cfg_attr(feature = "serde", serde(alias = "SRGB"))]
LuminanceRec709,
/// Light level approximation for the color, the Y′ (luma) of Rec. 709, which weights the gamma-encoded RGB channels by `0.2126, 0.7152, 0.0722`.
///
/// CSS filter functions such as `grayscale()` use this.
#[label("Luma (Rec. 709)")]
LumaRec709,
/// Light level approximation for the color, the Y′ (luma) of Rec. 601, which weights the gamma-encoded RGB channels by `0.299, 0.587, 0.114`.
///
/// The Luminosity family of blend modes uses this, rounded to `0.3, 0.59, 0.11`.
#[label("Luma (Rec. 601)")]
LumaRec601,
/// Perceptually uniform scale from black to white, the L (lightness) of OkLab.
#[label("Lightness (OkLab)")]
#[cfg_attr(feature = "serde", serde(alias = "Perceptual"))]
LightnessOkLab,
/// Mean of the three linear-light RGB channels.
#[menu_separator]
#[cfg_attr(feature = "serde", serde(alias = "AverageChannels"))]
ChannelsAverage,
/// Smallest of the three linear-light RGB channels.
#[cfg_attr(feature = "serde", serde(alias = "MinimumChannels"))]
ChannelsMinimum,
/// Largest of the three linear-light RGB channels, the V (value) of HSV.
#[cfg_attr(feature = "serde", serde(alias = "MaximumChannels"))]
ChannelsMaximum,
/// Midpoint of the largest and smallest gamma-encoded RGB channels, the L (lightness) of HSL.
///
/// The classic "Desaturate" command of many image editors uses this.
#[label("Lightness (HSL)")]
LightnessHsl,
}
#[repr(u32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
#[widget(Radio)]
pub enum RelativeAbsolute {
#[default]
Relative,
Absolute,
}
/// A group of colors whose inks the Selective Color adjustment offsets.
#[repr(u32)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType, FromPrimitive, IntoPrimitive)]
pub enum SelectiveColorChoice {
#[default]
Reds,
Yellows,
Greens,
Cyans,
Blues,
Magentas,
#[menu_separator]
Whites,
Neutrals,
Blacks,
}
/// One channel's Levels record: percentage input and output points and the midtones gamma.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct LevelsRecord {
pub shadows: f64,
pub midtones: f64,
pub highlights: f64,
pub output_minimums: f64,
pub output_maximums: f64,
}
/// The composite record that the three color channels pass through after their own, and the alpha record that stands apart.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct LevelsSettings {
pub composite: LevelsRecord,
pub red: LevelsRecord,
pub green: LevelsRecord,
pub blue: LevelsRecord,
pub alpha: LevelsRecord,
}
/// The composite curve that the three color channels pass through after their own, and the alpha curve that stands apart.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct CurvesSettings {
pub composite: TransferCurve,
pub red: TransferCurve,
pub green: TransferCurve,
pub blue: TransferCurve,
pub alpha: TransferCurve,
}
/// The percentage each hue contributes to the gray, and the color tinting it when `use_tint` is set.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct BlackAndWhiteSettings {
pub use_tint: bool,
pub tint: Color,
pub reds: f64,
pub yellows: f64,
pub greens: f64,
pub cyans: f64,
pub blues: f64,
pub magentas: f64,
}
/// One set of Hue/Saturation sliders: a hue in degrees and saturation and lightness percentages.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct HueSaturationSliders {
pub hue: f64,
pub saturation: f64,
pub lightness: f64,
}
/// The sliders for one range of hues, which apply fully from the range start to its end, fading out at the falloff ends. Edges are in degrees.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct HueRangeSettings {
pub sliders: HueSaturationSliders,
pub falloff_start: f64,
pub range_start: f64,
pub range_end: f64,
pub falloff_end: f64,
}
/// The master sliders shift every color, each hue range adds its own, and colorizing replaces them all with an absolute hue and saturation.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct HueSaturationSettings {
pub master: HueSaturationSliders,
pub colorize: bool,
pub colorize_sliders: HueSaturationSliders,
pub reds: HueRangeSettings,
pub yellows: HueRangeSettings,
pub greens: HueRangeSettings,
pub cyans: HueRangeSettings,
pub blues: HueRangeSettings,
pub magentas: HueRangeSettings,
}
/// The percentages of each source channel, plus a constant, that sum to one output channel.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct ChannelMixerRow {
pub red: f64,
pub green: f64,
pub blue: f64,
pub constant: f64,
}
/// A row for each output channel, or for the single gray channel when monochrome.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct ChannelMixerSettings {
pub monochrome: bool,
pub monochrome_mix: ChannelMixerRow,
pub red: ChannelMixerRow,
pub green: ChannelMixerRow,
pub blue: ChannelMixerRow,
}
/// Percentage offsets to the cyan, magenta, yellow, and black inks of one group of colors.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct SelectiveColorInks {
pub cyan: f64,
pub magenta: f64,
pub yellow: f64,
pub black: f64,
}
/// The ink offsets of each group of colors, and whether they are relative to the inks already present.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct SelectiveColorSettings {
pub mode: RelativeAbsolute,
pub reds: SelectiveColorInks,
pub yellows: SelectiveColorInks,
pub greens: SelectiveColorInks,
pub cyans: SelectiveColorInks,
pub blues: SelectiveColorInks,
pub magentas: SelectiveColorInks,
pub whites: SelectiveColorInks,
pub neutrals: SelectiveColorInks,
pub blacks: SelectiveColorInks,
}
/// Percentage shifts along the three opponent color axes for one tonal range.
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
pub struct ColorBalanceShifts {
pub cyan_red: f64,
pub magenta_green: f64,
pub yellow_blue: f64,
}
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct ColorBalanceSettings {
pub shadows: ColorBalanceShifts,
pub midtones: ColorBalanceShifts,
pub highlights: ColorBalanceShifts,
pub preserve_luminosity: bool,
}
/// The attribute key of a parameter in one of a node's groups of parameters, which the node names with the group's prefix.
fn grouped_key(group: &str, parameter: &str) -> String {
if group.is_empty() { parameter.to_string() } else { format!("{group}_{parameter}") }
}
impl LevelsRecord {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
visitor.parameter(&grouped_key(group, "highlights"), &mut self.highlights, 100.);
visitor.parameter(&grouped_key(group, "output_minimums"), &mut self.output_minimums, 0.);
visitor.parameter(&grouped_key(group, "output_maximums"), &mut self.output_maximums, 100.);
}
}
impl HueSaturationSliders {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [hue, saturation, lightness]: [f64; 3]) {
visitor.parameter(&grouped_key(group, "hue"), &mut self.hue, hue);
visitor.parameter(&grouped_key(group, "saturation"), &mut self.saturation, saturation);
visitor.parameter(&grouped_key(group, "lightness"), &mut self.lightness, lightness);
}
}
impl HueRangeSettings {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [falloff_start, range_start, range_end, falloff_end]: [f64; 4]) {
self.sliders.visit_parameters(visitor, group, [0.; 3]);
visitor.parameter(&grouped_key(group, "falloff_start"), &mut self.falloff_start, falloff_start);
visitor.parameter(&grouped_key(group, "range_start"), &mut self.range_start, range_start);
visitor.parameter(&grouped_key(group, "range_end"), &mut self.range_end, range_end);
visitor.parameter(&grouped_key(group, "falloff_end"), &mut self.falloff_end, falloff_end);
}
}
impl ChannelMixerRow {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str, [red, green, blue, constant]: [f64; 4]) {
visitor.parameter(&grouped_key(group, "red"), &mut self.red, red);
visitor.parameter(&grouped_key(group, "green"), &mut self.green, green);
visitor.parameter(&grouped_key(group, "blue"), &mut self.blue, blue);
visitor.parameter(&grouped_key(group, "constant"), &mut self.constant, constant);
}
}
impl SelectiveColorInks {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "cyan"), &mut self.cyan, 0.);
visitor.parameter(&grouped_key(group, "magenta"), &mut self.magenta, 0.);
visitor.parameter(&grouped_key(group, "yellow"), &mut self.yellow, 0.);
visitor.parameter(&grouped_key(group, "black"), &mut self.black, 0.);
}
}
impl ColorBalanceShifts {
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "cyan_red"), &mut self.cyan_red, 0.);
visitor.parameter(&grouped_key(group, "magenta_green"), &mut self.magenta_green, 0.);
visitor.parameter(&grouped_key(group, "yellow_blue"), &mut self.yellow_blue, 0.);
}
}
@@ -232,9 +232,7 @@ impl Appearance {
let row = cover_row(coverage, paint);
match placement {
CoverPlacement::Above => {
self.0.push(row);
}
CoverPlacement::Above => self.0.push(row),
CoverPlacement::Below => {
let mut reordered = List::new_from_item(row);
reordered.extend(std::mem::take(&mut self.0));
@@ -0,0 +1,712 @@
//! An item's effects: an ordered list of image operations on the pixels the item renders to, stored in the `ATTR_EFFECTS` attribute.
//! Each row is an [`EffectKind`] whose parameters ride its item as attributes, read as their defaults when absent.
//! Each renderer decodes the rows into [`EffectOperation`]s and carries them out its own way, at the resolution of each render.
use crate::Graphic;
use crate::adjustment::Adjustment;
use core_types::ATTR_TRANSFORM;
use core_types::Color;
use core_types::blending::BlendMode;
use core_types::color::SRGBA8;
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_EFFECTS, Item, List};
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2, DVec3};
use std::fmt::Debug;
use vector_types::vector::style::StrokeAlign;
/// The image operation an [`Effect`] carries out.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
pub enum EffectKind {
/// Softens the content by blurring it.
#[default]
Blur,
/// Casts the content's silhouette as a soft shadow beneath it.
DropShadow,
/// Casts a soft shadow inward from the content's edges, as if it were cut out of the surface.
InnerShadow,
/// Surrounds the content with a soft glow of its silhouette.
OuterGlow,
/// Glows inward from the content's edges, or outward from its center.
InnerGlow,
/// Shades the content's interior with soft bands from its silhouette cast two ways.
Satin,
/// Draws a band of color along the content's silhouette.
Outline,
/// Lights the content as if raised from the surface or pressed into it, with highlights and shadows along its edges.
BevelAndEmboss,
/// Paints over the content within its silhouette, mixing with its colors by a blend mode. A solid color paint is the color overlay adjustment.
PaintOverlay,
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
Desaturate,
GammaCorrection,
MakeOpaque,
BrightnessContrast,
Levels,
Curves,
BlackAndWhite,
HueSaturation,
Invert,
Threshold,
GradientMap,
Vibrance,
ChannelMixer,
SelectiveColor,
Posterize,
Exposure,
ColorBalance,
PhotoFilter,
ColorLookup,
}
impl std::fmt::Display for EffectKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Blur => "Blur",
Self::DropShadow => "Drop Shadow",
Self::InnerShadow => "Inner Shadow",
Self::OuterGlow => "Outer Glow",
Self::InnerGlow => "Inner Glow",
Self::Satin => "Satin",
Self::Outline => "Outline",
Self::BevelAndEmboss => "Bevel & Emboss",
Self::PaintOverlay => "Paint Overlay",
Self::Desaturate => "Desaturate",
Self::GammaCorrection => "Gamma Correction",
Self::MakeOpaque => "Make Opaque",
Self::BrightnessContrast => "Brightness/Contrast",
Self::Levels => "Levels",
Self::Curves => "Curves",
Self::BlackAndWhite => "Black & White",
Self::HueSaturation => "Hue/Saturation",
Self::Invert => "Invert",
Self::Threshold => "Threshold",
Self::GradientMap => "Gradient Map",
Self::Vibrance => "Vibrance",
Self::ChannelMixer => "Channel Mixer",
Self::SelectiveColor => "Selective Color",
Self::Posterize => "Posterize",
Self::Exposure => "Exposure",
Self::ColorBalance => "Color Balance",
Self::PhotoFilter => "Photo Filter",
Self::ColorLookup => "Color Lookup",
})
}
}
/// Where an inner glow starts from.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
#[widget(Radio)]
pub enum GlowSource {
/// Glows inward from the edges.
#[default]
Edge,
/// Glows outward from the center.
Center,
}
/// Which slopes a bevel shapes from the content's edges.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum BevelStyle {
/// Slopes up from the edges into the content.
#[default]
InnerBevel,
/// Slopes down from the edges away from the content.
OuterBevel,
/// Slopes across the edges, half inside the content and half outside.
Emboss,
/// Slopes away from the edges both ways, as if pressed into the surface along them.
PillowEmboss,
}
/// Whether a bevel rises from the surface or sinks into it.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
#[widget(Radio)]
pub enum BevelDirection {
/// Raised from the surface.
#[default]
Up,
/// Pressed into the surface.
Down,
}
/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units.
pub fn bevel_smoothing(size: f64) -> f64 {
size.max(0.) / 4.
}
/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in.
pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 {
let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians());
let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X);
(across * altitude.cos()).extend(altitude.sin())
}
/// An overlay's paint with its unit square fitted to `content_bounds`, the content's extent in the space it's drawn in, if it's a gradient or image without its own placement.
pub fn fitted_paint(paint: &Graphic, content_bounds: [DVec2; 2]) -> Option<Graphic> {
let unplaced = match paint {
Graphic::Gradient(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterCPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
Graphic::RasterGPU(item) => item.attribute::<DAffine2>(ATTR_TRANSFORM).is_none(),
_ => false,
};
if !unplaced {
return None;
}
let fit = DAffine2::from_translation(content_bounds[0]) * DAffine2::from_scale(content_bounds[1] - content_bounds[0]);
let mut paint = paint.clone();
match &mut paint {
Graphic::Gradient(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterCPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
Graphic::RasterGPU(item) => item.set_attribute(ATTR_TRANSFORM, fit),
_ => {}
}
Some(paint)
}
/// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item.
/// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored.
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct Effect(pub Item<EffectKind>);
impl Effect {
/// Creates an effect row carrying out the given operation, stamping only the parameters that differ from their implicit defaults.
pub fn new(operation: &EffectOperation) -> Self {
let mut item = Item::new_from_element(operation.kind());
operation.clone().visit_parameters(&mut WriteParameters(&mut item));
Self(item)
}
/// This effect's kind.
pub fn kind(&self) -> EffectKind {
*self.0.element()
}
/// Decodes the parameters into an [`EffectOperation`], falling back to the default for any absent attribute.
pub fn operation(&self) -> EffectOperation {
let mut operation = EffectOperation::placeholder(self.kind());
operation.visit_parameters(&mut ReadParameters(&self.0));
// A solid paint mixes the same into every pixel, so the renderers carry it out with the other adjustments
match operation {
EffectOperation::PaintOverlay {
paint: Graphic::Color(color),
blend_mode,
opacity,
} => EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: *color.element(),
blend_mode,
opacity,
}),
operation => operation,
}
}
}
/// An item's ordered list of effects. A blur acts on the result of those before it, while shadows and glows are cast from the content and stack in order beneath it (or within it, for an inner shadow).
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
pub struct Effects(pub List<Effect>);
impl Effects {
/// Creates the list of rows carrying out the given operations in order.
pub fn from_operations(operations: impl IntoIterator<Item = EffectOperation>) -> Self {
let mut effects = Self::default();
for operation in operations {
effects.0.push(Item::new_from_element(Effect::new(&operation)));
}
effects
}
/// The effects in the order they're carried out.
pub fn effects(&self) -> impl Iterator<Item = &Effect> {
self.0.iter_element_values()
}
/// The effects after the first `count`.
pub fn after(&self, count: usize) -> Self {
let mut remaining = Self::default();
for effect in self.effects().skip(count) {
remaining.0.push(Item::new_from_element(effect.clone()));
}
remaining
}
/// The effects decoded into the operations renderers carry out, in order.
pub fn operations(&self) -> impl Iterator<Item = EffectOperation> + '_ {
self.effects().map(Effect::operation)
}
/// How far past the content the effects together can paint, in document pixels.
pub fn reach(&self) -> f64 {
self.operations().map(|operation| operation.reach()).sum()
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned.
pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) {
match align {
StrokeAlign::Outside => (weight, 0.),
StrokeAlign::Inside => (0., weight),
StrokeAlign::Center => (weight / 2., weight / 2.),
}
}
/// Appends an effect to the item's list, after those already applied to it.
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS).0.push(Item::new_from_element(effect));
}
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in document pixels.
#[derive(Clone, Debug, PartialEq)]
pub enum EffectOperation {
Blur {
/// The standard deviation of the Gaussian, or the half width of the box.
radius: f64,
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
box_blur: bool,
/// Whether to blend the colors with their gamma encoding rather than in linear light.
gamma: bool,
},
DropShadow {
color: Color,
offset: DVec2,
blur: f64,
spread: f64,
},
InnerShadow {
color: Color,
offset: DVec2,
blur: f64,
spread: f64,
},
OuterGlow {
color: Color,
blur: f64,
spread: f64,
},
InnerGlow {
color: Color,
blur: f64,
/// How far the glow grows into the content before it softens.
choke: f64,
source: GlowSource,
},
Satin {
color: Color,
/// How far each of the two casts of the silhouette is moved, in opposite directions.
offset: DVec2,
blur: f64,
invert: bool,
},
Outline {
color: Color,
weight: f64,
align: StrokeAlign,
},
BevelAndEmboss {
style: BevelStyle,
/// How steep the slopes are, as a percentage.
depth: f64,
direction: BevelDirection,
/// How wide the slopes are.
size: f64,
/// How much the highlights and shadows are blurred.
soften: f64,
/// The direction the light comes from, in degrees counterclockwise from the right.
angle: f64,
/// How high the light is above the surface, in degrees from flat to straight overhead.
altitude: f64,
highlight_color: Color,
shadow_color: Color,
},
/// Paints over the content with a paint other than a solid color, since a solid one decodes into the color overlay adjustment instead.
PaintOverlay {
/// Placed in the space the content's item is, or fitted to the content's bounds if it's a gradient or image without its own placement.
paint: Graphic,
blend_mode: BlendMode,
/// Percent.
opacity: f64,
},
Adjustment(Adjustment),
}
impl EffectOperation {
/// The operation an effect of this kind carries out when its row gives none of its parameters, matching the defaults of the node that stamps it.
pub fn default_for(kind: EffectKind) -> Self {
Effect(Item::new_from_element(kind)).operation()
}
pub fn kind(&self) -> EffectKind {
match self {
Self::Blur { .. } => EffectKind::Blur,
Self::DropShadow { .. } => EffectKind::DropShadow,
Self::InnerShadow { .. } => EffectKind::InnerShadow,
Self::OuterGlow { .. } => EffectKind::OuterGlow,
Self::InnerGlow { .. } => EffectKind::InnerGlow,
Self::Satin { .. } => EffectKind::Satin,
Self::Outline { .. } => EffectKind::Outline,
Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss,
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
Self::Adjustment(adjustment) => adjustment.kind(),
}
}
/// How far past the content this operation can paint, or reads from, in document pixels.
pub fn reach(&self) -> f64 {
// A Gaussian is negligible past three standard deviations
match self {
Self::Blur { radius, .. } => 3. * radius.max(0.),
Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.),
Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.),
Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.),
Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.),
Self::Outline { weight, .. } => weight.max(0.),
Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)),
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
}
}
/// An operation of this kind with arbitrary parameters, for a visitor to fill in.
fn placeholder(kind: EffectKind) -> Self {
match kind {
EffectKind::Blur => Self::Blur {
radius: 0.,
box_blur: false,
gamma: false,
},
EffectKind::DropShadow => Self::DropShadow {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
spread: 0.,
},
EffectKind::InnerShadow => Self::InnerShadow {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
spread: 0.,
},
EffectKind::OuterGlow => Self::OuterGlow {
color: Color::TRANSPARENT,
blur: 0.,
spread: 0.,
},
EffectKind::InnerGlow => Self::InnerGlow {
color: Color::TRANSPARENT,
blur: 0.,
choke: 0.,
source: GlowSource::default(),
},
EffectKind::Satin => Self::Satin {
color: Color::TRANSPARENT,
offset: DVec2::ZERO,
blur: 0.,
invert: false,
},
EffectKind::Outline => Self::Outline {
color: Color::TRANSPARENT,
weight: 0.,
align: StrokeAlign::default(),
},
EffectKind::BevelAndEmboss => Self::BevelAndEmboss {
style: BevelStyle::default(),
depth: 0.,
direction: BevelDirection::default(),
size: 0.,
soften: 0.,
angle: 0.,
altitude: 0.,
highlight_color: Color::TRANSPARENT,
shadow_color: Color::TRANSPARENT,
},
EffectKind::PaintOverlay => Self::PaintOverlay {
paint: Graphic::default(),
blend_mode: BlendMode::default(),
opacity: 0.,
},
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
brightness: 0.,
contrast: 0.,
use_classic: false,
classic_pivot: 0.,
}),
EffectKind::Levels => Self::Adjustment(Adjustment::Levels(Default::default())),
EffectKind::Curves => Self::Adjustment(Adjustment::Curves(Default::default())),
EffectKind::BlackAndWhite => Self::Adjustment(Adjustment::BlackAndWhite(Default::default())),
EffectKind::HueSaturation => Self::Adjustment(Adjustment::HueSaturation(Default::default())),
EffectKind::Invert => Self::Adjustment(Adjustment::Invert),
EffectKind::Threshold => Self::Adjustment(Adjustment::Threshold { min_luminance: 0., max_luminance: 0. }),
EffectKind::GradientMap => Self::Adjustment(Adjustment::GradientMap {
gradient: Default::default(),
reverse: false,
}),
EffectKind::Vibrance => Self::Adjustment(Adjustment::Vibrance { vibrance: 0., saturation: 0. }),
EffectKind::ChannelMixer => Self::Adjustment(Adjustment::ChannelMixer(Default::default())),
EffectKind::SelectiveColor => Self::Adjustment(Adjustment::SelectiveColor(Default::default())),
EffectKind::Posterize => Self::Adjustment(Adjustment::Posterize { levels: 0 }),
EffectKind::Exposure => Self::Adjustment(Adjustment::Exposure {
exposure: 0.,
offset: 0.,
gamma_correction: 0.,
}),
EffectKind::ColorBalance => Self::Adjustment(Adjustment::ColorBalance(Default::default())),
EffectKind::PhotoFilter => Self::Adjustment(Adjustment::PhotoFilter {
color: Color::TRANSPARENT,
density: 0.,
preserve_luminosity: false,
}),
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
}
}
/// Visits each parameter with the attribute it rides and its implicit default, the one listing that writing and reading rows share.
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
match self {
Self::Blur { radius, box_blur, gamma } => {
visitor.parameter("radius", radius, 0.);
visitor.parameter("box_blur", box_blur, false);
visitor.parameter("gamma", gamma, false);
}
Self::DropShadow { color, offset, blur, spread } | Self::InnerShadow { color, offset, blur, spread } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
visitor.parameter("offset", offset, DVec2::splat(4.));
visitor.parameter("blur", blur, 4.);
visitor.parameter("spread", spread, 0.);
}
Self::OuterGlow { color, blur, spread } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
visitor.parameter("blur", blur, 8.);
visitor.parameter("spread", spread, 0.);
}
Self::InnerGlow { color, blur, choke, source } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf)));
visitor.parameter("blur", blur, 8.);
visitor.parameter("choke", choke, 0.);
visitor.parameter("source", source, GlowSource::default());
}
Self::Satin { color, offset, blur, invert } => {
visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80)));
visitor.parameter("offset", offset, DVec2::new(10., 4.));
visitor.parameter("blur", blur, 14.);
visitor.parameter("invert", invert, true);
}
Self::Outline { color, weight, align } => {
visitor.parameter("color", color, Color::BLACK);
visitor.parameter("weight", weight, 3.);
visitor.parameter("align", align, StrokeAlign::Outside);
}
Self::BevelAndEmboss {
style,
depth,
direction,
size,
soften,
angle,
altitude,
highlight_color,
shadow_color,
} => {
visitor.parameter("style", style, BevelStyle::default());
visitor.parameter("depth", depth, 100.);
visitor.parameter("direction", direction, BevelDirection::default());
visitor.parameter("size", size, 5.);
visitor.parameter("soften", soften, 0.);
visitor.parameter("angle", angle, 120.);
visitor.parameter("altitude", altitude, 30.);
visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf)));
visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf)));
}
Self::PaintOverlay { paint, blend_mode, opacity } => {
visitor.parameter("paint", paint, Graphic::from(Color::BLACK));
visitor.parameter("blend_mode", blend_mode, BlendMode::default());
visitor.parameter("opacity", opacity, 100.);
}
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
}
}
}
/// What a value needs to ride an attribute.
pub(crate) trait ParameterValue: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static {}
impl<T: Clone + Send + Sync + Default + Debug + PartialEq + CacheHash + 'static> ParameterValue for T {}
/// Handles each parameter of an operation, given the attribute key it rides and its implicit default.
pub(crate) trait ParameterVisitor {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T);
}
/// Stamps each parameter that differs from its default onto a row.
struct WriteParameters<'a>(&'a mut Item<EffectKind>);
impl ParameterVisitor for WriteParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
if *value != default {
self.0.set_attribute(key, value.clone());
}
}
}
/// Reads each parameter from a row, or its default where the row lacks it.
struct ReadParameters<'a>(&'a Item<EffectKind>);
impl ParameterVisitor for ReadParameters<'_> {
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
*value = self.0.attribute::<T>(key).cloned().unwrap_or(default);
}
}
#[cfg(test)]
mod tests {
use super::*;
use vector_types::{Gradient, GradientStop};
#[test]
fn rows_round_trip_their_operations_eliding_defaults() {
let operations = [
EffectOperation::Blur {
radius: 6.,
box_blur: true,
gamma: false,
},
EffectOperation::default_for(EffectKind::DropShadow),
EffectOperation::InnerShadow {
color: Color::RED,
offset: DVec2::new(-2., 3.),
blur: 1.,
spread: 5.,
},
EffectOperation::OuterGlow {
color: Color::BLUE,
blur: 8.,
spread: 2.,
},
EffectOperation::InnerGlow {
color: Color::GREEN,
blur: 3.,
choke: 1.,
source: GlowSource::Center,
},
EffectOperation::Satin {
color: Color::BLACK,
offset: DVec2::new(5., -6.),
blur: 2.,
invert: false,
},
EffectOperation::Outline {
color: Color::RED,
weight: 7.,
align: StrokeAlign::Center,
},
EffectOperation::BevelAndEmboss {
style: BevelStyle::PillowEmboss,
depth: 250.,
direction: BevelDirection::Down,
size: 12.,
soften: 2.,
angle: -45.,
altitude: 60.,
highlight_color: Color::YELLOW,
shadow_color: Color::BLUE,
},
EffectOperation::PaintOverlay {
paint: Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
position,
midpoint: 0.5,
color: Color::from_rgbaf32_unchecked(position as f32, 0., 1., 1.),
}))),
blend_mode: BlendMode::Multiply,
opacity: 60.,
},
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::GREEN,
blend_mode: BlendMode::Screen,
opacity: 100.,
}),
];
for operation in operations {
assert_eq!(Effect::new(&operation).operation(), operation);
}
// A solid paint decodes into the color overlay adjustment, which the Paint Overlay row also carries
let solid = EffectOperation::PaintOverlay {
paint: Graphic::from(Color::RED),
blend_mode: BlendMode::Normal,
opacity: 50.,
};
let solid_row = Effect::new(&solid);
assert_eq!(solid_row.kind(), EffectKind::PaintOverlay);
assert_eq!(
solid_row.operation(),
EffectOperation::Adjustment(Adjustment::ColorOverlay {
color: Color::RED,
blend_mode: BlendMode::Normal,
opacity: 50.,
})
);
let default_row = Effect::new(&EffectOperation::default_for(EffectKind::DropShadow));
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
}
#[test]
fn adjustment_rows_elide_their_defaults_and_name_grouped_parameters() {
use EffectKind::*;
let kinds = [
Desaturate,
GammaCorrection,
MakeOpaque,
BrightnessContrast,
Levels,
Curves,
BlackAndWhite,
HueSaturation,
Invert,
Threshold,
GradientMap,
Vibrance,
ChannelMixer,
SelectiveColor,
Posterize,
Exposure,
ColorBalance,
PhotoFilter,
ColorLookup,
PaintOverlay,
];
for kind in kinds {
let operation = EffectOperation::default_for(kind);
assert_eq!(operation.kind(), kind);
assert_eq!(Effect::new(&operation).0.attributes().iter_any().count(), 0, "{kind} stamps no defaults");
}
// A parameter in one of the node's groups rides the attribute named with the group's prefix
let mut levels = EffectOperation::default_for(Levels);
if let EffectOperation::Adjustment(Adjustment::Levels(settings)) = &mut levels {
settings.blue.midtones = 1.5;
}
let row = Effect::new(&levels);
assert_eq!(row.0.attribute::<f64>("blue_midtones"), Some(&1.5));
assert_eq!(row.operation(), levels);
}
}
@@ -0,0 +1,117 @@
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
use core_types::graphene_hash::CacheHash;
/// Style of noise pattern.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum NoiseType {
#[default]
Perlin,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2S")]
OpenSimplex2S,
Cellular,
ValueCubic,
Value,
WhiteNoise,
}
/// Style of layered levels of the noise pattern.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum FractalType {
#[default]
None,
#[label("Fractional Brownian Motion")]
FBm,
Ridged,
PingPong,
#[label("Progressive (Domain Warp Only)")]
DomainWarpProgressive,
#[label("Independent (Domain Warp Only)")]
DomainWarpIndependent,
}
/// Distance function used by the cellular noise.
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum CellularDistanceFunction {
#[default]
Euclidean,
#[label("Euclidean Squared (Faster)")]
EuclideanSq,
Manhattan,
Hybrid,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
pub enum CellularReturnType {
CellValue,
#[default]
#[label("Nearest (F1)")]
Nearest,
#[label("Next Nearest (F2)")]
NextNearest,
#[label("Average (F1 / 2 + F2 / 2)")]
Average,
#[label("Difference (F2 - F1)")]
Difference,
#[label("Product (F2 * F1 / 2)")]
Product,
#[label("Division (F1 / F2)")]
Division,
}
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(dyn_any::DynAny)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, node_macro::ChoiceType)]
#[widget(Dropdown)]
pub enum DomainWarpType {
#[default]
None,
#[label("OpenSimplex2")]
OpenSimplex2,
#[label("OpenSimplex2 Reduced")]
OpenSimplex2Reduced,
BasicGrid,
}
/// The settings of a noise pattern, whose lengths are measured in the document units of the space it's sampled in.
#[derive(Debug, Clone, PartialEq, CacheHash)]
pub struct NoiseSettings {
pub seed: i64,
pub scale: f64,
pub noise_type: NoiseType,
pub domain_warp_type: DomainWarpType,
pub domain_warp_amplitude: f64,
pub fractal_type: FractalType,
pub fractal_octaves: i64,
pub fractal_lacunarity: f64,
pub fractal_gain: f64,
pub fractal_weighted_strength: f64,
pub fractal_ping_pong_strength: f64,
pub cellular_distance_function: CellularDistanceFunction,
pub cellular_return_type: CellularReturnType,
pub cellular_jitter: f64,
}
/// A procedural pattern, a function of position in its own space that renders across any area at any resolution.
#[derive(Debug, Clone, PartialEq, CacheHash)]
pub enum GeneratorPattern {
Noise(NoiseSettings),
/// The Mandelbrot set, with the unit square spanning -2 to 1 along the real axis and -1.5 to 1.5 along the imaginary axis.
Mandelbrot,
}
@@ -2,7 +2,7 @@ use crate::appearance::{Appearance, Cover, Coverage};
use brush_types::Stroke;
use core_types::bounds::{BoundingBox, RenderBoundingBox};
use core_types::graphene_hash::CacheHash;
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, AttributeTypeConflictError, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::list::{ATTR_APPEARANCE, ATTR_PAINT, Item, ItemAttributeValues, List, NodeIdPath};
use core_types::math::quad::Quad;
use core_types::none;
use core_types::ops::FromAnchorPosition;
@@ -180,16 +180,15 @@ pub fn is_lone_anonymous_leaf(content: &List<Graphic>) -> bool {
/// Deeply flattens a `List<Graphic>`, collecting only elements matching a specific variant (extracted by `extract_variant`)
/// and discarding all other non-matching content. Recursion through `Graphic::GraphicList` sub-`List`s composes transforms and opacity.
/// Also gives the first attribute that the flattened lists have with values of different types.
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> (List<T>, Option<AttributeTypeConflictError>) {
fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) -> List<T> {
// Its list is already the flat answer, so hand it back rather than rebuilding it item by item
if is_lone_anonymous_leaf(&content) {
let Some(item) = content.into_iter().next() else { return (List::new(), None) };
let Some(item) = content.into_iter().next() else { return List::new() };
return (extract_variant(item.into_element()).unwrap_or_default(), None);
return extract_variant(item.into_element()).unwrap_or_default();
}
fn flatten_recursive<T: Clone>(output: &mut List<T>, conflict: &mut Option<AttributeTypeConflictError>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
fn flatten_recursive<T: Clone>(output: &mut List<T>, current_graphic_list: List<Graphic>, extract_variant: fn(Graphic) -> Option<List<T>>) {
for current_graphic_item in current_graphic_list.into_iter() {
// Whether the parent carries each composed attribute: a structural fact (attribute presence), never a value comparison.
// Flattening composes a parent attribute onto its children only when the parent has it,
@@ -245,7 +244,7 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
}
flatten_recursive(output, conflict, sub_list, extract_variant);
flatten_recursive(output, sub_list, extract_variant);
}
// Extract the target variant and push its items, composing the parent's attributes onto each
other => {
@@ -274,9 +273,7 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
item.set_attribute(ATTR_APPEARANCE, appearance.clone());
}
if let Some(item_conflict) = output.push(item) {
conflict.get_or_insert(item_conflict);
}
output.push(item);
}
}
}
@@ -285,9 +282,8 @@ fn flatten_graphic_list<T: Clone>(content: List<Graphic>, extract_variant: fn(Gr
}
let mut output = List::new();
let mut conflict = None;
flatten_recursive(&mut output, &mut conflict, content, extract_variant);
(output, conflict)
flatten_recursive(&mut output, content, extract_variant);
output
}
/// Whether a normalized paint graphic list actually carries renderable paint.
@@ -364,6 +360,16 @@ impl TryFromGraphic for Raster<CPU> {
}
}
impl TryFromGraphic for Raster<GPU> {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
Graphic::RasterGPU(item) => Some(List::new_from_item(item)),
Graphic::RasterGPUList(list) => Some(list),
_ => None,
}
}
}
impl TryFromGraphic for Color {
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
match graphic {
@@ -409,19 +415,7 @@ pub trait IntoGraphicList: Clone + Send + Sync + Default + std::fmt::Debug + Par
where
Self: std::marker::Sized,
{
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic).0
}
/// Deeply flattens any content of type `T`, failing with the flattened list and the first attribute that holds values of different
/// types in the flattened lists (their later items hold the first type's default).
fn try_into_flattened_list<T: TryFromGraphic>(self) -> Result<List<T>, (List<T>, AttributeTypeConflictError)>
where
Self: std::marker::Sized,
{
match flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic) {
(list, None) => Ok(list),
(list, Some(conflict)) => Err((list, conflict)),
}
flatten_graphic_list(self.into_graphic_list(), T::try_from_graphic)
}
}
@@ -1065,27 +1059,6 @@ mod tests {
assert_eq!(color_of(1), Some(Color::WHITE), "a padded item should inherit the parent appearance");
}
// Flattening lists that hold an attribute with different types keeps the first type, and says which attribute lost values
#[test]
fn flatten_reports_an_attribute_holding_different_types() {
let tagged = |value: Item<Vector>| Item::new_from_element(Graphic::VectorList(List::new_from_item(value)));
let mut graphics = List::new();
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
graphics.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", String::from("two"))));
let Err((flattened, conflict)) = graphics.clone().try_into_flattened_list::<Vector>() else {
panic!("expected the conflicting tag to be reported")
};
assert_eq!(conflict.name, "tag");
assert_eq!(flattened, graphics.clone().into_flattened_list::<Vector>());
assert_eq!(flattened.attribute::<f64>("tag", 1), Some(&0.));
let mut matching = List::new();
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 1_f64)));
matching.push(tagged(Item::new_from_element(Vector::default()).with_attribute("tag", 2_f64)));
assert!(matching.try_into_flattened_list::<Vector>().is_ok());
}
#[test]
fn embedded_item_keeps_its_attributes_inside_the_variant() {
let color = Item::new_from_element(Color::RED).with_attribute(ATTR_POSITION, 0.25_f64);
@@ -1,5 +1,8 @@
pub mod adjustment;
pub mod appearance;
pub mod artboard;
pub mod effects;
pub mod generator;
pub mod graphic;
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
@@ -8,8 +11,10 @@ pub use raster_types;
pub use vector_types;
// Re-export commonly used types at the crate root
pub use adjustment::Adjustment;
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
pub use artboard::Artboard;
pub use effects::{BevelDirection, BevelStyle, Effect, EffectKind, EffectOperation, Effects, GlowSource, fitted_paint, stamp_effect};
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
pub mod migrations {
@@ -1,70 +0,0 @@
[package]
name = "no-std-types"
description = "no_std types for Graphene (shader-compatible)"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[features]
# any feature that
# * must be usable in shaders
# * but requires std
# * and should be on by default
# should be in this list instead of `[workspace.dependency]`
std = [
"dep:dyn-any",
"dep:graphene-hash",
"dep:serde",
"dep:log",
"glam/debug-glam-assert",
"glam/std",
"glam/serde",
"half/std",
"half/serde",
"num-traits/std",
"num_enum/std",
]
wasm = ["tsify", "wasm-bindgen"]
[dependencies]
# Local dependencies
node-macro = { workspace = true }
# Local std dependencies
dyn-any = { workspace = true, optional = true }
graphene-hash = { workspace = true, optional = true }
# Workspace dependencies
bytemuck = { workspace = true }
glam = { workspace = true }
half = { workspace = true, default-features = false }
num-derive = { workspace = true }
num-traits = { workspace = true }
num_enum = { workspace = true }
spirv-std = { workspace = true }
# Workspace std dependencies
serde = { workspace = true, optional = true }
log = { workspace = true, optional = true }
# Workspace wasm dependencies
tsify = { workspace = true, optional = true }
wasm-bindgen = { workspace = true, optional = true }
[dev-dependencies]
core-types = { workspace = true }
[lints.rust]
# the spirv target is not in the list of common cfgs so must be added manually
unexpected_cfgs = { level = "warn", check-cfg = [
'cfg(target_arch, values("spirv"))',
] }
[package.metadata.cargo-shear]
ignored = ["core-types"]
@@ -1,9 +0,0 @@
pub trait Ctx: Clone + Send {}
impl<T: Ctx> Ctx for Option<T> {}
impl<T: Ctx + Sync> Ctx for &T {}
impl Ctx for () {}
pub trait ArcCtx: Send + Sync {}
#[cfg(feature = "std")]
impl<T: ArcCtx> Ctx for std::sync::Arc<T> {}
@@ -1,20 +0,0 @@
#![cfg_attr(not(feature = "std"), no_std)]
pub mod blending;
pub mod choice_type;
pub mod color;
pub mod context;
pub mod list;
pub mod shaders;
pub use context::Ctx;
pub use glam;
pub trait AsU32 {
fn as_u32(&self) -> u32;
}
impl AsU32 for u32 {
fn as_u32(&self) -> u32 {
*self
}
}
@@ -1,41 +0,0 @@
//! A zero-cost stand-in for `core_types::list::Item` used when node kernels are compiled for the GPU.
//!
//! Shader node kernels compile twice: under `std` against the real attribute-carrying `Item`, and under
//! `no_std` (SPIR-V) against this transparent wrapper, imported as `Item`. Only the element-access surface is
//! provided, since rust-gpu cannot allocate and attributes have no per-pixel meaning; attribute use fails the
//! shader build. It is named distinctly from `Item` so a search for the canonical type finds only that one.
/// A rank-0 wire value holding a single element, mirroring the element-access API of the real `Item`.
#[repr(transparent)]
#[derive(Copy, Clone, Debug, Default, PartialEq)]
pub struct ShaderItem<T> {
element: T,
}
impl<T> ShaderItem<T> {
/// Constructs an item with the given element.
pub fn new_from_element(element: T) -> Self {
Self { element }
}
/// Returns a shared reference to this item's element.
pub fn element(&self) -> &T {
&self.element
}
/// Returns a mutable reference to this item's element.
pub fn element_mut(&mut self) -> &mut T {
&mut self.element
}
/// Consumes this item and returns the owned element.
pub fn into_element(self) -> T {
self.element
}
}
impl<T> From<T> for ShaderItem<T> {
fn from(element: T) -> Self {
Self::new_from_element(element)
}
}
@@ -1,112 +0,0 @@
use crate::shaders::buffer_struct::BufferStruct;
macro_rules! glam_array {
($t:ty, $a:ty) => {
unsafe impl BufferStruct for $t {
type Buffer = $a;
#[inline]
fn write(from: Self) -> Self::Buffer {
<$t>::to_array(&from)
}
#[inline]
fn read(from: Self::Buffer) -> Self {
<$t>::from_array(from)
}
}
};
}
macro_rules! glam_cols_array {
($t:ty, $a:ty) => {
unsafe impl BufferStruct for $t {
type Buffer = $a;
#[inline]
fn write(from: Self) -> Self::Buffer {
<$t>::to_cols_array(&from)
}
#[inline]
fn read(from: Self::Buffer) -> Self {
<$t>::from_cols_array(&from)
}
}
};
}
glam_array!(glam::Vec2, [f32; 2]);
glam_array!(glam::Vec3, [f32; 3]);
// glam_array!(Vec3A, [f32; 4]);
glam_array!(glam::Vec4, [f32; 4]);
glam_cols_array!(glam::Mat2, [f32; 4]);
glam_cols_array!(glam::Mat3, [f32; 9]);
// glam_cols_array!(Mat3A, [f32; 4]);
glam_cols_array!(glam::Mat4, [f32; 16]);
glam_cols_array!(glam::Affine2, [f32; 6]);
glam_cols_array!(glam::Affine3A, [f32; 12]);
glam_array!(glam::DVec2, [f64; 2]);
glam_array!(glam::DVec3, [f64; 3]);
glam_array!(glam::DVec4, [f64; 4]);
glam_cols_array!(glam::DMat2, [f64; 4]);
glam_cols_array!(glam::DMat3, [f64; 9]);
glam_cols_array!(glam::DMat4, [f64; 16]);
glam_cols_array!(glam::DAffine2, [f64; 6]);
glam_cols_array!(glam::DAffine3, [f64; 12]);
glam_array!(glam::I16Vec2, [i16; 2]);
glam_array!(glam::I16Vec3, [i16; 3]);
glam_array!(glam::I16Vec4, [i16; 4]);
glam_array!(glam::U16Vec2, [u16; 2]);
glam_array!(glam::U16Vec3, [u16; 3]);
glam_array!(glam::U16Vec4, [u16; 4]);
glam_array!(glam::IVec2, [i32; 2]);
glam_array!(glam::IVec3, [i32; 3]);
glam_array!(glam::IVec4, [i32; 4]);
glam_array!(glam::UVec2, [u32; 2]);
glam_array!(glam::UVec3, [u32; 3]);
glam_array!(glam::UVec4, [u32; 4]);
glam_array!(glam::I64Vec2, [i64; 2]);
glam_array!(glam::I64Vec3, [i64; 3]);
glam_array!(glam::I64Vec4, [i64; 4]);
glam_array!(glam::U64Vec2, [u64; 2]);
glam_array!(glam::U64Vec3, [u64; 3]);
glam_array!(glam::U64Vec4, [u64; 4]);
unsafe impl BufferStruct for glam::Vec3A {
type Buffer = [f32; 4];
#[inline]
fn write(from: Self) -> Self::Buffer {
glam::Vec4::to_array(&from.extend(0.))
}
#[inline]
fn read(from: Self::Buffer) -> Self {
glam::Vec3A::from_vec4(glam::Vec4::from_array(from))
}
}
/// do NOT use slices, otherwise spirv will fail to compile
unsafe impl BufferStruct for glam::Mat3A {
type Buffer = [f32; 12];
#[inline]
fn write(from: Self) -> Self::Buffer {
let a = from.to_cols_array();
[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], 0., 0., 0.]
}
#[inline]
fn read(from: Self::Buffer) -> Self {
let a = from;
glam::Mat3A::from_cols_array(&[a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]])
}
}
@@ -1,63 +0,0 @@
//! I (@firestar99) copied this entire mod from one of my projects, as I haven't uploaded that lib to crates. Hopefully
//! rust-gpu improves and this entire thing becomes unnecessary in the future.
//!
//! https://github.com/Firestar99/nanite-at-home/tree/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/buffer-content
use bytemuck::Pod;
mod glam;
mod primitive;
/// A BufferStruct is a "parallel representation" of the original struct with some fundamental types remapped. This
/// struct hierarchy represents how data is stored in GPU Buffers, where all types must be [`Pod`] to allow
/// transmuting them to `&[u8]` with [`bytemuck`].
///
/// Notable type remappings (original: buffer):
/// * bool: u32 of 0 or 1
/// * any repr(u32) enum: u32 with remapping via [`num_enum`]
///
/// By adding `#[derive(ShaderStruct)]` to your struct (or enum), a parallel `{name}Buffer` struct is created with all
/// the members of the original struct, but with their types using the associated remapped types as specified by this
/// trait.
///
/// # Origin
/// I (@firestar99) copied this entire mod from my [Nanite-at-home] project, specifically the [buffer-content] crate
/// and the [buffer_struct] proc macro. The variant here has quite some modifications, to both cleaned up some of the
/// mistakes my implementation has and to customize it a bit for graphite.
///
/// Hopefully rust-gpu improves to the point where this remapping becomes unnecessary.
///
/// [Nanite-at-home]: https://github.com/Firestar99/nanite-at-home
/// [buffer-content]: https://github.com/Firestar99/nanite-at-home/tree/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/buffer-content
/// [buffer_struct]: https://github.com/Firestar99/nanite-at-home/blob/008dac8df656959c71efeddd2d3ddabcb801771c/rust-gpu-bindless/crates/macros/src/buffer_struct.rs
///
/// # Safety
/// The associated type Transfer must be the same on all targets. Writing followed by reading back a value must result
/// in the same value.
pub unsafe trait BufferStruct: Copy + Send + Sync + 'static {
type Buffer: Pod + Send + Sync;
fn write(from: Self) -> Self::Buffer;
fn read(from: Self::Buffer) -> Self;
}
/// Trait marking all [`BufferStruct`] whose read and write methods are identity. While [`BufferStruct`] only
/// requires `t == read(write(t))`, this trait additionally requires `t == read(t) == write(t)`. As this removes the
/// conversion requirement for writing to or reading from a buffer, one can acquire slices from buffers created of these
/// types.
///
/// Implementing this type is completely safe due to the [`Pod`] requirement.
pub trait BufferStructIdentity: Pod + Send + Sync {}
unsafe impl<T: BufferStructIdentity> BufferStruct for T {
type Buffer = Self;
fn write(from: Self) -> Self::Buffer {
from
}
fn read(from: Self::Buffer) -> Self {
from
}
}
@@ -1,134 +0,0 @@
use crate::shaders::buffer_struct::{BufferStruct, BufferStructIdentity};
use bytemuck::Pod;
use core::marker::PhantomData;
use core::num::Wrapping;
use spirv_std::arch::IndexUnchecked;
macro_rules! identity {
($t:ty) => {
impl BufferStructIdentity for $t {}
};
}
identity!(());
identity!(u8);
identity!(u16);
identity!(u32);
identity!(u64);
identity!(u128);
identity!(usize);
identity!(i8);
identity!(i16);
identity!(i32);
identity!(i64);
identity!(i128);
identity!(isize);
identity!(f32);
identity!(f64);
identity!(spirv_std::memory::Semantics);
identity!(spirv_std::ray_tracing::RayFlags);
identity!(spirv_std::indirect_command::DrawIndirectCommand);
identity!(spirv_std::indirect_command::DrawIndexedIndirectCommand);
identity!(spirv_std::indirect_command::DispatchIndirectCommand);
identity!(spirv_std::indirect_command::DrawMeshTasksIndirectCommandEXT);
identity!(spirv_std::indirect_command::TraceRaysIndirectCommandKHR);
// not pod
// identity!(spirv_std::indirect_command::TraceRaysIndirectCommand2KHR);
unsafe impl BufferStruct for bool {
type Buffer = u32;
#[inline]
fn write(from: Self) -> Self::Buffer {
from as u32
}
#[inline]
fn read(from: Self::Buffer) -> Self {
from != 0
}
}
unsafe impl<T: BufferStruct> BufferStruct for Wrapping<T>
where
// unfortunately has to be Pod, even though AnyBitPattern would be sufficient,
// due to bytemuck doing `impl<T: Pod> AnyBitPattern for T {}`
// see https://github.com/Lokathor/bytemuck/issues/164
T::Buffer: Pod,
{
type Buffer = Wrapping<T::Buffer>;
#[inline]
fn write(from: Self) -> Self::Buffer {
Wrapping(T::write(from.0))
}
#[inline]
fn read(from: Self::Buffer) -> Self {
Wrapping(T::read(from.0))
}
}
unsafe impl<T: BufferStruct + 'static> BufferStruct for PhantomData<T> {
type Buffer = PhantomData<T>;
#[inline]
fn write(_: Self) -> Self::Buffer {
PhantomData {}
}
#[inline]
fn read(_: Self::Buffer) -> Self {
PhantomData {}
}
}
/// Potential problem: you can't impl this for an array of BufferStruct, as it'll conflict with this impl due to the
/// blanket impl on all BufferStructPlain types.
unsafe impl<T: BufferStruct, const N: usize> BufferStruct for [T; N]
where
// rust-gpu does not like `[T; N].map()` nor `core::array::from_fn()` nor transmuting arrays with a const generic
// length, so for now we need to require T: Default and T::Transfer: Default for all arrays.
T: Default,
// unfortunately has to be Pod, even though AnyBitPattern would be sufficient,
// due to bytemuck doing `impl<T: Pod> AnyBitPattern for T {}`
// see https://github.com/Lokathor/bytemuck/issues/164
T::Buffer: Pod + Default,
{
type Buffer = [T::Buffer; N];
#[inline]
fn write(from: Self) -> Self::Buffer {
unsafe {
let mut ret = [T::Buffer::default(); N];
for i in 0..N {
*ret.index_unchecked_mut(i) = T::write(*from.index_unchecked(i));
}
ret
}
}
#[inline]
fn read(from: Self::Buffer) -> Self {
unsafe {
let mut ret = [T::default(); N];
for i in 0..N {
*ret.index_unchecked_mut(i) = T::read(*from.index_unchecked(i));
}
ret
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_bool() {
for x in [false, true] {
assert_eq!(x, <bool as BufferStruct>::read(<bool as BufferStruct>::write(x)));
}
}
}
@@ -1,10 +0,0 @@
//! supporting infrastructure for shaders
pub mod buffer_struct;
pub mod __private {
pub use bytemuck;
pub use glam;
pub use num_enum;
pub use spirv_std;
}
@@ -0,0 +1,26 @@
[package]
name = "raster-kernels"
description = "The GPU kernels of Graphene's raster operations, with the per-color CPU mapping of those that have one"
version.workspace = true
license.workspace = true
authors.workspace = true
edition.workspace = true
repository.workspace = true
readme.workspace = true
homepage.workspace = true
rust-version.workspace = true
publish.workspace = true
[lints]
workspace = true
[dependencies]
# Local dependencies
core-types = { workspace = true }
graphene-resource = { workspace = true }
graphic-types = { workspace = true }
vector-types = { workspace = true }
# Workspace dependencies
glam = { workspace = true }
thiserror = { workspace = true }
Loaded 100 of 235 files, more files were not shown because too many files have changed in this diff. Show more