Skip to main content

teksilo_render/
vertex.rs

1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4use bytemuck::{Pod, Zeroable};
5
6use teksilo_canvas::live_image::LiveImageQuad;
7use teksilo_canvas::render_frame::PaintData;
8use teksilo_canvas::{DecorationRect, GlyphQuad, PathEntry, ShadowQuad, ShapeQuad, Transform2D};
9
10/// Convert a single sRGB channel (0..1) to linear light (0..1).
11///
12/// `teksilo_tokens::Color::from_hex` parses hex values as sRGB-encoded f32
13/// without gamma conversion, which matches how designers specify colors.
14/// The wgpu surface is `Rgba8UnormSrgb`, which expects **linear** shader
15/// output and applies sRGB encoding on write. To avoid double gamma-
16/// encoding we linearize color data at the vertex-packing boundary.
17#[inline]
18fn srgb_to_linear(c: f32) -> f32 {
19    if c <= 0.04045 {
20        c / 12.92
21    } else {
22        ((c + 0.055) / 1.055).powf(2.4)
23    }
24}
25
26/// Linearize an RGBA color for GPU upload. Alpha passes through unchanged
27/// because `Rgba8UnormSrgb` only gamma-encodes RGB.
28#[inline]
29pub fn srgb_to_linear_rgba(c: [f32; 4]) -> [f32; 4] {
30    [
31        srgb_to_linear(c[0]),
32        srgb_to_linear(c[1]),
33        srgb_to_linear(c[2]),
34        c[3],
35    ]
36}
37
38/// Per-vertex flag: sample atlas `texture.rgb` directly (color emoji)
39/// instead of using the texture as an alpha mask tinted by vertex color.
40pub const QUAD_FLAG_COLOR_GLYPH: u32 = 1;
41
42/// Per-vertex flag: ignore the texture's alpha, which holds no alpha (the
43/// fourth byte of an RGBX or BGRX live picture). Drawn opaque.
44pub const QUAD_FLAG_OPAQUE: u32 = 2;
45
46/// Per-vertex flag: the texture holds blue, green, red in its red, green and
47/// blue channels (a BGRA or BGRX live picture); swapped after sampling,
48/// which filtering and sRGB decoding commute with, channel by channel.
49pub const QUAD_FLAG_SWAP_RB: u32 = 4;
50
51/// Vertex for the textured quad pipeline (glyphs, images).
52#[repr(C)]
53#[derive(Debug, Clone, Copy, Pod, Zeroable)]
54pub struct QuadVertex {
55    pub position: [f32; 2],
56    pub tex_coord: [f32; 2],
57    pub color: [f32; 4],
58    /// Per-vertex bitfield. Bit 0 ([`QUAD_FLAG_COLOR_GLYPH`]) selects the
59    /// color emoji path in the fragment shader.
60    pub flags: u32,
61    /// The glyph-edge correction for a monochrome glyph, as
62    /// [`TextContrast`](crate::text_contrast::TextContrast) packs it; `0`
63    /// for anything else (images, path masks, colour glyphs), which the
64    /// shader blends as is. The renderer fills it in, not the constructors.
65    pub text_params: u32,
66}
67
68/// Off-diagonal tolerance below which a transform counts as axis-aligned
69/// for glyph pixel-snapping. Matrix composition leaves float dust on `b`/`c`;
70/// any intentional rotation puts `|sin θ|` there, far above this bound.
71const GLYPH_SNAP_AXIS_EPS: f32 = 1e-4;
72
73/// Tolerance (in physical pixels) between the transformed glyph quad size
74/// and its atlas bitmap size for the quad to count as 1:1. Tight enough
75/// that residual mid-bucket zoom scaling (≥1% on any glyph bigger than
76/// ~6 px) never snaps, loose enough to absorb the float error of the
77/// logical→physical round-trip (`bitmap / (sf·rs) · sf · scale`).
78const GLYPH_SNAP_SIZE_EPS: f32 = 1.0 / 16.0;
79
80/// Apply a 2D affine transform to a physical-pixel position.
81/// Same convention as the renderer: `m = [a, b, c, d, tx, ty]` maps
82/// `(x, y) → (a·x + c·y + tx, b·x + d·y + ty)`.
83#[inline]
84fn apply_affine(p: [f32; 2], t: &Transform2D) -> [f32; 2] {
85    let [a, b, c, d, tx, ty] = t.m;
86    [a * p[0] + c * p[1] + tx, b * p[0] + d * p[1] + ty]
87}
88
89/// The four vertices of live picture `quad`, in device pixels: its `screen`
90/// (logical `[x, y, width, height]`) under `transform`, its corners sampling
91/// its `uv` (top-leading, top-trailing, bottom-trailing, bottom-leading) of
92/// a `texture`-sized texture. A quad that maps one texel to one device
93/// pixel, under a transform that neither rotates nor scales it, has its
94/// origin rounded to the pixel grid, so it samples texel centres exactly as
95/// glyphs do, unless its draw turned `pixel_snap` off; any other is placed
96/// where the transform puts it.
97pub(crate) fn live_quad_verts(
98    quad: &LiveImageQuad,
99    texture: (u32, u32),
100    scale_factor: f32,
101    transform: &Transform2D,
102    color: [f32; 4],
103    flags: u32,
104) -> [QuadVertex; 4] {
105    let (screen, uv) = (quad.screen, quad.uv);
106    let [x, y, w, h] = screen;
107    let (sx, sy, sw, sh) = (
108        x * scale_factor,
109        y * scale_factor,
110        w * scale_factor,
111        h * scale_factor,
112    );
113    let (tw, th) = (texture.0 as f32, texture.1 as f32);
114    // Texels the quad's top edge and leading edge cover.
115    let along = |from: [f32; 2], to: [f32; 2]| {
116        ((to[0] - from[0]) * tw).abs() + ((to[1] - from[1]) * th).abs()
117    };
118    let (across, down) = (along(uv[0], uv[1]), along(uv[0], uv[3]));
119    let [a, b, c, d, _, _] = transform.m;
120    let whole = |v: f32| (v - v.round()).abs() < GLYPH_SNAP_SIZE_EPS;
121    let one_to_one = quad.pixel_snap
122        && b.abs() < GLYPH_SNAP_AXIS_EPS
123        && c.abs() < GLYPH_SNAP_AXIS_EPS
124        && (a * sw - across).abs() < GLYPH_SNAP_SIZE_EPS
125        && (d * sh - down).abs() < GLYPH_SNAP_SIZE_EPS
126        && whole(across)
127        && whole(down);
128    let positions: [[f32; 2]; 4] = if one_to_one {
129        let [ox, oy] = apply_affine([sx, sy], transform);
130        let (ox, oy) = (ox.round(), oy.round());
131        let (cw, ch) = (across.round() * a.signum(), down.round() * d.signum());
132        [[ox, oy], [ox + cw, oy], [ox + cw, oy + ch], [ox, oy + ch]]
133    } else {
134        [
135            apply_affine([sx, sy], transform),
136            apply_affine([sx + sw, sy], transform),
137            apply_affine([sx + sw, sy + sh], transform),
138            apply_affine([sx, sy + sh], transform),
139        ]
140    };
141    std::array::from_fn(|i| QuadVertex {
142        position: positions[i],
143        tex_coord: uv[i],
144        color,
145        flags,
146        text_params: 0,
147    })
148}
149
150impl QuadVertex {
151    /// Convert a glyph quad to 4 vertices (two triangles via index buffer),
152    /// applying `scale_factor` (logical → physical pixels) and the current
153    /// affine `transform` (linear part unitless, translation already in
154    /// physical pixels). Atlas coordinates are in texels and normalized to
155    /// 0..1 using the atlas dimensions. Returned positions are in physical
156    /// pixels — the caller converts to NDC; it must NOT transform again.
157    ///
158    /// **Pixel-snap invariant.** The glyph atlas is sampled with bilinear
159    /// filtering so the residual GPU scaling between raster-scale buckets
160    /// (≤ ~12%, see `quantize_raster_scale`) stays smooth. Bilinear is only
161    /// loss-free when each texel maps exactly onto one framebuffer pixel,
162    /// and glyph origins are inherently fractional: shaping pen advances,
163    /// widget offsets, and scroll positions are all fractional floats. An
164    /// unsnapped origin makes the 2×2 kernel mix neighboring texels at
165    /// every edge (uniform blur) and bleed the glyph's last row into the
166    /// transparent atlas gutter (visibly cropping the bottom of letters
167    /// like "c"/"e"). So whenever the transformed quad maps 1:1 onto its
168    /// atlas bitmap — axis-aligned transform and transformed size equal to
169    /// the bitmap size within `GLYPH_SNAP_SIZE_EPS` — the origin is
170    /// rounded to the integer pixel grid and the opposite corner pinned at
171    /// exactly `origin + bitmap size`, making linear sampling an identity.
172    /// This covers identity, fractional DPI, pure translations, and
173    /// exact-bucket zoom (e.g. a 1.25× transform over a 1.25-bucket
174    /// raster). Rotated or residually scaled quads (mid-bucket zoom) skip
175    /// the snap and ride bilinear filtering as intended.
176    pub fn from_glyph_quad_transformed(
177        quad: &GlyphQuad,
178        scale_factor: f32,
179        atlas_width: u32,
180        atlas_height: u32,
181        transform: &Transform2D,
182    ) -> [QuadVertex; 4] {
183        let [x, y, w, h] = quad.screen;
184        let [ax, ay, aw, ah] = quad.atlas;
185        let sx = x * scale_factor;
186        let sy = y * scale_factor;
187        let sw = w * scale_factor;
188        let sh = h * scale_factor;
189
190        // Normalize atlas pixel coords to 0..1 UVs
191        let aw_f = atlas_width.max(1) as f32;
192        let ah_f = atlas_height.max(1) as f32;
193        let u0 = ax / aw_f;
194        let v0 = ay / ah_f;
195        let u1 = (ax + aw) / aw_f;
196        let v1 = (ay + ah) / ah_f;
197
198        let [a, b, c, d, _, _] = transform.m;
199        let axis_aligned = b.abs() < GLYPH_SNAP_AXIS_EPS && c.abs() < GLYPH_SNAP_AXIS_EPS;
200        let one_to_one = axis_aligned
201            && (a * sw - aw).abs() < GLYPH_SNAP_SIZE_EPS
202            && (d * sh - ah).abs() < GLYPH_SNAP_SIZE_EPS;
203        let positions: [[f32; 2]; 4] = if one_to_one {
204            let [ox, oy] = apply_affine([sx, sy], transform);
205            let ox = ox.round();
206            let oy = oy.round();
207            [[ox, oy], [ox + aw, oy], [ox + aw, oy + ah], [ox, oy + ah]]
208        } else {
209            [
210                apply_affine([sx, sy], transform),
211                apply_affine([sx + sw, sy], transform),
212                apply_affine([sx + sw, sy + sh], transform),
213                apply_affine([sx, sy + sh], transform),
214            ]
215        };
216
217        // Color emoji glyphs carry their RGB in the atlas bitmap. Mark
218        // them with a per-vertex flag so the fragment shader can sample
219        // `texture.rgb` directly instead of applying the alpha-mask path.
220        //
221        // The upstream color for color emoji is already `[1, 1, 1, 1]`
222        // (see text-typeset's `rasterize_glyph_quad`); srgb_to_linear
223        // leaves that unchanged, so the cached value still multiplies
224        // cleanly against the sampled RGB as an opacity factor.
225        let flags = if quad.is_color {
226            QUAD_FLAG_COLOR_GLYPH
227        } else {
228            0
229        };
230        let color = srgb_to_linear_rgba(quad.color);
231
232        [
233            QuadVertex {
234                position: positions[0],
235                tex_coord: [u0, v0],
236                color,
237                flags,
238                text_params: 0,
239            },
240            QuadVertex {
241                position: positions[1],
242                tex_coord: [u1, v0],
243                color,
244                flags,
245                text_params: 0,
246            },
247            QuadVertex {
248                position: positions[2],
249                tex_coord: [u1, v1],
250                color,
251                flags,
252                text_params: 0,
253            },
254            QuadVertex {
255                position: positions[3],
256                tex_coord: [u0, v1],
257                color,
258                flags,
259                text_params: 0,
260            },
261        ]
262    }
263}
264
265/// Vertex for the colored rectangle pipeline (decorations).
266#[repr(C)]
267#[derive(Debug, Clone, Copy, Pod, Zeroable)]
268pub struct RectVertex {
269    pub position: [f32; 2],
270    pub color: [f32; 4],
271}
272
273impl RectVertex {
274    /// Convert a decoration rect to 4 vertices.
275    pub fn from_decoration(rect: &DecorationRect, scale_factor: f32) -> [RectVertex; 4] {
276        let [x, y, w, h] = rect.rect;
277        let sx = x * scale_factor;
278        let sy = y * scale_factor;
279        let sw = w * scale_factor;
280        let sh = h * scale_factor;
281
282        [
283            RectVertex {
284                position: [sx, sy],
285                color: srgb_to_linear_rgba(rect.color),
286            },
287            RectVertex {
288                position: [sx + sw, sy],
289                color: srgb_to_linear_rgba(rect.color),
290            },
291            RectVertex {
292                position: [sx + sw, sy + sh],
293                color: srgb_to_linear_rgba(rect.color),
294            },
295            RectVertex {
296                position: [sx, sy + sh],
297                color: srgb_to_linear_rgba(rect.color),
298            },
299        ]
300    }
301}
302
303/// Vertex for the SDF shape pipeline (rounded rects, circles).
304#[repr(C)]
305#[derive(Debug, Clone, Copy, Pod, Zeroable)]
306pub struct SdfVertex {
307    pub position: [f32; 2],
308    /// Local UV coordinates (0..1) within the shape bounds.
309    pub local_uv: [f32; 2],
310    pub color: [f32; 4],
311    pub corner_radii: [f32; 4],
312    /// Shape bounds in pixels: [width, height, stroke_width, paint_type].
313    /// paint_type: 0=solid, 1=linear, 2=radial, 3=conic
314    pub shape_params: [f32; 4],
315    /// Gradient geometry: [start_x, start_y, end_x, end_y] (or center/radius for radial)
316    pub gradient_geo: [f32; 4],
317    /// Gradient stop 0: [r, g, b, a]
318    pub gradient_color0: [f32; 4],
319    /// Gradient stop 1: [r, g, b, a]
320    pub gradient_color1: [f32; 4],
321    /// Gradient stop 2: [r, g, b, a]
322    pub gradient_color2: [f32; 4],
323    /// Gradient stop 3: [r, g, b, a]
324    pub gradient_color3: [f32; 4],
325    /// Gradient stop offsets: [offset0, offset1, offset2, offset3]
326    pub gradient_offsets: [f32; 4],
327}
328
329impl SdfVertex {
330    /// Convert a shape quad to 4 vertices with a **logical** stroke width —
331    /// the border scales with the view transform (the default).
332    ///
333    /// The rasterized quad is expanded outward by `stroke_width / 2 + 1` on
334    /// every side. The SDF shader paints strokes **centered** on the rect
335    /// edge, so the outer half of the stroke falls outside the shape's
336    /// bounds — if the quad isn't padded, those fragments are never
337    /// rasterized and the stroke is visibly truncated by 1 dp on every
338    /// side (most noticeable on focus rings). `local_uv` is extrapolated
339    /// past `[0, 1]` for the padding fragments; the SDF still clips
340    /// correctly because `sd_rounded_rect` returns positive distances
341    /// outside the shape.
342    pub fn from_shape_quad(shape: &ShapeQuad, scale_factor: f32) -> [SdfVertex; 4] {
343        Self::shape_quad_verts(shape, scale_factor, shape.stroke_width * scale_factor)
344    }
345
346    /// Convert a shape quad to 4 vertices with a **cosmetic** stroke: the
347    /// border width is held constant in device pixels (`width × scale_factor`)
348    /// regardless of `zoom`, while the shape body still scales with the
349    /// transform. `zoom` is the uniform scale of the active view transform
350    /// (`hypot(m[0], m[1])`).
351    ///
352    /// The shader measures the SDF in `shape_params.xy = [w·sf, h·sf]` units,
353    /// and one such unit maps to `zoom` device px on screen, so baking the
354    /// stroke param as `width·sf / zoom` lands the rendered border at exactly
355    /// `width·sf` device px at every zoom. Assumes a uniform (non-anisotropic)
356    /// transform — the scene zoom is uniform and rotation preserves the column
357    /// norm.
358    pub fn from_shape_quad_cosmetic(
359        shape: &ShapeQuad,
360        scale_factor: f32,
361        zoom: f32,
362    ) -> [SdfVertex; 4] {
363        let zoom = zoom.max(1e-3);
364        Self::shape_quad_verts(
365            shape,
366            scale_factor,
367            shape.stroke_width * scale_factor / zoom,
368        )
369    }
370
371    /// Shared core for [`from_shape_quad`](Self::from_shape_quad) and
372    /// [`from_shape_quad_cosmetic`](Self::from_shape_quad_cosmetic). Bakes
373    /// `stroke_px` (physical device pixels) as the SDF stroke param and
374    /// derives the rasterization pad from it.
375    fn shape_quad_verts(shape: &ShapeQuad, scale_factor: f32, stroke_px: f32) -> [SdfVertex; 4] {
376        let [x, y, w, h] = shape.screen;
377        let sx = x * scale_factor;
378        let sy = y * scale_factor;
379        let sw = w * scale_factor;
380        let sh = h * scale_factor;
381
382        // Encode paint type and gradient data
383        let (paint_type, gradient_geo, colors, offsets) =
384            encode_paint_data(&shape.paint_data, [0.0, 0.0], w, h);
385
386        let stroke = stroke_px;
387        // Rasterization padding: enough to contain the outer half of the
388        // centered stroke plus a 1 px anti-aliasing margin. Filled shapes
389        // (stroke = 0) still get the AA margin so their edges don't clip.
390        let pad = stroke * 0.5 + 1.0;
391        let u_pad = if sw > 0.0 { pad / sw } else { 0.0 };
392        let v_pad = if sh > 0.0 { pad / sh } else { 0.0 };
393
394        let params = [sw, sh, stroke, paint_type as f32];
395        // Corner radii are authored in logical px but the shader compares
396        // them against `shape_params.xy`, which is in physical px after the
397        // scale_factor multiply above. Without scaling here, a 19×19
398        // logical circle (radius 9.5) renders as a 38×38 physical rect
399        // with 9.5 px corners on Retina — a rounded square instead of a
400        // circle.
401        let scaled_corner_radii = [
402            shape.corner_radii[0] * scale_factor,
403            shape.corner_radii[1] * scale_factor,
404            shape.corner_radii[2] * scale_factor,
405            shape.corner_radii[3] * scale_factor,
406        ];
407
408        let base = SdfVertex {
409            position: [0.0, 0.0],
410            local_uv: [0.0, 0.0],
411            color: srgb_to_linear_rgba(shape.color),
412            corner_radii: scaled_corner_radii,
413            shape_params: params,
414            gradient_geo,
415            gradient_color0: srgb_to_linear_rgba(colors[0]),
416            gradient_color1: srgb_to_linear_rgba(colors[1]),
417            gradient_color2: srgb_to_linear_rgba(colors[2]),
418            gradient_color3: srgb_to_linear_rgba(colors[3]),
419            gradient_offsets: offsets,
420        };
421
422        [
423            SdfVertex {
424                position: [sx - pad, sy - pad],
425                local_uv: [-u_pad, -v_pad],
426                ..base
427            },
428            SdfVertex {
429                position: [sx + sw + pad, sy - pad],
430                local_uv: [1.0 + u_pad, -v_pad],
431                ..base
432            },
433            SdfVertex {
434                position: [sx + sw + pad, sy + sh + pad],
435                local_uv: [1.0 + u_pad, 1.0 + v_pad],
436                ..base
437            },
438            SdfVertex {
439                position: [sx - pad, sy + sh + pad],
440                local_uv: [-u_pad, 1.0 + v_pad],
441                ..base
442            },
443        ]
444    }
445}
446
447/// Encode PaintData into vertex-friendly arrays.
448/// Returns (paint_type, gradient_geo, [4 colors], [4 offsets]).
449///
450/// `pub(crate)` — shared by [`SdfVertex`] (Tier 2) and
451/// [`PathGradientVertex`] (Tier 3 gradient paths), which both encode the
452/// same `PaintData` into the same vertex-attribute shape.
453///
454/// Geometry is normalized into the **quad's** 0..1 UV space, which is not
455/// always the space the paint was authored in: a Tier-3 path's quad may be
456/// snapped outward to whole device pixels, leaving its origin up to a pixel
457/// before the bounds the gradient endpoints are relative to. `origin` is
458/// where the quad starts in the paint's own coordinate space (`[0, 0]`
459/// when they coincide, which is every Tier-2 shape), and `width` / `height`
460/// are the quad's size in that same space. Without the shift a snapped
461/// path's gradient would sit a pixel off the identical unsnapped one.
462pub(crate) fn encode_paint_data(
463    paint_data: &PaintData,
464    origin: [f32; 2],
465    width: f32,
466    height: f32,
467) -> (u32, [f32; 4], [[f32; 4]; 4], [f32; 4]) {
468    let zero_colors = [[0.0; 4]; 4];
469    let zero_offsets = [0.0; 4];
470    let u = |x: f32| (x - origin[0]) / width;
471    let v = |y: f32| (y - origin[1]) / height;
472
473    match paint_data {
474        PaintData::Solid => (0, [0.0; 4], zero_colors, zero_offsets),
475        PaintData::LinearGradient { start, end, stops } => {
476            // Normalize coordinates to 0..1 UV space
477            let geo = [u(start[0]), v(start[1]), u(end[0]), v(end[1])];
478            let (colors, offsets) = encode_stops(stops);
479            (1, geo, colors, offsets)
480        }
481        PaintData::RadialGradient {
482            center,
483            radius,
484            stops,
485        } => {
486            // Normalize center and radius to UV space, accounting for aspect ratio.
487            // The shader computes distance in UV space where both axes span 0..1,
488            // so we normalize the radius relative to width (x-axis) and let the
489            // shader use aspect-corrected distance.
490            let aspect = height / width.max(0.0001);
491            let geo = [u(center[0]), v(center[1]), *radius / width, aspect];
492            let (colors, offsets) = encode_stops(stops);
493            (2, geo, colors, offsets)
494        }
495        PaintData::ConicGradient {
496            center,
497            start_angle,
498            stops,
499        } => {
500            let geo = [u(center[0]), v(center[1]), *start_angle, 0.0];
501            let (colors, offsets) = encode_stops(stops);
502            (3, geo, colors, offsets)
503        }
504    }
505}
506
507/// Encode up to 4 gradient stops into arrays. `pub(crate)` — see
508/// [`encode_paint_data`].
509pub(crate) fn encode_stops(stops: &[teksilo_canvas::GradientStop]) -> ([[f32; 4]; 4], [f32; 4]) {
510    let mut colors = [[0.0f32; 4]; 4];
511    let mut offsets = [0.0f32; 4];
512    for (i, stop) in stops.iter().take(4).enumerate() {
513        colors[i] = stop.color.to_array();
514        offsets[i] = stop.offset;
515    }
516    // If fewer than 4 stops, repeat last to fill
517    if !stops.is_empty() {
518        let last_idx = stops.len().min(4) - 1;
519        for i in stops.len()..4 {
520            colors[i] = colors[last_idx];
521            offsets[i] = offsets[last_idx];
522        }
523    }
524    (colors, offsets)
525}
526
527/// Vertex for the gradient-filled path pipeline (Tier 3 arbitrary paths
528/// filled with a `Paint` gradient — linear/radial/conic). Solid-filled
529/// paths keep using the lean `QuadVertex`/`quad_pipeline`, tinted by a
530/// flat vertex color (see `path_quad_verts` in `renderer.rs`); this
531/// vertex type is only built when `PathEntry::paint_data` is a gradient
532/// variant, and is drawn by the dedicated `path_gradient` pipeline
533/// (`shaders/path_gradient.wgsl`).
534///
535/// `tex_coord` samples the path atlas's AA **coverage mask** (alpha
536/// channel only — the atlas always rasterizes opaque white, see
537/// `path_atlas::rasterize_path`), exactly like `QuadVertex`'s monochrome-
538/// glyph path. `local_uv` is the shape-local 0..1 placement used for the
539/// analytic gradient math — same meaning as `SdfVertex::local_uv`. The
540/// gradient fields mirror `SdfVertex`'s layout exactly so the shared
541/// `encode_paint_data`/`encode_stops` helpers apply unchanged.
542#[repr(C)]
543#[derive(Debug, Clone, Copy, Pod, Zeroable)]
544pub struct PathGradientVertex {
545    pub position: [f32; 2],
546    /// Atlas UV — samples the path atlas's AA coverage mask.
547    pub tex_coord: [f32; 2],
548    /// Shape-local UV (0..1 across the path's bounds) — gradient placement.
549    pub local_uv: [f32; 2],
550    /// 1 = linear, 2 = radial, 3 = conic. Never 0 (Solid) — solid fills
551    /// never build a `PathGradientVertex`; see `path_gradient_quad_verts`
552    /// in `renderer.rs`, which branches on `PathEntry::paint_data` before
553    /// choosing this pipeline.
554    pub paint_type: u32,
555    /// Padding so the struct stride stays a multiple of 8 bytes.
556    pub _pad: u32,
557    /// Gradient geometry: `[start_x, start_y, end_x, end_y]` (or
558    /// center/radius for radial, center/angle for conic) in shape-local
559    /// UV space — see `encode_paint_data`.
560    pub gradient_geo: [f32; 4],
561    /// Gradient stop 0: [r, g, b, a]
562    pub gradient_color0: [f32; 4],
563    /// Gradient stop 1: [r, g, b, a]
564    pub gradient_color1: [f32; 4],
565    /// Gradient stop 2: [r, g, b, a]
566    pub gradient_color2: [f32; 4],
567    /// Gradient stop 3: [r, g, b, a]
568    pub gradient_color3: [f32; 4],
569    /// Gradient stop offsets: [offset0, offset1, offset2, offset3]
570    pub gradient_offsets: [f32; 4],
571}
572
573impl PathGradientVertex {
574    /// Build the 4 vertices for a gradient-filled path quad. Mirrors
575    /// `path_quad_verts`'s bounds/atlas-UV/position math (Tier 3, solid
576    /// paths) — same pixel-space quad, same atlas-region UV lookup, same
577    /// `transform` composition inside the function — but emits full
578    /// `paint_type` + gradient fields via the shared `encode_paint_data`
579    /// instead of a single flat tinted color.
580    ///
581    /// `opacity` is folded into EACH gradient stop's alpha
582    /// (`gradient_colorN[3] *= opacity`), not a flat `color` field,
583    /// because `path_gradient.wgsl`'s fragment shader ignores any flat
584    /// color for gradient paint types and only ever reads the gradient
585    /// stops — unlike the SDF pipeline, which (pre-existingly, and out of
586    /// scope here) does not fold `SetOpacity` into gradient `ShapeQuad`s.
587    pub(crate) fn from_path_entry(
588        entry: &PathEntry,
589        placement: &crate::path_atlas::PathPlacement,
590        scale_factor: f32,
591        atlas_width: u32,
592        atlas_height: u32,
593        opacity: f32,
594        transform: &Transform2D,
595    ) -> [PathGradientVertex; 4] {
596        // Same rule as `path_quad_verts`: the rect is the placement's, never
597        // re-derived from `entry.bounds`.
598        let region = &placement.region;
599        let [sx, sy, sw, sh] = placement.device_rect;
600
601        let aw = atlas_width.max(1) as f32;
602        let ah = atlas_height.max(1) as f32;
603        let u0 = region.x as f32 / aw;
604        let v0 = region.y as f32 / ah;
605        let u1 = (region.x + region.w) as f32 / aw;
606        let v1 = (region.y + region.h) as f32 / ah;
607
608        // Gradient endpoints are authored in logical pixels relative to
609        // `entry.bounds`' origin, but the quad may have been snapped outward
610        // to the device pixel grid. Re-base into the quad's space, in those
611        // same logical units, so the gradient lands where the author put it
612        // whether or not the snap moved the quad.
613        let sf = scale_factor.max(1e-4);
614        let origin = [
615            (sx - entry.bounds[0] * scale_factor) / sf,
616            (sy - entry.bounds[1] * scale_factor) / sf,
617        ];
618        let (paint_type, gradient_geo, raw_colors, gradient_offsets) =
619            encode_paint_data(&entry.paint_data, origin, sw / sf, sh / sf);
620        // Linearize (sRGB → linear, matching every other pipeline) and
621        // fold opacity into alpha — see the doc comment above.
622        let colors: [[f32; 4]; 4] = std::array::from_fn(|i| {
623            let mut c = srgb_to_linear_rgba(raw_colors[i]);
624            c[3] *= opacity;
625            c
626        });
627
628        let positions = [
629            apply_affine([sx, sy], transform),
630            apply_affine([sx + sw, sy], transform),
631            apply_affine([sx + sw, sy + sh], transform),
632            apply_affine([sx, sy + sh], transform),
633        ];
634        let tex_coords = [[u0, v0], [u1, v0], [u1, v1], [u0, v1]];
635        let local_uvs: [[f32; 2]; 4] = [[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]];
636
637        std::array::from_fn(|i| PathGradientVertex {
638            position: positions[i],
639            tex_coord: tex_coords[i],
640            local_uv: local_uvs[i],
641            paint_type,
642            _pad: 0,
643            gradient_geo,
644            gradient_color0: colors[0],
645            gradient_color1: colors[1],
646            gradient_color2: colors[2],
647            gradient_color3: colors[3],
648            gradient_offsets,
649        })
650    }
651}
652
653/// Standard quad indices for two triangles from 4 vertices.
654///
655/// 32-bit indices: a frame can carry far more than 16 384 quads (the u16
656/// vertex-index ceiling) — large text runs, dense data grids, big scenes —
657/// and a single contiguous batch can approach that count. u16 indices would
658/// silently wrap past vertex 65 535, corrupting draw calls in release and
659/// panicking in debug. The quad index buffer is therefore `Uint32`.
660pub const QUAD_INDICES: [u32; 6] = [0, 1, 2, 0, 2, 3];
661
662/// Generate indices for N quads.
663pub fn generate_quad_indices(count: usize) -> Vec<u32> {
664    let mut indices = Vec::with_capacity(count * 6);
665    for i in 0..count {
666        let base = (i * 4) as u32;
667        for &offset in &QUAD_INDICES {
668            indices.push(base + offset);
669        }
670    }
671    indices
672}
673
674/// Vertex for the shadow pipeline (box shadows with Gaussian blur).
675#[repr(C)]
676#[derive(Debug, Clone, Copy, Pod, Zeroable)]
677pub struct ShadowVertex {
678    pub position: [f32; 2],
679    /// Local UV coordinates (0..1) within the shadow quad bounds.
680    pub local_uv: [f32; 2],
681    pub shadow_color: [f32; 4],
682    pub corner_radii: [f32; 4],
683    /// [shape_width, shape_height, blur_radius, spread].
684    pub shadow_params: [f32; 4],
685    /// [offset_x, offset_y, 0, 0] — offset of inner shape center within shadow quad.
686    pub shape_offset: [f32; 4],
687}
688
689impl ShadowVertex {
690    /// Convert a shadow quad to 4 vertices.
691    pub fn from_shadow_quad(shadow: &ShadowQuad, scale_factor: f32) -> [ShadowVertex; 4] {
692        let [x, y, w, h] = shadow.screen;
693        let sx = x * scale_factor;
694        let sy = y * scale_factor;
695        let sw = w * scale_factor;
696        let sh = h * scale_factor;
697
698        let [sr_x, sr_y, sr_w, sr_h] = shadow.shape_rect;
699        let shape_w = sr_w * scale_factor;
700        let shape_h = sr_h * scale_factor;
701
702        // Offset of shape center relative to shadow quad center
703        let shadow_cx = sx + sw * 0.5;
704        let shadow_cy = sy + sh * 0.5;
705        let shape_cx = (sr_x + sr_w * 0.5) * scale_factor;
706        let shape_cy = (sr_y + sr_h * 0.5) * scale_factor;
707        let offset_x = shape_cx - shadow_cx;
708        let offset_y = shape_cy - shadow_cy;
709
710        let params = [
711            shape_w,
712            shape_h,
713            shadow.blur_radius * scale_factor,
714            shadow.spread * scale_factor,
715        ];
716        let offset = [offset_x, offset_y, 0.0, 0.0];
717        // Match the SDF pipeline: shadow_params.xy is in physical px after
718        // scale_factor, so the matching corner radii also have to be in
719        // physical px. Otherwise circular/pill shadow shapes degenerate
720        // into rounded squares on Retina.
721        let scaled_corner_radii = [
722            shadow.corner_radii[0] * scale_factor,
723            shadow.corner_radii[1] * scale_factor,
724            shadow.corner_radii[2] * scale_factor,
725            shadow.corner_radii[3] * scale_factor,
726        ];
727
728        [
729            ShadowVertex {
730                position: [sx, sy],
731                local_uv: [0.0, 0.0],
732                shadow_color: srgb_to_linear_rgba(shadow.color),
733                corner_radii: scaled_corner_radii,
734                shadow_params: params,
735                shape_offset: offset,
736            },
737            ShadowVertex {
738                position: [sx + sw, sy],
739                local_uv: [1.0, 0.0],
740                shadow_color: srgb_to_linear_rgba(shadow.color),
741                corner_radii: scaled_corner_radii,
742                shadow_params: params,
743                shape_offset: offset,
744            },
745            ShadowVertex {
746                position: [sx + sw, sy + sh],
747                local_uv: [1.0, 1.0],
748                shadow_color: srgb_to_linear_rgba(shadow.color),
749                corner_radii: scaled_corner_radii,
750                shadow_params: params,
751                shape_offset: offset,
752            },
753            ShadowVertex {
754                position: [sx, sy + sh],
755                local_uv: [0.0, 1.0],
756                shadow_color: srgb_to_linear_rgba(shadow.color),
757                corner_radii: scaled_corner_radii,
758                shadow_params: params,
759                shape_offset: offset,
760            },
761        ]
762    }
763}
764
765/// Vertex for the shader-driven animated-quad pipeline (procedural
766/// and sprite kinds). All four vertices of a quad carry the same
767/// `slot`, which the fragment shader uses to look up per-frame state
768/// (phase, resolved colors, atlas dims) in the `anim_uniforms` buffer.
769/// No color or timing is baked in the vertex — that's the whole point:
770/// rebuilding the vertex batch is unnecessary when only the phase
771/// changes, so the widget's `paint()` doesn't re-run per frame.
772#[repr(C)]
773#[derive(Debug, Clone, Copy, Pod, Zeroable)]
774pub struct AnimQuadVertex {
775    /// Pixel position; converted to NDC in the render loop.
776    pub position: [f32; 2],
777    /// Local UV within the quad (0..1 across each axis). The fragment
778    /// shader uses `uv.x` to decide sweep inclusion; the sprite shader
779    /// combines it with `AnimParams::atlas_cols`/`atlas_rows` to sample
780    /// the atlas cell.
781    pub uv: [f32; 2],
782    /// Index into the renderer's `AnimParams` uniform array. Same for
783    /// all four vertices of a quad; declared `@interpolate(flat)` in
784    /// WGSL to preserve the integer across rasterization.
785    pub slot: u32,
786    /// Struct padding to keep stride a multiple of 8 bytes (matches
787    /// `QuadVertex` convention for wgpu vertex-buffer layouts).
788    pub _pad: u32,
789}
790
791impl AnimQuadVertex {
792    pub fn from_animated_quad(
793        draw: &teksilo_canvas::AnimatedQuadDraw,
794        scale_factor: f32,
795    ) -> [AnimQuadVertex; 4] {
796        let [x, y, w, h] = draw.screen;
797        let sx = x * scale_factor;
798        let sy = y * scale_factor;
799        let sw = w * scale_factor;
800        let sh = h * scale_factor;
801        [
802            AnimQuadVertex {
803                position: [sx, sy],
804                uv: [0.0, 0.0],
805                slot: draw.slot,
806                _pad: 0,
807            },
808            AnimQuadVertex {
809                position: [sx + sw, sy],
810                uv: [1.0, 0.0],
811                slot: draw.slot,
812                _pad: 0,
813            },
814            AnimQuadVertex {
815                position: [sx + sw, sy + sh],
816                uv: [1.0, 1.0],
817                slot: draw.slot,
818                _pad: 0,
819            },
820            AnimQuadVertex {
821                position: [sx, sy + sh],
822                uv: [0.0, 1.0],
823                slot: draw.slot,
824                _pad: 0,
825            },
826        ]
827    }
828}
829
830#[cfg(test)]
831mod tests {
832    use super::*;
833    use teksilo_canvas::{DecorationKind, GradientStop, PaintData, ShapeKind, StrokeSpace};
834    use teksilo_tokens::Color;
835
836    /// Build a glyph quad with the given screen rect and atlas rect.
837    fn glyph(screen: [f32; 4], atlas: [f32; 4], is_color: bool) -> GlyphQuad {
838        GlyphQuad {
839            screen,
840            atlas,
841            color: [1.0, 1.0, 1.0, 1.0],
842            is_color,
843        }
844    }
845
846    fn assert_pos_near(actual: [f32; 2], expected: [f32; 2]) {
847        assert!(
848            (actual[0] - expected[0]).abs() < 1e-3 && (actual[1] - expected[1]).abs() < 1e-3,
849            "position {actual:?} != expected {expected:?}"
850        );
851    }
852
853    #[test]
854    fn glyph_quad_to_vertices() {
855        // Quad size (30×40) ≠ atlas size (64×64) → no snap; identity
856        // transform passes positions through unchanged.
857        let quad = glyph([10.0, 20.0, 30.0, 40.0], [0.0, 0.0, 64.0, 64.0], false);
858        let verts =
859            QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &Transform2D::IDENTITY);
860        assert_eq!(verts.len(), 4);
861        assert_eq!(verts[0].position, [10.0, 20.0]);
862        assert_eq!(verts[1].position, [40.0, 20.0]); // x + w
863        assert_eq!(verts[2].position, [40.0, 60.0]); // x + w, y + h
864        // Atlas coords normalized: 64/256 = 0.25
865        assert_eq!(verts[0].tex_coord, [0.0, 0.0]);
866        assert_eq!(verts[2].tex_coord, [0.25, 0.25]);
867    }
868
869    #[test]
870    fn scale_factor_applied_to_glyph_coords() {
871        // Physical size 60×80 ≠ atlas 128×128 → no snap.
872        let quad = glyph([10.0, 20.0, 30.0, 40.0], [0.0, 0.0, 128.0, 128.0], false);
873        let verts =
874            QuadVertex::from_glyph_quad_transformed(&quad, 2.0, 256, 256, &Transform2D::IDENTITY);
875        assert_eq!(verts[0].position, [20.0, 40.0]);
876        assert_eq!(verts[1].position, [80.0, 40.0]);
877    }
878
879    #[test]
880    fn glyph_snap_identity_fractional_origin() {
881        // 1:1 quad (30×40 == atlas 30×40) at a fractional origin: the
882        // origin rounds to the pixel grid and the far corner is pinned at
883        // exactly origin + bitmap size.
884        let quad = glyph([10.3, 20.7, 30.0, 40.0], [0.0, 0.0, 30.0, 40.0], false);
885        let verts =
886            QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &Transform2D::IDENTITY);
887        assert_eq!(verts[0].position, [10.0, 21.0]);
888        assert_eq!(verts[1].position, [40.0, 21.0]);
889        assert_eq!(verts[2].position, [40.0, 61.0]);
890        assert_eq!(verts[3].position, [10.0, 61.0]);
891    }
892
893    #[test]
894    fn glyph_snap_hidpi_scale_factor() {
895        // sf=2: logical 16×16 → physical 32×32 == atlas bitmap. Fractional
896        // logical origin (5.7, 8.3) → physical (11.4, 16.6) → snaps to
897        // (11, 17).
898        let quad = glyph([5.7, 8.3, 16.0, 16.0], [0.0, 0.0, 32.0, 32.0], false);
899        let verts =
900            QuadVertex::from_glyph_quad_transformed(&quad, 2.0, 256, 256, &Transform2D::IDENTITY);
901        assert_eq!(verts[0].position, [11.0, 17.0]);
902        assert_eq!(verts[2].position, [43.0, 49.0]);
903    }
904
905    #[test]
906    fn glyph_snap_fractional_dpi() {
907        // sf=1.25 (Linux fractional scaling): logical 20×20 → physical
908        // 25×25 == atlas bitmap. Origin (4.2, 7.8) → (5.25, 9.75) →
909        // snaps to (5, 10).
910        let quad = glyph([4.2, 7.8, 20.0, 20.0], [0.0, 0.0, 25.0, 25.0], false);
911        let verts =
912            QuadVertex::from_glyph_quad_transformed(&quad, 1.25, 256, 256, &Transform2D::IDENTITY);
913        assert_eq!(verts[0].position, [5.0, 10.0]);
914        assert_eq!(verts[2].position, [30.0, 35.0]);
915    }
916
917    #[test]
918    fn glyph_snap_exact_bucket_zoom() {
919        // A 1.25× zoom transform over a raster_scale=1.25 bucket: the
920        // bitmap is 1.25× denser (atlas 50×50 for a 20×20-logical glyph at
921        // sf=2 → pre-transform physical 40×40), so the transformed size
922        // (1.25·40 = 50) matches the bitmap exactly → snap fires even
923        // under zoom. Fractional translation rounds away.
924        let quad = glyph([4.0, 8.0, 20.0, 20.0], [0.0, 0.0, 50.0, 50.0], false);
925        let zoom = Transform2D {
926            m: [1.25, 0.0, 0.0, 1.25, 3.3, 7.8],
927        };
928        let verts = QuadVertex::from_glyph_quad_transformed(&quad, 2.0, 256, 256, &zoom);
929        // origin: (1.25·8 + 3.3, 1.25·16 + 7.8) = (13.3, 27.8) → (13, 28)
930        assert_eq!(verts[0].position, [13.0, 28.0]);
931        assert_eq!(verts[2].position, [63.0, 78.0]);
932    }
933
934    #[test]
935    fn glyph_no_snap_mid_bucket_residual() {
936        // A 1.1× zoom over a 1.25-bucket raster: transformed size
937        // (1.1·40 = 44) ≠ bitmap (50) → residual GPU scaling, no snap;
938        // all corners go through the plain affine transform.
939        let quad = glyph([4.0, 8.0, 20.0, 20.0], [0.0, 0.0, 50.0, 50.0], false);
940        let zoom = Transform2D {
941            m: [1.1, 0.0, 0.0, 1.1, 3.3, 7.8],
942        };
943        let verts = QuadVertex::from_glyph_quad_transformed(&quad, 2.0, 256, 256, &zoom);
944        assert_pos_near(verts[0].position, [1.1 * 8.0 + 3.3, 1.1 * 16.0 + 7.8]);
945        assert_pos_near(verts[2].position, [1.1 * 48.0 + 3.3, 1.1 * 56.0 + 7.8]);
946    }
947
948    #[test]
949    fn glyph_no_snap_rotation() {
950        // Rotated transform (b, c ≠ 0) never snaps, even at matching size.
951        let quad = glyph([10.0, 20.0, 30.0, 40.0], [0.0, 0.0, 30.0, 40.0], false);
952        let (s, c) = (0.1_f32.sin(), 0.1_f32.cos());
953        let rot = Transform2D {
954            m: [c, s, -s, c, 0.0, 0.0],
955        };
956        let verts = QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &rot);
957        assert_pos_near(
958            verts[0].position,
959            [c * 10.0 - s * 20.0, s * 10.0 + c * 20.0],
960        );
961        assert_pos_near(
962            verts[2].position,
963            [c * 40.0 - s * 60.0, s * 40.0 + c * 60.0],
964        );
965    }
966
967    #[test]
968    fn glyph_snap_translation_only_transform() {
969        // Pure fractional translation (e.g. scroll offset) still maps 1:1
970        // → snapped.
971        let quad = glyph([10.3, 20.0, 30.0, 40.0], [0.0, 0.0, 30.0, 40.0], false);
972        let pan = Transform2D {
973            m: [1.0, 0.0, 0.0, 1.0, 5.7, 3.2],
974        };
975        let verts = QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &pan);
976        // origin: (10.3 + 5.7, 20.0 + 3.2) = (16.0, 23.2) → (16, 23)
977        assert_eq!(verts[0].position, [16.0, 23.0]);
978        assert_eq!(verts[2].position, [46.0, 63.0]);
979    }
980
981    #[test]
982    fn glyph_snap_color_emoji_flag_preserved() {
983        let quad = glyph([10.3, 20.7, 30.0, 40.0], [0.0, 0.0, 30.0, 40.0], true);
984        let verts =
985            QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &Transform2D::IDENTITY);
986        assert_eq!(verts[0].position, [10.0, 21.0]);
987        for v in &verts {
988            assert_eq!(v.flags, QUAD_FLAG_COLOR_GLYPH);
989        }
990    }
991
992    #[test]
993    fn glyph_uvs_independent_of_snapping() {
994        // UVs come from the atlas rect alone — identical whether the
995        // position path snapped or not.
996        let quad = glyph([10.3, 20.7, 30.0, 40.0], [16.0, 32.0, 30.0, 40.0], false);
997        let snapped =
998            QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &Transform2D::IDENTITY);
999        let residual = Transform2D {
1000            m: [1.1, 0.0, 0.0, 1.1, 0.0, 0.0],
1001        };
1002        let unsnapped = QuadVertex::from_glyph_quad_transformed(&quad, 1.0, 256, 256, &residual);
1003        for (a, b) in snapped.iter().zip(unsnapped.iter()) {
1004            assert_eq!(a.tex_coord, b.tex_coord);
1005        }
1006        assert_eq!(snapped[0].tex_coord, [16.0 / 256.0, 32.0 / 256.0]);
1007        assert_eq!(snapped[2].tex_coord, [46.0 / 256.0, 72.0 / 256.0]);
1008    }
1009
1010    #[test]
1011    fn decoration_rect_to_vertices() {
1012        let rect = DecorationRect {
1013            rect: [0.0, 0.0, 100.0, 2.0],
1014            color: [1.0, 0.0, 0.0, 1.0],
1015            kind: DecorationKind::FocusRing,
1016        };
1017        let verts = RectVertex::from_decoration(&rect, 1.0);
1018        assert_eq!(verts.len(), 4);
1019        assert_eq!(verts[0].position, [0.0, 0.0]);
1020        assert_eq!(verts[2].position, [100.0, 2.0]);
1021    }
1022
1023    #[test]
1024    fn shape_quad_to_sdf_vertices() {
1025        let shape = ShapeQuad {
1026            screen: [0.0, 0.0, 100.0, 40.0],
1027            color: [0.0, 0.5, 0.0, 1.0],
1028            shape: ShapeKind::RoundedRect,
1029            stroke_width: 0.0,
1030            stroke_space: StrokeSpace::Logical,
1031            corner_radii: [6.0, 6.0, 6.0, 6.0],
1032            paint_data: PaintData::Solid,
1033        };
1034        let verts = SdfVertex::from_shape_quad(&shape, 1.0);
1035        assert_eq!(verts.len(), 4);
1036        assert_eq!(verts[0].corner_radii, [6.0, 6.0, 6.0, 6.0]);
1037        // Unfilled: quad is padded by the 1 dp AA margin on each side.
1038        // local_uv is extrapolated correspondingly.
1039        assert_eq!(verts[0].position, [-1.0, -1.0]);
1040        assert_eq!(verts[2].position, [101.0, 41.0]);
1041        assert!((verts[0].local_uv[0] - (-0.01)).abs() < 1e-5);
1042        assert!((verts[0].local_uv[1] - (-0.025)).abs() < 1e-5);
1043        assert!((verts[2].local_uv[0] - 1.01).abs() < 1e-5);
1044        assert!((verts[2].local_uv[1] - 1.025).abs() < 1e-5);
1045    }
1046
1047    #[test]
1048    fn sdf_scale_factor() {
1049        let shape = ShapeQuad {
1050            screen: [10.0, 10.0, 100.0, 40.0],
1051            color: [0.0, 0.0, 0.0, 1.0],
1052            shape: ShapeKind::RoundedRect,
1053            stroke_width: 2.0,
1054            stroke_space: StrokeSpace::Logical,
1055            corner_radii: [4.0; 4],
1056            paint_data: PaintData::Solid,
1057        };
1058        let verts = SdfVertex::from_shape_quad(&shape, 2.0);
1059        // Scaled origin (20, 20) is further offset by the rasterization pad
1060        // (stroke/2 + 1) = (2*2)/2 + 1 = 3 pixels.
1061        assert_eq!(verts[0].position, [17.0, 17.0]);
1062        assert_eq!(verts[0].shape_params[2], 4.0); // stroke_width * 2
1063        // Corner radii must scale with the rect so a circle stays a circle
1064        // on HiDPI. shape_params.xy is in physical px; corner_radii has to
1065        // match or radius/half_size diverges.
1066        assert_eq!(verts[0].corner_radii, [8.0; 4]);
1067    }
1068
1069    #[test]
1070    fn sdf_circle_stays_circle_on_hidpi() {
1071        // Regression: a 19×19 logical rect with 9.5 px corner radius is a
1072        // perfect circle. On Retina (scale_factor 2) the shader works in
1073        // physical px against `shape_params.xy`. If corner_radii is left in
1074        // logical px, the radio button / toggle pill renders as a rounded
1075        // square instead of a circle.
1076        let shape = ShapeQuad {
1077            screen: [0.0, 0.0, 19.0, 19.0],
1078            color: [0.0, 0.0, 0.0, 1.0],
1079            shape: ShapeKind::RoundedRect,
1080            stroke_width: 0.0,
1081            stroke_space: StrokeSpace::Logical,
1082            corner_radii: [9.5; 4],
1083            paint_data: PaintData::Solid,
1084        };
1085        let verts = SdfVertex::from_shape_quad(&shape, 2.0);
1086        assert_eq!(verts[0].shape_params[0], 38.0);
1087        assert_eq!(verts[0].shape_params[1], 38.0);
1088        assert_eq!(verts[0].corner_radii, [19.0; 4]);
1089    }
1090
1091    #[test]
1092    fn cosmetic_shape_stroke_param_is_inverse_zoom() {
1093        // Cosmetic border: the baked SDF stroke param = width·sf / zoom, so
1094        // after the shader's per-unit ×zoom mapping the border lands at a
1095        // constant width·sf device px at any zoom. The body size params stay
1096        // put (the body still zooms via the view transform).
1097        let shape = ShapeQuad {
1098            screen: [0.0, 0.0, 100.0, 100.0],
1099            color: [0.0, 0.0, 0.0, 1.0],
1100            shape: ShapeKind::RoundedRect,
1101            stroke_width: 2.0,
1102            stroke_space: StrokeSpace::Device,
1103            corner_radii: [10.0; 4],
1104            paint_data: PaintData::Solid,
1105        };
1106        let sf = 2.0;
1107        let logical = SdfVertex::from_shape_quad(&shape, sf);
1108        let z1 = SdfVertex::from_shape_quad_cosmetic(&shape, sf, 1.0);
1109        let z2 = SdfVertex::from_shape_quad_cosmetic(&shape, sf, 2.0);
1110        // zoom 1 matches the logical bake: width·sf = 2·2 = 4.
1111        assert!((z1[0].shape_params[2] - logical[0].shape_params[2]).abs() < 1e-4);
1112        assert!((z1[0].shape_params[2] - 4.0).abs() < 1e-4);
1113        // zoom 2 halves the param so the on-screen width stays width·sf.
1114        assert!((z2[0].shape_params[2] - 2.0).abs() < 1e-4);
1115        // Body size params unchanged across zoom (the quad corners zoom, not
1116        // the SDF body units): width·sf = 100·2 = 200.
1117        assert_eq!(z1[0].shape_params[0], z2[0].shape_params[0]);
1118        assert_eq!(z2[0].shape_params[0], 200.0);
1119    }
1120
1121    #[test]
1122    fn sdf_linear_gradient_encoding() {
1123        let shape = ShapeQuad {
1124            screen: [0.0, 0.0, 100.0, 50.0],
1125            color: [1.0, 1.0, 1.0, 1.0],
1126            shape: ShapeKind::RoundedRect,
1127            stroke_width: 0.0,
1128            stroke_space: StrokeSpace::Logical,
1129            corner_radii: [0.0; 4],
1130            paint_data: PaintData::LinearGradient {
1131                start: [0.0, 0.0],
1132                end: [100.0, 0.0],
1133                stops: vec![
1134                    GradientStop {
1135                        offset: 0.0,
1136                        color: Color::RED,
1137                    },
1138                    GradientStop {
1139                        offset: 1.0,
1140                        color: Color::BLUE,
1141                    },
1142                ],
1143            },
1144        };
1145        let verts = SdfVertex::from_shape_quad(&shape, 1.0);
1146        // paint_type = 1 (linear)
1147        assert!((verts[0].shape_params[3] - 1.0).abs() < 0.01);
1148        // gradient_geo: start=(0,0), end=(1,0) in UV
1149        assert!((verts[0].gradient_geo[0]).abs() < 0.01);
1150        assert!((verts[0].gradient_geo[2] - 1.0).abs() < 0.01);
1151        // First stop is red
1152        assert!((verts[0].gradient_color0[0] - 1.0).abs() < 0.01);
1153        // Offsets
1154        assert!((verts[0].gradient_offsets[0]).abs() < 0.01);
1155        assert!((verts[0].gradient_offsets[1] - 1.0).abs() < 0.01);
1156    }
1157
1158    #[test]
1159    fn linear_gradient_endpoints_are_rect_local_not_absolute() {
1160        // Regression for the HSV-canvas bug: the gradient endpoints
1161        // are normalized by the rect's width/height (`encode_paint_data`
1162        // doesn't see the rect origin), so callers MUST pass them in
1163        // rect-local coordinates. A rect at non-origin with rect-local
1164        // endpoints (0,0)→(0,h) must encode to start_uv=(0,0) and
1165        // end_uv=(0,1) — full gradient sampling across the rect.
1166        // Passing absolute coords would shift the endpoints away and
1167        // visibly squash the gradient.
1168        let shape = ShapeQuad {
1169            screen: [50.0, 100.0, 200.0, 200.0],
1170            color: [1.0, 1.0, 1.0, 1.0],
1171            shape: ShapeKind::RoundedRect,
1172            stroke_width: 0.0,
1173            stroke_space: StrokeSpace::Logical,
1174            corner_radii: [0.0; 4],
1175            paint_data: PaintData::LinearGradient {
1176                start: [0.0, 0.0],
1177                end: [0.0, 200.0],
1178                stops: vec![
1179                    GradientStop {
1180                        offset: 0.0,
1181                        color: Color::new(0.0, 0.0, 0.0, 0.0),
1182                    },
1183                    GradientStop {
1184                        offset: 1.0,
1185                        color: Color::BLACK,
1186                    },
1187                ],
1188            },
1189        };
1190        let verts = SdfVertex::from_shape_quad(&shape, 1.0);
1191        assert!((verts[0].gradient_geo[0]).abs() < 1e-5, "start_uv.x");
1192        assert!((verts[0].gradient_geo[1]).abs() < 1e-5, "start_uv.y");
1193        assert!((verts[0].gradient_geo[2]).abs() < 1e-5, "end_uv.x");
1194        assert!((verts[0].gradient_geo[3] - 1.0).abs() < 1e-5, "end_uv.y");
1195    }
1196
1197    /// Rasterize `entry`'s path into a scratch atlas and return the
1198    /// resulting region — the public-API way to obtain an `AtlasRegion`
1199    /// for a `PathGradientVertex` test (its `last_used_frame` field is
1200    /// private to `path_atlas`, so tests outside that module can't
1201    /// construct one by hand).
1202    fn rasterize_for_test(entry: &PathEntry, atlas_size: u32) -> crate::path_atlas::PathPlacement {
1203        place_for_test(entry, atlas_size, 1.0, false)
1204    }
1205
1206    fn place_for_test(
1207        entry: &PathEntry,
1208        atlas_size: u32,
1209        scale_factor: f32,
1210        snap: bool,
1211    ) -> crate::path_atlas::PathPlacement {
1212        let mut atlas = crate::path_atlas::PathAtlas::new(atlas_size, atlas_size);
1213        atlas.begin_frame();
1214        atlas
1215            .lookup_or_rasterize(
1216                &entry.path,
1217                &entry.stroke_style,
1218                entry.fill_rule,
1219                entry.bounds,
1220                scale_factor,
1221                1.0,
1222                snap,
1223            )
1224            .expect("test path rasterizes")
1225    }
1226
1227    /// Snapping the quad to the pixel grid must not move the gradient.
1228    ///
1229    /// The quad grows outward by up to a pixel on each side, and gradient
1230    /// geometry is normalized across the quad — so without re-basing, the
1231    /// same gradient would land in a different place depending on whether
1232    /// the snap happened to fire. The invariant: the device position of the
1233    /// gradient's start point is the path bounds' own origin, either way.
1234    #[test]
1235    fn snapping_the_quad_does_not_move_the_gradient() {
1236        // A half-pixel bounds origin: the case the snap exists for.
1237        let bounds_rect = teksilo_canvas::Rect::new(1.5, 1.5, 13.0, 13.0);
1238        let entry = gradient_path_entry(
1239            bounds_rect,
1240            PaintData::LinearGradient {
1241                start: [0.0, 0.0],
1242                end: [13.0, 0.0],
1243                stops: vec![
1244                    GradientStop {
1245                        offset: 0.0,
1246                        color: Color::RED,
1247                    },
1248                    GradientStop {
1249                        offset: 1.0,
1250                        color: Color::BLUE,
1251                    },
1252                ],
1253            },
1254        );
1255
1256        for snap in [false, true] {
1257            let placement = place_for_test(&entry, 256, 1.0, snap);
1258            let verts = PathGradientVertex::from_path_entry(
1259                &entry,
1260                &placement,
1261                1.0,
1262                256,
1263                256,
1264                1.0,
1265                &Transform2D::IDENTITY,
1266            );
1267            let [qx, _, qw, _] = placement.device_rect;
1268            // Where the gradient's first stop lands, in device pixels.
1269            let start_x = qx + verts[0].gradient_geo[0] * qw;
1270            let end_x = qx + verts[0].gradient_geo[2] * qw;
1271            assert!(
1272                (start_x - 1.5).abs() < 0.01,
1273                "snap={snap}: gradient start must sit at the bounds origin, got {start_x}"
1274            );
1275            assert!(
1276                (end_x - 14.5).abs() < 0.01,
1277                "snap={snap}: gradient end must sit at the bounds' far edge, got {end_x}"
1278            );
1279        }
1280    }
1281
1282    fn gradient_path_entry(bounds_rect: teksilo_canvas::Rect, paint_data: PaintData) -> PathEntry {
1283        use teksilo_canvas::{FillRule, StrokeStyle};
1284        PathEntry {
1285            path: teksilo_canvas::Path::rect(bounds_rect),
1286            color: [1.0, 1.0, 1.0, 1.0],
1287            stroke_style: StrokeStyle::solid(0.0),
1288            fill_rule: FillRule::Winding,
1289            bounds: bounds_rect.to_array(),
1290            paint_data,
1291        }
1292    }
1293
1294    #[test]
1295    fn path_gradient_linear_encoding() {
1296        let bounds_rect = teksilo_canvas::Rect::new(0.0, 0.0, 100.0, 50.0);
1297        let entry = gradient_path_entry(
1298            bounds_rect,
1299            PaintData::LinearGradient {
1300                start: [0.0, 0.0],
1301                end: [100.0, 0.0],
1302                stops: vec![
1303                    GradientStop {
1304                        offset: 0.0,
1305                        color: Color::RED,
1306                    },
1307                    GradientStop {
1308                        offset: 1.0,
1309                        color: Color::BLUE,
1310                    },
1311                ],
1312            },
1313        );
1314        let placement = rasterize_for_test(&entry, 256);
1315
1316        let verts = PathGradientVertex::from_path_entry(
1317            &entry,
1318            &placement,
1319            1.0,
1320            256,
1321            256,
1322            1.0,
1323            &Transform2D::IDENTITY,
1324        );
1325
1326        // paint_type = 1 (linear)
1327        assert_eq!(verts[0].paint_type, 1);
1328        // gradient_geo: start=(0,0), end=(1,0) in UV
1329        assert!((verts[0].gradient_geo[0]).abs() < 0.01);
1330        assert!((verts[0].gradient_geo[2] - 1.0).abs() < 0.01);
1331        // First stop is red (pure red/blue are fixed points of sRGB→linear)
1332        assert!((verts[0].gradient_color0[0] - 1.0).abs() < 0.01);
1333        assert!((verts[0].gradient_color0[1]).abs() < 0.01);
1334        // Offsets
1335        assert!((verts[0].gradient_offsets[0]).abs() < 0.01);
1336        assert!((verts[0].gradient_offsets[1] - 1.0).abs() < 0.01);
1337        // local_uv corners follow the same 0..1 convention as SdfVertex.
1338        assert_eq!(verts[0].local_uv, [0.0, 0.0]);
1339        assert_eq!(verts[1].local_uv, [1.0, 0.0]);
1340        assert_eq!(verts[2].local_uv, [1.0, 1.0]);
1341        assert_eq!(verts[3].local_uv, [0.0, 1.0]);
1342    }
1343
1344    #[test]
1345    fn path_gradient_endpoints_are_rect_local_not_absolute() {
1346        // Same regression as `linear_gradient_endpoints_are_rect_local_not_absolute`,
1347        // for the Tier-3 path case: gradient endpoints are normalized by
1348        // the path bounds' width/height alone (`encode_paint_data` never
1349        // sees the bounds origin), so a path positioned away from the
1350        // origin must still encode the same normalized start/end UVs.
1351        let bounds_rect = teksilo_canvas::Rect::new(50.0, 100.0, 200.0, 200.0);
1352        let entry = gradient_path_entry(
1353            bounds_rect,
1354            PaintData::LinearGradient {
1355                start: [0.0, 0.0],
1356                end: [0.0, 200.0],
1357                stops: vec![
1358                    GradientStop {
1359                        offset: 0.0,
1360                        color: Color::new(0.0, 0.0, 0.0, 0.0),
1361                    },
1362                    GradientStop {
1363                        offset: 1.0,
1364                        color: Color::BLACK,
1365                    },
1366                ],
1367            },
1368        );
1369        let placement = rasterize_for_test(&entry, 512);
1370
1371        let verts = PathGradientVertex::from_path_entry(
1372            &entry,
1373            &placement,
1374            1.0,
1375            512,
1376            512,
1377            1.0,
1378            &Transform2D::IDENTITY,
1379        );
1380        assert!((verts[0].gradient_geo[0]).abs() < 1e-5, "start_uv.x");
1381        assert!((verts[0].gradient_geo[1]).abs() < 1e-5, "start_uv.y");
1382        assert!((verts[0].gradient_geo[2]).abs() < 1e-5, "end_uv.x");
1383        assert!((verts[0].gradient_geo[3] - 1.0).abs() < 1e-5, "end_uv.y");
1384    }
1385
1386    #[test]
1387    fn path_gradient_opacity_folds_into_every_stop_alpha() {
1388        // The fold-opacity-into-gradient-stops fix this pipeline adds
1389        // (see `PathGradientVertex::from_path_entry` doc comment): unlike
1390        // the SDF pipeline's pre-existing gap, opacity must reach EVERY
1391        // gradient stop's alpha, since the fragment shader ignores any
1392        // flat vertex color for gradient paint types.
1393        let bounds_rect = teksilo_canvas::Rect::new(0.0, 0.0, 40.0, 20.0);
1394        let entry = gradient_path_entry(
1395            bounds_rect,
1396            PaintData::LinearGradient {
1397                start: [0.0, 0.0],
1398                end: [40.0, 0.0],
1399                stops: vec![
1400                    GradientStop {
1401                        offset: 0.0,
1402                        color: Color::RED,
1403                    },
1404                    GradientStop {
1405                        offset: 1.0,
1406                        color: Color::BLUE,
1407                    },
1408                ],
1409            },
1410        );
1411        let placement = rasterize_for_test(&entry, 128);
1412
1413        let full = PathGradientVertex::from_path_entry(
1414            &entry,
1415            &placement,
1416            1.0,
1417            128,
1418            128,
1419            1.0,
1420            &Transform2D::IDENTITY,
1421        );
1422        let half = PathGradientVertex::from_path_entry(
1423            &entry,
1424            &placement,
1425            1.0,
1426            128,
1427            128,
1428            0.5,
1429            &Transform2D::IDENTITY,
1430        );
1431
1432        assert!((full[0].gradient_color0[3] - 1.0).abs() < 1e-5);
1433        assert!((half[0].gradient_color0[3] - 0.5).abs() < 1e-5);
1434        assert!((half[0].gradient_color1[3] - 0.5).abs() < 1e-5);
1435    }
1436
1437    #[test]
1438    fn generate_indices_for_multiple_quads() {
1439        let indices = generate_quad_indices(2);
1440        assert_eq!(indices.len(), 12);
1441        assert_eq!(&indices[0..6], &[0, 1, 2, 0, 2, 3]);
1442        assert_eq!(&indices[6..12], &[4, 5, 6, 4, 6, 7]);
1443    }
1444
1445    #[test]
1446    fn shadow_quad_to_vertices() {
1447        let shadow = ShadowQuad {
1448            screen: [0.0, 0.0, 120.0, 60.0],
1449            color: [0.0, 0.0, 0.0, 0.3],
1450            corner_radii: [6.0; 4],
1451            shape_rect: [10.0, 8.0, 100.0, 40.0],
1452            blur_radius: 4.0,
1453            spread: 0.0,
1454        };
1455        let verts = ShadowVertex::from_shadow_quad(&shadow, 1.0);
1456        assert_eq!(verts.len(), 4);
1457        assert_eq!(verts[0].position, [0.0, 0.0]);
1458        assert_eq!(verts[2].position, [120.0, 60.0]);
1459        assert_eq!(verts[0].shadow_params[2], 4.0); // blur_radius
1460        assert_eq!(verts[0].corner_radii, [6.0; 4]);
1461    }
1462
1463    #[test]
1464    fn shadow_scale_factor() {
1465        let shadow = ShadowQuad {
1466            screen: [10.0, 10.0, 120.0, 60.0],
1467            color: [0.0, 0.0, 0.0, 0.3],
1468            corner_radii: [6.0; 4],
1469            shape_rect: [20.0, 18.0, 100.0, 40.0],
1470            blur_radius: 4.0,
1471            spread: 2.0,
1472        };
1473        let verts = ShadowVertex::from_shadow_quad(&shadow, 2.0);
1474        assert_eq!(verts[0].position, [20.0, 20.0]);
1475        assert_eq!(verts[0].shadow_params[0], 200.0); // shape_w * 2
1476        assert_eq!(verts[0].shadow_params[2], 8.0); // blur * 2
1477        assert_eq!(verts[0].shadow_params[3], 4.0); // spread * 2
1478        // Corner radii are compared against shadow_params.xy in the
1479        // shadow shader's SDF; both have to live in the same px space.
1480        assert_eq!(verts[0].corner_radii, [12.0; 4]);
1481    }
1482}