use std::ops::Range;
use crate::layout::{
backdrop::BackdropCmd,
quad::{ClipRect, MAX_ROUNDED_CLIPS},
render_list::{GlyphCmd, RectCmd},
};
const AA_REACH: f32 = 2.0;
pub const MAX_BLUR_RADIUS: f32 = 256.0;
const MIN_BLUR_SIGMA: f32 = 0.05;
const MAX_PASS_SIGMA: f32 = 8.0;
const MAX_BLUR_REDUCTION: u32 = 64;
pub(crate) fn blur_sigma(radius: f32) -> f32 {
radius * 0.5
}
pub(crate) fn blur_reach(radius: f32) -> f32 {
(blur_sigma(radius) * 3.0).ceil()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct OpacityGroup {
pub start: usize,
pub end: usize,
pub opacity: f32,
pub blur: f32,
pub clip: Option<ClipRect>,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayerCmd {
pub start_order: usize,
pub end_order: usize,
pub opacity: f32,
pub bounds: LayerBounds,
pub blur: Option<LayerBlur>,
}
impl LayerCmd {
pub fn is_visible(&self) -> bool {
self.opacity > 0.0 && !self.bounds.is_empty() && self.blur.is_none_or(|blur| blur.width > 0 && blur.height > 0)
}
pub fn painted(&self) -> ([i32; 2], [u32; 2]) {
match self.blur {
Some(blur) => ([blur.x, blur.y], [blur.width, blur.height]),
None => (
[self.bounds.x as i32, self.bounds.y as i32],
[self.bounds.width, self.bounds.height],
),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayerBlur {
pub sigma: f32,
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
pub clips: RoundedClipBoxes,
}
pub type RoundedClipBoxes = [Option<RoundedBox>; MAX_ROUNDED_CLIPS];
pub(crate) fn rounded_clip_boxes(clip: ClipRect) -> RoundedClipBoxes {
if !clip.active {
return [None; MAX_ROUNDED_CLIPS];
}
clip.rounded.map(|rounded| {
rounded.map(|rounded| {
let limit = (rounded.width.min(rounded.height) * 0.5).max(0.0);
RoundedBox::rect(
rounded.x,
rounded.y,
rounded.width,
rounded.height,
rounded.radius.to_array().map(|radius| radius.clamp(0.0, limit)),
)
})
})
}
#[cfg(feature = "devtools")]
pub(crate) fn rounded_clips_coverage(clips: &RoundedClipBoxes, x: f32, y: f32) -> f32 {
clips.iter().flatten().map(|clip| clip.coverage(x, y)).product()
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RoundedBox {
pub center: [f32; 2],
pub half: [f32; 2],
pub radii: [f32; 4],
pub inverse: [f32; 4],
pub scale: f32,
}
impl RoundedBox {
pub fn rect(x: f32, y: f32, width: f32, height: f32, radii: [f32; 4]) -> Self {
Self {
center: [x + width * 0.5, y + height * 0.5],
half: [width * 0.5, height * 0.5],
radii,
inverse: [1.0, 0.0, 0.0, 1.0],
scale: 1.0,
}
}
pub fn transformed(
x: f32,
y: f32,
width: f32,
height: f32,
radii: [f32; 4],
transform: [f32; 4],
origin: [f32; 2],
) -> Option<Self> {
let [a, b, c, d] = transform;
let determinant = a * d - b * c;
if !(determinant.is_finite() && determinant.abs() > 1.0e-6) {
return None;
}
let (dx, dy) = (width * 0.5 - origin[0], height * 0.5 - origin[1]);
Some(Self {
center: [x + origin[0] + a * dx + c * dy, y + origin[1] + b * dx + d * dy],
half: [width * 0.5, height * 0.5],
radii,
inverse: [d / determinant, -b / determinant, -c / determinant, a / determinant],
scale: determinant.abs().sqrt(),
})
}
pub fn extent(&self) -> [f32; 4] {
let [ia, ib, ic, id] = self.inverse;
let determinant = ia * id - ib * ic;
let (a, b, c, d) = (id / determinant, -ib / determinant, -ic / determinant, ia / determinant);
let reach_x = (a * self.half[0]).abs() + (c * self.half[1]).abs();
let reach_y = (b * self.half[0]).abs() + (d * self.half[1]).abs();
[
self.center[0] - reach_x,
self.center[1] - reach_y,
self.center[0] + reach_x,
self.center[1] + reach_y,
]
}
pub fn coverage(&self, x: f32, y: f32) -> f32 {
let (dx, dy) = (x - self.center[0], y - self.center[1]);
let [a, b, c, d] = self.inverse;
let p = [a * dx + c * dy, b * dx + d * dy];
let radius = match (p[0] >= 0.0, p[1] >= 0.0) {
(false, false) => self.radii[0],
(true, false) => self.radii[1],
(true, true) => self.radii[2],
(false, true) => self.radii[3],
};
let q = [p[0].abs() - self.half[0] + radius, p[1].abs() - self.half[1] + radius];
let distance = q[0].max(0.0).hypot(q[1].max(0.0)) + q[0].max(q[1]).min(0.0) - radius;
(0.5 - distance * self.scale).clamp(0.0, 1.0)
}
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct BlurPlan {
pub reduction: u32,
pub sigma: f32,
pub size: [u32; 2],
pub border: u32,
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
impl BlurPlan {
pub(crate) fn new(blur: &LayerBlur) -> Self {
let reduction = blur_reduction(blur.sigma);
if reduction == 1 {
return Self {
reduction,
sigma: blur.sigma,
size: [blur.width, blur.height],
border: 0,
};
}
let r = reduction as f32;
let widened = (r * r - 1.0) / 12.0 + r * r / 6.0;
let sigma = (blur.sigma * blur.sigma - widened).max(0.25).sqrt() / r;
Self {
reduction,
sigma: sigma.min(MAX_PASS_SIGMA * 1.25),
size: [
blur.width.div_ceil(reduction).max(1) + 2,
blur.height.div_ceil(reduction).max(1) + 2,
],
border: 1,
}
}
}
pub(crate) fn blur_pad(sigma: f32) -> i32 {
(sigma * 3.0).ceil() as i32 + 2 * blur_reduction(sigma) as i32 + 1
}
fn blur_reduction(sigma: f32) -> u32 {
let mut reduction = 1;
while sigma / reduction as f32 > MAX_PASS_SIGMA && reduction < MAX_BLUR_REDUCTION {
reduction *= 2;
}
reduction
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LayerBounds {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
impl LayerBounds {
pub fn is_empty(&self) -> bool {
self.width == 0 || self.height == 0
}
}
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum LayerStep {
Draws(Range<usize>),
Composite(usize),
Backdrop(usize),
}
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct LayerTarget {
pub layer: Option<usize>,
steps: Range<usize>,
}
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
#[derive(Default)]
pub(crate) struct LayerPlan {
targets: Vec<LayerTarget>,
steps: Vec<LayerStep>,
pending: Vec<LayerStep>,
backdrop_cursor: usize,
backdrop_steps: usize,
}
#[cfg_attr(not(any(feature = "render", feature = "devtools")), allow(dead_code))]
impl LayerPlan {
pub(crate) fn build(
&mut self,
draw_count: usize,
order_of: impl Fn(usize) -> usize,
layers: &[LayerCmd],
backdrops: &[BackdropCmd],
) {
self.targets.clear();
self.steps.clear();
self.pending.clear();
self.backdrop_cursor = 0;
self.backdrop_steps = 0;
let mut cursor = 0;
self.plan_target(
None,
0..draw_count,
usize::MAX,
&order_of,
layers,
backdrops,
&mut cursor,
);
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn has_backdrops(&self) -> bool {
self.backdrop_steps > 0
}
fn plan_draws(
&mut self,
next: &mut usize,
draw_end: usize,
order_limit: usize,
order_of: &impl Fn(usize) -> usize,
backdrops: &[BackdropCmd],
) {
while let Some(backdrop) = backdrops.get(self.backdrop_cursor)
&& backdrop.order < order_limit
{
let at = first_at_or_after(*next..draw_end, backdrop.order, order_of);
if at > *next {
self.pending.push(LayerStep::Draws(*next..at));
*next = at;
}
self.pending.push(LayerStep::Backdrop(self.backdrop_cursor));
self.backdrop_cursor += 1;
self.backdrop_steps += 1;
}
if draw_end > *next {
self.pending.push(LayerStep::Draws(*next..draw_end));
*next = draw_end;
}
}
pub(crate) fn targets(&self) -> &[LayerTarget] {
&self.targets
}
pub(crate) fn steps(&self, target: &LayerTarget) -> &[LayerStep] {
&self.steps[target.steps.clone()]
}
#[cfg_attr(not(feature = "render"), allow(dead_code))]
pub(crate) fn has_layers(&self) -> bool {
self.targets.len() > 1
}
#[allow(clippy::too_many_arguments)]
fn plan_target(
&mut self,
layer: Option<usize>,
draws: Range<usize>,
end_order: usize,
order_of: &impl Fn(usize) -> usize,
layers: &[LayerCmd],
backdrops: &[BackdropCmd],
cursor: &mut usize,
) -> usize {
let pending_start = self.pending.len();
let mut next = draws.start;
while *cursor < layers.len() && layers[*cursor].start_order < end_order {
let index = *cursor;
*cursor += 1;
let inner = layers[index];
let start = first_at_or_after(next..draws.end, inner.start_order, order_of);
let end = first_at_or_after(start..draws.end, inner.end_order, order_of);
self.plan_draws(&mut next, start, inner.start_order, order_of, backdrops);
if inner.is_visible() && end > start {
let target = self.plan_target(
Some(index),
start..end,
inner.end_order,
order_of,
layers,
backdrops,
cursor,
);
self.pending.push(LayerStep::Composite(target));
} else {
while *cursor < layers.len() && layers[*cursor].start_order < inner.end_order {
*cursor += 1;
}
}
while backdrops
.get(self.backdrop_cursor)
.is_some_and(|backdrop| backdrop.order < inner.end_order)
{
self.backdrop_cursor += 1;
}
next = end;
}
self.plan_draws(&mut next, draws.end, end_order, order_of, backdrops);
let steps_start = self.steps.len();
self.steps.extend(self.pending.drain(pending_start..));
self.targets.push(LayerTarget {
layer,
steps: steps_start..self.steps.len(),
});
self.targets.len() - 1
}
}
#[cfg(feature = "render")]
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct TargetSpace {
pub width: f32,
pub height: f32,
pub origin: [f32; 2],
layer_size: Option<[f32; 2]>,
}
#[cfg(feature = "render")]
impl TargetSpace {
pub(crate) fn window(width: f32, height: f32) -> Self {
Self {
width,
height,
origin: [0.0; 2],
layer_size: None,
}
}
pub(crate) fn layer(layer: &LayerCmd, texture_width: u32, texture_height: u32) -> Self {
let (origin, size) = layer.painted();
Self {
width: texture_width as f32,
height: texture_height as f32,
origin: [origin[0] as f32, origin[1] as f32],
layer_size: Some([size[0] as f32, size[1] as f32]),
}
}
#[cfg_attr(not(feature = "dx12"), allow(dead_code))]
pub(crate) fn blur_target(size: [u32; 2], texture_width: u32, texture_height: u32) -> Self {
Self {
width: texture_width as f32,
height: texture_height as f32,
origin: [0.0; 2],
layer_size: Some([size[0] as f32, size[1] as f32]),
}
}
#[cfg_attr(not(feature = "wgpu"), allow(dead_code))]
pub(crate) fn is_window(&self) -> bool {
self.layer_size.is_none()
}
pub(crate) fn viewport(&self) -> [f32; 4] {
[self.width, self.height, self.origin[0], self.origin[1]]
}
pub(crate) fn clip(&self, clip: ClipRect) -> ClipRect {
let Some([width, height]) = self.layer_size else {
return clip;
};
if !clip.active {
return ClipRect::rect(0.0, 0.0, width, height);
}
clip.translated(-self.origin[0], -self.origin[1])
}
pub(crate) fn layer_rect(&self, layer: LayerBounds) -> ClipRect {
ClipRect::rect(
layer.x as f32 - self.origin[0],
layer.y as f32 - self.origin[1],
layer.width as f32,
layer.height as f32,
)
}
}
#[cfg(feature = "render")]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct LayerComposite {
pub rect: [f32; 4],
pub target: [f32; 4],
pub opacity: [f32; 4],
}
#[cfg(feature = "render")]
impl LayerComposite {
pub(crate) fn new(layer: &LayerCmd, parent: &TargetSpace) -> Self {
let rect = parent.layer_rect(layer.bounds);
Self {
rect: [rect.x, rect.y, rect.width, rect.height],
target: [
parent.width,
parent.height,
parent.origin[0] - layer.bounds.x as f32,
parent.origin[1] - layer.bounds.y as f32,
],
opacity: [layer.opacity, 0.0, 0.0, 0.0],
}
}
}
#[cfg(feature = "render")]
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct LayerBlurPass {
pub rect: [f32; 4],
pub target: [f32; 4],
pub source: [f32; 4],
pub kernel: [f32; 4],
pub mode: [f32; 4],
pub limit: [f32; 4],
pub mask: [f32; 4],
pub mask_inverse: [f32; 4],
pub radii: [f32; 4],
pub clip: [f32; 4],
pub clip_inverse: [f32; 4],
pub clip_radii: [f32; 4],
pub outer_clip: [f32; 4],
pub outer_clip_radii: [f32; 4],
}
#[cfg(feature = "render")]
impl LayerBlurPass {
pub(crate) fn reduce(blur: &LayerBlur, plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
let r = plan.reduction as f32;
let border = plan.border as f32;
Self {
rect: [0.0, 0.0, plan.size[0] as f32, plan.size[1] as f32],
target: [target[0] as f32, target[1] as f32, -border, -border],
source: [r, r, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
kernel: [0.0, 0.0, 0.0, 1.0],
mode: [(plan.reduction / 2) as f32, 1.0, 1.0, 0.0],
limit: texel_limit([blur.width, blur.height]),
..Self::UNCUT
}
}
pub(crate) fn horizontal(plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
Self::gaussian(plan, [1.0, 0.0], source, target)
}
pub(crate) fn vertical(plan: &BlurPlan, source: [u32; 2], target: [u32; 2]) -> Self {
Self::gaussian(plan, [0.0, 1.0], source, target)
}
fn gaussian(plan: &BlurPlan, axis: [f32; 2], source: [u32; 2], target: [u32; 2]) -> Self {
Self {
rect: [0.0, 0.0, plan.size[0] as f32, plan.size[1] as f32],
target: [target[0] as f32, target[1] as f32, 0.0, 0.0],
source: [1.0, 1.0, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
kernel: [axis[0], axis[1], plan.sigma, 1.0],
mode: [0.0, 1.0, 1.0, 0.0],
limit: texel_limit(plan.size),
..Self::UNCUT
}
}
pub(crate) fn composite(layer: &LayerCmd, plan: &BlurPlan, parent: &TargetSpace, source: [u32; 2]) -> Self {
let rect = parent.layer_rect(layer.bounds);
let (origin, _) = layer.painted();
let scale = 1.0 / plan.reduction as f32;
let border = (plan.border * plan.reduction) as f32;
let clips = layer.blur.map_or([None; MAX_ROUNDED_CLIPS], |blur| blur.clips);
let (clip, clip_inverse, clip_radii, clip_scale) = box_uniforms(clips[0], parent);
let (outer_clip, _, outer_clip_radii, _) = box_uniforms(clips[1], parent);
Self {
clip,
clip_inverse,
clip_radii,
outer_clip,
outer_clip_radii,
rect: [rect.x, rect.y, rect.width, rect.height],
target: [
parent.width,
parent.height,
parent.origin[0] - origin[0] as f32 + border,
parent.origin[1] - origin[1] as f32 + border,
],
source: [scale, scale, 1.0 / source[0] as f32, 1.0 / source[1] as f32],
kernel: [0.0, 0.0, 0.0, layer.opacity],
mode: [0.0, 1.0, clip_scale, 1.0],
limit: texel_limit(plan.size),
..Self::UNCUT
}
}
pub(crate) fn backdrop(
region: &crate::layout::backdrop::BackdropRegion,
plan: &BlurPlan,
parent: &TargetSpace,
source: [u32; 2],
) -> Self {
let composite = Self::composite(®ion.layer, plan, parent, source);
let (mask, mask_inverse, radii, mask_scale) = box_uniforms(Some(region.mask), parent);
Self {
mask,
mask_inverse,
radii,
mode: [composite.mode[0], mask_scale, composite.mode[2], composite.mode[3]],
..composite
}
}
const UNCUT: Self = Self {
rect: [0.0; 4],
target: [0.0; 4],
source: [0.0; 4],
kernel: [0.0; 4],
mode: [0.0, 1.0, 1.0, 0.0],
limit: [0.0; 4],
mask: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
mask_inverse: [1.0, 0.0, 0.0, 1.0],
radii: [0.0; 4],
clip: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
clip_inverse: [1.0, 0.0, 0.0, 1.0],
clip_radii: [0.0; 4],
outer_clip: [0.0, 0.0, EVERYWHERE, EVERYWHERE],
outer_clip_radii: [0.0; 4],
};
}
#[cfg(feature = "render")]
const EVERYWHERE: f32 = 1.0e9;
#[cfg(feature = "render")]
fn box_uniforms(rounded: Option<RoundedBox>, parent: &TargetSpace) -> ([f32; 4], [f32; 4], [f32; 4], f32) {
match rounded {
Some(rounded) => (
[
rounded.center[0] - parent.origin[0],
rounded.center[1] - parent.origin[1],
rounded.half[0],
rounded.half[1],
],
rounded.inverse,
rounded.radii,
rounded.scale,
),
None => ([0.0, 0.0, EVERYWHERE, EVERYWHERE], [1.0, 0.0, 0.0, 1.0], [0.0; 4], 1.0),
}
}
#[cfg(feature = "render")]
fn texel_limit(size: [u32; 2]) -> [f32; 4] {
[
0.5,
0.5,
(size[0] as f32 - 0.5).max(0.5),
(size[1] as f32 - 0.5).max(0.5),
]
}
fn first_at_or_after(range: Range<usize>, order: usize, order_of: &impl Fn(usize) -> usize) -> usize {
let (mut low, mut high) = (range.start, range.end);
while low < high {
let mid = low + (high - low) / 2;
if order_of(mid) < order {
low = mid + 1;
} else {
high = mid;
}
}
low
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolve_layers(
groups: &[OpacityGroup],
orders: usize,
viewport: [f32; 2],
scale: f32,
rects: &[RectCmd],
glyphs: &[GlyphCmd],
#[cfg(feature = "raster")] images: &[crate::images::ImageCmd],
layers: &mut Vec<LayerCmd>,
) {
layers.clear();
if groups.is_empty() {
return;
}
let mut bounds = LayerBoundsBuilder::new(orders);
rects.iter().for_each(|rect| bounds.add_rect(rect));
glyphs.iter().for_each(|glyph| bounds.add_glyph(glyph));
#[cfg(feature = "raster")]
images.iter().for_each(|image| bounds.add_image(image));
bounds.build(groups, viewport, scale, layers);
}
pub(crate) type Extent = [f32; 4];
const EMPTY_EXTENT: Extent = [f32::INFINITY, f32::INFINITY, f32::NEG_INFINITY, f32::NEG_INFINITY];
pub(crate) fn rect_extent(rect: &RectCmd) -> Extent {
let reach = AA_REACH + rect.shadow.map_or(0.0, |shadow| shadow.outset()) + rect.stroke_style.outset(rect.stroke);
let extent = transformed_extent(
rect.x,
rect.y,
rect.width,
rect.height,
rect.transform,
rect.transform_origin,
reach,
);
clipped(extent, rect.clip)
}
pub(crate) fn glyph_reach(glyph: &GlyphCmd) -> f32 {
if glyph.shadow_sigma > 0.0 {
(glyph.shadow_sigma * 2.0).ceil() + 1.0 + AA_REACH
} else {
AA_REACH
}
}
pub(crate) fn glyph_extent(glyph: &GlyphCmd) -> Extent {
let reach = glyph_reach(glyph);
let extent = transformed_extent(
glyph.x,
glyph.y,
glyph.width,
glyph.height,
glyph.transform,
glyph.transform_origin,
reach,
);
clipped(extent, glyph.clip)
}
#[cfg(feature = "raster")]
pub(crate) fn image_extent(image: &crate::images::ImageCmd) -> Extent {
let extent = transformed_extent(
image.x,
image.y,
image.width,
image.height,
image.transform,
image.transform_origin,
AA_REACH,
);
clipped(extent, image.clip)
}
fn union(a: Extent, b: Extent) -> Extent {
[a[0].min(b[0]), a[1].min(b[1]), a[2].max(b[2]), a[3].max(b[3])]
}
struct LayerBoundsBuilder {
extents: Vec<Extent>,
}
impl LayerBoundsBuilder {
fn new(orders: usize) -> Self {
Self {
extents: vec![EMPTY_EXTENT; orders],
}
}
fn add(&mut self, order: usize, extent: Extent) {
let Some(slot) = self.extents.get_mut(order) else {
return;
};
*slot = union(*slot, extent);
}
fn add_rect(&mut self, rect: &RectCmd) {
self.add(rect.order, rect_extent(rect));
}
fn add_glyph(&mut self, glyph: &GlyphCmd) {
self.add(glyph.order, glyph_extent(glyph));
}
#[cfg(feature = "raster")]
fn add_image(&mut self, image: &crate::images::ImageCmd) {
self.add(image.order, image_extent(image));
}
fn build(&mut self, groups: &[OpacityGroup], viewport: [f32; 2], scale: f32, layers: &mut Vec<LayerCmd>) {
for group in groups {
let end = group.end.min(self.extents.len());
let start = group.start.min(end);
let extent = self.extents[start..end].iter().copied().fold(EMPTY_EXTENT, union);
let (bounds, blur) = blurred_bounds(group, extent, viewport, scale);
if blur.is_some() && start < end {
let shown = [
bounds.x as f32,
bounds.y as f32,
(bounds.x + bounds.width) as f32,
(bounds.y + bounds.height) as f32,
];
self.extents[start] = union(self.extents[start], shown);
}
layers.push(LayerCmd {
start_order: group.start,
end_order: group.end,
opacity: group.opacity.clamp(0.0, 1.0),
bounds,
blur,
});
}
layers.sort_by(|a, b| a.start_order.cmp(&b.start_order).then(b.end_order.cmp(&a.end_order)));
}
}
fn transformed_extent(
x: f32,
y: f32,
width: f32,
height: f32,
transform: [f32; 4],
origin: [f32; 2],
reach: f32,
) -> Extent {
let [a, b, c, d] = transform;
let corners = [
(-reach, -reach),
(width + reach, -reach),
(-reach, height + reach),
(width + reach, height + reach),
];
corners.iter().fold(EMPTY_EXTENT, |extent, &(local_x, local_y)| {
let (dx, dy) = (local_x - origin[0], local_y - origin[1]);
let px = x + origin[0] + a * dx + c * dy;
let py = y + origin[1] + b * dx + d * dy;
union(extent, [px, py, px, py])
})
}
pub(crate) fn clipped(extent: Extent, clip: ClipRect) -> Extent {
if !clip.active {
return extent;
}
[
extent[0].max(clip.x.floor()),
extent[1].max(clip.y.floor()),
extent[2].min((clip.x + clip.width).ceil()),
extent[3].min((clip.y + clip.height).ceil()),
]
}
fn grown(extent: Extent, by: f32) -> Extent {
[extent[0] - by, extent[1] - by, extent[2] + by, extent[3] + by]
}
fn intersection(a: Extent, b: Extent) -> Extent {
[a[0].max(b[0]), a[1].max(b[1]), a[2].min(b[2]), a[3].min(b[3])]
}
fn blurred_bounds(
group: &OpacityGroup,
extent: Extent,
viewport: [f32; 2],
scale: f32,
) -> (LayerBounds, Option<LayerBlur>) {
let radius = if group.blur.is_finite() {
group.blur.clamp(0.0, MAX_BLUR_RADIUS)
} else {
0.0
};
let sigma = blur_sigma(radius) * scale;
if sigma < MIN_BLUR_SIGMA {
return (pixel_bounds(extent, viewport), None);
}
let reach = (sigma * 3.0).ceil();
let mut shown = grown(extent, reach);
let mut clips = [None; MAX_ROUNDED_CLIPS];
if let Some(clip) = group.clip {
let clip = clip.scaled(scale);
clips = rounded_clip_boxes(clip);
let (x, y, width, height) = (clip.x, clip.y, clip.width, clip.height);
shown = intersection(shown, [x.floor(), y.floor(), (x + width).ceil(), (y + height).ceil()]);
}
let bounds = pixel_bounds(shown, viewport);
if bounds.is_empty() {
return (bounds, None);
}
let pad = blur_pad(sigma) as f32;
let visible = [
bounds.x as f32,
bounds.y as f32,
(bounds.x + bounds.width) as f32,
(bounds.y + bounds.height) as f32,
];
let painted = intersection(grown(extent, pad), grown(visible, pad));
let (x0, y0, x1, y1) = (
painted[0].floor(),
painted[1].floor(),
painted[2].ceil(),
painted[3].ceil(),
);
if !(x1 > x0 && y1 > y0) {
return (LayerBounds::default(), None);
}
(
bounds,
Some(LayerBlur {
sigma,
x: x0 as i32,
y: y0 as i32,
width: (x1 - x0) as u32,
height: (y1 - y0) as u32,
clips,
}),
)
}
fn pixel_bounds(extent: Extent, viewport: [f32; 2]) -> LayerBounds {
let x0 = extent[0].floor().max(0.0);
let y0 = extent[1].floor().max(0.0);
let x1 = extent[2].ceil().min(viewport[0].ceil());
let y1 = extent[3].ceil().min(viewport[1].ceil());
if !(x1 > x0 && y1 > y0) {
return LayerBounds::default();
}
LayerBounds {
x: x0 as u32,
y: y0 as u32,
width: (x1 - x0) as u32,
height: (y1 - y0) as u32,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn layer(start_order: usize, end_order: usize, opacity: f32) -> LayerCmd {
LayerCmd {
start_order,
end_order,
opacity,
bounds: LayerBounds {
x: 0,
y: 0,
width: 4,
height: 4,
},
blur: None,
}
}
fn plan(orders: &[usize], layers: &[LayerCmd]) -> Vec<(Option<usize>, Vec<LayerStep>)> {
let mut plan = LayerPlan::default();
plan.build(orders.len(), |index| orders[index], layers, &[]);
plan
.targets()
.iter()
.map(|target| (target.layer, plan.steps(target).to_vec()))
.collect()
}
#[test]
fn a_rounded_box_covers_what_is_inside_its_corners_under_any_transform() {
let upright = RoundedBox::rect(10.0, 20.0, 40.0, 20.0, [8.0, 0.0, 0.0, 0.0]);
assert_eq!(upright.extent(), [10.0, 20.0, 50.0, 40.0]);
assert_eq!(upright.coverage(30.5, 30.5), 1.0);
assert_eq!(upright.coverage(50.0, 30.5), 0.5);
assert_eq!(upright.coverage(51.5, 30.5), 0.0);
assert_eq!(upright.coverage(11.0, 21.0), 0.0);
assert_eq!(upright.coverage(49.0, 21.0), 1.0);
let turned =
RoundedBox::transformed(10.0, 20.0, 40.0, 20.0, [0.0; 4], [0.0, 1.0, -1.0, 0.0], [20.0, 10.0]).unwrap();
let extent = turned.extent();
assert!(
(extent[0] - 20.0).abs() < 1e-4 && (extent[2] - 40.0).abs() < 1e-4,
"{extent:?}"
);
assert!(
(extent[1] - 10.0).abs() < 1e-4 && (extent[3] - 50.0).abs() < 1e-4,
"{extent:?}"
);
assert_eq!(turned.coverage(30.5, 12.5), 1.0);
assert_eq!(turned.coverage(15.5, 30.5), 0.0);
let doubled = RoundedBox::transformed(10.0, 20.0, 40.0, 20.0, [0.0; 4], [2.0, 0.0, 0.0, 2.0], [0.0, 0.0]).unwrap();
assert_eq!(doubled.extent(), [10.0, 20.0, 90.0, 60.0]);
assert_eq!((doubled.coverage(89.0, 40.0), doubled.coverage(90.0, 40.0)), (1.0, 0.5));
assert!(RoundedBox::transformed(0.0, 0.0, 4.0, 4.0, [0.0; 4], [1.0, 2.0, 2.0, 4.0], [0.0, 0.0]).is_none());
}
#[test]
fn a_narrow_blur_runs_on_the_layer_and_a_wide_one_on_a_reduced_copy() {
let blur = |sigma: f32| LayerBlur {
sigma,
x: -10,
y: 0,
width: 201,
height: 100,
clips: [None; MAX_ROUNDED_CLIPS],
};
let narrow = BlurPlan::new(&blur(4.0));
assert_eq!(
(narrow.reduction, narrow.sigma, narrow.size, narrow.border),
(1, 4.0, [201, 100], 0)
);
assert_eq!(BlurPlan::new(&blur(MAX_PASS_SIGMA)).reduction, 1);
for sigma in [9.0, 20.0, 100.0, 384.0] {
let plan = BlurPlan::new(&blur(sigma));
let r = plan.reduction as f32;
assert!(
plan.reduction.is_power_of_two() && plan.reduction > 1,
"sigma {sigma}: {plan:?}"
);
assert!(plan.sigma <= MAX_PASS_SIGMA, "sigma {sigma}: {plan:?}");
assert_eq!(plan.border, 1);
assert_eq!(
plan.size,
[
201_u32.div_ceil(plan.reduction) + 2,
100_u32.div_ceil(plan.reduction) + 2
]
);
let total = ((r * r - 1.0) / 12.0 + r * r / 6.0 + (plan.sigma * r).powi(2)).sqrt();
assert!((total - sigma).abs() < sigma * 0.01, "sigma {sigma}: {total}");
}
}
#[test]
fn a_blurred_group_shows_inside_its_clip_and_is_painted_past_it() {
let group = OpacityGroup {
start: 0,
end: 1,
opacity: 1.0,
blur: 8.0,
clip: Some(ClipRect::rect(10.0, 0.0, 50.0, 100.0)),
};
let (bounds, blur) = blurred_bounds(&group, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
let blur = blur.expect("a blur");
assert_eq!(blur.sigma, 8.0);
assert_eq!(
bounds,
LayerBounds {
x: 20,
y: 6,
width: 80,
height: 78
}
);
assert_eq!((blur.x, blur.y), (20 - 27, 30 - 27));
assert_eq!(
(blur.x + blur.width as i32, blur.y + blur.height as i32),
(100 + 27, 60 + 27)
);
assert_eq!(
blur.clips, [None; MAX_ROUNDED_CLIPS],
"a clip without corners is in the bounds"
);
let rounded = OpacityGroup {
clip: Some(ClipRect::rounded_rect(
10.0,
0.0,
50.0,
100.0,
Some(crate::node::border::BorderRadius::new(4.0, 0.0, 0.0, 0.0)),
)),
..group
};
let (_, blur) = blurred_bounds(&rounded, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
assert_eq!(
blur.unwrap().clips,
[
Some(RoundedBox::rect(20.0, 0.0, 100.0, 200.0, [8.0, 0.0, 0.0, 0.0])),
None
]
);
let panel = ClipRect::rounded_rect(
0.0,
0.0,
50.0,
100.0,
Some(crate::node::border::BorderRadius::all(10.0)),
);
let rail = ClipRect::rounded_rect(
0.0,
80.0,
50.0,
20.0,
Some(crate::node::border::BorderRadius::new(4.0, 4.0, 0.0, 0.0)),
);
let nested = OpacityGroup {
clip: Some(panel.intersect(rail)),
..group
};
let (_, blur) = blurred_bounds(&nested, [0.0, 0.0, 100.0, 200.0], [100.0, 200.0], 2.0);
assert_eq!(
blur.unwrap().clips,
[
Some(RoundedBox::rect(0.0, 160.0, 100.0, 40.0, [8.0, 8.0, 0.0, 0.0])),
Some(RoundedBox::rect(0.0, 0.0, 100.0, 200.0, [20.0; 4])),
]
);
let unblurred = OpacityGroup { blur: 0.0, ..group };
let (bounds, blur) = blurred_bounds(&unblurred, [20.0, 30.0, 200.0, 60.0], [100.0, 100.0], 2.0);
assert!(blur.is_none());
assert_eq!((bounds.x, bounds.width), (20, 80));
}
fn backdrop(order: usize) -> BackdropCmd {
BackdropCmd {
order,
x: 0.0,
y: 0.0,
width: 4.0,
height: 4.0,
radii: [0.0; 4],
transform: [1.0, 0.0, 0.0, 1.0],
transform_origin: [2.0, 2.0],
clip: ClipRect::default(),
sigma: 4.0,
opacity: 1.0,
}
}
#[test]
fn backdrop_blurs_split_the_draws_of_the_target_they_are_in() {
let orders = [0, 2, 4, 6, 9];
let layers = [layer(3, 7, 0.5), layer(5, 7, 0.0)];
let backdrops = [1, 3, 5, 7, 8].map(backdrop);
let mut plan = LayerPlan::default();
plan.build(orders.len(), |index| orders[index], &layers, &backdrops);
let targets: Vec<_> = plan
.targets()
.iter()
.map(|target| (target.layer, plan.steps(target).to_vec()))
.collect();
assert_eq!(
targets,
vec![
(Some(0), vec![LayerStep::Backdrop(1), LayerStep::Draws(2..3)]),
(
None,
vec![
LayerStep::Draws(0..1),
LayerStep::Backdrop(0),
LayerStep::Draws(1..2),
LayerStep::Composite(0),
LayerStep::Backdrop(3),
LayerStep::Backdrop(4),
LayerStep::Draws(4..5),
]
),
]
);
assert!(plan.has_backdrops());
plan.build(orders.len(), |index| orders[index], &layers, &[]);
assert!(!plan.has_backdrops());
}
#[test]
fn without_layers_the_window_paints_every_draw_in_one_step() {
assert_eq!(plan(&[0, 1, 2], &[]), vec![(None, vec![LayerStep::Draws(0..3)])]);
}
#[test]
fn nested_layers_are_painted_before_the_targets_they_composite_into() {
let orders = [0, 1, 2, 3, 3, 4, 5, 6];
let layers = [layer(1, 6, 0.5), layer(3, 5, 0.4)];
assert_eq!(
plan(&orders, &layers),
vec![
(Some(1), vec![LayerStep::Draws(3..6)]),
(
Some(0),
vec![LayerStep::Draws(1..3), LayerStep::Composite(0), LayerStep::Draws(6..7)]
),
(
None,
vec![LayerStep::Draws(0..1), LayerStep::Composite(1), LayerStep::Draws(7..8)]
),
]
);
}
#[test]
fn an_invisible_layer_drops_its_draws_and_inner_layers() {
let orders = [0, 1, 2, 3];
let layers = [layer(1, 3, 0.0), layer(2, 3, 0.5)];
assert_eq!(
plan(&orders, &layers),
vec![(None, vec![LayerStep::Draws(0..1), LayerStep::Draws(3..4)])]
);
}
#[test]
fn a_layer_without_draws_is_skipped() {
let orders = [0, 1, 5];
let layers = [layer(2, 4, 0.5)];
assert_eq!(
plan(&orders, &layers),
vec![(None, vec![LayerStep::Draws(0..2), LayerStep::Draws(2..3)])]
);
}
#[test]
fn bounds_cover_transformed_content_in_whole_pixels_within_clip_and_viewport() {
let identity = [1.0, 0.0, 0.0, 1.0];
let extent = transformed_extent(10.25, 20.5, 30.0, 10.0, identity, [15.0, 5.0], 0.0);
assert_eq!(extent, [10.25, 20.5, 40.25, 30.5]);
assert_eq!(
pixel_bounds(extent, [100.0, 100.0]),
LayerBounds {
x: 10,
y: 20,
width: 31,
height: 11
}
);
let turned = transformed_extent(0.0, 0.0, 40.0, 10.0, [0.0, 1.0, -1.0, 0.0], [20.0, 5.0], 0.0);
assert!((turned[0] - 15.0).abs() < 1e-4 && (turned[2] - 25.0).abs() < 1e-4);
assert!((turned[1] + 15.0).abs() < 1e-4 && (turned[3] - 25.0).abs() < 1e-4);
let clip = ClipRect::rect(12.0, 0.0, 8.0, 200.0);
assert_eq!(clipped(extent, clip), [12.0, 20.5, 20.0, 30.5]);
assert_eq!(pixel_bounds([90.0, 90.0, 120.0, 95.0], [100.0, 100.0]).width, 10);
assert!(pixel_bounds([120.0, 0.0, 130.0, 10.0], [100.0, 100.0]).is_empty());
}
}