From aa7ebfc18ce407143d110efb731d3e42898783c8 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Wed, 14 Oct 2026 20:52:36 -0700 Subject: [PATCH] Add a Bevel & Emboss effect lighting the inner, outer, emboss, and pillow slopes --- .../data_panel/data_panel_message_handler.rs | 6 +- .../document/node_graph/node_inspector.rs | 4 +- node-graph/graph-craft/src/document/value.rs | 2 + .../interpreted-executor/src/node_registry.rs | 4 +- .../libraries/graphic-types/src/effects.rs | 108 ++++++++++++++- node-graph/libraries/graphic-types/src/lib.rs | 2 +- .../libraries/raster-kernels/src/effects.rs | 35 +++++ .../src/wgsl/effect_bevel_height.wgsl | 34 +++++ .../src/wgsl/effect_bevel_shading.wgsl | 16 +++ .../libraries/rendering/src/renderer.rs | 127 ++++++++++++++++-- .../wgpu-executor/src/raster_effects.rs | 52 ++++++- .../wgpu-executor/src/vello_render/tests.rs | 52 ++++++- node-graph/nodes/gstd/src/lib.rs | 2 +- node-graph/nodes/raster/src/effects.rs | 70 +++++++++- 14 files changed, 493 insertions(+), 21 deletions(-) create mode 100644 node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_height.wgsl create mode 100644 node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_shading.wgsl 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 71d1015e83..ece99d51bc 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, GlowSource, Graphic}; +use graphene_std::{Appearance, Artboard, BevelDirection, BevelStyle, Color, ContextFeatures, ContextOverrides, Cover, Coverage, Effect, EffectKind, Effects, GlowSource, Graphic}; use kurbo::BezPath; use std::any::Any; use std::sync::Arc; @@ -1242,6 +1242,8 @@ macro_rules! impl_table_item_layout_for_choice_enum { impl_table_item_layout_for_choice_enum!( BlendMode, Cover, + BevelDirection, + BevelStyle, EffectKind, GlowSource, GradientForm, @@ -1418,6 +1420,8 @@ macro_rules! known_item_types { Effect, EffectKind, GlowSource, + BevelStyle, + BevelDirection, 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 27a096a227..5e696367cd 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, GlowSource, Graphic, Vector}; +use graphene_std::{Artboard, BevelDirection, BevelStyle, GlowSource, Graphic, Vector}; use graphene_std::{NodeParameter, ParameterRef}; use math_parser::parser::{MessagePart, ParseError}; use std::path::PathBuf; @@ -439,6 +439,8 @@ 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(), 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 bf70f56e52..dce4ee03e5 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -580,6 +580,8 @@ tagged_value! { AdjustmentChannel(raster_nodes::adjustments::AdjustmentChannel), HueSaturationRange(raster_nodes::adjustments::HueSaturationRange), GlowSource(graphic_types::GlowSource), + BevelStyle(graphic_types::BevelStyle), + BevelDirection(graphic_types::BevelDirection), GridType(vector::misc::GridType), GridTopology(vector::misc::GridTopology), ArcType(vector::misc::ArcType), diff --git a/node-graph/interpreted-executor/src/node_registry.rs b/node-graph/interpreted-executor/src/node_registry.rs index 8dc345a390..04913bbd3b 100644 --- a/node-graph/interpreted-executor/src/node_registry.rs +++ b/node-graph/interpreted-executor/src/node_registry.rs @@ -5,7 +5,6 @@ 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; @@ -28,6 +27,7 @@ use graphene_std::vector::misc::{ use graphene_std::vector::style::{DashPattern, GradientForm, GradientHueDirection, GradientInterpolation, GradientSpace, GradientSpread, StrokeAlign, StrokeCap, StrokeJoin}; use graphene_std::vector::{QRCodeErrorCorrectionLevel, Vector, VectorModification}; use graphene_std::{Artboard, Context, Graphic, NodeIO, NodeIOTypes, ProtoNodeIdentifier, concrete, fn_type}; +use graphene_std::{BevelDirection, BevelStyle, GlowSource}; use node_registry_macros::async_node; use std::collections::HashMap; use std::sync::Arc; @@ -335,6 +335,8 @@ fn node_registry() -> HashMap "Inner Glow", Self::Satin => "Satin", Self::Outline => "Outline", + Self::BevelAndEmboss => "Bevel & Emboss", }) } } @@ -58,6 +61,48 @@ pub enum GlowSource { Center, } +/// Which slopes a bevel shapes from the content's edges. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Dropdown)] +pub enum BevelStyle { + /// Slopes up from the edges into the content. + #[default] + InnerBevel, + /// Slopes down from the edges away from the content. + OuterBevel, + /// Slopes across the edges, half inside the content and half outside. + Emboss, + /// Slopes away from the edges both ways, as if pressed into the surface along them. + PillowEmboss, +} + +/// Whether a bevel rises from the surface or sinks into it. +#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] +#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))] +#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash, CacheHash, DynAny, node_macro::ChoiceType)] +#[widget(Radio)] +pub enum BevelDirection { + /// Raised from the surface. + #[default] + Up, + /// Pressed into the surface. + Down, +} + +/// The deviation of the blur that rounds a bevel's slopes of `size`, in the same units. +pub fn bevel_smoothing(size: f64) -> f64 { + size.max(0.) / 4. +} + +/// The unit vector toward a bevel's light from its `angle` and `altitude` in degrees, with `lengths_to_target` mapping document directions into the y-down space it's lit in. +pub fn bevel_light(angle: f64, altitude: f64, lengths_to_target: DMat2) -> DVec3 { + let (angle, altitude) = (angle.to_radians(), altitude.clamp(0., 90.).to_radians()); + let across = (lengths_to_target * DVec2::new(angle.cos(), -angle.sin())).try_normalize().unwrap_or(DVec2::X); + (across * altitude.cos()).extend(altitude.sin()) +} + /// 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)] @@ -183,6 +228,22 @@ pub enum EffectOperation { weight: f64, align: StrokeAlign, }, + BevelAndEmboss { + style: BevelStyle, + /// How steep the slopes are, as a percentage. + depth: f64, + direction: BevelDirection, + /// How wide the slopes are. + size: f64, + /// How much the highlights and shadows are blurred. + soften: f64, + /// The direction the light comes from, in degrees counterclockwise from the right. + angle: f64, + /// How high the light is above the surface, in degrees from flat to straight overhead. + altitude: f64, + highlight_color: Color, + shadow_color: Color, + }, } impl EffectOperation { @@ -200,6 +261,7 @@ impl EffectOperation { Self::InnerGlow { .. } => EffectKind::InnerGlow, Self::Satin { .. } => EffectKind::Satin, Self::Outline { .. } => EffectKind::Outline, + Self::BevelAndEmboss { .. } => EffectKind::BevelAndEmboss, } } @@ -214,6 +276,7 @@ impl EffectOperation { Self::InnerGlow { blur, choke, .. } => choke.max(0.) + 3. * blur.max(0.), Self::Satin { offset, blur, .. } => offset.length() + 3. * blur.max(0.), Self::Outline { weight, .. } => weight.max(0.), + Self::BevelAndEmboss { size, soften, .. } => size.max(0.) + 3. * (soften.max(0.) + bevel_smoothing(*size)), } } @@ -259,6 +322,17 @@ impl EffectOperation { weight: 0., align: StrokeAlign::default(), }, + EffectKind::BevelAndEmboss => Self::BevelAndEmboss { + style: BevelStyle::default(), + depth: 0., + direction: BevelDirection::default(), + size: 0., + soften: 0., + angle: 0., + altitude: 0., + highlight_color: Color::TRANSPARENT, + shadow_color: Color::TRANSPARENT, + }, } } @@ -298,6 +372,27 @@ impl EffectOperation { visitor.parameter("weight", weight, 3.); visitor.parameter("align", align, StrokeAlign::Outside); } + Self::BevelAndEmboss { + style, + depth, + direction, + size, + soften, + angle, + altitude, + highlight_color, + shadow_color, + } => { + visitor.parameter("style", style, BevelStyle::default()); + visitor.parameter("depth", depth, 100.); + visitor.parameter("direction", direction, BevelDirection::default()); + visitor.parameter("size", size, 5.); + visitor.parameter("soften", soften, 0.); + visitor.parameter("angle", angle, 120.); + visitor.parameter("altitude", altitude, 30.); + visitor.parameter("highlight_color", highlight_color, Color::from(SRGBA8::new(0xff, 0xff, 0xff, 0xbf))); + visitor.parameter("shadow_color", shadow_color, Color::from(SRGBA8::new(0, 0, 0, 0xbf))); + } } } } @@ -372,6 +467,17 @@ mod tests { weight: 7., align: StrokeAlign::Center, }, + EffectOperation::BevelAndEmboss { + style: BevelStyle::PillowEmboss, + depth: 250., + direction: BevelDirection::Down, + size: 12., + soften: 2., + angle: -45., + altitude: 60., + highlight_color: Color::YELLOW, + shadow_color: Color::BLUE, + }, ]; 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 e8ff606196..a16700f4c3 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, GlowSource, stamp_effect}; +pub use effects::{BevelDirection, BevelStyle, 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 60837e52c6..1e43774d2a 100644 --- a/node-graph/libraries/raster-kernels/src/effects.rs +++ b/node-graph/libraries/raster-kernels/src/effects.rs @@ -196,3 +196,38 @@ impl RasterKernel for EdgeBand { Wgsl::function(include_str!("wgsl/effect_edge_band.wgsl")) } } + +gpu_params! { + /// A bevel's height from 0 to 1, from the two finished jump floods across the silhouette's edge. `style` is a [`graphic_types::BevelStyle`]. + #[derive(Clone)] + pub struct BevelHeight { + pub size: f32, + pub style: u32, + } +} + +impl RasterKernel for BevelHeight { + const INPUTS: usize = 2; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_bevel_height.wgsl")) + } +} + +gpu_params! { + /// The coverage of a bevel's highlight, or if `shadow` of its shadow, from its height lit from the direction of the unit vector `light`. + #[derive(Clone)] + pub struct BevelShading { + pub slope: f32, + pub light_x: f32, + pub light_y: f32, + pub light_z: f32, + pub shadow: bool, + } +} + +impl RasterKernel for BevelShading { + const INPUTS: usize = 1; + fn wgsl() -> Wgsl { + Wgsl::function(include_str!("wgsl/effect_bevel_shading.wgsl")) + } +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_height.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_height.wgsl new file mode 100644 index 0000000000..8c876219ca --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_height.wgsl @@ -0,0 +1,34 @@ +// A bevel's height from 0 to 1, shaped by the style over a slope `size` texels wide, from the nearest texels inside (input 0) and outside (input 1) +fn kernel(coord: vec2) -> vec4 { + let parameters = params(); + let to_inside = input_0_load(coord); + let to_outside = input_1_load(coord); + let size = parameters.size; + + // Texels inside the silhouette are those at no distance from it, and the edge lies about half a texel short of the nearest texel across it + let far = 4. * size + 4.; + var signed_distance: f32; + if to_inside.z > 0.5 && dot(to_inside.xy, to_inside.xy) == 0. { + signed_distance = select(far, length(to_outside.xy) - 0.5, to_outside.z > 0.5); + } else { + signed_distance = select(-far, 0.5 - length(to_inside.xy), to_inside.z > 0.5); + } + + var progress: f32; + switch parameters.style { + case 0u: { + progress = signed_distance / size; + } + case 1u: { + progress = (signed_distance + size) / size; + } + case 2u: { + progress = (signed_distance + size / 2.) / size; + } + default: { + progress = abs(signed_distance) / (size / 2.); + } + } + let height = clamp(progress, 0., 1.); + return vec4(height * height * (3. - 2. * height)); +} diff --git a/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_shading.wgsl b/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_shading.wgsl new file mode 100644 index 0000000000..71498fe956 --- /dev/null +++ b/node-graph/libraries/raster-kernels/src/wgsl/effect_bevel_shading.wgsl @@ -0,0 +1,16 @@ +// How far the light brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short. +// `slope` scales the height's gradient into the surface's steepness, and is negative for a bevel pressed into the surface. +fn kernel(coord: vec2) -> vec4 { + let parameters = params(); + let gradient = vec2( + input_0_load(coord + vec2(1, 0)).a - input_0_load(coord - vec2(1, 0)).a, + input_0_load(coord + vec2(0, 1)).a - input_0_load(coord - vec2(0, 1)).a, + ) / 2.; + let light = vec3(parameters.light_x, parameters.light_y, parameters.light_z); + let shade = dot(normalize(vec3(-parameters.slope * gradient, 1.)), light); + + if parameters.shadow { + return vec4(clamp((light.z - shade) / max(light.z, 1e-4), 0., 1.)); + } + return vec4(clamp((shade - light.z) / max(1. - light.z, 1e-4), 0., 1.)); +} diff --git a/node-graph/libraries/rendering/src/renderer.rs b/node-graph/libraries/rendering/src/renderer.rs index 4195ef2692..0eed19ea59 100644 --- a/node-graph/libraries/rendering/src/renderer.rs +++ b/node-graph/libraries/rendering/src/renderer.rs @@ -31,7 +31,7 @@ use graphic_types::vector_types::vector::style::{RenderMode, StrokeAlign, Stroke use graphic_types::vector_types::vector::{ GeometryCache, Path, PlacedContours, contour_bezpaths, contours_bounding_box, contours_stroke_inclusive_bounding_box, edit_item_geometry, edit_list_row_geometry, no_paths, }; -use graphic_types::{Appearance, Artboard, Cover, Coverage, Effects, FillAndStroke, Graphic, Vector}; +use graphic_types::{Appearance, Artboard, BevelStyle, Cover, Coverage, Effects, FillAndStroke, Graphic, Vector}; use kurbo::{Affine, BezPath, Cap, Join, PathEl, Shape}; use num_traits::Zero; use skrifa::instance::{LocationRef, NormalizedCoord, Size}; @@ -110,14 +110,19 @@ impl<'a, T> ItemRef<'a, T> { .attribute::(ATTR_EFFECTS) .filter(|effects| !effects.is_empty() && render_params.render_mode != RenderMode::Outline); + let pixel_scale = render_params.viewport_zoom.unwrap_or(1.) * render_params.scale; + let pixel_scale = if pixel_scale.is_normal() && pixel_scale > 0. { pixel_scale } else { 1. }; + match effects { Some(effects) => ItemCompositing { opacity, effects: Some((effects, fill)), + pixel_scale, }, None => ItemCompositing { opacity: opacity * fill, effects: None, + pixel_scale, }, } } @@ -192,6 +197,8 @@ struct ItemCompositing<'a> { opacity: f32, /// With the fill opacity, which the effects group applies to the content alone so the shadows and glows cast from it stay at full strength. effects: Option<(&'a Effects, f32)>, + /// How many output pixels span a document unit, which SVG lighting measures the bevels' slopes across. + pixel_scale: f64, } impl ItemCompositing<'_> { @@ -226,7 +233,7 @@ impl ItemCompositing<'_> { // Effects change nothing visible about content without edges, like a color or gradient layer filling everything let RenderBoundingBox::Rectangle(bounds) = bounds() else { return None }; - let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform)?; + let id = write_svg_effects_filter(&mut render.svg_defs, effects, fill, bounds, render.transform, self.pixel_scale)?; Some(format!("url(#{id})")) } } @@ -343,6 +350,60 @@ impl SvgFilterPrimitives { ) } + /// A bevel's height in the alpha channel, shaped by the `style` over a slope `size` user units wide. + /// SVG measures no distances from edges, so the silhouette's edge is moved to the slope's middle and blurred across the slope's width instead. + fn bevel_height(&mut self, full_content: &str, size: f64, style: BevelStyle) -> String { + let ramp = |primitives: &mut Self, operator: Option<&str>, width: f64| { + let silhouette = match operator { + Some(operator) => primitives.push("feMorphology", &format!(r#"in="{full_content}" operator="{operator}" radius="{}""#, width / 2.), ""), + None => full_content.to_string(), + }; + primitives.push("feGaussianBlur", &format!(r#"in="{silhouette}" stdDeviation="{}""#, width / 4.), "") + }; + + match style { + BevelStyle::InnerBevel => ramp(self, Some("erode"), size), + BevelStyle::OuterBevel => ramp(self, Some("dilate"), size), + BevelStyle::Emboss => ramp(self, None, size), + // Ramps up into the content and away from it, each half the slope wide, meeting low at the edge + BevelStyle::PillowEmboss => { + let rising_inward = ramp(self, Some("erode"), size / 2.); + let falling_outward = ramp(self, Some("dilate"), size / 2.); + self.push( + "feComposite", + &format!(r#"in="{rising_inward}" in2="{falling_outward}" operator="arithmetic" k2="1" k3="-1" k4="1""#), + "", + ) + } + } + } + + /// How far the `light` brightens the bevel's surface past a flat surface's brightness, or if `shadow`, how far it falls short, as coverage in the alpha channel. + /// `slope` scales the height's gradient per output pixel into the surface's steepness, and is negative for a bevel pressed into the surface. + fn bevel_shading(&mut self, height: &str, slope: f64, light: glam::DVec3, shadow: bool) -> String { + let azimuth = light.y.atan2(light.x).to_degrees(); + let elevation = light.z.clamp(-1., 1.).asin().to_degrees(); + // SVG lighting's Sobel kernel measures twice the gradient + let surface_scale = slope / 2.; + let lit = self.push( + "feDiffuseLighting", + &format!(r#"in="{height}" surfaceScale="{surface_scale}" diffuseConstant="1" lighting-color="white""#), + &format!(r#""#), + ); + + // The lit brightness in red becomes coverage in alpha, past the flat brightness for a highlight or short of it for a shadow + let flat = light.z; + let (scale, offset) = match shadow { + true => (-1. / flat.max(1e-4), 1.), + false => (1. / (1. - flat).max(1e-4), -flat / (1. - flat).max(1e-4)), + }; + self.push( + "feColorMatrix", + &format!(r#"in="{lit}" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 {scale} 0 0 0 {offset}""#), + "", + ) + } + /// The coverage tinted `color`. fn tint(&mut self, coverage: &str, color: Color) -> String { let flood = self.push( @@ -384,9 +445,10 @@ 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::effects::outline_extents; - use graphic_types::{EffectOperation, GlowSource}; +/// `pixel_scale` is how many output pixels span a document unit. +fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, bounds: [DVec2; 2], user_to_document: DAffine2, pixel_scale: f64) -> Option { + use graphic_types::effects::{bevel_light, outline_extents}; + use graphic_types::{BevelDirection, EffectOperation, GlowSource}; let determinant = user_to_document.matrix2.determinant(); if !determinant.is_normal() { @@ -471,6 +533,35 @@ fn write_svg_effects_filter(svg_defs: &mut String, effects: &Effects, fill: f32, primitives.shade_within(&mut full, &mut filled, &coverage, color); } } + EffectOperation::BevelAndEmboss { + style, + depth, + direction, + size, + soften, + angle, + altitude, + highlight_color, + shadow_color, + } => { + let (size, soften) = (size * length_scale, soften * length_scale); + if size < 0.01 { + continue; + } + + let height = primitives.bevel_height(&full, size, style); + let slope = depth / 100. * size / length_scale * pixel_scale * if direction == BevelDirection::Down { -1. } else { 1. }; + let light = bevel_light(angle, altitude, document_to_user); + for (shadow, color) in [(false, highlight_color), (true, shadow_color)] { + let mut coverage = primitives.bevel_shading(&height, slope, light, shadow); + if soften >= 0.01 { + coverage = primitives.push("feGaussianBlur", &format!(r#"in="{coverage}" stdDeviation="{soften}""#), ""); + } + + beneath = Some(primitives.shade_beneath(beneath, &coverage, color)); + primitives.shade_within(&mut full, &mut filled, &coverage, color); + } + } } } @@ -4118,6 +4209,7 @@ mod tests { 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::from_scale(DVec2::splat(2.)), + 1., ) .unwrap(); @@ -4136,7 +4228,7 @@ mod tests { gamma: false, }; let mut defs = String::new(); - write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY).unwrap(); + write_svg_effects_filter(&mut defs, &Effects::from_operations([blur]), 0.5, [DVec2::ZERO, DVec2::ONE], DAffine2::IDENTITY, 1.).unwrap(); // The fill fades a copy of the content, which is blurred in linear light and passed through as the filter's last result assert!(defs.contains(r#""#), "{defs}"); @@ -4145,13 +4237,13 @@ mod tests { } #[test] - fn svg_effects_filters_carry_out_inner_glows_satins_and_outlines() { + fn svg_effects_filters_carry_out_inner_glows_satins_outlines_and_bevels() { use graphic_types::vector_types::vector::style::StrokeAlign; - use graphic_types::{EffectOperation, GlowSource}; + use graphic_types::{BevelDirection, 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(); + write_svg_effects_filter(&mut defs, &Effects::from_operations([operation]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 1.).unwrap(); defs }; let invert = r#""#; @@ -4186,5 +4278,22 @@ mod tests { }); 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}"); + + // An inner bevel's height ramps up inside the edge, lit once each for highlight and shadow, steepened by the pixel scale + let bevel = EffectOperation::BevelAndEmboss { + style: BevelStyle::InnerBevel, + depth: 100., + direction: BevelDirection::Up, + size: 4., + soften: 0., + angle: 120., + altitude: 30., + highlight_color: Color::WHITE, + shadow_color: Color::BLACK, + }; + let mut bevel_defs = String::new(); + write_svg_effects_filter(&mut bevel_defs, &Effects::from_operations([bevel]), 1., [DVec2::ZERO, DVec2::splat(10.)], DAffine2::IDENTITY, 2.).unwrap(); + assert!(bevel_defs.contains(r#"operator="erode" radius="2""#) && bevel_defs.contains(r#"stdDeviation="1""#), "{bevel_defs}"); + assert_eq!(bevel_defs.matches(r#"surfaceScale="4""#).count(), 2, "{bevel_defs}"); } } diff --git a/node-graph/libraries/wgpu-executor/src/raster_effects.rs b/node-graph/libraries/wgpu-executor/src/raster_effects.rs index 6b1a6c903d..97102b8f02 100644 --- a/node-graph/libraries/wgpu-executor/src/raster_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/raster_effects.rs @@ -7,8 +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::effects::outline_extents; -use graphic_types::{EffectOperation, Effects, GlowSource}; +use graphic_types::effects::{bevel_light, bevel_smoothing, outline_extents}; +use graphic_types::{BevelDirection, EffectOperation, Effects, GlowSource}; use raster_kernels::RasterKernel; use raster_kernels::blur::BlurSpace; use raster_kernels::effects::*; @@ -183,6 +183,54 @@ impl<'a> EffectsPass<'a> { self.shade_within(&coverage, color)?; } } + EffectOperation::BevelAndEmboss { + style, + depth, + direction, + size, + soften, + angle, + altitude, + highlight_color, + shadow_color, + } => { + let (size, soften) = (size * length_scale, soften * length_scale); + if size < NEGLIGIBLE_LENGTH { + return Ok(()); + } + + // The surface's height, rounded by a blur, lit from the light's direction into its highlights and shadows + let to_inside = self.nearest_across_edge(size, false)?; + let to_outside = self.nearest_across_edge(size, true)?; + let kernel = BevelHeight { + size: size as f32, + style: style as u32, + }; + let mut height = self.run(&kernel, &[&to_inside, &to_outside])?; + if bevel_smoothing(size) >= NEGLIGIBLE_LENGTH { + height = blur_raster(&height, bevel_smoothing(size), false, BlurSpace::Premultiplied, self.pipeline)?; + } + let slope = (depth / 100. * size * if direction == BevelDirection::Down { -1. } else { 1. }) as f32; + let light = bevel_light(angle, altitude, lengths_to_pixels).as_vec3(); + + // Their parts outside the content lie beneath it, and those inside are placed over it + for (shadow, color) in [(false, highlight_color), (true, shadow_color)] { + let kernel = BevelShading { + slope, + light_x: light.x, + light_y: light.y, + light_z: light.z, + shadow, + }; + let mut coverage = self.run(&kernel, &[&height])?; + if soften >= NEGLIGIBLE_LENGTH { + coverage = blur_raster(&coverage, soften, false, BlurSpace::Premultiplied, self.pipeline)?; + } + + self.accumulate(&coverage, color)?; + self.shade_within(&coverage, color)?; + } + } } Ok(()) 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 b219cf0681..ddc74068e1 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render/tests.rs @@ -378,11 +378,11 @@ fn shadows_and_glows_fall_where_they_should() { } #[test] -fn inner_glows_satins_and_outlines_fall_where_they_should() { +fn inner_glows_satins_outlines_and_bevels_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}; + use graphic_types::{BevelDirection, BevelStyle, EffectOperation, GlowSource}; let size = UVec2::new(128, 128); let black = GraphicColor::BLACK; @@ -428,6 +428,37 @@ fn inner_glows_satins_and_outlines_fall_where_they_should() { 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"); + + // Lit from the upper left, a raised bevel's top slope catches the highlight and its bottom slope falls into shadow, which swap when it sinks + let bevel = |style, direction| EffectOperation::BevelAndEmboss { + style, + depth: 100., + direction, + size: 5., + soften: 0., + angle: 120., + altitude: 30., + highlight_color: GraphicColor::RED, + shadow_color: GraphicColor::BLUE, + }; + let reddish = |[red, green, blue, alpha]: [u8; 4]| red > 200 && green < 128 && blue < 128 && alpha > 128; + let bluish = |[red, green, blue, alpha]: [u8; 4]| blue > 200 && red < 128 && green < 128 && alpha > 128; + let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Up)) else { return }; + assert!(reddish(pixel(&pixels, size, 55, 32)), "the top slope is highlighted: {:?}", pixel(&pixels, size, 55, 32)); + assert!(bluish(pixel(&pixels, size, 55, 77)), "the bottom slope is shaded: {:?}", pixel(&pixels, size, 55, 77)); + assert_eq!(pixel(&pixels, size, 55, 55), white, "the flat top inside the slopes is unlit"); + assert_eq!(pixel(&pixels, size, 55, 20)[3], clear, "nothing outside"); + let Some(pixels) = render_square(bevel(BevelStyle::InnerBevel, BevelDirection::Down)) else { + return; + }; + assert!(bluish(pixel(&pixels, size, 55, 32)), "a sunken top slope is shaded: {:?}", pixel(&pixels, size, 55, 32)); + assert!(reddish(pixel(&pixels, size, 55, 77)), "a sunken bottom slope is highlighted: {:?}", pixel(&pixels, size, 55, 77)); + + // An outer bevel's slopes lie outside the content, beneath it + let Some(pixels) = render_square(bevel(BevelStyle::OuterBevel, BevelDirection::Up)) else { return }; + assert!(reddish(pixel(&pixels, size, 55, 27)), "the top slope outside is highlighted: {:?}", pixel(&pixels, size, 55, 27)); + assert!(bluish(pixel(&pixels, size, 55, 82)), "the bottom slope outside is shaded: {:?}", pixel(&pixels, size, 55, 82)); + assert_eq!(pixel(&pixels, size, 55, 40), white, "the content inside is unlit"); } #[test] @@ -567,12 +598,23 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() { use glam::DVec2; use graphic_types::raster_types::{CPU, GPU, Image, Raster, Storage}; use graphic_types::vector_types::vector::style::StrokeAlign; - use graphic_types::{EffectOperation, Effects, GlowSource}; + use graphic_types::{BevelDirection, BevelStyle, EffectOperation, Effects, GlowSource}; let size = UVec2::new(160, 160); let (min, max) = (50, 100); let shadow_color = GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75); let blur = |radius, box_blur, gamma| EffectOperation::Blur { radius, box_blur, gamma }; + let bevel = |style, direction, size, soften| EffectOperation::BevelAndEmboss { + style, + depth: 150., + direction, + size, + soften, + angle: 120., + altitude: 30., + highlight_color: GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 0.75), + shadow_color, + }; let cases = [ vec![blur(3., false, false)], @@ -637,6 +679,10 @@ fn a_rasters_evaluated_effects_match_the_rendered_effects_group() { weight: 9., align: StrokeAlign::Center, }], + vec![bevel(BevelStyle::InnerBevel, BevelDirection::Up, 8., 0.)], + vec![bevel(BevelStyle::OuterBevel, BevelDirection::Down, 6., 2.)], + vec![bevel(BevelStyle::Emboss, BevelDirection::Up, 10., 0.)], + vec![bevel(BevelStyle::PillowEmboss, BevelDirection::Up, 12., 1.)], ]; 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 e214031d23..1dcea916f9 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, GlowSource, Graphic, Vector, stamp_coverage}; +pub use graphic_types::{Appearance, Artboard, BevelDirection, BevelStyle, 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 1ba7c767d9..fd6a945e40 100644 --- a/node-graph/nodes/raster/src/effects.rs +++ b/node-graph/nodes/raster/src/effects.rs @@ -5,7 +5,7 @@ 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, GlowSource, Graphic, Vector, stamp_effect}; +use graphic_types::{BevelDirection, BevelStyle, Effect, EffectOperation, GlowSource, Graphic, Vector, stamp_effect}; use vector_types::Gradient; use vector_types::vector::style::StrokeAlign; use wgpu_executor::WgpuPipelineCache; @@ -290,6 +290,74 @@ fn outline( ) } +/// Raises the input graphics into a lit relief, with highlights on the slopes facing the light and shadows on those facing away. +#[node_macro::node(name("Bevel & Emboss"), category("Raster: Effect"), icon("NodeBlur"))] +fn bevel_and_emboss( + _: impl Ctx, + /// The content to raise. + #[implementations(Raster, Graphic, Vector, Raster, Color, Gradient, String)] + content: Item, + /// Where the slope lies: inside the edge, outside it, across it, or across it with the edge pressed in. + style: Item, + /// How steep the slope is. + #[unit("%")] + #[range] + #[hard(0..)] + #[soft(..1000)] + #[default(100.)] + depth: Item, + /// Whether the slope rises out of the surface or sinks into it. + direction: Item, + /// How wide the slope is. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..250)] + #[default(5.)] + size: Item, + /// How much the shading is blurred. + #[unit(" px")] + #[range] + #[hard(0..)] + #[soft(..16)] + soften: Item, + /// The direction the light comes from. + #[unit("°")] + #[range] + #[soft(-180..180)] + #[default(120.)] + angle: Item, + /// How high above the surface the light is, from the horizon to straight overhead. + #[unit("°")] + #[range] + #[hard(0..90)] + #[default(30.)] + altitude: Item, + /// The highlight's color, with its opacity. + #[default("#ffffffbf")] + highlight_color: Item, + /// The shadow's color, with its opacity. + #[default("#000000bf")] + shadow_color: Item, + #[scope(raster_kernel_pipeline::IDENTIFIER)] pipeline: Item, +) -> Result, Interrupt> { + apply_effect( + content, + EffectOperation::BevelAndEmboss { + style: *style.element(), + depth: *depth.element(), + direction: *direction.element(), + size: *size.element(), + soften: *soften.element(), + angle: *angle.element(), + altitude: *altitude.element(), + highlight_color: *highlight_color.element(), + shadow_color: *shadow_color.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(