ggplot-rs 0.28.0

A Rust implementation of ggplot2's Grammar of Graphics
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
//! A self-contained RGBA raster [`DrawBackend`] (feature `canvas`).
//!
//! Unlike the plotters bitmap backend it compiles to wasm and is tuned for
//! large-N: it rasterises points/lines/polygons/text into an RGBA byte buffer in
//! pure Rust (text via `ab_glyph` + the bundled font), so there's no per-mark
//! DOM node and no wasm↔JS call per draw. Hand `into_rgba()` to a `<canvas>`
//! (`putImageData`) in the browser, or `into_png()` a file natively.

// The low-level rasterisers take (buf, w, h, coords…, colour, alpha) — plenty of
// scalar arguments by nature.
#![allow(clippy::too_many_arguments)]

use ab_glyph::{point, Font, FontRef, PxScale, ScaleFont};

use super::backend::{
    DrawBackend, FontFace, LineStyle, PointStyle, RectStyle, TextAnchor, TextStyle,
};
use super::{Rect, RenderError};

const FONT: &[u8] = include_bytes!("../../assets/fonts/DejaVuSans.ttf");

/// An in-memory RGBA canvas (row-major, 4 bytes/pixel, opaque white ground).
pub struct PixelBackend {
    width: usize,
    height: usize,
    buf: Vec<u8>,
    plot_area: Rect,
    total_area: Rect,
    font: FontRef<'static>,
}

impl PixelBackend {
    pub fn new(width: u32, height: u32, plot_area: Rect) -> Self {
        let (w, h) = (width as usize, height as usize);
        PixelBackend {
            width: w,
            height: h,
            buf: vec![255; w * h * 4], // white, opaque
            plot_area,
            total_area: Rect {
                x: 0.0,
                y: 0.0,
                width: width as f64,
                height: height as f64,
            },
            font: FontRef::try_from_slice(FONT).expect("bundled font parses"),
        }
    }

    pub fn dimensions(&self) -> (u32, u32) {
        (self.width as u32, self.height as u32)
    }

    /// The raw RGBA buffer (`width*height*4` bytes) for `ctx.putImageData`.
    pub fn into_rgba(self) -> Vec<u8> {
        self.buf
    }

    /// Encode the canvas to PNG bytes.
    pub fn into_png(self) -> Result<Vec<u8>, RenderError> {
        let img = image::RgbaImage::from_raw(self.width as u32, self.height as u32, self.buf)
            .ok_or_else(|| RenderError::BackendError("buffer size mismatch".into()))?;
        let mut out = std::io::Cursor::new(Vec::new());
        img.write_to(&mut out, image::ImageOutputFormat::Png)
            .map_err(|e| RenderError::BackendError(format!("{e:?}")))?;
        Ok(out.into_inner())
    }
}

/// Alpha-blend one pixel (source-over onto the opaque ground).
fn blend(buf: &mut [u8], w: usize, h: usize, x: i32, y: i32, (r, g, b): (u8, u8, u8), a: f64) {
    if x < 0 || y < 0 || x as usize >= w || y as usize >= h {
        return;
    }
    let a = a.clamp(0.0, 1.0);
    if a <= 0.0 {
        return;
    }
    let i = (y as usize * w + x as usize) * 4;
    let inv = 1.0 - a;
    buf[i] = (r as f64 * a + buf[i] as f64 * inv).round() as u8;
    buf[i + 1] = (g as f64 * a + buf[i + 1] as f64 * inv).round() as u8;
    buf[i + 2] = (b as f64 * a + buf[i + 2] as f64 * inv).round() as u8;
    buf[i + 3] = 255;
}

/// An anti-aliased filled disc — the hot path for scatter points.
fn fill_circle(
    buf: &mut [u8],
    w: usize,
    h: usize,
    cx: f64,
    cy: f64,
    r: f64,
    c: (u8, u8, u8),
    a: f64,
) {
    let r = r.max(0.5);
    let (x0, x1) = ((cx - r - 1.0).floor() as i32, (cx + r + 1.0).ceil() as i32);
    let (y0, y1) = ((cy - r - 1.0).floor() as i32, (cy + r + 1.0).ceil() as i32);
    for y in y0..=y1 {
        for x in x0..=x1 {
            let d = ((x as f64 + 0.5 - cx).powi(2) + (y as f64 + 0.5 - cy).powi(2)).sqrt();
            let cov = (r - d + 0.5).clamp(0.0, 1.0); // 1px AA edge
            if cov > 0.0 {
                blend(buf, w, h, x, y, c, cov * a);
            }
        }
    }
}

