Skip to main content

mln_engine/text/
tiny_sdf.rs

1// C++ port of https://github.com/mapbox/tiny-sdf, which is in turn based on
2// the Felzenszwalb/Huttenlocher distance transform paper
3// (https://cs.brown.edu/~pff/papers/dt-final.pdf).
4
5use mln_style::bitmap::AlphaImage;
6
7// The distances are `f32`, where C++'s are `double`: that is faster, and
8// rounds a rare pixel one level away from C++'s.
9const INF: f32 = 1e20;
10
11/// One parabola of the lower envelope: rooted at `root` with the height
12/// `value`, and lowest from `start` until the next parabola's `start`.
13#[derive(Clone, Copy)]
14struct Parabola {
15    root: f32,
16    value: f32,
17    start: f32,
18}
19
20/// 1D squared distance transform of `line`, in place. `envelope` is scratch.
21fn edt1d(line: &mut [f32], envelope: &mut Vec<Parabola>) {
22    let Some((&first, rest)) = line.split_first() else {
23        return;
24    };
25    // A uniform line, such as a column of a glyph's padding, transforms to
26    // itself.
27    if rest.iter().all(|&value| value == first) {
28        return;
29    }
30
31    // The lower envelope of the parabolas. A parabola at INF is never the
32    // lowest while one isn't, so the envelope leaves them out; a line of
33    // nothing but INF is uniform.
34    envelope.clear();
35    for (q, &value) in line.iter().enumerate() {
36        if value >= INF {
37            continue;
38        }
39        let q = q as f32;
40        let height = value + q * q;
41        let start = loop {
42            let Some(top) = envelope.last() else { break -INF };
43            let start = (height - (top.value + top.root * top.root)) / (2.0 * q - 2.0 * top.root);
44            if start > top.start {
45                break start;
46            }
47            envelope.pop();
48        };
49        envelope.push(Parabola { root: q, value, start });
50    }
51
52    let mut parabolas = envelope.iter();
53    let Some(mut current) = parabolas.next() else {
54        return;
55    };
56    let mut next = parabolas.next();
57    for (q, out) in line.iter_mut().enumerate() {
58        let q = q as f32;
59        while let Some(parabola) = next.filter(|parabola| parabola.start < q) {
60            current = parabola;
61            next = parabolas.next();
62        }
63        let distance = q - current.root;
64        *out = distance * distance + current.value;
65    }
66}
67
68/// 2D Euclidean distance transform of `data`, `width` pixels wide, in place:
69/// squared along the columns, then the rows' square roots.
70fn edt(data: &mut [f32], width: usize, column: &mut Vec<f32>, envelope: &mut Vec<Parabola>) {
71    for x in 0..width {
72        column.clear();
73        column.extend(data[x..].iter().step_by(width));
74        edt1d(column, envelope);
75        for (pixel, &value) in data[x..].iter_mut().step_by(width).zip(column.iter()) {
76            *pixel = value;
77        }
78    }
79    for row in data.chunks_exact_mut(width) {
80        edt1d(row, envelope);
81        for pixel in row {
82            *pixel = pixel.sqrt();
83        }
84    }
85}
86
87/// Turns an alpha raster into a signed distance field of the same size.
88#[must_use]
89pub fn transform_raster_to_sdf(raster_input: &AlphaImage, radius: f64, cutoff: f64) -> AlphaImage {
90    let mut sdf = AlphaImage::new(raster_input.size);
91    let width = raster_input.size.width as usize;
92    let size = width * raster_input.size.height as usize;
93    if size == 0 {
94        return sdf;
95    }
96
97    // `grid_outer` measures the distance to the glyph, and `grid_inner` the
98    // distance to its outside: each starts at 0 where a pixel is what it
99    // measures the distance to, at INF where it isn't, and in between where
100    // the pixel is partly covered.
101    let mut grid_outer = Vec::with_capacity(size);
102    let mut grid_inner = Vec::with_capacity(size);
103    for &alpha in &raster_input.data[..size] {
104        let (outer, inner) = match alpha {
105            255 => (0.0, INF),
106            0 => (INF, 0.0),
107            _ => {
108                let a = f64::from(alpha) / 255.0;
109                ((0.5 - a).max(0.0).powi(2) as f32, (a - 0.5).max(0.0).powi(2) as f32)
110            }
111        };
112        grid_outer.push(outer);
113        grid_inner.push(inner);
114    }
115
116    let max_dimension = width.max(raster_input.size.height as usize);
117    let mut column = Vec::with_capacity(max_dimension);
118    let mut envelope = Vec::with_capacity(max_dimension);
119    edt(&mut grid_outer, width, &mut column, &mut envelope);
120    edt(&mut grid_inner, width, &mut column, &mut envelope);
121
122    for ((pixel, &outer), &inner) in sdf.data.iter_mut().zip(&grid_outer).zip(&grid_inner) {
123        let distance = f64::from(outer - inner);
124        *pixel = round_to_alpha(255.0 - 255.0 * (distance / radius + cutoff));
125    }
126
127    sdf
128}
129
130/// Rounds to the nearest integer, halfway cases away from zero, clamped to
131/// 0-255: C++'s `std::max(0l, std::min(255l, ::lround(x)))`, without a call
132/// to `lround`.
133fn round_to_alpha(x: f64) -> u8 {
134    if x.is_nan() || x <= 0.0 {
135        0
136    } else if x >= 255.0 {
137        255
138    } else {
139        let whole = x as u8;
140        // The subtraction is exact.
141        if x - f64::from(whole) >= 0.5 { whole + 1 } else { whole }
142    }
143}
144
145#[cfg(test)]
146mod tests {
147    use mln_style::size::Size;
148
149    use super::*;
150
151    #[test]
152    fn solid_and_empty() {
153        let img = AlphaImage::new(Size::new(3, 3));
154        let sdf = transform_raster_to_sdf(&img, 8.0, 0.25);
155        assert!(sdf.data.iter().all(|&v| v == 0));
156        let mut img = AlphaImage::new(Size::new(1, 1));
157        img.data[0] = 255;
158        let sdf = transform_raster_to_sdf(&img, 8.0, 0.25);
159        assert_eq!(sdf.data, vec![255]);
160    }
161
162    /// The distance field by definition: each pixel's squared distance is
163    /// the least, over every pixel, of the squared distance to it plus its
164    /// own value.
165    fn brute_force(raster: &AlphaImage, radius: f64, cutoff: f64) -> Vec<u8> {
166        let (width, height) = (raster.size.width as usize, raster.size.height as usize);
167        let grid = |inside: bool| -> Vec<f64> {
168            raster
169                .data
170                .iter()
171                .map(|&alpha| {
172                    let a = f64::from(alpha) / 255.0;
173                    match (alpha, inside) {
174                        (255, false) | (0, true) => 0.0,
175                        (0, false) | (255, true) => f64::INFINITY,
176                        (_, false) => (0.5 - a).max(0.0).powi(2),
177                        (_, true) => (a - 0.5).max(0.0).powi(2),
178                    }
179                })
180                .collect()
181        };
182        let distance = |grid: &[f64], x: usize, y: usize| {
183            let mut least = f64::INFINITY;
184            for (i, &value) in grid.iter().enumerate() {
185                let (dx, dy) = ((i % width) as f64 - x as f64, (i / width) as f64 - y as f64);
186                least = least.min(dx * dx + dy * dy + value);
187            }
188            least.sqrt()
189        };
190        let (outer, inner) = (grid(false), grid(true));
191        (0..width * height)
192            .map(|i| {
193                let (x, y) = (i % width, i / width);
194                let d = distance(&outer, x, y).min(1e10) - distance(&inner, x, y).min(1e10);
195                (255.0 - 255.0 * (d / radius + cutoff)).round().clamp(0.0, 255.0) as u8
196            })
197            .collect()
198    }
199
200    #[test]
201    fn matches_the_distance_field_by_definition() {
202        // A fixed pseudo-random sequence: mostly empty and solid pixels,
203        // some partly covered.
204        let mut state = 0x2545_f491_u32;
205        let mut next = move || {
206            state ^= state << 13;
207            state ^= state >> 17;
208            state ^= state << 5;
209            state
210        };
211        for (width, height) in [(1, 7), (7, 1), (5, 5), (12, 9), (30, 30)] {
212            for _ in 0..20 {
213                let mut raster = AlphaImage::new(Size::new(width, height));
214                for pixel in &mut raster.data {
215                    *pixel = match next() % 8 {
216                        0..=3 => 0,
217                        4 | 5 => 255,
218                        _ => (next() % 256) as u8,
219                    };
220                }
221                for radius in [8.0, 16.0] {
222                    assert_eq!(
223                        transform_raster_to_sdf(&raster, radius, 0.25).data,
224                        brute_force(&raster, radius, 0.25),
225                        "{width}x{height}: {:?}",
226                        raster.data
227                    );
228                }
229            }
230        }
231    }
232}