Skip to main content

aetna_core/
paint.rs

1//! Paint-stream types and helpers shared by every backend.
2//!
3//! The `QuadInstance` ABI is the cross-backend contract: every
4//! rect-shaped pipeline (stock or custom) reads the same 4 × `vec4<f32>`
5//! layout, so the layout pass's logical-pixel rects compose with each
6//! backend's GPU pipelines without per-backend tweaking. `aetna-wgpu`
7//! and `aetna-vulkano` build different pipelines around it; the bytes
8//! the vertex shader sees are identical.
9//!
10//! `PaintItem` + `InstanceRun` + [`close_run`] are the paint-stream
11//! batching shape: walk the [`crate::DrawOp`] list, pack `Quad`s into
12//! the instance buffer in groups of consecutive same-pipeline +
13//! same-scissor runs, intersperse text layers in their original
14//! z-order. Both backends consume this exactly the same way.
15//!
16//! The one paint concern this module *doesn't* own is `set_scissor` —
17//! that one needs the backend-specific encoder type, so each backend
18//! keeps a thin `set_scissor` of its own.
19
20use bytemuck::{Pod, Zeroable};
21
22use crate::shader::{ShaderHandle, StockShader, UniformBlock, UniformValue};
23use crate::tree::{Color, Rect};
24use crate::vector::IconMaterial;
25
26/// One instance of a rect-shaped shader. Layout is shared between
27/// `stock::rounded_rect` and any custom shader registered via the host's
28/// `register_shader`. The fragment shader interprets the slots however
29/// it wants; the vertex shader uses `rect` to place the unit quad in
30/// pixel space.
31///
32/// `inner_rect` is the original layout rect — equal to `rect` when
33/// `paint_overflow` is zero, smaller (set inside `rect`) when the
34/// element has opted into painting outside its bounds. SDF shaders
35/// anchor their geometry to `inner_rect` so the rounded outline stays
36/// where layout placed it; the overflow band is where focus rings,
37/// drop shadows, and other halos render.
38#[repr(C)]
39#[derive(Copy, Clone, Pod, Zeroable, Debug)]
40pub struct QuadInstance {
41    /// Painted rect — xy = top-left px, zw = size px. Equal to
42    /// `inner_rect` when no `paint_overflow`. Vertex shader reads at
43    /// `@location(1)`.
44    pub rect: [f32; 4],
45    /// `vec_a` slot — for stock::rounded_rect, this is `fill`. Vertex
46    /// shader reads at `@location(2)`.
47    pub slot_a: [f32; 4],
48    /// `vec_b` slot — for stock::rounded_rect, this is `stroke`.
49    /// Vertex shader reads at `@location(3)`.
50    pub slot_b: [f32; 4],
51    /// `vec_c` slot — for stock::rounded_rect, this is
52    /// `(stroke_width, radius, shadow, focus_width)`. Vertex shader
53    /// reads at `@location(4)`.
54    pub slot_c: [f32; 4],
55    /// Layout rect (xy = top-left px, zw = size px). SDF shaders use
56    /// this so the rect outline stays anchored to layout bounds even
57    /// when `rect` has been outset for `paint_overflow`. Vertex shader
58    /// reads at `@location(5)` — declared *after* the legacy slots so
59    /// custom shaders that only consume locations 1..=4 keep working
60    /// unchanged.
61    pub inner_rect: [f32; 4],
62    /// `vec_d` slot — for stock::rounded_rect, this is the focus-ring
63    /// color (rgba) with eased alpha already multiplied in. Zero when
64    /// the node isn't focused or isn't focusable. Vertex shader reads
65    /// at `@location(6)`.
66    pub slot_d: [f32; 4],
67}
68
69/// One line-segment primitive in a vector icon. The instance renders a
70/// single antialiased stroke into `rect`; higher-level icon paths are
71/// flattened into runs of these records by the backend recorder.
72#[repr(C)]
73#[derive(Copy, Clone, Pod, Zeroable, Debug)]
74pub struct IconInstance {
75    /// Painted bounds for the segment, outset for stroke width and AA.
76    /// Vertex shader reads at `@location(1)`.
77    pub rect: [f32; 4],
78    /// Segment endpoints in logical px: `(x0, y0, x1, y1)`.
79    /// Fragment shader reads at `@location(2)`.
80    pub line: [f32; 4],
81    /// Linear rgba color. Fragment shader reads at `@location(3)`.
82    pub color: [f32; 4],
83    /// `(stroke_width, reserved, reserved, reserved)`.
84    /// Fragment shader reads at `@location(4)`.
85    pub params: [f32; 4],
86}
87
88/// A contiguous run of instances drawn with the same pipeline + scissor.
89/// Built in tree order so a custom shader sandwiched between two stock
90/// surfaces is drawn at the right z-position.
91#[derive(Clone, Copy)]
92pub struct InstanceRun {
93    pub handle: ShaderHandle,
94    pub scissor: Option<PhysicalScissor>,
95    pub first: u32,
96    pub count: u32,
97}
98
99/// Which icon-draw path a backend uses for this run.
100///
101/// `Tess` runs index into the backend's tessellated vector mesh
102/// (vertex range, expanded triangles). `Msdf` runs index into the
103/// backend's per-instance MSDF buffer (one entry = one icon quad) and
104/// must bind the atlas page identified by `IconRun::page`.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum IconRunKind {
107    Tess,
108    Msdf,
109}
110
111/// A contiguous run of backend-owned icon draws sharing a scissor.
112///
113/// For `Tess` runs, `first..first+count` is a vertex range in the
114/// backend's vector-mesh buffer and `material` selects the fragment
115/// shader (flat / relief / glass). For `Msdf` runs, `first..first+count`
116/// is an instance range in the backend's MSDF instance buffer; `page`
117/// names the atlas page to bind. `material` is always `Flat` for MSDF
118/// runs — non-flat materials need the per-fragment local view-box
119/// coordinate that the tessellated path provides, so they stay on the
120/// `Tess` route.
121#[derive(Clone, Copy)]
122pub struct IconRun {
123    pub kind: IconRunKind,
124    pub scissor: Option<PhysicalScissor>,
125    pub first: u32,
126    pub count: u32,
127    pub page: u32,
128    pub material: IconMaterial,
129}
130
131/// Scissor in **physical pixels** (host swapchain extent), already
132/// clamped to the surface and snapped to integer pixel boundaries.
133#[derive(Clone, Copy, Debug, PartialEq, Eq)]
134pub struct PhysicalScissor {
135    pub x: u32,
136    pub y: u32,
137    pub w: u32,
138    pub h: u32,
139}
140
141/// Sequencing entry for the recorded paint stream.
142///
143/// - `QuadRun(idx)` — a contiguous instance run (indexed into `runs`).
144/// - `IconRun(idx)` — a vector icon run (backend-owned storage,
145///   indexed by the wgpu icon painter; other backends may keep using
146///   text fallback and never emit this item).
147/// - `Text(idx)` — a glyph layer (indexed into the backend's
148///   `TextLayer` vector).
149/// - `BackdropSnapshot` — a pass boundary. The backend ends the
150///   current render pass, copies the current target into its managed
151///   snapshot texture, and begins a new pass with `LoadOp::Load` so
152///   subsequent quads can sample the snapshot via the `backdrop` bind
153///   group. At most one of these is emitted per frame, inserted by
154///   [`crate::runtime::RunnerCore::prepare_paint`] immediately before
155///   the first quad bound to a `samples_backdrop` shader.
156#[derive(Clone, Copy)]
157pub enum PaintItem {
158    QuadRun(usize),
159    IconRun(usize),
160    Text(usize),
161    BackdropSnapshot,
162}
163
164/// Close the current run and append it to `runs` + `paint_items`. No-op
165/// when `run_key` is `None` or the run is empty.
166pub fn close_run(
167    runs: &mut Vec<InstanceRun>,
168    paint_items: &mut Vec<PaintItem>,
169    run_key: Option<(ShaderHandle, Option<PhysicalScissor>)>,
170    first: u32,
171    end: u32,
172) {
173    if let Some((handle, scissor)) = run_key {
174        let count = end - first;
175        if count > 0 {
176            let index = runs.len();
177            runs.push(InstanceRun {
178                handle,
179                scissor,
180                first,
181                count,
182            });
183            paint_items.push(PaintItem::QuadRun(index));
184        }
185    }
186}
187
188/// Convert a logical-pixel scissor to physical pixels, clamping to the
189/// physical viewport. Returns `None` when the input is `None`.
190pub fn physical_scissor(
191    scissor: Option<Rect>,
192    scale: f32,
193    viewport_px: (u32, u32),
194) -> Option<PhysicalScissor> {
195    let r = scissor?;
196    let x1 = (r.x * scale).floor().clamp(0.0, viewport_px.0 as f32) as u32;
197    let y1 = (r.y * scale).floor().clamp(0.0, viewport_px.1 as f32) as u32;
198    let x2 = (r.right() * scale).ceil().clamp(0.0, viewport_px.0 as f32) as u32;
199    let y2 = (r.bottom() * scale).ceil().clamp(0.0, viewport_px.1 as f32) as u32;
200    Some(PhysicalScissor {
201        x: x1,
202        y: y1,
203        w: x2.saturating_sub(x1),
204        h: y2.saturating_sub(y1),
205    })
206}
207
208/// Pack a quad's uniforms into the shared `QuadInstance` layout. Stock
209/// `rounded_rect` reads its named uniforms; everything else reads the
210/// generic `vec_a`/`vec_b`/`vec_c`/`vec_d` slots. `inner_rect` falls
211/// back to `rect` when the uniform isn't supplied — i.e. when the node
212/// has no `paint_overflow`.
213pub fn pack_instance(rect: Rect, shader: ShaderHandle, uniforms: &UniformBlock) -> QuadInstance {
214    let rect_arr = [rect.x, rect.y, rect.w, rect.h];
215    let inner_rect = uniforms
216        .get("inner_rect")
217        .map(value_to_vec4)
218        .unwrap_or(rect_arr);
219
220    match shader {
221        ShaderHandle::Stock(StockShader::RoundedRect) => QuadInstance {
222            rect: rect_arr,
223            inner_rect,
224            slot_a: uniforms
225                .get("fill")
226                .and_then(as_color)
227                .map(rgba_f32)
228                .unwrap_or([0.0; 4]),
229            slot_b: uniforms
230                .get("stroke")
231                .and_then(as_color)
232                .map(rgba_f32)
233                .unwrap_or([0.0; 4]),
234            slot_c: [
235                uniforms.get("stroke_width").and_then(as_f32).unwrap_or(0.0),
236                uniforms.get("radius").and_then(as_f32).unwrap_or(0.0),
237                uniforms.get("shadow").and_then(as_f32).unwrap_or(0.0),
238                uniforms.get("focus_width").and_then(as_f32).unwrap_or(0.0),
239            ],
240            slot_d: uniforms
241                .get("focus_color")
242                .and_then(as_color)
243                .map(rgba_f32)
244                .unwrap_or([0.0; 4]),
245        },
246        _ => QuadInstance {
247            rect: rect_arr,
248            inner_rect,
249            slot_a: uniforms.get("vec_a").map(value_to_vec4).unwrap_or([0.0; 4]),
250            slot_b: uniforms.get("vec_b").map(value_to_vec4).unwrap_or([0.0; 4]),
251            slot_c: uniforms.get("vec_c").map(value_to_vec4).unwrap_or([0.0; 4]),
252            slot_d: uniforms.get("vec_d").map(value_to_vec4).unwrap_or([0.0; 4]),
253        },
254    }
255}
256
257fn as_color(v: &UniformValue) -> Option<Color> {
258    match v {
259        UniformValue::Color(c) => Some(*c),
260        _ => None,
261    }
262}
263fn as_f32(v: &UniformValue) -> Option<f32> {
264    match v {
265        UniformValue::F32(f) => Some(*f),
266        _ => None,
267    }
268}
269
270/// Coerce any `UniformValue` into the four floats of a vec4 slot.
271/// Custom-shader authors typically pass `Color` (rgba) or `Vec4`
272/// (arbitrary semantics); `F32` packs into `.x` so a single scalar like
273/// `radius` doesn't need a Vec4 wrapper.
274fn value_to_vec4(v: &UniformValue) -> [f32; 4] {
275    match v {
276        UniformValue::Color(c) => rgba_f32(*c),
277        UniformValue::Vec4(a) => *a,
278        UniformValue::Vec2([x, y]) => [*x, *y, 0.0, 0.0],
279        UniformValue::F32(f) => [*f, 0.0, 0.0, 0.0],
280        UniformValue::Bool(b) => [if *b { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0],
281    }
282}
283
284/// Convert a token sRGB color to the four linear floats the shader
285/// reads. Tokens are authored in sRGB display space; the surface is an
286/// *Srgb format so alpha blending happens in linear space (correct
287/// for color blending, slightly fattens light-on-dark text).
288pub fn rgba_f32(c: Color) -> [f32; 4] {
289    [
290        srgb_to_linear(c.r as f32 / 255.0),
291        srgb_to_linear(c.g as f32 / 255.0),
292        srgb_to_linear(c.b as f32 / 255.0),
293        c.a as f32 / 255.0,
294    ]
295}
296
297fn srgb_to_linear(c: f32) -> f32 {
298    if c <= 0.04045 {
299        c / 12.92
300    } else {
301        ((c + 0.055) / 1.055).powf(2.4)
302    }
303}
304
305#[cfg(test)]
306mod tests {
307    use super::*;
308    use crate::shader::UniformBlock;
309    use crate::tokens;
310
311    #[test]
312    fn focus_uniforms_pack_into_rounded_rect_slots() {
313        // Focus ring rides on the node's own RoundedRect quad: focus_color
314        // packs into slot_d (rgba) and focus_width into slot_c.w (the
315        // params slot's previously-padding lane).
316        let mut uniforms = UniformBlock::new();
317        uniforms.insert("fill", UniformValue::Color(Color::rgba(40, 40, 40, 255)));
318        uniforms.insert("radius", UniformValue::F32(8.0));
319        uniforms.insert("focus_color", UniformValue::Color(tokens::FOCUS_RING));
320        uniforms.insert("focus_width", UniformValue::F32(tokens::FOCUS_RING_WIDTH));
321
322        let inst = pack_instance(
323            Rect::new(1.0, 2.0, 30.0, 40.0),
324            ShaderHandle::Stock(StockShader::RoundedRect),
325            &uniforms,
326        );
327
328        assert_eq!(inst.rect, [1.0, 2.0, 30.0, 40.0]);
329        assert_eq!(
330            inst.inner_rect, inst.rect,
331            "no inner_rect uniform → fall back to painted rect"
332        );
333        assert_eq!(inst.slot_c[1], 8.0, "radius in slot_c.y");
334        assert_eq!(
335            inst.slot_c[3],
336            tokens::FOCUS_RING_WIDTH,
337            "focus_width in slot_c.w"
338        );
339        assert!(inst.slot_d[3] > 0.0, "focus_color alpha should be visible");
340    }
341
342    #[test]
343    fn physical_scissor_converts_logical_to_physical_pixels() {
344        let scissor = physical_scissor(Some(Rect::new(10.2, 20.2, 30.2, 40.2)), 2.0, (200, 200))
345            .expect("scissor");
346
347        assert_eq!(
348            scissor,
349            PhysicalScissor {
350                x: 20,
351                y: 40,
352                w: 61,
353                h: 81
354            }
355        );
356    }
357}