waterui-shape 0.1.2

Shape primitives and filled shapes for WaterUI using Lyon tessellation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
//! Shape system for `WaterUI` with HDR support.
//!
//! This module provides a trait-based system for defining shapes that can be used
//! for clipping views and as filled views.
//!
//! Filled shapes are emitted as native `ResolvedShape` raw views so each backend
//! renders paths with its own 2D engine. Morphing shapes stay GPU-backed.
//!
//! # Example
//!
//! ```rust,ignore
//! use waterui::prelude::*;
//! use waterui::shape::*;
//!
//! // Clip to a circle
//! image("avatar.jpg").clip(Circle);
//!
//! // Fill a shape with HDR color
//! Circle.fill(Color::red().with_headroom(0.5))
//! ```

extern crate alloc;

use core::f32::consts::{FRAC_PI_2, PI, TAU};
#[cfg(feature = "gpu")]
use core::fmt;
use core::time::Duration;
#[cfg(feature = "gpu")]
use num_traits::ToPrimitive;
#[cfg(feature = "gpu")]
use std::time::Instant;

#[cfg(feature = "gpu")]
use nami::Signal as _;
use nami::{Computed, SignalExt as _, signal::IntoComputed};
#[cfg(feature = "gpu")]
use shaderloom::CompiledShader;
#[cfg(feature = "gpu")]
use waterui_core::reactive::watcher::BoxWatcherGuard;
use waterui_core::{Environment, View, easing::EasingCurve, metadata::MetadataKey};
use waterui_graphics::color::Color;
#[cfg(feature = "gpu")]
use waterui_graphics::{
    GpuContext, GpuFrame, GpuSurface, GpuView, reactive_color::ReactiveColor,
    single_bind_group_render_stages,
};

#[cfg(feature = "gpu")]
const MORPH_SHADER: CompiledShader = include!(concat!(env!("OUT_DIR"), "/morph.rs"));

// ============================================================================
// PathCommand - The primitive operations for drawing paths
// ============================================================================

/// A single path command for drawing shapes.
///
/// All coordinates are normalized (0.0-1.0) and scale with view bounds.
/// Native backends convert these to absolute coordinates based on view size.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum PathCommand {
    /// Move to a position without drawing.
    MoveTo {
        /// X coordinate (normalized 0.0-1.0)
        x: f32,
        /// Y coordinate (normalized 0.0-1.0)
        y: f32,
    },

    /// Draw a straight line to a position.
    LineTo {
        /// X coordinate (normalized 0.0-1.0)
        x: f32,
        /// Y coordinate (normalized 0.0-1.0)
        y: f32,
    },

    /// Draw a quadratic bezier curve.
    QuadTo {
        /// Control point x
        cx: f32,
        /// Control point y
        cy: f32,
        /// End point x
        x: f32,
        /// End point y
        y: f32,
    },

    /// Draw a cubic bezier curve.
    CubicTo {
        /// First control point x
        c1x: f32,
        /// First control point y
        c1y: f32,
        /// Second control point x
        c2x: f32,
        /// Second control point y
        c2y: f32,
        /// End point x
        x: f32,
        /// End point y
        y: f32,
    },

    /// Draw an arc.
    Arc {
        /// Center x (normalized)
        cx: f32,
        /// Center y (normalized)
        cy: f32,
        /// Radius x (normalized, relative to width)
        rx: f32,
        /// Radius y (normalized, relative to height)
        ry: f32,
        /// Start angle in radians
        start: f32,
        /// Sweep angle in radians (positive = clockwise)
        sweep: f32,
    },

    /// Close the current subpath by drawing a line to the start.
    Close,
}

#[inline]
const fn clamp_radius(value: f32) -> f32 {
    if value.is_finite() {
        value.clamp(0.0, 0.5)
    } else {
        0.0
    }
}

#[derive(Debug, Clone, Copy)]
struct CornerRadii {
    top_left: f32,
    top_right: f32,
    bottom_right: f32,
    bottom_left: f32,
}

impl CornerRadii {
    #[inline]
    fn sanitized(mut self) -> Self {
        self.top_left = clamp_radius(self.top_left);
        self.top_right = clamp_radius(self.top_right);
        self.bottom_right = clamp_radius(self.bottom_right);
        self.bottom_left = clamp_radius(self.bottom_left);

        // Prevent overlapping corner arcs (same behavior as CSS border-radius normalization).
        let mut scale = 1.0f32;
        let pairs = [
            self.top_left + self.top_right,
            self.bottom_left + self.bottom_right,
            self.top_left + self.bottom_left,
            self.top_right + self.bottom_right,
        ];
        for sum in pairs {
            if sum > 1.0 {
                scale = scale.min(1.0 / sum);
            }
        }
        if scale < 1.0 {
            self.top_left *= scale;
            self.top_right *= scale;
            self.bottom_right *= scale;
            self.bottom_left *= scale;
        }
        self
    }
}

