lievisual 0.1.0

Declarative visual scene IR + pluggable rendering backends (SVG / vello_cpu / GPU).
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
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
//! 声明式场景图 IR。
//!
//! 设计原则(参见 crate 文档):
//! - `z_index` 与 [`Transform`] 提升为 [`SceneNode`] 字段,而非每个图元重复携带。
//!   同理,`opacity` / `name` / `visible` 也属于节点(或整棵子树)属性。
//! - [`Element`] 枚举只描述几何与样式;新增图元变体时不影响层级/变换逻辑。
//! - 节点级 `opacity` 作用于整棵子树(Group 递归时逐层复合),`visible = false`
//!   时整棵子树跳过。
//! - 图层:`Scene` 可携带一组有序 [`Layer`](从底到顶)。图层整体控制
//!   `visible` / `opacity` / `transform`,层内节点再按 `z_index` 稳定排序;
//!   `Scene::nodes` 作为"默认层"(最底)保留,向后兼容。
//! - [`Element::Text`] 以样式化片段([`crate::text::RichSpan`])为核心表达文本,可携带
//!   预排版的 [`crate::text::TextLayout`];纯文本由 `spans` 拼接推导,各后端渲染一致。
//! - 统一排序助手:[`SceneNode::ordered`] 按 `z_index` 稳定升序遍历节点(同层保持插入次序),
//!   [`Scene::iter_ordered`] 为顶层集合的便捷入口;渲染与调用方复用同一套遍历逻辑。

use crate::geometry::{Color, Point, Rect, Transform, Vec2};
use crate::render::Renderer;
use crate::text::{RichSpan, TextLayout};
use kurbo::BezPath;

/// 图片在目标框(`Element::Image.frame`,pt/px 坐标)内的适应方式。
///
/// 与 liepress 的 [`crate::document::types::ObjectFit`] 一一对应,但作为
/// lievisual IR 的自包含枚举,避免渲染层依赖文档层。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ObjectFit {
    /// 等比缩放,完整显示(可能在框内留白)。对应 SVG `meet`。
    #[default]
    Contain,
    /// 等比缩放,填满框并裁剪溢出部分。对应 SVG `slice`。
    Cover,
    /// 拉伸填满框(可能变形)。
    Fill,
    /// 不缩放,按原始像素尺寸放置于框左上角(可能溢出或留白)。
    None,
}

/// 场景中的图片资源(自包含 RGBA8 位图)。
///
/// 持有已解码的像素位图([`crate::Pixmap`]),**lievisual 不做解码**——解码是调用方 /
/// 资源加载层的职责。`frame` 为显示区域(在 [`Element::Image`] 中给出),`object_fit`
/// 决定图片如何映射到 `frame`。
#[derive(Debug, Clone)]
pub struct SceneImage {
    /// 已解码的 RGBA8 位图。
    pub pixmap: crate::Pixmap,
    /// 适应方式。
    pub object_fit: ObjectFit,
}

impl SceneImage {
    /// 由已解码的 RGBA8 位图构造(默认 `object_fit = Contain`)。
    #[must_use]
    pub fn from_pixmap(pixmap: crate::Pixmap) -> Self {
        Self {
            pixmap,
            object_fit: ObjectFit::Contain,
        }
    }

    /// 便捷:由 RGBA8 像素构造位图(自动推导默认 `object_fit = Contain`)。
    ///
    /// 长度必须为 `4 * width * height`,否则返回 `None`。
    #[must_use]
    pub fn from_rgba8(
        width: u32,
        height: u32,
        pixels: impl Into<std::sync::Arc<[u8]>>,
    ) -> Option<Self> {
        crate::Pixmap::from_rgba8(width, height, pixels).map(Self::from_pixmap)
    }

    /// 便捷:由 PNG 字节解码构造(`png` 常驻依赖)。非 PNG / 解码失败返回 `None`。
    #[must_use]
    pub fn from_png(bytes: &[u8]) -> Option<Self> {
        crate::Pixmap::decode_png(bytes).map(Self::from_pixmap)
    }

    /// 由任意编码字节解码构造(`jpeg` / `webp` / `gif` 等,经 `image`)。
    ///
    /// 仅在启用 `extra-image-codecs` feature 时可用。默认 lievisual 不做解码,
    /// 图片以已解码 RGBA8 位图进入 IR。
    #[cfg(feature = "extra-image-codecs")]
    #[must_use]
    pub fn from_encoded(bytes: &[u8]) -> Option<Self> {
        let dyn_img = image::load_from_memory(bytes).ok()?;
        let rgba = dyn_img.to_rgba8();
        let (w, h) = rgba.dimensions();
        Self::from_rgba8(w, h, rgba.into_raw())
    }

    /// 原始像素宽。
    #[must_use]
    pub fn width(&self) -> u32 {
        self.pixmap.width()
    }

    /// 原始像素高。
    #[must_use]
    pub fn height(&self) -> u32 {
        self.pixmap.height()
    }

    /// 设置适应方式。
    #[must_use]
    pub fn with_object_fit(mut self, fit: ObjectFit) -> Self {
        self.object_fit = fit;
        self
    }

