mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-01 07:24:56 -10:00
Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
460d66cdab | ||
|
|
4f0d8c7f4c | ||
|
|
1335e9a0f8 | ||
|
|
89238b669a | ||
|
|
da2c5a2d13 | ||
|
|
c75ebbd143 | ||
|
|
addba860d3 | ||
|
|
9526711aa2 | ||
|
|
d8b9f67adb | ||
|
|
b149248db9 | ||
|
|
7b4dc4d8a7 | ||
|
|
feea64170a | ||
|
|
6541449a4a | ||
|
|
5e92356578 | ||
|
|
3ca1376f93 | ||
|
|
93d2738a23 | ||
|
|
9557c6adfc | ||
|
|
6c3232ee8c |
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
+2
@@ -590,6 +590,7 @@ dependencies = [
|
||||
"node-macro",
|
||||
"raster-kernels",
|
||||
"serde",
|
||||
"text-nodes",
|
||||
"vector-types",
|
||||
]
|
||||
|
||||
@@ -5745,6 +5746,7 @@ dependencies = [
|
||||
"glam",
|
||||
"graphene-resource",
|
||||
"graphic-types",
|
||||
"half",
|
||||
"log",
|
||||
"raster-types",
|
||||
"thiserror 2.0.21",
|
||||
|
||||
@@ -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,9 @@ 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 radial_blur_v1;
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
use migration_core::{Inputs, MigrationError, Node, NodeInput, encode, literal_of, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
const CENTER: u32 = 3;
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration reads and writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
DVec2([f64; 2]),
|
||||
DAffine2([f64; 6]),
|
||||
}
|
||||
|
||||
/// 'Radial Blur' takes a transform placing a circle in place of its center, which the transform's translation keeps.
|
||||
/// A wired center can't be read before it runs, so it becomes the identity, the circle at the content's origin.
|
||||
#[migration("blending_nodes::distortions::RadialBlurNode"@1 => @2)]
|
||||
pub fn radial_blur_v1(node: &Node, inputs: &mut Inputs) -> Result<(), MigrationError> {
|
||||
let Some(center) = node.inputs().get(CENTER as usize) else {
|
||||
return Err(MigrationError::invariant("Radial Blur has a Center input"));
|
||||
};
|
||||
|
||||
inputs.set(CENTER, transform_input(¢er.input));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The transform input placing the circle at the old `center`, shown in the graph if it was exposed or wired.
|
||||
fn transform_input(center: &NodeInput) -> NodeInput {
|
||||
let ([x, y], exposed) = match center {
|
||||
NodeInput::Value { exposed, .. } => match literal_of::<Tagged>(center) {
|
||||
Some(Tagged::DVec2(center)) => (center, *exposed),
|
||||
_ => ([0., 0.], *exposed),
|
||||
},
|
||||
_ => ([0., 0.], true),
|
||||
};
|
||||
|
||||
NodeInput::Value {
|
||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., x, y])),
|
||||
exposed,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::{decl, literal};
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
const CENTER_SLOT: usize = CENTER as usize;
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(5, |random, slot| match slot {
|
||||
CENTER_SLOT => literal(Tagged::DVec2([random.below(10) as f64, random.below(10) as f64])),
|
||||
_ => literal(random.below(10) as f64),
|
||||
})
|
||||
}
|
||||
|
||||
fn radial_blur_inputs(center: NodeInput) -> Vec<NodeInput> {
|
||||
let mut inputs: Vec<_> = (0..5).map(|index| literal(index as f64)).collect();
|
||||
inputs[CENTER_SLOT] = center;
|
||||
inputs
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&RadialBlurV1, &contract());
|
||||
check_undo(&RadialBlurV1, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_center_becomes_the_translation_of_the_transform_in_its_place() {
|
||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(literal(Tagged::DVec2([12.5, -4.]))));
|
||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||
|
||||
let expected = radial_blur_inputs(literal(Tagged::DAffine2([1., 0., 0., 1., 12.5, -4.])));
|
||||
assert_eq!(fixture.declaration_of(&migrated, radial_blur), Some(decl!("blending_nodes::distortions::RadialBlurNode"@2)));
|
||||
assert_eq!(fixture.inputs(&migrated, radial_blur), expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wired_center_becomes_the_identity_shown_in_the_graph() {
|
||||
let mut fixture = Fixture::new(&RadialBlurV1);
|
||||
let source = fixture.add(decl!("migration_testing::consumer"@1), Vec::new());
|
||||
let radial_blur = fixture.add(decl!("blending_nodes::distortions::RadialBlurNode"@1), radial_blur_inputs(NodeInput::Node { id: source, index: 0 }));
|
||||
let migrated = fixture.migrate(&RadialBlurV1).unwrap();
|
||||
|
||||
let identity = NodeInput::Value {
|
||||
value: encode(&Tagged::DAffine2([1., 0., 0., 1., 0., 0.])),
|
||||
exposed: true,
|
||||
};
|
||||
assert_eq!(fixture.inputs(&migrated, radial_blur), radial_blur_inputs(identity));
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,8 +35,9 @@ 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 graphene_std::{DisplaceMode, RadialBlurMethod, SpherizeMode, WaveType};
|
||||
use kurbo::BezPath;
|
||||
use std::any::Any;
|
||||
use std::ops::Range;
|
||||
@@ -1271,16 +1272,22 @@ impl_table_item_layout_for_choice_enum!(
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
BevelStyle,
|
||||
RadialBlurMethod,
|
||||
SpherizeMode,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
EffectKind,
|
||||
Generator,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
GradientForm,
|
||||
GradientSpread,
|
||||
GradientSpace,
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
@@ -1456,9 +1463,14 @@ macro_rules! known_item_types {
|
||||
EffectKind,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
RadialBlurMethod,
|
||||
SpherizeMode,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
DashPattern,
|
||||
BoxCorners,
|
||||
TransferCurve,
|
||||
@@ -1469,6 +1481,7 @@ macro_rules! known_item_types {
|
||||
GradientHueDirection,
|
||||
GradientInterpolation,
|
||||
GlowTechnique,
|
||||
NoiseDistribution,
|
||||
StrokeJoin,
|
||||
StrokeAlign,
|
||||
StrokeCap,
|
||||
|
||||
@@ -10,7 +10,7 @@ use crate::messages::portfolio::document::utility_types::misc::{AlignAggregate,
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{ChainNodeCopy, NodeTemplate};
|
||||
use crate::messages::portfolio::utility_types::PanelType;
|
||||
use crate::messages::prelude::*;
|
||||
use glam::{DAffine2, IVec2, UVec2};
|
||||
use glam::{DAffine2, DVec2, IVec2, UVec2};
|
||||
use graph_craft::document::NodeId;
|
||||
use graphene_std::Appearance;
|
||||
use graphene_std::list::Item;
|
||||
@@ -334,6 +334,7 @@ pub enum DocumentMessage {
|
||||
},
|
||||
UpdateEffectsReach {
|
||||
effects_reach: HashMap<NodeId, f64>,
|
||||
effects_frames: HashMap<NodeId, [DVec2; 2]>,
|
||||
},
|
||||
Undo,
|
||||
UngroupSelectedLayers,
|
||||
|
||||
@@ -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 {
|
||||
@@ -1945,13 +1952,20 @@ impl MessageHandler<DocumentMessage, DocumentMessageContext<'_>> for DocumentMes
|
||||
.collect();
|
||||
self.network_interface.update_appearance_attributes(layer_appearance_attributes);
|
||||
}
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach } => {
|
||||
DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames } => {
|
||||
let is_document_layer = |node_id: &NodeId| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]);
|
||||
|
||||
let layer_effects_reach = effects_reach
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| self.network_interface.document_network().nodes.contains_key(node_id) && self.network_interface.is_layer(node_id, &[]))
|
||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||
.map(|(node_id, reach)| (LayerNodeIdentifier::new(node_id, &self.network_interface), reach))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach);
|
||||
let layer_effects_frames = effects_frames
|
||||
.into_iter()
|
||||
.filter(|(node_id, _)| is_document_layer(node_id))
|
||||
.map(|(node_id, frames)| (LayerNodeIdentifier::new(node_id, &self.network_interface), frames))
|
||||
.collect();
|
||||
self.network_interface.update_effects_reach(layer_effects_reach, layer_effects_frames);
|
||||
}
|
||||
DocumentMessage::Undo => {
|
||||
if self.network_interface.transaction_status() != TransactionStatus::Finished || self.end_history_preview(viewport, responses).is_some() {
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
#[cfg(test)]
|
||||
mod clipping_tests;
|
||||
#[cfg(test)]
|
||||
pub(crate) mod document_diff;
|
||||
mod document_history;
|
||||
mod document_message;
|
||||
|
||||
@@ -139,18 +139,6 @@ static DOCUMENT_NODE_TYPES: once_cell::sync::Lazy<HashMap<DefinitionIdentifier,
|
||||
/// Only the position can be set for protonodes within a definition. The rest of the metadata comes from the node macro in NODE_METADATA
|
||||
fn document_node_definitions() -> HashMap<DefinitionIdentifier, DocumentNodeDefinition> {
|
||||
let custom = vec![
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Custom Node",
|
||||
version: 1,
|
||||
category: "Routing",
|
||||
icon: Some("NodeCustomNode"),
|
||||
node_template: NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
},
|
||||
description: Cow::Borrowed("An empty node network you can use to create your own custom nodes."),
|
||||
inspector: None,
|
||||
},
|
||||
DocumentNodeDefinition {
|
||||
identifier: "Merge",
|
||||
version: 1,
|
||||
@@ -701,6 +689,8 @@ 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.insert("displace_inspector".to_string(), Box::new(node_inspector::displace_inspector));
|
||||
map
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,11 @@ pub enum NodeGraphMessage {
|
||||
xy: Option<(i32, i32)>,
|
||||
add_transaction: bool,
|
||||
},
|
||||
/// Adds a subgraph with nothing in it, at the given grid position or else in view, and selects it.
|
||||
CreateEmptySubgraph {
|
||||
node_id: Option<NodeId>,
|
||||
xy: Option<(i32, i32)>,
|
||||
},
|
||||
CreateWire {
|
||||
output_connector: OutputConnector,
|
||||
input_connector: InputConnector,
|
||||
@@ -202,8 +207,6 @@ pub enum NodeGraphMessage {
|
||||
SelectedNodesSet {
|
||||
nodes: Vec<NodeId>,
|
||||
},
|
||||
SendClickTargets,
|
||||
EndSendClickTargets,
|
||||
UnloadWires,
|
||||
SendWires,
|
||||
UpdateVisibleNodes,
|
||||
@@ -383,6 +386,7 @@ impl NodeGraphMessage {
|
||||
| Self::SetImportExportDescriptionImpl { .. } => Some(breadcrumb_network_path),
|
||||
Self::AddNodes { .. }
|
||||
| Self::CreateNodeFromContextMenu { .. }
|
||||
| Self::CreateEmptySubgraph { .. }
|
||||
| Self::CreateWire { .. }
|
||||
| Self::CreateWires { .. }
|
||||
| Self::ConnectUpstreamOutputToInput { .. }
|
||||
@@ -442,8 +446,6 @@ impl NodeGraphMessage {
|
||||
| Self::SelectedNodesAdd { .. }
|
||||
| Self::SelectedNodesRemove { .. }
|
||||
| Self::SelectedNodesSet { .. }
|
||||
| Self::SendClickTargets
|
||||
| Self::EndSendClickTargets
|
||||
| Self::UnloadWires
|
||||
| Self::SendWires
|
||||
| Self::UpdateVisibleNodes
|
||||
|
||||
@@ -5,13 +5,14 @@ use crate::messages::input_mapper::utility_types::macros::{action_shortcut, acti
|
||||
use crate::messages::layout::utility_types::widget_prelude::*;
|
||||
use crate::messages::portfolio::document::document_message_handler::navigation_controls;
|
||||
use crate::messages::portfolio::document::graph_operation::utility_types::ModifyInputsContext;
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{DefinitionIdentifier, NodeInspectorContext, resolve_document_node_type};
|
||||
use crate::messages::portfolio::document::node_graph::utility_types::{ContextMenuData, FrontendGraphDataType, NodeEvaluationError, NodeGraphErrorDiagnostic};
|
||||
use crate::messages::portfolio::document::utility_types::document_metadata::LayerNodeIdentifier;
|
||||
use crate::messages::portfolio::document::utility_types::layers_in_view::LayersInView;
|
||||
use crate::messages::portfolio::document::utility_types::misc::GroupFolderType;
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::{
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint, TransactionStatus,
|
||||
self, FlowType, GlideOffsets, ImportOrExport, InputConnector, LayerClickTargetTypes, NodeNetworkInterface, NodeTemplate, NodeTypePersistentMetadata, OutputConnector, TransactionCheckpoint,
|
||||
TransactionStatus,
|
||||
};
|
||||
use crate::messages::portfolio::document::utility_types::nodes::{CollapsedLayers, LayerPanelChainInsertion, LayerPanelChainNode, LayerPanelEntry};
|
||||
use crate::messages::portfolio::document::utility_types::wires::{GraphWireStyle, WirePath, WirePathUpdate, build_vector_wire};
|
||||
@@ -422,6 +423,23 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
});
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::CreateEmptySubgraph { node_id, xy } => {
|
||||
let node_id = node_id.unwrap_or_else(NodeId::new);
|
||||
let (x, y) = xy.unwrap_or_else(|| {
|
||||
network_interface
|
||||
.node_graph_ptz(breadcrumb_network_path)
|
||||
.map_or((0, 0), |ptz| ((-ptz.pan.x / GRID_SIZE as f64) as i32, (-ptz.pan.y / GRID_SIZE as f64) as i32))
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id,
|
||||
node_template: Box::new(NodeTemplate::empty_subgraph()),
|
||||
});
|
||||
responses.add(NodeGraphMessage::ShiftNodePosition { node_id, x, y });
|
||||
responses.add(NodeGraphMessage::SelectedNodesSet { nodes: vec![node_id] });
|
||||
responses.add(NodeGraphMessage::SendGraph);
|
||||
}
|
||||
NodeGraphMessage::ConnectUpstreamOutputToInput { downstream_input, input_connector } => {
|
||||
let Some(upstream_node) = network_interface.upstream_output_connector(&downstream_input, selection_network_path) else {
|
||||
log::error!("Failed to find upstream node for downstream_input");
|
||||
@@ -769,24 +787,19 @@ impl<'a> MessageHandler<NodeGraphMessage, NodeGraphMessageContext<'a>> for NodeG
|
||||
}
|
||||
}
|
||||
|
||||
// Use the network interface to add a default node, then set the imports, exports, paste the nodes inside, and connect them to the imports/exports
|
||||
// Add an empty subgraph, then set its imports and exports, paste the nodes inside, and connect them to the imports and exports
|
||||
let encapsulating_node_id = NodeId::new();
|
||||
let mut default_node_template = resolve_network_node_type("Custom Node").expect("Custom Node should exist").default_node_template();
|
||||
let mut subgraph_template = NodeTemplate::empty_subgraph();
|
||||
let Some(center_of_selected_nodes) = network_interface.selected_nodes_bounding_box(breadcrumb_network_path).map(|[a, b]| (a + b) / 2.) else {
|
||||
log::error!("Could not get center of selected_nodes");
|
||||
return;
|
||||
};
|
||||
let center_of_selected_nodes_grid_space = IVec2::new((center_of_selected_nodes.x / 24. + 0.5).floor() as i32, (center_of_selected_nodes.y / 24. + 0.5).floor() as i32);
|
||||
default_node_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
subgraph_template.node_type_metadata = NodeTypePersistentMetadata::node(center_of_selected_nodes_grid_space - IVec2::new(3, 1));
|
||||
responses.add(DocumentMessage::AddTransaction);
|
||||
responses.add(NodeGraphMessage::InsertNode {
|
||||
node_id: encapsulating_node_id,
|
||||
node_template: Box::new(default_node_template),
|
||||
});
|
||||
responses.add(NodeGraphMessage::SetDisplayNameImpl {
|
||||
node_id: encapsulating_node_id,
|
||||
network_path: selection_network_path.to_vec(),
|
||||
alias: "Untitled Node".to_string(),
|
||||
node_template: Box::new(subgraph_template),
|
||||
});
|
||||
|
||||
responses.add(DocumentMessage::EnterNestedNetwork { node_id: encapsulating_node_id });
|
||||
@@ -2012,10 +2025,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);
|
||||
@@ -3198,11 +3207,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,
|
||||
@@ -3426,6 +3430,13 @@ impl NodeGraphMessageHandler {
|
||||
})
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
TextButton::new("New Custom Node")
|
||||
.tooltip_label("New Custom Node")
|
||||
.tooltip_description("Add an empty subgraph, which can be entered to build a node of your own out of other nodes.")
|
||||
.on_update(|_| NodeGraphMessage::CreateEmptySubgraph { node_id: None, xy: None }.into())
|
||||
.disabled(read_only)
|
||||
.widget_instance(),
|
||||
//
|
||||
Separator::new(SeparatorStyle::Unrelated).widget_instance(),
|
||||
//
|
||||
|
||||
@@ -40,7 +40,8 @@ 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::{DisplaceMode, RadialBlurMethod, SpherizeMode, WaveType};
|
||||
use graphene_std::{NodeParameter, ParameterRef};
|
||||
use math_parser::parser::{MessagePart, ParseError};
|
||||
use std::path::PathBuf;
|
||||
@@ -393,7 +394,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type,
|
||||
false => text_widget(default_info).into(),
|
||||
},
|
||||
Some(x) if id_is::<DVec2>(x) => vec2_widget(default_info, "X", "Y", unit.unwrap_or(""), None, false, false),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, &mut extra_widgets),
|
||||
Some(x) if id_is::<DAffine2>(x) => transform_widget(default_info, unit, &mut extra_widgets),
|
||||
Some(x) if id_is::<Color>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Gradient>(x) => color_widget(default_info, ColorInput::default().allow_none(false)),
|
||||
Some(x) if id_is::<Graphic>(x) => color_widget(default_info, ColorInput::default()),
|
||||
@@ -453,9 +454,15 @@ 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::<SpherizeMode>(x) => enum_choice::<SpherizeMode>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<WaveType>(x) => enum_choice::<WaveType>().for_socket(default_info).inspector_row(),
|
||||
Some(x) if id_is::<DisplaceMode>(x) => enum_choice::<DisplaceMode>().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(),
|
||||
@@ -786,8 +793,10 @@ pub fn footprint_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
last.clone()
|
||||
}
|
||||
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
/// The X, Y, rotation, W, and H of a transform input. W and H show as a multiplier, or with the parameter's `size_unit` (like " px") where it declares one, for a transform scaling a shape of unit size.
|
||||
pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, size_unit: Option<&str>, extra_widgets: &mut Vec<LayoutGroup>) -> LayoutGroup {
|
||||
let ParameterWidgetsInfo { document_node, node_id, index, .. } = parameter_widgets_info;
|
||||
let size_unit = size_unit.unwrap_or("x");
|
||||
|
||||
let mut location_widgets = start_widgets(¶meter_widgets_info);
|
||||
location_widgets.push(Separator::new(SeparatorStyle::Unrelated).widget_instance());
|
||||
@@ -854,7 +863,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
scale_widgets.extend_from_slice(&[
|
||||
NumberInput::new(Some(scale.x))
|
||||
.label("W")
|
||||
.unit("x")
|
||||
.unit(size_unit)
|
||||
.on_update(update_value_at_index(
|
||||
move |w: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(w.value.unwrap_or(scale.x), scale.y), rotation, translation) * skew_matrix;
|
||||
@@ -868,7 +877,7 @@ pub fn transform_widget(parameter_widgets_info: ParameterWidgetsInfo, extra_widg
|
||||
Separator::new(SeparatorStyle::Related).widget_instance(),
|
||||
NumberInput::new(Some(scale.y))
|
||||
.label("H")
|
||||
.unit("x")
|
||||
.unit(size_unit)
|
||||
.on_update(update_value_at_index(
|
||||
move |h: &NumberInput| {
|
||||
let transform = DAffine2::from_scale_angle_translation(DVec2::new(scale.x, h.value.unwrap_or(scale.y)), rotation, translation) * skew_matrix;
|
||||
@@ -3768,6 +3777,61 @@ 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(crate) fn displace_inspector(node_id: NodeId, context: &mut NodeInspectorContext) -> Vec<LayoutGroup> {
|
||||
use graphene_std::blending_nodes::distortions::displace::*;
|
||||
|
||||
// Each mode shows only the maps and distances it reads, and a wired mode shows both sets
|
||||
let mode = match get_document_node(node_id, context).ok().and_then(|document_node| document_node.input_value(ModeInput)) {
|
||||
Some(TaggedValue::DisplaceMode(mode)) => Some(*mode),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
let mut layout = vec![enum_choice::<DisplaceMode>().for_socket(ParameterWidgetsInfo::new(node_id, ModeInput, true, context)).inspector_row()];
|
||||
if !matches!(mode, Some(DisplaceMode::XAndY)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, DisplacementInput, true, context), ColorInput::default()));
|
||||
|
||||
let number_input = NumberInput::default().mode_range().unit("°").range_min(Some(-180.)).range_max(Some(180.));
|
||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, AngleInput, true, context), number_input)));
|
||||
|
||||
let number_input = NumberInput::default().unit(" px");
|
||||
layout.push(LayoutGroup::row(number_widget(ParameterWidgetsInfo::new(node_id, DistanceInput, true, context), number_input)));
|
||||
}
|
||||
if !matches!(mode, Some(DisplaceMode::Angle)) {
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, XDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(color_widget(ParameterWidgetsInfo::new(node_id, YDisplacementInput, true, context), ColorInput::default()));
|
||||
layout.push(vec2_widget(ParameterWidgetsInfo::new(node_id, OffsetInput, true, context), "X", "Y", " px", None, false, false));
|
||||
}
|
||||
|
||||
let edge_mode = enum_choice::<GradientSpread>()
|
||||
.for_socket(ParameterWidgetsInfo::new(node_id, EdgeModeInput, true, context))
|
||||
.inspector_row();
|
||||
layout.push(edge_mode);
|
||||
layout
|
||||
}
|
||||
|
||||
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() });
|
||||
|
||||
|
||||
@@ -53,6 +53,8 @@ pub struct DocumentMetadata {
|
||||
pub layer_appearance_attributes: HashMap<LayerNodeIdentifier, Arc<Appearance>>,
|
||||
/// How far each layer's effects paint past its content, in document pixels, for the layers with effects.
|
||||
pub layer_effects_reach: HashMap<LayerNodeIdentifier, f64>,
|
||||
/// The bounding box of the frames that each layer's effects paint anywhere in, in document pixels, for the layers with such effects.
|
||||
pub layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>,
|
||||
/// Transform from document space to viewport space.
|
||||
pub document_to_viewport: DAffine2,
|
||||
/// The transform from document space to viewport space that the latest render was made with, which is the one `upstream_footprints` include.
|
||||
@@ -364,7 +366,7 @@ impl DocumentMetadata {
|
||||
}
|
||||
|
||||
/// Get the bounding box of the specified layer in document space, expanded to include the actual rendered
|
||||
/// stroke geometry when the layer is a vector with a stroke style, and how far its effects paint past it. Only the first item of a
|
||||
/// stroke geometry when the layer is a vector with a stroke style, the frames its effects paint anywhere in, and how far they paint past it. Only the first item of a
|
||||
/// layer's vector data is recorded, so the others count through the click-target-based bounds, without their strokes.
|
||||
pub fn bounding_box_document_with_stroke_and_effects(&self, layer: LayerNodeIdentifier) -> Option<[DVec2; 2]> {
|
||||
let stroked = self.layer_vector_data.get(&layer).and_then(|item| {
|
||||
@@ -372,7 +374,8 @@ impl DocumentMetadata {
|
||||
let paths = paths_from_item_attributes(item.as_ref()).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, self.transform_to_document(layer), stroke.as_ref())
|
||||
});
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer)].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
let frames = self.layer_effects_frames.get(&layer).copied();
|
||||
let [min, max] = [stroked, self.bounding_box_document(layer), frames].into_iter().flatten().reduce(Quad::combine_bounds)?;
|
||||
|
||||
let reach = self.layer_effects_reach.get(&layer).copied().unwrap_or_default();
|
||||
Some([min - reach, max + reach])
|
||||
@@ -751,6 +754,25 @@ mod tests {
|
||||
assert_eq!((min.x, max.x), (0., 110.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounds_with_effects_hold_the_frames_the_effects_paint_in() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
let mut square = BezPath::new();
|
||||
square.move_to((-30., -30.));
|
||||
square.line_to((30., -30.));
|
||||
square.line_to((30., 30.));
|
||||
square.line_to((-30., 30.));
|
||||
square.close_path();
|
||||
|
||||
// A layer 30 across each way from its middle, with effects painting anywhere in a frame reaching 40 from it, and 2 past that
|
||||
let mut metadata = DocumentMetadata::default();
|
||||
metadata.click_targets.insert(layer, vec![Arc::new(ClickTarget::new_with_path(square, 0.))]);
|
||||
metadata.layer_effects_frames.insert(layer, [DVec2::splat(-40.), DVec2::splat(40.)]);
|
||||
metadata.layer_effects_reach.insert(layer, 2.);
|
||||
|
||||
assert_eq!(metadata.bounding_box_document_with_stroke_and_effects(layer), Some([DVec2::splat(-42.), DVec2::splat(42.)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_transform_as_rendered_stays_put_while_the_view_moves_on() {
|
||||
let layer = LayerNodeIdentifier::new_unchecked(NodeId(3));
|
||||
|
||||
@@ -52,7 +52,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),
|
||||
|
||||
@@ -475,7 +475,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 +523,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))
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -1,4 +1,4 @@
|
||||
use super::template::NodeTemplateImplementation;
|
||||
use super::template::{NodeTemplate, NodeTemplateImplementation};
|
||||
use super::{InputConnector, OutputConnector, catalog};
|
||||
use crate::messages::portfolio::document::node_graph::document_node_definitions::{network_node_identifiers, resolve_network_node_type};
|
||||
use crate::messages::portfolio::document::storage_tests::test_support::round_trip_through_gdd;
|
||||
@@ -308,7 +308,7 @@ async fn undoing_the_unlock_of_an_open_catalog_node_shows_it_read_only_again() {
|
||||
async fn undoing_the_creation_of_an_open_subgraph_leaves_it() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let subgraph = editor.create_node_by_name(DefinitionIdentifier::Network("Custom Node".to_string())).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.handle_message(DocumentMessage::EnterNestedNetwork { node_id: subgraph }).await;
|
||||
assert_eq!(editor.active_document().breadcrumb_network_path(), [subgraph]);
|
||||
|
||||
@@ -349,7 +349,7 @@ async fn a_subgraph_holding_a_catalog_node_pastes_into_a_document_without_it() {
|
||||
let custom = NodeId::new();
|
||||
let blend = NodeId::new();
|
||||
let interface = &mut editor.active_document_mut().network_interface;
|
||||
interface.insert_node(custom, resolve_network_node_type("Custom Node").expect("Custom Node").default_node_template(), &[]);
|
||||
interface.insert_node(custom, NodeTemplate::empty_subgraph(), &[]);
|
||||
interface.insert_node(blend, resolve_network_node_type("Blend").expect("Blend").default_node_template(), &[custom]);
|
||||
let DocumentNodeImplementation::Definition(shipped) = interface.document_node(&blend, &[custom]).expect("the Blend").implementation else {
|
||||
panic!("the Blend should name a table entry")
|
||||
|
||||
+88
-6
@@ -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};
|
||||
@@ -3119,7 +3119,7 @@ async fn imports_and_exports_keep_just_a_grid_cell_from_a_dot() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let path = [subgraph];
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
|
||||
@@ -3506,7 +3506,7 @@ async fn a_press_right_after_dragging_a_wire_out_of_an_output_drags_another_wire
|
||||
|
||||
/// Opens a new subgraph with one node inside, which is all that lies between its import and its export.
|
||||
async fn subgraph_holding_one_node(editor: &mut EditorTestUtils) -> (NodeId, NodeId) {
|
||||
let subgraph = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
editor.enter_editable_network(subgraph).await;
|
||||
editor.handle_message(NodeGraphMessage::AddImport).await;
|
||||
editor.handle_message(NodeGraphMessage::AddPrimaryExport).await;
|
||||
@@ -4041,18 +4041,30 @@ async fn a_session_preview_of_a_removed_node_is_dropped() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_new_subgraph_is_its_own_definition() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &editor.active_document().network_interface;
|
||||
assert!(matches!(network_interface.implementation(&subgraph, &[]), Some(DocumentNodeImplementation::Definition(_))));
|
||||
assert_eq!(network_interface.reference(&subgraph, &[]), None, "it shouldn't name a catalog definition");
|
||||
assert_eq!(network_interface.display_name(&subgraph, &[]), "Subgraph");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cannot_preview_node_without_outputs() {
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
|
||||
let custom_node = editor.create_node_by_name_at(DefinitionIdentifier::Network("Custom Node".to_string()), 0, 0).await;
|
||||
let subgraph = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let network_interface = &mut editor.active_document_mut().network_interface;
|
||||
|
||||
assert_eq!(network_interface.number_of_outputs(&custom_node, &[]), 0);
|
||||
assert_eq!(network_interface.number_of_outputs(&subgraph, &[]), 0);
|
||||
|
||||
// Attempting to toggle preview on a node without outputs should not enable previewing
|
||||
network_interface.toggle_preview(custom_node, &[]);
|
||||
network_interface.toggle_preview(subgraph, &[]);
|
||||
assert_eq!(network_interface.previewing(&[]), Previewing::No);
|
||||
}
|
||||
|
||||
@@ -4216,3 +4228,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]
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -1126,10 +1126,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();
|
||||
|
||||
|
||||
@@ -802,7 +802,7 @@ impl NodeNetworkInterface {
|
||||
self.query(network_path, "reference", |view| view.reference(node_id)).flatten()
|
||||
}
|
||||
|
||||
/// The icon of the node's definition, or the Custom Node icon when its definition has none or can't be found.
|
||||
/// The icon of the node's definition, or the generic subgraph icon when its definition has none or can't be found.
|
||||
pub fn node_icon(&self, node_id: &NodeId, network_path: &[NodeId]) -> &'static str {
|
||||
self.reference(node_id, network_path)
|
||||
.and_then(|reference| resolve_document_node_type(&reference)?.icon)
|
||||
@@ -875,16 +875,16 @@ impl NodeNetworkInterface {
|
||||
node.set_widget_override(index, widget_override);
|
||||
}
|
||||
|
||||
/// Returns the display name of the node. If the display name is empty, it will return "Untitled Node" or "Untitled Layer" depending on the node type.
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
pub fn display_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "display_name", |view| Ok(view.display_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The uneditable name in the Inspector which represents the function name of the node implementation.
|
||||
pub fn implementation_name(&self, node_id: &NodeId, network_path: &[NodeId]) -> String {
|
||||
self.query(network_path, "implementation_name", |view| Ok(view.implementation_name(node_id)))
|
||||
.unwrap_or_else(|| "Custom Node".to_string())
|
||||
.unwrap_or_else(|| "Subgraph".to_string())
|
||||
}
|
||||
|
||||
pub fn is_locked(&self, node_id: &NodeId, network_path: &[NodeId]) -> bool {
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -200,10 +200,11 @@ impl NodeNetworkInterface {
|
||||
self.document_metadata.layer_appearance_attributes = new_layer_appearance_attributes;
|
||||
}
|
||||
|
||||
/// Update how far each layer's effects paint past its content.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>) {
|
||||
/// Update how far each layer's effects paint past its content, and the frames they paint anywhere in.
|
||||
pub fn update_effects_reach(&mut self, new_layer_effects_reach: HashMap<LayerNodeIdentifier, f64>, new_layer_effects_frames: HashMap<LayerNodeIdentifier, [DVec2; 2]>) {
|
||||
self.document_metadata.mark_changed();
|
||||
self.document_metadata.layer_effects_reach = new_layer_effects_reach;
|
||||
self.document_metadata.layer_effects_frames = new_layer_effects_frames;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,6 +38,14 @@ pub struct NodeTemplate {
|
||||
}
|
||||
|
||||
impl NodeTemplate {
|
||||
/// A new subgraph with nothing in it, which names no definition since it becomes its own entry in the document's definitions table.
|
||||
pub fn empty_subgraph() -> Self {
|
||||
Self {
|
||||
implementation: NodeTemplateImplementation::Network(NodeNetworkTemplate::default()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The input slot named by the given parameter symbol, mirroring [`DocumentNode::input`].
|
||||
pub fn input<P: graphene_std::NodeParameter>(&self, _parameter: P) -> Option<&NodeInput> {
|
||||
self.inputs.get(P::INDEX)
|
||||
|
||||
@@ -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.) {
|
||||
@@ -332,13 +327,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()
|
||||
}
|
||||
|
||||
@@ -169,7 +169,7 @@ impl<'a, 'p> NetworkView<'a, 'p> {
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|identifier| identifier.implementation_name_from_identifier())
|
||||
.unwrap_or("Custom Node".to_string())
|
||||
.unwrap_or("Subgraph".to_string())
|
||||
}
|
||||
|
||||
/// The display name of the node, falling back to "Untitled Layer" or the implementation name when unnamed.
|
||||
|
||||
@@ -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:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1295,7 +1295,7 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
}
|
||||
|
||||
// The "Transform" wrapper network was replaced with the `transform` proto node directly. Convert old `Network("Transform")` instances to the proto node, forwarding the 5 user-facing inputs (Value, Translation, Rotation, Scale, Skew) and dropping the legacy migration sentinels (Origin Offset, Scale Appearance) at indices 5 and 6 if present.
|
||||
// Some old documents store it as a Custom Node subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Some old documents store it as a subgraph with no reference, where a Monitor feeds the Transform proto node. Those are converted the same way.
|
||||
// Pre-pass for the same reason as the Brush migration above: replacing the outer Transform's network impl orphans its child paths.
|
||||
let transform_layers: Vec<(NodeId, Vec<NodeId>, usize)> = document
|
||||
.network_interface
|
||||
@@ -1771,6 +1771,8 @@ pub fn document_migration_upgrades(document: &mut DocumentMessageHandler, reset_
|
||||
})
|
||||
.collect();
|
||||
|
||||
migrate_custom_node_subgraphs(document);
|
||||
|
||||
// Apply upgrades to each unmodified node, except those inside the read-only built-in subgraphs
|
||||
let nodes = document
|
||||
.network_interface
|
||||
@@ -4045,6 +4047,25 @@ fn migrate_removed_catalog_definitions(node_id: &NodeId, node: &DocumentNode, ne
|
||||
Some(())
|
||||
}
|
||||
|
||||
/// Gives each subgraph made from the removed Custom Node definition, from the catalog or by merging selected nodes, no reference and no default name, like one made with the New Custom Node button.
|
||||
/// Instances can share a definitions table entry holding the reference, so all of them are found before any is changed.
|
||||
fn migrate_custom_node_subgraphs(document: &mut DocumentMessageHandler) {
|
||||
let custom_node = Some(DefinitionIdentifier::Network("Custom Node".into()));
|
||||
let subgraphs: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
.network_interface
|
||||
.document_network()
|
||||
.recursive_nodes()
|
||||
.filter(|(node_id, _, path)| document.network_interface.reference(node_id, path) == custom_node)
|
||||
.map(|(node_id, _, path)| (*node_id, path))
|
||||
.collect();
|
||||
|
||||
for (node_id, network_path) in subgraphs {
|
||||
reset_default_display_name(document, &node_id, &network_path, "Custom Node");
|
||||
reset_default_display_name(document, &node_id, &network_path, "Untitled Node");
|
||||
document.network_interface.set_reference(&node_id, &network_path, None);
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits each removed Math f(…) node by the kind of string it held, into Math Aggregate or Math Formula.
|
||||
fn migrate_math_f_nodes(document: &mut DocumentMessageHandler) {
|
||||
let math_f_nodes: Vec<(NodeId, Vec<NodeId>)> = document
|
||||
@@ -4597,6 +4618,45 @@ mod tests {
|
||||
assert!(errors.is_empty(), "opening the document logged errors: {errors:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn opening_custom_node_subgraphs_drops_their_reference_and_default_names() {
|
||||
use crate::messages::portfolio::document::utility_types::network_interface::NodeTemplateImplementation;
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use crate::test_utils::test_prelude::*;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
|
||||
let mut editor = EditorTestUtils::create();
|
||||
editor.new_document().await;
|
||||
let from_catalog = editor.create_empty_subgraph_at(0, 0).await;
|
||||
let document = editor.active_document_mut();
|
||||
let Some(DocumentNodeImplementation::Definition(shared)) = document.network_interface.implementation(&from_catalog, &[]).cloned() else {
|
||||
panic!("the subgraph should name a definitions table entry")
|
||||
};
|
||||
|
||||
// A second instance of the same table entry, named as Merge Selected Nodes named the subgraphs it made
|
||||
let from_merging = NodeId::new();
|
||||
let instance = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::Definition(shared),
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(from_merging, instance, &[]);
|
||||
document.network_interface.set_reference(&from_catalog, &[], Some("Custom Node".into()));
|
||||
document.network_interface.set_display_name(&from_catalog, "Custom Node".into(), &[]);
|
||||
document.network_interface.set_display_name(&from_merging, "Untitled Node".into(), &[]);
|
||||
let serialized = document.serialize_document();
|
||||
|
||||
let opened = load_legacy_document(serialized, &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
let interface = &opened.network_interface;
|
||||
for node_id in [from_catalog, from_merging] {
|
||||
assert!(
|
||||
matches!(interface.implementation(&node_id, &[]), Some(DocumentNodeImplementation::Definition(_))),
|
||||
"the subgraph should still exist"
|
||||
);
|
||||
assert_eq!(interface.reference(&node_id, &[]), None);
|
||||
assert_eq!(interface.display_name(&node_id, &[]), "Subgraph");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_rasterize_node_on_the_export_compiles() {
|
||||
use crate::test_utils::test_prelude::*;
|
||||
|
||||
@@ -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");
|
||||
@@ -1061,6 +1055,7 @@ impl NodeGraphExecutor {
|
||||
vector_data,
|
||||
appearance_attributes,
|
||||
effects_reach,
|
||||
effects_frames,
|
||||
backgrounds: _,
|
||||
} = render_output.metadata;
|
||||
|
||||
@@ -1077,7 +1072,7 @@ impl NodeGraphExecutor {
|
||||
responses.add(DocumentMessage::UpdateClipTargets { clip_targets });
|
||||
responses.add(DocumentMessage::UpdateVectorData { vector_data });
|
||||
responses.add(DocumentMessage::UpdateAppearanceAttributes { appearance_attributes });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach });
|
||||
responses.add(DocumentMessage::UpdateEffectsReach { effects_reach, effects_frames });
|
||||
responses.add(DocumentMessage::RenderScrollbars);
|
||||
responses.add(DocumentMessage::RenderRulers);
|
||||
responses.add(OverlaysMessage::Draw);
|
||||
@@ -1205,15 +1200,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 +1254,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;
|
||||
};
|
||||
|
||||
@@ -423,6 +423,17 @@ impl EditorTestUtils {
|
||||
self.create_node(node_type, Some((x, y))).await
|
||||
}
|
||||
|
||||
/// Adds an empty subgraph at the grid position, as the graph's New Custom Node button does.
|
||||
pub async fn create_empty_subgraph_at(&mut self, x: i32, y: i32) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateEmptySubgraph {
|
||||
node_id: Some(node_id),
|
||||
xy: Some((x, y)),
|
||||
})
|
||||
.await;
|
||||
node_id
|
||||
}
|
||||
|
||||
async fn create_node(&mut self, node_type: DefinitionIdentifier, xy: Option<(i32, i32)>) -> NodeId {
|
||||
let node_id = NodeId::new();
|
||||
self.handle_message(NodeGraphMessage::CreateNodeFromContextMenu {
|
||||
@@ -509,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()
|
||||
);
|
||||
}
|
||||
@@ -32,7 +32,7 @@ pub struct DocumentNodeDefinition {
|
||||
}
|
||||
```
|
||||
|
||||
Only the definitions of nodes built from a nested network, such as the empty "Custom Node", are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
Only the definitions of built-in nodes made from a nested network are written by hand in that file. A node implemented as a single proto-node has its definition generated from the metadata the `node` macro records about its function signature (see [Creating a new node](#creating-a-new-node)), keyed by the proto-node identifier, which for the Opacity node is `graphene_std::blending_nodes::opacity::IDENTIFIER`.
|
||||
|
||||
## Inspector
|
||||
|
||||
|
||||
@@ -542,9 +542,15 @@ 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),
|
||||
SpherizeMode(graphic_types::SpherizeMode),
|
||||
WaveType(graphic_types::WaveType),
|
||||
DisplaceMode(graphic_types::DisplaceMode),
|
||||
GridType(vector::misc::GridType),
|
||||
GridTopology(vector::misc::GridTopology),
|
||||
ArcType(vector::misc::ArcType),
|
||||
@@ -714,6 +720,22 @@ impl TaggedValue {
|
||||
None
|
||||
}
|
||||
|
||||
fn to_gradient_spread(input: &str) -> Option<vector::style::GradientSpread> {
|
||||
use vector::style::GradientSpread;
|
||||
|
||||
let Some(("GradientSpread", variant)) = input.split_once("::").map(|(first, second)| (first.trim(), second.trim())) else {
|
||||
log::error!("Invalid GradientSpread default type: {input}");
|
||||
return None;
|
||||
};
|
||||
let spread = [GradientSpread::Pad, GradientSpread::Reflect, GradientSpread::Repeat, GradientSpread::Clear]
|
||||
.into_iter()
|
||||
.find(|spread| format!("{spread:?}") == variant);
|
||||
if spread.is_none() {
|
||||
log::error!("Invalid GradientSpread default type variant: {input}");
|
||||
}
|
||||
spread
|
||||
}
|
||||
|
||||
fn to_blend_mode(input: &str) -> Option<core_types::blending::BlendMode> {
|
||||
use core_types::blending::BlendMode;
|
||||
|
||||
@@ -756,6 +778,7 @@ impl TaggedValue {
|
||||
() if ty == TypeId::of::<Footprint>() => to_footprint(string).map(TaggedValue::Footprint)?,
|
||||
() if ty == TypeId::of::<vector::style::StrokeAlign>() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?,
|
||||
() if ty == TypeId::of::<core_types::blending::BlendMode>() => to_blend_mode(string).map(TaggedValue::BlendMode)?,
|
||||
() if ty == TypeId::of::<vector::style::GradientSpread>() => to_gradient_spread(string).map(TaggedValue::GradientSpread)?,
|
||||
() if ty == TypeId::of::<DashPattern>() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)),
|
||||
() if ty == TypeId::of::<BoxCorners>() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)),
|
||||
_ => {
|
||||
@@ -974,8 +997,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 +1013,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -28,7 +28,8 @@ 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 graphene_std::{DisplaceMode, RadialBlurMethod, SpherizeMode, WaveType};
|
||||
use node_registry_macros::async_node;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
@@ -292,9 +293,15 @@ fn node_registry() -> HashMap<ProtoNodeIdentifier, HashMap<NodeIOTypes, NodeCons
|
||||
GlowTechnique,
|
||||
GlowSource,
|
||||
MaskMode,
|
||||
MinimumMaximumMode,
|
||||
BevelStyle,
|
||||
BevelDirection,
|
||||
BevelTechnique,
|
||||
NoiseDistribution,
|
||||
RadialBlurMethod,
|
||||
SpherizeMode,
|
||||
WaveType,
|
||||
DisplaceMode,
|
||||
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,50 @@ 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::Twirl { .. }
|
||||
| EffectOperation::Pinch { .. }
|
||||
| EffectOperation::Spherize { .. }
|
||||
| EffectOperation::PolarCoordinates { .. }
|
||||
| EffectOperation::Ripple { .. }
|
||||
| EffectOperation::Wave { .. }
|
||||
| EffectOperation::Displace { .. }
|
||||
| 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 +390,27 @@ 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::Twirl { .. }
|
||||
| EffectOperation::Pinch { .. }
|
||||
| EffectOperation::Spherize { .. }
|
||||
| EffectOperation::PolarCoordinates { .. }
|
||||
| EffectOperation::Ripple { .. }
|
||||
| EffectOperation::Wave { .. }
|
||||
| EffectOperation::Displace { .. }
|
||||
| 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 +615,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 +657,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 +695,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 +722,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);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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]);
|
||||
}
|
||||
}
|
||||
@@ -315,3 +315,21 @@ impl GeneratorPattern {
|
||||
Self::decode(*item.element(), &|key| item.attributes().get_any(key))
|
||||
}
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
pub fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
let mix = |[x, y, z]: [u32; 3]| {
|
||||
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||
[x, y, z]
|
||||
};
|
||||
|
||||
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
}
|
||||
|
||||
/// A hash's top 24 bits as a fraction from 0 to 1, which an f32 holds exactly.
|
||||
pub fn hash_fraction(hash: u32) -> f32 {
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
@@ -14,7 +14,7 @@ use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
pub use vector_types::Vector;
|
||||
use vector_types::vector::{Path, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::vector::{Path, no_paths, paths_from_item_attributes, paths_from_list_row_attributes};
|
||||
use vector_types::{Gradient, GradientSpread};
|
||||
|
||||
/// The possible forms of graphical content that can be rendered by the Render node (to targets like SVG and raster) or another render boundary node.
|
||||
@@ -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>`.
|
||||
@@ -857,6 +874,20 @@ pub fn vector_item_bounding_box(item: &Item<Vector>, transform: DAffine2, includ
|
||||
}
|
||||
}
|
||||
|
||||
/// The bounding box of a vector list's item in its own space, before its transform, with its stroke, which is the frame its effects relative to its extent take.
|
||||
pub fn vector_list_item_local_bounds(list: &List<Vector>, index: usize) -> Option<[DVec2; 2]> {
|
||||
let stroke = list.attribute::<Appearance>(ATTR_APPEARANCE, index).and_then(Appearance::first_stroke_params);
|
||||
let paths = paths_from_list_row_attributes(list, index).unwrap_or_else(|| no_paths());
|
||||
list.element(index)?.stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())
|
||||
}
|
||||
|
||||
/// The bounding box of a vector item in its own space, before its transform, with its stroke, which is the frame its effects relative to its extent take.
|
||||
pub fn vector_item_local_bounds(item: &Item<Vector>) -> Option<[DVec2; 2]> {
|
||||
let stroke = item.attribute::<Appearance>(ATTR_APPEARANCE).and_then(Appearance::first_stroke_params);
|
||||
let paths = paths_from_item_attributes(item).unwrap_or_else(|| no_paths());
|
||||
item.element().stroke_inclusive_bounding_box_with_transform(paths, DAffine2::IDENTITY, stroke.as_ref())
|
||||
}
|
||||
|
||||
/// Combined bounding box of a vector list's items, inflating each item by its appearance's stroke when `include_stroke`.
|
||||
pub fn vector_list_bounding_box(list: &List<Vector>, transform: DAffine2, include_stroke: bool) -> RenderBoundingBox {
|
||||
let mut combined_bounds: Option<[DVec2; 2]> = None;
|
||||
|
||||
@@ -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::{DisplaceMode, RadialBlurMethod, SpherizeMode, WaveType};
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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 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::generator::pcg3d;
|
||||
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.);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::mandelbrot::{MandelbrotSetup, resolves_in_32_bits};
|
||||
use core_types::Color;
|
||||
use glam::{DVec2, IVec2};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType};
|
||||
use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, GeneratorPattern, NoiseSettings, NoiseType, hash_fraction, pcg3d};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
use raster_types::{Image, ImageError};
|
||||
|
||||
@@ -170,22 +170,7 @@ impl NoiseSampler {
|
||||
/// A random value from 0 to 1 for each cell of a grid, the same for the same seed and cell. In 32-bit math, which a GPU can match.
|
||||
fn white_noise(seed: i32, cell: IVec2) -> f32 {
|
||||
let [hash, _, _] = pcg3d([cell.x as u32, cell.y as u32, seed as u32]);
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
(hash >> 8) as f32 / (1_u32 << 24) as f32
|
||||
}
|
||||
|
||||
/// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result.
|
||||
fn pcg3d(input: [u32; 3]) -> [u32; 3] {
|
||||
let mix = |[x, y, z]: [u32; 3]| {
|
||||
let x = x.wrapping_add(y.wrapping_mul(z));
|
||||
let y = y.wrapping_add(z.wrapping_mul(x));
|
||||
let z = z.wrapping_add(x.wrapping_mul(y));
|
||||
[x, y, z]
|
||||
};
|
||||
|
||||
let v = mix(input.map(|value| value.wrapping_mul(1_664_525).wrapping_add(1_013_904_223)));
|
||||
mix(v.map(|value| value ^ (value >> 16)))
|
||||
hash_fraction(hash)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -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::*;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
//! The CPU twins of the GPU passes that mask content by another graphic and feather it toward its edges.
|
||||
//! The CPU twins of the GPU passes that mask, feather, and blur content by a radius mask.
|
||||
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::raster_effects::premultiplied_gamma_channels;
|
||||
use crate::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, Plane, VARIABLE_BOX_MAX_VALUE, variable_box_scale};
|
||||
use crate::raster_effects::{blur, premultiplied_gamma_channels, transferred};
|
||||
use core_types::Color;
|
||||
use core_types::color::{linear_to_srgb, srgb_to_linear};
|
||||
use glam::DVec2;
|
||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma};
|
||||
use graphic_types::masks::{FEATHER_FOOTPRINT_ALPHA, MaskMode, feather_parts, mask_coverage, mask_density_line, mask_feather_sigma, masked_radius_blur_code, masked_radius_blur_interpolation};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// How much the mask shows the content at each pixel, from 0 to 1, given the `colors` its graphic draws over a plane of `width` by `height` pixels.
|
||||
@@ -73,9 +74,170 @@ pub(crate) fn feather_strength(full: &Plane<[f32; 4]>, distance: f64) -> Plane<f
|
||||
}
|
||||
}
|
||||
|
||||
/// A masked radius blur map's color in 8-bit channels as the GPU renders the map: straight, then premultiplied.
|
||||
fn map_channels(color: Color) -> [f32; 4] {
|
||||
let eight_bit = |channel: f32| (channel.clamp(0., 1.) * 255.).round() / 255.;
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels().map(eight_bit);
|
||||
[eight_bit(red * alpha), eight_bit(green * alpha), eight_bit(blue * alpha), alpha]
|
||||
}
|
||||
|
||||
/// The 8-bit luminance code of each of a masked radius blur map's `colors` (see [`map_channels`]).
|
||||
pub(crate) fn masked_radius_blur_codes(colors: &[Color]) -> Vec<u8> {
|
||||
colors.iter().map(|&color| masked_radius_blur_code(map_channels(color))).collect()
|
||||
}
|
||||
|
||||
/// The luminance from 0 to 1 of each of a masked box blur map's `colors`, unrounded like the GPU's precise map texture, in the half floats the GPU keeps it in, which size the boxes finer than 8-bit codes could.
|
||||
pub(crate) fn masked_box_blur_luminances(colors: &[Color]) -> Vec<f32> {
|
||||
let luminance = |color: Color| {
|
||||
let [red, green, blue, alpha] = color.to_gamma_srgb_channels();
|
||||
mask_coverage([red * alpha, green * alpha, blue * alpha, alpha], MaskMode::Luminance).clamp(0., 1.)
|
||||
};
|
||||
colors.iter().map(|&color| half::f16::from_f32(luminance(color)).to_f32()).collect()
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded `image` blurred by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels along each axis) each pixel's map luminance `codes` picks,
|
||||
/// matching the GPU's `masked_radius_blur`, blurring in linear light if `linear`. O(width × height) for each of the levels.
|
||||
pub(crate) fn masked_radius_blur(image: &Plane<[f32; 4]>, codes: &[u8], levels: &[DVec2], linear: bool) -> Plane<[f32; 4]> {
|
||||
// Each code's level below and share of the level above, the same for every level and at any scale
|
||||
let lengths: Vec<f64> = levels.iter().map(|level| level.max_element()).collect();
|
||||
let interpolations: Vec<(usize, f32)> = (0..=255_u8)
|
||||
.map(|code| {
|
||||
let (below, above_parts) = masked_radius_blur_interpolation(code, &lengths);
|
||||
(below, above_parts as f32 / 255.)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Only the levels some pixel takes a share of are blurred, so a map of one luminance blurs once or twice
|
||||
let mut weighed = vec![false; levels.len()];
|
||||
for &code in codes {
|
||||
let (below, above_share) = interpolations[code as usize];
|
||||
weighed[below] |= above_share < 1.;
|
||||
if let Some(above) = weighed.get_mut(below + 1) {
|
||||
*above |= above_share > 0.;
|
||||
}
|
||||
}
|
||||
|
||||
let mut sum = Plane::<[f32; 4]>::new(image.width, image.height);
|
||||
for (index, &length) in levels.iter().enumerate().filter(|&(index, _)| weighed[index]) {
|
||||
let blurred = match length.max_element() >= NEGLIGIBLE_LENGTH {
|
||||
true => blur(image.clone(), (BlurKernel::Gaussian { sigma: length.x }, BlurKernel::Gaussian { sigma: length.y }), linear),
|
||||
false => image.clone(),
|
||||
};
|
||||
|
||||
let weight = |(below, above_share): (usize, f32)| match index {
|
||||
_ if index == below => 1. - above_share,
|
||||
_ if index == below + 1 => above_share,
|
||||
_ => 0.,
|
||||
};
|
||||
// Summed in gamma on purpose (see `masked_radius_blur_interpolation`)
|
||||
for ((sum, pixel), &code) in sum.data.iter_mut().zip(&blurred.data).zip(codes) {
|
||||
let weight = weight(interpolations[code as usize]);
|
||||
*sum = std::array::from_fn(|channel| sum[channel] + pixel[channel] * weight);
|
||||
}
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
/// The premultiplied gamma-encoded `image` box blurred at each pixel by its own half width along each axis, the fraction of the `radius` in pixels its map's `luminances` give,
|
||||
/// matching the GPU's `variable_box_blur`. Each box weighs pixels like [`BlurKernel::Box`], holding the edge pixels past the edges, in linear light if `linear`.
|
||||
/// It sums each box from running sums (a summed-area table) of whole-number counts, exact at any size, so O(width × height) at any radius.
|
||||
pub fn variable_box_blur(image: &Plane<[f32; 4]>, luminances: &[f32], radius: DVec2, linear: bool) -> Plane<[f32; 4]> {
|
||||
let (width, height) = (image.width, image.height);
|
||||
let summed = match linear {
|
||||
true => std::borrow::Cow::Owned(image.map(transferred(srgb_to_linear))),
|
||||
false => std::borrow::Cow::Borrowed(image),
|
||||
};
|
||||
let scale = variable_box_scale(width * height);
|
||||
let count = |value: f32| (value.clamp(0., VARIABLE_BOX_MAX_VALUE) * scale as f32).round_ties_even() as u64;
|
||||
|
||||
// Two channels at a time, as the GPU sums them, keeping the running sums to 16 bytes a pixel
|
||||
let mut averages = Plane::<[f32; 4]>::new(width, height);
|
||||
for first in [0, 2] {
|
||||
// Each channel counted in whole steps, summed over the pixels above and left of each corner between pixels, in rows of one more corner than pixels
|
||||
let corners = width + 1;
|
||||
let mut sums = vec![[0_u64; 2]; corners * (height + 1)];
|
||||
for y in 0..height {
|
||||
let mut row = [0_u64; 2];
|
||||
for x in 0..width {
|
||||
let pixel = summed.data[y * width + x];
|
||||
row = [row[0] + count(pixel[first]), row[1] + count(pixel[first + 1])];
|
||||
|
||||
let above = sums[y * corners + x + 1];
|
||||
sums[(y + 1) * corners + x + 1] = [above[0] + row[0], above[1] + row[1]];
|
||||
}
|
||||
}
|
||||
let sum_at = |x: usize, y: usize| sums[y * corners + x];
|
||||
|
||||
// The counts over the pixels from `start` up to `end`, with those past the edges repeating the nearest edge pixel
|
||||
let counts_continued = |start: [i64; 2], end: [i64; 2]| -> [f64; 2] {
|
||||
let spans = |axis: usize, size: usize| {
|
||||
let size = size as i64;
|
||||
let (inner_start, inner_end) = (start[axis].clamp(0, size), end[axis].clamp(0, size));
|
||||
[(0, 1, inner_start - start[axis]), (inner_start, inner_end, 1), (size - 1, size, end[axis] - inner_end)]
|
||||
};
|
||||
|
||||
let mut sum = [0.; 2];
|
||||
for (start_x, end_x, count_x) in spans(0, width) {
|
||||
for (start_y, end_y, count_y) in spans(1, height) {
|
||||
if count_x <= 0 || count_y <= 0 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let [start_x, end_x, start_y, end_y] = [start_x, end_x, start_y, end_y].map(|corner| corner as usize);
|
||||
let [top_left, top_right] = [sum_at(start_x, start_y), sum_at(end_x, start_y)];
|
||||
let [bottom_left, bottom_right] = [sum_at(start_x, end_y), sum_at(end_x, end_y)];
|
||||
let count = (count_x * count_y) as f64;
|
||||
sum = std::array::from_fn(|channel| sum[channel] + count * ((bottom_right[channel] + top_left[channel]) - (bottom_left[channel] + top_right[channel])) as f64);
|
||||
}
|
||||
}
|
||||
sum
|
||||
};
|
||||
|
||||
fill_rows(&mut averages.data, width, |y, row| {
|
||||
for (x, target) in row.iter_mut().enumerate() {
|
||||
let index = y * width + x;
|
||||
if luminances[index] <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
// A box of a fractional half width is the mix of the boxes of the whole half widths either side, weighed by that fraction along each axis
|
||||
let half_width = radius * luminances[index] as f64;
|
||||
let (whole, fraction) = (half_width.floor(), half_width - half_width.floor());
|
||||
let mut sum = [0.; 2];
|
||||
for wider in [[false, false], [true, false], [false, true], [true, true]] {
|
||||
let along = |axis: usize| if wider[axis] { fraction[axis] } else { 1. - fraction[axis] };
|
||||
let weight = along(0) * along(1);
|
||||
if weight <= 0. {
|
||||
continue;
|
||||
}
|
||||
|
||||
let reach = [0, 1].map(|axis| whole[axis] as i64 + wider[axis] as i64);
|
||||
let rectangle = counts_continued([x as i64 - reach[0], y as i64 - reach[1]], [x as i64 + reach[0] + 1, y as i64 + reach[1] + 1]);
|
||||
sum = std::array::from_fn(|channel| sum[channel] + weight * rectangle[channel]);
|
||||
}
|
||||
|
||||
let total = (2. * half_width.x + 1.) * (2. * half_width.y + 1.) * scale;
|
||||
target[first..first + 2].copy_from_slice(&sum.map(|channel| (channel / total) as f32));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Pixels not blurred keep their color, and the rest return to gamma from linear light
|
||||
let encode = transferred(linear_to_srgb);
|
||||
for ((average, &original), &luminance) in averages.data.iter_mut().zip(&image.data).zip(luminances) {
|
||||
*average = match luminance > 0. {
|
||||
false => original,
|
||||
true if linear => encode(*average),
|
||||
true => *average,
|
||||
};
|
||||
}
|
||||
averages
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::effect_kernels::box_weight;
|
||||
|
||||
/// The standard normal cumulative distribution, from the Abramowitz and Stegun approximation of the error function, accurate to 1e-7.
|
||||
fn normal_cdf(x: f64) -> f64 {
|
||||
@@ -160,4 +322,87 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Premultiplied colors varying across the plane up to its edges, every seventh pixel transparent and some translucent.
|
||||
fn colorful(width: usize, height: usize) -> Plane<[f32; 4]> {
|
||||
let data = (0..width * height)
|
||||
.map(|index| {
|
||||
let (x, y) = ((index % width) as f32 / width as f32, (index / width) as f32 / height as f32);
|
||||
let alpha = [0., 0.5, 0.5, 1., 1., 1., 1.][index % 7];
|
||||
[x * alpha, y * alpha, (1. - x * y) * alpha, alpha]
|
||||
})
|
||||
.collect();
|
||||
Plane { width, height, data }
|
||||
}
|
||||
|
||||
/// The box of `half_width` along each axis around a pixel of the plane, summed pixel by pixel with the edge pixels held past the edges.
|
||||
fn summed_box(plane: &Plane<[f32; 4]>, x: usize, y: usize, half_width: DVec2) -> [f32; 4] {
|
||||
let reach = half_width.ceil().as_i64vec2();
|
||||
let (mut sum, mut total) = ([0.; 4], 0.);
|
||||
for offset_y in -reach.y..=reach.y {
|
||||
for offset_x in -reach.x..=reach.x {
|
||||
let weight = box_weight(half_width.x, offset_x.unsigned_abs() as usize) * box_weight(half_width.y, offset_y.unsigned_abs() as usize);
|
||||
let source_x = (x as i64 + offset_x).clamp(0, plane.width as i64 - 1) as usize;
|
||||
let source_y = (y as i64 + offset_y).clamp(0, plane.height as i64 - 1) as usize;
|
||||
let pixel = plane.data[source_y * plane.width + source_x];
|
||||
|
||||
sum = std::array::from_fn(|channel| sum[channel] + weight * pixel[channel] as f64);
|
||||
total += weight;
|
||||
}
|
||||
}
|
||||
sum.map(|channel| (channel / total) as f32)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_box_blurs_box_each_pixel_by_its_own_fraction_of_the_radius() {
|
||||
let image = colorful(37, 29);
|
||||
// Luminances finer than 8-bit codes, with every 41st pixel unblurred
|
||||
let luminances: Vec<f32> = (0..37 * 29).map(|index| if index % 41 == 0 { 0. } else { ((index * 37) % 1000) as f32 / 1000. }).collect();
|
||||
let radius = DVec2::new(9.3, 6.);
|
||||
|
||||
for linear in [false, true] {
|
||||
let blurred = variable_box_blur(&image, &luminances, radius, linear);
|
||||
let decoded = if linear { image.map(transferred(srgb_to_linear)) } else { image.clone() };
|
||||
|
||||
// Counting in 4096 steps rounds by up to half a step, which gamma encoding stretches up to 13 times near black
|
||||
let tolerance = if linear { 2e-3 } else { 2e-4 };
|
||||
|
||||
for (index, &luminance) in luminances.iter().enumerate() {
|
||||
// A luminance of 0 leaves its pixel exactly as it is
|
||||
if luminance <= 0. {
|
||||
assert_eq!(blurred.data[index], image.data[index]);
|
||||
continue;
|
||||
}
|
||||
|
||||
let summed = summed_box(&decoded, index % 37, index / 37, radius * luminance as f64);
|
||||
let expected = if linear { transferred(linear_to_srgb)(summed) } else { summed };
|
||||
for channel in 0..4 {
|
||||
let difference = (blurred.data[index][channel] - expected[channel]).abs();
|
||||
assert!(
|
||||
difference < tolerance,
|
||||
"pixel {index} of luminance {luminance} differs by {difference} in channel {channel} (linear: {linear})"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_box_blurs_of_one_fraction_of_the_radius_are_the_box_blur_of_that_half_width() {
|
||||
let image = colorful(48, 40);
|
||||
let luminances = vec![0.6; 48 * 40];
|
||||
let radius = DVec2::new(20., 12.5);
|
||||
let half_width = radius * 0.6_f32 as f64;
|
||||
|
||||
for linear in [false, true] {
|
||||
let variable = variable_box_blur(&image, &luminances, radius, linear);
|
||||
let even = blur(image.clone(), (BlurKernel::Box { radius: half_width.x }, BlurKernel::Box { radius: half_width.y }), linear);
|
||||
for (index, (variable, even)) in variable.data.iter().zip(&even.data).enumerate() {
|
||||
for channel in 0..4 {
|
||||
let difference = (variable[channel] - even[channel]).abs();
|
||||
assert!(difference < 2e-4, "pixel {index} differs by {difference} in channel {channel} (linear: {linear})");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -5,7 +5,9 @@
|
||||
|
||||
use crate::renderer::{CanvasImage, Render, RenderOutputType, RenderParams, RenderSvgSegmentList, SvgRender, render_raster_cpu_image_svg};
|
||||
use crate::vello_scene_builder::{MAX_EFFECTS_AREA_PER_VIEWPORT_AREA, VelloSceneBuilder};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::math::quad::Quad;
|
||||
use core_types::transform::Footprint;
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
@@ -112,11 +114,17 @@ fn map_markers(id: u64) -> (String, String) {
|
||||
(format!("<!--effect-map-{id}-->"), format!("<!--/effect-map-{id}-->"))
|
||||
}
|
||||
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, covering everything to the `coverage` from 0 to 1.
|
||||
/// Coverage that is added leaves the effect out at 0, and coverage the content is multiplied by leaves it out at 1.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str, coverage: f64) -> String {
|
||||
/// The filter primitive standing for the map `id` names until it's resolved, flooding the region with `flood`, which leaves the effect out.
|
||||
/// Coverage that is added leaves the effect out when transparent, coverage the content is multiplied by leaves it out when opaque, and data a filter combines in other ways takes whatever value is neutral for it.
|
||||
pub(crate) fn map_placeholder(id: u64, result: &str, flood: Color) -> String {
|
||||
let color = SRGBA8::from(flood.with_alpha(1.)).to_rgb_hex();
|
||||
map_placeholder_primitive(id, &format!(r##"<feFlood flood-color="#{color}" flood-opacity="{}" result="{result}" />"##, flood.a()))
|
||||
}
|
||||
|
||||
/// The filter `primitive` standing for the map `id` names until it's resolved, which gives the result the map stands for.
|
||||
pub(crate) fn map_placeholder_primitive(id: u64, primitive: &str) -> String {
|
||||
let (opening, closing) = map_markers(id);
|
||||
format!(r#"{opening}<feFlood flood-opacity="{coverage}" result="{result}" />{closing}"#)
|
||||
format!("{opening}{primitive}{closing}")
|
||||
}
|
||||
|
||||
impl EffectMap {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,833 @@
|
||||
//! The SVG filter primitives carrying out the filter effects like the GPU passes do.
|
||||
|
||||
use super::SvgFilterPrimitives;
|
||||
use core_types::Color;
|
||||
use core_types::color::SRGBA8;
|
||||
use glam::DVec2;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::filters::{AVERAGE_VISIBILITY_RAMP, Convolution, HIGH_PASS_GRAY, Surroundings, UnsharpBlur, fill_shifts, noise_extent, unsharp, unsharp_change};
|
||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||
use raster_kernels::effect_kernels::{MAX_DIRECT_BOX_RADIUS, box_weight};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// The most weights an `feConvolveMatrix` kernel holds before browsers carry it out with less precision.
|
||||
const MAX_PRECISE_KERNEL_AREA: usize = 25;
|
||||
|
||||
/// A convolution's kernel on the user space's lattice, its weights listed as the matrix of an `feConvolveMatrix` of `order` weights across and down, with the `target` cell on the pixel being found.
|
||||
struct LatticeKernel {
|
||||
order: [usize; 2],
|
||||
target: [usize; 2],
|
||||
matrix: Vec<f64>,
|
||||
}
|
||||
|
||||
impl LatticeKernel {
|
||||
/// The kernel of `convolution`, its shifts in whole units of the user space, one to a pixel, or `None` if it holds more weights than browsers carry out precisely.
|
||||
fn new(convolution: &Convolution) -> Option<Self> {
|
||||
let mut weights: BTreeMap<(i64, i64), f64> = BTreeMap::new();
|
||||
for &(shift, weight) in &convolution.taps {
|
||||
*weights.entry((shift.x.round() as i64, shift.y.round() as i64)).or_default() += weight / convolution.divisor;
|
||||
}
|
||||
|
||||
// The faint pixels' colors stack a copy for each shift within the square the kernel reaches across, which must stay small too
|
||||
let reach = weights.keys().map(|&(x, y)| x.abs().max(y.abs())).max().unwrap_or(0);
|
||||
let side = 2 * reach.unsigned_abs() as usize + 1;
|
||||
if side * side > MAX_PRECISE_KERNEL_AREA {
|
||||
return None;
|
||||
}
|
||||
|
||||
// The matrix spans the weights and the pixel being found, and is applied turned halfway around, so it lists the weights from the last shift to the first
|
||||
let extent = |axis: fn(&(i64, i64)) -> i64| weights.keys().map(axis).fold((0, 0), |(least, most), value| (least.min(value), most.max(value)));
|
||||
let [(least_x, most_x), (least_y, most_y)] = [extent(|&(x, _)| x), extent(|&(_, y)| y)];
|
||||
let order = [(most_x - least_x + 1) as usize, (most_y - least_y + 1) as usize];
|
||||
let mut matrix = vec![0.; order[0] * order[1]];
|
||||
for (&(x, y), &weight) in &weights {
|
||||
let cell = (y - least_y) as usize * order[0] + (x - least_x) as usize;
|
||||
matrix[order[0] * order[1] - 1 - cell] = weight;
|
||||
}
|
||||
|
||||
// The target is how far the kernel reads left of and above the pixel being found
|
||||
let target = [-least_x as usize, -least_y as usize];
|
||||
Some(Self { order, target, matrix })
|
||||
}
|
||||
}
|
||||
|
||||
/// How much farther than the effects reach an SVG filter's region must extend, in document pixels, since a minimum's erosion of the colors reads past the region as black.
|
||||
pub(super) fn svg_region_reach_beyond(effects: &Effects) -> f64 {
|
||||
effects
|
||||
.operations()
|
||||
.map(|operation| match operation {
|
||||
EffectOperation::MinimumMaximum {
|
||||
radius,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
} => radius.max(0.).ceil(),
|
||||
_ => 0.,
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// The image with a filter effect carried out on it, in a user space of one unit to a pixel of its effect space, or as it is for any other operation.
|
||||
/// A filter on the pixel lattice runs natively only where one user unit is one device pixel (`pixel_exact`), and otherwise takes its result as the map the GPU renders for `capture`.
|
||||
/// Where the fill `forked` the content into two planes, no filter reading its input many times runs natively, since the filter can't split to keep chains of them from multiplying.
|
||||
pub(super) fn filter(&mut self, image: &str, operation: &EffectOperation, pixel_exact: bool, forked: bool, capture: EffectCapture) -> String {
|
||||
let native = pixel_exact && !forked;
|
||||
|
||||
if let Some(convolution) = operation.convolution() {
|
||||
return match native.then(|| LatticeKernel::new(&convolution)).flatten() {
|
||||
Some(kernel) => {
|
||||
let coverage = convolution.weighs_coverage.then(|| self.convolve_coverage(image, &kernel));
|
||||
let convolved = self.convolve(image, &convolution, &kernel);
|
||||
self.uncover(&convolved, coverage.as_deref().unwrap_or(image), convolution.surroundings)
|
||||
}
|
||||
// A kernel weighing the coverage too gives the colors the coverage it weighs, so the whole result comes as the map
|
||||
None if convolution.weighs_coverage => self.map_showing(capture, image),
|
||||
None => self.uncovered_map(image, capture, convolution.surroundings),
|
||||
};
|
||||
}
|
||||
|
||||
// Edges Only needs the length of each channel's gradient, which loses too much precision through the 8-bit results between primitives
|
||||
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||
return match blur {
|
||||
UnsharpBlur::Gaussian(radius) if !forked => self.unsharp_mask(image, radius, sharpening),
|
||||
_ => self.map_showing(capture, image),
|
||||
};
|
||||
}
|
||||
|
||||
match *operation {
|
||||
// The Euclidean length of the gradient loses too much precision through the 8-bit results between primitives
|
||||
EffectOperation::FindEdges => self.uncovered_map(image, capture, Surroundings::Matted(1.)),
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. } if forked => self.map_showing(capture, image),
|
||||
EffectOperation::MinimumMaximum { radius, mode } => self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum),
|
||||
// Random fields come from the GPU, one map for both the content and the fill since they don't depend on either
|
||||
EffectOperation::AddNoise { amount, distribution, .. } => self.add_noise(image, noise_extent(amount / 100., distribution), EffectCapture { plane: 0, ..capture }),
|
||||
EffectOperation::Dissolve { .. } => self.dissolve(image, EffectCapture { plane: 0, ..capture }),
|
||||
_ => image.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The map the GPU renders for `capture` given the image's coverage, matching the GPU's `uncover`, or the image as it is until the map resolves.
|
||||
/// It reads the image only once, so chains of filters taking maps stay linear in a browser that redoes a filter's input for each read.
|
||||
/// Continued colors' maps are opaque and placed atop the image, while matted ones hold the whole result, since lifting off the gray isn't a composite.
|
||||
fn uncovered_map(&mut self, image: &str, capture: EffectCapture, surroundings: Surroundings) -> String {
|
||||
match surroundings {
|
||||
Surroundings::Continued => {
|
||||
let map = self.map(capture);
|
||||
self.push("feComposite", &format!(r#"in="{map}" in2="{image}" operator="atop""#), "")
|
||||
}
|
||||
Surroundings::Matted(_) => self.map_showing(capture, image),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the filter reads its input more than a few times (natively, for those on the pixel lattice), so a chain of them in one filter would multiply their cost.
|
||||
pub(super) fn reads_input_often(&self, operation: &EffectOperation, native: bool) -> bool {
|
||||
match operation.convolution() {
|
||||
Some(convolution) => native && LatticeKernel::new(&convolution).is_some(),
|
||||
None => matches!(
|
||||
operation,
|
||||
EffectOperation::MinimumMaximum { .. } | EffectOperation::Sharpen { .. } | EffectOperation::HighPass { .. } | EffectOperation::AddNoise { .. } | EffectOperation::Dissolve { .. }
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
/// The image's straight colors as the filters read them, opaque where there's one, with faint pixels taking the nearest visible color within `reach` document pixels.
|
||||
/// Copies with the visible pixels made opaque and the rest left out stack nearest on top, so each pixel shows the first visible one exactly.
|
||||
fn visible_colors(&mut self, image: &str, reach: f64) -> String {
|
||||
// The alpha row raises 16 levels and up to full and leaves out 15 and below, matching the GPU's threshold, and beneath it all the covered pixels made opaque
|
||||
let opaque = |primitives: &mut Self, alpha_row: &str| {
|
||||
let values = format!("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 {alpha_row}");
|
||||
primitives.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="{values}""#), "")
|
||||
};
|
||||
let visible = opaque(self, "0 0 0 255 -15");
|
||||
let covered = opaque(self, "0 0 0 255 0");
|
||||
|
||||
let mut layers = Vec::new();
|
||||
for [x, y] in fill_shifts(reach.ceil() as i32).into_iter().skip(1) {
|
||||
// Each copy moves against its shift, so the pixel it lands on reads the one the shift points to, written without negative zeros
|
||||
let shift = -DVec2::new(x as f64, y as f64) + DVec2::ZERO;
|
||||
layers.push(self.push("feOffset", &format!(r#"in="{visible}" dx="{}" dy="{}""#, shift.x, shift.y), ""));
|
||||
}
|
||||
let layers = [vec![covered], layers.into_iter().rev().collect(), vec![visible]].concat();
|
||||
|
||||
let nodes: String = layers.iter().map(|layer| format!(r#"<feMergeNode in="{layer}" />"#)).collect();
|
||||
self.push("feMerge", "", &nodes)
|
||||
}
|
||||
|
||||
/// The opaque colors of the image convolved by an `feConvolveMatrix` of the `kernel` over the colors its surroundings describe, as the GPU's `convolve` does.
|
||||
fn convolve(&mut self, image: &str, convolution: &Convolution, kernel: &LatticeKernel) -> String {
|
||||
let colors = match convolution.surroundings {
|
||||
Surroundings::Continued => self.visible_colors(image, convolution.reach()),
|
||||
Surroundings::Matted(gray) => self.over_gray(image, gray),
|
||||
};
|
||||
|
||||
let ([columns, rows], [target_x, target_y]) = (kernel.order, kernel.target);
|
||||
let matrix = kernel.matrix.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
let attributes = format!(
|
||||
r#"in="{colors}" order="{columns} {rows}" kernelMatrix="{matrix}" divisor="1" bias="{}" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none" preserveAlpha="true""#,
|
||||
convolution.offset
|
||||
);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
}
|
||||
|
||||
/// The image's coverage weighed by the `kernel`, clamped, as the alpha of an `feConvolveMatrix` over every channel.
|
||||
fn convolve_coverage(&mut self, image: &str, kernel: &LatticeKernel) -> String {
|
||||
let ([columns, rows], [target_x, target_y]) = (kernel.order, kernel.target);
|
||||
let matrix = kernel.matrix.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
let attributes = format!(r#"in="{image}" order="{columns} {rows}" kernelMatrix="{matrix}" divisor="1" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none""#);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
}
|
||||
|
||||
/// The image composited over an opaque gray of level `gray`.
|
||||
fn over_gray(&mut self, image: &str, gray: f64) -> String {
|
||||
let percent = gray * 100.;
|
||||
let flood = self.push("feFlood", &format!(r#"flood-color="rgb({percent}%, {percent}%, {percent}%)" flood-opacity="1""#), "");
|
||||
self.push("feComposite", &format!(r#"in="{image}" in2="{flood}" operator="over""#), "")
|
||||
}
|
||||
|
||||
/// Filtered opaque `colors` given the image's coverage, as their `surroundings` describe, matching the GPU's `uncover`.
|
||||
fn uncover(&mut self, colors: &str, image: &str, surroundings: Surroundings) -> String {
|
||||
let Surroundings::Matted(gray) = surroundings else {
|
||||
return self.push("feComposite", &format!(r#"in="{colors}" in2="{image}" operator="in""#), "");
|
||||
};
|
||||
// The gray over the share the image leaves uncovered, taken off the opaque colors, which leaves the image's coverage as alpha and clamps as the GPU does
|
||||
let values = format!("0 0 0 0 {gray} 0 0 0 0 {gray} 0 0 0 0 {gray} 0 0 0 -1 1");
|
||||
let uncovered_gray = self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="{values}""#), "");
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{uncovered_gray}" operator="arithmetic" k2="1" k3="-1""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color and its coverage sharpened against a Gaussian blur of `radius` document pixels, by the amount and threshold fractions in `sharpening`,
|
||||
/// or with none, a high pass of its colors, matching the GPU's `unsharp_mask`.
|
||||
fn unsharp_mask(&mut self, image: &str, radius: f64, sharpening: Option<[f64; 2]>) -> String {
|
||||
let sigma = radius.max(0.);
|
||||
let blur = |primitives: &mut Self, input: &str| primitives.push("feGaussianBlur", &format!(r#"in="{input}" stdDeviation="{sigma} {sigma}""#), "");
|
||||
let matrix = |primitives: &mut Self, input: &str, values: &str| primitives.push("feColorMatrix", &format!(r#"in="{input}" type="matrix" values="{values}""#), "");
|
||||
let arithmetic = |primitives: &mut Self, first: &str, second: &str, [k2, k3, k4]: [f64; 3]| {
|
||||
primitives.push("feComposite", &format!(r#"in="{first}" in2="{second}" operator="arithmetic" k2="{k2}" k3="{k3}" k4="{k4}""#), "")
|
||||
};
|
||||
// Linear transfers stay exact through the truncation browsers round their results by
|
||||
let inverted = |primitives: &mut Self, input: &str| {
|
||||
let functions = ["R", "G", "B"].map(|channel| format!(r#"<feFunc{channel} type="linear" slope="-1" intercept="1" />"#)).concat();
|
||||
primitives.push("feComponentTransfer", &format!(r#"in="{input}""#), &functions)
|
||||
};
|
||||
|
||||
// The average of the visible colors alone, as the blur of them made opaque among the rest left out, divided by its alpha.
|
||||
// Where too little of the blur lands on visible colors to know their average, it eases into the pixel's own color.
|
||||
let visible = matrix(self, image, "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 -15");
|
||||
let blurred = blur(self, &visible);
|
||||
let [start, end] = AVERAGE_VISIBILITY_RAMP.map(f64::from);
|
||||
let weighted = matrix(self, &blurred, &format!("1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 {} {}", 1. / (end - start), -start / (end - start)));
|
||||
let own = matrix(self, image, "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0");
|
||||
let average = self.push("feComposite", &format!(r#"in="{weighted}" in2="{own}" operator="over""#), "");
|
||||
|
||||
// A high pass is the colors less their average, around middle gray, which adding the inverted average reaches with an alpha clamped back to full
|
||||
let Some([amount, threshold]) = sharpening else {
|
||||
let inverted_average = inverted(self, &average);
|
||||
let detail = arithmetic(self, &own, &inverted_average, [1., 1., HIGH_PASS_GRAY as f64 - 1.]);
|
||||
return self.push("feComposite", &format!(r#"in="{detail}" in2="{image}" operator="in""#), "");
|
||||
};
|
||||
|
||||
// The coverage sharpens the same way against its own blur, carried as an opaque gray then returned to alpha
|
||||
let coverage_gray = matrix(self, image, "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1");
|
||||
let blurred_coverage = blur(self, image);
|
||||
let blurred_gray = matrix(self, &blurred_coverage, "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 1");
|
||||
let to_alpha = |primitives: &mut Self, gray: &str| matrix(primitives, gray, "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0");
|
||||
|
||||
// Without a threshold, the change is the difference scaled by the amount, so one composite adds it back with nothing rounded between
|
||||
if threshold <= 0. {
|
||||
let colors = arithmetic(self, &own, &average, [1. + amount, -amount, 0.]);
|
||||
let sharpened_gray = arithmetic(self, &coverage_gray, &blurred_gray, [1. + amount, -amount, 0.]);
|
||||
let coverage = to_alpha(self, &sharpened_gray);
|
||||
return self.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), "");
|
||||
}
|
||||
|
||||
// The difference from the average, centered on level 128 and widened as far as it can be before the change it makes saturates, then mapped through the change by tables and added back.
|
||||
// Each table value lies a quarter level above the level it means, which the browser's truncation keeps.
|
||||
// Its scale is whole 128ths and its offset whole levels, as Firefox rounds them, with a zero difference landing under half a level above 128.
|
||||
let ideal_count = ((amount / (1. + threshold)).max(1.) * 127. / 255. * 128.).floor() as i64;
|
||||
let count = (65..=ideal_count.max(65)).rev().find(|count| count % 128 == 0 || count % 128 > 64).unwrap_or(65);
|
||||
let scale = count as f64 / 128.;
|
||||
let widening = scale * 255. / 127.;
|
||||
let offset = (128. - (255. * scale).floor()) / 255.;
|
||||
let table: String = (0..256)
|
||||
.map(|level| {
|
||||
let difference = (level as f64 - 128.) / 127. / widening;
|
||||
let change = unsharp_change(difference as f32, amount as f32, threshold as f32).clamp(-1., 1.) as f64;
|
||||
format!("{:.5}", ((128. + change * 127.).round() + 0.25) / 255.)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let sharpen = |primitives: &mut Self, own: &str, inverted_average: &str, channels: &[&str]| {
|
||||
let difference = arithmetic(primitives, own, inverted_average, [scale, scale, offset]);
|
||||
let functions = channels.iter().map(|channel| format!(r#"<feFunc{channel} type="table" tableValues="{table}" />"#)).collect::<String>();
|
||||
let change = primitives.push("feComponentTransfer", &format!(r#"in="{difference}""#), &functions);
|
||||
arithmetic(primitives, own, &change, [1., 255. / 127., -128. / 127.])
|
||||
};
|
||||
let inverted_average = inverted(self, &average);
|
||||
let colors = sharpen(self, &own, &inverted_average, &["R", "G", "B"]);
|
||||
let inverted_blurred_gray = inverted(self, &blurred_gray);
|
||||
let sharpened_gray = sharpen(self, &coverage_gray, &inverted_blurred_gray, &["R"]);
|
||||
let coverage = to_alpha(self, &sharpened_gray);
|
||||
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image's straight colors made opaque, for composites that combine colors without their coverage.
|
||||
fn opaque_colors(&mut self, image: &str) -> String {
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "")
|
||||
}
|
||||
|
||||
/// The image with each straight color offset by the noise in the GPU's map for `capture`, which holds offsets up to `extent` either way around middle gray, matching the GPU's `add_noise`.
|
||||
/// Until the map is resolved, its middle gray offsets nothing.
|
||||
fn add_noise(&mut self, image: &str, extent: f64, capture: EffectCapture) -> String {
|
||||
let colors = self.opaque_colors(image);
|
||||
let noise = self.map_unresolved_as(capture, Color::from(SRGBA8::new(128, 128, 128, 255)));
|
||||
let attributes = format!(r#"in="{colors}" in2="{noise}" operator="arithmetic" k2="1" k3="{}" k4="{}""#, 2. * extent, -extent);
|
||||
let noisy = self.push("feComposite", &attributes, "");
|
||||
self.push("feComposite", &format!(r#"in="{noisy}" in2="{image}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image shown fully opaque where its coverage passes the threshold level of the GPU's map for `capture` (its gray), by the share of it (its alpha), matching the GPU's `dissolve`.
|
||||
/// Until the map is resolved, its opaque black shows every covered pixel.
|
||||
fn dissolve(&mut self, image: &str, capture: EffectCapture) -> String {
|
||||
let field = self.map_unresolved_as(capture, Color::BLACK);
|
||||
let thresholds = self.push("feColorMatrix", &format!(r#"in="{field}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0""#), "");
|
||||
|
||||
// The coverage less the threshold, which passes at one 8-bit level or more
|
||||
let above = self.push("feComposite", &format!(r#"in="{image}" in2="{thresholds}" operator="arithmetic" k2="1" k3="-1""#), "");
|
||||
let passing = ["0"].into_iter().chain(std::iter::repeat_n("1", 255)).collect::<Vec<_>>().join(" ");
|
||||
let passed = self.push("feComponentTransfer", &format!(r#"in="{above}""#), &format!(r#"<feFuncA type="discrete" tableValues="{passing}" />"#));
|
||||
|
||||
let shown = self.push("feComposite", &format!(r#"in="{passed}" in2="{field}" operator="in""#), "");
|
||||
let colors = self.opaque_colors(image);
|
||||
self.push("feComposite", &format!(r#"in="{colors}" in2="{shown}" operator="in""#), "")
|
||||
}
|
||||
|
||||
/// The image with each pixel's color the lightest (or with `maximum` false, the darkest) in the square of `radius` document pixels around it,
|
||||
/// and its coverage the opposite extreme, matching the GPU's `neighborhood_extreme`, by `feMorphology` of the opaque colors and of the coverage.
|
||||
fn neighborhood_extreme(&mut self, image: &str, radius: f64, maximum: bool) -> String {
|
||||
let radius = radius.max(0.);
|
||||
let (colors_operator, coverage_operator) = if maximum { ("dilate", "erode") } else { ("erode", "dilate") };
|
||||
|
||||
let extreme_within = |primitives: &mut Self, whole_radius: f64| {
|
||||
if whole_radius <= 0. {
|
||||
return image.to_string();
|
||||
}
|
||||
let radius = format!(r#"radius="{whole_radius} {whole_radius}""#);
|
||||
|
||||
// The maximum spreads every covered pixel's straight color made opaque, and the minimum the colors matted over white, lifted back off within the grown coverage
|
||||
let colors = match maximum {
|
||||
true => primitives.push("feColorMatrix", &format!(r#"in="{image}" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), ""),
|
||||
false => primitives.over_gray(image, 1.),
|
||||
};
|
||||
let colors = primitives.push("feMorphology", &format!(r#"in="{colors}" operator="{colors_operator}" {radius}"#), "");
|
||||
let coverage = primitives.push("feMorphology", &format!(r#"in="{image}" operator="{coverage_operator}" {radius}"#), "");
|
||||
match maximum {
|
||||
true => primitives.push("feComposite", &format!(r#"in="{colors}" in2="{coverage}" operator="in""#), ""),
|
||||
false => primitives.uncover(&colors, &coverage, Surroundings::Matted(1.)),
|
||||
}
|
||||
};
|
||||
|
||||
let near = extreme_within(self, radius.floor());
|
||||
let fraction = radius.fract();
|
||||
if fraction <= 0. {
|
||||
return near;
|
||||
}
|
||||
let far = extreme_within(self, radius.ceil());
|
||||
self.push("feComposite", &format!(r#"in="{near}" in2="{far}" operator="arithmetic" k2="{}" k3="{fraction}""#, 1. - fraction), "")
|
||||
}
|
||||
|
||||
/// The image box blurred by a half width of `radius` user units in the color `space` ("sRGB" or "linearRGB"), weighing pixels as the GPU's box does (see [`box_weight`]).
|
||||
/// Where one user unit is one device pixel (`native`), it's a row then a column of `feConvolveMatrix` weights, and otherwise the GPU's result as the map for `capture`,
|
||||
/// with the Gaussian of the same variance standing in until the map resolves.
|
||||
pub(super) fn box_blur(&mut self, image: &str, radius: f64, space: &str, native: bool, capture: EffectCapture) -> String {
|
||||
// Past this the GPU halves the image before its box, which the map follows, and the kernels' markup stays short
|
||||
if !native || radius > MAX_DIRECT_BOX_RADIUS {
|
||||
let sigma = (radius * (radius + 1.) / 3.).sqrt();
|
||||
let attributes = format!(r#"in="{image}" stdDeviation="{sigma} {sigma}" color-interpolation-filters="{space}""#);
|
||||
return self.map_standing_in(capture, "feGaussianBlur", &attributes);
|
||||
}
|
||||
|
||||
// The weights from one end to the other, which read the same turned around, summing to the divisor.
|
||||
// Unlike other kernels, they stay precise past `MAX_PRECISE_KERNEL_AREA`, since browsers quantize between a kernel's least and greatest weights, a box's only two.
|
||||
let reach = radius.ceil() as usize;
|
||||
let weights: Vec<f64> = (0..=2 * reach).map(|index| box_weight(radius, index.abs_diff(reach))).collect();
|
||||
let divisor: f64 = weights.iter().sum();
|
||||
let matrix = weights.iter().map(f64::to_string).collect::<Vec<_>>().join(" ");
|
||||
|
||||
let mut pass = |input: &str, order: [usize; 2], [target_x, target_y]: [usize; 2]| {
|
||||
let attributes = format!(
|
||||
r#"in="{input}" order="{} {}" kernelMatrix="{matrix}" divisor="{divisor}" targetX="{target_x}" targetY="{target_y}" kernelUnitLength="1 1" edgeMode="none" preserveAlpha="false" color-interpolation-filters="{space}""#,
|
||||
order[0], order[1]
|
||||
);
|
||||
self.push("feConvolveMatrix", &attributes, "")
|
||||
};
|
||||
let row = pass(image, [weights.len(), 1], [reach, 0]);
|
||||
pass(&row, [1, weights.len()], [0, reach])
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{write_svg_effects_filter, write_svg_effects_filter_on_lattice};
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::list::Item;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::filters::NoiseDistribution;
|
||||
use graphic_types::{EffectOperation, Effects, MinimumMaximumMode};
|
||||
|
||||
fn convolution_kernel(text: &str, scale: f64, offset: f64) -> EffectOperation {
|
||||
EffectOperation::convolution_kernel(text, Some(scale), offset, false)
|
||||
}
|
||||
|
||||
/// The one layer that filters alone draw, with the content.
|
||||
fn one_layer(effects: &Effects) -> EffectLayers {
|
||||
EffectLayers::plan(effects, BlendMode::Normal, 1., true)
|
||||
}
|
||||
|
||||
fn filter(operations: Vec<EffectOperation>, pixel_exact: bool) -> (String, usize) {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let filter = write_svg_effects_filter_on_lattice(
|
||||
&mut defs,
|
||||
&effects,
|
||||
&one_layer(&effects),
|
||||
0,
|
||||
1.,
|
||||
1.,
|
||||
[DVec2::ZERO, DVec2::splat(10.)],
|
||||
0,
|
||||
&[],
|
||||
0..effects.len(),
|
||||
1.,
|
||||
pixel_exact,
|
||||
)
|
||||
.unwrap();
|
||||
(defs, filter.maps.len())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_turn_their_kernels_around_over_the_visible_colors() {
|
||||
let (defs, maps) = filter(vec![convolution_kernel("0 0 0\n0 0 2\n0 0 0", 2., 51.)], true);
|
||||
assert_eq!(maps, 0);
|
||||
|
||||
// The matrix spans the weight reading the pixel to the right and the pixel itself, turned around, after the stack of the nearest visible colors, nearest on top
|
||||
assert!(
|
||||
defs.contains(r#"<feColorMatrix in="SourceGraphic" type="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 -15""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert!(defs.contains(r#"<feMerge result="effect-11"><feMergeNode in="effect-2" /><feMergeNode in="effect-10" />"#), "{defs}");
|
||||
assert!(defs.contains(r#"<feMergeNode in="effect-3" /><feMergeNode in="effect-1" /></feMerge>"#), "{defs}");
|
||||
assert!(defs.contains(r#"order="2 1" kernelMatrix="1 0" divisor="1" bias="0.2" targetX="0" targetY="0""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="SourceGraphic" operator="in""#), "{defs}");
|
||||
assert!(!defs.contains("-0\""), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_target_their_center_in_any_shape() {
|
||||
// The order, the turned matrix, and the target of the `feConvolveMatrix` carrying out a kernel
|
||||
let matrix_of = |text: &str| {
|
||||
let (defs, _) = filter(vec![convolution_kernel(text, 1., 0.)], true);
|
||||
let attribute = |name: &str| defs.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).unwrap_or_default().to_string();
|
||||
["order", "kernelMatrix", "targetX", "targetY"].map(attribute)
|
||||
};
|
||||
|
||||
// A row lists its weights from the last, centered on its middle, as a column does down, and an even count centers after its middle
|
||||
assert_eq!(matrix_of("1 2 3"), ["3 1", "3 2 1", "1", "0"]);
|
||||
assert_eq!(matrix_of("1\n2\n3"), ["1 3", "3 2 1", "0", "1"]);
|
||||
assert_eq!(matrix_of("1 2\n3 4"), ["2 2", "4 3 2 1", "1", "1"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn convolution_kernels_take_the_gpus_map_off_the_pixel_lattice_or_past_precise_kernels() {
|
||||
// Where a user unit isn't a device pixel, or the kernel holds more weights than browsers keep precise, the colors come from the GPU, given the live coverage
|
||||
let (defs, maps) = filter(vec![convolution_kernel("0 0 0\n0 0 2\n0 0 0", 2., 51.)], false);
|
||||
assert_eq!(maps, 1);
|
||||
// The map lies atop the content, which shows as it is until the map resolves
|
||||
assert!(!defs.contains("feConvolveMatrix") && defs.contains(r#"in2="SourceGraphic" operator="atop""#), "{defs}");
|
||||
let (defs, maps) = filter(
|
||||
vec![convolution_kernel(
|
||||
&"1 1 1 1 1 1 1
|
||||
"
|
||||
.repeat(7),
|
||||
49.,
|
||||
0.,
|
||||
)],
|
||||
true,
|
||||
);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
|
||||
// A fill forks the content into two, which take a map each
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([convolution_kernel("2", 1., 0.)]);
|
||||
let faded = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::ONE], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert_eq!(faded.maps.len(), 2);
|
||||
}
|
||||
|
||||
fn box_blur(radius: f64, gamma: bool) -> EffectOperation {
|
||||
EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius,
|
||||
box_blur: true,
|
||||
gamma,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value of the attribute `name` of each `feConvolveMatrix` in the `defs`, in order.
|
||||
fn attribute_values(defs: &str, name: &str) -> Vec<String> {
|
||||
let primitives = defs.split("<feConvolveMatrix ").skip(1).filter_map(|rest| rest.split("/>").next());
|
||||
let value = |primitive: &str| primitive.split(&format!(r#"{name}=""#)).nth(1)?.split('"').next().map(str::to_string);
|
||||
primitives.filter_map(value).collect()
|
||||
}
|
||||
|
||||
/// The filter of a run of `operations` drawing one layer at `fill`, with whether one user unit is one device pixel, and the captures of its maps.
|
||||
fn filter_at(operations: Vec<EffectOperation>, fill: f32, pixel_exact: bool) -> (String, Vec<EffectCapture>) {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, true);
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, fill, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., pixel_exact).unwrap();
|
||||
(defs, filter.maps.iter().map(|map| map.capture).collect())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_blurs_on_the_pixel_lattice_convolve_a_row_then_a_column_of_the_gpus_weights() {
|
||||
// A whole half width weighs its pixels evenly, a row centered on each pixel and then a column of the row's result, in linear light
|
||||
let (defs, maps) = filter_at(vec![box_blur(2., false)], 1., true);
|
||||
assert!(maps.is_empty(), "{defs}");
|
||||
assert_eq!(attribute_values(&defs, "order"), ["5 1", "1 5"]);
|
||||
assert_eq!(attribute_values(&defs, "kernelMatrix"), ["1 1 1 1 1"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "divisor"), ["5"; 2]);
|
||||
assert_eq!([attribute_values(&defs, "targetX"), attribute_values(&defs, "targetY")], [["2", "0"], ["0", "2"]]);
|
||||
assert!(
|
||||
defs.contains(r#"<feConvolveMatrix in="SourceGraphic""#) && defs.contains(r#"<feConvolveMatrix in="effect-1""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert_eq!(attribute_values(&defs, "color-interpolation-filters"), ["linearRGB"; 2]);
|
||||
assert!(defs.contains(r#"edgeMode="none" preserveAlpha="false""#), "{defs}");
|
||||
|
||||
// A fractional half width weighs the pixels at its ends by the fraction of them it covers, here in gamma
|
||||
let (defs, _) = filter_at(vec![box_blur(2.5, true)], 1., true);
|
||||
assert_eq!(attribute_values(&defs, "order"), ["7 1", "1 7"]);
|
||||
assert_eq!(attribute_values(&defs, "kernelMatrix"), ["0.5 1 1 1 1 1 0.5"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "divisor"), ["6"; 2]);
|
||||
assert_eq!(attribute_values(&defs, "color-interpolation-filters"), ["sRGB"; 2]);
|
||||
|
||||
// Up to the widest box the GPU runs without halving the image, and on the faded fill as well as the content
|
||||
let (defs, maps) = filter_at(vec![box_blur(24., false)], 0.5, true);
|
||||
assert!(maps.is_empty(), "{defs}");
|
||||
assert_eq!(attribute_values(&defs, "order"), ["49 1", "1 49", "49 1", "1 49"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn box_blurs_off_the_pixel_lattice_or_wider_than_the_gpus_direct_box_take_the_gpus_map() {
|
||||
// The GPU's result stands in place of the content's, with a Gaussian of the box's variance until it resolves
|
||||
let (defs, maps) = filter_at(vec![box_blur(2., false)], 1., false);
|
||||
assert_eq!(maps, [EffectCapture { index: 0, plane: 0 }]);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
assert!(
|
||||
defs.contains(r#"<!--effect-map-"#) && defs.contains(r#"<feGaussianBlur in="SourceGraphic" stdDeviation="1.4142135623730951 1.4142135623730951""#),
|
||||
"{defs}"
|
||||
);
|
||||
|
||||
// A box the GPU blurs on a halved image is that box, and a fill forks the content into two maps
|
||||
let (defs, maps) = filter_at(vec![box_blur(24.5, true)], 0.5, true);
|
||||
assert_eq!(maps, [EffectCapture { index: 0, plane: 1 }, EffectCapture { index: 0, plane: 0 }]);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_native_convolutions_each_start_a_filter_of_their_own() {
|
||||
let blur = EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
};
|
||||
let sharpen = convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", 1., 0.);
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([blur, sharpen.clone(), sharpen]);
|
||||
let filter = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 1., 1., [DVec2::ZERO, DVec2::ONE], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
|
||||
// Each convolution reads the result before it as the source of a filter later in the list
|
||||
assert_eq!(filter.ids.len(), 3);
|
||||
assert_eq!(defs.matches(r#"<feColorMatrix in="SourceGraphic""#).count(), 4, "{defs}");
|
||||
}
|
||||
|
||||
/// How many primitives in the `defs` read the result read most.
|
||||
fn most_reads_of_a_result(defs: &str) -> usize {
|
||||
let results = defs.split(r#"result=""#).skip(1).filter_map(|rest| rest.split('"').next());
|
||||
let reads = |result: &str| defs.matches(&format!(r#"in="{result}""#)).count() + defs.matches(&format!(r#"in2="{result}""#)).count();
|
||||
results.map(reads).max().unwrap_or(0)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_convolutions_taking_maps_read_each_result_once() {
|
||||
// A browser works out a filter's input again for each read, so a chain reading any result twice would double its work at each stage
|
||||
let sharpen = || convolution_kernel("0 -1 0\n-1 5 -1\n0 -1 0", 1., 0.);
|
||||
for (fill, pixel_exact) in [(0.5, true), (1., false)] {
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([sharpen(), sharpen(), sharpen(), sharpen()]);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, true);
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, fill, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., pixel_exact).unwrap();
|
||||
assert!(!filter.maps.is_empty(), "{defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_minimums_and_maximums_read_each_result_once_where_the_fill_forks_the_content() {
|
||||
// Natively each reads its input twice, or four times for a fractional radius, so where the fill keeps the filter from splitting they take the GPU's results
|
||||
let minimum_maximum = |radius, mode| EffectOperation::MinimumMaximum { radius, mode };
|
||||
let operations = [1.5, 1., 2.5].map(|radius| minimum_maximum(radius, MinimumMaximumMode::Minimum));
|
||||
let effects = Effects::from_operations(operations.into_iter().chain([minimum_maximum(1.5, MinimumMaximumMode::Maximum)]));
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert_eq!(filter.maps.len(), 8, "both planes of each take a map: {defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chained_unsharp_masks_and_high_passes_read_each_result_once_where_the_fill_forks_the_content() {
|
||||
let unsharp = |threshold| EffectOperation::Sharpen {
|
||||
amount: 200.,
|
||||
radius: 2.,
|
||||
threshold,
|
||||
edges_only: false,
|
||||
};
|
||||
let effects = Effects::from_operations([EffectOperation::HighPass { radius: 2. }, unsharp(10.), EffectOperation::HighPass { radius: 1. }, unsharp(0.)]);
|
||||
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert_eq!(filter.maps.len(), 8, "both planes of each take a map: {defs}");
|
||||
assert_eq!(most_reads_of_a_result(&defs), 1, "{defs}");
|
||||
|
||||
// Without the fork, each runs natively in its own filter reading the one before
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., true);
|
||||
let mut defs = String::new();
|
||||
let filter = write_svg_effects_filter_on_lattice(&mut defs, &effects, &layers, 0, 1., 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1., true).unwrap();
|
||||
assert!(filter.maps.is_empty(), "{defs}");
|
||||
assert_eq!(filter.ids.len(), 4, "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stylize_filters_matte_morph_and_map_where_svg_cant_reach() {
|
||||
// Emboss convolves the content over middle gray, then lifts the gray back off within the coverage in one step
|
||||
let (emboss, _) = filter(vec![EffectOperation::Emboss { angle: 0., height: 2., amount: 100. }], true);
|
||||
assert!(emboss.contains(r#"flood-color="rgb(50%, 50%, 50%)""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"order="3 1" kernelMatrix="1 0 -1" divisor="1" bias="0.5" targetX="1" targetY="0""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 -1 1""#), "{emboss}");
|
||||
assert!(emboss.contains(r#"operator="arithmetic" k2="1" k3="-1""#), "{emboss}");
|
||||
|
||||
// Off the pixel lattice, its whole result comes from the GPU, with the content standing in as it is until the map resolves
|
||||
let (emboss, maps) = filter(vec![EffectOperation::Emboss { angle: 0., height: 2., amount: 100. }], false);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!emboss.contains("feConvolveMatrix") && emboss.contains(r#"--><feOffset in="SourceGraphic""#), "{emboss}");
|
||||
|
||||
// Find Edges takes its whole result as a map too, for the fill and the content each
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::FindEdges]);
|
||||
let find_edges = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
let planes: Vec<usize> = find_edges.maps.iter().map(|map| map.capture.plane).collect();
|
||||
assert_eq!(planes, [1, 0], "the fill and the content each take their own");
|
||||
assert!(!defs.contains("-1 1\""), "nothing lifts white off the maps: {defs}");
|
||||
|
||||
// A fractional radius mixes the morphologies of the whole radii around it
|
||||
let maximum = EffectOperation::MinimumMaximum {
|
||||
radius: 1.25,
|
||||
mode: MinimumMaximumMode::Maximum,
|
||||
};
|
||||
let (maximum, _) = filter(vec![maximum], true);
|
||||
assert!(
|
||||
maximum.contains(r#"operator="dilate" radius="1 1""#) && maximum.contains(r#"operator="erode" radius="2 2""#),
|
||||
"{maximum}"
|
||||
);
|
||||
assert!(maximum.contains(r#"operator="arithmetic" k2="0.75" k3="0.25""#), "{maximum}");
|
||||
|
||||
// The maximum spreads every covered pixel's color, and the minimum lifts white back off its colors within the grown coverage, in a region grown for its erosion
|
||||
assert!(maximum.contains(r#"values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 255 0""#), "{maximum}");
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::MinimumMaximum {
|
||||
radius: 2.,
|
||||
mode: MinimumMaximumMode::Minimum,
|
||||
}]);
|
||||
let minimum = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 1., 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert!(
|
||||
defs.contains(r#"operator="dilate" radius="2 2""#) && defs.contains(r#"values="0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 -1 1""#),
|
||||
"{defs}"
|
||||
);
|
||||
assert_eq!(minimum.region, [DVec2::splat(-5.), DVec2::splat(15.)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sharpening_blurs_natively_and_maps_its_coverage_off_the_lattice() {
|
||||
// Without a threshold, unsharp masking adds the scaled difference from a blur of the visible colors back in one composite, and sharpens the coverage the same way
|
||||
let unsharp = |threshold| EffectOperation::Sharpen {
|
||||
amount: 200.,
|
||||
radius: 2.,
|
||||
threshold,
|
||||
edges_only: false,
|
||||
};
|
||||
let (defs, maps) = filter(vec![unsharp(0.)], false);
|
||||
assert_eq!(maps, 0);
|
||||
assert_eq!(defs.matches("feGaussianBlur").count(), 2, "{defs}");
|
||||
assert_eq!(defs.matches(r#"operator="arithmetic" k2="3" k3="-2" k4="0""#).count(), 2, "{defs}");
|
||||
assert!(!defs.contains("tableValues"), "{defs}");
|
||||
|
||||
// With one, the difference maps through a table of the change it makes, where no change is level 128 written a quarter level up
|
||||
let (defs, _) = filter(vec![unsharp(10.)], false);
|
||||
assert_eq!(defs.matches(r#"<feFuncR type="table" tableValues=""#).count(), 2, "{defs}");
|
||||
assert!(defs.contains(" 0.50294 ") && defs.contains(r#"type="linear" slope="-1" intercept="1""#), "{defs}");
|
||||
|
||||
// The widening is whole 128ths and its offset whole levels, putting a zero difference at 128.04
|
||||
assert_eq!(defs.matches(r#"k2="0.953125" k3="0.953125" k4="-0.45098"#).count(), 2, "{defs}");
|
||||
|
||||
// Edges Only takes its whole result as one map even on the pixel lattice, as unsharp masking does for both planes where the fill forks
|
||||
let edges_only = EffectOperation::Sharpen {
|
||||
amount: 100.,
|
||||
radius: 1.,
|
||||
threshold: 0.,
|
||||
edges_only: true,
|
||||
};
|
||||
let (defs, maps) = filter(vec![edges_only], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feGaussianBlur") && !defs.contains("feConvolveMatrix"), "{defs}");
|
||||
let mut defs = String::new();
|
||||
let effects = Effects::from_operations([unsharp(0.)]);
|
||||
let faded = write_svg_effects_filter(&mut defs, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
let planes: Vec<usize> = faded.maps.iter().map(|map| map.capture.plane).collect();
|
||||
assert_eq!(planes, [1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kernel_applied_to_alpha_convolves_the_coverage_on_the_lattice_and_maps_its_result_off_it() {
|
||||
let sharpen = EffectOperation::convolution_kernel("0 -1 0\n-1 8 -1\n0 -1 0", None, 0., true);
|
||||
|
||||
// The colors convolve straight, and the coverage alongside them as the alpha of a convolution over every channel
|
||||
let (defs, maps) = filter(vec![sharpen.clone()], true);
|
||||
assert_eq!(maps, 0);
|
||||
assert_eq!(defs.matches("<feConvolveMatrix").count(), 2, "{defs}");
|
||||
assert_eq!(defs.matches(r#"preserveAlpha="true""#).count(), 1, "{defs}");
|
||||
|
||||
// Off the lattice, the colors take the coverage they weigh, so the whole result comes as the map
|
||||
let (defs, maps) = filter(vec![sharpen], false);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(!defs.contains("feConvolveMatrix"), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_come_from_the_gpu_combined_with_the_live_content() {
|
||||
// Add Noise adds the map's offsets, scaled out from middle gray to their extent, to the opaque colors within the live coverage
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 40.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let (defs, maps) = filter(vec![noise], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(defs.contains(r#"operator="arithmetic" k2="1" k3="0.8" k4="-0.4""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="SourceGraphic" operator="in""#), "{defs}");
|
||||
// Until the map is resolved, its middle gray offsets nothing
|
||||
assert!(defs.contains(r##"<feFlood flood-color="#808080" flood-opacity="1""##), "{defs}");
|
||||
|
||||
// Dissolve shows the opaque colors where the coverage is at least a level above the map's threshold (its gray), by the share the map gives (its alpha)
|
||||
let (defs, maps) = filter(vec![EffectOperation::Dissolve { opacity: 50., seed: 0 }], true);
|
||||
assert_eq!(maps, 1);
|
||||
assert!(defs.contains(r#"in="SourceGraphic" in2="effect-2" operator="arithmetic" k2="1" k3="-1""#), "{defs}");
|
||||
assert!(defs.contains(r#"in2="effect-1" operator="in""#), "{defs}");
|
||||
// Until the map is resolved, its opaque black shows every covered pixel
|
||||
assert!(defs.contains(r##"<feFlood flood-color="#000000" flood-opacity="1""##), "{defs}");
|
||||
|
||||
// Where the fill forks the content, each plane takes its whole result as a map, so chains of them don't multiply their reads
|
||||
let mut faded = String::new();
|
||||
let effects = Effects::from_operations([EffectOperation::Dissolve { opacity: 50., seed: 0 }]);
|
||||
let filter = write_svg_effects_filter(&mut faded, &effects, &one_layer(&effects), 0, 0.5, 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[], 0..effects.len(), 1.).unwrap();
|
||||
assert_eq!(filter.maps.len(), 2);
|
||||
let table = defs
|
||||
.split(r#"<feFuncA type="discrete" tableValues=""#)
|
||||
.nth(1)
|
||||
.and_then(|rest| rest.split('"').next())
|
||||
.unwrap_or_default();
|
||||
assert_eq!(table.split(' ').collect::<Vec<_>>(), [vec!["0"], vec!["1"; 255]].concat(), "{defs}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_change_endless_colors_within_the_view() {
|
||||
use crate::{Render, RenderParams, RenderSvgSegmentList, SvgRender};
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
|
||||
// A color with Add Noise after Levels draws through a filter over the view, with the noise's map and the Levels within it
|
||||
let levels = graphic_types::Adjustment::Exposure {
|
||||
exposure: 1.,
|
||||
offset: 0.,
|
||||
gamma_correction: 1.,
|
||||
};
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let effects = Effects::from_operations([noise, EffectOperation::Adjustment(levels)]);
|
||||
let color = Item::new_from_element(core_types::Color::BLUE).with_attribute(ATTR_EFFECTS, effects);
|
||||
let params = RenderParams {
|
||||
view: Some(Footprint {
|
||||
transform: DAffine2::IDENTITY,
|
||||
resolution: glam::UVec2::splat(32),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut render = SvgRender::new();
|
||||
List::new_from_item(color).render_svg(&mut render, ¶ms);
|
||||
assert_eq!(render.effect_maps.len(), 1);
|
||||
assert!(render.svg.to_svg_string().contains(r#"filter="url(#"#), "{}", render.svg.to_svg_string());
|
||||
assert!(render.svg_defs.contains(r#"x="0" y="0" width="32" height="32""#), "{}", render.svg_defs);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_fields_leave_a_mask_on_endless_colors_in_its_own_place() {
|
||||
use crate::{Render, RenderParams, SvgRender};
|
||||
use core_types::list::{ATTR_EFFECTS, List};
|
||||
use core_types::transform::Footprint;
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||||
use graphic_types::{Graphic, MaskMode};
|
||||
|
||||
// A gradient mask without a transform lies across the color's own unit square, as on the GPU, rather than across the view
|
||||
let stops = [(0., core_types::Color::BLACK), (1., core_types::Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let noise = EffectOperation::AddNoise {
|
||||
amount: 20.,
|
||||
distribution: NoiseDistribution::Uniform,
|
||||
monochromatic: false,
|
||||
seed: 0,
|
||||
};
|
||||
let mask = EffectOperation::Mask {
|
||||
mask: Graphic::from(Gradient::new(stops)),
|
||||
mode: MaskMode::Luminance,
|
||||
density: 100.,
|
||||
feather: 0.,
|
||||
invert: false,
|
||||
};
|
||||
let color = Item::new_from_element(core_types::Color::BLUE).with_attribute(ATTR_EFFECTS, Effects::from_operations([noise, mask]));
|
||||
|
||||
let params = RenderParams {
|
||||
view: Some(Footprint {
|
||||
transform: DAffine2::IDENTITY,
|
||||
resolution: glam::UVec2::splat(64),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let mut render = SvgRender::new();
|
||||
List::new_from_item(color).render_svg(&mut render, ¶ms);
|
||||
|
||||
// The gradient spans its own unit square rather than the 64 units in view
|
||||
let defs = &render.svg_defs;
|
||||
assert!(defs.contains("<mask") && defs.contains(r#"x1="0" y1="0" x2="1" y2="0">"#), "{defs}");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
//! SVG masks of content by another graphic: SVG's own `<mask>` for the masks before and after the other effects, and filter primitives for those between them.
|
||||
//! Both forms run the same steps as the GPU's passes: the coverage, its feather, then its density.
|
||||
//! Both forms run the same steps as the GPU's passes: the coverage, its feather, then its density. Also the masked radius blur's filter primitives.
|
||||
|
||||
use super::{ENDLESS_EXTENT, Render, RenderParams, RenderSvgSegmentList, SvgFilterPrimitives, SvgRender, drawn_bounding_box, nested_effects_reach, svg_drawn_paint, svg_effects_region};
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
@@ -8,7 +8,7 @@ use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
|
||||
use core_types::uuid::generate_uuid;
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::effects::{EffectOperation, Effects, spans_along_axes};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma};
|
||||
use graphic_types::masks::{MaskMode, mask_density_line, mask_feather_sigma, masked_radius_blur_weight};
|
||||
use graphic_types::{Appearance, Graphic};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
use std::fmt::Write;
|
||||
@@ -74,6 +74,23 @@ pub(super) fn holds_effects(graphic: &Graphic) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the graphic or anything nested in it is a GPU image, which SVG markup can't draw.
|
||||
fn holds_gpu_image(graphic: &Graphic) -> bool {
|
||||
match graphic {
|
||||
Graphic::RasterGPU(_) => true,
|
||||
Graphic::RasterGPUList(list) => !list.is_empty(),
|
||||
Graphic::Graphic(item) => holds_gpu_image(item.element()),
|
||||
Graphic::GraphicList(list) => list.iter_element_values().any(holds_gpu_image),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether SVG draws a blur's `radius_mask` as markup in its filter, keeping the blur resolution-independent, rather than taking its luminance as the GPU's map.
|
||||
/// Markup embedded as an image reaches no maps of the radius mask's own effects.
|
||||
pub(super) fn radius_mask_draws_as_markup(radius_mask: &Graphic) -> bool {
|
||||
!holds_effects(radius_mask) && !holds_gpu_image(radius_mask)
|
||||
}
|
||||
|
||||
/// A mask's graphic placed by its content's `placement`, which it follows.
|
||||
pub(super) fn placed(mask: &Graphic, placement: DAffine2) -> Graphic {
|
||||
Graphic::Graphic(Box::new(Item::new_from_element(mask.clone()).with_attribute(ATTR_TRANSFORM, placement)))
|
||||
@@ -127,7 +144,7 @@ pub(super) fn masked_extent(effects: &Effects, placement: DAffine2) -> Option<[D
|
||||
break;
|
||||
}
|
||||
|
||||
let reach = 3. * svg_feather_sigma(feather, length_scale) + nested_effects_reach(&mask, placement, EffectOperation::painted_reach);
|
||||
let reach = 3. * svg_feather_sigma(feather, length_scale) + nested_effects_reach(&mask, placement, |_| true);
|
||||
let [min, max] = [min - reach, max + reach];
|
||||
extent = Some(match extent {
|
||||
// Masks that don't overlap leave an empty extent at the first one's corner
|
||||
@@ -177,7 +194,7 @@ pub(super) fn write_endless_content_mask(render: &mut SvgRender, effects: &Effec
|
||||
let sigma = svg_feather_sigma(feather, length_scale);
|
||||
let region = match drawn_bounding_box(&mask, DAffine2::IDENTITY) {
|
||||
RenderBoundingBox::Rectangle([min, max]) => {
|
||||
let reach = 3. * sigma + nested_effects_reach(&mask, DAffine2::IDENTITY, EffectOperation::painted_reach);
|
||||
let reach = 3. * sigma + nested_effects_reach(&mask, DAffine2::IDENTITY, |_| true);
|
||||
[min - reach, max + reach]
|
||||
}
|
||||
_ => [DVec2::splat(-ENDLESS_EXTENT), DVec2::splat(ENDLESS_EXTENT)],
|
||||
@@ -249,6 +266,46 @@ fn write_combined_mask(svg_defs: &mut String, masks: &[&NativeMask], endless: bo
|
||||
}
|
||||
|
||||
impl SvgFilterPrimitives {
|
||||
/// Each level's parts of a masked radius blur's interpolation, in the alpha of its result, from the radius mask's 8-bit `luminance` (in alpha) for the `levels` of its radius, matching `masked_radius_blur_interpolation`.
|
||||
pub(super) fn masked_radius_blur_weights(&mut self, luminance: &str, levels: &[f64]) -> Vec<String> {
|
||||
(0..levels.len())
|
||||
.map(|level| {
|
||||
// A quarter of a level past each whole one lands on it whether a browser rounds or truncates, and none stays exactly none for one that doesn't
|
||||
let table = (0..=255_u8)
|
||||
.map(|code| {
|
||||
let weight = masked_radius_blur_weight(level, code, levels) as f64;
|
||||
let biased = if weight > 0. { weight + 0.25 } else { 0. };
|
||||
format!("{:.6}", (biased / 255.).min(1.))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
self.push("feComponentTransfer", &format!(r#"in="{luminance}""#), &format!(r#"<feFuncA type="table" tableValues="{table}" />"#))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The `image` blurred by each of a masked radius blur's Gaussian `levels` (in user units) weighed by its `weights` and summed, matching the GPU's `masked_radius_blur`.
|
||||
/// The levels blur in gamma if `gamma` and in linear light otherwise.
|
||||
pub(super) fn masked_radius_blur(&mut self, image: &str, weights: &[String], levels: &[f64], gamma: bool) -> String {
|
||||
let space = if gamma { "sRGB" } else { "linearRGB" };
|
||||
|
||||
let mut sum: Option<String> = None;
|
||||
for (&sigma, weight) in levels.iter().zip(weights) {
|
||||
let blurred = match sigma >= NEGLIGIBLE_LENGTH {
|
||||
true => self.push("feGaussianBlur", &format!(r#"in="{image}" stdDeviation="{sigma} {sigma}" color-interpolation-filters="{space}""#), ""),
|
||||
false => image.to_string(),
|
||||
};
|
||||
// Weighed and summed in gamma, the filter's own space, on purpose (see `masked_radius_blur_interpolation`)
|
||||
let weighted = self.push("feComposite", &format!(r#"in="{blurred}" in2="{weight}" operator="in""#), "");
|
||||
|
||||
sum = Some(match sum {
|
||||
Some(sum) => self.add(&sum, &weighted),
|
||||
None => weighted,
|
||||
});
|
||||
}
|
||||
sum.unwrap_or_else(|| image.to_string())
|
||||
}
|
||||
|
||||
/// The `mode`'s coverage of a mask graphic's `image`, in the alpha of the result, matching the GPU's `mask_coverage`.
|
||||
pub(super) fn mask_coverage(&mut self, image: &str, mode: MaskMode) -> String {
|
||||
match mode {
|
||||
|
||||
@@ -5,6 +5,7 @@ use graphic_types::effect_layers::EffectLayers;
|
||||
use graphic_types::effects::EffectCapture;
|
||||
use graphic_types::generator::GeneratorPattern;
|
||||
use graphic_types::raster_types::{CPU, Raster, Texture};
|
||||
use graphic_types::resampling::EffectFrame;
|
||||
use graphic_types::{Adjustment, EffectOperation, Effects};
|
||||
use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape, Stroke};
|
||||
use std::borrow::Cow;
|
||||
@@ -56,6 +57,7 @@ pub trait EffectsRenderer: Send {
|
||||
/// Renders the content `draw` draws, and each of the effects' drawn paints `draw_paint` draws by index, placed by `view` in premultiplied textures of `size`,
|
||||
/// returning one for each of the `layers` that `effects` carried out on it draw, with the mode it blends by.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is what effects relative to the content's extent take as their own.
|
||||
/// With a `capture`, the only texture instead holds that effect's coverage, as black with it in alpha.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
fn render_effects(
|
||||
@@ -67,6 +69,7 @@ pub trait EffectsRenderer: Send {
|
||||
fill: f32,
|
||||
opacity: f32,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
capture: Option<EffectCapture>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
@@ -376,6 +379,8 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
/// Draws the content `draw` draws with `effects` carried out on it in their `effect_space` (placed in the space of the drawn content), within `bounds` in that space (or everywhere for `None`),
|
||||
/// drawing again for each part of a split render. `draw_paint` draws each of the effects' drawn paints by its index among them, and `fill` fades the content but not the shadows and glows cast from it.
|
||||
/// The content blends by `blend_mode` and the effects by their own modes, each faded by `opacity`, onto what lies beneath, or with every effect flattened into the content's image if not `layered`.
|
||||
/// The `frame` places the unit square on the content's bounds in its own space, carried through its transform into the space of the drawn content, for effects relative to the content's extent.
|
||||
/// It comes with how far the content already paints past it in document units (its overhang), as a group's nested effects do, which those effects carry along.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub fn draw_effects(
|
||||
&mut self,
|
||||
@@ -386,12 +391,16 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
layered: bool,
|
||||
bounds: Option<Rect>,
|
||||
effect_space: DAffine2,
|
||||
frame: Option<(DAffine2, f64)>,
|
||||
draw_paint: &mut dyn FnMut(usize, &mut VelloSceneBuilder),
|
||||
draw: &mut dyn FnMut(&mut VelloSceneBuilder),
|
||||
) {
|
||||
let capture = self.effect_capture.take();
|
||||
let effect_to_device = DAffine2::from_cols_array(&self.view.as_coeffs()) * effect_space;
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) || !effect_to_device.matrix2.determinant().is_normal() {
|
||||
|
||||
// The effect space is tested alone too, since a tilted view can leave a rounding residue in the product where its own determinant is 0
|
||||
let collapsed = !effect_to_device.matrix2.determinant().is_normal() || !effect_space.matrix2.determinant().is_normal();
|
||||
if !self.effects_renderer.as_ref().is_some_and(|renderer| renderer.renders_effects()) || collapsed {
|
||||
self.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), opacity * fill);
|
||||
draw(self);
|
||||
self.pop_layer();
|
||||
@@ -400,11 +409,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let layers = EffectLayers::plan(effects, blend_mode, fill, layered);
|
||||
|
||||
// The texture follows the viewport's axes if the effect space only turns and evenly scales, or else its own axes, scaled evenly to keep every direction's detail.
|
||||
// A box blur, which isn't round, turns with its space only along that space's axes.
|
||||
let has_box_blur = effects
|
||||
.operations()
|
||||
.any(|operation| matches!(operation, EffectOperation::Blur { box_blur: true, .. }) && !operation.changes_nothing());
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_box_blur || is_axis_aligned(effect_to_device.matrix2));
|
||||
// A box blur or a minimum or maximum, whose square neighborhoods aren't round, turns with its space only along that space's axes.
|
||||
let has_square_kernel = effects.operations().any(|operation| {
|
||||
let square = matches!(operation, EffectOperation::Blur { box_blur: true, .. } | EffectOperation::MinimumMaximum { .. });
|
||||
square && !operation.changes_nothing()
|
||||
});
|
||||
let follows_viewport = is_similarity(effect_to_device.matrix2) && (!has_square_kernel || is_axis_aligned(effect_to_device.matrix2));
|
||||
let (frame_to_device, lengths_to_frame) = match follows_viewport {
|
||||
true => (DAffine2::IDENTITY, effect_to_device.matrix2),
|
||||
false => {
|
||||
@@ -414,22 +424,54 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
};
|
||||
let device_to_frame = frame_to_device.inverse();
|
||||
let document_to_frame = Affine::new(device_to_frame.to_cols_array()) * self.view;
|
||||
let length_scale = lengths_to_frame.determinant().abs().sqrt();
|
||||
let (reach, working_reach) = (effects.reach() * length_scale, effects.working_reach() * length_scale);
|
||||
|
||||
// The content and what its effects read past it, reaching into the viewport and rounded out to whole pixels of the frame.
|
||||
// Past the view, what they read without painting (like a mask's feather) is kept as far as it fits without lowering the resolution.
|
||||
// Effects relative to the content's extent paint farther from larger content, measured in their effect space, and others read past what they paint, like a kernel or a mask's feather
|
||||
let (effect_frame, overhang) = (frame.map(|(frame, _)| frame), frame.map_or(0., |(_, overhang)| overhang));
|
||||
let read_beyond_painted = effects.required_reach() - effects.reach();
|
||||
let reach = match bounds {
|
||||
Some(bounds) => effects.run_reach_around(effect_space, [DVec2::new(bounds.x0, bounds.y0), DVec2::new(bounds.x1, bounds.y1)], overhang) + read_beyond_painted,
|
||||
None => effects.required_reach(),
|
||||
};
|
||||
let length_scale = lengths_to_frame.determinant().abs().sqrt();
|
||||
let (reach, working_reach) = (reach * length_scale, (reach + effects.working_reach() - effects.required_reach()) * length_scale);
|
||||
|
||||
// Effects relative to the content's extent take its frame, measured in their effect space
|
||||
let effect_to_frame = device_to_frame * effect_to_device;
|
||||
let effect_frame = effect_frame.and_then(|frame| EffectFrame::new(effect_space.inverse() * frame, effect_to_frame));
|
||||
|
||||
// The content and what its effects read past it, reaching into the viewport and rounded out to whole pixels of the frame, and its effect frame where effects paint anywhere in it.
|
||||
// Past the view, what they read without painting or reading around each pixel (like a mask's feather) is kept as far as it fits without lowering the resolution.
|
||||
let viewport = Rect::new(0., 0., self.width() as f64, self.height() as f64);
|
||||
let viewport_in_frame = Affine::new(device_to_frame.to_cols_array()).transform_rect_bbox(viewport);
|
||||
let content_bounds = bounds.map_or(viewport_in_frame, |bounds| document_to_frame.transform_rect_bbox(bounds));
|
||||
let mut content_bounds = bounds.map_or(viewport_in_frame, |bounds| document_to_frame.transform_rect_bbox(bounds));
|
||||
if let Some(frame) = effect_frame.filter(|_| bounds.is_some() && effects.paint_across_frame()) {
|
||||
let [min, max] = frame.pixel_bounds();
|
||||
content_bounds = content_bounds.union(Rect::new(min.x, min.y, max.x, max.y));
|
||||
}
|
||||
let max_size = self.max_texture_size.min(u16::MAX as u32);
|
||||
let max_area = MAX_EFFECTS_AREA_PER_VIEWPORT_AREA * viewport.area();
|
||||
let painted_region = content_bounds.inflate(working_reach, working_reach).intersect(viewport_in_frame.inflate(reach, reach));
|
||||
let read_past_view = reach + growth_that_fits(painted_region, max_area, max_size as f64).min(working_reach - reach).max(0.);
|
||||
let region = content_bounds
|
||||
let mut region = content_bounds
|
||||
.inflate(working_reach, working_reach)
|
||||
.intersect(viewport_in_frame.inflate(read_past_view, read_past_view))
|
||||
.expand();
|
||||
|
||||
// Some read beyond the region, like a radial blur along its arcs, and content without bounds lies wherever they read
|
||||
let visible = content_bounds.inflate(reach, reach).intersect(viewport_in_frame);
|
||||
let corners = |rect: Rect| [DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)];
|
||||
if let Some([min, max]) = effects.source_region(corners(visible), effect_frame.as_ref(), effect_to_frame) {
|
||||
if !(visible.width() > 0. && visible.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
let source = Rect::new(min.x, min.y, max.x, max.y);
|
||||
region = match bounds {
|
||||
Some(_) => source.intersect(content_bounds.inflate(working_reach, working_reach)),
|
||||
None => source,
|
||||
}
|
||||
.expand();
|
||||
}
|
||||
|
||||
if !(region.width() > 0. && region.height() > 0.) {
|
||||
return;
|
||||
}
|
||||
@@ -441,10 +483,12 @@ impl<'a> VelloSceneBuilder<'a> {
|
||||
let size = UVec2::new(size_along(region.width()), size_along(region.height()));
|
||||
let origin = region.origin().to_vec2();
|
||||
|
||||
let content_view = Affine::scale(resolution) * Affine::translate(-origin) * document_to_frame;
|
||||
let frame_to_pixels = Affine::scale(resolution) * Affine::translate(-origin);
|
||||
let content_view = frame_to_pixels * document_to_frame;
|
||||
let effect_to_pixels = DAffine2::from_cols_array(&content_view.as_coeffs()) * effect_space;
|
||||
let effect_frame = effect_frame.map(|frame| frame.placed(DAffine2::from_cols_array(&frame_to_pixels.as_coeffs())));
|
||||
let Some(renderer) = self.effects_renderer.as_deref_mut() else { return };
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, capture, draw_paint, draw);
|
||||
let results = renderer.render_effects(size, content_view, effects, &layers, fill, opacity, effect_to_pixels, effect_frame, capture, draw_paint, draw);
|
||||
|
||||
// Draw each layer where the content was, blended onto what lies beneath, except a captured coverage, which is drawn as it is
|
||||
let area = Rect::new(0., 0., size.x as f64, size.y as f64);
|
||||
|
||||
@@ -29,6 +29,7 @@ fn operation(primitives: &[Primitive]) -> Option<EffectOperation> {
|
||||
|
||||
match primitive.kind() {
|
||||
Kind::GaussianBlur(blur) if *blur.input() == Input::SourceGraphic => Some(EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: standard_deviation(blur.std_dev_x().get(), blur.std_dev_y().get()),
|
||||
box_blur: false,
|
||||
gamma: primitive.color_interpolation() == ColorInterpolation::SRGB,
|
||||
|
||||
@@ -314,6 +314,7 @@ fn a_gaussian_blur_filter_becomes_a_blur_of_the_geometric_mean_of_its_standard_d
|
||||
assert_eq!(
|
||||
effects,
|
||||
Some(&Effects::from_operations([EffectOperation::Blur {
|
||||
radius_mask: Graphic::default(),
|
||||
radius: 2.,
|
||||
box_blur: false,
|
||||
gamma: false
|
||||
|
||||
@@ -1762,17 +1762,17 @@ impl GradientEvaluator {
|
||||
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
|
||||
#[widget(Radio)]
|
||||
pub enum GradientSpread {
|
||||
/// Extends the end colors outward.
|
||||
/// Extends the outermost edges outward.
|
||||
#[default]
|
||||
#[icon("GradientSpreadPad")]
|
||||
Pad,
|
||||
/// Loops the gradient by mirroring back-and-forth.
|
||||
/// Loops by mirroring back and forth.
|
||||
#[icon("GradientSpreadReflect")]
|
||||
Reflect,
|
||||
/// Loops the gradient as copies of itself.
|
||||
/// Loops as copies of itself.
|
||||
#[icon("GradientSpreadRepeat")]
|
||||
Repeat,
|
||||
/// Cuts off to transparency beyond the ends.
|
||||
/// Cuts off to transparency beyond the outer edges.
|
||||
#[icon("GradientSpreadClear")]
|
||||
Clear,
|
||||
}
|
||||
|
||||
@@ -108,6 +108,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
||||
StepKind::PhotoFilter => ("photo_filter", Some([Gamma, Gamma])),
|
||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -353,6 +353,11 @@ fn invert(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(1. - color.rgb, color.a);
|
||||
}
|
||||
|
||||
// Each channel inverted past middle gray, folding it back down
|
||||
fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||
}
|
||||
|
||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||
|
||||
@@ -5,32 +5,43 @@ use bytemuck::{Pod, Zeroable};
|
||||
use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::{DMat2, DVec2, UVec2};
|
||||
use glam::{DAffine2, DVec2, UVec2};
|
||||
use graphic_types::effect_layers::{EffectLayers, EffectPiece, LayerPart, PiecePlace, is_pixel_filter};
|
||||
use graphic_types::effects::{EffectCapture, GRADIENT_GLOW_FADE, GRADIENT_TABLE_SIZE, GlowFill, OutlineFill, bevel_light, contour_gradient_span, grow_and_tent, outline_extents, shadow_offset};
|
||||
use graphic_types::masks::mask_feather_sigma;
|
||||
use graphic_types::masks::{mask_feather_sigma, masked_radius_blur_levels};
|
||||
use graphic_types::resampling::{DisplacementField, EffectFrame, FrameWarp, RadialBlur, warp_frame};
|
||||
use graphic_types::{Adjustment, BevelDirection, BevelStyle, BevelTechnique, EffectOperation, Effects, GlowSource, GlowTechnique};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, MAX_KERNEL_REACH, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, MAX_DIRECT_BOX_RADIUS, NEGLIGIBLE_LENGTH, chamfer_passes};
|
||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use wgpu::util::DeviceExt;
|
||||
|
||||
mod filters;
|
||||
mod masks;
|
||||
mod resample;
|
||||
mod styles;
|
||||
|
||||
use resample::Displacement;
|
||||
|
||||
/// The format of the images the passes produce, with the precision to keep soft gradients smooth.
|
||||
pub(crate) const WORKING_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
|
||||
|
||||
/// The format of the silhouettes shadows and glows are cast from, which hold only coverage, or a distance.
|
||||
const COVERAGE_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::R16Float;
|
||||
|
||||
/// The format of sums carried between passes, which must keep full precision.
|
||||
const SUMS_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba32Float;
|
||||
|
||||
/// How many samples of a contour the shaders interpolate between, enough to follow its spline to well within a level.
|
||||
const CONTOUR_SAMPLES: u32 = 256;
|
||||
/// How many samples of a glow's or outline's gradient the shaders read.
|
||||
const GRADIENT_SAMPLES: u32 = GRADIENT_TABLE_SIZE as u32;
|
||||
|
||||
/// The most taps one kernel pass weighs, matching the length of the shader's array, which holds a kernel of [`MAX_KERNEL_REACH`] texels to each side in pairs.
|
||||
const MAX_TAPS: usize = 1 + 2 * MAX_KERNEL_REACH.div_ceil(2);
|
||||
/// How many taps the shader's parameters hold, enough for a blur kernel of [`raster_kernels::effect_kernels::MAX_KERNEL_REACH`] texels to each side in pairs, and few enough that a pass reading them all stays quick.
|
||||
/// A filter kernel with more takes a pass for each part of them.
|
||||
const PARAMETER_TAPS: usize = 81;
|
||||
const _: () = assert!(PARAMETER_TAPS > 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2));
|
||||
|
||||
/// How many renders a pooled texture survives unused before it is freed.
|
||||
const UNUSED_TEXTURE_RENDER_LIMIT: u64 = 3;
|
||||
@@ -46,7 +57,7 @@ struct Parameters {
|
||||
tap_count: u32,
|
||||
color: [f32; 4],
|
||||
values: [f32; 4],
|
||||
taps: [[f32; 4]; MAX_TAPS],
|
||||
taps: [[f32; 4]; PARAMETER_TAPS],
|
||||
}
|
||||
|
||||
impl Default for Parameters {
|
||||
@@ -121,24 +132,35 @@ pub(crate) struct EffectPasses {
|
||||
|
||||
impl EffectPasses {
|
||||
pub(crate) fn new(device: &wgpu::Device, adapter: &wgpu::Adapter) -> Self {
|
||||
let renders_working_formats = [WORKING_FORMAT, COVERAGE_FORMAT]
|
||||
let renders_working_formats = [WORKING_FORMAT, COVERAGE_FORMAT, SUMS_FORMAT]
|
||||
.into_iter()
|
||||
.all(|format| adapter.get_texture_format_features(format).allowed_usages.contains(wgpu::TextureUsages::RENDER_ATTACHMENT));
|
||||
if !renders_working_formats {
|
||||
log::warn!("This GPU can't render into the formats layer effects need, so content draws without its effects");
|
||||
}
|
||||
|
||||
// The styles' and masks' passes live in files of their own, sharing this one's bindings and helpers
|
||||
// The filters', resampling, styles', and masks' passes live in files of their own, sharing this one's bindings and helpers
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("vello_effects.wgsl"),
|
||||
source: wgpu::ShaderSource::Wgsl(concat!(include_str!("vello_effects.wgsl"), include_str!("vello_styles.wgsl"), include_str!("vello_masks.wgsl")).into()),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
concat!(
|
||||
include_str!("vello_effects.wgsl"),
|
||||
include_str!("vello_hash.wgsl"),
|
||||
include_str!("vello_effects/filters.wgsl"),
|
||||
include_str!("vello_resample.wgsl"),
|
||||
include_str!("vello_styles.wgsl"),
|
||||
include_str!("vello_masks.wgsl")
|
||||
)
|
||||
.into(),
|
||||
),
|
||||
});
|
||||
|
||||
let texture_entry = |binding| wgpu::BindGroupLayoutEntry {
|
||||
// The `content` input is only loaded rather than sampled, so it can also take a 32-bit float texture, which can't be filtered
|
||||
let texture_entry = |binding, filterable| wgpu::BindGroupLayoutEntry {
|
||||
binding,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: true },
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
@@ -147,9 +169,9 @@ impl EffectPasses {
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("vello_effects_bind_group_layout"),
|
||||
entries: &[
|
||||
texture_entry(0),
|
||||
texture_entry(1),
|
||||
texture_entry(2),
|
||||
texture_entry(0, true),
|
||||
texture_entry(1, true),
|
||||
texture_entry(2, false),
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 3,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
@@ -205,7 +227,8 @@ impl EffectPasses {
|
||||
}
|
||||
|
||||
/// Carries out `effects` on `content`, a texture of premultiplied pixels, returning each of the `layers` they draw in a pooled texture of [`WORKING_FORMAT`] the same size, with the mode it blends by.
|
||||
/// `lengths_to_pixels` maps the effects' lengths onto the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// `effect_to_pixels` places the effects' space on the texture's pixels, `fill` fades the content but not the shadows and glows cast from it, and `opacity` fades the layers.
|
||||
/// The `frame`, in the texture's pixels, is the content's extent, which displacements take as their own.
|
||||
/// `paints` holds the effects' drawn paints in order, each rendered over the same pixels as the content.
|
||||
/// With a `capture`, the only result is instead that effect's coverage, as black with it in alpha, or the share [`EffectCapture::THROUGH_MASK`] names.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
@@ -219,7 +242,8 @@ impl EffectPasses {
|
||||
layers: &EffectLayers,
|
||||
fill: f32,
|
||||
opacity: f32,
|
||||
lengths_to_pixels: DMat2,
|
||||
effect_to_pixels: DAffine2,
|
||||
frame: Option<EffectFrame>,
|
||||
paints: &[wgpu::Texture],
|
||||
capture: Option<EffectCapture>,
|
||||
) -> Vec<(wgpu::Texture, BlendMode)> {
|
||||
@@ -231,6 +255,7 @@ impl EffectPasses {
|
||||
textures,
|
||||
size: UVec2::new(content.width(), content.height()),
|
||||
};
|
||||
let lengths_to_pixels = effect_to_pixels.matrix2;
|
||||
let length_scale = lengths_to_pixels.determinant().abs().sqrt();
|
||||
|
||||
// The content at full strength, which casts every silhouette, read from the content itself (whatever its format) until a pass replaces it
|
||||
@@ -251,8 +276,13 @@ impl EffectPasses {
|
||||
let knocks_out_by_layer = |piece: &EffectPiece| piece.knocks_out && (fill < 1. || layers.knockout_cover(piece.capture, opacity) < 1. || layers.masks_fade_knockout_cover(piece.capture));
|
||||
let capture_needs_content_layer = capture == Some(EffectCapture::THROUGH_MASK) || captured_piece.as_ref().is_some_and(knocks_out_by_layer);
|
||||
|
||||
// Each operation with its index, for a capture to name, leaving out those that change nothing so they don't split the runs of adjustments around them
|
||||
let operations: Vec<(usize, EffectOperation)> = effects.operations().enumerate().filter(|(_, operation)| !changes_nothing(operation, length_scale)).collect();
|
||||
// Each operation with its index, for a capture to name, leaving out those that change nothing so they don't split the runs of adjustments around them.
|
||||
// A blur whose result is captured runs however slight, so its map still holds the content.
|
||||
let captured_blur =
|
||||
|index: usize, operation: &EffectOperation| matches!(operation, EffectOperation::Blur { .. }) && !operation.changes_nothing() && capture.is_some_and(|capture| capture.index == index);
|
||||
let operations: Vec<(usize, EffectOperation)> = (effects.operations().enumerate())
|
||||
.filter(|(index, operation)| captured_blur(*index, operation) || !changes_nothing(operation, length_scale))
|
||||
.collect();
|
||||
let mut paints = paints.iter();
|
||||
for (position, (index, operation)) in operations.iter().enumerate() {
|
||||
let index = *index;
|
||||
@@ -276,15 +306,82 @@ impl EffectPasses {
|
||||
};
|
||||
|
||||
match *operation {
|
||||
EffectOperation::Blur { radius, box_blur, gamma } => {
|
||||
EffectOperation::Blur { radius, box_blur, gamma, .. } if !operation.varies_blur_radius() => {
|
||||
let radius = radius * length_scale;
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
|
||||
// The blur gives its input back to the pool, so it takes a copy of the content rather than the content itself
|
||||
let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } };
|
||||
let unblurred = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.blur(unblurred, kernel, !gamma));
|
||||
filled = filled.map(|filled| recorder.blur(filled, kernel, !gamma));
|
||||
if box_blur && radius > MAX_DIRECT_BOX_RADIUS {
|
||||
// Past the widest box blurred directly, a box sums running sums as a masked box does with every pixel at the full radius, exact rather than blurred on a halved image
|
||||
let every_pixel = Parameters { color: [1.; 4], ..Default::default() };
|
||||
let full_radius = recorder.run("flood", COVERAGE_FORMAT, recorder.size, content, None, None, every_pixel);
|
||||
recorder.masked_box_blur(content, &mut full, &mut filled, &full_radius, DVec2::splat(radius), !gamma, true);
|
||||
recorder.textures.release(full_radius);
|
||||
} else {
|
||||
// The blur gives its input back to the pool, so it takes a copy of the content rather than the content itself
|
||||
let kernel = if box_blur { BlurKernel::Box { radius } } else { BlurKernel::Gaussian { sigma: radius } };
|
||||
let unblurred = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.blur(unblurred, kernel, !gamma));
|
||||
filled = filled.map(|filled| recorder.blur(filled, kernel, !gamma));
|
||||
}
|
||||
|
||||
// SVG takes the results of a box blur it can't run natively as maps
|
||||
if let Some(full) = &full {
|
||||
capture_plane(&mut recorder, 0, full, true);
|
||||
}
|
||||
if let Some(filled) = &filled {
|
||||
capture_plane(&mut recorder, 1, filled, true);
|
||||
}
|
||||
}
|
||||
// A blur varying its radius by its radius mask
|
||||
EffectOperation::Blur { radius, box_blur, gamma, .. } => {
|
||||
let Some(map) = paints.next() else { continue };
|
||||
if radius * length_scale < NEGLIGIBLE_LENGTH && !captured_blur(index, operation) {
|
||||
continue;
|
||||
}
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
|
||||
// The map's luminance picks each pixel's blur, which a map gives SVG where it can't draw the radius mask as markup.
|
||||
// A box takes it unrounded, since SVG reads the box's result rather than its luminance.
|
||||
let unrounded = Parameters {
|
||||
values: [if box_blur { 1. } else { 0. }, 0., 0., 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let luminance = recorder.run("masked_radius_blur_luminance", COVERAGE_FORMAT, recorder.size, map, None, None, unrounded);
|
||||
if !box_blur {
|
||||
capture_plane(&mut recorder, 0, &luminance, false);
|
||||
if capture == Some(piece(0)) && !capture_needs_content_layer {
|
||||
recorder.textures.release(luminance);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// The full-strength content is read by a later operation, as the unfaded result, or as a box blur's map, and capturing one plane ends the passes
|
||||
let captures_only = |plane: usize| capture == Some(piece(plane)) && !capture_needs_content_layer;
|
||||
let full_is_read = !captures_only(1) && (filled.is_none() || position + 1 < operations.len() || (box_blur && capture == Some(piece(0))));
|
||||
match box_blur {
|
||||
true => {
|
||||
if captures_only(0)
|
||||
&& let Some(filled) = filled.take()
|
||||
{
|
||||
recorder.textures.release(filled);
|
||||
}
|
||||
let radius = DVec2::splat(radius * length_scale);
|
||||
recorder.masked_box_blur(content, &mut full, &mut filled, &luminance, radius, !gamma, full_is_read);
|
||||
|
||||
// SVG has no box of each pixel's own width, so it takes the results as maps
|
||||
if let Some(full) = &full {
|
||||
capture_plane(&mut recorder, 0, full, true);
|
||||
}
|
||||
if let Some(filled) = &filled {
|
||||
capture_plane(&mut recorder, 1, filled, true);
|
||||
}
|
||||
}
|
||||
false => {
|
||||
let levels: Vec<f64> = masked_radius_blur_levels(radius, length_scale).into_iter().map(|level| level * length_scale).collect();
|
||||
recorder.masked_radius_blur(content, &mut full, &mut filled, &luminance, &levels, !gamma, full_is_read);
|
||||
}
|
||||
}
|
||||
recorder.textures.release(luminance);
|
||||
}
|
||||
EffectOperation::DropShadow {
|
||||
color,
|
||||
@@ -395,23 +492,22 @@ impl EffectPasses {
|
||||
invert,
|
||||
ref contour,
|
||||
} => {
|
||||
// The difference between the silhouette cast both ways along the offset, softened by the size
|
||||
// For PSD interop, the difference between the silhouette cast both ways, each softened and reshaped first
|
||||
let offset = lengths_to_pixels * shadow_offset(angle, distance);
|
||||
let full_content = full.as_ref().unwrap_or(content);
|
||||
let cast_toward = |recorder: &mut PassRecorder, offset: DVec2| {
|
||||
let silhouette = recorder.silhouette(full_content, offset, false);
|
||||
recorder.cast(silhouette, size, 0., GlowTechnique::Softer, 100., &TransferCurve::default(), length_scale)
|
||||
recorder.cast(silhouette, size, 0., GlowTechnique::Softer, 100., contour, length_scale)
|
||||
};
|
||||
let (forward, backward) = (cast_toward(&mut recorder, offset), cast_toward(&mut recorder, -offset));
|
||||
let parameters = Parameters {
|
||||
amount: if invert { 1. } else { 0. },
|
||||
..Default::default()
|
||||
};
|
||||
let difference = recorder.run("satin", COVERAGE_FORMAT, recorder.size, &forward, Some(&backward), None, parameters);
|
||||
let strength = recorder.run("satin", COVERAGE_FORMAT, recorder.size, &forward, Some(&backward), None, parameters);
|
||||
recorder.textures.release(forward);
|
||||
recorder.textures.release(backward);
|
||||
|
||||
let strength = recorder.shape(difference, 100., contour);
|
||||
capture_plane(&mut recorder, 0, &strength, false);
|
||||
recorder.place_within(layered.then_some((&mut pieces, piece(0))), content, &mut full, &mut filled, strength, Some(color), blend_mode);
|
||||
}
|
||||
@@ -489,7 +585,7 @@ impl EffectPasses {
|
||||
texture_depth,
|
||||
..
|
||||
} => {
|
||||
let texture = match operation.drawn_paint() {
|
||||
let texture = match operation.drawn_paints().next() {
|
||||
Some(_) => match paints.next() {
|
||||
Some(texture) => Some(texture),
|
||||
None => continue,
|
||||
@@ -610,6 +706,87 @@ impl EffectPasses {
|
||||
recorder.fade_by(content, &mut full, &mut filled, &strength);
|
||||
recorder.textures.release(strength);
|
||||
}
|
||||
EffectOperation::ConvolutionKernel { .. }
|
||||
| EffectOperation::Emboss { .. }
|
||||
| EffectOperation::FindEdges
|
||||
| EffectOperation::MinimumMaximum { .. }
|
||||
| EffectOperation::Sharpen { .. }
|
||||
| EffectOperation::HighPass { .. }
|
||||
| EffectOperation::AddNoise { .. }
|
||||
| EffectOperation::Dissolve { .. } => {
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let captured_plane = capture.filter(|capture| capture.index == index).map(|capture| capture.plane);
|
||||
recorder.filter(content, &mut full, &mut filled, operation, effect_to_pixels, captured_plane, &mut |recorder, plane, map| {
|
||||
capture_plane(recorder, plane, map, true)
|
||||
});
|
||||
}
|
||||
EffectOperation::MotionBlur { angle, distance, gamma } => {
|
||||
// Anchored at the effect space's origin, which is the content's, so the shear moves with it
|
||||
let Some(shear) = MotionBlurShear::new(angle, distance, lengths_to_pixels, effect_to_pixels.translation) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let unblurred = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.motion_blur(unblurred, &shear, !gamma));
|
||||
filled = filled.map(|filled| recorder.motion_blur(filled, &shear, !gamma));
|
||||
}
|
||||
EffectOperation::RadialBlur { method, amount, transform, gamma } => {
|
||||
let blur = RadialBlur::new(method, amount, transform);
|
||||
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let unblurred = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.radial_blur(unblurred, &blur, effect_to_pixels, !gamma));
|
||||
filled = filled.map(|filled| recorder.radial_blur(filled, &blur, effect_to_pixels, !gamma));
|
||||
}
|
||||
EffectOperation::Twirl { .. } | EffectOperation::Pinch { .. } | EffectOperation::Spherize { .. } | EffectOperation::PolarCoordinates { .. } => {
|
||||
// The frame the warp's transform places in the effect space, measured from its origin (the content's)
|
||||
let Some((warp, transform)) = FrameWarp::of(operation) else { continue };
|
||||
let square = warp_frame(transform, effect_to_pixels);
|
||||
let clears = matches!(warp, FrameWarp::Polar { .. });
|
||||
if square.is_none() && !clears {
|
||||
continue;
|
||||
}
|
||||
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let unwarped = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
|
||||
// Where its square collapses, Polar Coordinates clears everything
|
||||
let warped = |recorder: &mut PassRecorder, texture: wgpu::Texture| match &square {
|
||||
Some(square) => recorder.frame_warp(texture, &warp, square),
|
||||
None => {
|
||||
let cleared = recorder.scale(&texture, 0.);
|
||||
recorder.textures.release(texture);
|
||||
cleared
|
||||
}
|
||||
};
|
||||
full = Some(warped(&mut recorder, unwarped));
|
||||
filled = filled.map(|filled| warped(&mut recorder, filled));
|
||||
}
|
||||
EffectOperation::Ripple { .. } | EffectOperation::Wave { .. } => {
|
||||
let (Some(frame), Some((field, edge_mode))) = (&frame, DisplacementField::of(operation)) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let undisplaced = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.displace(undisplaced, Displacement::Field(field), frame, edge_mode));
|
||||
filled = filled.map(|filled| recorder.displace(filled, Displacement::Field(field), frame, edge_mode));
|
||||
}
|
||||
EffectOperation::Displace { edge_mode, .. } => {
|
||||
// Each of the maps is taken from the paints even without a frame, so those after stay matched to their operations
|
||||
let movements: Vec<DVec2> = operation.displacement_maps().into_iter().flatten().map(|(_, movement)| movement).collect();
|
||||
let maps: Vec<(&wgpu::Texture, DVec2)> = paints.by_ref().take(movements.len()).zip(movements.iter().copied()).collect();
|
||||
if maps.len() < movements.len() {
|
||||
continue;
|
||||
}
|
||||
let Some(frame) = &frame else { continue };
|
||||
|
||||
recorder.merge_beneath(content, &mut full, &mut filled, beneath.take());
|
||||
let undisplaced = full.take().unwrap_or_else(|| recorder.scale(content, 1.));
|
||||
full = Some(recorder.displace(undisplaced, Displacement::Maps(&maps), frame, edge_mode));
|
||||
filled = filled.map(|filled| recorder.displace(filled, Displacement::Maps(&maps), frame, edge_mode));
|
||||
}
|
||||
EffectOperation::Adjustment(_) => {
|
||||
// A run of adjustments is carried out from its first row, in a pass for each standalone step and one for the steps between them
|
||||
let is_adjustment = |position: usize| is_pixel_filter(&operations[position].1) && matches!(operations[position].1, EffectOperation::Adjustment(_));
|
||||
@@ -863,35 +1040,41 @@ impl EffectPasses {
|
||||
}
|
||||
chained.into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
|
||||
self.record_mipmaps(device, &mut recorder.encoder, target);
|
||||
self.record_mipmaps(device, &mut recorder.encoder, recorder.textures, target);
|
||||
queue.submit([recorder.encoder.finish()]);
|
||||
}
|
||||
|
||||
/// Records the averaging of each of `texture`'s smaller mip levels from the one above it, like the levels of an uploaded image.
|
||||
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture) {
|
||||
let level = |level: u32| {
|
||||
texture.create_view(&wgpu::TextureViewDescriptor {
|
||||
base_mip_level: level,
|
||||
mip_level_count: Some(1),
|
||||
..Default::default()
|
||||
})
|
||||
};
|
||||
/// Each is halved into a pooled texture and copied into place, since WebGL sets the levels read for a whole texture, so none is drawn into while another is read.
|
||||
pub(crate) fn record_mipmaps(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, textures: &mut EffectTextures, texture: &wgpu::Texture) {
|
||||
let format = texture.format();
|
||||
let mut above: Option<wgpu::Texture> = None;
|
||||
|
||||
for index in 1..texture.mip_level_count() {
|
||||
let level_size = UVec2::new(texture.width() >> index, texture.height() >> index).max(UVec2::ONE);
|
||||
self.record(
|
||||
device,
|
||||
encoder,
|
||||
"halve",
|
||||
texture.format(),
|
||||
&level(index),
|
||||
level_size,
|
||||
&level(index - 1),
|
||||
None,
|
||||
None,
|
||||
Parameters::default(),
|
||||
);
|
||||
let level = textures.acquire(device, level_size, format);
|
||||
|
||||
// The first level reads the top one through a view of every level
|
||||
let source = above.as_ref().unwrap_or(texture).create_view(&wgpu::TextureViewDescriptor::default());
|
||||
let target = level.create_view(&wgpu::TextureViewDescriptor::default());
|
||||
self.record(device, encoder, "halve", format, &target, level_size, &source, None, None, Parameters::default());
|
||||
|
||||
let extent = wgpu::Extent3d {
|
||||
width: level_size.x,
|
||||
height: level_size.y,
|
||||
depth_or_array_layers: 1,
|
||||
};
|
||||
let destination = wgpu::TexelCopyTextureInfo {
|
||||
mip_level: index,
|
||||
..texture.as_image_copy()
|
||||
};
|
||||
encoder.copy_texture_to_texture(level.as_image_copy(), destination, extent);
|
||||
|
||||
if let Some(above) = above.replace(level) {
|
||||
textures.release(above);
|
||||
}
|
||||
}
|
||||
above.into_iter().for_each(|texture| textures.release(texture));
|
||||
}
|
||||
|
||||
/// Records the shader's `entry_point` into `target`, a view of `format` and `size`, reading the `source` view and optionally the `secondary` and `content` views.
|
||||
@@ -983,7 +1166,7 @@ fn changes_nothing(operation: &EffectOperation, length_scale: f64) -> bool {
|
||||
EffectOperation::BevelAndEmboss { size, gloss_contour, .. } => size * length_scale < NEGLIGIBLE_LENGTH && gloss_contour.is_identity(),
|
||||
_ => false,
|
||||
};
|
||||
operation.changes_nothing() || (too_slight && operation.drawn_paint().is_none())
|
||||
operation.changes_nothing() || (too_slight && operation.drawn_paints().next().is_none())
|
||||
}
|
||||
|
||||
/// Which pixels seed a distance pass, and how far from each one its edge lies.
|
||||
@@ -1508,9 +1691,8 @@ impl PassRecorder<'_> {
|
||||
self.textures.drawn_passes.push("adjust");
|
||||
}
|
||||
|
||||
/// Blurs `texture` by `kernel` along both axes, in linear light if `linear`.
|
||||
/// Kernels too wide for one pass run on a texture halved enough times for them to fit, then doubled back to full size. O(width × height) per pass.
|
||||
fn blur(&mut self, texture: wgpu::Texture, kernel: BlurKernel, linear: bool) -> wgpu::Texture {
|
||||
/// Carries out `operation` on `texture`, in linear light if `linear`.
|
||||
fn in_light(&mut self, texture: wgpu::Texture, linear: bool, operation: impl FnOnce(&mut Self, wgpu::Texture) -> wgpu::Texture) -> wgpu::Texture {
|
||||
let format = texture.format();
|
||||
let mut texture = texture;
|
||||
|
||||
@@ -1518,36 +1700,7 @@ impl PassRecorder<'_> {
|
||||
let decoded = self.run("decode_to_linear", format, self.size, &texture, None, None, Parameters::default());
|
||||
self.replace(&mut texture, decoded);
|
||||
}
|
||||
|
||||
let levels = kernel.levels();
|
||||
let size = self.size;
|
||||
let level_size = |level: u32| UVec2::new(size.x.div_ceil(1 << level), size.y.div_ceil(1 << level));
|
||||
|
||||
for level in 1..=levels {
|
||||
let halved = self.run("resample", format, level_size(level), &texture, None, None, Parameters::default());
|
||||
self.replace(&mut texture, halved);
|
||||
}
|
||||
|
||||
let taps = kernel_taps(kernel, levels);
|
||||
let mut tap_array = [[0.; 4]; MAX_TAPS];
|
||||
tap_array[..taps.len()].copy_from_slice(&taps);
|
||||
for axis in [DVec2::X, DVec2::Y] {
|
||||
let step = axis / level_size(levels).as_dvec2();
|
||||
let parameters = Parameters {
|
||||
step: [step.x as f32, step.y as f32],
|
||||
tap_count: taps.len() as u32,
|
||||
taps: tap_array,
|
||||
..Default::default()
|
||||
};
|
||||
let convolved = self.run("convolve", format, level_size(levels), &texture, None, None, parameters);
|
||||
self.replace(&mut texture, convolved);
|
||||
}
|
||||
|
||||
for level in (0..levels).rev() {
|
||||
let doubled = self.run("resample", format, level_size(level), &texture, None, None, Parameters::default());
|
||||
self.replace(&mut texture, doubled);
|
||||
}
|
||||
|
||||
let mut texture = operation(self, texture);
|
||||
if linear {
|
||||
let encoded = self.run("encode_to_gamma", format, self.size, &texture, None, None, Parameters::default());
|
||||
self.replace(&mut texture, encoded);
|
||||
@@ -1555,6 +1708,44 @@ impl PassRecorder<'_> {
|
||||
|
||||
texture
|
||||
}
|
||||
|
||||
/// Blurs `texture` by `kernel` along both axes, in linear light if `linear`.
|
||||
/// Kernels too wide for one pass run on a texture halved enough times for them to fit, then doubled back to full size. O(width × height) per pass.
|
||||
fn blur(&mut self, texture: wgpu::Texture, kernel: BlurKernel, linear: bool) -> wgpu::Texture {
|
||||
self.in_light(texture, linear, |recorder, mut texture| {
|
||||
let format = texture.format();
|
||||
let levels = kernel.levels();
|
||||
let size = recorder.size;
|
||||
let level_size = |level: u32| UVec2::new(size.x.div_ceil(1 << level), size.y.div_ceil(1 << level));
|
||||
|
||||
for level in 1..=levels {
|
||||
let halved = recorder.run("resample", format, level_size(level), &texture, None, None, Parameters::default());
|
||||
recorder.replace(&mut texture, halved);
|
||||
}
|
||||
|
||||
let taps = kernel_taps(kernel, levels);
|
||||
let mut tap_array = [[0.; 4]; PARAMETER_TAPS];
|
||||
tap_array[..taps.len()].copy_from_slice(&taps);
|
||||
for axis in [DVec2::X, DVec2::Y] {
|
||||
let step = axis / level_size(levels).as_dvec2();
|
||||
let parameters = Parameters {
|
||||
step: [step.x as f32, step.y as f32],
|
||||
tap_count: taps.len() as u32,
|
||||
taps: tap_array,
|
||||
..Default::default()
|
||||
};
|
||||
let convolved = recorder.run("convolve", format, level_size(levels), &texture, None, None, parameters);
|
||||
recorder.replace(&mut texture, convolved);
|
||||
}
|
||||
|
||||
for level in (0..levels).rev() {
|
||||
let doubled = recorder.run("resample", format, level_size(level), &texture, None, None, Parameters::default());
|
||||
recorder.replace(&mut texture, doubled);
|
||||
}
|
||||
|
||||
texture
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Textures for the effect passes and the content they work on, kept between renders for reuse at the same sizes.
|
||||
@@ -1623,6 +1814,11 @@ mod tests {
|
||||
taps.iter().map(|tap| tap[1]).sum()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shaders_parameters_hold_as_many_taps_as_the_passes_write() {
|
||||
assert!(include_str!("vello_effects.wgsl").contains(&format!("taps: array<vec4<f32>, {PARAMETER_TAPS}>")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kernels_keep_brightness_and_fit_one_pass() {
|
||||
let kernels = [0.3, 1., 2.5, 7.9, 8., 12., 100., 4000.]
|
||||
@@ -1632,7 +1828,11 @@ mod tests {
|
||||
for kernel in kernels {
|
||||
let taps = kernel_taps(kernel, kernel.levels());
|
||||
|
||||
assert!(taps.len() <= MAX_TAPS, "{kernel:?} needs {} taps", taps.len());
|
||||
assert!(
|
||||
taps.len() <= 1 + 2 * raster_kernels::effect_kernels::MAX_KERNEL_REACH.div_ceil(2),
|
||||
"{kernel:?} needs {} taps",
|
||||
taps.len()
|
||||
);
|
||||
assert!((total_weight(&taps) - 1.).abs() < 1e-5, "{kernel:?} weighs {}", total_weight(&taps));
|
||||
}
|
||||
}
|
||||
@@ -1667,6 +1867,7 @@ mod tests {
|
||||
];
|
||||
let second_run = [Adjustment::Invert, Adjustment::Posterize { levels: 3 }];
|
||||
let blur = |radius| EffectOperation::Blur {
|
||||
radius_mask: Default::default(),
|
||||
radius,
|
||||
box_blur: false,
|
||||
gamma: false,
|
||||
@@ -1684,7 +1885,7 @@ mod tests {
|
||||
let apply = |textures: &mut EffectTextures, effects: &Effects| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DMat2::IDENTITY, &[], None);
|
||||
let results = passes.apply(&context.device, &queue, textures, &content, effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
};
|
||||
let draw = |textures: &mut EffectTextures| {
|
||||
@@ -1706,7 +1907,7 @@ mod tests {
|
||||
textures.drawn_passes.clear();
|
||||
let effects = Effects::from_operations(operations);
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, fill, false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DMat2::IDENTITY, &[], None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, fill, 1., DAffine2::IDENTITY, None, &[], None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -1750,7 +1951,7 @@ mod tests {
|
||||
let mut drawn = |layered: bool| {
|
||||
textures.drawn_passes.clear();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., layered);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DMat2::IDENTITY, &[], None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
textures.drawn_passes.clone()
|
||||
};
|
||||
@@ -1772,7 +1973,7 @@ mod tests {
|
||||
let content = textures.acquire(&context.device, UVec2::splat(16), wgpu::TextureFormat::Rgba8Unorm);
|
||||
let queue = context.queue.lock();
|
||||
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 1., false);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DMat2::IDENTITY, &[], None);
|
||||
let results = passes.apply(&context.device, &queue, &mut textures, &content, &effects, &layers, 1., 1., DAffine2::IDENTITY, None, &[], None);
|
||||
results.into_iter().for_each(|(result, _)| textures.release(result));
|
||||
|
||||
let drawn = |label: &str| textures.drawn_passes.iter().filter(|&&drawn| drawn == label).count();
|
||||
|
||||
@@ -14,8 +14,8 @@ struct Parameters {
|
||||
color: vec4<f32>,
|
||||
// Each pass's own settings, described where it reads them
|
||||
values: vec4<f32>,
|
||||
// Each kernel tap's distance in steps (x) and weight (y)
|
||||
taps: array<vec4<f32>, 25>,
|
||||
// Each kernel tap's distance in steps (x) and weight (y), a filter tap's shift in texels (xy) and weight (z), or values described where a pass reads them
|
||||
taps: array<vec4<f32>, 81>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var source: texture_2d<f32>;
|
||||
|
||||
@@ -0,0 +1,502 @@
|
||||
//! The GPU passes of the filter effects, matching the CPU's `filter_kernels`.
|
||||
|
||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder, SUMS_FORMAT, WORKING_FORMAT};
|
||||
use glam::{DAffine2, DMat2, DVec2};
|
||||
use graphic_types::effects::spans_along_axes;
|
||||
use graphic_types::filters::{
|
||||
Convolution, FieldSampling, NoiseDistribution, RandomField, SHARPEN_NEIGHBORS, SOBEL_TAPS, Surroundings, UnsharpBlur, VISIBLE_ALPHA, neighborhood_radii, noise_extent, sharpens_coverage, unsharp,
|
||||
};
|
||||
use graphic_types::{EffectOperation, MinimumMaximumMode};
|
||||
use raster_kernels::effect_kernels::BlurKernel;
|
||||
use raster_kernels::filter_kernels::pixel_fill_shifts;
|
||||
|
||||
/// The most texels a neighborhood's first pass reads each way, beyond which each further pass at most doubles its reach by reading two texels.
|
||||
const MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS: u32 = 8;
|
||||
|
||||
/// The `convolution`'s shifts mapped onto texels by `lengths_to_pixels`, with their weights divided by its divisor.
|
||||
fn convolution_taps(convolution: &Convolution, lengths_to_pixels: DMat2) -> Vec<[f32; 4]> {
|
||||
let tap = |&(shift, weight): &(DVec2, f64)| {
|
||||
let shift = lengths_to_pixels * shift;
|
||||
[shift.x as f32, shift.y as f32, (weight / convolution.divisor) as f32, 0.]
|
||||
};
|
||||
convolution.taps.iter().map(tap).collect()
|
||||
}
|
||||
|
||||
/// The [`SOBEL_TAPS`] mapped onto texels by `lengths_to_pixels`, with their weights across and down.
|
||||
fn sobel_taps(lengths_to_pixels: DMat2) -> [[f32; 4]; 8] {
|
||||
SOBEL_TAPS.map(|(shift, [across, down])| {
|
||||
let shift = lengths_to_pixels * shift;
|
||||
[shift.x as f32, shift.y as f32, across as f32, down as f32]
|
||||
})
|
||||
}
|
||||
|
||||
/// The parameters placing a random field's samples in each texel as `sampling` describes, matching the shader's `field_values`, with its integers split into exact halves.
|
||||
fn field_parameters(sampling: &FieldSampling, first_seed: u32, second_seed: u32) -> Parameters {
|
||||
let halves = |value: u32| [(value & 0xffff) as f32, (value >> 16) as f32];
|
||||
let axes = sampling.pixel_axes;
|
||||
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [axes.x_axis.x, axes.x_axis.y, axes.y_axis.x, axes.y_axis.y].map(|value| value as f32);
|
||||
taps[1] = [sampling.origin_fraction.x as f32, sampling.origin_fraction.y as f32, 0., 0.];
|
||||
taps[2] = [sampling.counts.x as f32, sampling.counts.y as f32, sampling.spreads.x as f32, sampling.spreads.y as f32];
|
||||
let ([first_low, first_high], [second_low, second_high]) = (halves(first_seed), halves(second_seed));
|
||||
taps[3] = [first_low, first_high, second_low, second_high];
|
||||
let ([x_low, x_high], [y_low, y_high]) = (halves(sampling.origin_cell.x as u32), halves(sampling.origin_cell.y as u32));
|
||||
taps[4] = [x_low, x_high, y_low, y_high];
|
||||
Parameters { taps, ..Default::default() }
|
||||
}
|
||||
|
||||
/// The passes of a random field filter, rendering its map for an SVG and carrying it out, with their parameters, or `None` for any other operation.
|
||||
fn field_passes(operation: &EffectOperation, effect_to_pixels: DAffine2) -> Option<(&'static str, &'static str, Parameters)> {
|
||||
let sampling = FieldSampling::new(effect_to_pixels.inverse());
|
||||
match *operation {
|
||||
EffectOperation::AddNoise {
|
||||
amount,
|
||||
distribution,
|
||||
monochromatic,
|
||||
seed,
|
||||
} => {
|
||||
let amount = amount / 100.;
|
||||
let gaussian = if distribution == NoiseDistribution::Gaussian { 1. } else { 0. };
|
||||
let parameters = Parameters {
|
||||
values: [
|
||||
(amount * sampling.deviation_scale) as f32,
|
||||
noise_extent(amount, distribution) as f32,
|
||||
gaussian,
|
||||
if monochromatic { 1. } else { 0. },
|
||||
],
|
||||
..field_parameters(&sampling, RandomField::NoiseOffsets.seed(seed), RandomField::NoiseAngles.seed(seed))
|
||||
};
|
||||
Some(("noise_map", "add_noise", parameters))
|
||||
}
|
||||
EffectOperation::Dissolve { opacity, seed } => {
|
||||
let parameters = Parameters {
|
||||
values: [(opacity / 100.) as f32, sampling.deviation_scale as f32, 0., 0.],
|
||||
..field_parameters(&sampling, RandomField::Dissolve.seed(seed), 0)
|
||||
};
|
||||
Some(("dissolve_map", "dissolve", parameters))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// Carries out a filter effect on both the full-strength content (`content` itself until a pass replaces it) and the faded fill, with `effect_to_pixels` placing the effect space on their pixels.
|
||||
/// A filter hands what an SVG takes as a map to `capture` as plane 0 for the content and 1 for the fill, and a random field's map, which an SVG asks for as `captured_plane` 0, serves both.
|
||||
#[expect(clippy::too_many_arguments)]
|
||||
pub(super) fn filter(
|
||||
&mut self,
|
||||
content: &wgpu::Texture,
|
||||
full: &mut Option<wgpu::Texture>,
|
||||
filled: &mut Option<wgpu::Texture>,
|
||||
operation: &EffectOperation,
|
||||
effect_to_pixels: DAffine2,
|
||||
captured_plane: Option<usize>,
|
||||
capture: &mut dyn FnMut(&mut Self, usize, &wgpu::Texture),
|
||||
) {
|
||||
// A random field doesn't depend on the content, so one map serves both planes, except where the fill forks them and an SVG takes each one's result
|
||||
if let Some((map_entry_point, filter_entry_point, parameters)) = field_passes(operation, effect_to_pixels) {
|
||||
let forked = filled.is_some();
|
||||
if captured_plane == Some(0) && !forked {
|
||||
let map = self.run(map_entry_point, WORKING_FORMAT, self.size, full.as_ref().unwrap_or(content), None, None, parameters);
|
||||
capture(self, 0, &map);
|
||||
self.textures.release(map);
|
||||
}
|
||||
|
||||
let filtered = self.run(filter_entry_point, WORKING_FORMAT, self.size, full.as_ref().unwrap_or(content), None, None, parameters);
|
||||
if forked {
|
||||
capture(self, 0, &filtered);
|
||||
}
|
||||
self.replace_or_fill(full, filtered);
|
||||
|
||||
if let Some(filled) = filled {
|
||||
let filtered = self.run(filter_entry_point, WORKING_FORMAT, self.size, filled, None, None, parameters);
|
||||
capture(self, 1, &filtered);
|
||||
self.replace(filled, filtered);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each texel's fill left, matching the CPU's `faded_by_shares`
|
||||
let unfiltered = full.as_ref().unwrap_or(content);
|
||||
let shares = filled
|
||||
.as_ref()
|
||||
.filter(|_| sharpens_coverage(operation))
|
||||
.map(|filled| self.run("fill_shares", WORKING_FORMAT, self.size, filled, None, Some(unfiltered), Parameters::default()));
|
||||
|
||||
// The fill fades the content after the filter, so the full-strength content decides which of the fill's pixels are visible
|
||||
let filtered_full = self.filtered(unfiltered, unfiltered, operation, effect_to_pixels, 0, capture);
|
||||
let filtered_filled = match filled.as_ref() {
|
||||
Some(filled) if shares.is_some() => Some(self.filtered(filled, unfiltered, operation, effect_to_pixels, 1, &mut |_, _, _| {})),
|
||||
Some(filled) => Some(self.filtered(filled, unfiltered, operation, effect_to_pixels, 1, capture)),
|
||||
None => None,
|
||||
};
|
||||
self.replace_or_fill(full, filtered_full);
|
||||
let (Some(filled), Some(filtered)) = (filled.as_mut(), filtered_filled) else { return };
|
||||
|
||||
let filtered = match shares {
|
||||
Some(shares) => {
|
||||
let full = full.as_ref().unwrap_or(content);
|
||||
let faded = self.run("faded_by_shares", WORKING_FORMAT, self.size, &filtered, Some(full), Some(&shares), Parameters::default());
|
||||
[filtered, shares].into_iter().for_each(|texture| self.textures.release(texture));
|
||||
capture(self, 1, &faded);
|
||||
faded
|
||||
}
|
||||
None => filtered,
|
||||
};
|
||||
self.replace(filled, filtered);
|
||||
}
|
||||
|
||||
/// The image with a filter effect carried out on it, where the `full`-strength content covers it visibly, handing any map an SVG takes to `capture` as `plane`.
|
||||
fn filtered(
|
||||
&mut self,
|
||||
image: &wgpu::Texture,
|
||||
full: &wgpu::Texture,
|
||||
operation: &EffectOperation,
|
||||
effect_to_pixels: DAffine2,
|
||||
plane: usize,
|
||||
capture: &mut dyn FnMut(&mut Self, usize, &wgpu::Texture),
|
||||
) -> wgpu::Texture {
|
||||
let lengths_to_pixels = effect_to_pixels.matrix2;
|
||||
if let Some(convolution) = operation.convolution() {
|
||||
let convolved = self.convolve(image, full, &convolution, lengths_to_pixels);
|
||||
if !convolution.weighs_coverage {
|
||||
return self.uncover_capturing(convolved, image, convolution.surroundings, plane, capture);
|
||||
}
|
||||
|
||||
// A kernel weighing the coverage too gives the colors the coverage it weighs, so an SVG off the pixel lattice takes the whole result as its map
|
||||
let coverage = self.run_in_chunks("sum_taps", SUMS_FORMAT, image, None, &convolution_taps(&convolution, lengths_to_pixels), [0., -1.]);
|
||||
let uncovered = self.uncover(convolved, &coverage, convolution.surroundings);
|
||||
self.textures.release(coverage);
|
||||
capture(self, plane, &uncovered);
|
||||
return uncovered;
|
||||
}
|
||||
|
||||
// An SVG takes the whole result as its map where it can't sharpen natively, though a sharpened fill is captured once faded by shares
|
||||
if let Some((blur, sharpening)) = unsharp(operation) {
|
||||
let sharpening = sharpening.map(|[amount, threshold]| [amount as f32, threshold as f32]);
|
||||
let sharpened = self.unsharp_mask(image, full, blur, sharpening, lengths_to_pixels);
|
||||
capture(self, plane, &sharpened);
|
||||
return sharpened;
|
||||
}
|
||||
|
||||
match *operation {
|
||||
EffectOperation::FindEdges => {
|
||||
let edges = self.find_edges(image, lengths_to_pixels);
|
||||
self.uncover_capturing(edges, image, Surroundings::Matted(1.), plane, capture)
|
||||
}
|
||||
// An SVG takes the whole result as its map where the fill forks the content
|
||||
EffectOperation::MinimumMaximum { radius, mode } => {
|
||||
let extreme = self.neighborhood_extreme(image, radius, mode == MinimumMaximumMode::Maximum, lengths_to_pixels);
|
||||
capture(self, plane, &extreme);
|
||||
extreme
|
||||
}
|
||||
_ => self.scale(image, 1.),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the shader's `entry_point` over the `taps` in passes of at most [`PARAMETER_TAPS`] each, so no pass runs long enough to stall the GPU, reading `source` and `secondary` with the shader's own `settings` in `values.x` and `y`.
|
||||
/// Each pass after the first takes on what those before it left (in `between_format`) as its `content`, with `values.z` 1, and the last gives the result in [`WORKING_FORMAT`], with `values.w` 1.
|
||||
fn run_in_chunks(
|
||||
&mut self,
|
||||
entry_point: &'static str,
|
||||
between_format: wgpu::TextureFormat,
|
||||
source: &wgpu::Texture,
|
||||
secondary: Option<&wgpu::Texture>,
|
||||
taps: &[[f32; 4]],
|
||||
settings: [f32; 2],
|
||||
) -> wgpu::Texture {
|
||||
let flag = |on: bool| if on { 1. } else { 0. };
|
||||
let passes = taps.len().div_ceil(PARAMETER_TAPS).max(1);
|
||||
|
||||
let mut result: Option<wgpu::Texture> = None;
|
||||
for pass in 0..passes {
|
||||
let chunk = &taps[(pass * PARAMETER_TAPS).min(taps.len())..((pass + 1) * PARAMETER_TAPS).min(taps.len())];
|
||||
let mut tap_array = [[0.; 4]; PARAMETER_TAPS];
|
||||
tap_array[..chunk.len()].copy_from_slice(chunk);
|
||||
|
||||
let last = pass + 1 == passes;
|
||||
let parameters = Parameters {
|
||||
tap_count: chunk.len() as u32,
|
||||
taps: tap_array,
|
||||
values: [settings[0], settings[1], flag(result.is_some()), flag(last)],
|
||||
..Default::default()
|
||||
};
|
||||
let format = if last { WORKING_FORMAT } else { between_format };
|
||||
let next = self.run(entry_point, format, self.size, source, secondary, result.as_ref(), parameters);
|
||||
if let Some(earlier) = result.replace(next) {
|
||||
self.textures.release(earlier);
|
||||
}
|
||||
}
|
||||
result.unwrap_or_else(|| self.scale(source, 1.))
|
||||
}
|
||||
|
||||
/// The opaque weighted sum `convolution` describes of the image's colors, those visible judged by the `full`-strength content, matching the CPU's `convolve` before the image's coverage returns.
|
||||
fn convolve(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, convolution: &Convolution, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let colors = self.surrounded_colors(image, full, convolution.surroundings, convolution.reach(), lengths_to_pixels);
|
||||
let taps = convolution_taps(convolution, lengths_to_pixels);
|
||||
|
||||
// Beyond the edges, continued colors read nothing, while matted ones read the gray they lie over
|
||||
let beyond = match convolution.surroundings {
|
||||
Surroundings::Continued => -1.,
|
||||
Surroundings::Matted(gray) => gray as f32,
|
||||
};
|
||||
// The sums of a kernel past one pass's taps carry between passes at full precision
|
||||
let convolved = self.run_in_chunks("convolve_taps", SUMS_FORMAT, &colors, None, &taps, [convolution.offset as f32, beyond]);
|
||||
|
||||
self.textures.release(colors);
|
||||
convolved
|
||||
}
|
||||
|
||||
/// The opaque colors a filter reading the image within `reach` document pixels sees, as its `surroundings` describe, those visible judged by the `full`-strength content, matching the CPU's `SurroundedColors`.
|
||||
fn surrounded_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, surroundings: Surroundings, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
match surroundings {
|
||||
Surroundings::Continued => self.visible_colors(image, full, reach, lengths_to_pixels),
|
||||
Surroundings::Matted(gray) => {
|
||||
let parameters = Parameters {
|
||||
values: [0., 0., gray as f32, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
self.run("matte_colors", WORKING_FORMAT, self.size, image, None, None, parameters)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Filtered opaque `colors` given the image's coverage, as their `surroundings` describe, matching the CPU's `uncovered`, in place of the colors.
|
||||
fn uncover(&mut self, colors: wgpu::Texture, image: &wgpu::Texture, surroundings: Surroundings) -> wgpu::Texture {
|
||||
let gray = match surroundings {
|
||||
Surroundings::Continued => -1.,
|
||||
Surroundings::Matted(gray) => gray as f32,
|
||||
};
|
||||
let parameters = Parameters {
|
||||
values: [0., 0., gray, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let uncovered = self.run("uncover", WORKING_FORMAT, self.size, &colors, None, Some(image), parameters);
|
||||
self.textures.release(colors);
|
||||
uncovered
|
||||
}
|
||||
|
||||
/// The filtered opaque `colors` given the image's coverage, as [`Self::uncover`] gives them, handing the map an SVG takes to `capture` as `plane`, matching the SVG's `uncovered_map`:
|
||||
/// the opaque colors for continued surroundings, which it places atop the image, and the whole result for matted ones.
|
||||
fn uncover_capturing(
|
||||
&mut self,
|
||||
colors: wgpu::Texture,
|
||||
image: &wgpu::Texture,
|
||||
surroundings: Surroundings,
|
||||
plane: usize,
|
||||
capture: &mut dyn FnMut(&mut Self, usize, &wgpu::Texture),
|
||||
) -> wgpu::Texture {
|
||||
if surroundings == Surroundings::Continued {
|
||||
capture(self, plane, &colors);
|
||||
}
|
||||
let uncovered = self.uncover(colors, image, surroundings);
|
||||
if surroundings != Surroundings::Continued {
|
||||
capture(self, plane, &uncovered);
|
||||
}
|
||||
uncovered
|
||||
}
|
||||
|
||||
/// The image's straight colors as the filters read them, matching the CPU's `visible_colors`, with texels faint in the `full`-strength content taking the nearest visible color within `reach` document pixels.
|
||||
fn visible_colors(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, reach: f64, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let shifts: Vec<[f32; 4]> = pixel_fill_shifts(reach, lengths_to_pixels).into_iter().map(|[x, y]| [x as f32, y as f32, 0., 0.]).collect();
|
||||
self.run_in_chunks("visible_colors", WORKING_FORMAT, image, Some(full), &shifts, [VISIBLE_ALPHA, 0.])
|
||||
}
|
||||
|
||||
/// The opaque result of Find Edges on the image matted over white, before its coverage returns, matching the CPU's `find_edges`.
|
||||
fn find_edges(&mut self, image: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let colors = self.surrounded_colors(image, image, Surroundings::Matted(1.), 1., lengths_to_pixels);
|
||||
let edges = self.run_in_chunks("find_edges", WORKING_FORMAT, &colors, None, &sobel_taps(lengths_to_pixels), [0., 1.]);
|
||||
self.textures.release(colors);
|
||||
edges
|
||||
}
|
||||
|
||||
/// For PSD interop, the share of its change Edges Only makes in each channel of each texel, the edge gain of the channel's Sobel gradient there, matching the CPU's `edge_gains`.
|
||||
/// The colors are read continued past those visible in the `full`-strength content, and the coverage with none beyond it.
|
||||
fn edge_gains(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
// A faint texel the gradient reads finds its nearest visible color within the square of a pixel around it
|
||||
let colors = self.surrounded_colors(image, full, Surroundings::Continued, 1., lengths_to_pixels);
|
||||
let gains = self.run_in_chunks("edge_gains", WORKING_FORMAT, &colors, Some(image), &sobel_taps(lengths_to_pixels), [0., -1.]);
|
||||
self.textures.release(colors);
|
||||
gains
|
||||
}
|
||||
|
||||
/// What the unsharp mask compares the image against for Edges Only: its straight colors (or for `coverage`, its coverage) moved toward their `neighbors`' average, consumed here, by the share their `gains` give.
|
||||
fn edges_only_average(&mut self, image: &wgpu::Texture, neighbors: wgpu::Texture, gains: &wgpu::Texture, coverage: bool) -> wgpu::Texture {
|
||||
let parameters = Parameters {
|
||||
values: [0., 0., if coverage { 1. } else { 0. }, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let average = self.run("edges_only_average", WORKING_FORMAT, self.size, image, Some(&neighbors), Some(gains), parameters);
|
||||
self.textures.release(neighbors);
|
||||
average
|
||||
}
|
||||
|
||||
/// The image with each straight color and its coverage sharpened against the `blur` around it, by the amount and threshold fractions in `sharpening`,
|
||||
/// or with none, a high pass of its colors, those visible judged by the `full`-strength content, matching the CPU's `unsharp_mask`.
|
||||
fn unsharp_mask(&mut self, image: &wgpu::Texture, full: &wgpu::Texture, blur: UnsharpBlur, sharpening: Option<[f32; 2]>, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let visibility = Parameters {
|
||||
values: [0., 0., VISIBLE_ALPHA, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let visible = self.run("visible_only", WORKING_FORMAT, self.size, image, Some(full), None, visibility);
|
||||
|
||||
// A high pass keeps the coverage, so only unsharp masking blurs it
|
||||
let (blurred_colors, blurred_coverage) = match blur {
|
||||
UnsharpBlur::Gaussian(radius) => {
|
||||
let kernel = BlurKernel::Gaussian {
|
||||
sigma: radius.max(0.) * lengths_to_pixels.determinant().abs().sqrt(),
|
||||
};
|
||||
let blurred_colors = self.blur(visible, kernel, false);
|
||||
let blurred_coverage = sharpening.is_some().then(|| {
|
||||
let coverage = self.scale(image, 1.);
|
||||
self.blur(coverage, kernel, false)
|
||||
});
|
||||
(blurred_colors, blurred_coverage)
|
||||
}
|
||||
UnsharpBlur::EdgeNeighbors => {
|
||||
let gains = self.edge_gains(image, full, lengths_to_pixels);
|
||||
let neighbors = self.neighbors_average(&visible, lengths_to_pixels);
|
||||
self.textures.release(visible);
|
||||
let blurred_colors = self.edges_only_average(image, neighbors, &gains, false);
|
||||
let blurred_coverage = sharpening.is_some().then(|| {
|
||||
let neighbors = self.neighbors_average(image, lengths_to_pixels);
|
||||
self.edges_only_average(image, neighbors, &gains, true)
|
||||
});
|
||||
self.textures.release(gains);
|
||||
(blurred_colors, blurred_coverage)
|
||||
}
|
||||
};
|
||||
|
||||
let [amount, threshold] = sharpening.unwrap_or_default();
|
||||
let parameters = Parameters {
|
||||
values: [amount, threshold, 0., if sharpening.is_none() { 1. } else { 0. }],
|
||||
..Default::default()
|
||||
};
|
||||
let sharpened = self.run("unsharp_mask", WORKING_FORMAT, self.size, image, Some(&blurred_colors), blurred_coverage.as_ref(), parameters);
|
||||
[Some(blurred_colors), blurred_coverage].into_iter().flatten().for_each(|texture| self.textures.release(texture));
|
||||
sharpened
|
||||
}
|
||||
|
||||
/// The average in every channel of each texel's four nearest neighbors ([`SHARPEN_NEIGHBORS`]), with none beyond the edges, matching the CPU's `neighbors_average`.
|
||||
fn neighbors_average(&mut self, texture: &wgpu::Texture, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let taps = SHARPEN_NEIGHBORS.map(|shift| {
|
||||
let shift = lengths_to_pixels * shift;
|
||||
[shift.x as f32, shift.y as f32, 0.25, 0.]
|
||||
});
|
||||
self.run_in_chunks("sum_taps", WORKING_FORMAT, texture, None, &taps, [0., -1.])
|
||||
}
|
||||
|
||||
/// The image with each texel's color the lightest (or with `maximum` false, the darkest) in the square of `radius` document pixels around it,
|
||||
/// and its coverage the opposite extreme, matching the CPU's `neighborhood_extreme`. O(width × height × log radius), with the radius along each axis at most the texture's size along it.
|
||||
fn neighborhood_extreme(&mut self, image: &wgpu::Texture, radius: f64, maximum: bool, lengths_to_pixels: DMat2) -> wgpu::Texture {
|
||||
let spans = spans_along_axes(lengths_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 self.scale(image, 1.);
|
||||
}
|
||||
let maximum = if maximum { 1. } else { 0. };
|
||||
|
||||
// A square reaching past the texture along an axis holds the same texels as one reaching just across it
|
||||
let [near_x, far_x] = [near_x, far_x].map(|radius| radius.min(self.size.x));
|
||||
let [near_y, far_y] = [near_y, far_y].map(|radius| radius.min(self.size.y));
|
||||
|
||||
let prepared = self.run(
|
||||
"neighborhood_prepare",
|
||||
WORKING_FORMAT,
|
||||
self.size,
|
||||
image,
|
||||
None,
|
||||
None,
|
||||
Parameters {
|
||||
values: [0., 0., maximum, 0.],
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
// The larger square's extremes grow from the smaller one's, which the finish reads in their place if the two squares are the same
|
||||
let near = match self.extremes_in_squares(&prepared, [0, 0], [near_x, near_y], maximum) {
|
||||
Some(near) => {
|
||||
self.textures.release(prepared);
|
||||
near
|
||||
}
|
||||
None => prepared,
|
||||
};
|
||||
let far = (fraction > 0.).then(|| self.extremes_in_squares(&near, [near_x, near_y], [far_x, far_y], maximum)).flatten();
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [fraction as f32, 0., maximum, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let finished = self.run("neighborhood_finish", WORKING_FORMAT, self.size, &near, far.as_ref(), None, parameters);
|
||||
[Some(near), far].into_iter().flatten().for_each(|texture| self.textures.release(texture));
|
||||
finished
|
||||
}
|
||||
|
||||
/// The extremes of each rectangle reaching `to` texels across and down from each texel, from the `extremes` of those reaching `from`, along the rows then the columns,
|
||||
/// or `None` if they already reach as far. Each axis takes passes logarithmic in its reach, each reading two texels after a first one reading a few.
|
||||
fn extremes_in_squares(&mut self, extremes: &wgpu::Texture, from: [u32; 2], to: [u32; 2], maximum: f32) -> Option<wgpu::Texture> {
|
||||
let mut widened = None;
|
||||
for (axis, from, to) in [([1., 0.], from[0], to[0]), ([0., 1.], from[1], to[1])] {
|
||||
let mut reach = from;
|
||||
for radius in widened_radii(from, to) {
|
||||
// A window grows from nothing by reading each texel it reaches, then from the two windows either side spanning it
|
||||
let (entry_point, distance) = if reach == 0 { ("neighborhood_extreme", radius) } else { ("neighborhood_widen", radius - reach) };
|
||||
let parameters = Parameters {
|
||||
step: axis,
|
||||
values: [distance as f32, 0., maximum, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let next = self.run(entry_point, WORKING_FORMAT, self.size, widened.as_ref().unwrap_or(extremes), None, None, parameters);
|
||||
self.replace_or_fill(&mut widened, next);
|
||||
reach = radius;
|
||||
}
|
||||
}
|
||||
widened
|
||||
}
|
||||
}
|
||||
|
||||
/// The radii a window of extremes widens through from `from` texels each way to `to`, each at most double the one before it, or from none, at most [`MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS`].
|
||||
/// Each is the next one halved and rounded up, so their count is logarithmic in `to`.
|
||||
fn widened_radii(from: u32, to: u32) -> Vec<u32> {
|
||||
let mut radii = Vec::new();
|
||||
let mut radius = to;
|
||||
while radius > from {
|
||||
radii.push(radius);
|
||||
|
||||
let reached_from = if from == 0 { MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS } else { from.saturating_mul(2) };
|
||||
if radius <= reached_from {
|
||||
break;
|
||||
}
|
||||
radius = radius.div_ceil(2);
|
||||
}
|
||||
radii.reverse();
|
||||
radii
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn each_neighborhood_pass_at_most_doubles_the_reach_before_it() {
|
||||
for from in [0, 1, 2, 5, 8, 100] {
|
||||
for to in from..from + 1000 {
|
||||
let radii = widened_radii(from, to);
|
||||
assert_eq!(radii.last().copied().unwrap_or(from), to, "from {from} to {to}");
|
||||
|
||||
let mut reach = from;
|
||||
for radius in radii {
|
||||
let most = if reach == 0 { MAX_FIRST_NEIGHBORHOOD_PASS_RADIUS } else { 2 * reach };
|
||||
assert!(reach < radius && radius <= most, "from {from} to {to}, {reach} widens to {radius}");
|
||||
reach = radius;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A first pass of 7 texels each way, then six doublings
|
||||
assert_eq!(widened_radii(0, 400), [7, 13, 25, 50, 100, 200, 400]);
|
||||
assert_eq!(widened_radii(400, 404), [404]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,478 @@
|
||||
|
||||
// =======
|
||||
// Filters
|
||||
// =======
|
||||
|
||||
// The filters work on the same premultiplied gamma-encoded pixels as the passes above, sharing their bindings and parameters
|
||||
|
||||
// A texel's straight color with an alpha of 1 if the full-strength content (`secondary`) covers it at least `values.x`, or nothing if it doesn't or lies beyond the edges
|
||||
fn visible_color_at(pixel: vec2<i32>) -> vec4<f32> {
|
||||
let size = vec2<i32>(textureDimensions(source));
|
||||
if any(pixel < vec2<i32>(0)) || any(pixel >= size) {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let color = textureLoad(source, pixel, 0);
|
||||
let visible = color.a > 0. && textureLoad(secondary, pixel, 0).a >= parameters.values.x;
|
||||
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
||||
}
|
||||
|
||||
// Each texel's straight color as the filters read it, matching the CPU's `visible_colors`: its own if it's visible, otherwise that of the first visible texel `taps[i].xy` texels away,
|
||||
// or failing that its own if it has any coverage. A pass after others (`values.z` 1) keeps the color they found (`content`), and only the last (`values.w` 1) falls back to the texel's own.
|
||||
@fragment
|
||||
fn visible_colors(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
if parameters.values.z > 0.5 {
|
||||
let found = textureLoad(content, pixel, 0);
|
||||
if found.a > 0.5 {
|
||||
return found;
|
||||
}
|
||||
}
|
||||
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let color = visible_color_at(pixel + vec2<i32>(parameters.taps[i].xy));
|
||||
if color.a > 0.5 {
|
||||
return color;
|
||||
}
|
||||
}
|
||||
|
||||
let own = textureLoad(source, pixel, 0);
|
||||
if parameters.values.w > 0.5 && own.a > 0. {
|
||||
return vec4<f32>(own.rgb / own.a, 1.);
|
||||
}
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
|
||||
// The content composited over an opaque gray of level `values.z`, which a matted filter reads
|
||||
@fragment
|
||||
fn matte_colors(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
return vec4<f32>(color.rgb + parameters.values.z * (1. - color.a), 1.);
|
||||
}
|
||||
|
||||
// A texel of the colors a filter reads, with an alpha of 1 where there's one, or beyond the edges nothing, or with `values.y` at or above 0 the opaque gray of that level
|
||||
fn color_at(pixel: vec2<i32>) -> vec4<f32> {
|
||||
let size = vec2<i32>(textureDimensions(source));
|
||||
if any(pixel < vec2<i32>(0)) || any(pixel >= size) {
|
||||
return select(vec4<f32>(0.), vec4<f32>(vec3<f32>(parameters.values.y), 1.), parameters.values.y >= 0.);
|
||||
}
|
||||
return textureLoad(source, pixel, 0);
|
||||
}
|
||||
|
||||
// The colors at a position in texels from the first texel's center, interpolated between those of the four texels around it with a color, matching the CPU's `BilinearTap`
|
||||
fn color_between(position: vec2<f32>) -> vec3<f32> {
|
||||
let whole = floor(position);
|
||||
let fraction = position - whole;
|
||||
let pixel = vec2<i32>(whole);
|
||||
|
||||
let top = mix(color_at(pixel), color_at(pixel + vec2<i32>(1, 0)), fraction.x);
|
||||
let bottom = mix(color_at(pixel + vec2<i32>(0, 1)), color_at(pixel + vec2<i32>(1, 1)), fraction.x);
|
||||
let between = mix(top, bottom, fraction.y);
|
||||
return select(vec3<f32>(0.), between.rgb / between.a, between.a > 0.);
|
||||
}
|
||||
|
||||
// The weighted sum of the colors (`source`) read `taps[i].xy` texels away, each weighted by `taps[i].z`, raised by the offset `values.x` and clamped,
|
||||
// matching the CPU's `convolve` before the content's coverage returns. A pass after others (`values.z` 1) adds to their sum (`content`), and only the last (`values.w` 1) clamps it.
|
||||
@fragment
|
||||
fn convolve_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let center = vec2<f32>(pixel);
|
||||
|
||||
var sum = vec3<f32>(parameters.values.x);
|
||||
if parameters.values.z > 0.5 {
|
||||
sum = textureLoad(content, pixel, 0).rgb;
|
||||
}
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let tap = parameters.taps[i];
|
||||
sum += color_between(center + tap.xy) * tap.z;
|
||||
}
|
||||
|
||||
if parameters.values.w > 0.5 {
|
||||
return vec4<f32>(clamp(sum, vec3<f32>(0.), vec3<f32>(1.)), 1.);
|
||||
}
|
||||
return vec4<f32>(sum, 1.);
|
||||
}
|
||||
|
||||
// For PSD interop, each channel of the colors matted over white (`source`) darkened by the length of its Sobel gradient, matching the CPU's `find_edges`.
|
||||
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down.
|
||||
@fragment
|
||||
fn find_edges(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let center = vec2<f32>(vec2<i32>(position.xy));
|
||||
|
||||
var across = vec3<f32>(0.);
|
||||
var down = vec3<f32>(0.);
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let tap = parameters.taps[i];
|
||||
let color = color_between(center + tap.xy);
|
||||
across += color * tap.z;
|
||||
down += color * tap.w;
|
||||
}
|
||||
return vec4<f32>(clamp(1. - sqrt(across * across + down * down), vec3<f32>(0.), vec3<f32>(1.)), 1.);
|
||||
}
|
||||
|
||||
// Filtered opaque colors (`source`) given the `content` texel's coverage, matching the CPU's `uncovered`: as straight colors, or with `values.z` at or above 0, lifted off the gray of that level they were filtered over
|
||||
@fragment
|
||||
fn uncover(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let colors = textureLoad(source, pixel, 0).rgb;
|
||||
let alpha = textureLoad(content, pixel, 0).a;
|
||||
|
||||
let gray = parameters.values.z;
|
||||
if gray < 0. {
|
||||
return vec4<f32>(colors * alpha, alpha);
|
||||
}
|
||||
return vec4<f32>(clamp(colors - gray * (1. - alpha), vec3<f32>(0.), vec3<f32>(alpha)), alpha);
|
||||
}
|
||||
|
||||
// The colors and coverage a neighborhood maximum (with `values.z` 1) or minimum works on, matching the CPU's `neighborhood_extreme`:
|
||||
// the straight colors of covered texels for the maximum, black elsewhere, or for the minimum the colors matted over white
|
||||
@fragment
|
||||
fn neighborhood_prepare(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if parameters.values.z > 0.5 {
|
||||
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, color.a), color.a > 0.);
|
||||
}
|
||||
return vec4<f32>(color.rgb + 1. - color.a, color.a);
|
||||
}
|
||||
|
||||
// The colors' extreme of two texels (the maximum with `values.z` 1, otherwise the minimum), and the opposite extreme of their coverages
|
||||
fn neighborhood_extremes(first: vec4<f32>, second: vec4<f32>) -> vec4<f32> {
|
||||
if parameters.values.z > 0.5 {
|
||||
return vec4<f32>(max(first.rgb, second.rgb), min(first.a, second.a));
|
||||
}
|
||||
return vec4<f32>(min(first.rgb, second.rgb), max(first.a, second.a));
|
||||
}
|
||||
|
||||
// A texel of what a neighborhood works on (`source`), or beyond the edges, the colors at their identity and no coverage
|
||||
fn neighborhood_texel(pixel: vec2<i32>) -> vec4<f32> {
|
||||
let size = vec2<i32>(textureDimensions(source));
|
||||
if any(pixel < vec2<i32>(0)) || any(pixel >= size) {
|
||||
return vec4<f32>(vec3<f32>(select(1., 0., parameters.values.z > 0.5)), 0.);
|
||||
}
|
||||
return textureLoad(source, pixel, 0);
|
||||
}
|
||||
|
||||
// The extremes over `values.x` texels each way along `step`, read one by one, matching the CPU's `window_extremes`
|
||||
@fragment
|
||||
fn neighborhood_extreme(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let step = vec2<i32>(parameters.step);
|
||||
let radius = i32(parameters.values.x);
|
||||
|
||||
var extremes = textureLoad(source, pixel, 0);
|
||||
for (var offset = 1; offset <= radius; offset++) {
|
||||
extremes = neighborhood_extremes(extremes, neighborhood_texel(pixel - step * offset));
|
||||
extremes = neighborhood_extremes(extremes, neighborhood_texel(pixel + step * offset));
|
||||
}
|
||||
return extremes;
|
||||
}
|
||||
|
||||
// The extremes (`source`) widened by `values.x` texels each way along `step`, from the two windows that far to either side, which span the wider one if `values.x` is at most their reach.
|
||||
// One past an edge reads the window at the edge instead, which lies within the wider one and also reaches beyond the edge.
|
||||
@fragment
|
||||
fn neighborhood_widen(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let last = vec2<i32>(textureDimensions(source)) - 1;
|
||||
let shift = vec2<i32>(parameters.step) * i32(parameters.values.x);
|
||||
|
||||
let before = textureLoad(source, clamp(pixel - shift, vec2<i32>(0), last), 0);
|
||||
let after = textureLoad(source, clamp(pixel + shift, vec2<i32>(0), last), 0);
|
||||
return neighborhood_extremes(before, after);
|
||||
}
|
||||
|
||||
// The extremes of a maximum (with `values.z` 1) or minimum back as premultiplied colors, the minimum's lifted back off white within the grown coverage
|
||||
fn premultiplied_extremes(extremes: vec4<f32>) -> vec4<f32> {
|
||||
if parameters.values.z > 0.5 {
|
||||
return vec4<f32>(extremes.rgb * extremes.a, extremes.a);
|
||||
}
|
||||
return vec4<f32>(clamp(extremes.rgb - (1. - extremes.a), vec3<f32>(0.), vec3<f32>(extremes.a)), extremes.a);
|
||||
}
|
||||
|
||||
// The extremes (`source`) back as premultiplied colors, mixed toward those of the next whole radius (`secondary`) by the fraction `values.x`, matching the CPU's `neighborhood_extreme`
|
||||
@fragment
|
||||
fn neighborhood_finish(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let near = premultiplied_extremes(textureLoad(source, pixel, 0));
|
||||
let far = premultiplied_extremes(textureLoad(secondary, pixel, 0));
|
||||
return mix(near, far, parameters.values.x);
|
||||
}
|
||||
|
||||
// The texels (`source`) read `taps[i].xy` texels away between those around them, each weighted by `taps[i].z`, with none beyond the edges (`values.y` below 0), matching the CPU's `neighbors_average`.
|
||||
// A pass after others (`values.z` 1) adds to their sum (`content`), and the last (`values.w` 1) clamps it.
|
||||
@fragment
|
||||
fn sum_taps(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
|
||||
var sum = vec4<f32>(0.);
|
||||
if parameters.values.z > 0.5 {
|
||||
sum = textureLoad(content, pixel, 0);
|
||||
}
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let tap = parameters.taps[i];
|
||||
let position = vec2<f32>(pixel) + tap.xy;
|
||||
let whole = vec2<i32>(floor(position));
|
||||
let fraction = position - floor(position);
|
||||
|
||||
let top = mix(color_at(whole), color_at(whole + vec2<i32>(1, 0)), fraction.x);
|
||||
let bottom = mix(color_at(whole + vec2<i32>(0, 1)), color_at(whole + vec2<i32>(1, 1)), fraction.x);
|
||||
sum += mix(top, bottom, fraction.y) * tap.z;
|
||||
}
|
||||
|
||||
if parameters.values.w > 0.5 {
|
||||
return clamp(sum, vec4<f32>(0.), vec4<f32>(1.));
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
|
||||
// The texels' straight colors made opaque where visible in the full-strength content in `secondary` and the rest left out, so dividing their blur by its alpha averages the visible colors alone
|
||||
@fragment
|
||||
fn visible_only(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let color = textureLoad(source, pixel, 0);
|
||||
let visible = color.a > 0. && textureLoad(secondary, pixel, 0).a >= parameters.values.z;
|
||||
return select(vec4<f32>(0.), vec4<f32>(color.rgb / color.a, 1.), visible);
|
||||
}
|
||||
|
||||
// The blurred visibilities between which unsharp masking eases from comparing a texel against its own color to the visible colors' average, matching the CPU's
|
||||
const AVERAGE_VISIBILITY_RAMP: vec2<f32> = vec2<f32>(8. / 255., 24. / 255.);
|
||||
|
||||
// The average of the visible colors a texel's own straight color is compared against, from the blur of them made opaque among the rest left out (`blurred`),
|
||||
// easing into its own color where too little of the blur lands on visible colors to know their average
|
||||
fn visible_average(own: vec3<f32>, blurred: vec4<f32>) -> vec3<f32> {
|
||||
let weight = clamp((blurred.a - AVERAGE_VISIBILITY_RAMP.x) / (AVERAGE_VISIBILITY_RAMP.y - AVERAGE_VISIBILITY_RAMP.x), 0., 1.);
|
||||
return select(own, own + (blurred.rgb / blurred.a - own) * weight, weight > 0.);
|
||||
}
|
||||
|
||||
// For PSD interop, the middle gray a high pass centers its differences on, matching the CPU's
|
||||
const HIGH_PASS_GRAY: f32 = 128. / 255.;
|
||||
|
||||
// For PSD interop, the Sobel gradient lengths between which Edges Only ramps from no change to the whole of it, matching the CPU's
|
||||
const EDGE_GAIN_RAMP: vec2<f32> = vec2<f32>(0.25, 1.);
|
||||
|
||||
// The image's coverage (`secondary`) at a position in texels from the first texel's center, interpolated between the four texels around it, with none beyond the edges
|
||||
fn coverage_between(position: vec2<f32>) -> f32 {
|
||||
let whole = floor(position);
|
||||
let fraction = position - whole;
|
||||
let size = vec2<i32>(textureDimensions(secondary));
|
||||
|
||||
var corners = array<f32, 4>(0., 0., 0., 0.);
|
||||
for (var corner = 0; corner < 4; corner++) {
|
||||
let at = vec2<i32>(whole) + vec2<i32>(corner % 2, corner / 2);
|
||||
if all(at >= vec2<i32>(0)) && all(at < size) {
|
||||
corners[corner] = textureLoad(secondary, at, 0).a;
|
||||
}
|
||||
}
|
||||
return mix(mix(corners[0], corners[1], fraction.x), mix(corners[2], corners[3], fraction.x), fraction.y);
|
||||
}
|
||||
|
||||
// For PSD interop, the share of its change Edges Only makes in each channel, by the length of the channel's Sobel gradient, matching the CPU's `edge_gains`.
|
||||
// Each tap `taps[i].xy` texels away weighs `taps[i].z` across and `taps[i].w` down, read on the continued colors (`source`) and the image's coverage (`secondary`).
|
||||
@fragment
|
||||
fn edge_gains(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let center = vec2<f32>(vec2<i32>(position.xy));
|
||||
|
||||
var across = vec4<f32>(0.);
|
||||
var down = vec4<f32>(0.);
|
||||
for (var i = 0u; i < parameters.tap_count; i++) {
|
||||
let tap = parameters.taps[i];
|
||||
let value = vec4<f32>(color_between(center + tap.xy), coverage_between(center + tap.xy));
|
||||
across += value * tap.z;
|
||||
down += value * tap.w;
|
||||
}
|
||||
|
||||
let gradient = sqrt(across * across + down * down);
|
||||
return clamp((gradient - EDGE_GAIN_RAMP.x) / (EDGE_GAIN_RAMP.y - EDGE_GAIN_RAMP.x), vec4<f32>(0.), vec4<f32>(1.));
|
||||
}
|
||||
|
||||
// What the unsharp mask compares the image (`source`) against for Edges Only: its straight colors moved toward their neighbors' visible average (`secondary`) by the share their edge gains (`content`) give,
|
||||
// made opaque so the unsharp mask reads them as the whole average. With `values.z` 1, it's the coverage moved toward its neighbors' average instead, matching the CPU's `unsharp_mask`.
|
||||
@fragment
|
||||
fn edges_only_average(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let image = textureLoad(source, pixel, 0);
|
||||
let neighbors = textureLoad(secondary, pixel, 0);
|
||||
let gains = textureLoad(content, pixel, 0);
|
||||
|
||||
if parameters.values.z > 0.5 {
|
||||
return vec4<f32>(0., 0., 0., image.a + (neighbors.a - image.a) * gains.a);
|
||||
}
|
||||
if image.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let own = image.rgb / image.a;
|
||||
return vec4<f32>(own + (visible_average(own, neighbors) - own) * gains.rgb, 1.);
|
||||
}
|
||||
|
||||
// For PSD interop, unsharp masking's change to values lying `difference` above the blur around them, by the amount `values.x` and threshold `values.y`, matching the CPU's `unsharp_change`
|
||||
fn unsharp_change(difference: vec4<f32>) -> vec4<f32> {
|
||||
return sign(difference) * max(parameters.values.x * abs(difference) - parameters.values.y, vec4<f32>(0.));
|
||||
}
|
||||
|
||||
// Sharpens the straight colors and coverage of the image (`source`) against the blur of its visible colors (`secondary`) and of its coverage (`content`), matching the CPU's `unsharp_mask`.
|
||||
// With `values.w` 1, it's a high pass instead: the colors' difference from their blur around middle gray, with the coverage kept.
|
||||
@fragment
|
||||
fn unsharp_mask(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let image = textureLoad(source, pixel, 0);
|
||||
if image.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let own = vec4<f32>(image.rgb / image.a, image.a);
|
||||
|
||||
let average = visible_average(own.rgb, textureLoad(secondary, pixel, 0));
|
||||
let difference = own - vec4<f32>(average, textureLoad(content, pixel, 0).a);
|
||||
|
||||
var sharpened = clamp(own + unsharp_change(difference), vec4<f32>(0.), vec4<f32>(1.));
|
||||
if parameters.values.w > 0.5 {
|
||||
sharpened = vec4<f32>(clamp(difference.rgb + HIGH_PASS_GRAY, vec3<f32>(0.), vec3<f32>(1.)), image.a);
|
||||
}
|
||||
return vec4<f32>(sharpened.rgb * sharpened.a, sharpened.a);
|
||||
}
|
||||
|
||||
// Each texel's share of the full-strength content's coverage (`content`) that the faded fill (`source`) left, matching the CPU's `fill_shares`
|
||||
@fragment
|
||||
fn fill_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let filled = textureLoad(source, pixel, 0).a;
|
||||
let full = textureLoad(content, pixel, 0).a;
|
||||
return vec4<f32>(0., 0., 0., select(0., min(filled / full, 1.), full > 0.));
|
||||
}
|
||||
|
||||
// The fill's filtered straight colors (`source`) at the coverage of the full-strength content's filtered result (`secondary`) scaled by each texel's share of it (`content`),
|
||||
// matching the CPU's `faded_by_shares`
|
||||
@fragment
|
||||
fn faded_by_shares(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let filled = textureLoad(source, pixel, 0);
|
||||
let full = textureLoad(secondary, pixel, 0);
|
||||
let alpha = full.a * textureLoad(content, pixel, 0).a;
|
||||
|
||||
var colors = vec3<f32>(0.);
|
||||
if filled.a > 0. {
|
||||
colors = filled.rgb / filled.a;
|
||||
} else if full.a > 0. {
|
||||
colors = full.rgb / full.a;
|
||||
}
|
||||
return vec4<f32>(colors * alpha, alpha);
|
||||
}
|
||||
|
||||
// =============
|
||||
// Random fields
|
||||
// =============
|
||||
|
||||
// For PSD interop, how many standard deviations Gaussian noise reaches, matching the CPU's
|
||||
const GAUSSIAN_NOISE_LIMIT: f32 = 3.5;
|
||||
|
||||
// Values strictly between 0 and 1 from the top 23 bits of each hash, which an f32 holds exactly with the half added, matching the CPU's `unit_interval`
|
||||
fn unit_interval(hash: vec3<u32>) -> vec3<f32> {
|
||||
return (vec3<f32>(hash >> vec3<u32>(9u)) + 0.5) / 8388608.;
|
||||
}
|
||||
|
||||
// A 32-bit integer from its exact low (x) and high (y) 16-bit halves
|
||||
fn joined_halves(halves: vec2<f32>) -> u32 {
|
||||
return u32(halves.x) | (u32(halves.y) << 16u);
|
||||
}
|
||||
|
||||
// The first or `second` field's seed, from its exact halves in `taps[3]`
|
||||
fn field_seed(second: bool) -> u32 {
|
||||
return joined_halves(select(parameters.taps[3].xy, parameters.taps[3].zw, second));
|
||||
}
|
||||
|
||||
// The three values a field of the `seed` holds at the cell `offset` texels from the texel's middle at `position`, matching the CPU's `FieldSampling`.
|
||||
// `taps[0]` holds the texels' axes in cells, `taps[1].xy` the rest of the way to the origin, and `taps[4]` the origin's cell in exact halves.
|
||||
fn field_values(position: vec2<f32>, offset: vec2<f32>, seed: u32) -> vec3<f32> {
|
||||
let axes = mat2x2<f32>(parameters.taps[0].xy, parameters.taps[0].zw);
|
||||
let origin_cell = vec2<u32>(joined_halves(parameters.taps[4].xy), joined_halves(parameters.taps[4].zw));
|
||||
let cell = origin_cell + bitcast<vec2<u32>>(vec2<i32>(floor(parameters.taps[1].xy + axes * (position + offset))));
|
||||
return unit_interval(pcg3d(vec3<u32>(cell, seed)));
|
||||
}
|
||||
|
||||
// How many samples a texel takes along each axis, from `taps[2].xy`
|
||||
fn sample_counts() -> vec2<u32> {
|
||||
return vec2<u32>(parameters.taps[2].xy);
|
||||
}
|
||||
|
||||
// The offset in texels of a texel's sample in `column` and `row`, spread as far as `taps[2].zw` from the first to the last
|
||||
fn sample_offset(column: u32, row: u32) -> vec2<f32> {
|
||||
return ((vec2<f32>(f32(column), f32(row)) + 0.5) / parameters.taps[2].xy - 0.5) * parameters.taps[2].zw;
|
||||
}
|
||||
|
||||
// The offsets Add Noise gives a texel's colors, matching the CPU's `add_noise`: its noise averaged over its samples (Gaussian with `values.z` 1), the same for every color with `values.w` 1,
|
||||
// scaled by `values.x` and kept within `values.y` either way
|
||||
fn noise_offsets(position: vec2<f32>) -> vec3<f32> {
|
||||
let counts = sample_counts();
|
||||
var sum = vec3<f32>(0.);
|
||||
for (var row = 0u; row < counts.y; row++) {
|
||||
for (var column = 0u; column < counts.x; column++) {
|
||||
let offset = sample_offset(column, row);
|
||||
let offsets = field_values(position, offset, field_seed(false));
|
||||
|
||||
// The Box-Muller transform of two uniform values into one with a normal distribution
|
||||
if parameters.values.z > 0.5 {
|
||||
let angles = field_values(position, offset, field_seed(true));
|
||||
sum += clamp(sqrt(-2. * log(offsets)) * cos(6.2831855 * angles), vec3<f32>(-GAUSSIAN_NOISE_LIMIT), vec3<f32>(GAUSSIAN_NOISE_LIMIT));
|
||||
} else {
|
||||
sum += 2. * offsets - 1.;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var noise = sum / f32(counts.x * counts.y);
|
||||
if parameters.values.w > 0.5 {
|
||||
noise = vec3<f32>(noise.x);
|
||||
}
|
||||
return clamp(noise * parameters.values.x, vec3<f32>(-parameters.values.y), vec3<f32>(parameters.values.y));
|
||||
}
|
||||
|
||||
// The offsets Add Noise gives each color, around middle gray and scaled to fill the range, which an SVG adds to the colors
|
||||
@fragment
|
||||
fn noise_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
return vec4<f32>(0.5 + noise_offsets(position.xy) / (2. * parameters.values.y), 1.);
|
||||
}
|
||||
|
||||
// Each straight color offset by noise and clamped, with the coverage kept
|
||||
@fragment
|
||||
fn add_noise(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let noisy = clamp(color.rgb / color.a + noise_offsets(position.xy), vec3<f32>(0.), vec3<f32>(1.));
|
||||
return vec4<f32>(noisy * color.a, color.a);
|
||||
}
|
||||
|
||||
// How much of a texel Dissolve shows, matching the CPU's `dissolve_field`: the share of its samples passing the opacity `values.x`, deviating from it less by `values.y`,
|
||||
// and the threshold level from 0 to 254 its coverage must pass
|
||||
fn dissolve_field(position: vec2<f32>) -> vec2<f32> {
|
||||
let counts = sample_counts();
|
||||
let seed = field_seed(false);
|
||||
var shown = 0.;
|
||||
for (var row = 0u; row < counts.y; row++) {
|
||||
for (var column = 0u; column < counts.x; column++) {
|
||||
shown += select(0., 1., field_values(position, sample_offset(column, row), seed).x < parameters.values.x);
|
||||
}
|
||||
}
|
||||
|
||||
let opacity = parameters.values.x;
|
||||
let share = clamp(opacity + (shown / f32(counts.x * counts.y) - opacity) * parameters.values.y, 0., 1.);
|
||||
let threshold = floor(field_values(position, vec2<f32>(0.), seed).y * 255.);
|
||||
return vec2<f32>(share, threshold);
|
||||
}
|
||||
|
||||
// The threshold level as a gray, a fraction of 255, at the share shown as its alpha, which an SVG combines with the coverage. Gray survives a conversion between color spaces.
|
||||
@fragment
|
||||
fn dissolve_map(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let field = dissolve_field(position.xy);
|
||||
return vec4<f32>(vec3<f32>(field.y / 255. * field.x), field.x);
|
||||
}
|
||||
|
||||
// The content shown fully opaque by the share where its coverage is at least one 8-bit level above the threshold, and hidden elsewhere
|
||||
@fragment
|
||||
fn dissolve(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let color = textureLoad(source, vec2<i32>(position.xy), 0);
|
||||
if color.a <= 0. {
|
||||
return vec4<f32>(0.);
|
||||
}
|
||||
let field = dissolve_field(position.xy);
|
||||
let shown = select(0., field.x, color.a * 255. > field.y + 0.5);
|
||||
return vec4<f32>(color.rgb / color.a * shown, shown);
|
||||
}
|
||||
@@ -1,8 +1,9 @@
|
||||
//! The GPU passes that fade content by a mask or a feather, whose shaders are in `vello_masks.wgsl`.
|
||||
//! The GPU passes that mask, feather, and blur content by a radius mask, with their shaders in `vello_masks.wgsl`.
|
||||
|
||||
use super::{COVERAGE_FORMAT, Parameters, PassRecorder, Seeds, WORKING_FORMAT};
|
||||
use graphic_types::masks::{MaskMode, feather_parts, mask_density_line};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH};
|
||||
use super::{COVERAGE_FORMAT, Parameters, PassRecorder, SUMS_FORMAT, Seeds, WORKING_FORMAT};
|
||||
use glam::DVec2;
|
||||
use graphic_types::masks::{MaskMode, feather_parts, mask_density_line, masked_radius_blur_interpolation};
|
||||
use raster_kernels::effect_kernels::{BlurKernel, NEGLIGIBLE_LENGTH, variable_box_scale};
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// How much the `mask` graphic's texture shows the content at each pixel, from 0 to 1, matching the CPU's `mask_strength`.
|
||||
@@ -63,6 +64,136 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill by the interpolation between Gaussian `levels` (from `masked_radius_blur_levels`, here in pixels)
|
||||
/// the map's `luminance` picks, matching the CPU's `masked_radius_blur`. The `luminance` holds 8-bit codes as fractions of 255.
|
||||
/// The levels blur in linear light if `linear`, and the full-strength content is left as it is unless `full_is_read`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn masked_radius_blur(
|
||||
&mut self,
|
||||
content: &wgpu::Texture,
|
||||
full: &mut Option<wgpu::Texture>,
|
||||
filled: &mut Option<wgpu::Texture>,
|
||||
luminance: &wgpu::Texture,
|
||||
levels: &[f64],
|
||||
linear: bool,
|
||||
full_is_read: bool,
|
||||
) {
|
||||
// The level below and the share of the level above for each 8-bit luminance code, which are the same at any scale
|
||||
let blends: Vec<half::f16> = (0..=255_u8)
|
||||
.flat_map(|code| {
|
||||
let (below, above_parts) = masked_radius_blur_interpolation(code, levels);
|
||||
[below as f32, above_parts as f32 / 255., 0., 0.]
|
||||
})
|
||||
.map(half::f16::from_f32)
|
||||
.collect();
|
||||
let table = self.row_texture("vello_effects_masked_radius_blur", wgpu::TextureFormat::Rgba16Float, 256, bytemuck::cast_slice(&blends));
|
||||
let interpolation = self.run("masked_radius_blur_interpolation", WORKING_FORMAT, self.size, luminance, Some(&table), None, Parameters::default());
|
||||
|
||||
if full_is_read && let Some(blurred) = self.masked_radius_blur_image(full.as_ref().unwrap_or(content), &interpolation, levels, linear) {
|
||||
self.replace_or_fill(full, blurred);
|
||||
}
|
||||
if let Some(filled) = filled
|
||||
&& let Some(blurred) = self.masked_radius_blur_image(filled, &interpolation, levels, linear)
|
||||
{
|
||||
self.replace(filled, blurred);
|
||||
}
|
||||
self.textures.release(interpolation);
|
||||
}
|
||||
|
||||
/// The `image` blurred by each texel's `interpolation` between the masked radius blur's Gaussian `levels`, in pixels.
|
||||
fn masked_radius_blur_image(&mut self, image: &wgpu::Texture, interpolation: &wgpu::Texture, levels: &[f64], linear: bool) -> Option<wgpu::Texture> {
|
||||
let mut sum: Option<wgpu::Texture> = None;
|
||||
for (index, &sigma) in levels.iter().enumerate() {
|
||||
let blurred = (sigma >= NEGLIGIBLE_LENGTH).then(|| {
|
||||
let copy = self.scale(image, 1.);
|
||||
self.blur(copy, BlurKernel::Gaussian { sigma }, linear)
|
||||
});
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [index as f32, if sum.is_some() { 1. } else { 0. }, 0., 0.],
|
||||
..Default::default()
|
||||
};
|
||||
// Summed in gamma on purpose (see `masked_radius_blur_interpolation`)
|
||||
let source = blurred.as_ref().unwrap_or(image);
|
||||
let accumulated = self.run("accumulate_masked_radius_blur_level", WORKING_FORMAT, self.size, source, Some(interpolation), sum.as_ref(), parameters);
|
||||
[sum.replace(accumulated), blurred].into_iter().flatten().for_each(|texture| self.textures.release(texture));
|
||||
}
|
||||
sum
|
||||
}
|
||||
|
||||
/// Box blurs both the full-strength content (`content` itself until a pass replaces it) and the faded fill at each texel by its own half width,
|
||||
/// the fraction of the `radius` in pixels along each axis that the map's unrounded `luminance` gives, matching the CPU's `variable_box_blur`.
|
||||
/// It blurs in linear light if `linear`, and leaves the full-strength content as it is unless `full_is_read`.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn masked_box_blur(
|
||||
&mut self,
|
||||
content: &wgpu::Texture,
|
||||
full: &mut Option<wgpu::Texture>,
|
||||
filled: &mut Option<wgpu::Texture>,
|
||||
luminance: &wgpu::Texture,
|
||||
radius: DVec2,
|
||||
linear: bool,
|
||||
full_is_read: bool,
|
||||
) {
|
||||
if full_is_read {
|
||||
let blurred = self.variable_box_blur(full.as_ref().unwrap_or(content), luminance, radius, linear);
|
||||
self.replace_or_fill(full, blurred);
|
||||
}
|
||||
if let Some(filled) = filled {
|
||||
let blurred = self.variable_box_blur(filled, luminance, radius, linear);
|
||||
self.replace(filled, blurred);
|
||||
}
|
||||
}
|
||||
|
||||
/// The `image` box blurred at each texel by its own half width (see [`Self::masked_box_blur`]), summing each box from running sums in two passes of two channels each.
|
||||
/// O(width × height × log16(width × height)) for the sums, and O(1) per texel at any radius for the boxes.
|
||||
fn variable_box_blur(&mut self, image: &wgpu::Texture, luminance: &wgpu::Texture, radius: DVec2, linear: bool) -> wgpu::Texture {
|
||||
let decoded = linear.then(|| self.run("decode_to_linear", WORKING_FORMAT, self.size, image, None, None, Parameters::default()));
|
||||
let scale = variable_box_scale(self.size.x as usize * self.size.y as usize);
|
||||
|
||||
let mut blurred: Option<wgpu::Texture> = None;
|
||||
for pair in 0..2 {
|
||||
let sums = self.running_sums(decoded.as_ref().unwrap_or(image), pair, scale);
|
||||
let parameters = Parameters {
|
||||
amount: if linear { 1. } else { 0. },
|
||||
values: [radius.x as f32, radius.y as f32, scale as f32, pair as f32],
|
||||
..Default::default()
|
||||
};
|
||||
let source = blurred.as_ref().unwrap_or(image);
|
||||
let next = self.run("variable_box_blur", WORKING_FORMAT, self.size, source, Some(luminance), Some(&sums), parameters);
|
||||
|
||||
[Some(sums), blurred.replace(next)].into_iter().flatten().for_each(|texture| self.textures.release(texture));
|
||||
}
|
||||
decoded.into_iter().for_each(|decoded| self.textures.release(decoded));
|
||||
|
||||
blurred.unwrap_or_else(|| self.scale(image, 1.))
|
||||
}
|
||||
|
||||
/// The running sums (a summed-area table) of two channels of the `image` (red and green for `pair` 0, blue and alpha for 1), counted in `scale` steps from 0 to 1,
|
||||
/// with two exact digits for each channel (see `RUNNING_SUM_DIGIT` in `vello_masks.wgsl`). Each pass sums blocks 16 times as long along an axis.
|
||||
fn running_sums(&mut self, image: &wgpu::Texture, pair: usize, scale: f64) -> wgpu::Texture {
|
||||
let digits = Parameters {
|
||||
values: [pair as f32, scale as f32, 0., 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let mut sums = self.run("variable_box_digits", SUMS_FORMAT, self.size, image, None, None, digits);
|
||||
|
||||
// The sums are read as the `content` input, the only one taking 32-bit floats, so the `image` fills the others
|
||||
for (axis, length) in [([1., 0.], self.size.x), ([0., 1.], self.size.y)] {
|
||||
let mut block = 1;
|
||||
while block < length {
|
||||
let parameters = Parameters {
|
||||
values: [axis[0], axis[1], block as f32, 0.],
|
||||
..Default::default()
|
||||
};
|
||||
let summed = self.run("variable_box_running_sums", SUMS_FORMAT, self.size, image, None, Some(&sums), parameters);
|
||||
self.replace(&mut sums, summed);
|
||||
block *= 16;
|
||||
}
|
||||
}
|
||||
sums
|
||||
}
|
||||
|
||||
/// Fades both the full-strength content (`content` itself until a pass replaces it) and the faded fill by a `strength` from 0 to 1.
|
||||
pub(super) fn fade_by(&mut self, content: &wgpu::Texture, full: &mut Option<wgpu::Texture>, filled: &mut Option<wgpu::Texture>, strength: &wgpu::Texture) {
|
||||
if let Some(filled) = filled {
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Records the passes that resample an item's content from elsewhere than nearby. Their shaders are in `vello_resample.wgsl`.
|
||||
|
||||
use super::{PARAMETER_TAPS, Parameters, PassRecorder};
|
||||
use glam::{DAffine2, DVec2};
|
||||
use graphic_types::resampling::{DISPLACEMENT_NEUTRAL_LEVEL, DisplacementField, EffectFrame, FrameWarp, MAX_WAVE_GENERATORS, RadialBlur, RadialBlurMethod};
|
||||
use graphic_types::vector_types::GradientSpread;
|
||||
use raster_kernels::resample_kernels::MotionBlurShear;
|
||||
|
||||
/// The tap array holding the frame's maps between the texture and its local space, and half its size, where the resampling shaders read them.
|
||||
fn frame_taps(frame: &EffectFrame) -> [[f32; 4]; PARAMETER_TAPS] {
|
||||
let to_local = frame.pixels_to_local().to_cols_array().map(|value| value as f32);
|
||||
let to_pixels = frame.local_to_pixels().to_cols_array().map(|value| value as f32);
|
||||
let half = (frame.size / 2.).as_vec2();
|
||||
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [to_local[0], to_local[1], to_local[2], to_local[3]];
|
||||
taps[1] = [to_local[4], to_local[5], to_pixels[0], to_pixels[1]];
|
||||
taps[2] = [to_pixels[2], to_pixels[3], to_pixels[4], to_pixels[5]];
|
||||
taps[3] = [half.x, half.y, 0., 0.];
|
||||
taps
|
||||
}
|
||||
|
||||
/// The first of the taps holding a wave's generators' phases, two generators to each.
|
||||
const WAVE_PHASE_TAPS: usize = 7;
|
||||
const _: () = assert!(WAVE_PHASE_TAPS + MAX_WAVE_GENERATORS.div_ceil(2) as usize <= PARAMETER_TAPS);
|
||||
|
||||
/// Where a displacement pass finds how far it moves each texel.
|
||||
pub(super) enum Displacement<'a> {
|
||||
/// One or two maps drawn over the same pixels, each with how far it moves the content where its amount is 1, in the frame's local space (see [`graphic_types::EffectOperation::displacement_maps`]).
|
||||
Maps(&'a [(&'a wgpu::Texture, DVec2)]),
|
||||
Field(DisplacementField),
|
||||
}
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// `texture` smeared along the motion blur's line by its two shears around a box, in linear light if `linear`, matching the CPU's `motion_blurred`.
|
||||
pub(super) fn motion_blur(&mut self, texture: wgpu::Texture, shear: &MotionBlurShear, linear: bool) -> wgpu::Texture {
|
||||
let [start, end] = shear.box_span();
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [start as f32, end as f32, shear.stride() as f32, 0.];
|
||||
let parameters = Parameters {
|
||||
values: [shear.slope as f32, shear.phase as f32, if shear.vertical { 1. } else { 0. }, 0.],
|
||||
taps,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.in_light(texture, linear, |recorder, mut texture| {
|
||||
for entry_point in ["motion_shear", "motion_box", "motion_unshear"] {
|
||||
let next = recorder.run(entry_point, texture.format(), recorder.size, &texture, None, None, parameters);
|
||||
recorder.replace(&mut texture, next);
|
||||
}
|
||||
texture
|
||||
})
|
||||
}
|
||||
|
||||
/// `texture` blurred along the radial blur's arcs or lines, in the effect space that `effect_to_pixels` places on the texture's pixels, in linear light if `linear`, matching the CPU's `radial_blurred`.
|
||||
pub(super) fn radial_blur(&mut self, texture: wgpu::Texture, blur: &RadialBlur, effect_to_pixels: DAffine2, linear: bool) -> wgpu::Texture {
|
||||
// The shader measures offsets from the center in the circle's space, placed here in double precision, since positions can lie far from the effect space's origin
|
||||
let circle_to_pixels = effect_to_pixels * blur.transform;
|
||||
let to_circle = circle_to_pixels.inverse().to_cols_array().map(|value| value as f32);
|
||||
let from_circle = circle_to_pixels.to_cols_array().map(|value| value as f32);
|
||||
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [to_circle[0], to_circle[1], to_circle[2], to_circle[3]];
|
||||
taps[1] = [to_circle[4], to_circle[5], from_circle[0], from_circle[1]];
|
||||
taps[2] = [from_circle[2], from_circle[3], from_circle[4], from_circle[5]];
|
||||
|
||||
// An arc in the circle's space spans at most this many pixels for each of its units, as the CPU's `RadialBlur::sample_count` measures it
|
||||
let pixels_per_length = effect_to_pixels.matrix2.determinant().abs().sqrt() * blur.longest_stretch();
|
||||
let parameters = Parameters {
|
||||
values: [blur.extent as f32, if blur.method == RadialBlurMethod::Zoom { 1. } else { 0. }, pixels_per_length as f32, 0.],
|
||||
taps,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
self.in_light(texture, linear, |recorder, mut texture| {
|
||||
let blurred = recorder.run("radial_blur", texture.format(), recorder.size, &texture, None, None, parameters);
|
||||
recorder.replace(&mut texture, blurred);
|
||||
texture
|
||||
})
|
||||
}
|
||||
|
||||
/// `texture` warped relative to the `frame`, matching the CPU's `frame_warped`.
|
||||
pub(super) fn frame_warp(&mut self, texture: wgpu::Texture, warp: &FrameWarp, frame: &EffectFrame) -> wgpu::Texture {
|
||||
let [kind, setting, extra] = warp.shader_parameters();
|
||||
let mut taps = frame_taps(frame);
|
||||
let (half_pixel, pixel_extent) = (frame.half_pixel().as_vec2(), frame.pixel_extent().as_vec2());
|
||||
taps[4] = [half_pixel.x, half_pixel.y, pixel_extent.x, pixel_extent.y];
|
||||
let parameters = Parameters {
|
||||
values: [kind, setting, extra, 0.],
|
||||
taps,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let warped = self.run("frame_warp", texture.format(), self.size, &texture, None, None, parameters);
|
||||
self.textures.release(texture);
|
||||
warped
|
||||
}
|
||||
|
||||
/// `texture` with each texel moved by the `displacement` relative to the `frame`, matching the CPU's `displaced`.
|
||||
pub(super) fn displace(&mut self, texture: wgpu::Texture, displacement: Displacement, frame: &EffectFrame, edge_mode: GradientSpread) -> wgpu::Texture {
|
||||
let mut taps = frame_taps(frame);
|
||||
let (half_pixel, pixel_extent) = (frame.half_pixel().as_vec2(), frame.pixel_extent().as_vec2());
|
||||
taps[4] = [half_pixel.x, half_pixel.y, pixel_extent.x, pixel_extent.y];
|
||||
|
||||
// The code the shader knows the edge mode by
|
||||
let mode = match edge_mode {
|
||||
GradientSpread::Pad => 0.,
|
||||
GradientSpread::Reflect => 1.,
|
||||
GradientSpread::Repeat => 2.,
|
||||
GradientSpread::Clear => 3.,
|
||||
};
|
||||
|
||||
// The shader's settings for the maps' movements, or the field's kind and settings, with a wave's seed carried exactly in `tap_count`
|
||||
let mut seed_field = 0;
|
||||
let (values, maps) = match displacement {
|
||||
Displacement::Maps(maps) => {
|
||||
// How far the source lies from each texel for each level of a map's luminance past the neutral one, the second map's in a tap
|
||||
let per_level = |movement: DVec2| (-movement / DISPLACEMENT_NEUTRAL_LEVEL).as_vec2();
|
||||
let [first, second] = [maps.first(), maps.get(1)].map(|map| map.map(|&(texture, movement)| (texture, per_level(movement))));
|
||||
let Some((first_map, first)) = first else { return texture };
|
||||
if let Some((_, second)) = second {
|
||||
taps[5] = [second.x, second.y, 1., 0.];
|
||||
}
|
||||
([first.x, first.y, mode, 0.], [Some(first_map), second.map(|(texture, _)| texture)])
|
||||
}
|
||||
Displacement::Field(DisplacementField::Ripple { wavelength, amplitude }) => {
|
||||
for (index, (direction, frequency, phase)) in DisplacementField::ripple_waves(wavelength, frame.origin).enumerate() {
|
||||
taps[5 + index] = [direction.x as f32, direction.y as f32, frequency as f32, phase as f32];
|
||||
}
|
||||
([DisplacementField::ripple_wave_amplitude(amplitude) as f32, 0., mode, 1.], [None, None])
|
||||
}
|
||||
Displacement::Field(DisplacementField::Wave {
|
||||
wave_type,
|
||||
total_generators,
|
||||
wavelength,
|
||||
amplitude,
|
||||
scale,
|
||||
seed,
|
||||
}) => {
|
||||
taps[5] = [wavelength[0] as f32, wavelength[1] as f32, amplitude[0] as f32, amplitude[1] as f32];
|
||||
taps[6] = [scale.x as f32, scale.y as f32, total_generators as f32, wave_type as u32 as f32];
|
||||
for (generator, (_, _, phases)) in DisplacementField::wave_generators(seed, total_generators, wavelength, amplitude, frame.origin).enumerate() {
|
||||
let offset = 2 * (generator % 2);
|
||||
taps[WAVE_PHASE_TAPS + generator / 2][offset..offset + 2].copy_from_slice(&phases.map(|phase| phase as f32));
|
||||
}
|
||||
seed_field = seed;
|
||||
([0., 0., mode, 2.], [None, None])
|
||||
}
|
||||
};
|
||||
let parameters = Parameters {
|
||||
values,
|
||||
taps,
|
||||
tap_count: seed_field,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let [first_map, second_map] = maps;
|
||||
let displaced = self.run("displace", texture.format(), self.size, &texture, first_map, second_map, parameters);
|
||||
self.textures.release(texture);
|
||||
displaced
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! The GPU passes of the layer styles' finer options: the outline's paints, and the bevel's contour and texture.
|
||||
|
||||
use super::{COVERAGE_FORMAT, GRADIENT_SAMPLES, MAX_TAPS, Parameters, PassRecorder, Seeds, WORKING_FORMAT};
|
||||
use super::{COVERAGE_FORMAT, GRADIENT_SAMPLES, PARAMETER_TAPS, Parameters, PassRecorder, Seeds, WORKING_FORMAT};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::{DVec2, DVec3};
|
||||
use graphic_types::BevelStyle;
|
||||
@@ -109,7 +109,7 @@ impl PassRecorder<'_> {
|
||||
BevelStyle::Emboss | BevelStyle::PillowEmboss => 2.,
|
||||
};
|
||||
|
||||
let mut taps = [[0.; 4]; MAX_TAPS];
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [style_number, (surface.slope_range.clamp(1., 100.) / 100.) as f32, start_slope as f32, end_slope as f32];
|
||||
taps[1] = [
|
||||
if reshaped { 1. } else { 0. },
|
||||
@@ -135,7 +135,7 @@ impl PassRecorder<'_> {
|
||||
/// Matches the CPU's `bevel_shading` and `foot_faded`.
|
||||
pub(super) fn bevel_amount(&mut self, brighter: &wgpu::Texture, height: &wgpu::Texture, gloss: Option<&(wgpu::Texture, bool)>, light_z: f64, shadow: bool, fades_at_foot: bool) -> wgpu::Texture {
|
||||
let flag = |on: bool| if on { 1. } else { 0. };
|
||||
let mut taps = [[0.; 4]; MAX_TAPS];
|
||||
let mut taps = [[0.; 4]; PARAMETER_TAPS];
|
||||
taps[0] = [flag(fades_at_foot), 0., 0., 0.];
|
||||
let parameters = Parameters {
|
||||
amount: BEVEL_FOOT_FADE as f32,
|
||||
|
||||
@@ -33,7 +33,7 @@ impl Shader {
|
||||
let common = include_str!("vello_generators.wgsl");
|
||||
match self {
|
||||
Self::Noise => [fastnoise_lite::WGSL_SOURCE, common, include_str!("vello_generators_noise.wgsl")].concat(),
|
||||
Self::WhiteNoise => [common, include_str!("vello_generators_white_noise.wgsl")].concat(),
|
||||
Self::WhiteNoise => [common, include_str!("vello_hash.wgsl"), include_str!("vello_generators_white_noise.wgsl")].concat(),
|
||||
Self::Mandelbrot => [common, include_str!("vello_generators_mandelbrot.wgsl")].concat(),
|
||||
}
|
||||
}
|
||||
@@ -398,7 +398,7 @@ impl GeneratorPasses {
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: TEXTURE_FORMAT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
})
|
||||
}
|
||||
|
||||
@@ -18,23 +18,7 @@ fn generate(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let point = parameters.corner + position.xy * parameters.texel;
|
||||
|
||||
let cell = vec2<i32>(floor(point));
|
||||
let hash = pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed)));
|
||||
|
||||
// The top 24 bits, which an f32 holds exactly
|
||||
let luminance = f32(hash.x >> 8u) / 16777216.;
|
||||
let luminance = hash_fraction(pcg3d(vec3<u32>(bitcast<vec2<u32>>(cell), bitcast<u32>(parameters.noise.seed))).x);
|
||||
|
||||
return vec4<f32>(vec3<f32>(linear_to_srgb(luminance)), 1.);
|
||||
}
|
||||
|
||||
// PCG3D from Jarzynski and Olano's "Hash Functions for GPU Rendering", which spreads every input bit across the result
|
||||
fn pcg3d(input: vec3<u32>) -> vec3<u32> {
|
||||
var v = input * 1664525u + 1013904223u;
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
v ^= v >> vec3<u32>(16u);
|
||||
v.x += v.y * v.z;
|
||||
v.y += v.z * v.x;
|
||||
v.z += v.x * v.y;
|
||||
return v;
|
||||
}
|
||||
Loaded 100 of 133 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user