// ============================================================================
// Shape Trait
// ============================================================================

/// A trait for types that can produce path commands for clipping.
///
/// All coordinates are normalized (0.0-1.0) and scale with view bounds.
/// Built-in shapes use stack-allocated arrays for zero heap allocation.
pub trait Shape {
    /// The iterator type returned by `path()`.
    type Iter: IntoIterator<Item = PathCommand>;

    /// Returns the path commands that define this shape.
    fn path(&self) -> Self::Iter;

    /// Returns what this shape *is*, for backends that can render it directly.
    ///
    /// Prefer this over [`Self::path`] wherever a backend can act on it. Path
    /// commands are normalized per axis, so resolving them against a non-square
    /// rect makes circular corners elliptical; the kind lets a backend resolve a
    /// normalized radius against the shorter side instead. Defaults to
    /// [`ShapeKind::CustomPath`], which means "only the path describes me".
    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::CustomPath
    }
}

// ============================================================================
// Common Shape Implementations
// ============================================================================

/// A circle inscribed in the view bounds.
#[derive(Debug, Clone, Copy, Default)]
pub struct Circle;

impl Shape for Circle {
    type Iter = [PathCommand; 1];

    fn path(&self) -> Self::Iter {
        [PathCommand::Arc {
            cx: 0.5,
            cy: 0.5,
            rx: 0.5,
            ry: 0.5,
            start: 0.0,
            sweep: TAU,
        }]
    }

    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::Circle
    }
}

/// An ellipse that fills the view bounds.
#[derive(Debug, Clone, Copy, Default)]
pub struct Ellipse;

impl Shape for Ellipse {
    type Iter = [PathCommand; 1];

    fn path(&self) -> Self::Iter {
        [PathCommand::Arc {
            cx: 0.5,
            cy: 0.5,
            rx: 0.5,
            ry: 0.5,
            start: 0.0,
            sweep: TAU,
        }]
    }

    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::Ellipse
    }
}

/// A capsule (pill) shape.
#[derive(Debug, Clone, Copy, Default)]
pub struct Capsule;

impl Shape for Capsule {
    type Iter = [PathCommand; 4];

    /// Unit-space approximation only — an ellipse inscribed in the box.
    ///
    /// A pill's caps are half its *shorter* side, which normalized per-axis
    /// coordinates cannot express without knowing the aspect ratio. Backends
    /// must render a capsule from [`ShapeKind::Capsule`], not from these
    /// commands.
    fn path(&self) -> Self::Iter {
        [
            PathCommand::MoveTo { x: 0.5, y: 0.0 },
            PathCommand::Arc {
                cx: 0.5,
                cy: 0.5,
                rx: 0.5,
                ry: 0.5,
                start: -FRAC_PI_2,
                sweep: PI,
            },
            PathCommand::Arc {
                cx: 0.5,
                cy: 0.5,
                rx: 0.5,
                ry: 0.5,
                start: FRAC_PI_2,
                sweep: PI,
            },
            PathCommand::Close,
        ]
    }

    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::Capsule
    }
}

/// A rectangle with uniform corner radius.
#[derive(Debug, Clone, Copy)]
pub struct RoundedRectangle {
    /// Corner radius (normalized, 0.0-0.5 range).
    pub corner_radius: f32,
}

impl RoundedRectangle {
    /// Creates a new rounded rectangle with the given corner radius.
    ///
    /// The radius is **normalized**, not a length: it is a fraction of the
    /// shape's shorter side, so `0.5` is fully rounded and anything above that
    /// saturates there. Passing a point value (`28.0` for a 56pt-tall row)
    /// therefore lands on `0.5` rather than failing, which is only what was
    /// intended when the shape happens to be that tall.
    ///
    /// Reach for [`Capsule`] when the intent is "fully rounded at whatever size
    /// this ends up": it says so directly and cannot drift as the shape resizes.
    #[must_use]
    pub const fn new(corner_radius: f32) -> Self {
        Self { corner_radius }
    }
}

impl Shape for RoundedRectangle {
    type Iter = [PathCommand; 10];