    /// SVG 输出用的 `preserveAspectRatio` 片段(无前缀)。
    ///
    /// `None` 配合 `"none"` + SVG 侧原始像素宽高,实现"不缩放、左上角"。
    #[must_use]
    pub fn preserve_aspect_ratio(&self) -> &'static str {
        match self.object_fit {
            ObjectFit::Contain => "xMidYMid meet",
            ObjectFit::Cover => "xMidYMid slice",
            ObjectFit::Fill => "none",
            ObjectFit::None => "none",
        }
    }
}

/// 一个完整的可渲染场景。
#[derive(Debug, Clone)]
pub struct Scene {
    pub width: f64,
    pub height: f64,
    pub background: Color,
    /// 顶层图元集合("默认层",位于所有 `layers` 之下)。`render_scene` 会先按 `z_index` 排序再绘制。
    pub nodes: Vec<SceneNode>,
    /// 有序图层(从底到顶)。每个图层整体控制 `visible` / `opacity` / `transform`,
    /// 层内节点按 `z_index` 稳定升序绘制。
    pub layers: Vec<Layer>,
    /// 文档标题(SVG 输出为 `<title>`,供无障碍/导出名使用)。
    pub title: Option<String>,
    /// 文档描述(SVG 输出为 `<desc>`)。
    pub description: Option<String>,
    /// 输出缩放(像素密度)。默认 1.0;SVG 端同时放大 `width`/`height` 而保持
    /// `viewBox` 不变,得到更高分辨率的位图导出。
    pub scale: f64,
}

impl Default for Scene {
    fn default() -> Self {
        Self {
            width: 0.0,
            height: 0.0,
            background: Color::WHITE,
            nodes: Vec::new(),
            layers: Vec::new(),
            title: None,
            description: None,
            scale: 1.0,
        }
    }
}

impl Scene {
    pub fn new(width: f64, height: f64) -> Self {
        Self {
            width,
            height,
            background: Color::WHITE,
            nodes: Vec::new(),
            layers: Vec::new(),
            title: None,
            description: None,
            scale: 1.0,
        }
    }

    /// 便捷构造器:背景 + 尺寸。
    #[must_use]
    pub fn with_background(mut self, bg: Color) -> Self {
        self.background = bg;
        self
    }

    /// 便捷构造器:文档标题。
    #[must_use]
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// 便捷构造器:文档描述。
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// 便捷构造器:输出缩放(像素密度)。
    #[must_use]
    pub fn with_scale(mut self, scale: f64) -> Self {
        self.scale = scale;
        self
    }

    /// 追加一个图元或节点(默认 z_index = 0,无变换)。
    /// 同时接受 [`Element`](经 `From<Element>` 自动转为 [`SceneNode`])与已配置的 [`SceneNode`]。
    pub fn push(&mut self, node: impl Into<SceneNode>) {
        self.nodes.push(node.into());
    }

    /// 追加一个带层级/变换的图元。
    pub fn push_node(&mut self, node: SceneNode) {
        self.nodes.push(node);
    }

    /// 追加一个递归组合(Group):子节点在父变换与层级下绘制。
    pub fn push_group(&mut self, children: Vec<SceneNode>) {
        self.nodes.push(SceneNode::group(children));
    }

    /// 追加一个图层(越后 push 越靠上)。
    pub fn push_layer(&mut self, layer: Layer) {
        self.layers.push(layer);
    }

    /// 所有图层(从底到顶)。
    pub fn layers(&self) -> &[Layer] {
        &self.layers
    }

    /// 按名称查找图层。
    pub fn layer(&self, name: &str) -> Option<&Layer> {
        self.layers.iter().find(|l| l.name == name)
    }

    /// 按名称查找图层(可变)。
    pub fn layer_mut(&mut self, name: &str) -> Option<&mut Layer> {
        self.layers.iter_mut().find(|l| l.name == name)
    }

    /// 渲染到任意后端。
    pub fn render(&self, renderer: &mut dyn Renderer) {
        renderer.render_scene(self);
    }

    /// 顶层图元按 `z_index` 升序遍历(稳定:同层保持插入次序)。
    /// 仅覆盖默认层 `nodes`;图层的遍历见 [`Layer::iter_ordered`] 与 [`Renderer::render_layer`]。
    pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
        SceneNode::ordered(&self.nodes)
    }
}

/// 一个命名图层:一组节点 + 图层级整体属性。
///
/// 图层按数组顺序从底到顶绘制;图层级 `visible = false` 时整层跳过,`opacity` /
/// `transform` 作用于层内所有节点(与 Group 的子树语义一致)。层内节点再按各自
/// `z_index` 稳定升序绘制。
#[derive(Debug, Clone)]
pub struct Layer {
    /// 图层名(SVG 端输出为 `<g id>`;可为空字符串以不输出)。
    pub name: String,
    /// 是否可见,默认 `true`。`false` 时整层跳过渲染。
    pub visible: bool,
    /// 图层整体透明度,0.0–1.0,默认 1.0。
    pub opacity: f64,
    /// 图层整体变换(应用于层内所有节点)。
    pub transform: Option<Transform>,
    /// 层内图元集合(按 `z_index` 稳定排序后绘制)。
    pub nodes: Vec<SceneNode>,
}

