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, max_radius, shadow, focus_width)`. `max_radius`
53 /// is the largest of the four per-corner radii (in `slot_e`); it
54 /// stays here so custom shaders that read scalar `slot_c.y` as
55 /// the radius keep working when corners are uniform. Vertex
56 /// shader reads at `@location(4)`.
57 pub slot_c: [f32; 4],
58 /// Layout rect (xy = top-left px, zw = size px). SDF shaders use
59 /// this so the rect outline stays anchored to layout bounds even
60 /// when `rect` has been outset for `paint_overflow`. Vertex shader
61 /// reads at `@location(5)` — declared *after* the legacy slots so
62 /// custom shaders that only consume locations 1..=4 keep working
63 /// unchanged.
64 pub inner_rect: [f32; 4],
65 /// `vec_d` slot — for stock::rounded_rect, this is the ring
66 /// color (rgba) with eased alpha already multiplied in. Zero when
67 /// the node isn't focused or isn't focusable. Vertex shader reads
68 /// at `@location(6)`.
69 pub slot_d: [f32; 4],
70 /// `vec_e` slot — for stock::rounded_rect, this is per-corner
71 /// radii in `(tl, tr, br, bl)` order (logical px). Custom shaders
72 /// that don't care about per-corner shapes can ignore this slot.
73 /// Vertex shader reads at `@location(7)`.
74 pub slot_e: [f32; 4],
75}
76
77/// One line-segment primitive in a vector icon. The instance renders a
78/// single antialiased stroke into `rect`; higher-level icon paths are
79/// flattened into runs of these records by the backend recorder.
80#[repr(C)]
81#[derive(Copy, Clone, Pod, Zeroable, Debug)]
82pub struct IconInstance {
83 /// Painted bounds for the segment, outset for stroke width and AA.
84 /// Vertex shader reads at `@location(1)`.
85 pub rect: [f32; 4],
86 /// Segment endpoints in logical px: `(x0, y0, x1, y1)`.
87 /// Fragment shader reads at `@location(2)`.
88 pub line: [f32; 4],
89 /// Linear rgba color. Fragment shader reads at `@location(3)`.
90 pub color: [f32; 4],
91 /// `(stroke_width, reserved, reserved, reserved)`.
92 /// Fragment shader reads at `@location(4)`.
93 pub params: [f32; 4],
94}
95
96/// A contiguous run of instances drawn with the same pipeline + scissor.
97/// Built in tree order so a custom shader sandwiched between two stock
98/// surfaces is drawn at the right z-position.
99#[derive(Clone, Copy)]
100pub struct InstanceRun {
101 pub handle: ShaderHandle,
102 pub scissor: Option<PhysicalScissor>,
103 pub first: u32,
104 pub count: u32,
105}
106
107/// Which icon-draw path a backend uses for this run.
108///
109/// `Tess` runs index into the backend's tessellated vector mesh
110/// (vertex range, expanded triangles). `Msdf` runs index into the
111/// backend's per-instance MSDF buffer (one entry = one icon quad) and
112/// must bind the atlas page identified by `IconRun::page`.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum IconRunKind {
115 Tess,
116 Msdf,
117}
118
119/// A contiguous run of backend-owned icon draws sharing a scissor.
120///
121/// For `Tess` runs, `first..first+count` is a vertex range in the
122/// backend's vector-mesh buffer and `material` selects the fragment
123/// shader (flat / relief / glass). For `Msdf` runs, `first..first+count`
124/// is an instance range in the backend's MSDF instance buffer; `page`
125/// names the atlas page to bind. `material` is always `Flat` for MSDF
126/// runs — non-flat materials need the per-fragment local view-box
127/// coordinate that the tessellated path provides, so they stay on the
128/// `Tess` route.
129#[derive(Clone, Copy)]
130pub struct IconRun {
131 pub kind: IconRunKind,
132 pub scissor: Option<PhysicalScissor>,
133 pub first: u32,
134 pub count: u32,
135 pub page: u32,
136 pub material: IconMaterial,
137}
138
139/// Scissor in **physical pixels** (host swapchain extent), already
140/// clamped to the surface and snapped to integer pixel boundaries.
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142pub struct PhysicalScissor {
143 pub x: u32,
144 pub y: u32,
145 pub w: u32,
146 pub h: u32,
147}
148
149/// Sequencing entry for the recorded paint stream.
150///
151/// - `QuadRun(idx)` — a contiguous instance run (indexed into `runs`).
152/// - `IconRun(idx)` — a vector icon run (backend-owned storage,
153/// indexed by the wgpu icon painter; other backends may keep using
154/// text fallback and never emit this item).
155/// - `Text(idx)` — a glyph layer (indexed into the backend's
156/// `TextLayer` vector).
157/// - `BackdropSnapshot` — a pass boundary. The backend ends the
158/// current render pass, copies the current target into its managed
159/// snapshot texture, and begins a new pass with `LoadOp::Load` so
160/// subsequent quads can sample the snapshot via the `backdrop` bind
161/// group. At most one of these is emitted per frame, inserted by
162/// [`crate::runtime::RunnerCore::prepare_paint`] immediately before
163/// the first quad bound to a `samples_backdrop` shader.
164#[derive(Clone, Copy)]
165pub enum PaintItem {
166 QuadRun(usize),
167 IconRun(usize),
168 Text(usize),
169 /// One raster image draw. Indexes into the backend's
170 /// `ImagePaint`-equivalent storage. Produced by
171 /// [`crate::runtime::TextRecorder::record_image`] from a
172 /// [`crate::ir::DrawOp::Image`].
173 Image(usize),
174 /// One app-owned-texture composite. Indexes into the backend's
175 /// `SurfacePaint`-equivalent storage. Produced by the backend's
176 /// surface recorder from a [`crate::ir::DrawOp::AppTexture`].
177 AppTexture(usize),
178 /// One app-supplied vector draw. Indexes into the backend's vector
179 /// storage; explicit render mode determines whether that storage is
180 /// tessellated geometry or an MSDF atlas entry. Produced from a
181 /// [`crate::ir::DrawOp::Vector`].
182 Vector(usize),
183 BackdropSnapshot,
184}
185
186/// Close the current run and append it to `runs` + `paint_items`. No-op
187/// when `run_key` is `None` or the run is empty.
188pub fn close_run(
189 runs: &mut Vec<InstanceRun>,
190 paint_items: &mut Vec<PaintItem>,
191 run_key: Option<(ShaderHandle, Option<PhysicalScissor>)>,
192 first: u32,
193 end: u32,
194) {
195 if let Some((handle, scissor)) = run_key {
196 let count = end - first;
197 if count > 0 {
198 let index = runs.len();
199 runs.push(InstanceRun {
200 handle,
201 scissor,
202 first,
203 count,
204 });
205 paint_items.push(PaintItem::QuadRun(index));
206 }
207 }
208}
209
210/// Convert a logical-pixel scissor to physical pixels, clamping to the
211/// physical viewport. Returns `None` when the input is `None`.
212pub fn physical_scissor(
213 scissor: Option<Rect>,
214 scale: f32,
215 viewport_px: (u32, u32),
216) -> Option<PhysicalScissor> {
217 let r = scissor?;
218 let x1 = (r.x * scale).floor().clamp(0.0, viewport_px.0 as f32) as u32;
219 let y1 = (r.y * scale).floor().clamp(0.0, viewport_px.1 as f32) as u32;
220 let x2 = (r.right() * scale).ceil().clamp(0.0, viewport_px.0 as f32) as u32;
221 let y2 = (r.bottom() * scale).ceil().clamp(0.0, viewport_px.1 as f32) as u32;
222 Some(PhysicalScissor {
223 x: x1,
224 y: y1,
225 w: x2.saturating_sub(x1),
226 h: y2.saturating_sub(y1),
227 })
228}
229
230/// Pack a quad's uniforms into the shared `QuadInstance` layout. Stock
231/// `rounded_rect` reads its named uniforms; everything else reads the
232/// generic `vec_a`/`vec_b`/`vec_c`/`vec_d` slots. `inner_rect` falls
233/// back to `rect` when the uniform isn't supplied — i.e. when the node
234/// has no `paint_overflow`.
235pub fn pack_instance(rect: Rect, shader: ShaderHandle, uniforms: &UniformBlock) -> QuadInstance {
236 let rect_arr = [rect.x, rect.y, rect.w, rect.h];
237 let inner_rect = uniforms
238 .get("inner_rect")
239 .map(value_to_vec4)
240 .unwrap_or(rect_arr);
241
242 match shader {
243 ShaderHandle::Stock(StockShader::RoundedRect) => {
244 let radii = uniforms.get("radii").map(value_to_vec4);
245 // Fall back to the scalar `radius` uniform when no
246 // per-corner block was inserted (custom callers, focus
247 // ring band, etc.). Either path produces a valid
248 // four-corner instance — callers that only set scalar
249 // `radius` get uniform corners.
250 let scalar_radius = uniforms.get("radius").and_then(as_f32).unwrap_or(0.0);
251 let radii = radii.unwrap_or([scalar_radius; 4]);
252 let max_radius = radii[0].max(radii[1]).max(radii[2]).max(radii[3]);
253 QuadInstance {
254 rect: rect_arr,
255 inner_rect,
256 slot_a: uniforms
257 .get("fill")
258 .and_then(as_color)
259 .map(rgba_f32)
260 .unwrap_or([0.0; 4]),
261 slot_b: uniforms
262 .get("stroke")
263 .and_then(as_color)
264 .map(rgba_f32)
265 .unwrap_or([0.0; 4]),
266 slot_c: [
267 uniforms.get("stroke_width").and_then(as_f32).unwrap_or(0.0),
268 max_radius,
269 uniforms.get("shadow").and_then(as_f32).unwrap_or(0.0),
270 uniforms.get("focus_width").and_then(as_f32).unwrap_or(0.0),
271 ],
272 slot_d: uniforms
273 .get("focus_color")
274 .and_then(as_color)
275 .map(rgba_f32)
276 .unwrap_or([0.0; 4]),
277 slot_e: radii,
278 }
279 }
280 _ => QuadInstance {
281 rect: rect_arr,
282 inner_rect,
283 slot_a: uniforms.get("vec_a").map(value_to_vec4).unwrap_or([0.0; 4]),
284 slot_b: uniforms.get("vec_b").map(value_to_vec4).unwrap_or([0.0; 4]),
285 slot_c: uniforms.get("vec_c").map(value_to_vec4).unwrap_or([0.0; 4]),
286 slot_d: uniforms.get("vec_d").map(value_to_vec4).unwrap_or([0.0; 4]),
287 slot_e: uniforms.get("vec_e").map(value_to_vec4).unwrap_or([0.0; 4]),
288 },
289 }
290}
291
292fn as_color(v: &UniformValue) -> Option<Color> {
293 match v {
294 UniformValue::Color(c) => Some(*c),
295 _ => None,
296 }
297}
298fn as_f32(v: &UniformValue) -> Option<f32> {
299 match v {
300 UniformValue::F32(f) => Some(*f),
301 _ => None,
302 }
303}
304
305/// Coerce any `UniformValue` into the four floats of a vec4 slot.
306/// Custom-shader authors typically pass `Color` (rgba) or `Vec4`
307/// (arbitrary semantics); `F32` packs into `.x` so a single scalar like
308/// `radius` doesn't need a Vec4 wrapper.
309fn value_to_vec4(v: &UniformValue) -> [f32; 4] {
310 match v {
311 UniformValue::Color(c) => rgba_f32(*c),
312 UniformValue::Vec4(a) => *a,
313 UniformValue::Vec2([x, y]) => [*x, *y, 0.0, 0.0],
314 UniformValue::F32(f) => [*f, 0.0, 0.0, 0.0],
315 UniformValue::Bool(b) => [if *b { 1.0 } else { 0.0 }, 0.0, 0.0, 0.0],
316 }
317}
318
319/// Convert a token sRGB color to the four linear floats the shader
320/// reads. Tokens are authored in sRGB display space; the surface is an
321/// *Srgb format so alpha blending happens in linear space (correct
322/// for color blending, slightly fattens light-on-dark text).
323pub fn rgba_f32(c: Color) -> [f32; 4] {
324 [
325 srgb_to_linear(c.r as f32 / 255.0),
326 srgb_to_linear(c.g as f32 / 255.0),
327 srgb_to_linear(c.b as f32 / 255.0),
328 c.a as f32 / 255.0,
329 ]
330}
331
332fn srgb_to_linear(c: f32) -> f32 {
333 if c <= 0.04045 {
334 c / 12.92
335 } else {
336 ((c + 0.055) / 1.055).powf(2.4)
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343 use crate::shader::UniformBlock;
344 use crate::tokens;
345
346 #[test]
347 fn focus_uniforms_pack_into_rounded_rect_slots() {
348 // Focus ring rides on the node's own RoundedRect quad: focus_color
349 // packs into slot_d (rgba) and focus_width into slot_c.w (the
350 // params slot's previously-padding lane).
351 let mut uniforms = UniformBlock::new();
352 uniforms.insert("fill", UniformValue::Color(Color::rgba(40, 40, 40, 255)));
353 uniforms.insert("radius", UniformValue::F32(8.0));
354 uniforms.insert("focus_color", UniformValue::Color(tokens::RING));
355 uniforms.insert("focus_width", UniformValue::F32(tokens::RING_WIDTH));
356
357 let inst = pack_instance(
358 Rect::new(1.0, 2.0, 30.0, 40.0),
359 ShaderHandle::Stock(StockShader::RoundedRect),
360 &uniforms,
361 );
362
363 assert_eq!(inst.rect, [1.0, 2.0, 30.0, 40.0]);
364 assert_eq!(
365 inst.inner_rect, inst.rect,
366 "no inner_rect uniform → fall back to painted rect"
367 );
368 assert_eq!(
369 inst.slot_c[1], 8.0,
370 "max corner radius in slot_c.y (uniform corners derived from scalar `radius` uniform)"
371 );
372 assert_eq!(
373 inst.slot_e,
374 [8.0, 8.0, 8.0, 8.0],
375 "scalar `radius` uniform fills all four corners on slot_e"
376 );
377 assert_eq!(
378 inst.slot_c[3],
379 tokens::RING_WIDTH,
380 "focus_width in slot_c.w"
381 );
382 assert!(inst.slot_d[3] > 0.0, "focus_color alpha should be visible");
383 }
384
385 #[test]
386 fn per_corner_radii_uniform_routes_to_slot_e() {
387 // The `radii` uniform overrides the scalar `radius` for the
388 // SDF, while `slot_c.y` carries the max corner so custom
389 // shaders that read scalar `slot_c.y` still see the right
390 // shape silhouette.
391 let mut uniforms = UniformBlock::new();
392 uniforms.insert("fill", UniformValue::Color(Color::rgba(40, 40, 40, 255)));
393 // Top-rounded only — the strip-on-card shape.
394 uniforms.insert("radii", UniformValue::Vec4([12.0, 12.0, 0.0, 0.0]));
395 uniforms.insert("radius", UniformValue::F32(12.0));
396
397 let inst = pack_instance(
398 Rect::new(0.0, 0.0, 100.0, 40.0),
399 ShaderHandle::Stock(StockShader::RoundedRect),
400 &uniforms,
401 );
402
403 assert_eq!(inst.slot_e, [12.0, 12.0, 0.0, 0.0]);
404 assert_eq!(inst.slot_c[1], 12.0, "max corner radius -> slot_c.y");
405 }
406
407 #[test]
408 fn physical_scissor_converts_logical_to_physical_pixels() {
409 let scissor = physical_scissor(Some(Rect::new(10.2, 20.2, 30.2, 40.2)), 2.0, (200, 200))
410 .expect("scissor");
411
412 assert_eq!(
413 scissor,
414 PhysicalScissor {
415 x: 20,
416 y: 40,
417 w: 61,
418 h: 81
419 }
420 );
421 }
422}