sealed-surface 0.4.0

Non-extractable data surface: tables, timeseries, scatter, treemap as glyphs, never DOM text
Documentation
//! Software pixmap + in-crate PNG encoder (DEFLATE).

use crate::deflate;
use crate::error::Error;
use crate::font;
use crate::theme::Rgb;

/// RGB888 pixmap.
#[derive(Debug, Clone)]
pub struct Pixmap {
    width: u32,
    height: u32,
    data: Vec<u8>,
}

impl Pixmap {
    pub(crate) fn new(width: u32, height: u32, fill: Rgb) -> Result<Self, Error> {
        if width == 0 || height == 0 {
            return Err(Error::Raster("width and height must be > 0"));
        }
        let n = (width as usize)
            .checked_mul(height as usize)
            .and_then(|px| px.checked_mul(3))
            .ok_or(Error::Raster("pixmap too large"))?;
        let mut data = vec![0u8; n];
        for px in data.chunks_exact_mut(3) {
            px[0] = fill.r;
            px[1] = fill.g;
            px[2] = fill.b;
        }
        Ok(Self {
            width,
            height,
            data,
        })
    }

    /// Pixel width.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Pixel height.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.height
    }

    pub(crate) fn fill_rect(&mut self, x: u32, y: u32, w: u32, h: u32, color: Rgb) {
        let x1 = x.min(self.width);
        let y1 = y.min(self.height);
        let x2 = x.saturating_add(w).min(self.width);
        let y2 = y.saturating_add(h).min(self.height);
        if x1 >= x2 || y1 >= y2 {
            return;
        }
        let row_w = (x2 - x1) as usize;
        let stride = self.width as usize * 3;
        let first = (y1 as usize) * stride + (x1 as usize) * 3;
        {
            let row = &mut self.data[first..first + row_w * 3];
            for px in row.chunks_exact_mut(3) {
                px[0] = color.r;
                px[1] = color.g;
                px[2] = color.b;
            }
        }
        for yy in (y1 + 1)..y2 {
            let dest = (yy as usize) * stride + (x1 as usize) * 3;
            self.data.copy_within(first..first + row_w * 3, dest);
        }
    }

    pub(crate) fn hline(&mut self, x: u32, y: u32, w: u32, color: Rgb) {
        self.fill_rect(x, y, w, 1, color);
    }

    pub(crate) fn vline(&mut self, x: u32, y: u32, h: u32, color: Rgb) {
        self.fill_rect(x, y, 1, h, color);
    }

    pub(crate) fn put(&mut self, x: u32, y: u32, color: Rgb) {
        if x >= self.width || y >= self.height {
            return;
        }
        let i = ((y as usize) * (self.width as usize) + (x as usize)) * 3;
        self.data[i] = color.r;
        self.data[i + 1] = color.g;
        self.data[i + 2] = color.b;
    }

    pub(crate) fn text_scaled(
        &mut self,
        x: u32,
        y: u32,
        s: &str,
        color: Rgb,
        max_w: u32,
        scale: crate::appearance::TypeScale,
    ) {
        let adv = scale.advance();
        let mut cx = x;
        for ch in s.chars() {
            if cx.saturating_sub(x).saturating_add(adv) > max_w {
                break;
            }
            font::each_pixel_scaled(ch, scale, |px, py| {
                self.put(cx.saturating_add(px), y.saturating_add(py), color);
            });
            cx = cx.saturating_add(adv);
        }
    }

    pub(crate) fn get(&self, x: u32, y: u32) -> Option<Rgb> {
        if x >= self.width || y >= self.height {
            return None;
        }
        let i = ((y as usize) * (self.width as usize) + (x as usize)) * 3;
        Some(Rgb::new(self.data[i], self.data[i + 1], self.data[i + 2]))
    }

    pub(crate) fn blend(&mut self, x: u32, y: u32, color: Rgb, alpha: u8) {
        let Some(bg) = self.get(x, y) else {
            return;
        };
        self.put(x, y, bg.mix(color, alpha));
    }

    /// Xiaolin Wu anti-aliased line.
    pub(crate) fn line_aa(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, color: Rgb) {
        let mut x0 = x0;
        let mut y0 = y0;
        let mut x1 = x1;
        let mut y1 = y1;
        let steep = (y1 - y0).abs() > (x1 - x0).abs();
        if steep {
            core::mem::swap(&mut x0, &mut y0);
            core::mem::swap(&mut x1, &mut y1);
        }
        if x0 > x1 {
            core::mem::swap(&mut x0, &mut x1);
            core::mem::swap(&mut y0, &mut y1);
        }
        let dx = x1 - x0;
        let dy = y1 - y0;
        let gradient = if dx.abs() < 1e-9 { 1.0 } else { dy / dx };

        let plot = |pm: &mut Self, x: i32, y: i32, a: f64| {
            if x < 0 || y < 0 {
                return;
            }
            let alpha = (a.clamp(0.0, 1.0) * 255.0) as u8;
            if steep {
                pm.blend(y as u32, x as u32, color, alpha);
            } else {
                pm.blend(x as u32, y as u32, color, alpha);
            }
        };

        let xend = x0.round();
        let yend = y0 + gradient * (xend - x0);
        let xgap = 1.0 - (x0 + 0.5).fract();
        let xpxl1 = xend as i32;
        let ypxl1 = yend.floor() as i32;
        plot(self, xpxl1, ypxl1, (1.0 - yend.fract()) * xgap);
        plot(self, xpxl1, ypxl1 + 1, yend.fract() * xgap);
        let mut intery = yend + gradient;

        let xend2 = x1.round();
        let yend2 = y1 + gradient * (xend2 - x1);
        let xgap2 = (x1 + 0.5).fract();
        let xpxl2 = xend2 as i32;
        let ypxl2 = yend2.floor() as i32;
        plot(self, xpxl2, ypxl2, (1.0 - yend2.fract()) * xgap2);
        plot(self, xpxl2, ypxl2 + 1, yend2.fract() * xgap2);

        let mut x = xpxl1 + 1;
        while x < xpxl2 {
            plot(self, x, intery.floor() as i32, 1.0 - intery.fract());
            plot(self, x, intery.floor() as i32 + 1, intery.fract());
            intery += gradient;
            x += 1;
        }
    }

    pub(crate) fn stroke_aa(&mut self, x0: f64, y0: f64, x1: f64, y1: f64, color: Rgb, width: u8) {
        self.line_aa(x0, y0, x1, y1, color);
        if width >= 2 {
            let dx = x1 - x0;
            let dy = y1 - y0;
            let len = (dx * dx + dy * dy).sqrt().max(1.0);
            let ox = -dy / len * 0.7;
            let oy = dx / len * 0.7;
            self.line_aa(x0 + ox, y0 + oy, x1 + ox, y1 + oy, color);
            if width >= 3 {
                self.line_aa(x0 - ox, y0 - oy, x1 - ox, y1 - oy, color);
            }
        }
    }

    /// Encode PNG (8-bit RGB, no interlace).
    ///
    /// # Errors
    ///
    /// Returns [`Error::Raster`] if the buffer is inconsistent.
    pub fn to_png(&self) -> Result<Vec<u8>, Error> {
        encode_png(self.width, self.height, &self.data)
    }
}

