hephaestus 0.1.0

Backend-agnostic 2D scene renderer for data visualization.
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
//! `EllipseGeom` — vectorised axis-aligned ellipses with independent
//! x and y radii.
//!
//! One ellipse per row (PointGeom-style: row == mark). The geom uses
//! the **centre + far-edge** convention: `(x, y)` is the centre and
//! `(x2, y2)` is the far edge along each axis. `rx = |x2 - x|`,
//! `ry = |y2 - y|`. The ellipse is always centred at `(x, y)` by
//! construction; off-centre bounding boxes aren't representable (a
//! deliberate constraint — ellipses are by definition centred).
//!
//! Channel naming matches RectGeom and SegmentGeom but the semantic
//! interpretation differs per the cross-geom convention: `(x, y)` is
//! always "the geom's natural anchor" — corner for Rect, start for
//! Segment, centre for Ellipse.
//!
//! Channels consumed:
//!
//! - `"x"`, `"y"` — centre position (required; data; numeric).
//! - `"x2"`, `"y2"` — far edge along each axis (required; data; numeric).
//! - `"x_offset"`, `"y_offset"`, `"x2_offset"`, `"y2_offset"` — per-edge
//!   absolute pt offsets after scale resolution. `x_offset` translates
//!   the centre; `x2_offset` translates the far edge. Independent
//!   offsets on centre vs far edge let you have, e.g., a centre at a
//!   data point with an absolute-pt radius (`x_offset = 0,
//!   x2_offset = r`).
//! - `"x_band"`, `"y_band"`, `"x2_band"`, `"y2_band"` — per-edge
//!   band-fraction offsets. All default to `0.0`. For band-filling
//!   ellipses on a discrete x scale, set `x2_band = 0.5` (centre at
//!   band centre, far edge at right of band → rx = half band width).
//! - `"fill"`, `"fill_opacity"`, `"stroke"`, `"stroke_opacity"`,
//!   `"linewidth"`, `"linetype"`, `"dash_offset"`, `"cap"`, `"join"` —
//!   same styling set as RectGeom.
//! - `"angle"` — rotation in **radians** around the ellipse centre,
//!   mathematical CCW (positive rotates the ellipse counter-clockwise
//!   in the rendered image). Default `0.0` (no rotation). Useful for
//!   eigenvector-aligned covariance ellipses.

use crate::brush::Brush;
use crate::geometry::{Affine, Point, Vec2};
use crate::path::FillRule;
use crate::primitives::ellipse as ellipse_path;
use crate::scene::SceneBuilder;

use super::resolve::{
    draw_stroke_with_linetype, override_alpha, pt_to_px, resolve_angle_channel,
    resolve_cap_channel, resolve_color_channel_or_theme, resolve_join_channel,
    resolve_linetype_channel, resolve_number_channel, resolve_number_channel_or, resolve_pick_id,
    resolve_position,
};
use super::state::{finalize_state, require_x_and_siblings, GeomState, KeysStrategy};
use super::{BuildableGeom, Channel, ExpectedOutput, Geom, GeomBuilder, GeomContext};

// ─── Defaults ────────────────────────────────────────────────────────────────

// Style defaults (linewidth, cap, join) live on `theme.geom.ellipse`.

const CHANNELS: &[(&str, ExpectedOutput)] = &[
    ("x", ExpectedOutput::Numbers),
    ("y", ExpectedOutput::Numbers),
    ("x2", ExpectedOutput::Numbers),
    ("y2", ExpectedOutput::Numbers),
    ("x_offset", ExpectedOutput::Numbers),
    ("y_offset", ExpectedOutput::Numbers),
    ("x2_offset", ExpectedOutput::Numbers),
    ("y2_offset", ExpectedOutput::Numbers),
    ("x_band", ExpectedOutput::Numbers),
    ("y_band", ExpectedOutput::Numbers),
    ("x2_band", ExpectedOutput::Numbers),
    ("y2_band", ExpectedOutput::Numbers),
    ("fill", ExpectedOutput::Colors),
    ("stroke", ExpectedOutput::Colors),
    ("fill_opacity", ExpectedOutput::Numbers),
    ("stroke_opacity", ExpectedOutput::Numbers),
    ("linewidth", ExpectedOutput::Numbers),
    ("linetype", ExpectedOutput::Linetypes),
    ("dash_offset", ExpectedOutput::Numbers),
    ("cap", ExpectedOutput::Strings),
    ("join", ExpectedOutput::Strings),
    ("expand", ExpectedOutput::Numbers),
    ("angle", ExpectedOutput::Numbers),
    ("pick_id", ExpectedOutput::Numbers),
];