impl Layer {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            visible: true,
            opacity: 1.0,
            transform: None,
            nodes: Vec::new(),
        }
    }

    /// 带初始图元的图层。
    pub fn with_nodes(mut self, nodes: Vec<SceneNode>) -> Self {
        self.nodes = nodes;
        self
    }

    /// 层内追加一个图元或节点。
    pub fn push(&mut self, node: impl Into<SceneNode>) {
        self.nodes.push(node.into());
    }

    /// 层内追加一个带层级/变换的节点。
    pub fn push_node(&mut self, node: SceneNode) {
        self.nodes.push(node);
    }

    /// 层内追加一个递归组合。
    pub fn push_group(&mut self, children: Vec<SceneNode>) {
        self.nodes.push(SceneNode::group(children));
    }

    /// 层内按 `z_index` 升序遍历(稳定:同层保持插入次序)。
    pub fn iter_ordered(&self) -> impl Iterator<Item = &SceneNode> {
        SceneNode::ordered(&self.nodes)
    }

    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }

    /// 设置整层可见性。
    #[must_use]
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// 设置整层透明度(0.0–1.0)。
    #[must_use]
    pub fn with_opacity(mut self, opacity: f64) -> Self {
        self.opacity = opacity.clamp(0.0, 1.0);
        self
    }

    /// 设置整层变换。
    #[must_use]
    pub fn with_transform(mut self, t: Transform) -> Self {
        self.transform = Some(t);
        self
    }
}

/// 场景中的单个节点:图元 + 层级 + 局部变换 + 节点属性。
///
/// 除 `element` 外的字段都是"子树级"属性:`transform` / `opacity` / `name` /
/// `visible` 对 `Group` 同样生效(`opacity` 与 `transform` 会随递归复合)。
#[derive(Debug, Clone)]
pub struct SceneNode {
    pub element: Element,
    pub z_index: i32,
    pub transform: Option<Transform>,
    /// 节点(及 Group 子树)整体透明度,0.0–1.0,默认 1.0。
    pub opacity: f64,
    /// 可选标识:调试、命中测试、SVG `id`。
    pub name: Option<String>,
    /// 是否可见,默认 `true`。`false` 时整棵子树跳过渲染。
    pub visible: bool,
    /// 可选裁剪形状:将整棵子树限制在其内部绘制。
    pub clip: Option<Clip>,
}

impl SceneNode {
    pub fn new(element: Element) -> Self {
        Self {
            element,
            z_index: 0,
            transform: None,
            opacity: 1.0,
            name: None,
            visible: true,
            clip: None,
        }
    }

    /// 构造递归组合节点(children 在父变换与层级下绘制)。
    pub fn group(children: Vec<SceneNode>) -> Self {
        Self {
            element: Element::Group { children },
            z_index: 0,
            transform: None,
            opacity: 1.0,
            name: None,
            visible: true,
            clip: None,
        }
    }

    /// 按 `z_index` 升序产出节点引用(稳定:同层保持插入次序)。
    pub fn ordered(nodes: &[SceneNode]) -> impl Iterator<Item = &SceneNode> {
        let mut order: Vec<usize> = (0..nodes.len()).collect();
        // 稳定排序:`sort_by_key` 对相等 z_index 保持相对次序。
        order.sort_by_key(|&i| nodes[i].z_index);
        order.into_iter().map(move |i| &nodes[i])
    }

    #[must_use]
    pub fn with_z(mut self, z: i32) -> Self {
        self.z_index = z;
        self
    }

    #[must_use]
    pub fn with_transform(mut self, t: Transform) -> Self {
        self.transform = Some(t);
        self
    }

    /// 设置节点透明度(0.0–1.0)。
    #[must_use]
    pub fn with_opacity(mut self, opacity: f64) -> Self {
        self.opacity = opacity.clamp(0.0, 1.0);
        self
    }

    /// 设置节点名称(调试 / 命中测试 / SVG `id`)。
    #[must_use]
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// 设置可见性。`false` 时整棵子树跳过渲染。
    #[must_use]
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// 设置裁剪形状:整棵子树限制在 `clip` 内部绘制。
    #[must_use]
    pub fn with_clip(mut self, clip: Clip) -> Self {
        self.clip = Some(clip);
        self
    }
}

/// 由 [`Element`] 构造节点(默认 z_index = 0,无变换),供 `Scene::push` 等接受 `Element`。
impl From<Element> for SceneNode {
    fn from(element: Element) -> Self {
        SceneNode::new(element)
    }
}

/// 裁剪形状:将节点(及整棵子树)限制在形状内部绘制。
///
/// 作为节点级属性([`SceneNode::clip`]),作用于子树;形状坐标为局部用户坐标,
/// 与节点 `transform` 复合(先变换后裁剪)。复用现有几何/路径类型,跨后端一致:
/// - SVG:`<clipPath>` + `clip-path="url(#...)"`
/// - vello:`push_clip_path` / `pop_clip_path`
#[derive(Debug, Clone, PartialEq)]
pub enum Clip {
    /// 矩形裁剪。
    Rect(Rect),
    /// 圆角矩形裁剪。
    RoundedRect { rect: Rect, radius: f64 },
    /// 圆形裁剪。
    Circle { center: Point, radius: f64 },
    /// 椭圆裁剪(可旋转)。
    Ellipse {
        center: Point,
        radii: Vec2,
        rotation: f64,
    },
    /// 任意贝塞尔路径裁剪(支持多子路径,默认 nonzero 填充规则)。
    Path(BezPath),
}