fn encode_png(width: u32, height: u32, rgb: &[u8]) -> Result<Vec<u8>, Error> {
    let expected = (width as usize)
        .checked_mul(height as usize)
        .and_then(|px| px.checked_mul(3))
        .ok_or(Error::Raster("png size overflow"))?;
    if rgb.len() != expected {
        return Err(Error::Raster("rgb length does not match dimensions"));
    }

    let mut raw = Vec::with_capacity((width as usize + 1) * height as usize * 3);
    for y in 0..height as usize {
        raw.push(0);
        let start = y * width as usize * 3;
        let end = start + width as usize * 3;
        raw.extend_from_slice(&rgb[start..end]);
    }

    let mut out = Vec::new();
    out.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
    let mut ihdr = Vec::new();
    ihdr.extend_from_slice(&width.to_be_bytes());
    ihdr.extend_from_slice(&height.to_be_bytes());
    ihdr.extend_from_slice(&[8, 2, 0, 0, 0]);
    write_chunk(&mut out, *b"IHDR", &ihdr);
    let deflated = deflate::zlib_deflate(&raw);
    write_chunk(&mut out, *b"IDAT", &deflated);
    write_chunk(&mut out, *b"IEND", &[]);
    Ok(out)
}

fn write_chunk(out: &mut Vec<u8>, ty: [u8; 4], data: &[u8]) {
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(&ty);
    out.extend_from_slice(data);
    let mut crc_in = Vec::with_capacity(4 + data.len());
    crc_in.extend_from_slice(&ty);
    crc_in.extend_from_slice(data);
    out.extend_from_slice(&crc32(&crc_in).to_be_bytes());
}

