iris: a mask is a shape, not a rectangle -- .masked_by, and touch obeys it

Iris, on the code fence: "the code block scrolling currently masks in an
inner rectangle. Ideally masks should have a shape associated with them,
rounded rectangle being one of them ... so that the mask becomes the
parent container with rounded edges. Make sure alpha works properly with
it, eg. on the corners where alpha should be decreased / multiplied."

`Mask` is now `{ primitive, parent }` -- the slot of a primitive already
written, plus the mask this one nests inside. The fragment stage
evaluates that primitive's own coverage at the masked pixel, through the
same `rounded_rect_coverage` a drawn rect goes through, and multiplies it
into the alpha along the whole `parent` chain. Nothing about the shape is
copied, so a rounded container's corner and its children's clipped corner
are one piece of arithmetic and cannot drift; two nested feathers dim a
pixel twice, which is the multiply she asked for.

`.masked()` is unchanged for callers: it writes an undrawn rect
(`Drawn::No`/`NOT_DRAWN` -- owned, moved, resized and freed like any
other primitive, simply never rasterized) and points at that, so square
clipping is the same mechanism rather than a special case. New
`.masked_by(shape)` draws `shape` behind the content in its own layer and
clips to the first primitive it drew, with no radius written twice; it
replaces `.masked().background(w)`, which drew both and clipped to the
box. `transcript-ui`'s `BlockFrame::Verbatim` is the first caller.

Hit-testing applies the shape (`SensorUi::run_sensors` ->
`UiRenderState::mask_admits`, coverage above one half, which is where the
drawn edge is), as well as the widget's own box -- the two ask different
questions and both have to hold. `primitive_corners` is a floor-for-floor
transliteration of the shader's `corners_of`, not `region.to_px()`: the
phone's 2.55 density puts nothing on a whole pixel, and skipping the
rounding disagrees with the pixels by up to one along each edge.

A mask's shape must be a rect, asserted by name in `set_mask_to`. A glyph
would need a CPU-side alpha plane before the hit test could agree with
the shader, and a standalone image a bind-group switch the fragment stage
cannot make. So no texture mask exists; the branch where one would go is
in both copies of `mask_coverage`. docs/LAYOUT.md's section end lists this
and the three other places the code is narrower than the design.

Tests. Layer 1, `layout_tests.rs`: the child's coverage swept across the
container's corner arc equals the container's own exactly; nested masks
multiply rather than intersect, asserted where both feathers are partial,
which is the only place the two differ; a press in a rounded-away corner
misses while one inside the curve and one on a straight edge hit; and
`a_plain_mask_still_clips_to_a_square_box`, the half this had no reason to
touch. The first version of the corner test swept the straight chord
between the arc's ends, which lies inside the circle everywhere -- it
proved nothing and said so, which is why it counts both sides now.

