mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-05 19:12:08 -10:00
Rename the 'Image to Channels' node to 'Into Channels' and defer its channels on any graphic
This commit is contained in:
1 parent
c465a3ebea
commit
12daaf8ab0
16 files changed
+279
-48
No files matched your search
@@ -86,6 +86,8 @@ pub enum Adjustment {
|
||||
opacity: f64,
|
||||
},
|
||||
Solarize,
|
||||
/// Shows the alpha as a gray of the same gamma-encoded level, keeping the alpha, so a luminance mask of the gray shows as much as the alpha.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl Adjustment {
|
||||
@@ -112,6 +114,7 @@ impl Adjustment {
|
||||
Self::ColorLookup { .. } => EffectKind::ColorLookup,
|
||||
Self::ColorOverlay { .. } => EffectKind::PaintOverlay,
|
||||
Self::Solarize => EffectKind::Solarize,
|
||||
Self::AlphaToGray => EffectKind::AlphaToGray,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -151,7 +154,7 @@ impl Adjustment {
|
||||
visitor.parameter("inverse", inverse, false);
|
||||
}
|
||||
Self::MakeOpaque { strength } => visitor.parameter("strength", strength, 100.),
|
||||
Self::Invert | Self::Solarize => {}
|
||||
Self::Invert | Self::Solarize | Self::AlphaToGray => {}
|
||||
Self::BrightnessContrast {
|
||||
brightness,
|
||||
contrast,
|
||||
|
||||
@@ -15,7 +15,7 @@ use core_types::Color;
|
||||
use core_types::blending::BlendMode;
|
||||
use core_types::color::SRGBA8;
|
||||
use core_types::graphene_hash::CacheHash;
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, List};
|
||||
use core_types::list::{ATTR_EFFECTS, ATTR_OPACITY, ATTR_OPACITY_FILL, Item, ItemAttributeValues, List};
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use dyn_any::DynAny;
|
||||
use glam::{DAffine2, DMat2, DVec2, DVec3};
|
||||
@@ -117,6 +117,8 @@ pub enum EffectKind {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
/// Shows the content's alpha as a gray, as 'Into Channels' does for its alpha output.
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for EffectKind {
|
||||
@@ -175,6 +177,7 @@ impl std::fmt::Display for EffectKind {
|
||||
Self::PhotoFilter => "Photo Filter",
|
||||
Self::ColorLookup => "Color Lookup",
|
||||
Self::Solarize => "Solarize",
|
||||
Self::AlphaToGray => "Alpha to Gray",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -846,8 +849,14 @@ pub fn contour_gradient_position(distance: f32, start: f32, span: f32) -> f32 {
|
||||
/// Appends an effect to the item's list, after those already applied to it, recording the item's transform at that point.
|
||||
/// Like a stroke's transform, it sets the space the effect's lengths and angles are measured in, so transforms applied later carry and scale the effect.
|
||||
pub fn stamp_effect<T>(item: &mut Item<T>, effect: Effect) {
|
||||
let transform = stamped_transform(item.attribute_cloned_or_default(ATTR_TRANSFORM));
|
||||
item.attribute_mut_or_insert_default::<Effects>(ATTR_EFFECTS)
|
||||
stamp_effect_on(item.attributes_mut(), effect);
|
||||
}
|
||||
|
||||
/// Like [`stamp_effect`], given the item's attributes.
|
||||
pub fn stamp_effect_on(attributes: &mut ItemAttributeValues, effect: Effect) {
|
||||
let transform = stamped_transform(attributes.get::<DAffine2>(ATTR_TRANSFORM).copied().unwrap_or_default());
|
||||
attributes
|
||||
.get_or_insert_default_mut::<Effects>(ATTR_EFFECTS)
|
||||
.0
|
||||
.push(Item::new_from_element(effect).with_attribute(ATTR_TRANSFORM, transform));
|
||||
}
|
||||
@@ -1886,6 +1895,7 @@ impl EffectOperation {
|
||||
}),
|
||||
EffectKind::ColorLookup => Self::Adjustment(Adjustment::ColorLookup { lut_file: Default::default() }),
|
||||
EffectKind::Solarize => Self::Adjustment(Adjustment::Solarize),
|
||||
EffectKind::AlphaToGray => Self::Adjustment(Adjustment::AlphaToGray),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2899,6 +2909,7 @@ mod tests {
|
||||
PhotoFilter,
|
||||
ColorLookup,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
PaintOverlay,
|
||||
];
|
||||
for kind in kinds {
|
||||
|
||||
@@ -24,7 +24,7 @@ pub use artboard::Artboard;
|
||||
pub use blend_if::BlendIfChannel;
|
||||
pub use effects::{
|
||||
BevelDirection, BevelStyle, BevelTechnique, Effect, EffectKind, EffectOperation, Effects, GlowSource, GlowTechnique, MinimumMaximumMode, linked_to_content, paint_with_envelope_effects,
|
||||
stamp_effect, stamped_transform,
|
||||
stamp_effect, stamp_effect_on, stamped_transform,
|
||||
};
|
||||
pub use filters::NoiseDistribution;
|
||||
pub use generator::Generator;
|
||||
|
||||
@@ -30,11 +30,12 @@ pub enum StepKind {
|
||||
ColorLookup,
|
||||
ColorOverlay,
|
||||
Solarize,
|
||||
AlphaToGray,
|
||||
}
|
||||
|
||||
impl StepKind {
|
||||
/// Every kind, in the order of their codes.
|
||||
pub const ALL: [StepKind; 21] = [
|
||||
pub const ALL: [StepKind; 22] = [
|
||||
StepKind::Desaturate,
|
||||
StepKind::GammaCorrection,
|
||||
StepKind::MakeOpaque,
|
||||
@@ -56,6 +57,7 @@ impl StepKind {
|
||||
StepKind::ColorLookup,
|
||||
StepKind::ColorOverlay,
|
||||
StepKind::Solarize,
|
||||
StepKind::AlphaToGray,
|
||||
];
|
||||
|
||||
/// The number a step's header holds for its kind, which the shader picks the step's function by.
|
||||
@@ -269,6 +271,7 @@ mod tests {
|
||||
opacity: 50.,
|
||||
},
|
||||
Adjustment::Solarize,
|
||||
Adjustment::AlphaToGray,
|
||||
];
|
||||
let steps = AdjustmentSteps::encode(&run.iter().collect::<Vec<_>>());
|
||||
|
||||
|
||||
@@ -226,6 +226,7 @@ pub fn visit_kernel<V: AdjustmentVisitor>(adjustment: &Adjustment, visitor: V) -
|
||||
}
|
||||
Adjustment::Invert => visitor.visit(Invert),
|
||||
Adjustment::Solarize => visitor.visit(Solarize),
|
||||
Adjustment::AlphaToGray => visitor.visit(AlphaToGray),
|
||||
Adjustment::Threshold { min_luminance, max_luminance } => visitor.visit(Threshold {
|
||||
min_luminance: (min_luminance / 100.) as f32,
|
||||
max_luminance: (max_luminance / 100.) as f32,
|
||||
@@ -1121,6 +1122,20 @@ impl MapColor for Solarize {
|
||||
}
|
||||
}
|
||||
|
||||
/// Grays each color to the gamma-encoded level of its alpha, keeping the alpha.
|
||||
struct AlphaToGray;
|
||||
|
||||
impl MapColor for AlphaToGray {
|
||||
fn map_cpu(&self, color: Color) -> Color {
|
||||
let gray = srgb_to_linear(color.a());
|
||||
color.map_rgb(|_| gray)
|
||||
}
|
||||
|
||||
fn encode_step(&self, steps: &mut AdjustmentSteps) {
|
||||
steps.push(StepKind::AlphaToGray, []);
|
||||
}
|
||||
}
|
||||
|
||||
struct Threshold {
|
||||
min_luminance: f32,
|
||||
max_luminance: f32,
|
||||
|
||||
@@ -1755,7 +1755,7 @@ fn svg_expresses_adjustment(adjustment: &Adjustment) -> bool {
|
||||
use graphic_types::adjustment::DesaturateMethod;
|
||||
|
||||
match adjustment {
|
||||
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } => true,
|
||||
Adjustment::Threshold { .. } | Adjustment::GradientMap { .. } | Adjustment::ChannelMixer(_) | Adjustment::ColorOverlay { .. } | Adjustment::AlphaToGray => true,
|
||||
Adjustment::Desaturate { method } => matches!(
|
||||
method,
|
||||
DesaturateMethod::LuminanceRec709 | DesaturateMethod::ChannelsAverage | DesaturateMethod::LumaRec709 | DesaturateMethod::LumaRec601
|
||||
@@ -2095,6 +2095,10 @@ impl SvgFilterPrimitives {
|
||||
};
|
||||
self.push("feColorMatrix", &format!(r#"in="{image}" color-interpolation-filters="{space}" {}"#, matrix([weights; 3])), "")
|
||||
}
|
||||
Adjustment::AlphaToGray => {
|
||||
let values = "0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0";
|
||||
self.push("feColorMatrix", &format!(r#"{} type="matrix" values="{values}""#, in_gamma(image)), "")
|
||||
}
|
||||
// TODO: Express the other cross-channel adjustments, which no SVG primitive covers exactly
|
||||
_ => image.to_string(),
|
||||
}
|
||||
|
||||
@@ -109,6 +109,7 @@ fn step_function(kind: StepKind) -> (&'static str, Option<[Encoding; 2]>) {
|
||||
StepKind::ColorLookup => ("color_lookup", Some([Gamma, Gamma])),
|
||||
StepKind::ColorOverlay => ("color_overlay", Some([Gamma, Gamma])),
|
||||
StepKind::Solarize => ("solarize", Some([Gamma, Gamma])),
|
||||
StepKind::AlphaToGray => ("alpha_to_gray", Some([Gamma, Gamma])),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -365,6 +365,11 @@ fn solarize(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(min(color.rgb, 1. - color.rgb), color.a);
|
||||
}
|
||||
|
||||
// The alpha as a gray of the same gamma-encoded level, keeping the alpha
|
||||
fn alpha_to_gray(color: vec4<f32>, at: u32) -> vec4<f32> {
|
||||
return vec4<f32>(vec3<f32>(color.a), color.a);
|
||||
}
|
||||
|
||||
// Matches `apply_levels` with the gamma of 1 that every caller here passes, so its power is left out
|
||||
fn apply_levels(value: f32, input_shadows: f32, input_highlights: f32, output_minimum: f32, output_maximum: f32) -> f32 {
|
||||
let highlights_minus_shadows = clamp(input_highlights - input_shadows, F32_EPSILON, 1.);
|
||||
|
||||
@@ -5279,9 +5279,20 @@ fn gpu_color_adjustments_match_the_cpu_kernels() {
|
||||
("Photo Filter", photo_filter(warming, 25., true)),
|
||||
("Photo Filter at full density", photo_filter(cooling, 100., false)),
|
||||
("Photo Filter at full density preserving luminosity", photo_filter(cooling, 100., true)),
|
||||
("Alpha to Gray", Adjustment::AlphaToGray),
|
||||
];
|
||||
let mut runs: Vec<(String, Vec<Adjustment>)> = runs.into_iter().map(|(name, adjustment)| (name.to_string(), vec![adjustment])).collect();
|
||||
|
||||
// The opaque grays of one channel each that 'Into Channels' outputs
|
||||
let opaque = Adjustment::MakeOpaque { strength: 100. };
|
||||
let green_gray = Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(0., 100., 0., 0.),
|
||||
..Default::default()
|
||||
}));
|
||||
runs.push(("Green as an opaque gray".to_string(), vec![green_gray, opaque.clone()]));
|
||||
runs.push(("Alpha as an opaque gray".to_string(), vec![Adjustment::AlphaToGray, opaque]));
|
||||
|
||||
// Every blend mode, overlaying an opaque color and a translucent one, each with a luma apart from every test color's, which Darker Color and Lighter Color compare, and off Hard Mix's steep ramp over them
|
||||
for blend_mode in BlendMode::list().into_iter().flatten().chain(&[BlendMode::Erase, BlendMode::Restore, BlendMode::MultiplyAlpha]) {
|
||||
for (color, opacity) in [
|
||||
|
||||
@@ -53,5 +53,10 @@ tsify = { workspace = true, optional = true }
|
||||
wasm-bindgen = { workspace = true, optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
# Local dependencies
|
||||
rendering = { workspace = true }
|
||||
wgpu-executor = { workspace = true }
|
||||
|
||||
# Workspace dependencies
|
||||
tokio = { workspace = true }
|
||||
futures = { workspace = true }
|
||||
@@ -15,7 +15,7 @@ pub use graphic_types::adjustment::{DesaturateMethod, RelativeAbsolute};
|
||||
pub use graphic_types::generator::{CellularDistanceFunction, CellularReturnType, DomainWarpType, FractalType, MandelbrotExterior, MandelbrotFractal, MandelbrotInterior, NoiseType};
|
||||
use graphic_types::{Effect, EffectOperation, Generator, Graphic, Vector, stamp_effect};
|
||||
use raster_kernels::{evaluate_color_parameter, evaluate_gradient_effects};
|
||||
use raster_types::{CPU, GPU, Image, Raster};
|
||||
use raster_types::{CPU, GPU, Raster};
|
||||
use vector_types::Gradient;
|
||||
|
||||
/// Stamps the adjustment onto the item's effects, to be carried out wherever its content is rendered or read.
|
||||
@@ -50,42 +50,6 @@ fn gamma_correction<T>(
|
||||
)
|
||||
}
|
||||
|
||||
/// The red, green, blue, and alpha channels of an image, split into separate node outputs.
|
||||
#[derive(Debug, Clone, dyn_any::DynAny, node_macro::Destructure)]
|
||||
pub struct ImageChannels {
|
||||
/// The red channel of the image, as a grayscale image.
|
||||
pub red: Item<Raster<CPU>>,
|
||||
/// The green channel of the image, as a grayscale image.
|
||||
pub green: Item<Raster<CPU>>,
|
||||
/// The blue channel of the image, as a grayscale image.
|
||||
pub blue: Item<Raster<CPU>>,
|
||||
/// The alpha channel of the image, as a grayscale image.
|
||||
pub alpha: Item<Raster<CPU>>,
|
||||
}
|
||||
|
||||
/// Separates an image into its red, green, blue, and alpha channels, each provided as a grayscale image.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), name("Image to Channels"))]
|
||||
fn image_to_channels(_: impl Ctx, image: Item<Raster<CPU>>) -> ImageChannels {
|
||||
let (image, attributes) = raster_kernels::evaluate_raster_effects(image).into_parts();
|
||||
let (width, height) = (image.width, image.height);
|
||||
|
||||
// O(4 × pixels), since all four channels are written even when only some outputs are connected
|
||||
let mut channels: [Vec<Color>; 4] = core::array::from_fn(|_| Vec::with_capacity(image.data.len()));
|
||||
for color in &image.data {
|
||||
for (channel, value) in channels.iter_mut().zip([color.r(), color.g(), color.b(), color.a()]) {
|
||||
channel.push(Color::from_rgbaf32_unchecked(value, value, value, 1.));
|
||||
}
|
||||
}
|
||||
|
||||
// Each channel image keeps the source image's attributes, such as its transform
|
||||
let [red, green, blue, alpha] = channels.map(|data| {
|
||||
let channel_image = Image { width, height, data };
|
||||
Item::from_parts(Raster::new_cpu(channel_image), attributes.clone())
|
||||
});
|
||||
|
||||
ImageChannels { red, green, blue, alpha }
|
||||
}
|
||||
|
||||
#[node_macro::node(category("Raster: Adjustment"), icon("NodeMakeOpaque"), version(2))]
|
||||
fn make_opaque<T>(
|
||||
_: impl Ctx,
|
||||
@@ -1461,6 +1425,7 @@ mod _graphene_hash_impls {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use raster_kernels::evaluate_color_effects;
|
||||
use raster_types::Image;
|
||||
|
||||
/// Matched to within one 8-bit level.
|
||||
fn assert_close(actual: [f32; 3], expected: [f32; 3]) {
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
use core_types::ATTR_OPACITY_FILL;
|
||||
use core_types::context::Ctx;
|
||||
use core_types::list::{ATTR_EFFECTS, Item, ItemAttributeValues};
|
||||
use graphic_types::adjustment::{Adjustment, ChannelMixerRow, ChannelMixerSettings};
|
||||
use graphic_types::{Effect, EffectOperation, Effects, Graphic, 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)]
|
||||
pub struct Channels {
|
||||
/// The red channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub red: Item<Graphic>,
|
||||
/// The green channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub green: Item<Graphic>,
|
||||
/// The blue channel of the graphic as a grayscale graphic, keeping the graphic's transparency.
|
||||
pub blue: Item<Graphic>,
|
||||
/// The alpha channel of the graphic as an opaque grayscale graphic, from black where the graphic is transparent to white where it's opaque.
|
||||
pub alpha: Item<Graphic>,
|
||||
}
|
||||
|
||||
/// Separates the input graphic into its red, green, blue, and alpha channels, each as a grayscale graphic.
|
||||
///
|
||||
/// The color channels keep the graphic's transparency, while the alpha channel is opaque, so it masks by its luminance as the alpha did.
|
||||
#[node_macro::node(category("Raster"), icon("NodeImageToChannels"), version(2))]
|
||||
fn into_channels(_: impl Ctx, content: Item<Graphic>) -> Channels {
|
||||
// Each output is the content with adjustments graying it by one channel, carried out wherever it's rendered or read
|
||||
let channel = |grays: &[Adjustment]| {
|
||||
let mut channel = content.clone();
|
||||
with_effects_holder(&mut channel, |attributes| grays.iter().for_each(|gray| stamp_adjustment(attributes, gray.clone())));
|
||||
channel
|
||||
};
|
||||
|
||||
Channels {
|
||||
red: channel(&[channel_gray([100., 0., 0.])]),
|
||||
green: channel(&[channel_gray([0., 100., 0.])]),
|
||||
blue: channel(&[channel_gray([0., 0., 100.])]),
|
||||
alpha: channel(&[Adjustment::AlphaToGray, Adjustment::MakeOpaque { strength: 100. }]),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
fn with_effects_holder<R>(graphic: &mut Item<Graphic>, edit: impl FnOnce(&mut ItemAttributeValues) -> R) -> R {
|
||||
let envelope_has_effects = graphic.attribute::<Effects>(ATTR_EFFECTS).is_some_and(|effects| !effects.is_empty());
|
||||
let envelope_acts_first = envelope_has_effects || graphic.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) != 1.;
|
||||
|
||||
if !envelope_acts_first && let Some(attributes) = lone_item_attributes(graphic.element_mut()) {
|
||||
return edit(attributes);
|
||||
}
|
||||
edit(graphic.attributes_mut())
|
||||
}
|
||||
|
||||
/// The attributes of the one item a graphic holds, or `None` if it holds a list.
|
||||
fn lone_item_attributes(graphic: &mut Graphic) -> Option<&mut ItemAttributeValues> {
|
||||
Some(match graphic {
|
||||
Graphic::Graphic(item) => item.attributes_mut(),
|
||||
Graphic::Vector(item) => item.attributes_mut(),
|
||||
Graphic::RasterCPU(item) => item.attributes_mut(),
|
||||
Graphic::RasterGPU(item) => item.attributes_mut(),
|
||||
Graphic::Color(item) => item.attributes_mut(),
|
||||
Graphic::Gradient(item) => item.attributes_mut(),
|
||||
Graphic::Generator(item) => item.attributes_mut(),
|
||||
Graphic::Text(item) => item.attributes_mut(),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Stamps the adjustment onto the effects in these attributes.
|
||||
fn stamp_adjustment(attributes: &mut ItemAttributeValues, adjustment: Adjustment) {
|
||||
stamp_effect_on(attributes, Effect::new(&EffectOperation::Adjustment(adjustment)));
|
||||
}
|
||||
|
||||
/// A monochrome Channel Mixer graying each color by its red, green, and blue channels weighted by the `weights` in percent.
|
||||
fn channel_gray(weights: [f64; 3]) -> Adjustment {
|
||||
let row = |[red, green, blue]: [f64; 3]| ChannelMixerRow { red, green, blue, constant: 0. };
|
||||
|
||||
// The rows a monochrome mixer ignores keep the node's defaults, so they stamp nothing
|
||||
Adjustment::ChannelMixer(Box::new(ChannelMixerSettings {
|
||||
monochrome: true,
|
||||
monochrome_mix: row(weights),
|
||||
red: row([100., 0., 0.]),
|
||||
green: row([0., 100., 0.]),
|
||||
blue: row([0., 0., 100.]),
|
||||
}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::color::Color;
|
||||
use glam::{DAffine2, 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.
|
||||
fn image(pixels: &[Color]) -> Item<Graphic> {
|
||||
let image = Image {
|
||||
width: pixels.len() as u32,
|
||||
height: 1,
|
||||
data: pixels.to_vec(),
|
||||
};
|
||||
let raster = Item::new_from_element(Raster::new_cpu(image)).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::new(pixels.len() as f64, 1.)));
|
||||
Item::new_from_element(Graphic::from(raster))
|
||||
}
|
||||
|
||||
/// The image a graphic holds alone.
|
||||
fn lone_image(graphic: &Item<Graphic>) -> &Item<Raster<CPU>> {
|
||||
let Graphic::RasterCPU(raster) = graphic.element() else { panic!("expected a lone image") };
|
||||
raster
|
||||
}
|
||||
|
||||
/// The graphic's rendered pixels as straight-alpha RGBA8, one pixel per document unit from its origin across a `size` view, or `None` without a GPU.
|
||||
fn rendered(graphic: &Item<Graphic>, size: UVec2) -> Option<Vec<[u8; 4]>> {
|
||||
use rendering::{Render, RenderParams};
|
||||
|
||||
let executor = futures::executor::block_on(wgpu_executor::WgpuExecutor::new())?;
|
||||
let list = core_types::list::List::new_from_item(graphic.clone());
|
||||
let draw = &mut |scene: &mut rendering::vello_scene_builder::VelloSceneBuilder| list.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
|
||||
let texture = executor.render_vello(size, DAffine2::IDENTITY, draw).expect("the graphic should render");
|
||||
let pixels = executor.read_texture_pixels(&texture).expect("the render should read back");
|
||||
Some(pixels.as_chunks::<4>().0.to_vec())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_grays_each_color_keeping_its_alpha_and_makes_the_alpha_opaque() {
|
||||
use raster_kernels::adjustments::adjust_color;
|
||||
|
||||
// A translucent pixel and a fully transparent one, whose hidden color its channels still gray
|
||||
let pixels = [Color::from_rgbaf32_unchecked(0.75, 0.1, 0.3, 0.6), Color::from_rgbaf32_unchecked(0.25, 0.5, 1., 0.)];
|
||||
let Channels { red, green, blue, alpha } = into_channels((), image(&pixels));
|
||||
|
||||
// Each output is the image itself, still an image, with adjustments graying each pixel to one channel's gamma-encoded level, or the alpha's
|
||||
for (channel, output) in [red, green, blue, alpha].into_iter().enumerate() {
|
||||
assert_eq!(output.attributes().iter_any().count(), 0, "the envelope stays empty");
|
||||
let raster = lone_image(&output);
|
||||
assert_eq!(raster.element().data, pixels, "the pixels are left alone");
|
||||
let effects = raster.attribute::<Effects>(ATTR_EFFECTS).cloned().unwrap_or_default();
|
||||
|
||||
for pixel in pixels {
|
||||
let gray = effects.operations().fold(pixel, |color, operation| match operation {
|
||||
EffectOperation::Adjustment(adjustment) => adjust_color(&adjustment, color),
|
||||
operation => panic!("{operation:?} isn't an adjustment"),
|
||||
});
|
||||
|
||||
// The colors keep the pixel's alpha, and the alpha is opaque
|
||||
let (level, kept_alpha) = match channel {
|
||||
3 => (pixel.a(), 1.),
|
||||
_ => (pixel.to_gamma_srgb_channels()[channel], pixel.a()),
|
||||
};
|
||||
let [r, g, b, a] = gray.to_gamma_srgb_channels();
|
||||
assert!(
|
||||
[r, g, b].iter().all(|gray| (gray - level).abs() < 1e-5) && (a - kept_alpha).abs() < 1e-6,
|
||||
"channel {channel} of {pixel:?} grays to {gray:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_color_outputs_keep_the_sources_transparency() {
|
||||
// Half transparent white, then fully transparent red, then opaque white
|
||||
let Channels { red, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::from_rgbaf32_unchecked(1., 0., 0., 0.), Color::WHITE]));
|
||||
|
||||
let Some(pixels) = rendered(&red, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3] == [255; 3] && pixels[0][3].abs_diff(128) <= 1, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1][3], 0, "the transparent pixel stays transparent");
|
||||
assert_eq!(pixels[2], [255; 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_adjusts_a_graphic_by_its_envelope_where_its_fill_acts_first() {
|
||||
use graphic_types::EffectKind::{AlphaToGray, MakeOpaque};
|
||||
|
||||
let kinds = |effects: Option<&Effects>| effects.map_or(Vec::new(), |effects| effects.effects().map(|effect| effect.kind()).collect::<Vec<_>>());
|
||||
|
||||
// A placement alone leaves the image within to take the effects, so a placement left at its default acts as no placement
|
||||
let placed = image(&[Color::WHITE]).with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::new(3., 0.)));
|
||||
let Channels { alpha, .. } = into_channels((), placed);
|
||||
assert_eq!(kinds(lone_image(&alpha).attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
|
||||
// The envelope's fill fades the image before the effects appended to the graphic, so they go on the envelope
|
||||
let faded = image(&[Color::WHITE]).with_attribute(ATTR_OPACITY_FILL, 0.5);
|
||||
let Channels { alpha, .. } = into_channels((), faded);
|
||||
assert_eq!(kinds(alpha.attribute(ATTR_EFFECTS)), [AlphaToGray, MakeOpaque]);
|
||||
assert!(lone_image(&alpha).attribute::<Effects>(ATTR_EFFECTS).is_none(), "the image within is left alone");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn into_channels_renders_an_images_alpha_opaque_across_its_rectangle() {
|
||||
// A half transparent pixel, which shows middle gray, then a fully transparent one, which shows black rather than nothing
|
||||
let Channels { alpha, .. } = into_channels((), image(&[Color::WHITE.with_alpha(0.5), Color::TRANSPARENT]));
|
||||
|
||||
let Some(pixels) = rendered(&alpha, UVec2::new(3, 1)) else { return };
|
||||
assert!(pixels[0][..3].iter().all(|level| level.abs_diff(128) <= 1) && pixels[0][3] == 255, "{:?}", pixels[0]);
|
||||
assert_eq!(pixels[1], [0, 0, 0, 255]);
|
||||
assert_eq!(pixels[2][3], 0, "past the image");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod adjustments;
|
||||
pub mod blending_nodes;
|
||||
pub mod channels;
|
||||
pub use raster_kernels::color_lookup_table;
|
||||
pub mod dehaze;
|
||||
pub mod filter;
|
||||
|
||||
Reference in new issue
Block a user