Skip to main content

epaint/shapes/
shape.rs

1//! The different shapes that can be painted.
2
3use alloc::sync::Arc;
4
5use emath::{Align2, Pos2, Rangef, Rect, Rot2, TSTransform, Vec2, pos2};
6
7use crate::{
8    Color32, CornerRadius, Direction, Mesh, Stroke, StrokeKind, TextureId, Vertex,
9    stroke::PathStroke,
10    text::{FontId, FontsView, Galley},
11};
12
13use super::{
14    BandShape, CircleShape, CubicBezierShape, EllipseShape, PaintCallback, PathShape,
15    QuadraticBezierShape, RectShape, TextShape,
16};
17
18/// A paint primitive such as a circle or a piece of text.
19/// Coordinates are all screen space points (not physical pixels).
20///
21/// You should generally recreate your [`Shape`]s each frame,
22/// but storing them should also be fine with one exception:
23/// [`Shape::Text`] depends on the current `pixels_per_point` (dpi scale)
24/// and so must be recreated every time `pixels_per_point` changes.
25#[must_use = "Add a Shape to a Painter"]
26#[derive(Clone, Debug, PartialEq)]
27pub enum Shape {
28    /// Paint nothing. This can be useful as a placeholder.
29    Noop,
30
31    /// Recursively nest more shapes - sometimes a convenience to be able to do.
32    /// For performance reasons it is better to avoid it.
33    Vec(Vec<Self>),
34
35    /// Circle with optional outline and fill.
36    Circle(CircleShape),
37
38    /// Ellipse with optional outline and fill.
39    Ellipse(EllipseShape),
40
41    /// A line between two points.
42    LineSegment { points: [Pos2; 2], stroke: Stroke },
43
44    /// A series of lines between points.
45    /// The path can have a stroke and/or fill (if closed).
46    ///
47    /// If you want a path of varying width, use [`Self::Band`] instead.
48    Path(PathShape),
49
50    /// A varying-width band along a direction.
51    ///
52    /// If you want a path of fixed width, use [`Self::Path`] instead.
53    Band(BandShape),
54
55    /// Rectangle with optional outline and fill.
56    Rect(RectShape),
57
58    /// Text.
59    ///
60    /// This needs to be recreated if `pixels_per_point` (dpi scale) changes.
61    Text(TextShape),
62
63    /// A general triangle mesh.
64    ///
65    /// Can be used to display images.
66    ///
67    /// Wrapped in an [`Arc`] to minimize the size of [`Shape`].
68    Mesh(Arc<Mesh>),
69
70    /// A quadratic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve).
71    QuadraticBezier(QuadraticBezierShape),
72
73    /// A cubic [Bézier Curve](https://en.wikipedia.org/wiki/B%C3%A9zier_curve).
74    CubicBezier(CubicBezierShape),
75
76    /// Backend-specific painting.
77    Callback(PaintCallback),
78}
79
80#[test]
81fn shape_size() {
82    assert_eq!(
83        core::mem::size_of::<Shape>(),
84        64,
85        "Shape changed size! If it shrank - good! Update this test. If it grew - bad! Try to find a way to avoid it."
86    );
87    assert!(
88        core::mem::size_of::<Shape>() <= 64,
89        "Shape is getting way too big!"
90    );
91}
92
93// Compile-time check that `Shape` is `Send + Sync` on every target.
94// Deliberately not a `#[test]`: tests never run on wasm, but `cargo check` does.
95const _: () = {
96    const fn assert_send_sync<T: Send + Sync>() {}
97    assert_send_sync::<Shape>();
98};
99
100impl From<Vec<Self>> for Shape {
101    #[inline(always)]
102    fn from(shapes: Vec<Self>) -> Self {
103        Self::Vec(shapes)
104    }
105}
106
107impl From<Mesh> for Shape {
108    #[inline(always)]
109    fn from(mesh: Mesh) -> Self {
110        Self::Mesh(mesh.into())
111    }
112}
113
114impl From<Arc<Mesh>> for Shape {
115    #[inline(always)]
116    fn from(mesh: Arc<Mesh>) -> Self {
117        Self::Mesh(mesh)
118    }
119}
120
121/// ## Constructors
122impl Shape {
123    /// A line between two points.
124    /// More efficient than calling [`Self::line`].
125    #[inline]
126    pub fn line_segment(points: [Pos2; 2], stroke: impl Into<Stroke>) -> Self {
127        Self::LineSegment {
128            points,
129            stroke: stroke.into(),
130        }
131    }
132
133    /// A horizontal line.
134    pub fn hline(x: impl Into<Rangef>, y: f32, stroke: impl Into<Stroke>) -> Self {
135        let x = x.into();
136        Self::LineSegment {
137            points: [pos2(x.min, y), pos2(x.max, y)],
138            stroke: stroke.into(),
139        }
140    }
141
142    /// A vertical line.
143    pub fn vline(x: f32, y: impl Into<Rangef>, stroke: impl Into<Stroke>) -> Self {
144        let y = y.into();
145        Self::LineSegment {
146            points: [pos2(x, y.min), pos2(x, y.max)],
147            stroke: stroke.into(),
148        }
149    }
150
151    /// A line through many points.
152    ///
153    /// Use [`Self::line_segment`] instead if your line only connects two points.
154    #[inline]
155    pub fn line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self {
156        Self::Path(PathShape::line(points, stroke))
157    }
158
159    /// A line that closes back to the start point again.
160    #[inline]
161    pub fn closed_line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self {
162        Self::Path(PathShape::closed_line(points, stroke))
163    }
164
165    /// Turn a line into equally spaced dots.
166    pub fn dotted_line(
167        path: &[Pos2],
168        color: impl Into<Color32>,
169        spacing: f32,
170        radius: f32,
171    ) -> Vec<Self> {
172        let mut shapes = Vec::new();
173        points_from_line(path, spacing, radius, color.into(), &mut shapes);
174        shapes
175    }
176
177    /// Turn a line into dashes.
178    pub fn dashed_line(
179        path: &[Pos2],
180        stroke: impl Into<Stroke>,
181        dash_length: f32,
182        gap_length: f32,
183    ) -> Vec<Self> {
184        let mut shapes = Vec::new();
185        dashes_from_line(
186            path,
187            stroke.into(),
188            &[dash_length],
189            &[gap_length],
190            &mut shapes,
191            0.,
192        );
193        shapes
194    }
195
196    /// Turn a line into dashes with different dash/gap lengths and a start offset.
197    pub fn dashed_line_with_offset(
198        path: &[Pos2],
199        stroke: impl Into<Stroke>,
200        dash_lengths: &[f32],
201        gap_lengths: &[f32],
202        dash_offset: f32,
203    ) -> Vec<Self> {
204        let mut shapes = Vec::new();
205        dashes_from_line(
206            path,
207            stroke.into(),
208            dash_lengths,
209            gap_lengths,
210            &mut shapes,
211            dash_offset,
212        );
213        shapes
214    }
215
216    /// Turn a line into dashes. If you need to create many dashed lines use this instead of
217    /// [`Self::dashed_line`].
218    pub fn dashed_line_many(
219        points: &[Pos2],
220        stroke: impl Into<Stroke>,
221        dash_length: f32,
222        gap_length: f32,
223        shapes: &mut Vec<Self>,
224    ) {
225        dashes_from_line(
226            points,
227            stroke.into(),
228            &[dash_length],
229            &[gap_length],
230            shapes,
231            0.,
232        );
233    }
234
235    /// Turn a line into dashes with different dash/gap lengths and a start offset. If you need to
236    /// create many dashed lines use this instead of [`Self::dashed_line_with_offset`].
237    pub fn dashed_line_many_with_offset(
238        points: &[Pos2],
239        stroke: impl Into<Stroke>,
240        dash_lengths: &[f32],
241        gap_lengths: &[f32],
242        dash_offset: f32,
243        shapes: &mut Vec<Self>,
244    ) {
245        dashes_from_line(
246            points,
247            stroke.into(),
248            dash_lengths,
249            gap_lengths,
250            shapes,
251            dash_offset,
252        );
253    }
254
255    /// A convex polygon with a fill and optional stroke.
256    ///
257    /// The most performant winding order is clockwise.
258    #[inline]
259    pub fn convex_polygon(
260        points: Vec<Pos2>,
261        fill: impl Into<Color32>,
262        stroke: impl Into<PathStroke>,
263    ) -> Self {
264        Self::Path(PathShape::convex_polygon(points, fill, stroke))
265    }
266
267    /// A filled triangle inscribed in `rect`, pointing down.
268    ///
269    /// `rotation` is in radians, and rotates the triangle around the center of `rect`:
270    /// `0.0` points down, `TAU / 4.0` left, `TAU / 2.0` up, and `-TAU / 4.0` right.
271    ///
272    /// Useful to paint small arrow icons in the ui, like the on combo boxes or submenu buttons.
273    pub fn rotated_triangle(rect: Rect, rotation: f32, fill: impl Into<Color32>) -> Self {
274        let rotation = Rot2::from_angle(rotation);
275        let points = [rect.left_top(), rect.right_top(), rect.center_bottom()]
276            .into_iter()
277            .map(|point| rect.center() + rotation * (point - rect.center()))
278            .collect();
279        Self::convex_polygon(points, fill, Stroke::NONE)
280    }
281
282    #[inline]
283    pub fn circle_filled(center: Pos2, radius: f32, fill_color: impl Into<Color32>) -> Self {
284        Self::Circle(CircleShape::filled(center, radius, fill_color))
285    }
286
287    #[inline]
288    pub fn circle_stroke(center: Pos2, radius: f32, stroke: impl Into<Stroke>) -> Self {
289        Self::Circle(CircleShape::stroke(center, radius, stroke))
290    }
291
292    #[inline]
293    pub fn ellipse_filled(center: Pos2, radius: Vec2, fill_color: impl Into<Color32>) -> Self {
294        Self::Ellipse(EllipseShape::filled(center, radius, fill_color))
295    }
296
297    #[inline]
298    pub fn ellipse_stroke(center: Pos2, radius: Vec2, stroke: impl Into<Stroke>) -> Self {
299        Self::Ellipse(EllipseShape::stroke(center, radius, stroke))
300    }
301
302    /// See also [`Self::rect_stroke`].
303    #[inline]
304    pub fn rect_filled(
305        rect: Rect,
306        corner_radius: impl Into<CornerRadius>,
307        fill_color: impl Into<Color32>,
308    ) -> Self {
309        Self::Rect(RectShape::filled(rect, corner_radius, fill_color))
310    }
311
312    /// See also [`Self::rect_filled`].
313    #[inline]
314    pub fn rect_stroke(
315        rect: Rect,
316        corner_radius: impl Into<CornerRadius>,
317        stroke: impl Into<Stroke>,
318        stroke_kind: StrokeKind,
319    ) -> Self {
320        Self::Rect(RectShape::stroke(rect, corner_radius, stroke, stroke_kind))
321    }
322
323    /// Paints a gradient rectangle that transitions from `color_from` to `color_to`
324    /// along the given `direction`.
325    ///
326    /// For example, [`Direction::TopDown`] paints `color_from` at the top edge fading
327    /// to `color_to` at the bottom edge.
328    #[inline]
329    pub fn gradient_rect(rect: Rect, direction: Direction, [from, to]: [Color32; 2]) -> Self {
330        let (left_top, right_top, left_bottom, right_bottom) = match direction {
331            Direction::TopDown => (from, from, to, to),
332            Direction::BottomUp => (to, to, from, from),
333            Direction::LeftToRight => (from, to, from, to),
334            Direction::RightToLeft => (to, from, to, from),
335        };
336
337        Self::from(Mesh {
338            indices: vec![0, 1, 2, 2, 1, 3],
339            vertices: vec![
340                Vertex::untextured(rect.left_top(), left_top),
341                Vertex::untextured(rect.right_top(), right_top),
342                Vertex::untextured(rect.left_bottom(), left_bottom),
343                Vertex::untextured(rect.right_bottom(), right_bottom),
344            ],
345            texture_id: Default::default(),
346        })
347    }
348
349    #[expect(clippy::needless_pass_by_value)]
350    pub fn text(
351        fonts: &mut FontsView<'_>,
352        pos: Pos2,
353        anchor: Align2,
354        text: impl ToString,
355        font_id: FontId,
356        color: Color32,
357    ) -> Self {
358        let galley = fonts.layout_no_wrap(text.to_string(), font_id, color);
359        let rect = anchor.anchor_size(pos, galley.size());
360        Self::galley(rect.min, galley, color)
361    }
362
363    /// Any uncolored parts of the [`Galley`] (using [`Color32::PLACEHOLDER`]) will be replaced with the given color.
364    ///
365    /// Any non-placeholder color in the galley takes precedence over this fallback color.
366    #[inline]
367    pub fn galley(pos: Pos2, galley: Arc<Galley>, fallback_color: Color32) -> Self {
368        TextShape::new(pos, galley, fallback_color).into()
369    }
370
371    /// All text color in the [`Galley`] will be replaced with the given color.
372    #[inline]
373    pub fn galley_with_override_text_color(
374        pos: Pos2,
375        galley: Arc<Galley>,
376        text_color: Color32,
377    ) -> Self {
378        TextShape::new(pos, galley, text_color)
379            .with_override_text_color(text_color)
380            .into()
381    }
382
383    #[inline]
384    pub fn mesh(mesh: impl Into<Arc<Mesh>>) -> Self {
385        let mesh = mesh.into();
386        debug_assert!(mesh.is_valid(), "Invalid mesh: {mesh:#?}");
387        Self::Mesh(mesh)
388    }
389
390    /// An image at the given position.
391    ///
392    /// `uv` should normally be `Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0))`
393    /// unless you want to crop or flip the image.
394    ///
395    /// `tint` is a color multiplier. Use [`Color32::WHITE`] if you don't want to tint the image.
396    pub fn image(texture_id: TextureId, rect: Rect, uv: Rect, tint: Color32) -> Self {
397        let mut mesh = Mesh::with_texture(texture_id);
398        mesh.add_rect_with_uv(rect, uv, tint);
399        Self::mesh(mesh)
400    }
401
402    /// The visual bounding rectangle (includes stroke widths)
403    pub fn visual_bounding_rect(&self) -> Rect {
404        match self {
405            Self::Noop => Rect::NOTHING,
406            Self::Vec(shapes) => {
407                let mut rect = Rect::NOTHING;
408                for shape in shapes {
409                    rect |= shape.visual_bounding_rect();
410                }
411                rect
412            }
413            Self::Circle(circle_shape) => circle_shape.visual_bounding_rect(),
414            Self::Ellipse(ellipse_shape) => ellipse_shape.visual_bounding_rect(),
415            Self::LineSegment { points, stroke } => {
416                if stroke.is_empty() {
417                    Rect::NOTHING
418                } else {
419                    Rect::from_two_pos(points[0], points[1]).expand(stroke.width * 0.5)
420                }
421            }
422            Self::Path(path_shape) => path_shape.visual_bounding_rect(),
423            Self::Band(band_shape) => band_shape.visual_bounding_rect(),
424            Self::Rect(rect_shape) => rect_shape.visual_bounding_rect(),
425            Self::Text(text_shape) => text_shape.visual_bounding_rect(),
426            Self::Mesh(mesh) => mesh.calc_bounds(),
427            Self::QuadraticBezier(bezier) => bezier.visual_bounding_rect(),
428            Self::CubicBezier(bezier) => bezier.visual_bounding_rect(),
429            Self::Callback(custom) => custom.rect,
430        }
431    }
432}
433
434/// ## Inspection and transforms
435impl Shape {
436    #[inline(always)]
437    pub fn texture_id(&self) -> crate::TextureId {
438        if let Self::Mesh(mesh) = self {
439            mesh.texture_id
440        } else if let Self::Rect(rect_shape) = self {
441            rect_shape.fill_texture_id()
442        } else {
443            crate::TextureId::default()
444        }
445    }
446
447    /// Scale the shape by `factor`, in-place.
448    ///
449    /// A wrapper around [`Self::transform`].
450    #[inline(always)]
451    pub fn scale(&mut self, factor: f32) {
452        self.transform(TSTransform::from_scaling(factor));
453    }
454
455    /// Move the shape by `delta`, in-place.
456    ///
457    /// A wrapper around [`Self::transform`].
458    #[inline(always)]
459    pub fn translate(&mut self, delta: Vec2) {
460        self.transform(TSTransform::from_translation(delta));
461    }
462
463    /// Transform (move/scale) the shape in-place.
464    ///
465    /// If using a [`PaintCallback`], note that only the rect is scaled as opposed
466    /// to other shapes where the stroke is also scaled.
467    pub fn transform(&mut self, transform: TSTransform) {
468        match self {
469            Self::Noop => {}
470            Self::Vec(shapes) => {
471                for shape in shapes {
472                    shape.transform(transform);
473                }
474            }
475            Self::Circle(circle_shape) => {
476                circle_shape.center = transform * circle_shape.center;
477                circle_shape.radius *= transform.scaling;
478                circle_shape.stroke.width *= transform.scaling;
479            }
480            Self::Ellipse(ellipse_shape) => {
481                ellipse_shape.center = transform * ellipse_shape.center;
482                ellipse_shape.radius *= transform.scaling;
483                ellipse_shape.stroke.width *= transform.scaling;
484            }
485            Self::LineSegment { points, stroke } => {
486                for p in points {
487                    *p = transform * *p;
488                }
489                stroke.width *= transform.scaling;
490            }
491            Self::Path(path_shape) => {
492                for p in &mut path_shape.points {
493                    *p = transform * *p;
494                }
495                path_shape.stroke.width *= transform.scaling;
496            }
497            Self::Band(band_shape) => band_shape.transform(transform),
498            Self::Rect(rect_shape) => {
499                rect_shape.rect = transform * rect_shape.rect;
500                rect_shape.corner_radius *= transform.scaling;
501                rect_shape.stroke.width *= transform.scaling;
502                rect_shape.blur_width *= transform.scaling;
503            }
504            Self::Text(text_shape) => {
505                text_shape.transform(transform);
506            }
507            Self::Mesh(mesh) => {
508                Arc::make_mut(mesh).transform(transform);
509            }
510            Self::QuadraticBezier(bezier) => {
511                for p in &mut bezier.points {
512                    *p = transform * *p;
513                }
514                bezier.stroke.width *= transform.scaling;
515            }
516            Self::CubicBezier(bezier) => {
517                for p in &mut bezier.points {
518                    *p = transform * *p;
519                }
520                bezier.stroke.width *= transform.scaling;
521            }
522            Self::Callback(shape) => {
523                shape.rect = transform * shape.rect;
524            }
525        }
526    }
527}
528
529// ----------------------------------------------------------------------------
530
531/// Creates equally spaced filled circles from a line.
532fn points_from_line(
533    path: &[Pos2],
534    spacing: f32,
535    radius: f32,
536    color: Color32,
537    shapes: &mut Vec<Shape>,
538) {
539    let mut position_on_segment = 0.0;
540    for &[start, end] in path.array_windows() {
541        let vector = end - start;
542        let segment_length = vector.length();
543        while position_on_segment < segment_length {
544            let new_point = start + vector * (position_on_segment / segment_length);
545            shapes.push(Shape::circle_filled(new_point, radius, color));
546            position_on_segment += spacing;
547        }
548        position_on_segment -= segment_length;
549    }
550}
551
552/// Creates dashes from a line.
553fn dashes_from_line(
554    path: &[Pos2],
555    stroke: Stroke,
556    dash_lengths: &[f32],
557    gap_lengths: &[f32],
558    shapes: &mut Vec<Shape>,
559    dash_offset: f32,
560) {
561    assert_eq!(
562        dash_lengths.len(),
563        gap_lengths.len(),
564        "Mismatched dash and gap lengths, got dash_lengths: {}, gap_lengths: {}",
565        dash_lengths.len(),
566        gap_lengths.len()
567    );
568    let mut position_on_segment = dash_offset;
569    let mut drawing_dash = false;
570    let mut step = 0;
571    let steps = dash_lengths.len();
572    for &[start, end] in path.array_windows() {
573        let vector = end - start;
574        let segment_length = vector.length();
575
576        let mut start_point = start;
577        while position_on_segment < segment_length {
578            let new_point = start + vector * (position_on_segment / segment_length);
579            if drawing_dash {
580                // This is the end point.
581                shapes.push(Shape::line_segment([start_point, new_point], stroke));
582                position_on_segment += gap_lengths[step];
583                // Increment step counter
584                step += 1;
585                if step >= steps {
586                    step = 0;
587                }
588            } else {
589                // Start a new dash.
590                start_point = new_point;
591                position_on_segment += dash_lengths[step];
592            }
593            drawing_dash = !drawing_dash;
594        }
595
596        // If the segment ends and the dash is not finished, add the segment's end point.
597        if drawing_dash {
598            shapes.push(Shape::line_segment([start_point, end], stroke));
599        }
600
601        position_on_segment -= segment_length;
602    }
603}