impl Clip {
    #[must_use]
    pub fn rect(rect: Rect) -> Self {
        Self::Rect(rect)
    }

    #[must_use]
    pub fn rounded_rect(rect: Rect, radius: f64) -> Self {
        Self::RoundedRect { rect, radius }
    }

    #[must_use]
    pub fn circle(center: Point, radius: f64) -> Self {
        Self::Circle { center, radius }
    }

    #[must_use]
    pub fn ellipse(center: Point, radii: Vec2, rotation: f64) -> Self {
        Self::Ellipse {
            center,
            radii,
            rotation,
        }
    }

    #[must_use]
    pub fn path(path: BezPath) -> Self {
        Self::Path(path)
    }

    /// 转为 kurbo 贝塞尔路径(供需要路径的渲染后端,如 vello)。
    #[must_use]
    pub fn to_bezpath(&self) -> BezPath {
        use kurbo::Shape;
        match self {
            Clip::Rect(rect) => {
                let mut p = BezPath::new();
                p.move_to((rect.min_x(), rect.min_y()));
                p.line_to((rect.max_x(), rect.min_y()));
                p.line_to((rect.max_x(), rect.max_y()));
                p.line_to((rect.min_x(), rect.max_y()));
                p.close_path();
                p
            }
            Clip::RoundedRect { rect, radius } => kurbo::RoundedRect::new(
                rect.min_x(),
                rect.min_y(),
                rect.max_x(),
                rect.max_y(),
                *radius,
            )
            .to_path(0.1),
            Clip::Circle { center, radius } => {
                kurbo::Circle::new((center.x, center.y), *radius).to_path(0.1)
            }
            Clip::Ellipse {
                center,
                radii,
                rotation,
            } => kurbo::Ellipse::new((center.x, center.y), (radii.x, radii.y), *rotation)
                .to_path(0.1),
            Clip::Path(path) => path.clone(),
        }
    }
}

/// 填充 + 描边样式。
#[derive(Debug, Clone, PartialEq, Default)]
pub struct FillStrokeStyle {
    pub fill: Option<Fill>,
    pub stroke: Option<Stroke>,
}

impl FillStrokeStyle {
    /// 纯填充样式。
    #[must_use]
    pub fn fill(color: Color) -> Self {
        Self {
            fill: Some(Fill::Solid(color)),
            stroke: None,
        }
    }

    /// 线性渐变填充样式。
    #[must_use]
    pub fn fill_gradient(gradient: impl Into<Fill>) -> Self {
        Self {
            fill: Some(gradient.into()),
            stroke: None,
        }
    }

    /// 纯描边样式。
    #[must_use]
    pub fn stroke(color: Color, width: f64) -> Self {
        Self {
            fill: None,
            stroke: Some(Stroke {
                color,
                width,
                ..Default::default()
            }),
        }
    }
}

/// 填充定义。
#[derive(Debug, Clone, PartialEq)]
pub enum Fill {
    Solid(Color),
    LinearGradient(LinearGradient),
    RadialGradient(RadialGradient),
}

impl From<Color> for Fill {
    fn from(c: Color) -> Self {
        Self::Solid(c)
    }
}

impl From<LinearGradient> for Fill {
    fn from(g: LinearGradient) -> Self {
        Self::LinearGradient(g)
    }
}

impl From<RadialGradient> for Fill {
    fn from(g: RadialGradient) -> Self {
        Self::RadialGradient(g)
    }
}

/// 线性渐变(`GradientPath` 与 `Fill::LinearGradient` 共用)。
#[derive(Debug, Clone, PartialEq)]
pub struct LinearGradient {
    pub start: Point,
    pub end: Point,
    pub stops: Vec<GradientStop>,
}

