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
//! [`AxisTheme`] — the bundle of elements that describe an "axis-like"
//! chrome surface — and its three-layer cascade.
//!
//! Every axis-like surface in hephaestus follows the same structural
//! pattern: optional baseline, ticks + minor ticks, tick labels,
//! title, plus the tick lengths and tick-label gap. This applies to
//! plot axes (one `AxisTheme` per (channel, side) of the panel) and
//! legends (one `AxisTheme` per `LegendTheme`, covering tick labels
//! beside keys / ticks alongside a colorbar / etc.). Capturing the
//! pattern once means a user who wants "thicker tick marks
//! everywhere" sets it on the shared `AxisTheme` root and it
//! propagates to plot axes and legend bar ticks alike.

use super::element::{Element, Rotation};
use super::font::FontSpec;
use super::length::Length;
use super::palette::ThemeColor;
use super::{LineElement, TextElement};

/// Where the axis title sits relative to the panel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum TitleLocation {
    /// Title sits in the outer chrome slot, beyond the tick labels,
    /// on the side of the panel the axis draws against. The default
    /// for Cartesian axes.
    #[default]
    Outside,
    /// Title sits inside the panel, aligned with the axis. Useful
    /// for compact plots and projection styles that put the title
    /// near the axis baseline.
    Inside,
}

/// Sparse axis theme — every field overrides the parent layer
/// when set, falls through when `None` / `Inherit`.
///
/// `Element<T>` fields use `Inherit` to mean "no opinion" (since
/// the variant already encodes the three-way Inherit / Blank / Set
/// distinction); plain typed fields wrap in `Option<...>` so partial
/// overrides cascade per-field without clobbering the rest. After
/// the three-layer cascade in [`PerAxis::resolve`], any remaining
/// `None` falls back to [`axis_concrete_defaults`].
#[derive(Debug, Clone, Default, PartialEq)]
pub struct AxisTheme {
    /// Axis title. For plot axes, this is the axis's textual label;
    /// for legends, the legend's overall title sits elsewhere
    /// (`LegendTheme.title`) and `AxisTheme.title` is ignored.
    pub title: Element<TextElement>,
    /// Tick labels. For plot axes these are tick labels; for
    /// standard legends they double as key labels.
    pub text: Element<TextElement>,
    /// Baseline. Set to `Element::Blank` when the surface has no
    /// baseline (most legends).
    pub line: Element<LineElement>,
    /// Major tick marks.
    pub ticks: Element<LineElement>,
    /// Minor tick marks. Typically only used by continuous scales.
    pub ticks_minor: Element<LineElement>,
    /// Major-tick length. **Sign flips direction**: positive extends
    /// outward (away from the panel); negative extends inward.
    pub tick_length: Option<Length>,
    /// Minor-tick length. Sign behaves the same way as
    /// `tick_length`.
    pub tick_length_minor: Option<Length>,
    /// Gap between the end of a tick and the near edge of its label
    /// (always positive — labels sit on the side the tick extends
    /// to).
    pub tick_gap: Option<Length>,
    /// Gap between the outer edge of the tick-label rail and the
    /// near edge of the axis title. Distinct from the title element's
    /// `margin` (which controls space around the title in its own
    /// local frame) so polar / rotated chrome can position the
    /// title at a known rail-distance regardless of orientation.
    pub title_gap: Option<Length>,
    /// Where the axis title sits relative to the panel.
    pub title_location: Option<TitleLocation>,
}

/// Default major tick mark length, pt. Matches ggplot2's
/// `axis.ticks.length = half_line / 2` at base size 11pt.
pub const DEFAULT_TICK_LENGTH_PT: f64 = 2.75;
/// Default minor tick mark length, pt — half the major.
pub const DEFAULT_MINOR_TICK_LENGTH_PT: f64 = 1.375;
/// Default gap between tick mark end and label near edge, pt.
/// Matches ggplot2's `0.8 * half_line / 2` axis-text margin.
pub const DEFAULT_TICK_GAP_PT: f64 = 2.2;
/// Default gap between tick-label rail outer edge and axis-title
/// near edge, pt. Matches ggplot2's `half_line / 2` axis-title
/// margin.
pub const DEFAULT_TITLE_GAP_PT: f64 = 2.75;
/// Default axis-title font size, pt — same as the root text size
/// (ggplot2's `axis.title` inherits `base_size`).
pub const DEFAULT_AXIS_TITLE_SIZE_PT: f64 = super::element::DEFAULT_TEXT_SIZE_PT;