    fn path(&self) -> Self::Iter {
        let r = CornerRadii {
            top_left: self.corner_radius,
            top_right: self.corner_radius,
            bottom_right: self.corner_radius,
            bottom_left: self.corner_radius,
        }
        .sanitized()
        .top_left;
        [
            PathCommand::MoveTo { x: r, y: 0.0 },
            PathCommand::LineTo { x: 1.0 - r, y: 0.0 },
            PathCommand::Arc {
                cx: 1.0 - r,
                cy: r,
                rx: r,
                ry: r,
                start: -FRAC_PI_2,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo { x: 1.0, y: 1.0 - r },
            PathCommand::Arc {
                cx: 1.0 - r,
                cy: 1.0 - r,
                rx: r,
                ry: r,
                start: 0.0,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo { x: r, y: 1.0 },
            PathCommand::Arc {
                cx: r,
                cy: 1.0 - r,
                rx: r,
                ry: r,
                start: FRAC_PI_2,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo { x: 0.0, y: r },
            PathCommand::Arc {
                cx: r,
                cy: r,
                rx: r,
                ry: r,
                start: PI,
                sweep: FRAC_PI_2,
            },
            PathCommand::Close,
        ]
    }

    fn shape_kind(&self) -> ShapeKind {
        let r = CornerRadii {
            top_left: self.corner_radius,
            top_right: self.corner_radius,
            bottom_right: self.corner_radius,
            bottom_left: self.corner_radius,
        }
        .sanitized()
        .top_left;
        ShapeKind::RoundedRect { corner_radius: r }
    }
}

/// A rectangle with independent corner radii.
#[derive(Debug, Clone, Copy)]
pub struct UnevenRoundedRectangle {
    /// Top-leading corner radius (normalized).
    pub top_leading: f32,
    /// Top-trailing corner radius (normalized).
    pub top_trailing: f32,
    /// Bottom-leading corner radius (normalized).
    pub bottom_leading: f32,
    /// Bottom-trailing corner radius (normalized).
    pub bottom_trailing: f32,
}

impl UnevenRoundedRectangle {
    /// Creates a new uneven rounded rectangle with independent corner radii.
    #[must_use]
    pub const fn new(
        top_leading: f32,
        top_trailing: f32,
        bottom_leading: f32,
        bottom_trailing: f32,
    ) -> Self {
        Self {
            top_leading,
            top_trailing,
            bottom_leading,
            bottom_trailing,
        }
    }
}

impl Shape for UnevenRoundedRectangle {
    type Iter = [PathCommand; 10];

    fn path(&self) -> Self::Iter {
        let corners = CornerRadii {
            top_left: self.top_leading,
            top_right: self.top_trailing,
            bottom_right: self.bottom_trailing,
            bottom_left: self.bottom_leading,
        }
        .sanitized();
        let tl = corners.top_left;
        let tr = corners.top_right;
        let bl = corners.bottom_left;
        let br = corners.bottom_right;
        [
            PathCommand::MoveTo { x: tl, y: 0.0 },
            PathCommand::LineTo {
                x: 1.0 - tr,
                y: 0.0,
            },
            PathCommand::Arc {
                cx: 1.0 - tr,
                cy: tr,
                rx: tr,
                ry: tr,
                start: -FRAC_PI_2,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo {
                x: 1.0,
                y: 1.0 - br,
            },
            PathCommand::Arc {
                cx: 1.0 - br,
                cy: 1.0 - br,
                rx: br,
                ry: br,
                start: 0.0,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo { x: bl, y: 1.0 },
            PathCommand::Arc {
                cx: bl,
                cy: 1.0 - bl,
                rx: bl,
                ry: bl,
                start: FRAC_PI_2,
                sweep: FRAC_PI_2,
            },
            PathCommand::LineTo { x: 0.0, y: tl },
            PathCommand::Arc {
                cx: tl,
                cy: tl,
                rx: tl,
                ry: tl,
                start: PI,
                sweep: FRAC_PI_2,
            },
            PathCommand::Close,
        ]
    }

    fn shape_kind(&self) -> ShapeKind {
        let corners = CornerRadii {
            top_left: self.top_leading,
            top_right: self.top_trailing,
            bottom_right: self.bottom_trailing,
            bottom_left: self.bottom_leading,
        }
        .sanitized();
        ShapeKind::UnevenRoundedRect {
            top_left: corners.top_left,
            top_right: corners.top_right,
            bottom_left: corners.bottom_left,
            bottom_right: corners.bottom_right,
        }
    }
}

/// A simple rectangle with sharp corners.
#[derive(Debug, Clone, Copy, Default)]
pub struct Rectangle;

impl Shape for Rectangle {
    type Iter = [PathCommand; 5];

    fn path(&self) -> Self::Iter {
        [
            PathCommand::MoveTo { x: 0.0, y: 0.0 },
            PathCommand::LineTo { x: 1.0, y: 0.0 },
            PathCommand::LineTo { x: 1.0, y: 1.0 },
            PathCommand::LineTo { x: 0.0, y: 1.0 },
            PathCommand::Close,
        ]
    }

    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::Rect
    }
}

// ============================================================================
// Custom Path Builder
// ============================================================================

/// A custom path defined by explicit commands.
#[derive(Debug, Clone, Default)]
pub struct Path {
    commands: Vec<PathCommand>,
}

impl Path {
    /// Creates a new empty path.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Moves to a position without drawing.
    #[must_use]
    pub fn move_to(mut self, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::MoveTo { x, y });
        self
    }

    /// Draws a straight line to a position.
    #[must_use]
    pub fn line_to(mut self, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::LineTo { x, y });
        self
    }

    /// Draws a quadratic bezier curve.
    #[must_use]
    pub fn quad_to(mut self, cx: f32, cy: f32, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::QuadTo { cx, cy, x, y });
        self
    }

    /// Draws a cubic bezier curve.
    #[must_use]
    pub fn cubic_to(mut self, c1x: f32, c1y: f32, c2x: f32, c2y: f32, x: f32, y: f32) -> Self {
        self.commands.push(PathCommand::CubicTo {
            c1x,
            c1y,
            c2x,
            c2y,
            x,
            y,
        });
        self
    }

    /// Draws an arc.
    #[must_use]
    pub fn arc(mut self, cx: f32, cy: f32, rx: f32, ry: f32, start: f32, sweep: f32) -> Self {
        self.commands.push(PathCommand::Arc {
            cx,
            cy,
            rx,
            ry,
            start,
            sweep,
        });
        self
    }

    /// Closes the current subpath.
    #[must_use]
    pub fn close(mut self) -> Self {
        self.commands.push(PathCommand::Close);
        self
    }
}

impl Shape for Path {
    type Iter = alloc::vec::IntoIter<PathCommand>;

