Skip to main content

ferrochart_render_cpu/
lib.rs

1//! CPU rendering backend for FerroChart, built on `tiny-skia`.
2//!
3//! Executes the `DrawCmd`s of a `Frame` one by one. `DrawCmd::Series` is expanded
4//! on the CPU with the core's `transform_helpers`, the same f32 arithmetic the
5//! wgpu shaders use, so both backends produce the same pixels. Rectangles,
6//! axis-aligned lines and text are drawn without anti-aliasing by direct
7//! source-over blending into the pixmap; only slanted or dashed lines go through
8//! `tiny-skia`'s anti-aliased stroker.
9//!
10//! Uses: golden-image tests, server-side rendering, fallback without a GPU. No
11//! performance targets.
12//!
13//! # Examples
14//!
15//! ```
16//! use ferrochart_core::chart::{SeriesData, SeriesOptions};
17//! use ferrochart_core::frame::SeriesKind;
18//! use ferrochart_core::geom::SizeCss;
19//! use ferrochart_core::render::Renderer;
20//! use ferrochart_core::testing::random_walk;
21//! use ferrochart_core::{Chart, ChartOptions};
22//! use ferrochart_render_cpu::CpuRenderer;
23//!
24//! let mut chart = Chart::new(ChartOptions::default());
25//! chart.resize(SizeCss { w: 320.0, h: 200.0 }, 1.0);
26//! let id = chart.add_series(chart.main_pane(), SeriesKind::Candlestick, SeriesOptions::default())?;
27//! chart.set_data(id, SeriesData::Ohlc(random_walk(7, 200, 0, 60_000)?))?;
28//!
29//! let mut renderer = CpuRenderer::new();
30//! chart.build_frame(0.0, &renderer.measurer());
31//! renderer.render(chart.frame(), &chart.data_view())?;
32//! assert_eq!(renderer.pixmap().map(|p| p.width()), Some(320));
33//! # Ok::<(), Box<dyn std::error::Error>>(())
34//! ```
35//!
36#![forbid(unsafe_code)]
37
38use ferrochart_core::chart::ChartDataView;
39use ferrochart_core::data::OhlcLevelView;
40use ferrochart_core::frame::{
41    DrawCmd, FontStyleRef, Frame, IconInst, LineDash, LineInst, PriceMapping, SeriesDraw,
42    SeriesKind, SeriesStyle, TextAlign, TextRun, YTransform,
43};
44use ferrochart_core::geom::{PointPx, Px, RectPx, Rgba, SizePx};
45use ferrochart_core::render::{RenderError, Renderer};
46use ferrochart_core::text::TextMeasurer;
47use ferrochart_core::transform_helpers::{
48    ICON_CIRCLE, band_coverage, bar_metrics, candle, chunk_of, coverage_8, dash_on, fill_coverage,
49    fill_edge, gradient_t, histogram, histogram_value_y, icon_coverage, initial_chunk_ref, is_gap,
50    is_up_rel, line_axis, line_coverage, line_segments, ohlc_bar, ohlc_rel, segment_coverage,
51    v_rel, x_center, y, y_bias, y_of_price,
52};
53use ferrochart_text::{GlyphCache, TextEngine};
54use tiny_skia::{FillRule, Mask, Paint, PathBuilder, Pixmap, Transform};
55
56/// Adapts a [`TextEngine`] to the core's [`TextMeasurer`].
57///
58/// # Examples
59///
60/// ```
61/// use ferrochart_core::frame::{FontId, FontStyleRef};
62/// use ferrochart_core::text::text_width;
63/// use ferrochart_render_cpu::EngineMeasurer;
64/// use ferrochart_text::TextEngine;
65///
66/// let engine = TextEngine::new();
67/// let style = FontStyleRef { font: FontId(0), size: 10.0 };
68/// let w = text_width(&EngineMeasurer(&engine), "100.00", style);
69/// assert!((w - engine.width(0, "100.00", 10.0)).abs() < 1e-4);
70/// ```
71#[derive(Clone, Copy, Debug)]
72pub struct EngineMeasurer<'a>(pub &'a TextEngine);
73
74impl TextMeasurer for EngineMeasurer<'_> {
75    fn ascii_advances(&self, style: FontStyleRef) -> &[f32; 128] {
76        self.0.ascii_advances(style.font.0)
77    }
78
79    fn subscript_advances(&self, style: FontStyleRef) -> Option<&[f32; 10]> {
80        Some(self.0.subscript_advances(style.font.0))
81    }
82
83    fn measure(&self, text: &str, style: FontStyleRef) -> SizePx {
84        SizePx {
85            w: self.0.width(style.font.0, text, style.size),
86            h: self.line_height(style),
87        }
88    }
89
90    fn line_height(&self, style: FontStyleRef) -> f32 {
91        self.0.line_metrics(style.font.0, style.size).height()
92    }
93}
94
95/// Integer pixel box `[x0, x1) × [y0, y1)`.
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
97struct IBox {
98    x0: i32,
99    y0: i32,
100    x1: i32,
101    y1: i32,
102}
103
104impl IBox {
105    fn of_rect(r: RectPx) -> Self {
106        Self {
107            x0: r.x.round() as i32,
108            y0: r.y.round() as i32,
109            x1: (r.x + r.w).round() as i32,
110            y1: (r.y + r.h).round() as i32,
111        }
112    }
113
114    fn intersect(self, o: Self) -> Self {
115        Self {
116            x0: self.x0.max(o.x0),
117            y0: self.y0.max(o.y0),
118            x1: self.x1.min(o.x1),
119            y1: self.y1.min(o.y1),
120        }
121    }
122
123    fn is_empty(self) -> bool {
124        self.x1 <= self.x0 || self.y1 <= self.y0
125    }
126}
127
128/// The CPU renderer.
129#[derive(Debug)]
130pub struct CpuRenderer {
131    pixmap: Option<Pixmap>,
132    text: TextEngine,
133    glyphs: GlyphCache,
134    clips: Vec<IBox>,
135}
136
137impl Default for CpuRenderer {
138    fn default() -> Self {
139        Self::new()
140    }
141}
142
143impl CpuRenderer {
144    /// A renderer with the bundled font. The target is sized by the first frame.
145    pub fn new() -> Self {
146        Self::with_text_engine(TextEngine::new())
147    }
148
149    /// A renderer with a custom text engine (extra fonts).
150    pub fn with_text_engine(text: TextEngine) -> Self {
151        Self {
152            pixmap: None,
153            text,
154            glyphs: GlyphCache::default(),
155            clips: Vec::new(),
156        }
157    }
158
159    /// The text measurer to pass to `Chart::build_frame`.
160    pub fn measurer(&self) -> EngineMeasurer<'_> {
161        EngineMeasurer(&self.text)
162    }
163
164    /// The text engine.
165    pub fn text_engine(&self) -> &TextEngine {
166        &self.text
167    }
168
169    /// The rendered image (premultiplied RGBA), once something was rendered.
170    pub fn pixmap(&self) -> Option<&Pixmap> {
171        self.pixmap.as_ref()
172    }
173
174    /// The rendered image as PNG.
175    ///
176    /// # Errors
177    ///
178    /// [`RenderError::InvalidSize`] if nothing was rendered yet,
179    /// [`RenderError::Backend`] if encoding fails.
180    pub fn encode_png(&self) -> Result<Vec<u8>, RenderError> {
181        self.pixmap
182            .as_ref()
183            .ok_or(RenderError::InvalidSize)?
184            .encode_png()
185            .map_err(|_| RenderError::Backend("PNG encoding failed"))
186    }
187
188    fn ensure_target(&mut self, size: SizePx) -> Result<(), RenderError> {
189        let (w, h) = (size.w.round(), size.h.round());
190        if !(w >= 1.0 && h >= 1.0 && w <= 16_384.0 && h <= 16_384.0) {
191            return Err(RenderError::InvalidSize);
192        }
193        let (w, h) = (w as u32, h as u32);
194        if self
195            .pixmap
196            .as_ref()
197            .is_none_or(|p| p.width() != w || p.height() != h)
198        {
199            self.pixmap = Some(Pixmap::new(w, h).ok_or(RenderError::InvalidSize)?);
200        }
201        Ok(())
202    }
203
204    fn clip(&self) -> Option<IBox> {
205        self.clips.last().copied()
206    }
207}
208
209impl Renderer for CpuRenderer {
210    fn render(&mut self, frame: &Frame, data: &ChartDataView<'_>) -> Result<(), RenderError> {
211        self.ensure_target(frame.size_px)?;
212        let Some(mut pixmap) = self.pixmap.take() else {
213            return Err(RenderError::InvalidSize);
214        };
215        let c = frame.clear_color;
216        pixmap.fill(tiny_skia::Color::from_rgba8(c.r, c.g, c.b, c.a));
217        let full = IBox {
218            x0: 0,
219            y0: 0,
220            x1: pixmap.width() as i32,
221            y1: pixmap.height() as i32,
222        };
223        for layer in &frame.layers {
224            self.clips.clear();
225            self.clips.push(full);
226            for cmd in &layer.cmds {
227                self.execute(&mut pixmap, frame, *data, cmd);
228            }
229        }
230        self.pixmap = Some(pixmap);
231        Ok(())
232    }
233
234    fn resize(&mut self, size: SizePx) {
235        // An invalid size keeps the old target; `render` reports it.
236        let _ = self.ensure_target(size);
237    }
238}
239
240impl CpuRenderer {
241    fn execute(&mut self, pm: &mut Pixmap, frame: &Frame, data: ChartDataView<'_>, cmd: &DrawCmd) {
242        let pools = &frame.pools;
243        match *cmd {
244            DrawCmd::PushClip(r) => {
245                let top = self
246                    .clip()
247                    .map_or(IBox::of_rect(r), |c| c.intersect(IBox::of_rect(r)));
248                self.clips.push(top);
249            }
250            // Never pop the full-target clip.
251            DrawCmd::PopClip if self.clips.len() > 1 => {
252                self.clips.pop();
253            }
254            DrawCmd::Rects(span) => {
255                for r in pools.rects.get(span.range()).unwrap_or(&[]) {
256                    self.fill_rect(pm, r.rect, r.color);
257                }
258            }
259            DrawCmd::Lines(span) => {
260                for l in pools.lines.get(span.range()).unwrap_or(&[]) {
261                    self.draw_line(pm, *l);
262                }
263            }
264            DrawCmd::Polyline { points, style } => {
265                let pts = pools.points.get(points.range()).unwrap_or(&[]);
266                for w in pts.windows(2) {
267                    self.draw_line(
268                        pm,
269                        LineInst {
270                            from: w[0],
271                            to: w[1],
272                            stroke: style,
273                        },
274                    );
275                }
276            }
277            DrawCmd::Polygon { points, fill } => {
278                let pts = pools.points.get(points.range()).unwrap_or(&[]);
279                self.fill_polygon(pm, pts, fill);
280            }
281            DrawCmd::Text(span) => {
282                for run in pools.text_runs.get(span.range()).unwrap_or(&[]) {
283                    let text = pools.text.get(run.text.range()).unwrap_or("");
284                    self.draw_text(pm, run, text);
285                }
286            }
287            DrawCmd::Series(s) => self.draw_series(pm, frame, data, &s),
288            DrawCmd::Icon(span) => {
289                for icon in pools.icons.get(span.range()).unwrap_or(&[]) {
290                    self.draw_icon(pm, icon);
291                }
292            }
293            // Unbalanced pops are ignored. No native kinds are declared here,
294            // so core never sends a custom draw.
295            DrawCmd::PopClip | DrawCmd::Custom(_) => {}
296        }
297    }
298
299    /// Source-over blend of `color × coverage/255` into pixel `(x, y)`.
300    fn blend(pm: &mut Pixmap, x: i32, y: i32, color: Rgba, coverage: u8) {
301        let w = pm.width() as i32;
302        let i = (y * w + x) as usize * 4;
303        let a = u32::from(color.a) * u32::from(coverage) / 255;
304        if a == 0 {
305            return;
306        }
307        let data = pm.data_mut();
308        let Some(px) = data.get_mut(i..i + 4) else {
309            return;
310        };
311        let inv = 255 - a;
312        let src = [color.r, color.g, color.b];
313        for k in 0..3 {
314            let s = u32::from(src[k]) * a / 255;
315            px[k] = (s + (u32::from(px[k]) * inv + 127) / 255).min(255) as u8;
316        }
317        px[3] = (a + (u32::from(px[3]) * inv + 127) / 255).min(255) as u8;
318    }
319
320    fn fill_box(&self, pm: &mut Pixmap, b: IBox, color: Rgba) {
321        let Some(clip) = self.clip() else {
322            return;
323        };
324        let b = b.intersect(clip);
325        if b.is_empty() || color.a == 0 {
326            return;
327        }
328        for y in b.y0..b.y1 {
329            for x in b.x0..b.x1 {
330                Self::blend(pm, x, y, color, 255);
331            }
332        }
333    }
334
335    /// Built-in icon by its coverage function; shader `fs_icon`.
336    fn draw_icon(&self, pm: &mut Pixmap, icon: &IconInst) {
337        let Some(clip) = self.clip() else {
338            return;
339        };
340        let reach = icon.size.0 * 0.5 + 1.0;
341        let b = IBox {
342            x0: (icon.pos.x - reach).floor() as i32,
343            y0: (icon.pos.y - reach).floor() as i32,
344            x1: (icon.pos.x + reach).ceil() as i32,
345            y1: (icon.pos.y + reach).ceil() as i32,
346        }
347        .intersect(clip);
348        if b.is_empty() || icon.color.a == 0 {
349            return;
350        }
351        for y in b.y0..b.y1 {
352            for x in b.x0..b.x1 {
353                let dx = x as f32 + 0.5 - icon.pos.x;
354                let dy = y as f32 + 0.5 - icon.pos.y;
355                let c = icon_coverage(icon.icon, dx, dy, icon.size.0);
356                Self::blend(pm, x, y, icon.color, coverage_8(c));
357            }
358        }
359    }
360
361    fn fill_rect(&self, pm: &mut Pixmap, r: RectPx, color: Rgba) {
362        self.fill_box(pm, IBox::of_rect(r), color);
363    }
364
365    fn draw_line(&self, pm: &mut Pixmap, l: LineInst) {
366        let width = l.stroke.width.0.max(1.0).round();
367        let solid = l.stroke.dash == LineDash::Solid;
368        // Axis-aligned solid lines: exact pixel columns/rows, no anti-aliasing.
369        let vertical = (l.from.x - l.to.x).abs() < 1e-3;
370        let horizontal = (l.from.y - l.to.y).abs() < 1e-3;
371        if solid && (vertical || horizontal) {
372            let half = width * 0.5;
373            let r = if vertical {
374                RectPx {
375                    x: l.from.x - half,
376                    y: l.from.y.min(l.to.y),
377                    w: width,
378                    h: (l.to.y - l.from.y).abs().max(1.0),
379                }
380            } else {
381                RectPx {
382                    x: l.from.x.min(l.to.x),
383                    y: l.from.y - half,
384                    w: (l.to.x - l.from.x).abs().max(1.0),
385                    h: width,
386                }
387            };
388            self.fill_rect(pm, r, l.stroke.color);
389            return;
390        }
391        // Slanted or dashed: per-pixel coverage, as the wgpu line shader.
392        let Some(clip) = self.clip() else {
393            return;
394        };
395        let (a, b) = (l.from, l.to);
396        let (dir, len) = line_axis(a, b);
397        let reach = width * 0.5 + 1.0;
398        let bx = IBox {
399            x0: (a.x.min(b.x) - reach).floor() as i32,
400            y0: (a.y.min(b.y) - reach).floor() as i32,
401            x1: (a.x.max(b.x) + reach).ceil() as i32,
402            y1: (a.y.max(b.y) + reach).ceil() as i32,
403        }
404        .intersect(clip);
405        if bx.is_empty() || l.stroke.color.a == 0 {
406            return;
407        }
408        for y in bx.y0..bx.y1 {
409            for x in bx.x0..bx.x1 {
410                let px = x as f32 + 0.5 - a.x;
411                let py = y as f32 + 0.5 - a.y;
412                let along = px * dir.x + py * dir.y;
413                let across = py * dir.x - px * dir.y;
414                let c = line_coverage(along, across, len, Px(width), l.stroke.dash);
415                if c > 0.0 {
416                    Self::blend(pm, x, y, l.stroke.color, coverage_8(c));
417                }
418            }
419        }
420    }
421
422    fn fill_polygon(&self, pm: &mut Pixmap, pts: &[PointPx], fill: Rgba) {
423        let mut pb = PathBuilder::new();
424        for (i, p) in pts.iter().enumerate() {
425            if i == 0 {
426                pb.move_to(p.x, p.y);
427            } else {
428                pb.line_to(p.x, p.y);
429            }
430        }
431        pb.close();
432        let Some(path) = pb.finish() else {
433            return;
434        };
435        let mask = self.mask(pm);
436        // Not anti-aliased: pixels whose centers are inside, as the wgpu
437        // backend's triangles. Drawing outlines cover the edges.
438        let mut paint = Self::paint(fill);
439        paint.anti_alias = false;
440        pm.fill_path(
441            &path,
442            &paint,
443            FillRule::Winding,
444            Transform::identity(),
445            mask.as_ref(),
446        );
447    }
448
449    fn paint(c: Rgba) -> Paint<'static> {
450        let mut paint = Paint::default();
451        paint.set_color_rgba8(c.r, c.g, c.b, c.a);
452        paint.anti_alias = true;
453        paint
454    }
455
456    /// A mask for the current clip, `None` if it covers the whole target.
457    fn mask(&self, pm: &Pixmap) -> Option<Mask> {
458        let clip = self.clip()?;
459        let (w, h) = (pm.width() as i32, pm.height() as i32);
460        if clip
461            == (IBox {
462                x0: 0,
463                y0: 0,
464                x1: w,
465                y1: h,
466            })
467        {
468            return None;
469        }
470        let mut mask = Mask::new(pm.width(), pm.height())?;
471        let rect = tiny_skia::Rect::from_ltrb(
472            clip.x0 as f32,
473            clip.y0 as f32,
474            clip.x1 as f32,
475            clip.y1 as f32,
476        )?;
477        let path = PathBuilder::from_rect(rect);
478        mask.fill_path(&path, FillRule::Winding, false, Transform::identity());
479        Some(mask)
480    }
481
482    fn draw_text(&mut self, pm: &mut Pixmap, run: &TextRun, text: &str) {
483        let font = run.style.font.0;
484        let size = run.style.size;
485        let width = self.text.width(font, text, size);
486        let m = self.text.line_metrics(font, size);
487        let x0 = match run.align {
488            TextAlign::Left => run.pos.x,
489            TextAlign::Center => run.pos.x - width * 0.5,
490            TextAlign::Right => run.pos.x - width,
491        }
492        .round();
493        // `pos.y` is the center of the ascent..descent box.
494        let baseline = (run.pos.y + (m.ascent - m.descent) * 0.5).round();
495        if let Some(bg) = run.bg {
496            let pad = bg.padding.0;
497            self.fill_rect(
498                pm,
499                RectPx {
500                    x: x0 - pad,
501                    y: baseline - m.ascent - pad,
502                    w: width + 2.0 * pad,
503                    h: m.ascent + m.descent + 2.0 * pad,
504                },
505                bg.color,
506            );
507        }
508        let Some(clip) = self.clip() else {
509            return;
510        };
511        let mut pen = 0.0_f32;
512        for ch in text.chars() {
513            let gx = (x0 + pen).round() as i32;
514            pen += self.text.advance(font, ch, size);
515            let Some(g) = self.glyphs.get(&self.text, font, ch, size) else {
516                continue;
517            };
518            let (left, top) = (gx + g.left, baseline as i32 + g.top);
519            for gy in 0..g.height as i32 {
520                let y = top + gy;
521                if y < clip.y0 || y >= clip.y1 {
522                    continue;
523                }
524                for gxi in 0..g.width as i32 {
525                    let x = left + gxi;
526                    if x < clip.x0 || x >= clip.x1 {
527                        continue;
528                    }
529                    let cov = g.coverage[(gy * g.width as i32 + gxi) as usize];
530                    if cov > 0 {
531                        Self::blend(pm, x, y, run.color, cov);
532                    }
533                }
534            }
535        }
536    }
537
538    fn draw_series(
539        &mut self,
540        pm: &mut Pixmap,
541        frame: &Frame,
542        data: ChartDataView<'_>,
543        s: &SeriesDraw,
544    ) {
545        let Some(view) = data.ohlc(s.series, s.lod_level) else {
546            return;
547        };
548        let Some(style) = frame.styles.get(s.style.0 as usize).copied() else {
549            return;
550        };
551        self.clips
552            .push(self.clip().map_or(IBox::of_rect(s.clip), |c| {
553                c.intersect(IBox::of_rect(s.clip))
554            }));
555        let m = bar_metrics(s.x_transform.step);
556        let yt = &s.y_transform;
557        let range = s.index_range;
558        let level = view.level;
559        let bar = |j: i64| {
560            Some([
561                view.open.at(view.first, j)?,
562                view.high.at(view.first, j)?,
563                view.low.at(view.first, j)?,
564                view.close.at(view.first, j)?,
565            ])
566        };
567        // Per-chunk reference price, exactly as the GPU backend chooses it.
568        let mut chunk = (i64::MIN, None::<f64>);
569        let mut chunk_ref = |j: i64| {
570            let c = chunk_of(level, j);
571            if chunk.0 != c {
572                chunk = (c, initial_chunk_ref(&view, c));
573            }
574            chunk.1
575        };
576        match s.kind {
577            SeriesKind::Candlestick | SeriesKind::HeikinAshi | SeriesKind::OhlcBar => {
578                for j in range.start..range.end {
579                    let (Some(ohlc), Some(r)) = (bar(j), chunk_ref(j)) else {
580                        continue;
581                    };
582                    let rel = ohlc_rel(yt, ohlc, r);
583                    if rel.iter().any(|&v| is_gap(v)) {
584                        continue;
585                    }
586                    let bias = y_bias(yt, r);
587                    let xc = x_center(&s.x_transform, j);
588                    let ys = rel.map(|v| y(yt, v, bias));
589                    let up = is_up_rel(rel[0], rel[3]);
590                    if s.kind == SeriesKind::OhlcBar {
591                        let color = if up { style.up } else { style.down };
592                        for r in ohlc_bar(xc, m, ys).into_iter().flatten() {
593                            self.fill_rect(pm, r, color);
594                        }
595                        continue;
596                    }
597                    let g = candle(xc, m, ys);
598                    let wick = if up { style.up_wick } else { style.down_wick };
599                    self.fill_rect(pm, g.wick, wick);
600                    if let Some(body) = g.body {
601                        let border = if up {
602                            style.up_border
603                        } else {
604                            style.down_border
605                        };
606                        let fill = if up { style.up } else { style.down };
607                        if m.show_border && border != fill {
608                            self.fill_rect(pm, body, border);
609                            let inner = RectPx {
610                                x: body.x + 1.0,
611                                y: body.y + 1.0,
612                                w: body.w - 2.0,
613                                h: body.h - 2.0,
614                            };
615                            if inner.w > 0.0 && inner.h > 0.0 {
616                                self.fill_rect(pm, inner, fill);
617                            }
618                        } else {
619                            self.fill_rect(pm, body, fill);
620                        }
621                    }
622                }
623            }
624            SeriesKind::Volume => {
625                let Some(volume) = view.volume else {
626                    self.clips.pop();
627                    return;
628                };
629                // Volumes are stored relative to 0; up/down uses the linear
630                // OHLC buffer.
631                let linear = YTransform {
632                    mapping: PriceMapping::Linear,
633                    ..*yt
634                };
635                let base = y_of_price(yt, 0.0);
636                let bias = y_bias(yt, 0.0);
637                for j in range.start..range.end {
638                    let (Some(ohlc), Some(v), Some(r)) =
639                        (bar(j), volume.at(view.first, j), chunk_ref(j))
640                    else {
641                        continue;
642                    };
643                    let rel = ohlc_rel(&linear, ohlc, r);
644                    // A gap bar of the source series has no volume bar.
645                    if rel.iter().any(|&v| is_gap(v)) {
646                        continue;
647                    }
648                    let xc = x_center(&s.x_transform, j);
649                    let r = histogram(xc, m, y(yt, v_rel(yt, v, 0.0), bias), base);
650                    let up = is_up_rel(rel[0], rel[3]);
651                    self.fill_rect(pm, r, if up { style.up } else { style.down });
652                }
653            }
654            SeriesKind::Histogram => {
655                let base = y_of_price(yt, style.base_value);
656                let colors = (level == 0).then(|| data.point_colors(s.series)).flatten();
657                for j in range.start..range.end {
658                    let (Some(v), Some(r)) = (bar(j), chunk_ref(j)) else {
659                        continue;
660                    };
661                    let rel = ohlc_rel(yt, v, r);
662                    let Some(yv) = histogram_value_y(yt, y_bias(yt, r), rel, base) else {
663                        continue;
664                    };
665                    let xc = x_center(&s.x_transform, j);
666                    let color = point_color(colors, j).unwrap_or(style.up);
667                    self.fill_rect(pm, histogram(xc, m, yv, base), color);
668                }
669            }
670            SeriesKind::Line | SeriesKind::Area | SeriesKind::Baseline => {
671                self.line_series(pm, s, &view, style);
672            }
673            SeriesKind::Band => self.band_series(pm, s, &view, data, style),
674            SeriesKind::Points => {
675                // A dot at the (last) value of each element, with the
676                // coverage of a circle icon (shader: `fs_points`).
677                let size = style.line_width.0;
678                let reach = size * 0.5 + 1.0;
679                for j in range.start..range.end {
680                    let (Some(v), Some(r)) = (bar(j), chunk_ref(j)) else {
681                        continue;
682                    };
683                    let last = ohlc_rel(yt, v, r)[3];
684                    if is_gap(last) {
685                        continue;
686                    }
687                    let xc = x_center(&s.x_transform, j);
688                    let yc = y(yt, last, y_bias(yt, r));
689                    let bbox = (xc - reach, yc - reach, xc + reach, yc + reach);
690                    self.shade_box(pm, bbox, |p| {
691                        let c = icon_coverage(ICON_CIRCLE, p.x - xc, p.y - yc, size);
692                        Some((style.up, c))
693                    });
694                }
695            }
696            // Custom, Kagi and Point & Figure series arrive as primitives,
697            // never as a series draw.
698            SeriesKind::Custom | SeriesKind::Kagi | SeriesKind::PointFigure => {}
699        }
700        self.clips.pop();
701    }
702
703    /// Blends `shade(p)` (color and coverage) into every pixel whose center
704    /// lies in `[x0, x1] × [y0, y1]`, within the clip, in row-major order.
705    fn shade_box(
706        &self,
707        pm: &mut Pixmap,
708        (x0, y0, x1, y1): (f32, f32, f32, f32),
709        shade: impl Fn(PointPx) -> Option<(Rgba, f32)>,
710    ) {
711        let Some(clip) = self.clip() else {
712            return;
713        };
714        let b = IBox {
715            x0: x0.floor() as i32,
716            y0: y0.floor() as i32,
717            x1: x1.ceil() as i32,
718            y1: y1.ceil() as i32,
719        }
720        .intersect(clip);
721        for py in b.y0..b.y1 {
722            for px in b.x0..b.x1 {
723                let p = PointPx {
724                    x: px as f32 + 0.5,
725                    y: py as f32 + 0.5,
726                };
727                if p.x < x0 || p.x > x1 || p.y < y0 || p.y > y1 {
728                    continue;
729                }
730                if let Some((color, cov)) = shade(p) {
731                    let c8 = coverage_8(cov);
732                    if c8 > 0 {
733                        Self::blend(pm, px, py, color, c8);
734                    }
735                }
736            }
737        }
738    }
739
740    /// A band between `upper` (the draw's series) and its pair: per element,
741    /// the area between the two edges `last(j)` → `first(j + 1)`, with the
742    /// coverage the shader uses (`fs_band`).
743    fn band_series(
744        &self,
745        pm: &mut Pixmap,
746        s: &SeriesDraw,
747        upper: &OhlcLevelView<'_>,
748        data: ChartDataView<'_>,
749        style: SeriesStyle,
750    ) {
751        let Some(lower) = s.pair.and_then(|p| data.ohlc(p, s.lod_level)) else {
752            return;
753        };
754        let yt = &s.y_transform;
755        let level = upper.level;
756        let bar = |v: &OhlcLevelView<'_>, j: i64| {
757            let ohlc = || {
758                Some([
759                    v.open.at(v.first, j)?,
760                    v.high.at(v.first, j)?,
761                    v.low.at(v.first, j)?,
762                    v.close.at(v.first, j)?,
763                ])
764            };
765            ohlc().unwrap_or([f64::NAN; 4])
766        };
767        let (mut chunk_u, mut chunk_l) = ((i64::MIN, None::<f64>), (i64::MIN, None::<f64>));
768        for j in s.index_range.start..s.index_range.end {
769            let c = chunk_of(level, j);
770            if chunk_u.0 != c {
771                chunk_u = (c, initial_chunk_ref(upper, c));
772                chunk_l = (c, initial_chunk_ref(&lower, c));
773            }
774            let (Some(ru), Some(rl)) = (chunk_u.1, chunk_l.1) else {
775                continue;
776            };
777            let u0 = ohlc_rel(yt, bar(upper, j), ru)[3];
778            let u1 = ohlc_rel(yt, bar(upper, j + 1), ru)[0];
779            let l0 = ohlc_rel(yt, bar(&lower, j), rl)[3];
780            let l1 = ohlc_rel(yt, bar(&lower, j + 1), rl)[0];
781            if is_gap(u0) || is_gap(u1) || is_gap(l0) || is_gap(l1) {
782                continue;
783            }
784            let (bu, bl) = (y_bias(yt, ru), y_bias(yt, rl));
785            let xj = x_center(&s.x_transform, j);
786            let xn = x_center(&s.x_transform, j + 1);
787            let a = PointPx {
788                x: xj,
789                y: y(yt, u0, bu),
790            };
791            let b = PointPx {
792                x: xn,
793                y: y(yt, u1, bu),
794            };
795            let (la, lb) = (y(yt, l0, bl), y(yt, l1, bl));
796            let bbox = (
797                xj - 1.0,
798                a.y.min(b.y).min(la).min(lb) - 1.0,
799                xn + 1.0,
800                a.y.max(b.y).max(la).max(lb) + 1.0,
801            );
802            self.shade_box(pm, bbox, |p| {
803                let (coverage, crossed) = band_coverage(p, a, b, la, lb, yt.a);
804                let color = if crossed {
805                    style.fill_bottom
806                } else {
807                    style.fill_top
808                };
809                Some((color, coverage))
810            });
811        }
812    }
813
814    /// Line, area and baseline series: fills first (area, baseline), then the
815    /// line, element by element, with the coverage functions the shaders use.
816    fn line_series(
817        &self,
818        pm: &mut Pixmap,
819        s: &SeriesDraw,
820        view: &OhlcLevelView<'_>,
821        style: SeriesStyle,
822    ) {
823        let yt = &s.y_transform;
824        let level = view.level;
825        let bar = |j: i64| {
826            Some([
827                view.open.at(view.first, j)?,
828                view.high.at(view.first, j)?,
829                view.low.at(view.first, j)?,
830                view.close.at(view.first, j)?,
831            ])
832        };
833        let mut chunk = (i64::MIN, None::<f64>);
834        // (bias, xj, xn, cur, next) of element j.
835        let mut elements = Vec::new();
836        for j in s.index_range.start..s.index_range.end {
837            let c = chunk_of(level, j);
838            if chunk.0 != c {
839                chunk = (c, initial_chunk_ref(view, c));
840            }
841            let Some(r) = chunk.1 else { continue };
842            let gap = [f64::NAN; 4];
843            let cur = ohlc_rel(yt, bar(j).unwrap_or(gap), r);
844            let next = ohlc_rel(yt, bar(j + 1).unwrap_or(gap), r);
845            let xj = x_center(&s.x_transform, j);
846            let xn = x_center(&s.x_transform, j + 1);
847            elements.push((y_bias(yt, r), xj, xn, cur, next));
848        }
849        let clip_top = s.clip.y;
850        let clip_bottom = s.clip.y + s.clip.h;
851        if s.kind != SeriesKind::Line {
852            let base_y = if s.kind == SeriesKind::Area {
853                clip_bottom
854            } else {
855                y_of_price(yt, style.base_value)
856            };
857            for &(bias, xj, xn, cur, next) in &elements {
858                let Some((a, b)) = fill_edge(yt, bias, xj, xn, cur, next, style.step) else {
859                    continue;
860                };
861                let bbox = (
862                    a.x - 1.0,
863                    a.y.min(b.y).min(base_y) - 1.0,
864                    b.x + 1.0,
865                    a.y.max(b.y).max(base_y) + 1.0,
866                );
867                self.shade_box(pm, bbox, |p| {
868                    let color = if s.kind == SeriesKind::Area {
869                        mix(
870                            style.fill_top,
871                            style.fill_bottom,
872                            gradient_t(Px(p.y), Px(clip_top), Px(clip_bottom)),
873                        )
874                    } else if p.y < base_y {
875                        style.fill_top
876                    } else {
877                        style.fill_bottom
878                    };
879                    Some((color, fill_coverage(p, a, b, Px(base_y))))
880                });
881            }
882        }
883        let base_y = y_of_price(yt, style.base_value);
884        let hw = style.line_width.0 * 0.5;
885        for &(bias, xj, xn, cur, next) in &elements {
886            for (a, b) in line_segments(yt, bias, xj, xn, cur, next, style.step)
887                .into_iter()
888                .flatten()
889            {
890                let bbox = (
891                    a.x.min(b.x) - hw - 1.0,
892                    a.y.min(b.y) - hw - 1.0,
893                    a.x.max(b.x) + hw + 1.0,
894                    a.y.max(b.y) + hw + 1.0,
895                );
896                self.shade_box(pm, bbox, |p| {
897                    if !dash_on(Px(p.x), style.line_width, style.line_dash) {
898                        return None;
899                    }
900                    let color = if s.kind == SeriesKind::Baseline && p.y >= base_y {
901                        style.down
902                    } else {
903                        style.up
904                    };
905                    Some((color, segment_coverage(p, a, b, Px(hw))))
906                });
907            }
908        }
909    }
910}
911
912/// Per-point color of element `j`; `None` for "use the series color".
913fn point_color(colors: Option<(i64, &[u32])>, j: i64) -> Option<Rgba> {
914    let (first, colors) = colors?;
915    let c = *colors.get(usize::try_from(j - first).ok()?)?;
916    (c & 0xFF != 0).then(|| Rgba::from_u32(c))
917}
918
919/// Linear mix of two colors, rounded half up to 8 bits. Shader: `mix8()`.
920fn mix(a: Rgba, b: Rgba, t: f32) -> Rgba {
921    let m = |x: u8, y: u8| {
922        let (x, y) = (f32::from(x), f32::from(y));
923        (x + (y - x) * t + 0.5).floor().clamp(0.0, 255.0) as u8
924    };
925    Rgba {
926        r: m(a.r, b.r),
927        g: m(a.g, b.g),
928        b: m(a.b, b.b),
929        a: m(a.a, b.a),
930    }
931}
932
933#[cfg(test)]
934mod tests {
935    use super::*;
936
937    #[test]
938    fn blend_is_source_over() {
939        let mut pm = Pixmap::new(1, 1).unwrap();
940        pm.fill(tiny_skia::Color::from_rgba8(0, 0, 0, 255));
941        CpuRenderer::blend(&mut pm, 0, 0, Rgba::hex(0x00FF_FFFF).with_alpha(128), 255);
942        assert_eq!(pm.data(), &[128, 128, 128, 255]);
943        CpuRenderer::blend(&mut pm, 0, 0, Rgba::hex(0x00FF_0000), 255);
944        assert_eq!(pm.data(), &[255, 0, 0, 255]);
945    }
946
947    #[test]
948    fn invalid_size_is_an_error() {
949        let mut r = CpuRenderer::new();
950        assert_eq!(
951            r.ensure_target(SizePx { w: 0.0, h: 10.0 }),
952            Err(RenderError::InvalidSize)
953        );
954        assert_eq!(r.encode_png(), Err(RenderError::InvalidSize));
955    }
956}