ferravex_render/
shapes.rs

1//! Anti-aliased immediate 2D shapes: rounded rectangles, circles, rings, arcs,
2//! capsules, polylines, gradients, soft shadows and additive glows.
3//!
4//! Smooth edges come from geometry alone: each edge gets a thin fringe strip
5//! whose outer vertices are transparent, about one device pixel wide. No texture,
6//! shader or render-state change is needed, so these draws batch with ordinary
7//! [`crate::draw_rectangle`] geometry and respect the current 2D camera. Every
8//! call writes straight into the frame's existing vertex stream and performs no
9//! heap allocation of its own.
10//!
11//! Vertex counts are bounded per call (see each function). Curves use 2–16
12//! segments per quarter turn, chosen from the on-screen radius. Their unit
13//! directions come from tables built once per process, so the hot path runs no
14//! per-point trigonometry (arcs and round joins rotate incrementally and
15//! re-anchor every 16 steps). Coordinates are
16//! the current camera's logical units (pixels with the default camera).
17//! Non-finite or degenerate input draws nothing.
18//!
19//! ```
20//! use ferravex_render::{Color, Rect, vec2, shapes::{self, Fill, Shadow}};
21//! let card = Rect::new(40., 40., 240., 120.);
22//! shapes::drop_shadow(card, 12., Shadow::soft(Color::new(0., 0., 0., 0.45)));
23//! shapes::fill_rounded_rect(card, 12., Fill::vertical(card,
24//!     Color::from_hex(0x2b3550), Color::from_hex(0x1b2133)));
25//! shapes::stroke_rounded_rect(card, 12., 1., Color::new(1., 1., 1., 0.12));
26//! shapes::fill_circle(vec2(80., 100.), 16., Color::from_hex(0xf7b553));
27//! shapes::glow_disc(vec2(80., 100.), 48., Color::new(1., 0.7, 0.3, 0.6));
28//! ```
29use crate::{Color, Rect, State, Vec2, Vec3, Vec4, effects, vec2};
30use std::f32::consts::{FRAC_PI_2, PI, TAU};
31
32/// Paint for filled shapes. Gradients are evaluated per vertex and interpolated
33/// by the GPU; linear gradients are exact on these convex fans. A radial
34/// gradient on a circle it is centered on (reaching at least its edge) is
35/// exact along every spoke; on any other shape the fill is drawn on a
36/// subdivided mesh (four bands, long edges split) so the gradient follows its
37/// own circles instead of stretching to the outline.
38///
39/// ```
40/// use ferravex_render::{Color, Rect, vec2, shapes::Fill};
41/// let fill = Fill::linear(vec2(0., 0.), vec2(10., 0.), Color::new(0., 0., 0., 1.),
42///     Color::new(1., 1., 1., 1.));
43/// assert_eq!(fill.at(vec2(5., 3.)).r, 0.5);
44/// let solid: Fill = Color::new(1., 0., 0., 1.).into();
45/// assert_eq!(solid.at(vec2(99., 99.)).r, 1.);
46/// let bar = Fill::vertical(Rect::new(0., 10., 4., 20.), Color::new(0., 0., 0., 1.),
47///     Color::new(1., 1., 1., 1.));
48/// assert_eq!(bar.at(vec2(2., 30.)).g, 1.);
49/// ```
50#[derive(Clone, Copy, Debug, PartialEq)]
51pub enum Fill {
52    /// One color everywhere.
53    Solid(Color),
54    /// Interpolates `start` at `from` to `end` at `to`, clamped beyond them.
55    Linear {
56        from: Vec2,
57        to: Vec2,
58        start: Color,
59        end: Color,
60    },
61    /// Interpolates `inner` at `center` to `outer` at `radius`, clamped beyond.
62    Radial {
63        center: Vec2,
64        radius: f32,
65        inner: Color,
66        outer: Color,
67    },
68}
69
70impl From<Color> for Fill {
71    fn from(color: Color) -> Self {
72        Self::Solid(color)
73    }
74}
75
76impl Fill {
77    /// Linear gradient between two points.
78    pub fn linear(from: Vec2, to: Vec2, start: Color, end: Color) -> Self {
79        Self::Linear {
80            from,
81            to,
82            start,
83            end,
84        }
85    }
86    /// Top-to-bottom gradient across `rect`.
87    pub fn vertical(rect: Rect, top: Color, bottom: Color) -> Self {
88        Self::linear(
89            vec2(rect.x, rect.y),
90            vec2(rect.x, rect.y + rect.h),
91            top,
92            bottom,
93        )
94    }
95    /// Left-to-right gradient across `rect`.
96    pub fn horizontal(rect: Rect, left: Color, right: Color) -> Self {
97        Self::linear(
98            vec2(rect.x, rect.y),
99            vec2(rect.x + rect.w, rect.y),
100            left,
101            right,
102        )
103    }
104    /// Radial gradient from `center` outward to `radius`.
105    pub fn radial(center: Vec2, radius: f32, inner: Color, outer: Color) -> Self {
106        Self::Radial {
107            center,
108            radius,
109            inner,
110            outer,
111        }
112    }
113    /// Color at a point.
114    pub fn at(&self, p: Vec2) -> Color {
115        match *self {
116            Self::Solid(c) => c,
117            Self::Linear {
118                from,
119                to,
120                start,
121                end,
122            } => {
123                let axis = to - from;
124                let len2 = axis.length_squared();
125                let t = if len2 > 0. {
126                    ((p - from).dot(axis) / len2).clamp(0., 1.)
127                } else {
128                    0.
129                };
130                mix(start, end, t)
131            }
132            Self::Radial {
133                center,
134                radius,
135                inner,
136                outer,
137            } => {
138                let t = if radius > 0. {
139                    ((p - center).length() / radius).clamp(0., 1.)
140                } else {
141                    1.
142                };
143                mix(inner, outer, t)
144            }
145        }
146    }
147    fn is_finite(&self) -> bool {
148        let c = |c: Color| c.r.is_finite() && c.g.is_finite() && c.b.is_finite() && c.a.is_finite();
149        match *self {
150            Self::Solid(a) => c(a),
151            Self::Linear {
152                from,
153                to,
154                start,
155                end,
156            } => from.is_finite() && to.is_finite() && c(start) && c(end),
157            Self::Radial {
158                center,
159                radius,
160                inner,
161                outer,
162            } => center.is_finite() && radius.is_finite() && c(inner) && c(outer),
163        }
164    }
165}
166
167/// Linear color interpolation (`t` is not clamped).
168pub fn mix(a: Color, b: Color, t: f32) -> Color {
169    Color::new(
170        a.r + (b.r - a.r) * t,
171        a.g + (b.g - a.g) * t,
172        a.b + (b.b - a.b) * t,
173        a.a + (b.a - a.a) * t,
174    )
175}
176
177fn fade(c: Color, alpha: f32) -> Color {
178    Color::new(c.r, c.g, c.b, c.a * alpha)
179}
180
181/// Soft drop shadow parameters for [`drop_shadow`].
182///
183/// ```
184/// use ferravex_render::{Color, vec2, shapes::Shadow};
185/// let s = Shadow::soft(Color::new(0., 0., 0., 0.5)).offset(vec2(0., 6.)).blur(18.);
186/// assert_eq!((s.blur, s.offset.y), (18., 6.));
187/// ```
188#[derive(Clone, Copy, Debug, PartialEq)]
189pub struct Shadow {
190    /// Shadow color at full coverage.
191    pub color: Color,
192    /// Displacement of the shadow from the caster.
193    pub offset: Vec2,
194    /// Width of the soft falloff, centered on the (spread) edge.
195    pub blur: f32,
196    /// Grows (or with negative values shrinks) the shadow before blurring.
197    pub spread: f32,
198}
199
200impl Shadow {
201    /// A gentle card shadow: 4 units down, 16 units of blur.
202    pub fn soft(color: Color) -> Self {
203        Self {
204            color,
205            offset: vec2(0., 4.),
206            blur: 16.,
207            spread: 0.,
208        }
209    }
210    pub fn offset(mut self, offset: Vec2) -> Self {
211        self.offset = offset;
212        self
213    }
214    pub fn blur(mut self, blur: f32) -> Self {
215        self.blur = blur;
216        self
217    }
218    pub fn spread(mut self, spread: f32) -> Self {
219        self.spread = spread;
220        self
221    }
222}
223
224/// How a [`polyline`] turns a corner.
225#[derive(Clone, Copy, Debug, Default, PartialEq)]
226pub enum Join {
227    /// Sharp corners, falling back to [`Join::Bevel`] beyond 4× the half width.
228    #[default]
229    Miter,
230    /// Corners are cut flat.
231    Bevel,
232    /// Corners are rounded.
233    Round,
234}
235
236/// How a [`polyline`] or [`stroke_arc`] ends.
237#[derive(Clone, Copy, Debug, Default, PartialEq)]
238pub enum Cap {
239    /// Ends exactly at the end point.
240    #[default]
241    Butt,
242    /// Extends half the width past the end point.
243    Square,
244    /// Semicircular end.
245    Round,
246}
247
248/// Line style for [`polyline`] and [`stroke_arc`].
249///
250/// ```
251/// use ferravex_render::{Color, shapes::{Cap, Join, Stroke}};
252/// let s = Stroke::new(3., Color::new(1., 1., 1., 1.)).join(Join::Round).cap(Cap::Round);
253/// assert!(!s.closed);
254/// ```
255#[derive(Clone, Copy, Debug, PartialEq)]
256pub struct Stroke {
257    pub width: f32,
258    pub color: Color,
259    pub join: Join,
260    pub cap: Cap,
261    /// Connect the last point back to the first.
262    pub closed: bool,
263}
264
265impl Stroke {
266    pub fn new(width: f32, color: Color) -> Self {
267        Self {
268            width,
269            color,
270            join: Join::Miter,
271            cap: Cap::Butt,
272            closed: false,
273        }
274    }
275    pub fn join(mut self, join: Join) -> Self {
276        self.join = join;
277        self
278    }
279    pub fn cap(mut self, cap: Cap) -> Self {
280        self.cap = cap;
281        self
282    }
283    pub fn closed(mut self, closed: bool) -> Self {
284        self.closed = closed;
285        self
286    }
287}
288
289// ---------------------------------------------------------------------------
290// Vertex sink shared by shapes, styled text and the UI kit.
291
292/// Appends immediate triangles to the frame stream with the same transform,
293/// lighting and look rules as [`crate::draw_triangle`], recording one batch.
294pub(crate) struct Sink<'a> {
295    pub(crate) s: &'a mut State,
296    start: u32,
297    /// Camera columns for `matrix * (x, y, 0, 1)`, read once per sink.
298    x: Vec4,
299    y: Vec4,
300    w: Vec4,
301    /// No lighting and no world palette: colors pass through unchanged.
302    plain: bool,
303}
304
305impl<'a> Sink<'a> {
306    pub(crate) fn new(s: &'a mut State) -> Self {
307        let start = s.vertices.len() as u32;
308        let m = s.matrix;
309        let plain = s.lighting.is_none() && !s.world_colors;
310        Self {
311            s,
312            start,
313            x: m.x_axis,
314            y: m.y_axis,
315            w: m.w_axis,
316            plain,
317        }
318    }
319    /// Logical units covered by one device pixel under the current camera.
320    pub(crate) fn device_pixel(&self) -> f32 {
321        Self::device_pixel_of(self.s)
322    }
323    /// Reserves room for `count` more vertices with the stream's power-of-two
324    /// growth policy, so a bounded shape does not grow storage mid-call.
325    #[inline]
326    pub(crate) fn reserve(&mut self, count: usize) {
327        self.s.reserve_vertices(count);
328    }
329    /// One stream vertex: shaded color and `matrix * (x, y, 0, 1)` without the
330    /// zero z column, as in `State::push_flat_2d` (only the sign of an exact
331    /// zero can differ from the general product).
332    #[inline]
333    fn project(&self, p: Vec2, mut c: Color) -> [f32; 8] {
334        if !self.plain {
335            c = self.shade(p, c);
336        }
337        let v = self.x * p.x + self.y * p.y + self.w;
338        [v.x, v.y, v.z, v.w, c.r, c.g, c.b, c.a]
339    }
340    /// Lighting and world palette for one vertex, as `crate::draw_triangle`.
341    #[inline(never)]
342    fn shade(&self, p: Vec2, mut c: Color) -> Color {
343        if let Some(l) = self.s.lighting {
344            c = l.shade_vertex(p.extend(0.), Vec3::Z, c);
345        }
346        if let Some(look) = self.s.world_look() {
347            c = look.shade(c);
348        }
349        c
350    }
351    #[inline]
352    pub(crate) fn tri(&mut self, a: Vec2, ca: Color, b: Vec2, cb: Color, c: Vec2, cc: Color) {
353        let v = [
354            self.project(a, ca),
355            self.project(b, cb),
356            self.project(c, cc),
357        ];
358        self.s.vertices.extend_from_slice(&v);
359    }
360    /// Axis-aligned rectangle with the triangle order of `draw_rectangle`.
361    #[inline]
362    pub(crate) fn rect(&mut self, x: f32, y: f32, w: f32, h: f32, c: Color) {
363        self.rect_edges(x, y, x + w, y + h, c)
364    }
365    /// [`Self::rect`] from its edges, for callers that must reproduce exact
366    /// edge arithmetic (such as merged runs of per-pixel text quads).
367    #[inline]
368    pub(crate) fn rect_edges(&mut self, left: f32, top: f32, right: f32, bottom: f32, c: Color) {
369        self.quad(
370            [
371                vec2(left, top),
372                vec2(right, top),
373                vec2(right, bottom),
374                vec2(left, bottom),
375            ],
376            [c; 4],
377        )
378    }
379    /// Quad `p0 p1 p2 p3` in winding order, as triangles `p0 p1 p3` and
380    /// `p3 p1 p2`. Each corner is projected once.
381    #[inline]
382    fn quad(&mut self, p: [Vec2; 4], c: [Color; 4]) {
383        let [a, b, e, d] = [0, 1, 2, 3].map(|i| self.project(p[i], c[i]));
384        self.s.vertices.extend_from_slice(&[a, b, d, d, b, e]);
385    }
386}
387
388impl Drop for Sink<'_> {
389    fn drop(&mut self) {
390        let count = self.s.vertices.len() as u32 - self.start;
391        if count > 0 {
392            let depth = self.s.depth;
393            self.s.record_immediate(self.start, count, depth);
394        }
395    }
396}
397
398// ---------------------------------------------------------------------------
399// Rounded-rectangle outlines: the shared core for rects, circles and capsules.
400
401/// Most segments per quarter turn chosen by [`quarter_segments`].
402const MAX_QUARTER: usize = 16;
403/// Most outline points: four quarters of `MAX_QUARTER + 1` points.
404const MAX_POINTS: usize = 4 * (MAX_QUARTER + 1);
405/// Corner directions of the four quarters, in outline order.
406const SIGNS: [Vec2; 4] = [vec2(1., 1.), vec2(-1., 1.), vec2(-1., -1.), vec2(1., -1.)];
407
408/// Unit vectors shared by every curved shape, built once per process with the
409/// exact angle expressions the shapes previously evaluated per point, so the
410/// geometry is bit-for-bit unchanged and no trigonometry runs per call.
411struct UnitTables {
412    /// `quarter[s][q * (s + 1) + step]` is the unit vector at
413    /// `(q + step / s) * π/2` for `s` in `1..=16` and quarter `q` in `0..4`.
414    quarter: [[Vec2; MAX_POINTS]; MAX_QUARTER + 1],
415    /// `circle[k][i]` is the unit vector at `i * τ / n` for `n = 4k`, `k` in
416    /// `1..=16`, and `circle[k][n]` repeats `circle[k][0]` to close the ring.
417    circle: [[Vec2; 4 * MAX_QUARTER + 1]; MAX_QUARTER + 1],
418}
419
420fn unit_tables() -> &'static UnitTables {
421    static TABLES: std::sync::OnceLock<UnitTables> = std::sync::OnceLock::new();
422    TABLES.get_or_init(|| {
423        let unit = |a: f32| vec2(a.cos(), a.sin());
424        let mut t = UnitTables {
425            quarter: [[Vec2::ZERO; MAX_POINTS]; MAX_QUARTER + 1],
426            circle: [[Vec2::ZERO; 4 * MAX_QUARTER + 1]; MAX_QUARTER + 1],
427        };
428        for s in 1..=MAX_QUARTER {
429            for i in 0..4 * (s + 1) {
430                let (quarter, step) = (i / (s + 1), i % (s + 1));
431                t.quarter[s][i] = unit((quarter as f32 + step as f32 / s as f32) * FRAC_PI_2);
432            }
433            let n = 4 * s;
434            for i in 0..n {
435                t.circle[s][i] = unit(i as f32 * TAU / n as f32);
436            }
437            t.circle[s][n] = t.circle[s][0];
438        }
439        t
440    })
441}
442
443/// `n + 1` unit vectors at `i * τ / n` for `i` in `0..n`, followed by the
444/// first again so consecutive pairs close the ring. `n` must be a multiple of
445/// four from 4 to 64 (other counts return `None`). Built once; no per-call trig.
446pub(crate) fn unit_circle(n: usize) -> Option<&'static [Vec2]> {
447    (n.is_multiple_of(4) && (4..=4 * MAX_QUARTER).contains(&n))
448        .then(|| &unit_tables().circle[n / 4][..=n])
449}
450
451/// Segments per quarter turn for a radius in device pixels.
452fn quarter_segments(radius_px: f32) -> usize {
453    if radius_px.is_nan() || radius_px <= 0.5 {
454        return 1;
455    }
456    ((radius_px.sqrt() * 1.5).ceil() as usize).clamp(2, MAX_QUARTER)
457}
458
459/// Segments for a full turn of a curve with `radius_px` device pixels: four
460/// times [`quarter_segments`], so always a multiple of four from 4 to 64.
461pub(crate) fn curve_segments(radius_px: f32) -> usize {
462    quarter_segments(radius_px) * 4
463}
464
465/// A rounded rectangle centered at `center` with unit axis `ax` (its local +X).
466#[derive(Clone, Copy)]
467struct Outline {
468    center: Vec2,
469    ax: Vec2,
470    half: Vec2,
471    radius: f32,
472    segments: usize,
473}
474
475/// One offset copy of an outline: its points and their (faded) colors.
476struct Ring {
477    points: [Vec2; MAX_POINTS],
478    colors: [Color; MAX_POINTS],
479}
480
481impl Outline {
482    fn new(rect: Rect, radius: f32, px: f32) -> Option<Self> {
483        if !(rect.is_finite() && radius.is_finite() && rect.w > 0. && rect.h > 0.) {
484            return None;
485        }
486        let half = vec2(rect.w, rect.h) * 0.5;
487        let radius = radius.clamp(0., half.x.min(half.y));
488        Some(Self {
489            center: vec2(rect.x, rect.y) + half,
490            ax: Vec2::X,
491            half,
492            radius,
493            segments: quarter_segments(radius / px),
494        })
495    }
496    fn points(&self) -> usize {
497        4 * (self.segments + 1)
498    }
499    /// The outline grown by `offset` (negative shrinks), with `fill` faded by
500    /// `alpha` at each point. Uses the shared quarter-arc table.
501    fn ring(&self, offset: f32, fill: &Fill, alpha: f32) -> Ring {
502        let half = (self.half + Vec2::splat(offset)).max(Vec2::ZERO);
503        let radius = (self.radius + offset).clamp(0., half.x.min(half.y));
504        let corner = half - Vec2::splat(radius);
505        let ay = self.ax.perp();
506        let per = self.segments + 1;
507        let units = &unit_tables().quarter[self.segments.clamp(1, MAX_QUARTER)];
508        let mut ring = Ring {
509            points: [Vec2::ZERO; MAX_POINTS],
510            colors: [Color::new(0., 0., 0., 0.); MAX_POINTS],
511        };
512        for (q, sign) in SIGNS.into_iter().enumerate() {
513            let base = corner * sign;
514            let span = q * per..(q + 1) * per;
515            for (point, unit) in ring.points[span.clone()].iter_mut().zip(&units[span]) {
516                let local = base + *unit * radius;
517                *point = self.center + self.ax * local.x + ay * local.y;
518            }
519        }
520        let n = self.points();
521        match *fill {
522            Fill::Solid(c) => ring.colors[..n].fill(fade(c, alpha)),
523            _ => {
524                for (c, p) in ring.colors[..n].iter_mut().zip(&ring.points[..n]) {
525                    *c = fade(fill.at(*p), alpha);
526                }
527            }
528        }
529        ring
530    }
531    /// Filled interior of `ring`, as a fan from the center.
532    fn fan(&self, sink: &mut Sink, ring: &Ring, fill: &Fill, alpha: f32) {
533        let n = self.points();
534        let center = fade(fill.at(self.center), alpha);
535        sink.reserve(n * 3);
536        let mut prev = n - 1;
537        for i in 0..n {
538            sink.tri(
539                self.center,
540                center,
541                ring.points[prev],
542                ring.colors[prev],
543                ring.points[i],
544                ring.colors[i],
545            );
546            prev = i;
547        }
548    }
549    /// Strip between two offset rings.
550    fn strip(&self, sink: &mut Sink, inner: &Ring, outer: &Ring) {
551        let n = self.points();
552        sink.reserve(n * 6);
553        let mut prev = n - 1;
554        for i in 0..n {
555            sink.quad(
556                [
557                    inner.points[prev],
558                    inner.points[i],
559                    outer.points[i],
560                    outer.points[prev],
561                ],
562                [
563                    inner.colors[prev],
564                    inner.colors[i],
565                    outer.colors[i],
566                    outer.colors[prev],
567                ],
568            );
569            prev = i;
570        }
571    }
572}
573
574/// Most subdivisions of one straight edge for a radial fill.
575const MAX_EDGE: usize = 8;
576/// Most points of a subdivided radial-fill ring.
577const MAX_DENSE: usize = MAX_POINTS + 4 * (MAX_EDGE - 1);
578/// Most interior rings of a subdivided radial fill (the outline is the last).
579const RADIAL_RINGS: usize = 4;
580
581/// A center fan only reproduces a radial gradient on a circle centered on the
582/// gradient whose radius reaches the circle's edge: then every spoke is the
583/// gradient's own linear ramp. Every other shape needs subdivision.
584fn radial_is_exact(outline: &Outline, center: Vec2, radius: f32, px: f32) -> bool {
585    let eps = px * 1e-3;
586    (outline.half.x - outline.half.y).abs() <= eps
587        && outline.radius >= outline.half.x - eps
588        && (center - outline.center).length() <= eps
589        && radius >= outline.radius - eps
590}
591
592/// A radial fill on a polar mesh: straight edges are subdivided and the
593/// interior is split into two to [`RADIAL_RINGS`] concentric bands (one per
594/// 16 device pixels of half extent), each vertex sampling the gradient.
595/// Without it a long edge spans one fan triangle and the gradient stretches
596/// into a rectangular patch.
597fn filled_radial(outline: Outline, fill: Fill, radius: f32, sink: &mut Sink, px: f32) {
598    let f = px * 0.5;
599    let n = outline.points();
600    let per = outline.segments + 1;
601    let corner = outline.half - Vec2::splat(outline.radius);
602    // About two subdivisions per gradient radius, at least 8 device pixels.
603    let step = (radius * 0.5).max(px * 8.);
604    let pieces = |length: f32| ((length / step).ceil() as usize).clamp(1, MAX_EDGE);
605    let edges = [pieces(2. * corner.x), pieces(2. * corner.y)];
606    let dense = |offset: f32| {
607        let base = outline.ring(offset, &Fill::Solid(Color::new(0., 0., 0., 0.)), 0.);
608        let mut out = [Vec2::ZERO; MAX_DENSE];
609        let mut len = 0;
610        for q in 0..4 {
611            for &p in &base.points[q * per..(q + 1) * per] {
612                out[len] = p;
613                len += 1;
614            }
615            // Quarters 0 and 2 end on horizontal edges, 1 and 3 on vertical.
616            let pieces = edges[q % 2];
617            let (a, b) = (
618                base.points[(q + 1) * per - 1],
619                base.points[(q + 1) * per % n],
620            );
621            for j in 1..pieces {
622                out[len] = a + (b - a) * (j as f32 / pieces as f32);
623                len += 1;
624            }
625        }
626        (out, len)
627    };
628    let colors = |points: &[Vec2], alpha: f32| {
629        let mut out = [Color::new(0., 0., 0., 0.); MAX_DENSE];
630        for (c, p) in out.iter_mut().zip(points) {
631            *c = fade(fill.at(*p), alpha);
632        }
633        out
634    };
635    let (edge, len) = dense(-f);
636    let (outer, _) = dense(f);
637    let center = outline.center;
638    let rings =
639        ((outline.half.x.max(outline.half.y) / px / 16.).ceil() as usize).clamp(2, RADIAL_RINGS);
640    let scaled = |k: usize| {
641        let mut out = [Vec2::ZERO; MAX_DENSE];
642        let t = k as f32 / rings as f32;
643        for (o, p) in out.iter_mut().zip(&edge[..len]) {
644            *o = if k == rings {
645                *p
646            } else {
647                center + (*p - center) * t
648            };
649        }
650        out
651    };
652    sink.reserve(len * (3 + 6 * rings));
653    let hub = fill.at(center);
654    let mut ring = scaled(1);
655    let mut ring_colors = colors(&ring[..len], 1.);
656    let mut prev = len - 1;
657    for i in 0..len {
658        sink.tri(
659            center,
660            hub,
661            ring[prev],
662            ring_colors[prev],
663            ring[i],
664            ring_colors[i],
665        );
666        prev = i;
667    }
668    let band = |sink: &mut Sink, a: &[Vec2], ca: &[Color], b: &[Vec2], cb: &[Color]| {
669        let mut prev = len - 1;
670        for i in 0..len {
671            sink.quad(
672                [a[prev], a[i], b[i], b[prev]],
673                [ca[prev], ca[i], cb[i], cb[prev]],
674            );
675            prev = i;
676        }
677    };
678    for k in 2..=rings {
679        let next = scaled(k);
680        let next_colors = colors(&next[..len], 1.);
681        band(sink, &ring, &ring_colors, &next, &next_colors);
682        (ring, ring_colors) = (next, next_colors);
683    }
684    band(
685        sink,
686        &ring,
687        &ring_colors,
688        &outer,
689        &colors(&outer[..len], 0.),
690    );
691}
692
693fn filled(outline: Outline, fill: Fill, sink: &mut Sink, px: f32) {
694    if let Fill::Radial { center, radius, .. } = fill
695        && !radial_is_exact(&outline, center, radius, px)
696    {
697        return filled_radial(outline, fill, radius, sink, px);
698    }
699    let f = px * 0.5;
700    let inner = outline.ring(-f, &fill, 1.);
701    outline.fan(sink, &inner, &fill, 1.);
702    outline.strip(sink, &inner, &outline.ring(f, &fill, 0.));
703}
704
705fn stroked(outline: Outline, width: f32, color: Color, sink: &mut Sink, px: f32) {
706    let f = px * 0.5;
707    let half = (width * 0.5).max(f);
708    let alpha = (width / px).min(1.);
709    let fill = Fill::Solid(color);
710    let rings = [
711        outline.ring(-half - f, &fill, 0.),
712        outline.ring(-half + f, &fill, alpha),
713        outline.ring(half - f, &fill, alpha),
714        outline.ring(half + f, &fill, 0.),
715    ];
716    for pair in rings.windows(2) {
717        outline.strip(sink, &pair[0], &pair[1]);
718    }
719}
720
721fn with_sink<R>(draw: impl FnOnce(&mut Sink, f32) -> R) -> R {
722    crate::edit(|s| {
723        let mut sink = Sink::new(s);
724        let px = sink.device_pixel();
725        draw(&mut sink, px)
726    })
727}
728
729/// Filled, anti-aliased rounded rectangle. `radius` is clamped to half the
730/// shorter side; zero gives crisp-but-smooth square corners.
731/// Emits at most 612 vertices, or 2,592 for a subdivided [`Fill::Radial`].
732///
733/// ```
734/// use ferravex_render::{Color, Rect, shapes};
735/// shapes::fill_rounded_rect(Rect::new(10., 10., 120., 40.), 8., Color::from_hex(0x1f2a3d));
736/// ```
737pub fn fill_rounded_rect(rect: Rect, radius: f32, fill: impl Into<Fill>) {
738    let fill = fill.into();
739    if !fill.is_finite() {
740        return;
741    }
742    with_sink(|sink, px| {
743        if let Some(outline) = Outline::new(rect, radius, px) {
744            filled(outline, fill, sink, px);
745        }
746    })
747}
748
749/// Anti-aliased rounded-rectangle border of `width`, centered on the edge of
750/// `rect`. Strokes thinner than a device pixel fade instead of vanishing.
751/// Emits at most 1,224 vertices.
752///
753/// ```
754/// use ferravex_render::{Color, Rect, shapes};
755/// shapes::stroke_rounded_rect(Rect::new(10., 10., 120., 40.), 8., 2., Color::from_hex(0xf7b553));
756/// ```
757pub fn stroke_rounded_rect(rect: Rect, radius: f32, width: f32, color: Color) {
758    if !(width.is_finite() && width > 0. && Fill::Solid(color).is_finite()) {
759        return;
760    }
761    with_sink(|sink, px| {
762        if let Some(outline) = Outline::new(rect, radius, px) {
763            stroked(outline, width, color, sink, px);
764        }
765    })
766}
767
768fn circle_rect(center: Vec2, radius: f32) -> Rect {
769    Rect::new(
770        center.x - radius,
771        center.y - radius,
772        radius * 2.,
773        radius * 2.,
774    )
775}
776
777/// Filled, anti-aliased circle (up to 64 segments). Emits at most 612 vertices,
778/// or 2,592 for a radial fill that is not centered on the circle.
779///
780/// ```
781/// use ferravex_render::{Color, vec2, shapes::{self, Fill}};
782/// let c = vec2(50., 50.);
783/// shapes::fill_circle(c, 20., Fill::radial(c, 20., Color::new(1., 1., 1., 1.),
784///     Color::new(0.2, 0.4, 1., 1.)));
785/// ```
786pub fn fill_circle(center: Vec2, radius: f32, fill: impl Into<Fill>) {
787    fill_rounded_rect(circle_rect(center, radius), radius, fill)
788}
789
790/// Anti-aliased ring of `width` centered on `radius`. Emits at most 1,224 vertices.
791///
792/// ```
793/// use ferravex_render::{Color, vec2, shapes};
794/// shapes::stroke_circle(vec2(50., 50.), 20., 3., Color::new(1., 1., 1., 0.8));
795/// ```
796pub fn stroke_circle(center: Vec2, radius: f32, width: f32, color: Color) {
797    stroke_rounded_rect(circle_rect(center, radius), radius, width, color)
798}
799
800/// Filled, anti-aliased capsule (a segment with round ends) of `radius`.
801/// Coincident end points draw a circle. Emits at most 612 vertices, or 2,592
802/// for a subdivided [`Fill::Radial`].
803///
804/// ```
805/// use ferravex_render::{Color, vec2, shapes};
806/// shapes::fill_capsule(vec2(20., 20.), vec2(120., 20.), 6., Color::from_hex(0x5bd5d8));
807/// ```
808pub fn fill_capsule(a: Vec2, b: Vec2, radius: f32, fill: impl Into<Fill>) {
809    let fill = fill.into();
810    if !(a.is_finite() && b.is_finite() && radius.is_finite() && radius > 0. && fill.is_finite()) {
811        return;
812    }
813    let axis = (b - a).normalize_or(Vec2::X);
814    let length = (b - a).length();
815    with_sink(|sink, px| {
816        let outline = Outline {
817            center: (a + b) * 0.5,
818            ax: axis,
819            half: vec2(length * 0.5 + radius, radius),
820            radius,
821            segments: quarter_segments(radius / px),
822        };
823        filled(outline, fill, sink, px);
824    })
825}
826
827/// Most corners [`fill_polygon`] accepts; longer input draws nothing.
828pub const MAX_POLYGON_POINTS: usize = 64;
829
830/// Filled, anti-aliased convex polygon through `points` in either winding.
831///
832/// Every edge gets the same half-pixel fringe as the rounded shapes, so icons,
833/// arrows, stars (as triangles) and badges built from polygons sit smoothly
834/// beside circles and rounded rectangles. Very sharp corners are mitred to at
835/// most four times the fringe width. Concave or self-intersecting input is not
836/// rejected but fills as the fan from its centroid; split such outlines into
837/// convex pieces. Fewer than three distinct corners, more than
838/// [`MAX_POLYGON_POINTS`], zero area or non-finite input draw nothing.
839/// Emits at most 576 vertices.
840///
841/// ```
842/// use ferravex_render::{Color, vec2, shapes};
843/// // A play triangle and a hexagon badge.
844/// shapes::fill_polygon(&[vec2(20., 10.), vec2(44., 24.), vec2(20., 38.)],
845///     Color::from_hex(0xf7b553));
846/// let hex: Vec<_> = (0..6).map(|i| {
847///     let a = i as f32 * std::f32::consts::TAU / 6.;
848///     vec2(100. + 20. * a.cos(), 24. + 20. * a.sin())
849/// }).collect();
850/// shapes::fill_polygon(&hex, Color::from_hex(0x5bd5d8));
851/// ```
852pub fn fill_polygon(points: &[Vec2], fill: impl Into<Fill>) {
853    let fill = fill.into();
854    let n = points.len();
855    if !(3..=MAX_POLYGON_POINTS).contains(&n)
856        || !fill.is_finite()
857        || !points.iter().all(|p| p.is_finite())
858    {
859        return;
860    }
861    // Shoelace area decides the winding; outward normals follow from it.
862    let mut twice_area = 0.;
863    let mut centroid = Vec2::ZERO;
864    for i in 0..n {
865        let (a, b) = (points[i], points[(i + 1) % n]);
866        twice_area += a.x * b.y - b.x * a.y;
867        centroid += a;
868    }
869    centroid /= n as f32;
870    if !twice_area.is_finite() || twice_area.abs() < 1e-6 {
871        return;
872    }
873    let outward = if twice_area > 0. { -1. } else { 1. };
874    with_sink(|sink, px| {
875        let f = px * 0.5;
876        let mut inner = [Vec2::ZERO; MAX_POLYGON_POINTS];
877        let mut outer = [Vec2::ZERO; MAX_POLYGON_POINTS];
878        let mut colors = [Color::new(0., 0., 0., 0.); MAX_POLYGON_POINTS];
879        let mut clear = [Color::new(0., 0., 0., 0.); MAX_POLYGON_POINTS];
880        for i in 0..n {
881            let p = points[i];
882            let prev = points[(i + n - 1) % n];
883            let next = points[(i + 1) % n];
884            let edge_in = (p - prev).normalize_or_zero();
885            let edge_out = (next - p).normalize_or_zero();
886            // Perpendiculars pointing away from the interior.
887            let n_in = edge_in.perp() * outward;
888            let n_out = edge_out.perp() * outward;
889            let miter = (n_in + n_out).normalize_or(n_out);
890            let cos = miter.dot(n_out).abs().max(0.25);
891            let reach = f / cos;
892            inner[i] = p - miter * reach;
893            outer[i] = p + miter * reach;
894            let c = fill.at(p);
895            colors[i] = c;
896            clear[i] = fade(c, 0.);
897        }
898        let hub = fill.at(centroid);
899        sink.reserve(n * 9);
900        let mut prev = n - 1;
901        for i in 0..n {
902            sink.tri(
903                centroid,
904                hub,
905                inner[prev],
906                colors[prev],
907                inner[i],
908                colors[i],
909            );
910            sink.quad(
911                [inner[prev], inner[i], outer[i], outer[prev]],
912                [colors[prev], colors[i], clear[i], clear[prev]],
913            );
914            prev = i;
915        }
916    })
917}
918
919/// Filled, anti-aliased triangle; a convenience for [`fill_polygon`].
920///
921/// ```
922/// use ferravex_render::{Color, vec2, shapes};
923/// shapes::fill_triangle(vec2(10., 40.), vec2(30., 6.), vec2(50., 40.), Color::from_hex(0xe5484d));
924/// ```
925pub fn fill_triangle(a: Vec2, b: Vec2, c: Vec2, fill: impl Into<Fill>) {
926    fill_polygon(&[a, b, c], fill)
927}
928
929/// Filled, anti-aliased pie slice of `radius` from `start` sweeping `sweep`
930/// radians (positive is clockwise on screen with Y down), for cooldown dials,
931/// timers and progress pies. A full turn or more fills the circle; a zero or
932/// non-finite sweep draws nothing. Emits at most 588 vertices.
933///
934/// ```
935/// use std::f32::consts::{FRAC_PI_2, TAU};
936/// use ferravex_render::{Color, vec2, shapes};
937/// // Two thirds of a timer, starting at 12 o'clock.
938/// shapes::fill_sector(vec2(40., 40.), 16., -FRAC_PI_2, TAU * 2. / 3., Color::from_hex(0xf7b553));
939/// ```
940pub fn fill_sector(center: Vec2, radius: f32, start: f32, sweep: f32, fill: impl Into<Fill>) {
941    let fill = fill.into();
942    if !(center.is_finite()
943        && radius.is_finite()
944        && radius > 0.
945        && start.is_finite()
946        && sweep.is_finite()
947        && fill.is_finite())
948        || sweep == 0.
949    {
950        return;
951    }
952    if sweep.abs() >= TAU {
953        return fill_circle(center, radius, fill);
954    }
955    with_sink(|sink, px| {
956        let f = px * 0.5;
957        let steps = ((quarter_segments(radius / px) * 4) as f32 * sweep.abs() / TAU)
958            .ceil()
959            .clamp(1., 64.) as usize;
960        let hub = fill.at(center);
961        let point = |i: usize, r: f32| {
962            let a = start + sweep * i as f32 / steps as f32;
963            center + vec2(a.cos(), a.sin()) * r
964        };
965        sink.reserve(steps * 9 + 12);
966        let inner_r = (radius - f).max(0.);
967        for i in 0..steps {
968            let (a0, a1) = (point(i, inner_r), point(i + 1, inner_r));
969            let (b0, b1) = (point(i, radius + f), point(i + 1, radius + f));
970            let (c0, c1) = (fill.at(a0), fill.at(a1));
971            sink.tri(center, hub, a0, c0, a1, c1);
972            sink.quad([a0, a1, b1, b0], [c0, c1, fade(c1, 0.), fade(c0, 0.)]);
973        }
974        // Soften both straight edges with a fringe on their outer side.
975        let sign = sweep.signum();
976        for (i, side) in [(0usize, -1.), (steps, 1.)] {
977            let tip = point(i, inner_r);
978            let dir = (tip - center).normalize_or_zero();
979            let out = dir.perp() * side * sign * f;
980            let (ch, ct) = (hub, fill.at(tip));
981            sink.quad(
982                [center, tip, tip + out, center + out],
983                [ch, ct, fade(ct, 0.), fade(ch, 0.)],
984            );
985        }
986    })
987}
988
989/// Soft shadow under a rounded rectangle. The falloff follows a smoothstep
990/// across `blur`, approximating a Gaussian with four feathered rings.
991/// Emits at most 1,836 vertices.
992///
993/// ```
994/// use ferravex_render::{Color, Rect, shapes::{self, Shadow}};
995/// shapes::drop_shadow(Rect::new(20., 20., 200., 90.), 10., Shadow::soft(Color::new(0., 0., 0., 0.5)));
996/// ```
997pub fn drop_shadow(rect: Rect, radius: f32, shadow: Shadow) {
998    let Shadow {
999        color,
1000        offset,
1001        blur,
1002        spread,
1003    } = shadow;
1004    if !(offset.is_finite() && blur.is_finite() && spread.is_finite()) {
1005        return;
1006    }
1007    let rect = Rect::new(
1008        rect.x + offset.x - spread,
1009        rect.y + offset.y - spread,
1010        rect.w + spread * 2.,
1011        rect.h + spread * 2.,
1012    );
1013    if !Fill::Solid(color).is_finite() {
1014        return;
1015    }
1016    with_sink(|sink, px| {
1017        let blur = blur.max(px);
1018        let Some(mut outline) = Outline::new(rect, radius + spread.max(0.), px) else {
1019            return;
1020        };
1021        outline.segments = quarter_segments((outline.radius + blur * 0.5) / px);
1022        let fill = Fill::Solid(color);
1023        let half = blur * 0.5;
1024        // Smoothstep alpha at five evenly spaced offsets.
1025        const T: [f32; 5] = [0., 0.25, 0.5, 0.75, 1.];
1026        let alpha = |t: f32| 1. - t * t * (3. - 2. * t);
1027        let rings = T.map(|t| outline.ring(-half + t * blur, &fill, alpha(t)));
1028        outline.fan(sink, &rings[0], &fill, 1.);
1029        for pair in rings.windows(2) {
1030            outline.strip(sink, &pair[0], &pair[1]);
1031        }
1032    })
1033}
1034
1035// ---------------------------------------------------------------------------
1036// Polylines and arcs.
1037
1038/// One cross-section of a stroke: its center and four points from the left
1039/// fringe to the right.
1040#[derive(Clone, Copy)]
1041struct Section(Vec2, [Vec2; 4]);
1042
1043struct Strokes<'s, 'a> {
1044    sink: &'s mut Sink<'a>,
1045    color: Color,
1046    alpha: f32,
1047    /// Half width of the opaque core and of the fringe.
1048    core: f32,
1049    fringe: f32,
1050    prev: Option<Section>,
1051}
1052
1053impl Strokes<'_, '_> {
1054    fn section(&mut self, p: Vec2, n: Vec2, scale: f32) {
1055        let outer = n * ((self.core + self.fringe) * scale);
1056        let inner = n * ((self.core - self.fringe).max(0.) * scale);
1057        let next = Section(p, [p + outer, p + inner, p - inner, p - outer]);
1058        if let Some(Section(center, prev)) = self.prev {
1059            let clear = fade(self.color, 0.);
1060            let solid = fade(self.color, self.alpha);
1061            let colors = [clear, solid, solid, clear];
1062            let q = next.1;
1063            for k in [0, 2] {
1064                self.sink.quad(
1065                    [prev[k], q[k], q[k + 1], prev[k + 1]],
1066                    [colors[k], colors[k], colors[k + 1], colors[k + 1]],
1067                );
1068            }
1069            if center == p {
1070                // A pivot (join or cap sweep): two wedges instead of a bowtie.
1071                self.sink.tri(p, solid, prev[1], solid, q[1], solid);
1072                self.sink.tri(p, solid, q[2], solid, prev[2], solid);
1073            } else {
1074                self.sink.quad([prev[1], q[1], q[2], prev[2]], [solid; 4]);
1075            }
1076        }
1077        self.prev = Some(next);
1078    }
1079    fn break_strip(&mut self) {
1080        self.prev = None;
1081    }
1082    /// Sections around `p` sweeping the normal from `from` by `angle` radians.
1083    fn sweep(&mut self, p: Vec2, from: Vec2, angle: f32, steps: usize) {
1084        turn(0., angle, steps, |_, u| {
1085            let n = vec2(from.x * u.x - from.y * u.y, from.x * u.y + from.y * u.x);
1086            self.section(p, n, 1.);
1087        });
1088    }
1089    /// A round cap: like [`Self::sweep`], but each section keeps only its
1090    /// `-normal` half, which faces away from the stroke body. The cap is then
1091    /// exactly a half disc beyond the end point, so translucent strokes do not
1092    /// double-cover the body under the cap. Degenerate halves keep the vertex
1093    /// count of a full sweep.
1094    fn sweep_cap(&mut self, p: Vec2, from: Vec2, angle: f32, steps: usize) {
1095        turn(0., angle, steps, |_, u| {
1096            let n = vec2(from.x * u.x - from.y * u.y, from.x * u.y + from.y * u.x);
1097            let outer = n * (self.core + self.fringe);
1098            let inner = n * (self.core - self.fringe).max(0.);
1099            let next = Section(p, [p, p, p - inner, p - outer]);
1100            if let Some(Section(_, prev)) = self.prev {
1101                let clear = fade(self.color, 0.);
1102                let solid = fade(self.color, self.alpha);
1103                let q = next.1;
1104                self.sink
1105                    .quad([prev[2], q[2], q[3], prev[3]], [solid, solid, clear, clear]);
1106                self.sink.tri(p, solid, q[2], solid, prev[2], solid);
1107            }
1108            self.prev = Some(next);
1109        });
1110    }
1111    fn cap(&mut self, p: Vec2, dir: Vec2, cap: Cap, start: bool, steps: usize) {
1112        let n = dir.perp();
1113        match cap {
1114            Cap::Butt => self.section(p, n, 1.),
1115            Cap::Square => {
1116                let shift = dir * self.core * if start { -1. } else { 1. };
1117                self.section(p + shift, n, 1.);
1118                if !start {
1119                    return;
1120                }
1121                self.section(p, n, 1.);
1122            }
1123            Cap::Round => {
1124                if start {
1125                    self.sweep_cap(p, -n, PI, steps * 2);
1126                    self.break_strip();
1127                    self.section(p, n, 1.);
1128                } else {
1129                    self.section(p, n, 1.);
1130                    self.break_strip();
1131                    self.sweep_cap(p, n, PI, steps * 2);
1132                }
1133            }
1134        }
1135    }
1136    fn join(&mut self, p: Vec2, d_in: Vec2, d_out: Vec2, join: Join, steps: usize) {
1137        let n_in = d_in.perp();
1138        let n_out = d_out.perp();
1139        let cross = d_in.x * d_out.y - d_in.y * d_out.x;
1140        if cross.abs() < 1e-4 && d_in.dot(d_out) > 0. {
1141            self.section(p, n_in, 1.);
1142            return;
1143        }
1144        let miter = (n_in + n_out).normalize_or_zero();
1145        let cos = miter.dot(n_in);
1146        if join == Join::Miter && cos > 0.25 {
1147            self.section(p, miter, 1. / cos);
1148            return;
1149        }
1150        let angle = cross.atan2(d_in.dot(d_out));
1151        let steps = if join == Join::Round {
1152            ((angle.abs() / FRAC_PI_2) * steps as f32).ceil().max(1.) as usize
1153        } else {
1154            1
1155        };
1156        self.sweep(p, n_in, angle, steps);
1157    }
1158}
1159
1160/// Calls `f(i, (cos a, sin a))` for `a = start + sweep * i / steps`, `i` in
1161/// `0..=steps` (`steps > 0`). Directions advance by one rotation per step and
1162/// are re-anchored with an exact `sin_cos` every 16 steps, so curves need
1163/// about one trigonometric evaluation per 16 points and stay within a few
1164/// ulps of the directly evaluated angles.
1165fn turn(start: f32, sweep: f32, steps: usize, mut f: impl FnMut(usize, Vec2)) {
1166    const ANCHOR: usize = 16;
1167    let (ds, dc) = (sweep / steps as f32).sin_cos();
1168    let mut u = Vec2::ZERO;
1169    for i in 0..=steps {
1170        u = if i % ANCHOR == 0 || i == steps {
1171            let (s, c) = (start + sweep * i as f32 / steps as f32).sin_cos();
1172            vec2(c, s)
1173        } else {
1174            vec2(u.x * dc - u.y * ds, u.x * ds + u.y * dc)
1175        };
1176        f(i, u);
1177    }
1178}
1179
1180fn stroke_setup(px: f32, stroke: &Stroke) -> Option<(f32, f32, f32)> {
1181    if !(stroke.width.is_finite() && stroke.width > 0. && Fill::Solid(stroke.color).is_finite()) {
1182        return None;
1183    }
1184    let fringe = px * 0.5;
1185    let core = (stroke.width * 0.5).max(fringe);
1186    let alpha = (stroke.width / px).min(1.);
1187    Some((core, fringe, alpha))
1188}
1189
1190/// Anti-aliased polyline through caller-owned `points` with joins and caps.
1191///
1192/// Consecutive duplicate points are skipped. Bevel and round joins overlap the
1193/// body on the inside of a turn, so translucent strokes may darken there.
1194/// Emits at most `18 × (sections)` vertices, where each point contributes one
1195/// section for miters, two for bevels and up to 17 for round joins/caps.
1196///
1197/// ```
1198/// use ferravex_render::{Color, vec2, shapes::{self, Cap, Join, Stroke}};
1199/// let path = [vec2(10., 80.), vec2(60., 20.), vec2(110., 70.), vec2(160., 30.)];
1200/// shapes::polyline(&path, Stroke::new(4., Color::from_hex(0x5bd5d8))
1201///     .join(Join::Round).cap(Cap::Round));
1202/// ```
1203pub fn polyline(points: &[Vec2], stroke: Stroke) {
1204    if points.len() < 2 || !points.iter().all(|p| p.is_finite()) {
1205        return;
1206    }
1207    with_sink(|sink, px| {
1208        let Some((core, fringe, alpha)) = stroke_setup(px, &stroke) else {
1209            return;
1210        };
1211        let steps = quarter_segments(core / px).min(8);
1212        let eps = px * 1e-3;
1213        // Distinct points via index filtering: no buffer is needed.
1214        let n = points.len();
1215        let next_distinct =
1216            |from: usize| (from + 1..n).find(|&j| (points[j] - points[from]).length() > eps);
1217        let mut strokes = Strokes {
1218            sink,
1219            color: stroke.color,
1220            alpha,
1221            core,
1222            fringe,
1223            prev: None,
1224        };
1225        let closed = stroke.closed && n > 2;
1226        // Collect the distinct path lazily: walk indices i0 -> i1 -> ...
1227        let Some(second) = next_distinct(0) else {
1228            return;
1229        };
1230        let last = {
1231            let mut i = 0;
1232            while let Some(j) = next_distinct(i) {
1233                i = j;
1234            }
1235            i
1236        };
1237        let closed = closed && (points[last] - points[0]).length() > eps;
1238        let first_dir = (points[second] - points[0]).normalize_or_zero();
1239        if closed {
1240            let closing = (points[0] - points[last]).normalize_or_zero();
1241            strokes.join(points[0], closing, first_dir, stroke.join, steps);
1242        } else {
1243            strokes.cap(points[0], first_dir, stroke.cap, true, steps);
1244        }
1245        let mut current = 0;
1246        let mut dir = first_dir;
1247        while let Some(next) = next_distinct(current) {
1248            let d_in = (points[next] - points[current]).normalize_or_zero();
1249            if current != 0 {
1250                strokes.join(points[current], dir, d_in, stroke.join, steps);
1251            }
1252            dir = d_in;
1253            current = next;
1254        }
1255        if closed {
1256            let closing = (points[0] - points[last]).normalize_or_zero();
1257            strokes.join(points[last], dir, closing, stroke.join, steps);
1258            strokes.join(points[0], closing, first_dir, stroke.join, steps);
1259        } else {
1260            strokes.cap(points[last], dir, stroke.cap, false, steps);
1261        }
1262    })
1263}
1264
1265/// Anti-aliased arc of `radius` from `start` sweeping `sweep` radians (positive
1266/// is clockwise on screen with Y down). Useful for radial meters and cooldowns.
1267/// A sweep of a full turn or more draws a closed ring. Emits at most 1,782 vertices.
1268///
1269/// ```
1270/// use std::f32::consts::{FRAC_PI_2, TAU};
1271/// use ferravex_render::{Color, vec2, shapes::{self, Cap, Stroke}};
1272/// // A 70% cooldown ring starting at 12 o'clock.
1273/// shapes::stroke_arc(vec2(40., 40.), 18., -FRAC_PI_2, 0.7 * TAU,
1274///     Stroke::new(5., Color::from_hex(0xf7b553)).cap(Cap::Round));
1275/// ```
1276pub fn stroke_arc(center: Vec2, radius: f32, start: f32, sweep: f32, stroke: Stroke) {
1277    if !(center.is_finite()
1278        && radius.is_finite()
1279        && radius > 0.
1280        && start.is_finite()
1281        && sweep.is_finite())
1282        || sweep == 0.
1283    {
1284        return;
1285    }
1286    if sweep.abs() >= TAU {
1287        return stroke_circle(center, radius, stroke.width, stroke.color);
1288    }
1289    with_sink(|sink, px| {
1290        let Some((core, fringe, alpha)) = stroke_setup(px, &stroke) else {
1291            return;
1292        };
1293        let cap_steps = quarter_segments(core / px).min(8);
1294        let steps = ((quarter_segments(radius / px) * 4) as f32 * sweep.abs() / TAU)
1295            .ceil()
1296            .clamp(1., 64.) as usize;
1297        let mut strokes = Strokes {
1298            sink,
1299            color: stroke.color,
1300            alpha,
1301            core,
1302            fringe,
1303            prev: None,
1304        };
1305        let sign = sweep.signum();
1306        turn(start, sweep, steps, |i, at| {
1307            if i == 0 || i == steps {
1308                let p = center + at * radius;
1309                strokes.cap(p, at.perp() * sign, stroke.cap, i == 0, cap_steps);
1310            } else {
1311                strokes.section(center + at * radius, at * -sign, 1.);
1312            }
1313        });
1314    })
1315}
1316
1317// ---------------------------------------------------------------------------
1318// Additive glows.
1319
1320fn glow_segments(radius: f32, px: f32) -> usize {
1321    (quarter_segments(radius / px) * 4).clamp(12, 48)
1322}
1323
1324/// `n + 1` unit directions for a glow of `n` segments (a multiple of four).
1325fn glow_units(n: usize) -> &'static [Vec2] {
1326    unit_circle(n).expect("glow segment counts are multiples of four in 12..=48")
1327}
1328
1329/// Writes additive triangles through the [`effects::draw_triangles`] path:
1330/// the same validation, per-frame budget and batch flags, without adapters.
1331fn additive(emit: impl FnOnce(&mut Additive)) {
1332    let style = effects::EffectStyle {
1333        blend: effects::EffectBlend::Additive,
1334        depth_test: None,
1335        depth_write: false,
1336    };
1337    effects::write_triangles(style, |writer| emit(&mut Additive(writer)));
1338}
1339
1340struct Additive<'w, 's>(&'w mut effects::TriangleWriter<'s>);
1341
1342impl Additive<'_, '_> {
1343    /// One triangle; false once the effect budget is exhausted.
1344    #[inline]
1345    fn tri(&mut self, t: [(Vec2, Color); 3]) -> bool {
1346        self.0
1347            .push(t.map(|(p, c)| ([p.x, p.y, 0.], [c.r, c.g, c.b, c.a])))
1348    }
1349    /// Two triangles per segment between consecutive glow rings, ring by ring,
1350    /// in the order the glows have always used. `point(ring, i)`, `i` in `0..=n`.
1351    fn bands(
1352        &mut self,
1353        rings: std::ops::Range<usize>,
1354        n: usize,
1355        point: impl Fn(usize, usize) -> (Vec2, Color),
1356    ) {
1357        for ring in rings {
1358            let (mut a, mut c) = (point(ring, 0), point(ring + 1, 0));
1359            for i in 0..n {
1360                let (b, d) = (point(ring, i + 1), point(ring + 1, i + 1));
1361                if !(self.tri([a, c, d]) && self.tri([a, d, b])) {
1362                    return;
1363                }
1364                (a, c) = (b, d);
1365            }
1366        }
1367    }
1368}
1369
1370/// Rings for a glow spanning `extent` device pixels: enough that the
1371/// piecewise-linear falloff shows no visible banding on large glows.
1372fn glow_rings(extent_px: f32) -> usize {
1373    ((extent_px / 14.).ceil() as usize).clamp(4, 12)
1374}
1375
1376/// Additive soft glow disc for particles, pickups and highlights. Brightness
1377/// falls off as `(1 - r/radius)²` over up to 12 rings; `color.a` scales
1378/// intensity. Additive light brightens what is underneath and never darkens.
1379/// Emits at most 3,312 vertices through [`crate::effects::draw_triangles`]
1380/// (its per-frame budget applies); a 24-unit particle glow uses 4 rings.
1381///
1382/// ```
1383/// use ferravex_render::{Color, vec2, shapes};
1384/// shapes::glow_disc(vec2(64., 64.), 40., Color::new(1., 0.6, 0.2, 0.8));
1385/// ```
1386pub fn glow_disc(center: Vec2, radius: f32, color: Color) {
1387    if !(center.is_finite() && radius.is_finite() && radius > 0. && Fill::Solid(color).is_finite())
1388    {
1389        return;
1390    }
1391    let px = crate::read(Sink::device_pixel_of);
1392    let n = glow_segments(radius, px);
1393    let rings = glow_rings(radius / px);
1394    let units = glow_units(n);
1395    let point = |ring: usize, i: usize| {
1396        let t = ring as f32 / rings as f32;
1397        (
1398            center + units[i] * radius * t,
1399            fade(color, (1. - t) * (1. - t)),
1400        )
1401    };
1402    // One fan to the first ring, then two triangles per segment per ring gap.
1403    additive(|out| {
1404        let hub = point(0, 0);
1405        let mut prev = point(1, 0);
1406        for k in 0..n {
1407            let next = point(1, k + 1);
1408            if !out.tri([hub, prev, next]) {
1409                return;
1410            }
1411            prev = next;
1412        }
1413        out.bands(1..rings, n, point);
1414    });
1415}
1416
1417/// Additive soft glow ring (shockwaves, selection halos, portals) of total
1418/// `width` centered on `radius`, brightest on the center line and fading as
1419/// `(1 - |offset|)²` toward both edges. Emits at most 6,912 vertices through
1420/// [`crate::effects::draw_triangles`]; a 16-unit-wide ring uses 4 bands.
1421///
1422/// ```
1423/// use ferravex_render::{Color, vec2, shapes};
1424/// shapes::glow_ring(vec2(64., 64.), 30., 12., Color::new(0.4, 0.8, 1., 0.9));
1425/// ```
1426pub fn glow_ring(center: Vec2, radius: f32, width: f32, color: Color) {
1427    if !(center.is_finite()
1428        && radius.is_finite()
1429        && radius > 0.
1430        && width.is_finite()
1431        && width > 0.
1432        && Fill::Solid(color).is_finite())
1433    {
1434        return;
1435    }
1436    let px = crate::read(Sink::device_pixel_of);
1437    let n = glow_segments(radius + width * 0.5, px);
1438    // Bands per side of the center line.
1439    let side = glow_rings(width * 0.5 / px);
1440    let bands = 2 * side;
1441    let units = glow_units(n);
1442    let point = |band: usize, i: usize| {
1443        let u = band as f32 / side as f32 - 1.;
1444        let r = (radius + u * width * 0.5).max(0.);
1445        let falloff = 1. - u.abs();
1446        (center + units[i] * r, fade(color, falloff * falloff))
1447    };
1448    additive(|out| out.bands(0..bands, n, point));
1449}
1450
1451impl Sink<'_> {
1452    pub(crate) fn device_pixel_of(s: &State) -> f32 {
1453        let m = s.matrix;
1454        let x = vec2(m.x_axis.x * s.w as f32, m.x_axis.y * s.h as f32) * 0.5;
1455        let ppu = x.length();
1456        if ppu.is_finite() && ppu > 1e-6 {
1457            1. / ppu
1458        } else {
1459            1.
1460        }
1461    }
1462}
1463
1464#[cfg(test)]
1465pub(crate) mod tests {
1466    use super::*;
1467    use crate::input::host_frame;
1468
1469    /// Runs `draw` in a frame and returns its vertices (clip space, RGBA).
1470    pub(crate) fn capture(w: u32, h: u32, draw: impl FnOnce()) -> Vec<[f32; 8]> {
1471        host_frame(1. / 60., w, h, draw);
1472        crate::read(|s| s.vertices.clone())
1473    }
1474
1475    fn screen(v: &[f32; 8], w: f32, h: f32) -> Vec2 {
1476        vec2((v[0] + 1.) * w * 0.5, (1. - v[1]) * h * 0.5)
1477    }
1478
1479    fn bounds(vertices: &[[f32; 8]], w: f32, h: f32, opaque: bool) -> [f32; 4] {
1480        let mut b = [f32::MAX, f32::MAX, f32::MIN, f32::MIN];
1481        for v in vertices.iter().filter(|v| !opaque || v[7] > 0.999) {
1482            let p = screen(v, w, h);
1483            b = [b[0].min(p.x), b[1].min(p.y), b[2].max(p.x), b[3].max(p.y)];
1484        }
1485        b
1486    }
1487
1488    #[test]
1489    fn rounded_rect_core_and_fringe_straddle_the_edge_by_half_a_pixel() {
1490        let v = capture(400, 300, || {
1491            fill_rounded_rect(
1492                Rect::new(10., 20., 100., 50.),
1493                8.,
1494                Color::new(1., 0., 0., 1.),
1495            )
1496        });
1497        assert!(v.len() <= 612 && v.len() % 3 == 0, "{}", v.len());
1498        let outer = bounds(&v, 400., 300., false);
1499        let core = bounds(&v, 400., 300., true);
1500        for (o, e) in outer.iter().zip([9.5, 19.5, 110.5, 70.5]) {
1501            assert!((o - e).abs() < 1e-3, "{outer:?}");
1502        }
1503        for (c, e) in core.iter().zip([10.5, 20.5, 109.5, 69.5]) {
1504            assert!((c - e).abs() < 1e-3, "{core:?}");
1505        }
1506        // Fringe vertices are transparent; core vertices are opaque.
1507        assert!(v.iter().all(|v| v[7] == 0. || v[7] == 1.));
1508    }
1509
1510    #[test]
1511    fn round_caps_cover_only_the_half_disc_beyond_each_end() {
1512        // A 100-unit line of width 20 with round caps: its opaque core is a
1513        // rectangle plus exactly one disc (two half discs), never two discs.
1514        let area = |v: &[[f32; 8]]| -> f32 {
1515            v.chunks(3)
1516                .filter(|t| t.iter().all(|v| v[7] > 0.999))
1517                .map(|t| {
1518                    let [a, b, c] = [t[0], t[1], t[2]].map(|v| screen(&v, 400., 300.));
1519                    ((b - a).perp_dot(c - a) * 0.5).abs()
1520                })
1521                .sum()
1522        };
1523        for draw in [
1524            Box::new(|| {
1525                polyline(
1526                    &[vec2(100., 150.), vec2(200., 150.)],
1527                    Stroke::new(20., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1528                )
1529            }) as Box<dyn Fn()>,
1530            Box::new(|| {
1531                stroke_arc(
1532                    vec2(200., 150.),
1533                    80.,
1534                    0.,
1535                    100. / 80.,
1536                    Stroke::new(20., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1537                )
1538            }),
1539        ] {
1540            let v = capture(400, 300, draw);
1541            let core = 9.5_f32; // half width minus the half-pixel fringe
1542            let expected = 100. * 2. * core + PI * core * core;
1543            let actual = area(&v);
1544            assert!(
1545                (actual - expected).abs() < expected * 0.04,
1546                "core area {actual} vs {expected}"
1547            );
1548        }
1549    }
1550
1551    #[test]
1552    fn polygons_and_sectors_are_smooth_bounded_and_reject_bad_input() {
1553        let white = Color::new(1., 1., 1., 1.);
1554        // A square polygon matches the rounded-rect edge convention exactly.
1555        for winding in [
1556            [
1557                vec2(10., 20.),
1558                vec2(110., 20.),
1559                vec2(110., 70.),
1560                vec2(10., 70.),
1561            ],
1562            [
1563                vec2(10., 70.),
1564                vec2(110., 70.),
1565                vec2(110., 20.),
1566                vec2(10., 20.),
1567            ],
1568        ] {
1569            let v = capture(400, 300, || fill_polygon(&winding, white));
1570            assert!(v.len() <= 9 * 4 && v.len() % 3 == 0, "{}", v.len());
1571            let outer = bounds(&v, 400., 300., false);
1572            let core = bounds(&v, 400., 300., true);
1573            for (o, e) in outer.iter().zip([9.5, 19.5, 110.5, 70.5]) {
1574                assert!((o - e).abs() < 1e-3, "{outer:?}");
1575            }
1576            for (c, e) in core.iter().zip([10.5, 20.5, 109.5, 69.5]) {
1577                assert!((c - e).abs() < 1e-3, "{core:?}");
1578            }
1579        }
1580        let many: Vec<_> = (0..MAX_POLYGON_POINTS)
1581            .map(|i| {
1582                let a = i as f32 * TAU / MAX_POLYGON_POINTS as f32;
1583                vec2(300. + 200. * a.cos(), 300. + 200. * a.sin())
1584            })
1585            .collect();
1586        let v = capture(1280, 800, || fill_polygon(&many, white));
1587        assert_eq!(v.len(), 576);
1588        assert!(v.iter().flatten().all(|x| x.is_finite()));
1589        let sector = capture(1280, 800, || {
1590            fill_sector(vec2(400., 400.), 390., -FRAC_PI_2, 6.2, white)
1591        });
1592        assert!(
1593            !sector.is_empty() && sector.len() <= 588,
1594            "{}",
1595            sector.len()
1596        );
1597        assert!(sector.iter().flatten().all(|x| x.is_finite()));
1598        // A quarter sector stays inside its quadrant (plus the fringe).
1599        let quarter = capture(400, 300, || {
1600            fill_sector(vec2(100., 100.), 40., 0., FRAC_PI_2, white)
1601        });
1602        let b = bounds(&quarter, 400., 300., false);
1603        assert!(
1604            b[0] >= 99. && b[1] >= 99. && b[2] <= 141. && b[3] <= 141.,
1605            "{b:?}"
1606        );
1607        let rejected = capture(400, 300, || {
1608            fill_polygon(&[vec2(0., 0.), vec2(10., 0.)], white);
1609            fill_polygon(&[vec2(0., 0.), vec2(10., 0.), vec2(20., 0.)], white);
1610            fill_polygon(&[vec2(0., 0.), vec2(f32::NAN, 0.), vec2(0., 9.)], white);
1611            fill_polygon(&many.repeat(2), white);
1612            fill_triangle(vec2(0., 0.), vec2(5., 5.), vec2(10., 10.), white);
1613            fill_sector(vec2(0., 0.), 10., 0., 0., white);
1614            fill_sector(vec2(0., 0.), -1., 0., 1., white);
1615            fill_sector(vec2(0., 0.), 10., 0., f32::NAN, white);
1616        });
1617        assert!(rejected.is_empty(), "{}", rejected.len());
1618    }
1619
1620    #[test]
1621    fn shapes_respect_documented_vertex_bounds_and_reject_bad_input() {
1622        type Case = (&'static str, usize, Box<dyn Fn()>);
1623        let cases: [Case; 8] = [
1624            (
1625                "rect",
1626                612,
1627                Box::new(|| {
1628                    fill_rounded_rect(
1629                        Rect::new(0., 0., 900., 900.),
1630                        450.,
1631                        Color::new(1., 1., 1., 1.),
1632                    )
1633                }),
1634            ),
1635            (
1636                "stroke",
1637                1224,
1638                Box::new(|| {
1639                    stroke_rounded_rect(
1640                        Rect::new(0., 0., 900., 900.),
1641                        450.,
1642                        3.,
1643                        Color::new(1., 1., 1., 1.),
1644                    )
1645                }),
1646            ),
1647            (
1648                "shadow",
1649                1836,
1650                Box::new(|| {
1651                    drop_shadow(
1652                        Rect::new(0., 0., 900., 900.),
1653                        400.,
1654                        Shadow::soft(Color::new(0., 0., 0., 1.)).blur(200.),
1655                    )
1656                }),
1657            ),
1658            (
1659                "capsule",
1660                612,
1661                Box::new(|| {
1662                    fill_capsule(
1663                        vec2(0., 0.),
1664                        vec2(900., 300.),
1665                        400.,
1666                        Color::new(1., 1., 1., 1.),
1667                    )
1668                }),
1669            ),
1670            (
1671                "arc",
1672                1782,
1673                Box::new(|| {
1674                    stroke_arc(
1675                        vec2(400., 400.),
1676                        390.,
1677                        0.,
1678                        6.2,
1679                        Stroke::new(80., Color::new(1., 1., 1., 1.)).cap(Cap::Round),
1680                    )
1681                }),
1682            ),
1683            (
1684                "glow",
1685                3312,
1686                Box::new(|| glow_disc(vec2(0., 0.), 2000., Color::new(1., 1., 1., 1.))),
1687            ),
1688            (
1689                "ring",
1690                6912,
1691                Box::new(|| glow_ring(vec2(0., 0.), 2000., 400., Color::new(1., 1., 1., 1.))),
1692            ),
1693            (
1694                "nan",
1695                0,
1696                Box::new(|| {
1697                    fill_rounded_rect(
1698                        Rect::new(f32::NAN, 0., 1., 1.),
1699                        0.,
1700                        Color::new(1., 1., 1., 1.),
1701                    );
1702                    fill_circle(vec2(0., 0.), -1., Color::new(1., 1., 1., 1.));
1703                    polyline(&[vec2(0., 0.)], Stroke::new(2., Color::new(1., 1., 1., 1.)));
1704                    polyline(
1705                        &[vec2(1., 1.), vec2(1., 1.)],
1706                        Stroke::new(2., Color::new(1., 1., 1., 1.)),
1707                    );
1708                    stroke_circle(vec2(0., 0.), 5., f32::INFINITY, Color::new(1., 1., 1., 1.));
1709                    glow_disc(vec2(0., 0.), 5., Color::new(f32::NAN, 1., 1., 1.));
1710                }),
1711            ),
1712        ];
1713        for (name, bound, draw) in cases {
1714            let v = capture(1280, 800, draw);
1715            assert!(v.len() <= bound, "{name}: {} > {bound}", v.len());
1716            assert!(v.iter().flatten().all(|x| x.is_finite()), "{name}");
1717            if bound > 0 {
1718                assert!(!v.is_empty(), "{name} drew nothing");
1719            }
1720        }
1721    }
1722
1723    #[test]
1724    fn polyline_joins_cover_corners_and_are_finite() {
1725        let path = [
1726            vec2(10., 10.),
1727            vec2(100., 10.),
1728            vec2(100., 100.),
1729            vec2(10., 100.),
1730        ];
1731        for join in [Join::Miter, Join::Bevel, Join::Round] {
1732            for cap in [Cap::Butt, Cap::Square, Cap::Round] {
1733                let v = capture(200, 200, || {
1734                    polyline(
1735                        &path,
1736                        Stroke::new(6., Color::new(1., 1., 1., 1.))
1737                            .join(join)
1738                            .cap(cap),
1739                    )
1740                });
1741                assert!(!v.is_empty() && v.len() % 3 == 0);
1742                assert!(v.iter().flatten().all(|x| x.is_finite()));
1743                let outer = bounds(&v, 200., 200., false);
1744                // Outer corner reaches the miter point for miters, never beyond it.
1745                assert!(outer[2] <= 103.5 + 1e-3, "{join:?} {cap:?} {outer:?}");
1746                if join == Join::Miter {
1747                    assert!((outer[2] - 103.5).abs() < 1e-3);
1748                }
1749            }
1750        }
1751        let closed = capture(200, 200, || {
1752            polyline(
1753                &path,
1754                Stroke::new(2., Color::new(1., 1., 1., 1.)).closed(true),
1755            )
1756        });
1757        let b = bounds(&closed, 200., 200., false);
1758        assert!(
1759            (b[0] - 8.5).abs() < 1e-3 && (b[1] - 8.5).abs() < 1e-3,
1760            "{b:?}"
1761        );
1762    }
1763
1764    /// Largest difference between the GPU-interpolated color at each opaque
1765    /// triangle's centroid and the gradient evaluated there.
1766    fn worst_centroid_error(v: &[[f32; 8]], w: f32, h: f32, fill: Fill) -> f32 {
1767        v.chunks(3)
1768            .filter(|t| t.iter().all(|v| v[7] > 0.999))
1769            .map(|t| {
1770                let p = t
1771                    .iter()
1772                    .map(|v| screen(v, w, h))
1773                    .fold(Vec2::ZERO, |a, b| a + b)
1774                    / 3.;
1775                let interpolated = t.iter().map(|v| v[4]).sum::<f32>() / 3.;
1776                (interpolated - fill.at(p).r).abs()
1777            })
1778            .fold(0., f32::max)
1779    }
1780
1781    #[test]
1782    fn radial_fills_on_long_rects_follow_the_gradient_not_the_outline() {
1783        let (black, white) = (Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.));
1784        let rect = Rect::new(40., 40., 520., 120.);
1785        let fill = Fill::radial(rect.center(), 70., white, black);
1786        let v = capture(600, 200, || fill_rounded_rect(rect, 12., fill));
1787        assert!(v.len() <= 2592 && v.len() % 3 == 0, "{}", v.len());
1788        // Every vertex samples the gradient; the subdivided mesh keeps the
1789        // interpolation close between them. A single fan from the center
1790        // stretches white across each long edge (error near 0.8).
1791        assert!(v.iter().flatten().all(|x| x.is_finite()));
1792        let error = worst_centroid_error(&v, 600., 200., fill);
1793        assert!(error < 0.2, "centroid error {error}");
1794        // Off-center gradients on circles are subdivided as well.
1795        let c = vec2(100., 100.);
1796        let off = Fill::radial(c + vec2(30., -20.), 50., white, black);
1797        let v = capture(200, 200, || fill_circle(c, 80., off));
1798        assert!(worst_centroid_error(&v, 200., 200., off) < 0.2);
1799        // A concentric circle keeps its exact single fan (as before).
1800        let exact = Fill::radial(c, 80., white, black);
1801        let fan = capture(200, 200, || fill_circle(c, 80., exact));
1802        assert!(fan.len() <= 612, "{}", fan.len());
1803    }
1804
1805    #[test]
1806    fn gradients_interpolate_per_vertex_and_glow_is_additive() {
1807        let rect = Rect::new(0., 0., 100., 100.);
1808        let v = capture(100, 100, || {
1809            fill_rounded_rect(
1810                rect,
1811                0.,
1812                Fill::vertical(rect, Color::new(0., 0., 0., 1.), Color::new(1., 1., 1., 1.)),
1813            )
1814        });
1815        for v in &v {
1816            let p = screen(v, 100., 100.);
1817            assert!((v[4] - (p.y / 100.).clamp(0., 1.)).abs() < 1e-4);
1818        }
1819        host_frame(1. / 60., 100, 100, || {
1820            glow_disc(vec2(50., 50.), 30., Color::new(1., 1., 1., 1.))
1821        });
1822        let (effects, commands) =
1823            crate::read(|s| (s.retained.effects.clone(), s.retained.commands.len()));
1824        assert_eq!(effects.len(), 1);
1825        assert_eq!(effects[0].flags & 4, 4, "additive blend flag");
1826        assert!(commands >= 1);
1827    }
1828}