1use egui::{Color32, Painter, Pos2, Stroke, StrokeKind, vec2};
24
25use crate::tokens::ViewportTokens;
26use crate::view::Mapping;
27
28pub const HIT_RADIUS: f32 = 12.0;
30
31pub const DRAWN_RADIUS: f32 = 5.0;
33
34pub const LINE_WIDTH: f32 = 1.5;
38pub const UNDER_WIDTH: f32 = 3.0;
39pub const OUTLINE_WIDTH: f32 = 1.5;
40
41fn snapped(painter: &Painter, w: f32) -> f32 {
43 egui_pop_core::scale::stroke(painter.ctx(), w)
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
48pub enum HandleKind {
49 Move,
51 Point,
53 Corner,
55 Edge,
57 Size,
59 Rotate,
61 Feather,
63 Control,
65}
66
67impl HandleKind {
68 pub fn name(self) -> &'static str {
69 match self {
70 HandleKind::Move => "move",
71 HandleKind::Point => "point",
72 HandleKind::Corner => "corner",
73 HandleKind::Edge => "edge",
74 HandleKind::Size => "size",
75 HandleKind::Rotate => "rotate",
76 HandleKind::Feather => "feather",
77 HandleKind::Control => "control",
78 }
79 }
80}
81
82#[derive(Clone, Copy, Debug, PartialEq)]
85pub struct Handle {
86 pub index: u32,
87 pub kind: HandleKind,
88 pub at: [f64; 2],
89}
90
91#[derive(Clone, Debug, PartialEq)]
93pub enum Shape {
94 Point([f64; 2]),
95 Line([f64; 2], [f64; 2]),
96 Rect([f64; 4]),
98 Circle {
99 center: [f64; 2],
100 radius: f64,
101 },
102 Ellipse {
105 center: [f64; 2],
106 radii: [f64; 2],
107 rotation: f64,
108 },
109 Path {
110 points: Vec<[f64; 2]>,
111 closed: bool,
112 },
113}
114
115impl Shape {
116 pub fn handles(&self) -> Vec<Handle> {
118 let h = |index, kind, at| Handle { index, kind, at };
119 match self {
120 Shape::Point(p) => vec![h(0, HandleKind::Move, *p)],
121 Shape::Line(a, b) => vec![
122 h(0, HandleKind::Point, *a),
123 h(1, HandleKind::Point, *b),
124 h(2, HandleKind::Move, mid(*a, *b)),
125 ],
126 Shape::Rect(r) => {
127 let [x0, y0, x1, y1] = *r;
128 let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
129 vec![
130 h(0, HandleKind::Corner, [x0, y0]),
131 h(1, HandleKind::Corner, [x1, y0]),
132 h(2, HandleKind::Corner, [x1, y1]),
133 h(3, HandleKind::Corner, [x0, y1]),
134 h(4, HandleKind::Edge, [mx, y0]),
135 h(5, HandleKind::Edge, [x1, my]),
136 h(6, HandleKind::Edge, [mx, y1]),
137 h(7, HandleKind::Edge, [x0, my]),
138 h(8, HandleKind::Move, [mx, my]),
139 ]
140 }
141 Shape::Circle { center, radius } => vec![
142 h(0, HandleKind::Move, *center),
143 h(1, HandleKind::Size, [center[0] + radius, center[1]]),
144 ],
145 Shape::Ellipse {
146 center,
147 radii,
148 rotation,
149 } => {
150 let at = |x: f64, y: f64| along(*center, *rotation, x, y);
151 vec![
152 h(0, HandleKind::Move, *center),
153 h(1, HandleKind::Size, at(radii[0], 0.0)),
154 h(2, HandleKind::Size, at(0.0, radii[1])),
155 h(3, HandleKind::Rotate, at(0.0, -radii[1] * ROTATE_OUT)),
156 ]
157 }
158 Shape::Path { points, .. } => {
159 let mut v: Vec<Handle> = points
160 .iter()
161 .enumerate()
162 .map(|(i, p)| h(i as u32, HandleKind::Point, *p))
163 .collect();
164 if !points.is_empty() {
165 let n = points.len() as f64;
166 let c = points
167 .iter()
168 .fold([0.0, 0.0], |a, p| [a[0] + p[0] / n, a[1] + p[1] / n]);
169 v.push(h(points.len() as u32, HandleKind::Move, c));
170 }
171 v
172 }
173 }
174 }
175
176 pub fn moved(&self, index: u32, from: [f64; 2], to: [f64; 2]) -> Shape {
180 let d = [to[0] - from[0], to[1] - from[1]];
181 let shift = |p: [f64; 2]| [p[0] + d[0], p[1] + d[1]];
182 match self {
183 Shape::Point(p) => Shape::Point(shift(*p)),
184 Shape::Line(a, b) => match index {
185 0 => Shape::Line(to, *b),
186 1 => Shape::Line(*a, to),
187 _ => Shape::Line(shift(*a), shift(*b)),
188 },
189 Shape::Rect(r) => {
190 let [mut x0, mut y0, mut x1, mut y1] = *r;
191 match index {
192 0 => (x0, y0) = (to[0], to[1]),
193 1 => (x1, y0) = (to[0], to[1]),
194 2 => (x1, y1) = (to[0], to[1]),
195 3 => (x0, y1) = (to[0], to[1]),
196 4 => y0 = to[1],
197 5 => x1 = to[0],
198 6 => y1 = to[1],
199 7 => x0 = to[0],
200 _ => {
201 x0 += d[0];
202 x1 += d[0];
203 y0 += d[1];
204 y1 += d[1];
205 }
206 }
207 Shape::Rect([x0.min(x1), y0.min(y1), x0.max(x1), y0.max(y1)])
208 }
209 Shape::Circle { center, radius } => match index {
210 1 => Shape::Circle {
211 center: *center,
212 radius: ((to[0] - center[0]).powi(2) + (to[1] - center[1]).powi(2)).sqrt(),
213 },
214 _ => Shape::Circle {
215 center: shift(*center),
216 radius: *radius,
217 },
218 },
219 Shape::Ellipse {
220 center,
221 radii,
222 rotation,
223 } => {
224 let v = [to[0] - center[0], to[1] - center[1]];
225 let (s, c) = rotation.sin_cos();
226 let (x, y) = (v[0] * c + v[1] * s, -v[0] * s + v[1] * c);
228 let (mut radii, mut rotation, mut center) = (*radii, *rotation, *center);
229 match index {
230 1 => radii[0] = x.abs().max(MIN_RADIUS),
231 2 => radii[1] = y.abs().max(MIN_RADIUS),
232 3 => rotation = v[0].atan2(-v[1]),
233 _ => center = shift(center),
234 }
235 Shape::Ellipse {
236 center,
237 radii,
238 rotation,
239 }
240 }
241 Shape::Path { points, closed } => {
242 let mut points = points.clone();
243 if let Some(p) = points.get_mut(index as usize) {
244 *p = to;
245 } else {
246 for p in &mut points {
247 *p = shift(*p);
248 }
249 }
250 Shape::Path {
251 points,
252 closed: *closed,
253 }
254 }
255 }
256 }
257}
258
259fn mid(a: [f64; 2], b: [f64; 2]) -> [f64; 2] {
260 [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0]
261}
262
263const ROTATE_OUT: f64 = 1.3;
265
266const MIN_RADIUS: f64 = 0.5;
268
269fn along(center: [f64; 2], rotation: f64, x: f64, y: f64) -> [f64; 2] {
272 let (s, c) = rotation.sin_cos();
273 [center[0] + x * c - y * s, center[1] + x * s + y * c]
274}
275
276fn ellipse_points(center: [f64; 2], radii: [f64; 2], rotation: f64, n: usize) -> Vec<[f64; 2]> {
278 (0..n)
279 .map(|i| {
280 let a = std::f64::consts::TAU * i as f64 / n as f64;
281 along(center, rotation, radii[0] * a.cos(), radii[1] * a.sin())
282 })
283 .collect()
284}
285
286#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
288pub enum Emphasis {
289 #[default]
291 Normal,
292 Selected,
294 Faint,
297}
298
299#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
301pub struct Style {
302 pub emphasis: Emphasis,
303 pub dashed: bool,
305}
306
307#[derive(Clone, Debug, PartialEq)]
310pub struct Overlay {
311 pub id: String,
312 pub shape: Shape,
313 pub handles: Vec<Handle>,
314 pub label: Option<String>,
315 pub style: Style,
316}
317
318impl Overlay {
319 pub fn new(id: impl Into<String>, shape: Shape) -> Overlay {
321 Overlay {
322 id: id.into(),
323 handles: shape.handles(),
324 shape,
325 label: None,
326 style: Style::default(),
327 }
328 }
329
330 pub fn guide(id: impl Into<String>, shape: Shape) -> Overlay {
332 Overlay {
333 id: id.into(),
334 shape,
335 handles: Vec::new(),
336 label: None,
337 style: Style::default(),
338 }
339 }
340
341 pub fn handles(mut self, handles: Vec<Handle>) -> Overlay {
344 self.handles = handles;
345 self
346 }
347
348 pub fn style(mut self, style: Style) -> Overlay {
350 self.style = style;
351 self
352 }
353
354 pub fn selected(mut self) -> Overlay {
356 self.style.emphasis = Emphasis::Selected;
357 self
358 }
359
360 pub fn faint(mut self) -> Overlay {
362 self.style.emphasis = Emphasis::Faint;
363 self
364 }
365
366 pub fn dashed(mut self) -> Overlay {
368 self.style.dashed = true;
369 self
370 }
371
372 pub fn label(mut self, label: impl Into<String>) -> Overlay {
374 self.label = Some(label.into());
375 self
376 }
377
378 pub fn apply(&mut self, start: &Shape, signal: &crate::Signal) -> bool {
382 let crate::Signal::Handle {
383 overlay,
384 handle,
385 phase,
386 from,
387 at,
388 ..
389 } = signal
390 else {
391 return false;
392 };
393 if *overlay != self.id {
394 return false;
395 }
396 let shape = match phase {
397 crate::Phase::Cancel => start.clone(),
398 crate::Phase::Begin => return false,
399 _ => start.moved(*handle, *from, *at),
400 };
401 let changed = shape != self.shape;
402 self.handles = shape.handles();
403 self.shape = shape;
404 changed
405 }
406}
407
408#[derive(Clone, Copy, Debug, PartialEq, Eq)]
410pub enum HandleState {
411 Rest,
412 Hover,
413 Active,
414}
415
416pub fn paint_handle(
418 painter: &Painter,
419 pos: Pos2,
420 kind: HandleKind,
421 state: HandleState,
422 t: &ViewportTokens,
423) {
424 paint_handle_styled(painter, pos, kind, state, Emphasis::Normal, t);
425}
426
427pub fn paint_handle_styled(
430 painter: &Painter,
431 pos: Pos2,
432 kind: HandleKind,
433 state: HandleState,
434 emphasis: Emphasis,
435 t: &ViewportTokens,
436) {
437 let alpha = if emphasis == Emphasis::Faint {
438 FAINT
439 } else {
440 1.0
441 };
442 let fill = match state {
443 HandleState::Rest => t.handle,
444 HandleState::Hover | HandleState::Active => t.handle_hover,
445 }
446 .gamma_multiply(alpha);
447 let r = if state == HandleState::Rest {
448 DRAWN_RADIUS
449 } else {
450 DRAWN_RADIUS + 1.5
451 };
452 let w = |x: f32| snapped(painter, x);
453 let outline = Stroke::new(w(OUTLINE_WIDTH), t.handle_outline.gamma_multiply(alpha));
454 match kind {
455 HandleKind::Move => {
456 painter.circle(pos, r, fill, outline);
457 painter.circle_filled(pos, r * 0.35, outline.color);
458 }
459 HandleKind::Corner | HandleKind::Edge => {
460 let rect = egui::Rect::from_center_size(pos, vec2(r * 1.8, r * 1.8));
461 painter.rect(rect, 0.0, fill, outline, StrokeKind::Middle);
462 }
463 HandleKind::Rotate => {
464 painter.circle(pos, r, Color32::TRANSPARENT, Stroke::new(w(2.5), fill));
465 painter.circle_stroke(pos, r + 1.5, outline);
466 }
467 HandleKind::Feather => {
468 painter.circle(
469 pos,
470 r,
471 Color32::TRANSPARENT,
472 Stroke::new(w(LINE_WIDTH), fill),
473 );
474 painter.circle_stroke(pos, r * 0.5, Stroke::new(w(LINE_WIDTH), fill));
475 }
476 HandleKind::Control => {
477 let d = r * 0.8;
479 let pts = vec![
480 pos + vec2(0.0, -d),
481 pos + vec2(d, 0.0),
482 pos + vec2(0.0, d),
483 pos + vec2(-d, 0.0),
484 ];
485 painter.add(egui::Shape::convex_polygon(pts, fill, outline));
486 }
487 HandleKind::Point | HandleKind::Size => {
488 painter.circle(pos, r, fill, outline);
489 }
490 }
491}
492
493const FAINT: f32 = 0.45;
495
496const DASH: [f32; 2] = [6.0, 4.0];
498
499fn outline(shape: &Shape, m: &Mapping) -> Option<(Vec<Pos2>, bool)> {
502 let s = |p: [f64; 2]| m.image_to_screen(p);
503 Some(match shape {
504 Shape::Point(_) => return None,
505 Shape::Line(a, b) => (vec![s(*a), s(*b)], false),
506 Shape::Rect(r) => (
507 vec![
508 s([r[0], r[1]]),
509 s([r[2], r[1]]),
510 s([r[2], r[3]]),
511 s([r[0], r[3]]),
512 ],
513 true,
514 ),
515 Shape::Circle { center, radius } => (
516 ellipse_points(*center, [*radius, *radius], 0.0, CURVE_POINTS)
517 .into_iter()
518 .map(s)
519 .collect(),
520 true,
521 ),
522 Shape::Ellipse {
523 center,
524 radii,
525 rotation,
526 } => (
527 ellipse_points(*center, *radii, *rotation, CURVE_POINTS)
528 .into_iter()
529 .map(s)
530 .collect(),
531 true,
532 ),
533 Shape::Path { points, closed } => (points.iter().map(|p| s(*p)).collect(), *closed),
534 })
535}
536
537const CURVE_POINTS: usize = 96;
539
540fn polyline(painter: &Painter, mut pts: Vec<Pos2>, closed: bool, stroke: Stroke, dashed: bool) {
542 if dashed {
543 if closed && let Some(first) = pts.first().copied() {
544 pts.push(first);
545 }
546 painter.extend(egui::Shape::dashed_line(&pts, stroke, DASH[0], DASH[1]));
547 } else if closed {
548 painter.add(egui::Shape::closed_line(pts, stroke));
549 } else {
550 painter.add(egui::Shape::line(pts, stroke));
551 }
552}
553
554pub fn paint_shape(painter: &Painter, m: &Mapping, o: &Overlay, t: &ViewportTokens) {
557 let s = |p: [f64; 2]| m.image_to_screen(p);
558 let w = |x: f32| snapped(painter, x);
559 let (line_color, line_width, alpha) = match o.style.emphasis {
560 Emphasis::Normal => (t.guide, LINE_WIDTH, 1.0),
561 Emphasis::Selected => (t.handle, LINE_WIDTH + 0.5, 1.0),
562 Emphasis::Faint => (t.guide, LINE_WIDTH, FAINT),
563 };
564 let under = Stroke::new(
565 w(UNDER_WIDTH + line_width - LINE_WIDTH),
566 t.handle_outline.gamma_multiply(alpha),
567 );
568 let over = Stroke::new(w(line_width), line_color.gamma_multiply(alpha));
569 let dashed = o.style.dashed;
570 match outline(&o.shape, m) {
571 Some((pts, closed)) => {
572 for stroke in [under, over] {
573 polyline(painter, pts.clone(), closed, stroke, dashed);
574 }
575 }
576 None => {
577 let c = s(first_point(&o.shape));
578 for stroke in [under, over] {
579 for (a, b) in [
580 (vec2(-6.0, 0.0), vec2(6.0, 0.0)),
581 (vec2(0.0, -6.0), vec2(0.0, 6.0)),
582 ] {
583 polyline(painter, vec![c + a, c + b], false, stroke, false);
584 }
585 }
586 }
587 }
588 if let Some(label) = &o.label {
589 let at = o
590 .handles
591 .first()
592 .map_or_else(|| first_point(&o.shape), |h| h.at);
593 let mut painter = painter.clone();
594 painter.multiply_opacity(alpha);
595 paint_label(
596 &painter,
597 s(at) + vec2(8.0, -8.0),
598 egui::Align2::LEFT_BOTTOM,
599 label,
600 );
601 }
602}
603
604pub fn paint_label(
613 painter: &Painter,
614 at: Pos2,
615 anchor: egui::Align2,
616 text: impl Into<String>,
617) -> egui::Rect {
618 let ctx = painter.ctx();
619 let kit = egui_pop_core::kit::Kit::of(ctx);
620 let c = &kit.viewport_label;
621 let size = if c.data.font_size > 0.0 {
622 c.data.font_size
623 } else {
624 egui_pop_core::theme::Tokens::of(ctx).font.small
625 };
626 let galley = painter.layout_no_wrap(
627 text.into(),
628 egui::FontId::proportional(size),
629 Color32::PLACEHOLDER,
630 );
631 let rect = anchor.anchor_size(at, c.measure(galley.size()));
632 c.paint_part(
633 &egui_pop_core::kit::KitCx {
634 painter,
635 ppp: ctx.pixels_per_point(),
636 },
637 &egui_pop_core::kit::Part {
638 rect,
639 room: rect,
640 state: egui_pop_core::kit::State::REST,
641 label: Some(&galley),
642 },
643 );
644 rect
645}
646
647fn first_point(shape: &Shape) -> [f64; 2] {
648 match shape {
649 Shape::Point(p) | Shape::Line(p, _) => *p,
650 Shape::Rect(r) => [r[0], r[1]],
651 Shape::Circle { center, .. } | Shape::Ellipse { center, .. } => *center,
652 Shape::Path { points, .. } => points.first().copied().unwrap_or([0.0, 0.0]),
653 }
654}
655
656pub const EDGE_RADIUS: f32 = 6.0;
658
659pub fn hit_edge(overlays: &[Overlay], m: &Mapping, pos: Pos2) -> Option<(usize, u32, [f64; 2])> {
665 for (i, o) in overlays.iter().enumerate().rev() {
666 if o.handles.is_empty() {
667 continue;
668 }
669 let Some((pts, closed)) = outline(&o.shape, m) else {
670 continue;
671 };
672 let curve = matches!(o.shape, Shape::Circle { .. } | Shape::Ellipse { .. });
673 let n = pts.len();
674 let count = if closed { n } else { n.saturating_sub(1) };
675 let mut best: Option<(u32, Pos2, f32)> = None;
676 for k in 0..count {
677 let (a, b) = (pts[k], pts[(k + 1) % n]);
678 let ab = b - a;
679 let t = if ab.length_sq() > 0.0 {
680 ((pos - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0)
681 } else {
682 0.0
683 };
684 let near = a + ab * t;
685 let d = near.distance(pos);
686 if d <= EDGE_RADIUS && best.is_none_or(|b| d < b.2) {
687 let segment = if curve { 0 } else { k as u32 };
688 best = Some((segment, near, d));
689 }
690 }
691 if let Some((segment, near, _)) = best {
692 return Some((i, segment, m.screen_to_image(near)));
693 }
694 }
695 None
696}
697
698pub fn hit(overlays: &[Overlay], m: &Mapping, pos: Pos2) -> Option<(usize, Handle)> {
700 let mut best: Option<(usize, Handle, f32)> = None;
701 for (i, o) in overlays.iter().enumerate().rev() {
702 for h in &o.handles {
703 let d = m.image_to_screen(h.at).distance(pos);
704 if d <= HIT_RADIUS && best.as_ref().is_none_or(|b| d < b.2) {
705 best = Some((i, *h, d));
706 }
707 }
708 if best.is_some() {
709 break;
710 }
711 }
712 best.map(|(i, h, _)| (i, h))
713}
714
715#[cfg(test)]
716mod tests {
717 use super::*;
718
719 #[test]
720 fn a_box_follows_its_corner_edge_and_body() {
721 let r = Shape::Rect([10.0, 10.0, 50.0, 30.0]);
722 assert_eq!(
723 r.moved(2, [50.0, 30.0], [60.0, 40.0]),
724 Shape::Rect([10.0, 10.0, 60.0, 40.0])
725 );
726 assert_eq!(
727 r.moved(7, [10.0, 20.0], [5.0, 99.0]),
728 Shape::Rect([5.0, 10.0, 50.0, 30.0])
729 );
730 assert_eq!(
731 r.moved(8, [30.0, 20.0], [31.0, 22.0]),
732 Shape::Rect([11.0, 12.0, 51.0, 32.0])
733 );
734 assert_eq!(
736 r.moved(0, [10.0, 10.0], [70.0, 50.0]),
737 Shape::Rect([50.0, 30.0, 70.0, 50.0])
738 );
739 }
740
741 #[test]
742 fn an_ellipse_sizes_along_its_axes_and_turns() {
743 let e = Shape::Ellipse {
744 center: [0.0, 0.0],
745 radii: [10.0, 5.0],
746 rotation: 0.0,
747 };
748 let h = e.handles();
749 assert_eq!(h.len(), 4);
750 assert_eq!(h[1].at, [10.0, 0.0]);
751 assert_eq!(h[3].kind, HandleKind::Rotate);
752 assert_eq!(
754 e.moved(1, [10.0, 0.0], [20.0, 7.0]),
755 Shape::Ellipse {
756 center: [0.0, 0.0],
757 radii: [20.0, 5.0],
758 rotation: 0.0
759 }
760 );
761 let Shape::Ellipse { rotation, .. } = e.moved(3, h[3].at, [8.0, 0.0]) else {
763 panic!()
764 };
765 assert!((rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9);
766 let turned = Shape::Ellipse {
767 center: [0.0, 0.0],
768 radii: [10.0, 5.0],
769 rotation,
770 };
771 let h = turned.handles();
772 assert!((h[1].at[0]).abs() < 1e-9 && (h[1].at[1] - 10.0).abs() < 1e-9);
773 }
774
775 #[test]
776 fn a_circle_sizes_from_its_size_handle() {
777 let c = Shape::Circle {
778 center: [0.0, 0.0],
779 radius: 5.0,
780 };
781 assert_eq!(
782 c.moved(1, [5.0, 0.0], [0.0, 12.0]),
783 Shape::Circle {
784 center: [0.0, 0.0],
785 radius: 12.0
786 }
787 );
788 }
789}