mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f2e2c7abcd | ||
|
|
f6804d9443 | ||
|
|
5471774764 | ||
|
|
f1ca7e7ab2 | ||
|
|
07ddc86fc2 | ||
|
|
3134753d07 | ||
|
|
cece2e9957 | ||
|
|
620f8d992b | ||
|
|
db2d8625a6 | ||
|
|
c6686a65c3 | ||
|
|
455008de2e | ||
|
|
48cf345355 | ||
|
|
a102519e39 | ||
|
|
508d67f5b3 | ||
|
|
fd9da9d56c | ||
|
|
4b62b39c74 | ||
|
|
b822b64e96 | ||
|
|
617ce90276 |
No files matched your search
@@ -20,6 +20,9 @@ on:
|
||||
linux:
|
||||
description: "Linux"
|
||||
type: boolean
|
||||
flatpak:
|
||||
description: "Flatpak (with the Linux build)"
|
||||
type: boolean
|
||||
debug:
|
||||
description: "Debug build"
|
||||
type: boolean
|
||||
@@ -33,6 +36,8 @@ on:
|
||||
type: boolean
|
||||
linux:
|
||||
type: boolean
|
||||
flatpak:
|
||||
type: boolean
|
||||
debug:
|
||||
type: boolean
|
||||
checkout_repo:
|
||||
@@ -815,7 +820,7 @@ jobs:
|
||||
path: target/artifacts
|
||||
|
||||
linux:
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux
|
||||
if: (github.event_name == 'push' && github.ref != 'refs/tags/latest-stable') || inputs.linux || inputs.flatpak
|
||||
runs-on: ${{ (github.event.pull_request.head.repo.fork || (inputs.checkout_repo && inputs.checkout_repo != github.repository)) && 'ubuntu-latest' || vars.LINUX_RUNNER || 'ubuntu-latest' }}
|
||||
permissions:
|
||||
contents: read
|
||||
@@ -892,12 +897,14 @@ jobs:
|
||||
fi
|
||||
|
||||
- name: 🔧 Install Flatpak tooling
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y flatpak flatpak-builder
|
||||
flatpak --user remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 🏗 Build Flatpak
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
run: |
|
||||
nix build .#graphite-flatpak-manifest${{ inputs.debug && '-dev' || '' }}
|
||||
|
||||
@@ -914,6 +921,7 @@ jobs:
|
||||
flatpak build-bundle repo Graphite.flatpak art.graphite.Graphite --runtime-repo=https://flathub.org/repo/flathub.flatpakrepo
|
||||
|
||||
- name: 📦 Upload Flatpak package
|
||||
if: github.event_name == 'push' || inputs.flatpak
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: graphite-flatpak
|
||||
@@ -921,7 +929,7 @@ jobs:
|
||||
compression-level: 0
|
||||
|
||||
- name: 💬 Update PR comment with Flatpak artifact link
|
||||
if: github.event_name != 'push' && steps.linux-comment.outputs.comment_id
|
||||
if: inputs.flatpak && steps.linux-comment.outputs.comment_id
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
# USAGE:
|
||||
# After reviewing the code, core team members may comment on a PR with `!build` followed by optional `<target>` and `<profile>` arguments.
|
||||
# This matches the syntax of the `cargo run build` CLI command, but allows platforms to be specified.
|
||||
# This extends the syntax of the `cargo run build` CLI command, allowing several targets and specific platforms to be built at once.
|
||||
#
|
||||
# `<target>`: `web` (default), `desktop` (all platforms), or `desktop:<platforms>` (subset of `windows+mac+linux`)
|
||||
# `<target>`: any of `web`, `desktop` (all platforms), `desktop:<platforms>`, or a bare platform (`windows`, `mac`, `linux`), joined by spaces or `+` (default: `web`)
|
||||
# `flatpak` additionally packages the Linux build as a Flatpak, which `desktop` and `linux` leave out
|
||||
# `<profile>`: `release` (default) or `debug`
|
||||
#
|
||||
# Only the comment's first line is parsed, so notes may follow on the lines below it.
|
||||
#
|
||||
# Examples:
|
||||
# - !build
|
||||
# - !build debug
|
||||
# - !build desktop
|
||||
# - !build web desktop
|
||||
# - !build linux
|
||||
# - !build linux+flatpak
|
||||
# - !build desktop:windows+mac
|
||||
# - !build desktop:linux debug
|
||||
# - !build web+desktop:linux debug
|
||||
name: "!build PR Command"
|
||||
|
||||
on:
|
||||
@@ -37,6 +43,7 @@ jobs:
|
||||
windows: ${{ steps.pr_info.outputs.windows }}
|
||||
mac: ${{ steps.pr_info.outputs.mac }}
|
||||
linux: ${{ steps.pr_info.outputs.linux }}
|
||||
flatpak: ${{ steps.pr_info.outputs.flatpak }}
|
||||
debug: ${{ steps.pr_info.outputs.debug }}
|
||||
|
||||
steps:
|
||||
@@ -46,8 +53,8 @@ jobs:
|
||||
# Passed through the environment so the comment text can't inject shell syntax
|
||||
COMMENT: ${{ github.event.comment.body }}
|
||||
run: |
|
||||
# Split into space-separated words
|
||||
read -ra WORDS <<< "$COMMENT"
|
||||
# Split the first line into space-separated words (comments posted from the web UI have CRLF line endings)
|
||||
read -ra WORDS <<< "${COMMENT%%$'\r'*}"
|
||||
|
||||
# First word must be "!build"
|
||||
if [[ "${WORDS[0]}" != "!build" ]]; then
|
||||
@@ -55,49 +62,47 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Initialize build flags (web defaults to true, matching the CLI default target)
|
||||
WEB="true"
|
||||
# Initialize build flags
|
||||
WEB="false"
|
||||
WINDOWS="false"
|
||||
MAC="false"
|
||||
LINUX="false"
|
||||
FLATPAK="false"
|
||||
DEBUG="false"
|
||||
PROFILE=""
|
||||
|
||||
# Parse target (optional, defaults to `web` if omitted)
|
||||
IDX=1
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
# Target: `web` enables just the web build (already the default, but accepted explicitly)
|
||||
"web")
|
||||
((IDX++)) ;;
|
||||
# Target: `desktop` enables all three desktop platforms
|
||||
"desktop")
|
||||
WEB="false"; WINDOWS="true"; MAC="true"; LINUX="true"; ((IDX++)) ;;
|
||||
# Target: `desktop:<platforms>` enables a subset of desktop platforms, split by `+`
|
||||
desktop:*)
|
||||
WEB="false"
|
||||
PLATFORMS="${WORDS[$IDX]#desktop:}"
|
||||
IFS='+' read -ra PARTS <<< "$PLATFORMS"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
case "$PART" in
|
||||
"windows") WINDOWS="true" ;;
|
||||
"mac") MAC="true" ;;
|
||||
"linux") LINUX="true" ;;
|
||||
*) echo "::error::Unrecognized platform: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
((IDX++))
|
||||
;;
|
||||
esac
|
||||
# Every remaining word is either the profile or a `+`-separated list of targets
|
||||
for WORD in "${WORDS[@]:1}"; do
|
||||
case "$WORD" in
|
||||
"debug" | "release")
|
||||
if [[ -n "$PROFILE" ]]; then
|
||||
echo "::error::Profile given more than once: $WORD"
|
||||
exit 1
|
||||
fi
|
||||
PROFILE="$WORD"
|
||||
if [[ "$WORD" == "debug" ]]; then DEBUG="true"; fi
|
||||
continue
|
||||
;;
|
||||
esac
|
||||
|
||||
# Parse profile (optional, defaults to `release` if omitted)
|
||||
case "${WORDS[$IDX]:-}" in
|
||||
"debug") DEBUG="true"; ((IDX++)) ;;
|
||||
"release") ((IDX++)) ;;
|
||||
esac
|
||||
IFS='+' read -ra PARTS <<< "$WORD"
|
||||
for PART in "${PARTS[@]}"; do
|
||||
# In `desktop:<platforms>`, the prefix only matters on the first platform since the others are split off as bare platforms
|
||||
case "$PART" in
|
||||
"web") WEB="true" ;;
|
||||
"desktop") WINDOWS="true"; MAC="true"; LINUX="true" ;;
|
||||
"windows" | "desktop:windows") WINDOWS="true" ;;
|
||||
"mac" | "desktop:mac") MAC="true" ;;
|
||||
"linux" | "desktop:linux") LINUX="true" ;;
|
||||
"flatpak" | "desktop:flatpak") LINUX="true"; FLATPAK="true" ;;
|
||||
*) echo "::error::Unrecognized argument: $PART"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
done
|
||||
|
||||
# Reject any unexpected trailing words
|
||||
if [[ $IDX -lt ${#WORDS[@]} ]]; then
|
||||
echo "::error::Unexpected argument: ${WORDS[$IDX]}"
|
||||
exit 1
|
||||
# Without any target, build for web to match the CLI default target
|
||||
if [[ "$WEB$WINDOWS$MAC$LINUX" != *true* ]]; then
|
||||
WEB="true"
|
||||
fi
|
||||
|
||||
# Write parsed build flags to job outputs
|
||||
@@ -105,6 +110,7 @@ jobs:
|
||||
echo "windows=$WINDOWS" >> $GITHUB_OUTPUT
|
||||
echo "mac=$MAC" >> $GITHUB_OUTPUT
|
||||
echo "linux=$LINUX" >> $GITHUB_OUTPUT
|
||||
echo "flatpak=$FLATPAK" >> $GITHUB_OUTPUT
|
||||
echo "debug=$DEBUG" >> $GITHUB_OUTPUT
|
||||
|
||||
# Fetch the PR's head branch and repo (needed for forked PRs where the code lives in another repo)
|
||||
@@ -139,6 +145,7 @@ jobs:
|
||||
windows: ${{ needs.setup.outputs.windows == 'true' }}
|
||||
mac: ${{ needs.setup.outputs.mac == 'true' }}
|
||||
linux: ${{ needs.setup.outputs.linux == 'true' }}
|
||||
flatpak: ${{ needs.setup.outputs.flatpak == 'true' }}
|
||||
debug: ${{ needs.setup.outputs.debug == 'true' }}
|
||||
checkout_repo: ${{ needs.setup.outputs.repo }}
|
||||
checkout_ref: ${{ needs.setup.outputs.ref }}
|
||||
|
||||
Generated
+31
-7
@@ -588,6 +588,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -2664,6 +2665,7 @@ dependencies = [
|
||||
"math-nodes",
|
||||
"node-macro",
|
||||
"path-bool-nodes",
|
||||
"raster-kernels",
|
||||
"raster-nodes",
|
||||
"rendering",
|
||||
"repeat-nodes",
|
||||
@@ -2695,6 +2697,7 @@ dependencies = [
|
||||
"graphic-types",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -2710,10 +2713,12 @@ dependencies = [
|
||||
"dyn-any",
|
||||
"glam",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"node-macro",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tsify",
|
||||
"vector-types",
|
||||
"wasm-bindgen",
|
||||
]
|
||||
@@ -4161,6 +4166,7 @@ dependencies = [
|
||||
"math-parser",
|
||||
"node-macro",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
@@ -5719,6 +5725,20 @@ dependencies = [
|
||||
"rustversion",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-kernels"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"fastnoise-lite",
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "raster-nodes"
|
||||
version = "0.0.0"
|
||||
@@ -5727,18 +5747,16 @@ dependencies = [
|
||||
"color",
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"fastnoise-lite",
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-core",
|
||||
"graphene-hash",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"image",
|
||||
"ndarray",
|
||||
"node-macro",
|
||||
"num_enum",
|
||||
"rand",
|
||||
"rand_chacha",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"serde",
|
||||
"thiserror 2.0.21",
|
||||
@@ -5991,12 +6009,14 @@ dependencies = [
|
||||
"log",
|
||||
"num-traits",
|
||||
"parley",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"skrifa",
|
||||
"text-nodes",
|
||||
"usvg",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -7974,6 +7994,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"qrcodegen",
|
||||
"rand",
|
||||
"raster-kernels",
|
||||
"repeat-nodes",
|
||||
"rustc-hash 2.1.3",
|
||||
"serde",
|
||||
@@ -8034,7 +8055,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_common"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"fearless_simd",
|
||||
@@ -8049,7 +8070,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"bytemuck",
|
||||
"hashbrown 0.17.1",
|
||||
@@ -8063,7 +8084,7 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "vello_gpu_shaders"
|
||||
version = "0.3.0"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=4df331db2a02cb0f1cef4a0190dbbb2a00f4b075#4df331db2a02cb0f1cef4a0190dbbb2a00f4b075"
|
||||
source = "git+https://github.com/Keavon/vello.git?rev=41dfe98e61b6322db38301025cc7eff51d6e9844#41dfe98e61b6322db38301025cc7eff51d6e9844"
|
||||
dependencies = [
|
||||
"naga",
|
||||
"wesl",
|
||||
@@ -8524,8 +8545,11 @@ dependencies = [
|
||||
"futures",
|
||||
"glam",
|
||||
"graphene-application-io",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"raster-types",
|
||||
"rendering",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
+4
-3
@@ -95,6 +95,7 @@ core-types = { path = "node-graph/libraries/core-types" }
|
||||
raster-types = { path = "node-graph/libraries/raster-types" }
|
||||
vector-types = { path = "node-graph/libraries/vector-types" }
|
||||
graphic-types = { path = "node-graph/libraries/graphic-types" }
|
||||
raster-kernels = { path = "node-graph/libraries/raster-kernels" }
|
||||
brush-types = { path = "node-graph/libraries/brush-types" }
|
||||
rendering = { path = "node-graph/libraries/rendering" }
|
||||
brush-nodes = { path = "node-graph/nodes/brush" }
|
||||
@@ -310,6 +311,6 @@ debug = true
|
||||
[patch.crates-io]
|
||||
rfd = { git = "https://github.com/timon-schelling/rfd.git", branch = "graphite" } # TODO: Remove this once https://github.com/PolyMeilex/rfd/pull/317 is merged and released
|
||||
# TODO: Remove these once the fork's fixes are upstreamed and released
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "4df331db2a02cb0f1cef4a0190dbbb2a00f4b075" }
|
||||
vello_gpu = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_common = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
vello_gpu_shaders = { git = "https://github.com/Keavon/vello.git", rev = "41dfe98e61b6322db38301025cc7eff51d6e9844" }
|
||||
@@ -21,7 +21,7 @@ pub(crate) struct RenderState {
|
||||
ui_texture: Option<wgpu::Texture>,
|
||||
bind_group: Option<wgpu::BindGroup>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_scene: Option<VelloSceneBuilder>,
|
||||
overlays_scene: Option<VelloSceneBuilder<'static>>,
|
||||
#[derivative(Debug = "ignore")]
|
||||
overlays_canvas: VelloCanvas,
|
||||
surface_outdated: bool,
|
||||
@@ -220,7 +220,7 @@ impl RenderState {
|
||||
self.viewport_offset = offset;
|
||||
}
|
||||
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder) {
|
||||
pub(crate) fn set_overlays_scene(&mut self, scene: VelloSceneBuilder<'static>) {
|
||||
self.surface_outdated = true;
|
||||
self.overlays_scene = Some(scene);
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ pub enum DesktopFrontendMessage {
|
||||
WindowUpdateDirectInput {
|
||||
enabled: bool,
|
||||
},
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder>),
|
||||
UpdateOverlays(Box<wgpu_executor::VelloSceneBuilder<'static>>),
|
||||
PersistenceUpdatePreferences {
|
||||
preferences: Preferences,
|
||||
},
|
||||
|
||||
@@ -252,16 +252,19 @@ impl<L: Layout> Gdd<L> {
|
||||
let mut entries: std::collections::BTreeMap<String, Option<Resource>> = std::collections::BTreeMap::new();
|
||||
let directories = self.working.list_dirs("").await?;
|
||||
let has_directory = |directory: &str| directories.iter().any(|name| name == directory);
|
||||
if has_directory(self.layout.resources_dir()) {
|
||||
if flat.is_none() && has_directory(self.layout.resources_dir()) {
|
||||
entries.extend(self.working.list(self.layout.resources_dir()).await?.into_iter().map(|path| (path, None)));
|
||||
}
|
||||
for (hash, resource) in embedded_bytes {
|
||||
entries.entry(self.layout.resource_path(&hash)).or_insert(Some(resource));
|
||||
}
|
||||
|
||||
// A copy without history has no older blobs to use as bases, so each blob is written in full
|
||||
match &flat {
|
||||
Some(flat) => {
|
||||
let named = flat.registry().resources.values().filter_map(|entry| entry.hash);
|
||||
for hash in named.filter(|hash| working_copy_hashes.contains(hash)) {
|
||||
entries.insert(self.layout.resource_path(&hash), None);
|
||||
}
|
||||
for hash in flat.registry().blob_hashes() {
|
||||
let record = self.blobs.full_record(&hash).ok_or(Error::MissingResource(hash.into()))?;
|
||||
entries.insert(self.layout.blob_path(&hash), Some(Resource::new_unchecked(record, hash.into())));
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
//! Finds the path of every layer in a runtime network, once for each instance of the networks holding it.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use document_graph_storage::NodeMetadataEntry;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId, NodeNetwork};
|
||||
|
||||
/// The path of every node its metadata marks as a layer.
|
||||
pub fn layer_paths(network: &NodeNetwork, node_metadata: &[NodeMetadataEntry]) -> Vec<Vec<NodeId>> {
|
||||
let layers: HashSet<(NetworkLocation, NodeId)> = node_metadata.iter().filter(|node| node.is_layer).map(|node| (node.network, node.local_id)).collect();
|
||||
|
||||
let mut layer_paths = Vec::new();
|
||||
for_each_network_instance(network, |network_path, nested| {
|
||||
let Some(location) = network.locate(network_path) else { return };
|
||||
let nested_layers = nested.nodes.keys().filter(|node_id| layers.contains(&(location, **node_id)));
|
||||
layer_paths.extend(nested_layers.map(|node_id| [network_path, &[*node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// Visits every network with its path, once for each instance of it.
|
||||
/// A definition is not entered again from inside itself.
|
||||
pub fn for_each_network_instance(network: &NodeNetwork, mut visit: impl FnMut(&[NodeId], &NodeNetwork)) {
|
||||
let mut stack = vec![(Vec::new(), Vec::new())];
|
||||
while let Some((network_path, enclosing_definitions)) = stack.pop() {
|
||||
let Some(nested) = network.nested_network(&network_path) else { continue };
|
||||
visit(&network_path, nested);
|
||||
|
||||
for (node_id, node) in &nested.nodes {
|
||||
let mut enclosing_definitions = enclosing_definitions.clone();
|
||||
match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) if enclosing_definitions.contains(&id) => continue,
|
||||
DocumentNodeImplementation::Definition(id) => enclosing_definitions.push(id),
|
||||
DocumentNodeImplementation::Network(_) => {}
|
||||
_ => continue,
|
||||
}
|
||||
stack.push(([network_path.as_slice(), &[*node_id]].concat(), enclosing_definitions));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
const DEFINITION: NetworkId = NetworkId(9);
|
||||
|
||||
fn node_metadata(network: NetworkLocation, local_id: u64, is_layer: bool) -> NodeMetadataEntry {
|
||||
NodeMetadataEntry {
|
||||
network,
|
||||
local_id: NodeId(local_id),
|
||||
position: None,
|
||||
is_layer,
|
||||
display_name: None,
|
||||
locked: false,
|
||||
pinned: false,
|
||||
input_metadata: Vec::new(),
|
||||
output_names: Vec::new(),
|
||||
output_descriptions: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let instance = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let definition = NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), instance.clone())).into_iter().collect(),
|
||||
definitions: [(DEFINITION, definition)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let metadata = [(None, 1, true), (None, 2, false), (Some(DEFINITION), 3, true), (Some(DEFINITION), 4, false)];
|
||||
let metadata: Vec<_> = metadata.into_iter().map(|(location, local_id, is_layer)| node_metadata(location, local_id, is_layer)).collect();
|
||||
|
||||
let mut layer_paths = layer_paths(&network, &metadata);
|
||||
layer_paths.sort();
|
||||
|
||||
assert_eq!(layer_paths, vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_definition_holding_itself_is_entered_once() {
|
||||
let recursive = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(DEFINITION),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), recursive.clone())].into_iter().collect(),
|
||||
definitions: [(
|
||||
DEFINITION,
|
||||
NodeNetwork {
|
||||
nodes: [(NodeId(2), recursive)].into_iter().collect(),
|
||||
..Default::default()
|
||||
},
|
||||
)]
|
||||
.into_iter()
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut network_paths = Vec::new();
|
||||
for_each_network_instance(&network, |network_path, _| network_paths.push(network_path.to_vec()));
|
||||
|
||||
assert_eq!(network_paths, vec![vec![], vec![NodeId(1)]]);
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,8 @@ pub mod codec;
|
||||
pub mod error;
|
||||
pub mod export;
|
||||
pub mod io;
|
||||
#[cfg(feature = "conversion")]
|
||||
pub mod layers;
|
||||
pub mod layout;
|
||||
mod load;
|
||||
pub mod manifest;
|
||||
|
||||
@@ -578,6 +578,50 @@ fn export_with_history_carries_history_only_resources() {
|
||||
});
|
||||
}
|
||||
|
||||
/// An export without history leaves behind the working copy's bytes of a resource only history still names.
|
||||
#[test]
|
||||
fn export_without_history_drops_history_only_resources() {
|
||||
use document_format::{ExportFormat, ExportOptions};
|
||||
use document_graph_storage::NoMetadata;
|
||||
use graphene_resource::{DataSource, ResourceHash, ResourceId, ResourceRegistry};
|
||||
|
||||
futures::executor::block_on(async {
|
||||
let mut gdd = GddV1::create_in(empty_container(), GddV1Layout, PeerId(9), UserId(9), 0xBEEF, "ed".into(), "std".into()).unwrap_or_else(|error| panic!("create_in failed: {error:?}"));
|
||||
let byte_store = empty_byte_store();
|
||||
|
||||
let removed_payload = b"bytes of a removed resource";
|
||||
let removed_hash = ResourceHash::from(&removed_payload[..]);
|
||||
gdd.add_resource(ResourceId::new(), removed_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let kept_payload = b"bytes of a kept resource";
|
||||
let kept_hash = ResourceHash::from(&kept_payload[..]);
|
||||
let kept_id = ResourceId::new();
|
||||
gdd.add_resource(kept_id, kept_payload).unwrap_or_else(|error| panic!("add_resource failed: {error:?}"));
|
||||
|
||||
let mut resources = ResourceRegistry::new();
|
||||
resources.push_source_back(&kept_id, DataSource::Embedded);
|
||||
resources.resolve(&kept_id, kept_hash);
|
||||
gdd.commit_from_runtime(&network_referencing_resource(kept_id), &NoMetadata, &resources, &byte_store)
|
||||
.unwrap_or_else(|error| panic!("commit_from_runtime failed: {error:?}"));
|
||||
|
||||
assert!(gdd.has_resource(&removed_hash).await, "the working copy should still hold the removed resource's bytes");
|
||||
|
||||
let options = ExportOptions {
|
||||
include_history: false,
|
||||
..Default::default()
|
||||
};
|
||||
let archive = gdd
|
||||
.export_to_bytes(ExportFormat::Zip, options, &byte_store, None)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("export failed: {error:?}"));
|
||||
let reopened = GddV1::open_from_archive(&archive, empty_container(), GddV1Layout)
|
||||
.await
|
||||
.unwrap_or_else(|error| panic!("reopen failed: {error:?}"));
|
||||
assert!(reopened.has_resource(&kept_hash).await, "bytes the registry names should travel with the export");
|
||||
assert!(!reopened.has_resource(&removed_hash).await, "history-only bytes should stay behind");
|
||||
});
|
||||
}
|
||||
|
||||
/// A document with un-retired hot ops (e.g. a freshly converted document saved without an interaction
|
||||
/// boundary, or a save mid-drag) must export losslessly: the hot log travels alongside history and the
|
||||
/// reopened document reflects the staged edits. Regression for the converted-artwork "no history"
|
||||
|
||||
@@ -8,14 +8,12 @@ use std::collections::{BTreeMap, btree_map};
|
||||
pub mod attr;
|
||||
|
||||
/// Unified storage-side position. The valid variants depend on `attr::node::ui::IS_LAYER`:
|
||||
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute`, `Chain`, or `Relative`.
|
||||
/// layers use `Absolute` or `Stack`; non-layer nodes use `Absolute` or `Chain`.
|
||||
#[derive(Copy, Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Position {
|
||||
Absolute([i32; 2]),
|
||||
Chain,
|
||||
Stack(u32),
|
||||
/// An offset from the top left corner of the bounding box of the positions of the nodes reading this one.
|
||||
Relative([i32; 2]),
|
||||
}
|
||||
|
||||
impl AttributeValue {
|
||||
|
||||
@@ -5,7 +5,7 @@ use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{PeerId, UserId};
|
||||
use graph_craft::application_io::resource::ResourceHash;
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use peer_transport::{Room, SyncTarget};
|
||||
|
||||
pub use document_format::Error as FormatError;
|
||||
@@ -97,10 +97,12 @@ impl LiveDocument {
|
||||
&mut self.gdd
|
||||
}
|
||||
|
||||
pub async fn network(&self) -> Result<NodeNetwork, LiveError> {
|
||||
/// The document's runtime network, with the path of every layer in it.
|
||||
pub async fn network_with_layers(&self) -> Result<(NodeNetwork, Vec<Vec<NodeId>>), LiveError> {
|
||||
let declarations = self.gdd.declarations(&self.gdd).await;
|
||||
let (network, _metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
Ok(network)
|
||||
let (network, node_metadata) = self.gdd.registry().to_runtime_with_metadata(&declarations, self.gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &node_metadata);
|
||||
Ok((network, layers))
|
||||
}
|
||||
|
||||
pub fn leave(&mut self) {
|
||||
|
||||
+115
-4
@@ -5,7 +5,8 @@ use document_container::archive::ArchiveFormat;
|
||||
use document_container::backends::memory::MemoryBackend;
|
||||
use document_format::{GddV1, GddV1Layout};
|
||||
use document_graph_storage::{NetworkMetadataEntry, NodeMetadataEntry};
|
||||
use graph_craft::document::NodeNetwork;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
|
||||
@@ -17,6 +18,8 @@ use migration_nodes as _;
|
||||
/// A document's runtime network, with the file it was opened from.
|
||||
pub struct LoadedDocument {
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`, once for each instance of the networks holding it.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
pub origin: DocumentOrigin,
|
||||
}
|
||||
|
||||
@@ -58,9 +61,13 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let named_gdd = path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case("gdd"));
|
||||
if !named_gdd && ArchiveFormat::detect(&bytes).is_none() {
|
||||
let document_string = String::from_utf8(bytes).map_err(|error| format!("Document {} is neither a .gdd archive nor text: {error}", path.display()))?;
|
||||
let network = legacy_network(&document_string).map_err(|error| format!("Failed to parse legacy document {}: {error}", path.display()))?;
|
||||
let parse_error = |error| format!("Failed to parse legacy document {}: {error}", path.display());
|
||||
let document: serde_json::Value = serde_json::from_str(&document_string).map_err(parse_error)?;
|
||||
let network = legacy_network(&document).map_err(parse_error)?;
|
||||
let layers = legacy_layer_paths(&network, &document);
|
||||
return Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Legacy(document_string),
|
||||
});
|
||||
}
|
||||
@@ -68,14 +75,118 @@ pub async fn open_document(path: &Path) -> Result<LoadedDocument, Box<dyn Error>
|
||||
let gdd = open_gdd(&bytes).await?;
|
||||
let declarations = gdd.declarations(&gdd).await;
|
||||
let (network, nodes, networks) = gdd.registry().to_runtime_with_full_metadata(&declarations, gdd.blobs())?;
|
||||
let layers = document_format::layers::layer_paths(&network, &nodes);
|
||||
Ok(LoadedDocument {
|
||||
network,
|
||||
layers,
|
||||
origin: DocumentOrigin::Gdd { gdd: Box::new(gdd), nodes, networks },
|
||||
})
|
||||
}
|
||||
|
||||
fn legacy_network(document_string: &str) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let document: serde_json::Value = serde_json::from_str(document_string)?;
|
||||
fn legacy_network(document: &serde_json::Value) -> Result<NodeNetwork, serde_json::Error> {
|
||||
let network = document["network_interface"]["network"].to_string();
|
||||
serde_json::from_str(&network)
|
||||
}
|
||||
|
||||
/// The path of every node a legacy document's metadata marks as a layer.
|
||||
fn legacy_layer_paths(network: &NodeNetwork, document: &serde_json::Value) -> Vec<Vec<NodeId>> {
|
||||
let mut layer_paths = Vec::new();
|
||||
document_format::layers::for_each_network_instance(network, |network_path, _| {
|
||||
let Some(network_metadata) = legacy_network_metadata(network, document, network_path) else {
|
||||
return;
|
||||
};
|
||||
let is_layer = |node_metadata: &serde_json::Value| node_metadata["node_type_metadata"]["Layer"].is_object();
|
||||
let layers = legacy_node_metadata(network_metadata).into_iter().filter(|(_, node_metadata)| is_layer(node_metadata));
|
||||
layer_paths.extend(layers.map(|(node_id, _)| [network_path, &[node_id]].concat()));
|
||||
});
|
||||
layer_paths
|
||||
}
|
||||
|
||||
/// The metadata of the network at this path in a legacy document.
|
||||
/// Older documents keep a held network's metadata inside its node's metadata, newer ones keep a definition's in a table.
|
||||
fn legacy_network_metadata<'a>(network: &NodeNetwork, document: &'a serde_json::Value, network_path: &[NodeId]) -> Option<&'a serde_json::Value> {
|
||||
let document_network_metadata = &document["network_interface"]["network_metadata"];
|
||||
let definitions = &document_network_metadata["persistent_metadata"]["definitions"];
|
||||
|
||||
let mut current = network;
|
||||
let mut network_metadata = document_network_metadata;
|
||||
for node_id in network_path {
|
||||
let node = current.nodes.get(node_id)?;
|
||||
network_metadata = match node.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => &definitions[id.0.to_string()],
|
||||
DocumentNodeImplementation::Network(_) => &legacy_node_metadata(network_metadata).remove(node_id)?["network_metadata"],
|
||||
_ => return None,
|
||||
};
|
||||
current = network.implementation_network(&node.implementation)?;
|
||||
}
|
||||
|
||||
Some(network_metadata)
|
||||
}
|
||||
|
||||
/// The metadata of each node in a legacy network, by ID.
|
||||
fn legacy_node_metadata(network_metadata: &serde_json::Value) -> HashMap<NodeId, &serde_json::Value> {
|
||||
let entries = network_metadata["persistent_metadata"]["node_metadata"].as_array().into_iter().flatten();
|
||||
entries.filter_map(|entry| Some((NodeId(entry[0].as_u64()?), &entry[1]["persistent_metadata"]))).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::{DocumentNode, NetworkId};
|
||||
|
||||
fn node(implementation: DocumentNodeImplementation) -> DocumentNode {
|
||||
DocumentNode { implementation, ..Default::default() }
|
||||
}
|
||||
|
||||
/// A network holding the nodes 3 and 4.
|
||||
fn inner_network() -> NodeNetwork {
|
||||
NodeNetwork {
|
||||
nodes: [3, 4].map(|id| (NodeId(id), DocumentNode::default())).into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn sorted_legacy_layer_paths(network: &NodeNetwork, document: &str) -> Vec<Vec<NodeId>> {
|
||||
let document = serde_json::from_str(document).expect("The test document should be valid JSON");
|
||||
let mut layer_paths = legacy_layer_paths(network, &document);
|
||||
layer_paths.sort();
|
||||
layer_paths
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_definition_is_found_through_each_instance() {
|
||||
let definition = NetworkId(9);
|
||||
let network = NodeNetwork {
|
||||
nodes: [1, 2].map(|id| (NodeId(id), node(DocumentNodeImplementation::Definition(definition)))).into_iter().collect(),
|
||||
definitions: [(definition, inner_network())].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [2, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]],
|
||||
"definitions": { "9": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} } }
|
||||
} } } }"#;
|
||||
|
||||
let expected = vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)], vec![NodeId(2), NodeId(3)]];
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_inside_a_held_network_is_found() {
|
||||
let network = NodeNetwork {
|
||||
nodes: [(NodeId(1), node(DocumentNodeImplementation::Network(inner_network())))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let document = r#"{ "network_interface": { "network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[1, { "persistent_metadata": {
|
||||
"node_type_metadata": { "Layer": {} },
|
||||
"network_metadata": { "persistent_metadata": {
|
||||
"node_metadata": [[3, { "persistent_metadata": { "node_type_metadata": { "Layer": {} } } }], [4, { "persistent_metadata": { "node_type_metadata": { "Node": {} } } }]]
|
||||
} }
|
||||
} }]]
|
||||
} } } }"#;
|
||||
|
||||
assert_eq!(sorted_legacy_layer_paths(&network, document), vec![vec![NodeId(1)], vec![NodeId(1), NodeId(3)]]);
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ mod tests {
|
||||
use crate::CompilerHost;
|
||||
use document_graph_storage::attr::node::ui::POSITION;
|
||||
use document_graph_storage::{NodeId, Position, TimeStamp, Value, to_value};
|
||||
use migration_core::{CHAIN_WIDTH, Declaration, FEEDER_ROW_HEIGHT};
|
||||
use migration_core::Declaration;
|
||||
use migration_runner::testing::{Fixture, Random, SourceContract, check_commutation_with, check_undo_with};
|
||||
|
||||
const COPY_TO_POINTS: Declaration = decl!("core_types::vector::CopyToPointsNode"@1);
|
||||
@@ -319,7 +319,7 @@ mod tests {
|
||||
};
|
||||
|
||||
assert_eq!(stages, [-1, 6, 13].map(|x| Some(Position::Absolute([x, 10]))));
|
||||
assert_eq!(position_of(group), Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
|
||||
assert_eq!(position_of(group), Some(Position::Absolute([-8, 13])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod renames;
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Node, migration};
|
||||
|
||||
/// 'Color Overlay' became the 'Paint Overlay' effect, which takes its color as a solid paint. A name it stored as its default would misname it.
|
||||
#[migration("raster_nodes::blending_nodes::ColorOverlayNode"@1 => "blending_nodes::effects::PaintOverlayNode"@2)]
|
||||
pub fn paint_overlay_from_color_overlay(node: &Node, attributes: &mut Attributes) {
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Color Overlay") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
let contract = SourceContract {
|
||||
display_names: &["Color Overlay"],
|
||||
..SourceContract::new(4, |random, _| literal(random.below(10) as f64))
|
||||
};
|
||||
check_commutation(&PaintOverlayFromColorOverlay, &contract);
|
||||
check_undo(&PaintOverlayFromColorOverlay, &contract);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Color Overlay", None), ("Tint", Some("Tint"))] {
|
||||
let mut fixture = Fixture::new(&PaintOverlayFromColorOverlay);
|
||||
let overlay = fixture.add(decl!("raster_nodes::blending_nodes::ColorOverlayNode"@1), Vec::new());
|
||||
let attributes = fixture.registry.node_instances.get_mut(&overlay).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&PaintOverlayFromColorOverlay).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@2)));
|
||||
assert_eq!(migrated.node_instances[&overlay].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
//! Nodes that only moved to a new identifier.
|
||||
|
||||
use migration_core::rename;
|
||||
|
||||
rename!("raster_nodes::filter::BlurNode"@1 => "blending_nodes::effects::BlurNode"@2);
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Node migrations, in a module per node crate and a file per step, each registering itself. Scaffold one with
|
||||
//! `cargo run migration new <identifier>` after bumping a node's `version(N)`.
|
||||
|
||||
mod blending_nodes;
|
||||
mod graphene_core;
|
||||
mod math_nodes;
|
||||
mod raster_nodes;
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
use migration_core::attr::node::ui::DISPLAY_NAME;
|
||||
use migration_core::{Attributes, Inputs, MigrationError, Node, literal, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration uses.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
GradientForm(GradientForm),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum GradientForm {
|
||||
Linear,
|
||||
Radial,
|
||||
}
|
||||
|
||||
const FORM: u32 = 1;
|
||||
|
||||
/// 'Gradient Form' became 'Gradient Curvature', whose start and end curvatures take the presets of the form it set: 0 and 0 for linear, 1 and 0.5 for
|
||||
/// radial. A wired form becomes linear, and a name it stored as its default is cleared.
|
||||
#[migration("math_nodes::GradientFormNode"@1 => "math_nodes::GradientCurvatureNode"@2)]
|
||||
pub fn gradient_curvature_from_gradient_form(node: &Node, inputs: &mut Inputs, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let [_, form] = node.inputs() else {
|
||||
return Err(MigrationError::invariant("Gradient Form has two inputs"));
|
||||
};
|
||||
let [start, end] = match literal_of::<Tagged>(&form.input) {
|
||||
Some(Tagged::GradientForm(GradientForm::Radial)) => [1., 0.5],
|
||||
_ => [0., 0.],
|
||||
};
|
||||
|
||||
inputs.set(FORM, literal(Tagged::Number(start)));
|
||||
inputs.push(literal(Tagged::Number(end)));
|
||||
|
||||
if node.attributes().get_typed::<String>(DISPLAY_NAME).as_deref() == Some("Gradient Form") {
|
||||
attributes.remove(node.id(), DISPLAY_NAME);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::TimeStamp;
|
||||
use migration_core::{NodeInput, decl};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn form(form: GradientForm) -> NodeInput {
|
||||
literal(Tagged::GradientForm(form))
|
||||
}
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
display_names: &["Gradient Form"],
|
||||
..SourceContract::new(2, |random, slot| match slot {
|
||||
1 if random.below(2) == 0 => form(GradientForm::Radial),
|
||||
1 => form(GradientForm::Linear),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&GradientCurvatureFromGradientForm, &contract());
|
||||
check_undo(&GradientCurvatureFromGradientForm, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forms_become_their_curvature_presets() {
|
||||
let gradient = literal(Tagged::Number(0.));
|
||||
for (old_form, [start, end]) in [
|
||||
(form(GradientForm::Linear), [0., 0.]),
|
||||
(form(GradientForm::Radial), [1., 0.5]),
|
||||
(NodeInput::Import { index: 0 }, [0., 0.]),
|
||||
] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![gradient.clone(), old_form]);
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, node), Some(decl!("math_nodes::GradientCurvatureNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, node), [gradient.clone(), literal(Tagged::Number(start)), literal(Tagged::Number(end))]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_old_default_name_is_cleared() {
|
||||
for (name, kept) in [("Gradient Form", None), ("Spotlight", Some("Spotlight"))] {
|
||||
let mut fixture = Fixture::new(&GradientCurvatureFromGradientForm);
|
||||
let node = fixture.add(decl!("math_nodes::GradientFormNode"@1), vec![literal(Tagged::Number(0.)), form(GradientForm::Linear)]);
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(DISPLAY_NAME, &name, TimeStamp::ORIGIN).unwrap();
|
||||
|
||||
let migrated = fixture.migrate(&GradientCurvatureFromGradientForm).unwrap();
|
||||
|
||||
assert_eq!(migrated.node_instances[&node].attributes().get_typed::<String>(DISPLAY_NAME).as_deref(), kept);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
//! Migrations of the nodes in `math_nodes`.
|
||||
|
||||
mod gradient_curvature_from_gradient_form;
|
||||
mod math_formula_from_math_f;
|
||||
mod renames;
|
||||
@@ -0,0 +1,104 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, Node, decl, literal, migration};
|
||||
|
||||
/// The pattern fills the plane rather than being cut off at the unit square, so it's read through that square filled with it, and the node gained a
|
||||
/// primary input.
|
||||
#[migration("raster_nodes::std_nodes::MandelbrotNode"@1 => @2)]
|
||||
pub fn mandelbrot_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) {
|
||||
inputs.insert(0, literal(Tagged::None));
|
||||
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 1.);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use document_graph_storage::{ROOT_NETWORK, TimeStamp};
|
||||
use migration_core::attr::node::ui::{IS_LAYER, POSITION};
|
||||
use migration_core::{NodeInput, Position};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(0, |_, _| literal(Tagged::None))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&MandelbrotV1, &contract());
|
||||
check_undo(&MandelbrotV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_export_reads_a_unit_square_filled_with_the_pattern() {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
fixture.export(NodeInput::Node { id: mandelbrot, index: 0 });
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, mandelbrot), [literal(Tagged::None)]);
|
||||
|
||||
let Some(NodeInput::Node { id: placement, .. }) = migrated.networks[&ROOT_NETWORK].exports[0].target else {
|
||||
panic!("the export should read a node")
|
||||
};
|
||||
assert_eq!(fixture.declaration_of(&migrated, placement), Some(decl!("transform_nodes::transform_nodes::TransformNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([0.5, 0.5])));
|
||||
}
|
||||
|
||||
/// The positions of the pattern, its paint, the rectangle, the fill, and the placement after migrating a pattern at `position`.
|
||||
fn placed_square(position: Position, layer: Option<[i32; 2]>) -> [Option<Position>; 5] {
|
||||
let mut fixture = Fixture::new(&MandelbrotV1);
|
||||
let mandelbrot = fixture.add(decl!("raster_nodes::std_nodes::MandelbrotNode"@1), Vec::new());
|
||||
let place = |fixture: &mut Fixture, node, position: Position| {
|
||||
let attributes = fixture.registry.node_instances.get_mut(&node).unwrap().attributes_mut();
|
||||
attributes.set_serialized(POSITION, &position, TimeStamp::ORIGIN).unwrap();
|
||||
};
|
||||
place(&mut fixture, mandelbrot, position);
|
||||
|
||||
let reader = match layer {
|
||||
Some(layer_position) => {
|
||||
let layer = fixture.add(decl!("graphic_nodes::layer"@1), vec![literal(Tagged::None), NodeInput::Node { id: mandelbrot, index: 0 }]);
|
||||
place(&mut fixture, layer, Position::Absolute(layer_position));
|
||||
let attributes = fixture.registry.node_instances.get_mut(&layer).unwrap().attributes_mut();
|
||||
attributes.set_serialized(IS_LAYER, &true, TimeStamp::ORIGIN).unwrap();
|
||||
layer
|
||||
}
|
||||
None => fixture.add(decl!("migration_testing::consumer"@1), vec![NodeInput::Node { id: mandelbrot, index: 0 }]),
|
||||
};
|
||||
|
||||
let migrated = fixture.migrate(&MandelbrotV1).unwrap();
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(reader, if layer.is_some() { 1 } else { 0 });
|
||||
let fill = reads(placement, 0);
|
||||
let (rectangle, paint) = (reads(fill, 0), reads(fill, 1));
|
||||
|
||||
[mandelbrot, paint, rectangle, fill, placement].map(|node| migrated.node_instances[&node].attributes().get_typed::<Position>(POSITION))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chained_pattern_gives_its_place_to_the_filled_rectangle() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Chain, Some([30, 10]));
|
||||
|
||||
assert_eq!([rectangle, fill, placement], [Some(Position::Chain); 3]);
|
||||
assert_eq!(pattern, Some(Position::Absolute([0, 0])));
|
||||
assert_eq!(paint, Some(Position::Absolute([7, 0])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placed_pattern_gets_its_square_to_the_right() {
|
||||
let [pattern, paint, rectangle, fill, placement] = placed_square(Position::Absolute([5, 5]), None);
|
||||
|
||||
assert_eq!(pattern, Some(Position::Absolute([5, 5])));
|
||||
assert_eq!(paint, Some(Position::Absolute([12, 5])));
|
||||
assert_eq!(rectangle, Some(Position::Absolute([12, 2])));
|
||||
assert_eq!(fill, Some(Position::Absolute([19, 5])));
|
||||
assert_eq!(placement, Some(Position::Absolute([26, 5])));
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Migrations of the nodes in `raster_nodes`.
|
||||
|
||||
mod mandelbrot_v1;
|
||||
mod mix_colors_from_mix_node;
|
||||
mod noise_pattern_v1;
|
||||
mod pattern_square;
|
||||
mod renames;
|
||||
@@ -0,0 +1,97 @@
|
||||
use super::pattern_square::{SquareNodes, Tagged, fill_square_with_pattern};
|
||||
use migration_core::{Attributes, Downstream, Inputs, MigrationError, Node, decl, literal_of, migration};
|
||||
|
||||
const CLIP: u32 = 1;
|
||||
|
||||
/// The pattern fills the plane, so the Clip toggle that cut it off at a 100-unit square is gone, and a clipped pattern is read through that square
|
||||
/// filled with it. A wired toggle counts as clipped.
|
||||
#[migration("raster_nodes::std_nodes::NoisePatternNode"@1 => @2)]
|
||||
pub fn noise_pattern_v1(node: &Node, inputs: &mut Inputs, downstream: &mut Downstream, attributes: &mut Attributes) -> Result<(), MigrationError> {
|
||||
let Some(clip) = node.inputs().get(CLIP as usize) else {
|
||||
return Err(MigrationError::invariant("Noise Pattern has a Clip input"));
|
||||
};
|
||||
let clipped = !matches!(literal_of::<Tagged>(&clip.input), Some(Tagged::Bool(false)));
|
||||
|
||||
inputs.remove(CLIP);
|
||||
|
||||
if clipped {
|
||||
let nodes = SquareNodes {
|
||||
rectangle: decl!("vector_nodes::generator_nodes::RectangleNode"@1),
|
||||
fill: decl!("graphene_core::vector::FillNode"@1),
|
||||
transform: decl!("transform_nodes::transform_nodes::TransformNode"@1),
|
||||
};
|
||||
fill_square_with_pattern(node, downstream, attributes, nodes, 100.);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{Declaration, NodeInput, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const NOISE_PATTERN: Declaration = decl!("raster_nodes::std_nodes::NoisePatternNode"@1);
|
||||
const CONSUMER: Declaration = decl!("migration_testing::consumer"@1);
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract {
|
||||
// The toggle a clipped pattern's readers move off of can't be reading that pattern, since its own migration removes it
|
||||
reads_own_output: |slot| slot != CLIP as usize,
|
||||
..SourceContract::new(16, |random, slot| match slot {
|
||||
1 => literal(Tagged::Bool(random.below(2) == 0)),
|
||||
_ => literal(Tagged::Number(random.below(10) as f64)),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn noise_inputs(clip: bool) -> Vec<NodeInput> {
|
||||
let mut inputs: Vec<NodeInput> = (0..16).map(|slot| literal(Tagged::Number(slot as f64))).collect();
|
||||
inputs[CLIP as usize] = literal(Tagged::Bool(clip));
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&NoisePatternV1, &contract());
|
||||
check_undo(&NoisePatternV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clipped_pattern_is_read_through_a_square_filled_with_it() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(true));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
// The settings after the removed toggle move down a slot
|
||||
let inputs = fixture.inputs(&migrated, noise);
|
||||
assert_eq!(inputs.len(), 15);
|
||||
assert_eq!(inputs[CLIP as usize], literal(Tagged::Number(2.)));
|
||||
|
||||
let reads = |node, slot: usize| match fixture.inputs(&migrated, node)[slot] {
|
||||
NodeInput::Node { id, .. } => id,
|
||||
_ => panic!("slot {slot} of {node:?} should read a node"),
|
||||
};
|
||||
let placement = reads(consumer, 0);
|
||||
let fill = reads(placement, 0);
|
||||
let paint = reads(fill, 1);
|
||||
assert_eq!(reads(paint, 0), noise);
|
||||
assert_eq!(fixture.declaration_of(&migrated, reads(fill, 0)), Some(decl!("vector_nodes::generator_nodes::RectangleNode"@1)));
|
||||
assert_eq!(fixture.inputs(&migrated, placement)[1], literal(Tagged::DVec2([50., 50.])));
|
||||
assert_eq!(fixture.inputs(&migrated, paint)[1], literal(Tagged::DVec2([-50., -50.])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unclipped_pattern_keeps_its_readers() {
|
||||
let mut fixture = Fixture::new(&NoisePatternV1);
|
||||
let noise = fixture.add(NOISE_PATTERN, noise_inputs(false));
|
||||
let consumer = fixture.add(CONSUMER, vec![NodeInput::Node { id: noise, index: 0 }]);
|
||||
let migrated = fixture.migrate(&NoisePatternV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.inputs(&migrated, noise).len(), 15);
|
||||
assert_eq!(fixture.inputs(&migrated, consumer), [NodeInput::Node { id: noise, index: 0 }]);
|
||||
assert_eq!(migrated.node_instances.len(), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
//! The square that Noise Pattern and Mandelbrot were cut off at before their patterns filled the plane, which their migrations keep.
|
||||
|
||||
use migration_core::attr::node::ui::POSITION;
|
||||
use migration_core::{Attributes, Declaration, Downstream, NewNode, Node, NodeInput, OutputConnector, Position, literal};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants these migrations use.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum Tagged {
|
||||
None,
|
||||
Number(f64),
|
||||
Bool(bool),
|
||||
BoxCorners(Vec<f64>),
|
||||
Color(Color),
|
||||
GradientRamp(GradientRamp),
|
||||
GradientForm(GradientForm),
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct Color {
|
||||
red: f32,
|
||||
green: f32,
|
||||
blue: f32,
|
||||
alpha: f32,
|
||||
linear: bool,
|
||||
}
|
||||
|
||||
impl Color {
|
||||
fn new(red: f32, green: f32, blue: f32, alpha: f32) -> Self {
|
||||
Self {
|
||||
red,
|
||||
green,
|
||||
blue,
|
||||
alpha,
|
||||
linear: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientRamp {
|
||||
stops: GradientStops,
|
||||
gradient_space: GradientSpace,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) struct GradientStops {
|
||||
color: Vec<Color>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientSpace {
|
||||
OkLab,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub(super) enum GradientForm {
|
||||
Linear,
|
||||
}
|
||||
|
||||
/// The declarations the square is built from, which each migration names itself so the runner orders it against them.
|
||||
pub(super) struct SquareNodes {
|
||||
pub rectangle: Declaration,
|
||||
pub fill: Declaration,
|
||||
pub transform: Declaration,
|
||||
}
|
||||
|
||||
/// Makes everything reading the pattern read a rectangle filled with it instead, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
pub(super) fn fill_square_with_pattern(node: &Node, downstream: &mut Downstream, attributes: &mut Attributes, nodes: SquareNodes, size: f64) {
|
||||
let consumers = downstream.consumers(0);
|
||||
if consumers.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let number = |number| literal(Tagged::Number(number));
|
||||
let pair = |value| literal(Tagged::DVec2([value, value]));
|
||||
let wire = |id| NodeInput::Node { id, index: 0 };
|
||||
let transform = |content, translation| vec![content, pair(translation), number(0.), pair(1.), pair(0.)];
|
||||
|
||||
let rectangle = downstream.add_node(NewNode {
|
||||
declaration: nodes.rectangle,
|
||||
inputs: vec![
|
||||
literal(Tagged::None),
|
||||
number(size),
|
||||
number(size),
|
||||
literal(Tagged::BoxCorners(Vec::new())),
|
||||
literal(Tagged::Bool(true)),
|
||||
literal(Tagged::Bool(false)),
|
||||
],
|
||||
});
|
||||
let paint = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(node.id()), -size / 2.),
|
||||
},
|
||||
"paint",
|
||||
);
|
||||
|
||||
// Past the rectangle and its paint, the Fill holds the defaults its definition gives a new node
|
||||
let backup_gradient = GradientRamp {
|
||||
stops: GradientStops {
|
||||
color: vec![Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)],
|
||||
},
|
||||
gradient_space: GradientSpace::OkLab,
|
||||
};
|
||||
let fill = downstream.add_node(NewNode {
|
||||
declaration: nodes.fill,
|
||||
inputs: vec![
|
||||
wire(rectangle),
|
||||
wire(paint),
|
||||
literal(Tagged::Color(Color::new(0., 0., 0., 0.))),
|
||||
literal(Tagged::GradientRamp(backup_gradient)),
|
||||
literal(Tagged::GradientForm(GradientForm::Linear)),
|
||||
literal(Tagged::Bool(false)),
|
||||
literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||
],
|
||||
});
|
||||
|
||||
let placement = downstream.add_node_keyed(
|
||||
NewNode {
|
||||
declaration: nodes.transform,
|
||||
inputs: transform(wire(fill), size / 2.),
|
||||
},
|
||||
"placement",
|
||||
);
|
||||
for consumer in consumers {
|
||||
downstream.connect(OutputConnector { node: placement, output: 0 }, consumer);
|
||||
}
|
||||
|
||||
// In a layer's chain, the filled rectangle takes the pattern's place. The pattern and its paint leave the chain with no coordinates to go by,
|
||||
// so they start at the graph's origin. Elsewhere the square sits to the pattern's right.
|
||||
let stored = node.attributes().get_typed::<Position>(POSITION);
|
||||
if stored == Some(Position::Chain) {
|
||||
for id in [placement, fill, rectangle] {
|
||||
attributes.set(id, POSITION, &Position::Chain);
|
||||
}
|
||||
|
||||
attributes.set(node.id(), POSITION, &Position::Absolute([0, 0]));
|
||||
attributes.set(paint, POSITION, &Position::Absolute([7, 0]));
|
||||
} else {
|
||||
let [x, y] = match stored {
|
||||
Some(Position::Absolute(coordinates)) => coordinates,
|
||||
_ => [0, 0],
|
||||
};
|
||||
for (id, [x_offset, y_offset]) in [(paint, [7, 0]), (rectangle, [7, -3]), (fill, [14, 0]), (placement, [21, 0])] {
|
||||
attributes.set(id, POSITION, &Position::Absolute([x + x_offset, y + y_offset]));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -335,8 +335,8 @@ fn add_nodes(target: &mut Registry, runs: &[(NodeId, Edits)], resolver: &dyn Dec
|
||||
}
|
||||
|
||||
/// Default positions for the nodes one run adds, read from the anchor's own position only. The nodes leading up to the anchor's
|
||||
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits relative to the nodes reading it,
|
||||
/// below the first one of this run that does, or on the anchor when nothing reads it.
|
||||
/// chain input form a row, or join the chain of a chained or layer anchor. Each other node sits below the first one reading it,
|
||||
/// or on the anchor when none does. Without absolute coordinates for the anchor, only the chain is placed.
|
||||
fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
|
||||
let Some(anchor_node) = target.node_instances.get(&anchor) else { return };
|
||||
let stored = anchor_node.attributes().get_typed::<Position>(POSITION);
|
||||
@@ -375,26 +375,22 @@ fn place_added_nodes(target: &mut Registry, anchor: NodeId, edits: &Edits) {
|
||||
}
|
||||
}
|
||||
|
||||
let readers: Vec<(NodeId, &[NodeInput])> = std::iter::once((anchor, anchor_inputs.as_slice()))
|
||||
.chain(edits.added_nodes.iter().map(|added| (added.id, added.node.inputs.as_slice())))
|
||||
.collect();
|
||||
let mut feeders_below: HashMap<NodeId, i32> = HashMap::new();
|
||||
if let Some([x, y]) = coordinates {
|
||||
let readers: Vec<(&[NodeInput], i32)> = std::iter::once((anchor_inputs.as_slice(), x))
|
||||
.chain(chain.iter().enumerate().map(|(step, id)| (added_inputs[id], x - CHAIN_WIDTH * (step as i32 + 1))))
|
||||
.collect();
|
||||
let mut feeders_below = vec![0; readers.len()];
|
||||
|
||||
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
|
||||
let reader = readers.iter().find(|(_, inputs)| reads(inputs, added.id)).map(|(reader, _)| *reader);
|
||||
let connected_downstream = edits.connections.iter().any(|(output, _)| output.node == added.id);
|
||||
|
||||
let position = match (reader, coordinates) {
|
||||
(Some(reader), _) => {
|
||||
let row = feeders_below.entry(reader).or_default();
|
||||
*row += 1;
|
||||
Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT * *row])
|
||||
}
|
||||
_ if connected_downstream => Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT]),
|
||||
(None, Some(coordinates)) => Position::Absolute(coordinates),
|
||||
(None, None) => continue,
|
||||
};
|
||||
positions.push((added.id, position));
|
||||
for added in edits.added_nodes.iter().filter(|added| !chain.contains(&added.id)) {
|
||||
let position = match readers.iter().position(|(inputs, _)| reads(inputs, added.id)) {
|
||||
Some(reader) => {
|
||||
feeders_below[reader] += 1;
|
||||
[readers[reader].1 - CHAIN_WIDTH, y + FEEDER_ROW_HEIGHT * feeders_below[reader]]
|
||||
}
|
||||
None => [x, y],
|
||||
};
|
||||
positions.push((added.id, Position::Absolute(position)));
|
||||
}
|
||||
}
|
||||
|
||||
for (id, position) in positions {
|
||||
|
||||
@@ -293,11 +293,9 @@ impl Generator<'_> {
|
||||
(DISPLAY_NAME, name.map(|name| Value::Str(name.to_string())))
|
||||
}
|
||||
1 => {
|
||||
let coordinates = [self.random.below(20) as i32, self.random.below(20) as i32];
|
||||
let position = match self.random.below(4) {
|
||||
let position = match self.random.below(3) {
|
||||
0 => Position::Chain,
|
||||
1 => Position::Relative(coordinates),
|
||||
_ => Position::Absolute(coordinates),
|
||||
_ => Position::Absolute([self.random.below(20) as i32, self.random.below(20) as i32]),
|
||||
};
|
||||
(POSITION, Some(to_value(&position).expect("positions serialize")))
|
||||
}
|
||||
|
||||
@@ -114,7 +114,7 @@ fn added_nodes_lead_up_to_a_placed_anchor() {
|
||||
|
||||
assert_eq!(far, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10])));
|
||||
assert_eq!(near, Some(Position::Absolute([20 - CHAIN_WIDTH, 10])));
|
||||
assert_eq!(below, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
|
||||
assert_eq!(below, Some(Position::Absolute([20 - 2 * CHAIN_WIDTH, 10 + FEEDER_ROW_HEIGHT])));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -122,7 +122,7 @@ fn added_nodes_join_a_chained_anchors_chain() {
|
||||
let [far, near, below] = placed_around(Position::Chain);
|
||||
|
||||
assert_eq!([far, near], [Some(Position::Chain); 2]);
|
||||
assert_eq!(below, Some(Position::Relative([-CHAIN_WIDTH, FEEDER_ROW_HEIGHT])));
|
||||
assert_eq!(below, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -12,7 +12,7 @@ pub(crate) struct NodeSource {
|
||||
pub version: u32,
|
||||
pub function: String,
|
||||
pub file: PathBuf,
|
||||
/// The parameters and output as written, without their attributes. Comparing it tells whether stored inputs still fit.
|
||||
/// The parameters and output as written, without their attributes or `#[data]` fields. Comparing it tells whether stored inputs still fit.
|
||||
pub signature: String,
|
||||
}
|
||||
|
||||
@@ -131,7 +131,10 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
}
|
||||
|
||||
let function_name = function.sig.ident.to_string();
|
||||
let parameters = function.sig.inputs.iter().map(|parameter| match parameter {
|
||||
|
||||
// A `#[data]` field is the node's own state rather than a stored input, so documents don't notice it changing
|
||||
let is_data_field = |parameter: &&syn::FnArg| matches!(parameter, syn::FnArg::Typed(typed) if typed.attrs.iter().any(|attribute| attribute.path().is_ident("data")));
|
||||
let parameters = function.sig.inputs.iter().filter(|parameter| !is_data_field(parameter)).map(|parameter| match parameter {
|
||||
syn::FnArg::Typed(typed) => {
|
||||
let (pattern, ty) = (&typed.pat, &typed.ty);
|
||||
quote::quote!(#pattern: #ty).to_string()
|
||||
@@ -149,3 +152,23 @@ fn node_source(function: &syn::ItemFn, file: &Path, module_path: &[String]) -> O
|
||||
signature,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_fields_are_left_out_of_the_signature() {
|
||||
let function: syn::ItemFn = syn::parse_quote! {
|
||||
#[node_macro::node(category("Raster"))]
|
||||
fn lookup(_: impl Ctx, image: Item<Color>, #[data] cache: Cache) -> Item<Color> {
|
||||
image
|
||||
}
|
||||
};
|
||||
let node = node_source(&function, Path::new("lib.rs"), &["raster_nodes".to_string()]).expect("the function is a node");
|
||||
|
||||
assert_eq!(node.identifier, "raster_nodes::LookupNode");
|
||||
assert!(!node.signature.contains("cache"), "{}", node.signature);
|
||||
assert!(node.signature.contains("image"), "{}", node.signature);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Scaffolds node migrations into `migration-nodes`, one file per step, in a module per node crate.
|
||||
|
||||
use crate::lineage::{MigrationStep, find_migrations};
|
||||
use crate::lineage::{MigrationStep, find_all_migrations};
|
||||
use crate::nodes::{NodeSource, find_nodes};
|
||||
use convert_case::{Case, Casing};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -18,7 +18,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
|
||||
match (command, arguments) {
|
||||
("new", []) => {
|
||||
let steps = missing_steps(&nodes, &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(&nodes, &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
println!("Every node version already has a migration leading to it");
|
||||
return Ok(());
|
||||
@@ -35,7 +35,7 @@ pub(crate) fn scaffold(workspace: &Path, command: &str, arguments: &[String]) ->
|
||||
));
|
||||
}
|
||||
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_migrations(&migrations)?);
|
||||
let steps = missing_steps(std::slice::from_ref(node), &find_all_migrations(workspace, &MIGRATION_CRATES)?);
|
||||
if steps.is_empty() {
|
||||
return Err(format!("migrations up to `{}`@{} already exist", node.identifier, node.version));
|
||||
}
|
||||
@@ -242,6 +242,7 @@ fn declare_module(file: &Path, module: &str) -> Result<(), String> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::lineage::find_migrations;
|
||||
|
||||
/// A workspace with one node crate and an empty `migration-nodes`, removed on drop.
|
||||
struct Workspace(PathBuf);
|
||||
@@ -329,6 +330,22 @@ mod tests {
|
||||
assert!(missing_steps(&nodes, &found).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_version_reached_from_a_compiled_migration_needs_no_step() {
|
||||
let workspace = Workspace::new("compiled");
|
||||
let compiled = workspace.0.join("document/migrations/compiled/src");
|
||||
std::fs::create_dir_all(&compiled).unwrap();
|
||||
std::fs::write(
|
||||
compiled.join("lib.rs"),
|
||||
"#[migration(\"old::Node\"@1 => \"blending_nodes::OpacityNode\"@2)]\npub fn opacity_from_node(inputs: &mut Inputs) {}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
scaffold(&workspace.0, "new", &[]).unwrap();
|
||||
assert!(!workspace.0.join(MIGRATIONS).join("blending_nodes/opacity_v1.rs").exists());
|
||||
assert!(workspace.read("legacy/brighten_v1.rs").contains("\"legacy::adjust::BrightenNode\"@1 => @2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_no_module_declares_is_no_migration() {
|
||||
let workspace = Workspace::new("undeclared");
|
||||
|
||||
@@ -987,17 +987,17 @@ mod test {
|
||||
.iter()
|
||||
.find_map(|(id, node)| (node.implementation == graph_craft::document::DocumentNodeImplementation::Definition(entry)).then_some(*id))
|
||||
.expect("the pasted layer");
|
||||
let (inner, input_index) = interface.document_network().definitions[&entry]
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface.document_network().definitions[&entry]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the entry should have a value input");
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("the entry should have an Extend node");
|
||||
let before = interface.document_network().definitions[&entry].clone();
|
||||
let NodeInput::Value { tagged_value, exposed } = &before.nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[layer]);
|
||||
|
||||
// Leaving out the stack below keeps the entry a working layer
|
||||
let no_base = NodeInput::type_default(graphene_std::list!(graphene_std::Graphic), false);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), no_base, &[layer]);
|
||||
assert_ne!(interface.document_network().definitions[&entry], before, "the edit should change the pasted entry");
|
||||
|
||||
editor.paste_from_clipboard(clipboard.clone()).await;
|
||||
|
||||
@@ -64,6 +64,9 @@ pub struct DropdownInput {
|
||||
// This uses `u32` instead of `usize` since it will be serialized as a normal JS number (we can replace this with `usize` if we switch to a Rust-based GUI)
|
||||
#[serde(rename = "selectedIndex")]
|
||||
pub selected_index: Option<u32>,
|
||||
// Shown while no entry is selected
|
||||
#[derivative(Default(value = "\"-\".to_string()"))]
|
||||
pub placeholder: String,
|
||||
#[serde(rename = "drawIcon")]
|
||||
pub draw_icon: bool,
|
||||
pub disabled: bool,
|
||||
|
||||
@@ -11,6 +11,7 @@ use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::core_types::misc::format_f64;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{INTERNAL_ATTRIBUTE_PREFIX, Item, List, NodeIdPath};
|
||||
use graphene_std::math::float_noise::round_away_float_noise;
|
||||
@@ -32,7 +33,7 @@ use graphene_std::vector::style::{
|
||||
DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin,
|
||||
};
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Graphic};
|
||||
use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -394,6 +395,7 @@ macro_rules! inspectable_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
List<i64>,
|
||||
@@ -450,6 +452,7 @@ macro_rules! inspectable_types {
|
||||
Item<Raster<GPU>>,
|
||||
Item<Color>,
|
||||
Item<Gradient>,
|
||||
Item<Generator>,
|
||||
Item<String>,
|
||||
Item<f64>,
|
||||
Item<i64>,
|
||||
@@ -792,6 +795,45 @@ impl TableItemLayout for Coverage {
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effects {
|
||||
fn type_name() -> &'static str {
|
||||
"Effects"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effects".to_string()
|
||||
}
|
||||
// The wrapping `Item` already contributes the breadcrumb; the inner list supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
// Label the spreadsheet's element button with the inner list's identifier, like Appearance
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for Effect {
|
||||
fn type_name() -> &'static str {
|
||||
"Effect"
|
||||
}
|
||||
fn identifier(&self) -> String {
|
||||
"Effect".to_string()
|
||||
}
|
||||
// The wrapping row already contributes the breadcrumb; the inner item supplies the next level
|
||||
fn layout_with_breadcrumb(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.value_page(data)
|
||||
}
|
||||
fn value_widgets(&self, target: PathStep, data: &LayoutData) -> Vec<WidgetInstance> {
|
||||
self.0.value_widgets(target, data)
|
||||
}
|
||||
fn value_page(&self, data: &mut LayoutData) -> Vec<LayoutGroup> {
|
||||
self.0.layout_with_breadcrumb(data)
|
||||
}
|
||||
}
|
||||
|
||||
impl TableItemLayout for TransferCurve {
|
||||
fn type_name() -> &'static str {
|
||||
"TransferCurve"
|
||||
@@ -857,6 +899,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.identifier(),
|
||||
Self::Color(item) => item.identifier(),
|
||||
Self::Gradient(item) => item.identifier(),
|
||||
Self::Generator(item) => item.identifier(),
|
||||
Self::Text(item) => item.identifier(),
|
||||
Self::NoneList(list) => list.identifier(),
|
||||
Self::GraphicList(list) => list.identifier(),
|
||||
@@ -865,6 +908,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.identifier(),
|
||||
Self::ColorList(list) => list.identifier(),
|
||||
Self::GradientList(list) => list.identifier(),
|
||||
Self::GeneratorList(list) => list.identifier(),
|
||||
Self::TextList(list) => list.identifier(),
|
||||
Self::StrokeList(list) => list.identifier(),
|
||||
}
|
||||
@@ -882,6 +926,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPU(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Color(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Gradient(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Generator(item) => item.layout_with_breadcrumb(data),
|
||||
Self::Text(item) => item.layout_with_breadcrumb(data),
|
||||
Self::NoneList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GraphicList(list) => list.layout_with_breadcrumb(data),
|
||||
@@ -890,6 +935,7 @@ impl TableItemLayout for Graphic {
|
||||
Self::RasterGPUList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::ColorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GradientList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::GeneratorList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::TextList(list) => list.layout_with_breadcrumb(data),
|
||||
Self::StrokeList(list) => list.layout_with_breadcrumb(data),
|
||||
}
|
||||
@@ -1213,6 +1259,11 @@ macro_rules! impl_table_item_layout_for_choice_enum {
|
||||
impl_table_item_layout_for_choice_enum!(
|
||||
BlendMode,
|
||||
Cover,
|
||||
BevelDirection,
|
||||
BevelStyle,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
@@ -1359,9 +1410,11 @@ macro_rules! known_item_types {
|
||||
List<Raster<GPU>>,
|
||||
List<Color>,
|
||||
List<Gradient>,
|
||||
List<Generator>,
|
||||
List<String>,
|
||||
List<f64>,
|
||||
Gradient,
|
||||
Generator,
|
||||
Color,
|
||||
NodeId,
|
||||
DAffine2,
|
||||
@@ -1383,6 +1436,12 @@ macro_rules! known_item_types {
|
||||
Appearance,
|
||||
Coverage,
|
||||
Cover,
|
||||
Effects,
|
||||
Effect,
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
|
||||
@@ -325,6 +325,9 @@ pub enum DocumentMessage {
|
||||
UpdateAppearanceAttributes {
|
||||
appearance_attributes: HashMap<NodeId, Arc<Appearance>>,
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
UngroupLayer {
|
||||
|
||||
@@ -1915,6 +1915,14 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished {
|
||||
return;
|
||||
@@ -2232,7 +2240,6 @@ impl DocumentMessageHandler {
|
||||
self.network_interface.validate_input_metadata(node_id, node, &path);
|
||||
self.network_interface.validate_output_names(node_id, node, &path);
|
||||
}
|
||||
self.network_interface.convert_positions_to_relative();
|
||||
|
||||
// Restoring the parallel-array invariant is how the document arrives, not an edit to it, so what the
|
||||
// fix-ups recorded must not ride along in the first real commit. They still have to reach storage,
|
||||
@@ -5070,15 +5077,11 @@ mod document_message_handler_tests {
|
||||
assert!(!base_lengths.is_empty(), "Instrumentation should have recorded at least one stack base");
|
||||
assert!(base_lengths.iter().all(|&len| len == 0), "Every stack base should be empty, found lengths {base_lengths:?}");
|
||||
|
||||
let news: Vec<graphene_std::list::List<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::List<graphene_std::Graphic>>(&editor.runtime)
|
||||
let news: Vec<graphene_std::list::Item<graphene_std::Graphic>> = instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<graphene_std::Graphic>>(&editor.runtime)
|
||||
.collect();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element list");
|
||||
let phantom_count = news
|
||||
.iter()
|
||||
.flat_map(|new| new.iter_element_values())
|
||||
.filter(|graphic| matches!(graphic, graphene_std::Graphic::None(_)))
|
||||
.count();
|
||||
assert!(!news.is_empty(), "Instrumentation should have recorded at least one stacked element");
|
||||
let phantom_count = news.iter().filter(|new| matches!(new.element(), graphene_std::Graphic::None(_))).count();
|
||||
assert_eq!(phantom_count, 0, "No stacked element should be a phantom None graphic");
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -957,10 +957,10 @@ fn set_import_child_positions(
|
||||
// Top of stack: set to `Absolute` position
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Absolute(child_pos), &[]);
|
||||
} else {
|
||||
// Below top: stack it `y_offset` below its previous sibling, based on that sibling's subtree extent
|
||||
// Below top: set `Stack` with `y_offset` based on previous sibling's subtree extent
|
||||
let prev_sibling_svg_index = n - i;
|
||||
let y_offset = child_extents_svg_order[prev_sibling_svg_index] + STACK_VERTICAL_GAP as u32;
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::stacked(y_offset), &[]);
|
||||
network_interface.set_layer_position_for_import(&child_layer.to_node(), LayerPosition::Stack(y_offset), &[]);
|
||||
}
|
||||
|
||||
// Recurse into group children to set their descendants' positions
|
||||
|
||||
@@ -761,20 +761,26 @@ impl<'a> ModifyInputsContext<'a> {
|
||||
self.responses.add(NodeGraphMessage::RunDocumentGraph);
|
||||
}
|
||||
|
||||
/// Write the Gradient Form to the last 'Gradient Form' node in the chain, inserting one only when the value differs
|
||||
/// Write the Gradient Form's curvatures to the last 'Gradient Curvature' node in the chain, inserting one only when the form differs
|
||||
/// from the default (`Linear`).
|
||||
pub fn gradient_form_set(&mut self, gradient_form: GradientForm) {
|
||||
use graphene_std::math_nodes::gradient_curvature::{EndCurvatureInput, IDENTIFIER, StartCurvatureInput};
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let Some(output_layer) = self.get_output_layer() else { return };
|
||||
|
||||
let target_input = gradient_chain_target_input(output_layer, self.network_interface);
|
||||
let identifier = graphene_std::math_nodes::gradient_form::IDENTIFIER;
|
||||
let create_if_nonexistent = gradient_form != GradientForm::default();
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, identifier, create_if_nonexistent) else {
|
||||
let Some(node_id) = self.existing_proto_node_id_at(&target_input, IDENTIFIER, create_if_nonexistent) else {
|
||||
return;
|
||||
};
|
||||
|
||||
let input_connector = InputConnector::node(node_id, graphene_std::math_nodes::gradient_form::GradientFormInput);
|
||||
self.set_input_with_refresh(input_connector, NodeInput::value(TaggedValue::GradientForm(gradient_form), false), false);
|
||||
let [start, end] = match gradient_form {
|
||||
GradientForm::Linear => LINEAR_DIALS,
|
||||
GradientForm::Radial => RADIAL_DIALS,
|
||||
};
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, StartCurvatureInput), NodeInput::value(TaggedValue::Number(start), false), false);
|
||||
self.set_input_with_refresh(InputConnector::node(node_id, EndCurvatureInput), NodeInput::value(TaggedValue::Number(end), false), false);
|
||||
}
|
||||
|
||||
/// Set the spread on the chain's gradient value, which is where the ramp carries it.
|
||||
@@ -1110,7 +1116,7 @@ pub fn set_stroke_paint_order(network_interface: &mut NodeNetworkInterface, netw
|
||||
if *was_chain {
|
||||
network_interface.set_chain_position(&node_id, network_path);
|
||||
} else if let Some(position) = position {
|
||||
network_interface.place_at(&node_id, *position, network_path);
|
||||
network_interface.set_absolute_position(&node_id, *position, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -175,44 +175,25 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeMerge"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(4), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(2), 0)],
|
||||
nodes: [
|
||||
// Primary (bottom) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::as_graphic::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -2)),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -2)),
|
||||
..Default::default()
|
||||
},
|
||||
// Secondary (left) input type coercion
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::import(generic!(T), 1)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::into_group::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 0)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -1)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(3), 0)],
|
||||
inputs: vec![NodeInput::node(NodeId(0), 0), NodeInput::node(NodeId(1), 0)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -2)),
|
||||
..Default::default()
|
||||
@@ -244,7 +225,7 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
icon: Some("NodeArtboard"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate {
|
||||
exports: vec![NodeInput::node(NodeId(3), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [
|
||||
NodeTemplate {
|
||||
call_argument: generic!(T),
|
||||
@@ -256,32 +237,13 @@ fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefi
|
||||
NodeInput::import(item!(TaggedValue), 4),
|
||||
NodeInput::import(item!(TaggedValue), 5),
|
||||
],
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Derive the parent layer's NodeId from the document path
|
||||
NodeTemplate {
|
||||
inputs: vec![NodeInput::Reflection(graph_craft::document::DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::path_of_subgraph::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-14, 3)),
|
||||
..Default::default()
|
||||
},
|
||||
// Stamp each item of the content with the parent layer's NodeId via the `editor:layer_path` attribute,
|
||||
// so editor tools (e.g. selection, click target routing) can trace data back to its owning layer.
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
NodeInput::value(TaggedValue::String(graphene_std::ATTR_EDITOR_LAYER_PATH.to_string()), false),
|
||||
NodeInput::node(NodeId(1), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::write_attribute::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(-7, -3)),
|
||||
..Default::default()
|
||||
},
|
||||
NodeTemplate {
|
||||
inputs: vec![
|
||||
NodeInput::import(graphene_std::Type::Fn(Box::new(concrete!(Context)), Box::new(list!(Artboard))), 0),
|
||||
NodeInput::node(NodeId(2), 0),
|
||||
NodeInput::node(NodeId(0), 0),
|
||||
],
|
||||
implementation: NodeTemplateImplementation::ProtoNode(graphic::extend::IDENTIFIER),
|
||||
node_type_metadata: NodeTypePersistentMetadata::node(IVec2::new(0, -4)),
|
||||
@@ -798,6 +760,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));
|
||||
|
||||
@@ -89,8 +89,6 @@ pub struct NodeGraphMessageHandler {
|
||||
pub selection_before_pointer_down: Vec<NodeId>,
|
||||
/// If the grip icon is held during a drag, then shift without pushing other nodes
|
||||
shift_without_push: bool,
|
||||
/// Whether dragging leaves the relative nodes upstream of the dragged ones where they are drawn.
|
||||
keep_upstream_in_place: bool,
|
||||
disconnecting: Option<InputConnector>,
|
||||
initial_disconnecting: bool,
|
||||
/// Node to select on pointer up if multiple nodes are selected and they were not dragged.
|
||||
@@ -1439,8 +1437,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
self.keep_upstream_in_place = ipp.keyboard.get(Key::Control as usize);
|
||||
|
||||
let mut graph_delta = IVec2::new(((point.x - drag_start.start_x) / 24.).round() as i32, ((point.y - drag_start.start_y) / 24.).round() as i32);
|
||||
let previous_round_x = drag_start.round_x;
|
||||
let previous_round_y = drag_start.round_y;
|
||||
@@ -1626,7 +1622,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
// End of dragging a node
|
||||
else if let Some((drag_start, _)) = &self.drag_start {
|
||||
self.shift_without_push = false;
|
||||
self.keep_upstream_in_place = false;
|
||||
|
||||
// Reset all offsets to end the rubber banding while dragging
|
||||
network_interface.clear_drag_offsets(selection_network_path);
|
||||
@@ -2170,7 +2165,7 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
// The shift can also push other nodes and the imports and exports, so everything it moves glides to where it lands
|
||||
let positions_before = (glide && graph_view_overlay_open).then(|| Self::glide_positions(network_interface, selection_network_path));
|
||||
|
||||
network_interface.shift_selected_nodes(direction, self.shift_without_push, self.keep_upstream_in_place, selection_network_path);
|
||||
network_interface.shift_selected_nodes(direction, self.shift_without_push, selection_network_path);
|
||||
|
||||
if !rubber_band {
|
||||
network_interface.clear_drag_offsets(selection_network_path);
|
||||
@@ -4081,7 +4076,6 @@ impl Default for NodeGraphMessageHandler {
|
||||
double_click_used_by_press: false,
|
||||
dot_drag_out: None,
|
||||
shift_without_push: false,
|
||||
keep_upstream_in_place: false,
|
||||
box_selection_start: None,
|
||||
drag_start_chain_nodes: Vec::new(),
|
||||
wire_insertion_preview: None,
|
||||
|
||||
@@ -40,7 +40,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, Graphic, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -388,6 +388,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
// ============
|
||||
// STRUCT TYPES
|
||||
// ============
|
||||
@@ -438,6 +439,9 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<BooleanOperation>(x) => enum_choice::<BooleanOperation>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<CentroidType>(x) => enum_choice::<CentroidType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DesaturateMethod>(x) => enum_choice::<DesaturateMethod>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<GlowSource>(x) => enum_choice::<GlowSource>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelStyle>(x) => enum_choice::<BevelStyle>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<BevelDirection>(x) => enum_choice::<BevelDirection>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<QRCodeErrorCorrectionLevel>(x) => enum_choice::<QRCodeErrorCorrectionLevel>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<ScaleType>(x) => enum_choice::<ScaleType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<InterpolationDistribution>(x) => enum_choice::<InterpolationDistribution>().for_socket(default_info).inspector_row(),
|
||||
@@ -1001,7 +1005,12 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
}
|
||||
}
|
||||
|
||||
let parameter_widgets_info = ParameterWidgetsInfo {
|
||||
blank_assist: false,
|
||||
..parameter_widgets_info
|
||||
};
|
||||
let ParameterWidgetsInfo {
|
||||
document_id,
|
||||
document_node,
|
||||
node_id,
|
||||
index,
|
||||
@@ -1025,8 +1034,27 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
Some(TaggedValue::TypeDefault(_)) => Font::default(),
|
||||
_ => return (first_widgets, second_widgets),
|
||||
};
|
||||
|
||||
let filters = vec![TypeFilter::font()];
|
||||
let file_drop_action = IngestAction::resource_input(document_id, node_id, index, &filters);
|
||||
let load_button = IconButton::new("FileImport", 24)
|
||||
.tooltip_label("Load Font File")
|
||||
.tooltip_description("Use a font that isn't in the list by loading its .ttf or .otf file. The font is saved with the document.")
|
||||
.on_update(move |_| {
|
||||
IngestMessage::SetResourceInput {
|
||||
document_id,
|
||||
node_id,
|
||||
input_index: index,
|
||||
filters: filters.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance();
|
||||
|
||||
{
|
||||
first_widgets.extend_from_slice(&[
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
load_button,
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
DropdownInput::new(vec![
|
||||
fonts
|
||||
@@ -1050,7 +1078,15 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
.collect::<Vec<_>>(),
|
||||
])
|
||||
.selected_index(fonts.font_catalog.iter().position(|family| family.name == font.font_family).map(|i| i as u32))
|
||||
.placeholder(font.font_family.clone())
|
||||
.virtual_scrolling(true)
|
||||
.on_file_drop(move |file| {
|
||||
IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file(PathBuf::from(&file.name), Some(file.mime_type.as_str()).filter(|mime| !mime.is_empty()), file.data.clone()).into(),
|
||||
action: file_drop_action.clone(),
|
||||
}
|
||||
.into()
|
||||
})
|
||||
.widget_instance(),
|
||||
]);
|
||||
|
||||
@@ -1094,6 +1130,7 @@ pub fn font_inputs(parameter_widgets_info: ParameterWidgetsInfo) -> (Vec<WidgetI
|
||||
})
|
||||
.map(|i| i as u32),
|
||||
)
|
||||
.placeholder(font.font_style.clone())
|
||||
.widget_instance(),
|
||||
]);
|
||||
second_widgets = Some(second_row);
|
||||
@@ -3013,6 +3050,79 @@ pub(crate) fn string_capitalization_inspector(node_id: NodeId, context: &mut Nod
|
||||
vec![capitalization, LayoutGroup::row(joiner_widgets), LayoutGroup::row(joiner_preset_buttons)]
|
||||
}
|
||||
|
||||
pub(crate) fn gradient_curvature_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::math_nodes::gradient_curvature::*;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
// The curvatures set in the panel, or `None` when either is fed from the graph, so it can't take a preset
|
||||
let curvatures = match get_document_node(node_id, context) {
|
||||
Ok(document_node) => {
|
||||
let curvature = |index: usize| match document_node.inputs.get(index).and_then(|input| input.as_non_exposed_value()) {
|
||||
Some(&TaggedValue::Number(value)) => Some(value),
|
||||
_ => None,
|
||||
};
|
||||
curvature(StartCurvatureInput::INDEX).zip(curvature(EndCurvatureInput::INDEX)).map(|(start, end)| [start, end])
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!("Could not get document node in gradient_curvature_inspector: {err}");
|
||||
return Vec::new();
|
||||
}
|
||||
};
|
||||
|
||||
// Each form's button sets both curvatures to the form's own, and stands out while they're exactly those
|
||||
let mut form = vec![
|
||||
TextLabel::new("Form")
|
||||
.tooltip_label("Form")
|
||||
.tooltip_description("Sets both curvatures to those of a standard gradient form.")
|
||||
.widget_instance(),
|
||||
];
|
||||
add_blank_assist(&mut form);
|
||||
form.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
for (label, [start, end], tooltip) in [
|
||||
("Linear", LINEAR_DIALS, "Sets both curvatures to 0, making straight contours."),
|
||||
("Radial", RADIAL_DIALS, "Sets the start curvature to 1 and the end curvature to 0.5, making circles around the start."),
|
||||
] {
|
||||
form.push(
|
||||
TextButton::new(label)
|
||||
.tooltip_description(tooltip)
|
||||
.emphasized(curvatures == Some([start, end]))
|
||||
.disabled(curvatures.is_none())
|
||||
.on_update(move |_: &TextButton| Message::Batched {
|
||||
messages: Box::new([
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: StartCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(start).into(),
|
||||
}
|
||||
.into(),
|
||||
NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: EndCurvatureInput::INDEX,
|
||||
value: TaggedValue::Number(end).into(),
|
||||
}
|
||||
.into(),
|
||||
]),
|
||||
})
|
||||
.on_commit(commit_value)
|
||||
.widget_instance(),
|
||||
);
|
||||
}
|
||||
|
||||
// The same sliders the curvatures would get without this panel
|
||||
let options = ParameterOptions {
|
||||
soft_min: Some(-1.),
|
||||
soft_max: Some(1.),
|
||||
slider: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut curvature = |index: usize| inspector_row_from_type(node_id, index, &concrete!(f64), options, context).unwrap_or_else(|rows| rows);
|
||||
|
||||
let mut layout = vec![LayoutGroup::row(form)];
|
||||
layout.extend(curvature(StartCurvatureInput::INDEX));
|
||||
layout.extend(curvature(EndCurvatureInput::INDEX));
|
||||
layout
|
||||
}
|
||||
|
||||
pub(crate) fn rectangle_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::vector::generator_nodes::rectangle::*;
|
||||
|
||||
|
||||
@@ -34,6 +34,8 @@ impl FrontendGraphDataType {
|
||||
"Gradient" => Self::Gradient,
|
||||
"String" => Self::Typography,
|
||||
"f64" | "i64" | "bool" | "DVec2" | "DAffine2" => Self::Number,
|
||||
// A generator draws pixels like an image, at whatever resolution is needed
|
||||
"Generator" => Self::Raster,
|
||||
raster if raster.starts_with("Raster") => Self::Raster,
|
||||
_ => Self::General,
|
||||
}
|
||||
|
||||
@@ -270,7 +270,7 @@ impl OverlayContext {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn take_scene(self) -> VelloSceneBuilder {
|
||||
pub fn take_scene(self) -> VelloSceneBuilder<'static> {
|
||||
let mut internal = self.internal.lock().expect("Failed to lock internal overlay context");
|
||||
let empty_scene = overlay_scene(&internal.viewport);
|
||||
std::mem::replace(&mut internal.scene, empty_scene)
|
||||
@@ -486,13 +486,13 @@ pub enum DrawHandles {
|
||||
}
|
||||
|
||||
pub(super) struct OverlayContextInternal {
|
||||
scene: VelloSceneBuilder,
|
||||
scene: VelloSceneBuilder<'static>,
|
||||
viewport: ViewportMessageHandler,
|
||||
visibility_settings: OverlaysVisibilitySettings,
|
||||
}
|
||||
|
||||
/// An empty scene covering the viewport's physical pixels, matching the resolution the viewport renders at.
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder {
|
||||
fn overlay_scene(viewport: &ViewportMessageHandler) -> VelloSceneBuilder<'static> {
|
||||
// The smallest texture size limit WebGL2 guarantees, which only matters for the overlays' tiny pattern images
|
||||
const MAX_TEXTURE_SIZE: u32 = 2048;
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::sync::Arc;
|
||||
#[derive(PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize)]
|
||||
pub enum ResourceMessage {
|
||||
StoreEmbedded { resource_id: ResourceId, data: Arc<[u8]> },
|
||||
StoreFont { resource_id: ResourceId, font: Font, data: Arc<[u8]> },
|
||||
AddFont { resource_id: ResourceId, font: Font },
|
||||
ResolveAll,
|
||||
Resolve { resource_id: ResourceId },
|
||||
|
||||
@@ -35,6 +35,20 @@ impl MessageHandler<ResourceMessage, ResourceMessageContext<'_>> for ResourceMes
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
}
|
||||
ResourceMessage::StoreFont { resource_id, font, data } => {
|
||||
let hash = ResourceHash::from(data.as_ref());
|
||||
self.registry.push_source_back(&resource_id, DataSource::Embedded);
|
||||
self.registry.push_source_back(
|
||||
&resource_id,
|
||||
DataSource::Font {
|
||||
family: font.font_family.clone(),
|
||||
style: Some(font.font_style.clone()),
|
||||
},
|
||||
);
|
||||
self.registry.resolve(&resource_id, hash);
|
||||
responses.add(ResourceStorageMessage::Store { data });
|
||||
responses.add(FontsMessage::ResourceResolved { font, hash });
|
||||
}
|
||||
ResourceMessage::AddFont { resource_id, font } => {
|
||||
let style = fonts.font_catalog.find_font_style_in_catalog(&font);
|
||||
let style_name = style.map(|style| style.to_named_style()).unwrap_or_else(|| font.font_style.clone());
|
||||
|
||||
@@ -6,6 +6,5 @@
|
||||
|
||||
mod lifecycle_tests;
|
||||
mod metadata_tests;
|
||||
mod relative_positions_tests;
|
||||
mod round_trip_tests;
|
||||
pub(crate) mod test_support;
|
||||
@@ -1,87 +0,0 @@
|
||||
//! Opening a document converts its absolute and stacked positions to positions relative to the nodes reading them, without moving any node.
|
||||
|
||||
use super::test_support::{node_paths, open_demo};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{LayerPersistentMetadata, LayerPosition, NodeLocator, NodeNetworkInterface, NodeTypePersistentMetadata};
|
||||
use glam::IVec2;
|
||||
use graphene_std::uuid::NodeId;
|
||||
|
||||
const DEMOS: [&str; 8] = [
|
||||
"changing-seasons.graphite",
|
||||
"isometric-fountain.graphite",
|
||||
"marbled-mandelbrot.graphite",
|
||||
"painted-dreams.graphite",
|
||||
"parametric-dunescape.graphite",
|
||||
"procedural-string-lights.graphite",
|
||||
"red-dress.graphite",
|
||||
"valley-of-spires.graphite",
|
||||
];
|
||||
|
||||
/// Each node in an editable network, by its network path and ID, with where it is drawn.
|
||||
type DrawnPositions = Vec<((Vec<NodeId>, NodeId), Option<IVec2>)>;
|
||||
|
||||
fn editable_positions(interface: &NodeNetworkInterface) -> DrawnPositions {
|
||||
node_paths(interface)
|
||||
.into_iter()
|
||||
.filter(|(network_path, _)| !interface.is_read_only(network_path))
|
||||
.map(|(network_path, node_id)| {
|
||||
let position = interface.position(&node_id, &network_path);
|
||||
((network_path, node_id), position)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Rewrites the converted positions the way older documents stored them, stacked layers as `Stack` and the rest as `Absolute`.
|
||||
fn revert_to_stored_positions(interface: &mut NodeNetworkInterface, positions: &DrawnPositions) {
|
||||
for ((network_path, node_id), position) in positions {
|
||||
if !interface.is_relative(node_id, network_path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let stack_offset = interface.stack_offset(node_id, network_path);
|
||||
let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) else { continue };
|
||||
match (stack_offset, position) {
|
||||
(Some(stack_offset), _) => {
|
||||
node.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Stack(stack_offset as u32),
|
||||
}));
|
||||
}
|
||||
(None, Some(position)) => {
|
||||
node.set_absolute_position(*position);
|
||||
}
|
||||
(None, None) => {}
|
||||
}
|
||||
interface.invalidate_position(node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_a_demo_makes_every_read_node_relative_where_it_was_drawn() {
|
||||
for demo in DEMOS {
|
||||
let mut document = open_demo(demo);
|
||||
let interface = &mut document.network_interface;
|
||||
|
||||
let converted = editable_positions(interface);
|
||||
assert!(converted.iter().all(|(_, position)| position.is_some()), "{demo}: every node should resolve a position");
|
||||
|
||||
for ((network_path, node_id), _) in &converted {
|
||||
let read_by_a_node = interface
|
||||
.with_outward_wires(network_path, |outward_wires| {
|
||||
outward_wires
|
||||
.iter()
|
||||
.any(|(output, readers)| output.node_id() == Some(*node_id) && readers.iter().any(|reader| reader.node_id().is_some()))
|
||||
})
|
||||
.unwrap_or_default();
|
||||
assert!(
|
||||
!read_by_a_node || !interface.is_absolute(node_id, network_path),
|
||||
"{demo}: node {node_id} is read by another node, so it should be relative"
|
||||
);
|
||||
}
|
||||
|
||||
revert_to_stored_positions(interface, &converted);
|
||||
interface.convert_positions_to_relative();
|
||||
|
||||
let reconverted = editable_positions(interface);
|
||||
let moved: Vec<_> = converted.iter().zip(&reconverted).filter(|(before, after)| before != after).collect();
|
||||
assert!(moved.is_empty(), "{demo}: converting should leave every node where it was drawn, but moved {moved:?}");
|
||||
}
|
||||
}
|
||||
@@ -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.));
|
||||
}
|
||||
|
||||
|
||||
@@ -141,7 +141,7 @@ impl NodeNetworkInterface {
|
||||
for layer in &selected_layers {
|
||||
let mut current_node = *layer;
|
||||
loop {
|
||||
if self.is_layer(¤t_node, network_path) && !self.is_stack(¤t_node, network_path) {
|
||||
if self.is_layer(¤t_node, network_path) && self.is_absolute(¤t_node, network_path) {
|
||||
stack_tops.insert(current_node);
|
||||
break;
|
||||
};
|
||||
|
||||
+16
-173
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition, NodeTemplate,
|
||||
NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, NodeNetworkInterface, NodeNetworkTemplate, NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata,
|
||||
OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
@@ -278,7 +278,7 @@ async fn a_dot_on_a_stack_wire_leaves_the_layer_beneath_it_where_it_was() {
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert_eq!(feeding(&editor, upper), Some(OutputConnector::node(dot, 0)), "the dot should feed the upper layer");
|
||||
assert_eq!(feeding(&editor, dot), Some(OutputConnector::node(lower, 0)), "the lower layer should feed the dot");
|
||||
assert!(!network_interface.is_stack(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
|
||||
assert!(network_interface.is_absolute(&lower, &[]), "a layer feeding a dot rather than a layer is no longer stacked");
|
||||
assert_eq!(network_interface.position(&lower, &[]), lower_position, "the lower layer shouldn't move");
|
||||
assert_invariants(&editor, "after putting a dot on a stack wire");
|
||||
}
|
||||
@@ -315,163 +315,6 @@ fn fill_definition() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let lower_reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
|
||||
let upper_reader = editor.create_node_by_name_at(fill_definition(), 30, 4).await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
for reader in [lower_reader, upper_reader] {
|
||||
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
|
||||
}
|
||||
let relative = NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(-7, 3))));
|
||||
network_interface.node_mut(NodeLocator::new(node, &[])).expect("the node exists").set_node_type(relative);
|
||||
network_interface.invalidate_position(&node, &[]);
|
||||
|
||||
// The offset applies to the top left corner of the box around both readers
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||
|
||||
network_interface.disconnect_input(&InputConnector::primary_input(upper_reader), &[]);
|
||||
assert!(network_interface.is_relative(&node, &[]), "A node still read by another node should stay relative");
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
|
||||
|
||||
network_interface.disconnect_input(&InputConnector::primary_input(lower_reader), &[]);
|
||||
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader should be pinned where it was drawn");
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 13)));
|
||||
|
||||
assert_invariants(&editor, "after a relative node loses its readers");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_connected_node_stays_where_it_is_drawn_and_follows_a_rewire() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
|
||||
let other_reader = editor.create_node_by_name_at(fill_definition(), 40, 30).await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 0, 0).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
|
||||
assert!(network_interface.is_relative(&node, &[]), "A node gaining its first reader should become relative to it");
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(0, 0)));
|
||||
|
||||
// Rewiring keeps the offset, so the node moves beside its new reader
|
||||
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(other_reader), &[]);
|
||||
network_interface.disconnect_input(&InputConnector::primary_input(reader), &[]);
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(20, 20)));
|
||||
|
||||
assert_invariants(&editor, "after connecting and rewiring a relative node");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn deleting_the_only_reader_of_a_relative_node_pins_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
|
||||
let node = editor.create_node_by_name_at(rectangle_definition(), 10, 10).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
|
||||
network_interface.delete_nodes(vec![reader], false, &[]);
|
||||
assert!(network_interface.is_absolute(&node, &[]), "A node losing its last reader to a delete should be pinned");
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 10)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dragging_a_node_carries_its_upstream_unless_it_is_kept_in_place() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let reader = editor.create_node_by_name_at(fill_definition(), 20, 10).await;
|
||||
let node = editor.create_node_by_name_at(fill_definition(), 10, 10).await;
|
||||
let source = editor.create_node_by_name_at(rectangle_definition(), 0, 10).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
network_interface.create_wire(&OutputConnector::primary_output(node), &InputConnector::primary_input(reader), &[]);
|
||||
network_interface.create_wire(&OutputConnector::primary_output(source), &InputConnector::primary_input(node), &[]);
|
||||
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![reader]);
|
||||
|
||||
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(10, 11)), "The node read by the dragged one should follow it");
|
||||
assert_eq!(network_interface.position(&source, &[]), Some(IVec2::new(0, 11)), "Everything upstream should follow too");
|
||||
|
||||
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
|
||||
assert_eq!(network_interface.position(&reader, &[]), Some(IVec2::new(20, 12)));
|
||||
assert_eq!(
|
||||
network_interface.position(&node, &[]),
|
||||
Some(IVec2::new(10, 11)),
|
||||
"Keeping the upstream in place should leave the node where it was drawn"
|
||||
);
|
||||
assert_eq!(
|
||||
network_interface.position(&source, &[]),
|
||||
Some(IVec2::new(0, 11)),
|
||||
"Keeping the upstream in place should leave its upstream too"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after dragging a node with and without its upstream");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_chain_node_out_of_its_chain_carries_its_upstream() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, near, far, source, outside) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
assert!(network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]), "fixture is wrong");
|
||||
let [far_before, source_before, outside_before] = [far, source, outside].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
|
||||
|
||||
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
|
||||
network_interface.shift_selected_nodes(Direction::Down, true, false, &[]);
|
||||
|
||||
assert!(!network_interface.is_chain(&far, &[]), "The chain upstream of a node moved out of it should leave the chain too");
|
||||
for (node_id, before) in [(far, far_before), (source, source_before), (outside, outside_before)] {
|
||||
assert_eq!(
|
||||
network_interface.position(&node_id, &[]),
|
||||
Some(before + IVec2::Y),
|
||||
"Node {node_id} upstream of the moved node should follow it"
|
||||
);
|
||||
}
|
||||
|
||||
assert_invariants(&editor, "after moving a chain node out of its chain");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_chain_node_out_while_keeping_its_upstream_leaves_the_upstream_in_place() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let (_, near, far, source, _) = layer_with_chain(&mut editor).await;
|
||||
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
let [far_before, source_before] = [far, source].map(|node_id| network_interface.position(&node_id, &[]).expect("every node has a position"));
|
||||
|
||||
network_interface.selected_nodes_mut(&[]).expect("the root network has a selection").set_selected_nodes(vec![near]);
|
||||
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
|
||||
network_interface.shift_selected_nodes(Direction::Down, true, true, &[]);
|
||||
|
||||
assert_eq!(
|
||||
network_interface.position(&far, &[]),
|
||||
Some(far_before),
|
||||
"The chain upstream of the moved node should stay where it was drawn"
|
||||
);
|
||||
assert_eq!(network_interface.position(&source, &[]), Some(source_before));
|
||||
|
||||
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
|
||||
network_interface.shift_selected_nodes(Direction::Up, true, true, &[]);
|
||||
assert!(
|
||||
network_interface.is_chain(&near, &[]) && network_interface.is_chain(&far, &[]),
|
||||
"Moving the node back should restore the whole chain"
|
||||
);
|
||||
|
||||
assert_invariants(&editor, "after moving a chain node out of its chain while keeping its upstream");
|
||||
}
|
||||
|
||||
/// Builds a layer fed by the chain `near <- far <- source` (a generator fixed at the upstream end), with an outside node also wired into the near node's second input.
|
||||
async fn layer_with_chain(editor: &mut EditorTestUtils) -> (NodeId, NodeId, NodeId, NodeId, NodeId) {
|
||||
let layer = editor.create_node_by_name_at(merge_definition(), 30, 10).await;
|
||||
@@ -1373,9 +1216,9 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let merge = editor.create_node_by_name_at(merge_definition(), 0, 0).await;
|
||||
let path = vec![merge];
|
||||
editor.enter_editable_network(merge).await;
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Origins to Polyline".into()), 0, 0).await;
|
||||
let path = vec![subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
let import_count = editor.active_document().network_interface.number_of_imports(&path);
|
||||
|
||||
// With a primary, the only one is past the last import
|
||||
@@ -1383,20 +1226,20 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let empty_connectors = network_interface.empty_import_export_connectors(true, &path);
|
||||
assert_eq!(empty_connectors.iter().map(|(index, _)| *index).collect::<Vec<_>>(), vec![import_count]);
|
||||
|
||||
// The attribute name given to Merge's interior Write Attribute node
|
||||
let write_attribute = network_interface
|
||||
// The closed setting given to the subgraph's interior Points to Polyline node
|
||||
let points_to_polyline = network_interface
|
||||
.nested_network(&path)
|
||||
.and_then(|network| {
|
||||
network
|
||||
.nodes
|
||||
.iter()
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::graphic::write_attribute::IDENTIFIER))
|
||||
.find(|(_, node)| node.implementation == DocumentNodeImplementation::ProtoNode(graphene_std::vector::points_to_polyline::IDENTIFIER))
|
||||
})
|
||||
.map(|(node_id, _)| *node_id)
|
||||
.expect("Merge should contain a Write Attribute node");
|
||||
let value_input = InputConnector::node_at_index(write_attribute, 1);
|
||||
.expect("Origins to Polyline should contain a Points to Polyline node");
|
||||
let value_input = InputConnector::node_at_index(points_to_polyline, 1);
|
||||
let Some(NodeInput::Value { tagged_value, .. }) = network_interface.input_from_connector(&value_input, &path) else {
|
||||
panic!("Merge's Write Attribute node should be given its attribute name as a value");
|
||||
panic!("The Points to Polyline node should be given its closed setting as a value");
|
||||
};
|
||||
let displaced_value = (**tagged_value).clone();
|
||||
|
||||
@@ -1414,7 +1257,7 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
"the new import should be wired to the input"
|
||||
);
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(merge, import_count), &[]);
|
||||
let new_input = network_interface.input_from_connector(&InputConnector::node_at_index(subgraph, import_count), &[]);
|
||||
assert!(
|
||||
matches!(new_input, Some(NodeInput::Value { tagged_value, exposed: true }) if **tagged_value == displaced_value),
|
||||
"the new import should take over the value its wire displaced, found {new_input:?}"
|
||||
@@ -1430,11 +1273,11 @@ async fn the_empty_import_connectors_add_the_next_import_or_fill_the_empty_prima
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(network_interface.empty_import_export_connectors(true, &path).iter().any(|(index, _)| *index == 0));
|
||||
|
||||
// The content given to Merge's interior Write Attribute node by its Into Group node
|
||||
let wired_input = InputConnector::node_at_index(write_attribute, 0);
|
||||
// The points given to the subgraph's interior Points to Polyline node by its Combine Paths node
|
||||
let wired_input = InputConnector::node_at_index(points_to_polyline, 0);
|
||||
assert!(
|
||||
matches!(network_interface.input_from_connector(&wired_input, &path), Some(NodeInput::Node { .. })),
|
||||
"Merge's Write Attribute node should be wired its content from another node"
|
||||
"The Points to Polyline node should have its points wired from another node"
|
||||
);
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::AddImportAndConnect {
|
||||
|
||||
@@ -889,12 +889,10 @@ impl document_graph_storage::NodeMetadataSource for MetadataCopySource<'_> {
|
||||
NodeTypePersistentMetadata::Layer(layer) => Some(match layer.position {
|
||||
LayerPosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
|
||||
LayerPosition::Stack(offset) => Position::Stack(offset),
|
||||
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
|
||||
}),
|
||||
NodeTypePersistentMetadata::Node(node) => Some(match *node.position() {
|
||||
NodePosition::Absolute(offset) => Position::Absolute([offset.x, offset.y]),
|
||||
NodePosition::Chain => Position::Chain,
|
||||
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
+14
-22
@@ -101,12 +101,6 @@ async fn wiring_and_export_edits_construct_the_exact_diff_ops() {
|
||||
let a = editor.create_node_by_name(rectangle_definition()).await;
|
||||
let b = editor.create_node_by_name(rectangle_definition()).await;
|
||||
|
||||
// Already read by `a`, so `b` is relative and the wiring edit below doesn't also reposition it
|
||||
editor
|
||||
.active_document_mut()
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(a, 2), NodeInput::node(b, 0), &[]);
|
||||
|
||||
let working = convert(&editor);
|
||||
let wire = NodeInput::node(b, 0);
|
||||
editor.active_document_mut().network_interface.set_input(&InputConnector::node_at_index(a, 1), wire.clone(), &[]);
|
||||
@@ -870,14 +864,15 @@ async fn reconciling_an_input_value_edit_reproduces_the_interface() {
|
||||
let group = only_group(editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[group]);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let (inner, index) = interface
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
let inner = interface
|
||||
.nested_network(&[group])
|
||||
.expect("the group's network")
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| Some((*id, node.inputs.iter().position(|input| input.as_value().is_some())?)))
|
||||
.expect("a node with a value input inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, index), NodeInput::value(TaggedValue::Number(42.), false), &[group]);
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some(*id))
|
||||
.expect("an Extend node inside the group");
|
||||
interface.set_input(&InputConnector::node_at_index(inner, 0), NodeInput::value(TaggedValue::None, false), &[group]);
|
||||
})
|
||||
.await;
|
||||
}
|
||||
@@ -1070,13 +1065,14 @@ fn table_layer(editor: &EditorTestUtils) -> (NodeId, graph_craft::document::Netw
|
||||
.expect("a committed layer should name a table entry")
|
||||
}
|
||||
|
||||
/// A node inside the table entry `definition`, and the index of one of its value inputs.
|
||||
fn value_input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
/// The Extend node inside the layer's table entry `definition`, and the index of its base input.
|
||||
fn input_inside(editor: &EditorTestUtils, definition: graph_craft::document::NetworkId) -> (NodeId, usize) {
|
||||
let extend = graph_craft::document::DocumentNodeImplementation::ProtoNode(graphene_std::graphic::extend::IDENTIFIER);
|
||||
editor.active_document().network_interface.document_network().definitions[&definition]
|
||||
.nodes
|
||||
.iter()
|
||||
.find_map(|(id, node)| node.inputs.iter().position(|input| matches!(input, NodeInput::Value { .. })).map(|index| (*id, index)))
|
||||
.expect("the layer's network should have a node with a value input")
|
||||
.find_map(|(id, node)| (node.implementation == extend).then_some((*id, 0)))
|
||||
.expect("the layer's network should have an Extend node")
|
||||
}
|
||||
|
||||
/// The network location `deltas` recorded for a write to an input of `node_id`.
|
||||
@@ -1125,7 +1121,7 @@ async fn an_edit_inside_a_table_entry_constructs_the_diff() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
@@ -1180,7 +1176,7 @@ async fn a_write_keeps_its_network_when_the_instance_changes_implementation() {
|
||||
let (layer, _) = table_layer(&editor);
|
||||
editor.active_document_mut().network_interface.make_editable(&[layer]);
|
||||
let (layer, definition) = table_layer(&editor);
|
||||
let (inner, input_index) = value_input_inside(&editor, definition);
|
||||
let (inner, input_index) = input_inside(&editor, definition);
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.discard_deltas();
|
||||
|
||||
@@ -1393,14 +1389,10 @@ async fn making_an_instance_unique_forks_its_network() {
|
||||
assert_ne!(forked, definition);
|
||||
assert!(!interface.is_shared(©, &[]) && !interface.is_shared(&layer, &[]));
|
||||
|
||||
let (inner, input_index) = value_input_inside(&editor, forked);
|
||||
let (inner, input_index) = input_inside(&editor, forked);
|
||||
let original = editor.active_document().network_interface.document_network().definitions[&definition].clone();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let NodeInput::Value { tagged_value, exposed } = &interface.document_network().definitions[&forked].nodes[&inner].inputs[input_index] else {
|
||||
unreachable!("the input was found as a value")
|
||||
};
|
||||
let flipped = NodeInput::value((**tagged_value).clone(), !exposed);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), flipped, &[copy]);
|
||||
interface.set_input(&InputConnector::node_at_index(inner, input_index), NodeInput::value(TaggedValue::None, false), &[copy]);
|
||||
|
||||
assert_ne!(interface.document_network().definitions[&forked], original, "the edit should change the copy's network");
|
||||
assert_eq!(interface.document_network().definitions[&definition], original, "the original's network should be untouched");
|
||||
|
||||
@@ -8,8 +8,8 @@ use graphene_std::{Color, Graphic};
|
||||
impl NodeNetworkInterface {
|
||||
/// The top left corner of a node in node graph grid coordinates.
|
||||
///
|
||||
/// A relative node sits at an offset from the nodes reading it and a chain node to the left of the layer it feeds,
|
||||
/// so both are resolved by walking downstream to the first absolute position.
|
||||
/// Only absolute positions are stored. A stack layer sits below its downstream sibling and a chain node to the
|
||||
/// left of the layer it feeds, so both are resolved by walking downstream to the first stored position.
|
||||
pub fn position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
|
||||
self.position_from_downstream(node_id, network_path, &mut HashSet::new(), &mut HashMap::new())
|
||||
}
|
||||
@@ -42,7 +42,7 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// Walks downstream to the first stored position, accumulating the relative offsets along the way. `visited`
|
||||
/// holds the nodes on the current walk, which stops it on a cyclic graph that concurrent edits can produce.
|
||||
/// stops the walk on a cyclic graph, which concurrent edits can produce, rather than recursing forever.
|
||||
fn position_from_downstream(&self, node_id: &NodeId, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
|
||||
if let Some(position) = resolved.get(node_id) {
|
||||
return Some(*position);
|
||||
@@ -53,7 +53,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
let position = self.resolve_position(node_id, network_path, visited, resolved);
|
||||
visited.remove(node_id);
|
||||
if let Some(position) = position {
|
||||
resolved.insert(*node_id, position);
|
||||
}
|
||||
@@ -70,7 +69,6 @@ impl NodeNetworkInterface {
|
||||
match &node_metadata.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
|
||||
LayerPosition::Absolute(position) => Some(position),
|
||||
LayerPosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
|
||||
LayerPosition::Stack(y_offset) => {
|
||||
let downstream_node_id = self
|
||||
.with_outward_wires(network_path, |outward_wires| {
|
||||
@@ -93,12 +91,10 @@ impl NodeNetworkInterface {
|
||||
},
|
||||
NodeTypePersistentMetadata::Node(node_metadata) => match node_metadata.position {
|
||||
NodePosition::Absolute(position) => Some(position),
|
||||
NodePosition::Relative(offset) => self.relative_position(node_id, offset, network_path, visited, resolved),
|
||||
NodePosition::Chain => {
|
||||
// A chain node is placed by its distance from the layer it feeds, so walk downstream to that layer
|
||||
let mut current_node_id = *node_id;
|
||||
let mut node_distance_from_layer = 1;
|
||||
let mut chain_visited = HashSet::new();
|
||||
loop {
|
||||
// TODO: Use root node to restore if previewing
|
||||
let downstream_node_id = self
|
||||
@@ -126,7 +122,7 @@ impl NodeNetworkInterface {
|
||||
.map(|layer_position| layer_position + IVec2::new(-node_distance_from_layer * NODE_CHAIN_WIDTH, 0));
|
||||
}
|
||||
|
||||
if !chain_visited.insert(downstream_node_id) {
|
||||
if !visited.insert(downstream_node_id) {
|
||||
log::error!("Cycle reached while resolving the chain position of node {node_id}");
|
||||
return None;
|
||||
}
|
||||
@@ -138,127 +134,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
fn relative_position(&self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId], visited: &mut HashSet<NodeId>, resolved: &mut HashMap<NodeId, IVec2>) -> Option<IVec2> {
|
||||
let readers = self.reading_nodes(node_id, network_path);
|
||||
let Some(top_left) = readers
|
||||
.iter()
|
||||
.filter_map(|reader| self.position_from_downstream(reader, network_path, visited, resolved))
|
||||
.reduce(IVec2::min)
|
||||
else {
|
||||
log::error!("Could not get the position of any node reading relative node {node_id}");
|
||||
return None;
|
||||
};
|
||||
Some(top_left + offset)
|
||||
}
|
||||
|
||||
/// The top left corner of the bounding box of the positions of the nodes reading `node_id`.
|
||||
fn readers_top_left(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<IVec2> {
|
||||
let readers = self.reading_nodes(node_id, network_path);
|
||||
self.positions(readers, network_path).into_iter().map(|(_, position)| position).reduce(IVec2::min)
|
||||
}
|
||||
|
||||
/// Stores `position` as an offset from the nodes reading the node, or as an absolute position if no node reads it.
|
||||
pub(crate) fn place_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
|
||||
match self.readers_top_left(node_id, network_path) {
|
||||
Some(top_left) => self.set_relative_position(node_id, position - top_left, network_path),
|
||||
None => self.set_absolute_position(node_id, position, network_path),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_relative_position(&mut self, node_id: &NodeId, offset: IVec2, network_path: &[NodeId]) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node_metadata for node {node_id}");
|
||||
return;
|
||||
};
|
||||
if !node.set_relative_position(offset) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_position(node_id, network_path);
|
||||
}
|
||||
|
||||
/// Converts every absolute node that another node reads, and every stacked layer, in all networks to a position relative to its readers.
|
||||
pub fn convert_positions_to_relative(&mut self) {
|
||||
let mut network_paths = Vec::new();
|
||||
self.for_each_network(&mut |network_path, _| network_paths.push(network_path.to_vec()));
|
||||
network_paths.retain(|network_path| !self.is_read_only(network_path));
|
||||
|
||||
for network_path in network_paths {
|
||||
let Some(network) = self.nested_network(&network_path) else { continue };
|
||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||
let positions: HashMap<NodeId, IVec2> = self.positions(node_ids.iter().copied(), &network_path).into_iter().collect();
|
||||
|
||||
let offsets: Vec<(NodeId, IVec2)> = node_ids
|
||||
.iter()
|
||||
.filter(|node_id| self.is_absolute(node_id, &network_path) || matches!(self.stored_layer_position(node_id, &network_path), Some(LayerPosition::Stack(_))))
|
||||
.filter_map(|node_id| {
|
||||
let top_left = self
|
||||
.reading_nodes(node_id, &network_path)
|
||||
.iter()
|
||||
.filter_map(|reader| positions.get(reader).copied())
|
||||
.reduce(IVec2::min)?;
|
||||
Some((*node_id, positions.get(node_id)? - top_left))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for (node_id, offset) in offsets {
|
||||
self.set_relative_position(&node_id, offset, &network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn stored_layer_position(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<LayerPosition> {
|
||||
match &self.node_metadata(node_id, network_path)?.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer_metadata) => Some(layer_metadata.position.clone()),
|
||||
NodeTypePersistentMetadata::Node(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes reading any output of `node_id`.
|
||||
fn reading_nodes(&self, node_id: &NodeId, network_path: &[NodeId]) -> Vec<NodeId> {
|
||||
let output_count = self.number_of_outputs(node_id, network_path);
|
||||
self.with_outward_wires(network_path, |outward_wires| {
|
||||
(0..output_count)
|
||||
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
|
||||
.flatten()
|
||||
.filter_map(InputConnector::node_id)
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Pins a relative node at its drawn position before `leaving_reader` stops reading it, if no other node reads it.
|
||||
pub(crate) fn pin_relative_node_losing_its_readers(&mut self, node_id: &NodeId, leaving_reader: &InputConnector, network_path: &[NodeId]) {
|
||||
if !self.is_relative(node_id, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
let output_count = self.number_of_outputs(node_id, network_path);
|
||||
let still_read = self.with_outward_wires(network_path, |outward_wires| {
|
||||
(0..output_count)
|
||||
.filter_map(|output_index| outward_wires.get(&OutputConnector::node(*node_id, output_index)))
|
||||
.flatten()
|
||||
.any(|reader| reader != leaving_reader && reader.node_id().is_some())
|
||||
});
|
||||
if still_read != Some(false) {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get the position of relative node {node_id} before it loses its readers");
|
||||
return;
|
||||
};
|
||||
self.set_absolute_position(node_id, position, network_path);
|
||||
}
|
||||
|
||||
/// Pins a relative node at `position`, where it was drawn, once no node reads it anymore.
|
||||
pub(crate) fn pin_relative_node_without_readers(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
|
||||
if self.is_relative(node_id, network_path) && self.reading_nodes(node_id, network_path).is_empty() {
|
||||
self.set_absolute_position(node_id, position, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the position of a node to an absolute position
|
||||
pub(crate) fn set_absolute_position(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
@@ -432,19 +307,19 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes `node_id`, the first chain node rather than the layer, and the chain nodes upstream of it out of the chain where they are drawn.
|
||||
pub(crate) fn unchain_upstream(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
/// node_id is the first chain node, not the layer
|
||||
pub(crate) fn set_upstream_chain_to_absolute(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
let Some(downstream_layer) = self.downstream_layer_for_chain_node(node_id, network_path) else {
|
||||
log::error!("Could not get downstream layer in unchain_upstream");
|
||||
log::error!("Could not get downstream layer in set_upstream_chain_to_absolute");
|
||||
return;
|
||||
};
|
||||
for upstream_id in &self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).collect::<Vec<_>>() {
|
||||
let Some(previous_position) = self.position(upstream_id, network_path) else {
|
||||
log::error!("Could not get position in unchain_upstream");
|
||||
log::error!("Could not get position in set_upstream_chain_to_absolute");
|
||||
return;
|
||||
};
|
||||
if self.is_chain(upstream_id, network_path) {
|
||||
self.place_at(upstream_id, previous_position, network_path);
|
||||
self.set_absolute_position(upstream_id, previous_position, network_path);
|
||||
// Reload click target of the layer which used to encapsulate the chain
|
||||
self.unload_node_click_targets(&downstream_layer, network_path);
|
||||
}
|
||||
@@ -455,44 +330,52 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Places `upstream_node_id` for a connection just made to `input_connector`. A layer that is the sole
|
||||
/// feed into the bottom of another layer stacks under it, a relative node keeps its offset from its
|
||||
/// readers, and an absolute node becomes relative to them where it sits.
|
||||
/// Places `upstream_node_id` for a connection just made to `input_connector`. Only layers move: one
|
||||
/// that is the sole feed into the bottom of another layer stacks under it, and any other layer is
|
||||
/// pinned where it already sits.
|
||||
///
|
||||
/// Returns whether the node could be placed, which is false only when it has no resolvable position.
|
||||
pub(crate) fn reposition_connected_upstream(&mut self, upstream_node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) -> bool {
|
||||
if self.position(upstream_node_id, network_path).is_none() {
|
||||
let Some(current_position) = self.position(upstream_node_id, network_path) else {
|
||||
log::error!("Could not get position of node {upstream_node_id} in reposition_connected_upstream");
|
||||
return false;
|
||||
};
|
||||
|
||||
if !self.is_layer(upstream_node_id, network_path) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let feeds_bottom_of_layer = match input_connector {
|
||||
InputConnector::Node { node_id, input_index: 0 } => self.is_layer(node_id, network_path),
|
||||
_ => false,
|
||||
// Only the bottom input of a layer stacks what feeds it; everything else leaves the layer where it is
|
||||
let InputConnector::Node {
|
||||
node_id: downstream_node_id,
|
||||
input_index,
|
||||
} = input_connector
|
||||
else {
|
||||
self.set_absolute_position(upstream_node_id, current_position, network_path);
|
||||
return true;
|
||||
};
|
||||
let single_outward_wire = self
|
||||
if *input_index != 0 || !self.is_layer(downstream_node_id, network_path) {
|
||||
self.set_absolute_position(upstream_node_id, current_position, network_path);
|
||||
return true;
|
||||
}
|
||||
|
||||
let multiple_outward_wires = self
|
||||
.outward_wires(network_path)
|
||||
.and_then(|all_outward_wires| all_outward_wires.get(&OutputConnector::primary_output(*upstream_node_id)))
|
||||
.is_some_and(|outward_wires| outward_wires.len() == 1);
|
||||
.is_some_and(|outward_wires| outward_wires.len() > 1);
|
||||
|
||||
if let InputConnector::Node { node_id: downstream_node_id, .. } = input_connector
|
||||
&& feeds_bottom_of_layer
|
||||
&& single_outward_wire
|
||||
&& self.is_layer(upstream_node_id, network_path)
|
||||
{
|
||||
if multiple_outward_wires {
|
||||
self.set_absolute_position(upstream_node_id, current_position, network_path);
|
||||
} else {
|
||||
self.set_stack_position_calculated_offset(upstream_node_id, downstream_node_id, network_path);
|
||||
} else if self.is_absolute(upstream_node_id, network_path)
|
||||
&& let Some(position) = self.position(upstream_node_id, network_path)
|
||||
{
|
||||
self.place_at(upstream_node_id, position, network_path);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
/// Places `node_id` after the connection feeding it was removed. A layer that still feeds the bottom
|
||||
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other absolute
|
||||
/// layer is placed at `previous_position`.
|
||||
/// of a single layer stacks under it, a node joins a chain where it is eligible, and any other layer
|
||||
/// is pinned at `previous_position`.
|
||||
///
|
||||
/// Returns whether the node could be placed, which is false only when its outward wires are missing.
|
||||
pub(crate) fn reposition_disconnected_upstream(&mut self, node_id: &NodeId, previous_position: IVec2, network_path: &[NodeId]) -> bool {
|
||||
@@ -515,8 +398,8 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
} else if !is_layer {
|
||||
self.try_set_node_to_chain(node_id, network_path);
|
||||
} else if !self.is_relative(node_id, network_path) {
|
||||
self.place_at(node_id, previous_position, network_path);
|
||||
} else {
|
||||
self.set_absolute_position(node_id, previous_position, network_path);
|
||||
}
|
||||
|
||||
true
|
||||
@@ -553,8 +436,7 @@ impl NodeNetworkInterface {
|
||||
self.invalidate_position(layer, network_path);
|
||||
}
|
||||
|
||||
/// Shifts the selected nodes one grid step. The relative nodes upstream of them follow, unless `keep_upstream` leaves them where they are drawn.
|
||||
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, keep_upstream: bool, network_path: &[NodeId]) {
|
||||
pub fn shift_selected_nodes(&mut self, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
|
||||
let Some(node_ids) = self
|
||||
.selected_nodes_in_nested_network(network_path)
|
||||
.map(|selected_nodes| selected_nodes.selected_nodes().copied().collect::<HashSet<_>>())
|
||||
@@ -562,90 +444,7 @@ impl NodeNetworkInterface {
|
||||
log::error!("Could not get selected nodes in shift_selected_nodes");
|
||||
return;
|
||||
};
|
||||
let placements_before = keep_upstream.then(|| self.placements(network_path));
|
||||
|
||||
self.shift_nodes(node_ids.clone(), direction, shift_without_push, network_path);
|
||||
|
||||
if let Some(placements_before) = placements_before {
|
||||
self.restore_followers(&placements_before, &node_ids, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored position of each node in the network and where it is drawn.
|
||||
fn placements(&self, network_path: &[NodeId]) -> HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)> {
|
||||
let Some(network) = self.nested_network(network_path) else { return HashMap::new() };
|
||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||
|
||||
self.positions(node_ids, network_path)
|
||||
.into_iter()
|
||||
.filter_map(|(node_id, position)| Some((node_id, (self.node_metadata(&node_id, network_path)?.persistent_metadata.node_type_metadata.clone(), position))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Moves each relative node that was only carried along by the nodes reading it back to where it was drawn, which keeps its upstream in place too.
|
||||
/// A node the shift made relative, such as a chain leaving its layer, counts as carried along, while a relative node the shift pushed does not.
|
||||
fn restore_followers(&mut self, placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>, moved_nodes: &HashSet<NodeId>, network_path: &[NodeId]) {
|
||||
let followers: HashSet<NodeId> = placements_before
|
||||
.iter()
|
||||
.filter(|(node_id, (stored_position, position))| {
|
||||
let was_relative = matches!(
|
||||
stored_position,
|
||||
NodeTypePersistentMetadata::Node(NodePersistentMetadata { position: NodePosition::Relative(_) })
|
||||
| NodeTypePersistentMetadata::Layer(LayerPersistentMetadata { position: LayerPosition::Relative(_) })
|
||||
);
|
||||
let stored_position_unchanged = self
|
||||
.node_metadata(node_id, network_path)
|
||||
.is_some_and(|metadata| metadata.persistent_metadata.node_type_metadata == *stored_position);
|
||||
|
||||
!moved_nodes.contains(node_id) && self.is_relative(node_id, network_path) && (stored_position_unchanged || !was_relative) && self.position(node_id, network_path) != Some(*position)
|
||||
})
|
||||
.map(|(node_id, _)| *node_id)
|
||||
.collect();
|
||||
|
||||
let mut restored = HashSet::new();
|
||||
for follower in &followers {
|
||||
self.restore_follower(follower, &followers, placements_before, &mut restored, network_path);
|
||||
}
|
||||
|
||||
// Joining a chain needs a node to line up with its reader, which a follower only does again once restored
|
||||
for follower in &followers {
|
||||
if !self.is_layer(follower, network_path) {
|
||||
self.try_set_node_to_chain(follower, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Restores the followers reading `node_id` first, since each one moves everything it reads.
|
||||
fn restore_follower(
|
||||
&mut self,
|
||||
node_id: &NodeId,
|
||||
followers: &HashSet<NodeId>,
|
||||
placements_before: &HashMap<NodeId, (NodeTypePersistentMetadata, IVec2)>,
|
||||
restored: &mut HashSet<NodeId>,
|
||||
network_path: &[NodeId],
|
||||
) {
|
||||
if !restored.insert(*node_id) {
|
||||
return;
|
||||
}
|
||||
for reader in self.reading_nodes(node_id, network_path) {
|
||||
if followers.contains(&reader) {
|
||||
self.restore_follower(&reader, followers, placements_before, restored, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some((_, previous_position)) = placements_before.get(node_id) {
|
||||
self.keep_drawn_at(node_id, *previous_position, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves an absolute or relative node back to `position` after an edit carried it away, along with everything relative to it.
|
||||
pub(crate) fn keep_drawn_at(&mut self, node_id: &NodeId, position: IVec2, network_path: &[NodeId]) {
|
||||
let Some(current_position) = self.position(node_id, network_path) else { return };
|
||||
let Some(mut node) = self.node_mut(NodeLocator::new(*node_id, network_path)) else { return };
|
||||
if node.shift_absolute_position(position - current_position) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_position(node_id, network_path);
|
||||
}
|
||||
self.shift_nodes(node_ids, direction, shift_without_push, network_path);
|
||||
}
|
||||
|
||||
pub(crate) fn shift_nodes(&mut self, node_ids: HashSet<NodeId>, direction: Direction, shift_without_push: bool, network_path: &[NodeId]) {
|
||||
@@ -711,15 +510,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
// A relative node already follows its readers, so shifting it with all of them would move it twice
|
||||
let shifting_nodes = node_ids.clone();
|
||||
for selected_node in &shifting_nodes {
|
||||
let readers = self.reading_nodes(selected_node, network_path);
|
||||
if self.is_relative(selected_node, network_path) && !readers.is_empty() && readers.iter().all(|reader| shifting_nodes.contains(reader)) {
|
||||
node_ids.remove(selected_node);
|
||||
}
|
||||
}
|
||||
|
||||
node_ids
|
||||
}
|
||||
|
||||
@@ -728,7 +518,14 @@ impl NodeNetworkInterface {
|
||||
/// A node that cannot be read blocks the shift rather than letting part of it through.
|
||||
fn stack_shift_up_is_blocked(&mut self, node_ids: &HashSet<NodeId>, network_path: &[NodeId]) -> bool {
|
||||
for node_id in node_ids {
|
||||
let Some(offset) = self.stack_offset(node_id, network_path) else { continue };
|
||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||
log::error!("Could not get node metadata for node {node_id} in stack_shift_up_is_blocked");
|
||||
return true;
|
||||
};
|
||||
let NodeTypePersistentMetadata::Layer(layer_metadata) = &node_metadata.persistent_metadata.node_type_metadata else {
|
||||
continue;
|
||||
};
|
||||
let LayerPosition::Stack(offset) = layer_metadata.position else { continue };
|
||||
|
||||
let Some(outward_wires) = self.outward_wires(network_path).and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(*node_id))) else {
|
||||
log::error!("Could not get outward wires in stack_shift_up_is_blocked");
|
||||
@@ -740,7 +537,7 @@ impl NodeNetworkInterface {
|
||||
continue;
|
||||
}
|
||||
|
||||
if offset <= 0 {
|
||||
if offset == 0 {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -765,9 +562,9 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
}
|
||||
|
||||
// Walk down the stack to its top layer, which anchors the rest
|
||||
// Walk down the stack to the layer holding an absolute position, which anchors the rest
|
||||
let mut downstream_absolute_layer = *node_id;
|
||||
while self.is_stack(&downstream_absolute_layer, network_path) {
|
||||
while !self.is_absolute(&downstream_absolute_layer, network_path) {
|
||||
let Some(downstream_node) = self
|
||||
.outward_wires(network_path)
|
||||
.and_then(|outward_wires| outward_wires.get(&OutputConnector::primary_output(downstream_absolute_layer)))
|
||||
@@ -805,7 +602,8 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare shift.
|
||||
/// Shifts one node vertically, pushing whatever it collides with unless the caller asked for a bare
|
||||
/// shift. A layer that moves drags its stacked sibling the other way, so the sibling stays put.
|
||||
fn shift_vertically(&mut self, node_id: &NodeId, shift_sign: i32, shift_without_push: bool, shifted_nodes: &mut HashSet<NodeId>, network_path: &[NodeId]) {
|
||||
if !shift_without_push && self.is_layer(node_id, network_path) {
|
||||
self.shift_node_or_parent(node_id, shift_sign, shifted_nodes, network_path);
|
||||
@@ -820,6 +618,18 @@ impl NodeNetworkInterface {
|
||||
if self.with_stack_dependents_if_loaded(network_path, |stack_dependents| matches!(stack_dependents.get(node_id), Some(LayerOwner::None))) == Some(true) {
|
||||
self.add_drag_offset(node_id, shift_sign, network_path);
|
||||
}
|
||||
|
||||
if !self.is_layer(node_id, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
let upstream_layer = self
|
||||
.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
|
||||
.nth(1)
|
||||
.filter(|upstream_node| self.is_stack(upstream_node, network_path));
|
||||
if let Some(upstream_layer) = upstream_layer {
|
||||
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves every node the shift pushed out of place back to where it started, as far as nothing has since
|
||||
@@ -902,6 +712,18 @@ impl NodeNetworkInterface {
|
||||
None => log::error!("Stack dependents should be loaded in vertical_shift_with_push"),
|
||||
}
|
||||
|
||||
// Shift the upstream layer so that it stays in the same place
|
||||
if self.is_layer(node_id, network_path) {
|
||||
let upstream_layer = {
|
||||
self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow)
|
||||
.nth(1)
|
||||
.filter(|upstream_node| self.is_stack(upstream_node, network_path))
|
||||
};
|
||||
if let Some(upstream_layer) = upstream_layer {
|
||||
self.shift_node(&upstream_layer, IVec2::new(0, -shift_sign), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(owned_nodes) = self.with_owned_nodes_if_loaded(node_id, network_path, |owned_nodes| owned_nodes.clone()) {
|
||||
for owned_node in owned_nodes {
|
||||
if self.is_absolute(&owned_node, network_path) {
|
||||
@@ -1023,7 +845,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
// A chain node has no position of its own to shift, so it leaves the chain first
|
||||
NodeTypePersistentMetadata::Node(node_position) if matches!(node_position.position(), NodePosition::Chain) => {
|
||||
self.unchain_upstream(node_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(node_id, network_path);
|
||||
self.shift_node(node_id, shift, network_path);
|
||||
}
|
||||
|
||||
@@ -1455,7 +1277,6 @@ impl NodeNetworkInterface {
|
||||
/// upstream node's spot and that whole branch is shifted left (in absolute graph space) to make room.
|
||||
pub fn insert_node_before_input(&mut self, node_id: &NodeId, input_connector: &InputConnector, network_path: &[NodeId]) {
|
||||
let feeder = self.upstream_output_connector(input_connector, network_path).and_then(|output| output.node_id());
|
||||
let feeder_position = feeder.and_then(|feeder| self.position(&feeder, network_path));
|
||||
|
||||
let Some(current_input) = self.input_from_connector(input_connector, network_path).cloned() else {
|
||||
log::error!("Could not get input in insert_node_before_input");
|
||||
@@ -1470,26 +1291,20 @@ impl NodeNetworkInterface {
|
||||
self.set_input(input_connector, NodeInput::node(*node_id, 0), network_path);
|
||||
|
||||
// If `set_input` chain-positioned the node (it joined a layer chain), there's nothing more to do
|
||||
if self.is_chain(node_id, network_path) {
|
||||
if !self.is_absolute(node_id, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise place the node where the displaced feeder was, then move the feeder's branch left to make room
|
||||
let (Some(feeder), Some(feeder_position)) = (feeder, feeder_position) else { return };
|
||||
// Otherwise place the node where the displaced feeder was, then shift the feeder's branch left to make room
|
||||
let Some(feeder) = feeder else { return };
|
||||
let Some(node_position) = self.position(node_id, network_path) else { return };
|
||||
let Some(feeder_position) = self.position(&feeder, network_path) else { return };
|
||||
|
||||
self.shift_node(node_id, feeder_position - node_position, network_path);
|
||||
|
||||
// A chain feeder derives its position from its distance to the layer, which this insertion already grew,
|
||||
// so shifting it would move it twice and cost it its place in the chain
|
||||
if self.is_chain(&feeder, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
// A relative feeder carries its upstream along
|
||||
if self.is_relative(&feeder, network_path) {
|
||||
let Some(current_feeder_position) = self.position(&feeder, network_path) else { return };
|
||||
self.shift_node(&feeder, feeder_position + IVec2::new(-NODE_CHAIN_WIDTH, 0) - current_feeder_position, network_path);
|
||||
if !self.is_absolute(&feeder, network_path) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
+9
-40
@@ -437,7 +437,7 @@ impl NodeNetworkInterface {
|
||||
let new_inputs = std::mem::take(&mut new_template.inputs);
|
||||
let new_input_metadata = std::mem::take(&mut new_template.input_metadata);
|
||||
|
||||
// A chain whose link into this node is dropped loses the layer it's positioned against, so it leaves the chain while that layer is still reachable
|
||||
// A chain whose link into this node is dropped loses the layer it's positioned against, so it becomes absolute while that layer is still reachable
|
||||
let chain_input_index = if self.is_layer(node_id, network_path) { LAYER_SECONDARY_INPUT_INDEX } else { PRIMARY_INPUT_INDEX };
|
||||
let disconnected_chain_node = self
|
||||
.document_node(node_id, network_path)
|
||||
@@ -453,24 +453,9 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.filter(|upstream_node_id| self.is_chain(upstream_node_id, network_path));
|
||||
if let Some(upstream_node_id) = disconnected_chain_node {
|
||||
self.unchain_upstream(&upstream_node_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(&upstream_node_id, network_path);
|
||||
}
|
||||
|
||||
let disconnected_upstream_positions: Vec<(NodeId, IVec2)> = self
|
||||
.document_node(node_id, network_path)
|
||||
.map(|node| {
|
||||
node.inputs
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(index, old_input)| new_inputs.get(*index) != Some(*old_input))
|
||||
.filter_map(|(_, old_input)| old_input.as_node())
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.unwrap_or_default()
|
||||
.into_iter()
|
||||
.filter_map(|upstream_node_id| Some((upstream_node_id, self.position(&upstream_node_id, network_path)?)))
|
||||
.collect();
|
||||
|
||||
let Some(mut node) = self.node_interface_mut(NodeLocator::new(*node_id, network_path)) else {
|
||||
log::error!("Could not get node {node_id} in replace_inputs");
|
||||
return None;
|
||||
@@ -478,10 +463,6 @@ impl NodeNetworkInterface {
|
||||
let old_inputs = node.replace_inputs(new_inputs.clone(), new_input_metadata);
|
||||
|
||||
self.update_outward_wires_for_inputs(network_path, node_id, &old_inputs, &new_inputs);
|
||||
|
||||
for (upstream_node_id, position) in disconnected_upstream_positions {
|
||||
self.pin_relative_node_without_readers(&upstream_node_id, position, network_path);
|
||||
}
|
||||
Some(old_inputs)
|
||||
}
|
||||
|
||||
@@ -619,17 +600,13 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
}
|
||||
|
||||
if let NodeInput::Node { node_id: upstream_node_id, .. } = &previous_input {
|
||||
self.pin_relative_node_losing_its_readers(upstream_node_id, input_connector, network_path);
|
||||
}
|
||||
|
||||
// A chain positions its nodes relative to the layer they feed, so either end of the rewire
|
||||
// leaving that layer breaks the chain it belonged to
|
||||
for chain_input in [&previous_input, &new_input] {
|
||||
if let NodeInput::Node { node_id: chain_node_id, .. } = chain_input
|
||||
&& self.is_chain(chain_node_id, network_path)
|
||||
{
|
||||
self.unchain_upstream(chain_node_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(chain_node_id, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -798,7 +775,7 @@ impl NodeNetworkInterface {
|
||||
{
|
||||
// If the node upstream from the disconnected input is a chain, then break the chain by setting it to absolute positioning
|
||||
if self.is_chain(upstream_node_id, network_path) {
|
||||
self.unchain_upstream(upstream_node_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(upstream_node_id, network_path);
|
||||
}
|
||||
// If the node upstream from the disconnected input has an outward wire to the bottom of a layer, set it back to stack positioning
|
||||
if self.is_layer(upstream_node_id, network_path) {
|
||||
@@ -910,17 +887,10 @@ impl NodeNetworkInterface {
|
||||
dot_template.node_type_metadata = NodeTypePersistentMetadata::node(center - IVec2::Y);
|
||||
self.insert_node(dot, dot_template, network_path);
|
||||
|
||||
let upstream_node = output_connector.node_id();
|
||||
let upstream_position = upstream_node.and_then(|upstream_node| self.position(&upstream_node, network_path));
|
||||
|
||||
self.create_wire(output_connector, &InputConnector::primary_input(dot), network_path);
|
||||
for fed_input in fed_inputs {
|
||||
self.create_wire(&OutputConnector::primary_output(dot), fed_input, network_path);
|
||||
}
|
||||
|
||||
if let (Some(upstream_node), Some(upstream_position)) = (upstream_node, upstream_position) {
|
||||
self.keep_drawn_at(&upstream_node, upstream_position, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Used to insert a group of nodes into the network
|
||||
@@ -1351,20 +1321,20 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn set_to_node_or_layer(&mut self, node_id: &NodeId, network_path: &[NodeId], is_layer: bool) {
|
||||
// If a layer is set to a node, take its chain out of the chain and its upstream sibling out of the stack where they are drawn
|
||||
// If a layer is set to a node, set upstream nodes to absolute position, and upstream siblings to absolute position
|
||||
let child_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::HorizontalFlow).nth(1) };
|
||||
let upstream_sibling_id = { self.upstream_flow_back_from_nodes(vec![*node_id], network_path, FlowType::PrimaryFlow).nth(1) };
|
||||
match (self.is_layer(node_id, network_path), is_layer) {
|
||||
(true, false) => {
|
||||
if let Some(child_id) = child_id {
|
||||
self.unchain_upstream(&child_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(&child_id, network_path);
|
||||
}
|
||||
if let Some(upstream_sibling_id) = upstream_sibling_id {
|
||||
let Some(upstream_sibling_position) = self.position(&upstream_sibling_id, network_path) else {
|
||||
log::error!("Could not get upstream sibling position in set_to_node_or_layer");
|
||||
return;
|
||||
};
|
||||
self.place_at(&upstream_sibling_id, upstream_sibling_position, network_path);
|
||||
self.set_absolute_position(&upstream_sibling_id, upstream_sibling_position, network_path);
|
||||
}
|
||||
}
|
||||
(false, true) => {
|
||||
@@ -1379,7 +1349,7 @@ impl NodeNetworkInterface {
|
||||
{
|
||||
self.set_stack_position_calculated_offset(&upstream_sibling_id, node_id, network_path);
|
||||
} else {
|
||||
self.unchain_upstream(&upstream_sibling_id, network_path);
|
||||
self.set_upstream_chain_to_absolute(&upstream_sibling_id, network_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1402,7 +1372,7 @@ impl NodeNetworkInterface {
|
||||
.filter(|downstream_node_id| self.is_layer(downstream_node_id, network_path))
|
||||
.and_then(|downstream_layer| self.position(&downstream_layer, network_path));
|
||||
|
||||
// First switch between layer and node where it is drawn
|
||||
// First set the position to absolute
|
||||
let absolute = match is_layer {
|
||||
true => NodeTypePersistentMetadata::layer(position),
|
||||
false => NodeTypePersistentMetadata::node(position),
|
||||
@@ -1412,7 +1382,6 @@ impl NodeNetworkInterface {
|
||||
return;
|
||||
};
|
||||
node.set_node_type(absolute);
|
||||
self.place_at(node_id, position, network_path);
|
||||
|
||||
// Try build the chain
|
||||
if is_layer {
|
||||
|
||||
@@ -954,27 +954,8 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "is_chain", |view| view.is_chain(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
pub fn is_relative(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.query(network_path, "is_relative", |view| view.is_relative(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the layer sits straight below the one layer reading it through its stack input.
|
||||
pub fn is_stack(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
self.stack_offset(node_id, network_path).is_some()
|
||||
}
|
||||
|
||||
/// The rows a stacked layer sits below the gap under the layer reading it.
|
||||
pub fn stack_offset(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<i32> {
|
||||
let stack_offset = self.query(network_path, "stack_offset", |view| view.stack_offset(node_id)).flatten()?;
|
||||
|
||||
let read_by_one_stack_input = self
|
||||
.with_outward_wires(network_path, |outward_wires| match outward_wires.get(&OutputConnector::primary_output(*node_id)).map(Vec::as_slice) {
|
||||
Some([InputConnector::Node { node_id: reader, input_index: 0 }]) => self.is_layer(reader, network_path),
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
read_by_one_stack_input.then_some(stack_offset)
|
||||
self.query(network_path, "is_stack", |view| view.is_stack(node_id)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Whether the node is an Artboard node by identity, regardless of whether it currently participates in the scene.
|
||||
@@ -1082,11 +1063,11 @@ impl NodeNetworkInterface {
|
||||
Some(transformed.bounding_box())
|
||||
}
|
||||
|
||||
/// Calculates the document bounds in document space, expanding vector layer bounds to include the rendered
|
||||
/// stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the document bounds in document space, expanding layer bounds to include the rendered stroke width and
|
||||
/// effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn document_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool) -> Option<[DVec2; 2]> {
|
||||
self.document_metadata.document_bounds(include_artboards, true, || {
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke(layer))
|
||||
self.combined_document_bounds(include_artboards, |metadata, layer| metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1103,17 +1084,17 @@ impl NodeNetworkInterface {
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
/// Calculates the selected layer bounds in document space, expanding vector layer bounds to include the
|
||||
/// rendered stroke width. Used for export so the output canvas captures strokes that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
/// Calculates the selected layer bounds in document space, expanding layer bounds to include the rendered stroke width
|
||||
/// and effects. Used for export so the output canvas captures strokes and shadows that overflow the path geometry.
|
||||
pub fn selected_bounds_document_space_with_stroke_and_effects(&self, include_artboards: bool, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(selected_nodes) = self.selected_nodes_in_nested_network(network_path) else {
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke");
|
||||
log::error!("Could not get selected nodes in selected_bounds_document_space_with_stroke_and_effects");
|
||||
return None;
|
||||
};
|
||||
selected_nodes
|
||||
.selected_layers(&self.document_metadata)
|
||||
.filter(|&layer| include_artboards || !self.is_artboard(&layer.to_node(), &[]))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke(layer))
|
||||
.filter_map(|layer| self.document_metadata.bounding_box_document_with_stroke_and_effects(layer))
|
||||
.reduce(Quad::combine_bounds)
|
||||
}
|
||||
|
||||
|
||||
+2
-8
@@ -14,8 +14,8 @@ use graph_craft::document::{DocumentNodeImplementation, NetworkLocation, NodeId,
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
|
||||
use super::{
|
||||
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface,
|
||||
NodeNetworkMetadata, NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
|
||||
DocumentNodePersistentMetadata, DocumentNodeTransientMetadata, InputMetadata, InputPersistentMetadata, LayerPosition, NavigationMetadata, NodeNetworkInterface, NodeNetworkMetadata,
|
||||
NodeNetworkPersistentMetadata, NodePersistentMetadata, NodePosition, NodeTypePersistentMetadata, PTZ, Previewing,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::network_definition_version;
|
||||
use crate::messages::portfolio::document::overlays::utility_types::OverlaysVisibilitySettings;
|
||||
@@ -180,12 +180,10 @@ pub fn position_from_runtime(node_type: &NodeTypePersistentMetadata) -> Position
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
LayerPosition::Absolute(v) => Position::Absolute([v.x, v.y]),
|
||||
LayerPosition::Stack(offset) => Position::Stack(offset),
|
||||
LayerPosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
|
||||
},
|
||||
NodeTypePersistentMetadata::Node(node) => match *node.position() {
|
||||
NodePosition::Absolute(v) => Position::Absolute([v.x, v.y]),
|
||||
NodePosition::Chain => Position::Chain,
|
||||
NodePosition::Relative(offset) => Position::Relative([offset.x, offset.y]),
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -204,10 +202,6 @@ pub fn position_to_runtime(position: Position, is_layer: bool) -> NodeTypePersis
|
||||
metadata
|
||||
}
|
||||
(Position::Chain, _) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Chain)),
|
||||
(Position::Relative([x, y]), true) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Relative(IVec2::new(x, y)),
|
||||
}),
|
||||
(Position::Relative([x, y]), false) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(IVec2::new(x, y)))),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+2
-19
@@ -144,31 +144,14 @@ impl NodeMut<'_> {
|
||||
self.set_node_type(node_type)
|
||||
}
|
||||
|
||||
/// Places the node at an offset from the top left corner of the bounding box of the nodes reading it.
|
||||
pub(crate) fn set_relative_position(&mut self, offset: IVec2) -> bool {
|
||||
let node_type = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(_) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Relative(offset),
|
||||
}),
|
||||
NodeTypePersistentMetadata::Node(_) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset))),
|
||||
};
|
||||
self.set_node_type(node_type)
|
||||
}
|
||||
|
||||
/// Offsets a node that is absolutely or relatively positioned, leaving a stack or chain node where it is.
|
||||
/// Offsets a node that is absolutely positioned, leaving a stack or chain node where it is.
|
||||
pub(crate) fn shift_absolute_position(&mut self, shift: IVec2) -> bool {
|
||||
let shifted = match self.metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Absolute(position),
|
||||
}) => NodeTypePersistentMetadata::layer(position + shift),
|
||||
NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Relative(offset),
|
||||
}) => NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::Relative(offset + shift),
|
||||
}),
|
||||
NodeTypePersistentMetadata::Node(ref node) => match node.position {
|
||||
NodePosition::Absolute(position) => NodeTypePersistentMetadata::node(position + shift),
|
||||
NodePosition::Relative(offset) => NodeTypePersistentMetadata::Node(NodePersistentMetadata::new(NodePosition::Relative(offset + shift))),
|
||||
NodePosition::Chain => return false,
|
||||
},
|
||||
NodeTypePersistentMetadata::Layer(_) => return false,
|
||||
@@ -182,7 +165,7 @@ impl NodeMut<'_> {
|
||||
return false;
|
||||
}
|
||||
self.set_node_type(NodeTypePersistentMetadata::Layer(LayerPersistentMetadata {
|
||||
position: LayerPosition::stacked(y_offset),
|
||||
position: LayerPosition::Stack(y_offset),
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1111,7 +1111,7 @@ impl NodeTypePersistentMetadata {
|
||||
/// All fields in LayerMetadata should automatically be updated by using the network interface API
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct LayerPersistentMetadata {
|
||||
/// Stores the position of a layer node, which can be Absolute or Relative, or Stack in older documents
|
||||
/// Stores the position of a layer node, which can either be Absolute or Stack
|
||||
pub position: LayerPosition,
|
||||
}
|
||||
|
||||
@@ -1123,7 +1123,7 @@ impl PartialEq for LayerPersistentMetadata {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct NodePersistentMetadata {
|
||||
/// Stores the position of a non layer node, which can be Absolute, Chain, or Relative
|
||||
/// Stores the position of a non layer node, which can either be Absolute or Chain
|
||||
pub(crate) position: NodePosition,
|
||||
}
|
||||
|
||||
@@ -1136,33 +1136,22 @@ impl NodePersistentMetadata {
|
||||
}
|
||||
}
|
||||
|
||||
/// A layer is positioned as Absolute or Relative to the nodes reading it. Stack is only read from older documents, which opening converts to Relative.
|
||||
/// A layer can either be position as Absolute or in a Stack
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum LayerPosition {
|
||||
// Position of the node in grid spaces
|
||||
Absolute(IVec2),
|
||||
// A layer is in a Stack when it feeds into the bottom input of a layer. The Y position stores the vertical distance between the layer and its upstream sibling/parent.
|
||||
Stack(u32),
|
||||
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
|
||||
Relative(IVec2),
|
||||
}
|
||||
|
||||
impl LayerPosition {
|
||||
/// Stacked `y_offset` rows below the gap under the layer reading it.
|
||||
pub fn stacked(y_offset: u32) -> Self {
|
||||
Self::Relative(IVec2::new(0, STACK_VERTICAL_GAP + y_offset as i32))
|
||||
}
|
||||
}
|
||||
|
||||
/// A node can be positioned as Absolute, in a Chain, or Relative to the nodes reading it
|
||||
/// A node can either be position as Absolute or in a Chain
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum NodePosition {
|
||||
// Position of the node in grid spaces
|
||||
Absolute(IVec2),
|
||||
// In a chain the position is based on the number of nodes to the first layer node
|
||||
Chain,
|
||||
// Offset from the top left corner of the bounding box of the positions of the nodes reading this one
|
||||
Relative(IVec2),
|
||||
}
|
||||
|
||||
/// Cached metadata that should be calculated when creating a node, and should be recalculated when modifying a node property that affects one of the cached fields.
|
||||
|
||||
@@ -237,22 +237,10 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_relative(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
pub fn is_stack(&self, node_id: &NodeId) -> Result<bool, NetworkError> {
|
||||
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Relative(_)),
|
||||
NodeTypePersistentMetadata::Node(node_metadata) => matches!(node_metadata.position, NodePosition::Relative(_)),
|
||||
})
|
||||
}
|
||||
|
||||
/// The rows a layer sits below the gap under the node reading it, if its position places it straight below that node.
|
||||
pub fn stack_offset(&self, node_id: &NodeId) -> Result<Option<i32>, NetworkError> {
|
||||
Ok(match &self.node_metadata(node_id)?.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer_metadata) => match layer_metadata.position {
|
||||
LayerPosition::Stack(y_offset) => Some(y_offset as i32),
|
||||
LayerPosition::Relative(offset) if offset.x == 0 => Some(offset.y - STACK_VERTICAL_GAP),
|
||||
_ => None,
|
||||
},
|
||||
NodeTypePersistentMetadata::Node(_) => None,
|
||||
NodeTypePersistentMetadata::Layer(layer_metadata) => matches!(layer_metadata.position, LayerPosition::Stack(_)),
|
||||
_ => false,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
@@ -295,10 +295,6 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
node: graphene_std::math_nodes::footprint_value::IDENTIFIER,
|
||||
aliases: &["graphene_math_nodes::FootprintValueNode", "graphene_core::ops::FootprintValueNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_form::IDENTIFIER,
|
||||
aliases: &["math_nodes::GradientTypeNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::math_nodes::gradient_spread::IDENTIFIER,
|
||||
aliases: &["math_nodes::SpreadMethodNode"],
|
||||
@@ -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::blending_nodes::effects::blur::IDENTIFIER,
|
||||
aliases: &["raster_nodes::filter::BlurNode", "graphene_raster_nodes::filter::BlurNode", "graphene_std::filter::BlurNode"],
|
||||
},
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::adjustments::brightness_contrast::IDENTIFIER,
|
||||
@@ -533,8 +529,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[
|
||||
"graphene_core::raster::ChannelMixerNode",
|
||||
],
|
||||
},
|
||||
// Color Overlay became Paint Overlay, whose paint input takes the old color input's value as a solid paint
|
||||
NodeReplacement {
|
||||
node: graphene_std::raster_nodes::blending_nodes::color_overlay::IDENTIFIER,
|
||||
node: graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER,
|
||||
aliases: &[
|
||||
"graphene_raster_nodes::adjustments::ColorOverlayNode",
|
||||
"graphene_raster_nodes::generate_curves::ColorOverlayNode",
|
||||
@@ -542,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 {
|
||||
@@ -1279,6 +1277,10 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
if *new == graphene_std::math_nodes::math_function::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Math f(x)");
|
||||
}
|
||||
|
||||
if *new == graphene_std::blending_nodes::effects::paint_overlay::IDENTIFIER {
|
||||
reset_default_display_name(document, node_id, &network_path, "Color Overlay");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1397,9 +1399,9 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The Merge and Artboard networks no longer pass their content through a Monitor node, since thumbnails are found from the layers themselves.
|
||||
// The Merge and Artboard networks no longer hold a Monitor node or write the layer's path onto their content, since the editor finds thumbnails and writes the paths itself.
|
||||
// Pre-pass for the same reason as the Brush, Transform, and Image migrations above: rebuilding the network orphans its child paths.
|
||||
let monitored_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
let outdated_layers: Vec<(NodeId, Vec<NodeId>, DefinitionIdentifier)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
@@ -1408,12 +1410,16 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let is_merge_or_artboard = [DefinitionIdentifier::Network("Merge".into()), DefinitionIdentifier::Network("Artboard".into())].contains(&reference);
|
||||
|
||||
let has_monitor = network.nodes.values().any(|inner_node| is_monitor(&inner_node.implementation));
|
||||
let path_of_subgraph = DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER);
|
||||
let has_removed_node = network
|
||||
.nodes
|
||||
.values()
|
||||
.any(|inner_node| is_monitor(&inner_node.implementation) || inner_node.implementation == path_of_subgraph);
|
||||
|
||||
(is_merge_or_artboard && has_monitor).then_some((*node_id, path, reference))
|
||||
(is_merge_or_artboard && has_removed_node).then_some((*node_id, path, reference))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path, reference) in &monitored_layers {
|
||||
for (node_id, network_path, reference) in &outdated_layers {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut definition.default_node_template());
|
||||
}
|
||||
@@ -1680,6 +1686,49 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// The "Gradient Form" node was replaced by "Gradient Curvature", whose two curvatures take the presets of the form it set
|
||||
const GRADIENT_FORM: [&str; 2] = ["math_nodes::GradientFormNode", "math_nodes::GradientTypeNode"];
|
||||
let gradient_form_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return None };
|
||||
GRADIENT_FORM.contains(&identifier.as_str().split('<').next().unwrap_or_default()).then_some((*node_id, path))
|
||||
})
|
||||
.collect();
|
||||
for (node_id, network_path) in &gradient_form_nodes {
|
||||
let Some(definition) = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(graphene_std::math_nodes::gradient_curvature::IDENTIFIER)) else {
|
||||
continue;
|
||||
};
|
||||
let mut node_template = definition.default_node_template();
|
||||
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
reset_default_display_name(document, node_id, network_path, "Gradient Form");
|
||||
|
||||
if let Some(input) = old_inputs.first() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), input.clone(), network_path);
|
||||
}
|
||||
|
||||
let [start, end] = match old_inputs.get(1).and_then(|input| input.as_value()) {
|
||||
Some(TaggedValue::GradientForm(GradientForm::Radial)) => graphene_std::renderer::dial_gradient::RADIAL_DIALS,
|
||||
Some(TaggedValue::GradientForm(GradientForm::Linear)) => graphene_std::renderer::dial_gradient::LINEAR_DIALS,
|
||||
_ => {
|
||||
log::warn!("Old \"Gradient Form\" node {node_id} has no fixed form to migrate, so it becomes linear");
|
||||
graphene_std::renderer::dial_gradient::LINEAR_DIALS
|
||||
}
|
||||
};
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(start), false), network_path);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 2), NodeInput::value(TaggedValue::Number(end), false), network_path);
|
||||
}
|
||||
|
||||
// "Position on Path" and "Tangent on Path" were merged into the multi-output "Evaluate Path" node, with position at output 0 and tangent direction at output 1.
|
||||
// Tangent instances get an "Inverse Tangent" node inserted to turn that direction back into the angle their downstream wires expect.
|
||||
const POSITION_ON_PATH: &str = "graphene_core::vector::PositionOnPathNode";
|
||||
@@ -1858,6 +1907,52 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew images cut off at a square, 100 units for a clipped Noise Pattern and 1 for Mandelbrot, where their
|
||||
// patterns now fill the plane. An old Noise Pattern has a Clip toggle, after the primary input or first from before that input existed,
|
||||
// and an old Mandelbrot lacks the primary input. Each takes the current inputs, with a square filled by its pattern where it was cut off.
|
||||
let old_pattern_nodes = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter_map(|(node_id, node, path)| {
|
||||
let reference = document.network_interface.reference(node_id, &path)?;
|
||||
let clipped = |clip_index: usize| !matches!(node.inputs.get(clip_index).and_then(|input| input.as_value()), Some(TaggedValue::Bool(false)));
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) {
|
||||
let starts_with_clip = matches!(node.inputs.first().and_then(|input| input.as_value()), Some(TaggedValue::Bool(_)));
|
||||
let clip_index = match node.inputs.len() {
|
||||
16 => 1,
|
||||
15 if starts_with_clip => 0,
|
||||
_ => return None,
|
||||
};
|
||||
return Some((*node_id, path, reference, Some(clip_index), clipped(clip_index).then_some(100.)));
|
||||
}
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER) && node.inputs.is_empty() {
|
||||
return Some((*node_id, path, reference, None, Some(1.)));
|
||||
}
|
||||
None
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (node_id, network_path, reference, clip_index, clipped_size) in &old_pattern_nodes {
|
||||
let Some(definition) = resolve_document_node_type(reference) else { continue };
|
||||
let mut node_template = definition.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let Some(old_inputs) = document.network_interface.replace_inputs(node_id, network_path, &mut node_template) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// The noise settings follow the Clip toggle, in the same order as the current inputs after the primary one
|
||||
if let Some(clip_index) = clip_index {
|
||||
for (offset, input) in old_inputs.iter().skip(clip_index + 1).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 1 + offset), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(size) = clipped_size {
|
||||
fill_square_with_pattern(document, node_id, network_path, *size);
|
||||
}
|
||||
}
|
||||
|
||||
// Parameters that historically accepted fractional numbers are now integers (the polygon and star "Sides", the index,
|
||||
// shift amount, and slice bound parameters of the list, string, and regex nodes, the "Path is Closed" index, and the
|
||||
// "Blend" count), so a stored F64 truncates as those slots' own casts and Floor node did, preserving what documents drew
|
||||
@@ -1910,9 +2005,6 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
// Last, so the rest of the graph is upgraded enough to compile when each Copy to Points node's content type is resolved
|
||||
migrate_copy_to_points_nodes(document);
|
||||
|
||||
// After the upgrades that add or rewire nodes, so the nodes they place are converted too
|
||||
document.network_interface.convert_positions_to_relative();
|
||||
|
||||
// Bringing an old document up to date is not a set of edits on it, it is how the document arrives.
|
||||
// The upgrades run through the ordinary mutators, so the store records them; dropping what they
|
||||
// recorded leaves the opened document as the baseline rather than as a pile of changes to itself.
|
||||
@@ -1920,6 +2012,76 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
document.require_whole_document_stage();
|
||||
}
|
||||
|
||||
/// Splices a rectangle filled with the pattern node's output onto the wires leaving it, covering the square from the origin of the pattern's space out to `size`.
|
||||
/// The rectangle is centered on its origin, so a Transform moves it onto the square, and the paint is moved back by the same amount to stay in place.
|
||||
fn fill_square_with_pattern(document: &mut DocumentMessageHandler, pattern_node_id: &NodeId, network_path: &[NodeId], size: f64) -> Option<()> {
|
||||
let downstream_consumers: Vec<InputConnector> = document
|
||||
.network_interface
|
||||
.outward_wires(network_path)
|
||||
.and_then(|wires| wires.get(&OutputConnector::node(*pattern_node_id, 0)))
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let was_in_chain = document.network_interface.is_chain(pattern_node_id, network_path);
|
||||
|
||||
let template = |identifier| resolve_document_node_type(&DefinitionIdentifier::ProtoNode(identifier)).map(|definition| definition.default_node_template());
|
||||
let rectangle_template = template(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)?;
|
||||
let fill_template = template(graphene_std::vector_nodes::fill::IDENTIFIER)?;
|
||||
let transform_template = template(graphene_std::transform_nodes::transform::IDENTIFIER)?;
|
||||
|
||||
let [rectangle_id, fill_id, paint_transform_id, placement_transform_id] = [(); 4].map(|_| NodeId::new());
|
||||
document.network_interface.insert_node(rectangle_id, rectangle_template, network_path);
|
||||
document.network_interface.insert_node(fill_id, fill_template, network_path);
|
||||
document.network_interface.insert_node(paint_transform_id, transform_template.clone(), network_path);
|
||||
document.network_interface.insert_node(placement_transform_id, transform_template, network_path);
|
||||
|
||||
let set_value = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, value: TaggedValue| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::value(value, false), network_path);
|
||||
};
|
||||
let wire = |document: &mut DocumentMessageHandler, node_id: NodeId, index: usize, source: NodeId| {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(node_id, index), NodeInput::node(source, 0), network_path);
|
||||
};
|
||||
|
||||
// The rectangle's width and height, and the half-square translations of the paint and the filled rectangle
|
||||
set_value(document, rectangle_id, 1, TaggedValue::Number(size));
|
||||
set_value(document, rectangle_id, 2, TaggedValue::Number(size));
|
||||
set_value(document, paint_transform_id, 1, TaggedValue::DVec2(DVec2::splat(-size / 2.)));
|
||||
set_value(document, placement_transform_id, 1, TaggedValue::DVec2(DVec2::splat(size / 2.)));
|
||||
|
||||
wire(document, paint_transform_id, 0, *pattern_node_id);
|
||||
wire(document, fill_id, 0, rectangle_id);
|
||||
wire(document, fill_id, 1, paint_transform_id);
|
||||
wire(document, placement_transform_id, 0, fill_id);
|
||||
for consumer in &downstream_consumers {
|
||||
document.network_interface.set_input(consumer, NodeInput::node(placement_transform_id, 0), network_path);
|
||||
}
|
||||
|
||||
// A pattern in a layer chain gives way to the filled rectangle there, moving below to paint it, and otherwise the new nodes sit beside it
|
||||
if was_in_chain {
|
||||
document.network_interface.force_set_upstream_to_chain(&placement_transform_id, network_path);
|
||||
|
||||
if let Some(fill_position) = document.network_interface.position(&fill_id, network_path) {
|
||||
document.network_interface.set_absolute_position(&paint_transform_id, fill_position + IVec2::new(-7, 3), network_path);
|
||||
document.network_interface.set_absolute_position(pattern_node_id, fill_position + IVec2::new(-14, 3), network_path);
|
||||
}
|
||||
} else if let Some(position) = document.network_interface.position(pattern_node_id, network_path) {
|
||||
let offsets = [
|
||||
(paint_transform_id, IVec2::new(7, 0)),
|
||||
(rectangle_id, IVec2::new(7, -3)),
|
||||
(fill_id, IVec2::new(14, 0)),
|
||||
(placement_transform_id, IVec2::new(21, 0)),
|
||||
];
|
||||
for (node_id, offset) in offsets {
|
||||
document.network_interface.shift_absolute_node_position(&node_id, position + offset, network_path);
|
||||
}
|
||||
}
|
||||
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Converts a legacy stroke dash input (a `List<f64>`, single `f64`, or comma/space separated `String`) to the `DashPattern` value type.
|
||||
fn migrate_dash_input(input: &NodeInput) -> Option<NodeInput> {
|
||||
let NodeInput::Value { tagged_value, exposed } = input else { return None };
|
||||
@@ -2451,7 +2613,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
(graphene_std::artboard::create_artboard::BackgroundInput.into(), Color::WHITE),
|
||||
(graphene_std::math_nodes::color_value::ColorInput.into(), Color::TRANSPARENT),
|
||||
(graphene_std::raster_nodes::adjustments::black_and_white::TintInput.into(), Color::BLACK),
|
||||
(graphene_std::raster_nodes::blending_nodes::color_overlay::ColorInput.into(), Color::BLACK),
|
||||
];
|
||||
for (parameter, fallback) in conversions {
|
||||
if reference != DefinitionIdentifier::ProtoNode(parameter.node_identifier.clone()) {
|
||||
@@ -2772,20 +2933,6 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
}
|
||||
}
|
||||
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER) && inputs_count == 15 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, 0), NodeInput::value(TaggedValue::None, false), network_path);
|
||||
for (i, input) in old_inputs.iter().enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, i + 1), input.clone(), network_path);
|
||||
}
|
||||
}
|
||||
|
||||
// The Threshold node's luminance calculation input was retired
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::threshold::IDENTIFIER) && inputs_count == 4 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
@@ -5104,6 +5251,54 @@ mod tests {
|
||||
assert!(matches!(migrated, NodeInput::Value { exposed: true, .. }), "the exposed flag should be kept");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gradient_form_nodes_become_gradient_curvature_presets() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplate;
|
||||
use graphene_std::renderer::dial_gradient::{LINEAR_DIALS, RADIAL_DIALS};
|
||||
|
||||
let (source_id, form_id) = (NodeId(1), NodeId(2));
|
||||
for (identifier, form, dials) in [
|
||||
("math_nodes::GradientFormNode", GradientForm::Radial, RADIAL_DIALS),
|
||||
("math_nodes::GradientTypeNode", GradientForm::Linear, LINEAR_DIALS),
|
||||
] {
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
let placeholder = || NodeInput::value(TaggedValue::None, false);
|
||||
document.network_interface.insert_node(
|
||||
source_id,
|
||||
NodeTemplate {
|
||||
inputs: vec![placeholder()],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.insert_node(
|
||||
form_id,
|
||||
NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(ProtoNodeIdentifier::new(identifier)),
|
||||
inputs: vec![placeholder(); 2],
|
||||
..Default::default()
|
||||
},
|
||||
&[],
|
||||
);
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(form_id, 0), NodeInput::node(source_id, 0), &[]);
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(form_id, 1), NodeInput::value(TaggedValue::GradientForm(form), false), &[]);
|
||||
migrate(&mut document);
|
||||
|
||||
let node = &document.network_interface.document_network().nodes[&form_id];
|
||||
assert!(matches!(&node.implementation, DocumentNodeImplementation::ProtoNode(identifier) if *identifier == graphene_std::math_nodes::gradient_curvature::IDENTIFIER));
|
||||
assert_eq!(node.inputs.first(), Some(&NodeInput::node(source_id, 0)), "the gradient feeding {identifier} should stay wired");
|
||||
|
||||
let curvature = |index: usize| node.inputs.get(index).and_then(|input| input.as_value()).cloned();
|
||||
assert_eq!(
|
||||
[curvature(1), curvature(2)],
|
||||
dials.map(|dial| Some(TaggedValue::Number(dial))),
|
||||
"{form:?} should become its curvature presets"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_duplicate_node_replacements() {
|
||||
let mut hashmap = HashMap::<ProtoNodeIdentifier, u32>::new();
|
||||
@@ -6053,4 +6248,79 @@ mod tests {
|
||||
assert!(converted > 0. && converted < 1., "bias {bias} became {converted}");
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Pattern and Mandelbrot once drew a square of their patterns, which now fill the plane, so the square becomes a rectangle filled with the pattern
|
||||
#[tokio::test]
|
||||
async fn clipped_patterns_become_rectangles_filled_with_them() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let proto = |identifier| DefinitionIdentifier::ProtoNode(identifier);
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let noise = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER)).await;
|
||||
let mandelbrot = editor.create_node_by_name(proto(graphene_std::raster_nodes::std_nodes::mandelbrot::IDENTIFIER)).await;
|
||||
let noise_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
let mandelbrot_reader = editor.create_node_by_name(proto(graphene_std::transform_nodes::transform::IDENTIFIER)).await;
|
||||
|
||||
let document = editor.active_document_mut();
|
||||
for (reader, pattern) in [(noise_reader, noise), (mandelbrot_reader, mandelbrot)] {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(reader, 0), NodeInput::node(pattern, 0), &[]);
|
||||
}
|
||||
|
||||
// Save them as an older editor did, the Noise Pattern with its Clip toggle on and the Mandelbrot without a primary input
|
||||
let mut noise_inputs = document.network_interface.document_node(&noise, &[]).unwrap().inputs.clone();
|
||||
noise_inputs.insert(1, NodeInput::value(TaggedValue::Bool(true), false));
|
||||
noise_inputs[2] = NodeInput::value(TaggedValue::Integer(7), false);
|
||||
for (node_id, inputs) in [(noise, noise_inputs), (mandelbrot, Vec::new())] {
|
||||
let mut legacy = NodeTemplate { inputs, ..Default::default() };
|
||||
legacy.normalize_input_metadata();
|
||||
document.network_interface.replace_inputs(&node_id, &[], &mut legacy);
|
||||
}
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
let input = |node_id: NodeId, index: usize| interface.document_node(&node_id, &[]).and_then(|node| node.inputs.get(index)).cloned();
|
||||
let upstream = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_node());
|
||||
let value = |node_id: NodeId, index: usize| input(node_id, index).and_then(|input| input.as_value().cloned());
|
||||
|
||||
// Each reader now reads a rectangle of the square's size, moved onto the square, filled with the pattern moved back by the same amount
|
||||
for (reader, pattern, size) in [(noise_reader, noise, 100.), (mandelbrot_reader, mandelbrot, 1.)] {
|
||||
let placement = upstream(reader, 0).expect("the reader should read the placement transform");
|
||||
assert_eq!(value(placement, 1), Some(TaggedValue::DVec2(DVec2::splat(size / 2.))));
|
||||
|
||||
let fill = upstream(placement, 0).expect("the placement should move the filled rectangle");
|
||||
let rectangle = upstream(fill, 0).expect("the fill should paint a rectangle");
|
||||
assert_eq!((value(rectangle, 1), value(rectangle, 2)), (Some(TaggedValue::Number(size)), Some(TaggedValue::Number(size))));
|
||||
|
||||
let paint = upstream(fill, 1).expect("the fill should paint with the moved pattern");
|
||||
assert_eq!(value(paint, 1), Some(TaggedValue::DVec2(DVec2::splat(-size / 2.))));
|
||||
assert_eq!(upstream(paint, 0), Some(pattern));
|
||||
}
|
||||
|
||||
// The noise settings shift down past the removed Clip toggle, and the Mandelbrot gains its primary input
|
||||
assert_eq!(interface.document_node(&noise, &[]).unwrap().inputs.len(), 15);
|
||||
assert_eq!(value(noise, 1), Some(TaggedValue::Integer(7)));
|
||||
assert_eq!(interface.document_node(&mandelbrot, &[]).unwrap().inputs.len(), 1);
|
||||
}
|
||||
|
||||
// The demo draws its patterns through layers and adjustments, which must all take the generators the patterns now are
|
||||
#[tokio::test]
|
||||
async fn marbled_mandelbrot_renders_after_migration() {
|
||||
use crate::messages::portfolio::ingest::utility_types::{DataTransferItem, IngestAction};
|
||||
use crate::messages::prelude::IngestMessage;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
let data = std::fs::read("../demo-artwork/marbled-mandelbrot.graphite").unwrap();
|
||||
editor.dispatch(IngestMessage::Ingest {
|
||||
content: DataTransferItem::from_file("marbled-mandelbrot.graphite".into(), None, data).into(),
|
||||
action: IngestAction::Open,
|
||||
});
|
||||
if let Err(error) = editor.eval_graph_until_finished().await {
|
||||
panic!("The migrated demo failed to render: {error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use graph_craft::application_io::resource::ResourceId;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster_nodes::color_lookup_table::{Lut, LutParseError};
|
||||
use graphene_std::text::Font;
|
||||
|
||||
#[derive(ExtractField)]
|
||||
pub struct IngestMessageContext {
|
||||
@@ -66,7 +67,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
let preferred = items.into_iter().min_by_key(|item| match item.data {
|
||||
TransferData::Svg(_) => 0,
|
||||
TransferData::Raster { .. } => 1,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => 2,
|
||||
TransferData::Text(_) => 3,
|
||||
TransferData::ApplicationData(_) => 4,
|
||||
});
|
||||
@@ -103,11 +104,17 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
return;
|
||||
}
|
||||
|
||||
// The file goes to the document that asked for it, which may no longer be active or open once the dialog closes
|
||||
let resource_id = ResourceId::new();
|
||||
|
||||
let font = if data_type == DataType::Font { Font::from_data(&data) } else { None };
|
||||
let resource_store_message = match font {
|
||||
Some(font) => ResourceMessage::StoreFont { resource_id, font, data: data.into() },
|
||||
None => ResourceMessage::StoreEmbedded { resource_id, data: data.into() },
|
||||
};
|
||||
|
||||
let messages = [
|
||||
DocumentMessage::AddTransaction,
|
||||
DocumentMessage::Resource(ResourceMessage::StoreEmbedded { resource_id, data: data.into() }),
|
||||
resource_store_message.into(),
|
||||
DocumentMessage::NodeGraph(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: input_index as usize,
|
||||
@@ -172,7 +179,7 @@ impl MessageHandler<IngestMessage, IngestMessageContext> for IngestMessageHandle
|
||||
};
|
||||
(insert, None)
|
||||
}
|
||||
TransferData::Lut(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) | TransferData::Text(_) | TransferData::ApplicationData(_) => return unsupported(responses),
|
||||
};
|
||||
|
||||
if !place_at_origin {
|
||||
@@ -209,7 +216,7 @@ fn unsupported(responses: &mut VecDeque<Message>) {
|
||||
});
|
||||
}
|
||||
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image or LUT only if it fully parses.
|
||||
/// The reason a node input refuses the file, or `None` if it accepts it. An input that lists its accepted types takes an image, LUT, or font only if it parses.
|
||||
fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> Option<&'static str> {
|
||||
const WRONG_TYPE: &str = "This input does not accept the format of the chosen file.";
|
||||
|
||||
@@ -233,6 +240,7 @@ fn rejection(data: &[u8], data_type: DataType, accepted_types: &[DataType]) -> O
|
||||
}
|
||||
LutParseError::Unreadable => "This file could not be read as a LUT. It may be corrupted or an unsupported format variant.",
|
||||
}),
|
||||
DataType::Font => Font::from_data(data).is_none().then_some("This file could not be read as a font."),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -442,6 +450,27 @@ mod tests {
|
||||
assert!(!stores(IDENTITY_CUBE, TypeFilter::raster()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_input_stores_a_font_file_under_the_name_it_carries() {
|
||||
let font_file: &[u8] = crate::messages::portfolio::fonts::FALLBACK_FONT_RESOURCE.as_ref();
|
||||
let stored_font = |data: &[u8]| {
|
||||
let responses = ingest_named(data, Some("custom.ttf"), resource_input(TypeFilter::font().types), true);
|
||||
responses.into_iter().find_map(|message| match message {
|
||||
Message::Portfolio(PortfolioMessage::DocumentPassMessage {
|
||||
document_id: REQUESTING_DOCUMENT,
|
||||
message: DocumentMessage::Resource(ResourceMessage::StoreFont { font, .. }),
|
||||
}) => Some(font),
|
||||
_ => None,
|
||||
})
|
||||
};
|
||||
|
||||
assert_eq!(stored_font(font_file), Some(Font::new("Source Sans Pro".to_string(), "Regular (400)".to_string())));
|
||||
|
||||
// A file cut off after its intact signature, and an image named as a font
|
||||
assert_eq!(stored_font(&font_file[..40]), None);
|
||||
assert_eq!(stored_font(&Image::new(8, 8, Color::WHITE).to_png()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_table_outside_a_node_input_only_shows_a_dialog() {
|
||||
let responses = ingest_named(IDENTITY_CUBE, Some("grade.cube"), IngestAction::Import, true);
|
||||
|
||||
@@ -23,6 +23,9 @@ const TEXT_MIME: &str = "text/plain";
|
||||
const GRAPHITE_PREFIX: &str = "graphite: ";
|
||||
const SNIFFED_TEXT_LENGTH: usize = 4096;
|
||||
|
||||
const FONT_FILE_EXTENSIONS: &[&str] = &["ttf", "otf"];
|
||||
const FONT_FILE_SIGNATURES: [&[u8]; 3] = [&[0, 1, 0, 0], b"OTTO", b"true"];
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
pub enum IngestAction {
|
||||
@@ -65,6 +68,7 @@ pub enum DataType {
|
||||
Gdd,
|
||||
Svg,
|
||||
Raster(ImageFormat),
|
||||
Font,
|
||||
Lut,
|
||||
Text,
|
||||
#[default]
|
||||
@@ -98,6 +102,7 @@ impl DataType {
|
||||
GDD_FILE_EXTENSION => Self::Gdd,
|
||||
"svg" => Self::Svg,
|
||||
extension if LUT_FILE_EXTENSIONS.contains(&extension) => Self::Lut,
|
||||
extension if FONT_FILE_EXTENSIONS.contains(&extension) => Self::Font,
|
||||
extension => ImageFormat::from_extension(extension).map_or(Self::Unknown, Self::Raster),
|
||||
}
|
||||
}
|
||||
@@ -113,6 +118,9 @@ impl DataType {
|
||||
if let Ok(format) = image::guess_format(data) {
|
||||
return Self::Raster(format);
|
||||
}
|
||||
if FONT_FILE_SIGNATURES.iter().any(|signature| data.starts_with(signature)) {
|
||||
return Self::Font;
|
||||
}
|
||||
|
||||
// Only the head is read as text, where a character split by the cut is the one invalid sequence tolerated
|
||||
let head = &data[..data.len().min(SNIFFED_TEXT_LENGTH)];
|
||||
@@ -139,8 +147,7 @@ impl DataType {
|
||||
Self::Svg => SVG_MIME,
|
||||
Self::Raster(format) => format.to_mime_type(),
|
||||
Self::Text => TEXT_MIME,
|
||||
// The LUT formats share no MIME type
|
||||
Self::Lut | Self::Unknown => return None,
|
||||
Self::Lut | Self::Font | Self::Unknown => return None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -151,6 +158,7 @@ impl DataType {
|
||||
Self::Svg => &["svg"],
|
||||
Self::Raster(format) => format.extensions_str(),
|
||||
Self::Lut => LUT_FILE_EXTENSIONS,
|
||||
Self::Font => FONT_FILE_EXTENSIONS,
|
||||
Self::Text | Self::Unknown => &[],
|
||||
}
|
||||
}
|
||||
@@ -189,6 +197,13 @@ impl TypeFilter {
|
||||
types: vec![DataType::Lut],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn font() -> Self {
|
||||
Self {
|
||||
name: "Font".into(),
|
||||
types: vec![DataType::Font],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TypeFilter> for FileFilter {
|
||||
@@ -221,6 +236,7 @@ pub enum TransferData {
|
||||
Document(Vec<u8>),
|
||||
LegacyDocument(String),
|
||||
Lut(Vec<u8>),
|
||||
Font(Vec<u8>),
|
||||
Other(Vec<u8>),
|
||||
}
|
||||
|
||||
@@ -232,6 +248,7 @@ impl TransferData {
|
||||
Self::Document(_) => DataType::Gdd,
|
||||
Self::LegacyDocument(_) => DataType::GraphiteLegacy,
|
||||
Self::Lut(_) => DataType::Lut,
|
||||
Self::Font(_) => DataType::Font,
|
||||
Self::Text(_) | Self::ApplicationData(_) => DataType::Text,
|
||||
Self::Other(_) => DataType::Unknown,
|
||||
}
|
||||
@@ -240,7 +257,7 @@ impl TransferData {
|
||||
pub fn into_bytes(self) -> Vec<u8> {
|
||||
match self {
|
||||
Self::Text(text) | Self::Svg(text) | Self::LegacyDocument(text) => text.into_bytes(),
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Other(data) => data,
|
||||
Self::Raster { data, .. } | Self::Document(data) | Self::Lut(data) | Self::Font(data) | Self::Other(data) => data,
|
||||
Self::ApplicationData(_) => DataTransferItem::from(self).into_raw().map(|(_, data)| data.into_bytes()).unwrap_or_default(),
|
||||
}
|
||||
}
|
||||
@@ -295,6 +312,7 @@ impl DataTransferItem {
|
||||
DataType::Svg => text(data, TransferData::Svg),
|
||||
DataType::Raster(format) => TransferData::Raster { format, data },
|
||||
DataType::Lut => TransferData::Lut(data),
|
||||
DataType::Font => TransferData::Font(data),
|
||||
DataType::Text | DataType::Unknown => TransferData::Other(data),
|
||||
};
|
||||
Self { data, path: Some(path) }
|
||||
@@ -312,7 +330,7 @@ impl DataTransferItem {
|
||||
},
|
||||
TransferData::Svg(svg) => Some((DataType::Svg, RawData::Text(svg))),
|
||||
TransferData::Raster { format, data } => Some((DataType::Raster(format), RawData::Bytes(data))),
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Other(_) => None,
|
||||
TransferData::Document(_) | TransferData::LegacyDocument(_) | TransferData::Lut(_) | TransferData::Font(_) | TransferData::Other(_) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -404,6 +422,7 @@ mod tests {
|
||||
DataType::from_content("\u{feff}<?xml version=\"1.0\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\"/>".as_bytes()),
|
||||
DataType::Svg
|
||||
);
|
||||
assert_eq!(DataType::from_content(b"OTTO\0\x0c"), DataType::Font);
|
||||
assert_eq!(DataType::from_content(b"just text"), DataType::Unknown);
|
||||
assert_eq!(DataType::from_content(&[0xff, 0xfe, 0x00]), DataType::Unknown);
|
||||
}
|
||||
@@ -426,6 +445,7 @@ mod tests {
|
||||
assert_eq!(detect(Some("application/graphite+json"), ""), DataType::GraphiteLegacy);
|
||||
assert_eq!(detect(Some("image/png"), "document.gdd"), DataType::Raster(ImageFormat::Png));
|
||||
assert_eq!(detect(None, "grade.CUBE"), DataType::Lut);
|
||||
assert_eq!(detect(None, "Custom.TTF"), DataType::Font);
|
||||
assert_eq!(detect(Some("application/vnd.iccprofile"), "profile.icm"), DataType::Lut);
|
||||
assert_eq!(detect(Some("text/csv"), "table.csv"), DataType::Unknown);
|
||||
assert_eq!(DataType::detect(&[], None, None), DataType::Unknown);
|
||||
|
||||
@@ -346,7 +346,7 @@ pub fn replaceable_paint_chain(layer: LayerNodeIdentifier, network_interface: &N
|
||||
// A generator discards its primary input, so the chain ends at whichever one is reached
|
||||
let generators = [graphene_std::math_nodes::color_value::IDENTIFIER, graphene_std::math_nodes::gradient_value::IDENTIFIER];
|
||||
let setters = [
|
||||
graphene_std::math_nodes::gradient_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,
|
||||
|
||||
@@ -698,8 +698,7 @@ mod test_artboard {
|
||||
Err(e) => panic!("Failed to evaluate graph: {e}"),
|
||||
};
|
||||
instrumented
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, List<Artboard>>(&editor.runtime)
|
||||
.flatten()
|
||||
.grab_all_input::<graphene_std::graphic::extend::NewInput, graphene_std::list::Item<Artboard>>(&editor.runtime)
|
||||
.collect()
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -448,11 +448,11 @@ impl NodeGraphExecutor {
|
||||
};
|
||||
|
||||
// Calculate the bounding box of the region to be exported (artboard bounds always contribute).
|
||||
// `AllArtwork` and `Selection` expand vector layer bounds by the rendered stroke width so strokes
|
||||
// drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
// `AllArtwork` and `Selection` expand layer bounds by the rendered stroke width and effects reach so strokes
|
||||
// and shadows drawn at render-time (without a `Solidify Stroke`) aren't clipped at the export canvas edge.
|
||||
let bounds = match export_config.bounds {
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke(true, &[]),
|
||||
ExportBounds::AllArtwork => document.network_interface.document_bounds_document_space_with_stroke_and_effects(true),
|
||||
ExportBounds::Selection => document.network_interface.selected_bounds_document_space_with_stroke_and_effects(true, &[]),
|
||||
ExportBounds::Artboard(id) => document.metadata().bounding_box_document(id),
|
||||
}
|
||||
.ok_or_else(|| "No bounding box".to_string())?;
|
||||
@@ -1034,6 +1034,7 @@ impl NodeGraphExecutor {
|
||||
clip_targets,
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -1050,6 +1051,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
@@ -19,6 +19,7 @@ use graphene_std::runtime::AsyncRuntime;
|
||||
use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
@@ -27,6 +28,8 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc::{Receiver, Sender};
|
||||
use thumbnails::Thumbnails;
|
||||
|
||||
#[cfg(test)]
|
||||
mod layer_path_tests;
|
||||
mod observer;
|
||||
mod thumbnails;
|
||||
|
||||
@@ -212,6 +215,7 @@ impl NodeRuntime {
|
||||
};
|
||||
|
||||
apply_previews(&mut network, &previewed);
|
||||
write_layer_paths(&mut network, &layers);
|
||||
self.observer.replace_all(observations);
|
||||
self.resources = resources;
|
||||
|
||||
@@ -584,31 +588,48 @@ mod tests {
|
||||
editor.dispatch(Message::Wake).iter().any(|message| matches!(message, FrontendMessage::TriggerSaveFile { .. }))
|
||||
}
|
||||
|
||||
/// Fills the document's layer with a trace of noise, which an export has to wait on over several evaluations.
|
||||
fn vectorize_layer(editor: &mut EditorTestUtils) {
|
||||
/// Adds a layer tracing an image of noise, which an export has to wait on over several evaluations.
|
||||
async fn add_traced_noise_layer(editor: &mut EditorTestUtils) {
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use graphene_std::raster::Image;
|
||||
use graphene_std::raster::color::Color;
|
||||
|
||||
// Pseudo-random grays from an xorshift sequence, so the trace finds many small regions
|
||||
let mut noise = Image::new(64, 64, Color::BLACK);
|
||||
let mut state = 0x2545_f491_u32;
|
||||
for pixel in &mut noise.data {
|
||||
state ^= state << 13;
|
||||
state ^= state >> 17;
|
||||
state ^= state << 5;
|
||||
let gray = (state % 256) as f32 / 255.;
|
||||
*pixel = Color::from_rgbaf32_unchecked(gray, gray, gray, 1.);
|
||||
}
|
||||
editor.create_raster_image(noise, None).await;
|
||||
|
||||
// Trace the image between the layer and the nodes feeding it
|
||||
let layer = editor.active_document().metadata().all_layers().next().unwrap();
|
||||
let mut create = |node_type| {
|
||||
let node_id = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(node_id),
|
||||
node_type,
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
node_id
|
||||
};
|
||||
let noise = create(DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::std_nodes::noise_pattern::IDENTIFIER));
|
||||
let vectorize = create(DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER));
|
||||
let content = InputConnector::node_at_index(layer.to_node(), 1);
|
||||
let image = editor
|
||||
.active_document()
|
||||
.network_interface
|
||||
.upstream_output_connector(&content, &[])
|
||||
.expect("the image layer has content");
|
||||
|
||||
let vectorize = NodeId::new();
|
||||
editor.dispatch(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
node_id: Some(vectorize),
|
||||
node_type: DefinitionIdentifier::ProtoNode(graphene_std::vectorize_nodes::vectorize::IDENTIFIER),
|
||||
xy: None,
|
||||
add_transaction: true,
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(noise),
|
||||
output_connector: image,
|
||||
input_connector: InputConnector::node_at_index(vectorize, 0),
|
||||
});
|
||||
editor.dispatch(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::primary_output(vectorize),
|
||||
input_connector: InputConnector::node_at_index(layer.to_node(), 1),
|
||||
input_connector: content,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -655,8 +676,7 @@ mod tests {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(DocumentMessage::SetRenderMode { render_mode: RenderMode::SvgPreview }).await;
|
||||
editor.draw_rect(0., 0., 512., 512.).await;
|
||||
vectorize_layer(&mut editor);
|
||||
add_traced_noise_layer(&mut editor).await;
|
||||
|
||||
send_export(&mut editor);
|
||||
editor.runtime.update();
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::DefinitionIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{InputConnector, OutputConnector};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graphene_std::graphic::extend;
|
||||
|
||||
fn rectangle() -> DefinitionIdentifier {
|
||||
DefinitionIdentifier::ProtoNode(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER)
|
||||
}
|
||||
|
||||
// A layer without an Extend node gets its path written onto its whole output
|
||||
#[tokio::test]
|
||||
async fn a_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let rectangle = editor.create_node_by_name_at(rectangle(), 0, 0).await;
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
assert!(editor.active_document().metadata().click_targets.is_empty(), "A node not shown as a layer should have no click targets");
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: rectangle, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(rectangle, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"A node shown as a layer should have click targets"
|
||||
);
|
||||
}
|
||||
|
||||
// A layer that is an Extend node gets its path written onto what it adds
|
||||
#[tokio::test]
|
||||
async fn an_extend_node_layer_gets_click_targets() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let extend = editor.create_node_by_name_at(DefinitionIdentifier::ProtoNode(extend::IDENTIFIER), 0, 0).await;
|
||||
let (below, added) = (editor.create_node_by_name_at(rectangle(), -10, 0).await, editor.create_node_by_name_at(rectangle(), -10, 4).await);
|
||||
for (rectangle, input) in [(below, InputConnector::node(extend, extend::BaseInput)), (added, InputConnector::node(extend, extend::NewInput))] {
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(rectangle, 0),
|
||||
input_connector: input,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::CreateWire {
|
||||
output_connector: OutputConnector::node(extend, 0),
|
||||
input_connector: InputConnector::Export(0),
|
||||
})
|
||||
.await;
|
||||
|
||||
editor.handle_message(NodeGraphMessage::SetToNodeOrLayer { node_id: extend, is_layer: true }).await;
|
||||
|
||||
let document = editor.active_document();
|
||||
let layer = LayerNodeIdentifier::new(extend, &document.network_interface);
|
||||
let click_targets = document.metadata().click_targets(layer);
|
||||
assert!(
|
||||
click_targets.is_some_and(|click_targets| !click_targets.is_empty()),
|
||||
"An Extend node shown as a layer should have click targets for what it adds"
|
||||
);
|
||||
}
|
||||
@@ -4,12 +4,11 @@ use crate::messages::frontend::FrontendMessage;
|
||||
use atlas::ThumbnailAtlasLayout;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graph_craft::application_io::PlatformEditorApi;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeNetwork};
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::application_io::{ApplicationIo, Texture};
|
||||
use graphene_std::bounds::RenderBoundingBox;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::graphic::extend;
|
||||
use graphene_std::list::{Item, List};
|
||||
#[cfg(feature = "gpu")]
|
||||
use graphene_std::ops::ConvertAsync;
|
||||
@@ -19,8 +18,9 @@ use graphene_std::raster_types::{CPU, GPU, Raster};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::transform::{Footprint, RenderQuality};
|
||||
use graphene_std::vector::Vector;
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic, NodeParameter};
|
||||
use graphene_std::{Artboard, Color, Context, ContextFeatures, Graphic};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::layer_content;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -399,20 +399,7 @@ pub fn layers_svg(layers: &[NodeId], network: &NodeNetwork, executor: &DynamicEx
|
||||
|
||||
/// The proto node giving the content a layer's thumbnail shows, which is only what the layer adds if it extends the stack below it.
|
||||
fn thumbnail_source(layer_path: &[NodeId], network: &NodeNetwork, executor: &DynamicExecutor) -> Option<NodeId> {
|
||||
let output = network.output_source(layer_path, 0)?;
|
||||
|
||||
// A hidden layer, or one passing through what's below it, has nothing of its own to show
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
let source = if node.implementation == DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
network.input_source(network_path, node.inputs.get(extend::NewInput::INDEX)?)?
|
||||
} else {
|
||||
output
|
||||
};
|
||||
let source = layer_content(layer_path, network)?.source(network)?;
|
||||
|
||||
executor.tree().source_map().get(source.as_slice()).map(|(id, _)| *id)
|
||||
}
|
||||
@@ -484,6 +471,7 @@ mod tests {
|
||||
use glam::UVec2;
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::application_io::TimingInformation;
|
||||
use interpreted_executor::layer_paths::layer_path_writer_id;
|
||||
|
||||
async fn compile_and_run(editor: &mut EditorTestUtils) {
|
||||
let portfolio = editor.portfolio_message_handler_mut();
|
||||
@@ -510,7 +498,7 @@ mod tests {
|
||||
let layer = editor.get_selected_layer().await.expect("The drawn rectangle should be selected").to_node();
|
||||
|
||||
compile_and_run(&mut editor).await;
|
||||
let merge_content = compiled_id(&editor, &[layer, shipped_node_id("Merge", NodeId(3))]);
|
||||
let merge_content = compiled_id(&editor, &[layer, layer_path_writer_id(shipped_node_id("Merge", NodeId(2)))]);
|
||||
assert!(merge_content.is_some(), "The Merge layer's content should be compiled");
|
||||
assert_eq!(
|
||||
editor.runtime.thumbnails.sources.get(&layer).copied(),
|
||||
|
||||
@@ -540,9 +540,10 @@
|
||||
margin-left: 8px;
|
||||
}
|
||||
|
||||
// A label alone in its row lines up with the parameter names that follow their expose buttons
|
||||
> .text-label:only-child {
|
||||
// A label with no expose button before it lines up with the parameter names that follow one
|
||||
> .text-label:first-child {
|
||||
margin-left: calc(20px + 8px + 8px);
|
||||
--wire-indent: 20px;
|
||||
}
|
||||
|
||||
> .separator.horizontal.unrelated {
|
||||
|
||||
@@ -8,27 +8,13 @@
|
||||
import { widgetSizingStyles } from "/src/utility-functions/widgets";
|
||||
import type { MenuListEntry, ActionShortcut, WidgetSizing } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
const DASH_ENTRY: MenuListEntry = {
|
||||
value: "",
|
||||
label: "-",
|
||||
icon: undefined,
|
||||
annotation: "",
|
||||
disabled: false,
|
||||
children: [],
|
||||
childrenHash: 0n,
|
||||
font: undefined,
|
||||
tooltipLabel: "",
|
||||
tooltipDescription: "",
|
||||
tooltipShortcut: undefined,
|
||||
tooltipCode: "",
|
||||
};
|
||||
|
||||
const dispatch = createEventDispatcher<{ selectedIndex: number; previewIndex: number; fileDrop: File }>();
|
||||
|
||||
let self: LayoutRow | undefined;
|
||||
|
||||
// Content
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, a dash is displayed
|
||||
export let selectedIndex: number | undefined = undefined; // When not provided, the placeholder is displayed
|
||||
export let placeholder = "-";
|
||||
export let drawIcon = false;
|
||||
export let disabled = false;
|
||||
// Children
|
||||
@@ -132,13 +118,13 @@
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function makeActiveEntry(): MenuListEntry {
|
||||
function makeActiveEntry(): MenuListEntry | undefined {
|
||||
const allEntries = entries.flat();
|
||||
|
||||
if (selectedIndex !== undefined && selectedIndex >= 0 && selectedIndex < allEntries.length) {
|
||||
return allEntries[selectedIndex];
|
||||
}
|
||||
return DASH_ENTRY;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function takesDraggedFile(e: DragEvent): boolean {
|
||||
@@ -187,10 +173,10 @@
|
||||
data-dropdown-input
|
||||
>
|
||||
<LayoutRow class="dropdown-box" classes={{ disabled, open }} {tooltipLabel} {tooltipDescription} {tooltipShortcut} on:click={() => !disabled && (open = true)} data-floating-menu-spawner>
|
||||
{#if activeEntry.icon}
|
||||
{#if activeEntry?.icon}
|
||||
<IconLabel class="dropdown-icon" icon={activeEntry.icon} />
|
||||
{/if}
|
||||
<TextLabel class="dropdown-label">{activeEntry.label}</TextLabel>
|
||||
<TextLabel class="dropdown-label">{activeEntry?.label ?? placeholder}</TextLabel>
|
||||
<IconLabel class="dropdown-arrow" icon="DropdownArrow" />
|
||||
</LayoutRow>
|
||||
<MenuList
|
||||
@@ -200,7 +186,7 @@
|
||||
on:activeEntry={({ detail }) => commitEntry(detail)}
|
||||
on:open={({ detail }) => (open = detail)}
|
||||
{open}
|
||||
activeEntry={activeEntry === DASH_ENTRY ? undefined : activeEntry}
|
||||
{activeEntry}
|
||||
{entries}
|
||||
entriesHash={entriesHash || 0n}
|
||||
{drawIcon}
|
||||
|
||||
@@ -577,6 +577,9 @@ tagged_value! {
|
||||
TonalRange(raster_nodes::adjustments::TonalRange),
|
||||
AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel),
|
||||
HueSaturationRange(raster_nodes::adjustments::HueSaturationRange),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -711,6 +714,25 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_stroke_align(input: &str) -> Option<vector::style::StrokeAlign> {
|
||||
let mut choices = input.split("::");
|
||||
let (first, second) = (choices.next()?.trim(), choices.next()?.trim());
|
||||
if first == "StrokeAlign" {
|
||||
return Some(match second {
|
||||
"Center" => vector::style::StrokeAlign::Center,
|
||||
"Inside" => vector::style::StrokeAlign::Inside,
|
||||
"Outside" => vector::style::StrokeAlign::Outside,
|
||||
_ => {
|
||||
log::error!("Invalid StrokeAlign default type variant: {input}");
|
||||
return None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
log::error!("Invalid StrokeAlign default type: {input}");
|
||||
None
|
||||
}
|
||||
|
||||
match ty {
|
||||
Type::Generic(_) => None,
|
||||
Type::Concrete(concrete_type) => {
|
||||
@@ -729,6 +751,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Graphic>() => to_color(string).map(TaggedValue::Color)?,
|
||||
() if ty == TypeId::of::<Gradient>() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?,
|
||||
() if ty == TypeId::of::<ReferencePoint>() => to_reference_point(string).map(TaggedValue::ReferencePoint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => return None,
|
||||
|
||||
@@ -2,6 +2,7 @@ use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{NodeId, NodeNetwork};
|
||||
use graph_craft::proto::{ConstructionArgs, ProtoNetwork, ProtoNode};
|
||||
use graphene_std::graphic::write_layer_path;
|
||||
use graphene_std::simplify_identifier_name;
|
||||
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
|
||||
use std::error::Error;
|
||||
@@ -57,6 +58,7 @@ enum Kind {
|
||||
Nullify,
|
||||
Expand,
|
||||
Scope,
|
||||
LayerPath,
|
||||
}
|
||||
|
||||
impl Kind {
|
||||
@@ -68,6 +70,7 @@ impl Kind {
|
||||
Kind::Nullify => "+nullify",
|
||||
Kind::Expand => "+expand",
|
||||
Kind::Scope => "+scope",
|
||||
Kind::LayerPath => "+layer-path",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -234,6 +237,7 @@ fn kind(proto: &ProtoNode, origin: &[NodeId], document: &Document) -> Kind {
|
||||
_ if appended && path.last() == Some(&NodeId(10)) => Kind::Nullify,
|
||||
_ if proto.original_location.auto_convert_index.is_some() => Kind::Convert,
|
||||
ConstructionArgs::Value(_) => Kind::Value,
|
||||
_ if proto.identifier == write_layer_path::IDENTIFIER => Kind::LayerPath,
|
||||
_ if origin.is_empty() => Kind::Scope,
|
||||
_ if document[origin].1.as_ref() == Some(&proto.identifier) => Kind::Document,
|
||||
_ => Kind::Expand,
|
||||
|
||||
@@ -13,6 +13,7 @@ use graph_craft::proto::ProtoNetwork;
|
||||
use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::DynamicExecutor;
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
@@ -24,13 +25,15 @@ use std::sync::{Arc, Mutex};
|
||||
pub struct OpenedDocument {
|
||||
pub gdd: Option<GddV1>,
|
||||
pub network: NodeNetwork,
|
||||
/// The path of every layer in `network`.
|
||||
pub layers: Vec<Vec<NodeId>>,
|
||||
/// What `dump` shows for each node and network, when asked for.
|
||||
pub names: Option<HashMap<Vec<NodeId>, String>>,
|
||||
}
|
||||
|
||||
/// Open `path` with [`document_loader::open_document`]. `with_names` also collects its display names.
|
||||
pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocument, Box<dyn Error>> {
|
||||
let LoadedDocument { network, origin } = document_loader::open_document(path).await?;
|
||||
let LoadedDocument { network, layers, origin } = document_loader::open_document(path).await?;
|
||||
|
||||
let (gdd, names) = match origin {
|
||||
DocumentOrigin::Legacy(document_string) => (None, with_names.then(|| dump::legacy_names(&document_string))),
|
||||
@@ -43,7 +46,7 @@ pub async fn open_document(path: &Path, with_names: bool) -> Result<OpenedDocume
|
||||
(Some(*gdd), names)
|
||||
}
|
||||
};
|
||||
Ok(OpenedDocument { gdd, network, names })
|
||||
Ok(OpenedDocument { gdd, network, layers, names })
|
||||
}
|
||||
|
||||
/// The name of each node, keyed by the path the dump visits it at.
|
||||
@@ -89,7 +92,9 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
(application_io, editor_api)
|
||||
}
|
||||
|
||||
pub fn compile_graph(network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
/// Compile `network`, writing the path of each of its `layers` onto what that layer renders.
|
||||
pub fn compile_graph(mut network: NodeNetwork, layers: &[Vec<NodeId>], editor_api: Arc<PlatformEditorApi>, gdd: Option<&GddV1>, runtime: RuntimeHandle) -> Result<ProtoNetwork, Box<dyn Error>> {
|
||||
write_layer_paths(&mut network, layers);
|
||||
let mut network = wrap_network_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
@@ -117,7 +122,7 @@ pub async fn compile_document(document: OpenedDocument) -> Result<CompiledDocume
|
||||
let (application_io, editor_api) = editor_api(document.gdd.as_ref()).await;
|
||||
let spawner = Arc::new(TokioSpawner::default());
|
||||
let runtime = AsyncRuntime::new(spawner.clone());
|
||||
let proto_network = compile_graph(document.network, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
let proto_network = compile_graph(document.network, &document.layers, editor_api, document.gdd.as_ref(), runtime.handle())?;
|
||||
|
||||
Ok(CompiledDocument {
|
||||
proto_network,
|
||||
|
||||
@@ -124,11 +124,11 @@ impl Viewer {
|
||||
}
|
||||
|
||||
fn recompile(&mut self) {
|
||||
let network = match self.runtime.block_on(self.live.network()) {
|
||||
Ok(network) => network,
|
||||
let (network, layers) = match self.runtime.block_on(self.live.network_with_layers()) {
|
||||
Ok(network_with_layers) => network_with_layers,
|
||||
Err(error) => return log::error!("Failed to build the runtime network: {error}"),
|
||||
};
|
||||
let proto = match compile_graph(network, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
let proto = match compile_graph(network, &layers, self.editor_api.clone(), Some(self.live.document()), self.graph_runtime.handle()) {
|
||||
Ok(proto) => proto,
|
||||
Err(error) => return log::error!("Compile failed: {error}"),
|
||||
};
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Writes each layer's path onto what it renders, so what's rendered can be traced back to its layer.
|
||||
|
||||
use crate::node_registry::NODE_REGISTRY;
|
||||
use graph_craft::ProtoNodeIdentifier;
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, DocumentNodeMetadata, NodeId, NodeInput, NodeNetwork};
|
||||
use graphene_std::NodeParameter;
|
||||
use graphene_std::graphic::{extend, write_layer_path};
|
||||
use graphene_std::list::NodeIdPath;
|
||||
use std::collections::HashMap;
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
/// What a layer adds to the document, which is what its thumbnail shows and what its path is written onto.
|
||||
pub enum LayerContent {
|
||||
/// What the Extend node the layer ends in is given to add, with the path of the network the node is in.
|
||||
Added { network_path: Vec<NodeId>, extend: NodeId },
|
||||
/// Everything the layer outputs, from the node at this path.
|
||||
Output(Vec<NodeId>),
|
||||
}
|
||||
|
||||
/// The content of the layer at this path, unless it's hidden or passes through what's below it and so has none of its own.
|
||||
pub fn layer_content(layer_path: &[NodeId], network: &NodeNetwork) -> Option<LayerContent> {
|
||||
let output = network.output_source(layer_path, 0)?;
|
||||
if !output.starts_with(layer_path) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let (node_id, network_path) = output.split_last()?;
|
||||
let node = network.nested_network(network_path)?.nodes.get(node_id)?;
|
||||
if node.implementation != DocumentNodeImplementation::ProtoNode(extend::IDENTIFIER) {
|
||||
return Some(LayerContent::Output(output));
|
||||
}
|
||||
|
||||
Some(LayerContent::Added {
|
||||
network_path: network_path.to_vec(),
|
||||
extend: *node_id,
|
||||
})
|
||||
}
|
||||
|
||||
impl LayerContent {
|
||||
/// The path of the node producing the content once compiled.
|
||||
pub fn source(&self, network: &NodeNetwork) -> Option<Vec<NodeId>> {
|
||||
match self {
|
||||
Self::Added { network_path, extend } => {
|
||||
let added = network.nested_network(network_path)?.nodes.get(extend)?.inputs.get(extend::NewInput::INDEX)?;
|
||||
network.input_source(network_path, added)
|
||||
}
|
||||
Self::Output(output) => Some(output.clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Puts a node after each layer's content that writes the layer's path onto it.
|
||||
/// A layer has none if its content may be of a type that can't carry the path.
|
||||
pub fn write_layer_paths(network: &mut NodeNetwork, layer_paths: &[Vec<NodeId>]) {
|
||||
let mut carries_layer_path = HashMap::new();
|
||||
|
||||
// O(layers * depth)
|
||||
for layer_path in layer_paths {
|
||||
let Some((layer, parent_path)) = layer_path.split_last() else { continue };
|
||||
let Some(content) = layer_content(layer_path, network) else { continue };
|
||||
|
||||
// An Extend node nested deeper than the layer may be in a network that other layers share.
|
||||
// So the writer goes after the layer's output, and the Extend node only decides if the content can carry the path.
|
||||
let content = match content {
|
||||
LayerContent::Added { network_path, extend } if network_path.len() > layer_path.len() => LayerContent::Output([network_path.as_slice(), &[extend]].concat()),
|
||||
content => content,
|
||||
};
|
||||
|
||||
let Some(source) = content.source(network) else { continue };
|
||||
if !source_can_carry_layer_path(source, network, &mut carries_layer_path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match content {
|
||||
// The writer goes between the Extend node and what it's given to add, inside the layer or beside it if the layer is that node
|
||||
LayerContent::Added { network_path, extend } => {
|
||||
let writer = layer_path_writer_id(extend);
|
||||
let layer_beside = if network_path.len() == layer_path.len() { Vec::new() } else { vec![*layer] };
|
||||
let Some(holder) = network_mut(network, &network_path) else { continue };
|
||||
let Some(added) = holder.nodes.get_mut(&extend).and_then(|node| node.inputs.get_mut(extend::NewInput::INDEX)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
// Every layer made from the same network shares the writer
|
||||
if *added == NodeInput::node(writer, 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let content = std::mem::replace(added, NodeInput::node(writer, 0));
|
||||
holder.nodes.insert(writer, layer_path_writer(content, layer_beside));
|
||||
}
|
||||
// The writer goes beside the layer, taking over everything its output feeds
|
||||
LayerContent::Output(_) => {
|
||||
let writer = layer_path_writer_id(*layer);
|
||||
let Some(holder) = network_mut(network, parent_path) else { continue };
|
||||
if holder.nodes.contains_key(&writer) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (output, written) = (NodeInput::node(*layer, 0), NodeInput::node(writer, 0));
|
||||
let inputs = holder.nodes.values_mut().flat_map(|node| &mut node.inputs).chain(&mut holder.exports);
|
||||
inputs.filter(|input| **input == output).for_each(|input| *input = written.clone());
|
||||
|
||||
holder.nodes.insert(writer, layer_path_writer(output, vec![*layer]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the layer path writer fares with what a proto node outputs.
|
||||
#[derive(Clone, Copy)]
|
||||
enum CarriesLayerPath {
|
||||
Always,
|
||||
/// The node outputs the type its one input is given, so that decides it.
|
||||
AsItsInput,
|
||||
Never,
|
||||
}
|
||||
|
||||
/// Whether the layer path writer can take everything the proto node at this path may output.
|
||||
fn source_can_carry_layer_path(mut source: Vec<NodeId>, network: &NodeNetwork, carries_layer_path: &mut HashMap<ProtoNodeIdentifier, CarriesLayerPath>) -> bool {
|
||||
loop {
|
||||
let Some((node_id, network_path)) = source.split_last() else { return false };
|
||||
let Some(node) = network.nested_network(network_path).and_then(|network| network.nodes.get(node_id)) else {
|
||||
return false;
|
||||
};
|
||||
let DocumentNodeImplementation::ProtoNode(identifier) = &node.implementation else { return false };
|
||||
|
||||
match *carries_layer_path.entry(identifier.clone()).or_insert_with(|| output_can_carry_layer_path(identifier)) {
|
||||
CarriesLayerPath::Always => return true,
|
||||
CarriesLayerPath::Never => return false,
|
||||
CarriesLayerPath::AsItsInput => {
|
||||
let Some(input_source) = node.inputs.first().and_then(|input| network.input_source(network_path, input)) else {
|
||||
return false;
|
||||
};
|
||||
source = input_source;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn output_can_carry_layer_path(identifier: &ProtoNodeIdentifier) -> CarriesLayerPath {
|
||||
let (Some(outputs), Some(writers)) = (NODE_REGISTRY.get(identifier), NODE_REGISTRY.get(&write_layer_path::IDENTIFIER)) else {
|
||||
return CarriesLayerPath::Never;
|
||||
};
|
||||
|
||||
let writes_type = |output: &graph_craft::Type| {
|
||||
let content = |writer: &graphene_std::NodeIOTypes| writer.inputs.get(write_layer_path::ContentInput::INDEX).is_some_and(|content| content.nested_type() == output);
|
||||
writers.keys().any(content)
|
||||
};
|
||||
if outputs.keys().all(|output| writes_type(output.return_value.nested_type())) {
|
||||
return CarriesLayerPath::Always;
|
||||
}
|
||||
|
||||
let as_its_input = |output: &graphene_std::NodeIOTypes| matches!(output.inputs.as_slice(), [input] if input.nested_type() == output.return_value.nested_type());
|
||||
if outputs.keys().all(as_its_input) {
|
||||
CarriesLayerPath::AsItsInput
|
||||
} else {
|
||||
CarriesLayerPath::Never
|
||||
}
|
||||
}
|
||||
|
||||
/// The network at this path, which is either an entry of the definitions table or held by its node.
|
||||
fn network_mut<'a>(network: &'a mut NodeNetwork, path: &[NodeId]) -> Option<&'a mut NodeNetwork> {
|
||||
// The last table entry along the path, which holds any networks after it
|
||||
let mut table_entry = None;
|
||||
let mut current = &*network;
|
||||
for (index, node_id) in path.iter().enumerate() {
|
||||
current = match ¤t.nodes.get(node_id)?.implementation {
|
||||
DocumentNodeImplementation::Definition(id) => {
|
||||
table_entry = Some((*id, index + 1));
|
||||
network.definitions.get(id)?
|
||||
}
|
||||
DocumentNodeImplementation::Network(held) => held,
|
||||
_ => return None,
|
||||
};
|
||||
}
|
||||
|
||||
let (mut current, held_path) = match table_entry {
|
||||
Some((id, held_from)) => (network.definitions.get_mut(&id)?, &path[held_from..]),
|
||||
None => (network, path),
|
||||
};
|
||||
for node_id in held_path {
|
||||
let DocumentNodeImplementation::Network(held) = &mut current.nodes.get_mut(node_id)?.implementation else {
|
||||
return None;
|
||||
};
|
||||
current = held;
|
||||
}
|
||||
|
||||
Some(current)
|
||||
}
|
||||
|
||||
/// The ID of the node writing the layer path onto what the node with this ID outputs or is given, which stays the same between compilations.
|
||||
pub fn layer_path_writer_id(node_id: NodeId) -> NodeId {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
"layer path writer".hash(&mut hasher);
|
||||
node_id.hash(&mut hasher);
|
||||
NodeId(hasher.finish())
|
||||
}
|
||||
|
||||
fn layer_path_writer(content: NodeInput, layer_beside: Vec<NodeId>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs: vec![
|
||||
content,
|
||||
// The writer is directly inside the layer or beside it, so removing only its own ID gives the path
|
||||
NodeInput::value(TaggedValue::Integer(1), false),
|
||||
NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(layer_beside)), false),
|
||||
NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath),
|
||||
],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(write_layer_path::IDENTIFIER),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use graph_craft::document::NetworkId;
|
||||
|
||||
#[test]
|
||||
fn content_that_cannot_carry_a_layer_path_is_left_alone() {
|
||||
let path_node = DocumentNode {
|
||||
inputs: vec![NodeInput::Reflection(DocumentNodeMetadata::DocumentNodePath)],
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::graphic::path_of_subgraph::IDENTIFIER),
|
||||
..Default::default()
|
||||
};
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), path_node)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(1)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
|
||||
fn proto_node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
inputs,
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn definition_node(id: NetworkId) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Definition(id),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// A network shaped like 'Merge', where an Extend node adds what the node beside it gives.
|
||||
fn merge_like(added: DocumentNode) -> NodeNetwork {
|
||||
let extend = proto_node(extend::IDENTIFIER, vec![NodeInput::value(TaggedValue::None, false), NodeInput::node(NodeId(2), 0)]);
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(1), extend), (NodeId(2), added)].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
// One network is shared by a layer at the root and by a layer inside another layer, so the one writer inside it has to suit both
|
||||
#[test]
|
||||
fn a_network_shared_by_layers_at_different_depths_writes_each_layer_path() {
|
||||
let (merge, group) = (NetworkId(1), NetworkId(2));
|
||||
let rectangle = proto_node(graphene_std::vector::generator_nodes::rectangle::IDENTIFIER, Vec::new());
|
||||
let group_network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(30), 0)],
|
||||
nodes: [(NodeId(30), definition_node(merge))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(merge)), (NodeId(20), definition_node(group))].into_iter().collect(),
|
||||
definitions: [(merge, merge_like(rectangle)), (group, group_network)].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// The outer layer comes first in one order and last in the other
|
||||
let orders = [
|
||||
[vec![NodeId(20)], vec![NodeId(10)], vec![NodeId(20), NodeId(30)]],
|
||||
[vec![NodeId(10)], vec![NodeId(20), NodeId(30)], vec![NodeId(20)]],
|
||||
];
|
||||
let written = orders.map(|layer_paths| {
|
||||
let mut network = network.clone();
|
||||
write_layer_paths(&mut network, &layer_paths);
|
||||
network
|
||||
});
|
||||
assert_eq!(written[0], written[1], "The order the layers are given in should not change what's written");
|
||||
|
||||
// The writer writes the path of the layer holding its network, whichever layer that is
|
||||
let writer = &written[0].definitions[&merge].nodes[&layer_path_writer_id(NodeId(1))];
|
||||
let (levels_up, layer_beside) = (writer.input(write_layer_path::LevelsUpInput), writer.input(write_layer_path::LayerBesideInput));
|
||||
assert_eq!(levels_up, Some(&NodeInput::value(TaggedValue::Integer(1), false)));
|
||||
assert_eq!(layer_beside, Some(&NodeInput::value(TaggedValue::NodeIdPath(NodeIdPath::from(Vec::new())), false)));
|
||||
}
|
||||
|
||||
// Content that already writes its own layer path, like the 'Merge' networks of older documents, gets no second writer
|
||||
#[test]
|
||||
fn a_network_writing_its_own_layer_path_is_left_alone() {
|
||||
let write_attribute = proto_node(graphene_std::graphic::write_attribute::IDENTIFIER, Vec::new());
|
||||
let mut network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(10), 0)],
|
||||
nodes: [(NodeId(10), definition_node(NetworkId(1)))].into_iter().collect(),
|
||||
definitions: [(NetworkId(1), merge_like(write_attribute))].into_iter().collect(),
|
||||
..Default::default()
|
||||
};
|
||||
let unchanged = network.clone();
|
||||
|
||||
write_layer_paths(&mut network, &[vec![NodeId(10)]]);
|
||||
|
||||
assert_eq!(network, unchanged);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
#![recursion_limit = "256"]
|
||||
|
||||
pub mod dynamic_executor;
|
||||
pub mod layer_paths;
|
||||
pub mod node_registry;
|
||||
pub mod util;
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ use graphene_animation::AnimationCurve;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
use graphene_std::generator::Generator;
|
||||
use graphene_std::gradient::Gradient;
|
||||
use graphene_std::list::{AttributeValueDyn, Bundle, Item, List, ListDyn, NodeIdPath};
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -27,6 +28,7 @@ use graphene_std::vector::misc::{
|
||||
use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification};
|
||||
use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type};
|
||||
use graphene_std::{BevelDirection, BevelStyle, GlowSource};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -56,6 +58,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Raster<CPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<String>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<NodeIdPath>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => List<f64>]),
|
||||
@@ -76,6 +79,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Raster<GPU>>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Color>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Gradient>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<Generator>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<DashPattern>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<BoxCorners>]),
|
||||
async_node!(graphene_core::memo::MemoizeNode<_, _>, input: Context, fn_params: [Context => Item<TransferCurve>]),
|
||||
@@ -285,6 +289,9 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
TonalRange,
|
||||
AdjustmentChannel,
|
||||
HueSaturationRange,
|
||||
GlowSource,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
@@ -318,6 +325,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Graphic,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
String,
|
||||
f64,
|
||||
DVec2,
|
||||
@@ -350,6 +358,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
Raster<CPU>,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
f64,
|
||||
i64,
|
||||
bool,
|
||||
@@ -390,6 +399,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
String,
|
||||
Color,
|
||||
Gradient,
|
||||
Generator,
|
||||
Artboard,
|
||||
));
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -441,6 +451,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
// This is what lets a paint list zip element-wise against the content it paints.
|
||||
node_types.extend(embed_adapter_row!(from_element: Color, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Gradient, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Generator, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: String, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Vector, element: Graphic));
|
||||
node_types.extend(embed_adapter_row!(from_element: Raster<CPU>, element: Graphic));
|
||||
@@ -498,6 +509,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
attribute_value_node!(List<String>),
|
||||
attribute_value_node!(List<Color>),
|
||||
attribute_value_node!(List<Gradient>),
|
||||
attribute_value_node!(List<Generator>),
|
||||
attribute_value_node!(List<Vector>),
|
||||
attribute_value_node!(List<Raster<CPU>>),
|
||||
#[cfg(feature = "gpu")]
|
||||
@@ -526,6 +538,7 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
transform_list_node!(element: Raster<GPU>),
|
||||
transform_list_node!(element: Color),
|
||||
transform_list_node!(element: Gradient),
|
||||
transform_list_node!(element: Generator),
|
||||
];
|
||||
node_types.extend(transform_list_rows);
|
||||
let mut map: HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeConstructor>> = HashMap::new();
|
||||
|
||||
@@ -32,9 +32,10 @@ pub use glam_ext::FallibleVec2Operations;
|
||||
pub use graphene_hash;
|
||||
pub use graphene_hash::CacheHash;
|
||||
pub use list::{
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME, ATTR_END,
|
||||
ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_LETTER_SPACING,
|
||||
ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME, ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
ATTR_BACKGROUND, ATTR_BLEND_MODE, ATTR_CLIP, ATTR_CLIPPING_MASK, ATTR_DIMENSIONS, ATTR_EDITOR_CLICK_TARGET, ATTR_EDITOR_LAYER_PATH, ATTR_EDITOR_MERGED_LAYERS, ATTR_EDITOR_TEXT_FRAME,
|
||||
ATTR_EFFECTS, ATTR_END, ATTR_FONT, ATTR_FONT_SIZE, ATTR_GRADIENT_CYCLIC, ATTR_GRADIENT_END_CURVATURE, ATTR_GRADIENT_FORM, ATTR_GRADIENT_HUE_DIRECTION, ATTR_GRADIENT_INTERPOLATION,
|
||||
ATTR_GRADIENT_SPACE, ATTR_GRADIENT_SPREAD, ATTR_GRADIENT_START_CURVATURE, ATTR_LETTER_SPACING, ATTR_LETTER_TILT, ATTR_LINE_HEIGHT, ATTR_LOCATION, ATTR_MAX_HEIGHT, ATTR_MAX_WIDTH, ATTR_NAME,
|
||||
ATTR_OPACITY, ATTR_OPACITY_FILL, ATTR_START, ATTR_TEXT_ALIGN, ATTR_TRANSFORM, ATTR_TYPE,
|
||||
};
|
||||
pub use memo::MemoHash;
|
||||
pub use num_traits;
|
||||
|
||||
@@ -61,6 +61,11 @@ pub const ATTR_CLIP: &str = "clip";
|
||||
pub const ATTR_GRADIENT_SPREAD: &str = "gradient_spread";
|
||||
/// Gradient's `GradientForm` (`Linear` or `Radial`).
|
||||
pub const ATTR_GRADIENT_FORM: &str = "gradient_form";
|
||||
/// Gradient's `f64` curvature dial for the contour through its start, from -1 to 1: 0 is a line, ±1 is the start point
|
||||
/// itself, and between is a circle bowing toward (positive) or away from (negative) the end. Absent, the form decides it.
|
||||
pub const ATTR_GRADIENT_START_CURVATURE: &str = "gradient_start_curvature";
|
||||
/// Gradient's `f64` curvature dial for the contour through its end, like `gradient_start_curvature` with the ends swapped.
|
||||
pub const ATTR_GRADIENT_END_CURVATURE: &str = "gradient_end_curvature";
|
||||
/// Gradient's `GradientSpace`, the color space its stops interpolate in.
|
||||
pub const ATTR_GRADIENT_SPACE: &str = "gradient_space";
|
||||
/// Gradient's `GradientHueDirection` (`Shorter`, `Longer`, `Increasing`, or `Decreasing`), which way around the
|
||||
@@ -80,6 +85,9 @@ pub const ATTR_POSITION: &str = "position";
|
||||
pub const ATTR_MIDPOINT: &str = "midpoint";
|
||||
/// Item's ordered list of paint passes, of type `Appearance`. Earlier coverages paint first, compositing below later ones.
|
||||
pub const ATTR_APPEARANCE: &str = "appearance";
|
||||
/// Item's ordered list of effects, of type `Effects`, which the renderer applies in turn to the pixels the item renders to.
|
||||
/// Unlike the appearance, it doesn't cascade to descendants.
|
||||
pub const ATTR_EFFECTS: &str = "effects";
|
||||
// TODO: Add a "fill_rule" attribute as a sibling of "paint" on the coverage list (uniform across covers) once a FillRule type ships
|
||||
/// Coverage's `Graphic` paint (implicit default `Graphic::None`, painting nothing), on the
|
||||
/// `List<Coverage>` inside an `Appearance`.
|
||||
|
||||
@@ -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 }
|
||||
@@ -40,4 +42,5 @@ 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,533 @@
|
||||
//! 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;
|
||||
use crate::parameters::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 dyn_any::DynAny;
|
||||
use graphene_resource::Resource;
|
||||
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 {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(_)
|
||||
)
|
||||
}
|
||||
|
||||
/// 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))]
|
||||
#[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 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,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Radio)]
|
||||
pub enum RelativeAbsolute {
|
||||
#[default]
|
||||
Relative,
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// 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.);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,684 @@
|
||||
//! 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 crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
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(&|key| self.0.attributes().get_any(key)));
|
||||
|
||||
// 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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[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,197 @@
|
||||
//! Procedural patterns described by their settings, rendered at whatever resolution is needed of whatever part is seen by the kernels of the `raster-kernels` crate.
|
||||
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, StampParameters};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use dyn_any::DynAny;
|
||||
use glam::DAffine2;
|
||||
use std::any::Any;
|
||||
|
||||
/// Style of noise pattern.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, 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))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, 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))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
pub enum CellularDistanceFunction {
|
||||
#[default]
|
||||
Euclidean,
|
||||
#[label("Euclidean Squared (Faster)")]
|
||||
EuclideanSq,
|
||||
Manhattan,
|
||||
Hybrid,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, 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))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny, node_macro::ChoiceType)]
|
||||
#[widget(Dropdown)]
|
||||
pub enum DomainWarpType {
|
||||
#[default]
|
||||
None,
|
||||
#[label("OpenSimplex2")]
|
||||
OpenSimplex2,
|
||||
#[label("OpenSimplex2 Reduced")]
|
||||
OpenSimplex2Reduced,
|
||||
BasicGrid,
|
||||
}
|
||||
|
||||
/// The settings of a noise pattern, with lengths measured in the document units of the space it's sampled in.
|
||||
#[derive(Debug, Clone, Default, 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,
|
||||
}
|
||||
|
||||
/// A procedural pattern filling the whole plane, which renderers draw at whatever resolution they need across whatever part they see.
|
||||
/// The item's transform places the pattern's own space, and a noise pattern's settings ride the item as attributes named after the Noise Pattern node's parameters.
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, CacheHash, DynAny)]
|
||||
pub enum Generator {
|
||||
#[default]
|
||||
Noise,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Generator {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::Noise => "Noise",
|
||||
Self::Mandelbrot => "Mandelbrot",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl BoundingBox for Generator {
|
||||
fn bounding_box(&self, transform: DAffine2, _include_stroke: bool) -> RenderBoundingBox {
|
||||
match transform.matrix2.determinant() == 0. {
|
||||
true => RenderBoundingBox::None,
|
||||
false => RenderBoundingBox::Infinite,
|
||||
}
|
||||
}
|
||||
|
||||
fn thumbnail_bounding_box(&self, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
self.bounding_box(transform, include_stroke)
|
||||
}
|
||||
}
|
||||
|
||||
impl NoiseSettings {
|
||||
/// Stamps every setting onto the generator's item, whatever its value, so which attributes the item carries doesn't depend on them.
|
||||
pub fn stamp(&self, item: &mut Item<Generator>) {
|
||||
self.clone().visit_parameters(&mut StampParameters(item));
|
||||
}
|
||||
|
||||
/// Visits each setting with the attribute it rides, named after the Noise Pattern node's parameter, and its default, which is the node's.
|
||||
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor) {
|
||||
visitor.parameter("seed", &mut self.seed, 0);
|
||||
visitor.parameter("scale", &mut self.scale, 10.);
|
||||
visitor.parameter("noise_type", &mut self.noise_type, NoiseType::default());
|
||||
visitor.parameter("domain_warp_type", &mut self.domain_warp_type, DomainWarpType::default());
|
||||
visitor.parameter("domain_warp_amplitude", &mut self.domain_warp_amplitude, 100.);
|
||||
visitor.parameter("fractal_type", &mut self.fractal_type, FractalType::default());
|
||||
visitor.parameter("fractal_octaves", &mut self.fractal_octaves, 3);
|
||||
visitor.parameter("fractal_lacunarity", &mut self.fractal_lacunarity, 2.);
|
||||
visitor.parameter("fractal_gain", &mut self.fractal_gain, 0.5);
|
||||
visitor.parameter("fractal_weighted_strength", &mut self.fractal_weighted_strength, 0.);
|
||||
visitor.parameter("fractal_ping_pong_strength", &mut self.fractal_ping_pong_strength, 2.);
|
||||
visitor.parameter("cellular_distance_function", &mut self.cellular_distance_function, CellularDistanceFunction::default());
|
||||
visitor.parameter("cellular_return_type", &mut self.cellular_return_type, CellularReturnType::default());
|
||||
visitor.parameter("cellular_jitter", &mut self.cellular_jitter, 1.);
|
||||
}
|
||||
}
|
||||
|
||||
impl GeneratorPattern {
|
||||
/// The pattern a generator draws, reading a noise pattern's settings with `attribute`, which looks one of the item's attributes up by key.
|
||||
/// Each setting the item lacks takes its default.
|
||||
pub fn decode<'a>(generator: Generator, attribute: &'a dyn Fn(&str) -> Option<&'a dyn Any>) -> Self {
|
||||
match generator {
|
||||
Generator::Noise => {
|
||||
let mut settings = NoiseSettings::default();
|
||||
settings.visit_parameters(&mut ReadParameters(attribute));
|
||||
Self::Noise(settings)
|
||||
}
|
||||
Generator::Mandelbrot => Self::Mandelbrot,
|
||||
}
|
||||
}
|
||||
|
||||
/// The pattern a generator item draws.
|
||||
pub fn of_item(item: &Item<Generator>) -> Self {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use crate::appearance::{Appearance, Cover, Coverage};
|
||||
use crate::generator::Generator;
|
||||
use brush_types::Stroke;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
@@ -26,6 +27,7 @@ pub enum Graphic {
|
||||
RasterGPU(Item<Raster<GPU>>),
|
||||
Color(Item<Color>),
|
||||
Gradient(Item<Gradient>),
|
||||
Generator(Item<Generator>),
|
||||
Text(Item<String>),
|
||||
NoneList(List<none::None>),
|
||||
GraphicList(List<Graphic>),
|
||||
@@ -34,6 +36,7 @@ pub enum Graphic {
|
||||
RasterGPUList(List<Raster<GPU>>),
|
||||
ColorList(List<Color>),
|
||||
GradientList(List<Gradient>),
|
||||
GeneratorList(List<Generator>),
|
||||
TextList(List<String>),
|
||||
StrokeList(List<Stroke>),
|
||||
}
|
||||
@@ -137,6 +140,23 @@ impl From<List<Gradient>> for Graphic {
|
||||
}
|
||||
}
|
||||
|
||||
// Generator
|
||||
impl From<Generator> for Graphic {
|
||||
fn from(generator: Generator) -> Self {
|
||||
Graphic::Generator(Item::new_from_element(generator))
|
||||
}
|
||||
}
|
||||
impl From<Item<Generator>> for Graphic {
|
||||
fn from(generator: Item<Generator>) -> Self {
|
||||
Graphic::Generator(generator)
|
||||
}
|
||||
}
|
||||
impl From<List<Generator>> for Graphic {
|
||||
fn from(generator: List<Generator>) -> Self {
|
||||
Graphic::GeneratorList(generator)
|
||||
}
|
||||
}
|
||||
|
||||
// Stroke
|
||||
impl From<Stroke> for Graphic {
|
||||
fn from(stroke: Stroke) -> Self {
|
||||
@@ -312,12 +332,14 @@ pub fn bake_paint_transforms(attributes: &mut ItemAttributeValues, transform: DA
|
||||
Graphic::RasterCPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::RasterGPU(item) => bake_item_transform(item, transform),
|
||||
Graphic::Gradient(item) => bake_item_transform(item, transform),
|
||||
Graphic::Generator(item) => bake_item_transform(item, transform),
|
||||
Graphic::Text(item) => bake_item_transform(item, transform),
|
||||
Graphic::GraphicList(list) => bake_list_transform(list, transform),
|
||||
Graphic::VectorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterCPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::RasterGPUList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GradientList(list) => bake_list_transform(list, transform),
|
||||
Graphic::GeneratorList(list) => bake_list_transform(list, transform),
|
||||
Graphic::TextList(list) => bake_list_transform(list, transform),
|
||||
Graphic::StrokeList(list) => bake_list_transform(list, transform),
|
||||
// A color has no spatial extent, so there is no placement for a transform to move
|
||||
@@ -380,6 +402,16 @@ impl TryFromGraphic for Gradient {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for Generator {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
Graphic::Generator(item) => Some(List::new_from_item(item)),
|
||||
Graphic::GeneratorList(list) => Some(list),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFromGraphic for String {
|
||||
fn try_from_graphic(graphic: Graphic) -> Option<List<Self>> {
|
||||
match graphic {
|
||||
@@ -418,7 +450,7 @@ impl IntoGraphicList for List<Graphic> {
|
||||
impl IntoGraphicList for List<Vector> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
// A synthetic container, not a real group layer, so it carries no `editor:layer_path` that would
|
||||
// overwrite the inner items' own stamps when flattened back out
|
||||
// overwrite the inner items' own layer paths when flattened back out
|
||||
List::new_from_element(Graphic::VectorList(self))
|
||||
}
|
||||
}
|
||||
@@ -447,6 +479,12 @@ impl IntoGraphicList for List<Gradient> {
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Generator> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
List::new_from_element(Graphic::GeneratorList(self))
|
||||
}
|
||||
}
|
||||
|
||||
impl IntoGraphicList for List<Stroke> {
|
||||
fn into_graphic_list(self) -> List<Graphic> {
|
||||
let layer_path: NodeIdPath = self.attribute_cloned_or_default(ATTR_EDITOR_LAYER_PATH, 0);
|
||||
@@ -560,6 +598,7 @@ impl Graphic {
|
||||
Graphic::RasterGPU(item) => item_clipped(item),
|
||||
Graphic::Color(item) => item_clipped(item),
|
||||
Graphic::Gradient(item) => item_clipped(item),
|
||||
Graphic::Generator(item) => item_clipped(item),
|
||||
Graphic::Text(item) => item_clipped(item),
|
||||
Graphic::NoneList(list) => all_clipped(list),
|
||||
Graphic::VectorList(list) => all_clipped(list),
|
||||
@@ -568,6 +607,7 @@ impl Graphic {
|
||||
Graphic::RasterGPUList(list) => all_clipped(list),
|
||||
Graphic::ColorList(list) => all_clipped(list),
|
||||
Graphic::GradientList(list) => all_clipped(list),
|
||||
Graphic::GeneratorList(list) => all_clipped(list),
|
||||
Graphic::TextList(list) => all_clipped(list),
|
||||
Graphic::StrokeList(list) => all_clipped(list),
|
||||
}
|
||||
@@ -606,6 +646,7 @@ impl Graphic {
|
||||
}
|
||||
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
|
||||
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
|
||||
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
|
||||
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
|
||||
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
|
||||
// A `Clear` spread cuts off to transparency past the ends, leaving the rest of the region unpainted
|
||||
@@ -652,9 +693,11 @@ impl Graphic {
|
||||
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
|
||||
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
|
||||
Graphic::Generator(item) => item_opacity_is_zero(item),
|
||||
Graphic::Text(item) => item_opacity_is_zero(item),
|
||||
Graphic::RasterCPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::RasterGPUList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::GeneratorList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::TextList(list) => every_item_has_zero_opacity(list),
|
||||
Graphic::StrokeList(list) => every_item_has_zero_opacity(list),
|
||||
}
|
||||
@@ -670,11 +713,12 @@ impl Graphic {
|
||||
match self {
|
||||
// A leaf always holds exactly one element, so only the none-typed content is truly empty
|
||||
Graphic::None(_) | Graphic::NoneList(_) => true,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Text(_) => false,
|
||||
Graphic::Graphic(_) | Graphic::Vector(_) | Graphic::RasterCPU(_) | Graphic::RasterGPU(_) | Graphic::Color(_) | Graphic::Gradient(_) | Graphic::Generator(_) | Graphic::Text(_) => false,
|
||||
Graphic::GraphicList(list) => list.is_empty(),
|
||||
Graphic::VectorList(list) => list.is_empty(),
|
||||
Graphic::ColorList(list) => list.is_empty(),
|
||||
Graphic::GradientList(list) => list.is_empty(),
|
||||
Graphic::GeneratorList(list) => list.is_empty(),
|
||||
Graphic::RasterCPUList(list) => list.is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.is_empty(),
|
||||
Graphic::TextList(list) => list.is_empty(),
|
||||
@@ -831,6 +875,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(list) => vector_list_bounding_box(list, transform, include_stroke),
|
||||
Graphic::RasterCPUList(list) => list.bounding_box(transform, include_stroke),
|
||||
@@ -838,6 +883,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -852,6 +898,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::RasterGPU(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Color(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Gradient(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Generator(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::Text(item) => item.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::VectorList(vector) => vector_list_bounding_box(vector, transform, include_stroke),
|
||||
Graphic::RasterCPUList(raster) => raster.thumbnail_bounding_box(transform, include_stroke),
|
||||
@@ -859,6 +906,7 @@ impl BoundingBox for Graphic {
|
||||
Graphic::GraphicList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::ColorList(color) => color.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GradientList(gradient) => gradient.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::GeneratorList(generator) => generator.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::TextList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
Graphic::StrokeList(list) => list.thumbnail_bounding_box(transform, include_stroke),
|
||||
}
|
||||
@@ -946,7 +994,7 @@ mod tests {
|
||||
Graphic::VectorList(List::new_from_element(Vector::default()))
|
||||
}
|
||||
|
||||
fn vector_list_stamped_with_layers(layers: [u64; 2]) -> List<Vector> {
|
||||
fn vector_list_with_layer_paths(layers: [u64; 2]) -> List<Vector> {
|
||||
let mut list = List::new();
|
||||
|
||||
for layer in layers {
|
||||
@@ -961,13 +1009,13 @@ mod tests {
|
||||
// The wrapper minted for a typed list is a container rather than a layer, so it must never claim a layer path
|
||||
#[test]
|
||||
fn wrapping_a_typed_list_leaves_the_wrapper_anonymous() {
|
||||
let graphic_list = vector_list_stamped_with_layers([7, 9]).into_graphic_list();
|
||||
let graphic_list = vector_list_with_layer_paths([7, 9]).into_graphic_list();
|
||||
|
||||
assert_eq!(graphic_list.len(), 1);
|
||||
assert!(!graphic_list.attribute_keys().any(|key| key == ATTR_EDITOR_LAYER_PATH));
|
||||
}
|
||||
|
||||
fn layer_stamps(flattened: &List<Vector>) -> Vec<Option<NodeId>> {
|
||||
fn item_layers(flattened: &List<Vector>) -> Vec<Option<NodeId>> {
|
||||
(0..flattened.len())
|
||||
.map(|index| {
|
||||
flattened
|
||||
@@ -980,22 +1028,22 @@ mod tests {
|
||||
.collect()
|
||||
}
|
||||
|
||||
// Round-tripping through that wrapper must not collapse the items' distinct stamps onto item 0's
|
||||
// Round-tripping through that wrapper must not collapse the items' distinct layer paths onto item 0's
|
||||
#[test]
|
||||
fn round_trip_through_the_wrapper_preserves_per_item_layer_paths() {
|
||||
let flattened: List<Vector> = vector_list_stamped_with_layers([7, 9]).into_flattened_list();
|
||||
let flattened: List<Vector> = vector_list_with_layer_paths([7, 9]).into_flattened_list();
|
||||
|
||||
assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
}
|
||||
|
||||
// The embedding adapter reaches the same flattened stamps as the wrapper, each item carrying its own inside its variant
|
||||
// The embedding adapter reaches the same flattened layer paths as the wrapper, each item carrying its own inside its variant
|
||||
#[test]
|
||||
fn embedding_each_item_preserves_per_item_layer_paths() {
|
||||
let embedded: List<Graphic> = vector_list_stamped_with_layers([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect();
|
||||
let embedded: List<Graphic> = vector_list_with_layer_paths([7, 9]).into_iter().map(|item| Item::new_from_element(Graphic::from(item))).collect();
|
||||
|
||||
let flattened: List<Vector> = embedded.into_flattened_list();
|
||||
|
||||
assert_eq!(layer_stamps(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
assert_eq!(item_layers(&flattened), [Some(NodeId(7)), Some(NodeId(9))]);
|
||||
}
|
||||
|
||||
// Flattening must not invent attributes that neither the parent graphic nor the child carried
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
pub mod adjustment;
|
||||
pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effects;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub(crate) mod parameters;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -8,8 +12,11 @@ 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 generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
|
||||
pub mod migrations {
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
//! Parameters riding an item as attributes, each read as its default when absent, which one listing per operation both writes and reads.
|
||||
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::Item;
|
||||
use std::any::Any;
|
||||
use std::fmt::Debug;
|
||||
|
||||
/// 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 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 an item, for rows whose attributes are part of their value.
|
||||
pub(crate) struct WriteParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for WriteParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, default: U) {
|
||||
if *value != default {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stamps every parameter onto an item, for an item on a wire, whose attributes mustn't come and go with their values.
|
||||
pub(crate) struct StampParameters<'a, T>(pub &'a mut Item<T>);
|
||||
|
||||
impl<T> ParameterVisitor for StampParameters<'_, T> {
|
||||
fn parameter<U: ParameterValue>(&mut self, key: &str, value: &mut U, _default: U) {
|
||||
self.0.set_attribute(key, value.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads each parameter from the attribute that the lookup finds by key, or its default where there's none.
|
||||
pub(crate) struct ReadParameters<'a>(pub &'a dyn Fn(&str) -> Option<&'a dyn Any>);
|
||||
|
||||
impl ParameterVisitor for ReadParameters<'_> {
|
||||
fn parameter<T: ParameterValue>(&mut self, key: &str, value: &mut T, default: T) {
|
||||
*value = (self.0)(key).and_then(|value| value.downcast_ref::<T>()).cloned().unwrap_or(default);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "raster-kernels"
|
||||
description = "The kernels carrying out Graphene's raster operations, such as each color adjustment"
|
||||
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 }
|
||||
raster-types = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
fastnoise-lite = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Bakes runs of adjustments into the lookup tables the GPU carries them out with, sampling the CPU kernels so the two agree by construction.
|
||||
|
||||
use crate::adjustments::adjust_colors;
|
||||
use core_types::Color;
|
||||
use graphic_types::adjustment::Adjustment;
|
||||
|
||||
/// Entries in a one-dimensional table, enough that interpolating between them strays less than a level from even a steep curve.
|
||||
pub const CURVE_TABLE_SIZE: usize = 4096;
|
||||
|
||||
/// Grid points along each axis of a color cube, enough that interpolating within its tetrahedra stays within a few levels of the smooth kernels.
|
||||
pub const CUBE_SIZE: usize = 65;
|
||||
|
||||
/// Grid points along each axis of a draft color cube, an eighth the work of [`CUBE_SIZE`] for settings changing every frame, at about three times its error.
|
||||
pub const DRAFT_CUBE_SIZE: usize = 33;
|
||||
|
||||
/// One pass of the GPU's adjustment shader, with the tables it looks colors up in. Values are gamma-encoded.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum AdjustmentPass {
|
||||
/// The red, green, blue, and alpha channels each through their own curve, sampled at [`CURVE_TABLE_SIZE`] values from 0 to 1.
|
||||
Curves(Vec<[f32; 4]>),
|
||||
/// Colors through a cube of `size` samples along each of red, green, and blue, with red varying fastest and blue slowest.
|
||||
/// Alpha passes through its own curve of [`CURVE_TABLE_SIZE`] samples.
|
||||
Cube { size: usize, colors: Vec<[f32; 3]>, alpha: Vec<f32> },
|
||||
/// Each color replaced by the entry of [`CURVE_TABLE_SIZE`] its luma (the weighted sum of its channels) picks, keeping its alpha.
|
||||
Luma { weights: [f32; 3], colors: Vec<[f32; 3]> },
|
||||
/// Vibrance, whose steep toe near black no table captures, computed directly from its amounts in -1..1 and its saturation scale.
|
||||
Vibrance { vibrance: f32, saturation_scale: f32 },
|
||||
}
|
||||
|
||||
impl AdjustmentPass {
|
||||
/// The passes that carry out `adjustments` in order, merging each run of those a table can capture into one pass, with cubes of `cube_size` along each side.
|
||||
pub fn plan(adjustments: &[Adjustment], cube_size: usize) -> Vec<Self> {
|
||||
let mut passes = Vec::new();
|
||||
let mut run: Vec<&Adjustment> = Vec::new();
|
||||
|
||||
for adjustment in adjustments {
|
||||
let own_pass = match adjustment {
|
||||
Adjustment::Vibrance { vibrance, saturation } => Some(Self::Vibrance {
|
||||
vibrance: (vibrance / 100.) as f32,
|
||||
saturation_scale: (1. + saturation / 100.) as f32,
|
||||
}),
|
||||
// A step in luma, which a table of luma keeps sharp where a cube would blur it
|
||||
Adjustment::Threshold { .. } => Some(Self::Luma {
|
||||
weights: [4915., 9667., 1802.].map(|weight| weight / 16384.),
|
||||
colors: luma_table(adjustment, [4915., 9667., 1802.].map(|weight| weight / 16384.)),
|
||||
}),
|
||||
// A gradient's hard stops are steps too
|
||||
Adjustment::GradientMap { .. } => Some(Self::Luma {
|
||||
weights: [0.3, 0.59, 0.11],
|
||||
colors: luma_table(adjustment, [0.3, 0.59, 0.11]),
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
match own_pass {
|
||||
Some(pass) => {
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
run.clear();
|
||||
passes.push(pass);
|
||||
}
|
||||
None => run.push(adjustment),
|
||||
}
|
||||
}
|
||||
passes.extend(Self::from_run(&run, cube_size));
|
||||
|
||||
passes
|
||||
}
|
||||
|
||||
/// Whether any of the passes looks colors up in a cube, the only table whose size varies.
|
||||
pub fn any_cube(passes: &[Self]) -> bool {
|
||||
passes.iter().any(|pass| matches!(pass, Self::Cube { .. }))
|
||||
}
|
||||
|
||||
/// One pass carrying out a run of adjustments in order, as four curves if each acts on the channels separately, or else as a cube.
|
||||
fn from_run(run: &[&Adjustment], cube_size: usize) -> Option<Self> {
|
||||
if run.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let apply_run = |colors: &mut [Color]| run.iter().for_each(|adjustment| adjust_colors(adjustment, colors));
|
||||
|
||||
// The color channels never read alpha, and alpha depends on alpha alone, so one ramp feeds every channel at once
|
||||
let mut ramp: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32;
|
||||
Color::from_gamma_srgb_channels(value, value, value, value)
|
||||
})
|
||||
.collect();
|
||||
apply_run(&mut ramp);
|
||||
let ramp: Vec<[f32; 4]> = ramp.iter().map(Color::to_gamma_srgb_channels).collect();
|
||||
|
||||
if run.iter().all(|adjustment| adjustment.is_per_channel()) {
|
||||
return Some(Self::Curves(ramp));
|
||||
}
|
||||
|
||||
let step = |index: usize| index as f32 / (cube_size - 1) as f32;
|
||||
let mut cube = Vec::with_capacity(cube_size.pow(3));
|
||||
for blue in 0..cube_size {
|
||||
for green in 0..cube_size {
|
||||
for red in 0..cube_size {
|
||||
cube.push(Color::from_gamma_srgb_channels(step(red), step(green), step(blue), 1.));
|
||||
}
|
||||
}
|
||||
}
|
||||
apply_run(&mut cube);
|
||||
|
||||
Some(Self::Cube {
|
||||
size: cube_size,
|
||||
colors: cube.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect(),
|
||||
alpha: ramp.iter().map(|channels| channels[3]).collect(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The adjustment's results for grays of each luma, which stand for every color of that luma when the adjustment reads only its luma.
|
||||
fn luma_table(adjustment: &Adjustment, weights: [f32; 3]) -> Vec<[f32; 3]> {
|
||||
let total: f32 = weights.iter().sum();
|
||||
let mut grays: Vec<Color> = (0..CURVE_TABLE_SIZE)
|
||||
.map(|index| {
|
||||
let value = index as f32 / (CURVE_TABLE_SIZE - 1) as f32 / total;
|
||||
Color::from_gamma_srgb_channels(value, value, value, 1.)
|
||||
})
|
||||
.collect();
|
||||
adjust_colors(adjustment, &mut grays);
|
||||
|
||||
grays.iter().map(|color| color.to_gamma_srgb_channels()).map(|[red, green, blue, _]| [red, green, blue]).collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
//! The kernels blending one color with another.
|
||||
|
||||
use crate::MapColor;
|
||||
use core_types::Color;
|
||||
use core_types::blending::{BlendMode, apply_blend_mode};
|
||||
|
||||
pub(crate) struct ColorOverlay {
|
||||
pub(crate) color: Color,
|
||||
pub(crate) blend_mode: BlendMode,
|
||||
pub(crate) opacity: f32,
|
||||
}
|
||||
|
||||
impl MapColor for ColorOverlay {
|
||||
fn map_cpu(&self, pixel: Color) -> Color {
|
||||
overlay_paint(pixel, self.color, self.blend_mode, self.opacity)
|
||||
}
|
||||
}
|
||||
|
||||
/// The color with `paint` mixed over it by the blend mode, as much as the paint's alpha times `opacity` (from 0 to 1), keeping the color's own alpha.
|
||||
pub fn overlay_paint(color: Color, paint: Color, blend_mode: BlendMode, opacity: f32) -> Color {
|
||||
let overlay = apply_blend_mode(paint, color, blend_mode);
|
||||
let amount = opacity * paint.a();
|
||||
let mix = |under: f32, over: f32| under + (over - under) * amount;
|
||||
|
||||
Color::from_rgbaf32_unchecked(mix(color.r(), overlay.r()), mix(color.g(), overlay.g()), mix(color.b(), overlay.b()), color.a())
|
||||
}
|
||||
+56
-29
@@ -8,35 +8,60 @@ mod format_look;
|
||||
|
||||
use crate::adjustments::{SRGB_TO_XYZ_D50, WHITE_XYZ_D50, XYZ_D50_TO_SRGB, multiply_matrix};
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use graphene_resource::{Resource, ResourceHash};
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use graphene_resource::{Resource, ResourceHash, WeakResource};
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
pub const LUT_FILE_EXTENSIONS: &[&str] = &["cube", "3dl", "look", "csp", "icc", "icm"];
|
||||
|
||||
/// A file's parse result, in the form the cache shares out.
|
||||
type ParsedLut = Result<Arc<Lut>, LutParseError>;
|
||||
|
||||
/// The last file a node parsed, kept as the node's own data so the file is not parsed anew each time the node runs again.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct LutCache(Arc<Mutex<Option<(ResourceHash, ParsedLut)>>>);
|
||||
/// A parse result, kept while the file it came from is still loaded somewhere.
|
||||
struct ParsedFile {
|
||||
hash: ResourceHash,
|
||||
file: WeakResource,
|
||||
parsed: ParsedLut,
|
||||
}
|
||||
|
||||
impl LutCache {
|
||||
/// [`Lut::parse`] for a resource, reusing the last result while the file's content hash stays the same.
|
||||
pub fn parse(&self, resource: &Resource) -> ParsedLut {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
let mut cached = self.0.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
/// The parse results of the files that are still loaded, shared by every adjustment that reads a lookup table.
|
||||
static PARSED_FILES: Mutex<Vec<ParsedFile>> = Mutex::new(Vec::new());
|
||||
|
||||
let hash = resource.hash();
|
||||
if let Some((cached_hash, result)) = cached.as_ref()
|
||||
&& *cached_hash == hash
|
||||
{
|
||||
return result.clone();
|
||||
fn parsed_files() -> MutexGuard<'static, Vec<ParsedFile>> {
|
||||
// A lock poisoned by a panic elsewhere still guards a usable cache
|
||||
PARSED_FILES.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// [`Lut::parse`] for a resource, reusing the result for as long as a file with the same content hash stays loaded. O(n) in the loaded files.
|
||||
pub fn parse_cached(resource: &Resource) -> ParsedLut {
|
||||
let hash = resource.hash();
|
||||
|
||||
{
|
||||
let mut parsed_files = parsed_files();
|
||||
|
||||
// Follows the copy in hand before pruning, in case another copy of the same content is the one that went away
|
||||
let cached = parsed_files.iter_mut().find(|entry| entry.hash == hash).map(|entry| {
|
||||
entry.file = resource.downgrade();
|
||||
entry.parsed.clone()
|
||||
});
|
||||
parsed_files.retain(|entry| entry.file.is_alive());
|
||||
|
||||
if let Some(parsed) = cached {
|
||||
return parsed;
|
||||
}
|
||||
|
||||
let result = Lut::parse(resource).map(Arc::new);
|
||||
*cached = Some((hash, result.clone()));
|
||||
result
|
||||
}
|
||||
|
||||
// Parsed outside the lock, so a large file doesn't hold up the adjustments reading other files
|
||||
let parsed = Lut::parse(resource).map(Arc::new);
|
||||
|
||||
let mut parsed_files = parsed_files();
|
||||
if !parsed_files.iter().any(|entry| entry.hash == hash) {
|
||||
parsed_files.push(ParsedFile {
|
||||
hash,
|
||||
file: resource.downgrade(),
|
||||
parsed: parsed.clone(),
|
||||
});
|
||||
}
|
||||
parsed
|
||||
}
|
||||
|
||||
/// Why a file could not be read as a lookup table.
|
||||
@@ -423,18 +448,20 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cache_parses_a_file_once_until_the_file_changes() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n1 1 1\n".to_vec());
|
||||
let cache = LutCache::default();
|
||||
let first = cache.parse(&file).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
fn the_cache_parses_a_file_once_while_it_stays_loaded() {
|
||||
let file = Resource::new(b"LUT_1D_SIZE 2\n0 0 0\n0.5 1 1\n".to_vec());
|
||||
let first = parse_cached(&file).unwrap();
|
||||
|
||||
// A cloned node shares its cache
|
||||
assert!(Arc::ptr_eq(&first, &cache.clone().parse(&file).unwrap()));
|
||||
// Any number of other files, failed ones included, leave it in place
|
||||
let others: Vec<Resource> = (0..20).map(|index| Resource::new(format!("not a table {index}").into_bytes())).collect();
|
||||
others.iter().for_each(|other| assert!(parse_cached(other).is_err()));
|
||||
assert!(Arc::ptr_eq(&first, &parse_cached(&file).unwrap()));
|
||||
|
||||
// Another file takes its place, a failed one included
|
||||
assert!(cache.parse(&Resource::new(b"hello world".to_vec())).is_err());
|
||||
assert!(!Arc::ptr_eq(&first, &cache.parse(&file).unwrap()));
|
||||
// Once no copy of it is loaded, parsing another file clears it out
|
||||
let content = file.to_vec();
|
||||
drop(file);
|
||||
assert!(parse_cached(&Resource::new(b"not a table either".to_vec())).is_err());
|
||||
assert!(!Arc::ptr_eq(&first, &parse_cached(&Resource::new(content)).unwrap()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,423 @@
|
||||
//! The image operations that effects are built from, on the CPU: blurring, growing shapes, and shifting.
|
||||
//! They mirror the renderer's GPU passes, so a raster's effects read the same in a node that needs its pixels as on the canvas.
|
||||
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Blurs and spreads shorter than this, in pixels, leave no visible trace.
|
||||
pub const NEGLIGIBLE_LENGTH: f64 = 0.01;
|
||||
|
||||
/// The largest Gaussian standard deviation, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_GAUSSIAN_SIGMA: f64 = 8.;
|
||||
|
||||
/// The largest box half width, in pixels, convolved on the image itself rather than a halved copy.
|
||||
pub const MAX_DIRECT_BOX_RADIUS: f64 = 24.;
|
||||
|
||||
/// The farthest texel from the center a kernel weighs, which fits both direct limits.
|
||||
pub const MAX_KERNEL_REACH: usize = 24;
|
||||
|
||||
/// The most times an image is halved for a blur, by which point it is one pixel across.
|
||||
const MAX_LEVELS: u32 = 16;
|
||||
|
||||
/// A blur's kernel along one axis, sized in pixels.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum BlurKernel {
|
||||
Gaussian { sigma: f64 },
|
||||
Box { radius: f64 },
|
||||
}
|
||||
|
||||
impl BlurKernel {
|
||||
/// How many times the image is halved before the kernel runs, so the kernel stays within [`MAX_KERNEL_REACH`].
|
||||
pub fn levels(self) -> u32 {
|
||||
let (length, direct_limit) = match self {
|
||||
Self::Gaussian { sigma } => (sigma, MAX_DIRECT_GAUSSIAN_SIGMA),
|
||||
Self::Box { radius } => (radius, MAX_DIRECT_BOX_RADIUS),
|
||||
};
|
||||
|
||||
(length / direct_limit).log2().ceil().clamp(0., MAX_LEVELS as f64) as u32
|
||||
}
|
||||
|
||||
/// The weights of the texels from the center outward for an image halved `levels` times, normalized so the symmetric kernel sums to 1.
|
||||
pub fn weights(self, levels: u32) -> Vec<f64> {
|
||||
let level_scale = (1 << levels) as f64;
|
||||
|
||||
let weights: Vec<f64> = match self {
|
||||
Self::Gaussian { sigma } => {
|
||||
// Halving the image and doubling it back blur it too, so the kernel makes up only the rest of the variance
|
||||
let pyramid_variance = (4_f64.powi(levels as i32) - 1.) / 3.;
|
||||
let sigma = (sigma * sigma - pyramid_variance).max(0.).sqrt() / level_scale;
|
||||
if sigma < NEGLIGIBLE_LENGTH {
|
||||
return vec![1.];
|
||||
}
|
||||
|
||||
let reach = ((3. * sigma).ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (-((i * i) as f64) / (2. * sigma * sigma)).exp()).collect()
|
||||
}
|
||||
// The texels at the ends weigh only the fraction of them the box covers, so the blur grows smoothly with its radius
|
||||
Self::Box { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
let reach = (radius.ceil() as usize).min(MAX_KERNEL_REACH);
|
||||
(0..=reach).map(|i| (radius + 1. - i as f64).clamp(0., 1.)).collect()
|
||||
}
|
||||
};
|
||||
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
weights.into_iter().map(|weight| weight / total).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// A pixel value the operations can weigh, sum, and compare: one coverage channel, or premultiplied color channels.
|
||||
pub trait Sample: Copy + Default + Send + Sync {
|
||||
fn scaled(self, factor: f32) -> Self;
|
||||
fn plus(self, other: Self) -> Self;
|
||||
fn max(self, other: Self) -> Self;
|
||||
}
|
||||
|
||||
impl Sample for f32 {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self * factor
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
self + other
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
f32::max(self, other)
|
||||
}
|
||||
}
|
||||
|
||||
impl Sample for [f32; 4] {
|
||||
fn scaled(self, factor: f32) -> Self {
|
||||
self.map(|channel| channel * factor)
|
||||
}
|
||||
fn plus(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel] + other[channel])
|
||||
}
|
||||
fn max(self, other: Self) -> Self {
|
||||
std::array::from_fn(|channel| self[channel].max(other[channel]))
|
||||
}
|
||||
}
|
||||
|
||||
/// An image of [`Sample`]s in rows, which the operations read and write.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Plane<T> {
|
||||
pub width: usize,
|
||||
pub height: usize,
|
||||
pub data: Vec<T>,
|
||||
}
|
||||
|
||||
impl<T: Sample> Plane<T> {
|
||||
pub fn new(width: usize, height: usize) -> Self {
|
||||
Self {
|
||||
width,
|
||||
height,
|
||||
data: vec![T::default(); width * height],
|
||||
}
|
||||
}
|
||||
|
||||
/// A plane of the same size whose pixels are `map` of this one's.
|
||||
pub fn map<U: Sample>(&self, map: impl Fn(T) -> U + Sync) -> Plane<U> {
|
||||
let mut mapped = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut mapped.data, self.width, |y, row| {
|
||||
let source = &self.data[y * self.width..(y + 1) * self.width];
|
||||
row.iter_mut().zip(source).for_each(|(target, &value)| *target = map(value));
|
||||
});
|
||||
mapped
|
||||
}
|
||||
|
||||
/// Combines this plane with `other`, of the same size, pixel by pixel.
|
||||
pub fn zip<U: Sample, V: Sample>(&self, other: &Plane<U>, combine: impl Fn(T, U) -> V + Sync) -> Plane<V> {
|
||||
let mut combined = Plane::new(self.width, self.height);
|
||||
fill_rows(&mut combined.data, self.width, |y, row| {
|
||||
let range = y * self.width..(y + 1) * self.width;
|
||||
let pairs = self.data[range.clone()].iter().zip(&other.data[range]);
|
||||
row.iter_mut().zip(pairs).for_each(|(target, (&a, &b))| *target = combine(a, b));
|
||||
});
|
||||
combined
|
||||
}
|
||||
|
||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||
fn transposed(&self) -> Self {
|
||||
let mut transposed = Self::new(self.height, self.width);
|
||||
fill_rows(&mut transposed.data, self.height, |x, row| {
|
||||
row.iter_mut().enumerate().for_each(|(y, target)| *target = self.data[y * self.width + x]);
|
||||
});
|
||||
transposed
|
||||
}
|
||||
|
||||
/// Runs `operation` on each row, which it reads in full and writes as a new row of `width` pixels.
|
||||
fn map_rows(&self, width: usize, operation: impl Fn(&[T], &mut [T]) + Sync) -> Self {
|
||||
let mut result = Self::new(width, self.height);
|
||||
fill_rows(&mut result.data, width, |y, row| operation(&self.data[y * self.width..(y + 1) * self.width], row));
|
||||
result
|
||||
}
|
||||
|
||||
/// Runs `along_rows` on the plane's rows, then on its columns by way of one transpose there and back.
|
||||
fn along_both_axes<P>(self, horizontal: P, vertical: P, along_rows: impl Fn(Self, P) -> Self) -> Self {
|
||||
let plane = along_rows(self, horizontal);
|
||||
along_rows(plane.transposed(), vertical).transposed()
|
||||
}
|
||||
|
||||
/// Blurs the plane by a kernel along each axis. Kernels too wide to convolve directly run on a copy halved along their axis enough times
|
||||
/// for them to fit, then doubled back. O(width × height) per pass, with a pass for each halving and doubling.
|
||||
pub fn blurred(self, horizontal: BlurKernel, vertical: BlurKernel) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, kernel| {
|
||||
let levels = kernel.levels();
|
||||
let length = plane.width;
|
||||
let level_length = |level: u32| length.div_ceil(1 << level);
|
||||
|
||||
for level in 1..=levels {
|
||||
plane = plane.map_rows(level_length(level), halve_row);
|
||||
}
|
||||
|
||||
let weights = kernel.weights(levels);
|
||||
plane = plane.map_rows(level_length(levels), |source, target| convolve_row(source, target, &weights));
|
||||
|
||||
for level in (0..levels).rev() {
|
||||
plane = plane.map_rows(level_length(level), double_row);
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Grows the shapes by a distance in pixels along each axis, in a square like SVG's `feMorphology`.
|
||||
pub fn dilated(self, horizontal: f64, vertical: f64) -> Self {
|
||||
self.along_both_axes(horizontal, vertical, |mut plane, distance| {
|
||||
let length = plane.width;
|
||||
|
||||
// Steps that double, then the remainder, so each step grows the shapes by up to as much as all the steps before it
|
||||
let (mut covered, mut step) = (0., 1.);
|
||||
while covered + step <= distance {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, step));
|
||||
covered += step;
|
||||
step *= 2.;
|
||||
}
|
||||
if distance - covered >= NEGLIGIBLE_LENGTH {
|
||||
plane = plane.map_rows(length, |source, target| dilate_row(source, target, distance - covered));
|
||||
}
|
||||
plane
|
||||
})
|
||||
}
|
||||
|
||||
/// Moves the image by a fractional offset in pixels, interpolating between pixels and leaving transparency where it uncovers the edges.
|
||||
pub fn shifted(self, offset_x: f64, offset_y: f64) -> Self {
|
||||
self.along_both_axes(offset_x, offset_y, |plane, offset| plane.map_rows(plane.width, |source, target| shift_row(source, target, offset)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Plane<f32> {
|
||||
/// The coverage of the band reaching `width` pixels from the silhouette's edge, outward or (if `inward`) inward, measured in straight lines so it rounds corners.
|
||||
pub fn edge_band(&self, width: f64, inward: bool) -> Self {
|
||||
// The edge lies about half a pixel short of the nearest pixel across it, and the band fades out over one pixel
|
||||
let distances = self.distances_across_edge(width, inward);
|
||||
let width = width as f32;
|
||||
distances.map(|distance| (width + 1. - distance).clamp(0., 1.))
|
||||
}
|
||||
|
||||
/// Each pixel's distance to the nearest pixel across the silhouette's edge: outside it if `inward`, or inside it otherwise, with those pixels at zero.
|
||||
/// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther pixels may find none and lie at infinity. O(width × height × log(reach)).
|
||||
pub fn distances_across_edge(&self, reach: f64, inward: bool) -> Self {
|
||||
// The side of the edge that distances are measured from, whose pixels are their own nearest
|
||||
let is_seed = |coverage: f32| (coverage >= 0.5) != inward;
|
||||
let mut nearest: Vec<Option<[i32; 2]>> = self.data.iter().map(|&coverage| is_seed(coverage).then_some([0, 0])).collect();
|
||||
|
||||
let (columns, rows) = (self.width as i32, self.height as i32);
|
||||
let length_squared = |[x, y]: [i32; 2]| x * x + y * y;
|
||||
let mut step = (reach.max(0.).ceil() as u32 + 1).next_power_of_two();
|
||||
while step >= 1 {
|
||||
let previous = nearest.clone();
|
||||
let step_length = step as i32;
|
||||
|
||||
// Each pixel keeps the nearest of the seeds that it and its eight neighbors a step away have found so far
|
||||
fill_rows(&mut nearest, self.width, |y, row| {
|
||||
for (x, best) in row.iter_mut().enumerate() {
|
||||
for neighbor_y in -1..=1 {
|
||||
for neighbor_x in -1..=1 {
|
||||
let (x, y) = (x as i32 + neighbor_x * step_length, y as i32 + neighbor_y * step_length);
|
||||
if x < 0 || y < 0 || x >= columns || y >= rows {
|
||||
continue;
|
||||
}
|
||||
let Some([offset_x, offset_y]) = previous[(y * columns + x) as usize] else { continue };
|
||||
|
||||
let candidate = [offset_x + neighbor_x * step_length, offset_y + neighbor_y * step_length];
|
||||
if best.is_none_or(|best| length_squared(candidate) < length_squared(best)) {
|
||||
*best = Some(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let data = nearest
|
||||
.into_iter()
|
||||
.map(|offset| offset.map_or(f32::INFINITY, |offset| (length_squared(offset) as f32).sqrt()))
|
||||
.collect();
|
||||
Self {
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The row's value at a position measured in pixels from the first pixel's center, interpolating linearly and holding the end pixels beyond the ends.
|
||||
fn sample_row<T: Sample>(row: &[T], position: f64) -> T {
|
||||
let last = row.len() as f64 - 1.;
|
||||
let position = position.clamp(0., last.max(0.));
|
||||
let index = position.floor() as usize;
|
||||
let fraction = (position - index as f64) as f32;
|
||||
|
||||
match row.get(index + 1) {
|
||||
Some(&next) if fraction > 0. => row[index].scaled(1. - fraction).plus(next.scaled(fraction)),
|
||||
_ => row[index],
|
||||
}
|
||||
}
|
||||
|
||||
/// Halves the row by averaging each pair of pixels, the last pixel of an odd row pairing with itself.
|
||||
fn halve_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let first = source[2 * index];
|
||||
let second = source.get(2 * index + 1).copied().unwrap_or(first);
|
||||
*value = first.plus(second).scaled(0.5);
|
||||
}
|
||||
}
|
||||
|
||||
/// Doubles a halved row back to its length, interpolating at each pixel's center within the pair it was averaged into.
|
||||
fn double_row<T: Sample>(source: &[T], target: &mut [T]) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
*value = sample_row(source, index as f64 / 2. - 0.25);
|
||||
}
|
||||
}
|
||||
|
||||
/// Weighs each pixel's neighbors by the symmetric kernel `weights`, from the center outward, holding the end pixels beyond the ends.
|
||||
fn convolve_row<T: Sample>(source: &[T], target: &mut [T], weights: &[f64]) {
|
||||
let last = source.len() as isize - 1;
|
||||
let at = |index: isize| source[index.clamp(0, last) as usize];
|
||||
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let index = index as isize;
|
||||
let mut sum = at(index).scaled(weights[0] as f32);
|
||||
for (distance, &weight) in weights.iter().enumerate().skip(1) {
|
||||
let pair = at(index - distance as isize).plus(at(index + distance as isize));
|
||||
sum = sum.plus(pair.scaled(weight as f32));
|
||||
}
|
||||
*value = sum;
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes each pixel's maximum with the row's values `step` pixels to either side.
|
||||
fn dilate_row<T: Sample>(source: &[T], target: &mut [T], step: f64) {
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64;
|
||||
*value = source[index].max(sample_row(source, position - step)).max(sample_row(source, position + step));
|
||||
}
|
||||
}
|
||||
|
||||
/// Moves the row by `offset` pixels, with nothing beyond its ends.
|
||||
fn shift_row<T: Sample>(source: &[T], target: &mut [T], offset: f64) {
|
||||
let length = source.len() as f64;
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
let position = index as f64 - offset;
|
||||
let floor = position.floor();
|
||||
let fraction = (position - floor) as f32;
|
||||
|
||||
let at = |index: f64| if index >= 0. && index < length { source[index as usize] } else { T::default() };
|
||||
*value = at(floor).scaled(1. - fraction).plus(at(floor + 1.).scaled(fraction));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kernel_weights_sum_to_one() {
|
||||
for kernel in [
|
||||
BlurKernel::Gaussian { sigma: 3. },
|
||||
BlurKernel::Gaussian { sigma: 40. },
|
||||
BlurKernel::Box { radius: 5.5 },
|
||||
BlurKernel::Box { radius: 100. },
|
||||
] {
|
||||
let levels = kernel.levels();
|
||||
let weights = kernel.weights(levels);
|
||||
let total = weights[0] + 2. * weights[1..].iter().sum::<f64>();
|
||||
|
||||
assert!((total - 1.).abs() < 1e-9, "{kernel:?} weights sum to {total}");
|
||||
assert!(weights.len() <= MAX_KERNEL_REACH + 1, "{kernel:?} reaches {} texels", weights.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_kernels_run_without_halving() {
|
||||
assert_eq!(BlurKernel::Gaussian { sigma: MAX_DIRECT_GAUSSIAN_SIGMA }.levels(), 0);
|
||||
assert_eq!(
|
||||
BlurKernel::Gaussian {
|
||||
sigma: MAX_DIRECT_GAUSSIAN_SIGMA * 1.01
|
||||
}
|
||||
.levels(),
|
||||
1
|
||||
);
|
||||
assert_eq!(BlurKernel::Box { radius: 1. }.levels(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gaussian_blur_spreads_a_point_with_the_requested_deviation() {
|
||||
// A single bright pixel blurs into the Gaussian itself, whose variance the pyramid must preserve at every level count
|
||||
for sigma in [2., 20.] {
|
||||
let size = 401;
|
||||
let mut plane = Plane::<f32>::new(size, 1);
|
||||
plane.data[size / 2] = 1.;
|
||||
|
||||
let blurred = plane.blurred(BlurKernel::Gaussian { sigma }, BlurKernel::Gaussian { sigma: 0. });
|
||||
let total: f32 = blurred.data.iter().sum();
|
||||
let variance: f64 = blurred.data.iter().enumerate().map(|(x, &value)| value as f64 * (x as f64 - (size / 2) as f64).powi(2)).sum::<f64>() / total as f64;
|
||||
|
||||
assert!((total - 1.).abs() < 1e-3, "sigma {sigma} keeps the total at {total}");
|
||||
assert!((variance.sqrt() - sigma).abs() / sigma < 0.05, "sigma {sigma} spreads to a deviation of {}", variance.sqrt());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dilation_grows_shapes_by_the_distance() {
|
||||
let mut plane = Plane::<f32>::new(21, 21);
|
||||
plane.data[10 * 21 + 10] = 1.;
|
||||
|
||||
let dilated = plane.dilated(3., 3.);
|
||||
let covered = dilated.data.iter().filter(|&&value| value >= 0.999).count();
|
||||
|
||||
assert_eq!(covered, 7 * 7, "a point grows into a 7 by 7 square");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_bands_round_the_corners_they_grow_around() {
|
||||
// A single pixel grows into a disk the band's width across, rather than a square
|
||||
let mut point = Plane::<f32>::new(21, 21);
|
||||
point.data[10 * 21 + 10] = 1.;
|
||||
let outward = point.edge_band(5., false);
|
||||
let at = |plane: &Plane<f32>, x: usize, y: usize| plane.data[y * 21 + x];
|
||||
|
||||
assert_eq!(at(&outward, 15, 10), 1., "the full width along an axis");
|
||||
assert_eq!(at(&outward, 17, 10), 0., "past the width");
|
||||
assert_eq!(at(&outward, 15, 14), 0., "past the width diagonally, where a square would still reach");
|
||||
|
||||
// Inward, only the pixels near the edge are covered
|
||||
let mut square = Plane::<f32>::new(21, 21);
|
||||
for y in 2..19 {
|
||||
square.data[y * 21 + 2..y * 21 + 19].fill(1.);
|
||||
}
|
||||
let inward = square.edge_band(3., true);
|
||||
|
||||
assert_eq!(at(&inward, 2, 10), 1., "at the edge");
|
||||
assert_eq!(at(&inward, 10, 10), 0., "deep inside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shifting_moves_by_fractions_of_a_pixel() {
|
||||
let mut plane = Plane::<f32>::new(4, 1);
|
||||
plane.data[1] = 1.;
|
||||
|
||||
let shifted = plane.shifted(0.25, 0.);
|
||||
|
||||
assert_eq!(shifted.data, vec![0., 0.75, 0.25, 0.]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
//! The kernels rendering each [`GeneratorPattern`] across any area of its space at any resolution.
|
||||
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2, Vec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
/// The most iterations a point is tested for escaping the Mandelbrot set, beyond which it counts as inside.
|
||||
const MANDELBROT_ITERATIONS: u32 = 255;
|
||||
|
||||
/// The pattern across `area` of its own space, from its minimum to its maximum corner, sampled at the centers of a `width` by `height` grid of pixels.
|
||||
/// Fails where an image of that size can't be allocated.
|
||||
/// The rows are rendered in parallel on native targets.
|
||||
pub fn render_pattern(pattern: &GeneratorPattern, area: [DVec2; 2], width: u32, height: u32) -> Result<Image<Color>, ImageError> {
|
||||
let mut image = Image::try_new(width, height, Color::TRANSPARENT)?;
|
||||
let pixel_size = (area[1] - area[0]) / DVec2::new(width as f64, height as f64);
|
||||
let pixel_center = |x: usize, y: usize| area[0] + (DVec2::new(x as f64, y as f64) + 0.5) * pixel_size;
|
||||
|
||||
let sample = pattern_sampler(pattern);
|
||||
fill_rows(&mut image.data, width as usize, |y, row| {
|
||||
row.iter_mut().enumerate().for_each(|(x, pixel)| *pixel = sample(pixel_center(x, y)));
|
||||
});
|
||||
|
||||
Ok(image)
|
||||
}
|
||||
|
||||
/// Samples the pattern's color at points in its own space, after the setup shared by every sample.
|
||||
pub fn pattern_sampler(pattern: &GeneratorPattern) -> impl Fn(DVec2) -> Color + Sync + use<> {
|
||||
let noise = match pattern {
|
||||
GeneratorPattern::Noise(settings) => Some(NoiseSampler::new(settings)),
|
||||
GeneratorPattern::Mandelbrot => None,
|
||||
};
|
||||
|
||||
move |point| match &noise {
|
||||
Some(noise) => Color::from_luminance(noise.sample(point)),
|
||||
None => {
|
||||
let value = mandelbrot_escape_iterations(point * 3. - DVec2::new(2., 1.5)) as f32 / MANDELBROT_ITERATIONS as f32;
|
||||
Color::from_rgbaf32_unchecked(value, value, value, 1.)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Samples a noise pattern's luminance, from 0 to 1, at positions in its space.
|
||||
struct NoiseSampler {
|
||||
noise: fastnoise_lite::FastNoiseLite,
|
||||
white_noise_seed: Option<i32>,
|
||||
domain_warp: bool,
|
||||
}
|
||||
|
||||
impl NoiseSampler {
|
||||
fn new(settings: &NoiseSettings) -> Self {
|
||||
let mut noise = fastnoise_lite::FastNoiseLite::with_seed(settings.seed as i32);
|
||||
noise.set_frequency(Some(1. / (settings.scale as f32).max(f32::EPSILON)));
|
||||
|
||||
// Domain warp
|
||||
let domain_warp_type = match settings.domain_warp_type {
|
||||
DomainWarpType::None => None,
|
||||
DomainWarpType::OpenSimplex2 => Some(fastnoise_lite::DomainWarpType::OpenSimplex2),
|
||||
DomainWarpType::OpenSimplex2Reduced => Some(fastnoise_lite::DomainWarpType::OpenSimplex2Reduced),
|
||||
DomainWarpType::BasicGrid => Some(fastnoise_lite::DomainWarpType::BasicGrid),
|
||||
};
|
||||
let domain_warp = domain_warp_type.is_some() && settings.domain_warp_amplitude > 0.;
|
||||
noise.set_domain_warp_type(domain_warp_type);
|
||||
noise.set_domain_warp_amp(Some(settings.domain_warp_amplitude as f32));
|
||||
|
||||
// Noise and fractal
|
||||
let noise_type = match settings.noise_type {
|
||||
NoiseType::Perlin => fastnoise_lite::NoiseType::Perlin,
|
||||
NoiseType::OpenSimplex2 => fastnoise_lite::NoiseType::OpenSimplex2,
|
||||
NoiseType::OpenSimplex2S => fastnoise_lite::NoiseType::OpenSimplex2S,
|
||||
NoiseType::Cellular => fastnoise_lite::NoiseType::Cellular,
|
||||
NoiseType::ValueCubic => fastnoise_lite::NoiseType::ValueCubic,
|
||||
NoiseType::Value => fastnoise_lite::NoiseType::Value,
|
||||
NoiseType::WhiteNoise => {
|
||||
return Self {
|
||||
noise,
|
||||
white_noise_seed: Some(settings.seed as i32),
|
||||
domain_warp: false,
|
||||
};
|
||||
}
|
||||
};
|
||||
noise.set_noise_type(Some(noise_type));
|
||||
let fractal_type = match settings.fractal_type {
|
||||
FractalType::None => fastnoise_lite::FractalType::None,
|
||||
FractalType::FBm => fastnoise_lite::FractalType::FBm,
|
||||
FractalType::Ridged => fastnoise_lite::FractalType::Ridged,
|
||||
FractalType::PingPong => fastnoise_lite::FractalType::PingPong,
|
||||
FractalType::DomainWarpProgressive => fastnoise_lite::FractalType::DomainWarpProgressive,
|
||||
FractalType::DomainWarpIndependent => fastnoise_lite::FractalType::DomainWarpIndependent,
|
||||
};
|
||||
noise.set_fractal_type(Some(fractal_type));
|
||||
noise.set_fractal_octaves(Some(settings.fractal_octaves as i32));
|
||||
noise.set_fractal_lacunarity(Some(settings.fractal_lacunarity as f32));
|
||||
noise.set_fractal_gain(Some(settings.fractal_gain as f32));
|
||||
noise.set_fractal_weighted_strength(Some(settings.fractal_weighted_strength as f32));
|
||||
noise.set_fractal_ping_pong_strength(Some(settings.fractal_ping_pong_strength as f32));
|
||||
|
||||
// Cellular
|
||||
let cellular_distance_function = match settings.cellular_distance_function {
|
||||
CellularDistanceFunction::Euclidean => fastnoise_lite::CellularDistanceFunction::Euclidean,
|
||||
CellularDistanceFunction::EuclideanSq => fastnoise_lite::CellularDistanceFunction::EuclideanSq,
|
||||
CellularDistanceFunction::Manhattan => fastnoise_lite::CellularDistanceFunction::Manhattan,
|
||||
CellularDistanceFunction::Hybrid => fastnoise_lite::CellularDistanceFunction::Hybrid,
|
||||
};
|
||||
let cellular_return_type = match settings.cellular_return_type {
|
||||
CellularReturnType::CellValue => fastnoise_lite::CellularReturnType::CellValue,
|
||||
CellularReturnType::Nearest => fastnoise_lite::CellularReturnType::Distance,
|
||||
CellularReturnType::NextNearest => fastnoise_lite::CellularReturnType::Distance2,
|
||||
CellularReturnType::Average => fastnoise_lite::CellularReturnType::Distance2Add,
|
||||
CellularReturnType::Difference => fastnoise_lite::CellularReturnType::Distance2Sub,
|
||||
CellularReturnType::Product => fastnoise_lite::CellularReturnType::Distance2Mul,
|
||||
CellularReturnType::Division => fastnoise_lite::CellularReturnType::Distance2Div,
|
||||
};
|
||||
noise.set_cellular_distance_function(Some(cellular_distance_function));
|
||||
noise.set_cellular_return_type(Some(cellular_return_type));
|
||||
noise.set_cellular_jitter(Some(settings.cellular_jitter as f32));
|
||||
|
||||
Self {
|
||||
noise,
|
||||
white_noise_seed: None,
|
||||
domain_warp,
|
||||
}
|
||||
}
|
||||
|
||||
fn sample(&self, position: DVec2) -> f32 {
|
||||
// White noise gives each square of one document unit its own random value
|
||||
if let Some(seed) = self.white_noise_seed {
|
||||
return white_noise(seed, position.floor().as_ivec2());
|
||||
}
|
||||
|
||||
let (mut x, mut y) = (position.x as f32, position.y as f32);
|
||||
if self.domain_warp {
|
||||
(x, y) = self.noise.domain_warp_2d(x, y);
|
||||
}
|
||||
(self.noise.get_noise_2d(x, y) + 1.) * 0.5
|
||||
}
|
||||
}
|
||||
|
||||
/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match.
|
||||
fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]);
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
let mix = |[x, y, z]: [u32; 3]| {
|
||||
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||
[x, y, z]
|
||||
};
|
||||
|
||||
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
}
|
||||
|
||||
/// How many iterations `c` takes to escape the Mandelbrot set, or the iteration limit if it doesn't. In f32, which a GPU can match near the boundary.
|
||||
fn mandelbrot_escape_iterations(c: DVec2) -> u32 {
|
||||
let c = c.as_vec2();
|
||||
let mut z = Vec2::ZERO;
|
||||
for iteration in 0..MANDELBROT_ITERATIONS {
|
||||
z = Vec2::new(z.x * z.x - z.y * z.y, 2. * z.x * z.y) + c;
|
||||
if z.length_squared() > 4. {
|
||||
return iteration;
|
||||
}
|
||||
}
|
||||
MANDELBROT_ITERATIONS
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renders_of_overlapping_areas_agree_where_they_overlap() {
|
||||
let noise = GeneratorPattern::Noise(NoiseSettings {
|
||||
seed: 7,
|
||||
scale: 10.,
|
||||
noise_type: NoiseType::OpenSimplex2,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::FBm,
|
||||
fractal_octaves: 3,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
});
|
||||
|
||||
// One pixel per unit across 0 to 32, and again across 16 to 48, as two neighboring tiles of a render would sample it
|
||||
let whole = render_pattern(&noise, [DVec2::ZERO, DVec2::splat(32.)], 32, 32).unwrap();
|
||||
let shifted = render_pattern(&noise, [DVec2::splat(16.), DVec2::splat(48.)], 32, 32).unwrap();
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(whole.data[(y + 16) * 32 + x + 16], shifted.data[y * 32 + x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn white_noise_is_the_same_wherever_and_however_finely_it_is_sampled() {
|
||||
let white_noise = |seed| {
|
||||
GeneratorPattern::Noise(NoiseSettings {
|
||||
seed,
|
||||
scale: 10.,
|
||||
noise_type: NoiseType::WhiteNoise,
|
||||
domain_warp_type: DomainWarpType::None,
|
||||
domain_warp_amplitude: 0.,
|
||||
fractal_type: FractalType::None,
|
||||
fractal_octaves: 1,
|
||||
fractal_lacunarity: 2.,
|
||||
fractal_gain: 0.5,
|
||||
fractal_weighted_strength: 0.,
|
||||
fractal_ping_pong_strength: 2.,
|
||||
cellular_distance_function: CellularDistanceFunction::Euclidean,
|
||||
cellular_return_type: CellularReturnType::Nearest,
|
||||
cellular_jitter: 1.,
|
||||
})
|
||||
};
|
||||
|
||||
// Each unit cell keeps its value when sampled four times as finely
|
||||
let coarse = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap();
|
||||
let fine = render_pattern(&white_noise(3), [DVec2::ZERO, DVec2::splat(4.)], 16, 16).unwrap();
|
||||
for y in 0..16 {
|
||||
for x in 0..16 {
|
||||
assert_eq!(fine.data[y * 16 + x], coarse.data[(y / 4) * 4 + x / 4]);
|
||||
}
|
||||
}
|
||||
|
||||
// The values spread across the whole range, and another seed gives others
|
||||
let luminances: Vec<f32> = coarse.data.iter().map(|color| color.r()).collect();
|
||||
assert!(luminances.iter().any(|&value| value < 0.5) && luminances.iter().any(|&value| value > 0.5));
|
||||
assert_ne!(render_pattern(&white_noise(4), [DVec2::ZERO, DVec2::splat(4.)], 4, 4).unwrap().data, coarse.data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
use core_types::Color;
|
||||
|
||||
/// A per-pixel color mapping, run by `map_cpu` on the CPU.
|
||||
pub trait MapColor: Sync + 'static {
|
||||
fn map_cpu(&self, color: Color) -> Color;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! The kernels carrying out raster operations, such as color adjustments and procedural patterns, each worked out once from its settings.
|
||||
|
||||
pub mod adjustment_tables;
|
||||
pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod raster_effects;
|
||||
pub mod value_effects;
|
||||
|
||||
pub use kernel::*;
|
||||
pub use raster_effects::evaluate_raster_effects;
|
||||
pub use value_effects::{evaluate_color_effects, evaluate_gradient_effects};
|
||||
Loaded 100 of 155 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user