draw

source of pkg::alloy::text::font::raster

1// Outlines into coverage masks (PLAN.md, F4 question 2): every2// line's signed area accumulated per pixel, then summed along each row,3// as font-rs does; curves are flattened into lines first. Grayscale,4// unhinted.56import std::vector;7import std::option;8import std::math;910import text;11import outline;1213// A mask covering nothing.14fn empty_mask() -> GlyphMask {15    return GlyphMask {16        .width = 0,17        .height = 0,18        .left = 0,19        .top = 0,20        .coverage = Vector<u8>::empty()21    };22}2324// The outline at `scale` pixels a font unit, moved right by `shift`25// pixels (a fraction, for subpixel positions).26exp fn rasterize(o: &Outline, scale: f32, shift: f32) -> GlyphMask {27    return rasterize_with(28        &o,29        &Affine { .a = scale, .b = 0.0, .c = 0.0, .d = -scale, .e = shift, .f = 0.0 }30    );31}3233// The outline taken from font units (y up) to pixels (y down) by the34// transform.35exp fn rasterize_with(o: &Outline, t: &Affine) -> GlyphMask {36    return rasterize_within(&o, &t, [-1000000, -1000000, 1000000, 1000000]);37}3839// The outline taken to pixels by the transform, its mask within the40// window (left, top, right, bottom), past which it is cut.41exp fn rasterize_within(o: &Outline, t: &Affine, window: [i32 : 4]) -> GlyphMask {42    if (o.points.length() == 0) {43        return empty_mask();44    }45    var x0: f32 = 1000000.0;46    var y0: f32 = 1000000.0;47    var x1: f32 = -1000000.0;48    var y1: f32 = -1000000.0;49    for (o.points.view()) |&p| {50        const x = t.a * p.x + t.c * p.y + t.e;51        const y = t.b * p.x + t.d * p.y + t.f;52        if (!(abs(x) < 1.0e7 && abs(y) < 1.0e7)) {53            return empty_mask(); // a transform out of reason54        }55        x0 = min(x0, x);56        x1 = max(x1, x);57        y0 = min(y0, y);58        y1 = max(y1, y);59    }60    // a column and a row past the right and bottom, where edges there fall61    const l = max(floor(x0), window[0] to f32);62    const t0 = max(floor(y0), window[1] to f32);63    const r = min(ceil(x1), window[2] to f32);64    const b = min(ceil(y1), window[3] to f32);65    if (!(l <= r && r - l < 4096.0) || !(t0 <= b && b - t0 < 4096.0)) {66        return empty_mask();67    }68    const left = l to i32;69    const top = t0 to i32;70    const width = (r - l) to u32 + 1;71    const height = (b - t0) to u32 + 1;72    var r = Rasterizer {73        .width = width,74        .height = height,75        .area = Vector<f32>::filled(0.0, width to u64 * height to u64 + 4)76    };77    // to the mask's pixels, from its top left78    var placed = copy t;79    placed.e -= left to f32;80    placed.f -= top to f32;81    var start: u64 = 0;82    for (o.ends.view()) |end| {83        r.contour(&o.points.view()[start..end to u64 + 1], placed);84        start = end to u64 + 1;85    }86    const count = width to u64 * height to u64;87    var coverage = Vector<u8>::filled(0, count);88    var sum: f32 = 0.0;89    for (coverage.items(), r.area.view()[..count]) |&var byte, area| {90        sum += area;91        byte = (min(abs(sum), 1.0) * 255.0 + 0.5) to u8;92    }93    return GlyphMask {94        .width = width,95        .height = height,96        .left = left,97        .top = top,98        .coverage = move coverage99    };100}101102type Rasterizer = struct {103    width: u32,104    height: u32,105    area: Vector<f32>,106};107108type Vec2 = struct {109    x: f32,110    y: f32,111};112113// One contour: quadratic curves between on-curve points, an off-curve114// pair implying the on-curve point midway, and cubic curves through115// their two control points.116fn contour(self r: &var Rasterizer, points: &[OutlinePoint], t: Affine) {117    const n = points.length();118    if (n < 2) {119        return;120    }121    // start at an on-curve point, or between the first two off-curve ones122    var first: u64 = 0;123    while (first < n && !(points[first].kind is ::On)) {124        first += 1;125    }126    if (first == n) {127        first = 0;128    }129    const start = if (points[first].kind is ::On) place(&points[first], t) else mid(130        place(&points[0], t),131        place(&points[1], t)132    );133    var current = start;134    var control: Option<Vec2> = ::None;135    var step: u64 = 1;136    while (step <= n) {137        const p = &points[(first + step) % n];138        const at = place(&p, t);139        match (p.kind) {140            ::On {141                if (control is ::Some |c|) {142                    r.curve(current, c, at);143                } else {144                    r.line(current, at);145                }146                current = at;147                control = ::None;148            }149            ::Quadratic {150                if (control is ::Some |c|) {151                    const between = mid(c, at);152                    r.curve(current, c, between);153                    current = between;154                }155                control = ::Some(at);156            }157            ::Cubic {158                // two control points, then the end (the start past the last)159                if (step + 1 > n) {160                    break;161                }162                const second = place(&points[(first + step + 1) % n], t);163                const end = if (step + 2 > n) start else place(&points[(first + step + 2) % n], t);164                r.cubic(current, at, second, end);165                current = end;166                step += 2;167            }168        }169        step += 1;170    }171    if (control is ::Some |c|) {172        r.curve(current, c, start);173    } else if (current.x != start.x || current.y != start.y) {174        r.line(current, start);175    }176}177178fn place(p: &OutlinePoint, t: Affine) -> Vec2 {179    return Vec2 { .x = t.a * p.x + t.c * p.y + t.e, .y = t.b * p.x + t.d * p.y + t.f };180}181182fn mid(a: Vec2, b: Vec2) -> Vec2 {183    return Vec2 { .x = (a.x + b.x) * 0.5, .y = (a.y + b.y) * 0.5 };184}185186fn curve(self r: &var Rasterizer, p0: Vec2, p1: Vec2, p2: Vec2) {187    const ddx = p0.x - 2.0 * p1.x + p2.x;188    const ddy = p0.y - 2.0 * p1.y + p2.y;189    const deviation = ddx * ddx + ddy * ddy;190    if (deviation < 0.333) {191        r.line(p0, p2);192        return;193    }194    const segments = 1 + floor(sqrt(sqrt(3.0 * deviation))) to u32;195    var previous = p0;196    for ([1..segments to u64 + 1]) |k| {197        const t = k to f32 / segments to f32;198        const u = 1.0 - t;199        const next = Vec2 {200            .x = u * u * p0.x + 2.0 * u * t * p1.x + t * t * p2.x,201            .y = u * u * p0.y + 2.0 * u * t * p1.y + t * t * p2.y202        };203        r.line(previous, next);204        previous = next;205    }206}207208// A cubic curve, flattened as finely as quadratic ones are: its second209// differences bound how far lines stray from it.210fn cubic(self r: &var Rasterizer, p0: Vec2, p1: Vec2, p2: Vec2, p3: Vec2) {211    const ax = p0.x - 2.0 * p1.x + p2.x;212    const ay = p0.y - 2.0 * p1.y + p2.y;213    const bx = p1.x - 2.0 * p2.x + p3.x;214    const by = p1.y - 2.0 * p2.y + p3.y;215    const deviation = max(ax * ax + ay * ay, bx * bx + by * by);216    if (deviation < 0.037) {217        r.line(p0, p3);218        return;219    }220    const segments = 1 + floor(sqrt(sqrt(27.0 * deviation))) to u32;221    var previous = p0;222    for ([1..segments to u64 + 1]) |k| {223        const t = k to f32 / segments to f32;224        const u = 1.0 - t;225        const a = u * u * u;226        const b = 3.0 * u * u * t;227        const c = 3.0 * u * t * t;228        const e = t * t * t;229        const next = Vec2 {230            .x = a * p0.x + b * p1.x + c * p2.x + e * p3.x,231            .y = a * p0.y + b * p1.y + c * p2.y + e * p3.y232        };233        r.line(previous, next);234        previous = next;235    }236}237238// The line's signed area into the cells it crosses (font-rs's239// accumulation).240fn line(self r: &var Rasterizer, start: Vec2, end: Vec2) {241    if (start.y == end.y) {242        return;243    }244    const downward = start.y <= end.y;245    const direction: f32 = if (downward) 1.0 else -1.0;246    const p0 = if (downward) start else end;247    const p1 = if (downward) end else start;248    const dxdy = (p1.x - p0.x) / (p1.y - p0.y);249    var x = p0.x;250    if (p0.y < 0.0) {251        x -= p0.y * dxdy;252    }253    const w = r.width to i64;254    const last = (r.width - 1) to f32;255    var area = &var r.area.items();256    const y_start = max(floor(p0.y), 0.0) to i64;257    const y_end = min(ceil(p1.y), r.height to f32) to i64;258    var y = y_start;259    while (y < y_end) {260        const row = y * w;261        const dy = min(y to f32 + 1.0, p1.y) - max(y to f32, p0.y);262        const x_next = x + dxdy * dy;263        const d = dy * direction;264        // left of the mask (a hair, by rounding, or cut by its window),265        // an edge counts at its left side, and right of it at its last266        // column267        const xa = clamp(min(x, x_next), 0.0, last);268        const xb = clamp(max(x, x_next), 0.0, last);269        const xa_floor = floor(xa);270        const a0 = xa_floor to i64;271        const b1 = ceil(xb) to i64;272        if (b1 < w + 2) {273            if (b1 <= a0 + 1) {274                const middle = 0.5 * (xa + xb) - xa_floor;275                area[(row + a0) to u64] += d - d * middle;276                area[(row + a0 + 1) to u64] += d * middle;277            } else {278                const s = 1.0 / (xb - xa);279                const af = xa - xa_floor;280                const first = 0.5 * s * (1.0 - af) * (1.0 - af);281                const bf = xb - b1 to f32 + 1.0;282                const last = 0.5 * s * bf * bf;283                area[(row + a0) to u64] += d * first;284                if (b1 == a0 + 2) {285                    area[(row + a0 + 1) to u64] += d * (1.0 - first - last);286                } else {287                    const second = s * (1.5 - af);288                    area[(row + a0 + 1) to u64] += d * (second - first);289                    for ([a0 + 2..b1 - 1]) |k| {290                        area[(row + k) to u64] += d * s;291                    }292                    const before_last = second + (b1 - a0 - 3) to f32 * s;293                    area[(row + b1 - 1) to u64] += d * (1.0 - before_last - last);294                }295                area[(row + b1) to u64] += d * last;296            }297        }298        x = x_next;299        y += 1;300    }301}