oarust 0.15.1

GPU-first semantic computing engine written in Rust
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
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
//! `oa::plot::Axes` — one subplot inside an `oa::plot::Figure`.
//!
//! Records one optional raster base plus ordered vector artists.
//! The parent Figure lowers the same commands through `Ui`'s GPU compositor
//! for both live (`show`) and terminal (`save_to` / `render`) sinks.
//!
//! Donor reference: `oa/ui/plot/axes.h`, `oa/ui/plot/axes.cpp`

use crate::Color;
use crate::ui::types::PixelRect;

// ── Axis scaling ──────────────────────────────────────────────────────────────

/// Data-to-display transform applied per axis at replay.
///
/// The transform happens in display space: ticks, grid, artists, and
/// `FigureView` pixel mapping all share `Axes::scaled_limits`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Scale {
	/// Identity mapping.
	#[default]
	Linear,
	/// Base-10 logarithm. Non-positive samples drop from artists; ticks land
	/// on whole decades. Device-resident series (`plot_matrix`) cannot be
	/// transformed host-side and require linear axes.
	Log10,
	/// Symmetric log: linear inside `±SYMLOG_LINTHRESH`, logarithmic beyond.
	/// Zero and negative data stay on the axis; ticks land on symmetric
	/// decades plus zero.
	Symlog,
}

/// Magnitude at which a [`Scale::Symlog`] axis switches from linear to log.
pub const SYMLOG_LINTHRESH: f32 = 1.0;

/// Transform one data value into display space; `NaN` drops the point.
pub(super) fn scale_value(value: f32, scale: Scale) -> f32 {
	match scale {
		Scale::Linear => value,
		Scale::Log10 => {
			if value > 0.0 && value.is_finite() {
				value.log10()
			} else {
				f32::NAN
			}
		}
		Scale::Symlog => {
			if !value.is_finite() {
				return f32::NAN;
			}
			let magnitude = value.abs();
			if magnitude <= SYMLOG_LINTHRESH {
				value
			} else {
				value.signum() * SYMLOG_LINTHRESH * (1.0 + (magnitude / SYMLOG_LINTHRESH).log10())
			}
		}
	}
}

/// Inverse of [`scale_value`], used for readouts and limit write-back.
pub(super) fn unscale_value(value: f32, scale: Scale) -> f32 {
	match scale {
		Scale::Linear => value,
		Scale::Log10 => 10f32.powf(value),
		Scale::Symlog => {
			let magnitude = value.abs();
			if magnitude <= SYMLOG_LINTHRESH {
				value
			} else {
				value.signum() * SYMLOG_LINTHRESH * 10f32.powf(magnitude / SYMLOG_LINTHRESH - 1.0)
			}
		}
	}
}

/// Resolve one axis' raw `[lo, hi]` into display space.
///
/// A logarithmic axis whose lower bound is non-positive floors at the
/// smallest positive recorded value; an axis without any positive data
/// falls back to the `[0, 1]` display decade.
fn scaled_axis(lo: f32, hi: f32, scale: Scale, positive_min: Option<f32>) -> (f32, f32) {
	match scale {
		Scale::Linear => (lo, hi),
		Scale::Log10 => {
			let lo = if lo.is_finite() && lo > 0.0 {
				lo
			} else if let Some(min) = positive_min {
				min
			} else {
				return (0.0, 1.0);
			};
			let hi = if hi.is_finite() && hi > lo {
				hi
			} else {
				lo * 10.0
			};
			(lo.log10(), hi.log10())
		}
		Scale::Symlog => {
			let lo = scale_value(lo, scale);
			let hi = scale_value(hi, scale);
			if lo.is_finite() && hi.is_finite() && lo < hi {
				(lo, hi)
			} else {
				(-SYMLOG_LINTHRESH, SYMLOG_LINTHRESH)
			}
		}
	}
}

/// Axis tick label presentation paired with explicit tick positions.
///
/// Applies to ticks recorded through [`Axes::xticks`]/[`Axes::yticks`];
/// `Labels` pairs one string per explicit value and requires equal lengths.
#[derive(Clone, Debug, Default)]
pub enum TickFormat {
	/// Precision derived from the explicit positions' spacing.
	#[default]
	Auto,
	/// Fixed decimal places — `Decimals(2)` renders `1.25`.
	Decimals(usize),
	/// Scientific notation — `1.2e3`.
	Scientific,
	/// Caller-provided labels, one per explicit tick value in order.
	Labels(Vec<String>),
}

// ── Style descriptors ─────────────────────────────────────────────────────────

/// Per-series line style.
#[derive(Clone, Debug)]
pub struct LineStyle {
	/// Alpha-zero selects the next deterministic theme palette color.
	pub color: Color,
	pub label: String,
	pub width: f32,
	pub antialias_samples: u32,
	/// Draw as a step function: each y value holds to the next x
	/// (matplotlib `steps-post`).
	pub step: bool,
	/// Skip rendering while keeping the palette slot and legend entry.
	pub hidden: bool,
}

impl Default for LineStyle {
	fn default() -> Self {
		Self {
			color: Color::new(0.0, 0.0, 0.0, 0.0), // palette auto
			label: String::new(),
			width: 1.35,
			antialias_samples: 4,
			step: false,
			hidden: false,
		}
	}
}

/// Per-series scatter style.
#[derive(Clone, Debug)]
pub struct ScatterStyle {
	pub color: Color,
	pub label: String,
	pub radius: f32,
	/// Skip rendering while keeping the palette slot and legend entry.
	pub hidden: bool,
}

impl Default for ScatterStyle {
	fn default() -> Self {
		Self {
			color: Color::new(0.0, 0.0, 0.0, 0.0),
			label: String::new(),
			radius: 3.0,
			hidden: false,
		}
	}
}

/// Per-series bar style.
#[derive(Clone, Debug)]
pub struct BarStyle {
	pub color: Color,
	pub label: String,
	/// Gap fraction between bars `[0, 0.95]`.
	pub gap: f32,
	/// Skip rendering while keeping the palette slot and legend entry.
	pub hidden: bool,
}

