From 7e2e1fe02857fe36c19dd40190f7a75b8396a130 Mon Sep 17 00:00:00 2001 From: Keavon Chambers Date: Sat, 5 Dec 2026 01:18:10 -0800 Subject: [PATCH] Rename the 'Channels to Image' node to 'From Channels' and defer its compositing of any graphics --- .../nodes/src/raster_nodes/renames.rs | 3 + .../messages/portfolio/document_migration.rs | 3 +- node-graph/nodes/raster/src/channels.rs | 230 +++++++++++++++++- node-graph/nodes/raster/src/std_nodes.rs | 130 +--------- 4 files changed, 232 insertions(+), 134 deletions(-) diff --git a/document/migrations/nodes/src/raster_nodes/renames.rs b/document/migrations/nodes/src/raster_nodes/renames.rs index db3c87319e..1a1bf93454 100644 --- a/document/migrations/nodes/src/raster_nodes/renames.rs +++ b/document/migrations/nodes/src/raster_nodes/renames.rs @@ -7,3 +7,6 @@ rename!("raster_nodes::blending_nodes::MixColorsNode"@1 => @2); // 'Image to Channels' became 'Into Channels', taking and giving graphics, whose stored input and channel outputs keep their places rename!("raster_nodes::adjustments::ImageToChannelsNode"@1 => "raster_nodes::channels::IntoChannelsNode"@2); + +// 'Channels to Image' became 'From Channels', taking and giving graphics, whose stored inputs and output keep their places +rename!("raster_nodes::std_nodes::ChannelsToImageNode"@1 => "raster_nodes::channels::FromChannelsNode"@2); diff --git a/editor/src/messages/portfolio/document_migration.rs b/editor/src/messages/portfolio/document_migration.rs index f20260c3ff..8eb7a08e5e 100644 --- a/editor/src/messages/portfolio/document_migration.rs +++ b/editor/src/messages/portfolio/document_migration.rs @@ -549,8 +549,9 @@ const NODE_REPLACEMENTS: &[NodeReplacement<'static>] = &[ aliases: &["raster_nodes::adjustments::ImageToChannelsNode"], }, NodeReplacement { - node: graphene_std::raster_nodes::std_nodes::channels_to_image::IDENTIFIER, + node: graphene_std::raster_nodes::channels::from_channels::IDENTIFIER, aliases: &[ + "raster_nodes::std_nodes::ChannelsToImageNode", "raster_nodes::std_nodes::CombineChannelsNode", "graphene_raster_nodes::std_nodes::CombineChannelsNode", "graphene_std::raster::CombineChannelsNode", diff --git a/node-graph/nodes/raster/src/channels.rs b/node-graph/nodes/raster/src/channels.rs index dc27901f26..5af2ce80e8 100644 --- a/node-graph/nodes/raster/src/channels.rs +++ b/node-graph/nodes/raster/src/channels.rs @@ -1,8 +1,10 @@ -use core_types::ATTR_OPACITY_FILL; +use core_types::blending::BlendMode; use core_types::context::Ctx; -use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues}; +use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues, List}; +use core_types::{ATTR_BLEND_MODE, ATTR_CLIPPING_MASK, ATTR_OPACITY, ATTR_OPACITY_FILL}; +use glam::DAffine2; use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings}; -use graphic_types::{Effect, EffectOperation, Effects, Graphic, stamp_effect_on}; +use graphic_types::{Effect, EffectOperation, Effects, Graphic, MaskMode, linked_to_content, stamp_effect_on}; /// The red, green, blue, and alpha channels of a graphic, split into separate node outputs. #[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)] @@ -37,6 +39,114 @@ fn into_channels(_: impl Ctx, content: Item) -> Channels { } } +/// Combines graphics into the red, green, blue, and alpha channels of one graphic. Each color channel comes from the same channel of its input, and the alpha from the alpha input's red channel, so grayscale graphics like those from 'Into Channels' recombine exactly. +/// +/// The inputs line up where they lie in the document, and the result covers them all, transparent where none lies. Unconnected color channels are black, and an unconnected alpha leaves the result opaque. +#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), version(2))] +fn from_channels( + _: impl Ctx, + _primary: (), + /// The graphic whose red channel becomes the red channel. + #[expose] + red: Item, + /// The graphic whose green channel becomes the green channel. + #[expose] + green: Item, + /// The graphic whose blue channel becomes the blue channel. + #[expose] + blue: Item, + /// The graphic whose red channel becomes the alpha, from transparent where it's black to opaque where it's white. Past its edges, the result is transparent. + #[expose] + alpha: Item, +) -> Item { + // An unconnected channel arrives as a graphic drawing nothing, which counts as absent + let present = |channel: Item| (!channel.element().draws_nothing()).then_some(channel); + let [red, green, blue, alpha] = [red, green, blue, alpha].map(present); + + // Each input made opaque, keeping only its own color channel, or none for the alpha, which also masks the group by a gray of its red channel + let opaque = |channel: Item, keep: Adjustment| { + let mut channel = without_compositing(channel); + with_effects_holder(&mut channel, |attributes| { + stamp_adjustment(attributes, Adjustment::MakeOpaque { strength: 100. }); + stamp_adjustment(attributes, keep); + }); + channel + }; + let mask = alpha.clone().map(|alpha| opaque(alpha, channel_gray([100., 0., 0.]))); + let kept = [Some(0), Some(1), Some(2), None].map(kept_channel); + let channels = [red, green, blue, alpha].into_iter().zip(kept).filter_map(|(channel, keep)| Some(opaque(channel?, keep))); + + // Each channel adds onto those before it, holding none of their channels, so the group covers every input + let mut group = List::default(); + for (index, mut channel) in channels.enumerate() { + if index > 0 { + channel.set_attribute(ATTR_BLEND_MODE, BlendMode::LinearDodge); + } + group.push(channel); + } + if group.is_empty() { + return Item::default(); + } + let mut result = Item::new_from_element(Graphic::GraphicList(group)); + + // The alpha's gray shows the group by its luminance, which for a gray is its level, or else the group is made opaque. + // Either effect also renders the group apart from what lies beneath, so its channels add only onto each other. + let effect = match mask { + Some(mask) => EffectOperation::Mask { + mask: linked_to_content(Graphic::Graphic(Box::new(mask)), DAffine2::IDENTITY), + mode: MaskMode::Luminance, + density: 100., + feather: 0., + invert: false, + }, + None => EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }), + }; + stamp_effect_on(result.attributes_mut(), Effect::new(&effect)); + + result +} + +/// The graphic without the opacity, fill, blend mode, and clipping a channel takes no part in, on its envelope and the one item it may hold. +fn without_compositing(mut graphic: Item) -> Item { + let strip = |attributes: &mut ItemAttributeValues| { + attributes.remove::(ATTR_OPACITY); + attributes.remove::(ATTR_OPACITY_FILL); + attributes.remove::(ATTR_BLEND_MODE); + attributes.remove::(ATTR_CLIPPING_MASK); + }; + strip(graphic.attributes_mut()); + if let Some(attributes) = lone_item_attributes(graphic.element_mut()) { + strip(attributes); + } + graphic +} + +/// A Channel Mixer keeping only the red, green, or blue channel by its `index`, or none for black. +fn kept_channel(index: Option) -> Adjustment { + let row = |row_index: usize| { + let weight = |channel: usize| if index == Some(row_index) && channel == row_index { 100. } else { 0. }; + ChannelMixerRow { + red: weight(0), + green: weight(1), + blue: weight(2), + constant: 0., + } + }; + + Adjustment::ChannelMixer(Box::new(ChannelMixerSettings { + monochrome: false, + monochrome_mix: ChannelMixerRow { + red: 40., + green: 40., + blue: 20., + constant: 0., + }, + red: row(0), + green: row(1), + blue: row(2), + })) +} + /// Gives `edit` the attributes of the item a graphic's effects go on. /// That's the one item the graphic holds, which keeps the handling of its own kind (an image's adjustments reach even its fully transparent pixels) and stays an image for 'Flatten Raster' to take out, /// unless the graphic's own effects or fill, which act before effects appended to the graphic, would then act after them. @@ -89,7 +199,7 @@ mod tests { use super::*; use core_types::ATTR_TRANSFORM; use core_types::color::Color; - use glam::{DAffine2, DVec2, UVec2}; + use glam::{DVec2, UVec2}; use raster_types::{CPU, Image, Raster}; /// An image of `pixels` in one row, one pixel per document unit, embedded in a graphic as a wire of images embeds it. @@ -195,4 +305,116 @@ mod tests { assert_eq!(pixels[1], [0, 0, 0, 255]); assert_eq!(pixels[2][3], 0, "past the image"); } + + /// A square image of `size` pixels filled with one straight color, placed at `x` with one pixel per document unit, embedded in a graphic as a wire of images embeds it. + fn filled(size: u32, color: Color, x: f64) -> Item { + let placement = DAffine2::from_scale_angle_translation(DVec2::splat(size as f64), 0., DVec2::new(x, 0.)); + Item::new_from_element(Graphic::from( + Item::new_from_element(Raster::new_cpu(Image::new(size, size, color))).with_attribute(ATTR_TRANSFORM, placement), + )) + } + + #[test] + fn from_channels_groups_each_input_keeping_only_its_own_channel() { + use core_types::ATTR_OPACITY; + use graphic_types::EffectKind::{ChannelMixer, MakeOpaque, Mask}; + + let gray = |value: f32| filled(2, Color::from_rgbaf32_unchecked(value, value, value, 1.), 0.); + let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::>()); + let members = |graphic: &Item| match graphic.element() { + Graphic::GraphicList(group) => group.clone(), + element => panic!("expected a group, found {element:?}"), + }; + + // Each input in turn, made opaque with only its own channel, its opacity left out, and those after the first added on, all masked by the alpha + let mut red = gray(0.25); + red.set_attribute(ATTR_OPACITY, 0.5); + let result = from_channels((), (), red, gray(0.5), gray(0.75), gray(1.)); + let group = members(&result); + assert_eq!(group.len(), 4); + for (index, member) in (0..group.len()).filter_map(|index| group.clone_item(index)).enumerate() { + let blend_mode = member.attribute_cloned_or_default::(ATTR_BLEND_MODE); + assert_eq!(blend_mode, if index == 0 { BlendMode::Normal } else { BlendMode::LinearDodge }); + assert_eq!(member.attribute_cloned_or::(ATTR_OPACITY, 1.), 1.); + let Graphic::RasterCPU(raster) = member.element() else { panic!("expected an image") }; + assert_eq!(kinds(raster.attribute(ATTR_EFFECTS)), [MakeOpaque, ChannelMixer]); + } + assert_eq!(kinds(result.attribute(ATTR_EFFECTS)), [Mask]); + + // Without the alpha, the group is made opaque, and the alpha alone gives black it masks + let opaque = from_channels((), (), gray(0.25), Item::default(), Item::default(), Item::default()); + assert_eq!((members(&opaque).len(), kinds(opaque.attribute(ATTR_EFFECTS))), (1, vec![MakeOpaque])); + let alpha = from_channels((), (), Item::default(), Item::default(), Item::default(), gray(0.5)); + assert_eq!((members(&alpha).len(), kinds(alpha.attribute(ATTR_EFFECTS))), (1, vec![Mask])); + assert!(from_channels((), (), Item::default(), Item::default(), Item::default(), Item::default()).element().draws_nothing()); + } + + #[test] + fn into_channels_and_back_from_channels_reproduces_the_image_with_its_partial_alpha() { + // Colors across each channel, with every third pixel half transparent + let data = (0..64) + .map(|index| { + let (x, y) = ((index % 8) as f32, (index / 8) as f32); + let alpha = if index % 3 == 0 { 0.5 } else { 1. }; + Color::from_gamma_srgb_channels(x / 7., y / 7., (x + y) / 14., alpha) + }) + .collect(); + let raster = Item::new_from_element(Raster::new_cpu(Image { width: 8, height: 8, data })).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.))); + let image = Item::new_from_element(Graphic::from(raster)); + + let Channels { red, green, blue, alpha } = into_channels((), image.clone()); + let recombined = from_channels((), (), red, green, blue, alpha); + + let size = UVec2::splat(8); + let (Some(original), Some(recombined)) = (rendered(&image, size), rendered(&recombined, size)) else { + return; + }; + for (index, (original, recombined)) in original.iter().zip(&recombined).enumerate() { + let stray = original.iter().zip(recombined).map(|(original, recombined)| original.abs_diff(*recombined)).max().unwrap_or_default(); + assert!(stray <= 2, "pixel {index} renders as {recombined:?} rather than {original:?}"); + } + } + + #[test] + fn from_channels_lines_up_its_inputs_where_they_lie_in_the_document() { + // Red and green overlap by half, and a half gray alpha starts a pixel in from the red + let half_gray = Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.); + let result = from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 2.), Item::default(), filled(4, half_gray, 1.)); + + let size = UVec2::new(8, 4); + let Some(pixels) = rendered(&result, size) else { return }; + let at = |x: u32| pixels[(size.x + x) as usize]; + let half_shown = |[red, green, blue, alpha]: [u8; 4], expected: [u8; 3]| [red, green, blue] == expected && alpha.abs_diff(128) <= 1; + assert_eq!(at(0)[3], 0, "outside the alpha"); + assert!(half_shown(at(1), [255, 0, 0]), "red alone, half shown: {:?}", at(1)); + assert!(half_shown(at(3), [255, 255, 0]), "red and green: {:?}", at(3)); + assert_eq!(at(5)[3], 0, "outside the alpha"); + } + + /// Red over the left four of a 12 by 4 render and green over the right four, past the red's rectangle, without an alpha. + fn red_and_green_apart() -> Item { + from_channels((), (), filled(4, Color::WHITE, 0.), filled(4, Color::WHITE, 8.), Item::default(), Item::default()) + } + + #[test] + fn from_channels_covers_a_green_input_shifted_past_the_red() { + // Over a gray beneath, which the channels don't add onto + let beneath = filled(12, Color::from_gamma_srgb_channels(0.5, 0.5, 0.5, 1.), 0.); + let group: List = [beneath, red_and_green_apart()].into_iter().collect(); + + let size = UVec2::new(12, 4); + let Some(pixels) = rendered(&Item::new_from_element(Graphic::GraphicList(group)), size) else { + return; + }; + assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]); + assert_eq!(pixels[(size.x + 10) as usize], [0, 255, 0, 255]); + } + + #[test] + fn from_channels_leaves_what_no_input_covers_transparent() { + let size = UVec2::new(12, 4); + let Some(pixels) = rendered(&red_and_green_apart(), size) else { return }; + assert_eq!(pixels[(size.x + 1) as usize], [255, 0, 0, 255]); + assert_eq!(pixels[(size.x + 6) as usize][3], 0, "between the inputs"); + } } diff --git a/node-graph/nodes/raster/src/std_nodes.rs b/node-graph/nodes/raster/src/std_nodes.rs index fa824b9fc1..6ed45b86dd 100644 --- a/node-graph/nodes/raster/src/std_nodes.rs +++ b/node-graph/nodes/raster/src/std_nodes.rs @@ -1,17 +1,15 @@ use crate::adjustments::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType}; use core_types::ATTR_TRANSFORM; use core_types::color::Color; -use core_types::color::{AlphaMut, LinearChannel, Luminance, RGBMut}; use core_types::context::Ctx; use core_types::list::Item; use core_types::math::bbox::Bbox; use core_types::transform::Transform; use dyn_any::DynAny; -use glam::{DAffine2, DVec2, UVec2}; +use glam::{DAffine2, DVec2}; use graphene_resource::Resource; use graphic_types::generator::{Generator, MandelbrotSettings, NoiseSettings}; use raster_kernels::evaluate_raster_effects; -use raster_types::{Bitmap, BitmapMut}; use raster_types::{CPU, Raster}; use raster_types::{Image, ImageError}; use std::fmt::Debug; @@ -29,95 +27,6 @@ impl From for Error { } } -/// Two rasters that must line up pixel for pixel but differ in size. -#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)] -#[error("{first} and {second} must be the same size, but {first} is {}×{} pixels and {second} is {}×{}", .first_size.x, .first_size.y, .second_size.x, .second_size.y)] -pub struct SizeMismatchError { - pub first: &'static str, - pub first_size: UVec2, - pub second: &'static str, - pub second_size: UVec2, -} - -#[node_macro::node(category("Raster"), icon("NodeChannelsToImage"), name("Channels to Image"), memoize)] -fn channels_to_image( - _: impl Ctx, - _primary: (), - #[expose] red: Item>, - #[expose] green: Item>, - #[expose] blue: Item>, - #[expose] alpha: Item>, -) -> Result>, SizeMismatchError> { - // An unconnected channel arrives as the default zero-sized raster, which counts as absent - let present = |channel: Item>| (channel.element().width > 0 && channel.element().height > 0).then_some(channel); - let channels = [red, green, blue, alpha].map(present); - - // All present channels must share the same dimensions - let dimensions = |channel: &Item>| UVec2::new(channel.element().width, channel.element().height); - let mut present_channels = ["Red", "Green", "Blue", "Alpha"] - .into_iter() - .zip(&channels) - .filter_map(|(name, channel)| Some((name, channel.as_ref()?))); - let Some((first, first_channel)) = present_channels.next() else { - return Ok(Item::default()); - }; - let (first_size, transform) = (dimensions(first_channel), first_channel.attribute_cloned_or_default::(ATTR_TRANSFORM)); - if let Some((second, second_channel)) = present_channels.find(|(_, channel)| dimensions(channel) != first_size) { - return Err(SizeMismatchError { - first, - first_size, - second, - second_size: dimensions(second_channel), - }); - } - let (width, height) = (first_size.x, first_size.y); - - // A channel's effects grow it by the margin they cast past its edges, so every channel is placed within the widest margin - let channels = channels.map(|channel| channel.map(evaluate_raster_effects)); - let margin = |channel: &Item>| ((channel.element().width - width) / 2, (channel.element().height - height) / 2); - let (margin_x, margin_y) = channels - .iter() - .flatten() - .map(margin) - .fold((0, 0), |(x, y), (channel_x, channel_y)| (x.max(channel_x), y.max(channel_y))); - - // Take this item's blending attributes from the first present channel, whose effects are carried out by now - let Some(mut attributes) = channels.iter().flatten().next().map(|channel| channel.attributes().clone()) else { - return Ok(Item::default()); - }; - let size = DVec2::new(width as f64, height as f64); - let unit_margin = DVec2::new(margin_x as f64, margin_y as f64) / size; - attributes.insert( - ATTR_TRANSFORM, - transform * DAffine2::from_translation(-unit_margin) * DAffine2::from_scale(DVec2::ONE + 2. * unit_margin), - ); - - // A channel's value at a pixel of the output, with nothing past its own edges, or `None` if the channel is absent - let value = |channel: &Option>>, x: u32, y: u32| { - channel.as_ref().map(|channel| { - let (channel_margin_x, channel_margin_y) = margin(channel); - let (x, y) = ((x + channel_margin_x).checked_sub(margin_x), (y + channel_margin_y).checked_sub(margin_y)); - x.zip(y).and_then(|(x, y)| channel.element().get_pixel(x, y)).map_or(0., |pixel| pixel.l().cast_linear_channel()) - }) - }; - - // Set each output pixel's channels from the present inputs, defaulting absent color channels to 0 and absent alpha to 1 - let [red, green, blue, alpha] = &channels; - let mut image = Image::new(width + 2 * margin_x, height + 2 * margin_y, Color::TRANSPARENT); - for y in 0..image.height() { - for x in 0..image.width() { - let image_pixel = image.get_pixel_mut(x, y).unwrap(); - - image_pixel.set_red(value(red, x, y).unwrap_or(0.)); - image_pixel.set_green(value(green, x, y).unwrap_or(0.)); - image_pixel.set_blue(value(blue, x, y).unwrap_or(0.)); - image_pixel.set_alpha(value(alpha, x, y).unwrap_or(1.)); - } - } - - Ok(Item::from_parts(Raster::new_cpu(image), attributes)) -} - #[node_macro::node(category(""))] fn extend_image_to_bounds(_: impl Ctx, image: Item>, bounds: Item) -> Result>, (Item>, ImageError)> { let image = evaluate_raster_effects(image); @@ -318,40 +227,3 @@ fn mandelbrot( settings.stamp(&mut generator); generator } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn channels_stay_aligned_when_effects_grow_only_one() { - use graphic_types::{Effect, EffectOperation, Graphic, stamp_effect}; - - let gray = |value: f32| { - let image = Image::new(8, 8, Color::from_rgbaf32_unchecked(value, value, value, 1.)); - Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(8.))) - }; - - // Only the red channel is blurred, which grows it by the blur's margin - let mut red = gray(1.); - stamp_effect( - &mut red, - Effect::new(&EffectOperation::Blur { - radius_mask: Graphic::default(), - radius: 1., - box_blur: false, - gamma: false, - }), - ); - let image = channels_to_image((), (), red, gray(0.5), gray(0.25), gray(1.)).unwrap(); - - // The other channels are placed within the same margin, and the whole image keeps its place in the document - let raster = image.element(); - assert!(raster.width > 8 && raster.height > 8, "the image grows to hold the blur, rather than coming out empty"); - let transform: DAffine2 = image.attribute_cloned_or_default(ATTR_TRANSFORM); - let to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * transform.inverse(); - let center = to_pixels.transform_point2(DVec2::splat(4.)).as_uvec2(); - let pixel = raster.get_pixel(center.x, center.y).unwrap(); - assert!((pixel.g() - 0.5).abs() < 1e-6 && (pixel.b() - 0.25).abs() < 1e-6, "the unblurred channels line up: {pixel:?}"); - } -}