forked from Chlumsky/msdfgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1392 lines (1340 loc) · 55.4 KB
/
main.cpp
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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR - standalone console program
* --------------------------------------------------------------------------
* A utility by Viktor Chlumsky, (c) 2014 - 2024
*
*/
#ifdef MSDFGEN_STANDALONE
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include "msdfgen.h"
#ifdef MSDFGEN_EXTENSIONS
#include "msdfgen-ext.h"
#endif
#include "core/ShapeDistanceFinder.h"
#define SDF_ERROR_ESTIMATE_PRECISION 19
#define DEFAULT_ANGLE_THRESHOLD 3.
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
#define DEFAULT_IMAGE_EXTENSION "png"
#define SAVE_DEFAULT_IMAGE_FORMAT savePng
#else
#define DEFAULT_IMAGE_EXTENSION "tiff"
#define SAVE_DEFAULT_IMAGE_FORMAT saveTiff
#endif
using namespace msdfgen;
enum Format {
AUTO,
PNG,
BMP,
TIFF,
RGBA,
FL32,
TEXT,
TEXT_FLOAT,
BINARY,
BINARY_FLOAT,
BINARY_FLOAT_BE
};
static bool is8bitFormat(Format format) {
return format == PNG || format == BMP || format == RGBA || format == TEXT || format == BINARY;
}
static char toupper(char c) {
return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
}
static bool parseUnsigned(unsigned &value, const char *arg) {
char *end = NULL;
value = (unsigned) strtoul(arg, &end, 10);
return end > arg && !*end;
}
static bool parseUnsignedDecOrHex(unsigned &value, const char *arg) {
char *end = NULL;
if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
arg += 2;
value = (unsigned) strtoul(arg, &end, 16);
} else
value = (unsigned) strtoul(arg, &end, 10);
return end > arg && !*end;
}
static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
if (*arg >= '0' && *arg <= '9') {
value = 0;
do {
value = 10*value+(*arg++-'0');
} while (*arg >= '0' && *arg <= '9');
return !*arg;
}
return false;
}
static bool parseDouble(double &value, const char *arg) {
char *end = NULL;
value = strtod(arg, &end);
return end > arg && !*end;
}
static bool parseAngle(double &value, const char *arg) {
char *end = NULL;
value = strtod(arg, &end);
if (end > arg) {
arg = end;
if (*arg == 'd' || *arg == 'D') {
++arg;
value *= M_PI/180;
}
return !*arg;
}
return false;
}
static void parseColoring(Shape &shape, const char *edgeAssignment) {
unsigned c = 0, e = 0;
if (shape.contours.size() < c) return;
Contour *contour = &shape.contours[c];
bool change = false;
bool clear = true;
for (const char *in = edgeAssignment; *in; ++in) {
switch (*in) {
case ',':
if (change)
++e;
if (clear)
while (e < contour->edges.size()) {
contour->edges[e]->color = WHITE;
++e;
}
++c, e = 0;
if (shape.contours.size() <= c) return;
contour = &shape.contours[c];
change = false;
clear = true;
break;
case '?':
clear = false;
break;
case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
if (change) {
++e;
change = false;
}
if (e < contour->edges.size()) {
contour->edges[e]->color = EdgeColor(
(*in == 'C' || *in == 'c')*CYAN|
(*in == 'M' || *in == 'm')*MAGENTA|
(*in == 'Y' || *in == 'y')*YELLOW|
(*in == 'W' || *in == 'w')*WHITE);
change = true;
}
break;
}
}
}
#ifdef MSDFGEN_EXTENSIONS
static bool parseUnicode(unicode_t &unicode, const char *arg) {
unsigned uuc;
if (parseUnsignedDecOrHex(uuc, arg)) {
unicode = uuc;
return true;
}
if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
unicode = (unicode_t) (unsigned char) arg[1];
return true;
}
return false;
}
#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
static FontHandle *loadVarFont(FreetypeHandle *library, const char *filename) {
std::string buffer;
while (*filename && *filename != '?')
buffer.push_back(*filename++);
FontHandle *font = loadFont(library, buffer.c_str());
if (font && *filename++ == '?') {
do {
buffer.clear();
while (*filename && *filename != '=')
buffer.push_back(*filename++);
if (*filename == '=') {
char *end = NULL;
double value = strtod(++filename, &end);
if (end > filename) {
filename = end;
setFontVariationAxis(library, font, buffer.c_str(), value);
}
}
} while (*filename++ == '&');
}
return font;
}
#endif
#endif
template <int N>
static void invertColor(const BitmapRef<float, N> &bitmap) {
const float *end = bitmap.pixels+N*bitmap.width*bitmap.height;
for (float *p = bitmap.pixels; p < end; ++p)
*p = 1.f-*p;
}
static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
int v = clamp(int((*values++)*0x100), 0xff);
fprintf(file, col ? " %02X" : "%02X", v);
}
fprintf(file, "\n");
}
return true;
}
static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
fprintf(file, col ? " %.9g" : "%.9g", *values++);
}
fprintf(file, "\n");
}
return true;
}
static bool writeBinBitmap(FILE *file, const float *values, int count) {
for (int pos = 0; pos < count; ++pos) {
unsigned char v = clamp(int((*values++)*0x100), 0xff);
fwrite(&v, 1, 1, file);
}
return true;
}
#ifdef __BIG_ENDIAN__
static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
#else
static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
#endif
{
return (int) fwrite(values, sizeof(float), count, file) == count;
}
#ifdef __BIG_ENDIAN__
static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
#else
static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
#endif
{
for (int pos = 0; pos < count; ++pos) {
const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
for (int i = sizeof(float)-1; i >= 0; --i)
fwrite(b+i, 1, 1, file);
}
return true;
}
static bool cmpExtension(const char *path, const char *ext) {
for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
if (a < path || toupper(*a) != toupper(*b))
return false;
return true;
}
template <int N>
static const char *writeOutput(const BitmapConstRef<float, N> &bitmap, const char *filename, Format &format) {
if (filename) {
if (format == AUTO) {
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
if (cmpExtension(filename, ".png")) format = PNG;
#else
if (cmpExtension(filename, ".png"))
return "PNG format is not available in core-only version.";
#endif
else if (cmpExtension(filename, ".bmp")) format = BMP;
else if (cmpExtension(filename, ".tiff") || cmpExtension(filename, ".tif")) format = TIFF;
else if (cmpExtension(filename, ".rgba")) format = RGBA;
else if (cmpExtension(filename, ".fl32")) format = FL32;
else if (cmpExtension(filename, ".txt")) format = TEXT;
else if (cmpExtension(filename, ".bin")) format = BINARY;
else
return "Could not deduce format from output file name.";
}
switch (format) {
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
#endif
case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";
case RGBA: return saveRgba(bitmap, filename) ? NULL : "Failed to write output RGBA image.";
case FL32: return saveFl32(bitmap, filename) ? NULL : "Failed to write output FL32 image.";
case TEXT: case TEXT_FLOAT: {
FILE *file = fopen(filename, "w");
if (!file) return "Failed to write output text file.";
if (format == TEXT)
writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height);
else if (format == TEXT_FLOAT)
writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height);
fclose(file);
return NULL;
}
case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {
FILE *file = fopen(filename, "wb");
if (!file) return "Failed to write output binary file.";
if (format == BINARY)
writeBinBitmap(file, bitmap.pixels, N*bitmap.width*bitmap.height);
else if (format == BINARY_FLOAT)
writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width*bitmap.height);
else if (format == BINARY_FLOAT_BE)
writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width*bitmap.height);
fclose(file);
return NULL;
}
default:;
}
} else {
if (format == AUTO || format == TEXT)
writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
else if (format == TEXT_FLOAT)
writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
else
return "Unsupported format for standard output.";
}
return NULL;
}
#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)
#define MSDFGEN_VERSION_STRING STRINGIZE(MSDFGEN_VERSION)
#ifdef MSDFGEN_VERSION_UNDERLINE
#define VERSION_UNDERLINE STRINGIZE(MSDFGEN_VERSION_UNDERLINE)
#else
#define VERSION_UNDERLINE "--------"
#endif
#if defined(MSDFGEN_EXTENSIONS) && (defined(MSDFGEN_DISABLE_SVG) || defined(MSDFGEN_DISABLE_PNG) || defined(MSDFGEN_DISABLE_VARIABLE_FONTS))
#define TITLE_SUFFIX " - custom config"
#define SUFFIX_UNDERLINE "----------------"
#elif !defined(MSDFGEN_EXTENSIONS) && defined(MSDFGEN_USE_OPENMP)
#define TITLE_SUFFIX " - core with OpenMP"
#define SUFFIX_UNDERLINE "-------------------"
#elif !defined(MSDFGEN_EXTENSIONS)
#define TITLE_SUFFIX " - core only"
#define SUFFIX_UNDERLINE "------------"
#elif defined(MSDFGEN_USE_SKIA) && defined(MSDFGEN_USE_OPENMP)
#define TITLE_SUFFIX " with Skia & OpenMP"
#define SUFFIX_UNDERLINE "-------------------"
#elif defined(MSDFGEN_USE_SKIA)
#define TITLE_SUFFIX " with Skia"
#define SUFFIX_UNDERLINE "----------"
#elif defined(MSDFGEN_USE_OPENMP)
#define TITLE_SUFFIX " with OpenMP"
#define SUFFIX_UNDERLINE "------------"
#else
#define TITLE_SUFFIX
#define SUFFIX_UNDERLINE
#endif
static const char *const versionText =
"MSDFgen v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
"(c) 2016 - " STRINGIZE(MSDFGEN_COPYRIGHT_YEAR) " Viktor Chlumsky";
static const char *const helpText =
"\n"
"Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
"------------------------------------------------------------------" VERSION_UNDERLINE SUFFIX_UNDERLINE "\n"
" Usage: msdfgen"
#ifdef _WIN32
".exe"
#endif
" <mode> <input specification> <options>\n"
"\n"
"MODES\n"
" sdf - Generate conventional monochrome (true) signed distance field.\n"
" psdf - Generate monochrome signed perpendicular distance field.\n"
" msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
" mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"
" metrics - Report shape metrics only.\n"
"\n"
"INPUT SPECIFICATION\n"
" -defineshape <definition>\n"
"\tDefines input shape using the ad-hoc text definition.\n"
#ifdef MSDFGEN_EXTENSIONS
" -font <filename.ttf> <character code>\n"
"\tLoads a single glyph from the specified font file.\n"
"\tFormat of character code is '?', 63, 0x3F (Unicode value), or g34 (glyph index).\n"
#endif
" -shapedesc <filename.txt>\n"
"\tLoads text shape description from a file.\n"
" -stdin\n"
"\tReads text shape description from the standard input.\n"
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
" -svg <filename.svg>\n"
"\tLoads the last vector path found in the specified SVG file.\n"
#endif
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_VARIABLE_FONTS)
" -varfont <filename and variables> <character code>\n"
"\tLoads a single glyph from a variable font. Specify variable values as x.ttf?var1=0.5&var2=1\n"
#endif
"\n"
// Keep alphabetical order!
"OPTIONS\n"
" -angle <angle>\n"
"\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
" -apxrange <outermost distance> <innermost distance>\n"
"\tSpecifies the outermost (negative) and innermost representable distance in pixels.\n"
" -arange <outermost distance> <innermost distance>\n"
"\tSpecifies the outermost (negative) and innermost representable distance in shape units.\n"
" -ascale <x scale> <y scale>\n"
"\tSets the scale used to convert shape units to pixels asymmetrically.\n"
" -autoframe\n"
"\tAutomatically scales (unless specified) and translates the shape to fit.\n"
" -coloringstrategy <simple / inktrap / distance>\n"
"\tSelects the strategy of the edge coloring heuristic.\n"
" -dimensions <width> <height>\n"
"\tSets the dimensions of the output image.\n"
" -edgecolors <sequence>\n"
"\tOverrides automatic edge coloring with the specified color sequence.\n"
#ifdef MSDFGEN_EXTENSIONS
" -emnormalize\n"
"\tBefore applying scale, normalizes font glyph coordinates so that 1 = 1 em.\n"
#endif
" -errorcorrection <mode>\n"
"\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"
" -errordeviationratio <ratio>\n"
"\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"
" -errorimproveratio <ratio>\n"
"\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"
" -estimateerror\n"
"\tComputes and prints the distance field's estimated fill error to the standard output.\n"
" -exportshape <filename.txt>\n"
"\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
" -exportsvg <filename.svg>\n"
"\tSaves the shape geometry into a simple SVG file.\n"
" -fillrule <nonzero / evenodd / positive / negative>\n"
"\tSets the fill rule for the scanline pass. Default is nonzero.\n"
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
" -format <png / bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"
#else
" -format <bmp / tiff / rgba / fl32 / text / textfloat / bin / binfloat / binfloatbe>\n"
#endif
"\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
" -guessorder\n"
"\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
" -help\n"
"\tDisplays this help.\n"
" -legacy\n"
"\tUses the original (legacy) distance field algorithms.\n"
#ifdef MSDFGEN_EXTENSIONS
" -noemnormalize\n"
"\tRaw integer font glyph coordinates will be used. Without this option, legacy scaling will be applied.\n"
#endif
#ifdef MSDFGEN_USE_SKIA
" -nopreprocess\n"
"\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"
#else
" -nooverlap\n"
"\tDisables resolution of overlapping contours.\n"
" -noscanline\n"
"\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
#endif
" -o <filename>\n"
"\tSets the output file name. The default value is \"output." DEFAULT_IMAGE_EXTENSION "\".\n"
#ifdef MSDFGEN_USE_SKIA
" -overlap\n"
"\tSwitches to distance field generator with support for overlapping contours.\n"
#endif
" -printmetrics\n"
"\tPrints relevant metrics of the shape to the standard output.\n"
" -pxrange <range>\n"
"\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
" -range <range>\n"
"\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
" -reverseorder\n"
"\tGenerates the distance field as if the shape's vertices were in reverse order.\n"
" -scale <scale>\n"
"\tSets the scale used to convert shape units to pixels.\n"
#ifdef MSDFGEN_USE_SKIA
" -scanline\n"
"\tPerforms an additional scanline pass to fix the signs of the distances.\n"
#endif
" -seed <n>\n"
"\tSets the random seed for edge coloring heuristic.\n"
" -stdout\n"
"\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
" -testrender <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
"\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
#else
"\tRenders an image preview using the generated distance field and saves it as a TIFF file.\n"
#endif
" -testrendermulti <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
"\tRenders an image preview without flattening the color channels.\n"
" -translate <x> <y>\n"
"\tSets the translation of the shape in shape units.\n"
" -version\n"
"\tPrints the version of the program.\n"
" -windingpreprocess\n"
"\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"
" -yflip\n"
"\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
"\n";
static const char *errorCorrectionHelpText =
"\n"
"ERROR CORRECTION MODES\n"
" auto-fast\n"
"\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"
" auto-full\n"
"\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"
" auto-mixed (default)\n"
"\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"
" disabled\n"
"\tDisables error correction.\n"
" distance-fast\n"
"\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"
" distance-full\n"
"\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"
" edge-fast\n"
"\tDetects inversion artifacts only by range testing.\n"
" edge-full\n"
"\tDetects inversion artifacts only by exact distance evaluation.\n"
" help\n"
"\tDisplays this help.\n"
"\n";
int main(int argc, const char *const *argv) {
#define ABORT(msg) do { fputs(msg "\n", stderr); return 1; } while (false)
// Parse command line arguments
enum {
NONE,
SVG,
FONT,
VAR_FONT,
DESCRIPTION_ARG,
DESCRIPTION_STDIN,
DESCRIPTION_FILE
} inputType = NONE;
enum {
SINGLE,
PERPENDICULAR,
MULTI,
MULTI_AND_TRUE,
METRICS
} mode = MULTI;
enum {
NO_PREPROCESS,
WINDING_PREPROCESS,
FULL_PREPROCESS
} geometryPreproc = (
#ifdef MSDFGEN_USE_SKIA
FULL_PREPROCESS
#else
NO_PREPROCESS
#endif
);
bool legacyMode = false;
MSDFGeneratorConfig generatorConfig;
generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;
bool scanlinePass = geometryPreproc == NO_PREPROCESS;
FillRule fillRule = FILL_NONZERO;
Format format = AUTO;
const char *input = NULL;
const char *output = "output." DEFAULT_IMAGE_EXTENSION;
const char *shapeExport = NULL;
const char *svgExport = NULL;
const char *testRender = NULL;
const char *testRenderMulti = NULL;
bool outputSpecified = false;
#ifdef MSDFGEN_EXTENSIONS
bool glyphIndexSpecified = false;
GlyphIndex glyphIndex;
unicode_t unicode = 0;
FontCoordinateScaling fontCoordinateScaling = FONT_SCALING_LEGACY;
bool fontCoordinateScalingSpecified = false;
#endif
int width = 64, height = 64;
int testWidth = 0, testHeight = 0;
int testWidthM = 0, testHeightM = 0;
bool autoFrame = false;
enum {
RANGE_UNIT,
RANGE_PX
} rangeMode = RANGE_PX;
Range range(1);
Range pxRange(2);
Vector2 translate;
Vector2 scale = 1;
bool scaleSpecified = false;
double angleThreshold = DEFAULT_ANGLE_THRESHOLD;
float outputDistanceShift = 0.f;
const char *edgeAssignment = NULL;
bool yFlip = false;
bool printMetrics = false;
bool estimateError = false;
bool skipColoring = false;
enum {
KEEP,
REVERSE,
GUESS
} orientation = KEEP;
unsigned long long coloringSeed = 0;
void (*edgeColoring)(Shape &, double, unsigned long long) = &edgeColoringSimple;
bool explicitErrorCorrectionMode = false;
int argPos = 1;
bool suggestHelp = false;
while (argPos < argc) {
const char *arg = argv[argPos];
#define ARG_CASE(s, p) if ((!strcmp(arg, s)) && argPos+(p) < argc && (++argPos, true))
#define ARG_CASE_OR ) || !strcmp(arg,
#define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
#define ARG_IS(s) (!strcmp(argv[argPos], s))
#define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
// Accept arguments prefixed with -- instead of -
if (arg[0] == '-' && arg[1] == '-')
++arg;
ARG_MODE("sdf", SINGLE)
ARG_MODE("psdf", PERPENDICULAR)
ARG_MODE("msdf", MULTI)
ARG_MODE("mtsdf", MULTI_AND_TRUE)
ARG_MODE("metrics", METRICS)
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
ARG_CASE("-svg", 1) {
inputType = SVG;
input = argv[argPos++];
continue;
}
#endif
#ifdef MSDFGEN_EXTENSIONS
//ARG_CASE -font, -varfont
if (argPos+2 < argc && (
(!strcmp(arg, "-font") && (inputType = FONT, true))
#ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
|| (!strcmp(arg, "-varfont") && (inputType = VAR_FONT, true))
#endif
) && (++argPos, true)) {
input = argv[argPos++];
const char *charArg = argv[argPos++];
unsigned gi;
switch (charArg[0]) {
case 'G': case 'g':
if (parseUnsignedDecOrHex(gi, charArg+1)) {
glyphIndex = GlyphIndex(gi);
glyphIndexSpecified = true;
}
break;
case 'U': case 'u':
++charArg;
// fallthrough
default:
parseUnicode(unicode, charArg);
}
continue;
}
ARG_CASE("-noemnormalize", 0) {
fontCoordinateScaling = FONT_SCALING_NONE;
fontCoordinateScalingSpecified = true;
continue;
}
ARG_CASE("-emnormalize", 0) {
fontCoordinateScaling = FONT_SCALING_EM_NORMALIZED;
fontCoordinateScalingSpecified = true;
continue;
}
ARG_CASE("-legacyfontscaling", 0) {
fontCoordinateScaling = FONT_SCALING_LEGACY;
fontCoordinateScalingSpecified = true;
continue;
}
#else
ARG_CASE("-svg", 1) {
ABORT("SVG input is not available in core-only version.");
}
ARG_CASE("-font", 2) {
ABORT("Font input is not available in core-only version.");
}
ARG_CASE("-varfont", 2) {
ABORT("Variable font input is not available in core-only version.");
}
#endif
ARG_CASE("-defineshape", 1) {
inputType = DESCRIPTION_ARG;
input = argv[argPos++];
continue;
}
ARG_CASE("-stdin", 0) {
inputType = DESCRIPTION_STDIN;
input = "stdin";
continue;
}
ARG_CASE("-shapedesc", 1) {
inputType = DESCRIPTION_FILE;
input = argv[argPos++];
continue;
}
ARG_CASE("-o" ARG_CASE_OR "-out" ARG_CASE_OR "-output" ARG_CASE_OR "-imageout", 1) {
output = argv[argPos++];
outputSpecified = true;
continue;
}
ARG_CASE("-stdout", 0) {
output = NULL;
continue;
}
ARG_CASE("-legacy", 0) {
legacyMode = true;
#ifdef MSDFGEN_EXTENSIONS
fontCoordinateScaling = FONT_SCALING_LEGACY;
fontCoordinateScalingSpecified = true;
#endif
continue;
}
ARG_CASE("-nopreprocess", 0) {
geometryPreproc = NO_PREPROCESS;
continue;
}
ARG_CASE("-windingpreprocess", 0) {
geometryPreproc = WINDING_PREPROCESS;
continue;
}
ARG_CASE("-preprocess", 0) {
geometryPreproc = FULL_PREPROCESS;
continue;
}
ARG_CASE("-nooverlap", 0) {
generatorConfig.overlapSupport = false;
continue;
}
ARG_CASE("-overlap", 0) {
generatorConfig.overlapSupport = true;
continue;
}
ARG_CASE("-noscanline", 0) {
scanlinePass = false;
continue;
}
ARG_CASE("-scanline", 0) {
scanlinePass = true;
continue;
}
ARG_CASE("-fillrule", 1) {
scanlinePass = true;
if (ARG_IS("nonzero")) fillRule = FILL_NONZERO;
else if (ARG_IS("evenodd") || ARG_IS("odd")) fillRule = FILL_ODD;
else if (ARG_IS("positive")) fillRule = FILL_POSITIVE;
else if (ARG_IS("negative")) fillRule = FILL_NEGATIVE;
else
fputs("Unknown fill rule specified.\n", stderr);
++argPos;
continue;
}
ARG_CASE("-format", 1) {
if (ARG_IS("auto")) format = AUTO;
#if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
else if (ARG_IS("png")) SET_FORMAT(PNG, "png");
#else
else if (ARG_IS("png"))
fputs("PNG format is not available in core-only version.\n", stderr);
#endif
else if (ARG_IS("bmp")) SET_FORMAT(BMP, "bmp");
else if (ARG_IS("tiff") || ARG_IS("tif")) SET_FORMAT(TIFF, "tiff");
else if (ARG_IS("rgba")) SET_FORMAT(RGBA, "rgba");
else if (ARG_IS("fl32")) SET_FORMAT(FL32, "fl32");
else if (ARG_IS("text") || ARG_IS("txt")) SET_FORMAT(TEXT, "txt");
else if (ARG_IS("textfloat") || ARG_IS("txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
else if (ARG_IS("bin") || ARG_IS("binary")) SET_FORMAT(BINARY, "bin");
else if (ARG_IS("binfloat") || ARG_IS("binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
else if (ARG_IS("binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
else
fputs("Unknown format specified.\n", stderr);
++argPos;
continue;
}
ARG_CASE("-dimensions" ARG_CASE_OR "-size", 2) {
unsigned w, h;
if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && w && h))
ABORT("Invalid dimensions. Use -dimensions <width> <height> with two positive integers.");
width = w, height = h;
continue;
}
ARG_CASE("-autoframe", 0) {
autoFrame = true;
continue;
}
ARG_CASE("-range" ARG_CASE_OR "-unitrange", 1) {
double r;
if (!parseDouble(r, argv[argPos++]))
ABORT("Invalid range argument. Use -range <range> with a real number.");
if (r == 0)
ABORT("Range must be non-zero.");
rangeMode = RANGE_UNIT;
range = Range(r);
continue;
}
ARG_CASE("-pxrange", 1) {
double r;
if (!parseDouble(r, argv[argPos++]))
ABORT("Invalid range argument. Use -pxrange <range> with a real number.");
if (r == 0)
ABORT("Range must be non-zero.");
rangeMode = RANGE_PX;
pxRange = Range(r);
continue;
}
ARG_CASE("-arange" ARG_CASE_OR "-aunitrange", 2) {
double r0, r1;
if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))
ABORT("Invalid range arguments. Use -arange <minimum> <maximum> with two real numbers.");
if (r0 == r1)
ABORT("Range must be non-empty.");
rangeMode = RANGE_UNIT;
range = Range(r0, r1);
continue;
}
ARG_CASE("-apxrange", 2) {
double r0, r1;
if (!(parseDouble(r0, argv[argPos++]) && parseDouble(r1, argv[argPos++])))
ABORT("Invalid range arguments. Use -apxrange <minimum> <maximum> with two real numbers.");
if (r0 == r1)
ABORT("Range must be non-empty.");
rangeMode = RANGE_PX;
pxRange = Range(r0, r1);
continue;
}
ARG_CASE("-scale", 1) {
double s;
if (!(parseDouble(s, argv[argPos++]) && s > 0))
ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
scale = s;
scaleSpecified = true;
continue;
}
ARG_CASE("-ascale", 2) {
double sx, sy;
if (!(parseDouble(sx, argv[argPos++]) && parseDouble(sy, argv[argPos++]) && sx > 0 && sy > 0))
ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
scale.set(sx, sy);
scaleSpecified = true;
continue;
}
ARG_CASE("-translate", 2) {
double tx, ty;
if (!(parseDouble(tx, argv[argPos++]) && parseDouble(ty, argv[argPos++])))
ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
translate.set(tx, ty);
continue;
}
ARG_CASE("-angle", 1) {
double at;
if (!parseAngle(at, argv[argPos++]))
ABORT("Invalid angle threshold. Use -angle <min angle> with a positive real number less than PI or a value in degrees followed by 'd' below 180d.");
angleThreshold = at;
continue;
}
ARG_CASE("-errorcorrection", 1) {
if (ARG_IS("disable") || ARG_IS("disabled") || ARG_IS("0") || ARG_IS("none") || ARG_IS("false")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (ARG_IS("default") || ARG_IS("auto") || ARG_IS("auto-mixed") || ARG_IS("mixed")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
} else if (ARG_IS("auto-fast") || ARG_IS("fast")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (ARG_IS("auto-full") || ARG_IS("full")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (ARG_IS("distance") || ARG_IS("distance-fast") || ARG_IS("indiscriminate") || ARG_IS("indiscriminate-fast")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (ARG_IS("distance-full") || ARG_IS("indiscriminate-full")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (ARG_IS("edge-fast")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
} else if (ARG_IS("edge") || ARG_IS("edge-full")) {
generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
} else if (ARG_IS("help")) {
puts(errorCorrectionHelpText);
return 0;
} else
fputs("Unknown error correction mode. Use -errorcorrection help for more information.\n", stderr);
++argPos;
explicitErrorCorrectionMode = true;
continue;
}
ARG_CASE("-errordeviationratio", 1) {
double edr;
if (!(parseDouble(edr, argv[argPos++]) && edr > 0))
ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");
generatorConfig.errorCorrection.minDeviationRatio = edr;
continue;
}
ARG_CASE("-errorimproveratio", 1) {
double eir;
if (!(parseDouble(eir, argv[argPos++]) && eir > 0))
ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");
generatorConfig.errorCorrection.minImproveRatio = eir;
continue;
}
ARG_CASE("-coloringstrategy" ARG_CASE_OR "-edgecoloring", 1) {
if (ARG_IS("simple")) edgeColoring = &edgeColoringSimple;
else if (ARG_IS("inktrap")) edgeColoring = &edgeColoringInkTrap;
else if (ARG_IS("distance")) edgeColoring = &edgeColoringByDistance;
else
fputs("Unknown coloring strategy specified.\n", stderr);
++argPos;
continue;
}
ARG_CASE("-edgecolors", 1) {
static const char *allowed = " ?,cmwyCMWY";
for (int i = 0; argv[argPos][i]; ++i) {
for (int j = 0; allowed[j]; ++j)
if (argv[argPos][i] == allowed[j])
goto EDGE_COLOR_VERIFIED;
ABORT("Invalid edge coloring sequence. Use -edgecolors <color sequence> with only the colors C, M, Y, and W. Separate contours by commas and use ? to keep the default assigment for a contour.");
EDGE_COLOR_VERIFIED:;
}
edgeAssignment = argv[argPos++];
continue;
}
ARG_CASE("-distanceshift", 1) {
double ds;
if (!parseDouble(ds, argv[argPos++]))
ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");
outputDistanceShift = (float) ds;
continue;
}
ARG_CASE("-exportshape", 1) {
shapeExport = argv[argPos++];
continue;
}
ARG_CASE("-exportsvg", 1) {
svgExport = argv[argPos++];
continue;
}
ARG_CASE("-testrender", 3) {
unsigned w, h;
testRender = argv[argPos++];
if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))
ABORT("Invalid arguments for test render. Use -testrender <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
testWidth = w, testHeight = h;
continue;
}
ARG_CASE("-testrendermulti", 3) {
unsigned w, h;
testRenderMulti = argv[argPos++];
if (!(parseUnsigned(w, argv[argPos++]) && parseUnsigned(h, argv[argPos++]) && (int) w > 0 && (int) h > 0))
ABORT("Invalid arguments for test render. Use -testrendermulti <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
testWidthM = w, testHeightM = h;
continue;
}
ARG_CASE("-yflip", 0) {
yFlip = true;
continue;
}
ARG_CASE("-printmetrics", 0) {
printMetrics = true;
continue;
}
ARG_CASE("-estimateerror", 0) {
estimateError = true;
continue;
}
ARG_CASE("-keeporder", 0) {
orientation = KEEP;
continue;
}
ARG_CASE("-reverseorder", 0) {
orientation = REVERSE;
continue;
}
ARG_CASE("-guessorder", 0) {
orientation = GUESS;
continue;
}
ARG_CASE("-seed", 1) {
if (!parseUnsignedLL(coloringSeed, argv[argPos++]))
ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
continue;
}
ARG_CASE("-version", 0) {
puts(versionText);
return 0;
}
ARG_CASE("-help", 0) {
puts(helpText);
return 0;
}
fprintf(stderr, "Unknown setting or insufficient parameters: %s\n", argv[argPos++]);
suggestHelp = true;
}
if (suggestHelp)
fprintf(stderr, "Use -help for more information.\n");