    fn path(&self) -> Self::Iter {
        self.commands.clone().into_iter()
    }

    fn shape_kind(&self) -> ShapeKind {
        ShapeKind::CustomPath
    }
}

// ============================================================================
// ClipShape Metadata
// ============================================================================

/// Metadata for clipping a view to a shape.
///
/// Carries both the structured [`ShapeKind`] and the unit-space path. Backends
/// should prefer the kind: [`PathCommand`] coordinates are normalized per axis,
/// so resolving them against a non-square rect turns a circular corner into an
/// elliptical one — a fully-rounded clip comes out as an ellipse instead of a
/// pill. The kind says what the shape *is*, letting a backend resolve a
/// normalized radius against the shorter side the way [`FilledShape`] already
/// does. The commands remain the fallback for [`ShapeKind::CustomPath`].
#[derive(Debug)]
pub struct ClipShape {
    kind: ShapeKind,
    commands: Vec<PathCommand>,
}

impl ClipShape {
    /// Creates a new clip shape from any type implementing Shape.
    #[allow(clippy::needless_pass_by_value)]
    pub fn new(shape: impl Shape) -> Self {
        Self {
            kind: shape.shape_kind(),
            commands: shape.path().into_iter().collect(),
        }
    }

    /// Returns the structured shape kind. Prefer this over [`Self::commands`];
    /// see the type documentation.
    #[must_use]
    pub const fn kind(&self) -> ShapeKind {
        self.kind
    }