/// A thick segment, drawn by stamping small discs along it.
#[allow(clippy::too_many_arguments)]
fn segment(
    buf: &mut [u8],
    w: usize,
    h: usize,
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    c: (u8, u8, u8),
    width: f64,
    a: f64,
) {
    let r = (width / 2.0).max(0.5);
    let (dx, dy) = (x1 - x0, y1 - y0);
    let len = (dx * dx + dy * dy).sqrt().max(1.0);
    let steps = len.ceil() as i32;
    for s in 0..=steps {
        let t = s as f64 / steps as f64;
        fill_circle(buf, w, h, x0 + dx * t, y0 + dy * t, r, c, a);
    }
}

/// Even-odd scanline polygon fill, one ring.
fn fill_polygon(buf: &mut [u8], w: usize, h: usize, pts: &[(f64, f64)], c: (u8, u8, u8), a: f64) {
    fill_polygon_rings(buf, w, h, &[pts], c, a);
}

/// Even-odd scanline fill across every ring at once (`geom_sf`'s polygon
/// holes, #178): every ring's edges are collected before sorting each
/// scanline's crossings, so a hole ring's pair of crossings on a given row
/// cancels the exterior's fill between them — the standard even-odd
/// definition generalises directly from one ring to several.
fn fill_polygon_rings(
    buf: &mut [u8],
    w: usize,
    h: usize,
    rings: &[&[(f64, f64)]],
    c: (u8, u8, u8),
    a: f64,
) {
    let (mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY);
    for ring in rings {
        if ring.len() < 3 {
            continue;
        }
        for p in ring.iter() {
            y0 = y0.min(p.1);
            y1 = y1.max(p.1);
        }
    }
    if !(y0.is_finite() && y1.is_finite()) {
        return;
    }
    let (y0, y1) = (y0.floor() as i32, y1.ceil() as i32);
    for y in y0..=y1 {
        let yc = y as f64 + 0.5;
        let mut xs: Vec<f64> = Vec::new();
        for ring in rings {
            let n = ring.len();
            if n < 3 {
                continue;
            }
            for i in 0..n {
                let (ax, ay) = ring[i];
                let (bx, by) = ring[(i + 1) % n];
                if (ay <= yc && by > yc) || (by <= yc && ay > yc) {
                    xs.push(ax + (yc - ay) / (by - ay) * (bx - ax));
                }
            }
        }
        xs.sort_by(|p, q| p.total_cmp(q));
        for span in xs.chunks(2) {
            if let [xa, xb] = span {
                for x in xa.round() as i32..=xb.round() as i32 {
                    blend(buf, w, h, x, y, c, a);
                }
            }
        }
    }
}

impl DrawBackend for PixelBackend {
    fn plot_area(&self) -> Rect {
        self.plot_area.clone()
    }
    fn total_area(&self) -> Rect {
        self.total_area.clone()
    }

    fn draw_circle(
        &mut self,
        (cx, cy): (f64, f64),
        radius: f64,
        style: &PointStyle,
    ) -> Result<(), RenderError> {
        fill_circle(
            &mut self.buf,
            self.width,
            self.height,
            cx,
            cy,
            radius,
            style.color,
            style.alpha,
        );
        Ok(())
    }

    fn draw_line(&mut self, pts: &[(f64, f64)], style: &LineStyle) -> Result<(), RenderError> {
        for w in pts.windows(2) {
            segment(
                &mut self.buf,
                self.width,
                self.height,
                w[0].0,
                w[0].1,
                w[1].0,
                w[1].1,
                style.color,
                style.width,
                style.alpha,
            );
        }
        Ok(())
    }

