Skip to main content

ferrochart_core/
transform_helpers.rs

1//! CPU implementation of the series transforms that the wgpu shaders perform.
2//!
3//! **Consistency rule**: the step from
4//! `XTransform`/`YTransform` to pixels is done in `f32`, with exactly the operation
5//! order the shaders use (no FMA), so that both backends round identically at
6//! pixel boundaries.
7//!
8//! Shader compilers may fuse `a * b + c` into an FMA (Metal compiles with
9//! fast-math by default, and WGSL cannot forbid it), which rounds differently
10//! from a separate multiply and add. The per-element transforms are therefore
11//! written **add first, multiply last** — `x = (d + shift) * step`,
12//! `y = (v_rel + bias) * a` — which no compiler can contract. The folded
13//! constants `shift` and `bias` are computed here, in f64, for both backends. Each function names its shader counterpart; the shaders are
14//! in `crates/ferrochart-render-wgpu/src/shaders/series.wgsl` and must
15//! mirror these functions line by line. Change both together.
16//!
17
18use crate::data::OhlcLevelView;
19use crate::data::lod::{f32_down, f32_up};
20use crate::frame::{LineDash, PriceMapping, XTransform, YTransform};
21use crate::geom::{PointPx, Px, RectPx};
22
23/// log2 of the number of elements per GPU chunk.
24pub const CHUNK_SHIFT: u32 = 12;
25/// Elements per GPU chunk. GPU buffers hold one more (the junction element).
26pub const CHUNK_LEN: i64 = 1 << CHUNK_SHIFT;
27
28/// Chunk number of element `e` of LOD `level`. Level 0 elements are
29/// logical indices; level `k >= 2` elements are bucket numbers, which already
30/// count from the anchor.
31///
32/// # Examples
33///
34/// ```
35/// use ferrochart_core::data::ANCHOR;
36/// use ferrochart_core::transform_helpers::{chunk_of, chunk_start, CHUNK_LEN};
37///
38/// assert_eq!(chunk_of(0, ANCHOR + CHUNK_LEN), 1);
39/// assert_eq!(chunk_start(0, 1), ANCHOR + CHUNK_LEN);
40/// assert_eq!(chunk_of(3, 5000), 1);
41/// assert_eq!(chunk_start(3, 1), CHUNK_LEN);
42/// ```
43pub fn chunk_of(level: u8, e: i64) -> i64 {
44    let from_anchor = if level == 0 {
45        e - crate::data::ANCHOR
46    } else {
47        e
48    };
49    from_anchor >> CHUNK_SHIFT
50}
51
52/// First element of chunk `c` of LOD `level`.
53pub fn chunk_start(level: u8, c: i64) -> i64 {
54    let from_anchor = c << CHUNK_SHIFT;
55    if level == 0 {
56        from_anchor + crate::data::ANCHOR
57    } else {
58        from_anchor
59    }
60}
61
62/// The reference price a renderer assigns to chunk `c` when it first writes it:
63/// the first finite, positive open in the chunk. The GPU backend freezes
64/// it; the stateless CPU backend recomputes it, which gives the same value
65/// unless the chunk's first bars changed after the GPU first saw them.
66pub fn initial_chunk_ref(view: &OhlcLevelView<'_>, c: i64) -> Option<f64> {
67    let start = chunk_start(view.level, c).max(view.first);
68    let end = (chunk_start(view.level, c) + CHUNK_LEN).min(view.end());
69    let opens = || (start..end).filter_map(|j| view.open.at(view.first, j));
70    // Value series may be zero or negative (oscillators), and a value bucket's
71    // first element may be a gap: fall back to the first finite open, then the
72    // first finite high. In log mode such a chunk only holds gaps anyway.
73    opens()
74        .find(|p| p.is_finite() && *p > 0.0)
75        .or_else(|| opens().find(|p| p.is_finite()))
76        .or_else(|| {
77            (start..end)
78                .filter_map(|j| view.high.at(view.first, j))
79                .find(|p| p.is_finite())
80        })
81}
82
83/// `[open, high, low, close]` relative to `chunk_ref`, exactly as stored in the
84/// GPU buffers: open/close rounded to nearest, high rounded up and low rounded
85/// down, so the drawn range always contains the true range.
86pub fn ohlc_rel(yt: &YTransform, ohlc: [f64; 4], chunk_ref: f64) -> [f32; 4] {
87    let r = map(yt.mapping, chunk_ref);
88    let [o, h, l, c] = ohlc.map(|v| map(yt.mapping, v) - r);
89    [o as f32, f32_up(h), f32_down(l), c as f32].map(gap_or)
90}
91
92/// Stored instead of a relative value that is not finite (a NaN gap of a value
93/// series, the log of a non-positive price). Shaders cannot rely on NaN
94/// checks under fast-math, so gaps are this finite sentinel. Shader: `GAP`.
95pub const GAP: f32 = 3.0e38;
96
97/// `v` if finite, else [`GAP`].
98fn gap_or(v: f32) -> f32 {
99    if v.is_finite() { v } else { GAP }
100}
101
102/// Whether a stored relative value is a gap. Shader: `is_gap()`.
103pub fn is_gap(v_rel: f32) -> bool {
104    // NaN compares false, so it counts as a gap too.
105    v_rel.abs() >= 1.0e38 || v_rel.is_nan()
106}
107
108/// Up/down decision on the relative values. Shader: `is_up_rel()`.
109pub fn is_up_rel(open_rel: f32, close_rel: f32) -> bool {
110    close_rel >= open_rel
111}
112
113/// Pixel snapping used everywhere: round half up, `floor(v + 0.5)`.
114/// Shader: `snap()`.
115pub fn snap(v: f32) -> f32 {
116    (v + 0.5).floor()
117}
118
119/// `offset / step`: the x offset in elements, so that
120/// `x = (d + shift) * step` (no multiply-add to fuse). The per-draw uniform.
121pub fn x_shift(xt: &XTransform) -> f32 {
122    if xt.step == 0.0 {
123        return 0.0;
124    }
125    (f64::from(xt.offset) / f64::from(xt.step)) as f32
126}
127
128/// x of the center of element `j`: `(d + shift) * step` with `d = j - base`.
129/// Shader: `x_center()`.
130///
131/// # Examples
132///
133/// ```
134/// use ferrochart_core::frame::XTransform;
135/// use ferrochart_core::transform_helpers::x_center;
136///
137/// let xt = XTransform { base: 100, step: 4.0, offset: 10.0 };
138/// assert_eq!(x_center(&xt, 102), 18.0);
139/// ```
140pub fn x_center(xt: &XTransform, j: i64) -> f32 {
141    let d = (j - xt.base) as f32;
142    let shifted = d + x_shift(xt);
143    shifted * xt.step
144}
145
146fn map(mapping: PriceMapping, v: f64) -> f64 {
147    match mapping {
148        PriceMapping::Linear => v,
149        PriceMapping::Log => v.ln(),
150    }
151}
152
153/// `f(value) - f(chunk_ref)` as f32: what the GPU buffers store. Computed
154/// on the CPU in both backends.
155pub fn v_rel(yt: &YTransform, value: f64, chunk_ref: f64) -> f32 {
156    (map(yt.mapping, value) - map(yt.mapping, chunk_ref)) as f32
157}
158
159/// The per-chunk uniform: `f(chunk_ref) - f(view_ref) + b / a`, so that
160/// `y = (v_rel + bias) * a` equals `a * (f(value) - f(view_ref)) + b`.
161pub fn y_bias(yt: &YTransform, chunk_ref: f64) -> f32 {
162    if yt.a == 0.0 {
163        return 0.0;
164    }
165    let delta = map(yt.mapping, chunk_ref) - map(yt.mapping, yt.view_ref);
166    (delta + f64::from(yt.b) / f64::from(yt.a)) as f32
167}
168
169/// `y = (v_rel + bias) * a` in f32, in this order. Shader: `y_of()`.
170pub fn y(yt: &YTransform, v_rel: f32, bias: f32) -> f32 {
171    let t = v_rel + bias;
172    t * yt.a
173}
174
175/// y of a single price, with `view_ref` as the chunk reference.
176///
177/// # Examples
178///
179/// ```
180/// use ferrochart_core::frame::{PriceMapping, YTransform};
181/// use ferrochart_core::transform_helpers::y_of_price;
182///
183/// let yt = YTransform { a: -2.0, b: 50.0, view_ref: 100.0, mapping: PriceMapping::Linear };
184/// assert_eq!(y_of_price(&yt, 110.0), 30.0);
185/// ```
186pub fn y_of_price(yt: &YTransform, price: f64) -> f32 {
187    y(yt, v_rel(yt, price, yt.view_ref), y_bias(yt, yt.view_ref))
188}
189
190/// How bars are drawn at a given element step.
191#[derive(Clone, Copy, Debug, PartialEq)]
192pub struct BarMetrics {
193    /// Body width in pixels: `max(1, floor(step * 0.8))`, made odd by subtracting 1.
194    pub body: f32,
195    /// Whether bodies are drawn (`step >= 1.5`); otherwise only high-low wicks.
196    pub show_body: bool,
197    /// Whether body borders are drawn (`step >= 3`).
198    pub show_border: bool,
199}
200
201/// Bar metrics for element spacing `step`. Shader: `bar_metrics()`.
202///
203/// # Examples
204///
205/// ```
206/// use ferrochart_core::transform_helpers::bar_metrics;
207///
208/// assert_eq!(bar_metrics(10.0).body, 7.0); // floor(8) = 8, even -> 7
209/// assert_eq!(bar_metrics(6.0).body, 3.0);  // floor(4.8) = 4 -> 3
210/// assert!(!bar_metrics(1.2).show_body);
211/// ```
212pub fn bar_metrics(step: f32) -> BarMetrics {
213    let mut body = (step * 0.8).floor().max(1.0);
214    if body % 2.0 == 0.0 {
215        body -= 1.0;
216    }
217    BarMetrics {
218        body,
219        show_body: step >= 1.5,
220        show_border: step >= 3.0,
221    }
222}
223
224/// Up/down rule: a bar is "up" when `close >= open`. Shader: `is_up()`.
225pub fn is_up(open: f64, close: f64) -> bool {
226    close >= open
227}
228
229/// Pixel geometry of one candle.
230#[derive(Clone, Copy, Debug, PartialEq)]
231pub struct CandleGeom {
232    /// 1-px wide high-low line.
233    pub wick: RectPx,
234    /// Body, if bodies are drawn at this step.
235    pub body: Option<RectPx>,
236}
237
238/// Vertical pixel span `[snap(min), snap(max))`, at least 1 px tall.
239fn v_span(y0: f32, y1: f32) -> (f32, f32) {
240    let top = snap(y0.min(y1));
241    let bottom = snap(y0.max(y1));
242    (top, (bottom - top).max(1.0))
243}
244
245/// Candle geometry from the element's center x and the y of its prices.
246/// Shader: `candle_vertex()`.
247///
248/// # Examples
249///
250/// ```
251/// use ferrochart_core::transform_helpers::{bar_metrics, candle};
252///
253/// let g = candle(10.3, bar_metrics(6.0), [20.0, 10.0, 40.0, 30.0]);
254/// assert_eq!((g.wick.x, g.wick.w, g.wick.y, g.wick.h), (10.0, 1.0, 10.0, 30.0));
255/// let body = g.body.unwrap();
256/// assert_eq!((body.x, body.w, body.y, body.h), (9.0, 3.0, 20.0, 10.0));
257/// ```
258pub fn candle(xc: f32, m: BarMetrics, ys: [f32; 4]) -> CandleGeom {
259    let [y_open, y_high, y_low, y_close] = ys;
260    let column = xc.floor();
261    let (wy, wh) = v_span(y_high, y_low);
262    let wick = RectPx {
263        x: column,
264        y: wy,
265        w: 1.0,
266        h: wh,
267    };
268    let body = m.show_body.then(|| {
269        let (by, bh) = v_span(y_open, y_close);
270        RectPx {
271            x: column - (m.body - 1.0) * 0.5,
272            y: by,
273            w: m.body,
274            h: bh,
275        }
276    });
277    CandleGeom { wick, body }
278}
279
280/// A histogram column from `y_value` down (or up) to `y_base`. Shader:
281/// `histogram_vertex()`.
282///
283/// # Examples
284///
285/// ```
286/// use ferrochart_core::transform_helpers::{bar_metrics, histogram};
287///
288/// let r = histogram(10.3, bar_metrics(6.0), 80.2, 100.0);
289/// assert_eq!((r.x, r.w, r.y, r.h), (9.0, 3.0, 80.0, 20.0));
290/// ```
291pub fn histogram(xc: f32, m: BarMetrics, y_value: f32, y_base: f32) -> RectPx {
292    let column = xc.floor();
293    let width = if m.show_body { m.body } else { 1.0 };
294    let (y, h) = v_span(y_value, y_base);
295    RectPx {
296        x: column - (width - 1.0) * 0.5,
297        y,
298        w: width,
299        h,
300    }
301}
302
303/// OHLC bar ("American line"): the high-low line, and when bodies are shown at
304/// this step, the open tick on the left and the close tick on the right
305/// (1 px thick, `(body - 1) / 2` long). Shader: `vs_ohlc_bar`.
306///
307/// # Examples
308///
309/// ```
310/// use ferrochart_core::transform_helpers::{bar_metrics, ohlc_bar};
311///
312/// let [wick, open, close] = ohlc_bar(10.3, bar_metrics(10.0), [20.0, 10.0, 40.0, 30.0]);
313/// let (wick, open, close) = (wick.unwrap(), open.unwrap(), close.unwrap());
314/// assert_eq!((wick.x, wick.y, wick.h), (10.0, 10.0, 30.0));
315/// assert_eq!((open.x, open.w, open.y, open.h), (7.0, 3.0, 20.0, 1.0));
316/// assert_eq!((close.x, close.w, close.y), (11.0, 3.0, 30.0));
317/// ```
318pub fn ohlc_bar(xc: f32, m: BarMetrics, ys: [f32; 4]) -> [Option<RectPx>; 3] {
319    let [y_open, y_high, y_low, y_close] = ys;
320    let column = xc.floor();
321    let (wy, wh) = v_span(y_high, y_low);
322    let wick = RectPx {
323        x: column,
324        y: wy,
325        w: 1.0,
326        h: wh,
327    };
328    let half = (m.body - 1.0) * 0.5;
329    if !m.show_body || half < 1.0 {
330        return [Some(wick), None, None];
331    }
332    let (oy, _) = v_span(y_open, y_open);
333    let (cy, _) = v_span(y_close, y_close);
334    let open = RectPx {
335        x: column - half,
336        y: oy,
337        w: half,
338        h: 1.0,
339    };
340    let close = RectPx {
341        x: column + 1.0,
342        y: cy,
343        w: half,
344        h: 1.0,
345    };
346    [Some(wick), Some(open), Some(close)]
347}
348
349/// Alpha coverage in 1/255 steps, as both backends blend it:
350/// `floor(coverage * 255 + 0.5)`. Shader: `coverage_8()`.
351pub fn coverage_8(coverage: f32) -> u8 {
352    (coverage * 255.0 + 0.5).floor().clamp(0.0, 255.0) as u8
353}
354
355/// Coverage of the pixel centered at `p` by the segment `a`→`b` drawn
356/// `2 × half_width` wide with round caps (consecutive segments of a polyline
357/// join without gaps). Anti-aliased over one pixel. Shader:
358/// `segment_coverage()`.
359///
360/// # Examples
361///
362/// ```
363/// use ferrochart_core::geom::{PointPx, Px};
364/// use ferrochart_core::transform_helpers::segment_coverage;
365///
366/// let (a, b) = (PointPx { x: 0.0, y: 10.0 }, PointPx { x: 20.0, y: 10.0 });
367/// assert_eq!(segment_coverage(PointPx { x: 5.5, y: 10.5 }, a, b, Px(1.0)), 1.0);
368/// assert_eq!(segment_coverage(PointPx { x: 5.5, y: 13.5 }, a, b, Px(1.0)), 0.0);
369/// ```
370pub fn segment_coverage(p: PointPx, a: PointPx, b: PointPx, half_width: Px) -> f32 {
371    let pax = p.x - a.x;
372    let pay = p.y - a.y;
373    let bax = b.x - a.x;
374    let bay = b.y - a.y;
375    let len2 = bax * bax + bay * bay;
376    let mut h = 0.0;
377    if len2 > 0.0 {
378        h = ((pax * bax + pay * bay) / len2).clamp(0.0, 1.0);
379    }
380    let dx = pax - bax * h;
381    let dy = pay - bay * h;
382    let d = (dx * dx + dy * dy).sqrt();
383    (half_width.0 + 0.5 - d).clamp(0.0, 1.0)
384}
385
386/// Direction and length of the line `a`→`b` (the length is at least 1e-4,
387/// so the direction is always defined). Shader: `vs_line()`.
388pub fn line_axis(a: PointPx, b: PointPx) -> (PointPx, f32) {
389    let dx = b.x - a.x;
390    let dy = b.y - a.y;
391    let len = (dx * dx + dy * dy).sqrt().max(1e-4);
392    (
393        PointPx {
394            x: dx / len,
395            y: dy / len,
396        },
397        len,
398    )
399}
400
401/// Coverage of a pixel by an immediate line (`LineInst`) of length
402/// `len` and `width`, butt ends, anti-aliased over one pixel: `along` is the
403/// pixel center's distance along the line from its start, `across` its
404/// signed distance from the axis. Dashes are `4w` on, `4w` off and dots `w`
405/// on, `2w` off, measured along the line. Shader: `line_coverage()`.
406///
407/// # Examples
408///
409/// ```
410/// use ferrochart_core::frame::LineDash;
411/// use ferrochart_core::geom::Px;
412/// use ferrochart_core::transform_helpers::line_coverage;
413///
414/// assert_eq!(line_coverage(5.0, 0.0, 10.0, Px(1.0), LineDash::Solid), 1.0);
415/// assert_eq!(line_coverage(5.0, 2.0, 10.0, Px(1.0), LineDash::Solid), 0.0);
416/// assert_eq!(line_coverage(5.0, 0.0, 10.0, Px(1.0), LineDash::Dashed), 0.0);
417/// ```
418pub fn line_coverage(along: f32, across: f32, len: f32, width: Px, dash: LineDash) -> f32 {
419    let half = width.0 * 0.5;
420    let cov_across = (half + 0.5 - across.abs()).clamp(0.0, 1.0);
421    let cov_along = (along.min(len - along) + 0.5).clamp(0.0, 1.0);
422    let on = match dash {
423        LineDash::Solid => true,
424        LineDash::Dashed => {
425            let t = along / (8.0 * width.0);
426            t - t.floor() < 0.5
427        }
428        LineDash::Dotted => {
429            let t = along / (3.0 * width.0);
430            t - t.floor() < 1.0 / 3.0
431        }
432    };
433    if on { cov_across * cov_along } else { 0.0 }
434}
435
436/// Built-in icon: filled circle (markers).
437pub const ICON_CIRCLE: u16 = 0;
438/// Built-in icon: filled square.
439pub const ICON_SQUARE: u16 = 1;
440/// Built-in icon: arrow pointing up.
441pub const ICON_ARROW_UP: u16 = 2;
442/// Built-in icon: arrow pointing down.
443pub const ICON_ARROW_DOWN: u16 = 3;
444
445/// Coverage of the pixel whose center is `(dx, dy)` from the center of a
446/// built-in icon `size` pixels across (the "atlas" is these signed
447/// distance functions), anti-aliased over one pixel; 0 for unknown icons.
448/// Shader: `icon_coverage()` in `prims.wgsl`.
449///
450/// # Examples
451///
452/// ```
453/// use ferrochart_core::transform_helpers::{ICON_ARROW_UP, ICON_CIRCLE, icon_coverage};
454///
455/// assert_eq!(icon_coverage(ICON_CIRCLE, 0.5, 0.5, 10.0), 1.0);
456/// assert_eq!(icon_coverage(ICON_CIRCLE, 6.5, 0.5, 10.0), 0.0);
457/// // The tip of an up arrow is at the top (y grows downwards).
458/// assert!(icon_coverage(ICON_ARROW_UP, 0.0, -4.0, 10.0) > 0.0);
459/// assert_eq!(icon_coverage(ICON_ARROW_UP, 4.0, -4.0, 10.0), 0.0);
460/// ```
461pub fn icon_coverage(icon: u16, dx: f32, dy: f32, size: f32) -> f32 {
462    let h = size * 0.5;
463    let ax = dx.abs();
464    let d = match icon {
465        ICON_CIRCLE => (dx * dx + dy * dy).sqrt() - h,
466        ICON_SQUARE => {
467            let s = h * 0.8;
468            (ax - s).max(dy.abs() - s)
469        }
470        ICON_ARROW_UP | ICON_ARROW_DOWN => {
471            let ty = if icon == ICON_ARROW_UP { dy } else { -dy };
472            // Head: the triangle (0, -h), (±h, 0); shaft: |x| ≤ 0.35h, 0 ≤ y ≤ h.
473            let head = ty.max((ax - ty - h) * 0.707_106_77);
474            let q = h * 0.5;
475            let shaft = (ax - h * 0.35).max((ty - q).abs() - q);
476            head.min(shaft)
477        }
478        _ => return 0.0,
479    };
480    (0.5 - d).clamp(0.0, 1.0)
481}
482
483/// Whether the dash pattern is "on" at pixel center `x` for a line of the
484/// given width (patterns follow the x axis, which suits the mostly horizontal
485/// series lines). Dashes: `4w` on, `4w` off; dots: `w` on, `w` off. Shader:
486/// `dash_on()`.
487pub fn dash_on(x: Px, width: Px, dash: LineDash) -> bool {
488    let period = match dash {
489        LineDash::Solid => return true,
490        LineDash::Dashed => 4.0 * width.0,
491        LineDash::Dotted => width.0,
492    };
493    let k = (x.0 / period).floor();
494    k - 2.0 * (k * 0.5).floor() < 0.5
495}
496
497/// Coverage of the pixel centered at `p` by the fill between the edge `a`→`b`
498/// and the horizontal line `base_y`, within the column range `[a.x, b.x)`
499/// (half-open, so adjacent columns never overlap). Both horizontal edges are
500/// anti-aliased. Shader: `fill_coverage()`.
501///
502/// # Examples
503///
504/// ```
505/// use ferrochart_core::geom::{PointPx, Px};
506/// use ferrochart_core::transform_helpers::fill_coverage;
507///
508/// let (a, b) = (PointPx { x: 0.0, y: 10.0 }, PointPx { x: 10.0, y: 10.0 });
509/// assert_eq!(fill_coverage(PointPx { x: 2.5, y: 15.5 }, a, b, Px(20.0)), 1.0);
510/// assert_eq!(fill_coverage(PointPx { x: 2.5, y: 5.5 }, a, b, Px(20.0)), 0.0);
511/// assert_eq!(fill_coverage(PointPx { x: 10.5, y: 15.5 }, a, b, Px(20.0)), 0.0);
512/// ```
513pub fn fill_coverage(p: PointPx, a: PointPx, b: PointPx, base_y: Px) -> f32 {
514    if !(p.x >= a.x && p.x < b.x) {
515        return 0.0;
516    }
517    let t = (p.x - a.x) / (b.x - a.x);
518    let edge = a.y + (b.y - a.y) * t;
519    let lo = edge.min(base_y.0);
520    let hi = edge.max(base_y.0);
521    ((p.y - lo).min(hi - p.y) + 0.5).clamp(0.0, 1.0)
522}
523
524/// Coverage of the pixel centered at `p` by a band between the upper edge
525/// `a`→`b` and the lower edge from `(a.x, lower_a)` to `(b.x, lower_b)`,
526/// within `[a.x, b.x)` like [`fill_coverage`], and whether the upper series
527/// is below the lower one there (`crossed`). `scale` is the y transform's
528/// `a`: its sign says which way values grow on screen. Shader:
529/// `band_coverage()`.
530///
531/// # Examples
532///
533/// ```
534/// use ferrochart_core::geom::PointPx;
535/// use ferrochart_core::transform_helpers::band_coverage;
536///
537/// let (a, b) = (PointPx { x: 0.0, y: 10.0 }, PointPx { x: 10.0, y: 10.0 });
538/// // Lower edge at y = 20: inside between 10 and 20 (y grows downwards, a < 0).
539/// assert_eq!(band_coverage(PointPx { x: 5.5, y: 15.5 }, a, b, 20.0, 20.0, -1.0), (1.0, false));
540/// assert_eq!(band_coverage(PointPx { x: 5.5, y: 25.5 }, a, b, 20.0, 20.0, -1.0).0, 0.0);
541/// // The "lower" series drawn above it: crossed.
542/// assert!(band_coverage(PointPx { x: 5.5, y: 7.5 }, a, b, 5.0, 5.0, -1.0).1);
543/// ```
544pub fn band_coverage(
545    p: PointPx,
546    a: PointPx,
547    b: PointPx,
548    lower_a: f32,
549    lower_b: f32,
550    scale: f32,
551) -> (f32, bool) {
552    if !(p.x >= a.x && p.x < b.x) {
553        return (0.0, false);
554    }
555    let t = (p.x - a.x) / (b.x - a.x);
556    let upper = a.y + (b.y - a.y) * t;
557    let lower = lower_a + (lower_b - lower_a) * t;
558    let lo = upper.min(lower);
559    let hi = upper.max(lower);
560    let coverage = ((p.y - lo).min(hi - p.y) + 0.5).clamp(0.0, 1.0);
561    (coverage, (lower - upper) * scale > 0.0)
562}
563
564/// The line segments of one element of a value series. `cur` and `next` are
565/// the stored relative `[first, max, min, last]` of elements `j` and `j + 1`
566/// (both relative to element `j`'s chunk reference), `xj`/`xn` their center
567/// x. Segment 0 is the max-min range of an LOD bucket (absent at level 0,
568/// where max == min); segment 1 connects `last(j)` to `first(j + 1)`, or for a
569/// step line runs horizontally to `xn`, and segment 2 is then the vertical
570/// step. Gaps break the line. Shader: `vs_line_series`.
571pub fn line_segments(
572    yt: &YTransform,
573    bias: f32,
574    xj: f32,
575    xn: f32,
576    cur: [f32; 4],
577    next: [f32; 4],
578    step: bool,
579) -> [Option<(PointPx, PointPx)>; 3] {
580    let [_, hi, lo, last] = cur;
581    let first_n = next[0];
582    let p = |x: f32, v: f32| PointPx {
583        x,
584        y: y(yt, v, bias),
585    };
586    let mut out = [None; 3];
587    if !is_gap(hi) && !is_gap(lo) && hi.to_bits() != lo.to_bits() {
588        out[0] = Some((p(xj, hi), p(xj, lo)));
589    }
590    if !is_gap(last) && !is_gap(first_n) {
591        if step {
592            out[1] = Some((p(xj, last), p(xn, last)));
593            out[2] = Some((p(xn, last), p(xn, first_n)));
594        } else {
595            out[1] = Some((p(xj, last), p(xn, first_n)));
596        }
597    }
598    out
599}
600
601/// The top edge of the fill under one element of an area or baseline series
602/// (see [`line_segments`]); `None` across gaps. Shader: `vs_fill_series`.
603pub fn fill_edge(
604    yt: &YTransform,
605    bias: f32,
606    xj: f32,
607    xn: f32,
608    cur: [f32; 4],
609    next: [f32; 4],
610    step: bool,
611) -> Option<(PointPx, PointPx)> {
612    let (last, first_n) = (cur[3], next[0]);
613    if is_gap(last) || is_gap(first_n) {
614        return None;
615    }
616    let y0 = y(yt, last, bias);
617    let y1 = if step { y0 } else { y(yt, first_n, bias) };
618    Some((PointPx { x: xj, y: y0 }, PointPx { x: xn, y: y1 }))
619}
620
621/// The y a histogram column of a value series reaches: of the element's max
622/// and min, the one farther from the base (so LOD buckets keep their spikes).
623/// `None` for a gap. Shader: `vs_value_histogram`.
624pub fn histogram_value_y(yt: &YTransform, bias: f32, cur: [f32; 4], base_y: f32) -> Option<f32> {
625    let (hi, lo) = (cur[1], cur[2]);
626    if is_gap(hi) || is_gap(lo) {
627        return None;
628    }
629    let (y_hi, y_lo) = (y(yt, hi, bias), y(yt, lo, bias));
630    Some(if (y_hi - base_y).abs() >= (y_lo - base_y).abs() {
631        y_hi
632    } else {
633        y_lo
634    })
635}
636
637/// Position of `y` in a vertical gradient from `top` (0) to `bottom` (1).
638/// Shader: `gradient_t()`.
639pub fn gradient_t(y: Px, top: Px, bottom: Px) -> f32 {
640    let h = bottom.0 - top.0;
641    if h <= 0.0 {
642        return 0.0;
643    }
644    ((y.0 - top.0) / h).clamp(0.0, 1.0)
645}
646
647#[cfg(test)]
648#[allow(clippy::float_cmp)] // exact values are the point of these tests
649mod tests {
650    use super::*;
651
652    #[test]
653    fn body_is_odd_and_fits_in_step() {
654        for i in 1..2000 {
655            let step = i as f32 * 0.05;
656            let m = bar_metrics(step);
657            assert!(m.body >= 1.0);
658            assert_eq!(m.body % 2.0, 1.0, "step {step}");
659            assert!(m.body <= step.max(1.0), "step {step}");
660        }
661    }
662
663    #[test]
664    fn log_mapping_is_relative() {
665        let yt = YTransform {
666            a: -100.0,
667            b: 0.0,
668            view_ref: 10.0,
669            mapping: PriceMapping::Log,
670        };
671        // One e-fold above the reference moves 100 px up.
672        assert!((y_of_price(&yt, 10.0 * core::f64::consts::E) + 100.0).abs() < 1e-3);
673    }
674}