// ─── EllipseGeom ─────────────────────────────────────────────────────────────

/// A vectorised ellipse geom. One ellipse per row.
pub struct EllipseGeom {
    pub(crate) state: GeomState,
}

crate::impl_geom_inherents!(EllipseGeom);

// ─── BuildableGeom impl ──────────────────────────────────────────────────────

impl BuildableGeom for EllipseGeom {
    fn build_from(builder: GeomBuilder<Self>) -> Self {
        let (keys_opt, channels) = builder.into_parts();
        let n = require_x_and_siblings(&channels, &["y", "x2", "y2"], "EllipseGeom");
        let state = finalize_state(
            keys_opt,
            channels,
            n,
            KeysStrategy::PerRow,
            CHANNELS,
            "EllipseGeom",
        );
        EllipseGeom { state }
    }
}

// ─── Geom impl ───────────────────────────────────────────────────────────────

impl Geom for EllipseGeom {
    fn state(&self) -> &GeomState {
        &self.state
    }

    fn state_mut(&mut self) -> &mut GeomState {
        &mut self.state
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn draw(&self, scene: &mut dyn SceneBuilder, ctx: &GeomContext<'_>) {
        let panel = ctx.panel_rect;
        let panel_w = panel.x1 - panel.x0;
        let panel_h = panel.y1 - panel.y0;
        if panel_w <= 0.0 || panel_h <= 0.0 {
            return;
        }
        let n = self.len();
        if n == 0 {
            return;
        }

        let x_scale_bound = ctx.scale_for("x");
        let y_scale_bound = ctx.scale_for("y");
        let x2_scale_bound = ctx.scale_for("x2").or(x_scale_bound);
        let y2_scale_bound = ctx.scale_for("y2").or(y_scale_bound);
        let x_offset_scale = ctx.scale_for("x_offset");
        let y_offset_scale = ctx.scale_for("y_offset");
        let x2_offset_scale = ctx.scale_for("x2_offset");
        let y2_offset_scale = ctx.scale_for("y2_offset");
        let x_band_scale = ctx.scale_for("x_band");
        let y_band_scale = ctx.scale_for("y_band");
        let x2_band_scale = ctx.scale_for("x2_band");
        let y2_band_scale = ctx.scale_for("y2_band");
        let fill_scale = ctx.scale_for("fill");
        let stroke_scale = ctx.scale_for("stroke");
        let fill_opacity_scale = ctx.scale_for("fill_opacity");
        let stroke_opacity_scale = ctx.scale_for("stroke_opacity");
        let linewidth_scale = ctx.scale_for("linewidth");
        let linetype_scale = ctx.scale_for("linetype");
        let dash_offset_scale = ctx.scale_for("dash_offset");
        let cap_scale = ctx.scale_for("cap");
        let join_scale = ctx.scale_for("join");
        let pick_id_scale = ctx.scale_for("pick_id");
        let expand_scale = ctx.scale_for("expand");
        let angle_scale = ctx.scale_for("angle");

        let channels = &self.state.channels;
        let (x_col, x_scale) = match channels.get("x") {
            Some(Channel::Data(c)) => (c, x_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (y_col, y_scale) = match channels.get("y") {
            Some(Channel::Data(c)) => (c, y_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (x2_col, x2_scale) = match channels.get("x2") {
            Some(Channel::Data(c)) => (c, x2_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };
        let (y2_col, y2_scale) = match channels.get("y2") {
            Some(Channel::Data(c)) => (c, y2_scale_bound),
            Some(Channel::RawData(c)) => (c, None),
            _ => return,
        };

        let x_offset_ch = channels.get("x_offset");
        let y_offset_ch = channels.get("y_offset");
        let x2_offset_ch = channels.get("x2_offset");
        let y2_offset_ch = channels.get("y2_offset");
        let x_band_ch = channels.get("x_band");
        let y_band_ch = channels.get("y_band");
        let x2_band_ch = channels.get("x2_band");
        let y2_band_ch = channels.get("y2_band");
        let fill_ch = channels.get("fill");
        let stroke_ch = channels.get("stroke");
        let fill_opacity_ch = channels.get("fill_opacity");
        let stroke_opacity_ch = channels.get("stroke_opacity");
        let linewidth_ch = channels.get("linewidth");
        let linetype_ch = channels.get("linetype");
        let dash_offset_ch = channels.get("dash_offset");
        let cap_ch = channels.get("cap");
        let join_ch = channels.get("join");
        let pick_id_ch = channels.get("pick_id");
        let expand_ch = channels.get("expand");
        let angle_ch = channels.get("angle");

        for i in 0..n {
            // ── Resolve centre + far edge in pixel space. ──
            let x_band = resolve_number_channel_or(x_band_ch, x_band_scale, i, 0.0);
            let x2_band = resolve_number_channel_or(x2_band_ch, x2_band_scale, i, 0.0);
            let y_band = resolve_number_channel_or(y_band_ch, y_band_scale, i, 0.0);
            let y2_band = resolve_number_channel_or(y2_band_ch, y2_band_scale, i, 0.0);

            let x_frac = resolve_position(x_col.get(i), x_scale, x_band);
            let x2_frac = resolve_position(x2_col.get(i), x2_scale, x2_band);
            let y_frac = resolve_position(y_col.get(i), y_scale, y_band);
            let y2_frac = resolve_position(y2_col.get(i), y2_scale, y2_band);
            if !x_frac.is_finite()
                || !x2_frac.is_finite()
                || !y_frac.is_finite()
                || !y2_frac.is_finite()
            {
                continue;
            }

            let (cx0, cy0) = ctx.projection.project_to_panel_px(panel, &[x_frac, y_frac]);
            let (x2_px0, y2_px0) = ctx
                .projection
                .project_to_panel_px(panel, &[x2_frac, y2_frac]);
            let mut cx = cx0;
            let mut x2_px = x2_px0;
            let mut cy = cy0;
            let mut y2_px = y2_px0;

            if let Some(off) = resolve_number_channel(x_offset_ch, x_offset_scale, i) {
                cx += pt_to_px(off, ctx.dpi);
            }
            if let Some(off) = resolve_number_channel(x2_offset_ch, x2_offset_scale, i) {
                x2_px += pt_to_px(off, ctx.dpi);
            }
            if let Some(off) = resolve_number_channel(y_offset_ch, y_offset_scale, i) {
                cy -= pt_to_px(off, ctx.dpi);
            }
            if let Some(off) = resolve_number_channel(y2_offset_ch, y2_offset_scale, i) {
                y2_px -= pt_to_px(off, ctx.dpi);
            }

            // `expand` grows the ellipse outward (positive) / shrinks
            // inward (negative) by the same pt amount along each axis,
            // so the boundary moves perpendicular to itself by `expand`
            // at every point only when rx == ry (a circle). For an
            // ellipse with rx != ry the effect is the natural radii
            // adjustment — sufficient and matches RectGeom's expand
            // semantics on the bounding box.
            let expand_px = pt_to_px(
                resolve_number_channel_or(expand_ch, expand_scale, i, 0.0),
                ctx.dpi,
            );
            let rx = (x2_px - cx).abs() + expand_px;
            let ry = (y2_px - cy).abs() + expand_px;
            if !rx.is_finite() || !ry.is_finite() || rx <= 0.0 || ry <= 0.0 {
                continue;
            }

            // ── Resolve styling. ──
            let fill_color = override_alpha(
                resolve_color_channel_or_theme(
                    fill_ch,
                    fill_scale,
                    i,
                    ctx.theme.geom.ellipse.fill.as_ref(),
                    &ctx.theme.palette,
                ),
                resolve_number_channel(fill_opacity_ch, fill_opacity_scale, i),
            );
            let stroke_color = override_alpha(
                resolve_color_channel_or_theme(
                    stroke_ch,
                    stroke_scale,
                    i,
                    ctx.theme.geom.ellipse.stroke.as_ref(),
                    &ctx.theme.palette,
                ),
                resolve_number_channel(stroke_opacity_ch, stroke_opacity_scale, i),
            );
            if fill_color.is_none() && stroke_color.is_none() {
                continue;
            }

            let path = ellipse_path(Point::new(cx, cy), Vec2::new(rx, ry));
            let pick = resolve_pick_id(pick_id_ch, pick_id_scale, i);

            // Rotation around the ellipse centre. Math CCW from the user
            // → negate for kurbo (screen y points down). Identity when
            // angle == 0 to keep the recording byte-identical for the
            // unrotated case (regression guard for existing tests).
            let angle = resolve_angle_channel(angle_ch, angle_scale, i);
            let xform = if angle == 0.0 {
                Affine::IDENTITY
            } else {
                Affine::rotate_about(-angle, Point::new(cx, cy))
            };

            if let Some(fc) = fill_color {
                scene.fill(
                    FillRule::NonZero,
                    xform,
                    &Brush::Solid(fc),
                    None,
                    &path,
                    pick,
                );
            }
            if let Some(sc) = stroke_color {
                let linewidth_pt = resolve_number_channel_or(
                    linewidth_ch,
                    linewidth_scale,
                    i,
                    ctx.theme.geom.ellipse.linewidth_pt,
                );
                let linewidth_px = pt_to_px(linewidth_pt, ctx.dpi);
                let dash_pattern_pt = resolve_linetype_channel(linetype_ch, linetype_scale, i);
                let dash_offset_pt =
                    resolve_number_channel_or(dash_offset_ch, dash_offset_scale, i, 0.0);
                let cap = resolve_cap_channel(cap_ch, cap_scale, i, ctx.theme.geom.ellipse.cap);
                let join =
                    resolve_join_channel(join_ch, join_scale, i, ctx.theme.geom.ellipse.join);
                draw_stroke_with_linetype(
                    scene,
                    &path,
                    /* closed */ true,
                    sc,
                    sc,
                    linewidth_px,
                    linewidth_pt,
                    cap,
                    join,
                    &dash_pattern_pt,
                    dash_offset_pt,
                    xform,
                    pick,
                    ctx.shapes,
                    ctx.theme.geom.marker_outline_pt,
                    ctx.dpi,
                );
            }
        }
    }
}

// ─── Tests ───────────────────────────────────────────────────────────────────

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

    use crate::color::Color;
    use crate::geometry::Rect;
    use crate::geometry::Shape as _;
    use crate::plot::geom::{linetype, DirectScaleResolver};
    use crate::plot::scale;
    use crate::plot::value::Value;
    use crate::scene::recording::{Op, RecordingScene};

    fn shapes() -> crate::shape::ShapeRegistry {
        crate::shape::ShapeRegistry::with_builtins()
    }

    fn ctx<'a>(
        panel: Rect,
        registry: &'a crate::shape::ShapeRegistry,
        scales: &'a DirectScaleResolver<'a>,
    ) -> GeomContext<'a> {
        GeomContext::new(panel, 96.0, registry, scales)
    }

    fn red() -> Color {
        Color::new([1.0, 0.0, 0.0, 1.0])
    }

    fn first_fill_bbox(scene: &RecordingScene) -> Option<Rect> {
        for op in &scene.ops {
            if let Op::Fill { path, .. } = op {
                let bb = path.bounding_box();
                return Some(Rect::new(bb.x0, bb.y0, bb.x1, bb.y1));
            }
        }
        None
    }

    // ── build() ──

    #[test]
    fn builder_requires_all_four_positions() {
        let r = std::panic::catch_unwind(|| {
            EllipseGeom::builder()
                .set("x", vec![0.0_f64])
                .set("y", vec![0.0_f64])
                .set("x2", vec![1.0_f64])
                // y2 missing
                .build()
        });
        assert!(r.is_err());
    }

    #[test]
    #[should_panic(expected = "must be data, not constant")]
    fn builder_x_constant_panics() {
        EllipseGeom::builder()
            .set("x", 0.0_f64)
            .set("y", vec![0.0_f64])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .build();
    }

    #[test]
    #[should_panic(expected = "does not match")]
    fn builder_length_mismatch_panics() {
        EllipseGeom::builder()
            .set("x", vec![0.0_f64, 1.0])
            .set("y", vec![0.0_f64, 1.0])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .build();
    }

    // ── Drawing: bbox checks ──

    #[test]
    fn ellipse_centre_and_radii_from_far_edge() {
        // Centre at (50, 50), far edge at (70, 60) → rx = 20, ry = 10.
        // Panel 100x100; x_frac 0.5 = 50 px, x2_frac 0.7 = 70 px.
        // y_frac 0.5 = 50 px (panel.y1 - 0.5*100 = 50), y2_frac 0.6 = 40
        // px (panel.y1 - 0.6*100 = 40). So ry = |40 - 50| = 10.
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = first_fill_bbox(&scene).expect("fill");
        // Ellipse centred at (50, 50) with rx=20, ry=10 → bbox (30, 40, 70, 60).
        assert!((bb.x0 - 30.0).abs() < 1e-6, "x0 = {}", bb.x0);
        assert!((bb.x1 - 70.0).abs() < 1e-6, "x1 = {}", bb.x1);
        assert!((bb.y0 - 40.0).abs() < 1e-6, "y0 = {}", bb.y0);
        assert!((bb.y1 - 60.0).abs() < 1e-6, "y1 = {}", bb.y1);
    }

    #[test]
    fn ellipse_inverted_far_edge_still_works() {
        // x2 < x — abs() should produce the same ellipse.
        let g = EllipseGeom::builder()
            .set("x", vec![0.7_f64])
            .set("y", vec![0.6_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.4_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = first_fill_bbox(&scene).expect("fill");
        // Centre at (70, 40), rx = |50-70| = 20, ry = |60-40| = 20.
        // bbox = (50, 20, 90, 60).
        assert!((bb.x0 - 50.0).abs() < 1e-6, "x0 = {}", bb.x0);
        assert!((bb.x1 - 90.0).abs() < 1e-6, "x1 = {}", bb.x1);
    }

    #[test]
    fn band_fill_on_discrete_x() {
        // Centre at band centre ("B"), x2_band = 0.5 → far edge at right
        // of band. rx = half band width.
        let x = scale::discrete(["A", "B"].into_iter().map(|s| Value::String(Arc::from(s))));
        let resolver = DirectScaleResolver::new().with("x", &x).with("x2", &x);
        let g = EllipseGeom::builder()
            .set("x", vec!["B"])
            .set("x2", vec!["B"])
            .set("y", vec![0.5_f64])
            .set("y2", vec![0.7_f64])
            .set("x2_band", vec![0.5_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &resolver),
        );
        let bb = first_fill_bbox(&scene).expect("fill");
        // Band B centre = 75 px; right edge = 100 px. rx = 25 px.
        // bbox.x0 = 50, bbox.x1 = 100.
        assert!((bb.x0 - 50.0).abs() < 1e-6, "x0 = {}", bb.x0);
        assert!((bb.x1 - 100.0).abs() < 1e-6, "x1 = {}", bb.x1);
    }

    #[test]
    fn pt_offset_on_far_edge_only_grows_radius() {
        // Centre at data point, no x_offset; x2 = x (same column),
        // x2_offset = +r pt → rx = r px (after pt→px conversion).
        // 9 pt at 96 dpi = 12 px.
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .set("x2_offset", vec![9.0_f64])
            .set("y2_offset", vec![9.0_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = first_fill_bbox(&scene).expect("fill");
        // Centre = 50, rx = ry = 12 → bbox (38, 38, 62, 62). For y, sign
        // flips but |delta| = 12.
        assert!((bb.x0 - 38.0).abs() < 1e-6);
        assert!((bb.x1 - 62.0).abs() < 1e-6);
        assert!((bb.y1 - bb.y0 - 24.0).abs() < 1e-6);
    }

    #[test]
    fn zero_radius_skips_row() {
        // x == x2 with no offsets → rx = 0 → row skipped.
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.5_f64])
            .set("y2", vec![0.5_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        assert!(scene.ops.is_empty());
    }

    #[test]
    fn nonfinite_position_skips_row() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64, f64::NAN])
            .set("y", vec![0.5_f64, 0.5])
            .set("x2", vec![0.7_f64, 0.7])
            .set("y2", vec![0.6_f64, 0.6])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let fills = scene
            .ops
            .iter()
            .filter(|op| matches!(op, Op::Fill { .. }))
            .count();
        assert_eq!(fills, 1);
    }

    #[test]
    fn no_fill_no_stroke_emits_nothing() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        assert!(scene.ops.is_empty());
    }

    #[test]
    fn stroke_uses_linewidth_pt_to_px() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("stroke", red())
            .set("linewidth", 2.0_f64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let widths: Vec<f64> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Stroke { stroke, .. } => Some(stroke.width),
                _ => None,
            })
            .collect();
        assert_eq!(widths.len(), 1);
        assert!((widths[0] - 2.0 * 96.0 / 72.0).abs() < 1e-9);
    }

    #[test]
    fn linetype_dashes_stroke() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("stroke", red())
            .set("linetype", Value::Linetype(linetype::dashed()))
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let dashed = scene.ops.iter().any(|op| match op {
            Op::Stroke { stroke, .. } => !stroke.dash_pattern.is_empty(),
            _ => false,
        });
        assert!(dashed);
    }

