summaryrefslogtreecommitdiffstats
path: root/tools/distfieldgen/main.cpp
blob: bb62a3c4b32dacd44a2f07d00e9f596bd5c8b37c (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#include <QtCore>
#include <QtGui>

const int inSize = 1024;
const int outSize = 32;
const int charRange = 0x8A;

static void usage()
{
    qWarning("Usage: distfieldgen [options] <font_filename>");
    qWarning(" ");
    qWarning(" options:");
    qWarning("  -d <directory>................................ output directory");

    qWarning(" ");
    exit(1);
}

void printProgress(int p)
{
    printf("\r[");
    for (int i = 0; i < 50; ++i)
        printf(i < p / 2 ? "=" : " ");
    printf("]");
    printf(" %d%%", p);
    fflush(stdout);
}

float mindist(const QImage &in, int w, int h, int x, int y, int r, float maxdist)
{
    int i, j, startx, starty, stopx, stopy, hit;
    float d, dx, dy;
    float mind = maxdist;
    int p;
    bool outside = (0 == qAlpha(in.pixel(x, y)));

    startx = qMax(0, x - r);
    starty = qMax(0, y - r);
    stopx = qMin(w, x + r);
    stopy = qMin(h, y + r);

    for (i = starty; i < stopy; i++) {
        for (j = startx; j < stopx; j++) {
            p = qAlpha(in.pixel(j, i));
            dx = j - x;
            dy = i - y;
            d = dx * dx + dy * dy;
            hit = (p != 0) == outside;
            if (hit && (d < mind)) {
                mind = d;
            }
        }
    }

    if (outside)
        return sqrtf(mind);
    else
        return -sqrtf(mind);
}

QImage renderDistanceField(const QImage &in)
{
    int outWidth = outSize * (float(in.width()) / in.height());
    int outHeight = outSize;
    QImage df(outWidth, outHeight, QImage::Format_ARGB32_Premultiplied);
    int x, y, ix, iy;
    float d;
    float sx = in.width() / float(outWidth);
    float sy = in.height() / float(outHeight);
    int r = 90;
    float maxsq = 2 * r * r;
    float max = qSqrt(maxsq);

    for(y = 0; y < outHeight; y++){
        for(x = 0; x < outWidth; x++){
            ix = (x * sx) + (sx / 2);
            iy = (y * sy) + (sy / 2);
            d = mindist(in, in.width(), in.height(), ix, iy, r, maxsq);
            float a = 127.5f + 127.5f * (-d / max);
            df.setPixel(x, y, qRgba(0, 0, 0, qRound(a)));
        }
    }

    return df;
}

class DistFieldGenTask : public QRunnable
{
public:
    DistFieldGenTask(int c, int nbGlyph, const QImage &glyph, QMap<int, QImage> *outList)
        : QRunnable()
        , m_char(c)
        , m_nbGlyph(nbGlyph)
        , m_glyph(glyph)
        , m_outList(outList)
    { }

    void run()
    {
        QImage df = renderDistanceField(m_glyph);
        QMutexLocker lock(&m_mutex);
        m_outList->insert(m_char, df);
        printProgress(float(m_outList->count()) / m_nbGlyph * 100);
    }

    static QMutex m_mutex;
    int m_char;
    int m_nbGlyph;
    QImage m_glyph;
    QMap<int, QImage> *m_outList;
};

QMutex DistFieldGenTask::m_mutex;

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QStringList args = QApplication::arguments();

    if (argc < 2 ||
        args.contains("--help") || args.contains("-help") || args.contains("--h") || args.contains("-h"))
        usage();

    QString fontFile;
    QString destDir;
    for (int i = 0; i < args.count(); ++i) {
        QString a = args.at(i);
        if (!a.startsWith('-') && QFileInfo(a).exists())
            fontFile = a;
        if (a == QLatin1String("-d"))
            destDir = args.at(++i);
    }

    // Load the font
    int fontID = QFontDatabase::addApplicationFont(fontFile);

    if (fontID == -1) {
        qWarning("Error: Invalid font file.");
        qWarning(" ");
        exit(1);
    }

    QFileInfo fi(fontFile);
    if (destDir.isEmpty()) {
        destDir = fi.canonicalPath();
    } else {
        QFileInfo dfi(destDir);
        if (!dfi.isDir()) {
            qWarning("Error: '%s' is not a directory.", destDir.toLatin1().constData());
            qWarning(" ");
            exit(1);
        }
        destDir = dfi.canonicalFilePath();
    }

    QStringList families = QFontDatabase::applicationFontFamilies(fontID);
    QFont f(families.at(0));
    f.setPixelSize(inSize);
    QFontMetricsF fm(f);

    printf("Rendering glyphs for font '%s'\n", f.family().toLatin1().constData());
    printProgress(0);

    QList<QImage> glyphs;
    QMap<int, QImage> distfields;

    // Render glyphs
    for (int i = 0; i < charRange; ++i) {
        QChar c(i);
        QImage glyph(fm.width(c), fm.height(), QImage::Format_ARGB32_Premultiplied);
        glyph.fill(Qt::transparent);
        QPainter p(&glyph);
        p.setFont(f);
        p.drawText(glyph.rect(), Qt::AlignHCenter | Qt::AlignVCenter, c);
        p.end();
        glyphs.append(glyph);
        printProgress(float(i) / charRange * 100);
    }

    printProgress(100);
    printf("\nGenerating distance field\n");
    printProgress(0);

    // Generate distance field for each glyph
    int i = 0;
    foreach (const QImage &g, glyphs) {
        QRunnable *run = new DistFieldGenTask(i, glyphs.count(), g, &distfields);
        QThreadPool::globalInstance()->start(run);
        ++i;
    }

    QThreadPool::globalInstance()->waitForDone();
    printProgress(100);
    printf("\nFinishing\n");
    printProgress(0);

    // Combine dist fields in one image
    int totalWidth = 0;
    foreach (const QImage &df, distfields.values())
        totalWidth += df.width() > 0 ? df.width() : outSize;

    QImage output(1024, (totalWidth / 1024 + 1) * outSize, QImage::Format_ARGB32_Premultiplied);
    output.fill(Qt::transparent);
    int combinedWidth = 0;
    i = 0;
    QPainter p(&output);
    foreach (const QImage &df, distfields.values()) {
        if (combinedWidth % 1024 + df.width() > 1024)
            combinedWidth = (combinedWidth / 1024 + 1) * 1024;
        p.drawImage(combinedWidth % 1024, (combinedWidth / 1024) * outSize, df);
        combinedWidth += df.width() > 0 ? df.width() : outSize;
        printProgress(float(i) / distfields.count() * 100);
        ++i;
    }
    p.end();
    printProgress(100);
    printf("\n");

    // Save output
    output.save(QString("%1/%2.png").arg(destDir).arg(fi.baseName()));

    return 0;
}