mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d27468144e | ||
|
|
33dd5e545a | ||
|
|
4f0d8c7f4c | ||
|
|
1335e9a0f8 | ||
|
|
89238b669a | ||
|
|
da2c5a2d13 | ||
|
|
c75ebbd143 | ||
|
|
addba860d3 | ||
|
|
9526711aa2 | ||
|
|
d8b9f67adb | ||
|
|
b149248db9 | ||
|
|
7b4dc4d8a7 | ||
|
|
feea64170a | ||
|
|
6541449a4a | ||
|
|
5e92356578 | ||
|
|
3ca1376f93 | ||
|
|
93d2738a23 | ||
|
|
9557c6adfc |
No files matched your search
@@ -7,6 +7,8 @@ on:
|
||||
push:
|
||||
branches:
|
||||
- master
|
||||
# Runs the checks on a pushed branch that has no PR yet, such as each branch of a stack
|
||||
workflow_dispatch: {}
|
||||
|
||||
# Cancel a PR's in-progress checks once a newer commit is pushed to it (other runs are keyed by their commit, so those never cancel each other)
|
||||
concurrency:
|
||||
@@ -245,7 +247,8 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
|
||||
# A manual run has no base commit of its own, so it compares against master
|
||||
BASE_REF: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha || 'master' }}
|
||||
steps:
|
||||
- name: 📥 Clone repository
|
||||
uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0
|
||||
@@ -259,7 +262,9 @@ jobs:
|
||||
rustflags: ""
|
||||
|
||||
- name: 📥 Fetch the base commit
|
||||
run: git fetch --depth=1 origin "$BASE_SHA"
|
||||
run: |
|
||||
git fetch --depth=1 origin "$BASE_REF"
|
||||
echo "BASE_SHA=$(git rev-parse FETCH_HEAD)" >> "$GITHUB_ENV"
|
||||
|
||||
- name: 🔬 Check migrations against the base commit
|
||||
run: cargo run --locked --package migration-snapshot -- check --baseline "$BASE_SHA"
|
||||
|
||||
Generated
+31
@@ -590,6 +590,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -2534,6 +2535,35 @@ dependencies = [
|
||||
"smallvec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui"
|
||||
version = "0.0.0"
|
||||
dependencies = [
|
||||
"core-types",
|
||||
"dyn-any",
|
||||
"futures",
|
||||
"glam",
|
||||
"graph-craft",
|
||||
"graph-ui-icons",
|
||||
"graphene-application-io",
|
||||
"graphene-hash",
|
||||
"graphene-std",
|
||||
"graphic-types",
|
||||
"interpreted-executor",
|
||||
"node-macro",
|
||||
"preprocessor",
|
||||
"rendering",
|
||||
"svg-convert",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
"vello_gpu",
|
||||
"wgpu-executor",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "graph-ui-icons"
|
||||
version = "0.0.0"
|
||||
|
||||
[[package]]
|
||||
name = "graphene-animation"
|
||||
version = "0.0.0"
|
||||
@@ -5745,6 +5775,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -34,6 +34,8 @@ members = [
|
||||
"node-graph/libraries/*",
|
||||
"node-graph/nodes/*",
|
||||
"node-graph/graph-craft",
|
||||
"node-graph/graph-ui",
|
||||
"node-graph/graph-ui/icons",
|
||||
"node-graph/graphene-cli",
|
||||
"node-graph/nodes/gstd",
|
||||
"node-graph/interpreted-executor",
|
||||
@@ -112,6 +114,8 @@ vectorize-nodes = { path = "node-graph/nodes/vectorize" }
|
||||
math-nodes = { path = "node-graph/nodes/math" }
|
||||
path-bool-nodes = { path = "node-graph/nodes/path-bool" }
|
||||
graph-craft = { path = "node-graph/graph-craft" }
|
||||
graph-ui = { path = "node-graph/graph-ui" }
|
||||
graph-ui-icons = { path = "node-graph/graph-ui/icons" }
|
||||
document-format = { path = "document/format" }
|
||||
document-graph-storage = { path = "document/graph-storage", default-features = false }
|
||||
document-container = { path = "document/container" }
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Bevel & Emboss' defaults to fitting gradient textures without a transform across the content.
|
||||
#[migration("blending_nodes::effects::BevelAndEmbossNode"@2 => @3)]
|
||||
pub fn bevel_and_emboss_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(20, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BevelAndEmbossV2, &contract());
|
||||
check_undo(&BevelAndEmbossV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_texture_placement() {
|
||||
let inputs: Vec<_> = (0..20).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BevelAndEmbossV2);
|
||||
let bevel = fixture.add(decl!("blending_nodes::effects::BevelAndEmbossNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BevelAndEmbossV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, bevel), Some(decl!("blending_nodes::effects::BevelAndEmbossNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, bevel), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
use migration_core::{Inputs, NodeInput, encode, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
TypeDefault(Type),
|
||||
}
|
||||
|
||||
/// Frozen mirror of the `Type` an empty list of graphics stores.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Type {
|
||||
Concrete(TypeDescriptor),
|
||||
List(Box<Type>),
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct TypeDescriptor {
|
||||
name: String,
|
||||
}
|
||||
|
||||
/// 'Blur' gained a radius mask after its radius, left empty to keep blurring the whole content by the radius.
|
||||
#[migration("blending_nodes::effects::BlurNode"@2 => @3)]
|
||||
pub fn blur_v2(inputs: &mut Inputs) {
|
||||
inputs.insert(2, empty_radius_mask());
|
||||
}
|
||||
|
||||
/// The radius mask input with nothing connected and not exposed, as the node's definition gives it.
|
||||
fn empty_radius_mask() -> NodeInput {
|
||||
let no_graphics = Tagged::TypeDefault(Type::List(Box::new(Type::Concrete(TypeDescriptor {
|
||||
name: "graphic_types::graphic::Graphic".to_string(),
|
||||
}))));
|
||||
NodeInput::Value {
|
||||
value: encode(&no_graphics),
|
||||
exposed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&BlurV2, &contract());
|
||||
check_undo(&BlurV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_inserts_an_empty_radius_mask_after_the_radius() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&BlurV2);
|
||||
let blur = fixture.add(decl!("blending_nodes::effects::BlurNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&BlurV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.insert(2, empty_radius_mask());
|
||||
assert_eq!(fixture.declaration_of(&migrated, blur), Some(decl!("blending_nodes::effects::BlurNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, blur), expected);
|
||||
assert!(matches!(expected[2], NodeInput::Value { exposed: false, .. }), "the radius mask is not exposed");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variant this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
}
|
||||
|
||||
/// 'Convolution Kernel' gained Apply to Alpha after its offset, left off to keep the content's coverage as it is.
|
||||
#[migration("blending_nodes::filters::ConvolutionKernelNode"@1 => @2)]
|
||||
pub fn convolution_kernel_v1(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Bool(false)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&ConvolutionKernelV1, &contract());
|
||||
check_undo(&ConvolutionKernelV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_appends_apply_to_alpha_turned_off() {
|
||||
let inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&ConvolutionKernelV1);
|
||||
let kernel = fixture.add(decl!("blending_nodes::filters::ConvolutionKernelNode"@1), inputs.clone());
|
||||
let migrated = fixture.migrate(&ConvolutionKernelV1).unwrap();
|
||||
|
||||
assert_eq!(fixture.declaration_of(&migrated, kernel), Some(decl!("blending_nodes::filters::ConvolutionKernelNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, kernel), [inputs, vec![literal(Tagged::Bool(false))]].concat());
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
//! Migrations of the nodes in `blending_nodes`.
|
||||
|
||||
mod bevel_and_emboss_v1;
|
||||
mod bevel_and_emboss_v2;
|
||||
mod blur_v2;
|
||||
mod convolution_kernel_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_shadow_v1;
|
||||
@@ -8,6 +11,8 @@ mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod outline_v3;
|
||||
mod paint_overlay_from_color_overlay;
|
||||
mod paint_overlay_v2;
|
||||
mod renames;
|
||||
mod satin_v1;
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Outline' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::OutlineNode"@3 => @4)]
|
||||
pub fn outline_v3(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(6, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OutlineV3, &contract());
|
||||
check_undo(&OutlineV3, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..6).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OutlineV3);
|
||||
let outline = fixture.add(decl!("blending_nodes::effects::OutlineNode"@3), inputs.clone());
|
||||
let migrated = fixture.migrate(&OutlineV3).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, outline), Some(decl!("blending_nodes::effects::OutlineNode"@4)));
|
||||
assert_eq!(fixture.inputs(&migrated, outline), expected);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use migration_core::{Inputs, NodeInput, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Bool(bool),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Paint Overlay' defaults to fitting gradients without a transform across the content.
|
||||
#[migration("blending_nodes::effects::PaintOverlayNode"@2 => @3)]
|
||||
pub fn paint_overlay_v2(inputs: &mut Inputs) {
|
||||
for input in added_inputs() {
|
||||
inputs.push(input);
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an unplaced gradient uses an explicit transform, and the transform itself.
|
||||
fn added_inputs() -> [NodeInput; 2] {
|
||||
[literal(Tagged::Bool(false)), literal(Tagged::DAffine2([1., 0., 0., 1., 0., 0.]))]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(4, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&PaintOverlayV2, &contract());
|
||||
check_undo(&PaintOverlayV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_an_unset_placement() {
|
||||
let inputs: Vec<_> = (0..4).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&PaintOverlayV2);
|
||||
let overlay = fixture.add(decl!("blending_nodes::effects::PaintOverlayNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&PaintOverlayV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend(added_inputs());
|
||||
assert_eq!(fixture.declaration_of(&migrated, overlay), Some(decl!("blending_nodes::effects::PaintOverlayNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, overlay), expected);
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ use crate::messages::input_mapper::utility_types::misc::ActionShortcut;
|
||||
use crate::messages::layout::utility_types::math_expression::MathExpressionCompletions;
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{
|
||||
BoxSelection, ContextMenuInformation, FrontendClickTargets, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
BoxSelection, ContextMenuInformation, FrontendGraphInput, FrontendGraphOutput, FrontendNode, FrontendNodeType, FrontendRemoteCursor, NodeGraphErrorDiagnostic,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{LayerPanelEntry, LayerStructureEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{WirePath, WirePathUpdate};
|
||||
@@ -196,10 +196,6 @@ pub enum FrontendMessage {
|
||||
#[serde(rename = "contextMenuInformation")]
|
||||
context_menu_information: Option<ContextMenuInformation>,
|
||||
},
|
||||
UpdateClickTargets {
|
||||
#[serde(rename = "clickTargets")]
|
||||
click_targets: Option<FrontendClickTargets>,
|
||||
},
|
||||
UpdateGraphViewOverlay {
|
||||
open: bool,
|
||||
},
|
||||
|
||||
@@ -87,9 +87,7 @@ pub fn input_mappings(zoom_with_scroll: bool, environment: Environment) -> Mappi
|
||||
entry!(KeyDown(KeyH); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedVisibility),
|
||||
entry!(KeyDown(KeyL); modifiers=[Accel], action_dispatch=NodeGraphMessage::ToggleSelectedLocked),
|
||||
entry!(KeyDown(KeyL); modifiers=[Alt], action_dispatch=NodeGraphMessage::ToggleSelectedAsLayersOrNodes),
|
||||
entry!(KeyDown(KeyC); modifiers=[Alt], action_dispatch=NodeGraphMessage::SendClickTargets),
|
||||
entry!(KeyDown(KeyM); modifiers=[Accel], action_dispatch=NodeGraphMessage::MergeSelectedNodes),
|
||||
entry!(KeyUp(KeyC); action_dispatch=NodeGraphMessage::EndSendClickTargets),
|
||||
entry!(KeyDown(ArrowUp); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Up }),
|
||||
entry!(KeyDown(ArrowRight); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Right }),
|
||||
entry!(KeyDown(ArrowDown); action_dispatch=NodeGraphMessage::NudgeSelectedNodes { direction: Direction::Down }),
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Layers clipped to a base through the editor's own graph, where the base's filters shape what clips to it but the shadows it casts don't.
|
||||
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::test_utils::gpu_executor;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use glam::{DAffine2, UVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graphene_std::blending_nodes::effects::{blur, drop_shadow};
|
||||
use graphene_std::graphic::{IntoGraphicList, extend};
|
||||
use graphene_std::list::{Item, List};
|
||||
use graphene_std::renderer::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use graphene_std::{Graphic, NodeParameter, ProtoNodeIdentifier, Vector};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Base {
|
||||
VectorLayer,
|
||||
ImageLayer,
|
||||
/// A group holding a vector layer, with the effect on the group.
|
||||
Group,
|
||||
}
|
||||
|
||||
async fn add_effect(editor: &mut EditorTestUtils, layer: LayerNodeIdentifier, effect: ProtoNodeIdentifier) {
|
||||
let node_type = DefinitionIdentifier::ProtoNode(effect.clone());
|
||||
editor.handle_message(NodeGraphMessage::CreateNodeInLayerWithTransaction { node_type, layer }).await;
|
||||
|
||||
if effect == blur::IDENTIFIER {
|
||||
let node_id = NodeGraphLayer::new(layer, &editor.active_document().network_interface)
|
||||
.upstream_node_id_from_protonode(effect)
|
||||
.expect("the layer has its blur");
|
||||
let value = Box::new(TaggedValue::Number(10.));
|
||||
editor
|
||||
.handle_message(NodeGraphMessage::SetInputValue {
|
||||
node_id,
|
||||
input_index: blur::RadiusInput::INDEX,
|
||||
value,
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
|
||||
/// The root stack of a document with a blue base filling (50, 50) to (130, 130) and a larger red layer clipped to it, with `effect` on the base.
|
||||
async fn clipped_stack(base: Base, effect: ProtoNodeIdentifier) -> List<Graphic> {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let blue = Color::from_rgbaf32_unchecked(0., 0., 1., 1.);
|
||||
let red = Color::from_rgbaf32_unchecked(1., 0., 0., 1.);
|
||||
|
||||
match base {
|
||||
Base::ImageLayer => editor.create_raster_image(Image::new(80, 80, blue), Some((90., 90.))).await,
|
||||
Base::VectorLayer | Base::Group => {
|
||||
editor.select_primary_color(blue).await;
|
||||
editor.select_secondary_color(blue).await;
|
||||
editor.draw_rect(50., 50., 130., 130.).await;
|
||||
}
|
||||
}
|
||||
let base_layer = editor.get_selected_layer().await.expect("the base is selected");
|
||||
if !matches!(base, Base::Group) {
|
||||
add_effect(&mut editor, base_layer, effect.clone()).await;
|
||||
}
|
||||
|
||||
editor.select_tool(ToolType::Select).await;
|
||||
editor.select_primary_color(red).await;
|
||||
editor.select_secondary_color(red).await;
|
||||
editor.draw_rect(20., 20., 200., 200.).await;
|
||||
let clipped_layer = editor.get_selected_layer().await.expect("the clipped layer is selected");
|
||||
editor
|
||||
.handle_message(GraphOperationMessage::FillColorSet {
|
||||
layer: clipped_layer,
|
||||
color: Some(red),
|
||||
})
|
||||
.await;
|
||||
editor.handle_message(DocumentMessage::ClipLayer { id: clipped_layer.to_node() }).await;
|
||||
|
||||
// Grouped once the red is clipped, the group takes the base's place beneath it
|
||||
if let Base::Group = base {
|
||||
let nodes = vec![base_layer.to_node()];
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes }).await;
|
||||
let group_folder_type = GroupFolderType::Layer;
|
||||
editor.handle_message(DocumentMessage::GroupSelectedLayers { group_folder_type }).await;
|
||||
let group = editor.get_selected_layer().await.expect("the group is selected");
|
||||
add_effect(&mut editor, group, effect).await;
|
||||
}
|
||||
|
||||
// The stack is what the root's 'Extend' nodes put together: the base's layer extended by the clipped one
|
||||
let instrumented = editor.eval_graph_until_finished().await.expect("the graph evaluates");
|
||||
let mut news = instrumented.grab_all_input::<extend::NewInput, Item<Graphic>>(&editor.runtime);
|
||||
let clipped = news.find(|new| new.element().had_clip_enabled()).expect("the clipped layer is extended onto the base");
|
||||
let mut bases = instrumented.grab_all_input::<extend::BaseInput, List<Graphic>>(&editor.runtime);
|
||||
let mut stack = bases.find(|base| base.len() == 1).expect("the base's layer is extended");
|
||||
stack.push(clipped);
|
||||
stack
|
||||
}
|
||||
|
||||
/// Checks in SVG and in Vello that the red clipped to the base shows past the base's edges if `blurred`, and that a shadow the base casts doesn't widen the clip.
|
||||
fn assert_clip(name: &str, graphic: &Graphic, blurred: bool) {
|
||||
// The clip's def in SVG carries out the blur but not the shadow
|
||||
let mut render = SvgRender::new();
|
||||
graphic.render_svg(
|
||||
&mut render,
|
||||
&RenderParams {
|
||||
for_export: true,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let body = render.svg.to_svg_string();
|
||||
let reference = body.rfind("url(#mask-").expect("the red is clipped");
|
||||
let id: String = body[reference + "url(#".len()..].chars().take_while(|&character| character != ')').collect();
|
||||
let defs = &render.svg_defs;
|
||||
let def_start = defs.find(&format!(r#"id="{id}""#)).expect("the clip has a def");
|
||||
let def_end = ["</mask>", "</clipPath>"]
|
||||
.iter()
|
||||
.filter_map(|closing| defs[def_start..].find(closing))
|
||||
.min()
|
||||
.expect("the clip's def is closed");
|
||||
let clip = &defs[def_start..def_start + def_end];
|
||||
assert_eq!(clip.contains("filter="), blurred, "{name}: the clip's def is {clip}");
|
||||
|
||||
// In Vello, the red past the base's edges shows where the blur reaches, but not where the shadow falls
|
||||
let size = UVec2::new(256, 256);
|
||||
let executor = gpu_executor();
|
||||
let texture = executor
|
||||
.render_vello(size, DAffine2::IDENTITY, &mut |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()))
|
||||
.expect("the clip renders");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render reads back");
|
||||
let pixel = |x: u32, y: u32| -> [u8; 4] {
|
||||
let index = (y * size.x + x) as usize * 4;
|
||||
[pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]]
|
||||
};
|
||||
|
||||
let within = pixel(90, 90);
|
||||
assert!(within[0] >= 250 && within[2] <= 5 && within[3] == 255, "{name}: within the base, the red is {within:?}");
|
||||
assert_eq!(pixel(134, 90)[0] > 0, blurred, "{name}: past the base's right edge, the red is {:?}", pixel(134, 90));
|
||||
assert_eq!(pixel(93, 135)[0] > 0, blurred, "{name}: past the base's bottom edge, the red is {:?}", pixel(93, 135));
|
||||
assert!(blurred || pixel(93, 135)[3] > 0, "{name}: the base's shadow shows where it falls");
|
||||
assert_eq!(pixel(170, 90)[3], 0, "{name}: the red is clipped away well past the base");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clipping_bases_clip_by_their_filters_but_not_the_shadows_they_cast() {
|
||||
for (effect_name, effect, blurred) in [("Blur", blur::IDENTIFIER, true), ("Drop Shadow", drop_shadow::IDENTIFIER, false)] {
|
||||
for base in [Base::VectorLayer, Base::ImageLayer, Base::Group] {
|
||||
let stack = clipped_stack(base, effect.clone()).await;
|
||||
assert_clip(&format!("{base:?} with {effect_name}"), &Graphic::GraphicList(stack.clone()), blurred);
|
||||
|
||||
// Flattened into one list of vectors, the base clips its sibling by the same rule
|
||||
if let Base::VectorLayer = base {
|
||||
let flattened: List<Vector> = stack.into_flattened_list();
|
||||
assert_clip(&format!("flattened vectors with {effect_name}"), &Graphic::VectorList(flattened), blurred);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crate::messages::tool::tool_messages::tool_prelude::*;
|
||||
use crate::node_graph_executor::InspectedContext;
|
||||
use glam::{Affine2, DAffine2, Vec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::blending::BlendMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
@@ -35,7 +36,7 @@ use graphene_std::vector::style::{
|
||||
use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector};
|
||||
use graphene_std::{
|
||||
Appearance, Artboard, BevelDirection, BevelStyle, BevelTechnique, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, GlowTechnique, Graphic,
|
||||
MaskMode,
|
||||
MaskMode, MinimumMaximumMode, NoiseDistribution,
|
||||
};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
@@ -1271,16 +1272,19 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
RadialBlurMethod,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
@@ -1456,9 +1460,11 @@ macro_rules! known_item_types {
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
RadialBlurMethod,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1469,6 +1475,7 @@ macro_rules! known_item_types {
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
|
||||
@@ -304,8 +304,15 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
let visibility_settings = self.overlays_visibility_settings;
|
||||
|
||||
// Send the overlays message to the overlays message handler
|
||||
self.overlays_message_handler
|
||||
.process_message(message, responses, OverlaysMessageContext { visibility_settings, viewport });
|
||||
self.overlays_message_handler.process_message(
|
||||
message,
|
||||
responses,
|
||||
OverlaysMessageContext {
|
||||
visibility_settings,
|
||||
viewport,
|
||||
graph_open: self.graph_view_overlay_open,
|
||||
},
|
||||
);
|
||||
}
|
||||
DocumentMessage::Inspector(message) => {
|
||||
let context = InspectorMessageContext {
|
||||
@@ -2680,7 +2687,6 @@ impl DocumentMessageHandler {
|
||||
fn finish_remote_reconcile(&mut self, reconciled: Reconciled, resources_changed: bool, open_network_transform: Option<DAffine2>, responses: &mut VecDeque<Message>) {
|
||||
for path in self.network_interface.paths_reaching(&reconciled.networks) {
|
||||
self.network_interface.unload_import_export_ports(&path);
|
||||
self.network_interface.unload_all_nodes_bounding_box(&path);
|
||||
self.network_interface.unload_outward_wires(&path);
|
||||
}
|
||||
self.network_interface.load_structure();
|
||||
|
||||
-3
@@ -807,9 +807,6 @@ fn import_usvg_node(modify_inputs: &mut ModifyInputsContext, node: &usvg::Node,
|
||||
// Set positions for all imported descendants in a single O(n) pass
|
||||
let parent_pos = modify_inputs.network_interface.position(&layer.to_node(), &[]).unwrap_or(IVec2::ZERO);
|
||||
set_import_child_positions(modify_inputs.network_interface, layer, parent_pos, &child_extents_svg_order, &group_extents_map);
|
||||
|
||||
// Invalidate caches once after all positions are set
|
||||
modify_inputs.network_interface.unload_all_nodes_bounding_box(&[]);
|
||||
}
|
||||
usvg::Node::Path(path) => {
|
||||
import_usvg_path(modify_inputs, node, path, layer, gradient_info);
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#[cfg(test)]
|
||||
mod clipping_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
|
||||
@@ -689,6 +689,7 @@ fn static_node_inspector() -> NodeInspector {
|
||||
map.insert("grid_inspector".to_string(), Box::new(node_inspector::grid_inspector));
|
||||
map.insert("spiral_inspector".to_string(), Box::new(node_inspector::spiral_inspector));
|
||||
map.insert("sample_polyline_inspector".to_string(), Box::new(node_inspector::sample_polyline_inspector));
|
||||
map.insert("sharpen_inspector".to_string(), Box::new(node_inspector::sharpen_inspector));
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
@@ -207,8 +207,6 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
SendClickTargets,
|
||||
EndSendClickTargets,
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
@@ -448,8 +446,6 @@ impl NodeGraphMessage {
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::SendClickTargets
|
||||
| Self::EndSendClickTargets
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
|
||||
@@ -24,14 +24,12 @@ use crate::messages::tool::common_functionality::utility_functions::{make_path_e
|
||||
use crate::messages::tool::tool_messages::tool_prelude::{Key, MouseMotion};
|
||||
use crate::messages::tool::utility_types::{HintData, HintGroup, HintInfo};
|
||||
use crate::messages::viewport::Position;
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graphene_std::math::math_ext::QuadExt;
|
||||
use graphene_std::vector::algorithms::bezpath_algorithms::bezpath_is_inside_bezpath;
|
||||
use graphene_std::*;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
use renderer::Quad;
|
||||
|
||||
#[derive(Debug, ExtractField)]
|
||||
pub struct NodeGraphMessageContext<'a> {
|
||||
@@ -2025,10 +2023,6 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
selected_nodes.set_selected_nodes(nodes);
|
||||
responses.add(EventMessage::SelectionChanged);
|
||||
}
|
||||
NodeGraphMessage::SendClickTargets => responses.add(FrontendMessage::UpdateClickTargets {
|
||||
click_targets: Some(network_interface.collect_frontend_click_targets(breadcrumb_network_path)),
|
||||
}),
|
||||
NodeGraphMessage::EndSendClickTargets => responses.add(FrontendMessage::UpdateClickTargets { click_targets: None }),
|
||||
NodeGraphMessage::UnloadWires => {
|
||||
self.frontend_wires.clear();
|
||||
responses.add(FrontendMessage::ClearAllNodeGraphWires);
|
||||
@@ -2543,13 +2537,13 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
HashSet::new()
|
||||
};
|
||||
let all_nodes = network_metadata.persistent_metadata.node_metadata.keys().cloned().collect::<Vec<_>>();
|
||||
let [selection_min, selection_max] = [box_selection_start.min(box_selection_end_graph), box_selection_start.max(box_selection_end_graph)];
|
||||
for node_id in all_nodes {
|
||||
let Some(click_targets) = network_interface.node_click_targets(&node_id, selection_network_path) else {
|
||||
log::error!("Could not get transient metadata for node {node_id}");
|
||||
let Some(body) = network_interface.with_layout(selection_network_path, |layout| layout.body(&node_id)).flatten() else {
|
||||
log::error!("Could not get the body of node {node_id}");
|
||||
continue;
|
||||
};
|
||||
let quad = Quad::from_box([box_selection_start, box_selection_end_graph]);
|
||||
if click_targets.node_click_target.intersect_path(|| quad.to_lines(), DAffine2::IDENTITY) {
|
||||
if body.overlaps(selection_min, selection_max) {
|
||||
if alt {
|
||||
nodes.remove(&node_id);
|
||||
} else {
|
||||
@@ -3211,11 +3205,6 @@ impl NodeGraphMessageHandler {
|
||||
pub fn actions_additional_if_node_graph_is_open(&self) -> ActionList {
|
||||
let mut common = actions!(NodeGraphMessageDiscriminant; EnterNestedNetwork, PointerDown, PointerMove, PointerUp);
|
||||
|
||||
// Only development builds draw the click targets, so users don't come across the overlay by accident
|
||||
if cfg!(debug_assertions) {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant; SendClickTargets, EndSendClickTargets));
|
||||
}
|
||||
|
||||
if self.has_selection {
|
||||
common.extend(actions!(NodeGraphMessageDiscriminant;
|
||||
Copy,
|
||||
|
||||
@@ -20,6 +20,7 @@ use graph_craft::application_io::resource::{DataSource, Resource, ResourceId};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput};
|
||||
use graph_craft::{Type, concrete, item};
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::color::SRGBA8;
|
||||
use graphene_std::raster::{
|
||||
@@ -40,7 +41,7 @@ use graphene_std::vector::style::{
|
||||
build_transform_with_y_preservation,
|
||||
};
|
||||
use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, Vector};
|
||||
use graphene_std::{Artboard, BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, Graphic, MaskMode, MinimumMaximumMode, NoiseDistribution, Vector};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -453,9 +454,12 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
Some(x) if id_is::<GlowTechnique>(x) => enum_choice::<GlowTechnique>().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::<MaskMode>(x) => enum_choice::<MaskMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<MinimumMaximumMode>(x) => enum_choice::<MinimumMaximumMode>().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::<RadialBlurMethod>(x) => enum_choice::<RadialBlurMethod>().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::<BevelTechnique>(x) => enum_choice::<BevelTechnique>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<NoiseDistribution>(x) => enum_choice::<NoiseDistribution>().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(),
|
||||
@@ -3768,6 +3772,29 @@ pub fn offset_path_inspector(node_id: NodeId, context: &mut NodeInspectorContext
|
||||
vec![LayoutGroup::row(distance), join, LayoutGroup::row(miter_limit)]
|
||||
}
|
||||
|
||||
pub(crate) fn sharpen_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::filters::sharpen::*;
|
||||
|
||||
// Edges Only compares against the four nearest neighbors in place of the blur, so it doesn't read the radius
|
||||
let edges_only = get_document_node(node_id, context)
|
||||
.ok()
|
||||
.and_then(|document_node| document_node.input(EdgesOnlyInput).and_then(|input| input.as_value()))
|
||||
.is_some_and(|tagged| matches!(tagged, TaggedValue::Bool(true)));
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit("%").min(0.).range_max(Some(500.));
|
||||
let amount = number_widget(ParameterWidgetsInfo::new(node_id, AmountInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit(" px").min(0.).range_max(Some(250.)).disabled(edges_only);
|
||||
let radius = number_widget(ParameterWidgetsInfo::new(node_id, RadiusInput, true, context), number_input);
|
||||
|
||||
let number_input = NumberInput::default().mode_range().min(0.).range_max(Some(255.));
|
||||
let threshold = number_widget(ParameterWidgetsInfo::new(node_id, ThresholdInput, true, context), number_input);
|
||||
|
||||
let edges_only = bool_widget(ParameterWidgetsInfo::new(node_id, EdgesOnlyInput, true, context), CheckboxInput::default());
|
||||
|
||||
vec![LayoutGroup::row(amount), LayoutGroup::row(radius), LayoutGroup::row(threshold), LayoutGroup::row(edges_only)]
|
||||
}
|
||||
|
||||
pub struct ParameterWidgetsInfo<'a> {
|
||||
document_id: DocumentId,
|
||||
network_interface: &'a NodeNetworkInterface,
|
||||
|
||||
@@ -212,23 +212,6 @@ pub struct NodeEvaluationError {
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, Default, serde::Serialize, serde::Deserialize)]
|
||||
pub struct FrontendClickTargets {
|
||||
#[serde(rename = "nodeClickTargets")]
|
||||
pub node_click_targets: Vec<String>,
|
||||
#[serde(rename = "layerClickTargets")]
|
||||
pub layer_click_targets: Vec<String>,
|
||||
#[serde(rename = "connectorClickTargets")]
|
||||
pub connector_click_targets: Vec<String>,
|
||||
#[serde(rename = "iconClickTargets")]
|
||||
pub icon_click_targets: Vec<String>,
|
||||
#[serde(rename = "allNodesBoundingBox")]
|
||||
pub all_nodes_bounding_box: String,
|
||||
#[serde(rename = "importExportNames")]
|
||||
pub import_export_names: Vec<String>,
|
||||
}
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub enum Direction {
|
||||
|
||||
@@ -5,6 +5,7 @@ use crate::messages::prelude::*;
|
||||
pub struct OverlaysMessageContext<'a> {
|
||||
pub visibility_settings: OverlaysVisibilitySettings,
|
||||
pub viewport: &'a ViewportMessageHandler,
|
||||
pub graph_open: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, ExtractField)]
|
||||
@@ -25,7 +26,7 @@ impl MessageHandler<OverlaysMessage, OverlaysMessageContext<'_>> for OverlaysMes
|
||||
|
||||
let overlay_context = OverlayContext::new(*viewport, visibility_settings);
|
||||
|
||||
if visibility_settings.all() {
|
||||
if visibility_settings.all() && !context.graph_open {
|
||||
responses.add(DocumentMessage::GridOverlays { context: overlay_context.clone() });
|
||||
responses.add(DocumentMessage::LayersPanelHoverOverlays { context: overlay_context.clone() });
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
//! Times laying out the demo artworks, building their click targets, and hit testing them, as the editor does on demand.
|
||||
|
||||
use super::test_support::open_demo;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{GlideOffsets, InputConnector, OutputConnector, Part};
|
||||
use crate::messages::portfolio::document::utility_types::wires::GraphWireStyle;
|
||||
use glam::DVec2;
|
||||
use graphene_std::uuid::NodeId;
|
||||
@@ -20,20 +20,32 @@ const DEMOS: [&str; 8] = [
|
||||
const REPETITIONS: u32 = 200;
|
||||
|
||||
#[test]
|
||||
fn wire_anchors_match_the_ports_of_every_demo_node() {
|
||||
fn wire_anchors_lie_on_the_ports_of_every_demo_node() {
|
||||
for demo in DEMOS {
|
||||
let document = open_demo(demo);
|
||||
let interface = &document.network_interface;
|
||||
|
||||
for node_id in interface.document_network().nodes.keys() {
|
||||
let ports = interface.compute_node_ports(node_id, &[]).expect("every node has ports");
|
||||
// A redirect dot's wires attach at its center, between the gutters they're grabbed from
|
||||
let body = interface.node_bounding_box(node_id, &[]).expect("every node has a body");
|
||||
let is_redirect_dot = interface.is_redirect_dot(node_id, &[]);
|
||||
let on_port = |wanted: Part, anchor: Option<DVec2>| {
|
||||
let port = interface.find_node_part(node_id, &[], |part, target| (part == wanted).then_some(*target));
|
||||
match (port, anchor) {
|
||||
(Some(_), Some(anchor)) if is_redirect_dot => anchor == (body[0] + body[1]) / 2.,
|
||||
(Some(port), Some(anchor)) => port.contains(anchor),
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
}
|
||||
};
|
||||
|
||||
for index in 0..interface.number_of_inputs(node_id, &[]) {
|
||||
let input = InputConnector::node_at_index(*node_id, index);
|
||||
assert_eq!(interface.input_position(&input, &[]), ports.input_port_position(index), "{demo}: input {index} of node {node_id}");
|
||||
let anchor = interface.input_position(&InputConnector::node_at_index(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Input(index as u32), anchor), "{demo}: input {index} of node {node_id} attaches at {anchor:?}");
|
||||
}
|
||||
for index in 0..interface.number_of_outputs(node_id, &[]) {
|
||||
let output = OutputConnector::node(*node_id, index);
|
||||
assert_eq!(interface.output_position(&output, &[]), ports.output_port_position(index), "{demo}: output {index} of node {node_id}");
|
||||
let anchor = interface.output_position(&OutputConnector::node(*node_id, index), &[]);
|
||||
assert!(on_port(Part::Output(index as u32), anchor), "{demo}: output {index} of node {node_id} attaches at {anchor:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -60,7 +72,7 @@ fn time_the_layout_click_targets_and_hit_tests() {
|
||||
let start = Instant::now();
|
||||
for _ in 0..REPETITIONS {
|
||||
for node_id in &node_ids {
|
||||
std::hint::black_box(interface.node_click_targets(node_id, &[]));
|
||||
std::hint::black_box(interface.find_node_part(node_id, &[], |_, target| std::hint::black_box(target).part.eq(&Part::Name).then_some(())));
|
||||
}
|
||||
}
|
||||
let all_click_targets = start.elapsed() / REPETITIONS;
|
||||
|
||||
@@ -35,7 +35,6 @@ fn store_drawn_positions_as_absolute(interface: &mut NodeNetworkInterface, posit
|
||||
if let Some(mut node) = interface.node_mut(NodeLocator::new(*node_id, network_path)) {
|
||||
node.set_absolute_position(*position);
|
||||
}
|
||||
interface.invalidate_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,14 +171,14 @@ fn the_layout_kept_after_a_drag_matches_the_network_as_stored() {
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
let kept = interface.positions(node_ids.iter().copied(), &[]);
|
||||
let Some((_, indices, graph)) = interface.layout_graph(&[]) else {
|
||||
let Some((laid_out, graph)) = interface.layout_graph(&[]) else {
|
||||
panic!("the root network is laid out")
|
||||
};
|
||||
let fresh = graph_layout::Layout::new(&graph);
|
||||
for (other, position) in kept {
|
||||
assert_eq!(
|
||||
Some(position),
|
||||
indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
laid_out.indices.get(&other).map(|index| fresh.node(*index).position),
|
||||
"After dragging {node_id} by {offset}, node {other} should be where the stored network places it"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,7 @@ mod layout;
|
||||
mod layout_pass;
|
||||
mod memo_network;
|
||||
mod mutations;
|
||||
mod node_parts;
|
||||
mod queries;
|
||||
mod reconcile;
|
||||
mod resolved_types;
|
||||
@@ -36,6 +37,7 @@ mod view;
|
||||
|
||||
pub use editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange};
|
||||
pub use layout_pass::NetworkLayout;
|
||||
pub use node_parts::{Part, PartTarget};
|
||||
pub use reconcile::{ReconcileError, Reconciled};
|
||||
use store::Guarded;
|
||||
pub use store::NodeLocator;
|
||||
@@ -52,7 +54,7 @@ use crate::consts::{
|
||||
STACK_VERTICAL_GAP,
|
||||
};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, resolve_document_node_type, resolve_proto_node_definition, resolve_proto_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendClickTargets, FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{FrontendGraphDataType, FrontendGraphInput, FrontendGraphOutput};
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::resolved_types::ResolvedDocumentNodeTypes;
|
||||
use crate::messages::portfolio::document::utility_types::text_metrics::text_width;
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_thick_wire_center_line, build_vector_wire};
|
||||
|
||||
@@ -93,7 +93,7 @@ impl NodeNetworkInterface {
|
||||
EditorDelta::NodeMetadata { network, node_id, change } => {
|
||||
let Some(mut node) = self.node_mut_at(*network, *node_id) else { return };
|
||||
match change {
|
||||
NodeMetadataChange::NodeType(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::NodeType(node_type) | NodeMetadataChange::Position(node_type) => node.set_node_type(node_type.clone()),
|
||||
NodeMetadataChange::DisplayName(display_name) => node.set_display_name(display_name.clone()),
|
||||
NodeMetadataChange::Locked(locked) => node.set_locked(*locked),
|
||||
NodeMetadataChange::Pinned(pinned) => node.set_pinned(*pinned),
|
||||
|
||||
@@ -88,34 +88,15 @@ impl NodeNetworkInterface {
|
||||
*network_metadata.transient_metadata.glide_offsets.borrow_mut() = glide_offsets;
|
||||
}
|
||||
|
||||
pub fn import_export_ports(&mut self, network_path: &[NodeId]) -> Option<&Ports> {
|
||||
self.load_import_export_ports(network_path);
|
||||
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
let Some(ports) = transient.import_export_ports.get_loaded_mut() else {
|
||||
log::error!("Could not load import export ports in import_export_ports");
|
||||
return None;
|
||||
};
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// Reads the import/export ports through &self, loading them first if needed.
|
||||
/// Reads the import/export ports through &self, building them again first if the layout they were placed by has changed.
|
||||
pub(crate) fn with_import_export_ports<R>(&self, network_path: &[NodeId], read: impl FnOnce(&Ports) -> R) -> Option<R> {
|
||||
self.network_metadata(network_path)?
|
||||
.transient_metadata
|
||||
.import_export_ports
|
||||
.with_loaded_or(|| self.compute_import_export_ports(network_path), read)
|
||||
}
|
||||
let generation = self.with_layout(network_path, NetworkLayout::generation)?;
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.import_export_ports;
|
||||
if cache.with_loaded(|(placed_by, _)| *placed_by != generation) == Some(true) {
|
||||
cache.unload();
|
||||
}
|
||||
|
||||
pub fn load_import_export_ports(&self, network_path: &[NodeId]) {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in load_import_export_ports");
|
||||
return;
|
||||
};
|
||||
network_metadata.transient_metadata.import_export_ports.ensure_loaded(|| self.compute_import_export_ports(network_path));
|
||||
cache.with_loaded_or(|| Some((generation, self.compute_import_export_ports(network_path)?)), |(_, ports)| read(ports))
|
||||
}
|
||||
|
||||
pub(crate) fn unload_import_export_ports(&mut self, network_path: &[NodeId]) {
|
||||
@@ -126,78 +107,13 @@ impl NodeNetworkInterface {
|
||||
transient.import_export_ports.unload();
|
||||
}
|
||||
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in all_nodes_bounding_box");
|
||||
return None;
|
||||
};
|
||||
|
||||
let bounding_box = network_metadata
|
||||
.transient_metadata
|
||||
.all_nodes_bounding_box
|
||||
.with_loaded_or(|| self.compute_all_nodes_bounding_box(network_path), |bounds| *bounds);
|
||||
if bounding_box.is_none() {
|
||||
log::error!("Could not load all nodes bounding box in all_nodes_bounding_box");
|
||||
}
|
||||
bounding_box
|
||||
}
|
||||
|
||||
/// The combined bounds of every node in the network, in node graph space.
|
||||
fn compute_all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
|
||||
Some(
|
||||
nodes
|
||||
.iter()
|
||||
.filter_map(|node_id| self.node_bounding_box(node_id, network_path))
|
||||
.reduce(Quad::combine_bounds)
|
||||
.unwrap_or([DVec2::new(0., 0.), DVec2::new(0., 0.)]),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn unload_all_nodes_bounding_box(&mut self, network_path: &[NodeId]) {
|
||||
let Some(transient) = self.network_transient_mut(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in unload_all_nodes_bounding_box");
|
||||
return;
|
||||
};
|
||||
transient.all_nodes_bounding_box.unload();
|
||||
transient.import_export_clearance.unload();
|
||||
self.unload_import_export_ports(network_path);
|
||||
pub fn all_nodes_bounding_box(&self, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_layout(network_path, NetworkLayout::bounds)
|
||||
}
|
||||
|
||||
pub(crate) fn import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in import_export_clearance");
|
||||
return None;
|
||||
};
|
||||
|
||||
network_metadata
|
||||
.transient_metadata
|
||||
.import_export_clearance
|
||||
.with_loaded_or(|| self.compute_import_export_clearance(network_path), |clearance| *clearance)
|
||||
}
|
||||
|
||||
/// The horizontal extents of the nodes in the network, with the redirect dots measured by their centers apart from the rest.
|
||||
fn compute_import_export_clearance(&self, network_path: &[NodeId]) -> Option<ImportExportClearance> {
|
||||
let network_metadata = self.network_metadata(network_path)?;
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for node_id in network_metadata.persistent_metadata.node_metadata.keys() {
|
||||
let Some([top_left, bottom_right]) = self.node_bounding_box(node_id, network_path) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
let center = (top_left.x + bottom_right.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, top_left.x, bottom_right.x);
|
||||
}
|
||||
}
|
||||
|
||||
Some(clearance)
|
||||
self.with_layout(network_path, NetworkLayout::clearance)
|
||||
}
|
||||
|
||||
pub fn outward_wires(&mut self, network_path: &[NodeId]) -> Option<&HashMap<OutputConnector, Vec<InputConnector>>> {
|
||||
@@ -364,6 +280,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
pub fn layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<u32> {
|
||||
self.layer_width_and_name_width(node_id, network_path).map(|(layer_width, _)| layer_width)
|
||||
}
|
||||
|
||||
pub(super) fn layer_width_and_name_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(u32, f64)> {
|
||||
let Some(node_metadata) = self.node_metadata(node_id, network_path) else {
|
||||
log::error!("Could not get nested node_metadata in layer_width");
|
||||
return None;
|
||||
@@ -376,7 +296,7 @@ impl NodeNetworkInterface {
|
||||
node_metadata
|
||||
.transient_metadata
|
||||
.layer_width
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |layer_width| *layer_width)
|
||||
.with_loaded_or(|| Some(self.compute_layer_width(node_id, network_path)), |widths| *widths)
|
||||
}
|
||||
|
||||
/// Unloads layer width if the node is a layer.
|
||||
@@ -475,7 +395,7 @@ impl NodeNetworkInterface {
|
||||
let vertical_start: bool = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, graph_wire_style);
|
||||
|
||||
let path_string = vector_wire.to_svg();
|
||||
let center_path_string = center_line.to_svg();
|
||||
@@ -523,7 +443,7 @@ impl NodeNetworkInterface {
|
||||
let vertical_start = upstream_output.node_id().is_some_and(|node_id| self.is_layer(&node_id, network_path));
|
||||
let thick = vertical_end && vertical_start;
|
||||
let vector_wire = build_vector_wire(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end);
|
||||
let center_line = build_thick_wire_center_line(output_position, input_position, vertical_start, vertical_end, wire_style);
|
||||
Some((vector_wire, center_line, thick))
|
||||
}
|
||||
|
||||
@@ -549,17 +469,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
/// The node's body, ports, and handles, built where it is drawn now.
|
||||
pub fn node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
self.compute_node_click_targets(node_id, network_path)
|
||||
}
|
||||
|
||||
pub(crate) fn with_node_click_targets<R>(&self, node_id: &NodeId, network_path: &[NodeId], read: impl FnOnce(&DocumentNodeClickTargets) -> R) -> Option<R> {
|
||||
self.compute_node_click_targets(node_id, network_path).as_ref().map(read)
|
||||
}
|
||||
|
||||
/// The box around the node's body where it sits in its grid cell, in node graph space.
|
||||
pub fn node_bounding_box(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<[DVec2; 2]> {
|
||||
self.with_node_click_targets(node_id, network_path, |click_targets| click_targets.node_click_target.bounding_box())
|
||||
.flatten()
|
||||
let body = self.with_layout(network_path, |layout| layout.body(node_id)).flatten()?;
|
||||
Some([body.min, body.max])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+71
-2
@@ -2,7 +2,7 @@ use super::{
|
||||
ChainInsertionPoint, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeLocator, NodeNetworkInterface, NodeNetworkTemplate, NodePersistentMetadata, NodePosition,
|
||||
NodeTemplate, NodeTemplateImplementation, NodeTypePersistentMetadata, OutputConnector, Previewing, RootNode, TransactionStatus,
|
||||
};
|
||||
use crate::consts::{GRID_SIZE, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::consts::{GRID_SIZE, LAYER_INDENT_OFFSET, STACK_VERTICAL_GAP, WIRE_DRAG_NODE_EXPAND_DELAY_MILLISECONDS};
|
||||
use crate::messages::input_mapper::utility_types::pointer::EditorPointerState;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::resolve_proto_node_type;
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, Direction};
|
||||
@@ -330,7 +330,6 @@ async fn a_relative_node_follows_its_readers_until_it_loses_the_last_one() {
|
||||
}
|
||||
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_positions(&[]);
|
||||
|
||||
assert_eq!(network_interface.position(&node, &[]), Some(IVec2::new(13, 7)));
|
||||
|
||||
@@ -4228,3 +4227,73 @@ async fn grouping_a_group_moves_the_layer_below_it_past_all_of_its_contents() {
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
assert_invariants(&editor, "after grouping a group");
|
||||
}
|
||||
|
||||
fn indent_below_parent(editor: &EditorTestUtils, layer: LayerNodeIdentifier) -> Option<i32> {
|
||||
let interface = &editor.active_document().network_interface;
|
||||
let parent = layer.parent(interface.document_metadata())?;
|
||||
Some(interface.position(&parent.to_node(), &[])?.x - interface.position(&layer.to_node(), &[])?.x)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reordering_the_layers_of_a_group_keeps_them_indented_below_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let top_two = artboard.children(editor.active_document().metadata()).take(2).map(LayerNodeIdentifier::to_node).collect();
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: top_two }).await;
|
||||
group_selected_layers(&mut editor).await;
|
||||
|
||||
let group = artboard
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the group should be the top layer of the artboard");
|
||||
for insert_index in [0, 2] {
|
||||
let moved = group.children(editor.active_document().metadata()).nth(1 - insert_index / 2).expect("the group should hold two layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![moved.to_node()] }).await;
|
||||
editor.handle_message(DocumentMessage::MoveSelectedLayersTo { parent: group, insert_index }).await;
|
||||
|
||||
for layer in group.children(editor.active_document().metadata()).chain([group]) {
|
||||
assert_eq!(indent_below_parent(&editor, layer), Some(LAYER_INDENT_OFFSET), "moving a layer to index {insert_index} of the group");
|
||||
}
|
||||
}
|
||||
assert_eq!(overlapping_layers(&editor), Vec::new());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn releasing_a_drag_of_a_layer_in_a_stack_leaves_every_layer_where_the_drag_drew_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.handle_message(new_artboard_message(NodeId::new())).await;
|
||||
for x in [0., 50., 100., 150.] {
|
||||
editor.draw_rect(x, 0., x + 40., 40.).await;
|
||||
}
|
||||
let artboard = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the artboard should be a layer");
|
||||
let third = artboard.children(editor.active_document().metadata()).nth(2).expect("the artboard should hold four layers");
|
||||
editor.handle_message(NodeGraphMessage::SelectedNodesSet { nodes: vec![third.to_node()] }).await;
|
||||
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
let layers: Vec<NodeId> = interface.document_network().nodes.keys().copied().filter(|node_id| interface.is_layer(node_id, &[])).collect();
|
||||
for keep_upstream in [false, true] {
|
||||
for offset in [IVec2::new(0, 3), IVec2::new(0, -2), IVec2::new(5, 0)] {
|
||||
let before = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.drag_selected_nodes(offset, keep_upstream, &[]);
|
||||
let dragging = interface.positions(layers.iter().copied(), &[]);
|
||||
interface.finish_drag(&[]);
|
||||
|
||||
assert_ne!(dragging, before, "dragging by {offset} keeping upstream: {keep_upstream} should move the layers");
|
||||
|
||||
assert_eq!(interface.positions(layers.iter().copied(), &[]), dragging, "dragging by {offset} keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -62,11 +62,21 @@ pub enum NodeMetadataChange {
|
||||
/// node do not have the same kinds of position. Encodes to `ui::position` and `ui::is_layer`, which
|
||||
/// merge independently, so a concurrent move and a concurrent layer toggle both survive.
|
||||
NodeType(NodeTypePersistentMetadata),
|
||||
/// Where a node that stays a layer or stays a node sits. Encodes to `ui::position` alone.
|
||||
Position(NodeTypePersistentMetadata),
|
||||
DisplayName(String),
|
||||
Locked(bool),
|
||||
Pinned(bool),
|
||||
}
|
||||
|
||||
impl NodeMetadataChange {
|
||||
/// The change from `before` to `after`, writing whether the node is a layer only when that changes.
|
||||
pub fn placement(before: &NodeTypePersistentMetadata, after: NodeTypePersistentMetadata) -> Self {
|
||||
let is_layer = |node_type: &NodeTypePersistentMetadata| matches!(node_type, NodeTypePersistentMetadata::Layer(_));
|
||||
if is_layer(before) == is_layer(&after) { Self::Position(after) } else { Self::NodeType(after) }
|
||||
}
|
||||
}
|
||||
|
||||
/// One field of a network's persistent metadata. The navigation transform and width are absent
|
||||
/// deliberately: they are per-peer view state, persisted to `session.json` rather than the registry.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
@@ -319,6 +329,10 @@ fn node_metadata_ops(global_id: document_graph_storage::NodeId, change: &NodeMet
|
||||
node_attribute(node_attr::ui::IS_LAYER, flag(matches!(node_type, NodeTypePersistentMetadata::Layer(_)))),
|
||||
]
|
||||
}
|
||||
NodeMetadataChange::Position(node_type) => vec![node_attribute(
|
||||
node_attr::ui::POSITION,
|
||||
Some(serialize_attribute(node_attr::ui::POSITION, &position_from_runtime(node_type))?),
|
||||
)],
|
||||
NodeMetadataChange::DisplayName(display_name) => vec![node_attribute(node_attr::ui::DISPLAY_NAME, non_empty(display_name))],
|
||||
NodeMetadataChange::Locked(locked) => vec![node_attribute(node_attr::ui::LOCKED, flag(*locked))],
|
||||
NodeMetadataChange::Pinned(pinned) => vec![node_attribute(node_attr::ui::PINNED, flag(*pinned))],
|
||||
|
||||
+28
-1
@@ -3,6 +3,7 @@ use super::editor_delta::{EditorDelta, NetworkMetadataChange, NodeMetadataChange
|
||||
use super::storage_metadata::StorageMetadataView;
|
||||
use super::{InputConnector, NodeTemplate};
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use document_graph_storage::attr::node as node_attr;
|
||||
use document_graph_storage::delta::compute_deltas;
|
||||
use document_graph_storage::{PeerId, Registry, RegistryDelta, Session};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
@@ -184,7 +185,7 @@ async fn per_field_metadata_edits_match_the_diff() {
|
||||
metadata_change(node, NodeMetadataChange::DisplayName(metadata.display_name.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Locked(metadata.locked)),
|
||||
metadata_change(node, NodeMetadataChange::Pinned(metadata.pinned)),
|
||||
metadata_change(node, NodeMetadataChange::NodeType(metadata.node_type_metadata.clone())),
|
||||
metadata_change(node, NodeMetadataChange::Position(metadata.node_type_metadata.clone())),
|
||||
EditorDelta::Graph(RuntimeDelta::SetVisibility {
|
||||
network: None,
|
||||
node_id: node,
|
||||
@@ -283,6 +284,32 @@ async fn unchanged_writes_emit_nothing() {
|
||||
assert!(emitted.is_empty(), "re-writing the same values should emit nothing, got {emitted:#?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn moving_a_layer_writes_only_its_position() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
editor.draw_rect(0., 0., 40., 40.).await;
|
||||
let layer = LayerNodeIdentifier::ROOT_PARENT
|
||||
.children(editor.active_document().metadata())
|
||||
.next()
|
||||
.expect("the rectangle should be a layer")
|
||||
.to_node();
|
||||
|
||||
let working = convert(&editor);
|
||||
editor.active_document_mut().network_interface.discard_deltas();
|
||||
editor.active_document_mut().network_interface.shift_node(&layer, glam::IVec2::new(3, 5), &[]);
|
||||
|
||||
let emitted = committed_deltas(&mut editor);
|
||||
let written: Vec<String> = construct(&editor, &emitted, &working)
|
||||
.into_iter()
|
||||
.filter_map(|op| match op {
|
||||
RegistryDelta::ChangeNodeAttribute { delta, .. } => Some(delta.key),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(written, [node_attr::ui::POSITION]);
|
||||
}
|
||||
|
||||
/// Structural writes go through the store too, so inserting and deleting a node must be recorded
|
||||
/// without the caller saying anything about it.
|
||||
#[tokio::test]
|
||||
|
||||
+3
-190
@@ -46,193 +46,6 @@ impl NodeNetworkInterface {
|
||||
(!hidden && output_index < self.number_of_outputs(node_id, network_path)).then_some(top_left + DVec2::new(5. * grid, grid * (output_index as f64 + 1.)))
|
||||
}
|
||||
|
||||
pub(crate) fn compute_node_ports(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Ports> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_ports for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let document_node = self.document_node(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
let mut ports = Ports::new();
|
||||
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
ports.insert_dot_ports(node_top_left + DVec2::new(0., GRID_SIZE as f64));
|
||||
} else if !self.is_layer(node_id, network_path) {
|
||||
let mut input_row_count = 0;
|
||||
for (input_index, input) in document_node.inputs.iter().enumerate() {
|
||||
if input.is_exposed() {
|
||||
ports.insert_node_input(input_index, input_row_count, node_top_left);
|
||||
}
|
||||
if input_index == 0 || input.is_exposed() {
|
||||
input_row_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
let start_index = if self.hidden_primary_output(node_id, network_path) { 1 } else { 0 };
|
||||
for output_index in start_index..self.number_of_outputs(node_id, network_path) {
|
||||
ports.insert_node_output(output_index, node_top_left);
|
||||
}
|
||||
} else {
|
||||
ports.insert_layer_input(0, node_top_left);
|
||||
if document_node.inputs.iter().filter(|input| input.is_exposed()).count() > 1 {
|
||||
ports.insert_layer_input(1, node_top_left);
|
||||
}
|
||||
ports.insert_layer_output(node_top_left);
|
||||
}
|
||||
|
||||
Some(ports)
|
||||
}
|
||||
|
||||
/// The node body, its ports, and for a layer its visibility, lock, grip and name handles, all in node graph space.
|
||||
pub(super) fn compute_node_click_targets(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<DocumentNodeClickTargets> {
|
||||
let Some(node_position) = self.position(node_id, network_path) else {
|
||||
log::error!("Could not get node position in compute_node_click_targets for node {node_id}");
|
||||
return None;
|
||||
};
|
||||
let node_metadata = self.node_metadata(node_id, network_path)?;
|
||||
let port_click_targets = self.compute_node_ports(node_id, network_path)?;
|
||||
let node_top_left = node_position.as_dvec2() * GRID_SIZE as f64;
|
||||
|
||||
// A redirect dot is centered on the grid point at the connector height of an ordinary node's first row.
|
||||
// Its body also covers the gutters beside it holding its ports, so every press near it moves the dot unless it lands on an available port.
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
const DOT_HALF_WIDTH: f64 = 15.;
|
||||
const DOT_HALF_HEIGHT: f64 = 8.;
|
||||
|
||||
let center = node_top_left + DVec2::new(0., GRID_SIZE as f64);
|
||||
let path = rounded_rectangle_path(
|
||||
center - DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
center + DVec2::new(DOT_HALF_WIDTH, DOT_HALF_HEIGHT),
|
||||
[DOT_HALF_HEIGHT; 4],
|
||||
);
|
||||
|
||||
return Some(DocumentNodeClickTargets {
|
||||
node_click_target: ClickTarget::new_with_path(path, 0.),
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
});
|
||||
}
|
||||
|
||||
let document_node_click_targets = if !node_metadata.persistent_metadata.is_layer() {
|
||||
let height = self.displayed_row_count(node_id, network_path) as u32 * GRID_SIZE;
|
||||
let width = 5 * GRID_SIZE;
|
||||
// Offset down by half a grid so the click target sits below the top connector strip.
|
||||
let node_click_target_top_left = node_top_left + DVec2::new(0., HALF_GRID_SIZE as f64);
|
||||
let node_click_target_bottom_right = node_click_target_top_left + DVec2::new(width as f64, height as f64);
|
||||
|
||||
let radius = 3.;
|
||||
let path = rounded_rectangle_path(node_click_target_top_left, node_click_target_bottom_right, [radius; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Node,
|
||||
}
|
||||
} else {
|
||||
let layer_width_cells = self.layer_width(node_id, network_path).unwrap_or_else(|| {
|
||||
log::error!("Could not get layer width in compute_node_click_targets");
|
||||
0
|
||||
});
|
||||
let width = layer_width_cells * GRID_SIZE;
|
||||
let height = LAYER_GRID_HEIGHT * GRID_SIZE;
|
||||
let locked = self.is_locked(node_id, network_path);
|
||||
|
||||
// The layer is `2 * GRID_SIZE` tall, so its vertical center sits one grid unit below `node_top_left.y`.
|
||||
// Visibility/lock buttons fill a 1-grid-cell square (so half-extents of HALF_GRID_SIZE each side of center).
|
||||
const LAYER_VERTICAL_CENTER: f64 = GRID_SIZE as f64;
|
||||
const ICON_HALF_EXTENT: f64 = HALF_GRID_SIZE as f64;
|
||||
|
||||
let visibility_offset = node_top_left + DVec2::new(width as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + visibility_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + visibility_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
let visibility_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// Update lock button click target, positioned one grid unit to the left of the visibility button (only when locked)
|
||||
let lock_click_target = if locked {
|
||||
let lock_offset = node_top_left + DVec2::new(width as f64 - GRID_SIZE as f64, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-ICON_HALF_EXTENT, -ICON_HALF_EXTENT) + lock_offset,
|
||||
DVec2::new(ICON_HALF_EXTENT, ICON_HALF_EXTENT) + lock_offset,
|
||||
[3.; 4],
|
||||
);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// The grip sits to the left of the leftmost icon, 8px wide but spanning the full layer-vertical-center band
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
let icons_width = if locked { GRID_SIZE as f64 } else { 0. };
|
||||
let grip_offset_right_edge = node_top_left + DVec2::new(width as f64 - ICON_HALF_EXTENT - icons_width, LAYER_VERTICAL_CENTER);
|
||||
let path = rounded_rectangle_path(
|
||||
DVec2::new(-GRIP_WIDTH, -ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
DVec2::new(0., ICON_HALF_EXTENT) + grip_offset_right_edge,
|
||||
[0.; 4],
|
||||
);
|
||||
let grip_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
// The double-click rename target is sized to the text bounds, not the surrounding `.details` area,
|
||||
// so the rest of the layer still drills into the subgraph on double-click
|
||||
|
||||
/// `.layer` margin-left (= 12), for chain layers the negative margin-left and positive padding-left cancel out, keeping content at this same offset
|
||||
const LAYER_LEFT_MARGIN: f64 = HALF_GRID_SIZE as f64;
|
||||
/// `.thumbnail` (70px) + its 1px side margins (= 72)
|
||||
const THUMBNAIL_BLOCK_WIDTH: f64 = 3. * GRID_SIZE as f64;
|
||||
/// `.details` margin-left
|
||||
const DETAILS_LEFT_MARGIN: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = LAYER_LEFT_MARGIN + THUMBNAIL_BLOCK_WIDTH + DETAILS_LEFT_MARGIN;
|
||||
/// Distance from layer's right edge to visibility's left edge (= 12)
|
||||
const VISIBILITY_INSET_FROM_LAYER_RIGHT: f64 = HALF_GRID_SIZE as f64;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
|
||||
let display_name = self.display_name(node_id, network_path);
|
||||
let name_click_target = if display_name.is_empty() {
|
||||
None
|
||||
} else {
|
||||
let name_left = node_top_left.x + NAME_LEFT_OFFSET;
|
||||
let icons_reserve = VISIBILITY_INSET_FROM_LAYER_RIGHT + icons_width + GRIP_WIDTH;
|
||||
let name_right_max = node_top_left.x + width as f64 - icons_reserve;
|
||||
let name_width = text_width(&display_name, FONT_SIZE);
|
||||
let name_right = (name_left + name_width).min(name_right_max);
|
||||
if name_right > name_left {
|
||||
// The 1-grid-tall name strip is centered vertically in the 2-grid-tall layer.
|
||||
let name_top = node_top_left.y + HALF_GRID_SIZE as f64;
|
||||
let name_bottom = node_top_left.y + GRID_SIZE as f64 + HALF_GRID_SIZE as f64;
|
||||
let path = rounded_rectangle_path(DVec2::new(name_left, name_top), DVec2::new(name_right, name_bottom), [3.; 4]);
|
||||
Some(ClickTarget::new_with_path(path, 0.))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// The layer click target spans the layer and its chain background
|
||||
let chain_width_grid_spaces = self.chain_width(node_id, network_path);
|
||||
|
||||
let node_bottom_right = node_top_left + DVec2::new(width as f64, height as f64);
|
||||
let chain_top_left = node_top_left - DVec2::new((chain_width_grid_spaces * GRID_SIZE) as f64, 0.);
|
||||
const CORNER_RADIUS: f64 = 10.;
|
||||
let path = rounded_rectangle_path(chain_top_left, node_bottom_right, [CORNER_RADIUS; 4]);
|
||||
let node_click_target = ClickTarget::new_with_path(path, 0.);
|
||||
|
||||
DocumentNodeClickTargets {
|
||||
node_click_target,
|
||||
port_click_targets,
|
||||
node_type_metadata: NodeTypeClickTargets::Layer(Box::new(LayerClickTargets {
|
||||
visibility_click_target,
|
||||
lock_click_target,
|
||||
grip_click_target,
|
||||
name_click_target,
|
||||
})),
|
||||
}
|
||||
};
|
||||
|
||||
Some(document_node_click_targets)
|
||||
}
|
||||
|
||||
/// The areas covered by the names beside each import and export port, which can be dragged to reorder them or right-clicked for a menu.
|
||||
/// Laid out as the frontend draws them, just past the connector.
|
||||
pub fn import_export_name_bounds(&self, network_path: &[NodeId]) -> Vec<(ImportOrExport, [DVec2; 2])> {
|
||||
@@ -339,9 +152,9 @@ impl NodeNetworkInterface {
|
||||
Some((1..row_count).find(|&row| first_row_center + import_export_row_offset(row) > y).unwrap_or(row_count))
|
||||
}
|
||||
|
||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons. Cached
|
||||
/// The width of a layer in grid units, which covers its thumbnail, its name and its icons, and the width of its name. Cached
|
||||
/// because measuring the name's text is slow.
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> u32 {
|
||||
pub(super) fn compute_layer_width(&self, node_id: &NodeId, network_path: &[NodeId]) -> (u32, f64) {
|
||||
const GAP_WIDTH: f64 = 8.;
|
||||
const FONT_SIZE: f64 = 14.;
|
||||
let left_thumbnail_padding = GRID_SIZE as f64 / 2.;
|
||||
@@ -356,7 +169,7 @@ impl NodeNetworkInterface {
|
||||
let icon_overhang_width = GRID_SIZE as f64 / 2.;
|
||||
|
||||
let layer_width_pixels = left_thumbnail_padding + thumbnail_width + GAP_WIDTH + text_width + grip_padding + grip_width + lock_icon_width + icon_overhang_width;
|
||||
((layer_width_pixels / 24.).ceil() as u32).max(8)
|
||||
(((layer_width_pixels / 24.).ceil() as u32).max(8), text_width)
|
||||
}
|
||||
pub fn import_export_position(&self, network_path: &[NodeId]) -> Option<(IVec2, IVec2)> {
|
||||
let Some(all_nodes_bounding_box) = self.all_nodes_bounding_box(network_path) else {
|
||||
|
||||
+59
-116
@@ -24,81 +24,6 @@ impl NodeNetworkInterface {
|
||||
all_selected_nodes
|
||||
}
|
||||
|
||||
pub fn collect_frontend_click_targets(&self, network_path: &[NodeId]) -> FrontendClickTargets {
|
||||
let mut all_node_click_targets = Vec::new();
|
||||
let mut connector_click_targets = Vec::new();
|
||||
let mut icon_click_targets = Vec::new();
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
log::error!("Could not get nested network_metadata in collect_frontend_click_targets");
|
||||
return FrontendClickTargets::default();
|
||||
};
|
||||
let nodes = network_metadata.persistent_metadata.node_metadata.keys().copied().collect::<Vec<_>>();
|
||||
self.with_import_export_ports(network_path, |import_export_click_targets| {
|
||||
for port in import_export_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
nodes.into_iter().for_each(|node_id| {
|
||||
self.with_node_click_targets(&node_id, network_path, |node_click_targets| {
|
||||
let mut node_path = String::new();
|
||||
|
||||
if let ClickTargetType::Path(path) = node_click_targets.node_click_target.target_type() {
|
||||
node_path.push_str(path.to_svg().as_str())
|
||||
}
|
||||
all_node_click_targets.push((node_id, node_path));
|
||||
for port in node_click_targets.port_click_targets.click_targets() {
|
||||
if let ClickTargetType::Path(path) = port.target_type() {
|
||||
connector_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
if let NodeTypeClickTargets::Layer(layer_metadata) = &node_click_targets.node_type_metadata {
|
||||
// Visibility button (eye icon)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.visibility_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Lock button (padlock icon), only when the layer is locked
|
||||
if let Some(lock_click_target) = &layer_metadata.lock_click_target
|
||||
&& let ClickTargetType::Path(path) = lock_click_target.target_type()
|
||||
{
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
// Drag grip (dotted symbol)
|
||||
if let ClickTargetType::Path(path) = layer_metadata.grip_click_target.target_type() {
|
||||
icon_click_targets.push(path.to_svg());
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut layer_click_targets = Vec::new();
|
||||
let mut node_click_targets = Vec::new();
|
||||
all_node_click_targets.into_iter().for_each(|(node_id, path)| {
|
||||
if self.is_layer(&node_id, network_path) {
|
||||
layer_click_targets.push(path);
|
||||
} else {
|
||||
node_click_targets.push(path);
|
||||
}
|
||||
});
|
||||
|
||||
let bounds = self.all_nodes_bounding_box(network_path).unwrap_or([DVec2::ZERO, DVec2::ZERO]);
|
||||
let all_nodes_bounding_box = rectangle_path(bounds[0], bounds[1]).to_svg();
|
||||
|
||||
let import_export_names = self
|
||||
.import_export_name_bounds(network_path)
|
||||
.into_iter()
|
||||
.map(|(_, [name_min, name_max])| rectangle_path(name_min, name_max).to_svg())
|
||||
.collect();
|
||||
FrontendClickTargets {
|
||||
node_click_targets,
|
||||
layer_click_targets,
|
||||
connector_click_targets,
|
||||
icon_click_targets,
|
||||
all_nodes_bounding_box,
|
||||
import_export_names,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_document_to_viewport_transform(&mut self, transform: DAffine2) {
|
||||
self.document_metadata.document_to_viewport = transform;
|
||||
}
|
||||
@@ -123,6 +48,24 @@ impl NodeNetworkInterface {
|
||||
Some(&mut navigation.node_graph_ptz)
|
||||
}
|
||||
|
||||
/// The first of the node's parts, its body last, that `find` picks something from. Each part is given in node graph space where the node sits in its
|
||||
/// grid cell, and an input by its index rather than the row a node draws it in.
|
||||
pub(crate) fn find_node_part<R>(&self, node_id: &NodeId, network_path: &[NodeId], mut find: impl FnMut(Part, &PartTarget) -> Option<R>) -> Option<R> {
|
||||
let rows_are_inputs = self.is_layer(node_id, network_path) || self.is_redirect_dot(node_id, network_path);
|
||||
let inputs = &self.document_node(node_id, network_path)?.inputs;
|
||||
|
||||
self.with_layout(network_path, |layout| {
|
||||
layout.find_part(node_id, |target| {
|
||||
let part = match target.part {
|
||||
Part::Input(row) if !rows_are_inputs => Part::Input(input_in_row(inputs, row as usize)? as u32),
|
||||
part => part,
|
||||
};
|
||||
find(part, target)
|
||||
})
|
||||
})
|
||||
.flatten()
|
||||
}
|
||||
|
||||
/// The node drawn topmost at `click`, in viewport space. Only the nodes whose reach covers it build their exact click targets.
|
||||
pub fn node_from_click(&self, click: DVec2, network_path: &[NodeId]) -> Option<NodeId> {
|
||||
let Some(network_metadata) = self.network_metadata(network_path) else {
|
||||
@@ -133,16 +76,13 @@ impl NodeNetworkInterface {
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
// Each node is pressed where it's drawn, even while gliding into its grid cell
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
let clicked_nodes = self
|
||||
.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata.node_click_target.intersect_point_no_stroke(point - glide_offsets.node(node_id))
|
||||
}) == Some(true)
|
||||
})
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
let reaching = self.nodes_reaching(point, network_path);
|
||||
let clicked_nodes = self.with_layout(network_path, |layout| {
|
||||
reaching
|
||||
.into_iter()
|
||||
.filter(|node_id| layout.body(node_id).is_some_and(|body| body.contains(point - glide_offsets.node(node_id))))
|
||||
.collect::<Vec<_>>()
|
||||
})?;
|
||||
// Redirect dots are drawn above nodes, which are drawn above layer chains, so the topmost clicked one is found in that order
|
||||
let drawing_layer = |node_id: &NodeId| {
|
||||
if self.is_redirect_dot(node_id, network_path) {
|
||||
@@ -165,25 +105,18 @@ impl NodeNetworkInterface {
|
||||
let point = network_metadata.persistent_metadata.navigation_metadata.node_graph_to_viewport.inverse().transform_point2(click);
|
||||
let glide_offsets = self.glide_offsets(network_path);
|
||||
|
||||
self.nodes_reaching(point, network_path)
|
||||
.iter()
|
||||
.filter_map(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
if let NodeTypeClickTargets::Layer(layer) = &transient_node_metadata.node_type_metadata {
|
||||
match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => layer.visibility_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Lock => layer.lock_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
LayerClickTargetTypes::Grip => layer.grip_click_target.intersect_point_no_stroke(point).then_some(*node_id),
|
||||
LayerClickTargetTypes::Name => layer.name_click_target.as_ref().and_then(|target| target.intersect_point_no_stroke(point).then_some(*node_id)),
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
let wanted = match click_target_type {
|
||||
LayerClickTargetTypes::Visibility => Part::Visibility,
|
||||
LayerClickTargetTypes::Lock => Part::Lock,
|
||||
LayerClickTargetTypes::Grip => Part::Grip,
|
||||
LayerClickTargetTypes::Name => Part::Name,
|
||||
};
|
||||
|
||||
self.nodes_reaching(point, network_path).into_iter().find(|node_id| {
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| (part == wanted && target.contains(point)).then_some(()))
|
||||
.is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// The dimmed connector for adding an import (or else export) under `point`, given in node graph space, as the index it adds with its center.
|
||||
@@ -269,13 +202,11 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_input_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|port| InputConnector::node_at_index(*node_id, port))
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Input(index) if target.contains(point) => Some(InputConnector::node_at_index(*node_id, index as usize)),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.find(|input_connector| !self.is_wired_dot_input(input_connector, network_path))
|
||||
.or_else(|| {
|
||||
@@ -302,13 +233,11 @@ impl NodeNetworkInterface {
|
||||
.iter()
|
||||
.filter(|node_id| covering_dot.is_none_or(|dot| dot == **node_id))
|
||||
.filter_map(|node_id| {
|
||||
self.with_node_click_targets(node_id, network_path, |transient_node_metadata| {
|
||||
transient_node_metadata
|
||||
.port_click_targets
|
||||
.clicked_output_port_from_point(point - glide_offsets.node(node_id))
|
||||
.map(|output_index| OutputConnector::node(*node_id, output_index))
|
||||
let point = point - glide_offsets.node(node_id);
|
||||
self.find_node_part(node_id, network_path, |part, target| match part {
|
||||
Part::Output(index) if target.contains(point) => Some(OutputConnector::node(*node_id, index as usize)),
|
||||
_ => None,
|
||||
})
|
||||
.flatten()
|
||||
})
|
||||
.next()
|
||||
.or_else(|| {
|
||||
@@ -426,3 +355,17 @@ impl NodeNetworkInterface {
|
||||
(layer_widths, chain_widths, has_left_input_wire)
|
||||
}
|
||||
}
|
||||
|
||||
/// The input drawn in `row` of a node, where the primary input's row is drawn even while it has no port.
|
||||
fn input_in_row(inputs: &[NodeInput], row: usize) -> Option<usize> {
|
||||
let mut current_row = 0;
|
||||
for (index, input) in inputs.iter().enumerate() {
|
||||
if input.is_exposed() && current_row == row {
|
||||
return Some(index);
|
||||
}
|
||||
if index == 0 || input.is_exposed() {
|
||||
current_row += 1;
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
@@ -6,10 +6,6 @@
|
||||
use super::*;
|
||||
|
||||
impl NodeNetworkInterface {
|
||||
pub(crate) fn invalidate_positions(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
|
||||
/// Unloads the network's import and export ports.
|
||||
pub(crate) fn invalidate_import_export(&mut self, network_path: &[NodeId]) {
|
||||
self.unload_import_export_ports(network_path);
|
||||
@@ -17,6 +13,5 @@ impl NodeNetworkInterface {
|
||||
|
||||
pub(crate) fn invalidate_node_appearance(&mut self, node_id: &NodeId, network_path: &[NodeId]) {
|
||||
self.try_unload_layer_width(node_id, network_path);
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Converts every node another node reads in all networks, whether absolute, chained, or stacked, to a position relative to the left of its readers, level with the highest.
|
||||
@@ -145,7 +144,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a layer to a stack position
|
||||
@@ -159,8 +157,6 @@ impl NodeNetworkInterface {
|
||||
} else if node.set_stack_position(y_offset) {
|
||||
self.transaction_modified();
|
||||
}
|
||||
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Sets the position of a node to a stack position without changing its y offset
|
||||
@@ -371,7 +367,6 @@ impl NodeNetworkInterface {
|
||||
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_positions(network_path);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+158
-36
@@ -1,7 +1,9 @@
|
||||
use super::node_parts::{NodeShape, PartTarget, PlacedNode};
|
||||
use super::*;
|
||||
use glam::UVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Node, NodeIndex, NodeKind, Placement, Wire};
|
||||
use std::cell::RefCell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const REACH_MARGIN: f64 = 16.;
|
||||
|
||||
@@ -9,13 +11,53 @@ const REACH_MARGIN: f64 = 16.;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct NetworkLayout {
|
||||
revision: u64,
|
||||
generation: u64,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
graph: Graph,
|
||||
shapes: Vec<NodeShape>,
|
||||
layout: Layout,
|
||||
bounds: [DVec2; 2],
|
||||
clearance: ImportExportClearance,
|
||||
}
|
||||
|
||||
/// Counts every layout made, so whatever is derived from one can tell when it was replaced, even without a new revision.
|
||||
static LAYOUT_GENERATIONS: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
impl NetworkLayout {
|
||||
fn new(revision: u64, laid_out: LaidOutNodes, graph: Graph, layout: Layout) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
let mut network_layout = Self {
|
||||
revision,
|
||||
generation: LAYOUT_GENERATIONS.fetch_add(1, Ordering::Relaxed),
|
||||
node_ids,
|
||||
indices,
|
||||
graph,
|
||||
shapes,
|
||||
layout,
|
||||
bounds: [DVec2::ZERO; 2],
|
||||
clearance: ImportExportClearance::default(),
|
||||
};
|
||||
network_layout.measure_bounds_and_clearance();
|
||||
network_layout
|
||||
}
|
||||
|
||||
fn into_parts(self) -> (LaidOutNodes, Graph, Layout) {
|
||||
let Self {
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
graph,
|
||||
layout,
|
||||
..
|
||||
} = self;
|
||||
(LaidOutNodes { node_ids, indices, shapes }, graph, layout)
|
||||
}
|
||||
|
||||
pub fn generation(&self) -> u64 {
|
||||
self.generation
|
||||
}
|
||||
|
||||
pub fn position(&self, node_id: &NodeId) -> Option<IVec2> {
|
||||
Some(self.node(node_id)?.position)
|
||||
}
|
||||
@@ -53,6 +95,33 @@ impl NetworkLayout {
|
||||
self.node(layer).map_or(0, |node| node.chain_length)
|
||||
}
|
||||
|
||||
/// The combined bounds of every node's body in node graph space, or a point at the origin for an empty network.
|
||||
pub fn bounds(&self) -> [DVec2; 2] {
|
||||
self.bounds
|
||||
}
|
||||
|
||||
/// What the imports and exports keep their distance from horizontally.
|
||||
pub(crate) fn clearance(&self) -> ImportExportClearance {
|
||||
self.clearance
|
||||
}
|
||||
|
||||
/// The node's body where it sits in its grid cell, in node graph space.
|
||||
pub fn body(&self, node_id: &NodeId) -> Option<PartTarget> {
|
||||
Some(self.placed(*self.indices.get(node_id)?).body())
|
||||
}
|
||||
|
||||
/// The first of the node's parts, its body last, that `find` picks something from.
|
||||
pub fn find_part<R>(&self, node_id: &NodeId, mut find: impl FnMut(&PartTarget) -> Option<R>) -> Option<R> {
|
||||
let placed = self.placed(*self.indices.get(node_id)?);
|
||||
let mut found = None;
|
||||
placed.parts(|target| {
|
||||
if found.is_none() {
|
||||
found = find(&target);
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
|
||||
/// Whether `point`, in node graph space, lies within the box around everything the node draws.
|
||||
pub fn reaches(&self, node_id: &NodeId, point: DVec2) -> bool {
|
||||
let Some(index) = self.indices.get(node_id) else { return false };
|
||||
@@ -62,6 +131,38 @@ impl NetworkLayout {
|
||||
point.cmpge(min).all() && point.cmplt(max).all()
|
||||
}
|
||||
|
||||
fn placed(&self, index: NodeIndex) -> PlacedNode<'_> {
|
||||
let node_layout = self.layout.node(index);
|
||||
PlacedNode {
|
||||
node: &self.graph[index],
|
||||
shape: &self.shapes[index.index()],
|
||||
position: node_layout.position,
|
||||
chain_length: node_layout.chain_length,
|
||||
}
|
||||
}
|
||||
|
||||
/// Measures the combined bounds of the node bodies, and the horizontal extents the imports and exports keep clear of, with redirect dots measured by their centers.
|
||||
fn measure_bounds_and_clearance(&mut self) {
|
||||
let widen = |span: Option<[f64; 2]>, left: f64, right: f64| Some(span.map_or([left, right], |[min, max]| [min.min(left), max.max(right)]));
|
||||
|
||||
let mut bounds: Option<[DVec2; 2]> = None;
|
||||
let mut clearance = ImportExportClearance::default();
|
||||
for index in (0..self.graph.nodes.len()).map(|index| NodeIndex::from(index as u32)) {
|
||||
let body = self.placed(index).body();
|
||||
bounds = Some(bounds.map_or([body.min, body.max], |[min, max]| [min.min(body.min), max.max(body.max)]));
|
||||
|
||||
if self.graph[index].kind == NodeKind::Waypoint {
|
||||
let center = (body.min.x + body.max.x) / 2.;
|
||||
clearance.dot_centers = widen(clearance.dot_centers, center, center);
|
||||
} else {
|
||||
clearance.node_sides = widen(clearance.node_sides, body.min.x, body.max.x);
|
||||
}
|
||||
}
|
||||
|
||||
self.bounds = bounds.unwrap_or_default();
|
||||
self.clearance = clearance;
|
||||
}
|
||||
|
||||
fn node(&self, node_id: &NodeId) -> Option<graph_layout::NodeLayout> {
|
||||
Some(self.layout.node(*self.indices.get(node_id)?))
|
||||
}
|
||||
@@ -86,12 +187,14 @@ struct DragOrigin {
|
||||
keep_upstream: bool,
|
||||
node_ids: Vec<NodeId>,
|
||||
indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
start: Graph,
|
||||
drag: Drag,
|
||||
}
|
||||
|
||||
impl DragOrigin {
|
||||
fn new(node_ids: Vec<NodeId>, indices: HashMap<NodeId, NodeIndex>, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
fn new(laid_out: LaidOutNodes, start: Graph, start_layout: Layout, dragged: &[NodeId], keep_upstream: bool, revision: u64) -> Self {
|
||||
let LaidOutNodes { node_ids, indices, shapes } = laid_out;
|
||||
let dragged = dragged.iter().filter_map(|node_id| indices.get(node_id).copied()).collect();
|
||||
Self {
|
||||
revision,
|
||||
@@ -99,6 +202,7 @@ impl DragOrigin {
|
||||
drag: Drag::new(start.clone(), start_layout, dragged, keep_upstream),
|
||||
node_ids,
|
||||
indices,
|
||||
shapes,
|
||||
start,
|
||||
}
|
||||
}
|
||||
@@ -154,7 +258,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
|
||||
/// Moves the selected nodes `offset` grid cells from where they are drawn, the same way as a drag.
|
||||
@@ -178,9 +281,14 @@ impl NodeNetworkInterface {
|
||||
.filter(|((before, after), _)| before.placement != after.placement)
|
||||
.map(|((_, after), node_id)| (*node_id, after.placement))
|
||||
.collect();
|
||||
(moved_placements, std::mem::take(&mut origin.node_ids), std::mem::take(&mut origin.indices), moved)
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: std::mem::take(&mut origin.node_ids),
|
||||
indices: std::mem::take(&mut origin.indices),
|
||||
shapes: std::mem::take(&mut origin.shapes),
|
||||
};
|
||||
(moved_placements, laid_out, moved)
|
||||
});
|
||||
let Some((moved_placements, node_ids, indices, graph)) = finished else { return };
|
||||
let Some((moved_placements, laid_out, graph)) = finished else { return };
|
||||
|
||||
let mut stored_all = true;
|
||||
for (node_id, placement) in moved_placements {
|
||||
@@ -189,13 +297,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
if stored_all && let Some(network_metadata) = self.network_metadata(network_path) {
|
||||
let layout = Layout::new(&graph);
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout {
|
||||
revision: store::revision(),
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
});
|
||||
network_metadata.transient_metadata.layout.store(NetworkLayout::new(store::revision(), laid_out, graph, layout));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,16 +310,15 @@ impl NodeNetworkInterface {
|
||||
let transient = self.network_transient_mut(network_path)?;
|
||||
let drag = transient.drag.take()?;
|
||||
transient.layout.unload();
|
||||
self.invalidate_positions(network_path);
|
||||
Some(drag)
|
||||
}
|
||||
|
||||
fn with_drag_origin<R>(&self, drag: &DragPreview, network_path: &[NodeId], revision: u64, read: impl FnOnce(&mut DragOrigin) -> R) -> Option<R> {
|
||||
let mut origin = drag.origin.borrow_mut();
|
||||
if origin.as_ref().is_none_or(|origin| (origin.revision, origin.keep_upstream) != (revision, drag.keep_upstream)) {
|
||||
let (node_ids, indices, start) = self.layout_graph(network_path)?;
|
||||
let (laid_out, start) = self.layout_graph(network_path)?;
|
||||
let start_layout = Layout::new(&start);
|
||||
*origin = Some(DragOrigin::new(node_ids, indices, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
*origin = Some(DragOrigin::new(laid_out, start, start_layout, &drag.dragged, drag.keep_upstream, revision));
|
||||
}
|
||||
origin.as_mut().map(read)
|
||||
}
|
||||
@@ -227,8 +328,8 @@ impl NodeNetworkInterface {
|
||||
let cache = &self.network_metadata(network_path)?.transient_metadata.layout;
|
||||
let cached = cache.with_loaded(|cached| (cached.revision == revision).then(|| cached.clone())).flatten()?;
|
||||
|
||||
let NetworkLayout { node_ids, indices, graph, layout, .. } = cached;
|
||||
Some(DragOrigin::new(node_ids, indices, graph, layout, dragged, keep_upstream, revision))
|
||||
let (laid_out, graph, layout) = cached.into_parts();
|
||||
Some(DragOrigin::new(laid_out, graph, layout, dragged, keep_upstream, revision))
|
||||
}
|
||||
|
||||
fn store_placement(&mut self, node_id: &NodeId, placement: Placement, network_path: &[NodeId]) -> bool {
|
||||
@@ -246,40 +347,38 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
if node.set_node_type(node_type) {
|
||||
self.transaction_modified();
|
||||
self.invalidate_positions(network_path);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn lay_out(&self, network_path: &[NodeId], revision: u64) -> Option<NetworkLayout> {
|
||||
let (node_ids, indices, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
let (laid_out, graph, layout) = match &self.network_metadata(network_path)?.transient_metadata.drag {
|
||||
Some(drag) => self.with_drag_origin(drag, network_path, revision, |origin| {
|
||||
let (graph, mut layout) = origin.drag.moved(drag.offset);
|
||||
layout.snap_chains(&graph);
|
||||
(origin.node_ids.clone(), origin.indices.clone(), graph, layout)
|
||||
let laid_out = LaidOutNodes {
|
||||
node_ids: origin.node_ids.clone(),
|
||||
indices: origin.indices.clone(),
|
||||
shapes: origin.shapes.clone(),
|
||||
};
|
||||
(laid_out, graph, layout)
|
||||
})?,
|
||||
None => {
|
||||
let (node_ids, indices, graph) = self.layout_graph(network_path)?;
|
||||
let (laid_out, graph) = self.layout_graph(network_path)?;
|
||||
let layout = Layout::new(&graph);
|
||||
(node_ids, indices, graph, layout)
|
||||
(laid_out, graph, layout)
|
||||
}
|
||||
};
|
||||
|
||||
Some(NetworkLayout {
|
||||
revision,
|
||||
layout,
|
||||
graph,
|
||||
node_ids,
|
||||
indices,
|
||||
})
|
||||
Some(NetworkLayout::new(revision, laid_out, graph, layout))
|
||||
}
|
||||
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(Vec<NodeId>, HashMap<NodeId, NodeIndex>, Graph)> {
|
||||
pub(crate) fn layout_graph(&self, network_path: &[NodeId]) -> Option<(LaidOutNodes, Graph)> {
|
||||
let network = self.nested_network(network_path)?;
|
||||
let node_ids: Vec<NodeId> = network.nodes.keys().copied().collect();
|
||||
let indices: HashMap<NodeId, NodeIndex> = node_ids.iter().enumerate().map(|(index, node_id)| (*node_id, NodeIndex::from(index as u32))).collect();
|
||||
|
||||
let nodes = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<Vec<_>>>()?;
|
||||
let (nodes, shapes) = node_ids.iter().map(|node_id| self.layout_node(node_id, network_path)).collect::<Option<(Vec<_>, Vec<_>)>>()?;
|
||||
let wires = node_ids
|
||||
.iter()
|
||||
.enumerate()
|
||||
@@ -297,10 +396,10 @@ impl NodeNetworkInterface {
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some((node_ids, indices, Graph { nodes, wires }))
|
||||
Some((LaidOutNodes { node_ids, indices, shapes }, Graph { nodes, wires }))
|
||||
}
|
||||
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<Node> {
|
||||
fn layout_node(&self, node_id: &NodeId, network_path: &[NodeId]) -> Option<(Node, NodeShape)> {
|
||||
let metadata = self.node_metadata(node_id, network_path)?;
|
||||
let (placement, is_layer) = match &metadata.persistent_metadata.node_type_metadata {
|
||||
NodeTypePersistentMetadata::Layer(layer) => match layer.position {
|
||||
@@ -314,17 +413,40 @@ impl NodeNetworkInterface {
|
||||
};
|
||||
|
||||
let is_redirect_dot = self.is_redirect_dot(node_id, network_path);
|
||||
let (layer_width, name_width) = if is_layer {
|
||||
self.layer_width_and_name_width(node_id, network_path).unwrap_or_default()
|
||||
} else {
|
||||
(0, 0.)
|
||||
};
|
||||
let (kind, size) = match (is_layer, is_redirect_dot) {
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(self.layer_width(node_id, network_path).unwrap_or_default(), LAYER_GRID_HEIGHT)),
|
||||
(true, _) => (NodeKind::Layer, UVec2::new(layer_width, LAYER_GRID_HEIGHT)),
|
||||
(false, true) => (NodeKind::Waypoint, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||
(false, false) => (NodeKind::Node, UVec2::new(5, self.node_height(node_id, network_path))),
|
||||
};
|
||||
Some(Node {
|
||||
|
||||
let primary_output_hidden = self.hidden_primary_output(node_id, network_path);
|
||||
let node = Node {
|
||||
placement,
|
||||
kind,
|
||||
size: size.as_ivec2(),
|
||||
chainable: !is_redirect_dot && !self.hidden_primary_output(node_id, network_path),
|
||||
chainable: !is_redirect_dot && !primary_output_hidden,
|
||||
held: false,
|
||||
})
|
||||
};
|
||||
let shape = NodeShape {
|
||||
inputs: self.number_of_displayed_inputs(node_id, network_path) as u32,
|
||||
outputs: self.number_of_outputs(node_id, network_path) as u32,
|
||||
primary_input_hidden: self.document_node(node_id, network_path)?.inputs.first().is_some_and(|input| !input.is_exposed()),
|
||||
primary_output_hidden,
|
||||
name_width,
|
||||
locked: self.is_locked(node_id, network_path),
|
||||
};
|
||||
Some((node, shape))
|
||||
}
|
||||
}
|
||||
|
||||
/// The nodes of a network in the order the layout indexes them, with what each draws beyond its size in the layout.
|
||||
pub(crate) struct LaidOutNodes {
|
||||
pub(crate) node_ids: Vec<NodeId>,
|
||||
pub(crate) indices: HashMap<NodeId, NodeIndex>,
|
||||
shapes: Vec<NodeShape>,
|
||||
}
|
||||
+6
-17
@@ -94,11 +94,9 @@ impl NodeNetworkInterface {
|
||||
self.set_to_node_or_layer(&parent_id, &encapsulating_path, false);
|
||||
}
|
||||
|
||||
// Update the outward wires and bounding box for all nodes in the encapsulating network
|
||||
// Update the outward wires for all nodes in the encapsulating network
|
||||
if let Some(encapsulating_transient) = self.network_transient_mut(&encapsulating_path) {
|
||||
encapsulating_transient.outward_wires.unload();
|
||||
encapsulating_transient.all_nodes_bounding_box.unload();
|
||||
encapsulating_transient.import_export_clearance.unload();
|
||||
}
|
||||
|
||||
// An export inserted as the first or second output of a node in the document network may have affected the document metadata structure
|
||||
@@ -141,7 +139,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
affects_document_structure |= encapsulating_network_path.is_empty() && inserted_index <= 1;
|
||||
}
|
||||
if affects_document_structure {
|
||||
@@ -179,7 +176,6 @@ impl NodeNetworkInterface {
|
||||
fn finish_signature_edit(&mut self, parent_id: NodeId, encapsulating_network_path: &[NodeId], network_path: &[NodeId]) {
|
||||
// Update the metadata for the encapsulating node
|
||||
self.unload_outward_wires(encapsulating_network_path);
|
||||
self.unload_all_nodes_bounding_box(encapsulating_network_path);
|
||||
if !self.is_eligible_to_be_layer(&parent_id, encapsulating_network_path) && self.is_layer(&parent_id, encapsulating_network_path) {
|
||||
self.set_to_node_or_layer(&parent_id, encapsulating_network_path, false);
|
||||
}
|
||||
@@ -572,8 +568,7 @@ impl NodeNetworkInterface {
|
||||
|
||||
/// Lightweight version of `set_input` for bulk import operations.
|
||||
/// Directly sets the input without `is_acyclic` checks, `load_structure`, position conversions,
|
||||
/// or per-node cache invalidation. Call `load_structure`, `unload_all_nodes_click_targets`, and
|
||||
/// `unload_all_nodes_bounding_box` once after all import wiring is complete.
|
||||
/// or per-node cache invalidation. Call `load_structure` once after all import wiring is complete.
|
||||
pub fn set_input_for_import(&mut self, input_connector: &InputConnector, new_input: NodeInput, network_path: &[NodeId]) {
|
||||
if matches!(input_connector, InputConnector::Export(_)) && matches!(new_input, NodeInput::Import { .. }) {
|
||||
log::error!("Cannot connect a network to an export, see https://github.com/GraphiteEditor/Graphite/issues/1762");
|
||||
@@ -673,8 +668,6 @@ impl NodeNetworkInterface {
|
||||
(NodeInput::Value { exposed: old_exposed, .. }, NodeInput::Value { exposed: new_exposed, .. }) => match input_connector {
|
||||
// Exposing or hiding a value input changes the node's port count
|
||||
InputConnector::Node { node_id, .. } if old_exposed != new_exposed => {
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
// A nested network draws its interior ports from the encapsulating node's inputs
|
||||
if matches!(self.implementation(node_id, network_path), Some(DocumentNodeImplementation::Definition(_))) {
|
||||
let nested_path = [network_path, &[*node_id]].concat();
|
||||
@@ -904,7 +897,6 @@ impl NodeNetworkInterface {
|
||||
|
||||
self.transaction_modified();
|
||||
}
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.unload_outward_wires(network_path);
|
||||
}
|
||||
|
||||
@@ -927,7 +919,6 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
|
||||
previous_entry
|
||||
}
|
||||
@@ -1092,7 +1083,6 @@ impl NodeNetworkInterface {
|
||||
outward_wires.retain(|output, _| output.node_id().is_none_or(|node_id| !removed_nodes.contains(&node_id)));
|
||||
}
|
||||
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
let Some(selected_nodes) = self.selected_nodes_mut(network_path) else {
|
||||
log::error!("Could not get selected nodes in NodeGraphMessage::DeleteNodes");
|
||||
return;
|
||||
@@ -1126,10 +1116,10 @@ impl NodeNetworkInterface {
|
||||
}
|
||||
}
|
||||
|
||||
let reconnected_offset = reconnect_to_input
|
||||
.as_ref()
|
||||
.and_then(NodeInput::as_node)
|
||||
.and_then(|reconnected| Some((reconnected, self.relative_offset(&reconnected, network_path)?)));
|
||||
let reconnected_offset = reconnect_to_input.as_ref().and_then(NodeInput::as_node).and_then(|reconnected| {
|
||||
let offset = self.relative_offset(node_id, network_path).or_else(|| self.relative_offset(&reconnected, network_path))?;
|
||||
Some((reconnected, offset))
|
||||
});
|
||||
|
||||
let mut exports_fed_by_import = Vec::new();
|
||||
|
||||
@@ -1365,7 +1355,6 @@ impl NodeNetworkInterface {
|
||||
transient.layer_width.unload();
|
||||
|
||||
self.transaction_modified();
|
||||
self.unload_all_nodes_bounding_box(network_path);
|
||||
self.invalidate_import_export(network_path);
|
||||
self.load_structure();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
//! The areas of a laid out node that react to the pointer, in node graph pixels. A hit test scans each node's reach, a box around
|
||||
//! everything the node draws, and builds the exact parts of only the nodes it lands in.
|
||||
|
||||
use crate::consts::{GRID_SIZE, HALF_GRID_SIZE};
|
||||
use glam::{DVec2, IVec2};
|
||||
use graph_layout::{CHAIN_WIDTH, Node, NodeKind};
|
||||
|
||||
const GRID: f64 = GRID_SIZE as f64;
|
||||
const HALF_GRID: f64 = HALF_GRID_SIZE as f64;
|
||||
/// How far a port on a node's side reaches outward, away from the node, and inward over it.
|
||||
const SIDE_PORT_OUTWARD_REACH: f64 = 12.;
|
||||
const SIDE_PORT_INWARD_REACH: f64 = 8.;
|
||||
const SIDE_PORT_HALF_HEIGHT: f64 = 12.;
|
||||
const STACK_PORT_HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
/// A waypoint's body also covers the gutters beside it, so a press near it moves it unless it lands on a port.
|
||||
const WAYPOINT_HALF_SIZE: DVec2 = DVec2::new(15., 8.);
|
||||
/// A waypoint's wires attach at its center but are grabbed from a round gutter on either side of it.
|
||||
const WAYPOINT_GUTTER_OFFSET: f64 = 10.;
|
||||
const WAYPOINT_GUTTER_RADIUS: f64 = 5.;
|
||||
const GRIP_WIDTH: f64 = 8.;
|
||||
const NAME_LEFT_OFFSET: f64 = HALF_GRID + 3. * GRID + 8.;
|
||||
|
||||
/// What a node draws beyond the size the layout gives it.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct NodeShape {
|
||||
/// How many inputs have a port, which doesn't count a hidden primary input.
|
||||
pub inputs: u32,
|
||||
pub outputs: u32,
|
||||
/// Whether a node's primary input has no port, though its row is still drawn.
|
||||
pub primary_input_hidden: bool,
|
||||
pub primary_output_hidden: bool,
|
||||
/// The width of a layer's name in pixels.
|
||||
pub name_width: f64,
|
||||
pub locked: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Part {
|
||||
Body,
|
||||
/// The input drawn in this grid row of a node, or a layer's stack input at 0 and side input at 1.
|
||||
Input(u32),
|
||||
Output(u32),
|
||||
Visibility,
|
||||
Lock,
|
||||
Grip,
|
||||
Name,
|
||||
}
|
||||
|
||||
/// A rounded rectangle of a node that reacts to the pointer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PartTarget {
|
||||
pub min: DVec2,
|
||||
pub max: DVec2,
|
||||
pub corner_radius: f64,
|
||||
pub part: Part,
|
||||
}
|
||||
|
||||
impl PartTarget {
|
||||
fn around(center: DVec2, half_size: DVec2, corner_radius: f64, part: Part) -> Self {
|
||||
Self {
|
||||
min: center - half_size,
|
||||
max: center + half_size,
|
||||
corner_radius,
|
||||
part,
|
||||
}
|
||||
}
|
||||
|
||||
/// A port on the left side of a node, reaching further out than over the node.
|
||||
fn input_port(center: DVec2, input: u32) -> Self {
|
||||
Self {
|
||||
min: center - DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
max: center + DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
corner_radius: 4.,
|
||||
part: Part::Input(input),
|
||||
}
|
||||
}
|
||||
|
||||
/// A port on the right side of a node, reaching further out than over the node.
|
||||
fn output_port(center: DVec2, output: u32) -> Self {
|
||||
Self {
|
||||
min: center - DVec2::new(SIDE_PORT_INWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
max: center + DVec2::new(SIDE_PORT_OUTWARD_REACH, SIDE_PORT_HALF_HEIGHT),
|
||||
corner_radius: 4.,
|
||||
part: Part::Output(output),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the rounded rectangle shares any area with the box from `min` to `max`.
|
||||
pub fn overlaps(&self, min: DVec2, max: DVec2) -> bool {
|
||||
if !min.cmplt(self.max).all() || !self.min.cmplt(max).all() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let radius = self.clamped_radius();
|
||||
let gap = (self.min + radius - max).max(min - (self.max - radius)).max(DVec2::ZERO);
|
||||
gap == DVec2::ZERO || gap.length_squared() < radius * radius
|
||||
}
|
||||
|
||||
/// Whether `point` is inside the rounded rectangle.
|
||||
pub fn contains(&self, point: DVec2) -> bool {
|
||||
if !point.cmpge(self.min).all() || !point.cmplt(self.max).all() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let radius = self.clamped_radius();
|
||||
let inner = point.clamp(self.min + radius, self.max - radius);
|
||||
point.distance_squared(inner) <= radius * radius
|
||||
}
|
||||
|
||||
fn clamped_radius(&self) -> f64 {
|
||||
self.corner_radius.min((self.max - self.min).min_element() / 2.)
|
||||
}
|
||||
}
|
||||
|
||||
/// A node as drawn at `position`, in grid cells, with the chain it is drawn beside if it is a layer.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct PlacedNode<'a> {
|
||||
pub node: &'a Node,
|
||||
pub shape: &'a NodeShape,
|
||||
pub position: IVec2,
|
||||
pub chain_length: u32,
|
||||
}
|
||||
|
||||
impl PlacedNode<'_> {
|
||||
/// The body: a layer with its chain span, a node below its top connector strip, or the pill around a waypoint.
|
||||
pub fn body(&self) -> PartTarget {
|
||||
let top_left = self.top_left();
|
||||
let size = self.node.size.as_dvec2() * GRID;
|
||||
|
||||
match self.node.kind {
|
||||
NodeKind::Waypoint => PartTarget::around(top_left + DVec2::new(0., GRID), WAYPOINT_HALF_SIZE, WAYPOINT_HALF_SIZE.y, Part::Body),
|
||||
NodeKind::Layer => PartTarget {
|
||||
min: top_left - DVec2::new(self.chain_width(), 0.),
|
||||
max: top_left + size,
|
||||
corner_radius: 10.,
|
||||
part: Part::Body,
|
||||
},
|
||||
NodeKind::Node => {
|
||||
let body_top_left = top_left + DVec2::new(0., HALF_GRID);
|
||||
PartTarget {
|
||||
min: body_top_left,
|
||||
max: body_top_left + size - DVec2::new(0., GRID),
|
||||
corner_radius: 3.,
|
||||
part: Part::Body,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Calls `visit` with each part, the body last.
|
||||
pub fn parts(&self, mut visit: impl FnMut(PartTarget)) {
|
||||
match self.node.kind {
|
||||
NodeKind::Waypoint => self.waypoint_ports(&mut visit),
|
||||
NodeKind::Layer => self.layer_parts(&mut visit),
|
||||
NodeKind::Node => self.node_ports(&mut visit),
|
||||
}
|
||||
visit(self.body());
|
||||
}
|
||||
|
||||
fn waypoint_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let center = self.top_left() + DVec2::new(0., GRID);
|
||||
let gutter = |x_offset: f64, part| PartTarget::around(center + DVec2::new(x_offset, 0.), DVec2::splat(WAYPOINT_GUTTER_RADIUS), WAYPOINT_GUTTER_RADIUS, part);
|
||||
visit(gutter(-WAYPOINT_GUTTER_OFFSET, Part::Input(0)));
|
||||
visit(gutter(WAYPOINT_GUTTER_OFFSET, Part::Output(0)));
|
||||
}
|
||||
|
||||
fn node_ports(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let top_left = self.top_left();
|
||||
let width = self.node.size.x as f64 * GRID;
|
||||
let row_center = |row: u32| GRID * (row as f64 + 1.);
|
||||
|
||||
let first_input_row = u32::from(self.shape.primary_input_hidden);
|
||||
for row in first_input_row..first_input_row + self.shape.inputs {
|
||||
visit(PartTarget::input_port(top_left + DVec2::new(0., row_center(row)), row));
|
||||
}
|
||||
for output in u32::from(self.shape.primary_output_hidden)..self.shape.outputs {
|
||||
visit(PartTarget::output_port(top_left + DVec2::new(width, row_center(output)), output));
|
||||
}
|
||||
}
|
||||
|
||||
fn layer_parts(&self, visit: &mut impl FnMut(PartTarget)) {
|
||||
let top_left = self.top_left();
|
||||
let size = self.node.size.as_dvec2() * GRID;
|
||||
|
||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, size.y + 8.), STACK_PORT_HALF_SIZE, 4., Part::Input(0)));
|
||||
if self.has_side_input() {
|
||||
visit(PartTarget::input_port(top_left + DVec2::new(0., GRID), 1));
|
||||
}
|
||||
visit(PartTarget::around(top_left + DVec2::new(2. * GRID, -8.), STACK_PORT_HALF_SIZE, 4., Part::Output(0)));
|
||||
|
||||
let icon_half_size = DVec2::splat(HALF_GRID);
|
||||
visit(PartTarget::around(top_left + DVec2::new(size.x, GRID), icon_half_size, 3., Part::Visibility));
|
||||
if self.shape.locked {
|
||||
visit(PartTarget::around(top_left + DVec2::new(size.x - GRID, GRID), icon_half_size, 3., Part::Lock));
|
||||
}
|
||||
|
||||
let icons_width = if self.shape.locked { GRID } else { 0. };
|
||||
let grip_right = top_left.x + size.x - HALF_GRID - icons_width;
|
||||
let handle_top = top_left.y + HALF_GRID;
|
||||
let handle_bottom = top_left.y + GRID + HALF_GRID;
|
||||
visit(PartTarget {
|
||||
min: DVec2::new(grip_right - GRIP_WIDTH, handle_top),
|
||||
max: DVec2::new(grip_right, handle_bottom),
|
||||
corner_radius: 0.,
|
||||
part: Part::Grip,
|
||||
});
|
||||
|
||||
let name_left = top_left.x + NAME_LEFT_OFFSET;
|
||||
let name_right = (name_left + self.shape.name_width).min(grip_right - GRIP_WIDTH);
|
||||
if name_right > name_left {
|
||||
visit(PartTarget {
|
||||
min: DVec2::new(name_left, handle_top),
|
||||
max: DVec2::new(name_right, handle_bottom),
|
||||
corner_radius: 3.,
|
||||
part: Part::Name,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn top_left(&self) -> DVec2 {
|
||||
self.position.as_dvec2() * GRID
|
||||
}
|
||||
|
||||
fn has_side_input(&self) -> bool {
|
||||
self.shape.inputs > 1
|
||||
}
|
||||
|
||||
fn chain_width(&self) -> f64 {
|
||||
if self.has_side_input() { (self.chain_length as i32 * CHAIN_WIDTH + 1) as f64 * GRID } else { 0. }
|
||||
}
|
||||
}
|
||||
@@ -328,7 +328,10 @@ fn field_deltas(
|
||||
}
|
||||
|
||||
if current_metadata.node_type_metadata != target_metadata.node_type_metadata {
|
||||
deltas.push(metadata(NodeMetadataChange::NodeType(target_metadata.node_type_metadata.clone())));
|
||||
deltas.push(metadata(NodeMetadataChange::placement(
|
||||
¤t_metadata.node_type_metadata,
|
||||
target_metadata.node_type_metadata.clone(),
|
||||
)));
|
||||
}
|
||||
if current_metadata.display_name != target_metadata.display_name {
|
||||
deltas.push(metadata(NodeMetadataChange::DisplayName(target_metadata.display_name.clone())));
|
||||
|
||||
+7
-6
@@ -229,13 +229,14 @@ impl NodeMut<'_> {
|
||||
|
||||
/// Whether the node is displayed as a layer or a node, together with its position.
|
||||
pub(crate) fn set_node_type(&mut self, node_type: NodeTypePersistentMetadata) -> bool {
|
||||
let changed = self.metadata.node_type_metadata != node_type;
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
if changed {
|
||||
let change = NodeMetadataChange::NodeType(self.metadata.node_type_metadata.clone());
|
||||
self.deltas.metadata(change);
|
||||
if self.metadata.node_type_metadata == node_type {
|
||||
return false;
|
||||
}
|
||||
changed
|
||||
|
||||
let change = NodeMetadataChange::placement(&self.metadata.node_type_metadata, node_type.clone());
|
||||
self.metadata.node_type_metadata = node_type;
|
||||
self.deltas.metadata(change);
|
||||
true
|
||||
}
|
||||
|
||||
/// The table entry the node's interface is stored in, or `None` for a node whose definition owns its interface.
|
||||
|
||||
@@ -3,12 +3,7 @@ use graphene_std::ParameterRef;
|
||||
use graphene_std::vector::misc::dvec2_to_point;
|
||||
use kurbo::{DEFAULT_ACCURACY, Shape};
|
||||
|
||||
/// Axis-aligned rectangle spanning the two opposite corners, used for node graph chrome click targets.
|
||||
pub fn rectangle_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Same as [`rectangle_path`] but with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
/// An axis-aligned rectangle spanning the two opposite corners, with per-corner radii ordered top left, top right, bottom right, bottom left.
|
||||
pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
if radii.iter().all(|radius| *radius == 0.) {
|
||||
@@ -19,16 +14,6 @@ pub fn rounded_rectangle_path(corner1: DVec2, corner2: DVec2, radii: [f64; 4]) -
|
||||
kurbo::RoundedRect::from_rect(rect, kurbo::RoundedRectRadii::new(top_left, top_right, bottom_right, bottom_left)).to_path(DEFAULT_ACCURACY)
|
||||
}
|
||||
|
||||
/// Ellipse inscribed in the box spanning the two opposite corners.
|
||||
pub fn ellipse_path(corner1: DVec2, corner2: DVec2) -> BezPath {
|
||||
let rect = kurbo::Rect::from_points(dvec2_to_point(corner1), dvec2_to_point(corner2));
|
||||
let mut path = kurbo::Ellipse::new(rect.center(), (rect.width() / 2., rect.height() / 2.), 0.).to_path(DEFAULT_ACCURACY);
|
||||
|
||||
// Kurbo emits the ellipse as an unclosed 360 degree arc, but hit testing only fills explicitly closed contours
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
|
||||
/// A copy of a node from a layer's chain, which can be inserted into a chain in this or another document.
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct ChainNodeCopy {
|
||||
@@ -292,13 +277,6 @@ pub(crate) fn side_port_bounds(center: DVec2, is_input: bool) -> [DVec2; 2] {
|
||||
[center - DVec2::new(left_reach, HALF_HEIGHT), center + DVec2::new(right_reach, HALF_HEIGHT)]
|
||||
}
|
||||
|
||||
/// The corners of the click target for a layer's top output or bottom input, which reaches only 8 px toward the connector it faces in a stack.
|
||||
fn stack_port_bounds(center: DVec2) -> [DVec2; 2] {
|
||||
const HALF_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
[center - HALF_SIZE, center + HALF_SIZE]
|
||||
}
|
||||
|
||||
pub(crate) fn port_click_target([corner1, corner2]: [DVec2; 2]) -> ClickTarget {
|
||||
const CORNER_RADIUS: f64 = 4.;
|
||||
|
||||
@@ -332,13 +310,6 @@ impl Ports {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn click_targets(&self) -> impl Iterator<Item = &ClickTarget> {
|
||||
self.input_ports
|
||||
.iter()
|
||||
.map(|(_, click_target)| click_target)
|
||||
.chain(self.output_ports.iter().map(|(_, click_target)| click_target))
|
||||
}
|
||||
|
||||
pub fn input_ports(&self) -> impl Iterator<Item = &(usize, ClickTarget)> {
|
||||
self.input_ports.iter()
|
||||
}
|
||||
@@ -348,51 +319,15 @@ impl Ports {
|
||||
}
|
||||
|
||||
pub(crate) fn insert_input_port_at_center(&mut self, input_index: usize, center: DVec2) {
|
||||
self.insert_custom_input_port(input_index, port_click_target(side_port_bounds(center, true)));
|
||||
self.input_ports.push((input_index, port_click_target(side_port_bounds(center, true))));
|
||||
self.input_anchors.push((input_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_input_port(&mut self, input_index: usize, click_target: ClickTarget) {
|
||||
self.input_ports.push((input_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_output_port_at_center(&mut self, output_index: usize, center: DVec2) {
|
||||
self.insert_custom_output_port(output_index, port_click_target(side_port_bounds(center, false)));
|
||||
self.output_ports.push((output_index, port_click_target(side_port_bounds(center, false))));
|
||||
self.output_anchors.push((output_index, center));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_custom_output_port(&mut self, output_index: usize, click_target: ClickTarget) {
|
||||
self.output_ports.push((output_index, click_target));
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_input(&mut self, input_index: usize, row_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(0., 24. + 24. * row_index as f64);
|
||||
self.insert_input_port_at_center(input_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_node_output(&mut self, output_index: usize, node_top_left: DVec2) {
|
||||
// The center of the click target is always 24 px down from the top left corner of the node
|
||||
let center = node_top_left + DVec2::new(5. * 24., 24. + 24. * output_index as f64);
|
||||
self.insert_output_port_at_center(output_index, center);
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_input(&mut self, input_index: usize, node_top_left: DVec2) {
|
||||
// The primary input sits beneath the layer's thumbnail, and the secondary input on its left side
|
||||
if input_index == 0 {
|
||||
let center = node_top_left + DVec2::new(2. * 24., 24. * 2. + 8.);
|
||||
self.insert_custom_input_port(input_index, port_click_target(stack_port_bounds(center)));
|
||||
} else {
|
||||
self.insert_input_port_at_center(input_index, node_top_left + DVec2::new(0., 24. * 1.));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert_layer_output(&mut self, node_top_left: DVec2) {
|
||||
// The center of the click target is 8 px above the layer, over its thumbnail
|
||||
let center = node_top_left + DVec2::new(2. * 24., -8.);
|
||||
self.insert_custom_output_port(0, port_click_target(stack_port_bounds(center)));
|
||||
}
|
||||
|
||||
pub fn clicked_input_port_from_point(&self, point: DVec2) -> Option<usize> {
|
||||
self.input_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
@@ -401,37 +336,12 @@ impl Ports {
|
||||
self.output_ports.iter().find_map(|(port, click_target)| click_target.intersect_point_no_stroke(point).then_some(*port))
|
||||
}
|
||||
|
||||
/// Adds the input and output of a redirect dot. Its wires both attach at its center, but they're grabbed from the gutters on either side of its body.
|
||||
pub(crate) fn insert_dot_ports(&mut self, center: DVec2) {
|
||||
const GUTTER_OFFSET: f64 = 10.;
|
||||
const GUTTER_RADIUS: f64 = 5.;
|
||||
|
||||
let gutter = |x_offset: f64| {
|
||||
let gutter_center = center + DVec2::new(x_offset, 0.);
|
||||
ClickTarget::new_with_path(ellipse_path(gutter_center - DVec2::splat(GUTTER_RADIUS), gutter_center + DVec2::splat(GUTTER_RADIUS)), 0.)
|
||||
};
|
||||
self.insert_custom_input_port(0, gutter(-GUTTER_OFFSET));
|
||||
self.insert_custom_output_port(0, gutter(GUTTER_OFFSET));
|
||||
self.input_anchors.push((0, center));
|
||||
self.output_anchors.push((0, center));
|
||||
}
|
||||
|
||||
pub fn input_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.input_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.input_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
self.input_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
}
|
||||
|
||||
pub fn output_port_position(&self, index: usize) -> Option<DVec2> {
|
||||
if let Some((_, anchor)) = self.output_anchors.iter().find(|(port_index, _)| *port_index == index) {
|
||||
return Some(*anchor);
|
||||
}
|
||||
self.output_ports
|
||||
.iter()
|
||||
.find_map(|(port_index, click_target)| if *port_index == index { click_target.bounding_box_center() } else { None })
|
||||
self.output_anchors.iter().find(|(port_index, _)| *port_index == index).map(|(_, anchor)| *anchor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -747,16 +657,12 @@ impl<T> TransientCache<T> {
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct NodeNetworkTransientMetadata {
|
||||
pub selected_nodes: SelectedNodes,
|
||||
/// Cache for the bounding box around all nodes in node graph space.
|
||||
pub(crate) all_nodes_bounding_box: TransientCache<[DVec2; 2]>,
|
||||
/// Cache for what the imports and exports keep their distance from, unloaded along with `all_nodes_bounding_box`.
|
||||
pub(crate) import_export_clearance: TransientCache<ImportExportClearance>,
|
||||
/// Cache for all outward wire connections
|
||||
pub(crate) outward_wires: TransientCache<HashMap<OutputConnector, Vec<InputConnector>>>,
|
||||
pub(crate) layout: TransientCache<NetworkLayout>,
|
||||
pub(crate) drag: Option<super::layout_pass::DragPreview>,
|
||||
/// All export connector click targets
|
||||
pub(crate) import_export_ports: TransientCache<Ports>,
|
||||
/// The import and export connector click targets, with the generation of the layout they were placed by.
|
||||
pub(crate) import_export_ports: TransientCache<(u64, Ports)>,
|
||||
|
||||
/// How far whatever is gliding into the place it just moved to is drawn from that place, which hit tests account for.
|
||||
pub(crate) glide_offsets: std::cell::RefCell<GlideOffsets>,
|
||||
@@ -1173,40 +1079,8 @@ impl From<LegacyNodePosition> for NodePosition {
|
||||
/// 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.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
pub struct DocumentNodeTransientMetadata {
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DocumentNodeClickTargets {
|
||||
/// In order to keep the displayed position of the node in sync with the click target, the displayed position of a node is derived from the top left of the click target
|
||||
/// Ensure node_click_target is kept in sync when modifying a node property that changes its size. Currently this is alias, inputs, is_layer, and metadata
|
||||
pub node_click_target: ClickTarget,
|
||||
/// Stores all port click targets in node graph space.
|
||||
pub port_click_targets: Ports,
|
||||
// Click targets that are specific to either nodes or layers, which are chosen states for displaying as a left-to-right node or bottom-to-top layer.
|
||||
pub node_type_metadata: NodeTypeClickTargets,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum NodeTypeClickTargets {
|
||||
Layer(Box<LayerClickTargets>),
|
||||
Node, // No transient click targets are stored exclusively for nodes
|
||||
}
|
||||
|
||||
/// All fields in TransientLayerMetadata should automatically be updated by using the network interface API
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LayerClickTargets {
|
||||
/// Cache for all visibility buttons. Should be automatically updated when update_click_target is called
|
||||
pub visibility_click_target: ClickTarget,
|
||||
/// Cache for the lock icon button, only present when the layer is locked.
|
||||
pub lock_click_target: Option<ClickTarget>,
|
||||
/// Cache for the grip icon, which is next to the visibility button.
|
||||
pub grip_click_target: ClickTarget,
|
||||
/// Cache for the layer's display-name text bounds. Used to detect double-click rename and
|
||||
/// to skip the drill-into-subgraph behavior when the click lands on the name itself.
|
||||
/// `None` for layers whose display name is empty.
|
||||
pub name_click_target: Option<ClickTarget>,
|
||||
/// Width in grid units from the left edge of the layer's thumbnail to its left end, and the measured width of its name, cached since text measurement is slow. Only loaded for layers.
|
||||
pub(crate) layer_width: TransientCache<(u32, f64)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::FrontendGraphDataType;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_std::{uuid::NodeId, vector::misc::dvec2_to_point};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, Point, Shape};
|
||||
use kurbo::{BezPath, DEFAULT_ACCURACY, Line, ParamCurve, Point, Shape, Vec2};
|
||||
|
||||
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
@@ -125,23 +125,27 @@ fn thick_wire_spans_single_cell(output_position: DVec2, input_position: DVec2) -
|
||||
(output_position.x - input_position.x).abs() < 1. && (output_position.y - input_position.y).abs() <= grid_spacing
|
||||
}
|
||||
|
||||
/// The center line that cleaves a thick layer-stack wire. Its ends reach past the wire (1.5px toward the output
|
||||
/// connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool) -> BezPath {
|
||||
/// The center line that cleaves a thick layer-stack wire, following its path. Its ends reach past the wire (1.5px toward the
|
||||
/// output connector and 2px toward the input) so the color runs through the full cleaved connector slots. Empty for other wires.
|
||||
pub fn build_thick_wire_center_line(output_position: DVec2, input_position: DVec2, vertical_out: bool, vertical_in: bool, graph_wire_style: GraphWireStyle) -> BezPath {
|
||||
if !(vertical_out && vertical_in) || thick_wire_spans_single_cell(output_position, input_position) {
|
||||
return BezPath::new();
|
||||
}
|
||||
|
||||
// The 8px wire trims 3px at each end; the center line trims less so it reaches further into the cleaved slots
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let output_trim = 1.5;
|
||||
let input_trim = 1.;
|
||||
let start = output_position + DVec2::new(0., output_trim * sign);
|
||||
let end = input_position - DVec2::new(0., input_trim * sign);
|
||||
let wire = build_vector_wire(output_position, input_position, true, true, graph_wire_style);
|
||||
let (Some(start), Some(end)) = (wire.segments().next().map(|segment| segment.start()), wire.segments().last().map(|segment| segment.end())) else {
|
||||
return BezPath::new();
|
||||
};
|
||||
|
||||
// The 8px wire trims 3px at each end, so the center line reaches further out to trim 1.5px and 1px instead
|
||||
let sign = (input_position.y - output_position.y).signum();
|
||||
let mut center_line = BezPath::new();
|
||||
center_line.move_to(dvec2_to_point(start));
|
||||
center_line.line_to(dvec2_to_point(end));
|
||||
center_line.move_to(start - Vec2::new(0., 1.5 * sign));
|
||||
center_line.line_to(start);
|
||||
for element in wire.elements().iter().skip(1) {
|
||||
center_line.push(*element);
|
||||
}
|
||||
center_line.line_to(end + Vec2::new(0., 2. * sign));
|
||||
center_line
|
||||
}
|
||||
|
||||
@@ -580,7 +584,7 @@ fn straight_wire_to_bezpath(locations: Vec<IVec2>) -> BezPath {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use kurbo::{Affine, Vec2};
|
||||
use kurbo::{Affine, ParamCurveNearest};
|
||||
|
||||
#[test]
|
||||
fn a_grid_aligned_wire_keeps_its_shape_when_moved_along_the_grid() {
|
||||
@@ -603,4 +607,30 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_center_line_of_a_stack_wire_runs_inside_it() {
|
||||
let ends = [
|
||||
(DVec2::new(48., 12.), DVec2::new(48., 84.)),
|
||||
(DVec2::new(240., 12.), DVec2::new(48., 132.)),
|
||||
(DVec2::new(48., 0.), DVec2::new(0., 27.)),
|
||||
];
|
||||
let half_wire_width = 4.;
|
||||
|
||||
for (output, input) in ends {
|
||||
for style in [GraphWireStyle::Direct, GraphWireStyle::GridAligned] {
|
||||
let wire = build_vector_wire(output, input, true, true, style);
|
||||
let center_line = build_thick_wire_center_line(output, input, true, true, style);
|
||||
|
||||
let samples = center_line.segments().flat_map(|segment| (0..=10).map(move |step| segment.eval(f64::from(step) / 10.)));
|
||||
for sample in samples {
|
||||
let distance = wire
|
||||
.segments()
|
||||
.map(|segment| segment.nearest(sample, DEFAULT_ACCURACY).distance_sq.sqrt())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
assert!(distance <= half_wire_width, "the center line from {output} to {input} drawn {style:?} leaves its wire at {sample:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ mod recompile_tests;
|
||||
mod runtime;
|
||||
pub use runtime::*;
|
||||
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ExecutionRequest {
|
||||
execution_id: u64,
|
||||
render_config: RenderConfig,
|
||||
@@ -41,6 +41,15 @@ pub struct ExecutionResponse {
|
||||
dropped_thumbnails: Vec<NodeId>,
|
||||
/// The latest result of each observation.
|
||||
observations: HashMap<ObservationKey, InspectResult>,
|
||||
/// The canvas the frame was presented to
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: Option<ViewportCanvasInfo>,
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
struct ViewportCanvasInfo {
|
||||
id: u64,
|
||||
resolution: DVec2,
|
||||
}
|
||||
|
||||
/// Names an observation so it can be changed or stopped without touching the others.
|
||||
@@ -192,18 +201,6 @@ impl NodeGraphExecutor {
|
||||
self.canvas_images_sent.clear();
|
||||
}
|
||||
|
||||
/// Allows the test runner to see if any more executions have been queued.
|
||||
#[cfg(test)]
|
||||
pub fn current_execution_id(&self) -> u64 {
|
||||
self.current_execution_id
|
||||
}
|
||||
|
||||
/// Allows the test runner to access last executions evaluation errors.
|
||||
#[cfg(test)]
|
||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
/// Execute the network by flattening it and creating a borrow stack.
|
||||
fn queue_execution(&mut self, render_config: RenderConfig) -> u64 {
|
||||
let execution_id = self.current_execution_id;
|
||||
@@ -253,29 +250,6 @@ impl NodeGraphExecutor {
|
||||
.expect("Failed to send the thumbnails in view");
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
}
|
||||
|
||||
/// Update the cached network if necessary.
|
||||
fn update_node_graph(&mut self, document: &mut DocumentMessageHandler, document_id: DocumentId, node_to_inspect: Vec<NodeId>, ignore_hash: bool) -> Result<(), String> {
|
||||
let inspected_node_changed = self.previous_node_to_inspect != node_to_inspect;
|
||||
@@ -527,6 +501,8 @@ impl NodeGraphExecutor {
|
||||
responses: existing_responses,
|
||||
dropped_thumbnails,
|
||||
mut observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
} = *execution_response;
|
||||
all_dropped_thumbnails.extend(dropped_thumbnails.iter().copied());
|
||||
|
||||
@@ -569,6 +545,29 @@ impl NodeGraphExecutor {
|
||||
continue;
|
||||
}
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let mut result = result;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
if let Some(canvas) = viewport_canvas_info {
|
||||
let placeholder = format!(
|
||||
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
||||
canvas.resolution.x, canvas.resolution.y, canvas.id,
|
||||
);
|
||||
match result.render_output() {
|
||||
Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) => {
|
||||
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
||||
svg.insert_str(end, &placeholder);
|
||||
}
|
||||
_ => {
|
||||
let svg = format!("<svg>{placeholder}</svg>");
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
|
||||
// A pending graph keeps the last frame, and the errors shown with it
|
||||
@@ -1036,11 +1035,6 @@ impl NodeGraphExecutor {
|
||||
responses.add(FrontendMessage::UpdateImageData { image_data, canvas_ids_in_use });
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
RenderOutputType::CanvasFrame { canvas_id, resolution } => {
|
||||
let svg = format!("<svg>{}</svg>", viewport_canvas_placeholder(canvas_id, resolution));
|
||||
responses.add(FrontendMessage::UpdateDocumentArtwork { svg });
|
||||
}
|
||||
RenderOutputType::Texture { .. } => {}
|
||||
RenderOutputType::Buffer { width, height, .. } => {
|
||||
log::error!("Invalid node graph output type: a {width}×{height} pixel buffer");
|
||||
@@ -1205,15 +1199,6 @@ fn measure_fill_geometry(data: &Arc<dyn Any + Send + Sync>) -> Option<(DAffine2,
|
||||
None
|
||||
}
|
||||
|
||||
/// The SVG element the frontend replaces with the viewport canvas, covering the viewport at its logical `resolution`.
|
||||
#[cfg(target_family = "wasm")]
|
||||
fn viewport_canvas_placeholder(canvas_id: u64, resolution: DVec2) -> String {
|
||||
format!(
|
||||
r#"<foreignObject width="{}" height="{}"><div data-canvas-placeholder="{}" data-is-viewport="true"></div></foreignObject>"#,
|
||||
resolution.x, resolution.y, canvas_id,
|
||||
)
|
||||
}
|
||||
|
||||
/// Says why an export saved nothing, given the evaluation's error, or else the graph's failure to compile.
|
||||
fn export_failure_dialog(evaluation_error: Option<String>) -> DialogMessage {
|
||||
DialogMessage::DisplayDialogError {
|
||||
@@ -1268,6 +1253,40 @@ mod test {
|
||||
use graphene_std::list::Item;
|
||||
use test_prelude::LayerNodeIdentifier;
|
||||
|
||||
impl NodeGraphExecutor {
|
||||
/// Allows the test runner to see if any more executions have been queued.
|
||||
pub fn current_execution_id(&self) -> u64 {
|
||||
self.current_execution_id
|
||||
}
|
||||
|
||||
/// Allows the test runner to access last executions evaluation errors.
|
||||
pub fn take_evaluation_errors(&mut self) -> Option<EvaluationErrors> {
|
||||
self.evaluation_errors.take()
|
||||
}
|
||||
|
||||
/// Updates the network, giving back the paths of its proto nodes so tests can read what their inputs received.
|
||||
pub(crate) fn update_node_graph_instrumented(&mut self, document: &mut DocumentMessageHandler) -> Result<Instrumented, String> {
|
||||
// We should always invalidate the cache.
|
||||
self.node_graph_hash = crate::application::generate_uuid();
|
||||
let mut network = document.network_interface.document_network().clone();
|
||||
network.inline_definitions().map_err(|error| error.to_string())?;
|
||||
let instrumented = Instrumented::new(&network);
|
||||
|
||||
let resources = document.resources.registry.clone();
|
||||
|
||||
self.sender
|
||||
.send(GraphRuntimeRequest::GraphUpdate(GraphUpdate {
|
||||
network,
|
||||
resources,
|
||||
previewed: Vec::new(),
|
||||
layers: document.network_interface.layer_paths(),
|
||||
observations: self.observations(&document.network_interface),
|
||||
}))
|
||||
.map_err(|e| e.to_string())?;
|
||||
Ok(instrumented)
|
||||
}
|
||||
}
|
||||
|
||||
/// The path of each proto node in an evaluated graph, by which tests read the values its inputs received.
|
||||
#[derive(Default)]
|
||||
pub struct Instrumented {
|
||||
|
||||
@@ -20,7 +20,7 @@ use graphene_std::vector::style::RenderMode;
|
||||
use graphene_std::{Context, NodeError, Poll};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle, ResolvedDocumentNodeTypesDelta};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use observer::Observer;
|
||||
pub use observer::{InspectResult, InspectedContext, Observation, ObservedConnector, ObservedValue};
|
||||
use std::sync::Arc;
|
||||
@@ -94,7 +94,7 @@ enum ViewportArtwork {
|
||||
}
|
||||
|
||||
/// Messages passed from the editor thread to the node runtime thread.
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug)]
|
||||
pub enum GraphRuntimeRequest {
|
||||
GraphUpdate(GraphUpdate),
|
||||
ExecutionRequest(ExecutionRequest),
|
||||
@@ -114,7 +114,7 @@ pub enum GraphRuntimeRequest {
|
||||
RenderOverlays(OverlayContext),
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug)]
|
||||
pub struct GraphUpdate {
|
||||
pub(super) network: NodeNetwork,
|
||||
pub(super) resources: ResourceRegistry,
|
||||
@@ -302,7 +302,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
if let Some(viewport) = viewport {
|
||||
texture = self.run_viewport(viewport).await;
|
||||
self.run_viewport(viewport).await;
|
||||
}
|
||||
|
||||
// Overlays that changed without new artwork are drawn over the artwork already shown
|
||||
@@ -315,63 +315,27 @@ impl NodeRuntime {
|
||||
texture
|
||||
}
|
||||
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) -> Option<Texture> {
|
||||
async fn run_viewport(&mut self, request: ExecutionRequest) {
|
||||
self.thumbnails.set_scale(request.render_config.scale);
|
||||
|
||||
let mut result = self.evaluate(request)?;
|
||||
let Some(mut result) = self.evaluate(request) else { return };
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let resolution = request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale;
|
||||
|
||||
let texture = if let Some(RenderOutput { data, metadata }) = result.render_output()
|
||||
&& let RenderOutputType::Texture(texture) = data
|
||||
{
|
||||
self.viewport_artwork = Some(ViewportArtwork::Texture(texture.clone()));
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
let frame = self.composite_viewport_frame();
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
{
|
||||
*data = RenderOutputType::CanvasFrame {
|
||||
canvas_id: self.wasm_canvas_cache.id(),
|
||||
resolution,
|
||||
};
|
||||
if let Some(RenderOutput { data, metadata }) = result.render_output() {
|
||||
let content = match data {
|
||||
RenderOutputType::Texture(texture) => Some(ViewportArtwork::Texture(texture.clone())),
|
||||
RenderOutputType::Svg { .. } if request.render_config.export_format == ExportFormat::Raster => Some(ViewportArtwork::Svg),
|
||||
_ => None,
|
||||
};
|
||||
if content.is_some() {
|
||||
self.viewport_artwork = content;
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
}
|
||||
}
|
||||
|
||||
frame
|
||||
} else if request.render_config.export_format == ExportFormat::Raster
|
||||
&& let Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { .. },
|
||||
metadata,
|
||||
}) = result.render_output()
|
||||
{
|
||||
// The viewport was rendered as SVG in place of the requested raster, so the frontend draws it beneath the overlays
|
||||
self.viewport_artwork = Some(ViewportArtwork::Svg);
|
||||
let path_contents = path_contents(&observations);
|
||||
self.rendered_layers = RenderedLayers::new(metadata, &path_contents, self.old_graph.as_ref());
|
||||
self.overlays_stale = true;
|
||||
let frame = self.composite_viewport_frame();
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
if let Some(RenderOutput {
|
||||
data: RenderOutputType::Svg { svg, .. },
|
||||
..
|
||||
}) = result.render_output()
|
||||
{
|
||||
let end = svg.rfind("</svg>").unwrap_or(svg.len());
|
||||
svg.insert_str(end, &viewport_canvas_placeholder(self.wasm_canvas_cache.id(), resolution));
|
||||
}
|
||||
|
||||
frame
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
texture
|
||||
self.respond(request, result, observations).await;
|
||||
}
|
||||
|
||||
/// Draws the latest overlays over the viewport's artwork, or alone above SVG artwork, presenting the frame on web.
|
||||
@@ -431,7 +395,7 @@ impl NodeRuntime {
|
||||
*data = RenderOutputType::Buffer { data: buffer, width, height };
|
||||
}
|
||||
let observations = self.observer.evaluate(&self.executor, self.old_graph.as_ref());
|
||||
self.respond(request.execution_id, result, observations).await;
|
||||
self.respond(request, result, observations).await;
|
||||
}
|
||||
|
||||
async fn run_eyedropper(&mut self, mut request: ExecutionRequest) {
|
||||
@@ -465,7 +429,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
let context = render_config.into_context_with_generations(self.async_runtime().snapshot());
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.tree().eval_tagged_value(self.output.node(), &context))) {
|
||||
let result = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.executor.execute(&self.output, context))) {
|
||||
Ok(Ok(Poll::Pending)) => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(_))) if render_config.for_export => ExecutionResult::Pending,
|
||||
Ok(Ok(Poll::Partial(value))) => ExecutionResult::Partial(value),
|
||||
@@ -475,7 +439,7 @@ impl NodeRuntime {
|
||||
ExecutionResult::Fallback(value, self.resolve_errors(&error))
|
||||
}
|
||||
Ok(Ok(Poll::Error(error))) => ExecutionResult::Error(self.resolve_errors(&error)),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error).error()), NodeErrorTrace::default())]))),
|
||||
Ok(Err(error)) => ExecutionResult::Error(EvaluationErrors(Box::new([(Arc::clone(NodeError::new(error.to_string()).error()), NodeErrorTrace::default())]))),
|
||||
Err(payload) => {
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
@@ -483,6 +447,8 @@ impl NodeRuntime {
|
||||
responses: VecDeque::new(),
|
||||
dropped_thumbnails: Vec::new(),
|
||||
observations: HashMap::new(),
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info: None,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
return None;
|
||||
@@ -491,18 +457,37 @@ impl NodeRuntime {
|
||||
Some(result)
|
||||
}
|
||||
|
||||
async fn respond(&mut self, execution_id: u64, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
async fn respond(&mut self, request: ExecutionRequest, result: ExecutionResult, observations: HashMap<ObservationKey, InspectResult>) {
|
||||
let mut responses = VecDeque::new();
|
||||
|
||||
// While the graph fails to compile, thumbnails stay stale to render once it compiles, not from the last network that did
|
||||
let dropped_thumbnails = if self.compile_failed { Vec::new() } else { self.update_thumbnails(&mut responses).await };
|
||||
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let mut result = result;
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
let viewport_canvas_info = (!request.render_config.for_export
|
||||
&& match result.render_output() {
|
||||
Some(RenderOutput { data, .. }) => match data {
|
||||
RenderOutputType::Texture(_) => true,
|
||||
RenderOutputType::Svg { .. } => request.render_config.export_format == ExportFormat::Raster,
|
||||
RenderOutputType::Buffer { .. } => false,
|
||||
},
|
||||
None => false,
|
||||
})
|
||||
.then(|| ViewportCanvasInfo {
|
||||
id: self.wasm_canvas_cache.id(),
|
||||
resolution: request.render_config.viewport.resolution.as_dvec2() / request.render_config.scale,
|
||||
});
|
||||
|
||||
let response = ExecutionResponse {
|
||||
execution_id,
|
||||
execution_id: request.execution_id,
|
||||
result,
|
||||
responses,
|
||||
dropped_thumbnails,
|
||||
observations,
|
||||
#[cfg(all(target_family = "wasm", feature = "wasm"))]
|
||||
viewport_canvas_info,
|
||||
};
|
||||
self.sender.send(NodeGraphUpdate::ExecutionResponse(Box::new(response))).expect("Failed to send response");
|
||||
}
|
||||
@@ -522,7 +507,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
fn update_network(&mut self, graph: NodeNetwork) -> Result<ResolvedDocumentNodeTypesDelta, (ResolvedDocumentNodeTypesDelta, String)> {
|
||||
let mut scoped_network = wrap_network_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
let mut scoped_network = wrap_network_with_render_node_in_scope(graph, self.editor_api.clone(), self.async_runtime().handle());
|
||||
|
||||
if let Err(e) = self.preprocessor.preprocess(&mut scoped_network, &|resource_id| self.resources.hash(&resource_id)) {
|
||||
return Err((ResolvedDocumentNodeTypesDelta::default(), e.to_string()));
|
||||
@@ -586,7 +571,7 @@ impl NodeRuntime {
|
||||
}
|
||||
|
||||
impl ExecutionResult {
|
||||
fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
pub(super) fn render_output(&mut self) -> Option<&mut RenderOutput> {
|
||||
let (Self::Value(value) | Self::Partial(value) | Self::Fallback(value, _)) = self else {
|
||||
return None;
|
||||
};
|
||||
|
||||
@@ -520,14 +520,18 @@ fn init_test_logger() {
|
||||
});
|
||||
}
|
||||
|
||||
/// Creates application IO with the GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||
/// The GPU executor shared by every test in the process, since creating a device and its pipelines for each test is slow.
|
||||
/// Panics if no adapter is found, since tests render on the GPU like the app does.
|
||||
fn gpu_application_io() -> PlatformApplicationIo {
|
||||
pub fn gpu_executor() -> <PlatformApplicationIo as ApplicationIo>::Executor {
|
||||
static GPU_EXECUTOR: LazyLock<Option<<PlatformApplicationIo as ApplicationIo>::Executor>> = LazyLock::new(|| futures::executor::block_on(PlatformApplicationIo::new()).gpu_executor().cloned());
|
||||
let executor = GPU_EXECUTOR.clone().expect(
|
||||
GPU_EXECUTOR.clone().expect(
|
||||
"Editor tests need a GPU adapter. Without a hardware GPU, install Mesa's lavapipe software Vulkan driver and point `VK_ADD_DRIVER_FILES` at its `lvp_icd.<arch>.json` (the Nix dev shell does this).",
|
||||
);
|
||||
PlatformApplicationIo::new_with_executor(executor)
|
||||
)
|
||||
}
|
||||
|
||||
/// Creates application IO with the GPU executor every test shares (see [`gpu_executor`]).
|
||||
fn gpu_application_io() -> PlatformApplicationIo {
|
||||
PlatformApplicationIo::new_with_executor(gpu_executor())
|
||||
}
|
||||
|
||||
/// Runs `operation`, returning its result along with the errors it logged.
|
||||
|
||||
@@ -538,30 +538,6 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Click target debug visualizations -->
|
||||
{#if $nodeGraph.clickTargets}
|
||||
<div class="click-targets" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
{#each $nodeGraph.clickTargets.nodeClickTargets as pathString}
|
||||
<path class="node" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.layerClickTargets as pathString}
|
||||
<path class="layer" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.connectorClickTargets as pathString}
|
||||
<path class="connector" d={pathString} />
|
||||
{/each}
|
||||
{#each $nodeGraph.clickTargets.iconClickTargets as pathString}
|
||||
<path class="visibility" d={pathString} />
|
||||
{/each}
|
||||
<path class="all-nodes-bounding-box" d={$nodeGraph.clickTargets.allNodesBoundingBox} />
|
||||
{#each $nodeGraph.clickTargets.importExportNames as pathString}
|
||||
<path class="import-export-name" d={pathString} />
|
||||
{/each}
|
||||
</svg>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<!-- Thick vertical layer connection wires -->
|
||||
<div class="wires" style:transform-origin="0 0" style:transform={`translate(${$nodeGraphTransform.x}px, ${$nodeGraphTransform.y}px) scale(${$nodeGraphTransform.scale})`}>
|
||||
<svg>
|
||||
@@ -1311,46 +1287,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.click-targets {
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
z-index: 10;
|
||||
|
||||
svg {
|
||||
overflow: visible;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
stroke-width: 1;
|
||||
fill: none;
|
||||
|
||||
.layer {
|
||||
stroke: yellow;
|
||||
}
|
||||
|
||||
.node {
|
||||
stroke: blue;
|
||||
}
|
||||
|
||||
.connector {
|
||||
stroke: green;
|
||||
}
|
||||
|
||||
.visibility {
|
||||
stroke: red;
|
||||
}
|
||||
|
||||
.all-nodes-bounding-box {
|
||||
stroke: purple;
|
||||
}
|
||||
|
||||
.import-export-name {
|
||||
stroke: orange;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.wires {
|
||||
pointer-events: none;
|
||||
position: absolute;
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Writable } from "svelte/store";
|
||||
import type { IconName } from "/src/icons";
|
||||
import type { SubscriptionsRouter } from "/src/subscriptions-router";
|
||||
import type { MessageBody } from "/src/subscriptions-router";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
import type { NodeGraphErrorDiagnostic, BoxSelection, ContextMenuInformation, FrontendNode, FrontendNodeType, WirePath } from "/wrapper/pkg/graphite_wasm_wrapper";
|
||||
|
||||
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
|
||||
|
||||
@@ -13,7 +13,6 @@ export type ThumbnailCanvases = { layersPanelCanvasId: number; nodeGraphCanvasId
|
||||
|
||||
type NodeGraphStoreState = {
|
||||
box: BoxSelection | undefined;
|
||||
clickTargets: FrontendClickTargets | undefined;
|
||||
contextMenuInformation: ContextMenuInformation | undefined;
|
||||
errors: NodeGraphErrorDiagnostic[];
|
||||
layerWidths: Map<bigint, number>;
|
||||
@@ -36,7 +35,6 @@ type NodeGraphStoreState = {
|
||||
};
|
||||
const initialState: NodeGraphStoreState = {
|
||||
box: undefined,
|
||||
clickTargets: undefined,
|
||||
contextMenuInformation: undefined,
|
||||
errors: [],
|
||||
layerWidths: new Map(),
|
||||
@@ -136,13 +134,6 @@ export function createNodeGraphStore(subscriptions: SubscriptionsRouter) {
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
|
||||
update((state) => {
|
||||
state.clickTargets = data.clickTargets;
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
|
||||
update((state) => {
|
||||
state.contextMenuInformation = data.contextMenuInformation;
|
||||
@@ -330,7 +321,6 @@ export function destroyNodeGraphStore() {
|
||||
|
||||
subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateBox");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateContextMenuInformation");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateImportReorderIndex");
|
||||
subscriptions.unsubscribeFrontendMessage("UpdateExportReorderIndex");
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::mover::Mover;
|
||||
use crate::graph::LAYER_BOTTOM_GAP;
|
||||
use crate::per_node::PerNode;
|
||||
use crate::{NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use std::mem;
|
||||
|
||||
pub(super) struct Snapshot {
|
||||
placements: PerNode<Placement>,
|
||||
@@ -16,38 +16,85 @@ impl Mover {
|
||||
Snapshot { placements, positions }
|
||||
}
|
||||
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) {
|
||||
let followers = self.followers(before, moved);
|
||||
let mut restored = PerNode::filled(&self.graph, false);
|
||||
followers
|
||||
.indices()
|
||||
.filter(|node| followers[*node])
|
||||
.for_each(|node| self.restore_follower(node, &followers, &before.positions, &mut restored));
|
||||
pub(super) fn restore_followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) {
|
||||
let followers = self.followers(before, kept);
|
||||
let mut pushed = PerNode::filled(&self.graph, None);
|
||||
for node in followers.indices().filter(|node| followers[*node]) {
|
||||
self.restore_follower(node, &followers, &before.positions, &mut pushed);
|
||||
}
|
||||
}
|
||||
|
||||
fn followers(&mut self, before: &Snapshot, moved: &[NodeIndex]) -> PerNode<bool> {
|
||||
fn followers(&mut self, before: &Snapshot, kept: &PerNode<bool>) -> PerNode<bool> {
|
||||
let (graph, layout) = self.graph_and_layout();
|
||||
PerNode::from_fn(graph, |node| {
|
||||
let placement = graph[node].placement;
|
||||
let unchanged = placement == before.placements[node];
|
||||
let was_relative = matches!(before.placements[node], Placement::Relative(_));
|
||||
let is_relative = matches!(placement, Placement::Relative(_));
|
||||
!moved.contains(&node) && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||
kept[node] && is_relative && (unchanged || !was_relative) && layout.positions[node] != before.positions[node]
|
||||
})
|
||||
}
|
||||
|
||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, restored: &mut PerNode<bool>) {
|
||||
if mem::replace(&mut restored[node], true) {
|
||||
return;
|
||||
fn restore_follower(&mut self, node: NodeIndex, followers: &PerNode<bool>, positions_before: &PerNode<IVec2>, pushed: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||
if let Some(push) = pushed[node] {
|
||||
return push;
|
||||
}
|
||||
pushed[node] = Some(IVec2::ZERO);
|
||||
|
||||
let following_readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).filter(|reader| followers[*reader]).collect();
|
||||
for reader in following_readers {
|
||||
self.restore_follower(reader, followers, positions_before, restored);
|
||||
let pushed_by_readers = following_readers
|
||||
.into_iter()
|
||||
.map(|reader| self.restore_follower(reader, followers, positions_before, pushed))
|
||||
.fold(IVec2::ZERO, IVec2::max);
|
||||
|
||||
let shift = positions_before[node] + pushed_by_readers - self.position(node);
|
||||
let shifted = self.graph[node].placement.shifted(shift);
|
||||
let clear = self.clear_of_the_layer_above(node, shifted);
|
||||
self.set_placement(node, clear);
|
||||
|
||||
let push = pushed_by_readers + clear.stored_offset() - shifted.stored_offset();
|
||||
pushed[node] = Some(push);
|
||||
push
|
||||
}
|
||||
|
||||
pub(super) fn carry_along(&mut self, before: &Snapshot, carried: &PerNode<bool>) {
|
||||
let mut shifts = PerNode::filled(&self.graph, None);
|
||||
for node in carried.indices().filter(|node| carried[*node]) {
|
||||
self.carry(node, carried, &before.positions, &mut shifts);
|
||||
}
|
||||
}
|
||||
|
||||
fn carry(&mut self, node: NodeIndex, carried: &PerNode<bool>, positions_before: &PerNode<IVec2>, shifts: &mut PerNode<Option<IVec2>>) -> IVec2 {
|
||||
if let Some(shift) = shifts[node] {
|
||||
return shift;
|
||||
}
|
||||
shifts[node] = Some(IVec2::ZERO);
|
||||
|
||||
let readers: Vec<NodeIndex> = self.readers.of(&self.graph, node).map(|wire| wire.target).collect();
|
||||
let mut shift = IVec2::ZERO;
|
||||
for reader in readers {
|
||||
shift = if carried[reader] {
|
||||
self.carry(reader, carried, positions_before, shifts)
|
||||
} else {
|
||||
self.position(reader) - positions_before[reader]
|
||||
};
|
||||
if shift != IVec2::ZERO {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let shift = positions_before[node] - self.position(node);
|
||||
let shifted = self.graph[node].placement.shifted(shift);
|
||||
self.set_placement(node, shifted);
|
||||
shifts[node] = Some(shift);
|
||||
shift
|
||||
}
|
||||
|
||||
fn clear_of_the_layer_above(&self, node: NodeIndex, placement: Placement) -> Placement {
|
||||
let Placement::Relative(offset) = placement else { return placement };
|
||||
let layer_above = self.readers.of(&self.graph, node).find(|wire| self.graph.feeds_stack(wire)).map(|wire| wire.target);
|
||||
let Some(layer_above) = layer_above.filter(|_| offset.x == 0) else { return placement };
|
||||
|
||||
let lowest_free_row = self.graph[layer_above].size.y + LAYER_BOTTOM_GAP;
|
||||
Placement::Relative(IVec2::new(0, offset.y.max(lowest_free_row)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
use crate::connections::WiresByNode;
|
||||
use crate::per_node::PerNode;
|
||||
use crate::{Graph, NodeIndex, Placement, Wire};
|
||||
use glam::IVec2;
|
||||
use std::mem;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct UpstreamOfDragged {
|
||||
moving_up_or_down: Upstream,
|
||||
moving_sideways: Upstream,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct Upstream {
|
||||
pub(super) kept: PerNode<bool>,
|
||||
pub(super) carried: PerNode<bool>,
|
||||
}
|
||||
|
||||
impl UpstreamOfDragged {
|
||||
pub(super) fn new(graph: &Graph, dragged: &[NodeIndex]) -> Self {
|
||||
let inputs = WiresByNode::inputs(graph);
|
||||
let everything = upstream_through(graph, &inputs, dragged, |_| true);
|
||||
let into_a_node = |wire: &Wire| !graph[wire.target].is_layer();
|
||||
let split = |kept: PerNode<bool>| {
|
||||
let carried = PerNode::from_fn(graph, |node| everything[node] && !kept[node] && matches!(graph[node].placement, Placement::Absolute(_)));
|
||||
Upstream { kept, carried }
|
||||
};
|
||||
Self {
|
||||
moving_up_or_down: split(upstream_through(graph, &inputs, dragged, |wire| into_a_node(wire) || graph.feeds_stack(wire))),
|
||||
moving_sideways: split(upstream_through(graph, &inputs, dragged, into_a_node)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn moving_by(&self, shift: IVec2) -> &Upstream {
|
||||
if shift.x == 0 { &self.moving_up_or_down } else { &self.moving_sideways }
|
||||
}
|
||||
}
|
||||
|
||||
fn upstream_through(graph: &Graph, inputs: &WiresByNode, dragged: &[NodeIndex], followed: impl Fn(&Wire) -> bool) -> PerNode<bool> {
|
||||
let mut upstream = PerNode::filled(graph, false);
|
||||
for node in dragged {
|
||||
upstream[*node] = true;
|
||||
}
|
||||
dragged
|
||||
.iter()
|
||||
.flat_map(|node| inputs.of(graph, *node))
|
||||
.filter(|wire| followed(wire))
|
||||
.for_each(|wire| mark_upstream(graph, inputs, wire.source, &mut upstream));
|
||||
for node in dragged {
|
||||
upstream[*node] = false;
|
||||
}
|
||||
upstream
|
||||
}
|
||||
|
||||
fn mark_upstream(graph: &Graph, inputs: &WiresByNode, node: NodeIndex, upstream: &mut PerNode<bool>) {
|
||||
if mem::replace(&mut upstream[node], true) {
|
||||
return;
|
||||
}
|
||||
inputs.of(graph, node).for_each(|wire| mark_upstream(graph, inputs, wire.source, upstream));
|
||||
}
|
||||
@@ -1,10 +1,12 @@
|
||||
mod followers;
|
||||
mod kept;
|
||||
mod mover;
|
||||
mod shift;
|
||||
mod stack;
|
||||
|
||||
use crate::{Graph, Layout, NodeIndex, Placement};
|
||||
use glam::IVec2;
|
||||
use kept::UpstreamOfDragged;
|
||||
use mover::Mover;
|
||||
|
||||
/// Nodes dragged from where they are drawn, computing the graph for any offset from the start alone.
|
||||
@@ -12,7 +14,7 @@ use mover::Mover;
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Drag {
|
||||
dragged: Vec<NodeIndex>,
|
||||
keep_upstream: bool,
|
||||
upstream: Option<UpstreamOfDragged>,
|
||||
rows_up: Vec<Graph>,
|
||||
held_in_place: Vec<HeldInPlace>,
|
||||
}
|
||||
@@ -26,8 +28,11 @@ struct HeldInPlace {
|
||||
|
||||
impl Drag {
|
||||
/// Holds the `dragged` nodes of `start`. With `keep_upstream`, nodes only carried along by them stay where they are drawn.
|
||||
/// Dragged layers still carry their content and chain, and carry the stacks below them when moved sideways.
|
||||
/// Nodes starting a tree of their own upstream of what moves follow the nodes reading them.
|
||||
#[must_use]
|
||||
pub fn new(start: Graph, start_layout: Layout, dragged: Vec<NodeIndex>, keep_upstream: bool) -> Self {
|
||||
let upstream = keep_upstream.then(|| UpstreamOfDragged::new(&start, &dragged));
|
||||
let stored: Vec<Placement> = start.nodes.iter().map(|node| node.placement).collect();
|
||||
let mut mover = Mover::new(start, Some(start_layout));
|
||||
mover.hold(&dragged);
|
||||
@@ -45,7 +50,7 @@ impl Drag {
|
||||
.collect();
|
||||
Self {
|
||||
dragged,
|
||||
keep_upstream,
|
||||
upstream,
|
||||
rows_up: vec![held],
|
||||
held_in_place,
|
||||
}
|
||||
@@ -74,7 +79,7 @@ impl Drag {
|
||||
[IVec2::new(0, offset.y.max(0)), IVec2::new(offset.x, 0)]
|
||||
.into_iter()
|
||||
.filter(|shift| *shift != IVec2::ZERO)
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.keep_upstream));
|
||||
.for_each(|shift| mover.shift_step(&self.dragged, shift, self.upstream.as_ref().map(|upstream| upstream.moving_by(shift))));
|
||||
mover.into_graph_and_layout()
|
||||
}
|
||||
|
||||
@@ -89,7 +94,7 @@ impl Drag {
|
||||
fn one_row_further_up(&self) -> Graph {
|
||||
let highest_so_far = self.rows_up.last().cloned().unwrap_or_default();
|
||||
let mut mover = Mover::new(highest_so_far, None);
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.keep_upstream);
|
||||
mover.shift_step(&self.dragged, IVec2::NEG_Y, self.upstream.as_ref().map(|upstream| upstream.moving_by(IVec2::NEG_Y)));
|
||||
mover.into_graph()
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,27 @@
|
||||
use super::kept::Upstream;
|
||||
use super::mover::Mover;
|
||||
use crate::NodeIndex;
|
||||
use glam::IVec2;
|
||||
|
||||
impl Mover {
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, keep_upstream: bool) {
|
||||
let before = keep_upstream.then(|| self.snapshot());
|
||||
let shifted = self.shift_nodes(dragged, shift);
|
||||
if let Some(before) = before {
|
||||
let moved: Vec<NodeIndex> = dragged.iter().chain(&shifted).copied().collect();
|
||||
self.restore_followers(&before, &moved);
|
||||
pub(super) fn shift_step(&mut self, dragged: &[NodeIndex], shift: IVec2, upstream: Option<&Upstream>) {
|
||||
let before = upstream.map(|upstream| (self.snapshot(), upstream));
|
||||
self.shift_nodes(dragged, shift);
|
||||
if let Some((before, upstream)) = before {
|
||||
self.restore_followers(&before, &upstream.kept);
|
||||
self.carry_along(&before, &upstream.carried);
|
||||
}
|
||||
}
|
||||
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) -> Vec<NodeIndex> {
|
||||
fn shift_nodes(&mut self, nodes: &[NodeIndex], shift: IVec2) {
|
||||
let mut shifted = Vec::new();
|
||||
for node in self.moving_on_their_own(nodes) {
|
||||
self.shift_node(node, shift, &mut shifted);
|
||||
}
|
||||
shifted
|
||||
}
|
||||
|
||||
fn shift_node(&mut self, node: NodeIndex, shift: IVec2, shifted: &mut Vec<NodeIndex>) {
|
||||
let moving = self.node_moving_for(node, shift);
|
||||
let Some(moving) = self.node_moving_for(node, shift) else { return };
|
||||
if shifted.contains(&moving) {
|
||||
return;
|
||||
}
|
||||
@@ -34,12 +34,12 @@ impl Mover {
|
||||
self.place_at(moving, position + shift);
|
||||
}
|
||||
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> NodeIndex {
|
||||
fn node_moving_for(&mut self, node: NodeIndex, shift: IVec2) -> Option<NodeIndex> {
|
||||
let (stack, layout) = self.stack_and_layout();
|
||||
match shift {
|
||||
IVec2 { x: 0, y: -1 } => stack.lowest_layer_with_room_above(layout, node),
|
||||
IVec2 { x: 0, .. } => node,
|
||||
_ => stack.top(node),
|
||||
IVec2 { x: 0, .. } => Some(node),
|
||||
_ => Some(stack.top(node)),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,8 +14,18 @@ impl Stack<'_> {
|
||||
self.climb(node, |layer| self.layer_above(layer))
|
||||
}
|
||||
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> NodeIndex {
|
||||
self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)))
|
||||
pub(super) fn lowest_layer_with_room_above(&self, layout: &Layout, node: NodeIndex) -> Option<NodeIndex> {
|
||||
let top_of_closed_up_run = self.climb(node, |layer| self.layer_above(layer).filter(|above| self.closed_up(layout, layer, *above)));
|
||||
(!self.closed_up_under_its_parent(layout, top_of_closed_up_run)).then_some(top_of_closed_up_run)
|
||||
}
|
||||
|
||||
fn closed_up_under_its_parent(&self, layout: &Layout, layer: NodeIndex) -> bool {
|
||||
let parent = self
|
||||
.readers
|
||||
.of(self.graph, layer)
|
||||
.find(|wire| wire.is_primary() && self.graph[wire.target].is_layer() && !self.graph.feeds_stack(wire))
|
||||
.map(|wire| wire.target);
|
||||
self.graph[layer].is_layer() && parent.is_some_and(|parent| self.closed_up(layout, layer, parent))
|
||||
}
|
||||
|
||||
fn closed_up(&self, layout: &Layout, layer: NodeIndex, above: NodeIndex) -> bool {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
mod common;
|
||||
|
||||
use common::{at, layer, stacked, wire};
|
||||
use common::{CHAINED, at, layer, node, stacked, wire};
|
||||
use glam::IVec2;
|
||||
use graph_layout::{Drag, Graph, Layout, Placement};
|
||||
|
||||
@@ -73,3 +73,148 @@ fn a_layer_pushed_up_with_its_upstream_kept_carries_the_layer_above_from_the_fir
|
||||
assert_eq!(layout.node(at(2)).position, before.node(at(2)).position + IVec2::new(0, -2));
|
||||
assert_eq!(layout.node(at(1)).position, before.node(at(1)).position + IVec2::new(0, -2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_dragged_up_with_its_upstream_kept_carries_its_chain_and_leaves_its_stack() {
|
||||
let start = Graph {
|
||||
nodes: vec![
|
||||
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||
node(CHAINED),
|
||||
node(Placement::Relative(IVec2::new(-8, 0))),
|
||||
layer(stacked(0)),
|
||||
],
|
||||
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 0, 0)],
|
||||
};
|
||||
let before = Layout::new(&start);
|
||||
let offset = IVec2::new(0, -4);
|
||||
|
||||
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(0)], true).moved(offset);
|
||||
|
||||
for carried in [0, 1, 2] {
|
||||
assert_eq!(layout.node(at(carried)).position, before.node(at(carried)).position + offset);
|
||||
}
|
||||
assert_eq!(layout.node(at(3)).position, before.node(at(3)).position);
|
||||
}
|
||||
|
||||
fn stack_of_layers_with_chains() -> Graph {
|
||||
let layers = [layer(Placement::Absolute(IVec2::new(30, 10))), layer(stacked(0)), layer(stacked(0))];
|
||||
let chains = [node(CHAINED), node(CHAINED), node(CHAINED)];
|
||||
let stack_wires = [wire(1, 0, 0), wire(2, 1, 0)];
|
||||
let chain_wires = [wire(3, 0, 1), wire(4, 1, 1), wire(5, 2, 1)];
|
||||
Graph {
|
||||
nodes: layers.into_iter().chain(chains).collect(),
|
||||
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn moved_by_dragging(graph: &Graph, dragged: &[u32], offset: IVec2) -> Vec<u32> {
|
||||
let before = Layout::new(graph);
|
||||
let (_, layout) = Drag::new(graph.clone(), Layout::new(graph), dragged.iter().copied().map(at).collect(), true).moved(offset);
|
||||
let node_count = u32::try_from(graph.nodes.len()).unwrap();
|
||||
(0..node_count).filter(|index| layout.node(at(*index)).position != before.node(at(*index)).position).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_in_the_middle_of_a_stack_dragged_sideways_with_its_upstream_kept_moves_its_whole_stack() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1], IVec2::new(10, 0)), vec![0, 1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_chain_node_dragged_with_its_upstream_kept_moves_alone() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[4], IVec2::new(0, 10)), vec![4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_pushed_up_with_its_upstream_kept_carries_the_closed_up_layers_above_with_their_chains() {
|
||||
let graph = stack_of_layers_with_chains();
|
||||
let mut stack_with_one_more_below = graph.clone();
|
||||
stack_with_one_more_below.nodes.push(layer(stacked(0)));
|
||||
stack_with_one_more_below.wires.push(wire(6, 2, 0));
|
||||
|
||||
assert_eq!(moved_by_dragging(&stack_with_one_more_below, &[2], IVec2::new(0, -1)), vec![0, 1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_of_one_stack_dragged_down_together_with_their_upstream_kept_carry_their_chains() {
|
||||
assert_eq!(moved_by_dragging(&stack_of_layers_with_chains(), &[1, 2], IVec2::new(0, 4)), vec![1, 2, 4, 5]);
|
||||
}
|
||||
|
||||
fn artboard_holding_a_stack_of_layers_with_chains() -> Graph {
|
||||
let artboard = layer(Placement::Absolute(IVec2::new(30, 10)));
|
||||
let layers = [layer(Placement::Relative(IVec2::new(-8, 3))), layer(stacked(0)), layer(stacked(0)), layer(stacked(0))];
|
||||
let chains = (0..4).flat_map(|_| [node(CHAINED), node(CHAINED), node(CHAINED)]);
|
||||
let stack_wires = [wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 0), wire(4, 3, 0)];
|
||||
let chain_wires = (0..4).flat_map(|layer| {
|
||||
let first = 5 + layer * 3;
|
||||
[wire(first, layer + 1, 1), wire(first + 1, first, 0), wire(first + 2, first + 1, 0)]
|
||||
});
|
||||
Graph {
|
||||
nodes: [artboard].into_iter().chain(layers).chain(chains).collect(),
|
||||
wires: stack_wires.into_iter().chain(chain_wires).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn releasing_a_drag_draws_every_node_where_the_drag_drew_it() {
|
||||
let stack = artboard_holding_a_stack_of_layers_with_chains();
|
||||
let reading_a_tree = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||
let drags = [
|
||||
(&stack, vec![1, 2], IVec2::new(5, 0), true),
|
||||
(&stack, vec![1, 2], IVec2::new(5, 0), false),
|
||||
(&stack, vec![2], IVec2::new(5, 0), false),
|
||||
(&stack, vec![3], IVec2::new(0, -2), true),
|
||||
(&stack, vec![3], IVec2::new(0, 3), true),
|
||||
(&stack, vec![3], IVec2::new(0, -2), false),
|
||||
(&stack, vec![3], IVec2::new(0, 3), false),
|
||||
(&reading_a_tree, vec![2], IVec2::new(0, 3), true),
|
||||
(&reading_a_tree, vec![2], IVec2::new(5, 0), true),
|
||||
];
|
||||
for (start, dragged, offset, keep_upstream) in drags {
|
||||
let mut drag = Drag::new(start.clone(), Layout::new(start), dragged.iter().copied().map(at).collect(), keep_upstream);
|
||||
let (_, dragging) = drag.moved(offset);
|
||||
let released = Layout::new(&drag.released(offset));
|
||||
|
||||
let node_count = u32::try_from(start.nodes.len()).unwrap();
|
||||
let drawn = |layout: &Layout| (0..node_count).map(|index| layout.node(at(index)).position).collect::<Vec<_>>();
|
||||
assert_eq!(drawn(&released), drawn(&dragging), "dragging {dragged:?} by {offset} keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layers_closed_up_under_the_layer_holding_them_cannot_be_pushed_up_into_it() {
|
||||
let start = artboard_holding_a_stack_of_layers_with_chains();
|
||||
for keep_upstream in [false, true] {
|
||||
let (_, layout) = Drag::new(start.clone(), Layout::new(&start), vec![at(3)], keep_upstream).moved(IVec2::new(0, -2));
|
||||
assert_eq!(layout.node(at(1)).position, Layout::new(&start).node(at(1)).position, "keeping upstream: {keep_upstream}");
|
||||
}
|
||||
}
|
||||
|
||||
fn artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own() -> Graph {
|
||||
Graph {
|
||||
nodes: vec![
|
||||
layer(Placement::Absolute(IVec2::new(30, 10))),
|
||||
layer(Placement::Relative(IVec2::new(-8, 3))),
|
||||
layer(stacked(0)),
|
||||
node(CHAINED),
|
||||
node(Placement::Absolute(IVec2::new(0, 30))),
|
||||
node(CHAINED),
|
||||
],
|
||||
wires: vec![wire(1, 0, 1), wire(2, 1, 0), wire(3, 2, 1), wire(4, 3, 0), wire(5, 4, 0)],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_layer_dragged_with_its_upstream_kept_carries_the_trees_its_chain_reads() {
|
||||
let graph = artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own();
|
||||
|
||||
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(0, 3)), vec![2, 3, 4, 5]);
|
||||
assert_eq!(moved_by_dragging(&graph, &[2], IVec2::new(5, 0)), vec![1, 2, 3, 4, 5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_trees_a_blocked_layer_reads_stay_with_it() {
|
||||
assert_eq!(
|
||||
moved_by_dragging(&artboard_holding_a_layer_whose_chain_reads_a_tree_of_its_own(), &[2], IVec2::new(0, -2)),
|
||||
Vec::<u32>::new()
|
||||
);
|
||||
}
|
||||
@@ -542,9 +542,12 @@ tagged_value! {
|
||||
GlowTechnique(graphic_types::GlowTechnique),
|
||||
GlowSource(graphic_types::GlowSource),
|
||||
MaskMode(graphic_types::MaskMode),
|
||||
MinimumMaximumMode(graphic_types::MinimumMaximumMode),
|
||||
BevelStyle(graphic_types::BevelStyle),
|
||||
BevelDirection(graphic_types::BevelDirection),
|
||||
BevelTechnique(graphic_types::BevelTechnique),
|
||||
NoiseDistribution(graphic_types::NoiseDistribution),
|
||||
RadialBlurMethod(graphic_types::RadialBlurMethod),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -974,8 +977,6 @@ pub enum RenderOutputType {
|
||||
/// The images the SVG draws to canvases, by the canvas ID their placeholders name.
|
||||
image_data: Vec<(u64, CanvasImage)>,
|
||||
},
|
||||
#[cfg(target_family = "wasm")]
|
||||
CanvasFrame { canvas_id: u64, resolution: DVec2 },
|
||||
}
|
||||
|
||||
impl CacheHash for RenderOutputType {
|
||||
@@ -992,11 +993,6 @@ impl CacheHash for RenderOutputType {
|
||||
svg.cache_hash(state);
|
||||
image_data.cache_hash(state);
|
||||
}
|
||||
#[cfg(target_family = "wasm")]
|
||||
Self::CanvasFrame { canvas_id, resolution } => {
|
||||
canvas_id.cache_hash(state);
|
||||
resolution.cache_hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
[package]
|
||||
name = "graph-ui"
|
||||
description = "The node graph UI of Graphite, drawn by Graphene"
|
||||
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 }
|
||||
dyn-any = { workspace = true }
|
||||
graph-craft = { workspace = true }
|
||||
graph-ui-icons = { workspace = true }
|
||||
graphene-application-io = { workspace = true }
|
||||
graphene-hash = { workspace = true }
|
||||
graphene-std = { workspace = true }
|
||||
graphic-types = { workspace = true }
|
||||
node-macro = { workspace = true }
|
||||
rendering = { workspace = true }
|
||||
svg-convert = { workspace = true }
|
||||
text-nodes = { workspace = true }
|
||||
vector-types = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
glam = { workspace = true }
|
||||
vello_gpu = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
interpreted-executor = { workspace = true }
|
||||
preprocessor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
futures = { workspace = true }
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "graph-ui-icons"
|
||||
description = "The icons of the node graph UI of Graphite, as SVG sources"
|
||||
version.workspace = true
|
||||
license.workspace = true
|
||||
authors.workspace = true
|
||||
edition.workspace = true
|
||||
repository.workspace = true
|
||||
readme.workspace = true
|
||||
homepage.workspace = true
|
||||
rust-version.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,39 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
use std::fmt::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
const FOLDERS: [&str; 2] = ["16x16-nodes", "16x16-ui-general"];
|
||||
|
||||
fn main() {
|
||||
let root = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("../../..");
|
||||
let assets = root.join("branding/assets");
|
||||
|
||||
let mut sources = Vec::new();
|
||||
println!("cargo:rerun-if-changed={}", assets.display());
|
||||
if assets.is_dir() {
|
||||
for folder in FOLDERS {
|
||||
for entry in std::fs::read_dir(assets.join(folder)).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_some_and(|extension| extension == "svg") {
|
||||
sources.push((icon_name(&path.file_stem().unwrap().to_string_lossy()), path));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("cargo:warning=No branding folder, icons will be missing");
|
||||
}
|
||||
sources.sort();
|
||||
|
||||
let mut table = String::from("static SOURCES: &[(&str, &str)] = &[\n");
|
||||
for (name, path) in &sources {
|
||||
writeln!(table, "\t({name:?}, include_str!({:?})),", path.display().to_string()).unwrap();
|
||||
}
|
||||
table.push_str("];\n");
|
||||
std::fs::write(PathBuf::from(std::env::var("OUT_DIR").unwrap()).join("icons.rs"), table).unwrap();
|
||||
}
|
||||
|
||||
fn icon_name(file_stem: &str) -> String {
|
||||
let capitalized = |word: &str| word[..1].to_uppercase() + &word[1..];
|
||||
file_stem.split('-').filter(|word| !word.is_empty()).map(capitalized).collect()
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
include!(concat!(env!("OUT_DIR"), "/icons.rs"));
|
||||
|
||||
pub fn svg(name: &str) -> Option<&'static str> {
|
||||
let index = SOURCES.binary_search_by_key(&name, |&(name, _)| name).ok()?;
|
||||
Some(SOURCES[index].1)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_icons_are_found_by_the_names_the_frontend_gives_them() {
|
||||
let icons_ts = std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../frontend/src/icons.ts")).unwrap();
|
||||
let imported = icons_ts.lines().filter_map(|line| line.strip_prefix("import ")?.split_once(" from \"/../branding/assets/"));
|
||||
let names = imported
|
||||
.filter(|(_, path)| path.starts_with("16x16-nodes/") || path.starts_with("16x16-ui-general/"))
|
||||
.map(|(name, _)| name);
|
||||
let missing: Vec<_> = names.filter(|name| svg(name).is_none()).collect();
|
||||
assert!(SOURCES.is_empty() || missing.is_empty(), "{missing:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
use crate::metrics::{CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, NODE_WIDTH, OUTPUT_CONNECTOR_RIGHT};
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Card {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub name: String,
|
||||
pub icon: String,
|
||||
pub primary_input: Option<Connector>,
|
||||
pub primary_output: Option<Connector>,
|
||||
pub secondary_inputs: Vec<Connector>,
|
||||
pub secondary_outputs: Vec<Connector>,
|
||||
pub selection: Selection,
|
||||
pub visible: bool,
|
||||
pub previewed: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub enum Selection {
|
||||
None,
|
||||
Inactive,
|
||||
Active,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Connector {
|
||||
pub name: String,
|
||||
pub data_type: DataType,
|
||||
pub connected: bool,
|
||||
pub highlight: Highlight,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, CacheHash)]
|
||||
pub enum Highlight {
|
||||
#[default]
|
||||
None,
|
||||
Hovered,
|
||||
WireSource,
|
||||
WireTarget,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub enum DataType {
|
||||
General,
|
||||
Number,
|
||||
Artboard,
|
||||
Graphic,
|
||||
Raster,
|
||||
Vector,
|
||||
Color,
|
||||
Gradient,
|
||||
Typography,
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl Keyed for Card {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Card {
|
||||
pub fn rows(&self) -> usize {
|
||||
1 + self.secondary_inputs.len().max(self.secondary_outputs.len())
|
||||
}
|
||||
|
||||
pub fn body(&self) -> [DVec2; 2] {
|
||||
let top_left = (self.cell.as_dvec2() + DVec2::new(0., 0.5)) * GRID_SIZE + self.glide;
|
||||
[top_left, top_left + DVec2::new(NODE_WIDTH, self.rows() as f64 * GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn inputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||
self.connectors(&self.primary_input, &self.secondary_inputs, INPUT_CONNECTOR_LEFT)
|
||||
}
|
||||
|
||||
pub fn outputs(&self) -> impl Iterator<Item = (DVec2, &Connector)> {
|
||||
self.connectors(&self.primary_output, &self.secondary_outputs, NODE_WIDTH + OUTPUT_CONNECTOR_RIGHT - CONNECTOR_SIZE)
|
||||
}
|
||||
|
||||
fn connectors<'a>(&self, primary: &'a Option<Connector>, secondary: &'a [Connector], left: f64) -> impl Iterator<Item = (DVec2, &'a Connector)> {
|
||||
let [top_left, _] = self.body();
|
||||
let rows = primary
|
||||
.iter()
|
||||
.map(|connector| (0, connector))
|
||||
.chain(secondary.iter().enumerate().map(|(index, connector)| (index + 1, connector)));
|
||||
rows.map(move |(row, connector)| (top_left + DVec2::new(left, row as f64 * GRID_SIZE + (GRID_SIZE - CONNECTOR_SIZE) / 2.), connector))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::{card, connector};
|
||||
|
||||
#[test]
|
||||
fn a_node_body_is_five_cells_wide_and_starts_half_a_cell_below_its_cell() {
|
||||
let mut card = Card {
|
||||
cell: IVec2::new(2, -1),
|
||||
primary_output: Some(connector("Shape")),
|
||||
..card(0)
|
||||
};
|
||||
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 12.)]);
|
||||
|
||||
card.secondary_inputs = vec![connector("Width"), connector("Height")];
|
||||
card.secondary_outputs = vec![connector("Area")];
|
||||
assert_eq!(card.body(), [DVec2::new(48., -12.), DVec2::new(168., 60.)], "a row for each secondary input");
|
||||
|
||||
let top_left = |(top_left, _): (DVec2, &Connector)| top_left;
|
||||
assert_eq!(card.inputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(45., 20.), DVec2::new(45., 44.)], "no primary input");
|
||||
assert_eq!(card.outputs().map(top_left).collect::<Vec<_>>(), [DVec2::new(165., -4.), DVec2::new(165., 20.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gliding_card_is_drawn_its_glide_away() {
|
||||
let glide = DVec2::new(3., -4.);
|
||||
let gliding = Card { glide, ..card(0) };
|
||||
assert_eq!(gliding.body(), card(0).body().map(|corner| corner + glide));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
use crate::metrics::{BORDER_DASHES, BORDER_WIDTH};
|
||||
use glam::DVec2;
|
||||
use std::f64::consts::{FRAC_PI_2, PI};
|
||||
use std::ops::Range;
|
||||
use vello_gpu::kurbo::{Arc, BezPath, CubicBez, Line, ParamCurve, PathEl, PathSeg, Point, QuadBez};
|
||||
|
||||
const MEASURE_TOLERANCE: f64 = 0.5;
|
||||
const MEASURE_DEPTH: u32 = 20;
|
||||
const ARC_TOLERANCE: f64 = 0.1;
|
||||
|
||||
struct Measured {
|
||||
distance: f64,
|
||||
segment: usize,
|
||||
t: f64,
|
||||
}
|
||||
|
||||
pub(crate) fn dashed(path: &BezPath, [dash, gap]: [f64; 2]) -> BezPath {
|
||||
let mut dashes = BezPath::new();
|
||||
for contour in contours(path) {
|
||||
let measured = measure(&contour);
|
||||
let Some(length) = measured.last().map(|last| last.distance) else { continue };
|
||||
let mut distance = 0.;
|
||||
for (index, interval) in [dash, gap].into_iter().cycle().enumerate() {
|
||||
if distance >= length {
|
||||
break;
|
||||
}
|
||||
if index % 2 == 0 {
|
||||
piece(&contour, &measured, distance..(distance + interval).min(length), &mut dashes);
|
||||
}
|
||||
distance += interval;
|
||||
}
|
||||
}
|
||||
dashes
|
||||
}
|
||||
|
||||
fn contours(path: &BezPath) -> Vec<Vec<PathSeg>> {
|
||||
let mut contours: Vec<Vec<PathSeg>> = Vec::new();
|
||||
let (mut start, mut last) = (Point::ZERO, Point::ZERO);
|
||||
for element in path.elements() {
|
||||
let segment = match *element {
|
||||
PathEl::MoveTo(point) => {
|
||||
contours.push(Vec::new());
|
||||
(start, last) = (point, point);
|
||||
continue;
|
||||
}
|
||||
PathEl::LineTo(point) => PathSeg::Line(Line::new(last, point)),
|
||||
PathEl::QuadTo(control, point) => PathSeg::Cubic(QuadBez::new(last, control, point).raise()),
|
||||
PathEl::CurveTo(first, second, point) => PathSeg::Cubic(CubicBez::new(last, first, second, point)),
|
||||
PathEl::ClosePath => PathSeg::Line(Line::new(last, start)),
|
||||
};
|
||||
last = segment.end();
|
||||
if let Some(contour) = contours.last_mut() {
|
||||
contour.push(segment);
|
||||
}
|
||||
}
|
||||
contours
|
||||
}
|
||||
|
||||
fn measure(contour: &[PathSeg]) -> Vec<Measured> {
|
||||
let mut measured = Vec::new();
|
||||
let mut distance = 0.;
|
||||
for (segment, piece) in contour.iter().enumerate() {
|
||||
distance = match piece {
|
||||
PathSeg::Cubic(cubic) => measure_cubic(*cubic, distance, 0_f64..1., MEASURE_DEPTH, segment, &mut measured),
|
||||
_ => chord(piece.start(), piece.end(), distance, segment, 1., &mut measured),
|
||||
};
|
||||
}
|
||||
measured
|
||||
}
|
||||
|
||||
fn measure_cubic(cubic: CubicBez, distance: f64, range: Range<f64>, depth: u32, segment: usize, measured: &mut Vec<Measured>) -> f64 {
|
||||
let strays = |control: Point, fraction: f64| {
|
||||
let on_chord = cubic.p0.lerp(cubic.p3, fraction);
|
||||
(control.x - on_chord.x).abs().max((control.y - on_chord.y).abs()) > MEASURE_TOLERANCE
|
||||
};
|
||||
if depth == 0 || !(strays(cubic.p1, 1. / 3.) || strays(cubic.p2, 2. / 3.)) {
|
||||
return chord(cubic.p0, cubic.p3, distance, segment, range.end, measured);
|
||||
}
|
||||
let (first, second) = cubic.subdivide();
|
||||
let middle = (range.start + range.end) / 2.;
|
||||
let distance = measure_cubic(first, distance, range.start..middle, depth - 1, segment, measured);
|
||||
measure_cubic(second, distance, middle..range.end, depth - 1, segment, measured)
|
||||
}
|
||||
|
||||
fn chord(from: Point, to: Point, distance: f64, segment: usize, t: f64, measured: &mut Vec<Measured>) -> f64 {
|
||||
let next = distance + from.distance(to);
|
||||
if next > distance {
|
||||
measured.push(Measured { distance: next, segment, t });
|
||||
}
|
||||
next
|
||||
}
|
||||
|
||||
fn at(measured: &[Measured], distance: f64) -> (usize, f64) {
|
||||
let index = measured.partition_point(|entry| entry.distance < distance).min(measured.len() - 1);
|
||||
let entry = &measured[index];
|
||||
let (start_distance, start_t) = match index.checked_sub(1).map(|previous| &measured[previous]) {
|
||||
Some(previous) if previous.segment == entry.segment => (previous.distance, previous.t),
|
||||
Some(previous) => (previous.distance, 0.),
|
||||
None => (0., 0.),
|
||||
};
|
||||
(entry.segment, start_t + (entry.t - start_t) * (distance - start_distance) / (entry.distance - start_distance))
|
||||
}
|
||||
|
||||
fn piece(contour: &[PathSeg], measured: &[Measured], range: Range<f64>, dashes: &mut BezPath) {
|
||||
let (start_segment, start_t) = at(measured, range.start);
|
||||
let (end_segment, end_t) = at(measured, range.end);
|
||||
dashes.move_to(contour[start_segment].eval(start_t));
|
||||
let mut push = |segment: usize, range: Range<f64>| match contour[segment].subsegment(range) {
|
||||
PathSeg::Line(line) => dashes.line_to(line.p1),
|
||||
PathSeg::Quad(quad) => dashes.quad_to(quad.p1, quad.p2),
|
||||
PathSeg::Cubic(cubic) => dashes.curve_to(cubic.p1, cubic.p2, cubic.p3),
|
||||
};
|
||||
if start_segment == end_segment {
|
||||
push(start_segment, start_t..end_t);
|
||||
return;
|
||||
}
|
||||
push(start_segment, start_t..1.);
|
||||
for segment in start_segment + 1..end_segment {
|
||||
push(segment, 0. ..1.);
|
||||
}
|
||||
push(end_segment, 0. ..end_t);
|
||||
}
|
||||
|
||||
enum BorderPart {
|
||||
Line(DVec2, DVec2),
|
||||
Corner(DVec2, f64),
|
||||
}
|
||||
|
||||
pub(crate) fn border(min: DVec2, max: DVec2, radius: f64, gaps: &[[DVec2; 2]], dashed: bool) -> BezPath {
|
||||
let inset = BORDER_WIDTH / 2.;
|
||||
let arc_radius = radius - inset;
|
||||
let corner_length = flattened_arc_length(radius, [0., FRAC_PI_2]);
|
||||
let [left, top] = (min + inset).to_array();
|
||||
let [right, bottom] = (max - inset).to_array();
|
||||
let parts = [
|
||||
BorderPart::Line(DVec2::new(left + arc_radius, top), DVec2::new(right - arc_radius, top)),
|
||||
BorderPart::Corner(DVec2::new(right - arc_radius, top + arc_radius), -FRAC_PI_2),
|
||||
BorderPart::Line(DVec2::new(right, top + arc_radius), DVec2::new(right, bottom - arc_radius)),
|
||||
BorderPart::Corner(DVec2::new(right - arc_radius, bottom - arc_radius), 0.),
|
||||
BorderPart::Line(DVec2::new(right - arc_radius, bottom), DVec2::new(left + arc_radius, bottom)),
|
||||
BorderPart::Corner(DVec2::new(left + arc_radius, bottom - arc_radius), FRAC_PI_2),
|
||||
BorderPart::Line(DVec2::new(left, bottom - arc_radius), DVec2::new(left, top + arc_radius)),
|
||||
BorderPart::Corner(DVec2::new(left + arc_radius, top + arc_radius), PI),
|
||||
];
|
||||
let length = |part: &BorderPart| match part {
|
||||
BorderPart::Line(from, to) => from.distance(*to),
|
||||
BorderPart::Corner(..) => corner_length,
|
||||
};
|
||||
let point = |part: &BorderPart, fraction: f64| match *part {
|
||||
BorderPart::Line(from, to) => from.lerp(to, fraction),
|
||||
BorderPart::Corner(center, start_angle) => center + arc_radius * DVec2::from_angle(start_angle + fraction * FRAC_PI_2),
|
||||
};
|
||||
let starts: Vec<f64> = parts.iter().scan(0., |start, part| Some(std::mem::replace(start, *start + length(part)))).collect();
|
||||
let perimeter: f64 = parts.iter().map(length).sum();
|
||||
|
||||
let mut left_out: Vec<[f64; 2]> = parts
|
||||
.iter()
|
||||
.zip(&starts)
|
||||
.flat_map(|(part, &start)| {
|
||||
let straight = matches!(part, BorderPart::Line(..));
|
||||
let inside = gaps.iter().filter_map(move |&gap| fractions_inside(|fraction| point(part, fraction), straight, gap));
|
||||
inside.map(move |[from, to]| [start + from * length(part), start + to * length(part)])
|
||||
})
|
||||
.collect();
|
||||
left_out.sort_by(|a, b| a[0].total_cmp(&b[0]));
|
||||
|
||||
let shown = if dashed {
|
||||
let [dash, gap] = BORDER_DASHES;
|
||||
let length = perimeter.floor();
|
||||
let fewer = (length / (dash + gap)).floor();
|
||||
let gaps = [fewer, fewer + 1.].map(|count| (length - count * dash) / count);
|
||||
let (count, gap) = if gaps[1] > 0. && (gaps[1] - gap).abs() <= (gaps[0] - gap).abs() {
|
||||
(fewer + 1., gaps[1])
|
||||
} else {
|
||||
(fewer, gaps[0])
|
||||
};
|
||||
(0..count as usize).map(|index| [index as f64 * (dash + gap), index as f64 * (dash + gap) + dash]).collect()
|
||||
} else {
|
||||
vec![[0., perimeter]]
|
||||
};
|
||||
let visible = shown.into_iter().flat_map(|[mut from, to]| {
|
||||
let mut pieces = Vec::new();
|
||||
for &[gap_from, gap_to] in &left_out {
|
||||
if gap_from < to && gap_to > from {
|
||||
pieces.extend((gap_from > from).then_some([from, gap_from]));
|
||||
from = from.max(gap_to);
|
||||
}
|
||||
}
|
||||
pieces.extend((from < to).then_some([from, to]));
|
||||
pieces
|
||||
});
|
||||
|
||||
let mut border = BezPath::new();
|
||||
for [from, to] in visible {
|
||||
let mut started = false;
|
||||
for (part, start) in parts.iter().zip(&starts) {
|
||||
if length(part) == 0. {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = [from, to].map(|at| ((at - start) / length(part)).clamp(0., 1.));
|
||||
if b <= a {
|
||||
continue;
|
||||
}
|
||||
if !started {
|
||||
border.move_to(<(f64, f64)>::from(point(part, a)));
|
||||
started = true;
|
||||
}
|
||||
match *part {
|
||||
BorderPart::Line(..) => border.line_to(<(f64, f64)>::from(point(part, b))),
|
||||
BorderPart::Corner(center, start_angle) => {
|
||||
border.extend(Arc::new(<(f64, f64)>::from(center), (arc_radius, arc_radius), start_angle + a * FRAC_PI_2, (b - a) * FRAC_PI_2, 0.).append_iter(ARC_TOLERANCE))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
border
|
||||
}
|
||||
|
||||
fn flattened_arc_length(radius: f64, [from, to]: [f64; 2]) -> f64 {
|
||||
let point = |angle: f64| radius * DVec2::from_angle(angle);
|
||||
let middle = (from + to) / 2.;
|
||||
let bulge = point(middle) - (point(from) + point(to)) / 2.;
|
||||
if bulge.abs().max_element() > MEASURE_TOLERANCE {
|
||||
flattened_arc_length(radius, [from, middle]) + flattened_arc_length(radius, [middle, to])
|
||||
} else {
|
||||
point(from).distance(point(to))
|
||||
}
|
||||
}
|
||||
|
||||
fn fractions_inside(point: impl Fn(f64) -> DVec2, straight: bool, [low, high]: [DVec2; 2]) -> Option<[f64; 2]> {
|
||||
let mut range = [0_f64, 1_f64];
|
||||
for axis in 0..2 {
|
||||
let value = |fraction: f64| point(fraction)[axis];
|
||||
let [start, end] = [value(0.), value(1.)];
|
||||
if start.min(end) > high[axis] || start.max(end) < low[axis] {
|
||||
return None;
|
||||
}
|
||||
if start == end {
|
||||
continue;
|
||||
}
|
||||
let fraction_at = |bound: f64| {
|
||||
if (bound - start) * (end - start) <= 0. {
|
||||
return 0.;
|
||||
}
|
||||
if (bound - end) * (end - start) >= 0. {
|
||||
return 1.;
|
||||
}
|
||||
if straight {
|
||||
return (bound - start) / (end - start);
|
||||
}
|
||||
let [mut before, mut after] = [0_f64, 1_f64];
|
||||
for _ in 0..f64::MANTISSA_DIGITS {
|
||||
let middle = (before + after) / 2.;
|
||||
if (value(middle) - bound) * (end - start) < 0. {
|
||||
before = middle;
|
||||
} else {
|
||||
after = middle;
|
||||
}
|
||||
}
|
||||
after
|
||||
};
|
||||
let [a, b] = [fraction_at(low[axis]), fraction_at(high[axis])];
|
||||
range = [range[0].max(a.min(b)), range[1].min(a.max(b))];
|
||||
}
|
||||
(range[0] < range[1]).then_some(range)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use vello_gpu::kurbo::Shape;
|
||||
|
||||
#[test]
|
||||
fn dashes_start_at_the_start_of_each_contour_and_are_cut_at_its_end() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0., 0.));
|
||||
path.line_to((12., 0.));
|
||||
path.move_to((0., 10.));
|
||||
path.line_to((4., 10.));
|
||||
let starts: Vec<Point> = dashed(&path, [3., 2.])
|
||||
.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
|
||||
.collect();
|
||||
assert_eq!(starts, [(0., 0.), (5., 0.), (10., 0.), (0., 10.)].map(Point::from));
|
||||
let ends: Vec<Point> = dashed(&path, [3., 2.])
|
||||
.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::LineTo(point) = element { Some(*point) } else { None })
|
||||
.collect();
|
||||
assert_eq!(ends, [(3., 0.), (8., 0.), (12., 0.), (3., 10.)].map(Point::from));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_curve_is_measured_along_chords_that_stray_from_it_by_at_most_half_a_pixel() {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((0., 0.));
|
||||
path.curve_to((0., 100.), (100., 100.), (100., 0.));
|
||||
let measured = measure(&contours(&path)[0]);
|
||||
let measured_length = measured.last().unwrap().distance;
|
||||
let length = vello_gpu::kurbo::ParamCurveArclen::arclen(&CubicBez::new((0., 0.), (0., 100.), (100., 100.), (100., 0.)), 1e-9);
|
||||
assert!(measured_length < length && length - measured_length < 1., "{measured_length} {length}");
|
||||
assert!(measured.windows(2).all(|pair| pair[0].t < pair[1].t), "the chords follow the curve");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_dashes_of_a_border_follow_its_outer_edge_with_flattened_corners_and_the_gap_nearest_two_pixels() {
|
||||
let starts = |path: &BezPath| {
|
||||
path.elements()
|
||||
.iter()
|
||||
.filter_map(|element| if let PathEl::MoveTo(point) = element { Some(*point) } else { None })
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let layer = starts(&border(DVec2::ZERO, DVec2::new(912., 48.), 8., &[], true));
|
||||
let on_top = layer.iter().filter(|point| point.y == 0.5).map(|point| point.x);
|
||||
assert!(
|
||||
on_top.clone().all(|x| ((x - 8.) / 5. - ((x - 8.) / 5.).round()).abs() < 1e-9),
|
||||
"the dashes along the top of a layer are five pixels apart"
|
||||
);
|
||||
assert_eq!(on_top.count(), 180);
|
||||
assert_eq!(layer.len(), 381);
|
||||
|
||||
assert_eq!(
|
||||
starts(&border(DVec2::ZERO, DVec2::new(120., 72.), 2., &[], true)).len(),
|
||||
76,
|
||||
"a node card, its corners measured as chords"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_border_is_left_out_inside_its_gaps_corners_included() {
|
||||
let [min, max] = [DVec2::ZERO, DVec2::new(100., 48.)];
|
||||
let starts = |path: &BezPath| path.elements().iter().filter(|element| matches!(element, PathEl::MoveTo(_))).count();
|
||||
assert_eq!(starts(&border(min, max, 8., &[], false)), 1);
|
||||
|
||||
let left = [DVec2::new(-8., -2.), DVec2::new(30., 50.)];
|
||||
let right = [DVec2::new(88., 12.), DVec2::new(112., 36.)];
|
||||
let cut = border(min, max, 8., &[left, right], false);
|
||||
assert_eq!(starts(&cut), 2, "the right gap splits what the left gap leaves");
|
||||
let bounds = cut.bounding_box();
|
||||
assert!((bounds.x0 - 30.).abs() < 1e-9 && bounds.x1 == 99.5, "{bounds:?}");
|
||||
let on_the_right = cut.elements().iter().filter_map(|element| element.end_point()).filter(|point| point.x == 99.5);
|
||||
assert!(
|
||||
on_the_right.clone().all(|point| !(12.001..=35.999).contains(&point.y)),
|
||||
"the right gap leaves out the middle of the right side"
|
||||
);
|
||||
assert!(on_the_right.clone().any(|point| (point.y - 12.).abs() < 1e-9) && on_the_right.clone().any(|point| (point.y - 36.).abs() < 1e-9));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use crate::card::{DataType, Highlight};
|
||||
use crate::metrics::GRID_SIZE;
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Dot {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub data_type: DataType,
|
||||
pub wired: bool,
|
||||
pub selected: bool,
|
||||
pub previewed: bool,
|
||||
pub highlight: Highlight,
|
||||
pub output_highlight: Highlight,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for Dot {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Dot {
|
||||
pub fn center(&self) -> DVec2 {
|
||||
(self.cell.as_dvec2() + DVec2::Y) * GRID_SIZE + self.glide
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::dot;
|
||||
|
||||
#[test]
|
||||
fn a_dot_sits_on_the_left_edge_of_its_cell_a_cell_down() {
|
||||
let dot = Dot { cell: IVec2::new(2, -1), ..dot(0) };
|
||||
assert_eq!(dot.center(), DVec2::new(48., 0.));
|
||||
let gliding = Dot { glide: DVec2::new(3., -4.), ..dot };
|
||||
assert_eq!(gliding.center(), DVec2::new(51., -4.), "a gliding dot is drawn its glide away");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use crate::metrics::{ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_PADDING, ERROR_TAIL_LEFT, ERROR_TAIL_SIZE, GRID_SIZE, LAYER_LEFT_MARGIN};
|
||||
use crate::replicated_map::Keyed;
|
||||
use crate::text;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct ErrorBadge {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub on_layer: bool,
|
||||
pub text: String,
|
||||
pub hovered: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for ErrorBadge {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl ErrorBadge {
|
||||
fn anchor(&self) -> DVec2 {
|
||||
let offset = if self.on_layer { DVec2::new(LAYER_LEFT_MARGIN, -GRID_SIZE / 2.) } else { DVec2::ZERO };
|
||||
self.cell.as_dvec2() * GRID_SIZE + offset + self.glide
|
||||
}
|
||||
|
||||
pub fn text_size(&self) -> DVec2 {
|
||||
text::paragraph_size(&self.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)
|
||||
}
|
||||
|
||||
pub fn body(&self, text_size: DVec2) -> [DVec2; 2] {
|
||||
let bottom_left = self.anchor();
|
||||
let size = text_size + 2. * ERROR_PADDING;
|
||||
[bottom_left - DVec2::Y * size.y, bottom_left + DVec2::X * size.x]
|
||||
}
|
||||
|
||||
pub fn text_top_left(&self, text_size: DVec2) -> DVec2 {
|
||||
let [top_left, _] = self.body(text_size);
|
||||
top_left + ERROR_PADDING
|
||||
}
|
||||
|
||||
pub fn tail(&self) -> [DVec2; 3] {
|
||||
let top_left = self.anchor() + DVec2::X * ERROR_TAIL_LEFT;
|
||||
[top_left, top_left + DVec2::X * ERROR_TAIL_SIZE.x, top_left + DVec2::new(ERROR_TAIL_SIZE.x / 2., ERROR_TAIL_SIZE.y)]
|
||||
}
|
||||
|
||||
pub fn covers(&self, point: DVec2, text_size: DVec2) -> bool {
|
||||
let [tail, ..] = self.tail();
|
||||
let within = |[min, max]: [DVec2; 2]| min.cmple(point).all() && point.cmple(max).all();
|
||||
within(self.body(text_size)) || within([tail, tail + ERROR_TAIL_SIZE])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::badge;
|
||||
|
||||
#[test]
|
||||
fn a_badge_stands_half_a_cell_above_its_card_or_above_the_thumbnail_of_its_layer() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(13, 22),
|
||||
..badge(0, "")
|
||||
};
|
||||
assert_eq!(badge.anchor(), DVec2::new(312., 528.));
|
||||
let on_layer = ErrorBadge { on_layer: true, ..badge };
|
||||
assert_eq!(on_layer.anchor(), DVec2::new(324., 516.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_badge_grows_up_and_right_from_its_anchor_with_its_tail_below() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(2, 1),
|
||||
..badge(0, "")
|
||||
};
|
||||
let text_size = DVec2::new(100., 36.);
|
||||
assert_eq!(badge.body(text_size), [DVec2::new(48., -28.), DVec2::new(164., 24.)]);
|
||||
assert_eq!(badge.text_top_left(text_size), DVec2::new(56., -20.), "the text is padded");
|
||||
assert_eq!(badge.tail(), [DVec2::new(54., 24.), DVec2::new(66., 24.), DVec2::new(60., 32.)]);
|
||||
let glide = DVec2::new(3., -4.);
|
||||
let gliding = ErrorBadge { glide, ..badge.clone() };
|
||||
assert_eq!(gliding.body(text_size), badge.body(text_size).map(|corner| corner + glide), "a gliding badge is drawn its glide away");
|
||||
assert_eq!(gliding.tail(), badge.tail().map(|corner| corner + glide), "its tail glides with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_badge_covers_its_box_and_the_box_around_its_tail() {
|
||||
let badge = ErrorBadge {
|
||||
cell: IVec2::new(2, 1),
|
||||
..badge(0, "Error")
|
||||
};
|
||||
let text_size = badge.text_size();
|
||||
let covers = |point| badge.covers(point, text_size);
|
||||
let [min, max] = badge.body(text_size);
|
||||
assert!(covers(min) && covers(max - 1.) && covers((min + max) / 2.), "the box");
|
||||
assert!(covers(DVec2::new(55., 31.)), "beside the tip of the tail, inside the box around it");
|
||||
assert!(!covers(DVec2::new(52., 30.)), "left of the tail");
|
||||
assert!(!covers(max + 1.), "beyond the box");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
// TODO(Timon): Replace with generalized icon crate
|
||||
|
||||
use crate::card::DataType;
|
||||
use crate::look::data_type_colors;
|
||||
use crate::metrics::ICON_SIZE;
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::List;
|
||||
use glam::DAffine2;
|
||||
use graphic_types::{IntoGraphicList, Vector};
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Write;
|
||||
use std::sync::{LazyLock, Mutex};
|
||||
use svg_convert::Options;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Icon {
|
||||
pub(crate) shapes: List<Vector>,
|
||||
pub(crate) overflows: bool,
|
||||
}
|
||||
|
||||
type Converted = HashMap<SRGBA8, HashMap<String, Option<Icon>>>;
|
||||
|
||||
static CONVERTED: LazyLock<Mutex<Converted>> = LazyLock::new(Mutex::default);
|
||||
|
||||
pub fn icon(name: &str, current: SRGBA8) -> Option<Icon> {
|
||||
let mut converted = CONVERTED.lock().unwrap();
|
||||
let converted = converted.entry(current).or_default();
|
||||
if let Some(icon) = converted.get(name) {
|
||||
return icon.clone();
|
||||
}
|
||||
let icon = graph_ui_icons::svg(name).and_then(|svg| convert(svg, current));
|
||||
converted.insert(name.to_string(), icon.clone());
|
||||
icon
|
||||
}
|
||||
|
||||
fn convert(svg: &str, current: SRGBA8) -> Option<Icon> {
|
||||
let mut style_sheet = format!("svg {{ fill: {}; }}", hex_color(current));
|
||||
for (class, _) in svg.split("class=\"").skip(1).filter_map(|rest| rest.split_once('"')) {
|
||||
write!(style_sheet, " .{class} {{ fill: {}; }}", hex_color(class_color(class)?)).unwrap();
|
||||
}
|
||||
let options = Options {
|
||||
style_sheet: Some(style_sheet),
|
||||
..Options::default()
|
||||
};
|
||||
let shapes: List<Vector> = svg_convert::convert(svg, &options).ok()?.into_flattened_list();
|
||||
|
||||
let overflows = match shapes.bounding_box(DAffine2::IDENTITY, false) {
|
||||
RenderBoundingBox::Rectangle([min, max]) => min.min_element() < 0. || max.max_element() > ICON_SIZE,
|
||||
RenderBoundingBox::Infinite => true,
|
||||
RenderBoundingBox::None => false,
|
||||
};
|
||||
Some(Icon { shapes, overflows })
|
||||
}
|
||||
|
||||
fn hex_color(color: SRGBA8) -> String {
|
||||
format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue)
|
||||
}
|
||||
|
||||
fn class_color(class: &str) -> Option<SRGBA8> {
|
||||
let token = class.strip_prefix("color-")?;
|
||||
let Some(mix) = token.strip_prefix("mix-") else { return token_color(token) };
|
||||
let (pair, percent) = mix.rsplit_once('-')?;
|
||||
let percent: u16 = percent.parse().ok().filter(|&percent| percent <= 100)?;
|
||||
let (a, b) = pair.match_indices('-').find_map(|(index, _)| Some((token_color(&pair[..index])?, token_color(&pair[index + 1..])?)))?;
|
||||
let mix = |a: u8, b: u8| ((u16::from(a) * (100 - percent) + u16::from(b) * percent + 50) / 100) as u8;
|
||||
Some(SRGBA8::new_opaque(mix(a.red, b.red), mix(a.green, b.green), mix(a.blue, b.blue)))
|
||||
}
|
||||
|
||||
fn token_color(token: &str) -> Option<SRGBA8> {
|
||||
if let Some((digit, _)) = token.split_once('-').filter(|(digit, _)| digit.len() == 1) {
|
||||
let value = u8::from_str_radix(digit, 16).ok()? * 0x11;
|
||||
return Some(SRGBA8::new_opaque(value, value, value));
|
||||
}
|
||||
let (name, dim) = token.strip_suffix("-dim").map_or((token, false), |name| (name, true));
|
||||
let data_type = match name {
|
||||
"general" => DataType::General,
|
||||
"number" => DataType::Number,
|
||||
"artboard" => DataType::Artboard,
|
||||
"graphic" => DataType::Graphic,
|
||||
"raster" => DataType::Raster,
|
||||
"vector" => DataType::Vector,
|
||||
"color" => DataType::Color,
|
||||
"gradient" => DataType::Gradient,
|
||||
"typography" => DataType::Typography,
|
||||
_ => return None,
|
||||
};
|
||||
let [bright, dimmed] = data_type_colors(data_type);
|
||||
Some(if dim { dimmed } else { bright })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::list::ATTR_APPEARANCE;
|
||||
use graphic_types::{Appearance, Cover, Graphic};
|
||||
|
||||
const CURRENT: SRGBA8 = SRGBA8::new_opaque(0x12, 0x34, 0x56);
|
||||
|
||||
fn icon(shapes: &str) -> Option<Icon> {
|
||||
convert(&format!(r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16">{shapes}</svg>"#), CURRENT)
|
||||
}
|
||||
|
||||
fn hex(color: Option<SRGBA8>) -> Option<String> {
|
||||
color.map(|color| format!("{:02x}{:02x}{:02x}", color.red, color.green, color.blue))
|
||||
}
|
||||
|
||||
fn fills(icon: &Icon) -> Vec<Option<String>> {
|
||||
let fill = |index| match icon.shapes.attribute::<Appearance>(ATTR_APPEARANCE, index)?.first_paint_of(Cover::Fill)? {
|
||||
Graphic::Color(color) => hex(Some(SRGBA8::from(*color.element()))),
|
||||
_ => None,
|
||||
};
|
||||
(0..icon.shapes.len()).map(fill).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_color_class_names_its_color() {
|
||||
assert_eq!(hex(class_color("color-8-uppergray")).as_deref(), Some("888888"));
|
||||
assert_eq!(hex(class_color("color-number-dim")).as_deref(), Some("886b60"));
|
||||
assert_eq!(hex(class_color("color-mix-gradient-gradient-dim-85")).as_deref(), Some("7651a7"));
|
||||
assert_eq!(hex(class_color("color-mix-raster-dim-7-middlegray-50")).as_deref(), Some("89795d"));
|
||||
assert_eq!(class_color("color-sepia"), None);
|
||||
assert_eq!(class_color("color-mix-general-sepia-50"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_is_its_shapes_in_document_order_filled_with_their_class_colors_or_the_current_color() {
|
||||
let icon = icon(r#"<path class="color-number" d="M2,2L14,2L14,14Z" /><circle cx="8" cy="8" r="2" />"#).unwrap();
|
||||
assert_eq!(fills(&icon), [Some("c9a699".to_string()), hex(Some(CURRENT))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_overflows_when_a_shape_reaches_past_its_box() {
|
||||
assert!(!icon(r#"<rect x="2" y="2" width="12" height="12" />"#).unwrap().overflows);
|
||||
assert!(icon(r#"<path d="M14,2L17,2L17,5L14,5Z" />"#).unwrap().overflows);
|
||||
assert!(
|
||||
icon(r#"<rect transform="translate(4)" x="2" y="2" width="12" height="12" />"#).unwrap().overflows,
|
||||
"moved out by its transform"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_icon_with_an_unknown_color_class_is_left_out() {
|
||||
assert!(icon(r#"<path class="color-sepia" d="M2,2L14,2Z" />"#).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
use crate::card::{Connector, Selection};
|
||||
use crate::metrics::{
|
||||
CONNECTOR_SIZE, GRID_SIZE, INPUT_CONNECTOR_LEFT, LAYER_BUTTON_SIZE, LAYER_DETAILS_MARGIN, LAYER_GRIP_WIDTH, LAYER_HEIGHT, LAYER_LEFT_MARGIN, LAYER_NAME_LEFT, LAYER_THUMBNAIL_IMAGE_INSET,
|
||||
LAYER_THUMBNAIL_MARGIN, LAYER_THUMBNAIL_WIDTH, STACK_CONNECTOR_SIZE,
|
||||
};
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Layer {
|
||||
pub key: NodeId,
|
||||
pub cell: IVec2,
|
||||
pub name: String,
|
||||
pub renaming: bool,
|
||||
pub width: u32,
|
||||
pub chain_width: u32,
|
||||
pub has_left_input_wire: bool,
|
||||
pub primary_input: Option<Connector>,
|
||||
pub primary_output: Option<Connector>,
|
||||
pub secondary_input: Option<Connector>,
|
||||
pub primary_input_connected_to_layer: bool,
|
||||
pub primary_output_connected_to_layer: bool,
|
||||
pub visible: bool,
|
||||
pub locked: bool,
|
||||
pub read_only: bool,
|
||||
pub selection: Selection,
|
||||
pub previewed: bool,
|
||||
pub hovered_button: Option<LayerButton>,
|
||||
pub hovered_button_clicked: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub enum LayerButton {
|
||||
Visibility,
|
||||
Lock,
|
||||
Grip,
|
||||
}
|
||||
|
||||
impl Keyed for Layer {
|
||||
type Key = NodeId;
|
||||
|
||||
fn key(&self) -> NodeId {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
impl Layer {
|
||||
fn top_left(&self) -> DVec2 {
|
||||
self.cell.as_dvec2() * GRID_SIZE + self.glide
|
||||
}
|
||||
|
||||
pub fn body(&self) -> [DVec2; 2] {
|
||||
let top_left = self.top_left();
|
||||
let left = if self.chain_width > 0 { -(self.chain_width as f64) * GRID_SIZE } else { LAYER_LEFT_MARGIN };
|
||||
[top_left + DVec2::X * left, top_left + DVec2::new(self.width as f64 * GRID_SIZE, LAYER_HEIGHT)]
|
||||
}
|
||||
|
||||
pub fn left_input_wire(&self) -> Option<DVec2> {
|
||||
let [min, _] = self.body();
|
||||
(self.has_left_input_wire && self.chain_width > 0).then(|| DVec2::new(min.x, min.y + LAYER_HEIGHT / 2.))
|
||||
}
|
||||
|
||||
pub fn thumbnail_block(&self) -> [DVec2; 2] {
|
||||
let left = self.top_left() + DVec2::X * LAYER_LEFT_MARGIN;
|
||||
[left, left + DVec2::new(LAYER_THUMBNAIL_WIDTH, LAYER_HEIGHT)]
|
||||
}
|
||||
|
||||
pub fn thumbnail(&self) -> [DVec2; 2] {
|
||||
let [min, max] = self.thumbnail_block();
|
||||
[min + DVec2::X * LAYER_THUMBNAIL_MARGIN, max - DVec2::X * LAYER_THUMBNAIL_MARGIN]
|
||||
}
|
||||
|
||||
pub fn thumbnail_image(&self) -> [DVec2; 2] {
|
||||
let [min, max] = self.thumbnail();
|
||||
[min + LAYER_THUMBNAIL_IMAGE_INSET, max - LAYER_THUMBNAIL_IMAGE_INSET]
|
||||
}
|
||||
|
||||
pub fn stack_output(&self) -> DVec2 {
|
||||
let [min, max] = self.thumbnail_block();
|
||||
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., min.y - STACK_CONNECTOR_SIZE.y)
|
||||
}
|
||||
|
||||
pub fn stack_input(&self) -> DVec2 {
|
||||
let [min, max] = self.thumbnail_block();
|
||||
DVec2::new((min.x + max.x - STACK_CONNECTOR_SIZE.x) / 2., max.y)
|
||||
}
|
||||
|
||||
pub fn secondary_input_connector(&self) -> DVec2 {
|
||||
self.top_left() + DVec2::new(INPUT_CONNECTOR_LEFT, (LAYER_HEIGHT - CONNECTOR_SIZE) / 2.)
|
||||
}
|
||||
|
||||
pub fn name_box(&self) -> [DVec2; 2] {
|
||||
let top_left = self.top_left() + DVec2::new(LAYER_NAME_LEFT, (LAYER_HEIGHT - GRID_SIZE) / 2.);
|
||||
[top_left, top_left + DVec2::new(self.name_width(), GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn name_width(&self) -> f64 {
|
||||
self.width as f64 * GRID_SIZE - LAYER_NAME_LEFT - LAYER_DETAILS_MARGIN
|
||||
}
|
||||
|
||||
pub fn visibility(&self) -> [DVec2; 2] {
|
||||
let [_, max] = self.body();
|
||||
let top_left = DVec2::new(max.x - LAYER_BUTTON_SIZE / 2., self.top_left().y + (LAYER_HEIGHT - LAYER_BUTTON_SIZE) / 2.);
|
||||
[top_left, top_left + LAYER_BUTTON_SIZE]
|
||||
}
|
||||
|
||||
pub fn grip(&self) -> [DVec2; 2] {
|
||||
let [right_of_grip, _] = self.lock().unwrap_or(self.visibility());
|
||||
[right_of_grip - DVec2::X * LAYER_GRIP_WIDTH, right_of_grip + DVec2::Y * LAYER_BUTTON_SIZE]
|
||||
}
|
||||
|
||||
pub fn lock(&self) -> Option<[DVec2; 2]> {
|
||||
let [min, max] = self.visibility();
|
||||
self.locked.then(|| [min - DVec2::X * LAYER_BUTTON_SIZE, max - DVec2::X * LAYER_BUTTON_SIZE])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::layer;
|
||||
|
||||
#[test]
|
||||
fn a_layer_spans_its_width_from_half_a_cell_into_its_cell() {
|
||||
let layer = Layer {
|
||||
cell: IVec2::new(2, -1),
|
||||
has_left_input_wire: true,
|
||||
..layer(0)
|
||||
};
|
||||
assert_eq!(layer.body(), [DVec2::new(60., -24.), DVec2::new(240., 24.)]);
|
||||
assert_eq!(layer.thumbnail_block(), [DVec2::new(60., -24.), DVec2::new(132., 24.)]);
|
||||
assert_eq!(layer.thumbnail(), [DVec2::new(61., -24.), DVec2::new(131., 24.)], "a pixel in from each side of its block");
|
||||
assert_eq!(
|
||||
layer.thumbnail_image(),
|
||||
[DVec2::new(63., -22.), DVec2::new(129., 22.)],
|
||||
"two pixels in from the thumbnail, at its aspect ratio"
|
||||
);
|
||||
assert_eq!(
|
||||
layer.name_box(),
|
||||
[DVec2::new(140., -12.), DVec2::new(232., 12.)],
|
||||
"the name follows the thumbnail and ends a margin short of the right edge"
|
||||
);
|
||||
assert_eq!(layer.stack_output(), DVec2::new(92., -36.), "the stack connectors are centred above and below the thumbnail");
|
||||
assert_eq!(layer.stack_input(), DVec2::new(92., 24.));
|
||||
assert_eq!(layer.secondary_input_connector(), DVec2::new(45., -4.), "the input on the left side sits where a node's would");
|
||||
assert_eq!(
|
||||
layer.visibility(),
|
||||
[DVec2::new(228., -12.), DVec2::new(252., 12.)],
|
||||
"the visibility button is centred on the right edge"
|
||||
);
|
||||
assert_eq!(layer.left_input_wire(), None, "no chain for a wire to enter");
|
||||
let gliding = Layer {
|
||||
glide: DVec2::new(3., -4.),
|
||||
..layer.clone()
|
||||
};
|
||||
assert_eq!(
|
||||
gliding.visibility(),
|
||||
layer.visibility().map(|corner| corner + DVec2::new(3., -4.)),
|
||||
"a gliding layer is drawn its glide away"
|
||||
);
|
||||
assert_eq!(layer.lock(), None, "an unlocked layer has no lock button");
|
||||
let locked = Layer { locked: true, ..layer.clone() };
|
||||
assert_eq!(locked.lock(), Some([DVec2::new(204., -12.), DVec2::new(228., 12.)]), "the lock button is left of the visibility button");
|
||||
assert_eq!(layer.grip(), [DVec2::new(220., -12.), DVec2::new(228., 12.)], "the grip is left of the visibility button");
|
||||
assert_eq!(locked.grip(), [DVec2::new(196., -12.), DVec2::new(204., 12.)], "the grip is left of the lock button");
|
||||
|
||||
let chained = Layer { chain_width: 8, ..layer };
|
||||
assert_eq!(chained.body(), [DVec2::new(-144., -24.), DVec2::new(240., 24.)], "the chain reaches left of the cell");
|
||||
assert_eq!(chained.thumbnail_block()[0], DVec2::new(60., -24.), "the thumbnail stays where it is");
|
||||
assert_eq!(chained.left_input_wire(), Some(DVec2::new(-144., 0.)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
use graphic_types::Graphic;
|
||||
use network_connector::NetworkConnectorKind;
|
||||
use scene::GraphUiScene;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use wire::WireInProgress;
|
||||
|
||||
pub mod card;
|
||||
mod dashes;
|
||||
pub mod dot;
|
||||
pub mod error_badge;
|
||||
pub mod icons;
|
||||
pub mod layer;
|
||||
mod look;
|
||||
pub mod metrics;
|
||||
pub mod network_connector;
|
||||
pub mod nodes;
|
||||
pub mod render;
|
||||
pub mod replicated_map;
|
||||
pub mod scene;
|
||||
#[cfg(test)]
|
||||
mod test_utils;
|
||||
mod text;
|
||||
pub mod wire;
|
||||
|
||||
#[derive(CacheHash)]
|
||||
pub struct GraphUi {
|
||||
pub scene: GraphUiScene,
|
||||
pub config: GraphUiConfig,
|
||||
pub thumbnails: Arc<BTreeMap<NodeId, Graphic>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, CacheHash)]
|
||||
pub struct GraphUiConfig {
|
||||
pub view: DAffine2,
|
||||
pub fade_artwork: f64,
|
||||
pub wire_in_progress: Option<WireInProgress>,
|
||||
pub reorder_bar: Option<(NetworkConnectorKind, DVec2)>,
|
||||
pub box_selection: Option<[DVec2; 2]>,
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::card::{Connector, DataType, Highlight};
|
||||
use crate::icons;
|
||||
use crate::metrics::{CHECKER_CELL, HOVERED_CONNECTOR_RING, HOVERED_CONNECTOR_SCALE, ICON_SIZE};
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::transform::ApplyTransform;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use std::sync::LazyLock;
|
||||
use vector_types::vector::algorithms::shapes::rounded_rectangle_bezpath;
|
||||
use vector_types::vector::style::{Stroke, StrokeJoin};
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect, Shape};
|
||||
|
||||
pub(crate) const CARD_OPACITY: f32 = 0.33;
|
||||
pub(crate) const GRID_DOT_OPACITY: f32 = 0.2;
|
||||
pub(crate) const BACKDROP: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
pub(crate) const SELECTED_DOT_RING_OPACITY: f32 = 0.5;
|
||||
pub(crate) const BORDER: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const PREVIEWED_BORDER: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||
pub(crate) const TEXT: SRGBA8 = SRGBA8::new_opaque(0xee, 0xee, 0xee);
|
||||
pub(crate) const LAYER_IN_INACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const LAYER_IN_ACTIVE_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x66, 0x66, 0x66);
|
||||
pub(crate) const HIDDEN_CARD: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||
pub(crate) const HIDDEN_TEXT: SRGBA8 = SRGBA8::new_opaque(0xaa, 0xaa, 0xaa);
|
||||
pub(crate) const SEPARATOR: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||
pub(crate) const HOVERED_BUTTON: SRGBA8 = SRGBA8::new_opaque(0x55, 0x55, 0x55);
|
||||
pub(crate) const DISABLED_ICON: SRGBA8 = SRGBA8::new_opaque(0x88, 0x88, 0x88);
|
||||
pub(crate) const BOX_SELECTION: SRGBA8 = SRGBA8::new_opaque(0x00, 0xa8, 0xff);
|
||||
pub(crate) const BOX_SELECTION_FILL_OPACITY: f32 = 0.05;
|
||||
pub(crate) const ERROR_RED: SRGBA8 = SRGBA8::new_opaque(0xd6, 0x53, 0x6e);
|
||||
pub(crate) const ERROR_TEXT: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
pub(crate) const ERROR_OPACITY: f64 = 0.5;
|
||||
pub(crate) const WIRE_SPLIT: SRGBA8 = SRGBA8::new_opaque(0x44, 0x44, 0x44);
|
||||
pub(crate) const THUMBNAIL_BACKGROUND: SRGBA8 = SRGBA8::new_opaque(0x22, 0x22, 0x22);
|
||||
const CHECKER_LIGHT: SRGBA8 = SRGBA8::new_opaque(0xff, 0xff, 0xff);
|
||||
const CHECKER_DARK: SRGBA8 = SRGBA8::new_opaque(0xcc, 0xcc, 0xcc);
|
||||
pub(crate) const CIRCLE_TOLERANCE: f64 = 1e-3;
|
||||
|
||||
pub(crate) static CONNECTOR_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.306A1.474,1.474,0,0,0,2.356,7.724L7.028,5.248c1.3-.687,1.3-1.809,0-2.5L2.356.276A1.474,1.474,0,0,0,0,1.694Z"));
|
||||
pub(crate) static STACK_OUTPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,6.953l2.521,-1.694a2.649,2.649,0,0,1,2.959,0l2.52,1.694v5.047h-8z"));
|
||||
pub(crate) static STACK_INPUT_OUTLINE: LazyLock<BezPath> = LazyLock::new(|| parsed("M0,0H8V8L5.479,6.319a2.666,2.666,0,0,0-2.959,0L0,8Z"));
|
||||
pub(crate) static STACK_OUTPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||
parsed(
|
||||
"M0,4.5 C0,4.5 0,-3.5 0,-3.5 C0,-3.5 3,-3.5 3,-3.5 C3,-3.5 3,2.565 3,2.565 C2.834,2.632 2.673,2.717 2.52,2.819 C2.52,2.819 0,4.5 0,4.5 Z\
|
||||
M5,2.566 C5,2.566 5,-3.5 5,-3.5 C5,-3.5 8,-3.5 8,-3.5 C8,-3.5 8,4.5 8,4.5 C8,4.5 5.479,2.819 5.479,2.819 C5.326,2.717 5.166,2.633 5,2.566 Z",
|
||||
)
|
||||
});
|
||||
pub(crate) static STACK_INPUT_WIRE_END: LazyLock<BezPath> = LazyLock::new(|| {
|
||||
parsed(
|
||||
"M2.512,9.26 C2.673,9.157 2.834,9.072 3,9 C3,9 3,16 3,16 C3,16 0,16 0,16 C0,16 0,10.95 0,10.95 C0,10.95 2.512,9.26 2.512,9.26 Z\
|
||||
M5,16 C5,16 5,9 5,9 C5.166,9.073 5.327,9.158 5.48,9.26 C5.48,9.26 8,10.95 8,10.95 C8,10.95 8,16 8,16 C8,16 5,16 5,16 Z",
|
||||
)
|
||||
});
|
||||
|
||||
fn parsed(path_data: &str) -> BezPath {
|
||||
BezPath::from_svg(path_data).expect("A connector outline is valid path data")
|
||||
}
|
||||
|
||||
pub(crate) fn data_type_colors(data_type: DataType) -> [SRGBA8; 2] {
|
||||
let colors = match data_type {
|
||||
DataType::General => [0xcfcfcf, 0x8a8a8a],
|
||||
DataType::Number => [0xc9a699, 0x886b60],
|
||||
DataType::Artboard => [0xfbf9eb, 0xb9b9a9],
|
||||
DataType::Graphic => [0x68c587, 0x37754c],
|
||||
DataType::Raster => [0xe4bb72, 0x9a7b43],
|
||||
DataType::Vector => [0x65bbe5, 0x417892],
|
||||
DataType::Color => [0xce6ea7, 0x924071],
|
||||
DataType::Gradient => [0xaf81eb, 0x6c489b],
|
||||
DataType::Typography => [0xeea7a7, 0x955252],
|
||||
DataType::Invalid => [0xd6536e, 0xa7324a],
|
||||
};
|
||||
colors.map(|color| {
|
||||
let [_, red, green, blue] = u32::to_be_bytes(color);
|
||||
SRGBA8::new_opaque(red, green, blue)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn connector(outline: &BezPath, top_left: DVec2, connector: &Connector) -> List<Vector> {
|
||||
drawn_connector(outline, top_left, connector.data_type, connector.connected, connector.highlight)
|
||||
}
|
||||
|
||||
pub(crate) fn drawn_connector(outline: &BezPath, top_left: DVec2, data_type: DataType, connected: bool, highlight: Highlight) -> List<Vector> {
|
||||
let [bright, dim] = data_type_colors(data_type);
|
||||
match highlight {
|
||||
Highlight::None => List::new_from_item(outlined(outline, top_left, if connected { bright } else { dim })),
|
||||
Highlight::WireSource => List::new_from_item(outlined(outline, top_left, bright)),
|
||||
Highlight::Hovered | Highlight::WireTarget => {
|
||||
let grown = Affine::translate((top_left.x, top_left.y)) * Affine::scale_about(HOVERED_CONNECTOR_SCALE, outline.bounding_box().center()) * outline.clone();
|
||||
let grown = Vector::item_from_bezpath(&grown);
|
||||
let ring = Stroke {
|
||||
join: StrokeJoin::Round,
|
||||
..Stroke::new(HOVERED_CONNECTOR_RING * HOVERED_CONNECTOR_SCALE)
|
||||
};
|
||||
List::from_iter([painted(grown.clone(), Coverage::new_stroke(&ring), dim.into()), painted(grown, Coverage::new_fill(), bright.into())])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn outlined(outline: &BezPath, top_left: DVec2, color: SRGBA8) -> Item<Vector> {
|
||||
let mut outline = Vector::item_from_bezpath(outline);
|
||||
outline.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
painted(outline, Coverage::new_fill(), color.into())
|
||||
}
|
||||
|
||||
pub(crate) fn rounded_rect(min: DVec2, max: DVec2, radii: [f64; 4]) -> Item<Vector> {
|
||||
Vector::item_from_bezpath(&rounded_rectangle_bezpath(min, max, radii))
|
||||
}
|
||||
|
||||
pub(crate) fn icon(name: &str, top_left: DVec2, current: SRGBA8) -> List<Vector> {
|
||||
let Some(icon) = icons::icon(name, current) else { return List::new() };
|
||||
let mut graphic = icon.shapes;
|
||||
if icon.overflows {
|
||||
let mut clip = rounded_rect(DVec2::ZERO, DVec2::splat(ICON_SIZE), [0.; 4]);
|
||||
stamp_coverage(&mut clip, Coverage::new_fill(), Graphic::VectorList(graphic), CoverPlacement::Above);
|
||||
graphic = List::new_from_item(clip);
|
||||
}
|
||||
graphic.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
graphic
|
||||
}
|
||||
|
||||
pub(crate) fn text(outline: &List<Vector>, top_left: DVec2, color: SRGBA8) -> List<Vector> {
|
||||
let glyphs = outline.clone().into_iter();
|
||||
let mut glyphs: List<Vector> = glyphs.map(|glyph| painted(glyph, Coverage::new_fill(), color.into())).collect();
|
||||
glyphs.left_apply_transform(&DAffine2::from_translation(top_left));
|
||||
glyphs
|
||||
}
|
||||
|
||||
pub(crate) fn checkerboard(min: DVec2, max: DVec2) -> List<Vector> {
|
||||
let mut dark = BezPath::new();
|
||||
let cells = ((max - min) / CHECKER_CELL).ceil().as_uvec2();
|
||||
for (column, row) in (0..cells.y)
|
||||
.flat_map(|row| (0..cells.x).map(move |column| (column, row)))
|
||||
.filter(|(column, row)| (column + row) % 2 == 1)
|
||||
{
|
||||
let cell_min = min + DVec2::new(column as f64, row as f64) * CHECKER_CELL;
|
||||
let cell_max = (cell_min + CHECKER_CELL).min(max);
|
||||
dark.extend(Rect::new(cell_min.x, cell_min.y, cell_max.x, cell_max.y).path_elements(0.));
|
||||
}
|
||||
let light = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), CHECKER_LIGHT.into());
|
||||
List::from_iter([light, painted(Vector::item_from_bezpath(&dark), Coverage::new_fill(), CHECKER_DARK.into())])
|
||||
}
|
||||
|
||||
pub(crate) fn painted(mut item: Item<Vector>, coverage: Coverage, color: Color) -> Item<Vector> {
|
||||
stamp_coverage(&mut item, coverage, Graphic::from(color), CoverPlacement::Above);
|
||||
item
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
use glam::DVec2;
|
||||
|
||||
pub const GRID_SIZE: f64 = 24.;
|
||||
pub const GRID_COLLAPSE_SPACING: f64 = 10.;
|
||||
pub const TEXT_SIZE: f64 = 14.;
|
||||
pub const BORDER_WIDTH: f64 = 1.;
|
||||
pub const BORDER_DASHES: [f64; 2] = [3., 2.];
|
||||
pub const ICON_SIZE: f64 = 16.;
|
||||
|
||||
pub const NODE_WIDTH: f64 = 5. * GRID_SIZE;
|
||||
pub const NODE_RADIUS: f64 = 2.;
|
||||
pub const NODE_ICON_LEFT: f64 = 8.;
|
||||
pub const NODE_NAME_LEFT: f64 = 32.;
|
||||
pub const NODE_NAME_MAX_WIDTH: f64 = 84.;
|
||||
pub const NODE_ROW_PADDING: f64 = 8.;
|
||||
|
||||
pub const CONNECTOR_SIZE: f64 = 8.;
|
||||
pub const INPUT_CONNECTOR_LEFT: f64 = -3.;
|
||||
pub const OUTPUT_CONNECTOR_RIGHT: f64 = 5.;
|
||||
pub const CONNECTOR_GAP: f64 = 16.;
|
||||
pub const HOVERED_CONNECTOR_SCALE: f64 = 1.3;
|
||||
pub const HOVERED_CONNECTOR_RING: f64 = 4.;
|
||||
pub const STACK_CONNECTOR_SIZE: DVec2 = DVec2::new(CONNECTOR_SIZE, 12.);
|
||||
|
||||
pub const IMPORT_EXPORT_CONNECTOR: DVec2 = DVec2::new(INPUT_CONNECTOR_LEFT, -CONNECTOR_SIZE / 2.);
|
||||
pub const IMPORT_NAME_INSET: f64 = 8.;
|
||||
pub const EXPORT_NAME_INSET: f64 = 9.;
|
||||
pub const IMPORT_EXPORT_NAME_RAISE: f64 = 1.;
|
||||
pub const IMPORT_EXPORT_SEPARATOR_OVERHANG: f64 = 4.;
|
||||
pub const REORDER_BAR_SIZE: DVec2 = DVec2::new(50., 2.);
|
||||
|
||||
pub const ERROR_PADDING: f64 = 8.;
|
||||
pub const ERROR_LINE_HEIGHT: f64 = 18.;
|
||||
pub const ERROR_MAX_WIDTH: f64 = 600.;
|
||||
pub const ERROR_RADIUS: f64 = 4.;
|
||||
pub const ERROR_TAIL_LEFT: f64 = 6.;
|
||||
pub const ERROR_TAIL_SIZE: DVec2 = DVec2::new(12., 8.);
|
||||
|
||||
pub const WIRE_WIDTH: f64 = 2.;
|
||||
pub const LIST_WIRE_WIDTH: f64 = 4.;
|
||||
pub const WIRE_DASHES: [f64; 2] = [3., 2.];
|
||||
pub const THICK_WIRE_WIDTH: f64 = 8.;
|
||||
|
||||
pub const DOT_RADIUS: f64 = 5.;
|
||||
pub const DOT_SELECTED_RING: f64 = 2.;
|
||||
pub const DOT_PREVIEWED_RING_OFFSET: f64 = 2.;
|
||||
pub const DOT_HOVERED_RING: f64 = 2.;
|
||||
pub const DOT_OUTPUT_ARROW: DVec2 = DVec2::new(6., -4.);
|
||||
|
||||
pub const LAYER_HEIGHT: f64 = 2. * GRID_SIZE;
|
||||
pub const LAYER_RADIUS: f64 = 8.;
|
||||
pub const LAYER_LEFT_MARGIN: f64 = GRID_SIZE / 2.;
|
||||
pub const LAYER_THUMBNAIL_WIDTH: f64 = 3. * GRID_SIZE;
|
||||
pub const LAYER_THUMBNAIL_MARGIN: f64 = 1.;
|
||||
pub const LAYER_THUMBNAIL_RADIUS: f64 = 2.;
|
||||
pub const LAYER_THUMBNAIL_IMAGE_INSET: f64 = 2.;
|
||||
pub const CHECKER_CELL: f64 = 8.;
|
||||
pub const LAYER_DETAILS_MARGIN: f64 = 8.;
|
||||
pub const LAYER_NAME_LEFT: f64 = LAYER_LEFT_MARGIN + LAYER_THUMBNAIL_WIDTH + LAYER_DETAILS_MARGIN;
|
||||
pub const LAYER_BUTTON_SIZE: f64 = GRID_SIZE;
|
||||
pub const LAYER_BUTTON_RADIUS: f64 = 2.;
|
||||
pub const LAYER_GRIP_WIDTH: f64 = 8.;
|
||||
pub const LAYER_GRIP_DOTS: DVec2 = DVec2::new(2.5, 9.5);
|
||||
pub const LAYER_GRIP_DOT_COUNT: [u32; 2] = [2, 3];
|
||||
pub const LAYER_GRIP_DOT_SPACING: f64 = 3.;
|
||||
pub const LAYER_GRIP_DOT_RADIUS: f64 = 0.5;
|
||||
pub const LAYER_THUMBNAIL_GAP: DVec2 = DVec2::new(8., 2.);
|
||||
@@ -0,0 +1,117 @@
|
||||
use crate::card::{Connector, Highlight};
|
||||
use crate::metrics::{BORDER_WIDTH, EXPORT_NAME_INSET, GRID_SIZE, IMPORT_EXPORT_CONNECTOR, IMPORT_EXPORT_NAME_RAISE, IMPORT_EXPORT_SEPARATOR_OVERHANG, IMPORT_NAME_INSET, REORDER_BAR_SIZE};
|
||||
use crate::replicated_map::Keyed;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||
pub enum NetworkConnectorKind {
|
||||
Import,
|
||||
Export,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct NetworkConnector {
|
||||
pub kind: NetworkConnectorKind,
|
||||
pub index: usize,
|
||||
pub position: IVec2,
|
||||
pub connector: Option<Connector>,
|
||||
pub add_highlight: Highlight,
|
||||
pub editable: bool,
|
||||
pub renaming: bool,
|
||||
pub glide: DVec2,
|
||||
}
|
||||
|
||||
impl Keyed for NetworkConnector {
|
||||
type Key = (NetworkConnectorKind, usize);
|
||||
|
||||
fn key(&self) -> (NetworkConnectorKind, usize) {
|
||||
(self.kind, self.index)
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkConnector {
|
||||
pub fn anchor(&self) -> DVec2 {
|
||||
self.position.as_dvec2() + self.glide
|
||||
}
|
||||
|
||||
pub fn connector_top_left(&self) -> DVec2 {
|
||||
self.anchor() + IMPORT_EXPORT_CONNECTOR
|
||||
}
|
||||
|
||||
pub fn name_box(&self, width: f64) -> [DVec2; 2] {
|
||||
let anchor = self.anchor();
|
||||
let left = match self.kind {
|
||||
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - width,
|
||||
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||
};
|
||||
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2. - IMPORT_EXPORT_NAME_RAISE);
|
||||
[top_left, top_left + DVec2::new(width, GRID_SIZE)]
|
||||
}
|
||||
|
||||
pub fn separator(&self, name_width: f64) -> [DVec2; 2] {
|
||||
let [name_min, name_max] = self.name_box(name_width);
|
||||
let toward_the_line = if self.index == 0 { GRID_SIZE } else { -GRID_SIZE };
|
||||
let top = self.anchor().y + toward_the_line - BORDER_WIDTH;
|
||||
[
|
||||
DVec2::new(name_min.x - IMPORT_EXPORT_SEPARATOR_OVERHANG, top),
|
||||
DVec2::new(name_max.x + IMPORT_EXPORT_SEPARATOR_OVERHANG, top + BORDER_WIDTH),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reorder_bar(kind: NetworkConnectorKind, anchor: DVec2) -> [DVec2; 2] {
|
||||
let left = match kind {
|
||||
NetworkConnectorKind::Import => anchor.x - IMPORT_NAME_INSET - REORDER_BAR_SIZE.x,
|
||||
NetworkConnectorKind::Export => anchor.x + EXPORT_NAME_INSET,
|
||||
};
|
||||
let top_left = DVec2::new(left, anchor.y - GRID_SIZE / 2.);
|
||||
[top_left, top_left + REORDER_BAR_SIZE]
|
||||
}
|
||||
|
||||
pub fn import_export_row_offset(index: usize) -> f64 {
|
||||
let rows = if index == 0 { 0 } else { index + 1 };
|
||||
rows as f64 * GRID_SIZE
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::test_utils::network_connector;
|
||||
|
||||
#[test]
|
||||
fn the_name_of_an_import_ends_left_of_its_connector_and_the_name_of_an_export_starts_right_of_it() {
|
||||
let primary = NetworkConnector {
|
||||
position: IVec2::new(48, -24),
|
||||
..network_connector(NetworkConnectorKind::Import, 0)
|
||||
};
|
||||
let secondary = NetworkConnector {
|
||||
position: IVec2::new(48, 24),
|
||||
..network_connector(NetworkConnectorKind::Import, 1)
|
||||
};
|
||||
assert_eq!(secondary.connector_top_left(), DVec2::new(45., 20.), "the connector box beside the anchor");
|
||||
let gliding = NetworkConnector {
|
||||
glide: DVec2::new(3., -4.),
|
||||
..secondary.clone()
|
||||
};
|
||||
assert_eq!(gliding.anchor(), DVec2::new(51., 20.), "a gliding import is drawn its glide away");
|
||||
assert_eq!(primary.name_box(30.), [DVec2::new(10., -37.), DVec2::new(40., -13.)], "an import's name ends left of its connector");
|
||||
let export = NetworkConnector {
|
||||
kind: NetworkConnectorKind::Export,
|
||||
..primary.clone()
|
||||
};
|
||||
assert_eq!(export.name_box(30.), [DVec2::new(57., -37.), DVec2::new(87., -13.)], "an export's name starts right of its connector");
|
||||
assert_eq!(primary.separator(30.), [DVec2::new(6., -1.), DVec2::new(44., 0.)], "the line under the primary name");
|
||||
assert_eq!(secondary.separator(20.), [DVec2::new(16., -1.), DVec2::new(44., 0.)], "the line over the next name, the same line");
|
||||
assert_eq!(
|
||||
reorder_bar(NetworkConnectorKind::Import, secondary.anchor()),
|
||||
[DVec2::new(-10., 12.), DVec2::new(40., 14.)],
|
||||
"the bar where an import would be dropped, above its row"
|
||||
);
|
||||
assert_eq!(
|
||||
reorder_bar(NetworkConnectorKind::Export, primary.anchor()),
|
||||
[DVec2::new(57., -36.), DVec2::new(107., -34.)],
|
||||
"the bar where an export would be dropped"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,816 @@
|
||||
use crate::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use crate::dashes::{border, dashed};
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::{Layer, LayerButton};
|
||||
use crate::look::{
|
||||
BORDER, BOX_SELECTION, BOX_SELECTION_FILL_OPACITY, CARD_OPACITY, CIRCLE_TOLERANCE, CONNECTOR_OUTLINE, DISABLED_ICON, ERROR_OPACITY, ERROR_RED, ERROR_TEXT, GRID_DOT_OPACITY, HIDDEN_CARD,
|
||||
HIDDEN_TEXT, HOVERED_BUTTON, LAYER_IN_ACTIVE_SELECTION, LAYER_IN_INACTIVE_SELECTION, PREVIEWED_BORDER, SELECTED_DOT_RING_OPACITY, SEPARATOR, STACK_INPUT_OUTLINE, STACK_INPUT_WIRE_END,
|
||||
STACK_OUTPUT_OUTLINE, STACK_OUTPUT_WIRE_END, TEXT, THUMBNAIL_BACKGROUND, WIRE_SPLIT, checkerboard, connector, data_type_colors, drawn_connector, icon, outlined, painted, rounded_rect, text,
|
||||
};
|
||||
use crate::metrics::{
|
||||
BORDER_WIDTH, CONNECTOR_GAP, CONNECTOR_SIZE, DOT_HOVERED_RING, DOT_OUTPUT_ARROW, DOT_PREVIEWED_RING_OFFSET, DOT_RADIUS, DOT_SELECTED_RING, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH, ERROR_RADIUS,
|
||||
GRID_COLLAPSE_SPACING, GRID_SIZE, HOVERED_CONNECTOR_SCALE, ICON_SIZE, LAYER_BUTTON_RADIUS, LAYER_BUTTON_SIZE, LAYER_GRIP_DOT_COUNT, LAYER_GRIP_DOT_RADIUS, LAYER_GRIP_DOT_SPACING, LAYER_GRIP_DOTS,
|
||||
LAYER_RADIUS, LAYER_THUMBNAIL_GAP, LAYER_THUMBNAIL_RADIUS, LIST_WIRE_WIDTH, NODE_ICON_LEFT, NODE_NAME_LEFT, NODE_NAME_MAX_WIDTH, NODE_RADIUS, NODE_ROW_PADDING, NODE_WIDTH, THICK_WIRE_WIDTH,
|
||||
WIRE_DASHES, WIRE_WIDTH,
|
||||
};
|
||||
use crate::network_connector::{NetworkConnector, reorder_bar};
|
||||
use crate::render::{graph_ui, render_config};
|
||||
use crate::replicated_map::{Keyed, ReplicatedMap};
|
||||
use crate::text::{Labels, Paragraphs};
|
||||
use crate::wire::{Wire, WireKey};
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, ATTR_GRADIENT_SPREAD, ATTR_OPACITY, Item, List};
|
||||
use core_types::transform::ApplyTransform;
|
||||
use core_types::{Color, Ctx, ExtractVarArgs};
|
||||
use glam::{DAffine2, DVec2, IVec2};
|
||||
use graphic_types::{CoverPlacement, Coverage, Graphic, Vector, stamp_coverage};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::convert::Infallible;
|
||||
use std::sync::{Arc, Mutex, PoisonError};
|
||||
use text_nodes::TextToVectorError;
|
||||
use vector_types::vector::style::Stroke;
|
||||
use vector_types::{Gradient, GradientInterpolation, GradientSpread, GradientStop};
|
||||
use vello_gpu::kurbo::{BezPath, Circle, Rect, Shape, flatten};
|
||||
|
||||
const GRID_DOT_ROUNDING_BIAS: f64 = 1. / 64.;
|
||||
const WIRE_FLATTENING_TOLERANCE: f64 = 0.02;
|
||||
|
||||
fn rows<T: Keyed + 'static>(ctx: &impl ExtractVarArgs, index: usize) -> &ReplicatedMap<T> {
|
||||
ctx.vararg(index).ok().and_then(|rows| rows.downcast_ref()).expect("A scene band is given the rows it draws")
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_grid(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let render_config = render_config(&ctx);
|
||||
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
|
||||
grid_dots(graph_ui(&ctx).config.view, viewport_size, render_config.scale)
|
||||
}
|
||||
|
||||
fn grid_dots(view: DAffine2, viewport_size: DVec2, scale: f64) -> List<Vector> {
|
||||
let zoom = view.matrix2.x_axis.length();
|
||||
let mut spacing = zoom * GRID_SIZE;
|
||||
if !spacing.is_finite() || spacing <= 0. {
|
||||
return List::new();
|
||||
}
|
||||
while spacing < GRID_COLLAPSE_SPACING {
|
||||
spacing *= 2.;
|
||||
}
|
||||
let radius = ((1. + (zoom - 0.5 + 0.001).floor() / 2.) * scale).ceil() as u32;
|
||||
let period = spacing * scale;
|
||||
let origin = (view.translation * scale - radius as f64).rem_euclid(DVec2::splat(period)) - period - GRID_DOT_ROUNDING_BIAS;
|
||||
|
||||
let dot_color = Color::WHITE.with_alpha(GRID_DOT_OPACITY);
|
||||
let stop = |column: u32, color| GradientStop {
|
||||
position: column as f64 / period,
|
||||
midpoint: 0.5,
|
||||
color,
|
||||
};
|
||||
let mut dots = List::new();
|
||||
for ([top, bottom], runs) in disc_columns(radius) {
|
||||
let mut bands = BezPath::new();
|
||||
for row in 0..=((viewport_size.y * scale - origin.y) / period).ceil() as u32 {
|
||||
let y = (origin.y + row as f64 * period).round();
|
||||
bands.extend(Rect::new(0., (y + top as f64) / scale, viewport_size.x, (y + bottom as f64) / scale).path_elements(0.));
|
||||
}
|
||||
|
||||
let start = runs[0][0];
|
||||
let stops = runs.iter().flat_map(|&[left, right]| [stop(left - start, dot_color), stop(right - start, Color::TRANSPARENT)]);
|
||||
let mut columns = Item::new_from_element(Gradient::new(stops));
|
||||
columns.set_attribute(ATTR_GRADIENT_SPREAD, GradientSpread::Repeat);
|
||||
columns.set_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped);
|
||||
columns.left_apply_transform(&DAffine2::from_scale_angle_translation(DVec2::splat(spacing), 0., DVec2::new((origin.x + start as f64) / scale, 0.)));
|
||||
|
||||
let mut group = Vector::item_from_bezpath(&bands);
|
||||
stamp_coverage(&mut group, Coverage::new_fill(), Graphic::Gradient(columns), CoverPlacement::Above);
|
||||
dots.push(group);
|
||||
}
|
||||
dots
|
||||
}
|
||||
|
||||
fn disc_columns(radius: u32) -> BTreeMap<[u32; 2], Vec<[u32; 2]>> {
|
||||
let lit = |column: u32, row: u32| (DVec2::new(column as f64, row as f64) + 0.5 - radius as f64).length() < radius as f64;
|
||||
let mut runs_by_rows = BTreeMap::<[u32; 2], Vec<[u32; 2]>>::new();
|
||||
for column in 0..2 * radius {
|
||||
let top = (0..radius).take_while(|&row| !lit(column, row)).count() as u32;
|
||||
let runs = runs_by_rows.entry([top, 2 * radius - top]).or_default();
|
||||
match runs.last_mut() {
|
||||
Some(run) if run[1] == column => run[1] += 1,
|
||||
_ => runs.push([column, column + 1]),
|
||||
}
|
||||
}
|
||||
runs_by_rows
|
||||
}
|
||||
|
||||
type Cache<Row, Texts = ()> = Arc<Mutex<RowCache<Row, Texts>>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct RowCache<Row: Keyed, Texts> {
|
||||
drawn: BTreeMap<Row::Key, (Row, List<Vector>)>,
|
||||
labels: Texts,
|
||||
}
|
||||
|
||||
impl<Row: Keyed, Texts: Default> Default for RowCache<Row, Texts> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
drawn: BTreeMap::new(),
|
||||
labels: Texts::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_changed_rows<'a, Row: Keyed + Placed + PartialEq + 'a, Texts, Error>(
|
||||
rows: impl IntoIterator<Item = &'a Row>,
|
||||
cache: &mut RowCache<Row, Texts>,
|
||||
draw: impl Fn(&Row, &mut Texts) -> Result<List<Vector>, Error>,
|
||||
) -> Result<List<Vector>, Error> {
|
||||
let mut kept = BTreeMap::new();
|
||||
let mut graphic = List::new();
|
||||
for row in rows {
|
||||
let entry = match cache.drawn.remove(&row.key()).map(|(drawn, drawing)| (drawn.placed_at(row.place()), drawing)) {
|
||||
Some(entry) if entry.0 == *row => entry,
|
||||
_ => {
|
||||
let at_origin = row.clone().placed_at(Default::default());
|
||||
let drawing = draw(&at_origin, &mut cache.labels)?;
|
||||
(at_origin, drawing)
|
||||
}
|
||||
};
|
||||
let mut placed = entry.1.clone();
|
||||
let offset = row.offset();
|
||||
if offset != DVec2::ZERO {
|
||||
placed.left_apply_transform(&DAffine2::from_translation(offset));
|
||||
}
|
||||
graphic.extend(placed);
|
||||
kept.insert(row.key(), entry);
|
||||
}
|
||||
cache.drawn = kept;
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_rows<'a, Row: Keyed + Placed + PartialEq + 'a>(rows: impl IntoIterator<Item = &'a Row>, cache: &Cache<Row>, draw: impl Fn(&Row) -> List<Vector>) -> List<Vector> {
|
||||
let Ok(graphic) = draw_changed_rows(rows, &mut cache.lock().unwrap_or_else(PoisonError::into_inner), |row, _| Ok::<_, Infallible>(draw(row)));
|
||||
graphic
|
||||
}
|
||||
|
||||
trait Placed: Clone {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn placed_at(self, _place: (IVec2, DVec2)) -> Self {
|
||||
self
|
||||
}
|
||||
|
||||
fn offset(&self) -> DVec2 {
|
||||
let (cell, glide) = self.place();
|
||||
cell.as_dvec2() * GRID_SIZE + glide
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Wire {}
|
||||
|
||||
impl Placed for Card {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Layer {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for Dot {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for ErrorBadge {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.cell, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (cell, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { cell, glide, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl Placed for NetworkConnector {
|
||||
fn place(&self) -> (IVec2, DVec2) {
|
||||
(self.position, self.glide)
|
||||
}
|
||||
|
||||
fn placed_at(self, (position, glide): (IVec2, DVec2)) -> Self {
|
||||
Self { position, glide, ..self }
|
||||
}
|
||||
|
||||
fn offset(&self) -> DVec2 {
|
||||
self.position.as_dvec2() + self.glide
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_layers(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Layer, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let layers = rows::<Layer>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(layers, &mut cache, draw_layer)?;
|
||||
|
||||
let shown: HashSet<&str> = layers.iter().map(|layer| layer.name.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_layer(layer: &Layer, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||
let mut graphic = List::new();
|
||||
let [min, max] = layer.body();
|
||||
let fill = match (layer.selection, layer.visible) {
|
||||
(Selection::Active, _) => LAYER_IN_ACTIVE_SELECTION.into(),
|
||||
(Selection::Inactive, _) => LAYER_IN_INACTIVE_SELECTION.into(),
|
||||
(Selection::None, true) => Color::BLACK,
|
||||
(Selection::None, false) => HIDDEN_CARD.into(),
|
||||
};
|
||||
graphic.push(painted(rounded_rect(min, max, [LAYER_RADIUS; 4]), Coverage::new_fill(), fill.with_alpha(CARD_OPACITY)));
|
||||
|
||||
if !layer.renaming {
|
||||
let [name, _] = layer.name_box();
|
||||
let text_color = if layer.visible { TEXT } else { HIDDEN_TEXT };
|
||||
graphic.extend(text(&labels.label(&layer.name, layer.name_width())?.outline, name, text_color));
|
||||
}
|
||||
|
||||
let [thumbnail_min, thumbnail_max] = layer.thumbnail();
|
||||
let thumbnail = rounded_rect(thumbnail_min, thumbnail_max, [LAYER_THUMBNAIL_RADIUS; 4]);
|
||||
graphic.push(painted(thumbnail, Coverage::new_fill(), THUMBNAIL_BACKGROUND.into()));
|
||||
let thumbnail_border = Vector::item_from_bezpath(&border(thumbnail_min, thumbnail_max, LAYER_THUMBNAIL_RADIUS, &[], false));
|
||||
graphic.push(painted(thumbnail_border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BORDER.into()));
|
||||
let [image_min, image_max] = layer.thumbnail_image();
|
||||
graphic.extend(checkerboard(image_min, image_max));
|
||||
|
||||
if let Some(output) = &layer.primary_output {
|
||||
graphic.extend(connector(&STACK_OUTPUT_OUTLINE, layer.stack_output(), output));
|
||||
if output.connected && layer.primary_output_connected_to_layer {
|
||||
graphic.push(outlined(&STACK_OUTPUT_WIRE_END, layer.stack_output(), data_type_colors(output.data_type)[1]));
|
||||
}
|
||||
}
|
||||
match &layer.primary_input {
|
||||
Some(input) => {
|
||||
graphic.extend(connector(&STACK_INPUT_OUTLINE, layer.stack_input(), input));
|
||||
if input.connected && layer.primary_input_connected_to_layer {
|
||||
graphic.push(outlined(&STACK_INPUT_WIRE_END, layer.stack_input(), data_type_colors(input.data_type)[1]));
|
||||
}
|
||||
}
|
||||
None => graphic.push(outlined(&STACK_INPUT_OUTLINE, layer.stack_input(), data_type_colors(DataType::General)[1])),
|
||||
}
|
||||
|
||||
let [block_min, block_max] = layer.thumbnail_block();
|
||||
let mut gaps = vec![[block_min - LAYER_THUMBNAIL_GAP, block_max + LAYER_THUMBNAIL_GAP], layer.visibility()];
|
||||
gaps.extend(layer.left_input_wire().map(|wire| [wire - CONNECTOR_GAP / 2., wire + CONNECTOR_GAP / 2.]));
|
||||
let border = Vector::item_from_bezpath(&border(min, max, LAYER_RADIUS, &gaps, layer.previewed));
|
||||
let border_color = if layer.previewed { PREVIEWED_BORDER } else { BORDER };
|
||||
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_thumbnails(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let graph_ui = graph_ui(&ctx);
|
||||
let thumbnails = graph_ui.thumbnails.iter().filter_map(|(key, thumbnail)| Some((graph_ui.scene.layers().get(key)?, thumbnail)));
|
||||
thumbnails
|
||||
.map(|(layer, thumbnail)| {
|
||||
let [min, max] = layer.thumbnail_image();
|
||||
let mut image = rounded_rect(DVec2::ZERO, DVec2::ONE, [0.; 4]);
|
||||
image.left_apply_transform(&DAffine2::from_scale_angle_translation(max - min, 0., min));
|
||||
stamp_coverage(&mut image, Coverage::new_fill(), thumbnail.clone(), CoverPlacement::Above);
|
||||
image
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_raised(ctx: impl Ctx + ExtractVarArgs, #[data] layers: Cache<Layer>, #[data] cards: Cache<Card>) -> List<Vector> {
|
||||
let mut graphic = draw_rows(rows::<Layer>(&ctx, 0), layers, draw_raised_parts_of_layer);
|
||||
graphic.extend(draw_rows(rows::<Card>(&ctx, 1), cards, draw_connectors_of_card));
|
||||
graphic
|
||||
}
|
||||
|
||||
fn draw_raised_parts_of_layer(layer: &Layer) -> List<Vector> {
|
||||
let mut graphic = List::new();
|
||||
if let Some(input) = &layer.secondary_input {
|
||||
graphic.extend(connector(&CONNECTOR_OUTLINE, layer.secondary_input_connector(), input));
|
||||
}
|
||||
let hovered = |button| layer.hovered_button == Some(button);
|
||||
let grip_color = match (hovered(LayerButton::Grip), layer.selection != Selection::None) {
|
||||
(true, _) => Some(Color::WHITE),
|
||||
(false, true) => Some(TEXT.into()),
|
||||
(false, false) => None,
|
||||
};
|
||||
if let Some(grip_color) = grip_color {
|
||||
let [grip, _] = layer.grip();
|
||||
let mut dots = BezPath::new();
|
||||
let [columns, rows] = LAYER_GRIP_DOT_COUNT;
|
||||
for (column, row) in (0..rows).flat_map(|row| (0..columns).map(move |column| (column, row))) {
|
||||
let center = grip + LAYER_GRIP_DOTS + DVec2::new(column as f64, row as f64) * LAYER_GRIP_DOT_SPACING;
|
||||
dots.extend(Circle::new((center.x, center.y), LAYER_GRIP_DOT_RADIUS).path_elements(CIRCLE_TOLERANCE));
|
||||
}
|
||||
graphic.push(painted(Vector::item_from_bezpath(&dots), Coverage::new_fill(), grip_color));
|
||||
}
|
||||
|
||||
let mut button = |[min, max]: [DVec2; 2], which: LayerButton, [resting, hover]: [&str; 2]| {
|
||||
let hovered = hovered(which) && !layer.read_only;
|
||||
if hovered {
|
||||
graphic.push(painted(rounded_rect(min, max, [LAYER_BUTTON_RADIUS; 4]), Coverage::new_fill(), HOVERED_BUTTON.into()));
|
||||
}
|
||||
let name = if hovered && !layer.hovered_button_clicked { hover } else { resting };
|
||||
graphic.extend(icon(name, min + (LAYER_BUTTON_SIZE - ICON_SIZE) / 2., if layer.read_only { DISABLED_ICON } else { TEXT }));
|
||||
};
|
||||
if let Some(lock) = layer.lock() {
|
||||
button(lock, LayerButton::Lock, ["PadlockLocked", "PadlockUnlocked"]);
|
||||
}
|
||||
let eye = if layer.visible { ["EyeVisible", "EyeHide"] } else { ["EyeHidden", "EyeShow"] };
|
||||
button(layer.visibility(), LayerButton::Visibility, eye);
|
||||
graphic
|
||||
}
|
||||
|
||||
fn draw_connectors_of_card(card: &Card) -> List<Vector> {
|
||||
card.inputs()
|
||||
.chain(card.outputs())
|
||||
.flat_map(|(top_left, input_or_output)| connector(&CONNECTOR_OUTLINE, top_left, input_or_output))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_thick_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
|
||||
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| wire.thick), cache, draw_wire)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_wires(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Wire>) -> List<Vector> {
|
||||
draw_rows(rows::<Wire>(&ctx, 0).iter().filter(|wire| !wire.thick), cache, draw_wire)
|
||||
}
|
||||
|
||||
fn draw_wire(wire: &Wire) -> List<Vector> {
|
||||
let [bright, dim] = data_type_colors(wire.data_type);
|
||||
let previewed = wire.key == WireKey::Preview;
|
||||
let color = if previewed || wire.insertion_target { bright } else { dim };
|
||||
let stroke = |path: &BezPath, width: f64, color: SRGBA8| painted(Vector::item_from_bezpath(path), Coverage::new_stroke(&Stroke::new(width)), color.into());
|
||||
let drawn = |path: &BezPath| if previewed { flattened(&dashed(path, WIRE_DASHES)) } else { flattened(path) };
|
||||
let path = drawn(&wire.path);
|
||||
if wire.thick {
|
||||
List::from_iter([stroke(&path, THICK_WIRE_WIDTH, color), stroke(&drawn(&wire.center_line), WIRE_WIDTH, WIRE_SPLIT)])
|
||||
} else if wire.list {
|
||||
List::from_iter([stroke(&path, LIST_WIRE_WIDTH, color), stroke(&path, WIRE_WIDTH, WIRE_SPLIT)])
|
||||
} else {
|
||||
List::new_from_item(stroke(&path, WIRE_WIDTH, color))
|
||||
}
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_wire_in_progress(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some(wire) = graph_ui(&ctx).config.wire_in_progress else { return List::new() };
|
||||
let [_, dim] = data_type_colors(wire.data_type);
|
||||
let path = flattened(&BezPath::from_vec(wire.path.to_vec()));
|
||||
List::new_from_item(painted(Vector::item_from_bezpath(&path), Coverage::new_stroke(&Stroke::new(WIRE_WIDTH)), dim.into()))
|
||||
}
|
||||
|
||||
fn flattened(path: &BezPath) -> BezPath {
|
||||
let mut lines = BezPath::new();
|
||||
flatten(path, WIRE_FLATTENING_TOLERANCE, |element| lines.push(element));
|
||||
lines
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_cards(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Card, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let cards = rows::<Card>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(cards, &mut cache, draw_card)?;
|
||||
|
||||
let shown: HashSet<&str> = cards.iter().flat_map(texts).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_card(card: &Card, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||
let mut graphic = List::new();
|
||||
let [min, max] = card.body();
|
||||
|
||||
let (card_color, text_color) = if card.visible { (Color::BLACK, TEXT) } else { (HIDDEN_CARD.into(), HIDDEN_TEXT) };
|
||||
let body = rounded_rect(min, max, [NODE_RADIUS; 4]);
|
||||
graphic.push(painted(body, Coverage::new_fill(), card_color.with_alpha(CARD_OPACITY)));
|
||||
|
||||
let (header_tint, rows_tint) = match card.selection {
|
||||
Selection::None => (0.05, 0.),
|
||||
Selection::Inactive => (0.15, 0.1),
|
||||
Selection::Active => (0.2, 0.15),
|
||||
};
|
||||
let header_bottom = if card.rows() == 1 { NODE_RADIUS } else { 0. };
|
||||
let header = rounded_rect(min, DVec2::new(max.x, min.y + GRID_SIZE), [NODE_RADIUS, NODE_RADIUS, header_bottom, header_bottom]);
|
||||
graphic.push(painted(header, Coverage::new_fill(), Color::WHITE.with_alpha(header_tint)));
|
||||
if card.selection != Selection::None && card.rows() > 1 {
|
||||
let rows = rounded_rect(DVec2::new(min.x, min.y + GRID_SIZE), max, [0., 0., NODE_RADIUS, NODE_RADIUS]);
|
||||
graphic.push(painted(rows, Coverage::new_fill(), Color::WHITE.with_alpha(rows_tint)));
|
||||
}
|
||||
graphic.extend(icon(&card.icon, min + DVec2::new(NODE_ICON_LEFT, (GRID_SIZE - ICON_SIZE) / 2.), text_color));
|
||||
let name = labels.label(&card.name, NODE_NAME_MAX_WIDTH)?;
|
||||
graphic.extend(text(&name.outline, min + DVec2::new(NODE_NAME_LEFT, 0.), text_color));
|
||||
|
||||
for row in 1..card.rows() {
|
||||
let (input, output) = (card.secondary_inputs.get(row - 1), card.secondary_outputs.get(row - 1));
|
||||
let Some(connector) = input.or(output) else { continue };
|
||||
let name = labels.label(&connector.name, NODE_WIDTH - 2. * NODE_ROW_PADDING)?;
|
||||
let left = if input.is_some() { NODE_ROW_PADDING } else { NODE_WIDTH - NODE_ROW_PADDING - name.width };
|
||||
graphic.extend(text(&name.outline, min + DVec2::new(left, row as f64 * GRID_SIZE), text_color));
|
||||
}
|
||||
|
||||
let border_color = if card.previewed { PREVIEWED_BORDER } else { BORDER };
|
||||
let gap = |edge: f64, (top_left, _): (DVec2, &Connector)| {
|
||||
let center = DVec2::new(edge, top_left.y + CONNECTOR_SIZE / 2.);
|
||||
[center - CONNECTOR_GAP / 2., center + CONNECTOR_GAP / 2.]
|
||||
};
|
||||
let gaps: Vec<[DVec2; 2]> = card.inputs().map(|input| gap(min.x, input)).chain(card.outputs().map(|output| gap(max.x, output))).collect();
|
||||
let border = Vector::item_from_bezpath(&border(min, max, NODE_RADIUS, &gaps, card.previewed));
|
||||
graphic.push(painted(border, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), border_color.into()));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn texts(card: &Card) -> impl Iterator<Item = &str> {
|
||||
let connectors = card.secondary_inputs.iter().chain(&card.secondary_outputs);
|
||||
std::iter::once(card.name.as_str()).chain(connectors.map(|connector| connector.name.as_str()))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_dots(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<Dot>) -> List<Vector> {
|
||||
draw_rows(rows::<Dot>(&ctx, 0), cache, draw_dot)
|
||||
}
|
||||
|
||||
fn draw_dot(dot: &Dot) -> List<Vector> {
|
||||
let [wired, unwired] = data_type_colors(dot.data_type);
|
||||
let center = dot.center();
|
||||
let grown = matches!(dot.highlight, Highlight::Hovered | Highlight::WireTarget);
|
||||
let scale = if grown { HOVERED_CONNECTOR_SCALE } else { 1. };
|
||||
let circle = |radius: f64| Vector::item_from_bezpath(&Circle::new((center.x, center.y), radius * scale).to_path(CIRCLE_TOLERANCE));
|
||||
let output_shown = dot.output_highlight != Highlight::None;
|
||||
let fill = if dot.wired && !output_shown { wired } else { unwired };
|
||||
let mut graphic = List::new_from_item(painted(circle(DOT_RADIUS), Coverage::new_fill(), fill.into()));
|
||||
|
||||
if grown {
|
||||
let offset = if dot.previewed { DOT_PREVIEWED_RING_OFFSET } else { 0. };
|
||||
let ring = circle(DOT_RADIUS + offset + DOT_HOVERED_RING / 2.);
|
||||
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_HOVERED_RING * scale)), unwired.into()));
|
||||
} else if dot.previewed {
|
||||
let radius = DOT_RADIUS + DOT_PREVIEWED_RING_OFFSET + BORDER_WIDTH;
|
||||
let ring = Vector::item_from_bezpath(&border(center - radius, center + radius, radius, &[], true));
|
||||
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), wired.into()));
|
||||
} else if dot.selected {
|
||||
let ring = circle(DOT_RADIUS + DOT_SELECTED_RING / 2.);
|
||||
graphic.push(painted(ring, Coverage::new_stroke(&Stroke::new(DOT_SELECTED_RING)), Color::WHITE.with_alpha(SELECTED_DOT_RING_OPACITY)));
|
||||
}
|
||||
|
||||
if output_shown {
|
||||
graphic.extend(drawn_connector(&CONNECTOR_OUTLINE, center + DOT_OUTPUT_ARROW, dot.data_type, true, dot.output_highlight));
|
||||
}
|
||||
graphic
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_errors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<ErrorBadge, Paragraphs>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let badges = rows::<ErrorBadge>(&ctx, 0);
|
||||
let errors = badges.iter();
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(errors.clone().filter(|error| !error.hovered).chain(errors.filter(|error| error.hovered)), &mut cache, draw_error)?;
|
||||
|
||||
let shown: HashSet<&str> = badges.iter().map(|error| error.text.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_error(error: &ErrorBadge, paragraphs: &mut Paragraphs) -> Result<List<Vector>, TextToVectorError> {
|
||||
let paragraph = paragraphs.paragraph(&error.text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH)?;
|
||||
let [min, max] = error.body(paragraph.size);
|
||||
let mut badge = List::new_from_item(painted(rounded_rect(min, max, [ERROR_RADIUS; 4]), Coverage::new_fill(), ERROR_RED.into()));
|
||||
let corners = error.tail();
|
||||
let mut tail = BezPath::new();
|
||||
tail.move_to((corners[0].x, corners[0].y));
|
||||
for corner in &corners[1..] {
|
||||
tail.line_to((corner.x, corner.y));
|
||||
}
|
||||
tail.close_path();
|
||||
badge.push(painted(Vector::item_from_bezpath(&tail), Coverage::new_fill(), ERROR_RED.into()));
|
||||
|
||||
badge.extend(text(¶graph.outline, error.text_top_left(paragraph.size), ERROR_TEXT));
|
||||
|
||||
let mut grouped = rounded_rect(min, corners.into_iter().fold(max, DVec2::max), [0.; 4]);
|
||||
stamp_coverage(&mut grouped, Coverage::new_fill(), Graphic::VectorList(badge), CoverPlacement::Above);
|
||||
if !error.hovered {
|
||||
grouped.set_attribute(ATTR_OPACITY, ERROR_OPACITY);
|
||||
}
|
||||
Ok(List::new_from_item(grouped))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""), memoize)]
|
||||
fn draw_network_connectors(ctx: impl Ctx + ExtractVarArgs, #[data] cache: Cache<NetworkConnector, Labels>) -> Result<List<Vector>, TextToVectorError> {
|
||||
let network_connectors = rows::<NetworkConnector>(&ctx, 0);
|
||||
let mut cache = cache.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let graphic = draw_changed_rows(network_connectors, &mut cache, draw_network_connector)?;
|
||||
|
||||
let connectors = network_connectors.iter().filter_map(|row| row.connector.as_ref());
|
||||
let shown: HashSet<&str> = connectors.map(|connector| connector.name.as_str()).collect();
|
||||
cache.labels.retain(|text| shown.contains(text));
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
fn draw_network_connector(row: &NetworkConnector, labels: &mut Labels) -> Result<List<Vector>, TextToVectorError> {
|
||||
let Some(entry) = &row.connector else {
|
||||
return Ok(drawn_connector(&CONNECTOR_OUTLINE, row.connector_top_left(), DataType::General, false, row.add_highlight));
|
||||
};
|
||||
let mut graphic = connector(&CONNECTOR_OUTLINE, row.connector_top_left(), entry);
|
||||
let name = labels.label(&entry.name, f64::INFINITY)?;
|
||||
if !row.renaming {
|
||||
let [top_left, _] = row.name_box(name.width);
|
||||
graphic.extend(text(&name.outline, top_left, TEXT));
|
||||
}
|
||||
if row.editable && row.index < 2 {
|
||||
let [min, max] = row.separator(name.width);
|
||||
graphic.push(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), SEPARATOR.into()));
|
||||
}
|
||||
Ok(graphic)
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_reorder_bar(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some((kind, anchor)) = graph_ui(&ctx).config.reorder_bar else { return List::new() };
|
||||
let [min, max] = reorder_bar(kind, anchor);
|
||||
List::new_from_item(painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::WHITE))
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn draw_box_selection(ctx: impl Ctx + ExtractVarArgs) -> List<Vector> {
|
||||
let Some([start, end]) = graph_ui(&ctx).config.box_selection else { return List::new() };
|
||||
let min = start.min(end);
|
||||
let max = min + (end - start).abs() + 2. * BORDER_WIDTH;
|
||||
let fill = painted(rounded_rect(min, max, [0.; 4]), Coverage::new_fill(), Color::from(BOX_SELECTION).with_alpha(BOX_SELECTION_FILL_OPACITY));
|
||||
let [inner_min, inner_max] = [min + BORDER_WIDTH / 2., max - BORDER_WIDTH / 2.];
|
||||
let outline = Rect::new(inner_min.x, inner_min.y, inner_max.x, inner_max.y).to_path(0.);
|
||||
let border = painted(Vector::item_from_bezpath(&outline), Coverage::new_stroke(&Stroke::new(BORDER_WIDTH)), BOX_SELECTION.into());
|
||||
List::from_iter([fill, border])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::network_connector::NetworkConnectorKind;
|
||||
use crate::render::rows_context;
|
||||
use crate::scene::GraphUiScene;
|
||||
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
|
||||
use core_types::bounds::{BoundingBox, RenderBoundingBox};
|
||||
use core_types::uuid::NodeId;
|
||||
use vello_gpu::kurbo::PathEl;
|
||||
|
||||
fn bounds(graphic: &List<Vector>) -> RenderBoundingBox {
|
||||
graphic.bounding_box(DAffine2::IDENTITY, false)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_card_that_only_moved_to_another_cell_keeps_its_vectors_and_is_drawn_at_that_cell() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.put(Card {
|
||||
name: "Path".to_string(),
|
||||
cell: IVec2::new(2, 1),
|
||||
..card(0)
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::new(-3, 5));
|
||||
let (scene, _) = edit.finish();
|
||||
let moved = draw(scene.clone());
|
||||
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a moved card keeps its vectors");
|
||||
let in_place = draw_card(scene.cards().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
|
||||
assert_eq!(bounds(&moved), bounds(&in_place), "a moved card is drawn at its new cell");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_gliding_layer_keeps_its_vectors_and_is_drawn_its_glide_away() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_layers(rows_context(scene.layers()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.layers.put(Layer {
|
||||
name: "Path".to_string(),
|
||||
cell: IVec2::new(2, 1),
|
||||
..layer(0)
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let drawn = cache.lock().unwrap().drawn[&NodeId(0)].1.elements_witness();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.layers.update(&NodeId(0), |layer| layer.glide = DVec2::new(-7.25, 3.5));
|
||||
let (scene, _) = edit.finish();
|
||||
let gliding = draw(scene.clone());
|
||||
assert!(drawn.matches(&cache.lock().unwrap().drawn[&NodeId(0)].1), "a gliding layer keeps its vectors");
|
||||
let in_place = draw_layer(scene.layers().get(&NodeId(0)).unwrap(), &mut Labels::default()).unwrap();
|
||||
assert_eq!(bounds(&gliding), bounds(&in_place), "a gliding layer is drawn its glide away");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dot_whose_look_changed_is_drawn_again_while_a_dot_that_only_moved_keeps_its_vectors() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_dots(rows_context(scene.dots()), &cache);
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.dots.replace_all([dot(0), dot(1)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
|
||||
let [moved, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.dots.update(&NodeId(0), |dot| dot.cell = IVec2::new(4, -2));
|
||||
edit.dots.update(&NodeId(1), |dot| {
|
||||
dot.cell = IVec2::new(4, 2);
|
||||
dot.selected = true;
|
||||
});
|
||||
let (scene, _) = edit.finish();
|
||||
let drawn = draw(scene.clone());
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(moved.matches(&cache.drawn[&NodeId(0)].1), "a dot that only moved keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a dot whose look changed is drawn again");
|
||||
let in_place: List<Vector> = scene.dots().iter().flat_map(draw_dot).collect();
|
||||
assert_eq!(bounds(&drawn), bounds(&in_place), "both dots are drawn at their new cells");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_cards_that_changed_are_drawn_again() {
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_cards(rows_context(scene.cards()), &cache).unwrap();
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all([card(0), card(1), card(2)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |key| cache.lock().unwrap().drawn[&NodeId(key)].1.elements_witness();
|
||||
let [unchanged, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.update(&NodeId(1), |card| card.selection = Selection::Active);
|
||||
edit.cards.remove(&NodeId(2));
|
||||
draw(edit.finish().0);
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(unchanged.matches(&cache.drawn[&NodeId(0)].1), "an unchanged card keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&NodeId(1)].1), "a changed card is drawn again");
|
||||
assert!(!cache.drawn.contains_key(&NodeId(2)), "a removed card is forgotten");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_card_shows_it() {
|
||||
let named = |key, name: &str| Card { name: name.to_string(), ..card(key) };
|
||||
let cache = Default::default();
|
||||
let draw = |cards: Vec<Card>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all(cards);
|
||||
draw_cards(rows_context(edit.finish().0.cards()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(0, "Path"), named(1, "Fill")]);
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, NODE_NAME_MAX_WIDTH).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(0, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(
|
||||
path.matches(&cache.labels.label("Path", NODE_NAME_MAX_WIDTH).unwrap().outline),
|
||||
"the label of a text still shown is kept"
|
||||
);
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", NODE_NAME_MAX_WIDTH).unwrap().outline),
|
||||
"the label of a text no card shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_layer_shows_it() {
|
||||
let named = |key, name: &str| Layer { name: name.to_string(), ..layer(key) };
|
||||
let cache = Default::default();
|
||||
let draw = |layers: Vec<Layer>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.layers.replace_all(layers);
|
||||
draw_layers(rows_context(edit.finish().0.layers()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(0, "Path"), named(1, "Fill")]);
|
||||
let max_width = layer(0).name_width();
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, max_width).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(0, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(path.matches(&cache.labels.label("Path", max_width).unwrap().outline), "the label of a text still shown is kept");
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", max_width).unwrap().outline),
|
||||
"the label of a text no layer shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_label_of_a_text_is_forgotten_once_no_import_or_export_shows_it() {
|
||||
let named = |kind, name: &str| NetworkConnector {
|
||||
connector: Some(connector(name)),
|
||||
..network_connector(kind, 0)
|
||||
};
|
||||
let cache = Default::default();
|
||||
let draw = |rows: Vec<NetworkConnector>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.network_connectors.replace_all(rows);
|
||||
draw_network_connectors(rows_context(edit.finish().0.network_connectors()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![named(NetworkConnectorKind::Import, "Path"), named(NetworkConnectorKind::Export, "Fill")]);
|
||||
let label = |text| cache.lock().unwrap().labels.label(text, f64::INFINITY).unwrap().outline.elements_witness();
|
||||
let [path, fill] = [label("Path"), label("Fill")];
|
||||
|
||||
draw(vec![named(NetworkConnectorKind::Import, "Path")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(path.matches(&cache.labels.label("Path", f64::INFINITY).unwrap().outline), "the label of a text still shown is kept");
|
||||
assert!(
|
||||
!fill.matches(&cache.labels.label("Fill", f64::INFINITY).unwrap().outline),
|
||||
"the label of a text no import or export shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_paragraph_of_an_error_is_forgotten_once_no_badge_shows_it() {
|
||||
let cache = Default::default();
|
||||
let draw = |badges: Vec<ErrorBadge>| {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.errors.replace_all(badges);
|
||||
draw_errors(rows_context(edit.finish().0.errors()), &cache).unwrap();
|
||||
};
|
||||
draw(vec![badge(0, "Failed"), badge(1, "Missing input")]);
|
||||
let paragraph = |text| cache.lock().unwrap().labels.paragraph(text, ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline.elements_witness();
|
||||
let [failed, missing] = [paragraph("Failed"), paragraph("Missing input")];
|
||||
|
||||
draw(vec![badge(0, "Failed")]);
|
||||
let mut cache = cache.lock().unwrap();
|
||||
assert!(
|
||||
failed.matches(&cache.labels.paragraph("Failed", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
|
||||
"the paragraph of a text still shown is kept"
|
||||
);
|
||||
assert!(
|
||||
!missing.matches(&cache.labels.paragraph("Missing input", ERROR_LINE_HEIGHT, ERROR_MAX_WIDTH).unwrap().outline),
|
||||
"the paragraph of a text no badge shows is laid out again"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_column_groups_of_a_grid_dot_light_each_pixel_of_its_disc_once() {
|
||||
for (radius, groups, pixels) in [(1, 1, 4), (2, 2, 12), (3, 2, 32), (4, 3, 52)] {
|
||||
let disc: Vec<[u32; 2]> = (0..2 * radius)
|
||||
.flat_map(|row| (0..2 * radius).map(move |column| [column, row]))
|
||||
.filter(|&[column, row]| (column as f64 + 0.5 - radius as f64).hypot(row as f64 + 0.5 - radius as f64) < radius as f64)
|
||||
.collect();
|
||||
let columns = disc_columns(radius);
|
||||
let mut lit: Vec<[u32; 2]> = columns
|
||||
.iter()
|
||||
.flat_map(|(&[top, bottom], runs)| (top..bottom).flat_map(move |row| runs.iter().flat_map(move |&[left, right]| (left..right).map(move |column| [column, row]))))
|
||||
.collect();
|
||||
lit.sort_by_key(|&[column, row]| [row, column]);
|
||||
assert_eq!((columns.len(), disc.len()), (groups, pixels), "the groups and pixels of the disc at radius {radius}");
|
||||
assert_eq!(lit, disc, "every pixel of the disc at radius {radius} is lit by exactly one group");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_wires_that_changed_are_drawn_again() {
|
||||
let key = |node| WireKey::Input { node: NodeId(node), index: 0 };
|
||||
let at = |node, y: f64| Wire {
|
||||
path: BezPath::from_vec(vec![PathEl::MoveTo((0., y).into()), PathEl::LineTo((48., y).into())]),
|
||||
..wire(key(node))
|
||||
};
|
||||
let cache = Default::default();
|
||||
let draw = |scene: GraphUiScene| draw_wires(rows_context(scene.wires()), &cache);
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.wires.replace_all([at(0, 0.), at(1, 24.)]);
|
||||
let (scene, _) = edit.finish();
|
||||
draw(scene.clone());
|
||||
let witness = |node| cache.lock().unwrap().drawn[&key(node)].1.elements_witness();
|
||||
let [unchanged, changed] = [witness(0), witness(1)];
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.wires.put(at(1, 48.));
|
||||
draw(edit.finish().0);
|
||||
let cache = cache.lock().unwrap();
|
||||
assert!(unchanged.matches(&cache.drawn[&key(0)].1), "the other wire keeps its vectors");
|
||||
assert!(!changed.matches(&cache.drawn[&key(1)].1), "the changed wire is drawn again");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
use crate::look::{BACKDROP, painted, rounded_rect};
|
||||
use crate::replicated_map::{Keyed, ReplicatedMap};
|
||||
use crate::{GraphUi, nodes};
|
||||
use core_types::list::{Item, List};
|
||||
use core_types::{CacheHash, CloneVarArgs, Color, Context, Ctx, ExtractAll, ExtractVarArgs, Interrupt, NodeError, OwnedContextImpl, ProtoNodeIdentifier};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType};
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeId, NodeInput, NodeNetwork};
|
||||
use graphene_application_io::RenderConfig;
|
||||
use graphic_types::{Coverage, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderParams};
|
||||
use std::error::Error;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
const BANDS: [ProtoNodeIdentifier; 13] = [
|
||||
nodes::draw_grid::IDENTIFIER,
|
||||
nodes::draw_thick_wires::IDENTIFIER,
|
||||
nodes::draw_layers::IDENTIFIER,
|
||||
nodes::draw_thumbnails::IDENTIFIER,
|
||||
nodes::draw_wires::IDENTIFIER,
|
||||
nodes::draw_wire_in_progress::IDENTIFIER,
|
||||
nodes::draw_cards::IDENTIFIER,
|
||||
nodes::draw_dots::IDENTIFIER,
|
||||
nodes::draw_raised::IDENTIFIER,
|
||||
nodes::draw_errors::IDENTIFIER,
|
||||
nodes::draw_network_connectors::IDENTIFIER,
|
||||
nodes::draw_reorder_bar::IDENTIFIER,
|
||||
nodes::draw_box_selection::IDENTIFIER,
|
||||
];
|
||||
|
||||
pub fn network() -> NodeNetwork {
|
||||
let node = |identifier, inputs| DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
let mut network = NodeNetwork::default();
|
||||
let root = NodeId(BANDS.len() as u64);
|
||||
let mut inputs = Vec::new();
|
||||
for (band, identifier) in (0..).map(NodeId).zip(BANDS) {
|
||||
network.nodes.insert(band, node(identifier, Vec::new()));
|
||||
inputs.push(NodeInput::node(band, 0));
|
||||
}
|
||||
inputs.push(NodeInput::scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER));
|
||||
network.nodes.insert(root, node(render_graph_ui::IDENTIFIER, inputs));
|
||||
network.exports.push(NodeInput::node(root, 0));
|
||||
network
|
||||
}
|
||||
|
||||
#[node_macro::node(category(""))]
|
||||
fn render_graph_ui(
|
||||
ctx: impl Ctx + ExtractVarArgs + ExtractAll + CloneVarArgs,
|
||||
grid: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
thick_wires: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
layers: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
thumbnails: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
wires: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
wire_in_progress: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
cards: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
dots: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
raised: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
errors: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
imports_exports: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
reorder_bar: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
box_selection: impl Node<Context<'static>, Output = List<Vector>>,
|
||||
#[scope(graphene_std::platform_application_io::wgpu_executor::IDENTIFIER)] executor: impl Node<Context<'static>, Output = Item<WgpuExecutor>>,
|
||||
) -> Result<Item<RenderOutput>, Interrupt> {
|
||||
let render_config = *render_config(&ctx);
|
||||
let context = OwnedContextImpl::from(ctx).into_context();
|
||||
let graph_ui = graph_ui(&context);
|
||||
|
||||
let viewport_size = render_config.viewport.resolution.as_dvec2() / render_config.scale;
|
||||
let opacity = graph_ui.config.fade_artwork as f32;
|
||||
let backdrop = painted(rounded_rect(DVec2::ZERO, viewport_size, [0.; 4]), Coverage::new_fill(), Color::from(BACKDROP).with_alpha(opacity));
|
||||
let mut drawn = vec![(List::new_from_item(backdrop), DAffine2::IDENTITY)];
|
||||
let scene = &graph_ui.scene;
|
||||
let wire_rows = rows_context(scene.wires());
|
||||
let raised_rows = OwnedContextImpl::default()
|
||||
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
|
||||
.into_context();
|
||||
let bands = [
|
||||
(grid.eval(&context)?, DAffine2::IDENTITY),
|
||||
(thick_wires.eval(&wire_rows)?, graph_ui.config.view),
|
||||
(layers.eval(&rows_context(scene.layers()))?, graph_ui.config.view),
|
||||
(thumbnails.eval(&context)?, graph_ui.config.view),
|
||||
(wires.eval(&wire_rows)?, graph_ui.config.view),
|
||||
(wire_in_progress.eval(&context)?, graph_ui.config.view),
|
||||
(cards.eval(&rows_context(scene.cards()))?, graph_ui.config.view),
|
||||
(dots.eval(&rows_context(scene.dots()))?, graph_ui.config.view),
|
||||
(raised.eval(&raised_rows)?, graph_ui.config.view),
|
||||
(errors.eval(&rows_context(scene.errors()))?, graph_ui.config.view),
|
||||
(imports_exports.eval(&rows_context(scene.network_connectors()))?, graph_ui.config.view),
|
||||
(reorder_bar.eval(&context)?, graph_ui.config.view),
|
||||
(box_selection.eval(&context)?, DAffine2::IDENTITY),
|
||||
];
|
||||
drawn.extend(bands);
|
||||
|
||||
let executor = executor.eval(&Context::default())?.into_element();
|
||||
let data = raster_frame(&executor, &drawn, &render_config).map_err(NodeError::new)?;
|
||||
Ok(Item::new_from_element(RenderOutput { data, metadata: Default::default() }))
|
||||
}
|
||||
|
||||
fn raster_frame(executor: &WgpuExecutor, drawn: &[(List<Vector>, DAffine2)], render_config: &RenderConfig) -> Result<RenderOutputType, Box<dyn Error + Send + Sync>> {
|
||||
let viewport = DAffine2::from_scale(DVec2::splat(render_config.scale));
|
||||
let mut draw = |scene: &mut VelloSceneBuilder| {
|
||||
for (band, transform) in drawn {
|
||||
band.render_to_vello(scene, viewport * *transform, &RenderParams::default());
|
||||
}
|
||||
};
|
||||
let texture = executor.render_vello(render_config.viewport.resolution, DAffine2::IDENTITY, &mut draw)?;
|
||||
Ok(RenderOutputType::Texture(texture))
|
||||
}
|
||||
|
||||
pub fn context(render_config: RenderConfig, graph_ui: GraphUi) -> OwnedContextImpl {
|
||||
OwnedContextImpl::default().with_varargs([Box::new(render_config), Box::new(graph_ui)])
|
||||
}
|
||||
|
||||
pub fn rows_context<T: Keyed + CacheHash + Send + Sync + 'static>(rows: &ReplicatedMap<T>) -> Context<'static> {
|
||||
OwnedContextImpl::default().with_vararg(Box::new(rows.clone())).into_context()
|
||||
}
|
||||
|
||||
pub(crate) fn render_config(ctx: &impl ExtractVarArgs) -> &RenderConfig {
|
||||
ctx.vararg(0).ok().and_then(|config| config.downcast_ref()).expect("The render config is the first vararg")
|
||||
}
|
||||
|
||||
pub(crate) fn graph_ui(ctx: &impl ExtractVarArgs) -> &GraphUi {
|
||||
ctx.vararg(1).ok().and_then(|graph_ui| graph_ui.downcast_ref()).expect("The graph UI is the second vararg")
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
use graphene_hash::CacheHash;
|
||||
use std::fmt::Debug;
|
||||
use std::hash::{DefaultHasher, Hasher};
|
||||
use std::ops::Deref;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
pub trait Keyed: Clone {
|
||||
type Key: Ord + Clone + Debug;
|
||||
|
||||
fn key(&self) -> Self::Key;
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ReplicatedMap<T: Keyed> {
|
||||
items: Arc<Vec<T>>,
|
||||
hash: Arc<OnceLock<u64>>,
|
||||
}
|
||||
|
||||
impl<T: Keyed> Default for ReplicatedMap<T> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
items: Arc::default(),
|
||||
hash: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed + PartialEq> PartialEq for ReplicatedMap<T> {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.items == other.items
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed + CacheHash> CacheHash for ReplicatedMap<T> {
|
||||
fn cache_hash<H: Hasher>(&self, state: &mut H) {
|
||||
let hash = self.hash.get_or_init(|| {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
self.items.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
});
|
||||
state.write_u64(*hash);
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed> ReplicatedMap<T> {
|
||||
pub fn get(&self, key: &T::Key) -> Option<&T> {
|
||||
self.position(key).ok().map(|index| &self.items[index])
|
||||
}
|
||||
|
||||
pub fn iter(&self) -> std::slice::Iter<'_, T> {
|
||||
self.items.iter()
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.items.is_empty()
|
||||
}
|
||||
|
||||
pub fn edit(self) -> ReplicatedMapEdit<T> {
|
||||
ReplicatedMapEdit { map: self, deltas: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, deltas: impl IntoIterator<Item = ReplicatedMapDelta<T>>) {
|
||||
for delta in deltas {
|
||||
match delta {
|
||||
ReplicatedMapDelta::Put(item) => self.put(item),
|
||||
ReplicatedMapDelta::Remove(key) => {
|
||||
let removed = self.remove(&key);
|
||||
debug_assert!(removed, "a delta removes an item that its map never held");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn position(&self, key: &T::Key) -> Result<usize, usize> {
|
||||
self.items.binary_search_by(|item| item.key().cmp(key))
|
||||
}
|
||||
|
||||
fn items_mut(&mut self) -> &mut Vec<T> {
|
||||
self.hash = Arc::default();
|
||||
Arc::make_mut(&mut self.items)
|
||||
}
|
||||
|
||||
fn put(&mut self, item: T) {
|
||||
match self.position(&item.key()) {
|
||||
Ok(index) => self.items_mut()[index] = item,
|
||||
Err(index) => self.items_mut().insert(index, item),
|
||||
}
|
||||
}
|
||||
|
||||
fn remove(&mut self, key: &T::Key) -> bool {
|
||||
let position = self.position(key);
|
||||
if let Ok(index) = position {
|
||||
self.items_mut().remove(index);
|
||||
}
|
||||
position.is_ok()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, T: Keyed> IntoIterator for &'a ReplicatedMap<T> {
|
||||
type Item = &'a T;
|
||||
type IntoIter = std::slice::Iter<'a, T>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
self.iter()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum ReplicatedMapDelta<T: Keyed> {
|
||||
Put(T),
|
||||
Remove(T::Key),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct ReplicatedMapEdit<T: Keyed> {
|
||||
map: ReplicatedMap<T>,
|
||||
deltas: Vec<ReplicatedMapDelta<T>>,
|
||||
}
|
||||
|
||||
impl<T: Keyed> Deref for ReplicatedMapEdit<T> {
|
||||
type Target = ReplicatedMap<T>;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.map
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Keyed> ReplicatedMapEdit<T> {
|
||||
pub fn put(&mut self, item: T)
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
if self.map.get(&item.key()) == Some(&item) {
|
||||
return;
|
||||
}
|
||||
self.map.put(item.clone());
|
||||
self.deltas.push(ReplicatedMapDelta::Put(item));
|
||||
}
|
||||
|
||||
pub fn update(&mut self, key: &T::Key, change: impl FnOnce(&mut T)) -> bool {
|
||||
let Ok(index) = self.map.position(key) else { return false };
|
||||
let item = &mut self.map.items_mut()[index];
|
||||
change(item);
|
||||
debug_assert!(item.key() == *key, "an update must not change the key of its item");
|
||||
self.deltas.push(ReplicatedMapDelta::Put(item.clone()));
|
||||
true
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, key: &T::Key) -> bool {
|
||||
let removed = self.map.remove(key);
|
||||
if removed {
|
||||
self.deltas.push(ReplicatedMapDelta::Remove(key.clone()));
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn replace_all(&mut self, items: impl IntoIterator<Item = T>)
|
||||
where
|
||||
T: PartialEq,
|
||||
{
|
||||
let mut items: Vec<T> = items.into_iter().collect();
|
||||
items.sort_by_key(T::key);
|
||||
debug_assert!(items.windows(2).all(|pair| pair[0].key() != pair[1].key()), "two items of a map share a key");
|
||||
|
||||
let removed = self.map.iter().rev().map(T::key).filter(|key| items.binary_search_by(|item| item.key().cmp(key)).is_err());
|
||||
self.deltas.extend(removed.map(ReplicatedMapDelta::Remove));
|
||||
let put = items.iter().filter(|item| self.map.get(&item.key()) != Some(item));
|
||||
self.deltas.extend(put.cloned().map(ReplicatedMapDelta::Put));
|
||||
|
||||
*self.map.items_mut() = items;
|
||||
}
|
||||
|
||||
pub fn finish(self) -> (ReplicatedMap<T>, Vec<ReplicatedMapDelta<T>>) {
|
||||
(self.map, self.deltas)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
struct Item {
|
||||
key: u8,
|
||||
value: u8,
|
||||
}
|
||||
|
||||
impl Keyed for Item {
|
||||
type Key = u8;
|
||||
|
||||
fn key(&self) -> u8 {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
fn item(key: u8, value: u8) -> Item {
|
||||
Item { key, value }
|
||||
}
|
||||
|
||||
fn map(items: &[Item]) -> ReplicatedMap<Item> {
|
||||
let mut edit = ReplicatedMap::default().edit();
|
||||
edit.replace_all(items.iter().copied());
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn small_maps() -> Vec<Vec<Item>> {
|
||||
let choices = [None, Some(0), Some(1)];
|
||||
let mut maps = Vec::new();
|
||||
for a in choices {
|
||||
for b in choices {
|
||||
for c in choices {
|
||||
maps.push([a, b, c].into_iter().zip(0..).filter_map(|(value, key)| Some(item(key, value?))).collect());
|
||||
}
|
||||
}
|
||||
}
|
||||
maps
|
||||
}
|
||||
|
||||
fn hash(map: &ReplicatedMap<Item>) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
map.cache_hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_copy_that_applies_the_deltas_of_an_edit_holds_the_same_items() {
|
||||
for old in small_maps() {
|
||||
for new in small_maps() {
|
||||
let mut copy = map(&old);
|
||||
|
||||
let mut edit = map(&old).edit();
|
||||
edit.replace_all(new.iter().copied());
|
||||
let (replaced, deltas) = edit.finish();
|
||||
assert_eq!(replaced, map(&new));
|
||||
assert_eq!(deltas.is_empty(), old == new, "{old:?} to {new:?}");
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, replaced, "{old:?} to {new:?}");
|
||||
|
||||
let mut copy = map(&old);
|
||||
let mut edit = map(&old).edit();
|
||||
for item in &old {
|
||||
assert!(edit.remove(&item.key));
|
||||
}
|
||||
for item in new.iter().rev() {
|
||||
edit.put(*item);
|
||||
}
|
||||
let (rebuilt, deltas) = edit.finish();
|
||||
assert_eq!(rebuilt, map(&new));
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, rebuilt, "{old:?} to {new:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn items_are_held_in_key_order_and_found_by_key() {
|
||||
let mut edit = ReplicatedMap::default().edit();
|
||||
edit.put(item(2, 0));
|
||||
edit.put(item(0, 0));
|
||||
edit.put(item(1, 0));
|
||||
edit.put(item(0, 1));
|
||||
assert_eq!(edit.get(&0), Some(&item(0, 1)), "an edit reads what it has done so far");
|
||||
let (map, _) = edit.finish();
|
||||
|
||||
assert_eq!(map.iter().copied().collect::<Vec<_>>(), [item(0, 1), item(1, 0), item(2, 0)]);
|
||||
assert_eq!(map.get(&1), Some(&item(1, 0)));
|
||||
assert_eq!(map.get(&3), None);
|
||||
assert_eq!(map.len(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_put_of_the_item_already_held_records_no_delta() {
|
||||
let mut edit = map(&[item(0, 0)]).edit();
|
||||
edit.put(item(0, 0));
|
||||
assert!(edit.finish().1.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_update_changes_the_item_in_the_copy_too() {
|
||||
let mut copy = map(&[item(0, 0), item(1, 0)]);
|
||||
|
||||
let mut edit = copy.clone().edit();
|
||||
assert!(edit.update(&1, |item| item.value = 1));
|
||||
assert!(!edit.update(&2, |item| item.value = 1));
|
||||
assert!(!edit.remove(&2));
|
||||
let (updated, deltas) = edit.finish();
|
||||
|
||||
assert_eq!(updated, map(&[item(0, 0), item(1, 1)]));
|
||||
copy.apply(deltas);
|
||||
assert_eq!(copy, updated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_leaves_other_holders_of_the_set_as_they_were() {
|
||||
let held = map(&[item(0, 0)]);
|
||||
|
||||
let mut edit = held.clone().edit();
|
||||
edit.put(item(1, 0));
|
||||
edit.remove(&0);
|
||||
|
||||
assert_eq!(held, map(&[item(0, 0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hash_follows_the_items() {
|
||||
let a = map(&[item(0, 0), item(1, 0)]);
|
||||
let held = a.clone();
|
||||
assert!(a.hash.get().is_none(), "nothing asked for the hash yet");
|
||||
assert_eq!(hash(&a), hash(&map(&[item(1, 0), item(0, 0)])));
|
||||
assert!(a.hash.get().is_some());
|
||||
assert!(held.hash.get().is_some(), "a clone made before shares the hash");
|
||||
|
||||
let mut edit = a.clone().edit();
|
||||
edit.update(&1, |item| item.value = 1);
|
||||
let (b, deltas) = edit.finish();
|
||||
assert!(b.hash.get().is_none(), "a change empties the hash");
|
||||
assert_ne!(hash(&a), hash(&b));
|
||||
|
||||
let mut copy = a.clone();
|
||||
copy.apply(deltas);
|
||||
assert!(copy.hash.get().is_none());
|
||||
assert_eq!(hash(©), hash(&b));
|
||||
|
||||
let mut edit = b.edit();
|
||||
edit.update(&1, |item| item.value = 0);
|
||||
assert_eq!(hash(&edit.finish().0), hash(&a), "the same items again hash the same");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
use crate::card::Card;
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::Layer;
|
||||
use crate::network_connector::NetworkConnector;
|
||||
use crate::replicated_map::{ReplicatedMap, ReplicatedMapDelta, ReplicatedMapEdit};
|
||||
use crate::wire::Wire;
|
||||
use graphene_hash::CacheHash;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, CacheHash)]
|
||||
pub struct GraphUiScene {
|
||||
cards: ReplicatedMap<Card>,
|
||||
layers: ReplicatedMap<Layer>,
|
||||
dots: ReplicatedMap<Dot>,
|
||||
wires: ReplicatedMap<Wire>,
|
||||
network_connectors: ReplicatedMap<NetworkConnector>,
|
||||
errors: ReplicatedMap<ErrorBadge>,
|
||||
}
|
||||
|
||||
impl GraphUiScene {
|
||||
pub fn cards(&self) -> &ReplicatedMap<Card> {
|
||||
&self.cards
|
||||
}
|
||||
|
||||
pub fn layers(&self) -> &ReplicatedMap<Layer> {
|
||||
&self.layers
|
||||
}
|
||||
|
||||
pub fn dots(&self) -> &ReplicatedMap<Dot> {
|
||||
&self.dots
|
||||
}
|
||||
|
||||
pub fn wires(&self) -> &ReplicatedMap<Wire> {
|
||||
&self.wires
|
||||
}
|
||||
|
||||
pub fn network_connectors(&self) -> &ReplicatedMap<NetworkConnector> {
|
||||
&self.network_connectors
|
||||
}
|
||||
|
||||
pub fn errors(&self) -> &ReplicatedMap<ErrorBadge> {
|
||||
&self.errors
|
||||
}
|
||||
|
||||
pub fn edit(self) -> GraphUiSceneEdit {
|
||||
GraphUiSceneEdit {
|
||||
cards: self.cards.edit(),
|
||||
layers: self.layers.edit(),
|
||||
dots: self.dots.edit(),
|
||||
wires: self.wires.edit(),
|
||||
network_connectors: self.network_connectors.edit(),
|
||||
errors: self.errors.edit(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply(&mut self, delta: GraphUiSceneDelta) {
|
||||
self.cards.apply(delta.cards);
|
||||
self.layers.apply(delta.layers);
|
||||
self.dots.apply(delta.dots);
|
||||
self.wires.apply(delta.wires);
|
||||
self.network_connectors.apply(delta.network_connectors);
|
||||
self.errors.apply(delta.errors);
|
||||
}
|
||||
}
|
||||
|
||||
pub struct GraphUiSceneEdit {
|
||||
pub cards: ReplicatedMapEdit<Card>,
|
||||
pub layers: ReplicatedMapEdit<Layer>,
|
||||
pub dots: ReplicatedMapEdit<Dot>,
|
||||
pub wires: ReplicatedMapEdit<Wire>,
|
||||
pub network_connectors: ReplicatedMapEdit<NetworkConnector>,
|
||||
pub errors: ReplicatedMapEdit<ErrorBadge>,
|
||||
}
|
||||
|
||||
impl GraphUiSceneEdit {
|
||||
pub fn finish(self) -> (GraphUiScene, GraphUiSceneDelta) {
|
||||
let (cards, card_deltas) = self.cards.finish();
|
||||
let (layers, layer_deltas) = self.layers.finish();
|
||||
let (dots, dot_deltas) = self.dots.finish();
|
||||
let (wires, wire_deltas) = self.wires.finish();
|
||||
let (network_connectors, network_connector_deltas) = self.network_connectors.finish();
|
||||
let (errors, error_deltas) = self.errors.finish();
|
||||
(
|
||||
GraphUiScene {
|
||||
cards,
|
||||
layers,
|
||||
dots,
|
||||
wires,
|
||||
network_connectors,
|
||||
errors,
|
||||
},
|
||||
GraphUiSceneDelta {
|
||||
cards: card_deltas,
|
||||
layers: layer_deltas,
|
||||
dots: dot_deltas,
|
||||
wires: wire_deltas,
|
||||
network_connectors: network_connector_deltas,
|
||||
errors: error_deltas,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct GraphUiSceneDelta {
|
||||
cards: Vec<ReplicatedMapDelta<Card>>,
|
||||
layers: Vec<ReplicatedMapDelta<Layer>>,
|
||||
dots: Vec<ReplicatedMapDelta<Dot>>,
|
||||
wires: Vec<ReplicatedMapDelta<Wire>>,
|
||||
network_connectors: Vec<ReplicatedMapDelta<NetworkConnector>>,
|
||||
errors: Vec<ReplicatedMapDelta<ErrorBadge>>,
|
||||
}
|
||||
|
||||
impl GraphUiSceneDelta {
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.cards.is_empty() && self.layers.is_empty() && self.dots.is_empty() && self.wires.is_empty() && self.network_connectors.is_empty() && self.errors.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::network_connector::NetworkConnectorKind;
|
||||
use crate::test_utils::{badge, card, connector, dot, layer, network_connector, wire};
|
||||
use crate::wire::WireKey;
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::IVec2;
|
||||
|
||||
#[test]
|
||||
fn a_copy_that_applies_the_delta_of_an_edit_equals_the_edited_scene() {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all([card(0), card(1)]);
|
||||
let (scene, _) = edit.finish();
|
||||
let mut copy = scene.clone();
|
||||
|
||||
let mut edit = scene.edit();
|
||||
edit.cards.put(card(2));
|
||||
edit.cards.update(&NodeId(0), |card| card.cell = IVec2::ONE);
|
||||
edit.cards.remove(&NodeId(1));
|
||||
edit.layers.put(layer(4));
|
||||
edit.dots.put(dot(3));
|
||||
edit.wires.put(wire(WireKey::Input { node: NodeId(2), index: 0 }));
|
||||
edit.network_connectors.put(network_connector(NetworkConnectorKind::Import, 0));
|
||||
edit.network_connectors.put(NetworkConnector {
|
||||
connector: Some(connector("Canvas")),
|
||||
..network_connector(NetworkConnectorKind::Export, 0)
|
||||
});
|
||||
edit.errors.put(badge(2, "An error"));
|
||||
let (edited, delta) = edit.finish();
|
||||
|
||||
assert!(!delta.is_empty());
|
||||
copy.apply(delta);
|
||||
assert_eq!(copy, edited);
|
||||
|
||||
let mut edit = copy.edit();
|
||||
edit.errors.remove(&NodeId(2));
|
||||
assert!(!edit.finish().1.is_empty(), "a change to one map is a delta");
|
||||
|
||||
assert!(edited.edit().finish().1.is_empty(), "an edit that changes nothing has no deltas");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
use crate::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use crate::dot::Dot;
|
||||
use crate::error_badge::ErrorBadge;
|
||||
use crate::layer::Layer;
|
||||
use crate::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use crate::wire::{Wire, WireKey};
|
||||
use core_types::uuid::NodeId;
|
||||
use glam::{DVec2, IVec2};
|
||||
use vello_gpu::kurbo::BezPath;
|
||||
|
||||
pub(crate) fn card(key: u64) -> Card {
|
||||
Card {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
name: String::new(),
|
||||
icon: String::new(),
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_inputs: Vec::new(),
|
||||
secondary_outputs: Vec::new(),
|
||||
selection: Selection::None,
|
||||
visible: true,
|
||||
previewed: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn layer(key: u64) -> Layer {
|
||||
Layer {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
name: String::new(),
|
||||
renaming: false,
|
||||
width: 8,
|
||||
chain_width: 0,
|
||||
has_left_input_wire: false,
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_input: None,
|
||||
primary_input_connected_to_layer: false,
|
||||
primary_output_connected_to_layer: false,
|
||||
visible: true,
|
||||
locked: false,
|
||||
read_only: false,
|
||||
selection: Selection::None,
|
||||
previewed: false,
|
||||
hovered_button: None,
|
||||
hovered_button_clicked: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dot(key: u64) -> Dot {
|
||||
Dot {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
data_type: DataType::General,
|
||||
wired: false,
|
||||
selected: false,
|
||||
previewed: false,
|
||||
highlight: Highlight::None,
|
||||
output_highlight: Highlight::None,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn wire(key: WireKey) -> Wire {
|
||||
Wire {
|
||||
key,
|
||||
path: BezPath::new(),
|
||||
data_type: DataType::General,
|
||||
thick: false,
|
||||
center_line: BezPath::new(),
|
||||
list: false,
|
||||
insertion_target: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn network_connector(kind: NetworkConnectorKind, index: usize) -> NetworkConnector {
|
||||
NetworkConnector {
|
||||
kind,
|
||||
index,
|
||||
position: IVec2::ZERO,
|
||||
connector: None,
|
||||
add_highlight: Highlight::None,
|
||||
editable: false,
|
||||
renaming: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn badge(key: u64, text: &str) -> ErrorBadge {
|
||||
ErrorBadge {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::ZERO,
|
||||
on_layer: false,
|
||||
text: text.to_string(),
|
||||
hovered: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn connector(name: &str) -> Connector {
|
||||
Connector {
|
||||
name: name.to_string(),
|
||||
data_type: DataType::General,
|
||||
connected: false,
|
||||
highlight: Highlight::None,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use crate::metrics::{GRID_SIZE, TEXT_SIZE};
|
||||
use core_types::list::{ATTR_GEOMETRY_CACHE, List};
|
||||
use glam::DVec2;
|
||||
use graphic_types::Vector;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::hash_map::Entry;
|
||||
use text_nodes::{FALLBACK_FONT_RESOURCE, TextToVectorError, TypesettingConfig};
|
||||
use vector_types::vector::GeometryCache;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Label {
|
||||
pub outline: List<Vector>,
|
||||
pub width: f64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Labels(HashMap<(String, u64), Label>);
|
||||
|
||||
impl Labels {
|
||||
pub fn label(&mut self, text: &str, max_width: f64) -> Result<&Label, TextToVectorError> {
|
||||
match self.0.entry((text.to_string(), max_width.to_bits())) {
|
||||
Entry::Occupied(label) => Ok(label.into_mut()),
|
||||
Entry::Vacant(label) => {
|
||||
let text = ellipsized(text, max_width);
|
||||
let (outline, width) = (outline(&text)?, width(&text));
|
||||
Ok(label.insert(Label { outline, width }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
|
||||
self.0.retain(|(text, _), _| shown(text));
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Paragraph {
|
||||
pub outline: List<Vector>,
|
||||
pub size: DVec2,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Paragraphs(HashMap<(String, u64, u64), Paragraph>);
|
||||
|
||||
impl Paragraphs {
|
||||
pub fn paragraph(&mut self, text: &str, line_height: f64, max_width: f64) -> Result<&Paragraph, TextToVectorError> {
|
||||
match self.0.entry((text.to_string(), line_height.to_bits(), max_width.to_bits())) {
|
||||
Entry::Occupied(paragraph) => Ok(paragraph.into_mut()),
|
||||
Entry::Vacant(paragraph) => {
|
||||
let (outline, size) = (paragraph_outline(text, line_height, max_width)?, paragraph_size(text, line_height, max_width));
|
||||
Ok(paragraph.insert(Paragraph { outline, size }))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn retain(&mut self, mut shown: impl FnMut(&str) -> bool) {
|
||||
self.0.retain(|(text, ..), _| shown(text));
|
||||
}
|
||||
}
|
||||
|
||||
fn width(text: &str) -> f64 {
|
||||
text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).x
|
||||
}
|
||||
|
||||
fn ellipsized(text: &str, max_width: f64) -> String {
|
||||
if width(text) <= max_width {
|
||||
return text.to_string();
|
||||
}
|
||||
let cut = |end: usize| format!("{}…", &text[..end]);
|
||||
let ends: Vec<usize> = text.char_indices().map(|(end, _)| end).collect();
|
||||
let fitting = ends.partition_point(|&end| width(&cut(end)) <= max_width);
|
||||
cut(ends[fitting.saturating_sub(1)])
|
||||
}
|
||||
|
||||
fn outline(text: &str) -> Result<List<Vector>, TextToVectorError> {
|
||||
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, typesetting(), false).map(with_geometry_caches)
|
||||
}
|
||||
|
||||
fn with_geometry_caches(mut outline: List<Vector>) -> List<Vector> {
|
||||
for index in 0..outline.len() {
|
||||
outline.set_attribute(ATTR_GEOMETRY_CACHE, index, GeometryCache::default());
|
||||
}
|
||||
outline
|
||||
}
|
||||
|
||||
pub fn paragraph_size(text: &str, line_height: f64, max_width: f64) -> DVec2 {
|
||||
let unwrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, None), true);
|
||||
let wrapped = text_nodes::bounding_box(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), true);
|
||||
DVec2::new(unwrapped.x.min(max_width), wrapped.y)
|
||||
}
|
||||
|
||||
fn paragraph_outline(text: &str, line_height: f64, max_width: f64) -> Result<List<Vector>, TextToVectorError> {
|
||||
text_nodes::to_path(text, &FALLBACK_FONT_RESOURCE, paragraph_typesetting(line_height, Some(max_width)), false).map(with_geometry_caches)
|
||||
}
|
||||
|
||||
fn typesetting() -> TypesettingConfig {
|
||||
TypesettingConfig {
|
||||
font_size: TEXT_SIZE,
|
||||
line_height_ratio: GRID_SIZE / TEXT_SIZE,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn paragraph_typesetting(line_height: f64, max_width: Option<f64>) -> TypesettingConfig {
|
||||
TypesettingConfig {
|
||||
font_size: TEXT_SIZE,
|
||||
line_height_ratio: line_height / TEXT_SIZE,
|
||||
max_width,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::look::{TEXT, text};
|
||||
use core_types::list::ATTR_PATHS;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[test]
|
||||
fn text_too_wide_is_cut_where_one_more_character_would_not_fit() {
|
||||
let name = "A Node With a Very Long Name";
|
||||
assert_eq!(ellipsized(name, 1000.), name);
|
||||
|
||||
let cut = ellipsized(name, 84.);
|
||||
let kept = cut.trim_end_matches('…');
|
||||
assert!(kept.len() < name.len() && width(&cut) <= 84., "{cut}");
|
||||
assert!(width(&format!("{}…", &name[..kept.len() + 1])) > 84., "{cut}");
|
||||
|
||||
assert_eq!(ellipsized(name, 0.), "…");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_paragraph_keeps_its_line_breaks_and_wraps_where_it_would_get_too_wide() {
|
||||
let line = "These input types are incompatible:";
|
||||
let one_line = paragraph_size(line, 18., 600.);
|
||||
assert_eq!(one_line, DVec2::new(width(line), 18.), "as wide as its text, a line high");
|
||||
assert_eq!(
|
||||
paragraph_size(&format!("{line}\n\nNext"), 18., 600.),
|
||||
DVec2::new(width(line), 54.),
|
||||
"an empty line between the paragraphs"
|
||||
);
|
||||
|
||||
let long = [line; 20].join(" ");
|
||||
let wrapped = paragraph_size(&long, 18., 600.);
|
||||
assert_eq!(wrapped.x, 600., "as wide as it may be once it wraps");
|
||||
assert!(wrapped.y >= 18. * (width(&long) / 600.).ceil(), "{wrapped}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_label_is_laid_out_once_until_its_text_is_no_longer_shown() {
|
||||
let mut labels = Labels::default();
|
||||
let path = labels.label("Path", 84.).unwrap().outline.elements_witness();
|
||||
labels.label("Fill", 84.).unwrap();
|
||||
assert!(path.matches(&labels.label("Path", 84.).unwrap().outline), "the second label of a text is the first");
|
||||
assert!(!path.matches(&labels.label("Path", 104.).unwrap().outline), "a label of another width is its own");
|
||||
|
||||
labels.retain(|text| text == "Fill");
|
||||
assert!(!path.matches(&labels.label("Path", 84.).unwrap().outline), "a forgotten label is laid out again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_contours_of_a_label_are_extracted_once_for_every_place_it_is_drawn() {
|
||||
let outline = Labels::default().label("Path", 84.).unwrap().outline.clone();
|
||||
let contours = |top_left| {
|
||||
let drawn = text(&outline, top_left, TEXT);
|
||||
let cache = drawn.attribute::<GeometryCache>(ATTR_GEOMETRY_CACHE, 0).cloned().unwrap_or_default();
|
||||
cache.contours(drawn.element(0).unwrap(), drawn.attribute(ATTR_PATHS, 0).unwrap())
|
||||
};
|
||||
assert!(Arc::ptr_eq(&contours(DVec2::ZERO), &contours(DVec2::ONE)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
use crate::card::DataType;
|
||||
use crate::replicated_map::Keyed;
|
||||
use core_types::uuid::NodeId;
|
||||
use graphene_hash::CacheHash;
|
||||
use vello_gpu::kurbo::{BezPath, PathEl};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, CacheHash)]
|
||||
pub struct Wire {
|
||||
pub key: WireKey,
|
||||
pub path: BezPath,
|
||||
pub data_type: DataType,
|
||||
pub thick: bool,
|
||||
pub center_line: BezPath,
|
||||
pub list: bool,
|
||||
pub insertion_target: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, CacheHash)]
|
||||
pub enum WireKey {
|
||||
Input { node: NodeId, index: usize },
|
||||
Export(usize),
|
||||
Preview,
|
||||
}
|
||||
|
||||
impl Keyed for Wire {
|
||||
type Key = WireKey;
|
||||
|
||||
fn key(&self) -> WireKey {
|
||||
self.key
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, CacheHash)]
|
||||
pub struct WireInProgress {
|
||||
pub path: [PathEl; 4],
|
||||
pub data_type: DataType,
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
mod render;
|
||||
mod timing;
|
||||
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::list::Item;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, ProtoNodeIdentifier};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::TaggedValue;
|
||||
use graph_craft::document::{DocumentNode, DocumentNodeImplementation, NodeInput, NodeNetwork};
|
||||
use graph_craft::item;
|
||||
use graph_craft::proto::ProtoNetwork;
|
||||
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use graph_ui::error_badge::ErrorBadge;
|
||||
use graph_ui::layer::Layer;
|
||||
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use graph_ui::wire::{Wire, WireKey};
|
||||
use graph_ui::{GraphUi, GraphUiConfig};
|
||||
use graphene_std::application_io::RenderConfig;
|
||||
use graphic_types::Graphic;
|
||||
use graphic_types::raster_types::Raster;
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use rendering::to_peniko::ToPenikoColor;
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use std::sync::Arc;
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect};
|
||||
use vello_gpu::peniko::Fill;
|
||||
use wgpu_executor::WgpuExecutor;
|
||||
|
||||
const ARTWORK: SRGBA8 = SRGBA8::new_opaque(0x30, 0x60, 0x90);
|
||||
|
||||
fn gpu() -> WgpuExecutor {
|
||||
futures::executor::block_on(WgpuExecutor::new()).expect("rendering needs a GPU adapter, such as lavapipe through `VK_ADD_DRIVER_FILES`")
|
||||
}
|
||||
|
||||
fn node(identifier: ProtoNodeIdentifier, inputs: Vec<NodeInput>) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(identifier),
|
||||
inputs,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn nested(network: NodeNetwork) -> DocumentNode {
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(network),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn network(gpu: &WgpuExecutor, nodes: impl IntoIterator<Item = DocumentNode>) -> NodeNetwork {
|
||||
let editor_api = Arc::new(PlatformEditorApi {
|
||||
application_io: Some(Arc::new(PlatformApplicationIo::new_with_executor(gpu.clone()))),
|
||||
});
|
||||
let editor_api = node(graphene_std::ops::passthrough::IDENTIFIER, vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)]);
|
||||
let nodes: Vec<DocumentNode> = [editor_api].into_iter().chain(nodes).collect();
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(nodes.len() as u64 - 1), 0)],
|
||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||
scope_injections: [("editor-api".to_string(), (NodeId(0), item!(Arc<PlatformEditorApi>)))].into_iter().collect(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn compiled(mut network: NodeNetwork) -> ProtoNetwork {
|
||||
preprocessor::Preprocessor::new().preprocess(&mut network, &|_| None).unwrap();
|
||||
graph_craft::util::compile(network)
|
||||
}
|
||||
|
||||
fn executor(network: NodeNetwork) -> (DynamicExecutor, OutputHandle) {
|
||||
let mut executor = DynamicExecutor::default();
|
||||
let (output, _) = executor.update(compiled(network)).unwrap();
|
||||
(executor, output)
|
||||
}
|
||||
|
||||
fn config(view: DAffine2, fade_artwork: f64) -> GraphUiConfig {
|
||||
GraphUiConfig {
|
||||
view,
|
||||
fade_artwork,
|
||||
wire_in_progress: None,
|
||||
reorder_bar: None,
|
||||
box_selection: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn context(render_config: RenderConfig, graph_ui: GraphUi) -> Context<'static> {
|
||||
graph_ui::render::context(render_config, graph_ui).into_context()
|
||||
}
|
||||
|
||||
fn thumbnail(gpu: &WgpuExecutor, painted: Rect, color: SRGBA8) -> Graphic {
|
||||
let mut paint = |scene: &mut VelloSceneBuilder| scene.fill(Fill::NonZero, Affine::IDENTITY, color.to_peniko_color(), None, &painted);
|
||||
let texture = gpu.render_vello(UVec2::new(72, 48), DAffine2::IDENTITY, &mut paint).unwrap();
|
||||
Graphic::RasterGPU(Item::new_from_element(Raster::new_gpu(texture)))
|
||||
}
|
||||
|
||||
fn card(key: u64, (x, y): (i32, i32), name: &str) -> Card {
|
||||
Card {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
name: name.to_string(),
|
||||
icon: "NodeCustomNode".to_string(),
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_inputs: Vec::new(),
|
||||
secondary_outputs: Vec::new(),
|
||||
selection: Selection::None,
|
||||
visible: true,
|
||||
previewed: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn layer(key: u64, (x, y): (i32, i32), name: &str) -> Layer {
|
||||
Layer {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
name: name.to_string(),
|
||||
renaming: false,
|
||||
width: 8,
|
||||
chain_width: 0,
|
||||
has_left_input_wire: false,
|
||||
primary_input: None,
|
||||
primary_output: None,
|
||||
secondary_input: None,
|
||||
primary_input_connected_to_layer: false,
|
||||
primary_output_connected_to_layer: false,
|
||||
visible: true,
|
||||
locked: false,
|
||||
read_only: false,
|
||||
selection: Selection::None,
|
||||
previewed: false,
|
||||
hovered_button: None,
|
||||
hovered_button_clicked: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn wire(key: WireKey, path: BezPath, data_type: DataType) -> Wire {
|
||||
Wire {
|
||||
key,
|
||||
path,
|
||||
data_type,
|
||||
thick: false,
|
||||
center_line: BezPath::new(),
|
||||
list: false,
|
||||
insertion_target: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn network_connector(kind: NetworkConnectorKind, index: usize, (x, y): (i32, i32), connector: Option<Connector>) -> NetworkConnector {
|
||||
NetworkConnector {
|
||||
kind,
|
||||
index,
|
||||
position: IVec2::new(x, y),
|
||||
connector,
|
||||
add_highlight: Highlight::None,
|
||||
editable: false,
|
||||
renaming: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn badge(key: u64, (x, y): (i32, i32), text: &str) -> ErrorBadge {
|
||||
ErrorBadge {
|
||||
key: NodeId(key),
|
||||
cell: IVec2::new(x, y),
|
||||
on_layer: false,
|
||||
text: text.to_string(),
|
||||
hovered: false,
|
||||
glide: DVec2::ZERO,
|
||||
}
|
||||
}
|
||||
|
||||
fn connector(name: &str, data_type: DataType) -> Connector {
|
||||
Connector {
|
||||
name: name.to_string(),
|
||||
data_type,
|
||||
connected: false,
|
||||
highlight: Highlight::None,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,490 @@
|
||||
use super::{ARTWORK, badge, config, connector, context, executor, gpu, layer, nested, network, network_connector, node, thumbnail, wire};
|
||||
use core_types::list::List;
|
||||
use core_types::uuid::NodeId;
|
||||
use core_types::{Context, OwnedContextImpl, Poll};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::document::value::{RenderOutput, RenderOutputType, TaggedValue};
|
||||
use graph_ui::GraphUi;
|
||||
use graph_ui::card::{Card, Connector, DataType, Highlight, Selection};
|
||||
use graph_ui::error_badge::ErrorBadge;
|
||||
use graph_ui::layer::Layer;
|
||||
use graph_ui::network_connector::{NetworkConnector, NetworkConnectorKind};
|
||||
use graph_ui::render::rows_context;
|
||||
use graph_ui::replicated_map::ReplicatedMap;
|
||||
use graph_ui::scene::{GraphUiScene, GraphUiSceneEdit};
|
||||
use graph_ui::wire::{Wire, WireKey};
|
||||
use graphene_std::application_io::{ExportFormat, RenderConfig};
|
||||
use graphene_std::transform::Footprint;
|
||||
use graphic_types::{Graphic, Vector};
|
||||
use rendering::vello_scene_builder::VelloSceneBuilder;
|
||||
use rendering::{Render, RenderParams};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use vello_gpu::kurbo::{Affine, BezPath, Rect};
|
||||
|
||||
const CARDS: usize = 300;
|
||||
const LAYERS: usize = 60;
|
||||
const ERRORS: usize = 10;
|
||||
const GLIDING: usize = 5;
|
||||
const COLUMNS: usize = 20;
|
||||
const SAMPLES: usize = 21;
|
||||
const RESOLUTION: UVec2 = UVec2::new(1920, 1080);
|
||||
const NAMES: [&str; 10] = [
|
||||
"Transform",
|
||||
"Fill",
|
||||
"Stroke",
|
||||
"Boolean Operation",
|
||||
"Copy to Points",
|
||||
"Sample Polyline",
|
||||
"Morph",
|
||||
"Blend Shapes",
|
||||
"Image Color Palette",
|
||||
"Rectangle",
|
||||
];
|
||||
const ICONS: [&str; 10] = [
|
||||
"NodeTransform",
|
||||
"NodeFill",
|
||||
"NodeStroke",
|
||||
"NodeBooleanOperation",
|
||||
"NodeRepeatOnPoints",
|
||||
"NodeSamplePolyline",
|
||||
"NodeMorph",
|
||||
"NodeBlend",
|
||||
"NodeImageColorPalette",
|
||||
"NodeRectangle",
|
||||
];
|
||||
const ERROR: &str = "These input types are incompatible:\n• Input 2:\n…found: Color\n…expected: Number\n\nThis is not a supported arrangement of types for the node.";
|
||||
const ROWS: [(&str, DataType); 8] = [
|
||||
("Translation", DataType::General),
|
||||
("Rotation", DataType::Number),
|
||||
("Scale", DataType::General),
|
||||
("Color", DataType::Color),
|
||||
("Width", DataType::Number),
|
||||
("Opacity", DataType::Number),
|
||||
("Gradient", DataType::Gradient),
|
||||
("Separation Disk Diameter", DataType::Number),
|
||||
];
|
||||
|
||||
fn selection(index: usize) -> Selection {
|
||||
if index.is_multiple_of(7) { Selection::Active } else { Selection::None }
|
||||
}
|
||||
|
||||
fn connector_from((name, data_type): (&str, DataType), connected: bool) -> Connector {
|
||||
Connector {
|
||||
connected,
|
||||
..connector(name, data_type)
|
||||
}
|
||||
}
|
||||
|
||||
fn card(index: usize) -> Card {
|
||||
Card {
|
||||
icon: ICONS[index % ICONS.len()].to_string(),
|
||||
primary_input: Some(connector_from(("Content", DataType::Vector), true)),
|
||||
primary_output: Some(connector_from(("Out", DataType::Vector), !index.is_multiple_of(4))),
|
||||
secondary_inputs: (0..2 + index % 3)
|
||||
.map(|row| connector_from(ROWS[(index + row) % ROWS.len()], (index + row).is_multiple_of(3)))
|
||||
.collect(),
|
||||
secondary_outputs: if index.is_multiple_of(5) {
|
||||
vec![connector_from(("Area", DataType::Number), false)]
|
||||
} else {
|
||||
Vec::new()
|
||||
},
|
||||
selection: selection(index),
|
||||
visible: !index.is_multiple_of(11),
|
||||
previewed: index == 0,
|
||||
..super::card(index as u64, ((index % COLUMNS) as i32 * 7, (index / COLUMNS) as i32 * 6), NAMES[index % NAMES.len()])
|
||||
}
|
||||
}
|
||||
|
||||
fn nth_layer(index: usize) -> Layer {
|
||||
Layer {
|
||||
width: 8 + (index % 3) as u32,
|
||||
chain_width: if index.is_multiple_of(2) { 8 } else { 0 },
|
||||
has_left_input_wire: index.is_multiple_of(4),
|
||||
primary_input: Some(connector_from(("", DataType::Graphic), !index.is_multiple_of(10))),
|
||||
primary_output: Some(connector_from(("", DataType::Graphic), true)),
|
||||
secondary_input: Some(connector_from(("", DataType::Vector), index.is_multiple_of(2))),
|
||||
primary_input_connected_to_layer: !index.is_multiple_of(10),
|
||||
primary_output_connected_to_layer: !index.is_multiple_of(10),
|
||||
visible: !index.is_multiple_of(11),
|
||||
locked: index.is_multiple_of(13),
|
||||
selection: selection(index),
|
||||
previewed: index == 1,
|
||||
..layer((CARDS + index) as u64, ((index % 10) as i32 * 14 + 3, (index / 10) as i32 * 6 + 3), NAMES[index % NAMES.len()])
|
||||
}
|
||||
}
|
||||
|
||||
fn unnamed(mut card: Card) -> Card {
|
||||
card.name.clear();
|
||||
let connectors = card
|
||||
.primary_input
|
||||
.iter_mut()
|
||||
.chain(&mut card.primary_output)
|
||||
.chain(&mut card.secondary_inputs)
|
||||
.chain(&mut card.secondary_outputs);
|
||||
connectors.for_each(|connector| connector.name.clear());
|
||||
card
|
||||
}
|
||||
|
||||
fn scene(cards: impl IntoIterator<Item = Card>) -> GraphUiScene {
|
||||
let mut edit = GraphUiScene::default().edit();
|
||||
edit.cards.replace_all(cards);
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn rewire(edit: &mut GraphUiSceneEdit) {
|
||||
let wires = wires(&edit.cards);
|
||||
edit.wires.replace_all(wires);
|
||||
}
|
||||
|
||||
fn wires(cards: &ReplicatedMap<Card>) -> Vec<Wire> {
|
||||
cards.iter().zip(cards.iter().skip(1)).map(|(from, to)| wire_between(from, to)).collect()
|
||||
}
|
||||
|
||||
fn wire_between(from: &Card, to: &Card) -> Wire {
|
||||
let center = |(top_left, _): (DVec2, &Connector)| top_left + 4.;
|
||||
let [start, end] = [from.outputs().next(), to.inputs().next()].map(|connector| connector.map(center).expect("every card has a primary input and output"));
|
||||
let point = |point: DVec2| (point.x, point.y);
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(point(start));
|
||||
path.line_to(point(start + DVec2::X * 12.));
|
||||
path.curve_to(point(start + DVec2::X * 48.), point(end - DVec2::X * 48.), point(end - DVec2::X * 12.));
|
||||
path.line_to(point(end));
|
||||
Wire {
|
||||
list: to.key.0.is_multiple_of(4),
|
||||
..wire(WireKey::Input { node: to.key, index: 0 }, path, DataType::Vector)
|
||||
}
|
||||
}
|
||||
|
||||
fn network_connectors(cells_down: i32) -> Vec<NetworkConnector> {
|
||||
let column = |kind, x| {
|
||||
let place = move |row: usize| (x, (cells_down + row as i32) * 24);
|
||||
let named = ROWS[..4].iter().enumerate().map(move |(index, &row)| NetworkConnector {
|
||||
editable: true,
|
||||
..network_connector(kind, index, place(if index == 0 { 0 } else { index + 1 }), Some(connector_from(row, true)))
|
||||
});
|
||||
named.chain([network_connector(kind, 4, place(6), None)])
|
||||
};
|
||||
column(NetworkConnectorKind::Import, -96).chain(column(NetworkConnectorKind::Export, COLUMNS as i32 * 7 * 24)).collect()
|
||||
}
|
||||
|
||||
fn error(index: usize) -> ErrorBadge {
|
||||
let card = card(index * 31 % CARDS);
|
||||
badge(card.key.0, card.cell.into(), ERROR)
|
||||
}
|
||||
|
||||
fn full_scene() -> GraphUiScene {
|
||||
let mut edit = scene((0..CARDS).map(card)).edit();
|
||||
edit.layers.replace_all((0..LAYERS).map(nth_layer));
|
||||
edit.network_connectors.replace_all(network_connectors(0));
|
||||
edit.errors.replace_all((0..ERRORS).map(error));
|
||||
rewire(&mut edit);
|
||||
edit.finish().0
|
||||
}
|
||||
|
||||
fn moved(card: &Card, offset: IVec2) -> Card {
|
||||
Card {
|
||||
cell: card.cell + offset,
|
||||
..card.clone()
|
||||
}
|
||||
}
|
||||
|
||||
fn reselected(card: &Card) -> Card {
|
||||
let selection = match card.selection {
|
||||
Selection::None => Selection::Inactive,
|
||||
Selection::Inactive => Selection::Active,
|
||||
Selection::Active => Selection::None,
|
||||
};
|
||||
Card { selection, ..card.clone() }
|
||||
}
|
||||
|
||||
fn median(mut times: Vec<Duration>) -> Duration {
|
||||
times.sort();
|
||||
times[times.len() / 2]
|
||||
}
|
||||
|
||||
fn ms(time: Duration) -> f64 {
|
||||
time.as_secs_f64() * 1000.
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "prints timings"]
|
||||
fn time_a_pan_a_card_change_and_a_rebuild_of_300_cards() {
|
||||
let gpu = gpu();
|
||||
let (render_graph_ui, graph_ui_output) = executor(network(&gpu, [nested(graph_ui::render::network())]));
|
||||
let (draw_cards, cards_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_cards::IDENTIFIER, vec![])]));
|
||||
let (draw_wires, wires_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_wires::IDENTIFIER, vec![])]));
|
||||
let (draw_grid, grid_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_grid::IDENTIFIER, vec![])]));
|
||||
let (draw_thumbnails, thumbnails_output) = executor(network(&gpu, [node(graph_ui::nodes::draw_thumbnails::IDENTIFIER, vec![])]));
|
||||
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint {
|
||||
resolution: RESOLUTION,
|
||||
..Default::default()
|
||||
},
|
||||
scale: 1.,
|
||||
export_format: ExportFormat::Raster,
|
||||
..Default::default()
|
||||
};
|
||||
let view = |sample: usize| DAffine2::from_scale_angle_translation(DVec2::splat(0.5), 0., DVec2::new(100. + sample as f64, 0.));
|
||||
let mut editor_scene = full_scene();
|
||||
let mut runtime_scene = editor_scene.clone();
|
||||
let thumbnails: Arc<BTreeMap<NodeId, Graphic>> = Arc::new(editor_scene.layers().iter().map(|layer| (layer.key, thumbnail(&gpu, Rect::new(12., 0., 60., 48.), ARTWORK))).collect());
|
||||
let mut render = |change: &mut dyn FnMut(&mut GraphUiSceneEdit), view: DAffine2| {
|
||||
let mut edit = std::mem::take(&mut editor_scene).edit();
|
||||
change(&mut edit);
|
||||
let (scene, delta) = edit.finish();
|
||||
editor_scene = scene;
|
||||
|
||||
let start = Instant::now();
|
||||
runtime_scene.apply(delta);
|
||||
let graph_ui = GraphUi {
|
||||
scene: runtime_scene.clone(),
|
||||
config: config(view, 0.5),
|
||||
thumbnails: thumbnails.clone(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let output = render_graph_ui.tree().eval_tagged_value(graph_ui_output.node(), &context).unwrap();
|
||||
let time = start.elapsed();
|
||||
|
||||
let Poll::Final(TaggedValue::RenderOutput(RenderOutput {
|
||||
data: RenderOutputType::Texture(texture),
|
||||
..
|
||||
})) = output
|
||||
else {
|
||||
panic!("{output:?}")
|
||||
};
|
||||
gpu.read_texture_pixels(&texture).unwrap();
|
||||
time
|
||||
};
|
||||
|
||||
render(&mut |_| {}, view(0));
|
||||
let pan = median((1..=SAMPLES).map(|sample| render(&mut |_| {}, view(sample))).collect());
|
||||
let interface_pan = median(
|
||||
(1..=SAMPLES)
|
||||
.map(|sample| render(&mut |edit| edit.network_connectors.replace_all(network_connectors(sample as i32 % 2)), view(sample)))
|
||||
.collect(),
|
||||
);
|
||||
let card_change = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let key = NodeId((sample * 37 % CARDS) as u64);
|
||||
render(
|
||||
&mut |edit| {
|
||||
edit.cards.update(&key, |card| *card = reselected(&moved(card, IVec2::Y)));
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let highlight = |card: &mut Card, highlight| card.primary_output.as_mut().expect("every card has a primary output").highlight = highlight;
|
||||
let mut hovered = None;
|
||||
let hover_move = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let key = NodeId((sample * 37 % CARDS) as u64);
|
||||
let left = hovered.replace(key);
|
||||
render(
|
||||
&mut |edit| {
|
||||
if let Some(left) = left {
|
||||
edit.cards.update(&left, |card| highlight(card, Highlight::None));
|
||||
}
|
||||
edit.cards.update(&key, |card| highlight(card, Highlight::Hovered));
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let glide_frame = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let glide = DVec2::new(-24. * 0.6_f64.powi(sample as i32 % 8 + 1), 0.);
|
||||
render(
|
||||
&mut |edit| {
|
||||
for index in 0..GLIDING {
|
||||
edit.cards.update(&NodeId((index * 61 % CARDS) as u64), |card| card.glide = glide);
|
||||
}
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
let mut every_card = |changed: fn(&Card, IVec2) -> Card| {
|
||||
median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let offset = if sample % 2 == 0 { IVec2::X } else { -IVec2::X };
|
||||
render(
|
||||
&mut |edit| {
|
||||
let cards: Vec<Card> = edit.cards.iter().map(|card| changed(card, offset)).collect();
|
||||
edit.cards.replace_all(cards);
|
||||
rewire(edit);
|
||||
},
|
||||
view(0),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
)
|
||||
};
|
||||
let rebuild = every_card(|card, offset| reselected(&moved(card, offset)));
|
||||
let every_card_moved = every_card(moved);
|
||||
|
||||
let draw = |card_at: fn(usize) -> Card| {
|
||||
let cards: Vec<Card> = (0..CARDS).map(card_at).collect();
|
||||
let scenes = [scene(cards.clone()), scene(cards.iter().map(reselected))];
|
||||
let times = (0..SAMPLES).map(|sample| {
|
||||
let context = rows_context(scenes[sample % 2].cards());
|
||||
let start = Instant::now();
|
||||
draw_cards.tree().eval::<Context, List<Vector>>(cards_output.node(), &context).expect("the cards are drawn");
|
||||
start.elapsed()
|
||||
});
|
||||
median(times.collect())
|
||||
};
|
||||
let drawn = draw(card);
|
||||
let drawn_unnamed = draw(|index| unnamed(card(index)));
|
||||
let text = drawn.saturating_sub(drawn_unnamed);
|
||||
|
||||
let wired = |cards: Vec<Card>| {
|
||||
let mut edit = scene(cards).edit();
|
||||
rewire(&mut edit);
|
||||
edit.finish().0
|
||||
};
|
||||
let cards: Vec<Card> = (0..CARDS).map(card).collect();
|
||||
let scenes = [wired(cards.clone()), wired(cards.iter().map(|card| moved(card, IVec2::X)).collect())];
|
||||
let wires_drawn = median(
|
||||
(0..SAMPLES)
|
||||
.map(|sample| {
|
||||
let context = rows_context(scenes[sample % 2].wires());
|
||||
let start = Instant::now();
|
||||
draw_wires.tree().eval::<Context, List<Vector>>(wires_output.node(), &context).expect("the wires are drawn");
|
||||
start.elapsed()
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
|
||||
let grid = |zoom: f64, scale: f64| {
|
||||
let resolution = (RESOLUTION.as_dvec2() * scale).as_uvec2();
|
||||
let render_config = RenderConfig {
|
||||
viewport: Footprint { resolution, ..render_config.viewport },
|
||||
scale,
|
||||
..render_config
|
||||
};
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let graph_ui = GraphUi {
|
||||
scene: GraphUiScene::default(),
|
||||
config: config(DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(100. + sample as f64, 0.)), 0.5),
|
||||
thumbnails: Default::default(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let mut scene = VelloSceneBuilder::new(resolution.x as u16, resolution.y as u16, Affine::IDENTITY, resolution.x);
|
||||
let start = Instant::now();
|
||||
let dots = draw_grid.tree().eval::<Context, List<Vector>>(grid_output.node(), &context).expect("the grid is drawn");
|
||||
let drawn = start.elapsed();
|
||||
dots.render_to_vello(&mut scene, DAffine2::from_scale(DVec2::splat(scale)), &RenderParams::default());
|
||||
(drawn, start.elapsed() - drawn)
|
||||
});
|
||||
let (drawn, encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
|
||||
(median(drawn), median(encoded))
|
||||
};
|
||||
let grids = [1., 2.].map(|scale| (scale, grid(0.5, scale), grid(1., scale)));
|
||||
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let graph_ui = GraphUi {
|
||||
scene: editor_scene.clone(),
|
||||
config: config(view(sample), 0.5),
|
||||
thumbnails: thumbnails.clone(),
|
||||
};
|
||||
let context = context(render_config, graph_ui);
|
||||
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
|
||||
let start = Instant::now();
|
||||
let drawn = draw_thumbnails
|
||||
.tree()
|
||||
.eval::<Context, List<Vector>>(thumbnails_output.node(), &context)
|
||||
.expect("the thumbnails are drawn");
|
||||
let elapsed = start.elapsed();
|
||||
drawn.render_to_vello(&mut scene, view(sample), &RenderParams::default());
|
||||
(elapsed, start.elapsed() - elapsed)
|
||||
});
|
||||
let (thumbnails_drawn, thumbnails_encoded): (Vec<Duration>, Vec<Duration>) = times.unzip();
|
||||
|
||||
let scene = full_scene();
|
||||
let raised_rows = OwnedContextImpl::default()
|
||||
.with_varargs([Box::new(scene.layers().clone()), Box::new(scene.cards().clone())])
|
||||
.into_context();
|
||||
let scene_bands = [
|
||||
("cards", graph_ui::nodes::draw_cards::IDENTIFIER, rows_context(scene.cards())),
|
||||
("raised", graph_ui::nodes::draw_raised::IDENTIFIER, raised_rows),
|
||||
("layers", graph_ui::nodes::draw_layers::IDENTIFIER, rows_context(scene.layers())),
|
||||
("wires", graph_ui::nodes::draw_wires::IDENTIFIER, rows_context(scene.wires())),
|
||||
("errors", graph_ui::nodes::draw_errors::IDENTIFIER, rows_context(scene.errors())),
|
||||
("imports/exports", graph_ui::nodes::draw_network_connectors::IDENTIFIER, rows_context(scene.network_connectors())),
|
||||
]
|
||||
.map(|(name, band, rows)| {
|
||||
let (band, output) = executor(network(&gpu, [node(band, Vec::new())]));
|
||||
(name, band.tree().eval::<Context, List<Vector>>(output.node(), &rows).expect("the band is drawn"))
|
||||
});
|
||||
let encoded = |band: &List<Vector>, zoom: f64, left: f64| {
|
||||
let times = (1..=SAMPLES).map(|sample| {
|
||||
let view = DAffine2::from_scale_angle_translation(DVec2::splat(zoom), 0., DVec2::new(left + sample as f64, 0.));
|
||||
let mut scene = VelloSceneBuilder::new(RESOLUTION.x as u16, RESOLUTION.y as u16, Affine::IDENTITY, RESOLUTION.x);
|
||||
let start = Instant::now();
|
||||
band.render_to_vello(&mut scene, view, &RenderParams::default());
|
||||
start.elapsed()
|
||||
});
|
||||
median(times.collect())
|
||||
};
|
||||
let band_encodes = [0.5, 1.].map(|zoom| {
|
||||
let bands = scene_bands.iter().map(|(name, band)| (*name, band.len(), encoded(band, zoom, 100.), encoded(band, zoom, -100_000.)));
|
||||
(zoom, bands.collect::<Vec<_>>())
|
||||
});
|
||||
|
||||
let profile = if cfg!(debug_assertions) { "dev" } else { "release" };
|
||||
println!(
|
||||
"{CARDS} cards, each wired to the next, {LAYERS} layers, four imports and four exports and {ERRORS} error badges at {}x{}, {profile} profile, CPU time without the GPU wait, median of {SAMPLES}",
|
||||
RESOLUTION.x, RESOLUTION.y
|
||||
);
|
||||
println!("pan step (view change only): {:.3} ms", ms(pan));
|
||||
println!("pan step that moves the imports and exports a cell: {:.3} ms", ms(interface_pan));
|
||||
println!("one-card change (one card moved and reselected, so drawn again, and its two wires): {:.3} ms", ms(card_change));
|
||||
println!("hover moving from one card to another: {:.3} ms", ms(hover_move));
|
||||
println!("glide frame of {GLIDING} cards and their wires: {:.3} ms", ms(glide_frame));
|
||||
println!("full rebuild (every card and wire changed): {:.3} ms", ms(rebuild));
|
||||
println!("every card only moved a cell (placed again, not drawn again), every wire changed: {:.3} ms", ms(every_card_moved));
|
||||
println!("draw_cards alone, every card drawn again: {:.3} ms, with every name empty: {:.3} ms", ms(drawn), ms(drawn_unnamed));
|
||||
println!("draw_wires alone, every wire drawn again: {:.3} ms", ms(wires_drawn));
|
||||
println!(
|
||||
"text (width, ellipsized, outline), the difference: {:.3} ms, {:.0}% of draw_cards, {:.0}% of a one-card change",
|
||||
ms(text),
|
||||
100. * text.as_secs_f64() / drawn.as_secs_f64(),
|
||||
100. * text.as_secs_f64() / card_change.as_secs_f64()
|
||||
);
|
||||
for (scale, (drawn, encoded), (drawn_at_1, encoded_at_1)) in grids {
|
||||
println!(
|
||||
"grid alone at zoom 0.5 and device scale {scale}: draw_grid {:.3} ms + Vello encode {:.3} ms (at zoom 1: {:.3} ms + {:.3} ms)",
|
||||
ms(drawn),
|
||||
ms(encoded),
|
||||
ms(drawn_at_1),
|
||||
ms(encoded_at_1)
|
||||
);
|
||||
}
|
||||
println!(
|
||||
"thumbnails alone, one on each of the {LAYERS} layers: draw_thumbnails {:.3} ms + Vello encode {:.3} ms",
|
||||
ms(median(thumbnails_drawn)),
|
||||
ms(median(thumbnails_encoded))
|
||||
);
|
||||
for (zoom, bands) in band_encodes {
|
||||
println!("Vello encode alone of each scene band at zoom {zoom}, on screen and with every item panned off screen (the bookkeeping before the cull):");
|
||||
for (name, items, on_screen, off_screen) in &bands {
|
||||
println!(" {name} ({items} items): {:.3} ms on screen, {:.3} ms off screen", ms(*on_screen), ms(*off_screen));
|
||||
}
|
||||
let on_screen: Duration = bands.iter().map(|(_, _, on_screen, _)| *on_screen).sum();
|
||||
let off_screen: Duration = bands.iter().map(|(_, _, _, off_screen)| *off_screen).sum();
|
||||
println!(" all six: {:.3} ms on screen, {:.3} ms off screen", ms(on_screen), ms(off_screen));
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use graphene_std::application_io::ApplicationIo;
|
||||
use graphene_std::runtime::{AsyncRuntime, RuntimeHandle, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::layer_paths::write_layer_paths;
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::collections::HashMap;
|
||||
use std::error::Error;
|
||||
use std::path::Path;
|
||||
@@ -95,7 +95,7 @@ pub async fn editor_api(gdd: Option<&GddV1>) -> (Arc<PlatformApplicationIo>, Arc
|
||||
/// 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 mut network = wrap_network_with_render_node_in_scope(network, editor_api, runtime);
|
||||
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
let preprocessed = match gdd {
|
||||
|
||||
@@ -5,7 +5,7 @@ use graph_craft::util::{DEMO_ART, compile};
|
||||
use graphene_std::application_io::EditorApi;
|
||||
use graphene_std::runtime::{AsyncRuntime, Spawn, Task};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::path::Path;
|
||||
|
||||
pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork) {
|
||||
@@ -13,7 +13,7 @@ pub fn setup_network(name: &str) -> (DynamicExecutor, OutputHandle, ProtoNetwork
|
||||
.unwrap()
|
||||
.network;
|
||||
let editor_api = std::sync::Arc::new(EditorApi::default());
|
||||
let mut network = wrap_network_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let mut network = wrap_network_with_render_node_in_scope(network, editor_api, AsyncRuntime::new(std::sync::Arc::new(DummySpawner)).handle());
|
||||
let preprocessor = preprocessor::Preprocessor::new();
|
||||
preprocessor.preprocess(&mut network, &|_| None).unwrap();
|
||||
let proto_network = compile(network);
|
||||
|
||||
@@ -21,7 +21,7 @@ use graphene_std::{Color, Context};
|
||||
use gungraun::prelude::*;
|
||||
use gungraun::{Callgrind, EntryPoint};
|
||||
use interpreted_executor::dynamic_executor::{DynamicExecutor, OutputHandle};
|
||||
use interpreted_executor::util::wrap_network_in_scope;
|
||||
use interpreted_executor::util::wrap_network_with_render_node_in_scope;
|
||||
use std::hint::black_box;
|
||||
use std::sync::Arc;
|
||||
use wgpu_executor::{WgpuContextBuilder, WgpuExecutor};
|
||||
@@ -70,7 +70,7 @@ impl Session {
|
||||
|
||||
/// Recompiles the document graph into the executor and renders the viewport, as the runtime does after an edit.
|
||||
fn update(&mut self, document: NodeNetwork) {
|
||||
let mut network = wrap_network_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
let mut network = wrap_network_with_render_node_in_scope(document, self.editor_api.clone(), self.runtime.handle());
|
||||
self.preprocessor.preprocess(&mut network, &|_| None).expect("Failed to preprocess the document");
|
||||
let proto_network = Compiler {}.compile_single(network).expect("Failed to compile the document").network;
|
||||
(self.output, _) = self.executor.update(proto_network).expect("Failed to update the executor");
|
||||
|
||||
@@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi};
|
||||
use graph_craft::document::value::RenderOutput;
|
||||
use graph_craft::proto::{NodeConstructor, TypeErasedBox};
|
||||
use graphene_animation::AnimationCurve;
|
||||
use graphene_std::RadialBlurMethod;
|
||||
use graphene_std::animation::RealTimeMode;
|
||||
use graphene_std::any::DynAnyNode;
|
||||
use graphene_std::brush::Stroke;
|
||||
@@ -28,7 +29,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, BevelTechnique, GlowSource, GlowTechnique, MaskMode};
|
||||
use graphene_std::{BevelDirection, BevelStyle, BevelTechnique, GlowSource, GlowTechnique, MaskMode, MinimumMaximumMode, NoiseDistribution};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -292,9 +293,12 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
GlowTechnique,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
NoiseDistribution,
|
||||
RadialBlurMethod,
|
||||
Stroke,
|
||||
ScaleType,
|
||||
ReferencePoint,
|
||||
|
||||
@@ -9,7 +9,7 @@ use graphene_std::RuntimeHandle;
|
||||
use graphene_std::uuid::NodeId;
|
||||
use std::sync::Arc;
|
||||
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
pub fn wrap_network_with_render_node_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
let definitions = std::mem::take(&mut network.definitions);
|
||||
|
||||
let inner_network = DocumentNode {
|
||||
@@ -114,10 +114,28 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let network = NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
nodes: [(NodeId(0), inner_network), (NodeId(1), render_node)].into_iter().collect(),
|
||||
definitions,
|
||||
generated: true,
|
||||
..Default::default()
|
||||
};
|
||||
wrap_network_in_scope(network, editor_api, runtime)
|
||||
}
|
||||
|
||||
pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformEditorApi>, runtime: RuntimeHandle) -> NodeNetwork {
|
||||
let definitions = std::mem::take(&mut network.definitions);
|
||||
|
||||
let inner_network = DocumentNode {
|
||||
implementation: DocumentNodeImplementation::Network(network),
|
||||
inputs: vec![],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// wrap the inner network in a scope
|
||||
let nodes = vec![
|
||||
inner_network,
|
||||
render_node,
|
||||
DocumentNode {
|
||||
implementation: DocumentNodeImplementation::ProtoNode(graphene_std::ops::passthrough::IDENTIFIER),
|
||||
inputs: vec![NodeInput::value(TaggedValue::EditorApi(editor_api), false)],
|
||||
@@ -130,12 +148,12 @@ pub fn wrap_network_in_scope(mut network: NodeNetwork, editor_api: Arc<PlatformE
|
||||
},
|
||||
];
|
||||
let scope_injections = vec![
|
||||
("editor-api".to_string(), (NodeId(2), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(3), item!(RuntimeHandle))),
|
||||
("editor-api".to_string(), (NodeId(1), item!(Arc<PlatformEditorApi>))),
|
||||
("runtime".to_string(), (NodeId(2), item!(RuntimeHandle))),
|
||||
];
|
||||
|
||||
NodeNetwork {
|
||||
exports: vec![NodeInput::node(NodeId(1), 0)],
|
||||
exports: vec![NodeInput::node(NodeId(0), 0)],
|
||||
nodes: nodes.into_iter().enumerate().map(|(id, node)| (NodeId(id as u64), node)).collect(),
|
||||
scope_injections: scope_injections.into_iter().collect(),
|
||||
definitions,
|
||||
|
||||
@@ -805,6 +805,11 @@ impl OwnedContextImpl {
|
||||
self.varargs = Some(Arc::new([value]));
|
||||
self
|
||||
}
|
||||
pub fn with_varargs<const N: usize>(mut self, values: [Box<dyn AnyHash + Send + Sync>; N]) -> Self {
|
||||
assert!(self.varargs.is_none_or(|value| value.is_empty()));
|
||||
self.varargs = Some(Arc::new(values));
|
||||
self
|
||||
}
|
||||
pub fn with_generations(mut self, generations: Generations) -> Self {
|
||||
self.generations = (!generations.is_empty()).then_some(generations);
|
||||
self
|
||||
|
||||
@@ -281,11 +281,11 @@ impl<'a, N> LazyInput<'a, N> {
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn eval<Input>(&self, input: Input) -> Result<N::Output, Interrupt>
|
||||
pub fn eval<Input>(&self, input: &Input) -> Result<N::Output, Interrupt>
|
||||
where
|
||||
N: Node<Input>,
|
||||
{
|
||||
self.status.record(self.index, self.node.eval(&input))
|
||||
self.status.record(self.index, self.node.eval(input))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -232,6 +232,17 @@ impl<T: CacheHash> CacheHash for std::collections::BTreeSet<T> {
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: CacheHash, V: CacheHash> CacheHash for std::collections::BTreeMap<K, V> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
core::hash::Hash::hash(&self.len(), state);
|
||||
for (key, value) in self {
|
||||
key.cache_hash(state);
|
||||
value.cache_hash(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: CacheHash + ?Sized> CacheHash for Box<T> {
|
||||
#[inline]
|
||||
fn cache_hash<H: core::hash::Hasher>(&self, state: &mut H) {
|
||||
|
||||
@@ -82,6 +82,7 @@ pub enum Adjustment {
|
||||
/// Percent.
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -107,6 +108,7 @@ impl Adjustment {
|
||||
Self::PhotoFilter { .. } => EffectKind::PhotoFilter,
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +125,7 @@ impl Adjustment {
|
||||
| Self::Posterize { .. }
|
||||
| Self::Exposure { .. }
|
||||
| Self::ColorBalance(_)
|
||||
| Self::Solarize
|
||||
)
|
||||
}
|
||||
|
||||
@@ -134,7 +137,7 @@ impl Adjustment {
|
||||
visitor.parameter("gamma", gamma, 2.2);
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque | Self::Invert => {}
|
||||
Self::MakeOpaque | Self::Invert | Self::Solarize => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::adjustment::Adjustment;
|
||||
use crate::effects::{BevelStyle, EffectCapture, EffectOperation, Effects, GlowFill, OutlineFill, outline_extents};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use std::borrow::Cow;
|
||||
use std::ops::Range;
|
||||
|
||||
/// Which side of the content a piece of an effect draws on, and how.
|
||||
@@ -99,9 +100,7 @@ impl EffectLayers {
|
||||
let has_beneath = |pieces: &[(EffectPiece, BlendMode)]| pieces.iter().any(|(piece, _)| piece.place == PiecePlace::Beneath);
|
||||
|
||||
// Flattened shadows and glows that no later pixel filter merges into the content would draw over the layered ones, so then everything is flattened
|
||||
let last_pixel_filter = (operations[..flattened].iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1);
|
||||
let last_pixel_filter = merged_into_content(&operations[..flattened]);
|
||||
let unmerged = pieces_from(last_pixel_filter, flattened);
|
||||
let mut pieces = pieces_from(flattened, operations.len());
|
||||
if has_beneath(&unmerged) && has_beneath(&pieces) {
|
||||
@@ -277,18 +276,39 @@ fn is_straight_along_backdrop(blend_mode: BlendMode) -> bool {
|
||||
matches!(blend_mode, BlendMode::Normal | BlendMode::Multiply | BlendMode::Screen | BlendMode::Exclusion | BlendMode::HardLight)
|
||||
}
|
||||
|
||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, or a feather does.
|
||||
/// Whether an effect row processes the pixels of the content and everything drawn with it so far, as a blur, an adjustment, a mask, a feather, or another filter does.
|
||||
/// A solid paint overlay decodes into the color overlay adjustment, but it paints within the content like any other paint overlay.
|
||||
pub fn is_pixel_filter(operation: &EffectOperation) -> bool {
|
||||
match operation {
|
||||
// TODO: Make a mask between other effects fade each layer drawn before it too, as the trailing masks do, rather than flattening those layers.
|
||||
// TODO: Likewise for a trailing feather, faded by the footprint of every layer drawn together (not the content's alone, which would erase shadows past it).
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
EffectOperation::Blur { .. } | EffectOperation::MotionBlur { .. } | EffectOperation::RadialBlur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } => true,
|
||||
operation if crate::filters::is_filter(operation) => true,
|
||||
EffectOperation::Adjustment(adjustment) => !matches!(adjustment, Adjustment::ColorOverlay { .. }),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How many of the `operations`, from the first, run through the last pixel filter among them, which merges the pieces before it into the content's image.
|
||||
fn merged_into_content(operations: &[EffectOperation]) -> usize {
|
||||
(operations.iter())
|
||||
.rposition(|operation| !operation.changes_nothing() && is_pixel_filter(operation))
|
||||
.map_or(0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// The effects carried out in the content's own image, which make a clipping base's shape: every row through the last pixel filter, which merges the pieces before it into that image, then the trailing masks fading it.
|
||||
/// The other pieces are cast from or laid over the content, so for PSD interop they don't shape a clip. Borrowed if nothing is left out.
|
||||
pub fn content_image_effects(effects: &Effects) -> Cow<'_, Effects> {
|
||||
let operations: Vec<EffectOperation> = effects.operations().collect();
|
||||
let trailing_masks = trailing_masks(&operations);
|
||||
let merged = merged_into_content(&operations[..trailing_masks.start]);
|
||||
if merged == trailing_masks.start {
|
||||
return Cow::Borrowed(effects);
|
||||
}
|
||||
|
||||
Cow::Owned(Effects((0..merged).chain(trailing_masks).filter_map(|index| effects.0.clone_item(index)).collect()))
|
||||
}
|
||||
|
||||
/// The rows from the first mask after every other effect that changes something to the end, or none without such a mask or an effect before it.
|
||||
fn trailing_masks(operations: &[EffectOperation]) -> Range<usize> {
|
||||
let no_rows = operations.len()..operations.len();
|
||||
@@ -359,7 +379,20 @@ fn pieces(index: usize, operation: &EffectOperation) -> Vec<(EffectPiece, BlendM
|
||||
}
|
||||
EffectOperation::PaintOverlay { blend_mode, .. } => vec![piece(0, Within, None, *blend_mode)],
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay { color, blend_mode, .. }) => vec![piece(0, Within, Some(*color), *blend_mode)],
|
||||
EffectOperation::Blur { .. } | EffectOperation::Mask { .. } | EffectOperation::Feather { .. } | EffectOperation::Adjustment(_) => Vec::new(),
|
||||
EffectOperation::Blur { .. }
|
||||
| EffectOperation::MotionBlur { .. }
|
||||
| EffectOperation::RadialBlur { .. }
|
||||
| EffectOperation::Mask { .. }
|
||||
| EffectOperation::Feather { .. }
|
||||
| EffectOperation::ConvolutionKernel { .. }
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
| EffectOperation::Adjustment(_) => Vec::new(),
|
||||
};
|
||||
pieces.into_iter().flatten().collect()
|
||||
}
|
||||
@@ -564,6 +597,7 @@ mod tests {
|
||||
#[test]
|
||||
fn rows_that_change_nothing_neither_flatten_nor_split_the_others() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -605,6 +639,7 @@ mod tests {
|
||||
#[test]
|
||||
fn trailing_masks_fade_each_layer_in_its_own_blend_mode() {
|
||||
let no_blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -642,6 +677,7 @@ mod tests {
|
||||
#[test]
|
||||
fn effects_before_a_blur_or_a_mode_css_lacks_are_flattened() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -668,6 +704,29 @@ mod tests {
|
||||
assert_eq!(parts(&layers), [[None]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn content_images_keep_the_filters_and_what_they_merge_but_not_the_pieces_around_them() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let shadow = || drop_shadow(RED, BlendMode::Multiply);
|
||||
let kinds = |operations: Vec<EffectOperation>| -> Vec<EffectKind> { content_image_effects(&Effects::from_operations(operations)).operations().map(|operation| operation.kind()).collect() };
|
||||
|
||||
// A shadow is cast from the content, unless a later filter merges it into the content's image
|
||||
assert!(kinds(vec![shadow()]).is_empty());
|
||||
assert_eq!(kinds(vec![blur.clone(), shadow()]), [EffectKind::Blur]);
|
||||
let merged = Effects::from_operations([shadow(), blur.clone()]);
|
||||
assert!(matches!(content_image_effects(&merged), Cow::Borrowed(_)));
|
||||
|
||||
// Trailing masks fade the content's image as they fade each layer
|
||||
assert_eq!(kinds(vec![shadow(), mask()]), [EffectKind::Mask]);
|
||||
let filtered = vec![mask(), inner_shadow(RED, BlendMode::Screen), blur, shadow(), mask()];
|
||||
assert_eq!(kinds(filtered), [EffectKind::Mask, EffectKind::InnerShadow, EffectKind::Blur, EffectKind::Mask]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn knocked_out_pieces_hide_behind_however_the_content_covers_them() {
|
||||
let same_layer = EffectLayers::plan(&Effects::from_operations([drop_shadow(RED, BlendMode::Normal)]), BlendMode::Normal, 0.5, true);
|
||||
|
||||
@@ -4,8 +4,10 @@
|
||||
|
||||
use crate::Graphic;
|
||||
use crate::adjustment::Adjustment;
|
||||
use crate::filters::{Convolution, NoiseDistribution};
|
||||
use crate::masks::{MaskMode, mask_feather_sigma};
|
||||
use crate::parameters::{ParameterVisitor, ReadParameters, WriteParameters};
|
||||
use crate::resampling::RadialBlurMethod;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
@@ -25,7 +27,7 @@ use vector_types::{Gradient, GradientSettings};
|
||||
/// The image operation an [`Effect`] carries out.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, CacheHash)]
|
||||
pub enum EffectKind {
|
||||
/// Softens the content by blurring it.
|
||||
/// Softens the content by blurring it, evenly or more where its radius mask is brighter.
|
||||
#[default]
|
||||
Blur,
|
||||
/// Casts the content's silhouette as a soft shadow beneath it.
|
||||
@@ -48,6 +50,26 @@ pub enum EffectKind {
|
||||
Mask,
|
||||
/// Fades the content out toward its edges, reaching nothing at them.
|
||||
Feather,
|
||||
/// Sums each pixel's neighbors weighted by a kernel of numbers.
|
||||
ConvolutionKernel,
|
||||
/// Grays the content, showing its edges in relief as if lit from one side.
|
||||
Emboss,
|
||||
/// Outlines the content's edges in dark over white.
|
||||
FindEdges,
|
||||
/// Spreads each pixel's darkest or lightest neighboring colors.
|
||||
MinimumMaximum,
|
||||
/// Exaggerates how much each pixel differs from a blur of those around it, or only along edges, from its four neighbors.
|
||||
Sharpen,
|
||||
/// Keeps how much each pixel differs from a blur of those around it, around middle gray.
|
||||
HighPass,
|
||||
/// Scatters random offsets across the colors, fixed in place on the content.
|
||||
AddNoise,
|
||||
/// Shows a random scattering of the content fully opaque and hides the rest, more where it's more opaque.
|
||||
Dissolve,
|
||||
/// Smears the content along a line, as if it moved while being captured.
|
||||
MotionBlur,
|
||||
/// Smears the content around a center or toward it.
|
||||
RadialBlur,
|
||||
// The adjustments, which change each color of the content on its own, as their nodes of the same names do
|
||||
Desaturate,
|
||||
GammaCorrection,
|
||||
@@ -68,6 +90,7 @@ pub enum EffectKind {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -84,6 +107,16 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PaintOverlay => "Paint Overlay",
|
||||
Self::Mask => "Mask",
|
||||
Self::Feather => "Feather",
|
||||
Self::ConvolutionKernel => "Convolution Kernel",
|
||||
Self::Emboss => "Emboss",
|
||||
Self::FindEdges => "Find Edges",
|
||||
Self::MinimumMaximum => "Minimum/Maximum",
|
||||
Self::Sharpen => "Sharpen",
|
||||
Self::HighPass => "High Pass",
|
||||
Self::AddNoise => "Add Noise",
|
||||
Self::Dissolve => "Dissolve",
|
||||
Self::MotionBlur => "Motion Blur",
|
||||
Self::RadialBlur => "Radial Blur",
|
||||
Self::Desaturate => "Desaturate",
|
||||
Self::GammaCorrection => "Gamma Correction",
|
||||
Self::MakeOpaque => "Make Opaque",
|
||||
@@ -103,6 +136,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::ColorBalance => "Color Balance",
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -133,6 +167,19 @@ pub enum GlowSource {
|
||||
Center,
|
||||
}
|
||||
|
||||
/// Which extreme of the colors around each pixel a Minimum/Maximum spreads.
|
||||
#[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 MinimumMaximumMode {
|
||||
/// Spreads the darkest colors, growing the content's coverage by the radius.
|
||||
#[default]
|
||||
Minimum,
|
||||
/// Spreads the lightest colors, shrinking the content's coverage by the radius.
|
||||
Maximum,
|
||||
}
|
||||
|
||||
/// One of the coverages an effect is drawn from, which a render can output in place of the effects' result, so an SVG can embed it as a map of what its filters can't work out.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct EffectCapture {
|
||||
@@ -287,37 +334,9 @@ pub fn texture_gray([red, green, blue, _]: [f32; 4]) -> f32 {
|
||||
0.299 * red + 0.587 * green + 0.114 * blue
|
||||
}
|
||||
|
||||
/// Whether a paint is a gradient or image without its own placement, which stretches across the content it paints.
|
||||
pub fn is_unplaced_paint(paint: &Graphic) -> bool {
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
/// An effect's drawn paint with its unit square fitted to `content_bounds`, the extent it fills 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> {
|
||||
if !is_unplaced_paint(paint) {
|
||||
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)
|
||||
}
|
||||
|
||||
/// The `graphic` expressed in the own space of content placed by `placement`, for an effect with a drawn graphic that follows the content (see [`EffectOperation::drawn_paint_follows_content`]).
|
||||
/// A gradient or image without its own placement stays as it is, since it stretches across the content wherever that lies.
|
||||
pub fn linked_to_content(graphic: Graphic, placement: DAffine2) -> Graphic {
|
||||
if is_unplaced_paint(&graphic) || placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||
if placement == DAffine2::IDENTITY || !placement.matrix2.determinant().is_normal() {
|
||||
return graphic;
|
||||
}
|
||||
Graphic::Graphic(Box::new(Item::new_from_element(graphic).with_attribute(ATTR_TRANSFORM, placement.inverse())))
|
||||
@@ -403,6 +422,7 @@ impl Effects {
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint, in the effect space of a run of them.
|
||||
/// It leaves out what [`Effects::reach_around`] adds from the content's bounds and what it paints past its frame, for the effects relative to its extent.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.painted_reach()).sum()
|
||||
}
|
||||
@@ -412,6 +432,11 @@ impl Effects {
|
||||
self.operations().map(|operation| operation.working_reach()).sum()
|
||||
}
|
||||
|
||||
/// How far past the content a render of the effects must reach to draw them right (see [`EffectOperation::required_reach`]), in the effect space of a run of them.
|
||||
pub fn required_reach(&self) -> f64 {
|
||||
self.operations().map(|operation| operation.required_reach()).sum()
|
||||
}
|
||||
|
||||
/// Splits the rows into runs stamped in the same space, in order, each with the transform its effects were stamped at.
|
||||
/// A transform applied between two effects starts a new run, which renders around the result of those before it.
|
||||
/// Effects that change nothing join the run they're in, and a run of only those takes the space of the next effect.
|
||||
@@ -438,31 +463,38 @@ impl Effects {
|
||||
runs
|
||||
}
|
||||
|
||||
/// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics that follow the content with them.
|
||||
/// Moves the transforms the effects were stamped at onto content whose `baked` transform went into its geometry, and the graphics and radial blur centers that follow the content with them.
|
||||
pub fn rebase_stamped_transforms(&mut self, baked: DAffine2) {
|
||||
if let Some(transforms) = self.0.iter_attribute_values_mut::<DAffine2>(ATTR_TRANSFORM) {
|
||||
transforms.for_each(|transform| *transform = rebased_stamped_transform(*transform, baked));
|
||||
}
|
||||
|
||||
// A mask's graphic lies in the content's own space, which `baked` now places within the geometry
|
||||
// A graphic following the content (see `EffectOperation::drawn_paint_follows_content`) lies in its own space, which `baked` now places within the geometry
|
||||
if baked == DAffine2::IDENTITY || !baked.matrix2.determinant().is_normal() {
|
||||
return;
|
||||
}
|
||||
for effect in self.0.iter_element_values_mut() {
|
||||
if effect.kind() == EffectKind::Mask
|
||||
&& let Some(mask) = effect.0.attribute_mut::<Graphic>("mask")
|
||||
&& !is_unplaced_paint(mask)
|
||||
{
|
||||
*mask = Graphic::Graphic(Box::new(Item::new_from_element(std::mem::take(mask)).with_attribute(ATTR_TRANSFORM, baked)));
|
||||
let key = match effect.kind() {
|
||||
EffectKind::Mask => "mask",
|
||||
EffectKind::Blur => "radius_mask",
|
||||
EffectKind::PaintOverlay | EffectKind::Outline => "paint",
|
||||
EffectKind::BevelAndEmboss => "texture",
|
||||
_ => continue,
|
||||
};
|
||||
if let Some(graphic) = effect.0.attribute_mut::<Graphic>(key) {
|
||||
*graphic = Graphic::Graphic(Box::new(Item::new_from_element(std::mem::take(graphic)).with_attribute(ATTR_TRANSFORM, baked)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The mask and feather rows alone, with the transforms they were stamped at, or `None` without any. They shape what clips to the content as they shape the content itself, unlike the other effects.
|
||||
pub fn shaping_only(&self) -> Option<Effects> {
|
||||
let shapes = |index: &usize| self.0.element(*index).is_some_and(|effect| matches!(effect.kind(), EffectKind::Mask | EffectKind::Feather));
|
||||
let shaping: List<Effect> = (0..self.len()).filter(shapes).filter_map(|index| self.0.clone_item(index)).collect();
|
||||
(!shaping.is_empty()).then_some(Effects(shaping))
|
||||
// A radial blur's center is a position measured from the effect space's origin, which moves by the translation `baked` took from the content
|
||||
for index in 0..self.0.len() {
|
||||
let stamped_transform = self.0.attribute_cloned_or_default::<DAffine2>(ATTR_TRANSFORM, index);
|
||||
if let Some(effect) = self.0.element_mut(index)
|
||||
&& matches!(effect.kind(), EffectKind::RadialBlur)
|
||||
{
|
||||
*effect.0.attribute_mut_or_insert_default::<DVec2>("center") += stamped_transform.matrix2 * baked.translation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The effects of a run of rows, borrowed when the run is every row.
|
||||
@@ -473,6 +505,12 @@ impl Effects {
|
||||
}
|
||||
}
|
||||
|
||||
/// The effects with operations that `keep` accepts, in order, each still stamped where it was.
|
||||
pub fn keeping(&self, keep: impl Fn(&EffectOperation) -> bool) -> Self {
|
||||
let kept = self.effects().enumerate().filter(|(_, effect)| keep(&effect.operation())).map(|(index, _)| index);
|
||||
Effects(kept.filter_map(|index| self.0.clone_item(index)).collect())
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint along each axis of the space `content_transform` places the content in.
|
||||
pub fn reach_along_axes(&self, content_transform: DAffine2) -> DVec2 {
|
||||
self.reach_along_axes_by(content_transform, EffectOperation::painted_reach)
|
||||
@@ -494,7 +532,7 @@ impl Effects {
|
||||
|
||||
/// How far past the content the effects reading around each pixel (see [`EffectOperation::reads_pixels_around`]) together read, along the axis of the space `content_transform` places the content in that they read furthest along.
|
||||
pub fn read_reach(&self, content_transform: DAffine2) -> f64 {
|
||||
let reach = |operation: &EffectOperation| if operation.reads_pixels_around() { operation.painted_reach() } else { 0. };
|
||||
let reach = |operation: &EffectOperation| if operation.reads_pixels_around() { operation.working_reach() } else { 0. };
|
||||
self.reach_along_axes_by(content_transform, reach).max_element()
|
||||
}
|
||||
|
||||
@@ -726,8 +764,13 @@ pub fn rebased_stamped_transform(stamped_transform: DAffine2, baked: DAffine2) -
|
||||
/// An effect's parameters decoded from its row, the form that renderers carry it out from. Lengths are in its [`effect_space`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum EffectOperation {
|
||||
/// Blurs the content after what lies beneath it joins it, evenly or as its radius mask varies the radius: by the interpolation between Gaussians [`crate::masks::masked_radius_blur_interpolation`] defines,
|
||||
/// or as a box blur, by a box at each pixel as wide as its fraction of the radius.
|
||||
Blur {
|
||||
/// The standard deviation of the Gaussian, or the half width of the box.
|
||||
/// Lies in the content's own space, so it moves with the content, with its luminance setting each point's fraction of the radius.
|
||||
/// One that draws nothing, the default, blurs the whole content by the radius.
|
||||
radius_mask: Graphic,
|
||||
/// The standard deviation of the Gaussian, or the half width of the box, where the radius mask is white.
|
||||
radius: f64,
|
||||
/// Whether to average a box of pixels rather than weighting them by a Gaussian.
|
||||
box_blur: bool,
|
||||
@@ -797,7 +840,7 @@ pub enum EffectOperation {
|
||||
contour: TransferCurve,
|
||||
},
|
||||
Outline {
|
||||
/// A solid color with the outline's opacity, a gradient, or any graphic, fitted when unplaced to the content and the outline's margin.
|
||||
/// A solid color with the outline's opacity, a gradient, or any graphic, placed in the space the content's item is.
|
||||
paint: Graphic,
|
||||
/// How the outline mixes with what lies beneath it, or with the content for the part inside its edge.
|
||||
blend_mode: BlendMode,
|
||||
@@ -846,7 +889,7 @@ pub enum EffectOperation {
|
||||
},
|
||||
/// 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.
|
||||
/// Placed in the space the content's item is.
|
||||
paint: Graphic,
|
||||
blend_mode: BlendMode,
|
||||
/// Percent.
|
||||
@@ -868,6 +911,76 @@ pub enum EffectOperation {
|
||||
/// How far in from the edges the fade reaches full strength.
|
||||
distance: f64,
|
||||
},
|
||||
ConvolutionKernel {
|
||||
/// The weights row by row, centered on each pixel as [`Convolution::custom`] places them.
|
||||
kernel: List<f64>,
|
||||
/// How many weights each row of the kernel holds.
|
||||
columns: u32,
|
||||
/// What the weighted sum is divided by.
|
||||
scale: f64,
|
||||
/// On a scale of 0 to 255.
|
||||
offset: f64,
|
||||
/// Whether the content's coverage is weighed by the kernel too, rather than kept.
|
||||
apply_to_alpha: bool,
|
||||
},
|
||||
Emboss {
|
||||
/// The direction the light comes from, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How far apart the two samples are, the difference between them showing as relief.
|
||||
height: f64,
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
},
|
||||
FindEdges,
|
||||
MinimumMaximum {
|
||||
/// How many pixels the square neighborhood reaches out from its center.
|
||||
radius: f64,
|
||||
mode: MinimumMaximumMode,
|
||||
},
|
||||
Sharpen {
|
||||
/// Percent.
|
||||
amount: f64,
|
||||
/// The standard deviation of the Gaussian blur the content is compared against, which Edges Only ignores.
|
||||
radius: f64,
|
||||
/// On a scale of 0 to 255.
|
||||
threshold: f64,
|
||||
/// Whether the content is compared against its four nearest neighbors only along edges, as [`crate::filters::edge_gain`] ramps it, rather than against the blur.
|
||||
edges_only: bool,
|
||||
},
|
||||
HighPass {
|
||||
radius: f64,
|
||||
},
|
||||
AddNoise {
|
||||
/// Percent of full brightness.
|
||||
amount: f64,
|
||||
distribution: NoiseDistribution,
|
||||
/// Whether each pixel's colors all take the same offset, so only their brightness changes.
|
||||
monochromatic: bool,
|
||||
seed: i64,
|
||||
},
|
||||
Dissolve {
|
||||
/// Percent of the content that shows where it's fully opaque.
|
||||
opacity: f64,
|
||||
seed: i64,
|
||||
},
|
||||
MotionBlur {
|
||||
/// The direction of the line, in degrees counterclockwise from the right.
|
||||
angle: f64,
|
||||
/// How long the line each point is smeared along is.
|
||||
distance: f64,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
RadialBlur {
|
||||
/// Whether the content spins around the center or zooms toward it.
|
||||
method: RadialBlurMethod,
|
||||
/// How far the blur smears, by the degrees of a spin or twice the percentage of the distance to the center of a zoom, up to 360.
|
||||
amount: f64,
|
||||
/// The point the blur spins around or zooms toward, measured from the effect space's origin (the content's).
|
||||
center: DVec2,
|
||||
/// Whether to blend the colors with their gamma encoding rather than in linear light.
|
||||
gamma: bool,
|
||||
},
|
||||
Adjustment(Adjustment),
|
||||
}
|
||||
|
||||
@@ -877,6 +990,21 @@ impl EffectOperation {
|
||||
Effect(Item::new_from_element(kind)).operation()
|
||||
}
|
||||
|
||||
/// A convolution kernel of the weights `text` writes (see [`crate::filters::parse_kernel`]), its sums divided by `scale` and raised by `offset` levels out of 255, weighing the coverage too if `apply_to_alpha`.
|
||||
/// Without a `scale`, it divides by the [`crate::filters::automatic_scale`].
|
||||
pub fn convolution_kernel(text: &str, scale: Option<f64>, offset: f64, apply_to_alpha: bool) -> Self {
|
||||
let (weights, columns) = crate::filters::parse_kernel(text);
|
||||
let scale = scale.unwrap_or_else(|| crate::filters::automatic_scale(&weights, columns));
|
||||
|
||||
Self::ConvolutionKernel {
|
||||
kernel: List::new_from_elements(weights),
|
||||
columns: columns as u32,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> EffectKind {
|
||||
match self {
|
||||
Self::Blur { .. } => EffectKind::Blur,
|
||||
@@ -890,10 +1018,43 @@ impl EffectOperation {
|
||||
Self::PaintOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Mask { .. } => EffectKind::Mask,
|
||||
Self::Feather { .. } => EffectKind::Feather,
|
||||
Self::ConvolutionKernel { .. } => EffectKind::ConvolutionKernel,
|
||||
Self::Emboss { .. } => EffectKind::Emboss,
|
||||
Self::FindEdges => EffectKind::FindEdges,
|
||||
Self::MinimumMaximum { .. } => EffectKind::MinimumMaximum,
|
||||
Self::Sharpen { .. } => EffectKind::Sharpen,
|
||||
Self::HighPass { .. } => EffectKind::HighPass,
|
||||
Self::AddNoise { .. } => EffectKind::AddNoise,
|
||||
Self::Dissolve { .. } => EffectKind::Dissolve,
|
||||
Self::MotionBlur { .. } => EffectKind::MotionBlur,
|
||||
Self::RadialBlur { .. } => EffectKind::RadialBlur,
|
||||
Self::Adjustment(adjustment) => adjustment.kind(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted sum of shifted copies of the content that a filter carries out, for the filters that are one.
|
||||
pub fn convolution(&self) -> Option<Convolution> {
|
||||
match self {
|
||||
// An empty kernel, like the identity, leaves the content as it is
|
||||
Self::ConvolutionKernel {
|
||||
kernel,
|
||||
columns,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
} => {
|
||||
let weights: Vec<f64> = kernel.iter_element_values().copied().collect();
|
||||
let convolution = Convolution {
|
||||
weighs_coverage: *apply_to_alpha,
|
||||
..Convolution::custom(&weights, *columns as usize, *scale, *offset)
|
||||
};
|
||||
(!weights.is_empty() && !convolution.is_identity()).then_some(convolution)
|
||||
}
|
||||
Self::Emboss { angle, height, amount } => Some(Convolution::emboss(*angle, *height, *amount)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation leaves the content as it is, like a blur of no radius or a shadow of no opacity.
|
||||
pub fn changes_nothing(&self) -> bool {
|
||||
match self {
|
||||
@@ -910,17 +1071,30 @@ impl EffectOperation {
|
||||
..
|
||||
} => (highlight_color.a() <= 0. && shadow_color.a() <= 0.) || (*size <= 0. && gloss_contour.is_identity()),
|
||||
Self::PaintOverlay { opacity, .. } => *opacity <= 0.,
|
||||
Self::MotionBlur { distance, .. } => *distance <= 0.,
|
||||
Self::RadialBlur { amount, .. } => *amount <= 0.,
|
||||
Self::Adjustment(Adjustment::ColorOverlay { color, opacity, .. }) => color.a() <= 0. || *opacity <= 0.,
|
||||
Self::Mask { density, .. } => *density <= 0.,
|
||||
Self::Feather { distance } => *distance <= 0.,
|
||||
Self::Adjustment(_) => false,
|
||||
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
|
||||
Self::Emboss { .. } | Self::FindEdges | Self::HighPass { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
Self::AddNoise { amount, .. } => *amount <= 0.,
|
||||
// The four neighbors lie a fixed distance away, so only the blur needs a radius
|
||||
Self::Sharpen { amount, radius, edges_only, .. } => *amount <= 0. || (!*edges_only && *radius <= 0.),
|
||||
Self::MinimumMaximum { radius, .. } => *radius <= 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this is a blur varying its radius by a radius mask that draws something, rather than blurring the whole content evenly.
|
||||
pub fn varies_blur_radius(&self) -> bool {
|
||||
matches!(self, Self::Blur { radius_mask, .. } if !radius_mask.draws_nothing())
|
||||
}
|
||||
|
||||
/// Whether this operation reads the pixels around each one of the image the effects before it leave, like a blur, rather than casting from the content's shape or changing each pixel alone.
|
||||
pub fn reads_pixels_around(&self) -> bool {
|
||||
match self {
|
||||
Self::Blur { .. } => true,
|
||||
Self::Blur { .. } | Self::MotionBlur { .. } | Self::RadialBlur { .. } => true,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } | Self::FindEdges | Self::MinimumMaximum { .. } | Self::Sharpen { .. } | Self::HighPass { .. } => true,
|
||||
// Cast from the content's shape, reading a mask's own image or a feather's map, or changing each pixel alone
|
||||
Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
@@ -930,17 +1104,27 @@ impl EffectOperation {
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::Feather { .. } => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::Adjustment(_) => false,
|
||||
Self::PaintOverlay { .. } | Self::Mask { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, or a feather.
|
||||
/// How far past the content this operation paints, which is nowhere for an operation that changes nothing, a mask, a feather, or a filter that keeps or shrinks the content's coverage.
|
||||
pub fn painted_reach(&self) -> f64 {
|
||||
if self.changes_nothing() || matches!(self, Self::Mask { .. } | Self::Feather { .. }) {
|
||||
0.
|
||||
} else {
|
||||
self.reach()
|
||||
}
|
||||
let keeps_coverage = matches!(
|
||||
self,
|
||||
Self::Mask { .. }
|
||||
| Self::Feather { .. }
|
||||
| Self::ConvolutionKernel { apply_to_alpha: false, .. }
|
||||
| Self::Emboss { .. }
|
||||
| Self::FindEdges
|
||||
| Self::MinimumMaximum {
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
..
|
||||
}
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
);
|
||||
if self.changes_nothing() || keeps_coverage { 0. } else { self.reach() }
|
||||
}
|
||||
|
||||
/// How far past the content this operation paints or reads from, which the region it's worked out over covers, and nowhere for an operation that changes nothing.
|
||||
@@ -948,10 +1132,16 @@ impl EffectOperation {
|
||||
if self.changes_nothing() { 0. } else { self.reach() }
|
||||
}
|
||||
|
||||
/// How far past the content a render must reach for this operation to come out right: as far as it paints, or for one reading around each pixel, as far as it reads.
|
||||
pub fn required_reach(&self) -> f64 {
|
||||
if self.reads_pixels_around() { self.working_reach() } else { self.painted_reach() }
|
||||
}
|
||||
|
||||
/// How far past the content this operation can paint, or reads from, in its effect space.
|
||||
pub fn reach(&self) -> f64 {
|
||||
match self {
|
||||
// A Gaussian is negligible past three standard deviations
|
||||
// A box reaches its half width, and the pixel past it for a fractional one, while a Gaussian fades out over three standard deviations
|
||||
Self::Blur { radius, box_blur: true, .. } => radius.max(0.) + 1.,
|
||||
Self::Blur { radius, .. } => 3. * radius.max(0.),
|
||||
// An inner shadow paints within the content but reads this far out to find the edges it casts from.
|
||||
// Shadows and glows end within their size, past which a precise glow fades over one more unit.
|
||||
@@ -965,11 +1155,22 @@ impl EffectOperation {
|
||||
Self::Mask { feather, .. } => 3. * mask_feather_sigma(*feather),
|
||||
// A feather paints nothing past the content, but finds edges up to this far past it, which a render cut short there would miss
|
||||
Self::Feather { distance } => distance.max(0.) + 1.,
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => 0.,
|
||||
Self::ConvolutionKernel { .. } | Self::Emboss { .. } => self.convolution().map_or(0., |convolution| convolution.read_reach()),
|
||||
// The Sobel taps' diagonal, then a faint pixel's nearest visible color within the square of a pixel around that, plus two pixels for rounding and copies between pixels
|
||||
Self::Sharpen { edges_only: true, .. } => 2. * std::f64::consts::SQRT_2 + 2.,
|
||||
Self::Sharpen { radius, .. } | Self::HighPass { radius } => 3. * radius.max(0.) + 1.,
|
||||
// The Sobel taps' diagonal, which a rotation can turn along an axis, plus two pixels for rounding and copies between pixels
|
||||
Self::FindEdges => std::f64::consts::SQRT_2 + 2.,
|
||||
Self::MinimumMaximum { radius, .. } => radius.max(0.).ceil() + 1.,
|
||||
// The line reaches half its length each way, past which its box leans half a pixel and its shears interpolate two pixels
|
||||
Self::MotionBlur { distance, .. } => distance.max(0.) / 2. + 3.,
|
||||
// It reaches farther from content lying farther from its center, which `Effects::reach_around` measures
|
||||
Self::RadialBlur { .. } => 0.,
|
||||
Self::PaintOverlay { .. } | Self::AddNoise { .. } | Self::Dissolve { .. } | Self::Adjustment(_) => 0.,
|
||||
}
|
||||
}
|
||||
|
||||
/// The graphic this operation paints with that renderers draw over the content's pixels on their own: a paint overlay's paint, an outline's drawn paint, a bevel's texture, or a mask's graphic.
|
||||
/// The graphic this operation paints with that renderers draw over the content's pixels on their own: a paint overlay's paint, an outline's drawn paint, a bevel's texture, a mask's graphic, or a blur's radius mask.
|
||||
/// An operation that changes nothing draws none, since renderers skip it.
|
||||
pub fn drawn_paint(&self) -> Option<&Graphic> {
|
||||
if self.changes_nothing() {
|
||||
@@ -984,31 +1185,18 @@ impl EffectOperation {
|
||||
},
|
||||
Self::BevelAndEmboss { texture, .. } => (!matches!(texture, Graphic::None(_) | Graphic::NoneList(_))).then_some(texture),
|
||||
Self::Mask { mask, .. } => Some(mask),
|
||||
Self::Blur { radius_mask, .. } => self.varies_blur_radius().then_some(radius_mask),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the graphic this operation draws with is placed in the content's own space, so it moves with the content, rather than in the space the content's item is placed in.
|
||||
/// The nodes stamping such operations express the graphic relative to the content's placement at that time with [`linked_to_content`].
|
||||
/// A paint lies there as given, like a fill's, while a mask's graphic is expressed relative to the content's placement at the time with [`linked_to_content`].
|
||||
pub fn drawn_paint_follows_content(&self) -> bool {
|
||||
matches!(self, Self::Mask { .. })
|
||||
}
|
||||
|
||||
/// The bounds a drawn paint without its own placement is fitted to, given the content's bounds and the length a document pixel spans along each of their axes.
|
||||
/// For PSD interop, an outline's paint fits the content grown by the whole pixels the outline reaches outside it, at least one.
|
||||
pub fn drawn_paint_bounds(&self, content_bounds: [DVec2; 2], pixel_spans: DVec2) -> [DVec2; 2] {
|
||||
match self {
|
||||
Self::Outline { weight, align, .. } => {
|
||||
// Interpolated between the whole weights PSD stores
|
||||
let margin_at = |weight: f64| outline_extents(weight, *align).0.ceil().max(1.);
|
||||
let weight = weight.max(0.);
|
||||
let below = weight.floor();
|
||||
let margin = margin_at(below) + (margin_at(below + 1.) - margin_at(below)) * (weight - below);
|
||||
|
||||
[content_bounds[0] - margin * pixel_spans, content_bounds[1] + margin * pixel_spans]
|
||||
}
|
||||
_ => content_bounds,
|
||||
}
|
||||
matches!(
|
||||
self,
|
||||
Self::Mask { .. } | Self::Blur { .. } | Self::PaintOverlay { .. } | Self::Outline { .. } | Self::BevelAndEmboss { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// This operation with each length that isn't finite (like one computed by dividing by zero) made zero, since no renderer can carry it out.
|
||||
@@ -1043,7 +1231,14 @@ impl EffectOperation {
|
||||
} => [depth, size, soften, angle, altitude, slope_range, texture_depth].into_iter().for_each(finite),
|
||||
Self::Mask { density, feather, .. } => [density, feather].into_iter().for_each(finite),
|
||||
Self::Feather { distance } => finite(distance),
|
||||
Self::PaintOverlay { .. } | Self::Adjustment(_) => {}
|
||||
Self::Emboss { angle, height, amount } => [angle, height, amount].into_iter().for_each(finite),
|
||||
Self::MinimumMaximum { radius, .. } | Self::HighPass { radius } => finite(radius),
|
||||
Self::Sharpen { amount, radius, threshold, .. } => [amount, radius, threshold].into_iter().for_each(finite),
|
||||
Self::AddNoise { amount, .. } => finite(amount),
|
||||
Self::Dissolve { opacity, .. } => finite(opacity),
|
||||
Self::MotionBlur { angle, distance, .. } => [angle, distance].into_iter().for_each(finite),
|
||||
Self::RadialBlur { amount, center, .. } => [amount, &mut center.x, &mut center.y].into_iter().for_each(finite),
|
||||
Self::PaintOverlay { .. } | Self::ConvolutionKernel { .. } | Self::FindEdges | Self::Adjustment(_) => {}
|
||||
}
|
||||
self
|
||||
}
|
||||
@@ -1052,6 +1247,7 @@ impl EffectOperation {
|
||||
fn placeholder(kind: EffectKind) -> Self {
|
||||
match kind {
|
||||
EffectKind::Blur => Self::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 0.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -1144,6 +1340,44 @@ impl EffectOperation {
|
||||
invert: false,
|
||||
},
|
||||
EffectKind::Feather => Self::Feather { distance: 0. },
|
||||
EffectKind::ConvolutionKernel => Self::ConvolutionKernel {
|
||||
kernel: List::new(),
|
||||
columns: 0,
|
||||
scale: 0.,
|
||||
offset: 0.,
|
||||
apply_to_alpha: false,
|
||||
},
|
||||
EffectKind::Emboss => Self::Emboss { angle: 0., height: 0., amount: 0. },
|
||||
EffectKind::FindEdges => Self::FindEdges,
|
||||
EffectKind::MinimumMaximum => Self::MinimumMaximum {
|
||||
radius: 0.,
|
||||
mode: MinimumMaximumMode::default(),
|
||||
},
|
||||
EffectKind::Sharpen => Self::Sharpen {
|
||||
amount: 0.,
|
||||
radius: 0.,
|
||||
threshold: 0.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectKind::HighPass => Self::HighPass { radius: 0. },
|
||||
EffectKind::AddNoise => Self::AddNoise {
|
||||
amount: 0.,
|
||||
distribution: NoiseDistribution::default(),
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
},
|
||||
EffectKind::Dissolve => Self::Dissolve { opacity: 0., seed: 0 },
|
||||
EffectKind::MotionBlur => Self::MotionBlur {
|
||||
angle: 0.,
|
||||
distance: 0.,
|
||||
gamma: false,
|
||||
},
|
||||
EffectKind::RadialBlur => Self::RadialBlur {
|
||||
method: RadialBlurMethod::default(),
|
||||
amount: 0.,
|
||||
center: DVec2::ZERO,
|
||||
gamma: false,
|
||||
},
|
||||
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),
|
||||
@@ -1179,6 +1413,7 @@ impl EffectOperation {
|
||||
preserve_luminosity: false,
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1189,8 +1424,9 @@ impl EffectOperation {
|
||||
let glow_color = Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf));
|
||||
|
||||
match self {
|
||||
Self::Blur { radius, box_blur, gamma } => {
|
||||
Self::Blur { radius_mask, radius, box_blur, gamma } => {
|
||||
visitor.parameter("radius", radius, 0.);
|
||||
visitor.parameter("radius_mask", radius_mask, Graphic::default());
|
||||
visitor.parameter("box_blur", box_blur, false);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
@@ -1350,6 +1586,68 @@ impl EffectOperation {
|
||||
visitor.parameter("invert", invert, false);
|
||||
}
|
||||
Self::Feather { distance } => visitor.parameter("distance", distance, 10.),
|
||||
Self::ConvolutionKernel {
|
||||
kernel,
|
||||
columns,
|
||||
scale,
|
||||
offset,
|
||||
apply_to_alpha,
|
||||
} => {
|
||||
visitor.parameter("kernel", kernel, List::new_from_elements(vec![0., 0., 0., 0., 1., 0., 0., 0., 0.]));
|
||||
visitor.parameter("columns", columns, 3);
|
||||
visitor.parameter("scale", scale, 1.);
|
||||
visitor.parameter("offset", offset, 0.);
|
||||
visitor.parameter("apply_to_alpha", apply_to_alpha, false);
|
||||
}
|
||||
// For PSD interop, the defaults are those of the filters' dialogs
|
||||
Self::Emboss { angle, height, amount } => {
|
||||
visitor.parameter("angle", angle, 135.);
|
||||
visitor.parameter("height", height, 3.);
|
||||
visitor.parameter("amount", amount, 100.);
|
||||
}
|
||||
Self::FindEdges => {}
|
||||
Self::MinimumMaximum { radius, mode } => {
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("mode", mode, MinimumMaximumMode::default());
|
||||
}
|
||||
Self::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
threshold,
|
||||
edges_only,
|
||||
} => {
|
||||
visitor.parameter("amount", amount, 50.);
|
||||
visitor.parameter("radius", radius, 1.);
|
||||
visitor.parameter("threshold", threshold, 0.);
|
||||
visitor.parameter("edges_only", edges_only, false);
|
||||
}
|
||||
Self::HighPass { radius } => visitor.parameter("radius", radius, 10.),
|
||||
Self::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => {
|
||||
visitor.parameter("amount", amount, 12.5);
|
||||
visitor.parameter("distribution", distribution, NoiseDistribution::default());
|
||||
visitor.parameter("monochromatic", monochromatic, false);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::Dissolve { opacity, seed } => {
|
||||
visitor.parameter("opacity", opacity, 50.);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::MotionBlur { angle, distance, gamma } => {
|
||||
visitor.parameter("angle", angle, 0.);
|
||||
visitor.parameter("distance", distance, 10.);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::RadialBlur { method, amount, center, gamma } => {
|
||||
visitor.parameter("method", method, RadialBlurMethod::default());
|
||||
visitor.parameter("amount", amount, 10.);
|
||||
visitor.parameter("center", center, DVec2::ZERO);
|
||||
visitor.parameter("gamma", gamma, false);
|
||||
}
|
||||
Self::Adjustment(adjustment) => adjustment.visit_parameters(visitor),
|
||||
}
|
||||
}
|
||||
@@ -1364,6 +1662,7 @@ mod tests {
|
||||
fn rows_round_trip_their_operations_eliding_defaults() {
|
||||
let operations = [
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 6.,
|
||||
box_blur: true,
|
||||
gamma: false,
|
||||
@@ -1462,11 +1761,66 @@ mod tests {
|
||||
invert: true,
|
||||
},
|
||||
EffectOperation::Feather { distance: 4.5 },
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Graphic::from(Color::WHITE),
|
||||
radius: 7.5,
|
||||
box_blur: true,
|
||||
gamma: true,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::ColorOverlay {
|
||||
color: Color::GREEN,
|
||||
blend_mode: BlendMode::Screen,
|
||||
opacity: 100.,
|
||||
}),
|
||||
EffectOperation::convolution_kernel("-1 0 1\n-2 0 2\n-1 0 1", Some(4.), 128., false),
|
||||
EffectOperation::convolution_kernel("0 -1 0\n-1 8 -1\n0 -1 0", None, 0., true),
|
||||
EffectOperation::Emboss {
|
||||
angle: -30.,
|
||||
height: 4.5,
|
||||
amount: 250.,
|
||||
},
|
||||
EffectOperation::FindEdges,
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 2.5,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
},
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 7.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Adjustment(Adjustment::Solarize),
|
||||
EffectOperation::Sharpen {
|
||||
amount: 180.,
|
||||
radius: 2.5,
|
||||
threshold: 4.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectOperation::HighPass { radius: 3.5 },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Gaussian,
|
||||
monochromatic: true,
|
||||
seed: 7,
|
||||
},
|
||||
EffectOperation::Dissolve { opacity: 25., seed: 3 },
|
||||
EffectOperation::MotionBlur {
|
||||
angle: -30.,
|
||||
distance: 25.5,
|
||||
gamma: true,
|
||||
},
|
||||
EffectOperation::RadialBlur {
|
||||
method: RadialBlurMethod::Zoom,
|
||||
amount: 40.,
|
||||
center: DVec2::new(10., -25.),
|
||||
gamma: false,
|
||||
},
|
||||
EffectOperation::default_for(EffectKind::RadialBlur),
|
||||
];
|
||||
|
||||
for operation in operations {
|
||||
@@ -1494,6 +1848,36 @@ mod tests {
|
||||
assert_eq!(default_row.0.attributes().iter_any().count(), 0, "a default operation stamps no parameters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blur_row_without_a_radius_mask_decodes_as_an_even_blur() {
|
||||
let blur = |radius_mask: Graphic| EffectOperation::Blur {
|
||||
radius_mask,
|
||||
radius: 5.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// An empty radius mask is elided from the row, which reads back as empty
|
||||
let row = Effect::new(&blur(Graphic::default()));
|
||||
assert!(row.0.attribute::<Graphic>("radius_mask").is_none());
|
||||
assert_eq!(row.operation(), blur(Graphic::default()));
|
||||
|
||||
// So the row decodes the same as one carrying an empty radius mask, or one that draws nothing, all blurring evenly with nothing drawn
|
||||
let mut carrying_empty = row.clone();
|
||||
carrying_empty.0.set_attribute("radius_mask", Graphic::default());
|
||||
let mut carrying_nothing = row.clone();
|
||||
carrying_nothing.0.set_attribute("radius_mask", Graphic::GraphicList(List::new()));
|
||||
for row in [row, carrying_empty, carrying_nothing] {
|
||||
let operation = row.operation();
|
||||
assert!(!operation.varies_blur_radius() && operation.drawn_paint().is_none(), "{operation:?}");
|
||||
}
|
||||
|
||||
// A radius mask drawing something varies the blur and draws as its paint
|
||||
let masked = blur(Graphic::from(Color::WHITE));
|
||||
assert!(Effect::new(&masked).0.attribute::<Graphic>("radius_mask").is_some());
|
||||
assert!(masked.varies_blur_radius() && masked.drawn_paint() == Some(&Graphic::from(Color::WHITE)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lengths_that_arent_finite_decode_as_zero() {
|
||||
let row = Effect::new(&EffectOperation::DropShadow {
|
||||
@@ -1542,41 +1926,6 @@ mod tests {
|
||||
assert_eq!(precise_falloff(0., 16., 16.), 1.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outline_paints_fit_the_whole_pixels_the_outline_reaches_outside() {
|
||||
let margin = |weight, align| {
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Graphic::from(Gradient::default()),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight,
|
||||
align,
|
||||
contour_gradient: false,
|
||||
};
|
||||
outline.drawn_paint_bounds([DVec2::ZERO, DVec2::splat(10.)], DVec2::ONE)[1].x - 10.
|
||||
};
|
||||
|
||||
assert_eq!(margin(8., StrokeAlign::Outside), 8.);
|
||||
// A centered outline of odd weight reaches into one more pixel, and one inside still fits a pixel past the content
|
||||
assert_eq!(margin(7., StrokeAlign::Center), 4.);
|
||||
assert_eq!(margin(40., StrokeAlign::Center), 20.);
|
||||
assert_eq!(margin(8., StrokeAlign::Inside), 1.);
|
||||
// Between whole weights, the margin is interpolated
|
||||
assert_eq!(margin(6.5, StrokeAlign::Center), 3.5);
|
||||
|
||||
// In a space a document pixel spans unevenly, the margin is measured along each axis
|
||||
let outline = EffectOperation::Outline {
|
||||
paint: Graphic::from(Gradient::default()),
|
||||
blend_mode: BlendMode::Normal,
|
||||
weight: 4.,
|
||||
align: StrokeAlign::Outside,
|
||||
contour_gradient: false,
|
||||
};
|
||||
assert_eq!(
|
||||
outline.drawn_paint_bounds([DVec2::ZERO, DVec2::splat(10.)], DVec2::new(2., 0.5)),
|
||||
[DVec2::new(-8., -2.), DVec2::new(18., 12.)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bevel_contours_continue_straight_past_their_ends() {
|
||||
// Inner and outer bevels map the range down from the top and up from the foot, while an emboss maps its whole slope
|
||||
@@ -1633,6 +1982,7 @@ mod tests {
|
||||
#[test]
|
||||
fn runs_join_effects_stamped_rounding_apart_and_those_changing_nothing() {
|
||||
let blur = |radius: f64| EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -1680,6 +2030,7 @@ mod tests {
|
||||
ColorBalance,
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
@@ -1750,6 +2101,56 @@ mod tests {
|
||||
|
||||
let effects = Effects::from_operations([mask]);
|
||||
assert_eq!((effects.reach(), effects.working_reach()), (0., 3. * mask_feather_sigma(4.)));
|
||||
// Unlike a convolution, which a render must read past the view for, the feather leaves edges past the view to what fits
|
||||
assert_eq!(effects.required_reach(), 0.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_convolution_paints_nothing_past_the_content_but_reads_past_it() {
|
||||
let sharpen = EffectOperation::convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", Some(1.), 0., false);
|
||||
assert_eq!(sharpen.painted_reach(), 0.);
|
||||
|
||||
// Weighing the coverage too, a kernel can spread it past the content
|
||||
let spread = EffectOperation::convolution_kernel("1 1 1", None, 0., true);
|
||||
assert_eq!(spread.painted_reach(), spread.reach());
|
||||
|
||||
// Its farthest copy a pixel away, a faint pixel's nearest visible color within the square around that, turned any way, and two pixels for rounding and copies between pixels
|
||||
let reach = 1. + std::f64::consts::SQRT_2 + 2.;
|
||||
assert_eq!((sharpen.working_reach(), sharpen.required_reach()), (reach, reach));
|
||||
|
||||
// The stylize and sharpen filters keep or shrink the coverage too, while a Minimum grows it
|
||||
let keeping = [
|
||||
EffectOperation::Emboss {
|
||||
angle: 135.,
|
||||
height: 3.,
|
||||
amount: 100.,
|
||||
},
|
||||
EffectOperation::FindEdges,
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
},
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 3.,
|
||||
threshold: 0.,
|
||||
edges_only: false,
|
||||
},
|
||||
EffectOperation::HighPass { radius: 3. },
|
||||
EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
},
|
||||
];
|
||||
assert!(keeping.iter().all(|operation| operation.painted_reach() == 0. && operation.working_reach() > 0.));
|
||||
let minimum = EffectOperation::MinimumMaximum {
|
||||
radius: 3.,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
};
|
||||
assert_eq!(minimum.painted_reach(), 4.);
|
||||
assert_eq!(Effects::from_operations([sharpen]).read_reach(DAffine2::IDENTITY), reach);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1778,14 +2179,56 @@ mod tests {
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::splat(2.), 0.5, DVec2::new(200., 100.));
|
||||
let drawn_at = DAffine2::from_translation(DVec2::new(5., 7.));
|
||||
let mask = Graphic::Graphic(Box::new(Item::new_from_element(Graphic::default()).with_attribute(ATTR_TRANSFORM, drawn_at)));
|
||||
let mut effects = masked_by(linked_to_content(mask, placement));
|
||||
let mut effects = masked_by(linked_to_content(mask.clone(), placement));
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert!(nested_placement(&mask_of(&effects)).abs_diff_eq(drawn_at, 1e-9));
|
||||
|
||||
// A gradient without its own placement stretches across the content wherever it lies, so it's left as it is
|
||||
let unplaced = Graphic::Gradient(Item::new_from_element(Gradient::default()));
|
||||
let mut effects = masked_by(unplaced.clone());
|
||||
// A blur's radius mask follows the content the same way
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: linked_to_content(mask, placement),
|
||||
radius: 4.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let mut effects = Effects::from_operations([blur]);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert_eq!(mask_of(&effects), unplaced);
|
||||
let Some(EffectOperation::Blur { radius_mask, .. }) = effects.operations().next() else {
|
||||
panic!("the row should stay a blur")
|
||||
};
|
||||
assert!(nested_placement(&radius_mask).abs_diff_eq(drawn_at, 1e-9));
|
||||
|
||||
// A gradient without a transform lies at the identity in the content's own space, so it follows the content like any other graphic
|
||||
let gradient = Graphic::Gradient(Item::new_from_element(Gradient::default()));
|
||||
let mut effects = masked_by(gradient);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
assert!(nested_placement(&mask_of(&effects)).abs_diff_eq(placement, 1e-9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn baking_the_content_placement_into_its_geometry_keeps_radial_blur_centers_in_place() {
|
||||
// Stamped on stretched and turned content, which `placement` then moves before going into the content's geometry
|
||||
let stamped = DAffine2::from_scale_angle_translation(DVec2::new(1.5, 0.5), 0.1, DVec2::ZERO);
|
||||
let placement = DAffine2::from_scale_angle_translation(DVec2::new(2., 3.), 0.5, DVec2::new(200., 100.));
|
||||
|
||||
for method in [RadialBlurMethod::Spin, RadialBlurMethod::Zoom] {
|
||||
let mut effects = Effects::from_operations([EffectOperation::RadialBlur {
|
||||
method,
|
||||
amount: 10.,
|
||||
center: DVec2::new(5., 7.),
|
||||
gamma: false,
|
||||
}]);
|
||||
effects.0.set_attribute(ATTR_TRANSFORM, 0, stamped);
|
||||
let pivot = |effects: &Effects, content_transform: DAffine2| {
|
||||
let Some(EffectOperation::RadialBlur { center, .. }) = effects.operations().next() else {
|
||||
panic!("the row should stay a radial blur")
|
||||
};
|
||||
effect_space(content_transform, effects.0.attribute_cloned_or_default(ATTR_TRANSFORM, 0)).transform_point2(center)
|
||||
};
|
||||
|
||||
let before = pivot(&effects, placement);
|
||||
effects.rebase_stamped_transforms(placement);
|
||||
let after = pivot(&effects, DAffine2::IDENTITY);
|
||||
assert!(after.abs_diff_eq(before, 1e-9), "{method:?}: {before} moved to {after}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
|
||||
|
||||
use crate::effects::{EffectOperation, Effects};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
|
||||
|
||||
/// The most rows or columns a kernel takes, beyond which those around its center are kept, so its 65,025 weights at most keep each render within reach.
|
||||
pub const MAX_KERNEL_SIDE: usize = 255;
|
||||
|
||||
/// The largest magnitude a weight divided by its divisor takes, so a kernel's sums stay finite.
|
||||
const MAX_WEIGHT: f64 = 1e6;
|
||||
|
||||
/// The least alpha at which a pixel's own color is read, below which (for its faint, poorly known color) it reads the color of the nearest pixel at least this covered.
|
||||
/// This is halfway between the sixteenth and fifteenth of 255 levels, so it divides 8-bit renders the same way everywhere.
|
||||
pub const VISIBLE_ALPHA: f32 = 15.5 / 255.;
|
||||
|
||||
/// What a filter reads beyond the content's visible colors, and how its result returns to the content's coverage.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum Surroundings {
|
||||
/// For PSD interop, a pixel too faint to be visible reads the nearest visible pixel's color (by [`fill_shifts`]) so colors continue past the edges, or with none within reach its own.
|
||||
/// The result keeps the content's coverage, unless the convolution weighs that too.
|
||||
Continued,
|
||||
/// The content is composited over an opaque gray of this level and filtered, then lifted back off the gray within its coverage, so its silhouette shows as an edge.
|
||||
Matted(f64),
|
||||
}
|
||||
|
||||
/// A weighted sum of copies of the content's straight colors, each shifted by a length in document pixels, divided by a divisor and raised by an offset, keeping the content's coverage unless it weighs that too.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Convolution {
|
||||
/// Each copy's shift from the pixel it adds into toward the pixel it reads, in document pixels, with its weight.
|
||||
pub taps: Vec<(DVec2, f64)>,
|
||||
/// What the weighted sum is divided by, which isn't zero.
|
||||
pub divisor: f64,
|
||||
/// How much the result's colors are raised, as a fraction of full brightness.
|
||||
pub offset: f64,
|
||||
/// What the sum reads beyond the content's visible colors, and how the result returns to the content's coverage.
|
||||
pub surroundings: Surroundings,
|
||||
/// Whether the coverage is weighed by the same copies, with none beyond the content and without the offset, then clamped, rather than kept.
|
||||
pub weighs_coverage: bool,
|
||||
}
|
||||
|
||||
impl Convolution {
|
||||
/// For PSD interop, the custom filter's kernel, given its weights row by row across `columns`, and kept to the [`MAX_KERNEL_SIDE`] rows and columns around its center.
|
||||
/// Each weight multiplies the pixel at its place in the kernel, whose center cell lies on the pixel being found: the middle row and column, or for an even count, the one after the middle.
|
||||
/// Weights that aren't finite count as zero, and a `scale` below 1 counts as 1.
|
||||
pub fn custom(weights: &[f64], columns: usize, scale: f64, offset: f64) -> Self {
|
||||
let scale = if scale.is_finite() { scale.max(1.) } else { 1. };
|
||||
|
||||
let taps = kept_weights(weights, columns)
|
||||
.filter_map(|(shift, weight)| {
|
||||
let weight = if weight.is_finite() { (weight / scale).clamp(-MAX_WEIGHT, MAX_WEIGHT) } else { 0. };
|
||||
(weight != 0.).then_some((shift, weight))
|
||||
})
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
taps,
|
||||
divisor: 1.,
|
||||
offset: if offset.is_finite() { offset / 255. } else { 0. },
|
||||
surroundings: Surroundings::Continued,
|
||||
weighs_coverage: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// For PSD interop, emboss's difference between two samples `height` pixels apart along the direction the light comes from at `angle` degrees, scaled by the `amount` percentage and lifted to middle gray.
|
||||
/// Each sample spreads over the pixels less than a pixel from it, weighted by how far short of a pixel they lie.
|
||||
pub fn emboss(angle: f64, height: f64, amount: f64) -> Self {
|
||||
// The direction without the rounding left by sines and cosines of right angles, so samples on whole pixels land exactly on them
|
||||
let angle = angle.to_radians();
|
||||
let without_rounding = |value: f64| if value.abs() < 1e-12 { 0. } else { value };
|
||||
let half = DVec2::new(without_rounding(angle.cos()), without_rounding(-angle.sin())) * height.max(0.) / 2.;
|
||||
let spread = |shift: DVec2| (1. - shift.length()).max(0.);
|
||||
|
||||
// Only the four pixels around each sample are less than a pixel from it, whatever the height. O(1).
|
||||
let mut shifts: Vec<DVec2> = [half, -half]
|
||||
.into_iter()
|
||||
.flat_map(|sample| [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| sample.floor() + corner))
|
||||
.collect();
|
||||
shifts.sort_by(|a, b| a.y.total_cmp(&b.y).then(a.x.total_cmp(&b.x)));
|
||||
shifts.dedup();
|
||||
let taps = shifts
|
||||
.into_iter()
|
||||
.map(|shift| (shift, (spread(shift - half) - spread(shift + half)) * amount / 100.))
|
||||
.filter(|(_, weight)| weight.abs() > 1e-12)
|
||||
.collect();
|
||||
|
||||
Self {
|
||||
taps,
|
||||
divisor: 1.,
|
||||
offset: 0.5,
|
||||
surroundings: Surroundings::Matted(0.5),
|
||||
weighs_coverage: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// How far from a pixel the farthest copy reads along either axis, in document pixels.
|
||||
pub fn reach(&self) -> f64 {
|
||||
self.taps.iter().map(|(shift, _)| shift.abs().max_element()).fold(0., f64::max)
|
||||
}
|
||||
|
||||
/// How far from a pixel its result reads in any direction, which a rotation can turn along an axis, in document pixels.
|
||||
/// That's the farthest copy, then for continued colors a faint pixel's nearest visible one within the square of [`Self::reach`], plus two pixels for rounding and copies between pixels.
|
||||
pub fn read_reach(&self) -> f64 {
|
||||
let farthest = self.taps.iter().map(|(shift, _)| shift.length()).fold(0., f64::max);
|
||||
let faint = match self.surroundings {
|
||||
Surroundings::Continued => std::f64::consts::SQRT_2 * self.reach().ceil(),
|
||||
Surroundings::Matted(_) => 0.,
|
||||
};
|
||||
farthest + faint + 2.
|
||||
}
|
||||
|
||||
/// Whether the result is the content as it is.
|
||||
pub fn is_identity(&self) -> bool {
|
||||
self.offset == 0. && matches!(self.taps.as_slice(), [(shift, weight)] if *shift == DVec2::ZERO && *weight == self.divisor)
|
||||
}
|
||||
}
|
||||
|
||||
/// The weights of a kernel written as text, row by row with each row padded by zeros to the widest, and how many columns it has.
|
||||
/// Each line is a row, with its numbers separated by spaces, commas, or both. Blank lines are skipped, and a number that can't be read counts as zero.
|
||||
pub fn parse_kernel(text: &str) -> (Vec<f64>, usize) {
|
||||
let rows: Vec<Vec<f64>> = text
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let tokens = line.split(|character: char| character.is_whitespace() || character == ',').filter(|token| !token.is_empty());
|
||||
tokens.map(|token| token.parse().unwrap_or(0.)).collect::<Vec<f64>>()
|
||||
})
|
||||
.filter(|row| !row.is_empty())
|
||||
.collect();
|
||||
|
||||
let columns = rows.iter().map(Vec::len).max().unwrap_or(0);
|
||||
let weights = rows.into_iter().flat_map(|row| {
|
||||
let padding = columns - row.len();
|
||||
row.into_iter().chain(std::iter::repeat_n(0., padding))
|
||||
});
|
||||
(weights.collect(), columns)
|
||||
}
|
||||
|
||||
/// The scale that keeps a kernel's brightness the same: the sum of the finite weights [`Convolution::custom`] keeps, but at least 1.
|
||||
pub fn automatic_scale(weights: &[f64], columns: usize) -> f64 {
|
||||
let sum: f64 = kept_weights(weights, columns).map(|(_, weight)| weight).filter(|weight| weight.is_finite()).sum();
|
||||
sum.clamp(1., f64::MAX)
|
||||
}
|
||||
|
||||
/// The weights given row by row across `columns`, kept to the [`MAX_KERNEL_SIDE`] rows and columns around the center, each with its shift from the center cell.
|
||||
fn kept_weights(weights: &[f64], columns: usize) -> impl Iterator<Item = (DVec2, f64)> + '_ {
|
||||
let full = [columns.max(1), weights.len().div_ceil(columns.max(1))];
|
||||
let kept = full.map(|count| count.min(MAX_KERNEL_SIDE));
|
||||
let start = [0, 1].map(|axis| full[axis] / 2 - kept[axis] / 2);
|
||||
let center = kept.map(|count| (count / 2) as f64);
|
||||
|
||||
(0..kept[0] * kept[1]).filter_map(move |index| {
|
||||
let (column, row) = (index % kept[0], index / kept[0]);
|
||||
let weight = *weights.get((row + start[1]) * full[0] + column + start[0])?;
|
||||
Some((DVec2::new(column as f64 - center[0], row as f64 - center[1]), weight))
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the operation is a pixel filter, which processes the pixels of the content and everything drawn with it so far.
|
||||
pub fn is_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(
|
||||
operation,
|
||||
EffectOperation::ConvolutionKernel { .. }
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. }
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether the operation is a pixel filter reading the pixels around each one, its details and edges, rather than only the pixel itself and a random field.
|
||||
pub fn reads_neighbors(operation: &EffectOperation) -> bool {
|
||||
is_filter(operation) && !is_random_field_filter(operation)
|
||||
}
|
||||
|
||||
/// Whether the operation is a pixel filter combining each pixel with a random field fixed to the content, which changes endless content as much as any other.
|
||||
pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. })
|
||||
}
|
||||
|
||||
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
|
||||
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
|
||||
pub fn has_filters(effects: &Effects) -> bool {
|
||||
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
|
||||
}
|
||||
|
||||
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
|
||||
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
|
||||
(DVec2::new(-1., -1.), [-1., -1.]),
|
||||
(DVec2::new(0., -1.), [0., -2.]),
|
||||
(DVec2::new(1., -1.), [1., -1.]),
|
||||
(DVec2::new(-1., 0.), [-2., 0.]),
|
||||
(DVec2::new(1., 0.), [2., 0.]),
|
||||
(DVec2::new(-1., 1.), [-1., 1.]),
|
||||
(DVec2::new(0., 1.), [0., 2.]),
|
||||
(DVec2::new(1., 1.), [1., 1.]),
|
||||
];
|
||||
|
||||
/// The blurred visibility around a pixel below which unsharp masking compares the pixel against its own color, and above which against the average of the visible colors, easing between the two.
|
||||
/// Below it, too little of the blur lands on visible pixels for 8-bit renders to know their average.
|
||||
pub const AVERAGE_VISIBILITY_RAMP: [f32; 2] = [8. / 255., 24. / 255.];
|
||||
|
||||
/// For PSD interop, the middle gray a high pass centers its differences on, as an 8-bit level.
|
||||
pub const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||
|
||||
/// How much of the visible colors' average a pixel is compared against, the rest being its own color, given how much of the blur around it lands on visible pixels.
|
||||
pub fn average_weight(visibility: f32) -> f32 {
|
||||
let [start, end] = AVERAGE_VISIBILITY_RAMP;
|
||||
((visibility - start) / (end - start)).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// Whether the filter sharpens or otherwise weighs the content's coverage, so a fill must fade its result rather than its input.
|
||||
pub fn sharpens_coverage(operation: &EffectOperation) -> bool {
|
||||
matches!(operation, EffectOperation::Sharpen { .. } | EffectOperation::ConvolutionKernel { apply_to_alpha: true, .. })
|
||||
}
|
||||
|
||||
/// For PSD interop, the shifts of the four nearest neighbors in document pixels, whose average Edges Only compares each pixel against.
|
||||
pub const SHARPEN_NEIGHBORS: [DVec2; 4] = [DVec2::new(0., -1.), DVec2::new(-1., 0.), DVec2::new(1., 0.), DVec2::new(0., 1.)];
|
||||
|
||||
/// For PSD interop, the Sobel gradient lengths (as Find Edges measures them, on values from 0 to 1) between which Edges Only ramps from no change to the whole of it.
|
||||
/// A step between flat areas has a quarter of that length at a sixteenth of full contrast, and its whole length at a quarter.
|
||||
pub const EDGE_GAIN_RAMP: [f32; 2] = [0.25, 1.];
|
||||
|
||||
/// For PSD interop, the share of its change that Edges Only makes in a channel whose Sobel gradient has the length `gradient`.
|
||||
pub fn edge_gain(gradient: f32) -> f32 {
|
||||
let [start, end] = EDGE_GAIN_RAMP;
|
||||
((gradient - start) / (end - start)).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// What unsharp masking or a high pass compares each pixel against.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum UnsharpBlur {
|
||||
/// A Gaussian blur with this standard deviation in document pixels.
|
||||
Gaussian(f64),
|
||||
/// For Edges Only, the average of the four nearest neighbors, [`SHARPEN_NEIGHBORS`], read between pixels where they don't land on one.
|
||||
/// Each channel is moved only part of the way toward it, by its [`edge_gain`], so it changes only along edges.
|
||||
EdgeNeighbors,
|
||||
}
|
||||
|
||||
/// What a Sharpen or High Pass compares each pixel against, with a Sharpen's amount and threshold as fractions, or `None` for any other operation.
|
||||
pub fn unsharp(operation: &EffectOperation) -> Option<(UnsharpBlur, Option<[f64; 2]>)> {
|
||||
match *operation {
|
||||
EffectOperation::Sharpen {
|
||||
amount,
|
||||
radius,
|
||||
threshold,
|
||||
edges_only,
|
||||
} => {
|
||||
let blur = if edges_only { UnsharpBlur::EdgeNeighbors } else { UnsharpBlur::Gaussian(radius) };
|
||||
Some((blur, Some([amount / 100., threshold.max(0.) / 255.])))
|
||||
}
|
||||
EffectOperation::HighPass { radius } => Some((UnsharpBlur::Gaussian(radius), None)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// For PSD interop, unsharp masking's change to a value lying `difference` above the blur around it: the difference scaled by `amount`, softened toward none by `threshold`, both fractions.
|
||||
pub fn unsharp_change(difference: f32, amount: f32, threshold: f32) -> f32 {
|
||||
difference.signum() * (amount * difference.abs() - threshold).max(0.)
|
||||
}
|
||||
|
||||
/// The whole radii a neighborhood minimum or maximum of `radius` document pixels mixes between, measured in pixels by `pixels_per_length`, with how far it lies toward the larger.
|
||||
pub fn neighborhood_radii(radius: f64, pixels_per_length: f64) -> ([u32; 2], f64) {
|
||||
let radius = radius.max(0.);
|
||||
let whole = |radius: f64| (radius * pixels_per_length).round() as u32;
|
||||
([whole(radius.floor()), whole(radius.ceil())], radius.fract())
|
||||
}
|
||||
|
||||
/// The whole-pixel shifts out to `reach` pixels along each axis, nearest first, which a faint pixel looks along for the visible pixel to read the color of.
|
||||
/// For PSD interop, ties go below before right, then left, then above. O(reach² log reach).
|
||||
pub fn fill_shifts(reach: i32) -> Vec<[i32; 2]> {
|
||||
let mut shifts: Vec<[i32; 2]> = (-reach..=reach).flat_map(|y| (-reach..=reach).map(move |x| [x, y])).collect();
|
||||
shifts.sort_by_key(|&[x, y]| (x * x + y * y, -y, -x));
|
||||
shifts
|
||||
}
|
||||
|
||||
/// How the random offsets Add Noise gives the colors are spread.
|
||||
#[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 NoiseDistribution {
|
||||
/// Every offset up to the amount is equally likely.
|
||||
#[default]
|
||||
Uniform,
|
||||
/// Offsets cluster around none, with the amount as their standard deviation, so most are subtle and a few reach well past it.
|
||||
Gaussian,
|
||||
}
|
||||
|
||||
/// For PSD interop, how many standard deviations Gaussian noise reaches, where its tails are cut off.
|
||||
pub const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||
|
||||
/// The random fields a seed gives, each hashed apart so the fields of one seed are unrelated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RandomField {
|
||||
/// Add Noise's offset for each color, or for Gaussian noise its first uniform value.
|
||||
NoiseOffsets,
|
||||
/// Gaussian noise's second uniform value for each color, its angle.
|
||||
NoiseAngles,
|
||||
/// Dissolve's two thresholds, for the opacity and for the coverage.
|
||||
Dissolve,
|
||||
}
|
||||
|
||||
impl RandomField {
|
||||
/// The value hashed with each cell for this field of the `seed`.
|
||||
pub fn seed(self, seed: i64) -> u32 {
|
||||
(seed as u32).wrapping_mul(4).wrapping_add(self as u32)
|
||||
}
|
||||
}
|
||||
|
||||
/// The largest offset Add Noise of `amount` (a fraction) gives a color, as a fraction of full brightness, past which every color would be pushed to black or white anyway.
|
||||
pub fn noise_extent(amount: f64, distribution: NoiseDistribution) -> f64 {
|
||||
let deviations = match distribution {
|
||||
NoiseDistribution::Uniform => 1.,
|
||||
NoiseDistribution::Gaussian => GAUSSIAN_NOISE_LIMIT as f64,
|
||||
};
|
||||
(amount.max(0.) * deviations).min(1.)
|
||||
}
|
||||
|
||||
/// The most samples a pixel takes of a random field along each of its axes, which it takes when it spans that many cells or more.
|
||||
pub const MAX_FIELD_SAMPLES_PER_AXIS: u32 = 4;
|
||||
|
||||
/// Where each pixel of a render reads a random field of one value per cell, the unit squares of the effect space, which fixes it to the content.
|
||||
/// A pixel no larger than a cell reads the one under its center. A larger one averages samples spread across it, as a downsample of the field at full size would.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct FieldSampling {
|
||||
/// The cell at the render's origin, kept apart from the rest of the way to it so 32-bit math on a GPU stays precise far from the effect space's origin.
|
||||
pub origin_cell: IVec2,
|
||||
/// The rest of the way from the origin's cell to the origin.
|
||||
pub origin_fraction: DVec2,
|
||||
/// A step of one pixel along each axis, in cells.
|
||||
pub pixel_axes: DMat2,
|
||||
/// How many samples are taken along each of a pixel's axes.
|
||||
pub counts: UVec2,
|
||||
/// How far apart the outermost samples are along each axis, in pixels, so each lands near the middle of a cell of its own.
|
||||
pub spreads: DVec2,
|
||||
/// For pixels spanning more cells than they sample, how much less an average of them all would deviate from the field's mean than the samples' average does.
|
||||
pub deviation_scale: f64,
|
||||
}
|
||||
|
||||
impl FieldSampling {
|
||||
/// The sampling of a render with its pixels placed in the effect space by `pixels_to_effect`.
|
||||
pub fn new(pixels_to_effect: DAffine2) -> Self {
|
||||
let origin = pixels_to_effect.translation;
|
||||
let origin_cell = origin.floor();
|
||||
let pixel_axes = pixels_to_effect.matrix2;
|
||||
|
||||
// A pixel spanning a cell give or take rounding takes one sample
|
||||
let spans = DVec2::new(pixel_axes.x_axis.length(), pixel_axes.y_axis.length());
|
||||
let counts = spans.map(|span| (span - 1e-3).ceil().clamp(1., MAX_FIELD_SAMPLES_PER_AXIS as f64));
|
||||
let spread = |span: f64, count: f64| if count > 1. { (span - 1.) / span * count / (count - 1.) } else { 0. };
|
||||
|
||||
Self {
|
||||
origin_cell: origin_cell.as_ivec2(),
|
||||
origin_fraction: origin - origin_cell,
|
||||
pixel_axes,
|
||||
counts: counts.as_uvec2(),
|
||||
spreads: DVec2::new(spread(spans.x, counts.x), spread(spans.y, counts.y)),
|
||||
deviation_scale: (counts / spans).min(DVec2::ONE).element_product().sqrt(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cell under the point `offset` pixels from the middle of the pixel at `pixel` (its column and row).
|
||||
fn cell_at(&self, pixel: [usize; 2], offset: DVec2) -> IVec2 {
|
||||
let position = DVec2::new(pixel[0] as f64, pixel[1] as f64) + 0.5 + offset;
|
||||
self.origin_cell.wrapping_add((self.origin_fraction + self.pixel_axes * position).floor().as_ivec2())
|
||||
}
|
||||
|
||||
/// The cell under the middle of the pixel at `pixel`.
|
||||
pub fn center_cell(&self, pixel: [usize; 2]) -> IVec2 {
|
||||
self.cell_at(pixel, DVec2::ZERO)
|
||||
}
|
||||
|
||||
/// The cells the pixel at `pixel` samples, row by row.
|
||||
pub fn sample_cells(&self, pixel: [usize; 2]) -> impl Iterator<Item = IVec2> + '_ {
|
||||
let place = |index: u32, count: u32, spread: f64| ((index as f64 + 0.5) / count as f64 - 0.5) * spread;
|
||||
(0..self.counts.y)
|
||||
.flat_map(move |row| (0..self.counts.x).map(move |column| self.cell_at(pixel, DVec2::new(place(column, self.counts.x, self.spreads.x), place(row, self.counts.y, self.spreads.y)))))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn kernels_parse_a_row_from_each_line() {
|
||||
// Spaces, commas, and tabs separate the numbers, blank lines are skipped, and a number that can't be read counts as zero
|
||||
let (weights, columns) = parse_kernel("1, 2 ,3\r\n\n 4\t-5e-1 x \n\n 6,,7\n");
|
||||
assert_eq!(columns, 3);
|
||||
assert_eq!(weights, vec![1., 2., 3., 4., -0.5, 0., 6., 7., 0.]);
|
||||
|
||||
// Rows shorter than the widest end in zeros
|
||||
assert_eq!(parse_kernel("1\n2 3 4"), (vec![1., 0., 0., 2., 3., 4.], 3));
|
||||
assert_eq!(parse_kernel(" \n\t\n"), (Vec::new(), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn weights_read_row_by_row_around_the_center() {
|
||||
// The weight right of the center reads the pixel to the right, divided by the scale
|
||||
let convolution = Convolution::custom(&[0., 0., 0., 0., 0., 2., 0., 0., 0.], 3, 4., 128.);
|
||||
assert_eq!(convolution.taps, vec![(DVec2::new(1., 0.), 0.5)]);
|
||||
assert!((convolution.offset - 128. / 255.).abs() < 1e-12);
|
||||
assert_eq!(convolution.reach(), 1.);
|
||||
|
||||
assert!(Convolution::custom(&[3.], 1, 3., 0.).is_identity());
|
||||
assert!(!Convolution::custom(&[3.], 1, 1., 0.).is_identity());
|
||||
// A scale below 1 divides by 1, and a weight past the largest stays finite
|
||||
assert_eq!(Convolution::custom(&[2.], 1, 0., 0.).taps, vec![(DVec2::ZERO, 2.)]);
|
||||
assert_eq!(Convolution::custom(&[2.], 1, 0.5, 0.).taps, vec![(DVec2::ZERO, 2.)]);
|
||||
assert_eq!(Convolution::custom(&[1e300], 1, 1., 0.).taps, vec![(DVec2::ZERO, MAX_WEIGHT)]);
|
||||
// Weights that aren't finite count as zero
|
||||
assert!(Convolution::custom(&[f64::INFINITY, f64::NAN, 0., 0., 1., 0.], 3, 1., 0.).is_identity());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernels_center_on_their_middle_row_and_column() {
|
||||
let shift = |x: f64, y: f64| DVec2::new(x, y);
|
||||
let shifts = |convolution: Convolution| convolution.taps.into_iter().map(|(shift, _)| shift).collect::<Vec<_>>();
|
||||
|
||||
// A row reads across and a column reads down, each around its middle
|
||||
assert_eq!(shifts(Convolution::custom(&[1., 2., 3.], 3, 1., 0.)), vec![shift(-1., 0.), shift(0., 0.), shift(1., 0.)]);
|
||||
assert_eq!(shifts(Convolution::custom(&[1., 2., 3.], 1, 1., 0.)), vec![shift(0., -1.), shift(0., 0.), shift(0., 1.)]);
|
||||
|
||||
// An even count centers on the cell after its middle, so a 2×2 kernel reaches only up and left
|
||||
let square = Convolution::custom(&[1., 2., 3., 4.], 2, 1., 0.);
|
||||
assert_eq!(square.taps, vec![(shift(-1., -1.), 1.), (shift(0., -1.), 2.), (shift(-1., 0.), 3.), (shift(0., 0.), 4.)]);
|
||||
let wide = Convolution::custom(&[1.; 8], 4, 1., 0.);
|
||||
assert_eq!((wide.taps[0].0, wide.taps[7].0), (shift(-2., -1.), shift(1., 0.)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernels_past_the_largest_keep_the_rows_and_columns_around_their_center() {
|
||||
// A kernel larger than one pass of the GPU's taps keeps every weight
|
||||
assert_eq!(Convolution::custom(&[1.; 121], 11, 1., 0.).taps.len(), 121);
|
||||
|
||||
let side = MAX_KERNEL_SIDE + 2;
|
||||
let center = side / 2 * side + side / 2;
|
||||
let mut wide = vec![0.; side * side];
|
||||
wide[center] = 3.;
|
||||
wide[center + 1] = 2.;
|
||||
wide[0] = 1.;
|
||||
assert_eq!(Convolution::custom(&wide, side, 1., 0.).taps, vec![(DVec2::ZERO, 3.), (DVec2::X, 2.)]);
|
||||
assert_eq!(Convolution::custom(&vec![1.; side * side], side, 1., 0.).reach(), (MAX_KERNEL_SIDE / 2) as f64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_automatic_scale_is_the_sum_of_the_kept_weights_but_at_least_1() {
|
||||
assert_eq!(automatic_scale(&[1.; 9], 3), 9.);
|
||||
assert_eq!(automatic_scale(&[2., f64::NAN, 3., f64::INFINITY], 4), 5.);
|
||||
// A sum past the largest finite number stays finite, rather than counting as 1
|
||||
assert_eq!(automatic_scale(&[f64::MAX, f64::MAX], 2), f64::MAX);
|
||||
|
||||
// Kernels summing below 1, like those finding edges, divide by 1
|
||||
assert_eq!(automatic_scale(&[0., -1., 0., -1., 5., -1., 0., -1., 0.], 3), 1.);
|
||||
assert_eq!(automatic_scale(&[-1., 0., 1.], 3), 1.);
|
||||
assert_eq!(automatic_scale(&[0.25, 0.25], 2), 1.);
|
||||
assert_eq!(automatic_scale(&[], 0), 1.);
|
||||
|
||||
let side = MAX_KERNEL_SIDE + 2;
|
||||
assert_eq!(automatic_scale(&vec![1.; side * side], side), (MAX_KERNEL_SIDE * MAX_KERNEL_SIDE) as f64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emboss_differences_samples_spread_around_the_light_direction() {
|
||||
// Light from the right at a height of 2 samples a pixel to each side, each exactly on one pixel
|
||||
let emboss = Convolution::emboss(0., 2., 100.);
|
||||
assert_eq!(emboss.taps, vec![(DVec2::new(-1., 0.), -1.), (DVec2::new(1., 0.), 1.)]);
|
||||
assert_eq!(emboss.offset, 0.5);
|
||||
|
||||
// Halfway between pixels, each sample spreads over the two beside it
|
||||
let between = Convolution::emboss(90., 1., 200.);
|
||||
let weight = |shift: DVec2| between.taps.iter().find(|(tap, _)| *tap == shift).map_or(0., |(_, weight)| *weight);
|
||||
assert!((weight(DVec2::new(0., -1.)) - 1.).abs() < 1e-12);
|
||||
assert!((weight(DVec2::ZERO)).abs() < 1e-12);
|
||||
assert!((weight(DVec2::new(0., 1.)) + 1.).abs() < 1e-12);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faint_pixels_look_nearest_first_and_below_before_right() {
|
||||
let shifts = fill_shifts(1);
|
||||
assert_eq!(shifts.len(), 9);
|
||||
assert_eq!(&shifts[..5], &[[0, 0], [0, 1], [1, 0], [-1, 0], [0, -1]]);
|
||||
assert_eq!(shifts[5], [1, 1]);
|
||||
}
|
||||
}
|
||||
@@ -630,10 +630,11 @@ impl Graphic {
|
||||
// Effects (like a mask, which shapes a clip) are more than an outline can express
|
||||
match self {
|
||||
Graphic::Vector(item) => {
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none() && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
|
||||
}
|
||||
Graphic::VectorList(list) => (0..list.len()).all(|index| {
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none()
|
||||
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
|
||||
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
|
||||
}),
|
||||
_ => false,
|
||||
@@ -742,6 +743,22 @@ impl Graphic {
|
||||
Graphic::StrokeList(list) => list.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this graphic draws nothing at all, such as an empty list or an image without pixels.
|
||||
pub fn draws_nothing(&self) -> bool {
|
||||
use raster_types::Storage;
|
||||
|
||||
let no_pixels = |raster: &Raster<CPU>| raster.width == 0 || raster.height == 0;
|
||||
match self {
|
||||
Graphic::Graphic(item) => item.element().draws_nothing(),
|
||||
Graphic::GraphicList(list) => list.iter_element_values().all(Graphic::draws_nothing),
|
||||
Graphic::RasterCPU(item) => no_pixels(item.element()),
|
||||
Graphic::RasterCPUList(list) => list.iter_element_values().all(no_pixels),
|
||||
Graphic::RasterGPU(item) => item.element().is_empty(),
|
||||
Graphic::RasterGPUList(list) => list.iter_element_values().all(Raster::<GPU>::is_empty),
|
||||
graphic => graphic.is_empty(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a vector object's own opacity and paint let a clipper reduce to an SVG `<clipPath>` instead of a `<mask>`.
|
||||
|
||||
@@ -3,10 +3,12 @@ pub mod appearance;
|
||||
pub mod artboard;
|
||||
pub mod effect_layers;
|
||||
pub mod effects;
|
||||
pub mod filters;
|
||||
pub mod generator;
|
||||
pub mod graphic;
|
||||
pub mod masks;
|
||||
pub(crate) mod parameters;
|
||||
pub mod resampling;
|
||||
|
||||
// Re-export all transitive dependencies so downstream crates only need to depend on graphic-types
|
||||
pub use core_types;
|
||||
@@ -18,12 +20,14 @@ pub use adjustment::Adjustment;
|
||||
pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage};
|
||||
pub use artboard::Artboard;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, fitted_paint, linked_to_content, paint_with_envelope_effects, stamp_effect,
|
||||
stamped_transform,
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
};
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector};
|
||||
pub use masks::MaskMode;
|
||||
pub use resampling::RadialBlurMethod;
|
||||
|
||||
pub mod migrations {
|
||||
use crate::Vector;
|
||||
|
||||
@@ -60,3 +60,63 @@ pub fn feather_parts(distance: f64) -> (f64, f64) {
|
||||
let distance = distance.max(0.);
|
||||
(distance / 2., distance / 6.)
|
||||
}
|
||||
|
||||
/// The most levels a masked radius blur interpolates between down to a document pixel, enough to halve from a radius of 1000 document pixels to one.
|
||||
pub const MASKED_RADIUS_BLUR_MAX_LEVELS: usize = 12;
|
||||
|
||||
/// The most levels finer than a document pixel that a masked radius blur adds when zoomed in, enough to reach an output pixel at a zoom of 25600%.
|
||||
pub const MASKED_RADIUS_BLUR_MAX_FINER_LEVELS: usize = 8;
|
||||
|
||||
/// The standard deviations, in document pixels, of the Gaussians a masked radius blur of `radius` interpolates between: none, then the radius halved while it spans a document pixel, or an output pixel at more `pixels_per_length` than one.
|
||||
/// Levels a factor of 2 apart interpolate into what reads as one blur, and under a pixel a blur hardly differs from none.
|
||||
pub fn masked_radius_blur_levels(radius: f64, pixels_per_length: f64) -> Vec<f64> {
|
||||
let finest = 1. / pixels_per_length.max(1.);
|
||||
|
||||
let (mut blurred, mut finer) = (vec![radius.max(0.)], 0);
|
||||
loop {
|
||||
let next = blurred[0] / 2.;
|
||||
let coarse = next >= 1. && blurred.len() + 1 < MASKED_RADIUS_BLUR_MAX_LEVELS;
|
||||
let fine = (finest..1.).contains(&next) && finer < MASKED_RADIUS_BLUR_MAX_FINER_LEVELS;
|
||||
if !(coarse || fine) {
|
||||
break;
|
||||
}
|
||||
|
||||
finer += fine as usize;
|
||||
blurred.insert(0, next);
|
||||
}
|
||||
std::iter::once(0.).chain(blurred).collect()
|
||||
}
|
||||
|
||||
/// The 8-bit code of a masked radius blur map's luminance at a pixel, given as premultiplied gamma-encoded channels, which picks the pixel's interpolation between blurs.
|
||||
pub fn masked_radius_blur_code(channels: [f32; 4]) -> u8 {
|
||||
(mask_coverage(channels, MaskMode::Luminance) * 255.).round() as u8
|
||||
}
|
||||
|
||||
/// For a masked radius blur map's luminance as an 8-bit `code`, the level below it among the `levels` (from [`masked_radius_blur_levels`]) and how many of 255 parts of the interpolation the level above takes, the rest going to the level below.
|
||||
///
|
||||
/// Each pixel of a Gaussian masked radius blur is the sum of its levels (its content blurred by Gaussians of their radii) weighed by their parts, on premultiplied gamma-encoded channels.
|
||||
/// The map value's fraction of the full radius falls between two levels. The parts are linear in the radius from no blur to the first level, and linear in its logarithm between blurred levels.
|
||||
/// On opaque hard edges, between Gaussian levels a factor of 2 apart, that strays at most about 20 of 255 sRGB levels from a true Gaussian of the map value's radius, against about 32 for the sum in linear light.
|
||||
/// Summing in gamma, even when the levels blur in linear light, is deliberate: a power space near 2.7 strays only about 12, but SVG would need a 256-entry table per level for it, where gamma costs nothing.
|
||||
pub fn masked_radius_blur_interpolation(code: u8, levels: &[f64]) -> (usize, u32) {
|
||||
let Some(&radius) = levels.last().filter(|_| levels.len() >= 2) else { return (0, 0) };
|
||||
let length = code as f64 / 255. * radius;
|
||||
let below = (0..levels.len() - 1).rev().find(|&level| length >= levels[level]).unwrap_or(0);
|
||||
let (low, high) = (levels[below], levels[below + 1]);
|
||||
|
||||
let share = match low > 0. {
|
||||
true => (length / low).log2() / (high / low).log2(),
|
||||
false => length / high,
|
||||
};
|
||||
(below, (share * 255.).round().clamp(0., 255.) as u32)
|
||||
}
|
||||
|
||||
/// How many of 255 parts of a masked radius blur's interpolation the `level` takes for the map luminance `code`, as [`masked_radius_blur_interpolation`] gives them.
|
||||
pub fn masked_radius_blur_weight(level: usize, code: u8, levels: &[f64]) -> u32 {
|
||||
let (below, above_parts) = masked_radius_blur_interpolation(code, levels);
|
||||
match level {
|
||||
_ if level == below => 255 - above_parts,
|
||||
_ if level == below + 1 => above_parts,
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! Effects that resample the content from elsewhere than nearby, like blurs along lines and arcs, and the frame of reference that those relative to the content's extent take.
|
||||
//! The frame is the content's bounds in its own space, carried through its transform, so a frame-relative effect moves rigidly with the content.
|
||||
|
||||
use crate::effects::{EffectOperation, Effects, effect_space, spans_along_axes};
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
|
||||
/// How a radial blur smears the content about its center.
|
||||
#[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 RadialBlurMethod {
|
||||
/// Smears along circles around the center, as if the content were spinning.
|
||||
#[default]
|
||||
Spin,
|
||||
/// Smears along lines through the center, as if the content were rushing closer.
|
||||
Zoom,
|
||||
}
|
||||
|
||||
/// For PSD interop, the motion blur angle and distance matching PSD's whole-degree `angle` and `distance`, with the line rounded to whole pixels as PSD rounds it.
|
||||
pub fn motion_blur_from_psd(angle: i32, distance: f64) -> (f64, f64) {
|
||||
let angle = (angle as f64).to_radians();
|
||||
let end = DVec2::new((distance * angle.cos() + 0.5).trunc(), (distance * angle.sin() + 0.5).trunc());
|
||||
(end.y.atan2(end.x).to_degrees(), end.length())
|
||||
}
|
||||
|
||||
/// For PSD interop, the degrees a spin blur's arcs span for each unit of its amount.
|
||||
pub const SPIN_DEGREES_PER_AMOUNT: f64 = 1.;
|
||||
|
||||
/// For PSD interop, the share of each point's distance from the center that a zoom blur's lines span (half toward the center and half away), for each unit of its amount.
|
||||
pub const ZOOM_FRACTION_PER_AMOUNT: f64 = 0.005;
|
||||
|
||||
/// How many samples a radial blur averages for each pixel along its arcs or lines, enough to follow PSD's integral of them to within a level.
|
||||
pub const RADIAL_SAMPLES_PER_PIXEL: f64 = 2.;
|
||||
|
||||
/// The most samples a radial blur averages at one pixel, enough for all but the longest arcs.
|
||||
pub const MAX_RADIAL_SAMPLES: u32 = 512;
|
||||
|
||||
/// The largest amount a radial blur takes: a spin around the whole circle, or a zoom from a tenth of each point's distance from the center to almost twice it.
|
||||
pub const MAX_RADIAL_BLUR_AMOUNT: f64 = 360.;
|
||||
|
||||
/// The placement of the unit square on `bounds` in a space that `transform` maps into another, which is the frame of content with those bounds in its own space.
|
||||
pub fn frame_of_bounds([min, max]: [DVec2; 2], transform: DAffine2) -> DAffine2 {
|
||||
transform * DAffine2::from_translation(min) * DAffine2::from_scale(max - min)
|
||||
}
|
||||
|
||||
/// The frame of reference of an effect relative to the content's extent: a parallelogram placed in the pixels the effect runs on.
|
||||
/// Positions within it are measured in the effect space's units from its center along its sides, its local space.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct EffectFrame {
|
||||
/// Places the frame's unit square in the pixels.
|
||||
pub to_pixels: DAffine2,
|
||||
/// How long the frame's sides are, in the effect space.
|
||||
pub size: DVec2,
|
||||
}
|
||||
|
||||
impl EffectFrame {
|
||||
/// The frame with the unit square that `placement` puts in the effect space, in the pixels that `effect_to_pixels` maps that space into. `None` where it collapses.
|
||||
pub fn new(placement: DAffine2, effect_to_pixels: DAffine2) -> Option<Self> {
|
||||
let size = DVec2::new(placement.matrix2.x_axis.length(), placement.matrix2.y_axis.length());
|
||||
let to_pixels = effect_to_pixels * placement;
|
||||
(placement.is_finite() && to_pixels.matrix2.determinant().is_normal()).then_some(Self { to_pixels, size })
|
||||
}
|
||||
|
||||
/// The bounding box of the frame in the pixels.
|
||||
pub fn pixel_bounds(&self) -> [DVec2; 2] {
|
||||
let corners = [DVec2::ZERO, DVec2::X, DVec2::Y, DVec2::ONE].map(|corner| self.to_pixels.transform_point2(corner));
|
||||
[corners.into_iter().reduce(DVec2::min).unwrap_or_default(), corners.into_iter().reduce(DVec2::max).unwrap_or_default()]
|
||||
}
|
||||
|
||||
/// This frame in other pixels, which `transform` maps these pixels into.
|
||||
pub fn placed(&self, transform: DAffine2) -> Self {
|
||||
Self {
|
||||
to_pixels: transform * self.to_pixels,
|
||||
size: self.size,
|
||||
}
|
||||
}
|
||||
|
||||
/// The map from the frame's local space into the pixels.
|
||||
pub fn local_to_pixels(&self) -> DAffine2 {
|
||||
self.to_pixels * DAffine2::from_translation(DVec2::splat(0.5)) * DAffine2::from_scale(self.size.recip())
|
||||
}
|
||||
|
||||
/// The map from the pixels into the frame's local space.
|
||||
pub fn pixels_to_local(&self) -> DAffine2 {
|
||||
self.local_to_pixels().inverse()
|
||||
}
|
||||
|
||||
/// Whether a point in the local space lies within the frame.
|
||||
pub fn contains(&self, local: DVec2) -> bool {
|
||||
let half = self.size / 2.;
|
||||
local.x.abs() <= half.x && local.y.abs() <= half.y
|
||||
}
|
||||
}
|
||||
|
||||
/// A radial blur's arcs or lines, in its effect space, which later transforms carry along with the content.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RadialBlur {
|
||||
pub method: RadialBlurMethod,
|
||||
/// The point the blur spins around or zooms toward, in the effect space, measured from its origin (the content's).
|
||||
pub center: DVec2,
|
||||
/// The angle a spin's arcs span, in radians, or the share of each point's distance from the center that a zoom's lines span, each centered on the point.
|
||||
pub extent: f64,
|
||||
}
|
||||
|
||||
impl RadialBlur {
|
||||
/// The blur of `amount` (up to [`MAX_RADIAL_BLUR_AMOUNT`]) about the `center`, a point in the effect space.
|
||||
pub fn new(method: RadialBlurMethod, amount: f64, center: DVec2) -> Self {
|
||||
let amount = amount.clamp(0., MAX_RADIAL_BLUR_AMOUNT);
|
||||
let extent = match method {
|
||||
RadialBlurMethod::Spin => (amount * SPIN_DEGREES_PER_AMOUNT).to_radians(),
|
||||
RadialBlurMethod::Zoom => amount * ZOOM_FRACTION_PER_AMOUNT,
|
||||
};
|
||||
|
||||
Self { method, center, extent }
|
||||
}
|
||||
|
||||
/// How far past the content the blur can paint, given the `farthest` the content reaches from its center: a spin's arcs carry that point along a chord, and a zoom's lines carry it outward.
|
||||
pub fn reach(&self, farthest: f64) -> f64 {
|
||||
match self.method {
|
||||
RadialBlurMethod::Spin => 2. * farthest * (self.extent.min(std::f64::consts::TAU) / 4.).sin(),
|
||||
RadialBlurMethod::Zoom => farthest * (self.extent / 2.) / (1. - self.extent / 2.),
|
||||
}
|
||||
}
|
||||
|
||||
/// How many samples the `point` (in the effect space) averages, spread along its arc or line by [`RADIAL_SAMPLES_PER_PIXEL`], given how many pixels each unit of the effect space spans.
|
||||
pub fn sample_count(&self, point: DVec2, pixels_per_length: f64) -> u32 {
|
||||
let length = (point - self.center).length() * self.extent * pixels_per_length * RADIAL_SAMPLES_PER_PIXEL;
|
||||
if !length.is_finite() {
|
||||
return 1;
|
||||
}
|
||||
((length.ceil() + 1.) as u32).clamp(1, MAX_RADIAL_SAMPLES)
|
||||
}
|
||||
|
||||
/// Sample `index` of the `count` the `point` averages, each in the middle of an equal share of its arc or line.
|
||||
pub fn sample(&self, point: DVec2, index: u32, count: u32) -> DVec2 {
|
||||
self.point_along(point, (index as f64 + 0.5) / count.max(1) as f64 - 0.5)
|
||||
}
|
||||
|
||||
/// The point a share `along` the arc or line through the `point`, which centers on it, from -0.5 at one end to 0.5 at the other.
|
||||
pub fn point_along(&self, point: DVec2, along: f64) -> DVec2 {
|
||||
let offset = point - self.center;
|
||||
|
||||
match self.method {
|
||||
RadialBlurMethod::Spin => self.center + DVec2::from_angle(self.extent * along).rotate(offset),
|
||||
RadialBlurMethod::Zoom => self.center + offset * (1. - self.extent * along),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of its input, in pixels, that the blur reads to produce `output` (in pixels), given the map from the effect space into the pixels and how many pixels each unit of that space spans.
|
||||
pub fn source(&self, output: [DVec2; 2], effect_to_pixels: DAffine2, pixels_per_length: f64) -> [DVec2; 2] {
|
||||
let pixels_to_effect = effect_to_pixels.inverse();
|
||||
|
||||
// A spin turns the region rigidly and a zoom scales it, so its boundary's samples bound all of them
|
||||
let read = traced_bounds(output, |point, include| {
|
||||
let point = pixels_to_effect.transform_point2(point);
|
||||
let steps = self.sample_count(point, pixels_per_length).clamp(2, 33) - 1;
|
||||
for step in 0..=steps {
|
||||
include(effect_to_pixels.transform_point2(self.point_along(point, step as f64 / steps as f64 - 0.5)));
|
||||
}
|
||||
});
|
||||
|
||||
union(output, read)
|
||||
}
|
||||
}
|
||||
|
||||
/// How many samples per side of a region its boundary is traced with to find what an effect reading from beyond its reach reads.
|
||||
const TRACED_SAMPLES_PER_SIDE: usize = 64;
|
||||
|
||||
/// The bounding box, in pixels, of the points that `sources` gives for each of many points along the boundary of `region` (in pixels), padded to cover what the samples between them miss.
|
||||
fn traced_bounds(region: [DVec2; 2], sources: impl Fn(DVec2, &mut dyn FnMut(DVec2))) -> [DVec2; 2] {
|
||||
let [min, max] = region;
|
||||
let corners = [min, DVec2::new(max.x, min.y), max, DVec2::new(min.x, max.y)];
|
||||
|
||||
let mut bounds = [DVec2::INFINITY, DVec2::NEG_INFINITY];
|
||||
let mut include = |point: DVec2| {
|
||||
if point.is_finite() {
|
||||
bounds = [bounds[0].min(point), bounds[1].max(point)];
|
||||
}
|
||||
};
|
||||
for side in 0..4 {
|
||||
let (start, end) = (corners[side], corners[(side + 1) % 4]);
|
||||
for step in 0..TRACED_SAMPLES_PER_SIDE {
|
||||
sources(start.lerp(end, step as f64 / TRACED_SAMPLES_PER_SIDE as f64), &mut include);
|
||||
}
|
||||
}
|
||||
if !(bounds[0].x <= bounds[1].x && bounds[0].y <= bounds[1].y) {
|
||||
return region;
|
||||
}
|
||||
|
||||
// Between neighboring samples, the traced curve strays little from the straight line through them
|
||||
let margin = 2. + 0.02 * (bounds[1] - bounds[0]).max_element();
|
||||
[bounds[0] - margin, bounds[1] + margin]
|
||||
}
|
||||
|
||||
fn union([a_min, a_max]: [DVec2; 2], [b_min, b_max]: [DVec2; 2]) -> [DVec2; 2] {
|
||||
[a_min.min(b_min), a_max.max(b_max)]
|
||||
}
|
||||
|
||||
impl EffectOperation {
|
||||
/// How far past the content this operation can paint, in its effect space, given the `corners` of the content's bounds there and how far the effects before it have `painted` past them.
|
||||
/// Most reach a fixed distance, but a radial blur reaches farther from content lying farther from its center.
|
||||
fn reach_around(&self, corners: [DVec2; 4], painted: f64) -> f64 {
|
||||
match self {
|
||||
// Nothing painted lies farther from the center than the bounds' farthest corner and what's painted past them
|
||||
Self::RadialBlur { method, amount, center, .. } => {
|
||||
let farthest = corners.into_iter().map(|corner| corner.distance(*center)).fold(0., f64::max) + painted;
|
||||
RadialBlur::new(*method, *amount, *center).reach(farthest)
|
||||
}
|
||||
_ => self.painted_reach(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this operation takes the content's frame, which effects relative to its extent measure from, unless it changes nothing.
|
||||
pub fn takes_frame(&self) -> bool {
|
||||
match self {
|
||||
Self::MotionBlur { .. }
|
||||
| Self::RadialBlur { .. }
|
||||
| Self::DropShadow { .. }
|
||||
| Self::InnerShadow { .. }
|
||||
| Self::OuterGlow { .. }
|
||||
| Self::InnerGlow { .. }
|
||||
| Self::Satin { .. }
|
||||
| Self::Outline { .. }
|
||||
| Self::BevelAndEmboss { .. }
|
||||
| Self::PaintOverlay { .. }
|
||||
| Self::Blur { .. }
|
||||
| Self::Mask { .. }
|
||||
| Self::Feather { .. }
|
||||
| Self::ConvolutionKernel { .. }
|
||||
| Self::Emboss { .. }
|
||||
| Self::FindEdges
|
||||
| Self::MinimumMaximum { .. }
|
||||
| Self::Sharpen { .. }
|
||||
| Self::HighPass { .. }
|
||||
| Self::AddNoise { .. }
|
||||
| Self::Dissolve { .. }
|
||||
| Self::Adjustment(_) => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A bound on how far a unit length in one space stretches in another, given the linear map between them.
|
||||
fn stretch_bound(linear_map: DMat2) -> f64 {
|
||||
let spans = spans_along_axes(linear_map);
|
||||
(spans.x * spans.x + spans.y * spans.y).sqrt()
|
||||
}
|
||||
|
||||
/// The corners of the content's `bounds` and its `overhang` past them, in a space that `space` maps an effect space into, carried into that effect space.
|
||||
/// The overhang there is as far as it can stretch, so content isn't cut short.
|
||||
fn measured_in_effect_space(space: DAffine2, [min, max]: [DVec2; 2], overhang: f64) -> ([DVec2; 4], f64) {
|
||||
let to_effect = match space.matrix2.determinant().is_normal() {
|
||||
true => space.inverse(),
|
||||
false => DAffine2::from_translation(-space.translation),
|
||||
};
|
||||
let corners = [min, DVec2::new(max.x, min.y), max, DVec2::new(min.x, max.y)].map(|corner| to_effect.transform_point2(corner));
|
||||
(corners, overhang * stretch_bound(to_effect.matrix2))
|
||||
}
|
||||
|
||||
impl Effects {
|
||||
/// How far past the content the effects of one run can paint, in their effect space, which `space` maps into the space the content's `bounds` are measured in,
|
||||
/// given how far the content already paints past them there (its `overhang`).
|
||||
pub fn run_reach_around(&self, space: DAffine2, bounds: [DVec2; 2], overhang: f64) -> f64 {
|
||||
let (corners, overhang) = measured_in_effect_space(space, bounds, overhang);
|
||||
(self.operations())
|
||||
.filter(|operation| !operation.changes_nothing())
|
||||
.fold(0., |painted, operation| painted + operation.reach_around(corners, overhang + painted))
|
||||
}
|
||||
|
||||
/// How far past the content the effects together can paint along each axis of the space `content_transform` places the content in, given the content's `bounds` there,
|
||||
/// past which a radial blur reaches farther the farther they lie from its center. The content's `overhang` is how far it already paints past them, as nested effects do.
|
||||
pub fn reach_around(&self, content_transform: DAffine2, bounds: [DVec2; 2], overhang: f64) -> DVec2 {
|
||||
self.reach_around_by(content_transform, bounds, overhang, |_| true)
|
||||
}
|
||||
|
||||
/// Like [`Effects::reach_around`], counting only how far those reading the pixels around each one of the image they work on read it (see [`EffectOperation::reads_pixels_around`]),
|
||||
/// along the axis they read furthest along.
|
||||
pub fn read_reach_around(&self, content_transform: DAffine2, bounds: [DVec2; 2], overhang: f64) -> f64 {
|
||||
let painted = self.reach_around_by(content_transform, bounds, overhang, EffectOperation::reads_pixels_around);
|
||||
(painted + self.read_beyond_painted(content_transform)).max_element()
|
||||
}
|
||||
|
||||
/// How much farther than they paint the effects reading around each pixel read, like a kernel, along each axis of the space `content_transform` places the content in.
|
||||
/// A render holds this much past the pixels it needs right, even those in view.
|
||||
pub fn read_beyond_painted(&self, content_transform: DAffine2) -> DVec2 {
|
||||
self.reach_along_axes_by(content_transform, |operation| operation.required_reach() - operation.painted_reach())
|
||||
}
|
||||
|
||||
/// Like [`Effects::reach_around`], counting only the effects that `counts` accepts, though every effect paints what those after it measure from.
|
||||
/// Each run measures the content's bounds and what's painted before it in its effect space.
|
||||
pub fn reach_around_by(&self, content_transform: DAffine2, bounds: [DVec2; 2], overhang: f64, counts: impl Fn(&EffectOperation) -> bool) -> DVec2 {
|
||||
let (mut painted, mut counted) = (DVec2::ZERO, DVec2::ZERO);
|
||||
|
||||
for (stamped_transform, rows) in self.runs() {
|
||||
let space = effect_space(content_transform, stamped_transform);
|
||||
let (corners, before) = measured_in_effect_space(space, bounds, overhang + painted.max_element());
|
||||
let (mut painted_in_run, mut counted_in_run) = (before, 0.);
|
||||
for operation in self.operations_in(rows).filter(|operation| !operation.changes_nothing()) {
|
||||
let reach = operation.reach_around(corners, painted_in_run);
|
||||
painted_in_run += reach;
|
||||
if counts(&operation) {
|
||||
counted_in_run += reach;
|
||||
}
|
||||
}
|
||||
|
||||
let spans = spans_along_axes(space.matrix2);
|
||||
painted += (painted_in_run - before) * spans;
|
||||
counted += counted_in_run * spans;
|
||||
}
|
||||
|
||||
counted
|
||||
}
|
||||
|
||||
/// Whether any of the effects takes the content's frame, which is costly to find for a stroked shape or a group.
|
||||
pub fn any_takes_frame(&self) -> bool {
|
||||
self.operations().any(|operation| operation.takes_frame())
|
||||
}
|
||||
|
||||
/// Whether how far the effects reach depends on the content's bounds, as a radial blur's does on how far they lie from its center.
|
||||
pub fn reach_depends_on_size(&self) -> bool {
|
||||
self.operations()
|
||||
.any(|operation| matches!(operation, EffectOperation::RadialBlur { .. }) && !operation.changes_nothing())
|
||||
}
|
||||
|
||||
/// The region, in pixels, that the content has to be rendered over so the effects can produce the `visible` part of their result (in pixels),
|
||||
/// if any of them reads from beyond its reach, as a radial blur reads along its arcs and lines. `effect_to_pixels` maps the effect space into the pixels.
|
||||
/// The stages before each effect may need different regions, all of which the result covers, since the effects' passes share one image.
|
||||
pub fn source_region(&self, visible: [DVec2; 2], effect_to_pixels: DAffine2) -> Option<[DVec2; 2]> {
|
||||
let operations: Vec<EffectOperation> = self.operations().filter(|operation| !operation.changes_nothing()).collect();
|
||||
if !operations.iter().any(|operation| matches!(operation, EffectOperation::RadialBlur { .. })) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let pixels_per_length = effect_to_pixels.matrix2.determinant().abs().sqrt();
|
||||
let spans = spans_along_axes(effect_to_pixels.matrix2);
|
||||
|
||||
// Folded backward from the visible result, each effect needing what it reads to produce the region the next one needs
|
||||
let mut region = visible;
|
||||
let mut covered = visible;
|
||||
for operation in operations.iter().rev() {
|
||||
region = match operation {
|
||||
EffectOperation::RadialBlur { method, amount, center, .. } => RadialBlur::new(*method, *amount, *center).source(region, effect_to_pixels, pixels_per_length),
|
||||
_ => {
|
||||
let reach = operation.reach() * spans;
|
||||
[region[0] - reach, region[1] + reach]
|
||||
}
|
||||
};
|
||||
covered = union(covered, region);
|
||||
}
|
||||
|
||||
Some(covered)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::effects::EffectOperation;
|
||||
|
||||
fn frame() -> EffectFrame {
|
||||
EffectFrame::new(frame_of_bounds([DVec2::new(100., 100.), DVec2::new(300., 200.)], DAffine2::IDENTITY), DAffine2::IDENTITY).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frames_map_their_local_space_from_the_middle() {
|
||||
let frame = frame();
|
||||
assert!((frame.local_to_pixels().transform_point2(DVec2::ZERO) - DVec2::new(200., 150.)).length() < 1e-9);
|
||||
assert!((frame.local_to_pixels().transform_point2(DVec2::new(100., -50.)) - DVec2::new(300., 100.)).length() < 1e-9);
|
||||
assert!(frame.contains(DVec2::new(99., 49.)));
|
||||
assert!(!frame.contains(DVec2::new(101., 0.)));
|
||||
assert!(EffectFrame::new(frame_of_bounds([DVec2::ZERO, DVec2::new(0., 5.)], DAffine2::IDENTITY), DAffine2::IDENTITY).is_none());
|
||||
|
||||
// Turned and scaled with its content, the frame keeps its sides' lengths in the effect space
|
||||
let turned = EffectFrame::new(frame_of_bounds([DVec2::ZERO, DVec2::new(40., 10.)], DAffine2::from_angle(0.5)), DAffine2::from_scale(DVec2::splat(2.))).unwrap();
|
||||
assert!((turned.size - DVec2::new(40., 10.)).length() < 1e-9);
|
||||
let right_middle = turned.local_to_pixels().transform_point2(DVec2::new(20., 0.));
|
||||
assert!((right_middle - DVec2::from_angle(0.5).rotate(DVec2::new(80., 10.))).length() < 1e-9, "{right_middle}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spins_sample_along_arcs_centered_on_each_point() {
|
||||
let blur = RadialBlur::new(RadialBlurMethod::Spin, 90. / SPIN_DEGREES_PER_AMOUNT, DVec2::ZERO);
|
||||
let point = DVec2::new(10., 0.);
|
||||
let count = blur.sample_count(point, 1.);
|
||||
|
||||
// An arc of a quarter turn at radius 10 is about 16 pixels long, sampled twice per pixel
|
||||
assert_eq!(count, 33);
|
||||
assert!((blur.sample(point, count / 2, count) - point).length() < 1e-9, "the middle sample is the point itself");
|
||||
assert!((blur.point_along(point, -0.5) - DVec2::from_angle(-std::f64::consts::FRAC_PI_4) * 10.).length() < 1e-9);
|
||||
|
||||
// Each sample lies in the middle of its share of the arc, so the first lies half a share within the arc's end
|
||||
let first = DVec2::from_angle(-std::f64::consts::FRAC_PI_4 * (1. - 1. / count as f64)) * 10.;
|
||||
assert!((blur.sample(point, 0, count) - first).length() < 1e-9);
|
||||
|
||||
// The samples of a whole turn spread evenly around the circle, so no two land together and they balance about the center
|
||||
let turn = RadialBlur::new(RadialBlurMethod::Spin, 360. / SPIN_DEGREES_PER_AMOUNT, DVec2::ZERO);
|
||||
let count = turn.sample_count(point, 1.);
|
||||
let mean = (0..count).map(|index| turn.sample(point, index, count)).sum::<DVec2>() / count as f64;
|
||||
assert!(mean.length() < 1e-9, "the samples of a whole turn average to {mean}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zooms_sample_along_lines_through_each_point_toward_the_center() {
|
||||
let blur = RadialBlur::new(RadialBlurMethod::Zoom, 0.5 / ZOOM_FRACTION_PER_AMOUNT, DVec2::new(100., 0.));
|
||||
|
||||
// For PSD interop, the line spans from three quarters to five quarters of the point's distance from the center
|
||||
let point = DVec2::new(100., 40.);
|
||||
assert!((blur.point_along(point, -0.5) - DVec2::new(100., 50.)).length() < 1e-9);
|
||||
assert!((blur.point_along(point, 0.5) - DVec2::new(100., 30.)).length() < 1e-9);
|
||||
|
||||
// Its samples lie in the middles of equal shares of the line, half a share within each end
|
||||
let count = blur.sample_count(point, 1.);
|
||||
let half_share = 10. / count as f64;
|
||||
assert!((blur.sample(point, 0, count) - DVec2::new(100., 50. - half_share)).length() < 1e-9);
|
||||
assert!((blur.sample(point, count / 2, count) - point).length() < 1e-9, "the middle sample is the point itself");
|
||||
assert!((blur.sample(point, count - 1, count) - DVec2::new(100., 30. + half_share)).length() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spin_reads_beyond_the_visible_part_of_its_result() {
|
||||
let effects = Effects::from_operations([EffectOperation::RadialBlur {
|
||||
method: RadialBlurMethod::Spin,
|
||||
amount: 60.,
|
||||
center: DVec2::new(200., 150.),
|
||||
gamma: false,
|
||||
}]);
|
||||
|
||||
// Only the top right corner of content from (100, 100) to (300, 200) is visible, and the arcs around its middle sweep past the corner's left and bottom
|
||||
let visible = [DVec2::new(250., 100.), DVec2::new(300., 130.)];
|
||||
let [min, max] = effects.source_region(visible, DAffine2::IDENTITY).unwrap();
|
||||
assert!(min.x < 230. && max.y > 150., "the region reaches from {min} to {max}");
|
||||
assert!(min.x <= 250. && min.y <= 100. && max.x >= 300. && max.y >= 130., "the region covers the visible part");
|
||||
|
||||
// The center lies in the effect space, so placing that space 50 pixels right moves what the spin reads along with it
|
||||
let shift = DVec2::new(50., 0.);
|
||||
let [moved_min, moved_max] = effects.source_region(visible.map(|corner| corner + shift), DAffine2::from_translation(shift)).unwrap();
|
||||
assert!((moved_min - (min + shift)).length() < 1e-9 && (moved_max - (max + shift)).length() < 1e-9);
|
||||
|
||||
// Effects that read only within their reach need nothing beyond it
|
||||
let blur = Effects::from_operations([EffectOperation::default_for(crate::EffectKind::Blur)]);
|
||||
assert_eq!(blur.source_region(visible, DAffine2::IDENTITY), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spins_reach_as_far_as_they_turn_what_earlier_effects_paint_on_skewed_content() {
|
||||
use crate::effects::{Effect, shadow_offset, stamp_effect};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::list::{ATTR_EFFECTS, Item};
|
||||
|
||||
// A sharp shadow cast 50 units down, then a half turn about a center off to the side
|
||||
let (angle, distance, amount) = (90., 50., 180.);
|
||||
let shadow = EffectOperation::DropShadow {
|
||||
color: core_types::Color::BLACK,
|
||||
blend_mode: Default::default(),
|
||||
angle,
|
||||
distance,
|
||||
spread: 0.,
|
||||
size: 0.,
|
||||
contour: Default::default(),
|
||||
knockout: true,
|
||||
};
|
||||
let center = DVec2::new(150., -40.);
|
||||
let spin = EffectOperation::RadialBlur {
|
||||
method: RadialBlurMethod::Spin,
|
||||
amount,
|
||||
center,
|
||||
gamma: false,
|
||||
};
|
||||
|
||||
// A square 100 across turned 45 degrees and squashed to a tenth of its height, with the effects stamped after the squash, or before it so the squash carries their spin
|
||||
let turn = DAffine2::from_angle(std::f64::consts::FRAC_PI_4);
|
||||
let squashed = DAffine2::from_scale(DVec2::new(1., 0.1)) * turn;
|
||||
for stamped in [squashed, turn] {
|
||||
let mut item = Item::new_from_element(()).with_attribute(ATTR_TRANSFORM, stamped);
|
||||
stamp_effect(&mut item, Effect::new(&shadow));
|
||||
stamp_effect(&mut item, Effect::new(&spin));
|
||||
item.set_attribute(ATTR_TRANSFORM, squashed);
|
||||
let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) else {
|
||||
panic!("stamping should add the effects attribute");
|
||||
};
|
||||
|
||||
let space = effect_space(squashed, crate::effects::stamped_transform(stamped));
|
||||
let corners = [DVec2::ZERO, DVec2::X, DVec2::ONE, DVec2::Y].map(|corner| squashed.transform_point2(corner * 100.));
|
||||
let bounds = [corners.into_iter().reduce(DVec2::min).unwrap(), corners.into_iter().reduce(DVec2::max).unwrap()];
|
||||
|
||||
// As SVG, culling, and enclosing layers measure it, and as Vello's effects group does in the effect space it's given
|
||||
let reaches = [
|
||||
effects.reach_around(squashed, bounds, 0.),
|
||||
effects.run_reach_around(space, bounds, 0.) * crate::effects::spans_along_axes(space.matrix2),
|
||||
];
|
||||
|
||||
// Where the renderers' spin, turning in the effect space, carries the corners of the content and its shadow
|
||||
let blur = RadialBlur::new(RadialBlurMethod::Spin, amount, center);
|
||||
for corner in corners {
|
||||
for cast in [DVec2::ZERO, shadow_offset(angle, distance)] {
|
||||
let point = space.inverse().transform_point2(corner) + cast;
|
||||
for step in 0..=200 {
|
||||
let spun = space.transform_point2(blur.point_along(point, step as f64 / 200. - 0.5));
|
||||
for reach in reaches {
|
||||
assert!(
|
||||
spun.cmpge(bounds[0] - reach).all() && spun.cmple(bounds[1] + reach).all(),
|
||||
"stamped at {stamped}, the spin carries the corner {corner} cast {cast} away to {spun}, past the reach of {reach} around {bounds:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radial_blurs_reach_farther_from_content_lying_farther_from_their_center() {
|
||||
let radial = |method, center| {
|
||||
Effects::from_operations([EffectOperation::RadialBlur {
|
||||
method,
|
||||
amount: 360.,
|
||||
center,
|
||||
gamma: false,
|
||||
}])
|
||||
};
|
||||
let reach = |effects: &Effects, content_transform, size| effects.reach_around(content_transform, [DVec2::ZERO, DVec2::splat(size)], 0.);
|
||||
let half_diagonal = 50. * std::f64::consts::SQRT_2;
|
||||
|
||||
// A full turn about the middle of a square 100 across sweeps its corners around their whole circle, as far as the diagonal
|
||||
let spin = radial(RadialBlurMethod::Spin, DVec2::splat(50.));
|
||||
assert!((reach(&spin, DAffine2::IDENTITY, 100.).x - 2. * half_diagonal).abs() < 1e-9);
|
||||
|
||||
// About the square's corner, the farthest corner lies twice as far, and from a square twice as large, twice as far again
|
||||
let about_corner = radial(RadialBlurMethod::Spin, DVec2::ZERO);
|
||||
assert!((reach(&about_corner, DAffine2::IDENTITY, 100.).x - 4. * half_diagonal).abs() < 1e-9);
|
||||
assert!((reach(&about_corner, DAffine2::IDENTITY, 200.).x - 8. * half_diagonal).abs() < 1e-9);
|
||||
|
||||
// About a center far off the content, its arcs sweep as far as its farthest corner lies from the center
|
||||
let far_center = DVec2::new(1000., 0.);
|
||||
let far_reach = 2. * far_center.distance(DVec2::new(0., 100.));
|
||||
assert!((reach(&radial(RadialBlurMethod::Spin, far_center), DAffine2::IDENTITY, 100.).x - far_reach).abs() < 1e-9);
|
||||
|
||||
// Scaled after it's applied, the spin measures the content in its effect space and reaches as far scaled along with it
|
||||
assert!((reach(&spin, DAffine2::from_scale(DVec2::splat(3.)), 300.) - 3. * reach(&spin, DAffine2::IDENTITY, 100.)).length() < 1e-9);
|
||||
|
||||
// Moved after it's applied, its center moves along with the content's origin, so it reaches as far
|
||||
let shift = DVec2::new(40., -70.);
|
||||
let moved = spin.reach_around(DAffine2::from_translation(shift), [shift, shift + 100.], 0.);
|
||||
assert!((moved - reach(&spin, DAffine2::IDENTITY, 100.)).length() < 1e-9);
|
||||
|
||||
// A zoom of 360 spans from a tenth to nineteen tenths of each point's distance, so it carries the farthest corner out ninefold
|
||||
let zoom = radial(RadialBlurMethod::Zoom, DVec2::splat(50.));
|
||||
assert!((reach(&zoom, DAffine2::IDENTITY, 100.).x - 9. * half_diagonal).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
@@ -25,5 +25,6 @@ vector-types = { workspace = true }
|
||||
# Workspace dependencies
|
||||
fastnoise-lite = { workspace = true }
|
||||
glam = { workspace = true }
|
||||
half = { workspace = true }
|
||||
log = { workspace = true }
|
||||
thiserror = { workspace = true }
|
||||
@@ -29,11 +29,12 @@ pub enum StepKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 20] = [
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -54,6 +55,7 @@ impl StepKind {
|
||||
StepKind::PhotoFilter,
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -266,6 +268,7 @@ mod tests {
|
||||
blend_mode: Default::default(),
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -223,6 +223,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
})
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1097,6 +1098,19 @@ impl MapColor for Invert {
|
||||
}
|
||||
}
|
||||
|
||||
/// For PSD interop, inverts each channel past middle gray, folding it back down.
|
||||
struct Solarize;
|
||||
|
||||
impl MapColor for Solarize {
|
||||
fn map_cpu(&self, color: Color) -> Color {
|
||||
color.map_gamma_rgb(|channel| channel.min(1. - channel))
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
steps.push(StepKind::Solarize, []);
|
||||
}
|
||||
}
|
||||
|
||||
struct Threshold {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
|
||||
@@ -86,11 +86,10 @@ impl BlurKernel {
|
||||
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()
|
||||
(0..=reach).map(|i| box_weight(radius, i)).collect()
|
||||
}
|
||||
Self::Tent { radius } => {
|
||||
let radius = radius / level_scale;
|
||||
@@ -108,6 +107,22 @@ impl BlurKernel {
|
||||
}
|
||||
}
|
||||
|
||||
/// How much a box of half width `radius` weighs the texel `distance` from its center, before normalizing: all of it within the box,
|
||||
/// and at each end the fraction of it the box covers, so the blur grows smoothly with its radius.
|
||||
pub fn box_weight(radius: f64, distance: usize) -> f64 {
|
||||
(radius + 1. - distance as f64).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// The greatest channel value a variable box blur counts, past 1 to keep bright high dynamic range values, which `vello_masks.wgsl` matches.
|
||||
pub const VARIABLE_BOX_MAX_VALUE: f32 = 16.;
|
||||
|
||||
/// How many steps from 0 to 1 a variable box blur counts each channel of an image of `pixels` in, up to [`VARIABLE_BOX_MAX_VALUE`].
|
||||
/// The GPU's running sums of those counts then stay exact in f32 digits (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`): 2^12 up to 8192 by 8192 pixels, halving for each doubling past it.
|
||||
pub fn variable_box_scale(pixels: usize) -> f64 {
|
||||
let pixel_bits = (pixels.max(1) as f64).log2().ceil();
|
||||
2_f64.powf((38. - pixel_bits).clamp(0., 12.))
|
||||
}
|
||||
|
||||
/// 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;
|
||||
@@ -178,7 +193,7 @@ impl<T: Sample> Plane<T> {
|
||||
}
|
||||
|
||||
/// The plane with its rows and columns swapped, so a horizontal operation can work vertically. O(width × height).
|
||||
fn transposed(&self) -> Self {
|
||||
pub(crate) 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]);
|
||||
|
||||
@@ -0,0 +1,912 @@
|
||||
//! The pixel filters on the CPU, which mirror the renderer's GPU passes on premultiplied gamma-encoded channels.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, Plane};
|
||||
use crate::generators::pcg3d;
|
||||
use glam::{DAffine2, DMat2, DVec2, IVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, GAUSSIAN_NOISE_LIMIT, HIGH_PASS_GRAY, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, average_weight,
|
||||
edge_gain, fill_shifts, neighborhood_radii, noise_extent, unsharp, unsharp_change,
|
||||
};
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// Carries out a filter effect on premultiplied gamma-encoded pixels, which `pixels_to_effect` places in the effect space, or returns them as they are for any other operation.
|
||||
/// The pixels visible in the `full`-strength content (the plane itself for `None`) are those whose colors the filter reads.
|
||||
pub fn filter(plane: Plane<[f32; 4]>, full: Option<&Plane<[f32; 4]>>, operation: &EffectOperation, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let document_to_pixels = pixels_to_effect.matrix2.inverse();
|
||||
if let Some(convolution) = operation.convolution() {
|
||||
return convolve(&plane, full.unwrap_or(&plane), &convolution, document_to_pixels);
|
||||
}
|
||||
|
||||
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||
let sharpening = sharpening.map(|[amount, threshold]| (amount as f32, threshold as f32));
|
||||
return unsharp_mask(&plane, full.unwrap_or(&plane), blur, sharpening, document_to_pixels);
|
||||
}
|
||||
|
||||
match *operation {
|
||||
EffectOperation::FindEdges => find_edges(&plane, document_to_pixels),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => neighborhood_extreme(&plane, radius, mode == MinimumMaximumMode::Maximum, document_to_pixels),
|
||||
EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => add_noise(&plane, amount / 100., distribution, monochromatic, seed, pixels_to_effect),
|
||||
EffectOperation::Dissolve { opacity, seed } => dissolve(&plane, opacity / 100., seed, pixels_to_effect),
|
||||
_ => plane,
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole-pixel shifts, nearest first, that a faint pixel looks along for a visible one within `reach` document pixels, measured through `document_to_pixels`. O(reach² log reach).
|
||||
pub fn pixel_fill_shifts(reach: f64, document_to_pixels: DMat2) -> Vec<[isize; 2]> {
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
let pixel_shift = |[x, y]: [i32; 2]| (document_to_pixels * DVec2::new(x as f64, y as f64)).round();
|
||||
(fill_shifts(reach.ceil() as i32).into_iter().map(pixel_shift))
|
||||
.map(|shift| [shift.x as isize, shift.y as isize])
|
||||
.filter(|&shift| seen.insert(shift))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Each pixel's straight color, as the filters read it, with an alpha of 1 where there is one: its own if it's visible in the `full`-strength content, otherwise that of the first visible pixel along `shifts`,
|
||||
/// or failing that its own if it has any coverage. O(width × height × shifts) for the faint pixels.
|
||||
pub(crate) fn visible_colors(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, shifts: &[[isize; 2]]) -> Plane<[f32; 4]> {
|
||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||
let covered = |x: isize, y: isize, least_alpha: f32| {
|
||||
let index = (x >= 0 && y >= 0 && x < columns && y < rows).then_some((y * columns + x) as usize)?;
|
||||
let [red, green, blue, alpha] = plane.data[index];
|
||||
(alpha > 0. && full.data[index][3] >= least_alpha).then(|| [red / alpha, green / alpha, blue / alpha, 1.])
|
||||
};
|
||||
|
||||
let mut colors = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut colors.data, plane.width, |y, row| {
|
||||
for (x, color) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let nearest_visible = shifts.iter().find_map(|&[shift_x, shift_y]| covered(x + shift_x, y + shift_y, VISIBLE_ALPHA));
|
||||
*color = nearest_visible.or_else(|| covered(x, y, 0.)).unwrap_or_default();
|
||||
}
|
||||
});
|
||||
colors
|
||||
}
|
||||
|
||||
/// A weighted copy of a plane shifted by a fixed fraction of a pixel, read as the four pixels around each position with their bilinear weights.
|
||||
struct BilinearTap {
|
||||
/// The whole-pixel part of the shift.
|
||||
whole: [isize; 2],
|
||||
/// The bilinear weights of the pixels at the whole shift and one past it along x, then the same one past it along y.
|
||||
bilinear: [f32; 4],
|
||||
weight: f32,
|
||||
}
|
||||
|
||||
impl BilinearTap {
|
||||
fn new(shift: DVec2, weight: f32) -> Self {
|
||||
let whole = shift.floor();
|
||||
let [x, y] = (shift - whole).as_vec2().to_array();
|
||||
Self {
|
||||
whole: [whole.x as isize, whole.y as isize],
|
||||
bilinear: [(1. - x) * (1. - y), x * (1. - y), (1. - x) * y, x * y],
|
||||
weight,
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted color between the four `corners` (straight colors with an alpha of 1 where there is one), interpolated among those with a color, matching the GPU's `color_between`.
|
||||
/// Leaving out those without one continues the colors past the edges between pixels too, rather than fading toward black.
|
||||
fn weighted(&self, corners: [[f32; 4]; 4]) -> [f32; 3] {
|
||||
let (mut color, mut covered) = ([0.; 3], 0.);
|
||||
for (corner, bilinear) in corners.into_iter().zip(self.bilinear) {
|
||||
(0..3).for_each(|channel| color[channel] += corner[channel] * bilinear);
|
||||
covered += corner[3] * bilinear;
|
||||
}
|
||||
if covered > 0. { color.map(|channel| channel / covered * self.weight) } else { [0.; 3] }
|
||||
}
|
||||
}
|
||||
|
||||
/// The opaque colors a filter reads, as its surroundings describe, with the color it reads beyond their edges.
|
||||
struct SurroundedColors {
|
||||
colors: Plane<[f32; 4]>,
|
||||
beyond: [f32; 4],
|
||||
}
|
||||
|
||||
impl SurroundedColors {
|
||||
/// The colors of the premultiplied pixels that a filter reading within `reach` document pixels sees, measured through `document_to_pixels`, those visible judged by the `full`-strength content.
|
||||
fn new(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, surroundings: Surroundings, reach: f64, document_to_pixels: DMat2) -> Self {
|
||||
match surroundings {
|
||||
Surroundings::Continued => Self {
|
||||
colors: visible_colors(plane, full, &pixel_fill_shifts(reach, document_to_pixels)),
|
||||
beyond: [0.; 4],
|
||||
},
|
||||
Surroundings::Matted(gray) => {
|
||||
let gray = gray as f32;
|
||||
let over_gray = |channel: f32, alpha: f32| channel + gray * (1. - alpha);
|
||||
Self {
|
||||
colors: plane.map(|[red, green, blue, alpha]| [over_gray(red, alpha), over_gray(green, alpha), over_gray(blue, alpha), 1.]),
|
||||
beyond: [gray, gray, gray, 1.],
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The coverage of the premultiplied pixels in each channel, read with none beyond the plane's edges and every pixel counted when reading between them.
|
||||
fn coverage(plane: &Plane<[f32; 4]>) -> Self {
|
||||
Self {
|
||||
colors: plane.map(|[.., alpha]| [alpha, alpha, alpha, 1.]),
|
||||
beyond: [0., 0., 0., 1.],
|
||||
}
|
||||
}
|
||||
|
||||
fn at(&self, x: isize, y: isize) -> [f32; 4] {
|
||||
let (columns, rows) = (self.colors.width as isize, self.colors.height as isize);
|
||||
match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||
true => self.colors.data[(y * columns + x) as usize],
|
||||
false => self.beyond,
|
||||
}
|
||||
}
|
||||
|
||||
/// The weighted sum of the colors that the `taps` read around a pixel.
|
||||
fn sum(&self, x: isize, y: isize, taps: &[BilinearTap]) -> [f32; 3] {
|
||||
let mut sum = [0.; 3];
|
||||
for tap in taps {
|
||||
let [shift_x, shift_y] = [x + tap.whole[0], y + tap.whole[1]];
|
||||
let corners = [
|
||||
self.at(shift_x, shift_y),
|
||||
self.at(shift_x + 1, shift_y),
|
||||
self.at(shift_x, shift_y + 1),
|
||||
self.at(shift_x + 1, shift_y + 1),
|
||||
];
|
||||
let weighted = tap.weighted(corners);
|
||||
(0..3).for_each(|channel| sum[channel] += weighted[channel]);
|
||||
}
|
||||
sum
|
||||
}
|
||||
}
|
||||
|
||||
/// A filtered pixel as a premultiplied color: its straight `colors` given the coverage of `alpha`, or for matted surroundings, colors filtered over the gray and lifted back off it within that coverage.
|
||||
fn uncovered(colors: [f32; 3], alpha: f32, surroundings: Surroundings) -> [f32; 4] {
|
||||
let [red, green, blue] = match surroundings {
|
||||
Surroundings::Continued => colors.map(|channel| channel.clamp(0., 1.) * alpha),
|
||||
Surroundings::Matted(gray) => colors.map(|channel| (channel.clamp(0., 1.) - gray as f32 * (1. - alpha)).max(0.).min(alpha)),
|
||||
};
|
||||
[red, green, blue, alpha]
|
||||
}
|
||||
|
||||
/// The premultiplied pixels with each one's color replaced by the weighted sum `convolution` describes, with its shifts measured through `document_to_pixels`.
|
||||
/// It reads the colors as the convolution's surroundings describe, those visible judged by the `full`-strength content, then divides, raises, and clamps the sum, keeping each pixel's coverage unless it weighs that too. O(width × height × taps).
|
||||
pub fn convolve(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, convolution: &Convolution, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let taps: Vec<BilinearTap> = convolution
|
||||
.taps
|
||||
.iter()
|
||||
.map(|&(shift, weight)| BilinearTap::new(document_to_pixels * shift, (weight / convolution.divisor) as f32))
|
||||
.collect();
|
||||
let offset = convolution.offset as f32;
|
||||
let colors = SurroundedColors::new(plane, full, convolution.surroundings, convolution.reach(), document_to_pixels);
|
||||
let coverage = convolution.weighs_coverage.then(|| SurroundedColors::coverage(plane));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let alpha = match &coverage {
|
||||
Some(coverage) => coverage.sum(x, y, &taps)[0].clamp(0., 1.),
|
||||
None => plane.data[y as usize * plane.width + x as usize][3],
|
||||
};
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let sum = colors.sum(x, y, &taps).map(|channel| channel + offset);
|
||||
*pixel = uncovered(sum, alpha, convolution.surroundings);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// Each pixel's share of the full-strength content's coverage that the faded fill left, which a filter sharpening the coverage fades its result by. O(width × height).
|
||||
pub fn fill_shares(full: &Plane<[f32; 4]>, filled: &Plane<[f32; 4]>) -> Plane<f32> {
|
||||
full.zip(filled, |full, filled| if full[3] > 0. { (filled[3] / full[3]).min(1.) } else { 0. })
|
||||
}
|
||||
|
||||
/// The fill's filtered straight colors at the coverage of the full-strength content's filtered result, scaled by each pixel's share of it from [`fill_shares`],
|
||||
/// so the fill fades the result as if after the filter. O(width × height).
|
||||
pub fn faded_by_shares(filtered_filled: &Plane<[f32; 4]>, filtered_full: &Plane<[f32; 4]>, shares: &Plane<f32>) -> Plane<[f32; 4]> {
|
||||
let straight = |[red, green, blue, alpha]: [f32; 4]| [red / alpha, green / alpha, blue / alpha];
|
||||
let colors = filtered_filled.zip(filtered_full, |filled, full| {
|
||||
let [red, green, blue] = if filled[3] > 0. {
|
||||
straight(filled)
|
||||
} else if full[3] > 0. {
|
||||
straight(full)
|
||||
} else {
|
||||
[0.; 3]
|
||||
};
|
||||
[red, green, blue, full[3]]
|
||||
});
|
||||
colors.zip(shares, |[red, green, blue, full_alpha], share| {
|
||||
let alpha = full_alpha * share;
|
||||
[red * alpha, green * alpha, blue * alpha, alpha]
|
||||
})
|
||||
}
|
||||
|
||||
/// For PSD interop, each straight color and the coverage sharpened against the `blur` around it, measured through `document_to_pixels`, by the `amount` and `threshold` fractions [`unsharp_change`] takes.
|
||||
/// The colors are compared against the average of those visible in the `full`-strength content alone (or where too few are, the pixel's own color), so the content's surroundings take no part.
|
||||
/// With no amount and threshold, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept. O(width × height) per blur pass.
|
||||
pub fn unsharp_mask(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, blur: UnsharpBlur, sharpening: Option<(f32, f32)>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
// The visible colors made opaque among the others left out, so dividing their blur by its alpha averages the visible colors alone
|
||||
let visible = plane.zip(full, |[red, green, blue, alpha], [.., full_alpha]| match alpha > 0. && full_alpha >= VISIBLE_ALPHA {
|
||||
true => [red / alpha, green / alpha, blue / alpha, 1.],
|
||||
false => [0.; 4],
|
||||
});
|
||||
|
||||
// A high pass keeps the coverage, so only unsharp masking blurs it
|
||||
let (blurred_colors, blurred_coverage) = match blur {
|
||||
UnsharpBlur::Gaussian(radius) => {
|
||||
let sigma = radius.max(0.) * spans_along_axes(document_to_pixels);
|
||||
let kernels = (BlurKernel::Gaussian { sigma: sigma.x }, BlurKernel::Gaussian { sigma: sigma.y });
|
||||
let blurred_coverage = sharpening.is_some().then(|| plane.map(|[.., alpha]| alpha).blurred(kernels.0, kernels.1));
|
||||
(visible.blurred(kernels.0, kernels.1), blurred_coverage)
|
||||
}
|
||||
UnsharpBlur::EdgeNeighbors => {
|
||||
let blurred_coverage = sharpening.is_some().then(|| neighbors_average(plane, document_to_pixels).map(|[.., alpha]| alpha));
|
||||
(neighbors_average(&visible, document_to_pixels), blurred_coverage)
|
||||
}
|
||||
};
|
||||
let gains = (blur == UnsharpBlur::EdgeNeighbors).then(|| edge_gains(plane, full, document_to_pixels));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let index = y * plane.width + x;
|
||||
let [red, green, blue, alpha] = plane.data[index];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Where too little of the blur lands on visible colors to know their average, the pixel eases into being compared against its own color.
|
||||
// Edges Only moves each channel only its gain's share of the way toward the average.
|
||||
let own = [red / alpha, green / alpha, blue / alpha, alpha];
|
||||
let blurred = blurred_colors.data[index];
|
||||
let weight = average_weight(blurred[3]);
|
||||
let gain = gains.as_ref().map_or([1.; 4], |gains| gains.data[index]);
|
||||
let average: [f32; 3] = std::array::from_fn(|channel| {
|
||||
if weight > 0. {
|
||||
own[channel] + (blurred[channel] / blurred[3] - own[channel]) * weight * gain[channel]
|
||||
} else {
|
||||
own[channel]
|
||||
}
|
||||
});
|
||||
let coverage_average = blurred_coverage.as_ref().map_or(alpha, |blurred_coverage| alpha + (blurred_coverage.data[index] - alpha) * gain[3]);
|
||||
let difference: [f32; 4] = std::array::from_fn(|channel| own[channel] - if channel == 3 { coverage_average } else { average[channel] });
|
||||
|
||||
let sharpened: [f32; 4] = match sharpening {
|
||||
Some((amount, threshold)) => std::array::from_fn(|channel| (own[channel] + unsharp_change(difference[channel], amount, threshold)).clamp(0., 1.)),
|
||||
None => std::array::from_fn(|channel| if channel == 3 { alpha } else { (difference[channel] + HIGH_PASS_GRAY).clamp(0., 1.) }),
|
||||
};
|
||||
let alpha = sharpened[3];
|
||||
*pixel = [sharpened[0] * alpha, sharpened[1] * alpha, sharpened[2] * alpha, alpha];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// The average of each pixel's four nearest neighbors ([`SHARPEN_NEIGHBORS`], measured through `document_to_pixels`) in every channel, read between pixels with none beyond the plane's edges,
|
||||
/// as Edges Only compares against, matching the GPU's `neighbors_average`. O(width × height).
|
||||
fn neighbors_average(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let taps = SHARPEN_NEIGHBORS.map(|shift| BilinearTap::new(document_to_pixels * shift, 0.25));
|
||||
let (columns, rows) = (plane.width as isize, plane.height as isize);
|
||||
let at = |x: isize, y: isize| match x >= 0 && y >= 0 && x < columns && y < rows {
|
||||
true => plane.data[(y * columns + x) as usize],
|
||||
false => [0.; 4],
|
||||
};
|
||||
|
||||
let mut average = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut average.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
for tap in &taps {
|
||||
let [x, y] = [x as isize + tap.whole[0], y as isize + tap.whole[1]];
|
||||
let corners = [at(x, y), at(x + 1, y), at(x, y + 1), at(x + 1, y + 1)];
|
||||
for (corner, bilinear) in corners.into_iter().zip(tap.bilinear) {
|
||||
(0..4).for_each(|channel| pixel[channel] += corner[channel] * bilinear * tap.weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
average
|
||||
}
|
||||
|
||||
/// For PSD interop, the share of its change Edges Only makes in each channel of each pixel, the [`edge_gain`] of the channel's Sobel gradient there, matching the GPU's `edge_gains`.
|
||||
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it. O(width × height).
|
||||
fn edge_gains(plane: &Plane<[f32; 4]>, full: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
// A faint pixel the gradient reads finds its nearest visible color within the square of a pixel around it
|
||||
let colors = SurroundedColors::new(plane, full, Surroundings::Continued, 1., document_to_pixels);
|
||||
let coverage = SurroundedColors::coverage(plane);
|
||||
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||
let (across, down) = (taps(0), taps(1));
|
||||
|
||||
let mut gains = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut gains.data, plane.width, |y, row: &mut [[f32; 4]]| {
|
||||
for (x, gain) in row.iter_mut().enumerate() {
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let [colors_across, colors_down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||
let [coverage_across, coverage_down] = [coverage.sum(x, y, &across)[0], coverage.sum(x, y, &down)[0]];
|
||||
|
||||
*gain = std::array::from_fn(|channel| match channel {
|
||||
3 => edge_gain(coverage_across.hypot(coverage_down)),
|
||||
_ => edge_gain(colors_across[channel].hypot(colors_down[channel])),
|
||||
});
|
||||
}
|
||||
});
|
||||
gains
|
||||
}
|
||||
|
||||
/// For PSD interop, each channel darkened by how steeply it changes, the length of its Sobel gradient, so edges show dark over white.
|
||||
/// The content is matted over white, so its silhouette shows as an edge too. O(width × height).
|
||||
pub fn find_edges(plane: &Plane<[f32; 4]>, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let surroundings = Surroundings::Matted(1.);
|
||||
let colors = SurroundedColors::new(plane, plane, surroundings, 1., document_to_pixels);
|
||||
let taps = |axis: usize| SOBEL_TAPS.map(|(shift, weights)| BilinearTap::new(document_to_pixels * shift, weights[axis] as f32));
|
||||
let (across, down) = (taps(0), taps(1));
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let alpha = plane.data[y * plane.width + x][3];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (x, y) = (x as isize, y as isize);
|
||||
let [across, down] = [colors.sum(x, y, &across), colors.sum(x, y, &down)];
|
||||
let edges = std::array::from_fn(|channel| 1. - across[channel].hypot(down[channel]));
|
||||
*pixel = uncovered(edges, alpha, surroundings);
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// For PSD interop, each pixel's color is the lightest in the square of `radius` document pixels around it (or with `maximum` false, the darkest), and its coverage the opposite extreme.
|
||||
/// The maximum spreads every covered pixel's straight color. The minimum spreads the darkest colors matted over white, lifted back off within the grown coverage, so faint pixels darken only as much as they cover.
|
||||
/// A fractional radius mixes the whole radii around it. O(width × height).
|
||||
pub fn neighborhood_extreme(plane: &Plane<[f32; 4]>, radius: f64, maximum: bool, document_to_pixels: DMat2) -> Plane<[f32; 4]> {
|
||||
let spans = spans_along_axes(document_to_pixels);
|
||||
let ([near_x, far_x], fraction) = neighborhood_radii(radius, spans.x);
|
||||
let ([near_y, far_y], _) = neighborhood_radii(radius, spans.y);
|
||||
if near_x.max(near_y) == 0 && (fraction <= 0. || far_x.max(far_y) == 0) {
|
||||
return plane.clone();
|
||||
}
|
||||
|
||||
// Colors and coverage in the form the filter takes the extremes of, with uncovered pixels' colors (and those beyond the edges) at the identity of their extreme
|
||||
let (prepared, beyond) = match maximum {
|
||||
true => (
|
||||
plane.map(|[red, green, blue, alpha]| match alpha > 0. {
|
||||
true => [red / alpha, green / alpha, blue / alpha, alpha],
|
||||
false => [0.; 4],
|
||||
}),
|
||||
[0.; 4],
|
||||
),
|
||||
false => (
|
||||
plane.map(|[red, green, blue, alpha]| [red + 1. - alpha, green + 1. - alpha, blue + 1. - alpha, alpha]),
|
||||
[1., 1., 1., 0.],
|
||||
),
|
||||
};
|
||||
let extreme = move |first: [f32; 4], second: [f32; 4]| -> [f32; 4] {
|
||||
std::array::from_fn(|channel| match (channel == 3) != maximum {
|
||||
true => first[channel].max(second[channel]),
|
||||
false => first[channel].min(second[channel]),
|
||||
})
|
||||
};
|
||||
// Back to premultiplied colors, which for the minimum lifts white back off within the grown coverage
|
||||
let premultiplied = move |[red, green, blue, alpha]: [f32; 4]| {
|
||||
let channel = |channel: f32| match maximum {
|
||||
true => channel * alpha,
|
||||
false => (channel - (1. - alpha)).max(0.).min(alpha),
|
||||
};
|
||||
[channel(red), channel(green), channel(blue), alpha]
|
||||
};
|
||||
|
||||
// The larger square's extremes grow from the smaller one's, as a square widened by another is the square of their radii summed
|
||||
let near = extremes_in_squares(prepared, [near_x, near_y], beyond, extreme);
|
||||
if fraction <= 0. {
|
||||
return near.map(premultiplied);
|
||||
}
|
||||
let far = extremes_in_squares(near.clone(), [far_x - near_x, far_y - near_y], beyond, extreme);
|
||||
near.zip(&far, |near, far| {
|
||||
let (near, far) = (premultiplied(near), premultiplied(far));
|
||||
std::array::from_fn(|channel| near[channel] + (far[channel] - near[channel]) * fraction as f32)
|
||||
})
|
||||
}
|
||||
|
||||
/// The `extreme` of each rectangle reaching `across` and `down` pixels from each pixel, with `beyond` read past the edges, along the rows then the columns. O(width × height).
|
||||
fn extremes_in_squares(plane: Plane<[f32; 4]>, [across, down]: [u32; 2], beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4] + Copy + Sync) -> Plane<[f32; 4]> {
|
||||
let along_rows = |plane: Plane<[f32; 4]>, radius: u32| {
|
||||
if radius == 0 {
|
||||
return plane;
|
||||
}
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
window_extremes(&plane.data[y * plane.width..(y + 1) * plane.width], row, radius as usize, beyond, extreme)
|
||||
});
|
||||
result
|
||||
};
|
||||
|
||||
let plane = along_rows(plane, across);
|
||||
match down {
|
||||
0 => plane,
|
||||
_ => along_rows(plane.transposed(), down).transposed(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `extreme` of each window of `2 × radius + 1` values along a row, with `beyond` read past its ends, by van Herk and Gil-Werman's blocks of extremes running from each block's start and to its end.
|
||||
/// O(length) whatever the radius, since a window as wide as the row already holds all of it.
|
||||
fn window_extremes(source: &[[f32; 4]], target: &mut [[f32; 4]], radius: usize, beyond: [f32; 4], extreme: impl Fn([f32; 4], [f32; 4]) -> [f32; 4]) {
|
||||
let radius = radius.min(source.len());
|
||||
let window = 2 * radius + 1;
|
||||
let padded: Vec<[f32; 4]> = std::iter::repeat_n(beyond, radius).chain(source.iter().copied()).chain(std::iter::repeat_n(beyond, radius)).collect();
|
||||
|
||||
let mut from_start = padded.clone();
|
||||
let mut to_end = padded.clone();
|
||||
for index in 1..padded.len() {
|
||||
if index % window != 0 {
|
||||
from_start[index] = extreme(from_start[index - 1], padded[index]);
|
||||
}
|
||||
}
|
||||
for index in (0..padded.len() - 1).rev() {
|
||||
if (index + 1) % window != 0 {
|
||||
to_end[index] = extreme(to_end[index + 1], padded[index]);
|
||||
}
|
||||
}
|
||||
|
||||
// Each window spans the end of one block and the start of the next
|
||||
for (index, value) in target.iter_mut().enumerate() {
|
||||
*value = extreme(to_end[index], from_start[index + window - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
/// A value strictly between 0 and 1 from the top 23 bits of a hash, which an f32 holds exactly with the half added, matching the GPU's.
|
||||
fn unit_interval(hash: u32) -> f32 {
|
||||
((hash >> 9) as f32 + 0.5) / (1_u32 << 23) as f32
|
||||
}
|
||||
|
||||
/// The three random values one field of the `seed` holds at a cell of the effect space.
|
||||
fn field_values(cell: IVec2, seed: u32) -> [f32; 3] {
|
||||
pcg3d([cell.x as u32, cell.y as u32, seed]).map(unit_interval)
|
||||
}
|
||||
|
||||
/// The noise each of a pixel's colors takes before the amount scales it, averaged over the pixel's samples of the field: uniform from -1 to 1, or Gaussian with a deviation of 1 cut off at [`GAUSSIAN_NOISE_LIMIT`].
|
||||
fn noise_at(sampling: &FieldSampling, pixel: [usize; 2], distribution: NoiseDistribution, monochromatic: bool, seed: i64) -> [f32; 3] {
|
||||
let (offsets_seed, angles_seed) = (RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed));
|
||||
|
||||
let mut sum = [0.; 3];
|
||||
let mut count = 0.;
|
||||
for cell in sampling.sample_cells(pixel) {
|
||||
let offsets = field_values(cell, offsets_seed);
|
||||
let noise = match distribution {
|
||||
NoiseDistribution::Uniform => offsets.map(|value| 2. * value - 1.),
|
||||
// The Box-Muller transform of two uniform values into one with a normal distribution
|
||||
NoiseDistribution::Gaussian => {
|
||||
let angles = field_values(cell, angles_seed);
|
||||
std::array::from_fn(|channel| ((-2. * offsets[channel].ln()).sqrt() * (std::f32::consts::TAU * angles[channel]).cos()).clamp(-GAUSSIAN_NOISE_LIMIT, GAUSSIAN_NOISE_LIMIT))
|
||||
}
|
||||
};
|
||||
(0..3).for_each(|channel| sum[channel] += noise[channel]);
|
||||
count += 1.;
|
||||
}
|
||||
|
||||
let average = sum.map(|channel| channel / count);
|
||||
if monochromatic { [average[0]; 3] } else { average }
|
||||
}
|
||||
|
||||
/// For PSD interop, each straight color offset by noise of `amount` (a fraction of full brightness) with its `distribution`, the same for every color of a pixel if it's `monochromatic`, and clamped.
|
||||
/// The coverage is kept. The noise is fixed to the cells of the effect space, which `pixels_to_effect` places the plane's pixels among. O(width × height × samples per pixel).
|
||||
pub fn add_noise(plane: &Plane<[f32; 4]>, amount: f64, distribution: NoiseDistribution, monochromatic: bool, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let extent = noise_extent(amount, distribution) as f32;
|
||||
let scale = (amount * sampling.deviation_scale) as f32;
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let noise = noise_at(&sampling, [x, y], distribution, monochromatic, seed);
|
||||
let noisy = |channel: f32, noise: f32| (channel / alpha + (noise * scale).clamp(-extent, extent)).clamp(0., 1.) * alpha;
|
||||
*pixel = [noisy(red, noise[0]), noisy(green, noise[1]), noisy(blue, noise[2]), alpha];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
/// For PSD interop, how much of a pixel Dissolve shows, from 0 to 1: the share of its samples passing the `opacity` (a fraction), and the threshold level from 0 to 254 its coverage must pass.
|
||||
/// For pixels spanning more cells than they sample, the share deviates from the opacity less, as it would over them all.
|
||||
fn dissolve_field(sampling: &FieldSampling, pixel: [usize; 2], opacity: f32, seed: i64) -> (f32, f32) {
|
||||
let seed = RandomField::Dissolve.seed(seed);
|
||||
|
||||
let (mut shown, mut count) = (0., 0.);
|
||||
for cell in sampling.sample_cells(pixel) {
|
||||
shown += if field_values(cell, seed)[0] < opacity { 1. } else { 0. };
|
||||
count += 1.;
|
||||
}
|
||||
let share = (opacity + (shown / count - opacity) * sampling.deviation_scale as f32).clamp(0., 1.);
|
||||
|
||||
let threshold = (field_values(sampling.center_cell(pixel), seed)[1] * 255.).floor();
|
||||
(share, threshold)
|
||||
}
|
||||
|
||||
/// For PSD interop, the content shown fully opaque where the `opacity` (a fraction) and the coverage each pass a threshold of their own, random for each cell of the effect space, and hidden elsewhere.
|
||||
/// The thresholds are fixed to those cells, which `pixels_to_effect` places the plane's pixels among, and pixels spanning several show the share of them passing. O(width × height × samples per pixel).
|
||||
pub fn dissolve(plane: &Plane<[f32; 4]>, opacity: f64, seed: i64, pixels_to_effect: DAffine2) -> Plane<[f32; 4]> {
|
||||
let sampling = FieldSampling::new(pixels_to_effect);
|
||||
let opacity = opacity as f32;
|
||||
|
||||
let mut result = Plane::new(plane.width, plane.height);
|
||||
fill_rows(&mut result.data, plane.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let [red, green, blue, alpha] = plane.data[y * plane.width + x];
|
||||
if alpha <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// The coverage passes a threshold level when it's at least one 8-bit level above it, a half level counting as the level below as browsers truncate it
|
||||
let (share, threshold) = dissolve_field(&sampling, [x, y], opacity, seed);
|
||||
let shown = if alpha * 255. > threshold + 0.5 { share } else { 0. };
|
||||
*pixel = [red / alpha * shown, green / alpha * shown, blue / alpha * shown, shown];
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn plane(width: usize, height: usize, data: Vec<[f32; 4]>) -> Plane<[f32; 4]> {
|
||||
Plane { width, height, data }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernels_of_any_shape_read_around_their_center() {
|
||||
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||
|
||||
// An even row centers on its second weight, so its first reads the pixel to the left, moving the colors right
|
||||
let line = plane(3, 1, vec![white, black, black]);
|
||||
let even = convolve(&line, &line, &Convolution::custom(&[1., 0.], 2, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(&even.data[1..], &[white, black]);
|
||||
|
||||
// A column reads the pixels above and below
|
||||
let column = plane(1, 3, vec![white, black, black]);
|
||||
let down = convolve(&column, &column, &Convolution::custom(&[1., 0., 0.], 1, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(&down.data[1..], &[white, black]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_of_one_weight_shifts_the_colors_within_the_coverage() {
|
||||
let (black, white) = ([0., 0., 0., 1.], [1.; 4]);
|
||||
let line = plane(4, 1, vec![black, white, black, [0.; 4]]);
|
||||
|
||||
// The weight right of the center reads the pixel to the right, moving the colors left
|
||||
let right = [0., 0., 0., 0., 0., 1., 0., 0., 0.];
|
||||
let shifted = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::IDENTITY);
|
||||
assert_eq!(shifted.data, vec![white, black, black, [0.; 4]]);
|
||||
|
||||
// A shift of half a pixel splits between two
|
||||
let halved = convolve(&line, &line, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(0.5)));
|
||||
assert_eq!(halved.data, vec![[0.5, 0.5, 0.5, 1.], [0.5, 0.5, 0.5, 1.], black, [0.; 4]]);
|
||||
|
||||
// A shift past the edge reads between the colors continued past it and none further, which it leaves out rather than darkening toward
|
||||
let edge = plane(5, 1, vec![white, white, [0.; 4], [0.; 4], [0.; 4]]);
|
||||
let past_edge = convolve(&edge, &edge, &Convolution::custom(&right, 3, 1., 0.), DMat2::from_diagonal(DVec2::splat(1.25)));
|
||||
assert_eq!(past_edge.data[1], white);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sums_are_divided_raised_and_clamped() {
|
||||
let gray = [0.25, 0.25, 0.25, 0.5];
|
||||
let line = plane(3, 1, vec![gray; 3]);
|
||||
|
||||
// Doubled to full brightness, then raised past it
|
||||
let raised = convolve(&line, &line, &Convolution::custom(&[2.], 1, 1., 255. / 4.), DMat2::IDENTITY);
|
||||
assert_eq!(raised.data[1], [0.5; 4]);
|
||||
|
||||
// The difference across a flat color is nothing, which the offset lifts to middle gray
|
||||
let difference = convolve(&line, &line, &Convolution::custom(&[-1., 0., 1.], 3, 2., 255. / 2.), DMat2::IDENTITY);
|
||||
assert_eq!(difference.data[1], [0.25, 0.25, 0.25, 0.5]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colors_continue_past_the_edges_from_the_nearest_visible_pixel() {
|
||||
let red = [1., 0., 0., 1.];
|
||||
let faint_blue = [0., 0., 0.01, 0.01];
|
||||
let line = plane(5, 1, vec![[0.; 4], [0.; 4], red, faint_blue, [0.; 4]]);
|
||||
|
||||
// Averaging three neighbors at the edge reads the red beyond it rather than black, leaving the red as it is
|
||||
let averaged = convolve(&line, &line, &Convolution::custom(&[1., 1., 1.], 3, 3., 0.), DMat2::IDENTITY);
|
||||
assert!((averaged.data[2][0] - 1.).abs() < 1e-6, "{:?}", averaged.data[2]);
|
||||
// The faint pixel reads red rather than its own blue, keeping its own coverage
|
||||
let faint = averaged.data[3];
|
||||
assert!(faint[0] > 0. && faint[2] == 0. && faint[3] == 0.01, "{faint:?}");
|
||||
}
|
||||
|
||||
/// A white square of `inner` pixels in the middle of a transparent square of `outer` pixels.
|
||||
fn white_square(outer: usize, inner: std::ops::Range<usize>) -> Plane<[f32; 4]> {
|
||||
let mut square = Plane::new(outer, outer);
|
||||
for y in inner.clone() {
|
||||
square.data[y * outer + inner.start..y * outer + inner.end].fill([1.; 4]);
|
||||
}
|
||||
square
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn emboss_grays_flat_colors_and_shows_the_silhouette_in_relief() {
|
||||
let square = white_square(16, 4..12);
|
||||
let embossed = convolve(&square, &square, &Convolution::emboss(0., 2., 100.), DMat2::IDENTITY);
|
||||
let at = |x: usize| embossed.data[8 * 16 + x];
|
||||
|
||||
// The inside is flat, so it's middle gray
|
||||
assert_eq!(at(8), [0.5, 0.5, 0.5, 1.]);
|
||||
// Lit from the right, the right edge's white falls off to the gray beyond it, and the left edge rises from it
|
||||
assert!(at(11)[0] < 0.5 && at(4)[0] > 0.5, "{:?} {:?}", at(11), at(4));
|
||||
assert_eq!(at(2), [0.; 4], "nothing outside");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_edges_whitens_flat_colors_and_darkens_the_silhouette() {
|
||||
let square = white_square(16, 4..12);
|
||||
let edges = find_edges(&square, DMat2::IDENTITY);
|
||||
let at = |x: usize, y: usize| edges.data[y * 16 + x];
|
||||
|
||||
assert_eq!(at(8, 8), [1.; 4]);
|
||||
// Over white, the white square's edge has no contrast, so it stays white
|
||||
assert_eq!(at(4, 8), [1.; 4]);
|
||||
|
||||
// A black square's edge against the white it's matted over is dark
|
||||
let black = white_square(16, 4..12).map(|[_, _, _, alpha]| [0., 0., 0., alpha]);
|
||||
let edges = find_edges(&black, DMat2::IDENTITY);
|
||||
assert_eq!(edges.data[8 * 16 + 4], [0., 0., 0., 1.]);
|
||||
assert_eq!(edges.data[8 * 16 + 8], [1.; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighborhood_maximum_spreads_light_colors_as_coverage_shrinks() {
|
||||
let mut square = white_square(16, 2..14);
|
||||
square.data[8 * 16 + 8] = [0., 0., 0., 1.];
|
||||
|
||||
let maximum = neighborhood_extreme(&square, 1., true, DMat2::IDENTITY);
|
||||
assert_eq!(maximum.data[8 * 16 + 8], [1.; 4], "the dark pixel takes its lighter neighbors' color");
|
||||
assert_eq!(maximum.data[8 * 16 + 2], [0.; 4], "the coverage shrinks by the radius");
|
||||
assert_eq!(maximum.data[8 * 16 + 3], [1.; 4]);
|
||||
|
||||
let minimum = neighborhood_extreme(&square, 1., false, DMat2::IDENTITY);
|
||||
assert_eq!(minimum.data[9 * 16 + 9], [0., 0., 0., 1.], "the dark pixel spreads");
|
||||
assert_eq!(minimum.data[8 * 16 + 1], [1.; 4], "the coverage grows by the radius, with the colors beyond taking no part");
|
||||
|
||||
// Half a radius more mixes halfway toward the next
|
||||
let between = neighborhood_extreme(&square, 1.5, false, DMat2::IDENTITY);
|
||||
assert_eq!(between.data[9 * 16 + 9], [0., 0., 0., 1.]);
|
||||
assert_eq!(between.data[10 * 16 + 10], [0.5, 0.5, 0.5, 1.]);
|
||||
assert_eq!(between.data[8 * 16], [0.5; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn neighborhood_extremes_keep_faint_colors_and_a_zero_radius_changes_nothing() {
|
||||
// A faint red block keeps its color at its own coverage, rather than taking either extreme's identity
|
||||
let mut faint = plane(7, 7, vec![[0.; 4]; 49]);
|
||||
for y in 1..6 {
|
||||
faint.data[y * 7 + 1..y * 7 + 6].fill([0.04, 0., 0., 0.04]);
|
||||
}
|
||||
for maximum in [true, false] {
|
||||
let extreme = neighborhood_extreme(&faint, 1., maximum, DMat2::IDENTITY);
|
||||
let [red, green, blue, alpha] = extreme.data[3 * 7 + 3];
|
||||
assert!(
|
||||
(red - 0.04).abs() < 1e-6 && green.abs() < 1e-6 && blue.abs() < 1e-6 && (alpha - 0.04).abs() < 1e-6,
|
||||
"{:?}",
|
||||
extreme.data[3 * 7 + 3]
|
||||
);
|
||||
|
||||
assert_eq!(neighborhood_extreme(&faint, 0., maximum, DMat2::IDENTITY).data, faint.data);
|
||||
}
|
||||
|
||||
// At twice the zoom, a radius of one document pixel reaches two pixels
|
||||
let mut dot = plane(9, 9, vec![[1.; 4]; 81]);
|
||||
dot.data[4 * 9 + 4] = [0., 0., 0., 1.];
|
||||
let spread = neighborhood_extreme(&dot, 1., false, DMat2::from_diagonal(DVec2::splat(2.)));
|
||||
assert_eq!(spread.data[2 * 9 + 6], [0., 0., 0., 1.]);
|
||||
assert_eq!(spread.data[9 + 4], [1.; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fill_fades_sharpened_coverage_evenly() {
|
||||
// Sharpening the faded square alone would overshoot at its edge, where the full-strength square's clamp at full coverage hides it
|
||||
let square = white_square(16, 4..12);
|
||||
let faded = square.map(|pixel| pixel.map(|channel| channel * 0.5));
|
||||
let sharpen = |plane: &Plane<[f32; 4]>| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((1., 0.)), DMat2::IDENTITY);
|
||||
assert!(sharpen(&faded).data.iter().any(|pixel| pixel[3] > 0.5));
|
||||
|
||||
let result = faded_by_shares(&sharpen(&faded), &sharpen(&square), &fill_shares(&square, &faded));
|
||||
assert!(result.data.iter().all(|pixel| pixel[3] == 0. || pixel[3] == 0.5), "{:?}", result.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn window_extremes_match_a_direct_search() {
|
||||
let values: Vec<[f32; 4]> = (0..37).map(|index| [((index * 7919) % 31) as f32; 4]).collect();
|
||||
for radius in [1, 2, 5, 40] {
|
||||
let mut fast = vec![[0.; 4]; values.len()];
|
||||
window_extremes(&values, &mut fast, radius, [-1.; 4], |first, second| std::array::from_fn(|channel| first[channel].max(second[channel])));
|
||||
|
||||
for (index, value) in fast.iter().enumerate() {
|
||||
let window = (index as isize - radius as isize)..=(index as isize + radius as isize);
|
||||
let direct = window.map(|at| values.get(at as usize).filter(|_| at >= 0).map_or(-1., |value| value[0])).fold(f32::MIN, f32::max);
|
||||
assert_eq!(value[0], direct, "radius {radius} at {index}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsharp_masking_exaggerates_differences_past_its_threshold() {
|
||||
// A gray line with a lighter middle, a step the blur softens
|
||||
let mut line = plane(9, 1, vec![[0.5, 0.5, 0.5, 1.]; 9]);
|
||||
line.data[4] = [0.6, 0.6, 0.6, 1.];
|
||||
|
||||
let gaussian = UnsharpBlur::Gaussian(1.);
|
||||
let sharpened = unsharp_mask(&line, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||
assert!(sharpened.data[4][0] > 0.6 && sharpened.data[3][0] < 0.5, "{:?}", sharpened.data);
|
||||
assert_eq!(sharpened.data[4][3], 1., "full coverage stays full");
|
||||
|
||||
// A threshold past the exaggerated difference leaves every pixel as it is
|
||||
let untouched = unsharp_mask(&line, &line, gaussian, Some((1., 0.2)), DMat2::IDENTITY);
|
||||
assert_eq!(untouched.data, line.data);
|
||||
|
||||
// A high pass of a flat color is middle gray
|
||||
let flat = plane(5, 1, vec![[0.3, 0.3, 0.3, 1.]; 5]);
|
||||
assert_eq!(
|
||||
unsharp_mask(&flat, &flat, UnsharpBlur::Gaussian(2.), None, DMat2::IDENTITY).data[2],
|
||||
[HIGH_PASS_GRAY, HIGH_PASS_GRAY, HIGH_PASS_GRAY, 1.]
|
||||
);
|
||||
|
||||
// A fill faint enough to fall below the visible threshold still averages the colors the full-strength content shows
|
||||
let faint = line.map(|pixel| pixel.map(|channel| channel * 0.05));
|
||||
let faint_sharpened = unsharp_mask(&faint, &line, gaussian, Some((1., 0.)), DMat2::IDENTITY);
|
||||
let straight = |pixel: [f32; 4]| pixel[0] / pixel[3];
|
||||
assert!((straight(faint_sharpened.data[4]) - straight(sharpened.data[4])).abs() < 1e-4, "{:?}", faint_sharpened.data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edges_only_sharpens_against_the_neighbors_as_far_as_an_edge_runs_through() {
|
||||
// A gray step up by `height` between columns, across which the Sobel gradient is four times as long, read along the middle row
|
||||
let step = |height: f32| {
|
||||
let mut columns = plane(6, 3, vec![[0.4, 0.4, 0.4, 1.]; 18]);
|
||||
(0..3).for_each(|y| (3..6).for_each(|x| columns.data[y * 6 + x] = [0.4 + height, 0.4 + height, 0.4 + height, 1.]));
|
||||
columns
|
||||
};
|
||||
let sharpen = |plane: &Plane<[f32; 4]>, amount: f32, threshold: f32| unsharp_mask(plane, plane, UnsharpBlur::EdgeNeighbors, Some((amount, threshold)), DMat2::IDENTITY).data;
|
||||
let close = |actual: f32, expected: f32| (actual - expected).abs() < 1e-5;
|
||||
|
||||
// A strong step sharpens fully, each side moving by its difference from its four neighbors' average, a quarter of the step, while flat areas stay
|
||||
let strong = sharpen(&step(0.4), 1., 0.);
|
||||
assert!(close(strong[8][0], 0.3) && close(strong[9][0], 0.9) && close(strong[7][0], 0.4), "{strong:?}");
|
||||
|
||||
// A step under a sixteenth of full contrast stays as it is, and one of an eighth sharpens a third as much
|
||||
assert!(close(sharpen(&step(0.05), 1., 0.)[8][0], 0.4));
|
||||
assert!(close(sharpen(&step(0.125), 1., 0.)[8][0], 0.4 - 0.125 / 4. / 3.));
|
||||
|
||||
// The threshold softens the change, which half the amount halves
|
||||
assert!(close(sharpen(&step(0.4), 1., 0.05)[8][0], 0.35));
|
||||
assert!(close(sharpen(&step(0.4), 0.5, 0.)[8][0], 0.35));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_applied_to_alpha_weighs_the_coverage_too() {
|
||||
let mut line = plane(5, 1, vec![[0.; 4]; 5]);
|
||||
line.data[2] = [0.6, 0.3, 0., 1.];
|
||||
let average = Convolution::custom(&[1., 1., 1.], 3, 3., 0.);
|
||||
|
||||
// Averaged with its neighbors, the coverage of a lone pixel spreads a third of itself to each side
|
||||
let spread = convolve(
|
||||
&line,
|
||||
&line,
|
||||
&Convolution {
|
||||
weighs_coverage: true,
|
||||
..average.clone()
|
||||
},
|
||||
DMat2::IDENTITY,
|
||||
);
|
||||
let alphas: Vec<f32> = spread.data.iter().map(|pixel| pixel[3]).collect();
|
||||
assert!(alphas.iter().zip([0., 1., 1., 1., 0.]).all(|(alpha, thirds)| (alpha - thirds / 3.).abs() < 1e-6), "{alphas:?}");
|
||||
|
||||
// Otherwise, the coverage stays as it is
|
||||
let kept = convolve(&line, &line, &average, DMat2::IDENTITY);
|
||||
assert!(kept.data.iter().zip(&line.data).all(|(kept, line)| kept[3] == line[3]));
|
||||
}
|
||||
|
||||
/// The mean and standard deviation of each color's offset from middle gray, and the correlation between the first two colors' offsets.
|
||||
fn offset_statistics(noisy: &Plane<[f32; 4]>) -> ([f64; 3], [f64; 3], f64) {
|
||||
let count = noisy.data.len() as f64;
|
||||
let offsets: Vec<[f64; 3]> = noisy.data.iter().map(|pixel| std::array::from_fn(|channel| pixel[channel] as f64 / pixel[3] as f64 - 0.5)).collect();
|
||||
let mean: [f64; 3] = std::array::from_fn(|channel| offsets.iter().map(|offset| offset[channel]).sum::<f64>() / count);
|
||||
let deviation: [f64; 3] = std::array::from_fn(|channel| (offsets.iter().map(|offset| (offset[channel] - mean[channel]).powi(2)).sum::<f64>() / count).sqrt());
|
||||
let covariance = offsets.iter().map(|offset| (offset[0] - mean[0]) * (offset[1] - mean[1])).sum::<f64>() / count;
|
||||
(mean, deviation, covariance / (deviation[0] * deviation[1]))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_follows_its_distribution_independently_for_each_color() {
|
||||
let gray = plane(256, 256, vec![[0.5, 0.5, 0.5, 1.]; 256 * 256]);
|
||||
let amount = 0.2;
|
||||
|
||||
// Uniform noise spreads evenly up to the amount, with a deviation of the amount over √3
|
||||
let uniform = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 0, DAffine2::IDENTITY);
|
||||
let (mean, deviation, correlation) = offset_statistics(&uniform);
|
||||
for channel in 0..3 {
|
||||
assert!(
|
||||
mean[channel].abs() < 0.002 && (deviation[channel] / (amount / 3_f64.sqrt()) - 1.).abs() < 0.02,
|
||||
"{mean:?} {deviation:?}"
|
||||
);
|
||||
}
|
||||
assert!(correlation.abs() < 0.02, "{correlation}");
|
||||
assert!(uniform.data.iter().all(|pixel| (pixel[0] - 0.5).abs() <= amount as f32 && pixel[3] == 1.));
|
||||
|
||||
// Gaussian noise deviates by the amount, cut off at its limit
|
||||
let gaussian = add_noise(&gray, amount, NoiseDistribution::Gaussian, false, 0, DAffine2::IDENTITY);
|
||||
let (_, deviation, _) = offset_statistics(&gaussian);
|
||||
assert!((deviation[0] / amount - 1.).abs() < 0.03, "{deviation:?}");
|
||||
|
||||
// Monochromatic noise shifts every color of a pixel together, and another seed gives other noise
|
||||
let monochromatic = add_noise(&gray, amount, NoiseDistribution::Gaussian, true, 0, DAffine2::IDENTITY);
|
||||
assert!(monochromatic.data.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2]));
|
||||
let reseeded = add_noise(&gray, amount, NoiseDistribution::Uniform, false, 1, DAffine2::IDENTITY);
|
||||
assert_ne!(reseeded.data[..64], uniform.data[..64]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_is_fixed_to_the_effect_spaces_cells_and_averages_where_pixels_span_several() {
|
||||
let gray = |size: usize| plane(size, size, vec![[0.5, 0.5, 0.5, 1.]; size * size]);
|
||||
let noise = |plane: &Plane<[f32; 4]>, pixels_to_effect| add_noise(plane, 0.3, NoiseDistribution::Uniform, false, 4, pixels_to_effect);
|
||||
|
||||
// A plane placed three cells right and five down holds the same noise at the same cells
|
||||
let placed = noise(&gray(16), DAffine2::IDENTITY);
|
||||
let moved = noise(&gray(16), DAffine2::from_translation(DVec2::new(3., 5.)));
|
||||
assert_eq!(moved.data[0], placed.data[5 * 16 + 3]);
|
||||
assert_eq!(moved.data[16 + 2], placed.data[6 * 16 + 5]);
|
||||
|
||||
// Pixels spanning eight cells each deviate as an average over all 64 would, an eighth as much
|
||||
let zoomed_out = noise(&gray(128), DAffine2::from_scale(DVec2::splat(8.)));
|
||||
let (_, deviation, _) = offset_statistics(&zoomed_out);
|
||||
assert!((deviation[0] / (0.3 / 3_f64.sqrt() / 8.) - 1.).abs() < 0.05, "{deviation:?}");
|
||||
|
||||
// Pixels at exactly one cell each take one sample, like zoomed in
|
||||
assert_eq!(FieldSampling::new(DAffine2::IDENTITY).counts, glam::UVec2::ONE);
|
||||
assert_eq!(FieldSampling::new(DAffine2::from_scale(DVec2::splat(0.25))).counts, glam::UVec2::ONE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dissolve_shows_opaque_pixels_by_the_opacity_and_the_coverage() {
|
||||
let shown_share = |plane: &Plane<[f32; 4]>| plane.data.iter().filter(|pixel| pixel[3] > 0.).count() as f64 / plane.data.len() as f64;
|
||||
let red = |alpha: f32| plane(256, 256, vec![[alpha, 0., 0., alpha]; 256 * 256]);
|
||||
|
||||
// Where the content is opaque, the opacity's share shows, and a larger opacity shows those and more
|
||||
let some = dissolve(&red(1.), 0.3, 0, DAffine2::IDENTITY);
|
||||
let more = dissolve(&red(1.), 0.6, 0, DAffine2::IDENTITY);
|
||||
assert!((shown_share(&some) - 0.3).abs() < 0.01 && (shown_share(&more) - 0.6).abs() < 0.01);
|
||||
assert!(some.data.iter().zip(&more.data).all(|(some, more)| some[3] <= more[3]));
|
||||
|
||||
// Half-covered content shows half as much, each shown pixel fully opaque in its straight color
|
||||
let half = dissolve(&red(0.5), 1., 0, DAffine2::IDENTITY);
|
||||
assert!((shown_share(&half) - 127. / 255.).abs() < 0.01, "{}", shown_share(&half));
|
||||
assert!(half.data.iter().all(|pixel| *pixel == [0.; 4] || *pixel == [1., 0., 0., 1.]));
|
||||
|
||||
// Pixels spanning several cells show the share of them passing the opacity
|
||||
let zoomed_out = dissolve(&red(1.), 0.3, 0, DAffine2::from_scale(DVec2::splat(2.)));
|
||||
let average = zoomed_out.data.iter().map(|pixel| pixel[3] as f64).sum::<f64>() / zoomed_out.data.len() as f64;
|
||||
assert!((average - 0.3).abs() < 0.01 && zoomed_out.data.iter().any(|pixel| pixel[3] == 0.5), "{average}");
|
||||
|
||||
// For PSD interop, the opacity and the coverage pass thresholds of their own, so equal products show different pixels, neither set holding the other
|
||||
let quarter = dissolve(&red(64. / 255.), 1., 0, DAffine2::IDENTITY);
|
||||
let half_at_half = dissolve(&red(128. / 255.), 0.5, 0, DAffine2::IDENTITY);
|
||||
let only_in = |first: &Plane<[f32; 4]>, second: &Plane<[f32; 4]>| first.data.iter().zip(&second.data).filter(|(first, second)| first[3] > 0. && second[3] <= 0.).count();
|
||||
assert!(only_in(&quarter, &half_at_half) > 1000 && only_in(&half_at_half, &quarter) > 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_values_lie_strictly_between_zero_and_one() {
|
||||
assert!(unit_interval(u32::MAX) < 1. && unit_interval(0) > 0.);
|
||||
}
|
||||
}
|
||||
@@ -176,7 +176,7 @@ fn white_noise(seed: i32, cell: IVec2) -> 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] {
|
||||
pub(crate) 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));
|
||||
|
||||
@@ -5,12 +5,14 @@ pub mod adjustments;
|
||||
mod blending;
|
||||
pub mod color_lookup_table;
|
||||
pub mod effect_kernels;
|
||||
pub mod filter_kernels;
|
||||
pub mod generators;
|
||||
mod kernel;
|
||||
pub mod layer_blending;
|
||||
pub mod mandelbrot;
|
||||
mod masks;
|
||||
pub mod masks;
|
||||
pub mod raster_effects;
|
||||
pub mod resample_kernels;
|
||||
pub mod value_effects;
|
||||
|
||||
pub use kernel::*;
|
||||
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user