Skip to main content

rust_glass/
paint.rs

1//! Painting: shapes, text, images, masks and glass. Widgets paint in points.
2//! The draw list stores pixels, ready for the GPU.
3
4use std::rc::Rc;
5
6use bytemuck::{Pod, Zeroable};
7
8use crate::color::Color;
9use crate::geometry::{Rect, Vec2, lerp, vec2};
10use crate::icon::Icon;
11use crate::material::{Corner, Glass, Material};
12use crate::text::{TextEngine, TextLayout};
13
14#[repr(C)]
15#[derive(Clone, Copy, Pod, Zeroable, Debug)]
16pub(crate) struct ShapeInst {
17    pub rect: [f32; 4],
18    pub uv: [f32; 4],
19    pub color: [f32; 4],
20    pub color2: [f32; 4],
21    pub radius: [f32; 2],
22    pub stroke: f32,
23    pub soft: f32,
24    pub clip: [f32; 4],
25    pub kind: u32,
26    pub mask: u32,
27    pub power: f32,
28    pub pad: f32,
29}
30
31#[repr(C)]
32#[derive(Clone, Copy, Pod, Zeroable, Debug)]
33pub(crate) struct MaskInst {
34    pub rect: [f32; 4],
35    pub radius: [f32; 2],
36    pub power: f32,
37    pub invert: f32,
38    pub feather: [f32; 4],
39    /// Number of the mask this one is combined with. 0 is none.
40    pub parent: u32,
41    pub pad: [u32; 3],
42}
43
44#[repr(C)]
45#[derive(Clone, Copy, Pod, Zeroable, Debug)]
46pub(crate) struct GShapeInst {
47    pub center: [f32; 2],
48    pub half: [f32; 2],
49    pub radius: [f32; 2],
50    pub power: f32,
51    pub pad: f32,
52    pub tint: [f32; 4],
53}
54
55#[repr(C)]
56#[derive(Clone, Copy, Pod, Zeroable, Debug)]
57pub(crate) struct GlassInst {
58    pub bounds: [f32; 4],
59    pub clip: [f32; 4],
60    pub tint: [f32; 4],
61    pub shape_start: u32,
62    pub shape_count: u32,
63    pub mask: u32,
64    pub fuse: f32,
65    pub inner_amount: f32,
66    pub inner_height: f32,
67    pub outer_amount: f32,
68    pub outer_height: f32,
69    pub dispersion: f32,
70    pub blur: f32,
71    pub magnify: f32,
72    pub opacity: f32,
73    pub face_lo: f32,
74    pub face_hi: f32,
75    pub saturation: f32,
76    pub light_bend: f32,
77    pub rim: f32,
78    pub rim_width: f32,
79    pub dark_edge: f32,
80    pub light_spill: f32,
81    pub inner_glow: f32,
82    pub inner_shadow: f32,
83    pub brightness: f32,
84    pub rim_base: f32,
85    pub pinch: f32,
86    pub pinch_width: f32,
87    pub origin: [f32; 2],
88    pub shadow: f32,
89    pub shadow_radius: f32,
90    pub shadow_y: f32,
91    pub shadow_tint: f32,
92}
93
94const RRECT: u32 = 0;
95const GLYPH: u32 = 1;
96const SPRITE: u32 = 2;
97const IMAGE: u32 = 3;
98const ARC: u32 = 4;
99const LINE: u32 = 5;
100
101/// Handle to an uploaded image. Index 0 is a white pixel.
102#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]
103pub struct ImageId(pub u32);
104
105#[derive(Clone, Copy, Debug)]
106pub(crate) enum Cmd {
107    Shapes { start: u32, end: u32, image: ImageId },
108    Glass { index: u32, probe: u32 },
109}
110
111#[derive(Default)]
112pub(crate) struct LayerList {
113    pub shapes: Vec<ShapeInst>,
114    pub glasses: Vec<(GlassInst, Option<u64>)>,
115    /// (is_glass, index, image)
116    order: Vec<(bool, u32, ImageId)>,
117}
118
119/// Flattened frame, consumed by the renderer.
120#[derive(Default)]
121pub(crate) struct DrawData {
122    pub shapes: Vec<ShapeInst>,
123    pub glasses: Vec<GlassInst>,
124    pub gshapes: Vec<GShapeInst>,
125    pub masks: Vec<MaskInst>,
126    pub cmds: Vec<Cmd>,
127    /// Keys of measured elements, in probe order.
128    pub probes: Vec<(u64, [f32; 4])>,
129    pub clear: [f32; 4],
130    pub light: [f32; 2],
131    pub time: f32,
132    pub ppp: f32,
133}
134
135#[derive(Default)]
136pub(crate) struct Paint {
137    pub ppp: f32,
138    pub layers: Vec<LayerList>,
139    pub data: DrawData,
140    /// Global material adjustments, from the theme.
141    pub glass_tint: f32,
142    pub reduce_transparency: bool,
143    pub increase_contrast: bool,
144}
145
146impl Paint {
147    pub fn begin(&mut self, ppp: f32) {
148        self.ppp = ppp;
149        for l in &mut self.layers {
150            l.shapes.clear();
151            l.glasses.clear();
152            l.order.clear();
153        }
154        let d = &mut self.data;
155        d.shapes.clear();
156        d.glasses.clear();
157        d.gshapes.clear();
158        d.masks.clear();
159        d.cmds.clear();
160        d.probes.clear();
161    }
162
163    pub fn ensure_layer(&mut self, i: usize) {
164        while self.layers.len() <= i {
165            self.layers.push(LayerList::default());
166        }
167    }
168
169    /// Concatenate layers in the given order.
170    pub fn flatten(&mut self, order: &[usize]) {
171        let d = &mut self.data;
172        for &li in order {
173            let l = &self.layers[li];
174            for &(is_glass, idx, image) in &l.order {
175                if is_glass {
176                    let (g, key) = l.glasses[idx as usize];
177                    let index = d.glasses.len() as u32;
178                    d.glasses.push(g);
179                    let probe = match key {
180                        Some(k) => {
181                            let s = d.gshapes[g.shape_start as usize];
182                            d.probes.push((
183                                k,
184                                [
185                                    s.center[0] - s.half[0],
186                                    s.center[1] - s.half[1],
187                                    s.center[0] + s.half[0],
188                                    s.center[1] + s.half[1],
189                                ],
190                            ));
191                            d.probes.len() as u32 - 1
192                        }
193                        None => u32::MAX,
194                    };
195                    d.cmds.push(Cmd::Glass { index, probe });
196                } else {
197                    let at = d.shapes.len() as u32;
198                    d.shapes.push(l.shapes[idx as usize]);
199                    if let Some(Cmd::Shapes { end, image: im, .. }) = d.cmds.last_mut()
200                        && *end == at
201                        && (*im == image || image.0 == u32::MAX || im.0 == u32::MAX)
202                    {
203                        *end += 1;
204                        if im.0 == u32::MAX {
205                            *im = image;
206                        }
207                    } else {
208                        d.cmds.push(Cmd::Shapes { start: at, end: at + 1, image });
209                    }
210                }
211            }
212        }
213        for c in &mut d.cmds {
214            if let Cmd::Shapes { image, .. } = c
215                && image.0 == u32::MAX
216            {
217                *image = ImageId(0);
218            }
219        }
220    }
221}
222
223/// Marks a shape that does not care which image is bound.
224const ANY_IMAGE: ImageId = ImageId(u32::MAX);
225
226/// Draws shapes, text, images and glass into one layer. Get one from
227/// [`Ui::painter`](crate::Ui::painter) or
228/// [`Context::painter`](crate::Context::painter). All positions are in points.
229pub struct Painter<'a> {
230    pub(crate) paint: &'a mut Paint,
231    pub(crate) text: &'a mut TextEngine,
232    /// The layer painted into.
233    pub layer: usize,
234    /// Nothing is painted outside this rectangle.
235    pub clip: Rect,
236    /// Mask applied to everything painted. 0 is none.
237    pub mask: u32,
238    /// Opacity of everything painted, from 0 to 1.
239    pub opacity: f32,
240}
241
242/// How far the edges of a mask fade out, in points. 0 is a hard edge.
243#[derive(Clone, Copy, Debug, Default)]
244pub struct Feather {
245    /// Fade at the left edge.
246    pub left: f32,
247    /// Fade at the top edge.
248    pub top: f32,
249    /// Fade at the right edge.
250    pub right: f32,
251    /// Fade at the bottom edge.
252    pub bottom: f32,
253}
254
255impl Painter<'_> {
256    fn px(&self, r: Rect) -> [f32; 4] {
257        let s = self.paint.ppp;
258        [r.min.x * s, r.min.y * s, r.max.x * s, r.max.y * s]
259    }
260
261    fn base(&self, r: Rect, color: Color) -> ShapeInst {
262        ShapeInst {
263            rect: self.px(r),
264            uv: [0.0; 4],
265            color: color.fade(self.opacity).to_array(),
266            color2: color.fade(self.opacity).to_array(),
267            radius: [0.0; 2],
268            stroke: 0.0,
269            soft: 0.0,
270            clip: self.px(self.clip),
271            kind: RRECT,
272            mask: self.mask,
273            power: 2.0,
274            pad: 0.0,
275        }
276    }
277
278    fn push(&mut self, s: ShapeInst, image: ImageId) {
279        if s.color[3] <= 0.0 && s.color2[3] <= 0.0 {
280            return;
281        }
282        let e = if s.kind == RRECT { s.soft * 2.5 } else { 0.0 } + s.stroke;
283        let c = s.clip;
284        let (x0, x1) = (s.rect[0].min(s.rect[2]) - e, s.rect[0].max(s.rect[2]) + e);
285        let (y0, y1) = (s.rect[1].min(s.rect[3]) - e, s.rect[1].max(s.rect[3]) + e);
286        if x1 < c[0] || y1 < c[1] || x0 > c[2] || y0 > c[3] {
287            return;
288        }
289        let l = &mut self.paint.layers[self.layer];
290        l.order.push((false, l.shapes.len() as u32, image));
291        l.shapes.push(s);
292    }
293
294    fn round(&self, s: &mut ShapeInst, r: Rect, corner: Corner) {
295        let (rad, n) = corner.resolve(r.size());
296        s.radius = [rad.x * self.paint.ppp, rad.y * self.paint.ppp];
297        s.power = n;
298    }
299
300    /// Adds a mask and returns its number, for [`Painter::with_mask`]. Paint
301    /// shows inside `rect`, or outside with `invert`. `feather` fades the
302    /// edges of the rectangle.
303    ///
304    /// The new mask is combined with the painter's current mask, so content a
305    /// widget masks for itself still fades at the edge of a scroll area.
306    pub fn add_mask(&mut self, rect: Rect, corner: impl Into<Corner>, invert: bool, feather: Feather) -> u32 {
307        let (rad, n) = corner.into().resolve(rect.size());
308        let s = self.paint.ppp;
309        let f = feather;
310        let m = MaskInst {
311            rect: self.px(rect),
312            radius: [rad.x * s, rad.y * s],
313            power: n,
314            invert: invert as u32 as f32,
315            feather: [f.left * s, f.top * s, f.right * s, f.bottom * s],
316            parent: self.mask,
317            pad: [0; 3],
318        };
319        self.paint.data.masks.push(m);
320        self.paint.data.masks.len() as u32
321    }
322
323    /// Runs `f` with `mask` applied to everything it paints.
324    pub fn with_mask(&mut self, mask: u32, f: impl FnOnce(&mut Painter)) {
325        let old = std::mem::replace(&mut self.mask, mask);
326        f(self);
327        self.mask = old;
328    }
329
330    /// Fills a rectangle.
331    pub fn fill(&mut self, rect: Rect, corner: impl Into<Corner>, color: Color) {
332        let mut s = self.base(rect, color);
333        self.round(&mut s, rect, corner.into());
334        self.push(s, ANY_IMAGE);
335    }
336
337    /// Fills a rectangle with a linear gradient from `start` to `end`.
338    /// `direction` is in coordinates where the rectangle runs from 0 to 1, so
339    /// `vec2(0.0, 1.0)` goes from top to bottom.
340    pub fn gradient(
341        &mut self,
342        rect: Rect,
343        corner: impl Into<Corner>,
344        start: Color,
345        end: Color,
346        direction: Vec2,
347    ) {
348        let mut s = self.base(rect, start);
349        self.round(&mut s, rect, corner.into());
350        s.color2 = end.fade(self.opacity).to_array();
351        s.uv = [direction.x, direction.y, 0.0, 0.0];
352        self.push(s, ANY_IMAGE);
353    }
354
355    /// Draws the outline of a rectangle, centered on its edge.
356    pub fn stroke(&mut self, rect: Rect, corner: impl Into<Corner>, width: f32, color: Color) {
357        let mut s = self.base(rect, color);
358        self.round(&mut s, rect, corner.into());
359        s.stroke = (width * self.paint.ppp).max(0.75);
360        self.push(s, ANY_IMAGE);
361    }
362
363    /// Draws a soft shadow of a rectangle, blurred by `softness` points.
364    pub fn shadow(&mut self, rect: Rect, corner: impl Into<Corner>, softness: f32, color: Color) {
365        let mut s = self.base(rect, color);
366        self.round(&mut s, rect, corner.into());
367        s.soft = softness * self.paint.ppp;
368        self.push(s, ANY_IMAGE);
369    }
370
371    /// Draws a line from `from` to `to` with round ends.
372    pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) {
373        let mut s = self.base(Rect { min: from, max: to }, color);
374        s.stroke = (width * 0.5 * self.paint.ppp).max(0.35);
375        s.kind = LINE;
376        self.push(s, ANY_IMAGE);
377    }
378
379    /// Draws an arc with round ends around `center`. Angles are in radians,
380    /// clockwise from the right. The color runs from `start_color` to
381    /// `end_color` along the arc.
382    #[allow(clippy::too_many_arguments)]
383    pub fn arc(
384        &mut self,
385        center: Vec2,
386        radius: f32,
387        width: f32,
388        start: f32,
389        sweep: f32,
390        start_color: Color,
391        end_color: Color,
392    ) {
393        let mut s = self.base(Rect::from_center_size(center, Vec2::splat(radius * 2.0)), start_color);
394        s.color2 = end_color.fade(self.opacity).to_array();
395        s.radius = [start, sweep.clamp(0.0, std::f32::consts::TAU)];
396        s.stroke = width * 0.5 * self.paint.ppp;
397        s.kind = ARC;
398        self.push(s, ANY_IMAGE);
399    }
400
401    /// Draws the part `uv` (0 to 1 on both axes) of an image into `rect`,
402    /// multiplied by `tint`.
403    pub fn image(&mut self, rect: Rect, corner: impl Into<Corner>, image: ImageId, uv: Rect, tint: Color) {
404        let mut s = self.base(rect, tint);
405        self.round(&mut s, rect, corner.into());
406        s.uv = [uv.min.x, uv.min.y, uv.max.x, uv.max.y];
407        s.kind = IMAGE;
408        self.push(s, image);
409    }
410
411    /// Draws laid out text with its top left corner at `position`.
412    pub fn text(&mut self, position: Vec2, layout: &Rc<TextLayout>, color: Color) {
413        self.text_scaled(position, layout, color, 1.0, position);
414    }
415
416    /// Draws text scaled around `origin`. It is rasterized close to its final
417    /// size, so it stays sharp while a control grows or shrinks.
418    pub fn text_scaled(
419        &mut self,
420        position: Vec2,
421        layout: &Rc<TextLayout>,
422        color: Color,
423        scale: f32,
424        origin: Vec2,
425    ) {
426        let (pos, l, c, about) = (position, layout, color, origin);
427        if c.a * self.opacity <= 0.002 {
428            return;
429        }
430        let ppp = self.paint.ppp;
431        let moving = (scale - 1.0).abs() > 1e-3;
432        let want = l.font_size * ppp * scale;
433        let px = if moving { (want * 2.0).round().max(2.0) * 0.5 } else { l.font_size * ppp };
434        let residual = if moving { want / px } else { 1.0 };
435        let about_px = about * ppp;
436        for g in &l.glyphs {
437            // Baselines sit on whole pixels at rest. While scaled, the glyph
438            // moves away from that same snapped place, so the text lands
439            // exactly where it rests and never hops by a fraction of a pixel
440            // when the scale reaches 1.
441            let mut rest = (pos + g.pos) * ppp;
442            rest.y = rest.y.round();
443            let at = if moving { about_px + (rest - about_px) * scale } else { rest };
444            let Some((e, o)) = self.text.glyph(g, px, at) else { continue };
445            let min = if moving { at + (o - at + e.offset) * residual } else { o + e.offset };
446            let max = min + e.size * residual;
447            let mut s = self.base(Rect::default(), c);
448            s.rect = [min.x, min.y, max.x, max.y];
449            s.uv = e.uv;
450            s.kind = if e.color { SPRITE } else { GLYPH };
451            self.push(s, ANY_IMAGE);
452        }
453    }
454
455    /// Draws text centered in `rect`, scaled around the center.
456    pub fn text_centered(&mut self, rect: Rect, layout: &Rc<TextLayout>, color: Color, scale: f32) {
457        let pos = rect.center() - layout.size * 0.5;
458        self.text_scaled(pos, layout, color, scale, rect.center());
459    }
460
461    /// Draws an icon `size` points wide, centered on `center`.
462    pub fn icon(&mut self, center: Vec2, size: f32, icon: Icon, color: Color) {
463        let c = color;
464        let want = size * self.paint.ppp;
465        // Even pixel sizes; small residual scale while animating.
466        let px = ((want / 2.0).round() * 2.0).max(4.0);
467        let Some(e) = self.text.icon(icon, px as u32) else { return };
468        let at = center * self.paint.ppp;
469        let mut min = at - Vec2::splat(want * 0.5);
470        if (want - px).abs() < 0.51 {
471            min = vec2(min.x.round(), min.y.round());
472        }
473        let mut s = self.base(Rect::default(), c);
474        s.rect = [min.x, min.y, min.x + want, min.y + want];
475        s.uv = e.uv;
476        s.kind = GLYPH;
477        self.push(s, ANY_IMAGE);
478    }
479
480    /// Blurs what is already painted under `rect` by `radius` points, on
481    /// this layer and below. Use it to soften content while it appears or
482    /// disappears. A radius below half a point does nothing.
483    ///
484    /// ```
485    /// # use rust_glass::prelude::*;
486    /// # fn f(ui: &mut Ui, appear: f32) {
487    /// let rect = ui.allocate(vec2(200.0, 80.0));
488    /// ui.label("Fading in");
489    /// // Sharp once `appear` reaches 1.
490    /// ui.painter().blur(rect, 12.0, 10.0 * (1.0 - appear));
491    /// # }
492    /// ```
493    pub fn blur(&mut self, rect: Rect, corner: impl Into<Corner>, radius: f32) {
494        if radius < 0.5 {
495            return;
496        }
497        let opacity = std::mem::replace(&mut self.opacity, 1.0);
498        self.glass(&Glass::new(rect, corner, Material::blur(radius)));
499        self.opacity = opacity;
500    }
501
502    /// Paints a glass element. It bends and blurs everything painted before
503    /// it, on this layer and below.
504    pub fn glass(&mut self, g: &Glass) {
505        if g.presence <= 0.001 || g.shapes.is_empty() || self.opacity <= 0.001 {
506            return;
507        }
508        let s = self.paint.ppp;
509        let m: &Material = &g.material;
510        // The setting runs from clear over the preset to fully tinted.
511        let setting = self.paint.glass_tint.clamp(0.0, 1.0);
512        let preset = crate::theme::Theme::DEFAULT_GLASS_TINT;
513        let frost = ((setting - preset) / (1.0 - preset)).max(0.0) * m.glass_tint_response;
514        let clear = ((preset - setting) / preset).max(0.0) * m.glass_tint_response;
515        let solid_ui = if self.paint.reduce_transparency { m.glass_tint_response } else { 0.0 };
516        let presence = g.presence * self.opacity;
517        let start = self.paint.data.gshapes.len() as u32;
518        let mut min_half = f32::MAX;
519        for sh in &g.shapes {
520            let size = sh.rect.size().max(Vec2::splat(0.5));
521            let (rad, n) = sh.corner.resolve(size);
522            let c = sh.rect.center();
523            min_half = min_half.min(size.x.min(size.y) * 0.5);
524            let tint = sh.tint.or(m.tint).unwrap_or(Color::TRANSPARENT);
525            // Do not let a missing tint drag neighbours towards black.
526            let tint = if tint.a <= 0.0 { m.tint.unwrap_or(Color::WHITE).alpha(0.0) } else { tint };
527            self.paint.data.gshapes.push(GShapeInst {
528                center: [c.x * s, c.y * s],
529                half: [size.x * 0.5 * s, size.y * 0.5 * s],
530                radius: [rad.x * s, rad.y * s],
531                power: n,
532                pad: 0.0,
533                tint: tint.to_array(),
534            });
535        }
536        // The curved part cannot be wider than the element, and the bend scales
537        // with it so small controls keep the same look.
538        let max_depth = min_half * 0.98;
539        let k = (max_depth / m.depth.max(0.1)).min(1.0);
540        let depth = m.depth * k;
541        let refraction = m.refraction * k.max(0.35) * presence;
542
543        let d = g.darkness;
544        let mut lo = lerp(m.light_range.0, m.dark_range.0, d);
545        let mut hi = lerp(m.light_range.1, m.dark_range.1, d);
546        let solid = (solid_ui * 0.9).max(frost * 0.72);
547        let target = lerp(0.97, 0.13, d);
548        if m.tint.is_none() {
549            lo *= 1.0 - 0.05 * clear;
550            hi = lerp(hi, 1.0, 0.25 * clear);
551        }
552        // The frost setting moves from clear to fully tinted.
553        if m.tint.is_none() || m.tint_follow > 0.5 {
554            lo = lerp(lo, target, solid);
555            hi = lerp(hi, lerp(1.0, 0.18, d), solid);
556        }
557        let blur = m.blur * (1.0 + frost * 1.5) * (1.0 - 0.62 * clear) + 12.0 * solid_ui;
558        let bounds = g.bounds();
559        let grow = m.shadow_radius * 2.0 + m.shadow_y.abs() + 3.0;
560        let shadow = (m.shadow * (1.0 + g.shadow_boost)).min(0.6);
561        // Stronger edges, except on glass that has no edge at all.
562        let hc = if self.paint.increase_contrast && m.rim > 0.0 { 0.5 } else { 0.0 };
563        let c = bounds.center();
564        let inst = GlassInst {
565            bounds: self.px(bounds.expand(grow + g.fuse * 0.3)),
566            clip: self.px(self.clip),
567            tint: [m.sideways, m.corner_dispersion, 0.0, m.tint_follow],
568            shape_start: start,
569            shape_count: g.shapes.len() as u32,
570            mask: self.mask,
571            fuse: g.fuse * s,
572            inner_amount: refraction * s,
573            inner_height: depth * s,
574            outer_amount: m.outer_refraction * k * presence * s,
575            outer_height: m.outer_depth * k * s,
576            dispersion: m.dispersion,
577            blur: blur * s * presence.sqrt(),
578            magnify: lerp(1.0, m.magnify, presence),
579            opacity: presence,
580            face_lo: lo,
581            face_hi: hi,
582            saturation: m.saturation,
583            light_bend: g.light_bend,
584            rim: (m.rim * lerp(1.0, 0.72, d)).min(1.0),
585            rim_width: m.rim_width * s.max(1.0),
586            dark_edge: (m.dark_edge + hc).min(0.9),
587            light_spill: m.light_spill * presence,
588            inner_glow: m.inner_glow * lerp(1.0, 0.6, d),
589            inner_shadow: m.inner_shadow,
590            brightness: g.brightness,
591            rim_base: m.rim_base,
592            pinch: m.pinch * k * presence * s,
593            pinch_width: m.pinch_width * k * s,
594            origin: [c.x * s, c.y * s],
595            shadow: shadow * presence,
596            shadow_radius: m.shadow_radius * s,
597            shadow_y: m.shadow_y * s,
598            shadow_tint: m.shadow_tint,
599        };
600        let l = &mut self.paint.layers[self.layer];
601        l.order.push((true, l.glasses.len() as u32, ImageId(0)));
602        l.glasses.push((inst, g.stat_key));
603    }
604}