diff --git a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs index 9fa4faec5a..71d1015e83 100644 --- a/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs +++ b/editor/src/messages/portfolio/document/data_panel/data_panel_message_handler.rs @@ -32,7 +32,7 @@ use graphene_std::vector::style::{ DashPattern, FillChoice, GradientForm, GradientHueDirection, GradientInterpolation, GradientRamp, GradientSettings, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin, }; use graphene_std::vector::{CurveType, Path, PointId, QRCodeErrorCorrectionLevel, SegmentId, Vector}; -use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, Graphic}; +use graphene_std::{Appearance, Artboard, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic}; use kurbo::BezPath; use std::any::Any; use std::sync::Arc; @@ -1243,6 +1243,7 @@ impl_table_item_layout_for_choice_enum!( BlendMode, Cover, EffectKind, + GlowSource, GradientForm, GradientSpread, GradientSpace, @@ -1416,6 +1417,7 @@ macro_rules! known_item_types { Effects, Effect, EffectKind, + GlowSource, DashPattern, BoxCorners, TransferCurve, diff --git a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs index 309fd64b07..27a096a227 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_inspector.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_inspector.rs @@ -40,7 +40,7 @@ use graphene_std::vector::style::{ build_transform_with_y_preservation, }; use graphene_std::vector::{QRCodeErrorCorrectionLevel, VectorModification}; -use graphene_std::{Artboard, Graphic, Vector}; +use graphene_std::{Artboard, GlowSource, Graphic, Vector}; use graphene_std::{NodeParameter, ParameterRef}; use math_parser::parser::{MessagePart, ParseError}; use std::path::PathBuf; @@ -438,6 +438,7 @@ pub(crate) fn inspector_row_from_type(node_id: NodeId, index: usize, ty: &Type, Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), + Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), Some(x) if id_is::(x) => enum_choice::().for_socket(default_info).inspector_row(), diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index fa9c102c78..bf70f56e52 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -579,6 +579,7 @@ tagged_value! { TonalRange(raster_nodes::adjustments::TonalRange), AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel), HueSaturationRange(raster_nodes::adjustments::HueSaturationRange), + GlowSource(graphic_types::GlowSource), GridType(vector::misc::GridType), GridTopology(vector::misc::GridTopology), ArcType(vector::misc::ArcType), @@ -708,6 +709,25 @@ impl TaggedValue { None } + fn to_stroke_align(input: &str) -> Option { + let mut choices = input.split("::"); + let (first, second) = (choices.next()?.trim(), choices.next()?.trim()); + if first == "StrokeAlign" { + return Some(match second { + "Center" => vector::style::StrokeAlign::Center, + "Inside" => vector::style::StrokeAlign::Inside, + "Outside" => vector::style::StrokeAlign::Outside, + _ => { + log::error!("Invalid StrokeAlign default type variant: {input}"); + return None; + } + }); + } + + log::error!("Invalid StrokeAlign default type: {input}"); + None + } + match ty { Type::Generic(_) => None, Type::Concrete(concrete_type) => { @@ -726,6 +746,7 @@ impl TaggedValue { () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, () if ty == TypeId::of::() => to_gradient(string).map(|gradient| TaggedValue::GradientRamp(gradient.into()))?, () if ty == TypeId::of::() => to_reference_point(string).map(TaggedValue::ReferencePoint)?, + () if ty == TypeId::of::() => to_stroke_align(string).map(TaggedValue::StrokeAlign)?, () if ty == TypeId::of::() => TaggedValue::DashPattern(core_types::misc::parse_f64_list(string)), () if ty == TypeId::of::() => TaggedValue::BoxCorners(core_types::misc::parse_f64_list(string)), _ => return None, diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index e616f6966e..8dc345a390 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -5,6 +5,7 @@ use graph_craft::application_io::{PlatformApplicationIo, PlatformEditorApi}; use graph_craft::document::value::RenderOutput; use graph_craft::proto::{NodeConstructor, TypeErasedBox}; use graphene_animation::AnimationCurve; +use graphene_std::GlowSource; use graphene_std::animation::RealTimeMode; use graphene_std::any::DynAnyNode; use graphene_std::brush::Stroke; @@ -333,6 +334,7 @@ fn node_registry() -> HashMap "Drop Shadow", Self::InnerShadow => "Inner Shadow", Self::OuterGlow => "Outer Glow", + Self::InnerGlow => "Inner Glow", + Self::Satin => "Satin", + Self::Outline => "Outline", }) } } +/// Where an inner glow starts from. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Radio)] +pub enum GlowSource { + /// Glows inward from the edges. + #[default] + Edge, + /// Glows outward from the center. + Center, +} + /// One image operation of an [`Effects`] list: an [`EffectKind`] plus its parameters, carried as attributes on the inner item. /// Each parameter's attribute is named after the input of the node that stamps the kind. Attributes the kind doesn't take are ignored. #[derive(Clone, Debug, Default, PartialEq, CacheHash)] @@ -98,6 +122,15 @@ impl Effects { } } +/// How far an outline of `weight` reaches outside the silhouette's edge and inside it, by where it's aligned. +pub fn outline_extents(weight: f64, align: StrokeAlign) -> (f64, f64) { + match align { + StrokeAlign::Outside => (weight, 0.), + StrokeAlign::Inside => (0., weight), + StrokeAlign::Center => (weight / 2., weight / 2.), + } +} + /// Appends an effect to the item's list, after those already applied to it. pub fn stamp_effect(item: &mut Item, effect: Effect) { item.attribute_mut_or_insert_default::(ATTR_EFFECTS).0.push(Item::new_from_element(effect)); @@ -131,6 +164,25 @@ pub enum EffectOperation { blur: f64, spread: f64, }, + InnerGlow { + color: Color, + blur: f64, + /// How far the glow grows into the content before it softens. + choke: f64, + source: GlowSource, + }, + Satin { + color: Color, + /// How far each of the two casts of the silhouette is moved, in opposite directions. + offset: DVec2, + blur: f64, + invert: bool, + }, + Outline { + color: Color, + weight: f64, + align: StrokeAlign, + }, } impl EffectOperation { @@ -145,6 +197,9 @@ impl EffectOperation { Self::DropShadow { .. } => EffectKind::DropShadow, Self::InnerShadow { .. } => EffectKind::InnerShadow, Self::OuterGlow { .. } => EffectKind::OuterGlow, + Self::InnerGlow { .. } => EffectKind::InnerGlow, + Self::Satin { .. } => EffectKind::Satin, + Self::Outline { .. } => EffectKind::Outline, } } @@ -156,6 +211,9 @@ impl EffectOperation { Self::DropShadow { offset, blur, spread, .. } => offset.length() + spread.max(0.) + 3. * blur.max(0.), Self::InnerShadow { offset, blur, .. } => offset.length() + 3. * blur.max(0.), Self::OuterGlow { blur, spread, .. } => spread.max(0.) + 3. * blur.max(0.), + Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.), + Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.), + Self::Outline { weight, .. } => weight.max(0.), } } @@ -184,6 +242,23 @@ impl EffectOperation { blur: 0., spread: 0., }, + EffectKind::InnerGlow => Self::InnerGlow { + color: Color::TRANSPARENT, + blur: 0., + choke: 0., + source: GlowSource::default(), + }, + EffectKind::Satin => Self::Satin { + color: Color::TRANSPARENT, + offset: DVec2::ZERO, + blur: 0., + invert: false, + }, + EffectKind::Outline => Self::Outline { + color: Color::TRANSPARENT, + weight: 0., + align: StrokeAlign::default(), + }, } } @@ -206,6 +281,23 @@ impl EffectOperation { visitor.parameter("blur", blur, 8.); visitor.parameter("spread", spread, 0.); } + Self::InnerGlow { color, blur, choke, source } => { + visitor.parameter("color", color, Color::from(SRGBA8::new(0xff, 0xff, 0xbe, 0xbf))); + visitor.parameter("blur", blur, 8.); + visitor.parameter("choke", choke, 0.); + visitor.parameter("source", source, GlowSource::default()); + } + Self::Satin { color, offset, blur, invert } => { + visitor.parameter("color", color, Color::from(SRGBA8::new(0, 0, 0, 0x80))); + visitor.parameter("offset", offset, DVec2::new(10., 4.)); + visitor.parameter("blur", blur, 14.); + visitor.parameter("invert", invert, true); + } + Self::Outline { color, weight, align } => { + visitor.parameter("color", color, Color::BLACK); + visitor.parameter("weight", weight, 3.); + visitor.parameter("align", align, StrokeAlign::Outside); + } } } } @@ -263,6 +355,23 @@ mod tests { blur: 8., spread: 2., }, + EffectOperation::InnerGlow { + color: Color::GREEN, + blur: 3., + choke: 1., + source: GlowSource::Center, + }, + EffectOperation::Satin { + color: Color::BLACK, + offset: DVec2::new(5., -6.), + blur: 2., + invert: false, + }, + EffectOperation::Outline { + color: Color::RED, + weight: 7., + align: StrokeAlign::Center, + }, ]; for operation in operations { diff --git a/node-graph/libraries/graphic-types/src/lib.rs b/node-graph/libraries/graphic-types/src/lib.rs index f6f146995b..e8ff606196 100644 --- a/node-graph/libraries/graphic-types/src/lib.rs +++ b/node-graph/libraries/graphic-types/src/lib.rs @@ -14,7 +14,7 @@ pub use vector_types; pub use adjustment::Adjustment; pub use appearance::{Appearance, Cover, CoverPlacement, Coverage, FillAndStroke, stamp_coverage}; pub use artboard::Artboard; -pub use effects::{Effect, EffectKind, EffectOperation, Effects, stamp_effect}; +pub use effects::{Effect, EffectKind, EffectOperation, Effects, GlowSource, stamp_effect}; pub use graphic::{Graphic, IntoGraphicList, TryFromGraphic, Vector}; pub mod migrations { diff --git a/node-graph/libraries/raster-kernels/src/effects.rs b/node-graph/libraries/raster-kernels/src/effects.rs index fdb9681068..60837e52c6 100644 --- a/node-graph/libraries/raster-kernels/src/effects.rs +++ b/node-graph/libraries/raster-kernels/src/effects.rs @@ -123,3 +123,76 @@ impl RasterKernel for CompositeBeneath { Wgsl::function(include_str!("wgsl/effect_composite_beneath.wgsl")) } } + +gpu_params! { + /// The coverage of everything a coverage doesn't cover. + #[derive(Clone)] + pub struct InvertCoverage {} +} + +impl RasterKernel for InvertCoverage { + const INPUTS: usize = 1; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_invert_coverage.wgsl")) + } +} + +gpu_params! { + /// The coverage of satin's shading, from the two casts of the silhouette. + #[derive(Clone)] + pub struct SatinShading { + pub invert: bool, + } +} + +impl RasterKernel for SatinShading { + const INPUTS: usize = 2; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_satin.wgsl")) + } +} + +gpu_params! { + /// Starts a jump flood from the texels inside the content's silhouette, or outside it if `inward`. + #[derive(Clone)] + pub struct JumpFloodSeed { + pub inward: bool, + } +} + +impl RasterKernel for JumpFloodSeed { + const INPUTS: usize = 1; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_jump_flood_seed.wgsl")) + } +} + +gpu_params! { + /// One step of a jump flood, spreading the nearest seeds found so far by `step` texels. + #[derive(Clone)] + pub struct JumpFloodStep { + pub step: i32, + } +} + +impl RasterKernel for JumpFloodStep { + const INPUTS: usize = 1; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_jump_flood_step.wgsl")) + } +} + +gpu_params! { + /// The coverage of the band `width` texels wide along the silhouette's edge, from a finished jump flood. + #[derive(Clone)] + pub struct EdgeBand { + pub width: f32, + } +} + +impl RasterKernel for EdgeBand { + const INPUTS: usize = 1; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_edge_band.wgsl")) + } +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_edge_band.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_edge_band.wgsl new file mode 100644 index 0000000000..7972467b93 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_edge_band.wgsl @@ -0,0 +1,8 @@ +// Covers the texels within `width` texels of the edge, which lies about half a texel short of the nearest seed, fading out over one texel +fn kernel(coord: vec2) -> vec4 { + let nearest = input_0_load(coord); + if nearest.z < 0.5 { + return vec4(0.); + } + return vec4(clamp(params().width + 1. - length(nearest.xy), 0., 1.)); +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_invert_coverage.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_invert_coverage.wgsl new file mode 100644 index 0000000000..5054797313 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_invert_coverage.wgsl @@ -0,0 +1,3 @@ +fn kernel(coord: vec2) -> vec4 { + return vec4(1. - input_0_load(coord).a); +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_seed.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_seed.wgsl new file mode 100644 index 0000000000..08f38e9d4a --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_seed.wgsl @@ -0,0 +1,7 @@ +// Jump flooding keeps each texel's offset to the nearest seed found so far (xy) and whether one is found (z). +// The seeds are the texels inside the content's silhouette, or outside it if `inward`, and each is its own nearest. +fn kernel(coord: vec2) -> vec4 { + let inside = input_0_load(coord).a >= 0.5; + let seed = inside != params().inward; + return vec4(0., 0., select(0., 1., seed), 0.); +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_step.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_step.wgsl new file mode 100644 index 0000000000..85e68adba3 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_jump_flood_step.wgsl @@ -0,0 +1,25 @@ +// Takes the nearest of the seeds that the texel and its eight neighbors `step` texels away have found so far +fn kernel(coord: vec2) -> vec4 { + let step = params().step; + + var best = input_0_load(coord); + for (var neighbor_y = -1; neighbor_y <= 1; neighbor_y++) { + for (var neighbor_x = -1; neighbor_x <= 1; neighbor_x++) { + let direction = vec2(neighbor_x, neighbor_y); + let neighbor = coord + direction * step; + if any(neighbor < vec2(0)) || any(neighbor >= input_0_size()) { + continue; + } + let found = input_0_load(neighbor); + if found.z < 0.5 { + continue; + } + + let candidate = found.xy + vec2(direction * step); + if best.z < 0.5 || dot(candidate, candidate) < dot(best.xy, best.xy) { + best = vec4(candidate, 1., 0.); + } + } + } + return best; +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_satin.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_satin.wgsl new file mode 100644 index 0000000000..bbb3fd128d --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_satin.wgsl @@ -0,0 +1,5 @@ +// Satin's shading from two casts of the silhouette: how much one covers without the other, or how much they agree if `invert` +fn kernel(coord: vec2) -> vec4 { + let difference = abs(input_0_load(coord).a - input_1_load(coord).a); + return vec4(select(difference, 1. - difference, params().invert)); +} diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 429aa0648b..4195ef2692 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -307,6 +307,74 @@ impl SvgFilterPrimitives { self.push("feComposite", &format!(r#"in="{first}" in2="{second}" operator="arithmetic" k2="1" k3="1""#), "") } + /// The coverage of the content's silhouette (or of the area outside it, if `inverse`), cast by `offset`, grown by `spread` and softened by `blur`, all in user units. + fn cast(&mut self, full_content: &str, offset: DVec2, blur: f64, spread: f64, inverse: bool) -> String { + let mut coverage = match offset == DVec2::ZERO { + true => full_content.to_string(), + false => self.push("feOffset", &format!(r#"in="{full_content}" dx="{}" dy="{}""#, offset.x, offset.y), ""), + }; + if inverse { + let opaque = self.push("feFlood", r#"flood-opacity="1""#, ""); + coverage = self.push("feComposite", &format!(r#"in="{opaque}" in2="{coverage}" operator="out""#), ""); + } + if spread >= 0.01 { + coverage = self.push("feMorphology", &format!(r#"in="{coverage}" operator="dilate" radius="{spread}""#), ""); + } + if blur >= 0.01 { + coverage = self.push("feGaussianBlur", &format!(r#"in="{coverage}" stdDeviation="{blur}""#), ""); + } + coverage + } + + /// The coverage of the band reaching `width` user units from the silhouette's edge, outward or (if `inward`) inward. + /// SVG measures no straight-line distances, so a blur thresholded where it falls to that of a straight edge's at the width rounds the corners instead. + fn edge_band(&mut self, full_content: &str, width: f64, inward: bool) -> String { + // At this distance past a straight edge, a Gaussian of half the width falls to Φ(-2), dropping by φ(2) / σ per unit + const THRESHOLD: f64 = 0.022_750_13; + const FALLOFF: f64 = 0.053_990_97; + + let silhouette = self.cast(full_content, DVec2::ZERO, width / 2., 0., inward); + let slope = width / 2. / FALLOFF; + let intercept = 0.5 - slope * THRESHOLD; + self.push( + "feComponentTransfer", + &format!(r#"in="{silhouette}""#), + &format!(r#""#), + ) + } + + /// The coverage tinted `color`. + fn tint(&mut self, coverage: &str, color: Color) -> String { + let flood = self.push( + "feFlood", + &format!(r##"flood-color="#{}" flood-opacity="{}""##, SRGBA8::from(color.with_alpha(1.)).to_rgb_hex(), color.a()), + "", + ); + self.push("feComposite", &format!(r#"in="{flood}" in2="{coverage}" operator="in""#), "") + } + + /// Stacks the coverage, tinted `color`, over the shadows and glows already `beneath` the content. + fn shade_beneath(&mut self, beneath: Option, coverage: &str, color: Color) -> String { + let tinted = self.tint(coverage, color); + match beneath { + Some(beneath) => self.push("feComposite", &format!(r#"in="{tinted}" in2="{beneath}" operator="over""#), ""), + None => tinted, + } + } + + /// Places the coverage, tinted `color`, over both the full-strength content and the faded fill, within the content so it stays visible over a faded fill. + fn shade_within(&mut self, full_content: &mut String, filled: &mut Option, coverage: &str, color: Color) { + let tinted = self.tint(coverage, color); + let within = self.push("feComposite", &format!(r#"in="{tinted}" in2="{full_content}" operator="in""#), ""); + + let mut over = |image: &str| { + let uncovered = self.push("feComposite", &format!(r#"in="{image}" in2="{tinted}" operator="out""#), ""); + self.add(&within, &uncovered) + }; + *filled = filled.as_deref().map(&mut over); + *full_content = over(full_content); + } + /// The image with the shadows and glows `beneath` it, knocked out by the full-strength content so a faded fill doesn't reveal them. fn composite_beneath(&mut self, image: &str, beneath: &str, full_content: &str) -> String { let knocked_out = self.push("feComposite", &format!(r#"in="{beneath}" in2="{full_content}" operator="out""#), ""); @@ -317,7 +385,8 @@ impl SvgFilterPrimitives { /// Writes an SVG filter into `svg_defs` that carries out `effects` like the GPU passes do, returning its ID, or `None` if the user space is degenerate. /// `bounds` is the content's extent in the filtered group's user space, which `user_to_document` maps into the document space the effects' lengths are measured in. fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2) -> Option { - use graphic_types::EffectOperation; + use graphic_types::effects::outline_extents; + use graphic_types::{EffectOperation, GlowSource}; let determinant = user_to_document.matrix2.determinant(); if !determinant.is_normal() { @@ -335,7 +404,7 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, let mut beneath: Option = None; for effect in effects.operations() { - let (color, offset, blur, spread, inner) = match effect { + match effect { EffectOperation::Blur { radius, box_blur, gamma } => { let radius = radius * length_scale; if radius < 0.01 { @@ -355,51 +424,53 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, filled = filled.map(|filled| primitives.push("feGaussianBlur", &attributes(&filled), "")); full = primitives.push("feGaussianBlur", &attributes(&full), ""); - continue; } - EffectOperation::DropShadow { color, offset, blur, spread } => (color, offset, blur, spread, false), - EffectOperation::OuterGlow { color, blur, spread } => (color, DVec2::ZERO, blur, spread, false), - EffectOperation::InnerShadow { color, offset, blur, spread } => (color, offset, blur, spread, true), - }; + EffectOperation::DropShadow { color, offset, blur, spread } => { + let coverage = primitives.cast(&full, document_to_user * offset, blur * length_scale, spread * length_scale, false); + beneath = Some(primitives.shade_beneath(beneath, &coverage, color)); + } + EffectOperation::OuterGlow { color, blur, spread } => { + let coverage = primitives.cast(&full, DVec2::ZERO, blur * length_scale, spread * length_scale, false); + beneath = Some(primitives.shade_beneath(beneath, &coverage, color)); + } + EffectOperation::InnerShadow { color, offset, blur, spread } => { + let coverage = primitives.cast(&full, document_to_user * offset, blur * length_scale, spread * length_scale, true); + primitives.shade_within(&mut full, &mut filled, &coverage, color); + } + EffectOperation::InnerGlow { color, blur, choke, source } => { + let mut coverage = primitives.cast(&full, DVec2::ZERO, blur * length_scale, choke * length_scale, true); + if source == GlowSource::Center { + coverage = primitives.push("feComponentTransfer", &format!(r#"in="{coverage}""#), r#""#); + } + primitives.shade_within(&mut full, &mut filled, &coverage, color); + } + EffectOperation::Satin { color, offset, blur, invert } => { + let offset = document_to_user * offset; + let forward = primitives.cast(&full, offset, blur * length_scale, 0., false); + let backward = primitives.cast(&full, -offset, blur * length_scale, 0., false); - // The silhouette, or the area outside it for an inner shadow, cast by the offset, grown by the spread, and softened by the blur - let offset = document_to_user * offset; - let mut coverage = match offset == DVec2::ZERO { - true => full.clone(), - false => primitives.push("feOffset", &format!(r#"in="{full}" dx="{}" dy="{}""#, offset.x, offset.y), ""), - }; - if inner { - let opaque = primitives.push("feFlood", r#"flood-opacity="1""#, ""); - coverage = primitives.push("feComposite", &format!(r#"in="{opaque}" in2="{coverage}" operator="out""#), ""); - } - if spread * length_scale >= 0.01 { - coverage = primitives.push("feMorphology", &format!(r#"in="{coverage}" operator="dilate" radius="{}""#, spread * length_scale), ""); - } - if blur * length_scale >= 0.01 { - coverage = primitives.push("feGaussianBlur", &format!(r#"in="{coverage}" stdDeviation="{}""#, blur * length_scale), ""); - } - - let flood = primitives.push( - "feFlood", - &format!(r##"flood-color="#{}" flood-opacity="{}""##, SRGBA8::from(color.with_alpha(1.)).to_rgb_hex(), color.a()), - "", - ); - let tinted = primitives.push("feComposite", &format!(r#"in="{flood}" in2="{coverage}" operator="in""#), ""); - - if inner { - // Placed over the image within the full-strength content, so it stays visible over a faded fill - let within = primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{full}" operator="in""#), ""); - let mut over = |image: &str| { - let uncovered = primitives.push("feComposite", &format!(r#"in="{image}" in2="{tinted}" operator="out""#), ""); - primitives.add(&within, &uncovered) - }; - filled = filled.map(|filled| over(&filled)); - full = over(&full); - } else { - beneath = Some(match beneath { - Some(beneath) => primitives.push("feComposite", &format!(r#"in="{tinted}" in2="{beneath}" operator="over""#), ""), - None => tinted, - }); + // The difference either way, each clamped at zero, adds up to its absolute value + let difference = |primitives: &mut SvgFilterPrimitives, first: &str, second: &str| { + primitives.push("feComposite", &format!(r#"in="{first}" in2="{second}" operator="arithmetic" k2="1" k3="-1""#), "") + }; + let (ahead, behind) = (difference(&mut primitives, &forward, &backward), difference(&mut primitives, &backward, &forward)); + let mut coverage = primitives.add(&ahead, &behind); + if invert { + coverage = primitives.push("feComponentTransfer", &format!(r#"in="{coverage}""#), r#""#); + } + primitives.shade_within(&mut full, &mut filled, &coverage, color); + } + EffectOperation::Outline { color, weight, align } => { + let (outside, inside) = outline_extents(weight * length_scale, align); + if outside >= 0.01 { + let coverage = primitives.edge_band(&full, outside, false); + beneath = Some(primitives.shade_beneath(beneath, &coverage, color)); + } + if inside >= 0.01 { + let coverage = primitives.edge_band(&full, inside, true); + primitives.shade_within(&mut full, &mut filled, &coverage, color); + } + } } } @@ -4072,4 +4143,48 @@ mod tests { assert!(defs.contains(r#"in="effect-1" stdDeviation="3" color-interpolation-filters="linearRGB""#), "{defs}"); assert!(defs.ends_with(r#""#), "{defs}"); } + + #[test] + fn svg_effects_filters_carry_out_inner_glows_satins_and_outlines() { + use graphic_types::vector_types::vector::style::StrokeAlign; + use graphic_types::{EffectOperation, GlowSource}; + + let filter = |operation| { + let mut defs = String::new(); + write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY).unwrap(); + defs + }; + let invert = r#""#; + + // A glow from the center is the inverse of one from the edges, cast from the area outside the content + let inner_glow = filter(EffectOperation::InnerGlow { + color: Color::WHITE, + blur: 2., + choke: 1., + source: GlowSource::Center, + }); + assert!( + inner_glow.contains(r#"operator="out""#) && inner_glow.contains(r#"operator="dilate" radius="1""#) && inner_glow.contains(invert), + "{inner_glow}" + ); + + // Satin takes the difference both ways between two opposite casts + let satin = filter(EffectOperation::Satin { + color: Color::BLACK, + offset: DVec2::new(3., 0.), + blur: 1., + invert: false, + }); + assert!(satin.contains(r#"dx="3" dy="0""#) && satin.contains(r#"dx="-3" dy="-0""#), "{satin}"); + assert_eq!(satin.matches(r#"k2="1" k3="-1""#).count(), 2, "{satin}"); + + // A centered outline draws half its weight on each side, outside beneath the content and inside within it + let outline = filter(EffectOperation::Outline { + color: Color::BLACK, + weight: 4., + align: StrokeAlign::Center, + }); + assert_eq!(outline.matches(r#"stdDeviation="1""#).count(), 2, "{outline}"); + assert_eq!(outline.matches(r#"k2="1" k3="1""#).count(), 2, "placed within the content, then above what lies beneath it: {outline}"); + } } diff --git a/node-graph/libraries/wgpu-executor/src/raster_effects.rs b/node-graph/libraries/wgpu-executor/src/raster_effects.rs index c97f2f33fb..6b1a6c903d 100644 --- a/node-graph/libraries/wgpu-executor/src/raster_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/raster_effects.rs @@ -7,7 +7,8 @@ use crate::shader_runtime::raster_kernel_runtime::RasterKernelInput; use core_types::list::{ATTR_EFFECTS, Item}; use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM, Color, NodeError}; use glam::{DAffine2, DMat2, DVec2, UVec2}; -use graphic_types::{EffectOperation, Effects}; +use graphic_types::effects::outline_extents; +use graphic_types::{EffectOperation, Effects, GlowSource}; use raster_kernels::RasterKernel; use raster_kernels::blur::BlurSpace; use raster_kernels::effects::*; @@ -157,6 +158,31 @@ impl<'a> EffectsPass<'a> { let coverage = self.cast(lengths_to_pixels * offset, blur * length_scale, spread * length_scale, true)?; self.shade_within(&coverage, color)?; } + EffectOperation::InnerGlow { color, blur, choke, source } => { + let mut coverage = self.cast(DVec2::ZERO, blur * length_scale, choke * length_scale, true)?; + if source == GlowSource::Center { + coverage = self.run(&InvertCoverage {}, &[&coverage])?; + } + self.shade_within(&coverage, color)?; + } + EffectOperation::Satin { color, offset, blur, invert } => { + let offset = lengths_to_pixels * offset; + let forward = self.cast(offset, blur * length_scale, 0., false)?; + let backward = self.cast(-offset, blur * length_scale, 0., false)?; + let coverage = self.run(&SatinShading { invert }, &[&forward, &backward])?; + self.shade_within(&coverage, color)?; + } + EffectOperation::Outline { color, weight, align } => { + let (outside, inside) = outline_extents(weight * length_scale, align); + if outside >= NEGLIGIBLE_LENGTH { + let coverage = self.edge_band(outside, false)?; + self.accumulate(&coverage, color)?; + } + if inside >= NEGLIGIBLE_LENGTH { + let coverage = self.edge_band(inside, true)?; + self.shade_within(&coverage, color)?; + } + } } Ok(()) @@ -269,4 +295,24 @@ impl<'a> EffectsPass<'a> { fn composite_beneath(&self, image: &Raster, beneath: &Raster, full_content: &Raster) -> Result, NodeError> { self.run(&CompositeBeneath {}, &[image, beneath, full_content]) } + + /// The coverage of the band reaching `width` pixels from the content's silhouette edge, outward or (if `inward`) inward, measured in straight lines so it rounds corners. + fn edge_band(&self, width: f64, inward: bool) -> Result, NodeError> { + let nearest = self.nearest_across_edge(width, inward)?; + self.run(&EdgeBand { width: width as f32 }, &[&nearest]) + } + + /// Each texel's offset to the nearest texel across the content's silhouette edge: outside it if `inward`, or inside it otherwise, in the layout [`JumpFloodStep`] keeps. + /// Jump flooding finds them in a pass for each halving of a step that starts past `reach`, so farther texels may find none. + fn nearest_across_edge(&self, reach: f64, inward: bool) -> Result, NodeError> { + let mut nearest = self.run(&JumpFloodSeed { inward }, &[&self.full])?; + + let mut step = (reach.max(0.).ceil() as u32 + 1).next_power_of_two() as i32; + while step >= 1 { + nearest = self.run(&JumpFloodStep { step }, &[&nearest])?; + step /= 2; + } + + Ok(nearest) + } } diff --git a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs index 152c76dc85..b219cf0681 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -377,6 +377,59 @@ fn shadows_and_glows_fall_where_they_should() { } } +#[test] +fn inner_glows_satins_and_outlines_fall_where_they_should() { + use core_types::Color as GraphicColor; + use glam::DVec2; + use graphic_types::vector_types::vector::style::StrokeAlign; + use graphic_types::{EffectOperation, GlowSource}; + + let size = UVec2::new(128, 128); + let black = GraphicColor::BLACK; + let render_square = |effect| render_square_with_effects(vec![effect], 1., 30., 80., size); + let (white, clear) = ([255, 255, 255, 255], 0); + + // A hard inner glow from the edges covers a band inside them, and one from the center covers the rest + let inner_glow = |source| EffectOperation::InnerGlow { + color: black, + blur: 0., + choke: 3., + source, + }; + let Some(pixels) = render_square(inner_glow(GlowSource::Edge)) else { return }; + assert_eq!(pixel(&pixels, size, 31, 55), [0, 0, 0, 255], "the edge glows"); + assert_eq!(pixel(&pixels, size, 55, 55), white, "the center doesn't"); + assert_eq!(pixel(&pixels, size, 25, 55)[3], clear, "nothing outside"); + let Some(pixels) = render_square(inner_glow(GlowSource::Center)) else { return }; + assert_eq!(pixel(&pixels, size, 31, 55), white, "the edge doesn't glow"); + assert_eq!(pixel(&pixels, size, 55, 55), [0, 0, 0, 255], "the center does"); + + // Satin shades where the two casts of the silhouette disagree, which for a horizontal offset is a band along each side + let satin = EffectOperation::Satin { + color: black, + offset: DVec2::new(10., 0.), + blur: 0., + invert: false, + }; + let Some(pixels) = render_square(satin) else { return }; + assert_eq!(pixel(&pixels, size, 35, 55), [0, 0, 0, 255], "the left band"); + assert_eq!(pixel(&pixels, size, 55, 55), white, "the middle, where both casts cover"); + assert_eq!(pixel(&pixels, size, 75, 55), [0, 0, 0, 255], "the right band"); + + // An outline outside the edge rounds the corners it grows around, and one inside stays within the content + let outline = |align| EffectOperation::Outline { color: black, weight: 5., align }; + let Some(pixels) = render_square(outline(StrokeAlign::Outside)) else { return }; + assert_eq!(pixel(&pixels, size, 26, 55), [0, 0, 0, 255], "within the weight of the edge"); + assert_eq!(pixel(&pixels, size, 23, 55)[3], clear, "past the weight"); + assert_eq!(pixel(&pixels, size, 27, 27), [0, 0, 0, 255], "near the corner"); + assert!(pixel(&pixels, size, 26, 26)[3] < 128, "beyond the rounded corner, where a square would reach"); + assert_eq!(pixel(&pixels, size, 55, 55), white, "the content shows"); + let Some(pixels) = render_square(outline(StrokeAlign::Inside)) else { return }; + assert_eq!(pixel(&pixels, size, 32, 55), [0, 0, 0, 255], "inside the edge"); + assert_eq!(pixel(&pixels, size, 40, 55), white, "past the weight inside"); + assert_eq!(pixel(&pixels, size, 28, 55)[3], clear, "nothing outside"); +} + #[test] fn later_shadows_stack_over_earlier_ones_beneath_the_content() { use core_types::Color as GraphicColor; @@ -513,7 +566,8 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() { use core_types::{ATTR_OPACITY_FILL, ATTR_TRANSFORM}; use glam::DVec2; use graphic_types::raster_types::{CPU, GPU, Image, Raster, Storage}; - use graphic_types::{EffectOperation, Effects}; + use graphic_types::vector_types::vector::style::StrokeAlign; + use graphic_types::{EffectOperation, Effects, GlowSource}; let size = UVec2::new(160, 160); let (min, max) = (50, 100); @@ -544,6 +598,45 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() { }, blur(2., false, false), ], + vec![EffectOperation::InnerGlow { + color: shadow_color, + blur: 5., + choke: 2., + source: GlowSource::Edge, + }], + vec![EffectOperation::InnerGlow { + color: shadow_color, + blur: 8., + choke: 0., + source: GlowSource::Center, + }], + vec![EffectOperation::Satin { + color: shadow_color, + offset: DVec2::new(7., 3.), + blur: 6., + invert: true, + }], + vec![EffectOperation::Satin { + color: shadow_color, + offset: DVec2::new(-4., 9.), + blur: 3., + invert: false, + }], + vec![EffectOperation::Outline { + color: shadow_color, + weight: 6., + align: StrokeAlign::Outside, + }], + vec![EffectOperation::Outline { + color: shadow_color, + weight: 5., + align: StrokeAlign::Inside, + }], + vec![EffectOperation::Outline { + color: shadow_color, + weight: 9., + align: StrokeAlign::Center, + }], ]; let Some(executor) = executor() else { return }; diff --git a/node-graph/nodes/gstd/src/lib.rs b/node-graph/nodes/gstd/src/lib.rs index 7872a36a3d..e214031d23 100644 --- a/node-graph/nodes/gstd/src/lib.rs +++ b/node-graph/nodes/gstd/src/lib.rs @@ -13,7 +13,7 @@ pub use graphene_application_io as application_io; pub use graphene_core; pub use graphene_core::debug; pub use graphic_nodes; -pub use graphic_types::{Appearance, Artboard, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, Graphic, Vector, stamp_coverage}; +pub use graphic_types::{Appearance, Artboard, Cover, CoverPlacement, Coverage, Effect, EffectKind, EffectOperation, Effects, GlowSource, Graphic, Vector, stamp_coverage}; pub use math_nodes; pub use path_bool_nodes; pub use raster_nodes; diff --git a/node-graph/nodes/raster/src/effects.rs b/node-graph/nodes/raster/src/effects.rs index fc208ca2aa..1ba7c767d9 100644 --- a/node-graph/nodes/raster/src/effects.rs +++ b/node-graph/nodes/raster/src/effects.rs @@ -5,8 +5,9 @@ use core_types::transform::Footprint; use core_types::{Color, Ctx, Interrupt, NodeError}; use glam::DVec2; use graphic_types::raster_types::{CPU, GPU, Raster}; -use graphic_types::{Effect, EffectOperation, Graphic, Vector, stamp_effect}; +use graphic_types::{Effect, EffectOperation, GlowSource, Graphic, Vector, stamp_effect}; use vector_types::Gradient; +use vector_types::vector::style::StrokeAlign; use wgpu_executor::WgpuPipelineCache; use wgpu_executor::raster_effects::evaluate_raster_effects; @@ -181,6 +182,114 @@ fn outer_glow( ) } +/// Glows inward from the edges of the input graphics, or outward from their center. +#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))] +fn inner_glow( + _: impl Ctx, + /// The content to glow within. + #[implementations(Raster, Graphic, Vector, Raster, Color, Gradient, String)] + content: Item, + /// The glow's color, with its opacity. + #[default("#ffffbebf")] + color: Item, + /// How soft the glow's edges are. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..100)] + #[default(8.)] + blur: Item, + /// How far the glow grows into the content before it softens. + #[unit(" px")] + #[hard(0..)] + choke: Item, + /// Whether the glow starts from the edges or the center. + source: Item, + #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item, +) -> Result, Interrupt> { + apply_effect( + content, + EffectOperation::InnerGlow { + color: *color.element(), + blur: *blur.element(), + choke: *choke.element(), + source: *source.element(), + }, + pipeline, + ) +} + +/// Shades the inside of the input graphics with soft, glossy bands that follow their shape. +#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))] +fn satin( + _: impl Ctx, + /// The content to shade. + #[implementations(Raster, Graphic, Vector, Raster, Color, Gradient, String)] + content: Item, + /// The shading's color, with its opacity. + #[default("#00000080")] + color: Item, + /// How far apart the bands are drawn, and in which direction. + #[unit(" px")] + #[default(10., 4.)] + offset: Item, + /// How soft the bands are. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..100)] + #[default(14.)] + blur: Item, + /// Shade where the bands overlap rather than where they don't. + #[default(true)] + invert: Item, + #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item, +) -> Result, Interrupt> { + apply_effect( + content, + EffectOperation::Satin { + color: *color.element(), + offset: *offset.element(), + blur: *blur.element(), + invert: *invert.element(), + }, + pipeline, + ) +} + +/// Draws a band of color along the edge of the input graphics, outside, inside, or centered on it. +#[node_macro::node(category("Raster: Effect"), icon("NodeBlur"))] +fn outline( + _: impl Ctx, + /// The content to outline. + #[implementations(Raster, Graphic, Vector, Raster, Color, Gradient, String)] + content: Item, + /// The outline's color, with its opacity. + #[default(Color::BLACK)] + color: Item, + /// How thick the outline is. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..100)] + #[default(3.)] + weight: Item, + /// Whether the outline is drawn outside the edge, inside it, or centered on it. + #[default(StrokeAlign::Outside)] + align: Item, + #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item, +) -> Result, Interrupt> { + apply_effect( + content, + EffectOperation::Outline { + color: *color.element(), + weight: *weight.element(), + align: *align.element(), + }, + pipeline, + ) +} + /// Uploads an image to the GPU and carries out its effects into the pixels, at the image's own resolution, for what comes next to run on the GPU right away. #[node_macro::node(category("Raster"), icon("NodeUploadTexture"))] fn eager(