/// 径向渐变:从 `center` 以 `radius` 为外圈半径向外铺色。
#[derive(Debug, Clone, PartialEq)]
pub struct RadialGradient {
    pub center: Point,
    pub radius: f64,
    pub stops: Vec<GradientStop>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct GradientStop {
    pub offset: f64,
    pub color: Color,
}

/// 描边定义。
#[derive(Debug, Clone, PartialEq)]
pub struct Stroke {
    pub color: Color,
    pub width: f64,
    /// 线帽:butt / round / square。
    pub line_cap: LineCap,
    /// 连接:miter / round / bevel。
    pub line_join: LineJoin,
    /// 虚线数组(on/off 交替,单位与 `width` 相同)。空表示实线。
    pub dash_array: Vec<f64>,
    /// 虚线起点偏移。
    pub dash_offset: f64,
    /// 尖角连接上限(miter join)。默认 10.0,与 SVG / kurbo 对齐。
    pub miter_limit: f64,
}

impl Default for Stroke {
    fn default() -> Self {
        Self {
            color: Color::default(),
            width: 0.0,
            line_cap: LineCap::default(),
            line_join: LineJoin::default(),
            dash_array: Vec::new(),
            dash_offset: 0.0,
            miter_limit: 10.0,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineCap {
    #[default]
    Butt,
    Round,
    Square,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LineJoin {
    #[default]
    Miter,
    Round,
    Bevel,
}

impl Stroke {
    /// 便捷构造:纯色描边。
    #[must_use]
    pub fn new(color: Color, width: f64) -> Self {
        Self {
            color,
            width,
            ..Default::default()
        }
    }

    /// 便捷构造:虚线描边(`dash_array` 为 on/off 交替长度)。
    #[must_use]
    pub fn dashed(color: Color, width: f64, dash_array: Vec<f64>) -> Self {
        Self {
            color,
            width,
            dash_array,
            ..Default::default()
        }
    }
}

/// 声明式图元枚举。仅描述几何与样式。
#[derive(Debug, Clone)]
pub enum Element {
    Rect {
        rect: Rect,
        style: FillStrokeStyle,
    },
    Circle {
        center: Point,
        radius: f64,
        style: FillStrokeStyle,
    },
    /// 椭圆(可旋转):`radii` 为两个半轴长,`rotation` 为绕中心的旋转(弧度)。
    Ellipse {
        center: Point,
        radii: Vec2,
        rotation: f64,
        style: FillStrokeStyle,
    },
    /// 圆角矩形:`radius` 为四角统一圆角半径。
    RoundedRect {
        rect: Rect,
        radius: f64,
        style: FillStrokeStyle,
    },
    Line {
        start: Point,
        end: Point,
        style: Stroke,
    },
    /// 开放折线(仅描边)。
    Polyline {
        points: Vec<Point>,
        style: Stroke,
    },
    /// 闭合多边形(填充 + 可选描边)。
    Polygon {
        points: Vec<Point>,
        style: FillStrokeStyle,
    },
    /// 圆弧(开放,仅描边)。`radii` 为两半轴长,角度单位为弧度。
    Arc {
        center: Point,
        radii: Vec2,
        start_angle: f64,
        sweep_angle: f64,
        style: Stroke,
    },
    /// 扇形(闭合,含圆心到两端点的连线,填充 + 可选描边)。适合饼图。
    Pie {
        center: Point,
        radius: f64,
        start_angle: f64,
        sweep_angle: f64,
        style: FillStrokeStyle,
    },
    /// 闭合/开放路径,使用 kurbo 贝塞尔路径。
    Path {
        path: BezPath,
        style: FillStrokeStyle,
        /// true 表示闭合路径(用于填充)。
        closed: bool,
    },
    /// 图片:自包含二进制资源 + 显示框(pt/px 坐标)。
    ///
    /// - `image`:图片字节与原始像素尺寸、适应方式(见 [`SceneImage`]);
    /// - `frame`:显示区域,后端按 `image.object_fit` 将图片映射到该框;
    /// - `opacity`:整体透明度(0–1),默认 1.0。
    ///
    /// - SVG:`<image>` 标签(`data:` URI + `preserveAspectRatio`);
    /// - vello:解码为位图后以 image paint 绘制(受 `object_fit` 与 `frame` 裁剪)。
    Image {
        image: SceneImage,
        frame: Rect,
        opacity: f64,
    },
    /// 带渐变填充的路径。
    GradientPath {
        path: BezPath,
        gradient: LinearGradient,
        stroke: Option<Stroke>,
    },
    /// 文本:以样式化片段([`RichSpan`])为核心,可选预排版 layout。
    ///
    /// - `spans`:样式化片段(vello 等后端据此排版字形),单文本即单个片段;
    /// - `style`:块级定位样式(`align` / `baseline` / `rotation` / `max_width`)与默认字体;
    /// - `layout`:预排版结果,存在时后端应优先使用(精确字形定位)。
    ///
    /// 纯文本内容(SVG 后端)由 `spans` 拼接推导,保证各后端渲染一致。
    Text {
        spans: Vec<RichSpan>,
        position: Point,
        style: crate::text::TextStyle,
        layout: Option<std::sync::Arc<TextLayout>>,
    },
    /// 递归组合:子节点在父变换与层级下绘制。
    Group {
        children: Vec<SceneNode>,
    },
}

impl Element {
    /// 矩形图元。
    #[must_use]
    pub fn rect(rect: Rect, style: FillStrokeStyle) -> Self {
        Self::Rect { rect, style }
    }

    /// 圆图元。
    #[must_use]
    pub fn circle(center: Point, radius: f64, style: FillStrokeStyle) -> Self {
        Self::Circle {
            center,
            radius,
            style,
        }
    }

    /// 椭圆图元。
    #[must_use]
    pub fn ellipse(center: Point, radii: Vec2, rotation: f64, style: FillStrokeStyle) -> Self {
        Self::Ellipse {
            center,
            radii,
            rotation,
            style,
        }
    }

    /// 圆角矩形图元。
    #[must_use]
    pub fn rounded_rect(rect: Rect, radius: f64, style: FillStrokeStyle) -> Self {
        Self::RoundedRect {
            rect,
            radius,
            style,
        }
    }

    /// 线段图元。
    #[must_use]
    pub fn line(start: Point, end: Point, style: Stroke) -> Self {
        Self::Line { start, end, style }
    }

    /// 折线图元(开放,仅描边)。
    #[must_use]
    pub fn poly(points: Vec<Point>, style: Stroke) -> Self {
        Self::Polyline {
            points,
            style,
        }
    }

    /// 多边形图元(闭合,可填充 + 描边)。
    #[must_use]
    pub fn polygon(points: Vec<Point>, style: FillStrokeStyle) -> Self {
        Self::Polygon { points, style }
    }

    /// 圆弧图元(开放,仅描边)。
    #[must_use]
    pub fn arc(
        center: Point,
        radii: Vec2,
        start_angle: f64,
        sweep_angle: f64,
        style: Stroke,
    ) -> Self {
        Self::Arc {
            center,
            radii,
            start_angle,
            sweep_angle,
            style,
        }
    }

    /// 扇形图元(闭合,填充 + 可选描边)。
    #[must_use]
    pub fn pie(
        center: Point,
        radius: f64,
        start_angle: f64,
        sweep_angle: f64,
        style: FillStrokeStyle,
    ) -> Self {
        Self::Pie {
            center,
            radius,
            start_angle,
            sweep_angle,
            style,
        }
    }

    /// 纯文本图元(layout 为空,由后端自行排版)。
    ///
    /// `style` 既作为块级定位(`align` / `baseline` / `rotation` / `max_width`),
    /// 也作为默认字体样式;内部生成单个 [`RichSpan`]。
    #[must_use]
    pub fn text(
        content: impl Into<String>,
        position: Point,
        style: crate::text::TextStyle,
    ) -> Self {
        Self::Text {
            spans: vec![RichSpan::new(content, style.clone())],
            position,
            style,
            layout: None,
        }
    }

    /// 富文本图元:由一段段样式化片段组成(`style` 提供块级定位与默认字体)。
    #[must_use]
    pub fn rich_text(spans: Vec<RichSpan>, position: Point, style: crate::text::TextStyle) -> Self {
        Self::Text {
            spans,
            position,
            style,
            layout: None,
        }
    }

    /// 图片图元:`image` 为自包含资源,`frame` 为显示区域(pt/px 坐标)。
    ///
    /// `opacity` 默认 1.0;`object_fit` 由 [`SceneImage::object_fit`] 控制。
    #[must_use]
    pub fn image(image: SceneImage, frame: Rect) -> Self {
        Self::Image {
            image,
            frame,
            opacity: 1.0,
        }
    }
}

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

    /// 构造一个 x 坐标可区分、z_index 可指定的矩形节点(用于稳定性断言)。
    fn rect_node(x: f64, z: i32) -> SceneNode {
        SceneNode::new(Element::rect(
            Rect::new(x, 0.0, x + 1.0, 1.0),
            FillStrokeStyle::fill(Color::BLACK),
        ))
        .with_z(z)
    }

    fn rect_x(node: &SceneNode) -> f64 {
        match &node.element {
            Element::Rect { rect, .. } => rect.min_x(),
            _ => panic!("expected rect"),
        }
    }

    /// 元素构造器、节点构建器与默认值。
    mod element {
        use super::*;

        #[test]
        fn push_accepts_element_and_scene_node() {
            let mut scene = Scene::new(100.0, 100.0);
            scene.push(Element::rect(
                Rect::new(0.0, 0.0, 1.0, 1.0),
                FillStrokeStyle::fill(Color::BLACK),
            ));
            scene.push(SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 1.0, 1.0),
                FillStrokeStyle::fill(Color::BLACK),
            )));
            assert_eq!(scene.nodes.len(), 2);
        }

        #[test]
        fn builder_chaining() {
            let node = SceneNode::new(Element::circle(
                Point::new(1.0, 2.0),
                3.0,
                FillStrokeStyle::stroke(Color::BLACK, 1.0),
            ))
            .with_z(7)
            .with_transform(Transform::translate(1.0, 2.0))
            .with_opacity(0.5)
            .with_name("node-a")
            .with_visible(false);
            assert_eq!(node.z_index, 7);
            assert_eq!(node.transform, Some(Transform::translate(1.0, 2.0)));
            assert_eq!(node.opacity, 0.5);
            assert_eq!(node.name.as_deref(), Some("node-a"));
            assert!(!node.visible);
        }

        #[test]
        fn node_defaults() {
            let node = SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 1.0, 1.0),
                FillStrokeStyle::fill(Color::BLACK),
            ));
            assert_eq!(node.opacity, 1.0);
            assert!(node.name.is_none());
            assert!(node.visible);
        }

        #[test]
        fn from_element_conversion() {
            let node: SceneNode = Element::line(
                Point::new(0.0, 0.0),
                Point::new(1.0, 1.0),
                Stroke::new(Color::BLACK, 1.0),
            )
            .into();
            assert_eq!(node.z_index, 0);
            assert!(node.transform.is_none());
        }

        #[test]
        fn element_constructors() {
            let r = Element::rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(r, Element::Rect { .. }));

            let c = Element::circle(
                Point::new(1.0, 2.0),
                3.0,
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(c, Element::Circle { .. }));

            let e = Element::ellipse(
                Point::new(1.0, 2.0),
                Vec2::new(4.0, 2.0),
                0.1,
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(e, Element::Ellipse { .. }));

            let rr = Element::rounded_rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                3.0,
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(rr, Element::RoundedRect { .. }));

            let l = Element::line(
                Point::new(0.0, 0.0),
                Point::new(1.0, 1.0),
                Stroke::new(Color::BLACK, 1.0),
            );
            assert!(matches!(l, Element::Line { .. }));

            let p = Element::poly(
                vec![Point::new(0.0, 0.0), Point::new(1.0, 1.0)],
                Stroke::new(Color::BLACK, 1.0),
            );
            assert!(matches!(p, Element::Polyline { .. }));

            let pg = Element::polygon(
                vec![
                    Point::new(0.0, 0.0),
                    Point::new(1.0, 1.0),
                    Point::new(0.0, 1.0),
                ],
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(pg, Element::Polygon { .. }));

            let a = Element::arc(
                Point::new(0.0, 0.0),
                Vec2::new(5.0, 5.0),
                0.0,
                std::f64::consts::FRAC_PI_2,
                Stroke::new(Color::BLACK, 1.0),
            );
            assert!(matches!(a, Element::Arc { .. }));

            let pie = Element::pie(
                Point::new(0.0, 0.0),
                5.0,
                0.0,
                std::f64::consts::FRAC_PI_2,
                FillStrokeStyle::fill(Color::BLACK),
            );
            assert!(matches!(pie, Element::Pie { .. }));

            let t = Element::text(
                "hi",
                Point::new(0.0, 0.0),
                crate::text::TextStyle::new(Color::BLACK, 12.0, "sans-serif"),
            );
            match t {
                Element::Text {
                    spans,
                    position,
                    style,
                    layout,
                } => {
                    assert_eq!(spans.len(), 1);
                    assert_eq!(spans[0].text, "hi");
                    assert_eq!(position, Point::new(0.0, 0.0));
                    assert_eq!(style.font_size, 12.0);
                    assert!(layout.is_none());
                }
                _ => panic!("expected text"),
            }
        }

        #[test]
        fn stroke_dash_and_miter_defaults() {
            let s = Stroke::new(Color::BLACK, 2.0);
            assert!(s.dash_array.is_empty());
            assert_eq!(s.dash_offset, 0.0);
            assert_eq!(s.miter_limit, 10.0);

            let d = Stroke::dashed(Color::BLACK, 2.0, vec![4.0, 2.0]);
            assert_eq!(d.dash_array, vec![4.0, 2.0]);
        }

        #[test]
        fn radial_gradient_into_fill() {
            let g = RadialGradient {
                center: Point::new(0.0, 0.0),
                radius: 10.0,
                stops: vec![
                    GradientStop {
                        offset: 0.0,
                        color: Color::BLACK,
                    },
                    GradientStop {
                        offset: 1.0,
                        color: Color::WHITE,
                    },
                ],
            };
            let style = FillStrokeStyle::fill_gradient(g);
            assert!(matches!(style.fill, Some(Fill::RadialGradient(_))));
        }

        #[test]
        fn rect_center_helper() {
            // kurbo Rect::new(x0, y0, x1, y1);origin(2,4) 宽10 高6 → (2,4)-(12,10)。
            assert_eq!(
                Rect::new(2.0, 4.0, 12.0, 10.0).center(),
                Point::new(7.0, 7.0)
            );
        }

        #[test]
        fn clip_constructors_and_bezpath() {
            let c = Clip::circle(Point::new(1.0, 2.0), 5.0);
            assert!(matches!(c, Clip::Circle { radius: 5.0, .. }));
            // to_bezpath 应产出闭合的圆路径
            let p = c.to_bezpath();
            assert!(!p.is_empty());

            let r = Clip::rect(Rect::new(0.0, 0.0, 10.0, 20.0));
            assert!(matches!(r, Clip::Rect(_)));
            assert!(!r.to_bezpath().is_empty());

            let rr = Clip::rounded_rect(Rect::new(0.0, 0.0, 10.0, 10.0), 2.0);
            assert!(matches!(rr, Clip::RoundedRect { .. }));

            let e = Clip::ellipse(Point::new(0.0, 0.0), Vec2::new(3.0, 4.0), 0.0);
            assert!(matches!(e, Clip::Ellipse { .. }));

            let mut bp = BezPath::new();
            bp.move_to((0.0, 0.0));
            bp.line_to((1.0, 0.0));
            let p2 = Clip::path(bp);
            assert!(matches!(p2, Clip::Path(_)));
            assert!(!p2.to_bezpath().is_empty());
        }

        #[test]
        fn scene_node_clip_builder() {
            let node = SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 10.0, 10.0),
                FillStrokeStyle::fill(Color::BLACK),
            ))
            .with_clip(Clip::circle(Point::new(5.0, 5.0), 3.0));
            assert!(node.clip.is_some());
            // 默认无 clip
            let n = SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 1.0, 1.0),
                FillStrokeStyle::fill(Color::BLACK),
            ));
            assert!(n.clip.is_none());
        }
    }

    /// 排序:z_index 升序与同 z 稳定性。
    mod ordering {
        use super::*;

        #[test]
        fn iter_ordered_sorts_z_ascending() {
            let mut scene = Scene::new(100.0, 100.0);
            scene.push_node(rect_node(0.0, 5));
            scene.push_node(rect_node(0.0, -3));
            scene.push_node(rect_node(0.0, 1));
            let zs: Vec<i32> = scene.iter_ordered().map(|n| n.z_index).collect();
            assert_eq!(zs, vec![-3, 1, 5]);
        }

        #[test]
        fn ordered_is_stable_within_same_z() {
            // 同 z_index 的三个节点,用可区分的 x 坐标验证保持插入次序。
            let nodes = vec![rect_node(10.0, 0), rect_node(20.0, 0), rect_node(30.0, 0)];
            let xs: Vec<f64> = SceneNode::ordered(&nodes).map(rect_x).collect();
            assert_eq!(xs, vec![10.0, 20.0, 30.0]);
        }

        #[test]
        fn layer_iter_ordered_sorts_within_layer() {
            let layer = Layer::new("l").with_nodes(vec![
                rect_node(0.0, 5),
                rect_node(0.0, -2),
                rect_node(0.0, 1),
            ]);
            let zs: Vec<i32> = layer.iter_ordered().map(|n| n.z_index).collect();
            assert_eq!(zs, vec![-2, 1, 5]);
        }
    }

    /// Scene 元数据、分组、图层装载与查询。
    mod scene {
        use super::*;

        #[test]
        fn scene_metadata_defaults_and_builders() {
            let scene = Scene::new(10.0, 20.0)
                .with_title("图表")
                .with_description("示例")
                .with_scale(2.0);
            assert_eq!(scene.title.as_deref(), Some("图表"));
            assert_eq!(scene.description.as_deref(), Some("示例"));
            assert_eq!(scene.scale, 2.0);
            let d = Scene::default();
            assert_eq!(d.scale, 1.0);
        }

        #[test]
        fn scene_node_group_and_push_group() {
            let group = SceneNode::group(vec![rect_node(0.0, 0), rect_node(0.0, 1)]);
            match &group.element {
                Element::Group { children } => assert_eq!(children.len(), 2),
                _ => panic!("expected group"),
            }
            let mut scene = Scene::new(10.0, 10.0);
            scene.push_group(vec![rect_node(0.0, 0)]);
            assert!(matches!(&scene.nodes[0].element, Element::Group { .. }));
        }

        #[test]
        fn scene_push_layer_and_lookup() {
            let mut scene = Scene::new(100.0, 100.0);
            scene.push_layer(Layer::new("grid"));
            scene.push_layer(Layer::new("data").with_nodes(vec![rect_node(0.0, 0)]));
            assert_eq!(scene.layers().len(), 2);
            assert!(scene.layer("data").is_some());
            assert!(scene.layer("missing").is_none());
            scene.layer_mut("grid").unwrap().visible = false;
            assert!(!scene.layers[0].visible);
        }

        #[test]
        fn scene_default_has_empty_layers() {
            let scene = Scene::new(10.0, 10.0);
            assert!(scene.layers.is_empty());
        }
    }

    /// Layer 默认值与构建器。
    mod layer {
        use super::*;

        #[test]
        fn layer_defaults_and_builders() {
            let layer = Layer::new("data").with_nodes(vec![rect_node(0.0, 1)]);
            assert_eq!(layer.name, "data");
            assert!(layer.visible);
            assert_eq!(layer.opacity, 1.0);
            assert!(layer.transform.is_none());
            assert_eq!(layer.nodes.len(), 1);

            let l2 = Layer::new("x")
                .with_visible(false)
                .with_opacity(0.5)
                .with_transform(Transform::translate(1.0, 2.0));
            assert!(!l2.visible);
            assert_eq!(l2.opacity, 0.5);
            assert_eq!(l2.transform, Some(Transform::translate(1.0, 2.0)));
        }
    }

    /// 图片资源:SceneImage 的 object-fit 映射与构造。
    mod image {
        use super::*;

        fn img(w: u32, h: u32) -> SceneImage {
            let px = vec![0u8; (w * h * 4) as usize];
            SceneImage::from_rgba8(w, h, px).unwrap()
        }

        #[test]
        fn preserve_aspect_ratio_mapping() {
            let base = img(10, 10);
            assert_eq!(base.preserve_aspect_ratio(), "xMidYMid meet");
            assert_eq!(
                base.clone()
                    .with_object_fit(ObjectFit::Cover)
                    .preserve_aspect_ratio(),
                "xMidYMid slice"
            );
            assert_eq!(
                base.clone()
                    .with_object_fit(ObjectFit::Fill)
                    .preserve_aspect_ratio(),
                "none"
            );
            assert_eq!(
                base.clone()
                    .with_object_fit(ObjectFit::None)
                    .preserve_aspect_ratio(),
                "none"
            );
        }

        #[test]
        fn default_object_fit_is_contain() {
            assert_eq!(img(1, 1).object_fit, ObjectFit::Contain);
        }

        #[test]
        fn from_rgba8_validates_dimensions() {
            assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 64]).is_some());
            // 长度不足 → None。
            assert!(SceneImage::from_rgba8(4, 4, vec![0u8; 63]).is_none());
        }

        #[test]
        fn from_png_roundtrips() {
            let pm = crate::Pixmap::from_rgba8(2, 2, vec![255u8; 16]).unwrap();
            let png = pm.to_png();
            let img = SceneImage::from_png(&png).expect("有效 PNG 应可解码");
            assert_eq!(img.width(), 2);
            assert_eq!(img.height(), 2);
            assert_eq!(img.pixmap.pixels(), pm.pixels());
        }

        #[test]
        fn image_element_constructs() {
            let img = img(4, 4);
            let el = Element::image(img, Rect::new(0.0, 0.0, 10.0, 10.0));
            match &el {
                Element::Image {
                    image,
                    frame,
                    opacity,
                } => {
                    assert_eq!(image.width(), 4);
                    assert_eq!(image.height(), 4);
                    assert_eq!(frame.width(), 10.0);
                    assert_eq!(*opacity, 1.0);
                }
                _ => panic!("expected image"),
            }
        }
    }
}