/// Concrete fallback values for an `AxisTheme` matching ggplot2's
/// `theme_gray()` defaults: no baseline (axis line blank), grey30
/// tick labels at `rel(0.8)`, grey20 tick marks, axis title at the
/// root text size rotated along the axis. Used as the safety net for
/// any field still `None` after the three-layer cascade.
fn build_axis_concrete_defaults() -> AxisTheme {
    let line = super::element::line_concrete_defaults();
    AxisTheme {
        // Axis titles read along the axis baseline — `Along` lets
        // the chrome resolve to 0° on Top / Bottom and 90° on
        // Left / Right (text reads up the column) without the
        // renderer special-casing vertical sides.
        title: Element::Set(TextElement {
            size_pt: Some(Length::Abs(DEFAULT_AXIS_TITLE_SIZE_PT)),
            angle: Some(Rotation::Along),
            color: Some(ThemeColor::Ink),
            font: FontSpec::default(),
            ..TextElement::default()
        }),
        text: Element::Set(TextElement {
            size_pt: Some(Length::Rel(0.8)),
            color: Some(ThemeColor::mix(ThemeColor::Paper, ThemeColor::Ink, 0.7)),
            font: FontSpec::default(),
            ..TextElement::default()
        }),
        // ggplot2 theme_gray has `axis.line = element_blank()` —
        // the grey panel does the work the axis line otherwise
        // would.
        line: Element::Blank,
        ticks: Element::Set(LineElement {
            color: Some(ThemeColor::mix(ThemeColor::Paper, ThemeColor::Ink, 0.8)),
            ..line.clone()
        }),
        ticks_minor: Element::Set(LineElement {
            color: Some(ThemeColor::mix(ThemeColor::Paper, ThemeColor::Ink, 0.8)),
            ..line
        }),
        tick_length: Some(Length::Abs(DEFAULT_TICK_LENGTH_PT)),
        tick_length_minor: Some(Length::Abs(DEFAULT_MINOR_TICK_LENGTH_PT)),
        tick_gap: Some(Length::Abs(DEFAULT_TICK_GAP_PT)),
        title_gap: Some(Length::Abs(DEFAULT_TITLE_GAP_PT)),
        title_location: Some(TitleLocation::Outside),
    }
}

/// Three-layer axis cascade — `all` (every axis), `by_channel`
/// (every axis on a given channel), `by_channel_side` (a specific
/// (channel, side) axis).
///
/// Resolution walks `by_channel_side[ch][side]` → `by_channel[ch]`
/// → `all`, per `AxisTheme` field independently.
#[derive(Debug, Clone, PartialEq)]
pub struct PerAxis {
    /// Applies to every axis.
    pub all: AxisTheme,
    /// Per-channel override (sparse).
    pub by_channel: [AxisTheme; 2],
    /// Per-(channel, side) override (sparse, most specific).
    pub by_channel_side: [[AxisTheme; 2]; 2],
}

impl PerAxis {
    /// Construct with `all = root` and every override slot empty.
    pub fn new(root: AxisTheme) -> Self {
        Self {
            all: root,
            by_channel: [AxisTheme::default(), AxisTheme::default()],
            by_channel_side: [
                [AxisTheme::default(), AxisTheme::default()],
                [AxisTheme::default(), AxisTheme::default()],
            ],
        }
    }