impl Default for BarStyle {
	fn default() -> Self {
		Self {
			color: Color::new(0.0, 0.0, 0.0, 0.0),
			label: String::new(),
			gap: 0.18,
			hidden: false,
		}
	}
}

/// Dense row-major heatmap style.
///
/// Donor: `oa::plot::HeatmapStyle`.
#[derive(Clone, Debug)]
pub struct HeatmapStyle {
	pub v_min: f32,
	pub v_max: f32,
	/// Colormap index evaluated by the shared `draw_heatmap` kernel:
	/// 0 = plasma, 1 = viridis (default), 2 = blue-white-orange diverging,
	/// 3 = grayscale.
	pub colormap: u32,
	/// Scale `v_min`/`v_max` automatically from data.
	///
	/// Only the host `heatmap` path can inspect values; the device-resident
	/// `heatmap_matrix` path requires an explicit `v_min`/`v_max` range.
	pub auto_scale: bool,
	/// Draw a thin grid between cells.
	pub show_grid: bool,
	/// Reserve a strip at the right of the cell for a value-ramp colorbar
	/// with min/mid/max labels.
	pub colorbar: bool,
}

/// Box-summary style shared by every dataset in one `boxplot` call.
#[derive(Clone, Debug)]
pub struct BoxStyle {
	/// Alpha-zero cycles the theme palette per dataset slot.
	pub color: Color,
	pub label: String,
	/// Box width as a fraction of the dataset slot `[0, 0.95]`.
	pub width: f32,
	/// Whisker reach in interquartile-range units (matplotlib `whis`).
	pub whisk: f32,
	/// Skip rendering while keeping the palette slot and legend entry.
	pub hidden: bool,
}

impl Default for BoxStyle {
	fn default() -> Self {
		Self {
			color: Color::new(0.0, 0.0, 0.0, 0.0),
			label: String::new(),
			width: 0.5,
			whisk: 1.5,
			hidden: false,
		}
	}
}

impl Default for HeatmapStyle {
	fn default() -> Self {
		Self {
			v_min: 0.0,
			v_max: 1.0,
			colormap: 1, // viridis
			auto_scale: true,
			show_grid: true,
			colorbar: false,
		}
	}
}

// ── Internal command records ──────────────────────────────────────────────────

/// Insertion-order artist kind — mirrors the donor's `ArtistRef`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum ArtistKind {
	Line,
	Scatter,
	Bar,
	/// Device-resident `Matrix` line series.
	LineMatrix,
	/// Host ring-buffer series appended through `Axes::stream_push`.
	Stream,
	/// Filled band between two y curves.
	Band,
	/// Quartile boxes over one or more datasets.
	BoxPlot,
}

/// Retained commands within one Axes.
#[derive(Default, Clone)]
pub(super) struct AxesCommands {
	pub(super) title: String,
	pub(super) title_color: Color,
	pub(super) caption: String,
	pub(super) caption_color: Color,
	pub(super) x_label: String,
	pub(super) y_label: String,
	pub(super) imshow: Option<ImshowCmd>,
	pub(super) heatmap: Option<Heatmap>,
	pub(super) heatmap_matrix: Option<HeatmapMatrixCmd>,
	pub(super) lines: Vec<LineCmd>,
	pub(super) scatters: Vec<ScatterCmd>,
	pub(super) bars: Vec<BarCmd>,
	pub(super) line_matrices: Vec<LineMatrixCmd>,
	pub(super) streams: Vec<StreamCmd>,
	pub(super) bands: Vec<BandCmd>,
	pub(super) boxes: Vec<BoxCmd>,
	pub(super) annotations: Vec<AnnotationCmd>,
	/// Insertion-order list of artists — used by Figure to replay in call order.
	pub(super) artists: Vec<ArtistKind>,
	pub(super) limits: Option<LimitsCmd>,
	pub(super) x_scale: Scale,
	pub(super) y_scale: Scale,
	/// Explicit data-space tick positions; `None` = nice-number locator.
	pub(super) x_ticks: Option<Vec<f32>>,
	pub(super) y_ticks: Option<Vec<f32>>,
	pub(super) x_tick_format: TickFormat,
	pub(super) y_tick_format: TickFormat,
	pub(super) categories: Vec<String>,
	pub(super) show_grid: bool,
	pub(super) show_legend: bool,
	pub(super) border_color: Option<Color>,
}

impl AxesCommands {
	pub(super) fn new() -> Self {
		Self {
			show_grid: true,
			show_legend: true,
			..Default::default()
		}
	}
}

#[derive(Clone)]
pub(super) struct ImshowCmd {
	pub(super) texture: crate::Texture,
}

#[derive(Clone)]
pub(super) struct Heatmap {
	pub(super) values: Vec<f32>,
	pub(super) rows: i32,
	pub(super) cols: i32,
	pub(super) style: HeatmapStyle,
}

/// Device-resident dense heatmap; the matrix stays on the GPU.
#[derive(Clone)]
pub(super) struct HeatmapMatrixCmd {
	pub(super) values: crate::Matrix,
	pub(super) style: HeatmapStyle,
}

#[derive(Clone)]
pub(super) struct LineCmd {
	pub(super) x: Vec<f32>,
	pub(super) y: Vec<f32>,
	pub(super) style: LineStyle,
}

#[derive(Clone)]
pub(super) struct ScatterCmd {
	pub(super) x: Vec<f32>,
	pub(super) y: Vec<f32>,
	pub(super) style: ScatterStyle,
}

#[derive(Clone)]
pub(super) struct BarCmd {
	pub(super) y: Vec<f32>,
	/// `(index, size)` inside each x slot for grouped bars; `None` = full slot.
	pub(super) group: Option<(usize, usize)>,
	/// Running-sum baseline per bar for stacked layers; `None` = zero base.
	pub(super) stack_base: Option<Vec<f32>>,
	pub(super) style: BarStyle,
}

