text_fonts

source of font::bitmaps

1// Bitmap color glyphs (decisions/F10.md, "Color emoji"): PNGs2// in CBDT, found through CBLC's strikes, and in sbix, Apple's; the strike3// nearest a size is decoded (png.alloy), premultiplied and resampled to4// the size, a box filter shrinking and bilinear interpolation growing.56import std::vector;7import std::option;8import std::math;9import std::result;1011import pkg::alloy::text::font::reader;12import pkg::alloy::text::font::face;13import png;14import pkg::alloy::text;1516// How CBLC's index subtables find a glyph's image.17type IndexFormat = enum : u16 {18    Offsets32 = 1, // an offset a glyph19    SameSize = 2, // images of one size, in order20    Offsets16 = 3,21    Pairs = 4, // a glyph and its offset, for glyphs here and there22    SameSizePairs = 5, // images of one size, for the glyphs listed23};2425// The image formats CBDT keeps PNGs in: with small metrics, big ones,26// or metrics in CBLC's index.27type ImageFormat = enum : u16 {28    SmallMetrics = 17,29    BigMetrics = 18,30    IndexMetrics = 19,31};3233// A glyph's PNG and where it goes: its strike's size, and the pixels from34// the pen to its image's left and up to its top, at that size.35type Bitmap = struct {36    png: &[u8],37    ppem: f32,38    left: f32,39    top: f32,40};4142// Whether the face has a bitmap for the glyph, in CBDT or sbix.43pub fn has_bitmap_glyph(face: &Face, glyph: u32) -> bool {44    return find_bitmap(&face, glyph, 64.0) is ::Some;45}4647// The glyph's bitmap at the size in pixels, None when the face has none.48pub fn bitmap_glyph(face: &Face, glyph: u32, size: f32) -> Option<ColorMask> {49    const bitmap = if (find_bitmap(&face, glyph, size) is ::Some |b|) b else {50        return ::None;51    };52    const image = match (read_png(&bitmap.png)) {53        ::Ok |move image| move image;54        ::Err {55            return ::None;56        }57    };58    return resample(&image, size / bitmap.ppem, bitmap.left, bitmap.top);59}6061fn find_bitmap(face: &Face, glyph: u32, size: f32) -> Option<Bitmap> {62    if (face.colors.cblc is ::Some |cblc| && face.colors.cbdt is ::Some |cbdt|) {63        if (cbdt_bitmap(&face.data(), cblc, cbdt, glyph, size) is ::Some |b|) {64            return ::Some(b);65        }66    }67    if (face.colors.sbix is ::Some |sbix|) {68        return sbix_bitmap(&face.data(), sbix, glyph, size, face.glyph_count);69    }70    return ::None;71}7273// Of strikes of sizes `ppem`, whether one of `candidate` is a better74// choice for the size than one of `best` (0 for none): the smallest at75// or above the size, else the largest.76fn better(candidate: u32, best: u32, size: f32) -> bool {77    if (best == 0) {78        return true;79    }80    const fits = candidate to f32 >= size;81    const best_fits = best to f32 >= size;82    if (fits != best_fits) {83        return fits;84    }85    return if (fits) candidate < best else candidate > best;86}8788/* --- CBDT and CBLC --- */8990fn cbdt_bitmap(d: &[u8], cblc: u64, cbdt: u64, glyph: u32, size: f32) -> Option<Bitmap> {91    // the strike, of those of 32-bit images having one for the glyph92    var best: Option<Bitmap> = ::None;93    var best_ppem: u32 = 0;94    for ([..u32_at(&d, cblc + 4) to u64]) |k| {95        const strike = cblc + 8 + k * 48;96        const ppem = u8_at(&d, strike + 45);97        if (98            u8_at(&d, strike + 46) == 3299            && u16_at(&d, strike + 40) <= glyph100            && glyph <= u16_at(&d, strike + 42)101            && ppem > 0102            && better(ppem, best_ppem, size)103        ) {104            if (cbdt_image(&d, cblc, cbdt, strike, glyph) is ::Some |b|) {105                best = ::Some(b);106                best_ppem = ppem;107            }108        }109    }110    return best;111}112113// The strike's image of the glyph, if it has one.114fn cbdt_image(d: &[u8], cblc: u64, cbdt: u64, strike: u64, glyph: u32) -> Option<Bitmap> {115    const sub = if (index_subtable(&d, cblc, strike, glyph) is ::Some |s|) s else {116        return ::None;117    };118    const index_format = if (IndexFormat::from(u16_at(&d, sub.at) to u16) is ::Some |f|) f else {119        return ::None;120    };121    const image_format = if (122        ImageFormat::from(u16_at(&d, sub.at + 2) to u16) is ::Some |f|123    ) f else {124        return ::None;125    };126    const images = cbdt + u32_at(&d, sub.at + 4) to u64;127    const k = (glyph - sub.first) to u64;128    // the glyph's image data, from its start to its end129    var start: u64 = 0;130    var end: u64 = 0;131    // the index's big metrics, for images that have none132    var metrics: u64 = 0;133    match (index_format) {134        ::Offsets32 {135            start = images + u32_at(&d, sub.at + 8 + k * 4) to u64;136            end = images + u32_at(&d, sub.at + 12 + k * 4) to u64;137        }138        ::Offsets16 {139            start = images + u16_at(&d, sub.at + 8 + k * 2) to u64;140            end = images + u16_at(&d, sub.at + 10 + k * 2) to u64;141        }142        ::SameSize {143            const image_size = u32_at(&d, sub.at + 8) to u64;144            start = images + k * image_size;145            end = start + image_size;146            metrics = sub.at + 12;147        }148        ::Pairs {149            const count = u32_at(&d, sub.at + 8) to u64;150            for ([..count]) |j| {151                const pair = sub.at + 12 + j * 4;152                if (u16_at(&d, pair) == glyph) {153                    start = images + u16_at(&d, pair + 2) to u64;154                    end = images + u16_at(&d, pair + 6) to u64;155                    break;156                }157            }158        }159        ::SameSizePairs {160            const image_size = u32_at(&d, sub.at + 8) to u64;161            const count = u32_at(&d, sub.at + 20) to u64;162            for ([..count]) |j| {163                if (u16_at(&d, sub.at + 24 + j * 2) == glyph) {164                    start = images + j * image_size;165                    end = start + image_size;166                    break;167                }168            }169            metrics = sub.at + 12;170        }171    }172    if (end <= start || end > d.length()) {173        return ::None;174    }175    // bearings in pixels at the strike's size, then the PNG's length176    var left: i32 = 0;177    var top: i32 = 0;178    var data = start;179    match (image_format) {180        ::SmallMetrics {181            left = signed(u8_at(&d, start + 2));182            top = signed(u8_at(&d, start + 3));183            data = start + 5;184        }185        ::BigMetrics {186            left = signed(u8_at(&d, start + 2));187            top = signed(u8_at(&d, start + 3));188            data = start + 8;189        }190        ::IndexMetrics {191            if (metrics == 0) {192                return ::None;193            }194            left = signed(u8_at(&d, metrics + 2));195            top = signed(u8_at(&d, metrics + 3));196        }197    }198    const length = u32_at(&d, data) to u64;199    if (data + 4 + length > end) {200        return ::None;201    }202    return ::Some(Bitmap {203        .png = &d[data + 4..data + 4 + length],204        .ppem = u8_at(&d, strike + 45) to f32,205        .left = left to f32,206        .top = top to f32207    });208}209210fn signed(byte: u32) -> i32 => if (byte >= 0x80) byte to i32 - 0x100 else byte to i32;211212// An index subtable: where it is, and the first glyph of its range.213type Subtable = struct {214    at: u64,215    first: u32,216};217218// The strike's index subtable holding the glyph.219fn index_subtable(d: &[u8], cblc: u64, strike: u64, glyph: u32) -> Option<Subtable> {220    const array = cblc + u32_at(&d, strike) to u64;221    for ([..u32_at(&d, strike + 8) to u64]) |k| {222        const entry = array + k * 8;223        const first = u16_at(&d, entry);224        if (first <= glyph && glyph <= u16_at(&d, entry + 2)) {225            return ::Some(Subtable { .at = array + u32_at(&d, entry + 4) to u64, .first = first });226        }227    }228    return ::None;229}230231/* --- sbix --- */232233fn sbix_bitmap(d: &[u8], sbix: u64, glyph: u32, size: f32, glyph_count: u32) -> Option<Bitmap> {234    if (glyph >= glyph_count) {235        return ::None;236    }237    var best: Option<u64> = ::None;238    var best_ppem: u32 = 0;239    for ([..u32_at(&d, sbix + 4) to u64]) |k| {240        const strike = sbix + u32_at(&d, sbix + 8 + k * 4) to u64;241        const ppem = u16_at(&d, strike);242        if (ppem > 0 && sbix_data(&d, strike, glyph) is ::Some && better(ppem, best_ppem, size)) {243            best = ::Some(strike);244            best_ppem = ppem;245        }246    }247    const strike = if (best is ::Some |s|) s else {248        return ::None;249    };250    var range = if (sbix_data(&d, strike, glyph) is ::Some |r|) r else {251        return ::None;252    };253    // a duplicate names the glyph whose image it shows254    if (tag_at(&d, range[0] + 4) == "dupe") {255        range = if (sbix_data(&d, strike, u16_at(&d, range[0] + 8)) is ::Some |r|) r else {256            return ::None;257        };258    }259    if (tag_at(&d, range[0] + 4) != "png ") {260        return ::None;261    }262    const png = &d[range[0] + 8..range[1]];263    // the image's bottom left is at the origin offset; its height from264    // the PNG's header265    const height = if (png.length() >= 24) u32_at(&png, 20) to f32 else 0.0;266    return ::Some(Bitmap {267        .png = &png,268        .ppem = best_ppem to f32,269        .left = i16_at(&d, range[0]) to f32,270        .top = i16_at(&d, range[0] + 2) to f32 + height271    });272}273274// Where the strike's record of the glyph starts and ends, if it has one275// with an image.276fn sbix_data(d: &[u8], strike: u64, glyph: u32) -> Option<[u64 : 2]> {277    const start = strike + u32_at(&d, strike + 4 + glyph to u64 * 4) to u64;278    const end = strike + u32_at(&d, strike + 8 + glyph to u64 * 4) to u64;279    if (end < start + 8 || end > d.length()) {280        return ::None;281    }282    return ::Some([start, end]);283}284285/* --- Resampling --- */286287// The image, premultiplied, at `scale` times its size, its top left at288// (left, top) pixels of its strike from the pen (y up); None past 2048289// pixels a side.290fn resample(image: &RgbaImage, scale: f32, left: f32, top: f32) -> Option<ColorMask> {291    const x = left * scale;292    const y = -top * scale;293    if (294        !(image.width to f32 * scale <= 2048.0)295        || !(image.height to f32 * scale <= 2048.0)296        || !(abs(x) < 1.0e6)297        || !(abs(y) < 1.0e6)298    ) {299        return ::None;300    }301    const x0 = floor(x) to i32;302    const y0 = floor(y) to i32;303    const width = max(ceil(x + image.width to f32 * scale) to i32 - x0, 1) to u32;304    const height = max(ceil(y + image.height to f32 * scale) to i32 - y0, 1) to u32;305    // premultiplied, as floats306    const count = image.width to u64 * image.height to u64;307    var source = Vector<f32>::with_capacity(count * 4);308    for ([..count]) |k| {309        const p = &image.pixels.view()[k * 4..k * 4 + 4];310        const a = p[3] to f32 / 255.0;311        source.push(p[0] to f32 / 255.0 * a);312        source.push(p[1] to f32 / 255.0 * a);313        source.push(p[2] to f32 / 255.0 * a);314        source.push(a);315    }316    const columns = weights(width, image.width, scale, x - x0 to f32);317    const rows = weights(height, image.height, scale, y - y0 to f32);318    // across, each source row to the width; then down319    const w = width to u64;320    var across = Vector<f32>::filled(0.0, image.height to u64 * w * 4);321    for ([..image.height to u64]) |sy| {322        for ([..w]) |ox| {323            for (columns.get(ox).view()) |&tap| {324                const s = (sy * image.width to u64 + tap.index) * 4;325                const o = (sy * w + ox) * 4;326                for ([..4 to u64]) |c| {327                    across.get_var(o + c) += source.get(s + c) * tap.weight;328                }329            }330        }331    }332    var pixels = Vector<u8>::filled(0, w * height to u64 * 4);333    for ([..height to u64]) |oy| {334        for ([..w]) |ox| {335            var sum: [f32 : 4] = [0.0, 0.0, 0.0, 0.0];336            for (rows.get(oy).view()) |&tap| {337                const s = (tap.index * w + ox) * 4;338                for ([..4 to u64]) |c| {339                    sum[c] += across.get(s + c) * tap.weight;340                }341            }342            const o = (oy * w + ox) * 4;343            for ([..4 to u64]) |c| {344                pixels.get_var(o + c) = (clamp(sum[c], 0.0, 1.0) * 255.0 + 0.5) to u8;345            }346        }347    }348    return ::Some(ColorMask {349        .width = width,350        .height = height,351        .left = x0,352        .top = y0,353        .pixels = move pixels,354        .foreground = false355    });356}357358// A source pixel's share of an output pixel.359type Tap = struct {360    index: u64,361    weight: f32,362};363364// For each of `count` output pixels along an axis, the source pixels it365// takes from: those a box of one output pixel (one source pixel when366// growing) around its center covers, by how much. `offset` is where the367// image starts in the first output pixel.368fn weights(count: u32, sources: u32, scale: f32, offset: f32) -> Vector<Vector<Tap>> {369    var out = Vector<Vector<Tap>>::with_capacity(count to u64);370    const half = max(1.0 / scale, 1.0) * 0.5;371    for ([..count to u64]) |o| {372        const center = (o to f32 + 0.5 - offset) / scale;373        const low = center - half;374        const high = center + half;375        var taps = Vector<Tap>::empty();376        const first = max(floor(low), 0.0) to u64;377        const last = min(ceil(high), sources to f32) to u64;378        for ([first..max(last, first)]) |k| {379            const covered = min(high, k to f32 + 1.0) - max(low, k to f32);380            if (covered > 0.0) {381                taps.push(Tap { .index = k, .weight = covered / (high - low) });382            }383        }384        out.push(move taps);385    }386    return move out;387}