Compare commits

..
10 changed files with 1032 additions and 114 deletions

No files matched your search

@@ -115,6 +115,16 @@ impl Adjustment {
}
}
/// Whether the adjustment might change a color's alpha, which only Make Opaque and the alpha records of Levels and Curves do.
pub fn may_change_alpha(&self) -> bool {
match self {
Self::MakeOpaque { .. } => true,
Self::Levels(settings) => !settings.alpha.is_identity(),
Self::Curves(settings) => settings.alpha != TransferCurve::default(),
_ => false,
}
}
/// Whether each channel of the result depends only on the same channel of the color, making the adjustment four curves.
pub fn is_per_channel(&self) -> bool {
matches!(
@@ -486,6 +496,20 @@ fn grouped_key(group: &str, parameter: &str) -> String {
}
impl LevelsRecord {
/// The record leaving every value as it is, as its node's defaults do.
pub const IDENTITY: Self = Self {
shadows: 0.,
midtones: 1.,
highlights: 100.,
output_minimums: 0.,
output_maximums: 100.,
};
/// Whether the record leaves every value as it is.
pub fn is_identity(&self) -> bool {
*self == Self::IDENTITY
}
fn visit_parameters(&mut self, visitor: &mut impl ParameterVisitor, group: &str) {
visitor.parameter(&grouped_key(group, "shadows"), &mut self.shadows, 0.);
visitor.parameter(&grouped_key(group, "midtones"), &mut self.midtones, 1.);
@@ -454,6 +454,17 @@ impl Effects {
self.operations().all(|operation| operation.changes_nothing())
}
/// Whether the effects might change the content's alpha, as any but an adjustment keeping it (see [`Adjustment::may_change_alpha`]) can unless it changes nothing.
pub fn may_change_alpha(&self) -> bool {
self.operations().any(|operation| {
!operation.changes_nothing()
&& match &operation {
EffectOperation::Adjustment(adjustment) => adjustment.may_change_alpha(),
_ => true,
}
})
}
/// The effects of the given range of rows decoded into operations, in order.
pub fn operations_in(&self, rows: Range<usize>) -> impl Iterator<Item = EffectOperation> + '_ {
self.effects().skip(rows.start).take(rows.len()).map(Effect::operation)
@@ -1,6 +1,6 @@
//! The definitions the filter effects share across renderers: each pixel filter as weighted copies of the content shifted by document lengths, which the CPU, GPU, and SVG each carry out.
use crate::effects::{EffectOperation, Effects};
use crate::effects::EffectOperation;
use core_types::graphene_hash::CacheHash;
use dyn_any::DynAny;
use glam::{DAffine2, DMat2, DVec2, IVec2, UVec2};
@@ -181,12 +181,6 @@ pub fn is_random_field_filter(operation: &EffectOperation) -> bool {
matches!(operation, EffectOperation::Speckle { .. } | EffectOperation::Dissolve { .. })
}
/// Whether any of the effects is a pixel filter reading the pixels around each one that changes something, which reads endless content over the area in view.
/// The random field filters change endless content without its neighbors (see [`is_random_field_filter`]).
pub fn has_filters(effects: &Effects) -> bool {
effects.operations().any(|operation| reads_neighbors(&operation) && !operation.changes_nothing())
}
/// For PSD interop, the shifts Find Edges reads its Sobel gradient from, in document pixels, with their weights across and down.
pub const SOBEL_TAPS: [(DVec2, [f64; 2]); 8] = [
(DVec2::new(-1., -1.), [-1., -1.]),
+129 -35
View File
@@ -630,16 +630,17 @@ impl Graphic {
}
}
pub fn can_reduce_to_clip_path(&self) -> bool {
/// Whether this graphic clips as its outline would, with `inherited_appearance` cascading from an ancestor to vectors lacking their own.
pub fn can_reduce_to_clip_path(&self, inherited_appearance: Option<&Appearance>) -> bool {
// Effects (like a mask, which shapes a clip) are more than an outline can express
match self {
Graphic::Vector(item) => {
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing)
&& vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), item.attribute::<Appearance>(ATTR_APPEARANCE))
let appearance = Appearance::cascade(item.attribute(ATTR_APPEARANCE), inherited_appearance);
item.attribute::<Effects>(ATTR_EFFECTS).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(item.attribute_cloned_or(ATTR_OPACITY, 1.), appearance)
}
Graphic::VectorList(list) => (0..list.len()).all(|index| {
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing)
&& vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), list.attribute::<Appearance>(ATTR_APPEARANCE, index))
let appearance = Appearance::cascade(list.attribute(ATTR_APPEARANCE, index), inherited_appearance);
list.attribute::<Effects>(ATTR_EFFECTS, index).is_none_or(Effects::change_nothing) && vector_can_reduce_to_clip_path(list.attribute_cloned_or(ATTR_OPACITY, index, 1.), appearance)
}),
_ => false,
}
@@ -648,16 +649,22 @@ impl Graphic {
pub fn is_guaranteed_fully_opaque(&self) -> bool {
match self {
Graphic::None(_) | Graphic::NoneList(_) => false,
// The group's own opacity scales whatever it wraps, so full alpha there is a precondition
Graphic::Graphic(item) => item_opacity_is_full(item) && item.element().is_guaranteed_fully_opaque(),
Graphic::GraphicList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque),
Graphic::Vector(item) => vector_is_guaranteed_fully_opaque(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
),
// The group's own opacity and effects act on whatever it wraps, so they must keep it at full alpha
Graphic::Graphic(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_opaque(),
Graphic::GraphicList(list) => {
!list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_opaque)
}
Graphic::Vector(item) => {
!item_effects_may_change_alpha(item)
&& vector_is_guaranteed_fully_opaque(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
)
}
Graphic::VectorList(list) => {
!list.is_empty()
&& !list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
vector_is_guaranteed_fully_opaque(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
@@ -669,11 +676,12 @@ impl Graphic {
Graphic::RasterCPU(_) | Graphic::RasterCPUList(_) => false,
Graphic::RasterGPU(_) | Graphic::RasterGPUList(_) => false,
Graphic::Generator(_) | Graphic::GeneratorList(_) => false,
Graphic::Color(item) => item_opacity_is_full(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && list.iter_element_values().all(|color| color.is_opaque()),
Graphic::Color(item) => item_opacity_is_full(item) && !item_effects_may_change_alpha(item) && item.element().is_opaque(),
Graphic::ColorList(list) => !list.is_empty() && every_item_has_full_opacity(list) && !list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.is_opaque()),
// A `Clear` spread cuts off to transparency past the ends, and curved contours may leave gaps, leaving the rest of the region unpainted
Graphic::Gradient(item) => {
item_opacity_is_full(item)
&& !item_effects_may_change_alpha(item)
&& item.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| item.attributes().get_any(key))
&& item.element().iter().all(|stop| stop.color.is_opaque())
@@ -681,6 +689,7 @@ impl Graphic {
Graphic::GradientList(list) => {
!list.is_empty()
&& every_item_has_full_opacity(list)
&& !list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
list.attribute_cloned_or_default::<GradientSpread>(ATTR_GRADIENT_SPREAD, index) != GradientSpread::Clear
&& gradient_paints_everywhere(&|key| list.attribute_any(key, index))
@@ -693,27 +702,41 @@ impl Graphic {
}
pub fn is_guaranteed_fully_transparent(&self) -> bool {
// An effect that might change alpha, like Make Opaque or a shadow, can show content its paints leave transparent, so only its opacity can hide it
match self {
Graphic::None(_) | Graphic::NoneList(_) => true,
Graphic::Graphic(item) => item_opacity_is_zero(item) || item.element().is_guaranteed_fully_transparent(),
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent),
Graphic::Vector(item) => vector_is_guaranteed_fully_transparent(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
),
Graphic::VectorList(list) => (0..list.len()).all(|index| {
vector_is_guaranteed_fully_transparent(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
)
}),
Graphic::Color(item) => item_opacity_is_zero(item) || item.element().a() == 0.,
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|color| color.a() == 0.),
Graphic::Graphic(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().is_guaranteed_fully_transparent()),
Graphic::GraphicList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(Graphic::is_guaranteed_fully_transparent)),
Graphic::Vector(item) => {
item_opacity_is_zero(item)
|| (!item_effects_may_change_alpha(item)
&& vector_is_guaranteed_fully_transparent(
item.attribute_cloned_or(ATTR_OPACITY, 1.),
item.attribute_cloned_or(ATTR_OPACITY_FILL, 1.),
item.attribute::<Appearance>(ATTR_APPEARANCE),
item.attribute::<Effects>(ATTR_EFFECTS),
))
}
Graphic::VectorList(list) => {
every_item_has_zero_opacity(list)
|| (!list_effects_may_change_alpha(list)
&& (0..list.len()).all(|index| {
vector_is_guaranteed_fully_transparent(
list.attribute_cloned_or(ATTR_OPACITY, index, 1.),
list.attribute_cloned_or(ATTR_OPACITY_FILL, index, 1.),
list.attribute::<Appearance>(ATTR_APPEARANCE, index),
list.attribute::<Effects>(ATTR_EFFECTS, index),
)
}))
}
Graphic::Color(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && item.element().a() == 0.),
Graphic::ColorList(list) => every_item_has_zero_opacity(list) || (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|color| color.a() == 0.)),
// A stopless ramp paints as solid black, matching `Gradient::evaluate`, so it counts as transparent only once it has stops
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
Graphic::GradientList(list) => every_item_has_zero_opacity(list) || list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)),
Graphic::Gradient(item) => item_opacity_is_zero(item) || (!item_effects_may_change_alpha(item) && !item.element().is_empty() && item.element().iter().all(|stop| stop.color.a() == 0.)),
Graphic::GradientList(list) => {
every_item_has_zero_opacity(list)
|| (!list_effects_may_change_alpha(list) && list.iter_element_values().all(|stops| !stops.is_empty() && stops.iter().all(|stop| stop.color.a() == 0.)))
}
// Their content is never inspected, so zeroed opacity is the only invisibility these can report
Graphic::RasterCPU(item) => item_opacity_is_zero(item),
Graphic::RasterGPU(item) => item_opacity_is_zero(item),
@@ -806,12 +829,13 @@ fn vector_is_guaranteed_fully_opaque(opacity: f64, opacity_fill: f64, appearance
}
/// Whether a vector object draws nothing visible, either through its opacity or through its paint.
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>) -> bool {
fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appearance: Option<&Appearance>, effects: Option<&Effects>) -> bool {
if opacity <= f64::EPSILON {
return true;
}
let fills_invisible = opacity_fill <= f64::EPSILON
// Fill opacity fades the paints but not what effects paint at full strength, like overlays and shadows
let fills_invisible = (opacity_fill <= f64::EPSILON && effects.is_none_or(Effects::change_nothing))
|| appearance.is_none_or(|appearance| {
appearance
.covers_with_paints()
@@ -829,6 +853,16 @@ fn vector_is_guaranteed_fully_transparent(opacity: f64, opacity_fill: f64, appea
fills_invisible && strokes_invisible
}
/// Whether a lone item's effects might change its alpha, so its element's own alpha can't vouch for it being opaque or transparent.
fn item_effects_may_change_alpha<T>(item: &Item<T>) -> bool {
item.attribute::<Effects>(ATTR_EFFECTS).is_some_and(Effects::may_change_alpha)
}
/// Whether the effects of any item of a list might change its alpha (see [`item_effects_may_change_alpha`]).
fn list_effects_may_change_alpha<T>(list: &List<T>) -> bool {
(0..list.len()).any(|index| list.attribute::<Effects>(ATTR_EFFECTS, index).is_some_and(Effects::may_change_alpha))
}
/// Whether a lone item's opacity zeroes it out, independent of what its element holds.
fn item_opacity_is_zero<T>(item: &Item<T>) -> bool {
item.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) <= f64::EPSILON
@@ -1308,4 +1342,64 @@ mod graphic_is_opaque_tests {
let reduced = item.with_attribute(ATTR_OPACITY, 0.5);
assert!(!Graphic::Graphic(Box::new(reduced)).is_guaranteed_fully_opaque());
}
#[test]
fn effects_that_might_change_alpha_leave_content_neither_known_opaque_nor_known_transparent() {
use crate::adjustment::{Adjustment, LevelsRecord, LevelsSettings};
use crate::effects::EffectOperation;
use crate::vector_types::vector::style::Stroke;
let effected = |graphic: Graphic, operation: EffectOperation| Item::new_from_element(graphic).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]));
let colors = |alpha: f64, operation: EffectOperation| {
let color = Color::from_rgbaf32(1., 0., 0., alpha as f32).unwrap();
Graphic::ColorList(List::new_from_item(Item::new_from_element(color).with_attribute(ATTR_EFFECTS, Effects::from_operations([operation]))))
};
let make_opaque = || EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
let dissolve = || EffectOperation::Dissolve { opacity: 50., seed: 0 };
let levels = |record: LevelsRecord, alpha: LevelsRecord| {
EffectOperation::Adjustment(Adjustment::Levels(Box::new(LevelsSettings {
composite: record,
red: LevelsRecord::IDENTITY,
green: LevelsRecord::IDENTITY,
blue: LevelsRecord::IDENTITY,
alpha,
})))
};
let identity = LevelsRecord::IDENTITY;
let darkened = LevelsRecord { output_maximums: 50., ..identity };
// Adjustments keeping alpha leave paints as opaque or transparent as their colors
assert!(colors(1., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_opaque());
assert!(colors(0., EffectOperation::Adjustment(Adjustment::Invert)).is_guaranteed_fully_transparent());
assert!(colors(1., levels(darkened, identity)).is_guaranteed_fully_opaque());
// Effects that might fade a paint, or show a transparent one, leave it unknown
assert!(!colors(1., dissolve()).is_guaranteed_fully_opaque());
assert!(!colors(1., levels(identity, darkened)).is_guaranteed_fully_opaque());
assert!(!colors(0., make_opaque()).is_guaranteed_fully_transparent());
assert!(!colors(0., make_opaque()).is_guaranteed_to_cover_opaquely());
// A group's own effects act on all it wraps, though its zero opacity still hides it
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(1.), dissolve()))).is_guaranteed_fully_opaque());
assert!(!Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()))).is_guaranteed_fully_transparent());
assert!(Graphic::Graphic(Box::new(effected(color_graphic(0.), make_opaque()).with_attribute(ATTR_OPACITY, 0.))).is_guaranteed_fully_transparent());
// A vector's own effects, like a shadow cast by a shape with no visible paint, do too
let mut shape = Item::new_from_element(Vector::default());
shape.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_stroke(&Stroke::new(4.)), color_graphic(0.)));
assert!(Graphic::Vector(Box::new(shape.clone())).is_guaranteed_fully_transparent());
let shadowed = shape
.clone()
.with_attribute(ATTR_EFFECTS, Effects::from_operations([EffectOperation::default_for(crate::effects::EffectKind::DropShadow)]));
assert!(!Graphic::Vector(Box::new(shadowed)).is_guaranteed_fully_transparent());
// Zero fill opacity hides a vector's paints but not an overlay its effects paint over them, though that keeps alpha
let mut filled = Item::new_from_element(Vector::default()).with_attribute(ATTR_OPACITY_FILL, 0.);
filled.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), color_graphic(1.)));
assert!(Graphic::Vector(Box::new(filled.clone())).is_guaranteed_fully_transparent());
let overlay = EffectOperation::default_for(crate::effects::EffectKind::PaintOverlay);
assert!(matches!(overlay, EffectOperation::Adjustment(Adjustment::ColorOverlay { .. })), "{overlay:?}");
let overlaid = filled.with_attribute(ATTR_EFFECTS, Effects::from_operations([overlay]));
assert!(!Graphic::Vector(Box::new(overlaid)).is_guaranteed_fully_transparent());
}
}
@@ -2007,4 +2007,69 @@ mod tests {
assert_eq!(adjust_color(&make_opaque(100.), Color::from_rgbaf32_unchecked(0.8, 0.4, 0.2, alpha)).a(), 1.);
}
}
#[test]
fn adjustments_changing_alpha_are_known_to_without_running_their_kernels() {
use core_types::transfer_curve::TransferCurve;
use glam::DVec2;
use graphic_types::effects::{EffectKind, EffectOperation};
let kinds = [
EffectKind::Desaturate,
EffectKind::GammaCorrection,
EffectKind::MakeOpaque,
EffectKind::BrightnessContrast,
EffectKind::Levels,
EffectKind::Curves,
EffectKind::BlackAndWhite,
EffectKind::HueSaturation,
EffectKind::Invert,
EffectKind::Threshold,
EffectKind::GradientMap,
EffectKind::Vibrance,
EffectKind::ChannelMixer,
EffectKind::SelectiveColor,
EffectKind::Posterize,
EffectKind::Exposure,
EffectKind::ColorBalance,
EffectKind::PhotoFilter,
EffectKind::ColorLookup,
EffectKind::Solarize,
];
let defaults = kinds.map(|kind| match EffectOperation::default_for(kind) {
EffectOperation::Adjustment(adjustment) => adjustment,
operation => panic!("{kind} isn't an adjustment: {operation:?}"),
});
// Levels and Curves change alpha by their alpha records and curves, and nothing else of theirs
let identity = settings::LevelsRecord::IDENTITY;
let darkened = settings::LevelsRecord { output_maximums: 50., ..identity };
let levels = |composite, alpha| {
Adjustment::Levels(Box::new(settings::LevelsSettings {
composite,
red: identity,
green: identity,
blue: identity,
alpha,
}))
};
let curve = TransferCurve::new(vec![DVec2::ZERO, DVec2::new(1., 0.5)]);
let curves = |composite: TransferCurve, alpha: TransferCurve| {
Adjustment::Curves(Box::new(settings::CurvesSettings {
composite,
alpha,
..Default::default()
}))
};
let settings = [
levels(darkened, identity),
levels(identity, darkened),
curves(curve.clone(), TransferCurve::default()),
curves(TransferCurve::default(), curve),
];
for adjustment in defaults.iter().chain(&settings) {
assert_eq!(adjustment.may_change_alpha(), !preserves_alpha(adjustment), "{adjustment:?}");
}
}
}
@@ -258,9 +258,24 @@ pub fn adjusted_gradient_with_blend_ifs(
Some((resampled, resampled_settings))
}
/// Whether [`color_after_effects`] and [`gradient_after_effects`] carry out every one of the effects, since each changes every color on its own:
/// an adjustment, a Blend If reading only the value's own colors, or an effect that changes nothing.
pub fn carries_out_every_effect(effects: &Effects) -> bool {
effects.operations().all(|operation| match operation {
EffectOperation::Adjustment(_) => true,
EffectOperation::BlendIf(ranges) => ranges.underlying.show_everything(),
_ => operation.changes_nothing(),
})
}
/// The color with the adjustments among the effects carried out on it, faded by each Blend If where it reads the color, for the paints and nodes that read the value.
pub fn color_after_effects(color: Color, effects: &Effects) -> Color {
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), 1.)
filled_color_after_effects(color, effects, 1.)
}
/// Like [`color_after_effects`], carried out over the color faded by a `fill`, which leaves the paint overlays among them at full strength, as the renderers fade content.
pub fn filled_color_after_effects(color: Color, effects: &Effects, fill: f32) -> Color {
filled_color_with_blend_ifs(color, &adjustments(effects), &content_blend_ifs(effects), fill)
}
/// Carries out the effects on any number of colors as [`color_after_effects`] does on one, with each adjustment's kernel prepared once.
@@ -270,7 +285,12 @@ pub fn prepared_color_after_effects(effects: &Effects) -> Box<dyn Fn(Color) -> C
/// The gradient with the effects carried out along its ramp as [`color_after_effects`] carries them out on a color, with the settings to read the result with, or `None` with nothing to carry out.
pub fn gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects) -> Option<(Gradient, GradientSettings)> {
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), 1.)
filled_gradient_after_effects(gradient, settings, effects, 1.)
}
/// Like [`gradient_after_effects`], carried out along the ramp faded by a `fill` as [`filled_color_after_effects`] carries them out on a color.
pub fn filled_gradient_after_effects(gradient: &Gradient, settings: GradientSettings, effects: &Effects, fill: f32) -> Option<(Gradient, GradientSettings)> {
adjusted_gradient_with_blend_ifs(gradient, settings, &adjustments(effects), &content_blend_ifs(effects), fill)
}
/// The color with its effects carried out as [`color_after_effects`] does and consumed, though not its opacity (see [`evaluate_color_parameter`]).
@@ -1,6 +1,6 @@
use crate::renderer::{
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, painted_gradient, spread_adjusted_samples,
svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
ItemRef, RenderParams, SvgGradientLayer, composite_paint_colors, faded_paint_color, format_transform_matrix, gradient_placement, gradient_shape, paint_draws_by_its_colors, painted_gradient,
spread_adjusted_samples, svg_gradient_standard, transform_is_invertible, with_two_stops_at_least, write_svg_gradient_paint,
};
use crate::{Render, RenderSvgSegmentList, SvgRender};
use core_types::color::SRGBA8;
@@ -88,7 +88,7 @@ impl RenderExt for List<Color> {
/// Adds one gradient item's paint server into `svg_defs` and returns its ID, or `None` when the item is absent or paints nothing.
/// One painted through a mask fills a pattern spanning `bounds`, which `stroke_transform` places in the painted element's space.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
fn render_gradient_paint(
item: Option<ItemRef<'_, Gradient>>,
svg_defs: &mut String,
@@ -101,14 +101,13 @@ fn render_gradient_paint(
let mut stop = String::new();
let item = item?;
let (stops, settings) = painted_gradient(item)?;
let (stops, settings, paint_opacity) = painted_gradient(item, for_mask)?;
let shape = gradient_shape(item);
let local_gradient_transform: DAffine2 = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = item.paint_opacity(for_mask);
if paint_opacity < 1. {
for (_, color, _) in &mut samples {
*color = color.with_alpha(color.a() * paint_opacity);
@@ -303,10 +302,11 @@ impl RenderExt for Graphic {
target: PaintTarget,
) -> Self::Output {
let paint_attr = target.paint_attr();
let by_colors = paint_draws_by_its_colors(self);
match self {
Graphic::Color(item) => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
Graphic::ColorList(color_list) => color_list.render(
Graphic::Color(item) if by_colors => render_color_paint(faded_paint_color(ItemRef::Item(item), render_params.for_mask), target),
Graphic::ColorList(color_list) if by_colors => color_list.render(
svg_defs,
user_to_document,
paint_reach,
@@ -317,11 +317,11 @@ impl RenderExt for Graphic {
render_params,
target,
),
Graphic::Gradient(item) => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
Graphic::Gradient(item) if by_colors => render_gradient_paint(Some(ItemRef::Item(item)), svg_defs, item_transform, element_transform, stroke_transform, bounds, render_params.for_mask)
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
// One gradient resolves to a paint server; stacking several needs them composited, which only the pattern below can do
Graphic::GradientList(gradient_list) if gradient_list.len() <= 1 => gradient_list
Graphic::GradientList(gradient_list) if by_colors => gradient_list
.render(
svg_defs,
user_to_document,
@@ -336,7 +336,10 @@ impl RenderExt for Graphic {
.map(|gradient_id| format!(r##" {paint_attr}="url(#{gradient_id})""##))
.unwrap_or_else(|| format!(r#" {paint_attr}="none""#)),
Graphic::None(_) | Graphic::NoneList(_) => format!(r#" {paint_attr}="none""#),
Graphic::Graphic(_)
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
| Graphic::RasterGPU(_)
+521 -58
View File
@@ -51,7 +51,8 @@ use num_traits::Zero;
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
use raster_kernels::raster_effects::adjusted_raster;
use raster_kernels::value_effects::{
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, color_after_effects, filled_color_with_blend_ifs, gradient_after_effects,
BlendIfStep, adjusted_color, adjusted_gradient, adjusted_gradient_with_blend_ifs, blend_ifs_span_runs, carries_out_every_effect, filled_color_after_effects, filled_color_with_blend_ifs,
filled_gradient_after_effects,
};
use skrifa::instance::{LocationRef, NormalizedCoord, Size};
use skrifa::outline::{DrawSettings, OutlinePen};
@@ -120,12 +121,12 @@ impl<'a, T> ItemRef<'a, T> {
}
}
/// The alpha multiplier this item's opacity attributes apply when it serves as a paint.
/// Fill opacity fades a paint just as opacity does, but a masker drops it so it cannot reach the content clipped to it.
pub(crate) fn paint_opacity(self, for_mask: bool) -> f32 {
let opacity_fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
/// The fill and opacity this item's opacity attributes fade it by when it serves as a paint, the fill before its effects and the opacity after them, as for any content.
/// A masker drops the fill so it cannot reach the content clipped to it.
pub(crate) fn paint_fill_and_opacity(self, for_mask: bool) -> (f32, f32) {
let fill = if for_mask { 1. } else { self.attribute_cloned_or::<f64>(ATTR_OPACITY_FILL, 1.) };
(self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) * opacity_fill) as f32
(fill as f32, self.attribute_cloned_or::<f64>(ATTR_OPACITY, 1.) as f32)
}
/// How the item's opacity attributes and effects apply as it renders, with `content_transform` placing its content in the space it's drawn in.
@@ -539,6 +540,7 @@ impl ItemCompositing<'_> {
// The color a solid paint draws, which is `None` for no paint, or no color at all for a paint that isn't solid
let solid_color = |paint: Option<&Graphic>| match paint {
None | Some(Graphic::None(_) | Graphic::NoneList(_)) => Some(None),
Some(paint) if !paint_draws_by_its_colors(paint) => None,
Some(Graphic::Color(item)) => Some(faded_paint_color(ItemRef::Item(item), for_mask)),
Some(Graphic::ColorList(list)) => Some(composite_paint_colors(list, for_mask)),
Some(_) => None,
@@ -2630,25 +2632,60 @@ fn rect_bounds(rect: kurbo::Rect) -> RenderBoundingBox {
RenderBoundingBox::Rectangle([DVec2::new(rect.x0, rect.y0), DVec2::new(rect.x1, rect.y1)])
}
/// The color one paint item contributes, with its effects carried out (see [`color_after_effects`]) and faded by its opacity attributes.
pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option<Color> {
let mut color = *item.element()?;
if let Some(effects) = item.attribute::<Effects>(ATTR_EFFECTS) {
color = color_after_effects(color, effects);
/// Whether a solid or gradient paint draws by its colors, with each item's effects carried out on them (see [`faded_paint_color`] and [`painted_gradient`]), which is exact
/// only where every effect changes each color on its own. Any other paint renders as content with its whole effect stack, clipped to the shape.
pub(crate) fn paint_draws_by_its_colors(paint: &Graphic) -> bool {
match paint {
// Stacked gradients can't composite into one brush
Graphic::GradientList(list) if list.len() > 1 => false,
Graphic::Color(_) | Graphic::ColorList(_) | Graphic::Gradient(_) | Graphic::GradientList(_) => !paint_has_effects_beyond_its_colors(paint),
_ => false,
}
Some(color.with_alpha(color.a() * item.paint_opacity(for_mask)))
}
/// The ramp one gradient paint item contributes, with its effects carried out along it (see [`gradient_after_effects`]), and the settings to read it with.
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>) -> Option<(Cow<'_, Gradient>, GradientSettings)> {
/// Whether an item of a solid or gradient paint has an effect that doesn't change each color on its own (see [`carries_out_every_effect`]).
fn paint_has_effects_beyond_its_colors(paint: &Graphic) -> bool {
fn beyond_colors(effects: Option<&Effects>) -> bool {
effects.is_some_and(|effects| !carries_out_every_effect(effects))
}
fn list_beyond_colors<T>(list: &List<T>) -> bool {
(0..list.len()).any(|index| beyond_colors(list.attribute(ATTR_EFFECTS, index)))
}
match paint {
Graphic::Color(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
Graphic::Gradient(item) => beyond_colors(item.attribute(ATTR_EFFECTS)),
Graphic::ColorList(list) => list_beyond_colors(list),
Graphic::GradientList(list) => list_beyond_colors(list),
_ => false,
}
}
/// The color one paint item contributes, faded by its fill with its effects carried out over that (see [`filled_color_after_effects`]), then faded by its opacity.
pub(crate) fn faded_paint_color(item: ItemRef<'_, Color>, for_mask: bool) -> Option<Color> {
let color = *item.element()?;
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
let filled = match item.attribute::<Effects>(ATTR_EFFECTS) {
Some(effects) => filled_color_after_effects(color, effects, fill),
None => color.with_alpha(color.a() * fill),
};
Some(filled.with_alpha(filled.a() * opacity))
}
/// The ramp one gradient paint item contributes, faded by its fill with its effects carried out along it (see [`filled_gradient_after_effects`]), the settings to read it with,
/// and the opacity left to fade it by, which takes the fill too where there was nothing to carry out along the ramp.
pub(crate) fn painted_gradient(item: ItemRef<'_, Gradient>, for_mask: bool) -> Option<(Cow<'_, Gradient>, GradientSettings, f32)> {
let gradient = item.element()?;
let settings = gradient_settings_from_item(item);
let (fill, opacity) = item.paint_fill_and_opacity(for_mask);
let adjusted = item.attribute::<Effects>(ATTR_EFFECTS).and_then(|effects| gradient_after_effects(gradient, settings, effects));
let adjusted = item
.attribute::<Effects>(ATTR_EFFECTS)
.and_then(|effects| filled_gradient_after_effects(gradient, settings, effects, fill));
Some(match adjusted {
Some((gradient, settings)) => (Cow::Owned(gradient), settings),
None => (Cow::Borrowed(gradient), settings),
Some((gradient, settings)) => (Cow::Owned(gradient), settings, opacity),
None => (Cow::Borrowed(gradient), settings, opacity * fill),
})
}
@@ -2917,6 +2954,8 @@ pub struct RenderParams {
pub canvas_image_scale: f64,
/// The nearest ancestor's appearance, cascading to items that lack their own.
pub inherited_appearance: Option<Appearance>,
/// The frame in the document of the shape a paint fills, within which endless content painting it is seen and has its effects carried out.
pub paint_frame: Option<DAffine2>,
}
impl RenderParams {
@@ -3128,6 +3167,24 @@ fn svg_only_approximates(paint: &Graphic) -> bool {
}
}
/// Whether a solid or gradient paint rendering as content (see [`paint_draws_by_its_colors`]) takes maps or images from the GPU for its effects, which can't reach the pattern it paints through.
/// Found by rendering it as content in the document, placed by `content_transform` in the current user space.
fn svg_paint_needs_the_gpu(paint: &Graphic, render: &SvgRender, content_transform: DAffine2, render_params: &RenderParams) -> bool {
if !paint_has_effects_beyond_its_colors(paint) || !render.images_replace_markup(render_params) {
return false;
}
let mut content = SvgRender::new();
content.transform = render.transform * content_transform;
content.ancestors_reach = render.ancestors_reach;
let paint_render_params = RenderParams {
inherited_appearance: None,
..render_params.clone()
};
paint.render_svg(&mut content, &paint_render_params);
!content.effect_maps.is_empty() || !content.deferred_images.is_empty()
}
/// Maps a gradient's `transform` into the frame handed to the renderer: most shapes keep the full matrix (so a
/// non-uniform transform makes an ellipse), while linear is reduced to the equivalent non-sheared gradient line (the
/// axis projected onto the band normal) so the iso-color bands keep following a sheared transform, which Vello can
@@ -3575,9 +3632,9 @@ fn apollonian_geometry(parameters: &GradientApollonian) -> vello_gpu::PencilGeom
}
/// How Vello draws one gradient paint item, in the space `multiplied_transform` places it in.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_opacity`] explains.
/// `for_mask` keeps the fill opacity at full, as [`ItemRef::paint_fill_and_opacity`] explains.
fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transform: &DAffine2, for_mask: bool) -> Option<VelloGradientPaint> {
let (stops, settings) = painted_gradient(gradient_item)?;
let (stops, settings, paint_opacity) = painted_gradient(gradient_item, for_mask)?;
let shape = gradient_shape(gradient_item);
let gradient_transform: DAffine2 = gradient_item.attribute_cloned_or_default(ATTR_TRANSFORM);
@@ -3585,7 +3642,6 @@ fn create_gradient_paint(gradient_item: ItemRef<'_, Gradient>, multiplied_transf
let mut samples = spread_adjusted_samples(&stops, settings, shape.reaches_before_start());
with_two_stops_at_least(shape, &mut samples);
let paint_opacity = gradient_item.paint_opacity(for_mask);
if paint_opacity < 1. {
// A stopless ramp gets its black stop downstream, too late to be faded, so it needs one here instead
if samples.is_empty() {
@@ -3864,7 +3920,11 @@ fn render_graphic_item_svg(item: ItemRef<'_, Graphic>, next_clips: bool, mask_st
if next_clips && mask_state.is_none() {
let uuid = generate_uuid();
let (base, nested) = clipping_base(element, transform, item.attribute::<Effects>(ATTR_EFFECTS));
let mask_type = if base.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
let mask_type = if base.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
MaskType::Clip
} else {
MaskType::Mask
};
// A base nested to take the item's effects carries the item's transform itself
let base_transform = if nested { DAffine2::IDENTITY } else { transform };
@@ -4781,6 +4841,22 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
let override_paint_order = can_draw_aligned_stroke && can_use_paint_order;
let use_face_fill = item.fills_faces();
// Fills drawn as paths of their own composite with the stroke's path as one shape, through a group taking its opacity and blend mode
if (needs_separate_alignment_fill || use_face_fill) && (opacity < 1. || blend_mode != BlendMode::default()) {
let group_attributes = |attributes: &mut SvgRenderAttrs| {
if opacity < 1. {
attributes.push("opacity", opacity.to_string());
}
if blend_mode != BlendMode::default() {
attributes.push("style", blend_mode.render());
}
};
render.parent_tag("g", group_attributes, |render| {
render_vector_shape_svg(item, vector, 1., BlendMode::default(), folded, render, render_params)
});
return;
}
if needs_separate_alignment_fill && !wants_stroke_below {
emit_svg_fill_path(
render,
@@ -4889,7 +4965,7 @@ fn render_vector_shape_svg(item: ItemRef<'_, Vector>, vector: &Vector, opacity:
let paint_bounds = match paint {
Graphic::Gradient(item) if gradient_draws_masked(ItemRef::Item(item)) => stroke_bounds_matrix,
Graphic::GradientList(list) if list.len() == 1 && gradient_draws_masked(ItemRef::ListItem(list, 0)) => stroke_bounds_matrix,
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) => bounds_matrix,
Graphic::Color(_) | Graphic::Gradient(_) | Graphic::ColorList(_) | Graphic::GradientList(_) if paint_draws_by_its_colors(paint) => bounds_matrix,
_ => stroke_bounds_matrix,
};
paint.render(
@@ -4970,7 +5046,11 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
if next_clips && clip_mask_state.is_none() {
let masker = Graphic::VectorList(vector_clipping_base(vector, item));
let mask_type = if masker.can_reduce_to_clip_path() { MaskType::Clip } else { MaskType::Mask };
let mask_type = if masker.can_reduce_to_clip_path(render_params.inherited_appearance.as_ref()) {
MaskType::Clip
} else {
MaskType::Mask
};
let uuid = generate_uuid();
let mut masker_svg = SvgRender::new();
@@ -5012,12 +5092,14 @@ fn render_vector_item_svg(item: ItemRef<'_, Vector>, next_clips: bool, clip_mask
None => compositing,
};
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles, takes the GPU's image of the item
// A fill or drawn stroke SVG only approximates, like a gradient of Apollonian circles or a paint with effects needing the GPU, takes the GPU's image of the item
let item_transform = item.attribute_cloned_or_default(ATTR_TRANSFORM);
let approximates = |paint: &Graphic| svg_only_approximates(paint) || svg_paint_needs_the_gpu(paint, render, item_transform, render_params);
let svg_approximates_paint = render_params.render_mode != RenderMode::Outline
&& appearance().is_some_and(|appearance| {
let FillAndStroke { fill_paint, stroke_paint, stroke, .. } = appearance.fill_and_stroke();
let strokes = stroke.is_some_and(|stroke| stroke.weight() > 0.);
fill_paint.is_some_and(svg_only_approximates) || (strokes && stroke_paint.is_some_and(svg_only_approximates))
fill_paint.is_some_and(approximates) || (strokes && stroke_paint.is_some_and(approximates))
});
let compositing = ItemCompositing {
svg_approximates_paint,
@@ -5257,6 +5339,13 @@ fn render_vector_item_to_vello(
let use_layer = can_draw_aligned_stroke;
// A paint is seen within the shape it fills, or the stroke's outline for the stroke
let painting_within = |bounds: [DVec2; 2]| RenderParams {
paint_frame: Some(frame_of_bounds(bounds, multiplied_transform)),
..paint_render_params.clone()
};
let stroke_bounds = || element.stroke_inclusive_bounding_box_with_transform(element_paths, DAffine2::IDENTITY, stroke).unwrap_or(layer_bounds);
let do_fill_path = |scene: &mut VelloSceneBuilder, path: &kurbo::BezPath, fill_rule: peniko::Fill| {
let Some(paint) = fill_paint else { return };
@@ -5282,15 +5371,18 @@ fn render_vector_item_to_vello(
});
};
let by_colors = paint_draws_by_its_colors(paint);
match paint {
Graphic::None(_) | Graphic::NoneList(_) => (),
Graphic::Color(item) => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) => gradient_fill(scene, ItemRef::Item(item)),
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
Graphic::GradientList(list) if list.len() <= 1 => gradient_fill(scene, ItemRef::ListItem(list, 0)),
Graphic::Color(item) if by_colors => solid_fill(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) if by_colors => solid_fill(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) if by_colors => gradient_fill(scene, ItemRef::Item(item)),
Graphic::GradientList(list) if by_colors => gradient_fill(scene, ItemRef::ListItem(list, 0)),
// Any other graphic content paints as a texture clipped to the path
Graphic::GradientList(_)
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::GradientList(_)
| Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
@@ -5304,8 +5396,9 @@ fn render_vector_item_to_vello(
| Graphic::GraphicList(_)
| Graphic::TextList(_)
| Graphic::StrokeList(_) => {
scene.push_clip_layer(fill_rule, kurbo::Affine::new(element_transform.to_cols_array()), path);
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
// The paint composites within its own layer, as in its SVG pattern, so its blend modes act on nothing beneath the shape
scene.push_layer(fill_rule, peniko::Mix::Normal, 1., kurbo::Affine::new(element_transform.to_cols_array()), path);
paint.render_to_vello(scene, multiplied_transform, &painting_within(layer_bounds));
scene.pop_layer();
}
};
@@ -5376,15 +5469,18 @@ fn render_vector_item_to_vello(
});
};
let by_colors = paint_draws_by_its_colors(paint);
match paint {
Graphic::None(_) | Graphic::NoneList(_) => (),
Graphic::Color(item) => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) => gradient_stroke(scene, ItemRef::Item(item)),
// Stacked gradients cannot be composited into one brush, so they fall through to the clipped texture path
Graphic::GradientList(list) if list.len() <= 1 => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
Graphic::Color(item) if by_colors => solid_stroke(scene, faded_paint_color(ItemRef::Item(item), render_params.for_mask)),
Graphic::ColorList(list) if by_colors => solid_stroke(scene, composite_paint_colors(list, render_params.for_mask)),
Graphic::Gradient(item) if by_colors => gradient_stroke(scene, ItemRef::Item(item)),
Graphic::GradientList(list) if by_colors => gradient_stroke(scene, ItemRef::ListItem(list, 0)),
// Any other graphic content paints as a texture clipped to the stroked region
Graphic::GradientList(_)
Graphic::Color(_)
| Graphic::ColorList(_)
| Graphic::Gradient(_)
| Graphic::GradientList(_)
| Graphic::Graphic(_)
| Graphic::Vector(_)
| Graphic::RasterCPU(_)
@@ -5400,8 +5496,9 @@ fn render_vector_item_to_vello(
| Graphic::StrokeList(_) => {
let stroked = placed.stroke_outline(&stroke, 0.01);
scene.push_clip_layer(peniko::Fill::NonZero, element_affine, &*stroked);
paint.render_to_vello(scene, multiplied_transform, paint_render_params);
// The paint composites within its own layer, as for the fill
scene.push_layer(peniko::Fill::NonZero, peniko::Mix::Normal, 1., element_affine, &*stroked);
paint.render_to_vello(scene, multiplied_transform, &painting_within(stroke_bounds()));
scene.pop_layer();
}
};
@@ -6325,10 +6422,10 @@ fn render_color_item_svg(item: ItemRef<'_, Color>, render: &mut SvgRender, rende
render_edgeless_color_svg(item, render, &compositing, color, render_params);
}
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for filters and warps, which change even a flat color,
/// and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
/// Whether endless content carries out its `effects` over the area in view rather than on its paint: for those reading the pixels around each one (like filters, warps, blurs, and Pixelate),
/// which change a ramp and some even a flat color, and for Blend Ifs spanning effect runs, which the paint's layers can't carry from one run to the next.
fn carried_out_in_view(effects: &Effects) -> bool {
graphic_types::filters::has_filters(effects) || warps_change_endless_content(effects) || blend_ifs_span_runs(effects)
effects.operations().any(|operation| operation.reads_pixels_around() && !operation.changes_nothing()) || blend_ifs_span_runs(effects)
}
/// Whether any of the effects is a warp that changes something, which it does within its frame even to endless content.
@@ -6550,7 +6647,15 @@ fn draw_endless_item_with_effects(
if layer {
scene.push_viewport_layer(peniko::BlendMode::new(blend_mode.to_peniko(), peniko::Compose::SrcOver), compositing.opacity);
}
compositing.draw_with_effects(scene, parent_transform, render_params, || RenderBoundingBox::Infinite, || None, 0., draw);
// Effects relative to the content's extent, like Pixelate, take the region it's seen in, being the shape it paints or else the view
let view = scene.view().inverse().transform_rect_bbox(kurbo::Rect::new(0., 0., scene.width() as f64, scene.height() as f64));
let frame = (render_params.paint_frame).unwrap_or_else(|| frame_of_bounds([DVec2::new(view.x0, view.y0), DVec2::new(view.x1, view.y1)], DAffine2::IDENTITY));
let bounds = match render_params.paint_frame {
Some(frame) => RenderBoundingBox::Rectangle((frame * Quad::from_box([DVec2::ZERO, DVec2::ONE])).bounding_box()),
None => RenderBoundingBox::Infinite,
};
compositing.draw_with_effects(scene, parent_transform, render_params, || bounds, || Some(frame), 0., draw);
if layer {
scene.pop_layer();
}
@@ -6622,26 +6727,33 @@ fn gradient_control_interior_is_clickable(gradient_form: GradientForm) -> bool {
gradient_form == GradientForm::Radial
}
/// For thumbnails the gradient fills a finite rect at the footprint's document space bounds, with a 1-unit margin to cover the `as u32` truncation of `Footprint::resolution`.
/// For thumbnails the gradient fills a finite rect around the footprint's document area in the user space, with a 1-unit margin for the `as u32` truncation of `Footprint::resolution`.
/// The viewBox crops the overshoot. Canvas rendering keeps the polyline path since Chrome rejects rects larger than ~20 million.
fn gradient_thumbnail_rect(render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
if render_params.thumbnail {
let truncated_size = render_params.footprint.resolution.as_dvec2();
let margin = DVec2::ONE;
Some((render_params.footprint.transform.translation - margin / 2., truncated_size + margin))
} else {
None
fn gradient_thumbnail_rect(render: &SvgRender, render_params: &RenderParams) -> Option<(DVec2, DVec2)> {
if !render_params.thumbnail {
return None;
}
let truncated_size = render_params.footprint.resolution.as_dvec2();
let margin = DVec2::ONE;
let (min, size) = (render_params.footprint.transform.translation - margin / 2., truncated_size + margin);
if !render.transform.matrix2.determinant().is_normal() {
return Some((min, size));
}
// Content drawn in a space of its own, like a paint's pattern, takes the area mapped into that space
let [min, max] = (render.transform.inverse() * Quad::from_box([min, min + size])).bounding_box();
Some((min, max - min))
}
/// Emits one item of gradient content as SVG.
fn render_gradient_item_svg(item: ItemRef<'_, Gradient>, render: &mut SvgRender, render_params: &RenderParams) {
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render_params), render, render_params);
render_gradient_item_svg_with_thumbnail_rect(item, gradient_thumbnail_rect(render, render_params), render, render_params);
}
impl Render for List<Gradient> {
fn render_svg(&self, render: &mut SvgRender, render_params: &RenderParams) {
let thumbnail_rect = gradient_thumbnail_rect(render_params);
let thumbnail_rect = gradient_thumbnail_rect(render, render_params);
render_list_items_svg(self, render, render_params, |index, render| {
render_gradient_item_svg_with_thumbnail_rect(ItemRef::ListItem(self, index), thumbnail_rect, render, render_params)
@@ -12115,7 +12227,7 @@ mod tests {
// A gradient's dark start is hidden and its light end shown
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
stamp_effect(&mut gradient, blend_if());
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).expect("the Blend If fades the ramp");
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).expect("the Blend If fades the ramp");
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
assert!(ramp.evaluate(0., settings).a() < 1e-6, "the start is hidden");
assert!(close(ramp.evaluate(1., settings), Color::WHITE), "the end shows");
@@ -12141,12 +12253,363 @@ mod tests {
let mut gradient = Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]));
stamp_effect(&mut gradient, invert());
let (ramp, settings) = painted_gradient(ItemRef::Item(&gradient)).unwrap();
let (ramp, settings, _) = painted_gradient(ItemRef::Item(&gradient), false).unwrap();
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
assert!(close(ramp.evaluate(0., settings), Color::WHITE), "the start turns white");
assert!(close(ramp.evaluate(1., settings), Color::BLACK), "the end turns black");
}
#[test]
fn paints_fade_by_their_fill_before_their_adjustments_and_by_their_opacity_after() {
use graphic_types::{Effect, EffectOperation, stamp_effect};
let close = |actual: Color, expected: Color| (actual.to_vec4() - expected.to_vec4()).abs().max_element() < 1e-6;
let make_opaque = || Effect::new(&EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. }));
let half_filled = |opacity: f64| Item::new_from_element(Color::RED).with_attribute(ATTR_OPACITY_FILL, 0.5).with_attribute(ATTR_OPACITY, opacity);
// Making a half-filled red opaque restores what the fill faded, though not what the opacity fades after it
let mut red = half_filled(1.);
stamp_effect(&mut red, make_opaque());
assert!(close(faded_paint_color(ItemRef::Item(&red), false).unwrap(), Color::RED));
let mut faded_red = half_filled(0.5);
stamp_effect(&mut faded_red, make_opaque());
assert!(close(faded_paint_color(ItemRef::Item(&faded_red), false).unwrap(), Color::RED.with_alpha(0.5)));
// Without effects, both fade it, though a masker drops the fill
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), false).unwrap(), Color::RED.with_alpha(0.25)));
assert!(close(faded_paint_color(ItemRef::Item(&half_filled(0.5)), true).unwrap(), Color::RED.with_alpha(0.5)));
// A gradient's ramp takes the fill where its effects are carried out along it, leaving only the opacity to fade it by, and otherwise leaves both
let half_filled_ramp = || Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE])).with_attribute(ATTR_OPACITY_FILL, 0.5);
let mut opaque_ramp = half_filled_ramp();
stamp_effect(&mut opaque_ramp, make_opaque());
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&opaque_ramp), false).unwrap();
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 1., "{opacity}");
let plain_ramp = half_filled_ramp();
let (ramp, settings, opacity) = painted_gradient(ItemRef::Item(&plain_ramp), false).unwrap();
assert!(ramp.evaluate(0.5, settings).a() > 1. - 1e-6 && opacity == 0.5, "{opacity}");
}
/// A square 100 across covered by a `paint`.
fn square_covered_by(coverage: Coverage, paint: Graphic) -> List<Vector> {
use kurbo::Shape;
let mut square = Vector::item_from_bezpath(&kurbo::Rect::new(0., 0., 100., 100.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
List::new_from_item(square)
}
/// A paint of `element` with the effect `operations` stamped on it.
fn effected_paint<T>(element: T, operations: impl IntoIterator<Item = graphic_types::EffectOperation>) -> Item<T> {
Item::new_from_element(element).with_attribute(ATTR_EFFECTS, Effects::from_operations(operations))
}
fn speckle(amount: f64) -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Speckle {
amount,
distribution: graphic_types::NoiseDistribution::Uniform,
monochromatic: false,
seed: 0,
}
}
#[test]
fn paints_draw_by_their_colors_only_where_every_effect_changes_each_color_alone() {
use graphic_types::EffectOperation;
let invert = EffectOperation::Adjustment(Adjustment::Invert);
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let mut underlying_darks_hidden = BlendIfRanges::default();
underlying_darks_hidden.underlying.gray.falloff_start = 50.;
underlying_darks_hidden.underlying.gray.range_start = 50.;
let twirl = EffectOperation::Twirl {
angle: 90.,
transform: DAffine2::from_scale(DVec2::splat(100.)),
};
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
// Adjustments, Blend Ifs reading the paint's own colors, and effects changing nothing keep to the fast path
for operations in [vec![], vec![invert.clone()], vec![EffectOperation::BlendIf(Box::new(darks_hidden)), invert.clone()], vec![speckle(0.)]] {
assert!(paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, operations.clone()))), "{operations:?}");
assert!(paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), operations))));
}
// Effects reading neighbors, positions, or what lies beneath don't, nor do lists holding a paint with one
for operation in [speckle(50.), twirl, pixelate, EffectOperation::BlendIf(Box::new(underlying_darks_hidden))] {
assert!(!paint_draws_by_its_colors(&Graphic::Color(effected_paint(Color::BLACK, [operation.clone()]))), "{operation:?}");
assert!(!paint_draws_by_its_colors(&Graphic::Gradient(effected_paint(Gradient::default(), [operation.clone()]))));
let colors: List<Color> = [Item::new_from_element(Color::WHITE), effected_paint(Color::BLACK, [operation])].into_iter().collect();
assert!(!paint_draws_by_its_colors(&Graphic::ColorList(colors)));
}
// So an inverted fill stays a plain color in SVG, without a pattern
let mut render = SvgRender::new();
square_covered_by(Coverage::new_fill(), Graphic::Color(effected_paint(Color::BLACK, [invert]))).render_svg(&mut render, &RenderParams::default());
let svg = render.svg.to_svg_string();
assert!(svg.contains(r##"fill="#ffffff""##) && !render.svg_defs.contains("<pattern"), "{svg}");
}
#[test]
fn svg_paints_with_effects_beyond_their_colors_render_as_content_clipped_to_the_shape() {
use glam::UVec2;
use graphic_types::EffectOperation;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
let in_view = RenderParams {
view: Some(Footprint {
resolution: UVec2::new(160, 160),
..Default::default()
}),
..Default::default()
};
let stroke = |align: StrokeAlign| Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) });
let coverages = || [Coverage::new_fill(), stroke(StrokeAlign::Center), stroke(StrokeAlign::Inside), stroke(StrokeAlign::Outside)];
// A grained color or a twirled gradient, which SVG's filters can't draw in a pattern, takes the GPU's image of the vector
let twirl = EffectOperation::Twirl {
angle: 180.,
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100.), 0., DVec2::splat(50.)),
};
let gradient = || Gradient::from(vec![Color::BLACK, Color::WHITE]);
for paint in [Graphic::Color(effected_paint(Color::RED, [speckle(50.)])), Graphic::Gradient(effected_paint(gradient(), [twirl]))] {
for coverage in coverages() {
let images = deferred_images_of(Graphic::VectorList(square_covered_by(coverage, paint.clone())), &in_view);
assert!(
matches!(
&images[..],
[DeferredImage {
content: DeferredContent::Item(Graphic::Vector(_)),
..
}]
),
"{} images",
images.len()
);
}
}
// A masked gradient, which SVG draws, paints natively through a pattern holding the mask
let mut left_half = Vector::item_from_bezpath(&kurbo::Shape::to_path(&kurbo::Rect::new(0., 0., 50., 100.), 0.1));
left_half.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(Color::WHITE))));
let mask = EffectOperation::Mask {
mask: Graphic::VectorList(List::new_from_item(left_half)),
mode: graphic_types::MaskMode::Luminance,
density: 100.,
feather: 0.,
invert: false,
};
for coverage in coverages() {
let mut render = SvgRender::new();
square_covered_by(coverage, Graphic::Gradient(effected_paint(gradient(), [mask.clone()]))).render_svg(&mut render, &in_view);
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
assert!(render.deferred_images.is_empty() && render.effect_maps.is_empty(), "{svg}");
assert!(svg.contains(r##"="url(#pattern-"##) && defs.contains("<pattern") && defs.contains("<mask"), "{svg}\n{defs}");
}
// Where no image can replace markup, the grained color paints through a pattern spanning the stroke as well as the fill
let thumbnail = RenderParams { thumbnail: true, ..in_view };
let pattern_width = |coverage: Coverage| {
let mut render = SvgRender::new();
square_covered_by(coverage, Graphic::Color(effected_paint(Color::RED, [speckle(50.)]))).render_svg(&mut render, &thumbnail);
assert!(render.deferred_images.is_empty(), "{}", render.svg.to_svg_string());
let defs = render.svg_defs;
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
let width = pattern.split(r#"width=""#).nth(1).and_then(|rest| rest.split('"').next()).expect("the pattern has a width");
width.parse::<f64>().unwrap()
};
assert_eq!(pattern_width(Coverage::new_fill()), 100.);
for (align, stroked_width) in [(StrokeAlign::Center, 110.), (StrokeAlign::Inside, 100.), (StrokeAlign::Outside, 120.)] {
let width = pattern_width(stroke(align));
assert!(width >= stroked_width, "{align:?}: {width}");
}
}
#[test]
fn svg_endless_gradients_and_their_paints_blur_natively_and_pixelate_through_the_gpu() {
use glam::UVec2;
use graphic_types::EffectOperation;
let in_view = RenderParams {
view: Some(Footprint {
resolution: UVec2::new(160, 160),
..Default::default()
}),
..Default::default()
};
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let pixelate = EffectOperation::Pixelate { cell_size: 10., offset: DVec2::ZERO };
let gradient = |operation: &EffectOperation| Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [operation.clone()]));
let render_of = |graphic: Graphic| {
let mut render = SvgRender::new();
List::new_from_element(graphic).render_svg(&mut render, &in_view);
render
};
// A gradient layer and a square it fills blur by SVG's own filter
for graphic in [gradient(&blur), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&blur)))] {
let render = render_of(graphic);
assert!(render.deferred_images.is_empty() && render.svg_defs.contains("feGaussianBlur"), "{}", render.svg_defs);
}
// SVG can't pixelate, so each takes the GPU's image of it
for graphic in [gradient(&pixelate), Graphic::VectorList(square_covered_by(Coverage::new_fill(), gradient(&pixelate)))] {
let images = render_of(graphic).deferred_images;
assert_eq!(images.len(), 1);
}
}
#[test]
fn svg_thumbnails_fill_the_patterns_of_moved_shapes_with_their_gradient_paints() {
use core_types::transform::RenderQuality;
// A square moved 500 across, filled by a blurred gradient through a pattern in the square's own space
let blur = graphic_types::EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let mut square = square_covered_by(Coverage::new_fill(), Graphic::Gradient(effected_paint(Gradient::from(vec![Color::BLACK, Color::WHITE]), [blur])));
square.set_attribute(ATTR_TRANSFORM, 0, DAffine2::from_translation(DVec2::new(500., 0.)));
let thumbnail = RenderParams {
footprint: Footprint::from_bounds([DVec2::new(500., 0.), DVec2::new(600., 100.)], RenderQuality::Full),
thumbnail: true,
..Default::default()
};
let mut render = SvgRender::new();
square.render_svg(&mut render, &thumbnail);
let defs = render.svg_defs;
// The gradient's rectangle covers the pattern's tile, from 0 to 100 in the square's space
let pattern = &defs[defs.find("<pattern").expect("the paint draws through a pattern")..];
let rect = &pattern[pattern.find("<rect").expect("the gradient fills a rectangle")..];
let attribute = |name: &str| -> f64 { rect.split(&format!(r#" {name}=""#)).nth(1).and_then(|rest| rest.split('"').next()).unwrap().parse().unwrap() };
let (x, width) = (attribute("x"), attribute("width"));
assert!(x <= 0. && x + width >= 100., "{rect}");
}
#[test]
fn svg_shortcuts_for_opaque_or_transparent_paints_look_past_effects_that_might_change_alpha() {
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
use graphic_types::{CoverPlacement, EffectOperation};
let svg_of = |list: List<Vector>| {
let mut render = SvgRender::new();
list.render_svg(&mut render, &RenderParams::default());
(render.svg.to_svg_string(), render.svg_defs)
};
// Black faded away by a Blend If hiding the darks
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let faded_black = || Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
// A clipping base filled with it masks what clips to it by its alpha, rather than clipping to its outline as if it were opaque
for (base_paint, clips) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
let mut list = square_covered_by(Coverage::new_fill(), base_paint);
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
list.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
let (svg, defs) = svg_of(list);
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
}
// An outside stroke beneath it isn't hidden within the shape by drawing the fill over it, which would leave its inner half showing through
for (fill_paint, paint_order) in [(Graphic::Color(Item::new_from_element(Color::BLACK)), true), (faded_black(), false)] {
let mut list = square_covered_by(Coverage::new_fill(), fill_paint);
let red = Graphic::Color(Item::new_from_element(Color::RED));
let outside = Stroke {
align: StrokeAlign::Outside,
..Stroke::new(10.)
};
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
appearance.replace_or_insert(Coverage::new_stroke(&outside), red, DAffine2::IDENTITY, CoverPlacement::Above);
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
let (svg, defs) = svg_of(list);
assert_eq!(svg.contains("paint-order"), paint_order, "{svg}");
assert_eq!(defs.contains("alignment-"), !paint_order, "{svg}\n{defs}");
}
// A transparent stroke made opaque is drawn
let transparent_red = Color::from_rgbaf32_unchecked(1., 0., 0., 0.);
let made_opaque = Graphic::Color(effected_paint(transparent_red, [EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. })]));
let (svg, _) = svg_of(square_covered_by(Coverage::new_stroke(&Stroke::new(4.)), made_opaque));
assert!(svg.contains(r##"stroke="#ff0000""##), "{svg}");
}
#[test]
fn svg_fills_drawn_apart_from_an_aligned_stroke_share_the_shapes_opacity_and_blend_mode() {
use graphic_types::CoverPlacement;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
// A translucent fill can't hide an outside stroke's inner half, so it's drawn as a path of its own
let mut list = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED.with_alpha(0.5))));
let outside = Stroke {
align: StrokeAlign::Outside,
..Stroke::new(10.)
};
let mut appearance = list.attribute::<Appearance>(ATTR_APPEARANCE, 0).unwrap().clone();
appearance.replace_or_insert(
Coverage::new_stroke(&outside),
Graphic::Color(Item::new_from_element(Color::BLUE)),
DAffine2::IDENTITY,
CoverPlacement::Above,
);
list.set_attribute(ATTR_APPEARANCE, 0, appearance);
list.set_attribute(ATTR_OPACITY, 0, 0.5);
list.set_attribute(ATTR_BLEND_MODE, 0, BlendMode::Multiply);
let mut render = SvgRender::new();
list.render_svg(&mut render, &RenderParams::default());
let svg = render.svg.to_svg_string();
// Both paths lie in one group taking the opacity and blend mode, which neither takes again
let group = &svg[svg.find("<g").expect("the paths are grouped")..];
assert!(group.matches("<path").count() == 2, "{svg}");
assert!(svg.matches(r#" opacity="0.5""#).count() == 1 && group.starts_with(r#"<g opacity="0.5""#), "{svg}");
assert!(svg.matches("multiply").count() == 1, "{svg}");
}
#[test]
fn svg_clipping_bases_filled_by_an_inherited_paint_clip_by_its_alpha() {
use graphic_types::EffectOperation;
// Black faded away by a Blend If hiding the darks, or plain opaque black
let mut darks_hidden = BlendIfRanges::default();
darks_hidden.content.gray.falloff_start = 50.;
darks_hidden.content.gray.range_start = 50.;
let faded_black = Graphic::Color(effected_paint(Color::BLACK, [EffectOperation::BlendIf(Box::new(darks_hidden))]));
let opaque_black = Graphic::Color(Item::new_from_element(Color::BLACK));
// A group's fill cascades to a square without its own, which a red square clips to
for (inherited_fill, clips) in [(opaque_black, true), (faded_black, false)] {
let mut squares = square_covered_by(Coverage::new_fill(), Graphic::default());
squares.set_attribute(ATTR_APPEARANCE, 0, Appearance::default());
let clipped = square_covered_by(Coverage::new_fill(), Graphic::Color(Item::new_from_element(Color::RED)));
squares.push(clipped.into_iter().next().unwrap().with_attribute(ATTR_CLIPPING_MASK, true));
let group = Item::new_from_element(Graphic::VectorList(squares)).with_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), inherited_fill));
let mut render = SvgRender::new();
List::new_from_item(group).render_svg(&mut render, &RenderParams::default());
let (svg, defs) = (render.svg.to_svg_string(), render.svg_defs);
assert_eq!(defs.contains("<clipPath"), clips, "{svg}\n{defs}");
assert_eq!(defs.contains("<mask"), !clips, "{svg}\n{defs}");
}
}
#[test]
fn svg_endless_colors_carry_out_filters_over_the_area_in_view_in_nested_groups() {
use glam::UVec2;
@@ -211,7 +211,7 @@ fn a_clip_path_becomes_a_hidden_clipper_beneath_the_content_it_clips() -> Result
let content = converted(r#"<clipPath id="clip"><rect width="4" height="4"/></clipPath><g clip-path="url(#clip)"><rect width="8" height="8"/></g>"#)?;
let clipped = group(&content, 0);
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
assert_eq!(clipped.and_then(|clipped| clipped.attribute::<f64>(ATTR_OPACITY_FILL, 0)), Some(&0.));
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
Ok(())
@@ -314,7 +314,7 @@ fn a_mask_region_that_cuts_its_content_clips_the_masked_content() -> Result<(),
let within_region = group(&content, 0).and_then(|masked| masked.element(1));
assert!(within_region.is_some_and(Graphic::had_clip_enabled));
let clipped = within_region.and_then(Graphic::as_graphic_list);
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(Graphic::can_reduce_to_clip_path));
assert!(clipped.and_then(|clipped| clipped.element(0)).is_some_and(|clipped| clipped.can_reduce_to_clip_path(None)));
assert!(clipped.and_then(|clipped| clipped.element(1)).is_some_and(Graphic::had_clip_enabled));
Ok(())
}
@@ -1715,6 +1715,250 @@ fn endless_layers_clip_to_the_shape_beneath_them() {
}
}
/// Black on the left half of a render 140 across and white on the right, with nothing between, its effects measured in its own space spanning the render.
fn hard_edged_gradient() -> core_types::list::Item<graphic_types::vector_types::gradient::Gradient> {
use core_types::list::{ATTR_GRADIENT_INTERPOLATION, Item};
use core_types::{ATTR_TRANSFORM, Color};
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Stepped)
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
}
/// Pixelate with cells 10 across in a gradient's space spanning a render 140 across.
fn pixelated_by_tens() -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Pixelate {
cell_size: 10. / 140.,
offset: glam::DVec2::ZERO,
}
}
/// A Gaussian blur of radius 4 in a gradient's space spanning a render 140 across.
fn blurred_by_four() -> graphic_types::EffectOperation {
graphic_types::EffectOperation::Blur {
radius_mask: graphic_types::Graphic::default(),
radius: 4. / 140.,
box_blur: false,
gamma: false,
}
}
#[test]
fn endless_gradients_pixelate_and_blur_over_the_view() {
use core_types::list::{ATTR_EFFECTS, ATTR_GRADIENT_INTERPOLATION};
use core_types::{ATTR_TRANSFORM, Color};
use graphic_types::vector_types::gradient::{Gradient, GradientInterpolation};
use graphic_types::{Effects, Graphic};
use rendering::{Render, RenderParams};
let size = UVec2::new(140, 140);
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
// A smooth black-to-white ramp across the render bands into cells 10 across, each one color
let ramp = core_types::list::Item::new_from_element(Gradient::from(vec![Color::BLACK, Color::WHITE]))
.with_attribute(ATTR_GRADIENT_INTERPOLATION, GradientInterpolation::Linear)
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(glam::DVec2::splat(140.)))
.with_attribute(ATTR_EFFECTS, Effects::from_operations([pixelated_by_tens()]));
let Some(pixelated) = draw(&Graphic::Gradient(ramp)) else { return };
for cell in 1..13 {
let first = pixel(&pixelated, size, cell * 10 + 1, 70);
assert!((cell * 10 + 2..cell * 10 + 9).all(|x| pixel(&pixelated, size, x, 70) == first), "cell {cell} is one color");
assert_ne!(first, pixel(&pixelated, size, cell * 10 + 11, 70), "cell {cell} differs from the next");
}
// The hard edge halfway across softens, from gray just beside it to black and white farther away
let blurred = draw(&Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, Effects::from_operations([blurred_by_four()])))).unwrap();
let gray = |x: u32| pixel(&blurred, size, x, 70)[0];
assert!(gray(66) > 10 && gray(66) < 128 && gray(73) > 128 && gray(73) < 245, "{} and {}", gray(66), gray(73));
assert!(gray(50) < 3 && gray(90) > 252, "{} and {}", gray(50), gray(90));
}
#[test]
fn paints_with_effects_beyond_their_colors_show_them_within_the_shape() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_TRANSFORM, Color as GraphicColor};
use glam::DVec2;
use graphic_types::vector_types::gradient::Gradient;
use graphic_types::vector_types::vector::style::{Stroke, StrokeAlign};
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, MaskMode, NoiseDistribution, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let draw = |graphic: &Graphic| render(size, |scene| graphic.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default()));
let square_covered_by = |coverage: Coverage, paint: Graphic| {
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
Graphic::VectorList(List::new_from_item(square))
};
let close = |a: [u8; 4], b: [u8; 4]| a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 2);
// A color and a gradient across the render, grained, twirled, and masked to its left half, with the gradient's effects measured in its own space that spans the render
let color = || Item::new_from_element(GraphicColor::from_gamma_srgb_channels(0.8, 0.2, 0.4, 1.));
let gradient = || Item::new_from_element(Gradient::from(vec![GraphicColor::BLACK, GraphicColor::WHITE])).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(140.)));
let speckle = EffectOperation::Speckle {
amount: 50.,
distribution: NoiseDistribution::Uniform,
monochromatic: false,
seed: 0,
};
let twirl = EffectOperation::Twirl {
angle: 180.,
transform: DAffine2::from_scale_angle_translation(DVec2::splat(100. / 140.), 0., DVec2::splat(0.5)),
};
let mut left_half = Vector::item_from_bezpath(&Rect::new(0., 0., 0.5, 1.).to_path(0.001));
left_half.set_attribute(
ATTR_APPEARANCE,
Appearance::new_single(Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::WHITE))),
);
let mask = EffectOperation::Mask {
mask: Graphic::VectorList(List::new_from_item(left_half)),
mode: MaskMode::Luminance,
density: 100.,
feather: 0.,
invert: false,
};
let effected = |operation: &EffectOperation| Effects::from_operations([operation.clone()]);
let paints = [
("speckled color", Graphic::Color(color().with_attribute(ATTR_EFFECTS, effected(&speckle))), Graphic::Color(color())),
(
"speckled gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&speckle))),
Graphic::Gradient(gradient()),
),
(
"twirled gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&twirl))),
Graphic::Gradient(gradient()),
),
(
"masked gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&mask))),
Graphic::Gradient(gradient()),
),
(
"pixelated gradient",
Graphic::Gradient(gradient().with_attribute(ATTR_EFFECTS, effected(&pixelated_by_tens()))),
Graphic::Gradient(gradient()),
),
(
"blurred hard-edged gradient",
Graphic::Gradient(hard_edged_gradient().with_attribute(ATTR_EFFECTS, effected(&blurred_by_four()))),
Graphic::Gradient(hard_edged_gradient()),
),
];
for (name, paint, plain) in paints {
// The paint drawn as a layer filling everything, which the shape's paint matches where it covers it
let Some(layer) = draw(&paint) else { return };
// A fill shows the effect within the square and nothing past it
let filled = draw(&square_covered_by(Coverage::new_fill(), paint.clone())).unwrap();
let plain_filled = draw(&square_covered_by(Coverage::new_fill(), plain.clone())).unwrap();
for (x, y) in (22..118).flat_map(|x| (22..118).map(move |y| (x, y))) {
assert!(close(pixel(&filled, size, x, y), pixel(&layer, size, x, y)), "{name}: the fill matches the layer at ({x}, {y})");
}
for (x, y) in [(10, 70), (130, 70), (70, 10), (70, 130)] {
assert_eq!(pixel(&filled, size, x, y)[3], 0, "{name}: nothing is filled at ({x}, {y}), past the square");
}
let changed = (0..filled.len()).filter(|&index| !close(filled[index], plain_filled[index])).count();
assert!(changed > 500, "{name}: the effect changes the fill at {changed} pixels");
// A stroke shows it within its band, wherever its alignment places it along the square's left edge
for (align, band) in [(StrokeAlign::Center, 16..24), (StrokeAlign::Inside, 21..29), (StrokeAlign::Outside, 11..19)] {
let stroked = draw(&square_covered_by(Coverage::new_stroke(&Stroke { align, ..Stroke::new(10.) }), paint.clone())).unwrap();
for (x, y) in band.clone().flat_map(|x| (40..100).map(move |y| (x, y))) {
assert!(
close(pixel(&stroked, size, x, y), pixel(&layer, size, x, y)),
"{name}, {align:?}: the stroke matches the layer at ({x}, {y})"
);
}
for x in [band.start - 4, band.end + 3] {
assert_eq!(pixel(&stroked, size, x, 70)[3], 0, "{name}, {align:?}: nothing is stroked at ({x}, 70), past the band");
}
}
}
}
#[test]
fn a_half_filled_paint_made_opaque_looks_the_same_whether_drawn_by_its_color_or_as_content() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_OPACITY_FILL, Color as GraphicColor};
use graphic_types::adjustment::Adjustment;
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let filled_square = |operations: Vec<EffectOperation>| {
let paint = Item::new_from_element(GraphicColor::RED)
.with_attribute(ATTR_OPACITY_FILL, 0.5)
.with_attribute(ATTR_EFFECTS, Effects::from_operations(operations));
let mut square = Vector::item_from_bezpath(&Rect::new(20., 20., 120., 120.).to_path(0.1));
square.set_attribute(ATTR_APPEARANCE, Appearance::new_single(Coverage::new_fill(), Graphic::Color(paint)));
Graphic::VectorList(List::new_from_item(square))
};
// The fill fades the red before Make Opaque restores it, alike when a blur of the flat color draws it as content
let make_opaque = EffectOperation::Adjustment(Adjustment::MakeOpaque { strength: 100. });
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
for operations in [vec![make_opaque.clone()], vec![make_opaque, blur]] {
let count = operations.len();
let Some(pixels) = render(size, |scene| filled_square(operations.clone()).render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default())) else {
return;
};
for (x, y) in [(70, 70), (25, 70), (115, 115)] {
assert_eq!(pixel(&pixels, size, x, y), [255, 0, 0, 255], "{count} effects at ({x}, {y})");
}
}
}
#[test]
fn a_paints_own_blend_mode_composites_within_the_paint_rather_than_onto_what_lies_beneath_the_shape() {
use core_types::list::{ATTR_APPEARANCE, ATTR_EFFECTS, Item, List};
use core_types::{ATTR_BLEND_MODE, Color as GraphicColor};
use graphic_types::vector_types::vector::style::Stroke;
use graphic_types::{Appearance, Coverage, EffectOperation, Effects, Graphic, Vector};
use rendering::{Render, RenderParams};
use vello_gpu::kurbo::Shape;
let size = UVec2::new(140, 140);
let shape = |rect: Rect, coverage: Coverage, paint: Graphic| {
let mut vector = Vector::item_from_bezpath(&rect.to_path(0.1));
vector.set_attribute(ATTR_APPEARANCE, Appearance::new_single(coverage, paint));
Graphic::VectorList(List::new_from_item(vector))
};
let background = shape(Rect::new(0., 0., 140., 140.), Coverage::new_fill(), Graphic::ColorList(List::new_from_element(GraphicColor::RED)));
// Green multiplied with nothing beneath it in its paint stays green, whatever lies beneath the shape, as in SVG's pattern, though a blur of it draws it as content
let blur = EffectOperation::Blur {
radius_mask: Graphic::default(),
radius: 4.,
box_blur: false,
gamma: false,
};
let green = Item::new_from_element(GraphicColor::GREEN)
.with_attribute(ATTR_BLEND_MODE, BlendMode::Multiply)
.with_attribute(ATTR_EFFECTS, Effects::from_operations([blur]));
for (coverage, inside) in [(Coverage::new_fill(), (70, 70)), (Coverage::new_stroke(&Stroke::new(10.)), (20, 70))] {
let square = shape(Rect::new(20., 20., 120., 120.), coverage, Graphic::Color(green.clone()));
let Some(pixels) = render(size, |scene| {
background.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
square.render_to_vello(scene, DAffine2::IDENTITY, &RenderParams::default());
}) else {
return;
};
let (x, y) = inside;
assert_eq!(pixel(&pixels, size, x, y), [0, 255, 0, 255], "green at ({x}, {y})");
}
}
#[test]
fn feathers_fade_the_content_to_nothing_at_its_edges() {
use graphic_types::EffectOperation;