/// Device-resident line series; the matrix stays on the GPU.
///
/// `xy` selects the layout contract: `true` = rank-2 `[2, N]` with one X
/// block followed by one Y block (the `draw_plot_line` explicit-XY ABI);
/// `false` = rank-1 `[N]` y-vs-index.
#[derive(Clone)]
pub(super) struct LineMatrixCmd {
	pub(super) values: crate::Matrix,
	pub(super) xy: bool,
	pub(super) style: LineStyle,
}

/// Host ring-buffer line series for live data.
///
/// The window's x domain is `[0, capacity - 1]` sample indices; samples
/// arrive through `Axes::stream_push` and the oldest drop once `len` reaches
/// `capacity`, so a full window scrolls like a rolling trace.
#[derive(Clone)]
pub(super) struct StreamCmd {
	pub(super) values: Vec<f32>,
	pub(super) head: usize,
	pub(super) len: usize,
	pub(super) style: LineStyle,
}

impl StreamCmd {
	/// Append one sample, dropping the oldest when the window is full.
	fn push(&mut self, value: f32) {
		let capacity = self.values.len();
		if self.len < capacity {
			self.values[(self.head + self.len) % capacity] = value;
			self.len += 1;
		} else {
			self.values[self.head] = value;
			self.head = (self.head + 1) % capacity;
		}
	}

	/// Window contents in draw order (oldest first).
	pub(super) fn ordered(&self) -> impl Iterator<Item = f32> + '_ {
		let capacity = self.values.len();
		(0..self.len).map(move |index| self.values[(self.head + index) % capacity])
	}
}

/// One box-summary artist; each entry is one dataset's quartiles.
///
/// Quartiles are resolved eagerly at record time so replay stays free of
/// data inspection and automatic limits can read the whisker extents.
#[derive(Clone)]
pub(super) struct BoxCmd {
	/// `(slot, q1, median, q3, whisker_lo, whisker_hi)` per dataset.
	pub(super) summaries: Vec<(f32, f32, f32, f32, f32, f32)>,
	pub(super) style: BoxStyle,
}

/// Filled band between two host y curves at x = 0..n-1.
///
/// The band is the matplotlib `fill_between` / error-band primitive: replay
/// shades the region between `y_lo` and `y_hi` with `style.color`.
#[derive(Clone)]
pub(super) struct BandCmd {
	pub(super) y_lo: Vec<f32>,
	pub(super) y_hi: Vec<f32>,
	pub(super) style: LineStyle,
}

/// Data-space text annotation.
#[derive(Clone)]
pub(super) struct AnnotationCmd {
	pub(super) text: String,
	pub(super) x: f32,
	pub(super) y: f32,
}

#[derive(Clone, Debug)]
pub(super) struct LimitsCmd {
	pub(super) x_min: f32,
	pub(super) x_max: f32,
	pub(super) y_min: f32,
	pub(super) y_max: f32,
}

/// One resolved legend entry, in artist insertion order.
///
/// `row` is `usize::MAX` for unlabeled artists (no legend row) and the
/// drawn row index otherwise; `artist` is the `cmds.artists` position used
/// by `set_artist_hidden`.
pub(super) struct LegendEntry {
	pub(super) artist: usize,
	pub(super) label: String,
	pub(super) color: Color,
	pub(super) hidden: bool,
	pub(super) row: usize,
}

/// Pixels reserved at the right of a cell for a heatmap colorbar.
pub(super) const COLORBAR_RESERVE: u32 = 46;

/// Data viewport and surrounding text bands within one figure cell.
pub(super) struct AxesLayout {
	pub(super) plot: PixelRect,
	pub(super) title: PixelRect,
	pub(super) caption: PixelRect,
	pub(super) x_ticks: PixelRect,
	pub(super) y_ticks: PixelRect,
	pub(super) x_label: PixelRect,
	pub(super) y_label: PixelRect,
}

const LEGEND_WIDTH: u32 = 124;
const LEGEND_INSET: u32 = 6;
const LEGEND_ROW_HEIGHT: u32 = 15;

/// Legend geometry shared by figure replay and `FigureView` hit-testing.
pub(super) fn legend_row_rect(rect: PixelRect, row: usize) -> PixelRect {
	let w = rect.w.saturating_sub(2 * LEGEND_INSET).min(LEGEND_WIDTH);
	let h = rect.h.saturating_sub(2 * LEGEND_INSET);
	let offset = row.saturating_mul(LEGEND_ROW_HEIGHT as usize);
	if w < 38 || offset.saturating_add(LEGEND_ROW_HEIGHT as usize) > h as usize {
		return PixelRect::default();
	}
	PixelRect::new(
		rect.x + (rect.w - w - LEGEND_INSET) as i32,
		rect.y + LEGEND_INSET as i32 + offset as i32,
		w,
		LEGEND_ROW_HEIGHT,
	)
}

// ── Axes ──────────────────────────────────────────────────────────────────────

/// One subplot inside an `oa::plot::Figure`.
#[derive(Clone)]
pub struct Axes {
	pub(super) cmds: AxesCommands,
	/// Artist index kept at full strength while the rest render dimmed —
	/// `FigureView` sets this from legend hover.
	pub(super) highlight: Option<usize>,
}

impl Default for Axes {
	fn default() -> Self {
		Self {
			cmds: AxesCommands::new(),
			highlight: None,
		}
	}
}

impl Axes {
	/// Set the axes title rendered above its plot region.
	///
	/// `color` with alpha zero (the default) uses the theme text color.
	pub fn title(&mut self, text: &str) {
		self.title_color(text, Color::new(0.0, 0.0, 0.0, 0.0));
	}

	/// Set the axes title with an explicit text color.
	pub fn title_color(&mut self, text: &str, color: Color) {
		self.cmds.title = text.to_owned();
		self.cmds.title_color = color;
	}

	/// Set the secondary caption line below the title.
	///
	/// Used by the image-classify tutorial to show the ground-truth label.
	/// Alpha-zero color uses the theme secondary text color.
	pub fn caption(&mut self, text: &str) {
		self.cmds.caption = text.to_owned();
		self.cmds.caption_color = Color::new(0.0, 0.0, 0.0, 0.0);
	}