    /// Returns the unit-space path commands.
    #[must_use]
    pub fn commands(&self) -> &[PathCommand] {
        &self.commands
    }
}

impl MetadataKey for ClipShape {}

// ============================================================================
// ShapeKind - For backend rendering optimization
// ============================================================================

/// The kind of shape for backend rendering optimization.
#[derive(Debug, Clone, Copy, Default)]
pub enum ShapeKind {
    /// Rectangle with sharp corners.
    #[default]
    Rect,
    /// Circle inscribed in bounds.
    Circle,
    /// Ellipse filling bounds.
    Ellipse,
    /// Rectangle with uniform corner radius.
    RoundedRect {
        /// Corner radius (normalized 0.0-0.5).
        corner_radius: f32,
    },
    /// Rectangle with per-corner radii.
    UnevenRoundedRect {
        /// Top-left corner radius.
        top_left: f32,
        /// Top-right corner radius.
        top_right: f32,
        /// Bottom-left corner radius.
        bottom_left: f32,
        /// Bottom-right corner radius.
        bottom_right: f32,
    },
    /// Capsule (pill) shape.
    Capsule,
    /// Custom path.
    CustomPath,
}

/// Resolved shape payload rendered directly by native backends.
#[derive(Debug, Clone)]
pub struct ResolvedShape {
    /// Shape kind for backend-side optimization.
    pub kind: ShapeKind,
    /// Path commands in unit coordinate space.
    pub commands: Vec<PathCommand>,
    /// Environment-resolved fill color that remains reactive to theme changes.
    pub fill: Computed<waterui_graphics::ResolvedColor>,
}

waterui_core::raw_view!(ResolvedShape, waterui_core::layout::StretchAxis::Both);

/// Resolved morphing shape payload rendered directly by capable backends.
#[derive(Debug, Clone)]
pub struct ResolvedMorphShape {
    /// Source shape kind.
    pub from: ShapeKind,
    /// Target shape kind.
    pub to: ShapeKind,
    /// Environment-resolved fill color that remains reactive to theme changes.
    pub fill: Computed<waterui_graphics::ResolvedColor>,
    /// Time-based morph animation configuration.
    pub animation: MorphAnimation,
    /// Optional explicit progress signal.
    pub progress: Option<Computed<f32>>,
}

impl waterui_core::NativeView for ResolvedMorphShape {
    fn stretch_axis(&self) -> waterui_core::layout::StretchAxis {
        waterui_core::layout::StretchAxis::Both
    }
}

// ============================================================================
// FilledShape - Shape as a View with backend-native fill rendering
// ============================================================================

/// A shape filled with a color, resolved to `ResolvedShape`.
#[derive(Debug)]
pub struct FilledShape {
    kind: ShapeKind,
    commands: Vec<PathCommand>,
    fill: Color,
}

impl FilledShape {
    /// Creates a new filled shape from a shape and color.
    #[allow(clippy::needless_pass_by_value)]
    pub fn new(shape: impl Shape, fill: impl Into<Color>) -> Self {
        Self {
            kind: ShapeKind::CustomPath,
            commands: shape.path().into_iter().collect(),
            fill: fill.into(),
        }
    }

    #[allow(clippy::needless_pass_by_value)]
    fn with_kind(kind: ShapeKind, shape: impl Shape, fill: impl Into<Color>) -> Self {
        Self {
            kind,
            commands: shape.path().into_iter().collect(),
            fill: fill.into(),
        }
    }

    /// Returns the path commands.
    #[must_use]
    pub fn commands(&self) -> &[PathCommand] {
        &self.commands
    }

    /// Returns the fill color.
    #[must_use]
    pub const fn fill(&self) -> &Color {
        &self.fill
    }

    /// Returns the shape kind.
    #[must_use]
    pub const fn kind(&self) -> ShapeKind {
        self.kind
    }

    /// Creates a morphing shape animation from this shape to another built-in shape.
    ///
    /// Morphing currently supports SDF-backed built-in shapes:
    /// `Rectangle`, `Circle`, `Ellipse`, `RoundedRectangle`, `UnevenRoundedRectangle`, `Capsule`.
    #[must_use]
    #[allow(clippy::needless_pass_by_value)]
    pub fn morph_to(self, target: impl ShapeExt) -> MorphShape {
        MorphShape::new(self.kind, target.shape_kind(), self.fill)
    }
}

/// Configuration for shape morph animations.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MorphAnimation {
    /// Duration of one forward morph cycle.
    pub duration: Duration,
    /// Easing curve applied to normalized cycle progress.
    pub easing: EasingCurve,
    /// Whether the animation repeats after reaching the end.
    pub repeat: bool,
    /// Whether repeating animation should play in reverse every other cycle.
    pub autoreverse: bool,
}

impl Default for MorphAnimation {
    fn default() -> Self {
        Self {
            duration: Duration::from_millis(900),
            easing: EasingCurve::EASE_IN_OUT,
            repeat: true,
            autoreverse: true,
        }
    }
}

impl MorphAnimation {
    /// Creates a one-shot morph animation.
    #[must_use]
    pub const fn once(duration: Duration, easing: EasingCurve) -> Self {
        Self {
            duration,
            easing,
            repeat: false,
            autoreverse: false,
        }
    }

    #[cfg(feature = "gpu")]
    #[must_use]
    fn sample(self, elapsed: Duration) -> f32 {
        if self.duration.is_zero() {
            return 1.0;
        }
        let raw = elapsed.as_secs_f32() / self.duration.as_secs_f32();
        let cycle = if self.repeat {
            let base = raw.fract();
            let index = raw
                .floor()
                .to_u64()
                .expect("MorphAnimation::sample: cycle index must fit into u64");
            if self.autoreverse && index % 2 == 1 {
                1.0 - base
            } else {
                base
            }
        } else {
            raw.clamp(0.0, 1.0)
        };
        self.easing.ease(cycle).clamp(0.0, 1.0)
    }
}

/// A morphing filled shape view.
#[derive(Debug, Clone)]
pub struct MorphShape {
    from: ShapeKind,
    to: ShapeKind,
    fill: Color,
    animation: MorphAnimation,
    progress: Option<Computed<f32>>,
}

