aboutsummaryrefslogtreecommitdiff
path: root/sys/libfont/test.c
blob: 7ce9dc0a0616e29a2ca57f5edde7201bcc0f7299 (plain)
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
#include <u.h>
#include <libn.h>
#include <libfont.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define DIV 2
#define W 1920/DIV
#define H 1080
#define L H/80

static char *phrase = "strlen(info)=000";

int
main()
{
    int i, j, k, err;
    float x, dx, dy, scale, sx, sy;
    uchar *bitmap, *work;
    font·Info *info;
    mmap·Reader fontfile;
    int w, h, off, y, ascent, descent, baseln;
    int adv, lsb, r0[2], r1[2];

    err = 0;
    fontfile = mmap·open("/home/nolln/root/data/Inconsolata-Regular.ttf");
    if (!fontfile.len) {
        err = 1;
        goto end;
    }

    info   = font·make(fontfile.ubuf, 0, mem·sys, nil);
    if (!info) 
        panicf("failed to load info");

    bitmap = calloc(W*H, sizeof(*bitmap)); 
    scale  = font·scaleheightto(info, L);

    font·vmetrics(info, &ascent, &descent, &baseln);
    ascent *= scale;

    x  = 0.;
    dy = 0.;
    for (i = 0; i < strlen(phrase); i++) {
        dx = x - (float)floor(x);
        font·code_hmetrics(info, phrase[i], &adv, &lsb);
        font·code_bbox_subpixel(info, phrase[i], scale, scale, dx, 0, r0, r0+1, r1, r1+1);

        y   = ascent + r0[1];
        dy  = y - (float)floor(y);

        w = r1[0]-r0[0];
        h = r1[1]-r0[1];

        work = calloc(w*h, sizeof(*bitmap)); 
        font·code_fillbitmap_subpixel_prefilter(info, work, w, h, w, scale, scale, dx, 0, 1, 1, &sx, &sy, phrase[i]);

        off = (int)floor(x+sx) + r0[0] + ((int)floor(sy)+y) * W; 
        for (j = 0; j < h; j++) {
            for (k = 0; k < w; k++) {
                bitmap[off + W*j + k] += work[k + w*j];
            }
        }
        free(work);

        x += scale * adv;
        if (phrase[i+1])
            x += scale * font·code_kernadvance(info, phrase[i], phrase[i+1]);
    }

    stbi_write_png("out.png", W, H, 1, bitmap, W);

    font·free(info);
    free(bitmap);
end:
    mmap·close(fontfile);
    return err;
}