	/// Set caption with an explicit text color.
	pub fn caption_color(&mut self, text: &str, color: Color) {
		self.cmds.caption = text.to_owned();
		self.cmds.caption_color = color;
	}

	/// Set the horizontal axis label centered below the tick labels.
	pub fn x_label(&mut self, text: &str) {
		self.cmds.x_label = text.to_owned();
	}

	/// Set the vertical axis label, read bottom-to-top to the left of the ticks.
	pub fn y_label(&mut self, text: &str) {
		self.cmds.y_label = text.to_owned();
	}

	/// Display a texture as a raster base for this axes. Standalone images
	/// fit inside the subplot with their aspect ratio preserved.
	pub fn imshow(&mut self, texture: crate::Texture) {
		self.cmds.imshow = Some(ImshowCmd { texture });
	}

	/// Dense row-major heatmap.  Donor: `oa::plot::Axes::heatmap`.
	pub fn heatmap(&mut self, values: &[f32], rows: i32, cols: i32, style: HeatmapStyle) {
		let Some(count) = usize::try_from(rows).ok().and_then(|rows| {
			usize::try_from(cols)
				.ok()
				.and_then(|cols| rows.checked_mul(cols))
		}) else {
			return;
		};
		if count == 0 || values.len() < count {
			return;
		}
		self.cmds.heatmap = Some(Heatmap {
			values: values[..count].to_vec(),
			rows,
			cols,
			style,
		});
	}

	/// Dense device-resident heatmap from a rank-2 `F32` `oa::Matrix`.
	///
	/// The matrix stays on the GPU; replay lowers it to one `draw_heatmap`
	/// dispatch through the UI compositor. `style.auto_scale` cannot inspect
	/// device data — callers must supply an explicit `v_min`/`v_max` range or
	/// replay fails validation.
	pub fn heatmap_matrix(&mut self, values: crate::Matrix, style: HeatmapStyle) {
		if values.dtype() != crate::DType::F32 || values.shape().len() != 2 {
			return;
		}
		self.cmds.heatmap_matrix = Some(HeatmapMatrixCmd { values, style });
	}

	/// Line plot: y-values vs index.  Repeated calls append ordered series.
	pub fn plot(&mut self, y: &[f32], style: LineStyle) {
		if y.is_empty() {
			return;
		}
		let x: Vec<f32> = (0..y.len()).map(|i| i as f32).collect();
		self.cmds.lines.push(LineCmd {
			x,
			y: y.to_vec(),
			style,
		});
		self.cmds.artists.push(ArtistKind::Line);
	}

	/// Explicit X/Y line plot.
	pub fn plot_xy(&mut self, x: &[f32], y: &[f32], style: LineStyle) {
		if x.is_empty() || x.len() != y.len() {
			return;
		}
		self.cmds.lines.push(LineCmd {
			x: x.to_vec(),
			y: y.to_vec(),
			style,
		});
		self.cmds.artists.push(ArtistKind::Line);
	}

	/// Device-resident explicit-XY line series from an `F32` `[2, N]`
	/// `oa::Matrix` laid out as one X block followed by one Y block.
	///
	/// The matrix stays on the GPU and is retained until composition
	/// completes. Device data cannot be inspected host-side: the series does
	/// not contribute to automatic limits (set `limits` explicitly or record
	/// a host artist as well) and requires linear axes — a logarithmic axis
	/// fails at replay rather than silently drawing untransformed data.
	pub fn plot_matrix(&mut self, values: &crate::Matrix, style: LineStyle) {
		let shape = values.shape();
		if values.dtype() != crate::DType::F32 || shape.len() != 2 || shape[0] != 2 || shape[1] == 0 {
			return;
		}
		self.cmds.line_matrices.push(LineMatrixCmd {
			values: values.clone(),
			xy: true,
			style,
		});
		self.cmds.artists.push(ArtistKind::LineMatrix);
	}

	/// Device-resident y-vs-index line series from an `F32` `[N]` `oa::Matrix`.
	///
	/// Same device-resident contract as [`Axes::plot_matrix`]; x positions
	/// are the sample indices `0..N-1`, which do contribute to automatic
	/// x limits.
	pub fn plot_matrix_y(&mut self, values: &crate::Matrix, style: LineStyle) {
		if values.dtype() != crate::DType::F32 || values.shape().len() != 1 || values.shape()[0] == 0 {
			return;
		}
		self.cmds.line_matrices.push(LineMatrixCmd {
			values: values.clone(),
			xy: false,
			style,
		});
		self.cmds.artists.push(ArtistKind::LineMatrix);
	}

	/// Data-space text annotation anchored at `(x, y)`.
	///
	/// The text renders just above the data point; non-finite or
	/// scale-dropped points are skipped at replay.
	pub fn annotate(&mut self, text: &str, x: f32, y: f32) {
		if text.is_empty() {
			return;
		}
		self.cmds.annotations.push(AnnotationCmd {
			text: text.to_owned(),
			x,
			y,
		});
	}

	/// Category labels replacing numeric x tick labels at bar positions.
	///
	/// Pass one label per bar slot; an empty list restores numeric ticks.
	pub fn categories(&mut self, labels: &[&str]) {
		self.cmds.categories = labels.iter().map(|label| (*label).to_owned()).collect();
	}

	/// Set the x axis scaling (default: linear).
	pub fn xscale(&mut self, scale: Scale) {
		self.cmds.x_scale = scale;
	}

	/// Set the y axis scaling (default: linear).
	pub fn yscale(&mut self, scale: Scale) {
		self.cmds.y_scale = scale;
	}

	/// Explicit x tick positions in data space.
	///
	/// Positions map through the x scale at replay — a `Log10` axis drops
	/// non-positive values — and share grid placement with the labels.
	/// An empty slice restores the automatic nice-number locator.
	pub fn xticks(&mut self, values: &[f32]) {
		self.cmds.x_ticks = if values.is_empty() {
			None
		} else {
			Some(values.to_vec())
		};
	}