impl MorphShape {
    fn new(from: ShapeKind, to: ShapeKind, fill: Color) -> Self {
        Self {
            from,
            to,
            fill,
            animation: MorphAnimation::default(),
            progress: None,
        }
    }

    /// Sets explicit animation configuration.
    #[must_use]
    pub const fn animation(mut self, animation: MorphAnimation) -> Self {
        self.animation = animation;
        self
    }

    /// Sets the cycle duration (keeps other animation options unchanged).
    #[must_use]
    pub const fn duration(mut self, duration: Duration) -> Self {
        self.animation.duration = duration;
        self
    }

    /// Sets easing (keeps other animation options unchanged).
    #[must_use]
    pub const fn easing(mut self, easing: EasingCurve) -> Self {
        self.animation.easing = easing;
        self
    }

    /// Enables/disables repeating.
    #[must_use]
    pub const fn repeat(mut self, repeat: bool) -> Self {
        self.animation.repeat = repeat;
        self
    }

    /// Enables/disables autoreverse for repeating animations.
    #[must_use]
    pub const fn autoreverse(mut self, autoreverse: bool) -> Self {
        self.animation.autoreverse = autoreverse;
        self
    }

    /// Overrides animated progress with an explicit reactive progress signal `[0, 1]`.
    ///
    /// When set, this takes precedence over the time-based animation config.
    #[must_use]
    pub fn progress(mut self, progress: impl IntoComputed<f32>) -> Self {
        self.progress = Some(progress.into_computed());
        self
    }
}

impl View for FilledShape {
    fn body(self, env: &Environment) -> impl View {
        ResolvedShape {
            kind: self.kind,
            commands: self.commands,
            fill: self.fill.resolve(env).computed(),
        }
    }
}

impl View for MorphShape {
    fn body(self, env: &Environment) -> impl View {
        let resolved = self.fill.resolve(env).computed();
        // The GPU fallback renderer also consumes `progress`, so clone it
        // only on that path; the lean path moves it into the native node.
        #[cfg(feature = "gpu")]
        let progress_for_gpu = self.progress.clone();
        let native = waterui_core::Native::new(ResolvedMorphShape {
            from: self.from,
            to: self.to,
            fill: resolved,
            animation: self.animation,
            progress: self.progress,
        });
        #[cfg(feature = "gpu")]
        let native = native.with_fallback(GpuSurface::new(MorphShapeRenderer::new(
            kind_to_morph_shape(self.from)
                .expect("morph source shape must be a built-in morphable shape"),
            kind_to_morph_shape(self.to)
                .expect("morph target shape must be a built-in morphable shape"),
            ReactiveColor::new(&Computed::constant(self.fill), env),
            self.animation,
            progress_for_gpu,
        )));
        native
    }
}

// ============================================================================
// MorphShapeRenderer - SDF morphing for built-in shapes
// ============================================================================

#[cfg(feature = "gpu")]
#[derive(Debug, Clone, Copy)]
struct MorphSdfShape {
    shape_type: u32,
    radii: [f32; 4],
}

#[cfg(feature = "gpu")]
fn kind_to_morph_shape(kind: ShapeKind) -> Option<MorphSdfShape> {
    match kind {
        ShapeKind::Rect => Some(MorphSdfShape {
            shape_type: 0,
            radii: [0.0; 4],
        }),
        ShapeKind::Circle => Some(MorphSdfShape {
            shape_type: 1,
            radii: [0.0; 4],
        }),
        ShapeKind::Ellipse => Some(MorphSdfShape {
            shape_type: 2,
            radii: [0.0; 4],
        }),
        ShapeKind::RoundedRect { corner_radius } => Some(MorphSdfShape {
            shape_type: 3,
            radii: [clamp_radius(corner_radius); 4],
        }),
        ShapeKind::UnevenRoundedRect {
            top_left,
            top_right,
            bottom_left,
            bottom_right,
        } => {
            let corners = CornerRadii {
                top_left,
                top_right,
                bottom_right,
                bottom_left,
            }
            .sanitized();
            Some(MorphSdfShape {
                shape_type: 3,
                radii: [
                    corners.top_left,
                    corners.top_right,
                    corners.bottom_right,
                    corners.bottom_left,
                ],
            })
        }
        ShapeKind::Capsule => Some(MorphSdfShape {
            shape_type: 4,
            radii: [0.0; 4],
        }),
        ShapeKind::CustomPath => None,
    }
}

#[cfg(feature = "gpu")]
#[repr(C)]
#[derive(Debug, Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
struct MorphUniforms {
    color: [f32; 4],
    dimensions_and_progress: [f32; 4], // width, height, progress, pad
    shape_types: [f32; 4],             // from_type, to_type, pad, pad
    from_radii: [f32; 4],              // tl, tr, br, bl
    to_radii: [f32; 4],                // tl, tr, br, bl
}