fn crc32(data: &[u8]) -> u32 {
    let mut crc = 0xFFFF_FFFFu32;
    for &b in data {
        let idx = ((crc ^ u32::from(b)) & 0xFF) as usize;
        crc = CRC_TABLE[idx] ^ (crc >> 8);
    }
    crc ^ 0xFFFF_FFFF
}

const CRC_TABLE: [u32; 256] = make_crc_table();

const fn make_crc_table() -> [u32; 256] {
    let mut table = [0u32; 256];
    let mut n = 0;
    while n < 256 {
        let mut c = n as u32;
        let mut k = 0;
        while k < 8 {
            if c & 1 != 0 {
                c = 0xEDB8_8320 ^ (c >> 1);
            } else {
                c >>= 1;
            }
            k += 1;
        }
        table[n] = c;
        n += 1;
    }
    table
}

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

    #[test]
    fn png_signature() {
        let pm = Pixmap::new(2, 2, Rgb::new(0, 0, 0)).expect("pixmap");
        let png = pm.to_png().expect("png");
        assert_eq!(&png[..8], &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);
    }

    #[test]
    fn png_idat_roundtrip() {
        let mut pm = Pixmap::new(8, 4, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
        pm.fill_rect(1, 1, 3, 2, Rgb::new(0x3d, 0x9e, 0xff));
        let png = pm.to_png().expect("png");
        let raw = extract_idat_inflate(&png).expect("idat");
        let mut expect = Vec::new();
        for y in 0..4u32 {
            expect.push(0);
            for x in 0..8u32 {
                let i = ((y * 8 + x) * 3) as usize;
                expect.extend_from_slice(&pm.data[i..i + 3]);
            }
        }
        assert_eq!(raw, expect);
    }

    #[test]
    fn png_deflate_beats_raw_for_flat_fill() {
        let pm = Pixmap::new(320, 180, Rgb::new(0x0b, 0x0d, 0x10)).expect("pixmap");
        let png = pm.to_png().expect("png");
        let raw_rgb = (320 * 180 * 3) as usize;
        assert!(
            png.len() < raw_rgb / 4,
            "compressed {} vs raw {}",
            png.len(),
            raw_rgb
        );
    }

    fn extract_idat_inflate(png: &[u8]) -> Result<Vec<u8>, &'static str> {
        let mut i = 8usize;
        let mut z = Vec::new();
        while i + 12 <= png.len() {
            let len = u32::from_be_bytes(png[i..i + 4].try_into().unwrap()) as usize;
            let ty = &png[i + 4..i + 8];
            let data = &png[i + 8..i + 8 + len];
            if ty == b"IDAT" {
                z.extend_from_slice(data);
            }
            if ty == b"IEND" {
                break;
            }
            i += 12 + len;
        }
        crate::deflate::zlib_inflate(&z)
    }
}