	/// Explicit y tick positions in data space; see [`Axes::xticks`].
	pub fn yticks(&mut self, values: &[f32]) {
		self.cmds.y_ticks = if values.is_empty() {
			None
		} else {
			Some(values.to_vec())
		};
	}

	/// Label presentation for explicit [`Axes::xticks`] positions.
	pub fn xformat(&mut self, format: TickFormat) {
		self.cmds.x_tick_format = format;
	}

	/// Label presentation for explicit [`Axes::yticks`] positions.
	pub fn yformat(&mut self, format: TickFormat) {
		self.cmds.y_tick_format = format;
	}

	/// Point cloud scatter.
	pub fn scatter(&mut self, x: &[f32], y: &[f32], style: ScatterStyle) {
		if x.is_empty() || x.len() != y.len() {
			return;
		}
		self.cmds.scatters.push(ScatterCmd {
			x: x.to_vec(),
			y: y.to_vec(),
			style,
		});
		self.cmds.artists.push(ArtistKind::Scatter);
	}

	/// Vertical bar chart at x = 0..n-1.
	pub fn bar(&mut self, y: &[f32], style: BarStyle) {
		if y.is_empty() {
			return;
		}
		self.cmds.bars.push(BarCmd {
			y: y.to_vec(),
			group: None,
			stack_base: None,
			style,
		});
		self.cmds.artists.push(ArtistKind::Bar);
	}

	/// Grouped bar chart — `series[i]` shares each x slot side-by-side.
	///
	/// `styles` pairs per layer; a short list falls back to defaults (palette
	/// colors). Each layer is its own artist, so legend rows and visibility
	/// toggling work per series.
	pub fn bar_grouped(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
		let size = series.len();
		if size == 0 || series.iter().any(|layer| layer.is_empty()) {
			return;
		}
		for (index, layer) in series.iter().enumerate() {
			self.cmds.bars.push(BarCmd {
				y: (*layer).to_vec(),
				group: Some((index, size)),
				stack_base: None,
				style: styles.get(index).cloned().unwrap_or_default(),
			});
			self.cmds.artists.push(ArtistKind::Bar);
		}
	}

	/// Stacked bar chart — `series[i]` accumulates on top of the layers
	/// before it.
	///
	/// Style and artist semantics match [`Axes::bar_grouped`]; each layer's
	/// baseline is the running sum of the previous layers' values.
	pub fn bar_stacked(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
		if series.is_empty() || series.iter().any(|layer| layer.is_empty()) {
			return;
		}
		let count = series[0].len();
		if series.iter().any(|layer| layer.len() != count) {
			return;
		}
		let mut base = vec![0.0_f32; count];
		for (index, layer) in series.iter().enumerate() {
			self.cmds.bars.push(BarCmd {
				y: (*layer).to_vec(),
				group: None,
				stack_base: Some(base.clone()),
				style: styles.get(index).cloned().unwrap_or_default(),
			});
			self.cmds.artists.push(ArtistKind::Bar);
			for (acc, &value) in base.iter_mut().zip(layer.iter()) {
				*acc += if value.is_finite() { value } else { 0.0 };
			}
		}
	}

	/// Begin a rolling line series of fixed `capacity` samples.
	///
	/// Returns the series handle for [`Axes::stream_push`]. The window's x
	/// domain is the sample indices `0..capacity-1`, so the trace fills from
	/// the left and then scrolls as the oldest samples drop.
	pub fn stream(&mut self, capacity: usize, style: LineStyle) -> usize {
		let index = self.cmds.streams.len();
		self.cmds.streams.push(StreamCmd {
			values: vec![0.0; capacity.max(1)],
			head: 0,
			len: 0,
			style,
		});
		self.cmds.artists.push(ArtistKind::Stream);
		index
	}

	/// Append samples to a [`Axes::stream`] series.
	///
	/// Out-of-range handles are ignored, matching the silent-skip contract of
	/// the other recording methods.
	pub fn stream_push(&mut self, series: usize, values: &[f32]) {
		if let Some(stream) = self.cmds.streams.get_mut(series) {
			for &value in values {
				stream.push(value);
			}
		}
	}

	/// Fill the band between two equal-length y curves at x = 0..n-1.
	///
	/// The error-band / `fill_between` primitive: `style.color` (alpha
	/// included) tints the shaded region. Band x positions are the sample
	/// indices, so a non-linear x axis is rejected at replay.
	pub fn band(&mut self, y_lo: &[f32], y_hi: &[f32], style: LineStyle) {
		if y_lo.is_empty() || y_lo.len() != y_hi.len() {
			return;
		}
		self.cmds.bands.push(BandCmd {
			y_lo: y_lo.to_vec(),
			y_hi: y_hi.to_vec(),
			style,
		});
		self.cmds.artists.push(ArtistKind::Band);
	}

	/// Box-and-whisker summary over one or more datasets.
	///
	/// Each dataset becomes one box centered on its own x slot, palette-colored
	/// in order. Quartiles use linear interpolation (matplotlib default) and
	/// whiskers extend `style.whisk` × IQR, clamped to the data extremes.
	pub fn boxplot(&mut self, datasets: &[&[f32]], style: BoxStyle) {
		if datasets.is_empty() {
			return;
		}
		let mut summaries = Vec::with_capacity(datasets.len());
		for (index, dataset) in datasets.iter().enumerate() {
			let mut sorted: Vec<f32> = dataset.iter().copied().filter(|v| v.is_finite()).collect();
			if sorted.is_empty() {
				continue;
			}
			sorted.sort_by(f32::total_cmp);
			let q1 = percentile(&sorted, 0.25);
			let median = percentile(&sorted, 0.5);
			let q3 = percentile(&sorted, 0.75);
			let iqr = (q3 - q1) * style.whisk;
			let lo = sorted
				.iter()
				.copied()
				.find(|&v| v >= q1 - iqr)
				.unwrap_or(sorted[0]);
			let hi = sorted
				.iter()
				.copied()
				.rev()
				.find(|&v| v <= q3 + iqr)
				.unwrap_or(sorted[sorted.len() - 1]);
			summaries.push((index as f32, q1, median, q3, lo, hi));
		}
		if summaries.is_empty() {
			return;
		}
		self.cmds.boxes.push(BoxCmd { summaries, style });
		self.cmds.artists.push(ArtistKind::BoxPlot);
	}