#[cfg(feature = "gpu")]
struct MorphShapeRenderer {
    from: MorphSdfShape,
    to: MorphSdfShape,
    fill_color: ReactiveColor,
    animation: MorphAnimation,
    progress: Option<Computed<f32>>,
    progress_guard: Option<BoxWatcherGuard>,
    start_time: Instant,
    pipeline: Option<wgpu::RenderPipeline>,
    uniform_buffer: Option<wgpu::Buffer>,
    bind_group: Option<wgpu::BindGroup>,
    pipeline_format: Option<wgpu::TextureFormat>,
}

#[cfg(feature = "gpu")]
impl fmt::Debug for MorphShapeRenderer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MorphShapeRenderer")
            .field("from", &self.from)
            .field("to", &self.to)
            .finish_non_exhaustive()
    }
}

#[cfg(feature = "gpu")]
impl MorphShapeRenderer {
    fn new(
        from: MorphSdfShape,
        to: MorphSdfShape,
        fill_color: ReactiveColor,
        animation: MorphAnimation,
        progress: Option<Computed<f32>>,
    ) -> Self {
        Self {
            from,
            to,
            fill_color,
            animation,
            progress,
            progress_guard: None,
            start_time: Instant::now(),
            pipeline: None,
            uniform_buffer: None,
            bind_group: None,
            pipeline_format: None,
        }
    }
}

#[cfg(feature = "gpu")]
impl GpuView for MorphShapeRenderer {
    fn setup(
        &mut self,
        ctx: &GpuContext<'_>,
        _env: &mut waterui_core::Environment,
    ) -> impl core::future::Future<Output = ()> {
        self.fill_color.install(&ctx.redraw_handle);
        if let Some(progress) = &self.progress {
            let redraw = ctx.redraw_handle.clone();
            self.progress_guard = Some(progress.watch(move |_| redraw.request_redraw()));
        }

        let (vertex_shader, fragment_shader, bind_group_layout) = single_bind_group_render_stages(
            &MORPH_SHADER,
            ctx.device,
            "the morph shape shader",
            "vs_main",
            "fs_main",
        );

        let uniform_buffer = ctx.device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("Morph Shape Uniforms"),
            size: core::mem::size_of::<MorphUniforms>() as u64,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let bind_group = ctx.device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("Morph Shape Bind Group"),
            layout: &bind_group_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: uniform_buffer.as_entire_binding(),
            }],
        });

        let pipeline_layout = ctx
            .device
            .create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
                label: Some("Morph Shape Pipeline Layout"),
                bind_group_layouts: &[Some(&bind_group_layout)],
                immediate_size: 0,
            });

        let blend = ctx.alpha_blend_state();

        let pipeline = ctx
            .device
            .create_render_pipeline(&wgpu::RenderPipelineDescriptor {
                label: Some("Morph Shape Pipeline"),
                layout: Some(&pipeline_layout),
                vertex: wgpu::VertexState {
                    module: vertex_shader.module(),
                    entry_point: Some(vertex_shader.entry_point()),
                    buffers: &[],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                },
                fragment: Some(wgpu::FragmentState {
                    module: fragment_shader.module(),
                    entry_point: Some(fragment_shader.entry_point()),
                    targets: &[Some(wgpu::ColorTargetState {
                        format: ctx.surface_format,
                        blend,
                        write_mask: wgpu::ColorWrites::ALL,
                    })],
                    compilation_options: wgpu::PipelineCompilationOptions::default(),
                }),
                primitive: wgpu::PrimitiveState {
                    topology: wgpu::PrimitiveTopology::TriangleList,
                    ..Default::default()
                },
                depth_stencil: None,
                multisample: wgpu::MultisampleState::default(),
                multiview_mask: None,
                cache: None,
            });

        self.pipeline = Some(pipeline);
        self.uniform_buffer = Some(uniform_buffer);
        self.bind_group = Some(bind_group);
        self.pipeline_format = Some(ctx.surface_format);
        self.start_time = Instant::now();
        core::future::ready(())
    }

    fn render(&mut self, frame: &mut GpuFrame) {
        assert_eq!(
            self.pipeline_format,
            Some(frame.format),
            "MorphShape target format changed after setup"
        );
        let pipeline = self
            .pipeline
            .as_ref()
            .expect("MorphShape render called before setup");
        let uniform_buffer = self
            .uniform_buffer
            .as_ref()
            .expect("MorphShape render called before setup");
        let bind_group = self
            .bind_group
            .as_ref()
            .expect("MorphShape render called before setup");

        let progress = if let Some(signal) = &self.progress {
            let value = signal.get();
            assert!(value.is_finite(), "MorphShape progress must be finite");
            value.clamp(0.0, 1.0)
        } else {
            self.animation.sample(self.start_time.elapsed())
        };

        let fill_color = self.fill_color.get();
        let [r, g, b] = fill_color.linear_with_headroom();
        let uniforms = MorphUniforms {
            color: [r, g, b, fill_color.opacity],
            dimensions_and_progress: [
                u32_to_f32(frame.width),
                u32_to_f32(frame.height),
                progress,
                0.0,
            ],
            shape_types: [
                u32_to_f32(self.from.shape_type),
                u32_to_f32(self.to.shape_type),
                0.0,
                0.0,
            ],
            from_radii: self.from.radii,
            to_radii: self.to.radii,
        };
        frame
            .queue
            .write_buffer(uniform_buffer, 0, bytemuck::bytes_of(&uniforms));

        let mut encoder = frame
            .device
            .create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("Morph Shape Encoder"),
            });

        {
            let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
                label: Some("Morph Shape Render Pass"),
                color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                    view: &frame.view,
                    depth_slice: None,
                    resolve_target: None,
                    ops: wgpu::Operations {
                        load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
                        store: wgpu::StoreOp::Store,
                    },
                })],
                depth_stencil_attachment: None,
                timestamp_writes: None,
                occlusion_query_set: None,
                multiview_mask: None,
            });

            render_pass.set_pipeline(pipeline);
            render_pass.set_bind_group(0, bind_group, &[]);
            render_pass.draw(0..6, 0..1);
        }

        frame.queue.submit(core::iter::once(encoder.finish()));

        // Request continuous redraw while animation is active
        let animation_active = self.progress.is_none()
            && (self.animation.repeat || self.start_time.elapsed() < self.animation.duration);
        if animation_active {
            frame.request_redraw();
        }
    }
}

