1use 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#[must_use = "Add a Shape to a Painter"]
26#[derive(Clone, Debug, PartialEq)]
27pub enum Shape {
28 Noop,
30
31 Vec(Vec<Self>),
34
35 Circle(CircleShape),
37
38 Ellipse(EllipseShape),
40
41 LineSegment { points: [Pos2; 2], stroke: Stroke },
43
44 Path(PathShape),
49
50 Band(BandShape),
54
55 Rect(RectShape),
57
58 Text(TextShape),
62
63 Mesh(Arc<Mesh>),
69
70 QuadraticBezier(QuadraticBezierShape),
72
73 CubicBezier(CubicBezierShape),
75
76 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
93const _: () = {
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
121impl Shape {
123 #[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 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 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 #[inline]
155 pub fn line(points: Vec<Pos2>, stroke: impl Into<PathStroke>) -> Self {
156 Self::Path(PathShape::line(points, stroke))
157 }
158
159 #[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 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 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 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 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 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 #[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 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 #[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 #[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 #[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 #[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 #[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 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 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
434impl 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 #[inline(always)]
451 pub fn scale(&mut self, factor: f32) {
452 self.transform(TSTransform::from_scaling(factor));
453 }
454
455 #[inline(always)]
459 pub fn translate(&mut self, delta: Vec2) {
460 self.transform(TSTransform::from_translation(delta));
461 }
462
463 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
529fn 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
552fn 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 shapes.push(Shape::line_segment([start_point, new_point], stroke));
582 position_on_segment += gap_lengths[step];
583 step += 1;
585 if step >= steps {
586 step = 0;
587 }
588 } else {
589 start_point = new_point;
591 position_on_segment += dash_lengths[step];
592 }
593 drawing_dash = !drawing_dash;
594 }
595
596 if drawing_dash {
598 shapes.push(Shape::line_segment([start_point, end], stroke));
599 }
600
601 position_on_segment -= segment_length;
602 }
603}