`iris/tests/mask_sdf.rs` is the only test here that needs a GPU: it lifts
`distance_from_rect` and `rounded_rect_coverage` out of
`iris_core::SHAPE_SHADER` by name -- lifted, not copied, since a copy
would be edited alongside the shader -- and runs them in a compute pass
over ~200k points at five radii against `iris_core::rounded_rect_coverage`.
Worst disagreement under 1e-5; the negative control (`+ 0.01` inside the
shader's smoothstep) fails it at 0.03.

Layer 2 for looking: `./run-headless.sh phone --phone --shot /tmp/mask.png
--seconds 6 -- -p transcript-fixture` draws the fixture's horizontally
scrolled code fence clipped on the curve at both top corners.

Two things found on the way and fixed here:

- The winit backend had the defect the Android one was fixed for in
  85869d0 -- `Backends::PRIMARY` and an `.expect` on the adapter. This
  VM's Venus device disappears when the host runs out of virgl contexts,
  which happened mid-task, and layer 2 aborted with `Could not get
  adapter!` while GL sat there working. It probes and rebuilds the
  instance on `Backends::GL` exactly as Android does now, and the request
  names the backends it tried. The rule had been written on one member of
  a set of two.
- `active_primitive_count` counted mask shapes, so `iris::frame`'s
  `primitives=` -- a number Iris reads off a phone report as "how much is
  on screen" -- would have gained one per masked widget.

`widget_trait!` now accepts a `///` doc comment on its functions, since
`masked_by` is public API and rustdoc is where a contract is read.

docs/LAYOUT.md, docs/RUST.md (both queue boxes, the commands, and where
the GPU test sits among the three layers), docs/IRIS.md and
docs/IRIS_TODO.md ("Masks defined relative to each other", now closed).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
irisandClaude Opus 5 committed 2026-09-08 02:18:57 -04:00
1 parent 3eb0e033d5
commit 38bf6309cb
23 files changed
+1284 -122

No files matched your search

+37 -12
View File
@@ -49,22 +49,47 @@ impl MaskIdx {
pub type MoveIdx = Id<u32>;
/// A clip, as a reference to a primitive already written plus the mask it
/// nests inside. The fragment stage evaluates that primitive's coverage
/// *at the masked pixel* -- for a rect, the same `rounded_rect_coverage`
/// from the same SDF the rect itself is drawn with -- and multiplies it
/// into the pixel's alpha, so a rounded container's corner and its
/// children's clipped corner are the same arithmetic and cannot disagree.
/// See LAYOUT.md's "Masks with a shape".
///
/// **No `kind` and no `flags`**, which the design sketched: the referenced
/// instance already carries its own `binding`, and a copy of it here is a
/// second thing to keep in step; alpha-only is the only mode there is, so
/// there is nothing to select. Both are a field away if a second mode
/// appears.
#[repr(C)]
#[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)]
pub struct Mask {
pub region: UiRegion,
/// The mask-owning widget's own move slot -- resolved in the fragment
/// shader against the same chain the vertex shader walks for a
/// primitive's own corners, so a mask and the content clipped by it
/// can move independently. See LAYOUT.md section 2b.
pub move_idx: MoveIdx,
/// The slot in `UiRenderState::primitives` of the primitive whose
/// coverage this mask is. Today always a `RectPrimitive`: a glyph or
/// a standalone image would need, respectively, a CPU-side alpha
/// plane for the hit test to agree with the shader, and a bind-group
/// switch the fragment stage cannot make -- `Painter::set_mask`
/// rejects both by name rather than leaving the shader to read a rect
/// that is not there.
///
/// Who owns it depends on which way the mask was set. A plain
/// `.masked()` writes its own undrawn rect, so the primitive is in
/// the masking widget's `ActiveData::primitives` and lives exactly as
/// long as the mask. `.masked_by(shape)` points at a *child's*
/// primitive, which that child can free on any redraw of its own --
/// so `UiRenderState::remask_shape_users` marks the mask's owner for
/// redraw whenever a referenced slot is freed, since that widget's
/// own `set_mask` is the only thing that resolves the slot again.
pub primitive: u32,
/// The mask this one was set *inside* (`MaskIdx::NONE` at the top), so
/// clipping nests: the fragment stage walks the chain and a pixel has
/// to be inside every mask on it. Chained rather than intersected on
/// the CPU because each mask moves with its own widget -- a code fence
/// inside a transcript row carries the row's scroll, the list's own
/// box does not, and one region resolved when the fence was last drawn
/// gets the second of those wrong as soon as the row moves.
/// clipping nests: the fragment stage walks the chain and multiplies
/// every coverage on it, which is what makes a pixel inside two
/// feathered corners dimmed by both. Chained rather than intersected
/// on the CPU because each mask moves with its own widget -- a code
/// fence inside a transcript row carries the row's scroll, the list's
/// own box does not, and one region resolved when the fence was last
/// drawn gets the second of those wrong as soon as the row moves.
///
/// A child holds one ref on its parent's slot (`Painter::set_mask`),
/// released when the child's own slot goes
+8 -1
View File
@@ -18,6 +18,7 @@ mod atlas;
mod data;
mod frame_report;
mod primitive;
mod sdf;
mod texture;
mod util;
@@ -25,8 +26,14 @@ pub use atlas::*;
pub use data::{Mask, MaskIdx, MoveIdx, MoveOffset};
pub use frame_report::{FrameReport, FrameStats, JANK_THRESHOLD};
pub use primitive::*;
pub use sdf::{distance_from_rect, rounded_rect_coverage};
const SHAPE_SHADER: &str = include_str!("./shader.wgsl");
/// The one shader every primitive is drawn with. Public so a test can run
/// a function out of it against the CPU transliteration in [`sdf`] --
/// `iris/tests/mask_sdf.rs`, which LAYOUT.md's "Masks with a shape" turns
/// on: a masked corner that cannot be tapped and a masked corner that is
/// not drawn are only the same corner while the two agree.
pub const SHAPE_SHADER: &str = include_str!("./shader.wgsl");
/// The `wgpu::Limits` both platform backends (`android::render::
/// AndroidRenderer::new`, `default::render::UiRenderer::new`) ask
+32 -3
View File
@@ -21,6 +21,10 @@ pub const IMAGE_BINDING: u32 = 1;
pub trait Primitive: Pod {
const BINDING: u32;
fn vec(data: &mut PrimitiveData) -> &mut PrimitiveVec<Self>;
/// The read-only half of [`Self::vec`], for a caller that wants to
/// look one entry up rather than write one -- a mask reading the
/// radius of the rect it clips to ([`Primitives::data`]).
fn vec_ref(data: &PrimitiveData) -> &PrimitiveVec<Self>;
}
macro_rules! primitives {
@@ -86,6 +90,9 @@ macro_rules! primitives {
fn vec(data: &mut PrimitiveData) -> &mut PrimitiveVec<Self> {
&mut data.$name
}
fn vec_ref(data: &PrimitiveData) -> &PrimitiveVec<Self> {
&data.$name
}
}
)*
};
@@ -287,6 +294,15 @@ impl Primitives {
&self.instances[slot as usize]
}
/// The per-primitive data behind `slot`, or `None` if that slot holds
/// a different kind of primitive -- the `binding` check is the same
/// one the shader's dispatch switch makes, and it is what stops a
/// caller reading a glyph's index into the rect table.
pub fn primitive_data<P: Primitive>(&self, slot: u32) -> Option<&P> {
let inst = self.instance(slot);
(inst.binding == P::BINDING).then(|| &P::vec_ref(&self.data)[inst.idx as usize])
}
pub fn region_mut(&mut self, h: &PrimitiveHandle) -> &mut UiRegion {
self.updated = true;
&mut self.instances[h.slot as usize].region
@@ -391,10 +407,23 @@ pub struct OrderChange {
pub pos: usize,
}
/// Whether a primitive goes into its layer's draw order. [`Drawn::No`] is
/// a primitive written only to be *referenced* -- a mask's shape
/// (LAYOUT.md's "Masks with a shape"). It is owned, moved, resized and
/// freed exactly like any other; it is simply never rasterized.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Drawn {
Yes,
No,
}
/// The `pos` of a [`Drawn::No`] primitive: it is in no layer's order, so
/// there is no position to renumber or free.
pub const NOT_DRAWN: usize = usize::MAX;
/// Where one primitive lives: its stable slot in the global arena, and
/// where in a layer's draw order it currently sits. A handle with no
/// layer position (`pos == NOT_DRAWN`) is a primitive that exists to be
/// *referenced* -- a mask's shape -- and is never rasterized.
/// where in a layer's draw order it currently sits ([`NOT_DRAWN`] if it is
/// only referenced).
#[derive(Debug)]
pub struct PrimitiveHandle {
pub layer: usize,
+54
View File
@@ -0,0 +1,54 @@
//! The rounded-rect coverage function, on the CPU.
//!
//! `shader.wgsl`'s `distance_from_rect`/`rounded_rect_coverage` are a
//! transliteration of these two, line for line, and
//! `mask_sdf_matches_the_shader` in `iris`'s layout tests compares the two
//! at a grid of points against values the shader itself produced. They are
//! kept together here, in the crate both a renderer and a hit test can
//! reach, because LAYOUT.md's "Masks with a shape" turns on the two
//! agreeing: a masked corner that cannot be tapped and a masked corner
//! that is not drawn have to be the same corner, and they are only the
//! same corner while one function decides both.
//!
//! Window pixels throughout, matching the shader's `pos` -- not `UiRegion`
//! units, which the shader has already resolved by the time it evaluates
//! this.
use crate::util::Vec2;
/// The signed distance from `pos` to a rounded rect given by its centre,
/// its corner offset (half its size) and its corner `radius`. Negative
/// inside.
pub fn distance_from_rect(pos: Vec2, center: Vec2, corner: Vec2, radius: f32) -> f32 {
// vec from center to pixel
let p = pos - center;
// vec from inner rect corner to pixel
let q = Vec2::new(
p.x.abs() - (corner.x - radius),
p.y.abs() - (corner.y - radius),
);
let clamped = Vec2::new(q.x.max(0.0), q.y.max(0.0));
(clamped.x * clamped.x + clamped.y * clamped.y).sqrt() - radius
}
/// How much of the pixel at `pos` a rounded rect covers, anti-aliased over
/// the half-pixel either side of its edge: 1 well inside, 0 well outside.
///
/// The half-pixel feather is why a hit test asks for **more than a half**
/// rather than "any coverage at all": half is where the geometric edge is,
/// so the two answer the same question the drawn shape does.
pub fn rounded_rect_coverage(pos: Vec2, top_left: Vec2, bot_right: Vec2, radius: f32) -> f32 {
let edge: f32 = 0.5;
let corner = (bot_right - top_left) / 2.0;
let center = top_left + corner;
let dist = distance_from_rect(pos, center, corner, radius);
1.0 - smoothstep(-edge.min(radius), edge, dist)
}
/// WGSL's `smoothstep`, which Rust has no equivalent of. Undefined in WGSL
/// when `low == high`, which is why the caller above never passes a zero
/// radius into the low edge without `edge` bounding it.
fn smoothstep(low: f32, high: f32, x: f32) -> f32 {
let t = ((x - low) / (high - low)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
+71 -36
View File
@@ -30,13 +30,11 @@ struct GlyphInfo {
flags: u32,
}
/// Mirrors `Mask` in data.rs: the slot of the primitive whose coverage
/// clips this mask's subtree, and the mask it nests inside
/// (`4294967295u` at the top).
struct Mask {
x: UiSpan,
y: UiSpan,
move_idx: u32,
/// The mask this one is nested inside, or `4294967295u`. Mirrors
/// `Mask::parent` in data.rs; walked below with the same bound the
/// move chain uses.
primitive: u32,
parent: u32,
}
@@ -57,11 +55,6 @@ struct UiScalar {
abs: f32,
}
struct UiVec2 {
rel: vec2<f32>,
abs: vec2<f32>,
}
// The shared glyph atlas: every page is one layer. Growing it recreates this
// texture with headroom and copies the old layers across -- see
// GpuTextures::grow_array -- rather than the binding_array<texture_2d<f32>>
@@ -157,6 +150,27 @@ struct Region {
bot_right: vec2<f32>,
}
/// One primitive's on-screen corners in window pixels. Written once and
/// used by both stages: the vertex stage for the primitive it is drawing,
/// the fragment stage for a mask's -- so the shape a mask clips to and the
/// shape that was drawn cannot be computed two different ways.
struct Corners {
top_left: vec2<f32>,
bot_right: vec2<f32>,
}
fn corners_of(inst: PrimitiveInstance) -> Corners {
let top_left_rel = vec2(inst.x.start.rel, inst.y.start.rel);
let top_left_abs = vec2(inst.x.start.abs, inst.y.start.abs);
let bot_right_rel = vec2(inst.x.end.rel, inst.y.end.rel);
let bot_right_abs = vec2(inst.x.end.abs, inst.y.end.abs);
let move_delta = resolve_move(inst.move_idx);
return Corners(
floor(top_left_rel * window.dim) + floor(top_left_abs) + move_delta,
floor(bot_right_rel * window.dim) + floor(bot_right_abs) + move_delta,
);
}
@vertex
fn vs_main(
@builtin(vertex_index) vi: u32,
@@ -165,14 +179,9 @@ fn vs_main(
var out: VertexOutput;
let inst = instances[in.slot];
let top_left_rel = vec2(inst.x.start.rel, inst.y.start.rel);
let top_left_abs = vec2(inst.x.start.abs, inst.y.start.abs);
let bot_right_rel = vec2(inst.x.end.rel, inst.y.end.rel);
let bot_right_abs = vec2(inst.x.end.abs, inst.y.end.abs);
let move_delta = resolve_move(inst.move_idx);
let top_left = floor(top_left_rel * window.dim) + floor(top_left_abs) + move_delta;
let bot_right = floor(bot_right_rel * window.dim) + floor(bot_right_abs) + move_delta;
let c = corners_of(inst);
let top_left = c.top_left;
let bot_right = c.bot_right;
let size = bot_right - top_left;
let uv = vec2<f32>(
@@ -214,28 +223,38 @@ fn fs_main(
}
}
// Every mask on the chain, not just the innermost: a widget that set
// its own mask inside another is clipped by both, and each carries its
// own move slot (`Mask::parent` in data.rs).
// its own mask inside another is clipped by both, and the coverages
// multiply -- so a pixel inside two feathered corners is dimmed by
// both, which is what a compositor does (`Mask::parent` in data.rs).
var mask_idx = in.mask_idx;
for (var step = 0u; step < PARENT_CHAIN_LIMIT; step++) {
if mask_idx == 4294967295u {
break;
}
let mask = masks[mask_idx];
let mask_delta = resolve_move(mask.move_idx);
let tl = UiVec2(vec2(mask.x.start.rel, mask.y.start.rel), vec2(mask.x.start.abs, mask.y.start.abs));
let br = UiVec2(vec2(mask.x.end.rel, mask.y.end.rel), vec2(mask.x.end.abs, mask.y.end.abs));
let top_left = floor(tl.rel * window.dim) + floor(tl.abs) + mask_delta;
let bot_right = floor(br.rel * window.dim) + floor(br.abs) + mask_delta;
if pos.x < top_left.x || pos.x > bot_right.x || pos.y < top_left.y || pos.y > bot_right.y {
color *= 0.0;
}
color.a *= mask_coverage(pos, mask);
mask_idx = mask.parent;
}
return color;
}
/// How much of `pos` one mask lets through: the referenced primitive's
/// own coverage at that pixel, from the same SDF the primitive is drawn
/// with. Nothing about the shape is copied into the mask, so a rounded
/// container's corner and its children's clipped corner are the same
/// arithmetic.
fn mask_coverage(pos: vec2<f32>, mask: Mask) -> f32 {
let inst = instances[mask.primitive];
if inst.binding != RECT {
// Unreachable: `Painter::set_mask` rejects a glyph or an image
// shape by name (see `Mask::primitive`). Letting the pixel
// through rather than reading a `rects` entry that is not there.
return 1.0;
}
let c = corners_of(inst);
return rounded_rect_coverage(pos, c.top_left, c.bot_right, rects[inst.idx].radius);
}
fn draw_texture(region: Region) -> vec4<f32> {
return textureSample(image_texture, samp, region.uv);
}
@@ -251,19 +270,35 @@ fn draw_glyph(region: Region, g: GlyphInfo) -> vec4<f32> {
return color;
}
/// The anti-aliased coverage of a rounded rect at one pixel -- the one
/// function both a drawn rect and a mask go through, and the
/// transliteration of `iris_core::rounded_rect_coverage` on the CPU,
/// which the hit test uses so a corner that cannot be tapped and a corner
/// that is not drawn are the same corner.
fn rounded_rect_coverage(
pos: vec2<f32>,
top_left: vec2<f32>,
bot_right: vec2<f32>,
radius: f32,
) -> f32 {
let edge = 0.5;
let corner = (bot_right - top_left) / 2.0;
let center = top_left + corner;
let dist = distance_from_rect(pos, center, corner, radius);
return 1.0 - smoothstep(-min(edge, radius), edge, dist);
}
fn draw_rounded_rect(region: Region, rect: Rect) -> vec4<f32> {
var color = unpack4x8unorm(rect.color);
let edge = 0.5;
let size = region.bot_right - region.top_left;
let corner = size / 2.0;
let center = region.top_left + corner;
let dist = distance_from_rect(region.pos, center, corner, rect.radius);
color.a *= 1.0 - smoothstep(-min(edge, rect.radius), edge, dist);
color.a *= rounded_rect_coverage(region.pos, region.top_left, region.bot_right, rect.radius);
if rect.thickness > 0.0 {
let size = region.bot_right - region.top_left;
let corner = size / 2.0;
let center = region.top_left + corner;
let dist2 = distance_from_rect(region.pos, center, corner - rect.thickness, rect.inner_radius);
color.a *= smoothstep(-min(edge, rect.inner_radius), edge, dist2);
}
+64 -7
View File
@@ -1,7 +1,10 @@
use crate::{
RenderedText, Size, StrongWidget, TextAttrs, TextBuffer, TextData, TextureHandle, UiRegion,
UiRenderState, UiRsc, UiScalar, UiVec2, WidgetId,
render::{GlyphPrimitive, Mask, MaskIdx, MoveIdx, Primitive, PrimitiveHandle, PrimitiveInst},
Color, RenderedText, Size, StrongWidget, TextAttrs, TextBuffer, TextData, TextureHandle,
UiRegion, UiRenderState, UiRsc, UiScalar, UiVec2, WidgetId,
render::{
Drawn, GlyphPrimitive, Mask, MaskIdx, MoveIdx, Primitive, PrimitiveHandle, PrimitiveInst,
RectPrimitive,
},
util::Vec2,
};
@@ -26,8 +29,20 @@ pub struct Painter<'a> {
impl<'a> Painter<'a> {
fn primitive_at<P: Primitive>(&mut self, primitive: P, region: UiRegion) {
self.write_primitive(primitive, region, Drawn::Yes);
}
/// The one path every primitive this widget owns goes through --
/// drawn or, for a mask's shape, only referenced.
fn write_primitive<P: Primitive>(
&mut self,
primitive: P,
region: UiRegion,
drawn: Drawn,
) -> u32 {
let h = self.state.write_primitive(
self.layer,
drawn,
PrimitiveInst {
id: self.id,
primitive,
@@ -40,7 +55,9 @@ impl<'a> Painter<'a> {
// TODO: I have no clue if this works at all :joy:
self.rsc.ui_mut().masks.push_ref(self.mask);
}
let slot = h.slot;
self.primitives.push(h);
slot
}
/// Writes a primitive to be rendered
@@ -55,16 +72,46 @@ impl<'a> Painter<'a> {
/// Clip everything this widget draws, itself and its descendants, to
/// `region`. One call per widget; a widget drawn inside another
/// widget's mask nests instead -- the new mask chains to the inherited
/// one (`Mask::parent`) and the fragment stage requires a pixel to be
/// inside both, which is what lets a transcript row's code fence clip
/// one (`Mask::parent`) and the fragment stage multiplies both
/// coverages, which is what lets a transcript row's code fence clip
/// to itself *and* to the list it scrolls inside.
///
/// The clip is a **primitive**, not a rectangle copied into the mask:
/// this writes an undrawn `RectPrimitive` at `region` and points the
/// mask at it, so the fragment stage evaluates the same rounded-rect
/// coverage a drawn rect gets. See LAYOUT.md's "Masks with a shape".
///
/// The slot is allocated once and **rewritten in place** on every
/// later draw rather than pushed again, because a descendant whose own
/// region did not change is not redrawn (`draw_inner`'s fast path) and
/// so keeps pointing at whichever slot it was drawn under. See
/// `ActiveData::own_mask` for what pushing a fresh one cost.
pub fn set_mask(&mut self, region: UiRegion) {
let shape = self.write_primitive(RectPrimitive::color(Color::NONE), region, Drawn::No);
self.set_mask_to(shape);
}
/// Clip everything this widget draws after this call to `shape`'s
/// own shape -- the first primitive `shape`'s subtree drew, which
/// must already have been drawn this frame
/// (`UiRenderState::first_primitive`). What `.masked_by()` uses to
/// clip a container's content to the rounded background it draws,
/// with no radius argument anywhere that could fall out of step with
/// the one being drawn.
pub fn set_mask_to_widget<W: ?Sized>(&mut self, shape: &StrongWidget<W>) {
let slot = self.state.first_primitive(shape.id()).unwrap_or_else(|| {
panic!(
"'{}' was given as a mask's shape but drew no primitive, so there is nothing to \
clip to",
self.rsc.widgets().label(shape.id()),
)
});
self.set_mask_to(slot);
}
/// Points this widget's mask at a primitive that has already been
/// written -- the shared half of [`Self::set_mask`].
fn set_mask_to(&mut self, shape: u32) {
// `assert!`, not `debug_assert!`: one comparison per widget draw,
// and the second call silently *replacing* the first is a widget
// drawn unclipped -- which reaches the screen and nothing says so.
@@ -75,10 +122,20 @@ impl<'a> Painter<'a> {
"set_mask called twice while drawing one widget: the second would replace the first \
rather than nest inside it",
);
// A glyph would need a CPU-side alpha plane for the hit test to
// agree with the shader, and a standalone image a bind-group
// switch the fragment stage cannot make -- see `Mask::primitive`.
// Named here rather than left to the shader, which would read a
// rect that is not there and clip to nothing.
let binding = self.state.primitives.instance(shape).binding;
assert_eq!(
binding,
RectPrimitive::BINDING,
"a mask's shape must be a rect primitive; primitive {shape} is binding {binding}",
);
let parent = self.mask;
let mask = Mask {
region,
move_idx: self.move_slot,
primitive: shape,
parent,
};
let old_parent = if self.own_mask == MaskIdx::NONE {
+158 -5
View File
@@ -4,7 +4,10 @@ use std::time::{Duration, Instant};
use crate::{
ActiveData, IdLike, MaskIdx, MoveIdx, Painter, PixelRegion, PrimitiveLayers, RegionAlign,
StrongWidget, UiRegion, UiRsc, UiVec2, WidgetId, Widgets,
render::{MoveOffset, Primitive, PrimitiveHandle, PrimitiveInst, Primitives},
render::{
Drawn, MoveOffset, NOT_DRAWN, Primitive, PrimitiveHandle, PrimitiveInst, Primitives,
RectPrimitive, rounded_rect_coverage,
},
util::{HashMap, HashSet, Id, Vec2},
};
@@ -166,14 +169,19 @@ impl UiRenderState {
)
}
/// Writes a primitive into the arena and into `layer`'s draw order.
/// Writes a primitive into the arena and, unless it is
/// [`Drawn::No`], into `layer`'s draw order.
pub(super) fn write_primitive<P: Primitive>(
&mut self,
layer: usize,
drawn: Drawn,
inst: PrimitiveInst<P>,
) -> PrimitiveHandle {
let (slot, data_idx) = self.primitives.alloc(inst);
let pos = self.layers[layer].push(slot, false);
let pos = match drawn {
Drawn::Yes => self.layers[layer].push(slot, false),
Drawn::No => NOT_DRAWN,
};
PrimitiveHandle {
layer,
pos,
@@ -357,8 +365,16 @@ impl UiRenderState {
/// on screen", which is what a report reads as "did this frame have
/// more to draw than the last one", not "how much work did this frame
/// do" (`take_counters` answers that).
///
/// A mask's shape does not count: it is a [`Drawn::No`] primitive
/// that is never rasterized, so including it would put one extra on
/// the line for every masked widget and make a number Iris reads off
/// a phone report disagree with what is drawn.
pub fn active_primitive_count(&self) -> usize {
self.active.values().map(|a| a.primitives.len()).sum()
self.active
.values()
.map(|a| a.primitives.iter().filter(|h| h.pos != NOT_DRAWN).count())
.sum()
}
fn redraw_all(&mut self, root: Option<&StrongWidget>, rsc: &mut dyn UiRsc) {
@@ -690,11 +706,14 @@ impl UiRenderState {
if let Some(active) = &mut active {
for h in &active.primitives {
let mask = self.primitives.free(h);
self.layers[h.layer].free(h.pos, h.is_image());
if h.pos != NOT_DRAWN {
self.layers[h.layer].free(h.pos, h.is_image());
}
if mask != MaskIdx::NONE {
rsc.ui_mut().masks.remove(mask);
}
}
Self::remask_shape_users(&self.active, id, active.own_mask, &active.primitives, rsc);
active.textures.clear();
rsc.ui_mut().textures.free();
if undraw {
@@ -735,6 +754,54 @@ impl UiRenderState {
active
}
/// A mask whose shape primitive was just freed clips to a slot that
/// now holds something else, so the widget that owns it is marked for
/// redraw -- its own `set_mask` is the only thing that resolves the
/// slot, and it is the same mechanism a dirty widget already goes
/// through.
///
/// `own` is the mask belonging to the widget being removed and is
/// skipped: this runs in the middle of that widget's own redraw,
/// which sets its mask again on the way out, and a mark left on
/// itself would redraw it every frame from then on. Skipping it is
/// also what keeps the O(active) scan off the ordinary path -- a
/// plain `.masked()` frees exactly its own shape, so `stale` is empty
/// and this returns before touching `active`.
///
/// Both `Vec`s start empty and stay unallocated in that case, and
/// membership is a linear scan of two lists that are a handful long
/// (a widget's own primitives, and the live masks): this runs once
/// per widget removed, which is once per dirty widget per frame, and
/// a set built there would be an allocation on the phone's frame
/// path in exchange for nothing at these sizes.
fn remask_shape_users(
active: &HashMap<WidgetId, ActiveData>,
id: WidgetId,
own: MaskIdx,
freed: &[PrimitiveHandle],
rsc: &mut dyn UiRsc,
) {
let mut stale: Vec<MaskIdx> = Vec::new();
for (i, mask) in rsc.ui().masks.iter().enumerate() {
let idx = Id::preset(i as u32);
if idx != own && freed.iter().any(|h| h.slot == mask.primitive) {
stale.push(idx);
}
}
if stale.is_empty() {
return;
}
let mut owners: Vec<WidgetId> = Vec::new();
for (widget, data) in active {
if *widget != id && stale.contains(&data.own_mask) {
owners.push(*widget);
}
}
for owner in owners {
rsc.widgets_mut().needs_redraw.insert(owner);
}
}
fn remove_rec(&mut self, id: WidgetId, rsc: &mut dyn UiRsc) -> Option<ActiveData> {
let inst = self.remove(id, true, rsc);
if let Some(inst) = &inst {
@@ -970,6 +1037,92 @@ impl UiRenderState {
parts.join(" -> ")
}
/// One primitive's corners in window pixels -- the transliteration of
/// `shader.wgsl`'s `corners_of`, `floor` for `floor`. The rounding is
/// the whole reason this is not `region.to_px()`: the shader floors
/// each half separately before adding the move delta, and a hit test
/// that skipped it would disagree with the pixels by up to one along
/// each edge -- invisible in every test written against a whole-pixel
/// layout and wrong on the phone, whose 2.55 density makes nothing
/// land on a whole pixel.
pub fn primitive_corners(&self, slot: u32, rsc: &dyn UiRsc) -> PixelRegion {
let inst = self.primitives.instance(slot);
let delta = self.resolve_move_chain(inst.move_idx, rsc);
let size = self.output_size;
let corner = |c: UiVec2| (c.get_rel() * size).floor() + c.get_abs().floor() + delta;
PixelRegion {
top_left: corner(inst.region.top_left()),
bot_right: corner(inst.region.bot_right()),
}
}
/// Where a mask's clip actually is on screen: the box of the
/// primitive it references. Its *shape* within that box is
/// [`Self::mask_coverage`]'s -- this is the bounding box, which is
/// what a test asking "is the clip over the right part of the screen"
/// wants and all a square-cornered mask has ever had.
pub fn mask_region(&self, mask: MaskIdx, rsc: &dyn UiRsc) -> PixelRegion {
self.primitive_corners(rsc.ui().masks[mask.idx()].primitive, rsc)
}
/// How much of the pixel at `pos` (window pixels) survives `mask` and
/// every mask it nests inside: the referenced primitives' own
/// coverage, multiplied along the chain. The CPU half of
/// `shader.wgsl`'s `fs_main` mask loop -- same order, same bound, same
/// `rounded_rect_coverage` -- so a corner that cannot be tapped and a
/// corner that is not drawn are the same corner (LAYOUT.md's "Masks
/// with a shape", point 4).
///
/// A mask whose shape is not a rect covers everything, exactly as the
/// shader's own `mask_coverage` does: `Painter::set_mask_to` rejects
/// those by name, so this is the unreachable half of the same
/// agreement rather than a second policy.
pub fn mask_coverage(&self, mask: MaskIdx, pos: Vec2, rsc: &dyn UiRsc) -> f32 {
let mut coverage = 1.0;
let mut at = mask;
for i in 0..PARENT_CHAIN_LIMIT {
if at == MaskIdx::NONE {
return coverage;
}
let m = rsc.ui().masks[at.idx()];
if let Some(rect) = self.primitives.primitive_data::<RectPrimitive>(m.primitive) {
let c = self.primitive_corners(m.primitive, rsc);
coverage *= rounded_rect_coverage(pos, c.top_left, c.bot_right, rect.radius);
}
at = m.parent;
debug_assert!(
i + 1 < PARENT_CHAIN_LIMIT || at == MaskIdx::NONE,
"mask chain exceeded PARENT_CHAIN_LIMIT ({PARENT_CHAIN_LIMIT}) from {mask:?} -- a \
repeated slot means a `parent` link is cyclic, all-distinct slots mean the tree \
nests deeper than shader.wgsl's own walk of the same bound",
);
}
coverage
}
/// Whether `pos` is inside `mask` at all -- more than half covered,
/// which is where the drawn edge is (`rounded_rect_coverage`'s doc).
/// What a hit test asks.
pub fn mask_admits(&self, mask: MaskIdx, pos: Vec2, rsc: &dyn UiRsc) -> bool {
self.mask_coverage(mask, pos, rsc) > 0.5
}
/// The first primitive `id`'s subtree wrote this frame, depth first
/// in draw order -- what a mask pointed at a widget clips to
/// (`Painter::set_mask_to_widget`). A widget that draws more than one
/// (a bordered rect is one primitive; a card with a stripe is two)
/// gives its first; a widget that wants another names it.
pub fn first_primitive(&self, id: WidgetId) -> Option<u32> {
let active = self.active.get(&id)?;
if let Some(h) = active.primitives.first() {
return Some(h.slot);
}
active
.children
.iter()
.find_map(|child| self.first_primitive(*child))
}
pub fn window_region(&self, id: &impl IdLike, rsc: &dyn UiRsc) -> Option<PixelRegion> {
let region = self.resolved_region(id, rsc)?;
Some(region.to_px(self.output_size))