    #[test]
    fn declared_channels_alphabetical() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.0_f64])
            .set("y", vec![0.0_f64])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .set("fill", red())
            .build();
        let names: Vec<&str> = g.declared_channels().iter().map(|d| d.name).collect();
        let mut sorted = names.clone();
        sorted.sort();
        assert_eq!(names, sorted);
        // No "corner_radius" — that belongs to RectGeom.
        assert!(!names.contains(&"corner_radius"));
    }

    #[test]
    fn pick_id_channel_passes_through_per_row() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.3_f64, 0.5, 0.7])
            .set("y", vec![0.5_f64, 0.5, 0.5])
            .set("x2", vec![0.35_f64, 0.55, 0.75])
            .set("y2", vec![0.6_f64, 0.6, 0.6])
            .set("fill", red())
            .set("pick_id", vec![10_i64, 20, 30])
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let picks: Vec<u32> = scene
            .ops
            .iter()
            .filter_map(|op| match op {
                Op::Fill {
                    pick_id: crate::pick::PickId::Id(n),
                    ..
                } => Some(*n),
                _ => None,
            })
            .collect();
        assert_eq!(picks, vec![10, 20, 30]);
    }

    #[test]
    fn pick_id_unset_emits_skip() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        for op in &scene.ops {
            if let Op::Fill { pick_id, .. } = op {
                assert!(matches!(pick_id, crate::pick::PickId::Skip));
            }
        }
    }

    #[test]
    fn pick_id_zero_maps_to_block() {
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .set("pick_id", 0_i64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let has_block = scene.ops.iter().any(|op| {
            matches!(
                op,
                Op::Fill {
                    pick_id: crate::pick::PickId::Block,
                    ..
                }
            )
        });
        assert!(has_block);
    }

    #[test]
    #[should_panic(expected = "must be a non-negative integer")]
    fn pick_id_above_24_bit_panics_at_build() {
        EllipseGeom::builder()
            .set("x", vec![0.0_f64])
            .set("y", vec![0.0_f64])
            .set("x2", vec![1.0_f64])
            .set("y2", vec![1.0_f64])
            .set("pick_id", 0x100_0000_i64)
            .build();
    }

    #[test]
    fn angle_zero_produces_identity_xform() {
        // Regression guard: explicit angle=0 produces the same Affine
        // (Identity) as a geom without an angle binding at all.
        let g_no_angle = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .build();
        let g_zero = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .set("angle", 0.0_f64)
            .build();
        let panel = Rect::new(0.0, 0.0, 100.0, 100.0);
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut s1 = RecordingScene::default();
        let mut s2 = RecordingScene::default();
        g_no_angle.draw(&mut s1, &ctx(panel, &shapes, &scales));
        g_zero.draw(&mut s2, &ctx(panel, &shapes, &scales));
        let coeffs = |scene: &RecordingScene| {
            scene.ops.iter().find_map(|op| match op {
                Op::Fill { transform, .. } => Some(transform.as_coeffs()),
                _ => None,
            })
        };
        assert_eq!(coeffs(&s1), coeffs(&s2));
    }

    #[test]
    fn angle_uses_centre_as_pivot() {
        // Ellipse centred at (50, 50). After rotation by π/2 (math CCW),
        // the centre stays at (50, 50). The Affine's translation should
        // therefore be (50, 50) post-rotation about that point — i.e.,
        // the matrix maps (50, 50) back to (50, 50).
        use std::f64::consts::FRAC_PI_2;
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .set("angle", FRAC_PI_2)
            .build();
        let panel = Rect::new(0.0, 0.0, 100.0, 100.0);
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(&mut scene, &ctx(panel, &shapes, &scales));
        let xform = scene
            .ops
            .iter()
            .find_map(|op| match op {
                Op::Fill { transform, .. } => Some(*transform),
                _ => None,
            })
            .expect("fill op");
        let pivot_world = xform * crate::geometry::Point::new(50.0, 50.0);
        assert!(
            (pivot_world.x - 50.0).abs() < 1e-6,
            "pivot.x = {}",
            pivot_world.x
        );
        assert!(
            (pivot_world.y - 50.0).abs() < 1e-6,
            "pivot.y = {}",
            pivot_world.y
        );
    }

    #[test]
    fn expand_grows_ellipse_radii() {
        // Centre at 0.5, far edge at 0.7 → rx = 20 px. expand = 3pt =
        // 4 px → rx = 24 px. bbox width = 48 px.
        let g = EllipseGeom::builder()
            .set("x", vec![0.5_f64])
            .set("y", vec![0.5_f64])
            .set("x2", vec![0.7_f64])
            .set("y2", vec![0.6_f64])
            .set("fill", red())
            .set("expand", 3.0_f64)
            .build();
        let shapes = shapes();
        let scales = DirectScaleResolver::new();
        let mut scene = RecordingScene::default();
        g.draw(
            &mut scene,
            &ctx(Rect::new(0.0, 0.0, 100.0, 100.0), &shapes, &scales),
        );
        let bb = first_fill_bbox(&scene).expect("fill");
        let expand_px = 3.0 * 96.0 / 72.0;
        let expected_w = 2.0 * (20.0 + expand_px);
        assert!(
            (bb.x1 - bb.x0 - expected_w).abs() < 0.5,
            "width = {}",
            bb.x1 - bb.x0
        );
    }
}