    /// Resolve every `AxisTheme` field for `(ch, side)`, returning
    /// concrete values. Walks `by_channel_side[ch][side]` →
    /// `by_channel[ch]` → `all` → [`axis_concrete_defaults`],
    /// per-field.
    ///
    /// Use [`Self::resolve_with_root`] to continue the text cascade
    /// into a theme-wide root text element.
    pub fn resolve(&self, ch: u8, side: u8) -> ResolvedAxis {
        self.resolve_with_root(ch, side, None)
    }

    /// [`Self::resolve`] with `root_text` as the final parent of both
    /// text-shaped slots — the theme's own `text` element, so a
    /// figure-wide font or line height reaches axis titles and tick
    /// labels like it reaches every other text slot.
    pub fn resolve_with_root(
        &self,
        ch: u8,
        side: u8,
        root_text: Option<&TextElement>,
    ) -> ResolvedAxis {
        let ci = ch as usize;
        let si = side as usize;
        debug_assert!(ci < 2 && si < 2, "channel/side out of range: {ch}, {side}");

        let defaults = axis_concrete_defaults();
        let axis_root_text = self.all.text.as_set();
        let root_line = self.all.line.as_set();

        let by_ch = &self.by_channel[ci];
        let by_cs = &self.by_channel_side[ci][si];

        let title = cascade_element_chain(
            [&by_cs.title, &by_ch.title, &self.all.title],
            defaults.title.as_set(),
            &[axis_root_text, root_text],
        );
        let text = cascade_element_chain(
            [&by_cs.text, &by_ch.text, &self.all.text],
            defaults.text.as_set(),
            &[root_text],
        );
        let line = cascade_line_chain(
            [&by_cs.line, &by_ch.line, &self.all.line],
            defaults.line.as_set(),
            None,
        );
        let ticks = cascade_line_chain(
            [&by_cs.ticks, &by_ch.ticks, &self.all.ticks],
            defaults.ticks.as_set(),
            root_line,
        );
        let ticks_minor = cascade_line_chain(
            [
                &by_cs.ticks_minor,
                &by_ch.ticks_minor,
                &self.all.ticks_minor,
            ],
            defaults.ticks_minor.as_set(),
            root_line,
        );

        let tick_length = by_cs
            .tick_length
            .or(by_ch.tick_length)
            .or(self.all.tick_length)
            .or(defaults.tick_length)
            .expect("axis_concrete_defaults sets tick_length");
        let tick_length_minor = by_cs
            .tick_length_minor
            .or(by_ch.tick_length_minor)
            .or(self.all.tick_length_minor)
            .or(defaults.tick_length_minor)
            .expect("axis_concrete_defaults sets tick_length_minor");
        let tick_gap = by_cs
            .tick_gap
            .or(by_ch.tick_gap)
            .or(self.all.tick_gap)
            .or(defaults.tick_gap)
            .expect("axis_concrete_defaults sets tick_gap");
        let title_gap = by_cs
            .title_gap
            .or(by_ch.title_gap)
            .or(self.all.title_gap)
            .or(defaults.title_gap)
            .expect("axis_concrete_defaults sets title_gap");
        let title_location = by_cs
            .title_location
            .or(by_ch.title_location)
            .or(self.all.title_location)
            .or(defaults.title_location)
            .expect("axis_concrete_defaults sets title_location");

        ResolvedAxis {
            title,
            text,
            line,
            ticks,
            ticks_minor,
            tick_length,
            tick_length_minor,
            tick_gap,
            title_gap,
            title_location,
        }
    }
}

impl Default for PerAxis {
    fn default() -> Self {
        Self::new(AxisTheme::default())
    }
}

impl AxisTheme {
    /// Resolve this single `AxisTheme` against the per-type concrete
    /// defaults — useful when a caller holds one `AxisTheme` rather
    /// than a [`PerAxis`] (legends, polar chrome). Equivalent to
    /// `PerAxis::new(self.clone()).resolve(0, 0)` but allocates less.
    pub fn resolved(&self) -> ResolvedAxis {
        PerAxis::new(self.clone()).resolve(0, 0)
    }
}