#[cfg(feature = "gpu")]
fn u32_to_f32(value: u32) -> f32 {
    value
        .to_f32()
        .expect("shape dimensions must be representable as f32")
}

// ============================================================================
// ShapeExt - Extension trait for adding fill to shapes
// ============================================================================

/// Extension trait for filling shapes with color.
pub trait ShapeExt: Shape + Sized {
    /// Fills the shape with the specified color.
    fn fill(self, color: impl Into<Color>) -> FilledShape {
        FilledShape::with_kind(self.shape_kind(), self, color)
    }

    /// Creates a morphing filled shape from this shape to another built-in shape.
    ///
    /// Morphing currently supports SDF-backed built-in shapes:
    /// `Rectangle`, `Circle`, `Ellipse`, `RoundedRectangle`, `UnevenRoundedRectangle`, `Capsule`.
    fn morph_to(self, target: impl ShapeExt, fill: impl Into<Color>) -> MorphShape {
        MorphShape::new(self.shape_kind(), target.shape_kind(), fill.into())
    }
}

impl ShapeExt for Circle {}

impl ShapeExt for Ellipse {}

impl ShapeExt for Capsule {}

impl ShapeExt for Rectangle {}

impl ShapeExt for RoundedRectangle {}

impl ShapeExt for UnevenRoundedRectangle {}

impl ShapeExt for Path {}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn rounded_rectangle_radius_is_clamped() {
        let kind = RoundedRectangle::new(9.0).shape_kind();
        match kind {
            ShapeKind::RoundedRect { corner_radius } => {
                assert!((corner_radius - 0.5).abs() < 1e-6);
            }
            _ => panic!("unexpected kind"),
        }
    }

    #[test]
    fn uneven_radii_are_normalized_when_edges_overlap() {
        let kind = UnevenRoundedRectangle::new(0.8, 0.8, 0.8, 0.8).shape_kind();
        match kind {
            ShapeKind::UnevenRoundedRect {
                top_left,
                top_right,
                bottom_left,
                bottom_right,
            } => {
                assert!((top_left - 0.5).abs() < 1e-6);
                assert!((top_right - 0.5).abs() < 1e-6);
                assert!((bottom_left - 0.5).abs() < 1e-6);
                assert!((bottom_right - 0.5).abs() < 1e-6);
            }
            _ => panic!("unexpected kind"),
        }
    }

    #[cfg(feature = "gpu")]
    #[test]
    fn one_shot_animation_reaches_end() {
        let animation = MorphAnimation::once(Duration::from_millis(200), EasingCurve::LINEAR);
        assert!((animation.sample(Duration::ZERO) - 0.0).abs() < 1e-6);
        assert!((animation.sample(Duration::from_millis(100)) - 0.5).abs() < 1e-3);
        assert!((animation.sample(Duration::from_secs(1)) - 1.0).abs() < 1e-6);
    }
}