	/// Histogram: bin `values` into `bins` bars.
	pub fn histogram(&mut self, values: &[f32], bins: i32, style: BarStyle) {
		if bins <= 0 || values.is_empty() {
			return;
		}
		let bins = (bins as usize).min(4096);
		let finite: Vec<f32> = values.iter().copied().filter(|v| v.is_finite()).collect();
		if finite.is_empty() {
			return;
		}
		let v_min = finite.iter().cloned().fold(f32::INFINITY, f32::min);
		let v_max = finite.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
		let range = (v_max - v_min).max(1e-8);
		let mut counts = vec![0.0f32; bins];
		for &v in &finite {
			let idx = (((v - v_min) / range) * bins as f32) as usize;
			counts[idx.min(bins - 1)] += 1.0;
		}
		self.bar(&counts, style);
	}

	/// Fixed data limits; degenerate input restores auto-limits.
	pub fn limits(&mut self, x_min: f32, x_max: f32, y_min: f32, y_max: f32) {
		if [x_min, x_max, y_min, y_max]
			.iter()
			.all(|value| value.is_finite())
			&& x_min < x_max
			&& y_min < y_max
		{
			self.cmds.limits = Some(LimitsCmd {
				x_min,
				x_max,
				y_min,
				y_max,
			});
		} else {
			self.auto_limits();
		}
	}

	/// Restore automatic data-driven limits.
	pub fn auto_limits(&mut self) {
		self.cmds.limits = None;
	}

	/// Toggle the background grid (default: on).
	pub fn grid(&mut self, visible: bool) {
		self.cmds.show_grid = visible;
	}

	/// Toggle the labeled-series legend (default: on).
	pub fn legend(&mut self, visible: bool) {
		self.cmds.show_legend = visible;
	}

	/// Border color around the axes rect (default: none).
	pub fn border_color(&mut self, color: Color) {
		self.cmds.border_color = Some(color);
	}

	/// Clear all recorded commands.
	pub fn clear(&mut self) {
		self.cmds = AxesCommands::new();
	}

	/// Number of recorded artists in insertion order.
	pub fn artist_count(&self) -> usize {
		self.cmds.artists.len()
	}

	/// Visibility flag of the `index`-th artist in insertion order.
	pub fn artist_hidden(&self, index: usize) -> Option<bool> {
		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
		for (position, kind) in self.cmds.artists.iter().enumerate() {
			let hidden = match kind {
				ArtistKind::Line => self.cmds.lines.get(line).map(|cmd| cmd.style.hidden),
				ArtistKind::Scatter => self.cmds.scatters.get(scatter).map(|cmd| cmd.style.hidden),
				ArtistKind::Bar => self.cmds.bars.get(bar).map(|cmd| cmd.style.hidden),
				ArtistKind::LineMatrix => self
					.cmds
					.line_matrices
					.get(matrix)
					.map(|cmd| cmd.style.hidden),
				ArtistKind::Stream => self.cmds.streams.get(stream).map(|cmd| cmd.style.hidden),
				ArtistKind::Band => self.cmds.bands.get(band).map(|cmd| cmd.style.hidden),
				ArtistKind::BoxPlot => self.cmds.boxes.get(bx).map(|cmd| cmd.style.hidden),
			};
			if position == index {
				return hidden;
			}
			match kind {
				ArtistKind::Line => line += 1,
				ArtistKind::Scatter => scatter += 1,
				ArtistKind::Bar => bar += 1,
				ArtistKind::LineMatrix => matrix += 1,
				ArtistKind::Stream => stream += 1,
				ArtistKind::Band => band += 1,
				ArtistKind::BoxPlot => bx += 1,
			}
		}
		None
	}

