Add a strength percentage to the 'Make Opaque' node (#5058)

This commit is contained in:
Keavon Chambers authored and GitHub committed 2026-12-02 00:03:39 -08:00
1 parent 19df13ad1d
commit bb2514d816
13 files changed
+188 -28

No files matched your search

@@ -0,0 +1,43 @@
use migration_core::{Inputs, literal, migration};
use serde::{Deserialize, Serialize};
/// Frozen mirror of the `TaggedValue` variant this migration writes.
#[derive(Serialize, Deserialize)]
enum Tagged {
Number(f64),
}
/// 'Make Opaque' gained a Strength percentage, set to 100% to keep making the content fully opaque.
#[migration("raster_nodes::adjustments::MakeOpaqueNode"@1 => @2)]
pub fn make_opaque_v1(inputs: &mut Inputs) {
inputs.push(literal(Tagged::Number(100.)));
}
#[cfg(test)]
mod tests {
use super::*;
use migration_core::decl;
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
fn contract() -> SourceContract {
SourceContract::new(1, |random, _slot| literal(random.below(10) as f64))
}
#[test]
fn rewrites_history() {
check_commutation(&MakeOpaqueV1, &contract());
check_undo(&MakeOpaqueV1, &contract());
}
#[test]
fn keeps_the_content_and_adds_full_strength() {
let content = literal(1.);
let mut fixture = Fixture::new(&MakeOpaqueV1);
let make_opaque = fixture.add(decl!("raster_nodes::adjustments::MakeOpaqueNode"@1), vec![content.clone()]);
let migrated = fixture.migrate(&MakeOpaqueV1).unwrap();
assert_eq!(fixture.declaration_of(&migrated, make_opaque), Some(decl!("raster_nodes::adjustments::MakeOpaqueNode"@2)));
assert_eq!(fixture.inputs(&migrated, make_opaque), [content, literal(Tagged::Number(100.))]);
}
}
@@ -1,5 +1,6 @@
//! Migrations of the nodes in `raster_nodes`.
mod make_opaque_v1;
mod mandelbrot_v1;
mod mandelbrot_v2;
mod mix_colors_from_mix_node;
@@ -3045,6 +3045,18 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
inputs_count = 3;
}
// Make Opaque gained a Strength input, set to 100% to keep making the content fully opaque
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster_nodes::adjustments::make_opaque::IDENTIFIER) && inputs_count == 1 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, 0), old_inputs[0].clone(), network_path);
document
.network_interface
.set_input(&InputConnector::node_at_index(*node_id, 1), NodeInput::value(TaggedValue::Number(100.), false), network_path);
inputs_count = 2;
}
// The removed "Brightness/Contrast Classic" node had no Use Classic input, so its three inputs become the unified node with the toggle on
if reference == DefinitionIdentifier::ProtoNode(graphene_std::raster::brightness_contrast::IDENTIFIER) && inputs_count == 3 {
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
@@ -5915,6 +5927,33 @@ mod tests {
}
}
#[test]
fn make_opaques_from_before_their_strength_open_fully_opaque() {
use crate::messages::portfolio::document_storage_io::load_legacy_document;
use graph_craft::application_io::resource::HashMapResourceStorage;
use graphene_std::raster_nodes::adjustments::make_opaque;
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(make_opaque::IDENTIFIER)).expect("the Make Opaque definition should exist");
let mut inputs = definition.default_node_template().inputs;
inputs.truncate(1);
let content = inputs.clone();
// Saved with its content alone, before its strength
let mut document = DocumentMessageHandler::default();
let node_template = NodeTemplate {
implementation: NodeTemplateImplementation::ProtoNode(make_opaque::IDENTIFIER),
inputs,
..Default::default()
};
document.network_interface.insert_node(NodeId(1), node_template, &[]);
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
let node = opened.network_interface.document_node(&NodeId(1), &[]).expect("the node should still exist");
assert_eq!(node.inputs[..1], content, "Make Opaque should keep its content");
assert_eq!(node.inputs[1..], [NodeInput::value(TaggedValue::Number(100.), false)], "Make Opaque should open at full strength");
}
// Serialize, Sample Image, and Empty Image nodes open as As String, Passthrough, and Image nodes, keeping their wires and Serialize's stored text
#[test]
fn removed_nodes_open_as_their_stand_ins() {
@@ -23,7 +23,10 @@ pub enum Adjustment {
gamma: f64,
inverse: bool,
},
MakeOpaque,
MakeOpaque {
/// Percent.
strength: f64,
},
BrightnessContrast {
/// Percent.
brightness: f64,
@@ -90,7 +93,7 @@ impl Adjustment {
match self {
Self::Desaturate { .. } => EffectKind::Desaturate,
Self::GammaCorrection { .. } => EffectKind::GammaCorrection,
Self::MakeOpaque => EffectKind::MakeOpaque,
Self::MakeOpaque { .. } => EffectKind::MakeOpaque,
Self::BrightnessContrast { .. } => EffectKind::BrightnessContrast,
Self::Levels(_) => EffectKind::Levels,
Self::Curves(_) => EffectKind::Curves,
@@ -117,7 +120,7 @@ impl Adjustment {
matches!(
self,
Self::GammaCorrection { .. }
| Self::MakeOpaque
| Self::MakeOpaque { .. }
| Self::BrightnessContrast { .. }
| Self::Levels(_)
| Self::Curves(_)
@@ -137,7 +140,8 @@ impl Adjustment {
visitor.parameter("gamma", gamma, 2.2);
visitor.parameter("inverse", inverse, false);
}
Self::MakeOpaque | Self::Invert | Self::Solarize => {}
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
Self::Invert | Self::Solarize => {}
Self::BrightnessContrast {
brightness,
contrast,
@@ -636,6 +636,13 @@ mod tests {
let layers = EffectLayers::plan(&effects, BlendMode::Normal, 0.5, true);
assert_eq!(layers.flattened, 0);
assert_eq!(parts(&layers), [[Some((0, 0, PiecePlace::Beneath)), None, Some((2, 0, PiecePlace::Within))]]);
// Making the content opaque at no strength leaves the multiplying shadow before it blending with what lies beneath, which any strength flattens
let make_opaque = |strength| Effects::from_operations([drop_shadow(RED, BlendMode::Multiply), EffectOperation::Adjustment(Adjustment::MakeOpaque { strength })]);
let layers = EffectLayers::plan(&make_opaque(0.), BlendMode::Normal, 1., true);
assert_eq!(layers.flattened, 0);
assert_eq!(modes(&layers), [BlendMode::Multiply, BlendMode::Normal]);
assert_eq!(EffectLayers::plan(&make_opaque(1.), BlendMode::Normal, 1., true).flattened, 2);
}
fn mask() -> EffectOperation {
@@ -1224,6 +1224,7 @@ impl EffectOperation {
DisplaceMode::XAndY => *offset == DVec2::ZERO,
},
Self::Adjustment(Adjustment::ColorOverlay { color, opacity, .. }) => color.a() <= 0. || *opacity <= 0.,
Self::Adjustment(Adjustment::MakeOpaque { strength }) => *strength <= 0.,
Self::Mask { density, .. } => *density <= 0.,
Self::Feather { distance } => *distance <= 0.,
Self::ConvolutionKernel { .. } => self.convolution().is_none(),
@@ -1636,7 +1637,7 @@ impl EffectOperation {
},
EffectKind::Desaturate => Self::Adjustment(Adjustment::Desaturate { method: Default::default() }),
EffectKind::GammaCorrection => Self::Adjustment(Adjustment::GammaCorrection { gamma: 0., inverse: false }),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque),
EffectKind::MakeOpaque => Self::Adjustment(Adjustment::MakeOpaque { strength: 0. }),
EffectKind::BrightnessContrast => Self::Adjustment(Adjustment::BrightnessContrast {
brightness: 0.,
contrast: 0.,
@@ -221,7 +221,7 @@ mod tests {
let run = [
Adjustment::Desaturate { method: Default::default() },
Adjustment::GammaCorrection { gamma: 2.2, inverse: false },
Adjustment::MakeOpaque,
Adjustment::MakeOpaque { strength: 100. },
Adjustment::BrightnessContrast {
brightness: 10.,
contrast: 10.,
@@ -131,7 +131,9 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
let exponent = if *inverse { 1. / gamma } else { gamma };
visitor.visit(GammaCorrection { exponent: exponent as f32 })
}
Adjustment::MakeOpaque => visitor.visit(MakeOpaque),
Adjustment::MakeOpaque { strength } => visitor.visit(MakeOpaque {
strength: (strength / 100.).clamp(0., 1.) as f32,
}),
Adjustment::BrightnessContrast {
brightness,
contrast,
@@ -438,15 +440,23 @@ impl MapColor for GammaCorrection {
}
}
struct MakeOpaque;
struct MakeOpaque {
strength: f32,
}
impl MapColor for MakeOpaque {
fn map_cpu(&self, color: Color) -> Color {
color.with_alpha(1.)
// At full strength, even an alpha that isn't finite becomes opaque
if self.strength >= 1. {
return color.with_alpha(1.);
}
// Alpha moves toward 1 by the strength, in a form exact at both ends, keeping the straight color
color.with_alpha(color.a() * (1. - self.strength) + self.strength)
}
fn encode_step(&self, steps: &mut AdjustmentSteps) {
steps.push(StepKind::MakeOpaque, []);
steps.push(StepKind::MakeOpaque, [texel(&[self.strength])]);
}
}
@@ -1978,4 +1988,23 @@ mod tests {
assert_eq!((mapped(&ramp, 0), mapped(&ramp, 255)), (0., 1.), "{spread:?}");
}
}
#[test]
fn making_opaque_lifts_alpha_by_its_strength_keeping_the_straight_color() {
let make_opaque = |strength| Adjustment::MakeOpaque { strength };
// Even a fully transparent pixel's hidden color shows, as the strength lifts its alpha
for color in [COLORS[1], Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, 0.), Color::from_rgbaf32_unchecked(0.3, 0.6, 0.1, 0.1)] {
assert_eq!(adjust_color(&make_opaque(0.), color), color);
assert_eq!(adjust_color(&make_opaque(100.), color), color.with_alpha(1.));
let half = adjust_color(&make_opaque(50.), color);
assert_eq!(half.with_alpha(color.a()), color);
assert!((half.a() - (color.a() + 1.) / 2.).abs() < 1e-6, "{half:?}");
}
for alpha in [f32::NAN, f32::INFINITY] {
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
}
}
}
@@ -1949,7 +1949,8 @@ mod tests {
blue: identity,
alpha: LevelsRecord { output_minimums: 50., ..identity },
}));
for adjustment in [Adjustment::MakeOpaque, raised_alpha] {
let make_opaque = Adjustment::MakeOpaque { strength: 100. };
for adjustment in [make_opaque.clone(), raised_alpha] {
let [empty, translucent, colored_without_alpha] = adjusted(std::slice::from_ref(&adjustment));
assert_eq!((empty, colored_without_alpha), ([0.; 4], [0.; 4]), "{adjustment:?}");
assert!(translucent[3] > 0.5, "{adjustment:?}");
@@ -1960,7 +1961,7 @@ mod tests {
alpha: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.)]),
..Default::default()
}));
assert_eq!(adjusted(&[emptied, Adjustment::MakeOpaque]), [[0.; 4]; 3]);
assert_eq!(adjusted(&[emptied, make_opaque]), [[0.; 4]; 3]);
}
#[test]
@@ -6839,9 +6839,14 @@ mod tests {
assert!(invert.contains(r#"<feComponentTransfer in="SourceGraphic" color-interpolation-filters="sRGB""#), "{invert}");
assert!(invert.contains(r#"<feFuncR type="table" tableValues="1.0000 0.9961"#), "{invert}");
// Making the content opaque leaves the empty space around it empty
let make_opaque = filter(Adjustment::MakeOpaque);
assert!(make_opaque.contains(r#"<feFuncA type="table" tableValues="0.0000 1.0000"#), "{make_opaque}");
// Making the content opaque leaves the empty space around it empty, a partial strength lifts alpha partway, and none is left out for changing nothing
let make_opaque = |strength| filter(Adjustment::MakeOpaque { strength });
let full = make_opaque(100.);
assert!(full.contains(r#"<feFuncA type="table" tableValues="0.0000 1.0000"#), "{full}");
let half = make_opaque(50.);
assert!(half.contains(r#"<feFuncA type="table" tableValues="0.0000 0.5020 0.5039"#), "{half}");
let none = make_opaque(0.);
assert!(!none.contains("feComponentTransfer"), "{none}");
// A luma in linear light is a matrix there
let desaturate = filter(Adjustment::Desaturate {
@@ -6866,7 +6871,7 @@ mod tests {
// A hidden color under full transparency, which only the CPU's straight colors keep for Make Opaque to reveal
let hidden = Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, 0.);
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(2, 2, hidden)));
stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque)));
stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })));
stamp_effect(&mut item, Effect::new(&EffectOperation::Adjustment(Adjustment::Invert)));
let mut scene = VelloSceneBuilder::new(16, 16, kurbo::Affine::IDENTITY, 4096);
@@ -345,8 +345,15 @@ fn gamma_correction(color: vec4<f32>, at: u32) -> vec4<f32> {
return vec4<f32>(rust_powf(color.r, inverse), rust_powf(color.g, inverse), rust_powf(color.b, inverse), color.a);
}
// The strength (x) that alpha moves toward 1 by, keeping the straight color
fn make_opaque(color: vec4<f32>, at: u32) -> vec4<f32> {
return vec4<f32>(color.rgb, 1.);
let strength = step_texel(at).x;
// At full strength, even an alpha that isn't finite becomes opaque
if strength >= 1. {
return vec4<f32>(color.rgb, 1.);
}
return vec4<f32>(color.rgb, color.a * (1. - strength) + strength);
}
fn invert(color: vec4<f32>, at: u32) -> vec4<f32> {
@@ -2604,6 +2604,7 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
blend_mode: BlendMode::Normal,
opacity: 100.,
};
let make_opaque = |strength| EffectOperation::Adjustment(Adjustment::MakeOpaque { strength });
let mask_cases = [
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false)],
vec![mask(&mask_image, MaskMode::Alpha, 70., 3., true)],
@@ -2648,6 +2649,16 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
vec![painted(&checker), masked_radius_blur(&mask_image, 8., true, false)],
// Boxes of each pixel's own fractional width across hard edges, in gamma
vec![painted(&checks), masked_radius_blur(&resampled, 15.5, true, true)],
// Masked content's translucent alpha lifted toward opaque by each strength, with the empty space around it left empty
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(0.)],
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(50.)],
vec![mask(&mask_image, MaskMode::Luminance, 100., 0., false), make_opaque(100.)],
// No strength still carries out the adjustments after it
vec![
mask(&mask_image, MaskMode::Luminance, 100., 0., false),
make_opaque(0.),
EffectOperation::Adjustment(Adjustment::Invert),
],
];
// Content in a color of its own, so every mode has colors to blend
@@ -3172,7 +3183,8 @@ fn gpu_tone_adjustments_match_the_cpu_kernels() {
),
("Invert", Adjustment::Invert),
("Solarize", Adjustment::Solarize),
("Make Opaque", Adjustment::MakeOpaque),
("Make Opaque", Adjustment::MakeOpaque { strength: 100. }),
("Make Opaque at half strength", Adjustment::MakeOpaque { strength: 50. }),
];
assert_gpu_adjustments_match_the_cpu_kernels(runs.into_iter().map(|(name, adjustment)| (name, vec![adjustment])).collect());
}
@@ -3847,7 +3859,7 @@ fn gpu_runs_of_several_adjustments_match_the_cpu_kernels() {
("Exposure, Vibrance, Invert, then Posterize", vec![exposure.clone(), vibrance.clone(), Adjustment::Invert, posterize]),
(
"Levels fading alpha, Make Opaque, Channel Mixer, then Threshold",
vec![levels.clone(), Adjustment::MakeOpaque, channel_mixer.clone(), threshold],
vec![levels.clone(), Adjustment::MakeOpaque { strength: 100. }, channel_mixer.clone(), threshold],
),
("Vibrance, an unreadable Color Lookup, then Curves", vec![vibrance.clone(), unreadable_lookup.clone(), curves.clone()]),
("an unreadable Color Lookup alone", vec![unreadable_lookup]),
@@ -3860,12 +3872,12 @@ fn gpu_runs_of_several_adjustments_match_the_cpu_kernels() {
("Color Balance, then a Color Burn of black", vec![color_balance, color_burn]),
(
"Curves emptying faint pixels, then Make Opaque",
vec![emptying_curves.clone(), Adjustment::MakeOpaque, Adjustment::Invert],
vec![emptying_curves.clone(), Adjustment::MakeOpaque { strength: 100. }, Adjustment::Invert],
),
// The pass emptying a pixel ends before the Color Lookup's own pass, and the one after it with Make Opaque still leaves the pixel empty
(
"Curves emptying faint pixels, then a Color Lookup and Make Opaque",
vec![emptying_curves, identity_lookup, Adjustment::MakeOpaque],
vec![emptying_curves, identity_lookup, Adjustment::MakeOpaque { strength: 100. }],
),
];
assert_gpu_adjustments_stray_at_most(0.3, runs, &[1., 0.5]);
@@ -3920,7 +3932,7 @@ fn passes_of_a_split_run_hand_on_their_results_unrounded() {
// An alpha too faint for a half float to hold, which Make Opaque then lifts
let faint = levels(identity, record(0., 100., 2e-6));
let lifted = vec![faint, split, Adjustment::MakeOpaque];
let lifted = vec![faint, split, Adjustment::MakeOpaque { strength: 100. }];
// Grays a 4096th apart, hundreds of which land within the stretch
let grays: Vec<core_types::Color> = (0..=4096)
@@ -4214,10 +4226,12 @@ fn adjustments_leave_the_empty_space_around_content_empty() {
alpha: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.)]),
..Default::default()
}));
let make_opaque = |strength| Adjustment::MakeOpaque { strength };
let cases = [
("Make Opaque", vec![Adjustment::MakeOpaque], 255),
("Make Opaque", vec![make_opaque(100.)], 255),
("Make Opaque at half strength", vec![make_opaque(50.)], 255),
("Levels with a raised alpha output", vec![raised_alpha], 255),
("Curves emptying alpha, then Make Opaque", vec![emptied, Adjustment::MakeOpaque], 0),
("Curves emptying alpha, then Make Opaque", vec![emptied, make_opaque(100.)], 0),
];
for (name, run, alpha_within) in cases {
+13 -4
View File
@@ -86,9 +86,18 @@ fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
ImageChannels { red, green, blue, alpha }
}
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"))]
fn make_opaque<T>(_: impl Ctx, #[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>) -> Item<T> {
adjust(input, Adjustment::MakeOpaque)
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
fn make_opaque<T>(
_: impl Ctx,
#[implementations(Raster<CPU>, Color, Gradient, Graphic, Vector, Raster<GPU>, String, Generator)] input: Item<T>,
/// How far translucent parts move toward full opacity, keeping their colors, from unchanged at 0% to fully opaque at 100%.
#[unit("%")]
#[range]
#[hard(0..100)]
#[default(100.)]
strength: Item<f64>,
) -> Item<T> {
adjust(input, Adjustment::MakeOpaque { strength: strength.into_element() })
}
// Aims for interoperable compatibility with:
@@ -2185,7 +2194,7 @@ mod tests {
gamma: false,
}),
);
let result = evaluate_raster_effects(super::make_opaque((), item));
let result = evaluate_raster_effects(super::make_opaque((), item, Item::new_from_element(100.)));
// Just outside the square, the blur's faint white becomes opaque white, where making it opaque first would have blurred in black
let transform: DAffine2 = result.attribute_cloned_or_default(ATTR_TRANSFORM);