    fn draw_rect(
        &mut self,
        (x0, y0): (f64, f64),
        (x1, y1): (f64, f64),
        style: &RectStyle,
    ) -> Result<(), RenderError> {
        // No native rounded-rect primitive here: approximate as a polygon
        // (a plain rectangle when corner_radius is 0, same as before).
        let r = if style.corner_radius > 0.0 {
            super::backend::rounded_rect_points(x0, y0, x1, y1, style.corner_radius)
        } else {
            vec![(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
        };
        if let Some(fill) = style.fill {
            fill_polygon(
                &mut self.buf,
                self.width,
                self.height,
                &r,
                fill,
                style.alpha,
            );
        }
        if let Some(stroke) = style.stroke {
            let n = r.len();
            for i in 0..n {
                let (a, b) = (r[i], r[(i + 1) % n]);
                segment(
                    &mut self.buf,
                    self.width,
                    self.height,
                    a.0,
                    a.1,
                    b.0,
                    b.1,
                    stroke,
                    style.stroke_width,
                    style.alpha,
                );
            }
        }
        Ok(())
    }

    fn draw_polygon(&mut self, pts: &[(f64, f64)], style: &RectStyle) -> Result<(), RenderError> {
        if let Some(fill) = style.fill {
            fill_polygon(
                &mut self.buf,
                self.width,
                self.height,
                pts,
                fill,
                style.alpha,
            );
        }
        if let Some(stroke) = style.stroke {
            for w in pts.windows(2) {
                segment(
                    &mut self.buf,
                    self.width,
                    self.height,
                    w[0].0,
                    w[0].1,
                    w[1].0,
                    w[1].1,
                    stroke,
                    style.stroke_width,
                    style.alpha,
                );
            }
            if let (Some(first), Some(last)) = (pts.first(), pts.last()) {
                segment(
                    &mut self.buf,
                    self.width,
                    self.height,
                    last.0,
                    last.1,
                    first.0,
                    first.1,
                    stroke,
                    style.stroke_width,
                    style.alpha,
                );
            }
        }
        Ok(())
    }

    fn draw_polygon_rings(
        &mut self,
        rings: &[Vec<(f64, f64)>],
        style: &RectStyle,
    ) -> Result<(), RenderError> {
        if let Some(fill) = style.fill {
            let ring_refs: Vec<&[(f64, f64)]> = rings.iter().map(Vec::as_slice).collect();
            fill_polygon_rings(
                &mut self.buf,
                self.width,
                self.height,
                &ring_refs,
                fill,
                style.alpha,
            );
        }
        if let Some(stroke) = style.stroke {
            for ring in rings {
                if ring.len() < 2 {
                    continue;
                }
                for w in ring.windows(2) {
                    segment(
                        &mut self.buf,
                        self.width,
                        self.height,
                        w[0].0,
                        w[0].1,
                        w[1].0,
                        w[1].1,
                        stroke,
                        style.stroke_width,
                        style.alpha,
                    );
                }
                if let (Some(first), Some(last)) = (ring.first(), ring.last()) {
                    segment(
                        &mut self.buf,
                        self.width,
                        self.height,
                        last.0,
                        last.1,
                        first.0,
                        first.1,
                        stroke,
                        style.stroke_width,
                        style.alpha,
                    );
                }
            }
        }
        Ok(())
    }

    fn draw_text(
        &mut self,
        text: &str,
        (x, y): (f64, f64),
        style: &TextStyle,
    ) -> Result<(), RenderError> {
        let scale = PxScale::from(style.size as f32);
        let font = &self.font;
        let scaled = font.as_scaled(scale);
        let width: f32 = text
            .chars()
            .map(|c| scaled.h_advance(font.glyph_id(c)))
            .sum();
        let start_x = match style.anchor {
            TextAnchor::Start => x,
            TextAnchor::Middle => x - width as f64 / 2.0,
            TextAnchor::End => x - width as f64,
        };
        // Approximate the SVG "middle" baseline; bold faked by a bump in coverage.
        let baseline = (y + style.size * 0.35) as f32;
        let bold = style.face == FontFace::Bold;
        let (bw, bh, color) = (self.width, self.height, style.color);
        let mut pen = start_x as f32;
        for ch in text.chars() {
            let gid = font.glyph_id(ch);
            let glyph = gid.with_scale_and_position(scale, point(pen, baseline));
            if let Some(outlined) = font.outline_glyph(glyph) {
                let bounds = outlined.px_bounds();
                outlined.draw(|gx, gy, cov| {
                    let a = if bold {
                        (cov as f64 * 1.4).min(1.0)
                    } else {
                        cov as f64
                    };
                    blend(
                        &mut self.buf,
                        bw,
                        bh,
                        bounds.min.x as i32 + gx as i32,
                        bounds.min.y as i32 + gy as i32,
                        color,
                        a,
                    );
                });
            }
            pen += scaled.h_advance(gid);
        }
        Ok(())
    }
}

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

    fn pixel(buf: &[u8], w: usize, x: i32, y: i32) -> (u8, u8, u8) {
        let i = (y as usize * w + x as usize) * 4;
        (buf[i], buf[i + 1], buf[i + 2])
    }

    /// A ring after the other is a hole cut out of the fill under the
    /// even-odd rule (`geom_sf`'s `Polygon`, #178) — a 20×20 square with a
    /// 6×6 hole in the middle leaves the hole's centre at the white ground,
    /// while a point between the hole and the exterior edge is filled.
    #[test]
    fn fill_polygon_rings_cuts_out_a_hole() {
        let (w, h) = (20usize, 20usize);
        let mut buf = vec![255u8; w * h * 4];
        let exterior: Vec<(f64, f64)> = vec![(1.0, 1.0), (19.0, 1.0), (19.0, 19.0), (1.0, 19.0)];
        let hole: Vec<(f64, f64)> = vec![(7.0, 7.0), (13.0, 7.0), (13.0, 13.0), (7.0, 13.0)];
        fill_polygon_rings(&mut buf, w, h, &[&exterior, &hole], (200, 50, 50), 1.0);
        assert_eq!(pixel(&buf, w, 10, 10), (255, 255, 255), "hole stays blank");
        assert_eq!(
            pixel(&buf, w, 3, 3),
            (200, 50, 50),
            "ring between is filled"
        );
        // Without the hole ring, the same point would be filled — proving
        // it's the second ring that cuts it, not some other effect.
        let mut filled = vec![255u8; w * h * 4];
        fill_polygon_rings(&mut filled, w, h, &[&exterior], (200, 50, 50), 1.0);
        assert_eq!(pixel(&filled, w, 10, 10), (200, 50, 50));
    }

    /// Two disjoint rings (a multipolygon's two parts, drawn in one call)
    /// each fill independently.
    #[test]
    fn fill_polygon_rings_handles_disjoint_rings() {
        let (w, h) = (20usize, 20usize);
        let mut buf = vec![255u8; w * h * 4];
        let a: Vec<(f64, f64)> = vec![(1.0, 1.0), (5.0, 1.0), (5.0, 5.0), (1.0, 5.0)];
        let b: Vec<(f64, f64)> = vec![(14.0, 14.0), (18.0, 14.0), (18.0, 18.0), (14.0, 18.0)];
        fill_polygon_rings(&mut buf, w, h, &[&a, &b], (10, 20, 30), 1.0);
        assert_eq!(pixel(&buf, w, 3, 3), (10, 20, 30));
        assert_eq!(pixel(&buf, w, 16, 16), (10, 20, 30));
        assert_eq!(
            pixel(&buf, w, 10, 10),
            (255, 255, 255),
            "gap between stays blank"
        );
    }

    /// The `DrawBackend::draw_polygon_rings` trait method itself (not just
    /// the free `fill_polygon_rings` the unit tests above call directly):
    /// fills with a real hole cut-out *and* strokes every ring, through
    /// dynamic dispatch (`&mut dyn DrawBackend`), the way `geom_sf` calls
    /// it.
    #[test]
    fn draw_polygon_rings_trait_method_fills_and_strokes_every_ring() {
        let pa = Rect {
            x: 0.0,
            y: 0.0,
            width: 20.0,
            height: 20.0,
        };
        let mut backend = PixelBackend::new(20, 20, pa);
        let dyn_backend: &mut dyn DrawBackend = &mut backend;
        let exterior = vec![(1.0, 1.0), (19.0, 1.0), (19.0, 19.0), (1.0, 19.0)];
        let hole = vec![(7.0, 7.0), (13.0, 7.0), (13.0, 13.0), (7.0, 13.0)];
        dyn_backend
            .draw_polygon_rings(
                &[exterior, hole],
                &RectStyle {
                    fill: Some((200, 50, 50)),
                    stroke: Some((0, 0, 0)),
                    stroke_width: 1.0,
                    alpha: 1.0,
                    clip: true,
                    corner_radius: 0.0,
                },
            )
            .unwrap();
        let buf = backend.into_rgba();
        assert_eq!(pixel(&buf, 20, 10, 10), (255, 255, 255), "hole stays blank");
        assert_eq!(
            pixel(&buf, 20, 3, 3),
            (200, 50, 50),
            "ring between is filled"
        );
        // The hole's own outline should be stroked (near-black somewhere
        // along it), distinguishing this from a plain single-ring fill.
        let near_hole_edge = pixel(&buf, 20, 7, 10);
        assert_ne!(near_hole_edge, (255, 255, 255), "hole outline is stroked");
    }

    /// A ring with fewer than 2 points is skipped by the stroke loop
    /// (rather than panicking on `windows(2)`/`first()`/`last()`), while a
    /// valid sibling ring still strokes normally.
    #[test]
    fn draw_polygon_rings_skips_a_degenerate_ring_when_stroking() {
        let pa = Rect {
            x: 0.0,
            y: 0.0,
            width: 20.0,
            height: 20.0,
        };
        let mut backend = PixelBackend::new(20, 20, pa);
        let dyn_backend: &mut dyn DrawBackend = &mut backend;
        let degenerate: Vec<(f64, f64)> = vec![(5.0, 5.0)];
        let real = vec![(1.0, 1.0), (10.0, 1.0), (10.0, 10.0), (1.0, 10.0)];
        dyn_backend
            .draw_polygon_rings(
                &[degenerate, real],
                &RectStyle {
                    fill: None,
                    stroke: Some((0, 0, 0)),
                    stroke_width: 1.0,
                    alpha: 1.0,
                    clip: true,
                    corner_radius: 0.0,
                },
            )
            .unwrap();
        // No panic is the main assertion; the real ring's top edge should
        // still be stroked.
        let buf = backend.into_rgba();
        assert_ne!(pixel(&buf, 20, 5, 1), (255, 255, 255));
    }
}