	/// Show or hide the `index`-th artist in insertion order.
	///
	/// Hidden artists keep their palette slot and legend entry but skip
	/// rendering; `FigureView` legend toggling writes this flag.
	pub fn set_artist_hidden(&mut self, index: usize, hidden: bool) {
		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
		for (position, kind) in self.cmds.artists.iter().enumerate() {
			if position == index {
				match kind {
					ArtistKind::Line => {
						if let Some(cmd) = self.cmds.lines.get_mut(line) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::Scatter => {
						if let Some(cmd) = self.cmds.scatters.get_mut(scatter) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::Bar => {
						if let Some(cmd) = self.cmds.bars.get_mut(bar) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::LineMatrix => {
						if let Some(cmd) = self.cmds.line_matrices.get_mut(matrix) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::Stream => {
						if let Some(cmd) = self.cmds.streams.get_mut(stream) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::Band => {
						if let Some(cmd) = self.cmds.bands.get_mut(band) {
							cmd.style.hidden = hidden;
						}
					}
					ArtistKind::BoxPlot => {
						if let Some(cmd) = self.cmds.boxes.get_mut(bx) {
							cmd.style.hidden = hidden;
						}
					}
				}
				return;
			}
			match kind {
				ArtistKind::Line => line += 1,
				ArtistKind::Scatter => scatter += 1,
				ArtistKind::Bar => bar += 1,
				ArtistKind::LineMatrix => matrix += 1,
				ArtistKind::Stream => stream += 1,
				ArtistKind::Band => band += 1,
				ArtistKind::BoxPlot => bx += 1,
			}
		}
	}

	/// Highlight the `index`-th artist in insertion order, dimming the rest.
	///
	/// `None` restores uniform emphasis; `FigureView` legend hover writes this.
	pub fn set_series_highlight(&mut self, index: Option<usize>) {
		self.highlight = index;
	}

	// ── Shared layout / legend helpers ──────────────────────────────────────

	/// Whether the cell records data on numeric or categorical axes.
	pub(super) fn has_ticks(&self) -> bool {
		!self.cmds.artists.is_empty()
			|| !self.cmds.annotations.is_empty()
			|| self.cmds.limits.is_some()
			|| self.cmds.x_ticks.is_some()
			|| self.cmds.y_ticks.is_some()
			|| !self.cmds.categories.is_empty()
	}

	/// Reserve title, label, tick and colorbar bands around the data viewport.
	///
	/// Figure replay and `FigureView` hit-testing share this helper so
	/// pixel↔data mapping always agrees with the drawn artists.
	pub(super) fn layout(&self, cell: PixelRect) -> AxesLayout {
		let colorbar = self
			.cmds
			.heatmap
			.as_ref()
			.is_some_and(|heatmap| heatmap.style.colorbar)
			|| self
				.cmds
				.heatmap_matrix
				.as_ref()
				.is_some_and(|heatmap| heatmap.style.colorbar);
		// Keep at least half the cell available for data, including when a
		// workspace pane is temporarily too small to display all its labels.
		let reserve = |budget: &mut u32, pixels: u32| {
			let pixels = pixels.min(*budget);
			*budget -= pixels;
			pixels
		};
		let mut width_budget = cell.w / 2;
		let mut height_budget = cell.h / 2;
		let ticks = self.has_ticks() && cell.w >= 64 && cell.h >= 36;
		let colorbar_w = reserve(
			&mut width_budget,
			if colorbar { COLORBAR_RESERVE } else { 0 },
		);
		let y_label_w = reserve(
			&mut width_budget,
			if self.cmds.y_label.is_empty() { 0 } else { 19 },
		);
		let right = reserve(&mut width_budget, if ticks && !colorbar { 15 } else { 0 });
		let y_ticks_w = reserve(&mut width_budget, if ticks { 48 } else { 0 });
		let top = reserve(
			&mut height_budget,
			if !self.cmds.title.is_empty() {
				22
			} else if ticks {
				8
			} else {
				0
			},
		);
		let x_label_h = reserve(
			&mut height_budget,
			if self.cmds.x_label.is_empty() { 0 } else { 19 },
		);
		let x_ticks_h = reserve(&mut height_budget, if ticks { 18 } else { 0 });
		let caption_h = reserve(
			&mut height_budget,
			if self.cmds.caption.is_empty() { 0 } else { 18 },
		);
		let x = cell.x + (y_label_w + y_ticks_w) as i32;
		let y = cell.y + top as i32;
		let w = cell.w - y_label_w - y_ticks_w - right - colorbar_w;
		let h = cell.h - top - x_ticks_h - x_label_h - caption_h;
		let bottom = y + h as i32;
		AxesLayout {
			plot: PixelRect::new(x, y, w, h),
			title: PixelRect::new(x, cell.y, w, top),
			caption: PixelRect::new(x, bottom + (x_ticks_h + x_label_h) as i32, w, caption_h),
			x_ticks: PixelRect::new(cell.x, bottom, cell.w - colorbar_w, x_ticks_h),
			y_ticks: PixelRect::new(
				cell.x + y_label_w as i32,
				cell.y,
				y_ticks_w,
				top + h + x_ticks_h,
			),
			x_label: PixelRect::new(x, bottom + x_ticks_h as i32, w, x_label_h),
			y_label: PixelRect::new(cell.x, y, y_label_w, h),
		}
	}

	/// Labeled-series legend entries in insertion order.
	///
	/// The palette counter advances for every alpha-zero artist — hidden and
	/// unlabeled included — so colors stay stable across legend toggles.
	/// `row` numbers only the labeled entries, matching the drawn rows.
	pub(super) fn legend_entries(&self, palette: &[crate::Color]) -> Vec<LegendEntry> {
		let mut entries = Vec::new();
		let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
			(0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
		let mut palette_idx = 0usize;
		for (position, kind) in self.cmds.artists.iter().enumerate() {
			let (label, color, hidden) = match kind {
				ArtistKind::Line => {
					let Some(cmd) = self.cmds.lines.get(line) else {
						continue;
					};
					line += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::Scatter => {
					let Some(cmd) = self.cmds.scatters.get(scatter) else {
						continue;
					};
					scatter += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::Bar => {
					let Some(cmd) = self.cmds.bars.get(bar) else {
						continue;
					};
					bar += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::LineMatrix => {
					let Some(cmd) = self.cmds.line_matrices.get(matrix) else {
						continue;
					};
					matrix += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::Stream => {
					let Some(cmd) = self.cmds.streams.get(stream) else {
						continue;
					};
					stream += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::Band => {
					let Some(cmd) = self.cmds.bands.get(band) else {
						continue;
					};
					band += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
				ArtistKind::BoxPlot => {
					let Some(cmd) = self.cmds.boxes.get(bx) else {
						continue;
					};
					bx += 1;
					(&cmd.style.label, cmd.style.color, cmd.style.hidden)
				}
			};
			let color = if color.a == 0.0 {
				let resolved = palette[palette_idx % palette.len()];
				palette_idx += 1;
				resolved
			} else {
				color
			};
			entries.push(LegendEntry {
				artist: position,
				label: label.clone(),
				color,
				hidden,
				row: usize::MAX,
			});
		}
		let mut row = 0usize;
		for entry in &mut entries {
			if !entry.label.is_empty() {
				entry.row = row;
				row += 1;
			}
		}
		entries
	}

	// ── Computed limits ───────────────────────────────────────────────────────

	/// Compute the data-driven Y range from all recorded artists.
	pub(super) fn data_y_range(&self) -> (f32, f32) {
		let mut y_min = f32::INFINITY;
		let mut y_max = f32::NEG_INFINITY;
		for line in &self.cmds.lines {
			for &v in &line.y {
				if v.is_finite() {
					y_min = y_min.min(v);
					y_max = y_max.max(v);
				}
			}
		}
		for scatter in &self.cmds.scatters {
			for &value in &scatter.y {
				if value.is_finite() {
					y_min = y_min.min(value);
					y_max = y_max.max(value);
				}
			}
		}
		for bar in &self.cmds.bars {
			for (index, &v) in bar.y.iter().enumerate() {
				if v.is_finite() {
					let base = bar.stack_base.as_ref().map_or(0.0, |bases| bases[index]);
					y_min = y_min.min((base + v).min(base.min(0.0)));
					y_max = y_max.max((base + v).max(base.max(0.0)));
				}
			}
		}
		for stream in &self.cmds.streams {
			for value in stream.ordered() {
				if value.is_finite() {
					y_min = y_min.min(value);
					y_max = y_max.max(value);
				}
			}
		}
		for band in &self.cmds.bands {
			for &value in band.y_lo.iter().chain(&band.y_hi) {
				if value.is_finite() {
					y_min = y_min.min(value);
					y_max = y_max.max(value);
				}
			}
		}
		for boxes in &self.cmds.boxes {
			for &(_, _, _, _, lo, hi) in &boxes.summaries {
				y_min = y_min.min(lo);
				y_max = y_max.max(hi);
			}
		}
		if !y_min.is_finite() || !y_max.is_finite() {
			return (0.0, 1.0);
		}
		if (y_max - y_min).abs() < 1e-6 {
			return (y_min - 1.0, y_max + 1.0);
		}
		(y_min, y_max)
	}

	/// Effective data limits `[x_min, x_max, y_min, y_max]` after explicit
	/// `limits` or automatic data-driven resolution. Interactive views use
	/// this to map pixel coordinates into data space.
	pub fn data_limits(&self) -> [f32; 4] {
		let limits = self.effective_limits();
		[limits.x_min, limits.x_max, limits.y_min, limits.y_max]
	}

	/// The explicit `limits` override, or `None` when limits are data-driven.
	pub fn explicit_limits(&self) -> Option<[f32; 4]> {
		self
			.cmds
			.limits
			.as_ref()
			.map(|l| [l.x_min, l.x_max, l.y_min, l.y_max])
	}

	/// Compute the effective data limits (explicit or automatic).
	pub(super) fn effective_limits(&self) -> LimitsCmd {
		if let Some(lim) = &self.cmds.limits {
			return lim.clone();
		}
		let (y_min, y_max) = self.data_y_range();
		let mut x_min = f32::INFINITY;
		let mut x_max = f32::NEG_INFINITY;
		for value in self
			.cmds
			.lines
			.iter()
			.flat_map(|line| line.x.iter())
			.chain(
				self
					.cmds
					.scatters
					.iter()
					.flat_map(|scatter| scatter.x.iter()),
			)
			.copied()
			.filter(|value| value.is_finite())
		{
			x_min = x_min.min(value);
			x_max = x_max.max(value);
		}
		for bar in &self.cmds.bars {
			x_min = x_min.min(0.0);
			x_max = x_max.max(bar.y.len().saturating_sub(1) as f32);
		}
		for matrix in &self.cmds.line_matrices {
			if !matrix.xy {
				let count = matrix.values.shape().first().copied().unwrap_or(0);
				x_min = x_min.min(0.0);
				x_max = x_max.max(count.saturating_sub(1) as f32);
			}
		}
		for stream in &self.cmds.streams {
			if stream.len == 0 {
				continue;
			}
			x_min = x_min.min(0.0);
			x_max = x_max.max(stream.values.len().saturating_sub(1) as f32);
		}
		for band in &self.cmds.bands {
			x_min = x_min.min(0.0);
			x_max = x_max.max(band.y_lo.len().saturating_sub(1) as f32);
		}
		for boxes in &self.cmds.boxes {
			x_min = x_min.min(0.0);
			x_max = x_max.max(boxes.summaries.len().saturating_sub(1) as f32);
		}
		if !x_min.is_finite() || !x_max.is_finite() || (x_max - x_min).abs() < 1e-6 {
			x_min = 0.0;
			x_max = 1.0;
		}
		LimitsCmd {
			x_min,
			x_max,
			y_min,
			y_max,
		}
	}

	/// Effective limits transformed into display space by the axis scales.
	///
	/// Under linear scaling this equals `data_limits`; under `Log10` the
	/// ends are `log10` of the positive range (see [`scaled_axis`]).
	pub(super) fn scaled_limits(&self) -> LimitsCmd {
		let raw = self.effective_limits();
		let (x_min, x_max) = scaled_axis(
			raw.x_min,
			raw.x_max,
			self.cmds.x_scale,
			self.min_positive_x(),
		);
		let (y_min, y_max) = scaled_axis(
			raw.y_min,
			raw.y_max,
			self.cmds.y_scale,
			self.min_positive_y(),
		);
		LimitsCmd {
			x_min,
			x_max,
			y_min,
			y_max,
		}
	}

	/// Smallest positive x value across host artists, for log limit floors.
	fn min_positive_x(&self) -> Option<f32> {
		let mut min = f32::INFINITY;
		for value in self.cmds.lines.iter().flat_map(|line| line.x.iter()).chain(
			self
				.cmds
				.scatters
				.iter()
				.flat_map(|scatter| scatter.x.iter()),
		) {
			if value.is_finite() && *value > 0.0 {
				min = min.min(*value);
			}
		}
		for bars in &self.cmds.bars {
			if bars.y.len() > 1 {
				min = min.min(1.0);
			}
		}
		min.is_finite().then_some(min)
	}

	/// Smallest positive y value across host artists, for log limit floors.
	fn min_positive_y(&self) -> Option<f32> {
		let mut min = f32::INFINITY;
		for value in self
			.cmds
			.lines
			.iter()
			.flat_map(|line| line.y.iter())
			.chain(
				self
					.cmds
					.scatters
					.iter()
					.flat_map(|scatter| scatter.y.iter()),
			)
			.chain(self.cmds.bars.iter().flat_map(|bars| bars.y.iter()))
		{
			if value.is_finite() && *value > 0.0 {
				min = min.min(*value);
			}
		}
		min.is_finite().then_some(min)
	}
}

/// Linear-interpolation percentile over sorted values (matplotlib default).
fn percentile(sorted: &[f32], q: f32) -> f32 {
	let pos = q * (sorted.len() - 1) as f32;
	let lo = pos.floor() as usize;
	let hi = (lo + 1).min(sorted.len() - 1);
	sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo as f32)
}