mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-12-02 00:01:59 -10:00
Compare commits
1
Commits
master
..
glow-noise
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f302670e12 |
No files matched your search
@@ -0,0 +1,48 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
}
|
||||
|
||||
/// 'Inner Glow' gained Noise, Jitter, and a seed, set to none to keep the glow smooth.
|
||||
#[migration("blending_nodes::effects::InnerGlowNode"@2 => @3)]
|
||||
pub fn inner_glow_v2(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Integer(0)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(9, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&InnerGlowV2, &contract());
|
||||
check_undo(&InnerGlowV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||
let inputs: Vec<_> = (0..9).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&InnerGlowV2);
|
||||
let inner_glow = fixture.add(decl!("blending_nodes::effects::InnerGlowNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&InnerGlowV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend([literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||
assert_eq!(fixture.declaration_of(&migrated, inner_glow), Some(decl!("blending_nodes::effects::InnerGlowNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, inner_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -6,9 +6,11 @@ mod blur_v2;
|
||||
mod convolution_kernel_v1;
|
||||
mod drop_shadow_v1;
|
||||
mod inner_glow_v1;
|
||||
mod inner_glow_v2;
|
||||
mod inner_shadow_v1;
|
||||
mod mask_by_any_graphic;
|
||||
mod outer_glow_v1;
|
||||
mod outer_glow_v2;
|
||||
mod outline_v1;
|
||||
mod outline_v2;
|
||||
mod outline_v3;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
use migration_core::{Inputs, literal, migration};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Frozen mirror of the `TaggedValue` variants this migration writes.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
enum Tagged {
|
||||
Number(f64),
|
||||
Integer(i64),
|
||||
}
|
||||
|
||||
/// 'Outer Glow' gained Noise, Jitter, and a seed, set to none to keep the glow smooth.
|
||||
#[migration("blending_nodes::effects::OuterGlowNode"@2 => @3)]
|
||||
pub fn outer_glow_v2(inputs: &mut Inputs) {
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Number(0.)));
|
||||
inputs.push(literal(Tagged::Integer(0)));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use migration_core::decl;
|
||||
use migration_runner::testing::{Fixture, SourceContract, check_commutation, check_undo};
|
||||
|
||||
fn contract() -> SourceContract {
|
||||
SourceContract::new(8, |random, _slot| literal(random.below(10) as f64))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_history() {
|
||||
check_commutation(&OuterGlowV2, &contract());
|
||||
check_undo(&OuterGlowV2, &contract());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_the_inputs_and_adds_no_noise_or_jitter() {
|
||||
let inputs: Vec<_> = (0..8).map(|index| literal(index as f64)).collect();
|
||||
|
||||
let mut fixture = Fixture::new(&OuterGlowV2);
|
||||
let outer_glow = fixture.add(decl!("blending_nodes::effects::OuterGlowNode"@2), inputs.clone());
|
||||
let migrated = fixture.migrate(&OuterGlowV2).unwrap();
|
||||
|
||||
let mut expected = inputs;
|
||||
expected.extend([literal(Tagged::Number(0.)), literal(Tagged::Number(0.)), literal(Tagged::Integer(0))]);
|
||||
assert_eq!(fixture.declaration_of(&migrated, outer_glow), Some(decl!("blending_nodes::effects::OuterGlowNode"@3)));
|
||||
assert_eq!(fixture.inputs(&migrated, outer_glow), expected);
|
||||
}
|
||||
}
|
||||
@@ -2467,6 +2467,25 @@ fn migrate_node(node_id: &NodeId, node: &DocumentNode, network_path: &[NodeId],
|
||||
inputs_count += 1;
|
||||
}
|
||||
|
||||
// 'Outer Glow' gained Noise, Jitter, and a seed, set to none to keep the glow smooth
|
||||
if reference == DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER) && inputs_count == 8 {
|
||||
let mut node_template = resolve_document_node_type(&reference)?.default_node_template();
|
||||
document.network_interface.replace_implementation(node_id, network_path, &mut node_template);
|
||||
let old_inputs = document.network_interface.replace_inputs(node_id, network_path, &mut node_template)?;
|
||||
|
||||
for (index, input) in old_inputs.into_iter().take(8).enumerate() {
|
||||
document.network_interface.set_input(&InputConnector::node_at_index(*node_id, index), input, network_path);
|
||||
}
|
||||
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)];
|
||||
for (index, value) in (8..).zip(smooth) {
|
||||
document
|
||||
.network_interface
|
||||
.set_input(&InputConnector::node_at_index(*node_id, index), NodeInput::value(value, false), network_path);
|
||||
}
|
||||
|
||||
inputs_count = 11;
|
||||
}
|
||||
|
||||
// Upgrade the legacy 4-input Fill node (content, fill: Fill, _backup_color, _backup_gradient: Gradient) to the value-model
|
||||
// 7-input shape (content, fill: generic paint list, _backup_color, _backup_gradient, _gradient_form, _has_transform, _transform).
|
||||
if reference == DefinitionIdentifier::ProtoNode(graphene_std::vector_nodes::fill::IDENTIFIER) && inputs_count == 4 {
|
||||
@@ -5927,6 +5946,42 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outer_glows_from_before_their_grain_open_smooth() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
use graph_craft::application_io::resource::HashMapResourceStorage;
|
||||
use graphene_std::blending_nodes::effects::outer_glow;
|
||||
|
||||
let definition = resolve_document_node_type(&DefinitionIdentifier::ProtoNode(outer_glow::IDENTIFIER)).expect("the Outer Glow definition should exist");
|
||||
let template = definition.default_node_template();
|
||||
|
||||
// One saved before its blend mode and one saved after it, but before its grain
|
||||
let mut document = DocumentMessageHandler::default();
|
||||
for (index, before_blend_mode) in [true, false].into_iter().enumerate() {
|
||||
let mut inputs = template.inputs.clone();
|
||||
if before_blend_mode {
|
||||
inputs.remove(2);
|
||||
}
|
||||
inputs.truncate(if before_blend_mode { 7 } else { 8 });
|
||||
|
||||
let node_template = NodeTemplate {
|
||||
implementation: NodeTemplateImplementation::ProtoNode(outer_glow::IDENTIFIER),
|
||||
inputs,
|
||||
..Default::default()
|
||||
};
|
||||
document.network_interface.insert_node(NodeId(index as u64 + 1), node_template, &[]);
|
||||
}
|
||||
|
||||
let opened = load_legacy_document(document.serialize_document(), &HashMapResourceStorage::new(), false).expect("the document should open");
|
||||
|
||||
let smooth = [TaggedValue::Number(0.), TaggedValue::Number(0.), TaggedValue::Integer(0)].map(|value| NodeInput::value(value, false));
|
||||
for index in 0..2 {
|
||||
let node = opened.network_interface.document_node(&NodeId(index + 1), &[]).expect("the node should still exist");
|
||||
assert_eq!(node.inputs.len(), 11);
|
||||
assert_eq!(node.inputs[8..], smooth, "the glow should open without grain");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn make_opaques_from_before_their_strength_open_fully_opaque() {
|
||||
use crate::messages::portfolio::document_storage_io::load_legacy_document;
|
||||
|
||||
@@ -598,9 +598,36 @@ pub(crate) fn collapses(transform: &DAffine2) -> bool {
|
||||
!transform.matrix2.determinant().is_normal()
|
||||
}
|
||||
|
||||
/// For PSD interop, an outer glow filled with a gradient fades out once its strength before range and contour falls below this.
|
||||
/// For PSD interop, an outer glow filled with a gradient or roughened by noise fades out once its strength before range and contour falls below this.
|
||||
pub const GRADIENT_GLOW_FADE: f64 = 0.12;
|
||||
|
||||
/// The most a glow's alpha reaches where its `raw` strength (before range and contour) is: all of it, or for PSD interop, if it `fades`, no more than its raw strength over [`GRADIENT_GLOW_FADE`].
|
||||
pub fn glow_alpha_limit(raw: f64, fades: bool) -> f64 {
|
||||
let limit = raw / GRADIENT_GLOW_FADE;
|
||||
match fades {
|
||||
// A limit that isn't a number would panic each clamp it bounds
|
||||
true if limit.is_nan() => 0.,
|
||||
true => limit.clamp(0., 1.),
|
||||
false => 1.,
|
||||
}
|
||||
}
|
||||
|
||||
/// The mean of an `alpha` offset by `noise` times a grain uniform from -1 to 1, held from 0 to `limit`, which a pixel spanning a great many cells of grain averages to.
|
||||
pub fn expected_grained_alpha(alpha: f64, noise: f64, limit: f64) -> f64 {
|
||||
// Held at none or at the limit across the whole span of the grain, or without one
|
||||
if noise <= 0. || alpha + noise <= 0. || alpha - limit >= noise {
|
||||
return alpha.clamp(0., limit);
|
||||
}
|
||||
|
||||
// Each end the span reaches past moves the mean by the triangle held there over the span, which is no larger than the noise
|
||||
let below = (noise - alpha).max(0.);
|
||||
let above = (alpha - limit + noise).max(0.);
|
||||
alpha + below * (below / (4. * noise)) - above * (above / (4. * noise))
|
||||
}
|
||||
|
||||
/// How many grain values, spread evenly from -1 to 1, a jittered gradient glow averages its expected color over, enough to follow a smooth gradient within a level.
|
||||
pub const JITTER_EXPECTATION_SAMPLES: usize = 32;
|
||||
|
||||
/// How many evenly spaced samples of a glow's or outline's gradient the renderers look its colors up in, enough to follow it within a level.
|
||||
pub const GRADIENT_TABLE_SIZE: usize = 256;
|
||||
|
||||
@@ -640,11 +667,11 @@ impl GlowFill {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the fill paints nothing anywhere.
|
||||
pub fn is_invisible(&self) -> bool {
|
||||
/// Whether the fill paints nothing anywhere, even with a glow's `noise` percentage, which raises a transparent gradient's alpha (but not its opacity or a solid color's).
|
||||
pub fn is_invisible(&self, noise: f64) -> bool {
|
||||
match self {
|
||||
Self::Solid(color) => color.a() <= 0.,
|
||||
Self::Gradient { visible, opacity, .. } => !visible || *opacity <= 0.,
|
||||
Self::Gradient { visible, opacity, .. } => (!visible && noise == 0.) || *opacity <= 0.,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -655,17 +682,77 @@ impl GlowFill {
|
||||
Some((samples, *opacity))
|
||||
}
|
||||
|
||||
/// How much each sample of a glow's grain offsets its alpha and moves its gradient's color, from its `noise` and `jitter` percentages, or `None` if the grain changes nothing.
|
||||
pub fn grain_amounts(&self, noise: f64, jitter: f64) -> Option<[f64; 2]> {
|
||||
// Only a gradient has colors to move
|
||||
let jitter = if matches!(self, Self::Gradient { .. }) { jitter } else { 0. };
|
||||
let amounts = [noise / 100., jitter / 100.];
|
||||
|
||||
(amounts != [0.; 2]).then_some(amounts)
|
||||
}
|
||||
|
||||
/// The color with its alpha that a glow paints where its `strength` is, after its range and contour, given its `raw` strength before them.
|
||||
/// For PSD interop, a gradient's own alpha is the glow's, which an outer glow (if `fades`) fades out by as its raw strength nears none.
|
||||
/// For PSD interop, a gradient's own alpha is the glow's, held under [`glow_alpha_limit`] if the glow `fades` (as an outer one filled with a gradient or noise does).
|
||||
pub fn color_at(&self, strength: f64, raw: f64, fades: bool) -> Color {
|
||||
match self {
|
||||
Self::Solid(color) => color.with_alpha(color.a() * strength as f32),
|
||||
Self::Gradient { evaluator, opacity, .. } => {
|
||||
let color = evaluator.evaluate(1. - strength);
|
||||
let fade = if fades { (raw / GRADIENT_GLOW_FADE).min(1.) } else { 1. };
|
||||
color.with_alpha(color.a().min(fade as f32) * opacity)
|
||||
self.grained_color_at(strength, raw, fades, [0.; 2], &[0.], 1.)
|
||||
}
|
||||
|
||||
/// The color with its alpha that a glow roughened by grain paints where its `strength` is, as [`Self::color_at`] describes, from the grain's `samples` across the pixel, each from -1 to 1.
|
||||
/// For PSD interop, each sample adds the noise of `amounts` times itself to the alpha before it's held, and moves a gradient's color (but not its alpha) the jitter times itself toward its start.
|
||||
/// The pixel averages its samples, with their color and alpha's deviation from their expected values scaled by `deviation_scale`, for a pixel spanning more grain than it samples.
|
||||
pub fn grained_color_at(&self, strength: f64, raw: f64, fades: bool, [noise, jitter]: [f64; 2], samples: &[f64], deviation_scale: f64) -> Color {
|
||||
let limit = glow_alpha_limit(raw, fades);
|
||||
let (clean, opacity) = match self {
|
||||
Self::Solid(color) => (color.with_alpha(strength as f32), color.a()),
|
||||
Self::Gradient { evaluator, opacity, .. } => (evaluator.evaluate(1. - strength), *opacity),
|
||||
};
|
||||
let alpha = clean.a() as f64;
|
||||
|
||||
// The sums over some grain of each sample's alpha, and of its gamma-encoded straight color weighted by that
|
||||
let sums = |grains: &[f64]| {
|
||||
let (mut alphas, mut colors) = (0., [0.; 3]);
|
||||
for &grain in grains {
|
||||
let sample_alpha = (alpha + noise * grain).clamp(0., limit);
|
||||
let color = match self {
|
||||
Self::Gradient { evaluator, .. } if jitter != 0. => evaluator.evaluate((1. - strength - jitter * grain).clamp(0., 1.)),
|
||||
_ => clean,
|
||||
};
|
||||
let [red, green, blue, _] = color.to_gamma_srgb_channels();
|
||||
for (sum, channel) in colors.iter_mut().zip([red, green, blue]) {
|
||||
*sum += channel as f64 * sample_alpha;
|
||||
}
|
||||
alphas += sample_alpha;
|
||||
}
|
||||
(alphas, colors)
|
||||
};
|
||||
let (alphas, colors) = sums(samples);
|
||||
let count = samples.len().max(1) as f64;
|
||||
|
||||
let expected = expected_grained_alpha(alpha, noise, limit);
|
||||
let pixel_alpha = (expected + (alphas / count - expected) * deviation_scale).clamp(0., limit);
|
||||
|
||||
// The samples' color, and for a pixel spanning more grain than it samples, a jittered color expected over evenly spread grain, each weighted by its share of the pixel's alpha
|
||||
let (mut weight, mut weighted) = (alphas / count * deviation_scale, colors.map(|channel| channel / count * deviation_scale));
|
||||
if jitter != 0. && deviation_scale < 1. {
|
||||
let evenly: [f64; JITTER_EXPECTATION_SAMPLES] = std::array::from_fn(|index| 2. * (index as f64 + 0.5) / JITTER_EXPECTATION_SAMPLES as f64 - 1.);
|
||||
let (expected_alphas, expected_colors) = sums(&evenly);
|
||||
if expected_alphas > 0. {
|
||||
let expected_weight = expected * (1. - deviation_scale);
|
||||
weight += expected_weight;
|
||||
for (sum, channel) in weighted.iter_mut().zip(expected_colors) {
|
||||
*sum += channel / expected_alphas * expected_weight;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let [red, green, blue] = match weight > 0. {
|
||||
true => weighted.map(|channel| (channel / weight) as f32),
|
||||
false => {
|
||||
let [red, green, blue, _] = clean.to_gamma_srgb_channels();
|
||||
[red, green, blue]
|
||||
}
|
||||
};
|
||||
Color::from_gamma_srgb_channels(red, green, blue, pixel_alpha as f32 * opacity)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,7 +802,8 @@ impl<'a> OutlineFill<'a> {
|
||||
pub fn is_invisible(&self) -> bool {
|
||||
match self {
|
||||
Self::Solid(color) => color.a() <= 0.,
|
||||
Self::ContourGradient(gradient) => gradient.is_invisible(),
|
||||
// An outline has no grain
|
||||
Self::ContourGradient(gradient) => gradient.is_invisible(0.),
|
||||
Self::Drawn(_) => false,
|
||||
}
|
||||
}
|
||||
@@ -856,6 +944,12 @@ pub enum EffectOperation {
|
||||
/// The percentage of the glow's strength it reaches full opacity at.
|
||||
range: f64,
|
||||
contour: TransferCurve,
|
||||
/// The percentage of full opacity a random grain fixed to the content adds to or takes from the glow's opacity.
|
||||
noise: f64,
|
||||
/// The percentage of a gradient's length the same grain moves each pixel's color along it, leaving its opacity as it is.
|
||||
jitter: f64,
|
||||
/// The random variation of the grain. The same seed always gives the same grain.
|
||||
seed: i64,
|
||||
},
|
||||
InnerGlow {
|
||||
/// A solid color with the glow's opacity, or a gradient running from the content's edge inward (or from its center outward).
|
||||
@@ -869,6 +963,12 @@ pub enum EffectOperation {
|
||||
size: f64,
|
||||
range: f64,
|
||||
contour: TransferCurve,
|
||||
/// The percentage of full opacity a random grain fixed to the content adds to or takes from the glow's opacity.
|
||||
noise: f64,
|
||||
/// The percentage of a gradient's length the same grain moves each pixel's color along it, leaving its opacity as it is.
|
||||
jitter: f64,
|
||||
/// The random variation of the grain. The same seed always gives the same grain.
|
||||
seed: i64,
|
||||
},
|
||||
Satin {
|
||||
color: Color,
|
||||
@@ -1217,7 +1317,7 @@ impl EffectOperation {
|
||||
match self {
|
||||
Self::Blur { radius, .. } => *radius <= 0.,
|
||||
Self::DropShadow { color, .. } | Self::InnerShadow { color, .. } | Self::Satin { color, .. } => color.a() <= 0.,
|
||||
Self::OuterGlow { color, .. } | Self::InnerGlow { color, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible()),
|
||||
Self::OuterGlow { color, noise, .. } | Self::InnerGlow { color, noise, .. } => GlowFill::of(color).is_none_or(|fill| fill.is_invisible(*noise)),
|
||||
Self::Outline { paint, weight, contour_gradient, .. } => *weight <= 0. || OutlineFill::of(paint, *contour_gradient).is_none_or(|fill| fill.is_invisible()),
|
||||
// A gloss contour shades even flat ground, so a bevel without slopes still draws it
|
||||
Self::BevelAndEmboss {
|
||||
@@ -1423,8 +1523,12 @@ impl EffectOperation {
|
||||
} => {
|
||||
[angle, distance, spread, size].into_iter().for_each(finite);
|
||||
}
|
||||
Self::OuterGlow { spread, size, range, .. } => [spread, size, range].into_iter().for_each(finite),
|
||||
Self::InnerGlow { choke, size, range, .. } => [choke, size, range].into_iter().for_each(finite),
|
||||
Self::OuterGlow {
|
||||
spread, size, range, noise, jitter, ..
|
||||
} => [spread, size, range, noise, jitter].into_iter().for_each(finite),
|
||||
Self::InnerGlow {
|
||||
choke, size, range, noise, jitter, ..
|
||||
} => [choke, size, range, noise, jitter].into_iter().for_each(finite),
|
||||
Self::Satin { angle, distance, size, .. } => [angle, distance, size].into_iter().for_each(finite),
|
||||
Self::Outline { weight, .. } => finite(weight),
|
||||
Self::BevelAndEmboss {
|
||||
@@ -1531,6 +1635,9 @@ impl EffectOperation {
|
||||
size: 0.,
|
||||
range: 0.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
},
|
||||
EffectKind::InnerGlow => Self::InnerGlow {
|
||||
color: Graphic::default(),
|
||||
@@ -1541,6 +1648,9 @@ impl EffectOperation {
|
||||
size: 0.,
|
||||
range: 0.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
},
|
||||
EffectKind::Satin => Self::Satin {
|
||||
color: Color::TRANSPARENT,
|
||||
@@ -1787,6 +1897,9 @@ impl EffectOperation {
|
||||
size,
|
||||
range,
|
||||
contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
} => {
|
||||
visitor.parameter("color", color, Graphic::from(glow_color));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::Screen);
|
||||
@@ -1795,6 +1908,9 @@ impl EffectOperation {
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("range", range, 50.);
|
||||
visitor.parameter("contour", contour, TransferCurve::default());
|
||||
visitor.parameter("noise", noise, 0.);
|
||||
visitor.parameter("jitter", jitter, 0.);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::InnerGlow {
|
||||
color,
|
||||
@@ -1805,6 +1921,9 @@ impl EffectOperation {
|
||||
size,
|
||||
range,
|
||||
contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
} => {
|
||||
visitor.parameter("color", color, Graphic::from(glow_color));
|
||||
visitor.parameter("blend_mode", blend_mode, BlendMode::Screen);
|
||||
@@ -1814,6 +1933,9 @@ impl EffectOperation {
|
||||
visitor.parameter("size", size, 5.);
|
||||
visitor.parameter("range", range, 50.);
|
||||
visitor.parameter("contour", contour, TransferCurve::default());
|
||||
visitor.parameter("noise", noise, 0.);
|
||||
visitor.parameter("jitter", jitter, 0.);
|
||||
visitor.parameter("seed", seed, 0);
|
||||
}
|
||||
Self::Satin {
|
||||
color,
|
||||
@@ -2098,6 +2220,9 @@ mod tests {
|
||||
size: 8.,
|
||||
range: 75.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 25.,
|
||||
jitter: 0.,
|
||||
seed: 7,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: Graphic::from(Color::GREEN),
|
||||
@@ -2108,6 +2233,9 @@ mod tests {
|
||||
size: 3.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 60.,
|
||||
seed: 0,
|
||||
},
|
||||
EffectOperation::Satin {
|
||||
color: Color::BLACK,
|
||||
@@ -2408,6 +2536,140 @@ mod tests {
|
||||
assert_eq!((distance, spread, size), (0., 3., 0.));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_glows_noise_and_jitter_that_arent_finite_decode_as_zero() {
|
||||
let row = Effect::new(&EffectOperation::InnerGlow {
|
||||
color: Graphic::from(Color::BLACK),
|
||||
blend_mode: BlendMode::Screen,
|
||||
technique: GlowTechnique::Softer,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: f64::NAN,
|
||||
jitter: f64::INFINITY,
|
||||
seed: 3,
|
||||
});
|
||||
|
||||
let EffectOperation::InnerGlow { noise, jitter, seed, .. } = row.operation() else {
|
||||
panic!("the row changed kind")
|
||||
};
|
||||
assert_eq!((noise, jitter, seed), (0., 0., 3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fading_glow_paints_nothing_where_its_raw_strength_isnt_a_number() {
|
||||
let gradient = Graphic::from(Gradient::new([0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::from_rgbaf32_unchecked(1., position as f32, 0., 1.),
|
||||
})));
|
||||
let gradient = GlowFill::of(&gradient).expect("a gradient fills a glow");
|
||||
|
||||
for paint in [GlowFill::Solid(Color::BLACK), gradient] {
|
||||
assert_eq!(paint.color_at(0.5, f64::NAN, true).a(), 0.);
|
||||
assert_eq!(paint.grained_color_at(0.5, f64::NAN, true, [0.5, 0.5], &[0.25, -0.5], 1.).a(), 0.);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expected_grained_alpha_is_its_mean_over_the_grain() {
|
||||
// The held alpha averaged over grain spread evenly from -1 to 1
|
||||
let mean = |alpha: f64, noise: f64, limit: f64| {
|
||||
let count = 100_000;
|
||||
let held = |index: usize| (alpha + noise * (2. * (index as f64 + 0.5) / count as f64 - 1.)).clamp(0., limit);
|
||||
(0..count).map(held).sum::<f64>() / count as f64
|
||||
};
|
||||
|
||||
// Held at neither end, at none, at full, at both, under limits below the alpha and of none, and without noise
|
||||
let cases = [(0.5, 0.2, 1.), (0.1, 0.5, 1.), (1., 0.5, 1.), (0.5, 1., 1.), (0.8, 0.3, 0.4), (0.3, 0.6, 0.), (0.4, 0., 0.25)];
|
||||
for (alpha, noise, limit) in cases {
|
||||
let expected = expected_grained_alpha(alpha, noise, limit);
|
||||
assert!((expected - mean(alpha, noise, limit)).abs() < 1e-6, "alpha {alpha}, noise {noise}, limit {limit}: {expected}");
|
||||
}
|
||||
|
||||
// On a plateau, half the grain leaves it opaque and the rest fades it evenly by up to the noise
|
||||
assert_eq!(expected_grained_alpha(1., 0.5, 1.), 0.875);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_expected_grained_alpha_keeps_its_alpha_under_noise_too_slight_to_move_it() {
|
||||
// Held at full, at neither end, at the limit, and at none
|
||||
for (alpha, limit) in [(1., 1.), (0.5, 1.), (0.3, 0.3), (0., 1.)] {
|
||||
let expected = expected_grained_alpha(alpha, 1e-20, limit);
|
||||
assert!((expected - alpha).abs() < 1e-12, "alpha {alpha}, limit {limit}: {expected}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_raises_a_glow_of_a_transparent_gradient_but_not_one_of_no_opacity() {
|
||||
let transparent = |opacity: f64| {
|
||||
let stops = [0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::RED.with_alpha(0.),
|
||||
});
|
||||
Graphic::from(Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_OPACITY, opacity))
|
||||
};
|
||||
let glows = |color: Graphic, noise: f64| {
|
||||
let outer = EffectOperation::OuterGlow {
|
||||
color: color.clone(),
|
||||
blend_mode: BlendMode::Screen,
|
||||
technique: GlowTechnique::Softer,
|
||||
spread: 0.,
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let inner = EffectOperation::InnerGlow {
|
||||
color,
|
||||
blend_mode: BlendMode::Screen,
|
||||
technique: GlowTechnique::Softer,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
[outer, inner]
|
||||
};
|
||||
|
||||
for glow in glows(transparent(1.), 0.) {
|
||||
assert!(glow.changes_nothing(), "{glow:?} without noise");
|
||||
}
|
||||
for glow in glows(transparent(1.), 100.) {
|
||||
assert!(!glow.changes_nothing(), "{glow:?} with noise");
|
||||
}
|
||||
// The paint's opacity, and a solid color's alpha, fade the glow after the noise
|
||||
for glow in glows(transparent(0.), 100.).into_iter().chain(glows(Graphic::from(Color::TRANSPARENT), 100.)) {
|
||||
assert!(glow.changes_nothing(), "{glow:?} of no opacity");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jittered_gradient_glow_spanning_far_more_grain_than_it_samples_takes_its_expected_color() {
|
||||
use core_types::list::ATTR_GRADIENT_SPACE;
|
||||
use vector_types::gradient::GradientSpace;
|
||||
|
||||
// A gradient from black to white in gamma, so a color's gray is its place along it
|
||||
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let paint = Graphic::from(Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma));
|
||||
let paint = GlowFill::of(&paint).expect("a gradient fills a glow");
|
||||
|
||||
// Full strength jittered fully has a mean gray of a quarter, from which samples all moved to the end deviate the most
|
||||
let gray = |deviation_scale: f64| paint.grained_color_at(1., 1., false, [0., 1.], &[-1.; 16], deviation_scale).to_gamma_srgb_channels()[0];
|
||||
assert!((gray(1.) - 1.).abs() < 1e-3, "{}", gray(1.));
|
||||
assert!((gray(0.) - 0.25).abs() < 1e-3, "{}", gray(0.));
|
||||
assert!((gray(0.25) - (0.25 + 0.75 * 0.25)).abs() < 1e-3, "{}", gray(0.25));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadows_fall_away_from_the_light() {
|
||||
// Light from the upper left casts the shadow down and to the right
|
||||
|
||||
@@ -302,12 +302,21 @@ pub enum RandomField {
|
||||
NoiseAngles,
|
||||
/// Dissolve's two thresholds, for the opacity and for the coverage.
|
||||
Dissolve,
|
||||
/// The grain a glow's noise and jitter share.
|
||||
GlowGrain,
|
||||
}
|
||||
|
||||
impl RandomField {
|
||||
/// The value hashed with each cell for this field of the `seed`.
|
||||
pub fn seed(self, seed: i64) -> u32 {
|
||||
(seed as u32).wrapping_mul(4).wrapping_add(self as u32)
|
||||
// Each seed spreads across four fields, and all four are taken
|
||||
let offset = match self {
|
||||
Self::NoiseOffsets => 0,
|
||||
Self::NoiseAngles => 1,
|
||||
Self::Dissolve => 2,
|
||||
Self::GlowGrain => 3,
|
||||
};
|
||||
(seed as u32).wrapping_mul(4).wrapping_add(offset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -481,7 +481,7 @@ fn unit_interval(hash: u32) -> f32 {
|
||||
}
|
||||
|
||||
/// The three random values one field of the `seed` holds at a cell of the effect space.
|
||||
fn field_values(cell: IVec2, seed: u32) -> [f32; 3] {
|
||||
pub(crate) fn field_values(cell: IVec2, seed: u32) -> [f32; 3] {
|
||||
pcg3d([cell.x as u32, cell.y as u32, seed]).map(unit_interval)
|
||||
}
|
||||
|
||||
|
||||
@@ -200,8 +200,10 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
// Delete this baking once its callers read back the GPU's renders, which are exact.
|
||||
let pixels_per_length = spans_along_axes(effect_to_pixels);
|
||||
|
||||
// Displacements take the image's own rectangle in the effect space as their frame, which moves with it
|
||||
// The plane's pixels in the effect space, where random fields lie, with its origin at the content's (the image's corner past the margin)
|
||||
let pixels_to_effect = DAffine2::from_mat2(effect_to_pixels.inverse()) * DAffine2::from_translation(-DVec2::new(margin_x as f64, margin_y as f64));
|
||||
let effect_to_plane = DAffine2::from_translation(DVec2::new(margin_x as f64, margin_y as f64)) * DAffine2::from_mat2(effect_to_pixels);
|
||||
// Displacements take the image's own rectangle in the effect space as their frame, which moves with it
|
||||
let frame = EffectFrame::new(DAffine2::from_mat2(effect_to_pixels.inverse()) * DAffine2::from_scale(size), effect_to_plane);
|
||||
|
||||
// A layered effect's coverages become pieces, which the content knocks out once its layer is drawn, and a flattened one is knocked out by the faded content now
|
||||
@@ -281,12 +283,17 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
size,
|
||||
range,
|
||||
ref contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
..
|
||||
} => {
|
||||
let Some(paint) = GlowFill::of(color) else { continue };
|
||||
let raw = cast_strength(full.map(|[_, _, _, alpha]| alpha), size, spread, technique, pixels_per_length);
|
||||
let strength = shaped(raw.clone(), range, contour);
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, true), &full, knockout_fill);
|
||||
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect);
|
||||
let fades = matches!(paint, GlowFill::Gradient { .. }) || noise > 0.;
|
||||
let glow = knocked_out(glow_tint(&paint, &strength, &raw, fades, grain.as_ref()), &full, knockout_fill);
|
||||
place_beneath(&mut pieces, piece(0), &mut beneath, glow);
|
||||
}
|
||||
EffectOperation::InnerShadow {
|
||||
@@ -313,20 +320,32 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
size,
|
||||
range,
|
||||
ref contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
} => {
|
||||
let Some(paint) = GlowFill::of(color) else { continue };
|
||||
let outside = full.map(|[_, _, _, alpha]| 1. - alpha);
|
||||
|
||||
// For PSD interop, an edge glow's grain reaches a pixel past its size into the content, measured half a pixel farther so rounding can't decide it
|
||||
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, pixels_to_effect).map(|grain| match source {
|
||||
GlowSource::Edge => {
|
||||
let reach = (size + 1.) * (pixels_per_length.x * pixels_per_length.y).sqrt() + 0.5;
|
||||
grain.within(&outside.distances_to_silhouette(reach + 1.), reach as f32)
|
||||
}
|
||||
GlowSource::Center => grain,
|
||||
});
|
||||
|
||||
// A glow from the center is strongest where the glow from the edges is weakest
|
||||
let outside = full.map(|[_, _, _, alpha]| 1. - alpha);
|
||||
let mut strength = cast(outside, size, choke, technique, range, contour, pixels_per_length);
|
||||
if source == GlowSource::Center {
|
||||
strength = strength.map(|strength| 1. - strength);
|
||||
}
|
||||
|
||||
// An inner glow doesn't fade, since the content bounds it
|
||||
let glow = match paint {
|
||||
GlowFill::Solid(color) => tinted(&strength, color),
|
||||
GlowFill::Gradient { .. } => glow_tint(&paint, &strength, &strength, false),
|
||||
let glow = match (&paint, &grain) {
|
||||
(GlowFill::Solid(color), None) => tinted(&strength, *color),
|
||||
_ => glow_tint(&paint, &strength, &strength, false, grain.as_ref()),
|
||||
};
|
||||
place_within(&mut pieces, piece(0), &mut full, &mut filled, glow, blend_mode);
|
||||
}
|
||||
@@ -676,9 +695,6 @@ fn evaluate(raster: &Raster<CPU>, transform: DAffine2, effects: &Effects, fill:
|
||||
merge_beneath(&mut full, &mut filled, &mut beneath);
|
||||
// A filter sharpening the coverage fades the fill's result by the share of the full-strength coverage each pixel's fill left, as if the fill faded the result
|
||||
let shares = filled.as_ref().filter(|_| sharpens_coverage(operation)).map(|filled| crate::filter_kernels::fill_shares(&full, filled));
|
||||
|
||||
// The effect space's origin is the content's, at the image's corner past the margin
|
||||
let pixels_to_effect = DAffine2::from_mat2(effect_to_pixels.inverse()) * DAffine2::from_translation(-DVec2::new(margin_x as f64, margin_y as f64));
|
||||
// The fill fades the content after the filter, so the full-strength content decides which of the fill's pixels are visible
|
||||
let filtered_filled = filled.map(|filled| crate::filter_kernels::filter(filled, Some(&full), operation, pixels_to_effect));
|
||||
full = crate::filter_kernels::filter(full, None, operation, pixels_to_effect);
|
||||
@@ -839,12 +855,22 @@ fn shaped(strength: Plane<f32>, range: f64, contour: &TransferCurve) -> Plane<f3
|
||||
strength.map(|strength| shape_strength(strength as f64, range, &|value| contour.evaluate(value)) as f32)
|
||||
}
|
||||
|
||||
/// The premultiplied color a glow filled with `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them.
|
||||
/// An outer glow `fades` out with its raw strength when filled with a gradient.
|
||||
fn glow_tint(paint: &GlowFill, strength: &Plane<f32>, raw: &Plane<f32>, fades: bool) -> Plane<[f32; 4]> {
|
||||
strength
|
||||
.zip(raw, |strength, raw| [strength, raw, 0., 0.])
|
||||
.map(|[strength, raw, ..]| premultiplied_gamma_channels(paint.color_at(strength as f64, raw as f64, fades)))
|
||||
/// The premultiplied color a glow filled with `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them, held under its fade if it `fades`.
|
||||
/// A `grain` roughens it as [`GlowFill::grained_color_at`] describes, where it reaches. O(width × height × samples per pixel).
|
||||
fn glow_tint(paint: &GlowFill, strength: &Plane<f32>, raw: &Plane<f32>, fades: bool, grain: Option<&styles::GlowGrain>) -> Plane<[f32; 4]> {
|
||||
let mut tinted = Plane::<[f32; 4]>::new(strength.width, strength.height);
|
||||
fill_rows(&mut tinted.data, strength.width, |y, row| {
|
||||
for (x, pixel) in row.iter_mut().enumerate() {
|
||||
let index = y * strength.width + x;
|
||||
let (strength, raw) = (strength.data[index] as f64, raw.data[index] as f64);
|
||||
let color = match grain.and_then(|grain| Some((grain, grain.samples([x, y], index)?))) {
|
||||
Some((grain, (samples, count))) => paint.grained_color_at(strength, raw, fades, grain.amounts, &samples[..count], grain.sampling.deviation_scale),
|
||||
None => paint.color_at(strength, raw, fades),
|
||||
};
|
||||
*pixel = premultiplied_gamma_channels(color);
|
||||
}
|
||||
});
|
||||
tinted
|
||||
}
|
||||
|
||||
/// A silhouette's coverage tinted `color`.
|
||||
@@ -1817,6 +1843,194 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn glow_grain_is_fixed_to_the_effect_spaces_cells_and_samples_each_one_a_pixel_spans() {
|
||||
let paint = GlowFill::Solid(Color::BLACK);
|
||||
let grain = |seed, pixels_to_effect| styles::GlowGrain::new(&paint, 100., 0., seed, pixels_to_effect).expect("noise roughens the glow");
|
||||
let first = |grain: &styles::GlowGrain, x: usize, y: usize| grain.samples([x, y], 0).map_or(f64::NAN, |(samples, _)| samples[0]);
|
||||
|
||||
// A plane placed three cells right and five down holds the same grain at the same cells
|
||||
let (placed, moved) = (grain(0, DAffine2::IDENTITY), grain(0, DAffine2::from_translation(DVec2::new(3., 5.))));
|
||||
assert_eq!(first(&moved, 0, 0), first(&placed, 3, 5));
|
||||
assert_eq!(first(&moved, 2, 1), first(&placed, 5, 6));
|
||||
|
||||
// Uniform from -1 to 1, and another seed gives other grain
|
||||
let values: Vec<f64> = (0..64 * 64).map(|index| first(&placed, index % 64, index / 64)).collect();
|
||||
let deviation = (values.iter().map(|value| value * value).sum::<f64>() / values.len() as f64).sqrt();
|
||||
assert!((deviation * 3_f64.sqrt() - 1.).abs() < 0.03, "{deviation}");
|
||||
assert_ne!(first(&grain(1, DAffine2::IDENTITY), 0, 0), first(&placed, 0, 0));
|
||||
|
||||
// A pixel spanning four cells each way samples sixteen
|
||||
assert_eq!(grain(0, DAffine2::from_scale(DVec2::splat(4.))).samples([0, 0], 0).map(|(_, count)| count), Some(16));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_roughens_a_glows_opacity_by_its_amount_within_its_extent_at_any_zoom() {
|
||||
// A glow 10 wide around content 40 wide, rendered at `pixels` across the content
|
||||
let glowing = |noise: f64, pixels: u32| {
|
||||
let glow = EffectOperation::OuterGlow {
|
||||
color: Graphic::from(Color::BLACK),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 100.,
|
||||
size: 10.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let item = Item::new_from_element(Raster::new_cpu(Image::new(pixels, pixels, Color::WHITE)))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(40.)))
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([glow]));
|
||||
evaluate_raster_effects(item).element().clone()
|
||||
};
|
||||
// The mean opacity of the glow's solid plateau, beside the content, and the clean and noisy renders
|
||||
let plateau_mean = |pixels: u32| {
|
||||
let (clean, noisy) = (glowing(0., pixels), glowing(50., pixels));
|
||||
let width = clean.width as usize;
|
||||
let margin = (width - pixels as usize) / 2;
|
||||
let plateau: Vec<usize> = (0..clean.data.len())
|
||||
.filter(|&index| clean.data[index].a() > 0.999 && (index % width < margin || index % width >= width - margin))
|
||||
.collect();
|
||||
let mean = plateau.iter().map(|&index| noisy.data[index].a() as f64).sum::<f64>() / plateau.len() as f64;
|
||||
(mean, plateau.len(), clean, noisy)
|
||||
};
|
||||
|
||||
// On the plateau, about half the pixels stay opaque and the rest fade evenly by up to half
|
||||
let (mean, count, clean, noisy) = plateau_mean(40);
|
||||
assert!(count > 500 && (mean - 0.875).abs() < 0.01, "{mean} over {count} pixels");
|
||||
// Past the glow's reach, the noise adds nothing
|
||||
assert!((0..clean.data.len()).filter(|&index| clean.data[index].a() == 0.).all(|index| noisy.data[index].a() == 0.));
|
||||
|
||||
// Zoomed out to four document pixels a pixel, each pixel averages its samples' opacities, keeping the same mean
|
||||
let (mean, count, ..) = plateau_mean(10);
|
||||
assert!(count > 40 && (mean - 0.875).abs() < 0.02, "zoomed out, {mean} over {count} pixels");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inner_glows_grain_reaches_a_pixel_past_its_size_at_any_scale() {
|
||||
// An inner glow 6 deep in content 40 wide, at `scale` pixels per document pixel, its noise as strong as can be
|
||||
let glowing = |noise: f64, scale: u32| {
|
||||
let glow = EffectOperation::InnerGlow {
|
||||
color: Graphic::from(Color::BLACK),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 6.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(40 * scale, 40 * scale, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(40.)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(&glow));
|
||||
evaluate_raster_effects(item).element().clone()
|
||||
};
|
||||
|
||||
for scale in [1, 3] {
|
||||
let (clean, noisy) = (glowing(0., scale), glowing(100., scale));
|
||||
let width = clean.width as usize;
|
||||
let margin = (width - 40 * scale as usize) / 2;
|
||||
// How many pixels the grain changes in the middle of the column at a depth in document pixels from the left edge
|
||||
let ring = |depth: usize| {
|
||||
(10 * scale as usize..30 * scale as usize)
|
||||
.filter(|&offset| {
|
||||
let index = (margin + offset) * width + margin + depth * scale as usize + scale as usize / 2;
|
||||
clean.data[index] != noisy.data[index]
|
||||
})
|
||||
.count()
|
||||
};
|
||||
|
||||
// The ring a pixel past the size is grained, like within it, and the ring beyond isn't
|
||||
assert!(ring(6) > 0 && ring(3) > 0, "scale {scale}: rings {} and {}", ring(3), ring(6));
|
||||
assert_eq!(ring(7), 0, "scale {scale}: past the reach");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_jittered_glow_zoomed_far_out_matches_its_full_size_render_downsampled() {
|
||||
use core_types::list::ATTR_GRADIENT_SPACE;
|
||||
use vector_types::gradient::{GradientSpace, GradientStop};
|
||||
|
||||
// A full-strength glow from the center of content 512 wide, from black to white in gamma, with noise and jitter as strong as can be, at `pixels` across it
|
||||
let stops = [(0., Color::BLACK), (1., Color::WHITE)].map(|(position, color)| GradientStop { position, midpoint: 0.5, color });
|
||||
let paint = Graphic::from(Item::new_from_element(Gradient::new(stops)).with_attribute(ATTR_GRADIENT_SPACE, GradientSpace::RgbGamma));
|
||||
let glowing = |pixels: u32| {
|
||||
let glow = EffectOperation::InnerGlow {
|
||||
color: paint.clone(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Center,
|
||||
choke: 0.,
|
||||
size: 4.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 100.,
|
||||
jitter: 100.,
|
||||
seed: 0,
|
||||
};
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(pixels, pixels, Color::WHITE))).with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(512.)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(&glow));
|
||||
let raster = evaluate_raster_effects(item).element().clone();
|
||||
let margin = (raster.width - pixels) as usize / 2;
|
||||
move |x: usize, y: usize| raster.data[(margin + y) * raster.width as usize + margin + x].to_gamma_srgb_channels()
|
||||
};
|
||||
|
||||
// Each pixel 32 wide away from the content's edge, against the average of the 32 by 32 pixels at full size it spans
|
||||
let (full, zoomed_out) = (glowing(512), glowing(16));
|
||||
let (mut squared_differences, mut differences, mut count) = (0., 0., 0.);
|
||||
for (x, y) in (1..15).flat_map(|y| (1..15).map(move |x| (x, y))) {
|
||||
let downsampled = (0..32 * 32).map(|index| full(32 * x + index % 32, 32 * y + index / 32)[0] as f64).sum::<f64>() / (32 * 32) as f64;
|
||||
let difference = zoomed_out(x, y)[0] as f64 - downsampled;
|
||||
(squared_differences, differences, count) = (squared_differences + difference * difference, differences + difference, count + 1.);
|
||||
}
|
||||
|
||||
// Both deviate from the grain's mean by as little, so they differ about as much as that, and on average not at all
|
||||
let (deviation, mean) = ((squared_differences / count).sqrt() * 255., differences / count * 255.);
|
||||
assert!(deviation < 6., "zoomed out, the gray deviates from the downsample by {deviation} levels");
|
||||
assert!(mean.abs() < 1.5, "zoomed out, the gray is off by {mean} levels on average");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_shows_an_outer_glow_of_a_transparent_gradient() {
|
||||
use vector_types::gradient::GradientStop;
|
||||
|
||||
// A gradient transparent throughout, on a glow 10 wide around content 40 wide
|
||||
let stops = [0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::RED.with_alpha(0.),
|
||||
});
|
||||
let glowing = |noise: f64| {
|
||||
let glow = EffectOperation::OuterGlow {
|
||||
color: Graphic::from(Gradient::new(stops)),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 100.,
|
||||
size: 10.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let item = Item::new_from_element(Raster::new_cpu(Image::new(40, 40, Color::WHITE)))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_scale(DVec2::splat(40.)))
|
||||
.with_attribute(ATTR_EFFECTS, Effects::from_operations([glow]));
|
||||
evaluate_raster_effects(item).element().data.clone()
|
||||
};
|
||||
|
||||
// The grain raises about half the glow's pixels into view, each in the gradient's color
|
||||
let shown = |pixels: &[Color]| pixels.iter().filter(|pixel| pixel.a() > 0. && pixel.a() < 1.).copied().collect::<Vec<_>>();
|
||||
let noisy = shown(&glowing(100.));
|
||||
assert!(shown(&glowing(0.)).is_empty());
|
||||
assert!(noisy.len() > 1000, "{} pixels show", noisy.len());
|
||||
assert!(noisy.iter().all(|pixel| pixel.r() > 0.99 && pixel.g() < 0.01), "{:?}", noisy.first());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inner_shadow_of_only_choke_shades_an_opaque_raster() {
|
||||
use graphic_types::{Effect, stamp_effect};
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
//! The CPU steps of the layer styles' finer options: the outline's paints, and the bevel's contour and texture.
|
||||
//! The CPU steps of the layer styles' finer options: the outline's paints, the bevel's contour and texture, and the glows' grain.
|
||||
|
||||
use crate::effect_kernels::{NEGLIGIBLE_LENGTH, Plane};
|
||||
use crate::filter_kernels::field_values;
|
||||
use core_types::Color;
|
||||
use core_types::transfer_curve::{TransferCurve, TransferCurveEvaluator};
|
||||
use glam::{DVec2, DVec3};
|
||||
use glam::{DAffine2, DVec2, DVec3};
|
||||
use graphic_types::effects::{
|
||||
ANTIALIASED_CONTOUR_OFFSETS, BEVEL_FOOT_FADE, BevelStyle, GRADIENT_TABLE_SIZE, GlowFill, bevel_lighting, bevel_lit, contour_end_slopes, contour_gradient_position, extended_contour,
|
||||
slope_contour_input, slope_contour_reshapes, texture_gray,
|
||||
};
|
||||
use graphic_types::filters::{FieldSampling, MAX_FIELD_SAMPLES_PER_AXIS, RandomField};
|
||||
use raster_types::parallel_rows::fill_rows;
|
||||
|
||||
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
||||
@@ -174,3 +176,53 @@ pub(super) fn bevel_shading(height: &Plane<f32>, surface: &BevelSurface, rise: f
|
||||
pub(super) fn foot_faded(amounts: [Plane<f32>; 2], height: &Plane<f32>) -> [Plane<f32>; 2] {
|
||||
amounts.map(|amount| amount.zip(height, |amount, height| amount.min((height + 0.5) / BEVEL_FOOT_FADE as f32)))
|
||||
}
|
||||
|
||||
/// The most samples of grain a pixel takes.
|
||||
const MAX_GRAIN_SAMPLES: usize = (MAX_FIELD_SAMPLES_PER_AXIS * MAX_FIELD_SAMPLES_PER_AXIS) as usize;
|
||||
|
||||
/// The random grain roughening a glow, as [`GlowFill::grained_color_at`] takes it.
|
||||
pub(super) struct GlowGrain {
|
||||
/// Where each pixel samples the grain, fixed to the cells of the effect space.
|
||||
pub sampling: FieldSampling,
|
||||
/// The field of the grain that the glow's seed gives.
|
||||
field: u32,
|
||||
/// How much each sample offsets the alpha (the noise) and moves a gradient's color (the jitter).
|
||||
pub amounts: [f64; 2],
|
||||
/// Which pixels the grain reaches, if not all of them.
|
||||
reaches: Option<Vec<bool>>,
|
||||
}
|
||||
|
||||
impl GlowGrain {
|
||||
/// The grain roughening a glow filled with `paint` by the `noise` and `jitter` percentages with its `seed`, on a plane that `plane_to_effect` places in the effect space, or `None` if it changes nothing.
|
||||
pub fn new(paint: &GlowFill, noise: f64, jitter: f64, seed: i64, plane_to_effect: DAffine2) -> Option<Self> {
|
||||
let amounts = paint.grain_amounts(noise, jitter)?;
|
||||
|
||||
Some(Self {
|
||||
sampling: FieldSampling::new(plane_to_effect),
|
||||
field: RandomField::GlowGrain.seed(seed),
|
||||
amounts,
|
||||
reaches: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The grain kept to the pixels no farther than `reach` from the content's edge, given each pixel's `distances` to it as [`Plane::distances_to_silhouette`] measures them.
|
||||
pub fn within(self, distances: &Plane<f32>, reach: f32) -> Self {
|
||||
let reaches = Some(distances.data.iter().map(|&distance| distance <= reach).collect());
|
||||
Self { reaches, ..self }
|
||||
}
|
||||
|
||||
/// The grain's samples from -1 to 1 at the pixel in column and row `pixel` (`index` in its plane), as many as the sampling takes, or `None` past its reach.
|
||||
pub fn samples(&self, pixel: [usize; 2], index: usize) -> Option<([f64; MAX_GRAIN_SAMPLES], usize)> {
|
||||
if self.reaches.as_ref().is_some_and(|reaches| !reaches[index]) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let mut samples = [0.; MAX_GRAIN_SAMPLES];
|
||||
let mut count = 0;
|
||||
for cell in self.sampling.sample_cells(pixel).take(MAX_GRAIN_SAMPLES) {
|
||||
samples[count] = 2. * field_values(cell, self.field)[0] as f64 - 1.;
|
||||
count += 1;
|
||||
}
|
||||
Some((samples, count))
|
||||
}
|
||||
}
|
||||
@@ -1603,10 +1603,10 @@ fn write_svg_effects_filter_on_lattice(
|
||||
.iter()
|
||||
.any(|part| matches!(part, LayerPart::Piece(piece) if piece.place == PiecePlace::IntoContent { over: true }));
|
||||
|
||||
// A glow's solid color tints its maps, a gradient's maps come tinted (so it has no color), and a fill that paints nothing has neither
|
||||
let glow_color = |paint: &Graphic| match GlowFill::of(paint)? {
|
||||
// A glow's solid color tints its maps, a gradient's maps come tinted (so it has no color), and a fill that paints nothing (even with the glow's `noise`) has neither
|
||||
let glow_color = |paint: &Graphic, noise: f64| match GlowFill::of(paint)? {
|
||||
GlowFill::Solid(color) => Some(Some(color)),
|
||||
fill => (!fill.is_invisible()).then_some(None),
|
||||
fill => (!fill.is_invisible(noise)).then_some(None),
|
||||
};
|
||||
|
||||
// The coverage planes that the GPU works out for an effect, each shading within the content or beneath it, in a color (or none, for a map already tinted) mixed by a blend mode
|
||||
@@ -1691,11 +1691,11 @@ fn write_svg_effects_filter_on_lattice(
|
||||
}
|
||||
EffectOperation::DropShadow { color, .. } => shade(BENEATH, Some(color), BlendMode::Normal),
|
||||
EffectOperation::InnerShadow { color, blend_mode, .. } | EffectOperation::Satin { color, blend_mode, .. } => shade(WITHIN, Some(color), blend_mode),
|
||||
EffectOperation::OuterGlow { color, .. } => match glow_color(&color) {
|
||||
EffectOperation::OuterGlow { color, noise, .. } => match glow_color(&color, noise) {
|
||||
Some(color) => shade(BENEATH, color, BlendMode::Normal),
|
||||
None => continue,
|
||||
},
|
||||
EffectOperation::InnerGlow { color, blend_mode, .. } => match glow_color(&color) {
|
||||
EffectOperation::InnerGlow { color, blend_mode, noise, .. } => match glow_color(&color, noise) {
|
||||
Some(color) => shade(WITHIN, color, blend_mode),
|
||||
None => continue,
|
||||
},
|
||||
@@ -6827,6 +6827,33 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_effects_filters_map_glows_of_a_transparent_gradient_only_with_noise() {
|
||||
use graphic_types::{EffectKind, EffectOperation};
|
||||
use vector_types::GradientStop;
|
||||
|
||||
// The planes of the maps the GPU renders for a glow of a gradient transparent throughout, roughened by `noise`
|
||||
let planes = |kind, noise| {
|
||||
let stops = [0., 1.].map(|position| GradientStop {
|
||||
position,
|
||||
midpoint: 0.5,
|
||||
color: Color::RED.with_alpha(0.),
|
||||
});
|
||||
let mut glow = EffectOperation::default_for(kind);
|
||||
if let EffectOperation::OuterGlow { color, noise: amount, .. } | EffectOperation::InnerGlow { color, noise: amount, .. } = &mut glow {
|
||||
(*color, *amount) = (Graphic::from(Gradient::new(stops)), noise);
|
||||
}
|
||||
let filters = write_filters(&mut String::new(), &Effects::from_operations([glow]), 1., [DVec2::ZERO, DVec2::splat(10.)], 0, &[]);
|
||||
filters.iter().flat_map(|filter| filter.maps.iter().map(|map| map.capture.plane)).collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
// The noise's grain raises the gradient's alpha where nothing else does
|
||||
for kind in [EffectKind::OuterGlow, EffectKind::InnerGlow] {
|
||||
assert!(planes(kind, 0.).is_empty(), "{kind:?} without noise");
|
||||
assert_eq!(planes(kind, 100.), [0], "{kind:?} with noise");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn svg_effects_filters_express_adjustments_where_svg_can() {
|
||||
use graphic_types::adjustment::DesaturateMethod;
|
||||
|
||||
@@ -428,9 +428,13 @@ impl EffectPasses {
|
||||
size,
|
||||
range,
|
||||
ref contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
..
|
||||
} => {
|
||||
let Some(paint) = GlowFill::of(color) else { continue };
|
||||
let grain = styles::GlowGrain::new(&paint, noise, jitter, seed, effect_to_pixels);
|
||||
let full_content = full.as_ref().unwrap_or(content);
|
||||
let silhouette = recorder.silhouette(full_content, DVec2::ZERO, false);
|
||||
let raw = recorder.cast_strength(silhouette, size, spread, technique, length_scale);
|
||||
@@ -439,8 +443,12 @@ impl EffectPasses {
|
||||
|
||||
// A solid color tints the coverage as it stacks, but a gradient paints each pixel its own color, which a map captures whole
|
||||
let (coverage, color) = match paint {
|
||||
GlowFill::Solid(color) => (recorder.scale(strength, 1.), Some(color)),
|
||||
GlowFill::Gradient { .. } => match recorder.gradient_glow_tint(&paint, strength, &raw, true) {
|
||||
// For PSD interop, a noisy solid glow fades out like a gradient one
|
||||
GlowFill::Solid(color) => match &grain {
|
||||
Some(grain) => (recorder.grained_glow_strength(strength, &raw, true, grain), Some(color)),
|
||||
None => (recorder.scale(strength, 1.), Some(color)),
|
||||
},
|
||||
GlowFill::Gradient { .. } => match recorder.gradient_glow_tint(&paint, strength, &raw, true, grain.as_ref()) {
|
||||
Some(tinted) => (tinted, None),
|
||||
None => continue,
|
||||
},
|
||||
@@ -475,27 +483,46 @@ impl EffectPasses {
|
||||
size,
|
||||
range,
|
||||
ref contour,
|
||||
noise,
|
||||
jitter,
|
||||
seed,
|
||||
} => {
|
||||
let Some(paint) = GlowFill::of(color) else { continue };
|
||||
let mut grain = styles::GlowGrain::new(&paint, noise, jitter, seed, effect_to_pixels);
|
||||
let outside = recorder.silhouette(full.as_ref().unwrap_or(content), DVec2::ZERO, true);
|
||||
|
||||
// For PSD interop, an edge glow's grain reaches a pixel past its size into the content, measured half a pixel farther so rounding can't decide it
|
||||
let distances = match (&mut grain, source) {
|
||||
(Some(grain), GlowSource::Edge) => {
|
||||
let reach = (size + 1.) * length_scale + 0.5;
|
||||
grain.reach = Some(reach);
|
||||
Some(recorder.distances(&outside, reach + 1., Seeds::Covered))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// A glow from the center is strongest where the glow from the edges is weakest
|
||||
let outside = recorder.silhouette(full.as_ref().unwrap_or(content), DVec2::ZERO, true);
|
||||
let mut strength = recorder.cast(outside, size, choke, technique, range, contour, length_scale);
|
||||
if source == GlowSource::Center {
|
||||
let inverted = recorder.run("invert_coverage", COVERAGE_FORMAT, recorder.size, &strength, None, None, Parameters::default());
|
||||
recorder.replace(&mut strength, inverted);
|
||||
}
|
||||
|
||||
// A gradient paints each pixel its own color, which a map captures whole, and doesn't fade since the content bounds it
|
||||
// A gradient paints each pixel its own color, which a map captures whole, and an inner glow doesn't fade, since the content bounds it
|
||||
let destination = layered.then_some((&mut pieces, piece(0)));
|
||||
match paint {
|
||||
GlowFill::Solid(color) => {
|
||||
if let Some(grain) = &grain {
|
||||
let grained = recorder.grained_glow_strength(&strength, distances.as_ref().unwrap_or(&strength), false, grain);
|
||||
recorder.replace(&mut strength, grained);
|
||||
}
|
||||
distances.into_iter().for_each(|texture| recorder.textures.release(texture));
|
||||
capture_plane(&mut recorder, 0, &strength, false);
|
||||
recorder.place_within(destination, content, &mut full, &mut filled, strength, Some(color), blend_mode);
|
||||
}
|
||||
GlowFill::Gradient { .. } => {
|
||||
let tinted = recorder.gradient_glow_tint(&paint, &strength, &strength, false);
|
||||
recorder.textures.release(strength);
|
||||
let tinted = recorder.gradient_glow_tint(&paint, &strength, distances.as_ref().unwrap_or(&strength), false, grain.as_ref());
|
||||
[Some(strength), distances].into_iter().flatten().for_each(|texture| recorder.textures.release(texture));
|
||||
let Some(tinted) = tinted else { continue };
|
||||
capture_plane(&mut recorder, 0, &tinted, true);
|
||||
recorder.place_within(destination, content, &mut full, &mut filled, tinted, None, blend_mode);
|
||||
@@ -1460,17 +1487,20 @@ impl PassRecorder<'_> {
|
||||
}
|
||||
|
||||
/// The premultiplied color a glow filled with the gradient in `paint` paints at each pixel, from its `strength` after range and contour and its `raw` strength before them.
|
||||
/// An outer glow `fades` out with its raw strength, matching the CPU's `glow_tint`.
|
||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, raw: &wgpu::Texture, fades: bool) -> Option<wgpu::Texture> {
|
||||
/// An outer glow `fades` out with its raw strength (the `content`), and a `grain` roughens it, kept within the reach that an inner glow's distances (then the `content`) give.
|
||||
/// Matches the CPU's `glow_tint`.
|
||||
fn gradient_glow_tint(&mut self, paint: &GlowFill, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: Option<&styles::GlowGrain>) -> Option<wgpu::Texture> {
|
||||
let (samples, opacity) = paint.gradient_samples(GRADIENT_SAMPLES as usize)?;
|
||||
let samples: Vec<half::f16> = samples.into_iter().flatten().map(half::f16::from_f32).collect();
|
||||
let samples = self.row_texture("vello_effects_gradient", wgpu::TextureFormat::Rgba16Float, GRADIENT_SAMPLES, bytemuck::cast_slice(&samples));
|
||||
|
||||
let parameters = Parameters {
|
||||
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, 0.],
|
||||
values: [if fades { 1. } else { 0. }, GRADIENT_GLOW_FADE as f32, opacity, grain.map_or(0., |grain| grain.amounts[0] as f32)],
|
||||
amount: grain.map_or(0., |grain| grain.amounts[1] as f32),
|
||||
taps: grain.map_or([[0.; 4]; PARAMETER_TAPS], styles::GlowGrain::taps),
|
||||
..Default::default()
|
||||
};
|
||||
Some(self.run("gradient_glow_tint", WORKING_FORMAT, self.size, strength, Some(&samples), Some(raw), parameters))
|
||||
Some(self.run("gradient_glow_tint", WORKING_FORMAT, self.size, strength, Some(&samples), Some(content), parameters))
|
||||
}
|
||||
|
||||
/// Each pixel's distance from the `seeds` in `seed_values`, matching the CPU's distance passes, or far past `reach` pixels.
|
||||
|
||||
@@ -216,24 +216,70 @@ fn shape_strength(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f
|
||||
}
|
||||
|
||||
// A glow's premultiplied color from its strength after range and contour (`source`), as the gradient `secondary` holds in a row of straight colors from its start to its end.
|
||||
// Its alpha is the gradient's, faded with `values.x` 1 as the `content` strength before range and contour falls below `values.y`, then by the opacity `values.z`, matching `GlowFill::color_at`.
|
||||
// Its alpha is the gradient's, held under 1, or with `values.x` 1 under the `content` strength before range and contour over `values.y`, then faded by the opacity `values.z`.
|
||||
// Where it's grained, each sample adds `values.w` of itself to the alpha first and moves the color (but not the alpha) `amount` of itself toward the gradient's start, and they average.
|
||||
// Matches `GlowFill::grained_color_at`.
|
||||
@fragment
|
||||
fn gradient_glow_tint(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let strength = textureLoad(source, pixel, 0).r;
|
||||
|
||||
let samples = f32(textureDimensions(secondary).x);
|
||||
let uv = vec2<f32>(((1. - strength) * (samples - 1.) + 0.5) / samples, 0.5);
|
||||
let color = textureSampleLevel(secondary, linear_sampler, uv, 0.);
|
||||
|
||||
var alpha = color.a;
|
||||
let place = 1. - textureLoad(source, pixel, 0).r;
|
||||
let clean = gradient_glow_sample(place);
|
||||
var limit = 1.;
|
||||
if parameters.values.x > 0.5 {
|
||||
alpha = min(alpha, textureLoad(content, pixel, 0).r / parameters.values.y);
|
||||
limit = clamp(textureLoad(content, pixel, 0).r / parameters.values.y, 0., 1.);
|
||||
}
|
||||
|
||||
var alpha = clamp(clean.a, 0., limit);
|
||||
var color = clean.rgb;
|
||||
if (parameters.values.w != 0. || parameters.amount != 0.) && grain_reaches(pixel) {
|
||||
let counts = sample_counts();
|
||||
var sums = vec4<f32>(0.);
|
||||
for (var row = 0u; row < counts.y; row++) {
|
||||
for (var column = 0u; column < counts.x; column++) {
|
||||
sums += gradient_glow_grained(place, clean, limit, glow_grain_sample(position.xy, column, row));
|
||||
}
|
||||
}
|
||||
let expected = expected_grained_alpha(clean.a, parameters.values.w, limit);
|
||||
alpha = grained_alpha(sums.a, expected, limit);
|
||||
|
||||
// The samples' color, and for a texel spanning more grain than it samples, a jittered color expected over `taps[5].w` evenly spread grain values, each weighted by its share of the texel's alpha
|
||||
let deviation_scale = parameters.taps[5].x;
|
||||
var weighted = sums / f32(counts.x * counts.y) * deviation_scale;
|
||||
if parameters.amount != 0. && deviation_scale < 1. {
|
||||
let evenly = u32(parameters.taps[5].w);
|
||||
var expected_sums = vec4<f32>(0.);
|
||||
for (var index = 0u; index < evenly; index++) {
|
||||
expected_sums += gradient_glow_grained(place, clean, limit, 2. * (f32(index) + 0.5) / f32(evenly) - 1.);
|
||||
}
|
||||
if expected_sums.a > 0. {
|
||||
weighted += vec4<f32>(expected_sums.rgb / expected_sums.a, 1.) * expected * (1. - deviation_scale);
|
||||
}
|
||||
}
|
||||
if weighted.a > 0. {
|
||||
color = weighted.rgb / weighted.a;
|
||||
}
|
||||
}
|
||||
|
||||
alpha *= parameters.values.z;
|
||||
return vec4<f32>(color.rgb * alpha, alpha);
|
||||
return vec4<f32>(color * alpha, alpha);
|
||||
}
|
||||
|
||||
// A grained gradient glow's sample of the `grain`, from -1 to 1, as its straight color weighted by its alpha, and that alpha.
|
||||
// The grain adds `values.w` of itself to the `clean` alpha, held under `limit`, and moves the color `amount` of itself from its `place` toward the gradient's start.
|
||||
fn gradient_glow_grained(place: f32, clean: vec4<f32>, limit: f32, grain: f32) -> vec4<f32> {
|
||||
let sample_alpha = clamp(clean.a + parameters.values.w * grain, 0., limit);
|
||||
var sample_color = clean.rgb;
|
||||
if parameters.amount != 0. {
|
||||
sample_color = gradient_glow_sample(clamp(place - parameters.amount * grain, 0., 1.)).rgb;
|
||||
}
|
||||
return vec4<f32>(sample_color * sample_alpha, sample_alpha);
|
||||
}
|
||||
|
||||
// The straight color of the gradient `secondary` holds in a row at a place from 0 to 1 along it, interpolated between its samples
|
||||
fn gradient_glow_sample(place: f32) -> vec4<f32> {
|
||||
let samples = f32(textureDimensions(secondary).x);
|
||||
return textureSampleLevel(secondary, linear_sampler, vec2<f32>((place * (samples - 1.) + 0.5) / samples, 0.5), 0.);
|
||||
}
|
||||
|
||||
// The coverage of where a silhouette doesn't reach, which turns an inner glow from the edges into one from the center
|
||||
@fragment
|
||||
|
||||
@@ -31,7 +31,7 @@ fn sobel_taps(lengths_to_pixels: DMat2) -> [[f32; 4]; 8] {
|
||||
}
|
||||
|
||||
/// The parameters placing a random field's samples in each texel as `sampling` describes, matching the shader's `field_values`, with its integers split into exact halves.
|
||||
fn field_parameters(sampling: &FieldSampling, first_seed: u32, second_seed: u32) -> Parameters {
|
||||
pub(super) fn field_parameters(sampling: &FieldSampling, first_seed: u32, second_seed: u32) -> Parameters {
|
||||
let halves = |value: u32| [(value & 0xffff) as f32, (value >> 16) as f32];
|
||||
let axes = sampling.pixel_axes;
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
//! The GPU passes of the layer styles' finer options: the outline's paints, and the bevel's contour and texture.
|
||||
//! The GPU passes of the layer styles' finer options: the outline's paints, the bevel's contour and texture, and the glows' grain.
|
||||
|
||||
use super::filters::field_parameters;
|
||||
use super::{COVERAGE_FORMAT, GRADIENT_SAMPLES, PARAMETER_TAPS, Parameters, PassRecorder, Seeds, WORKING_FORMAT};
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::{DVec2, DVec3};
|
||||
use glam::{DAffine2, DVec2, DVec3};
|
||||
use graphic_types::BevelStyle;
|
||||
use graphic_types::effects::{BEVEL_FOOT_FADE, GlowFill, contour_end_slopes, slope_contour_reshapes};
|
||||
use graphic_types::effects::{BEVEL_FOOT_FADE, GRADIENT_GLOW_FADE, GlowFill, JITTER_EXPECTATION_SAMPLES, contour_end_slopes, slope_contour_reshapes};
|
||||
use graphic_types::filters::{FieldSampling, RandomField};
|
||||
use raster_kernels::effect_kernels::NEGLIGIBLE_LENGTH;
|
||||
|
||||
/// An outline's coverage outside the content's edge and inside it, where it reaches, and each pixel's place across it for a contour gradient.
|
||||
@@ -95,7 +97,63 @@ pub(super) struct BevelSurface<'a> {
|
||||
pub texture_depth: f64,
|
||||
}
|
||||
|
||||
/// The first tap [`field_parameters`] leaves free, which holds a grain's own parameters.
|
||||
const GRAIN_TAP: usize = 5;
|
||||
|
||||
/// The random grain roughening a glow, matching the CPU's `GlowGrain`.
|
||||
pub(super) struct GlowGrain {
|
||||
/// Where each texel samples the grain, fixed to the cells of the effect space.
|
||||
sampling: FieldSampling,
|
||||
/// The field of the grain that the glow's seed gives.
|
||||
field: u32,
|
||||
/// How much each sample offsets the alpha (the noise) and moves a gradient's color (the jitter).
|
||||
pub amounts: [f64; 2],
|
||||
/// How far from the content's edge the grain reaches, in texels as the distance passes measure them, if not everywhere.
|
||||
pub reach: Option<f64>,
|
||||
}
|
||||
|
||||
impl GlowGrain {
|
||||
/// The grain roughening a glow filled with `paint` by the `noise` and `jitter` percentages with its `seed`, on texels that `effect_to_pixels` places the effect space on.
|
||||
/// `None` if it changes nothing, or if the texels collapse the effect space, where they can't sample it.
|
||||
pub fn new(paint: &GlowFill, noise: f64, jitter: f64, seed: i64, effect_to_pixels: DAffine2) -> Option<Self> {
|
||||
let amounts = paint.grain_amounts(noise, jitter)?;
|
||||
if !effect_to_pixels.matrix2.determinant().is_normal() {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(Self {
|
||||
sampling: FieldSampling::new(effect_to_pixels.inverse()),
|
||||
field: RandomField::GlowGrain.seed(seed),
|
||||
amounts,
|
||||
reach: None,
|
||||
})
|
||||
}
|
||||
|
||||
/// The [`field_parameters`] of the grain's field, then a tap of the grain's own, matching the shader's `grained_alpha`, `grain_reaches`, and `gradient_glow_tint`.
|
||||
pub fn taps(&self) -> [[f32; 4]; PARAMETER_TAPS] {
|
||||
let mut taps = field_parameters(&self.sampling, self.field, 0).taps;
|
||||
taps[GRAIN_TAP] = [
|
||||
self.sampling.deviation_scale as f32,
|
||||
if self.reach.is_some() { 1. } else { 0. },
|
||||
self.reach.unwrap_or_default() as f32,
|
||||
JITTER_EXPECTATION_SAMPLES as f32,
|
||||
];
|
||||
taps
|
||||
}
|
||||
}
|
||||
|
||||
impl PassRecorder<'_> {
|
||||
/// A glow's `strength` roughened by the `grain`, held under the fade of its raw strength (the `content`) if it `fades`, and kept within the reach that an inner glow's distances (then the `content`) give.
|
||||
/// Matches the CPU's `GlowFill::grained_color_at`.
|
||||
pub(super) fn grained_glow_strength(&mut self, strength: &wgpu::Texture, content: &wgpu::Texture, fades: bool, grain: &GlowGrain) -> wgpu::Texture {
|
||||
let parameters = Parameters {
|
||||
values: [grain.amounts[0] as f32, if fades { GRADIENT_GLOW_FADE as f32 } else { 0. }, 0., 0.],
|
||||
taps: grain.taps(),
|
||||
..Default::default()
|
||||
};
|
||||
self.run("grained_glow_strength", COVERAGE_FORMAT, self.size, strength, None, Some(content), parameters)
|
||||
}
|
||||
|
||||
/// How much brighter than flat ground the `light` lights each texel of a bevel's surface, negative where darker, with its `height` running from -0.5 at its slopes' foot to 0.5 at their top.
|
||||
/// The slopes rise `rise` texels as the `surface` options shape them. Matches the CPU's `bevel_shading` before its gloss contour.
|
||||
/// With `direct` as `Some(shadow)`, it's instead the highlight, or if `shadow` the shadow, that makes without a gloss contour or a fade at the foot.
|
||||
|
||||
@@ -579,6 +579,9 @@ fn shadows_and_glows_fall_where_they_should() {
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: Default::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let Some(pixels) = render_square_with_effects(vec![glow], 1., 30., 80., size) else { return };
|
||||
for (x, y) in [(27, 55), (82, 55), (55, 27), (55, 82)] {
|
||||
@@ -611,6 +614,9 @@ fn inner_glows_satins_outlines_and_bevels_fall_where_they_should() {
|
||||
size: 3.,
|
||||
range: 100.,
|
||||
contour: Default::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let Some(pixels) = render_square(inner_glow(GlowSource::Edge)) else { return };
|
||||
assert_eq!(pixel(&pixels, size, 31, 55), [0, 0, 0, 255], "the edge glows");
|
||||
@@ -1884,6 +1890,9 @@ fn a_trailing_mask_fades_a_glow_that_still_screens_what_lies_beneath() {
|
||||
size: 5.,
|
||||
range: 50.,
|
||||
contour: Default::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
|
||||
// At 60% density, a mask that's black over the square's left half and absent past the square shows 40% there, and all of the right half
|
||||
@@ -2298,9 +2307,20 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
size,
|
||||
range,
|
||||
contour,
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let glow = |technique, spread, size, range, contour| gradient_glow(shadow_color.into(), technique, spread, size, range, contour);
|
||||
let stop = |position, color| GradientStop { position, midpoint: 0.5, color };
|
||||
// A glow roughened by `noise` and, for a gradient, scattered along it by `jitter`
|
||||
let grained = |glow: EffectOperation, noise_amount: f64, jitter_amount: f64| {
|
||||
let mut glow = glow;
|
||||
if let EffectOperation::OuterGlow { noise, jitter, .. } | EffectOperation::InnerGlow { noise, jitter, .. } = &mut glow {
|
||||
(*noise, *jitter) = (noise_amount, jitter_amount);
|
||||
}
|
||||
glow
|
||||
};
|
||||
let fading = Graphic::from(Gradient::new([
|
||||
stop(0., GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 1.)),
|
||||
stop(0.4, GraphicColor::from_rgbaf32_unchecked(0.9, 0.2, 0.1, 0.8)),
|
||||
@@ -2349,6 +2369,72 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
vec![glow(GlowTechnique::Precise, 0., 12., 75., bow.clone())],
|
||||
vec![glow(GlowTechnique::Precise, 50., 16., 100., TransferCurve::default())],
|
||||
vec![glow(GlowTechnique::Precise, 80., 10., 100., TransferCurve::default())],
|
||||
// Grain fixed to the content roughens a glow's opacity, and scatters a gradient glow's colors along it
|
||||
vec![grained(glow(GlowTechnique::Precise, 100., 12., 100., TransferCurve::default()), 60., 0.)],
|
||||
vec![grained(glow(GlowTechnique::Softer, 0., 10., 50., TransferCurve::default()), 100., 0.)],
|
||||
vec![grained(gradient_glow(fading.clone(), GlowTechnique::Precise, 0., 14., 75., TransferCurve::default()), 40., 50.)],
|
||||
vec![grained(
|
||||
EffectOperation::InnerGlow {
|
||||
color: shadow_color.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 12.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
},
|
||||
50.,
|
||||
0.,
|
||||
)],
|
||||
vec![grained(
|
||||
EffectOperation::InnerGlow {
|
||||
color: inner_gradient.clone(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Softer,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 12.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
},
|
||||
30.,
|
||||
60.,
|
||||
)],
|
||||
// Jitter alone, and noisy inner glows reshaped by a range and a contour, from the edges and the center, with other seeds
|
||||
vec![grained(gradient_glow(opaque.clone(), GlowTechnique::Softer, 20., 12., 100., TransferCurve::default()), 0., 80.)],
|
||||
vec![EffectOperation::InnerGlow {
|
||||
color: shadow_color.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Edge,
|
||||
choke: 10.,
|
||||
size: 12.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]),
|
||||
noise: 70.,
|
||||
jitter: 0.,
|
||||
seed: 3,
|
||||
}],
|
||||
vec![EffectOperation::InnerGlow {
|
||||
color: shadow_color.into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Center,
|
||||
choke: 10.,
|
||||
size: 12.,
|
||||
range: 60.,
|
||||
contour: TransferCurve::new(vec![DVec2::ZERO, DVec2::new(0.25, 0.75), DVec2::ONE]),
|
||||
noise: 50.,
|
||||
jitter: 0.,
|
||||
seed: 5,
|
||||
}],
|
||||
vec![glow(GlowTechnique::Softer, 0., 6., 50., bow.clone())],
|
||||
vec![gradient_glow(fading.clone(), GlowTechnique::Precise, 0., 14., 75., TransferCurve::default())],
|
||||
vec![gradient_glow(opaque.clone(), GlowTechnique::Softer, 25., 12., 50., bow.clone())],
|
||||
@@ -2361,6 +2447,9 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
size: 7.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
}],
|
||||
vec![EffectOperation::InnerGlow {
|
||||
color: shadow_color.into(),
|
||||
@@ -2371,6 +2460,9 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
size: 10.,
|
||||
range: 75.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
}],
|
||||
vec![EffectOperation::Satin {
|
||||
color: shadow_color,
|
||||
@@ -2418,6 +2510,9 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
size: 9.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
}],
|
||||
vec![bevel(BevelStyle::InnerBevel, BevelTechnique::Smooth, BevelDirection::Up, 8., 0.)],
|
||||
vec![bevel(BevelStyle::OuterBevel, BevelTechnique::ChiselHard, BevelDirection::Down, 6., 2.)],
|
||||
@@ -2592,6 +2687,9 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
size: 7.,
|
||||
range: 50.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.,
|
||||
jitter: 0.,
|
||||
seed: 0,
|
||||
};
|
||||
let masked_radius_blur = |radius_mask: &Graphic, radius, box_blur, gamma| EffectOperation::Blur {
|
||||
radius_mask: radius_mask.clone(),
|
||||
@@ -2880,6 +2978,8 @@ fn cpu_evaluated_effects_match_the_gpu_passes() {
|
||||
..
|
||||
}) => 8,
|
||||
Some(operation @ EffectOperation::Outline { .. }) if operation.drawn_paints().next().is_some() => 3,
|
||||
// A noisy outer glow fades by its raw strength over 0.12, which amplifies eightfold the rounding of that strength where it falls steeply, across a full spread's last pixel
|
||||
Some(EffectOperation::OuterGlow { noise, spread, .. }) if *noise > 0. && *spread >= 100. => 8,
|
||||
// A texture's paint rounds to eight bits, which the two renderers can land a level apart, moving the surface by its depth times its span over 255
|
||||
Some(EffectOperation::BevelAndEmboss { texture, .. }) if !matches!(texture, Graphic::None(_)) => 6,
|
||||
// A slope contour steeper than a straight line amplifies the rounding of the GPU's half-float heights
|
||||
@@ -4251,6 +4351,145 @@ fn adjustments_leave_the_empty_space_around_content_empty() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grained_glows_match_the_cpu_zoomed_in_and_out() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
use core_types::Color as GraphicColor;
|
||||
use core_types::list::Item;
|
||||
use core_types::transfer_curve::TransferCurve;
|
||||
use glam::DVec2;
|
||||
use graphic_types::raster_types::{Image, Raster};
|
||||
use graphic_types::vector_types::gradient::{Gradient, GradientStop};
|
||||
use graphic_types::{EffectOperation, Effects, GlowSource, GlowTechnique, Graphic};
|
||||
use raster_kernels::evaluate_raster_effects;
|
||||
|
||||
let (min, max) = (24., 56.);
|
||||
let stop = |position, color| GradientStop { position, midpoint: 0.5, color };
|
||||
let fading = Graphic::from(Gradient::new([
|
||||
stop(0., GraphicColor::from_rgbaf32_unchecked(1., 0.9, 0.2, 1.)),
|
||||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.2, 0., 0.6, 0.3)),
|
||||
]));
|
||||
let transparent = Graphic::from(Gradient::new([
|
||||
stop(0., GraphicColor::from_rgbaf32_unchecked(0.9, 0.1, 0.3, 0.)),
|
||||
stop(1., GraphicColor::from_rgbaf32_unchecked(0.1, 0.6, 0.9, 0.)),
|
||||
]));
|
||||
let glows = [
|
||||
EffectOperation::OuterGlow {
|
||||
color: GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75).into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 30.,
|
||||
size: 8.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 60.,
|
||||
jitter: 0.,
|
||||
seed: 2,
|
||||
},
|
||||
EffectOperation::InnerGlow {
|
||||
color: fading,
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
source: GlowSource::Edge,
|
||||
choke: 0.,
|
||||
size: 8.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 40.,
|
||||
jitter: 50.,
|
||||
seed: 0,
|
||||
},
|
||||
// Shown only by its noise, with its colors jittered
|
||||
EffectOperation::OuterGlow {
|
||||
color: transparent,
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 50.,
|
||||
size: 8.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 100.,
|
||||
jitter: 40.,
|
||||
seed: 5,
|
||||
},
|
||||
// Noise too slight to change anything in 32-bit floats
|
||||
EffectOperation::OuterGlow {
|
||||
color: GraphicColor::from_rgbaf32_unchecked(0.1, 0.2, 0.8, 0.75).into(),
|
||||
blend_mode: BlendMode::Normal,
|
||||
technique: GlowTechnique::Precise,
|
||||
spread: 100.,
|
||||
size: 8.,
|
||||
range: 100.,
|
||||
contour: TransferCurve::default(),
|
||||
noise: 0.000001,
|
||||
jitter: 0.,
|
||||
seed: 2,
|
||||
},
|
||||
];
|
||||
|
||||
let zooms = [
|
||||
// Twice and half as many pixels as document pixels, with the render's corner at negative document pixels so the grain's cells there are negative too
|
||||
(2., DVec2::new(10., 6.), 160),
|
||||
(0.5, DVec2::new(4., 2.), 48),
|
||||
// An eighth as many, where each pixel spans more grain than it samples
|
||||
(0.125, DVec2::new(3., 2.), 16),
|
||||
// The render cutting off the content's upper left, so it starts partway into the grain
|
||||
(2., DVec2::new(-70., -60.), 160),
|
||||
];
|
||||
for (scale, offset, side) in zooms {
|
||||
for glow in glows.clone() {
|
||||
let effects = Effects::from_operations([glow.clone()]);
|
||||
let size = UVec2::splat(side);
|
||||
let square = Rect::new(min, min, max, max);
|
||||
// The grain lies in the effect space, which has its origin at the content's, the square's corner
|
||||
let effect_space = DAffine2::from_translation(DVec2::splat(min));
|
||||
let Some(gpu) = render(size, |scene| {
|
||||
scene.draw_placed(Affine::translate((offset.x, offset.y)) * Affine::scale(scale), |scene| {
|
||||
scene.draw_effects(&effects, 1., 1., BlendMode::Normal, true, Some(square), effect_space, None, &mut |_, _| {}, &mut |scene| {
|
||||
scene.fill(Fill::NonZero, Affine::IDENTITY, Color::WHITE, None, &square)
|
||||
});
|
||||
});
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
|
||||
// The same square as a raster at the same pixels per document pixel
|
||||
let pixels = ((max - min) * scale) as u32;
|
||||
let mut item = Item::new_from_element(Raster::new_cpu(Image::new(pixels, pixels, GraphicColor::WHITE)))
|
||||
.with_attribute(ATTR_TRANSFORM, DAffine2::from_translation(DVec2::splat(min)) * DAffine2::from_scale(DVec2::splat(max - min)));
|
||||
graphic_types::stamp_effect(&mut item, graphic_types::Effect::new(&glow));
|
||||
let evaluated = evaluate_raster_effects(item);
|
||||
let placement: DAffine2 = evaluated.attribute_cloned_or_default(ATTR_TRANSFORM);
|
||||
let raster = evaluated.element();
|
||||
let document_to_pixels = DAffine2::from_scale(DVec2::new(raster.width as f64, raster.height as f64)) * placement.inverse();
|
||||
|
||||
let mut worst = 0;
|
||||
for y in 0..size.y {
|
||||
for x in 0..size.x {
|
||||
let document = (DVec2::new(x as f64 + 0.5, y as f64 + 0.5) - offset) / scale;
|
||||
let point = document_to_pixels.transform_point2(document).floor();
|
||||
let inside = point.x >= 0. && point.y >= 0. && point.x < raster.width as f64 && point.y < raster.height as f64;
|
||||
let cpu = match inside {
|
||||
true => {
|
||||
let [red, green, blue, alpha] = raster.data[(point.y as u32 * raster.width + point.x as u32) as usize].to_gamma_srgb_channels();
|
||||
[red * alpha, green * alpha, blue * alpha, alpha].map(|channel| channel * 255.)
|
||||
}
|
||||
false => [0.; 4],
|
||||
};
|
||||
|
||||
let gpu = pixel(&gpu, size, x, y);
|
||||
let gpu_alpha = gpu[3] as f32 / 255.;
|
||||
for channel in 0..4 {
|
||||
let gpu_channel = if channel == 3 { gpu[3] as f32 } else { gpu[channel] as f32 * gpu_alpha };
|
||||
worst = worst.max((cpu[channel] - gpu_channel).abs().round() as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(worst <= 2, "{effects:?} at {scale} pixels per document pixel differs from the GPU by up to {worst} levels");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn soft_chisels_on_translucent_content_match_the_cpu() {
|
||||
use core_types::ATTR_TRANSFORM;
|
||||
|
||||
@@ -166,3 +166,61 @@ fn bevel_amount(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32
|
||||
}
|
||||
return vec4<f32>(amount);
|
||||
}
|
||||
|
||||
// =====
|
||||
// Glows
|
||||
// =====
|
||||
|
||||
// The glow's sample in `column` and `row` of its grain at the texel's middle `position`, from -1 to 1, in the first field
|
||||
fn glow_grain_sample(position: vec2<f32>, column: u32, row: u32) -> f32 {
|
||||
return 2. * field_values(position, sample_offset(column, row), field_seed(false)).x - 1.;
|
||||
}
|
||||
|
||||
// Whether a glow's grain reaches the texel: everywhere, or with `taps[5].y` 1 where its distance from the content's edge (`content`) is at most `taps[5].z`
|
||||
fn grain_reaches(pixel: vec2<i32>) -> bool {
|
||||
return parameters.taps[5].y < 0.5 || textureLoad(content, pixel, 0).r <= parameters.taps[5].z;
|
||||
}
|
||||
|
||||
// The mean of an `alpha` offset by `noise` times a grain uniform from -1 to 1, held from 0 to `limit`, matching the CPU's `expected_grained_alpha`
|
||||
fn expected_grained_alpha(alpha: f32, noise: f32, limit: f32) -> f32 {
|
||||
// Held at none or at the limit across the whole span of the grain, or without one
|
||||
if noise <= 0. || alpha + noise <= 0. || alpha - limit >= noise {
|
||||
return clamp(alpha, 0., limit);
|
||||
}
|
||||
|
||||
// Each end the span reaches past moves the mean by the triangle held there over the span, which is no larger than the noise
|
||||
let below = max(noise - alpha, 0.);
|
||||
let above = max(alpha - limit + noise, 0.);
|
||||
return alpha + below * (below / (4. * noise)) - above * (above / (4. * noise));
|
||||
}
|
||||
|
||||
// A glow's `alphas` summed over its samples, averaged with their deviation from the `expected` one scaled by `taps[5].x`, and held under `limit`
|
||||
fn grained_alpha(alphas: f32, expected: f32, limit: f32) -> f32 {
|
||||
let counts = sample_counts();
|
||||
return clamp(expected + (alphas / f32(counts.x * counts.y) - expected) * parameters.taps[5].x, 0., limit);
|
||||
}
|
||||
|
||||
// A glow's strength (`source`) as its alpha, held under 1 or with `values.y` above 0 under its raw strength (`content`) over that, where it's grained:
|
||||
// each sample adds `values.x` of itself first, and they average, matching the CPU's `GlowFill::grained_color_at`
|
||||
@fragment
|
||||
fn grained_glow_strength(@builtin(position) position: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let pixel = vec2<i32>(position.xy);
|
||||
let strength = textureLoad(source, pixel, 0).r;
|
||||
var limit = 1.;
|
||||
if parameters.values.y > 0. {
|
||||
limit = clamp(textureLoad(content, pixel, 0).r / parameters.values.y, 0., 1.);
|
||||
}
|
||||
if !grain_reaches(pixel) {
|
||||
return vec4<f32>(clamp(strength, 0., limit));
|
||||
}
|
||||
|
||||
let noise = parameters.values.x;
|
||||
let counts = sample_counts();
|
||||
var alphas = 0.;
|
||||
for (var row = 0u; row < counts.y; row++) {
|
||||
for (var column = 0u; column < counts.x; column++) {
|
||||
alphas += clamp(strength + noise * glow_grain_sample(position.xy, column, row), 0., limit);
|
||||
}
|
||||
}
|
||||
return vec4<f32>(grained_alpha(alphas, expected_grained_alpha(strength, noise, limit), limit));
|
||||
}
|
||||
@@ -289,7 +289,7 @@ fn glow_paint(paint: Item<Graphic>) -> Graphic {
|
||||
}
|
||||
|
||||
/// Surrounds the input graphics with a soft glow of their silhouette.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeOuterGlow"), version(2))]
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeOuterGlow"), version(3))]
|
||||
fn outer_glow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow around.
|
||||
@@ -323,6 +323,19 @@ fn outer_glow<T>(
|
||||
range: Item<f64>,
|
||||
/// Reshapes how the glow's strength falls off across its size.
|
||||
contour: Item<TransferCurve>,
|
||||
/// How much random grain, fixed in place on the content, roughens the glow's opacity.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
noise: Item<f64>,
|
||||
/// How much the same grain scatters a gradient glow's colors along the gradient, leaving its opacity as it is.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
jitter: Item<f64>,
|
||||
/// The random variation of the grain. The same seed always gives the same grain.
|
||||
#[hard(0..)]
|
||||
seed: Item<i64>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
@@ -335,13 +348,16 @@ fn outer_glow<T>(
|
||||
size: *size.element(),
|
||||
range: *range.element(),
|
||||
contour: contour.into_element(),
|
||||
noise: *noise.element(),
|
||||
jitter: *jitter.element(),
|
||||
seed: *seed.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
}
|
||||
|
||||
/// Glows inward from the edges of the input graphics, or outward from their center.
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeInnerGlow"), version(2))]
|
||||
#[node_macro::node(category("Raster: Effect"), icon("NodeInnerGlow"), version(3))]
|
||||
fn inner_glow<T>(
|
||||
_: impl Ctx,
|
||||
/// The content to glow within.
|
||||
@@ -377,6 +393,19 @@ fn inner_glow<T>(
|
||||
range: Item<f64>,
|
||||
/// Reshapes how the glow's strength falls off across its size.
|
||||
contour: Item<TransferCurve>,
|
||||
/// How much random grain, fixed in place on the content, roughens the glow's opacity.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
noise: Item<f64>,
|
||||
/// How much the same grain scatters a gradient glow's colors along the gradient, leaving its opacity as it is.
|
||||
#[unit("%")]
|
||||
#[range]
|
||||
#[hard(0..100)]
|
||||
jitter: Item<f64>,
|
||||
/// The random variation of the grain. The same seed always gives the same grain.
|
||||
#[hard(0..)]
|
||||
seed: Item<i64>,
|
||||
) -> Item<T> {
|
||||
let mut content = content;
|
||||
stamp_effect(
|
||||
@@ -390,6 +419,9 @@ fn inner_glow<T>(
|
||||
size: *size.element(),
|
||||
range: *range.element(),
|
||||
contour: contour.into_element(),
|
||||
noise: *noise.element(),
|
||||
jitter: *jitter.element(),
|
||||
seed: *seed.element(),
|
||||
}),
|
||||
);
|
||||
content
|
||||
|
||||
Reference in new issue
Block a user