/// Bundle of resolved [`AxisTheme`] fields for one (channel, side).
/// Returned by [`PerAxis::resolve`]; elements are owned (cascaded
/// through every layer including the type's concrete fallback) so
/// callers can read each field without re-walking the chain.
///
/// `Length` fields remain unresolved here — they're resolved against
/// the relevant parent at draw time (text size against base text,
/// tick length against the line root, etc.).
#[derive(Debug, Clone)]
pub struct ResolvedAxis {
    /// Axis title element, or `None` if Blank.
    pub title: Option<TextElement>,
    /// Tick label element, or `None`.
    pub text: Option<TextElement>,
    /// Baseline element, or `None`.
    pub line: Option<LineElement>,
    /// Major tick element, or `None`.
    pub ticks: Option<LineElement>,
    /// Minor tick element, or `None`.
    pub ticks_minor: Option<LineElement>,
    /// Major-tick length (sign flips direction).
    pub tick_length: Length,
    /// Minor-tick length (sign flips direction).
    pub tick_length_minor: Length,
    /// Gap between tick end and label near-edge.
    pub tick_gap: Length,
    /// Gap between the outer edge of the label rail and the axis
    /// title's near edge. Always positive.
    pub title_gap: Length,
    /// Axis-title placement.
    pub title_location: TitleLocation,
}

/// Walk the cascade chain for a `TextElement` slot and merge into
/// a single owned `TextElement`. `Blank` at any level short-
/// circuits to `None`. `Set` accumulates into the running merged
/// element; `Inherit` skips. After the chain, the default-axis
/// element is the next fallback, then any cross-element root (e.g.
/// `theme.axis.all.text` as the root for `theme.axis.all.title`).
fn cascade_element_chain<const N: usize>(
    chain: [&Element<TextElement>; N],
    axis_default: Option<&TextElement>,
    extra_roots: &[Option<&TextElement>],
) -> Option<TextElement> {
    // Walk most-specific to least-specific. The first Blank short-
    // circuits to None; Set values merge child-over-parent via
    // TextElement::cascade. Inherit just skips that layer.
    let mut merged: Option<TextElement> = None;
    for e in chain {
        match e {
            Element::Blank => return None,
            Element::Set(v) => {
                merged = Some(match merged {
                    Some(m) => m.cascade(v),
                    None => v.clone(),
                });
            }
            Element::Inherit => {}
        }
    }
    if let Some(d) = axis_default {
        merged = Some(match merged {
            Some(m) => m.cascade(d),
            None => d.clone(),
        });
    }
    for r in extra_roots.iter().flatten() {
        merged = Some(match merged {
            Some(m) => m.cascade(r),
            None => (*r).clone(),
        });
    }
    merged
}

/// Same as [`cascade_element_chain`] but for `LineElement` slots.
fn cascade_line_chain<const N: usize>(
    chain: [&Element<LineElement>; N],
    axis_default: Option<&LineElement>,
    extra_root: Option<&LineElement>,
) -> Option<LineElement> {
    let mut merged: Option<LineElement> = None;
    for e in chain {
        match e {
            Element::Blank => return None,
            Element::Set(v) => {
                merged = Some(match merged {
                    Some(m) => m.cascade(v),
                    None => v.clone(),
                });
            }
            Element::Inherit => {}
        }
    }
    if let Some(d) = axis_default {
        merged = Some(match merged {
            Some(m) => m.cascade(d),
            None => d.clone(),
        });
    }
    if let Some(r) = extra_root {
        merged = Some(match merged {
            Some(m) => m.cascade(r),
            None => r.clone(),
        });
    }
    merged
}

/// Built once. `PerAxis::resolve` reads it on every axis it resolves —
/// roughly ten times per plot per frame — and each construction builds
/// seven `Element`s carrying `FontSpec`s and linetype `Arc`s.
static AXIS_CONCRETE_DEFAULTS: std::sync::LazyLock<AxisTheme> =
    std::sync::LazyLock::new(build_axis_concrete_defaults);

/// Bottom-of-cascade concrete values for an [`AxisTheme`].
pub fn axis_concrete_defaults() -> AxisTheme {
    AXIS_CONCRETE_DEFAULTS.clone()
}