main.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR - standalone console program
  3. * --------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2023
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #define _USE_MATH_DEFINES
  9. #define _CRT_SECURE_NO_WARNINGS
  10. #include <cstdio>
  11. #include <cmath>
  12. #include <cstring>
  13. #include <string>
  14. #include "msdfgen.h"
  15. #ifdef MSDFGEN_EXTENSIONS
  16. #include "msdfgen-ext.h"
  17. #endif
  18. #include "core/ShapeDistanceFinder.h"
  19. #define SDF_ERROR_ESTIMATE_PRECISION 19
  20. #define DEFAULT_ANGLE_THRESHOLD 3.
  21. #ifdef MSDFGEN_EXTENSIONS
  22. #define DEFAULT_IMAGE_EXTENSION "png"
  23. #define SAVE_DEFAULT_IMAGE_FORMAT savePng
  24. #else
  25. #define DEFAULT_IMAGE_EXTENSION "tif"
  26. #define SAVE_DEFAULT_IMAGE_FORMAT saveTiff
  27. #endif
  28. using namespace msdfgen;
  29. enum Format {
  30. AUTO,
  31. PNG,
  32. BMP,
  33. TIFF,
  34. TEXT,
  35. TEXT_FLOAT,
  36. BINARY,
  37. BINARY_FLOAT,
  38. BINARY_FLOAT_BE
  39. };
  40. static bool is8bitFormat(Format format) {
  41. return format == PNG || format == BMP || format == TEXT || format == BINARY;
  42. }
  43. static char toupper(char c) {
  44. return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
  45. }
  46. static bool parseUnsigned(unsigned &value, const char *arg) {
  47. char c;
  48. return sscanf(arg, "%u%c", &value, &c) == 1;
  49. }
  50. static bool parseUnsignedDecOrHex(unsigned &value, const char *arg) {
  51. if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
  52. char c;
  53. return sscanf(arg+2, "%x%c", &value, &c) == 1;
  54. }
  55. return parseUnsigned(value, arg);
  56. }
  57. static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
  58. char c;
  59. return sscanf(arg, "%llu%c", &value, &c) == 1;
  60. }
  61. static bool parseDouble(double &value, const char *arg) {
  62. char c;
  63. return sscanf(arg, "%lf%c", &value, &c) == 1;
  64. }
  65. static bool parseAngle(double &value, const char *arg) {
  66. char c1, c2;
  67. int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
  68. if (result == 1)
  69. return true;
  70. if (result == 2 && (c1 == 'd' || c1 == 'D')) {
  71. value *= M_PI/180;
  72. return true;
  73. }
  74. return false;
  75. }
  76. static void parseColoring(Shape &shape, const char *edgeAssignment) {
  77. unsigned c = 0, e = 0;
  78. if (shape.contours.size() < c) return;
  79. Contour *contour = &shape.contours[c];
  80. bool change = false;
  81. bool clear = true;
  82. for (const char *in = edgeAssignment; *in; ++in) {
  83. switch (*in) {
  84. case ',':
  85. if (change)
  86. ++e;
  87. if (clear)
  88. while (e < contour->edges.size()) {
  89. contour->edges[e]->color = WHITE;
  90. ++e;
  91. }
  92. ++c, e = 0;
  93. if (shape.contours.size() <= c) return;
  94. contour = &shape.contours[c];
  95. change = false;
  96. clear = true;
  97. break;
  98. case '?':
  99. clear = false;
  100. break;
  101. case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
  102. if (change) {
  103. ++e;
  104. change = false;
  105. }
  106. if (e < contour->edges.size()) {
  107. contour->edges[e]->color = EdgeColor(
  108. (*in == 'C' || *in == 'c')*CYAN|
  109. (*in == 'M' || *in == 'm')*MAGENTA|
  110. (*in == 'Y' || *in == 'y')*YELLOW|
  111. (*in == 'W' || *in == 'w')*WHITE);
  112. change = true;
  113. }
  114. break;
  115. }
  116. }
  117. }
  118. #ifdef MSDFGEN_EXTENSIONS
  119. static bool parseUnicode(unicode_t &unicode, const char *arg) {
  120. unsigned uuc;
  121. if (parseUnsignedDecOrHex(uuc, arg)) {
  122. unicode = uuc;
  123. return true;
  124. }
  125. if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
  126. unicode = (unicode_t) (unsigned char) arg[1];
  127. return true;
  128. }
  129. return false;
  130. }
  131. static FontHandle * loadVarFont(FreetypeHandle *library, const char *filename) {
  132. std::string buffer;
  133. while (*filename && *filename != '?')
  134. buffer.push_back(*filename++);
  135. FontHandle *font = loadFont(library, buffer.c_str());
  136. if (font && *filename++ == '?') {
  137. do {
  138. buffer.clear();
  139. while (*filename && *filename != '=')
  140. buffer.push_back(*filename++);
  141. if (*filename == '=') {
  142. double value = 0;
  143. int skip = 0;
  144. if (sscanf(++filename, "%lf%n", &value, &skip) == 1) {
  145. setFontVariationAxis(library, font, buffer.c_str(), value);
  146. filename += skip;
  147. }
  148. }
  149. } while (*filename++ == '&');
  150. }
  151. return font;
  152. }
  153. #endif
  154. template <int N>
  155. static void invertColor(const BitmapRef<float, N> &bitmap) {
  156. const float *end = bitmap.pixels+N*bitmap.width*bitmap.height;
  157. for (float *p = bitmap.pixels; p < end; ++p)
  158. *p = 1.f-*p;
  159. }
  160. static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
  161. for (int row = 0; row < rows; ++row) {
  162. for (int col = 0; col < cols; ++col) {
  163. int v = clamp(int((*values++)*0x100), 0xff);
  164. fprintf(file, col ? " %02X" : "%02X", v);
  165. }
  166. fprintf(file, "\n");
  167. }
  168. return true;
  169. }
  170. static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
  171. for (int row = 0; row < rows; ++row) {
  172. for (int col = 0; col < cols; ++col) {
  173. fprintf(file, col ? " %.9g" : "%.9g", *values++);
  174. }
  175. fprintf(file, "\n");
  176. }
  177. return true;
  178. }
  179. static bool writeBinBitmap(FILE *file, const float *values, int count) {
  180. for (int pos = 0; pos < count; ++pos) {
  181. unsigned char v = clamp(int((*values++)*0x100), 0xff);
  182. fwrite(&v, 1, 1, file);
  183. }
  184. return true;
  185. }
  186. #ifdef __BIG_ENDIAN__
  187. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  188. #else
  189. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  190. #endif
  191. {
  192. return (int) fwrite(values, sizeof(float), count, file) == count;
  193. }
  194. #ifdef __BIG_ENDIAN__
  195. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  196. #else
  197. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  198. #endif
  199. {
  200. for (int pos = 0; pos < count; ++pos) {
  201. const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
  202. for (int i = sizeof(float)-1; i >= 0; --i)
  203. fwrite(b+i, 1, 1, file);
  204. }
  205. return true;
  206. }
  207. static bool cmpExtension(const char *path, const char *ext) {
  208. for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
  209. if (a < path || toupper(*a) != toupper(*b))
  210. return false;
  211. return true;
  212. }
  213. template <int N>
  214. static const char * writeOutput(const BitmapConstRef<float, N> &bitmap, const char *filename, Format &format) {
  215. if (filename) {
  216. if (format == AUTO) {
  217. #ifdef MSDFGEN_EXTENSIONS
  218. if (cmpExtension(filename, ".png")) format = PNG;
  219. #else
  220. if (cmpExtension(filename, ".png"))
  221. return "PNG format is not available in core-only version.";
  222. #endif
  223. else if (cmpExtension(filename, ".bmp")) format = BMP;
  224. else if (cmpExtension(filename, ".tif") || cmpExtension(filename, ".tiff")) format = TIFF;
  225. else if (cmpExtension(filename, ".txt")) format = TEXT;
  226. else if (cmpExtension(filename, ".bin")) format = BINARY;
  227. else
  228. return "Could not deduce format from output file name.";
  229. }
  230. switch (format) {
  231. #ifdef MSDFGEN_EXTENSIONS
  232. case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
  233. #endif
  234. case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
  235. case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";
  236. case TEXT: case TEXT_FLOAT: {
  237. FILE *file = fopen(filename, "w");
  238. if (!file) return "Failed to write output text file.";
  239. if (format == TEXT)
  240. writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  241. else if (format == TEXT_FLOAT)
  242. writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  243. fclose(file);
  244. return NULL;
  245. }
  246. case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {
  247. FILE *file = fopen(filename, "wb");
  248. if (!file) return "Failed to write output binary file.";
  249. if (format == BINARY)
  250. writeBinBitmap(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  251. else if (format == BINARY_FLOAT)
  252. writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  253. else if (format == BINARY_FLOAT_BE)
  254. writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  255. fclose(file);
  256. return NULL;
  257. }
  258. default:;
  259. }
  260. } else {
  261. if (format == AUTO || format == TEXT)
  262. writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  263. else if (format == TEXT_FLOAT)
  264. writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  265. else
  266. return "Unsupported format for standard output.";
  267. }
  268. return NULL;
  269. }
  270. #define STRINGIZE_(x) #x
  271. #define STRINGIZE(x) STRINGIZE_(x)
  272. #define MSDFGEN_VERSION_STRING STRINGIZE(MSDFGEN_VERSION)
  273. #ifdef MSDFGEN_VERSION_UNDERLINE
  274. #define VERSION_UNDERLINE STRINGIZE(MSDFGEN_VERSION_UNDERLINE)
  275. #else
  276. #define VERSION_UNDERLINE "--------"
  277. #endif
  278. #if !defined(MSDFGEN_EXTENSIONS) && defined(MSDFGEN_USE_OPENMP)
  279. #define TITLE_SUFFIX " - core with OpenMP"
  280. #define SUFFIX_UNDERLINE "-------------------"
  281. #elif !defined(MSDFGEN_EXTENSIONS)
  282. #define TITLE_SUFFIX " - core only"
  283. #define SUFFIX_UNDERLINE "------------"
  284. #elif defined(MSDFGEN_USE_SKIA) && defined(MSDFGEN_USE_OPENMP)
  285. #define TITLE_SUFFIX " with Skia & OpenMP"
  286. #define SUFFIX_UNDERLINE "-------------------"
  287. #elif defined(MSDFGEN_USE_SKIA)
  288. #define TITLE_SUFFIX " with Skia"
  289. #define SUFFIX_UNDERLINE "----------"
  290. #elif defined(MSDFGEN_USE_OPENMP)
  291. #define TITLE_SUFFIX " with OpenMP"
  292. #define SUFFIX_UNDERLINE "------------"
  293. #else
  294. #define TITLE_SUFFIX
  295. #define SUFFIX_UNDERLINE
  296. #endif
  297. static const char * const versionText =
  298. "MSDFgen v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
  299. "(c) 2016 - " STRINGIZE(MSDFGEN_COPYRIGHT_YEAR) " Viktor Chlumsky";
  300. static const char * const helpText =
  301. "\n"
  302. "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION_STRING TITLE_SUFFIX "\n"
  303. "------------------------------------------------------------------" VERSION_UNDERLINE SUFFIX_UNDERLINE "\n"
  304. " Usage: msdfgen"
  305. #ifdef _WIN32
  306. ".exe"
  307. #endif
  308. " <mode> <input specification> <options>\n"
  309. "\n"
  310. "MODES\n"
  311. " sdf - Generate conventional monochrome (true) signed distance field.\n"
  312. " psdf - Generate monochrome signed pseudo-distance field.\n"
  313. " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
  314. " mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"
  315. " metrics - Report shape metrics only.\n"
  316. "\n"
  317. "INPUT SPECIFICATION\n"
  318. " -defineshape <definition>\n"
  319. "\tDefines input shape using the ad-hoc text definition.\n"
  320. #ifdef MSDFGEN_EXTENSIONS
  321. " -font <filename.ttf> <character code>\n"
  322. "\tLoads a single glyph from the specified font file.\n"
  323. "\tFormat of character code is '?', 63, 0x3F (Unicode value), or g34 (glyph index).\n"
  324. #endif
  325. " -shapedesc <filename.txt>\n"
  326. "\tLoads text shape description from a file.\n"
  327. " -stdin\n"
  328. "\tReads text shape description from the standard input.\n"
  329. #ifdef MSDFGEN_EXTENSIONS
  330. " -svg <filename.svg>\n"
  331. "\tLoads the last vector path found in the specified SVG file.\n"
  332. " -varfont <filename and variables> <character code>\n"
  333. "\tLoads a single glyph from a variable font. Specify variable values as x.ttf?var1=0.5&var2=1\n"
  334. #endif
  335. "\n"
  336. // Keep alphabetical order!
  337. "OPTIONS\n"
  338. " -angle <angle>\n"
  339. "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
  340. " -ascale <x scale> <y scale>\n"
  341. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  342. " -autoframe\n"
  343. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  344. " -coloringstrategy <simple / inktrap / distance>\n"
  345. "\tSelects the strategy of the edge coloring heuristic.\n"
  346. " -distanceshift <shift>\n"
  347. "\tShifts all normalized distances in the output distance field by this value.\n"
  348. " -edgecolors <sequence>\n"
  349. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  350. " -errorcorrection <mode>\n"
  351. "\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"
  352. " -errordeviationratio <ratio>\n"
  353. "\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"
  354. " -errorimproveratio <ratio>\n"
  355. "\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"
  356. " -estimateerror\n"
  357. "\tComputes and prints the distance field's estimated fill error to the standard output.\n"
  358. " -exportshape <filename.txt>\n"
  359. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  360. " -fillrule <nonzero / evenodd / positive / negative>\n"
  361. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  362. #ifdef MSDFGEN_EXTENSIONS
  363. " -format <png / bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  364. #else
  365. " -format <bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  366. #endif
  367. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  368. " -guessorder\n"
  369. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  370. " -help\n"
  371. "\tDisplays this help.\n"
  372. " -legacy\n"
  373. "\tUses the original (legacy) distance field algorithms.\n"
  374. #ifdef MSDFGEN_USE_SKIA
  375. " -nopreprocess\n"
  376. "\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"
  377. #else
  378. " -nooverlap\n"
  379. "\tDisables resolution of overlapping contours.\n"
  380. " -noscanline\n"
  381. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  382. #endif
  383. " -o <filename>\n"
  384. "\tSets the output file name. The default value is \"output." DEFAULT_IMAGE_EXTENSION "\".\n"
  385. #ifdef MSDFGEN_USE_SKIA
  386. " -overlap\n"
  387. "\tSwitches to distance field generator with support for overlapping contours.\n"
  388. #endif
  389. " -printmetrics\n"
  390. "\tPrints relevant metrics of the shape to the standard output.\n"
  391. " -pxrange <range>\n"
  392. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  393. " -range <range>\n"
  394. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  395. " -reverseorder\n"
  396. "\tGenerates the distance field as if the shape's vertices were in reverse order.\n"
  397. " -scale <scale>\n"
  398. "\tSets the scale used to convert shape units to pixels.\n"
  399. #ifdef MSDFGEN_USE_SKIA
  400. " -scanline\n"
  401. "\tPerforms an additional scanline pass to fix the signs of the distances.\n"
  402. #endif
  403. " -seed <n>\n"
  404. "\tSets the random seed for edge coloring heuristic.\n"
  405. " -size <width> <height>\n"
  406. "\tSets the dimensions of the output image.\n"
  407. " -stdout\n"
  408. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  409. " -testrender <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  410. #ifdef MSDFGEN_EXTENSIONS
  411. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  412. #else
  413. "\tRenders an image preview using the generated distance field and saves it as a TIFF file.\n"
  414. #endif
  415. " -testrendermulti <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  416. "\tRenders an image preview without flattening the color channels.\n"
  417. " -translate <x> <y>\n"
  418. "\tSets the translation of the shape in shape units.\n"
  419. " -version\n"
  420. "\tPrints the version of the program.\n"
  421. " -windingpreprocess\n"
  422. "\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"
  423. " -yflip\n"
  424. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  425. "\n";
  426. static const char *errorCorrectionHelpText =
  427. "\n"
  428. "ERROR CORRECTION MODES\n"
  429. " auto-fast\n"
  430. "\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"
  431. " auto-full\n"
  432. "\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"
  433. " auto-mixed (default)\n"
  434. "\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"
  435. " disabled\n"
  436. "\tDisables error correction.\n"
  437. " distance-fast\n"
  438. "\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"
  439. " distance-full\n"
  440. "\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"
  441. " edge-fast\n"
  442. "\tDetects inversion artifacts only by range testing.\n"
  443. " edge-full\n"
  444. "\tDetects inversion artifacts only by exact distance evaluation.\n"
  445. " help\n"
  446. "\tDisplays this help.\n"
  447. "\n";
  448. int main(int argc, const char * const *argv) {
  449. #define ABORT(msg) do { fputs(msg "\n", stderr); return 1; } while (false)
  450. // Parse command line arguments
  451. enum {
  452. NONE,
  453. SVG,
  454. FONT,
  455. VAR_FONT,
  456. DESCRIPTION_ARG,
  457. DESCRIPTION_STDIN,
  458. DESCRIPTION_FILE
  459. } inputType = NONE;
  460. enum {
  461. SINGLE,
  462. PSEUDO,
  463. MULTI,
  464. MULTI_AND_TRUE,
  465. METRICS
  466. } mode = MULTI;
  467. enum {
  468. NO_PREPROCESS,
  469. WINDING_PREPROCESS,
  470. FULL_PREPROCESS
  471. } geometryPreproc = (
  472. #ifdef MSDFGEN_USE_SKIA
  473. FULL_PREPROCESS
  474. #else
  475. NO_PREPROCESS
  476. #endif
  477. );
  478. bool legacyMode = false;
  479. MSDFGeneratorConfig generatorConfig;
  480. generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;
  481. bool scanlinePass = geometryPreproc == NO_PREPROCESS;
  482. FillRule fillRule = FILL_NONZERO;
  483. Format format = AUTO;
  484. const char *input = NULL;
  485. const char *output = "output." DEFAULT_IMAGE_EXTENSION;
  486. const char *shapeExport = NULL;
  487. const char *testRender = NULL;
  488. const char *testRenderMulti = NULL;
  489. bool outputSpecified = false;
  490. #ifdef MSDFGEN_EXTENSIONS
  491. bool glyphIndexSpecified = false;
  492. GlyphIndex glyphIndex;
  493. unicode_t unicode = 0;
  494. int svgPathIndex = 0;
  495. #endif
  496. int width = 64, height = 64;
  497. int testWidth = 0, testHeight = 0;
  498. int testWidthM = 0, testHeightM = 0;
  499. bool autoFrame = false;
  500. enum {
  501. RANGE_UNIT,
  502. RANGE_PX
  503. } rangeMode = RANGE_PX;
  504. double range = 1;
  505. double pxRange = 2;
  506. Vector2 translate;
  507. Vector2 scale = 1;
  508. bool scaleSpecified = false;
  509. double angleThreshold = DEFAULT_ANGLE_THRESHOLD;
  510. float outputDistanceShift = 0.f;
  511. const char *edgeAssignment = NULL;
  512. bool yFlip = false;
  513. bool printMetrics = false;
  514. bool estimateError = false;
  515. bool skipColoring = false;
  516. enum {
  517. KEEP,
  518. REVERSE,
  519. GUESS
  520. } orientation = KEEP;
  521. unsigned long long coloringSeed = 0;
  522. void (*edgeColoring)(Shape &, double, unsigned long long) = edgeColoringSimple;
  523. bool explicitErrorCorrectionMode = false;
  524. int argPos = 1;
  525. bool suggestHelp = false;
  526. while (argPos < argc) {
  527. const char *arg = argv[argPos];
  528. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  529. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  530. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  531. // Accept arguments prefixed with -- instead of -
  532. if (arg[0] == '-' && arg[1] == '-')
  533. ++arg;
  534. ARG_MODE("sdf", SINGLE)
  535. ARG_MODE("psdf", PSEUDO)
  536. ARG_MODE("msdf", MULTI)
  537. ARG_MODE("mtsdf", MULTI_AND_TRUE)
  538. ARG_MODE("metrics", METRICS)
  539. #ifdef MSDFGEN_EXTENSIONS
  540. ARG_CASE("-svg", 1) {
  541. inputType = SVG;
  542. input = argv[argPos+1];
  543. argPos += 2;
  544. continue;
  545. }
  546. //ARG_CASE -font, -varfont
  547. if (argPos+2 < argc && ((!strcmp(arg, "-font") && (inputType = FONT)) || (!strcmp(arg, "-varfont") && (inputType = VAR_FONT)))) {
  548. input = argv[argPos+1];
  549. const char *charArg = argv[argPos+2];
  550. unsigned gi;
  551. switch (charArg[0]) {
  552. case 'G': case 'g':
  553. if (parseUnsignedDecOrHex(gi, charArg+1)) {
  554. glyphIndex = GlyphIndex(gi);
  555. glyphIndexSpecified = true;
  556. }
  557. break;
  558. case 'U': case 'u':
  559. ++charArg;
  560. default:
  561. parseUnicode(unicode, charArg);
  562. }
  563. argPos += 3;
  564. continue;
  565. }
  566. #else
  567. ARG_CASE("-svg", 1) {
  568. ABORT("SVG input is not available in core-only version.");
  569. }
  570. ARG_CASE("-font", 2) {
  571. ABORT("Font input is not available in core-only version.");
  572. }
  573. ARG_CASE("-varfont", 2) {
  574. ABORT("Variable font input is not available in core-only version.");
  575. }
  576. #endif
  577. ARG_CASE("-defineshape", 1) {
  578. inputType = DESCRIPTION_ARG;
  579. input = argv[argPos+1];
  580. argPos += 2;
  581. continue;
  582. }
  583. ARG_CASE("-stdin", 0) {
  584. inputType = DESCRIPTION_STDIN;
  585. input = "stdin";
  586. argPos += 1;
  587. continue;
  588. }
  589. ARG_CASE("-shapedesc", 1) {
  590. inputType = DESCRIPTION_FILE;
  591. input = argv[argPos+1];
  592. argPos += 2;
  593. continue;
  594. }
  595. ARG_CASE("-o", 1) {
  596. output = argv[argPos+1];
  597. outputSpecified = true;
  598. argPos += 2;
  599. continue;
  600. }
  601. ARG_CASE("-stdout", 0) {
  602. output = NULL;
  603. argPos += 1;
  604. continue;
  605. }
  606. ARG_CASE("-legacy", 0) {
  607. legacyMode = true;
  608. argPos += 1;
  609. continue;
  610. }
  611. ARG_CASE("-nopreprocess", 0) {
  612. geometryPreproc = NO_PREPROCESS;
  613. argPos += 1;
  614. continue;
  615. }
  616. ARG_CASE("-windingpreprocess", 0) {
  617. geometryPreproc = WINDING_PREPROCESS;
  618. argPos += 1;
  619. continue;
  620. }
  621. ARG_CASE("-preprocess", 0) {
  622. geometryPreproc = FULL_PREPROCESS;
  623. argPos += 1;
  624. continue;
  625. }
  626. ARG_CASE("-nooverlap", 0) {
  627. generatorConfig.overlapSupport = false;
  628. argPos += 1;
  629. continue;
  630. }
  631. ARG_CASE("-overlap", 0) {
  632. generatorConfig.overlapSupport = true;
  633. argPos += 1;
  634. continue;
  635. }
  636. ARG_CASE("-noscanline", 0) {
  637. scanlinePass = false;
  638. argPos += 1;
  639. continue;
  640. }
  641. ARG_CASE("-scanline", 0) {
  642. scanlinePass = true;
  643. argPos += 1;
  644. continue;
  645. }
  646. ARG_CASE("-fillrule", 1) {
  647. scanlinePass = true;
  648. if (!strcmp(argv[argPos+1], "nonzero")) fillRule = FILL_NONZERO;
  649. else if (!strcmp(argv[argPos+1], "evenodd") || !strcmp(argv[argPos+1], "odd")) fillRule = FILL_ODD;
  650. else if (!strcmp(argv[argPos+1], "positive")) fillRule = FILL_POSITIVE;
  651. else if (!strcmp(argv[argPos+1], "negative")) fillRule = FILL_NEGATIVE;
  652. else
  653. fputs("Unknown fill rule specified.\n", stderr);
  654. argPos += 2;
  655. continue;
  656. }
  657. ARG_CASE("-format", 1) {
  658. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  659. #ifdef MSDFGEN_EXTENSIONS
  660. else if (!strcmp(argv[argPos+1], "png")) SET_FORMAT(PNG, "png");
  661. #else
  662. else if (!strcmp(argv[argPos+1], "png"))
  663. fputs("PNG format is not available in core-only version.\n", stderr);
  664. #endif
  665. else if (!strcmp(argv[argPos+1], "bmp")) SET_FORMAT(BMP, "bmp");
  666. else if (!strcmp(argv[argPos+1], "tiff") || !strcmp(argv[argPos+1], "tif")) SET_FORMAT(TIFF, "tif");
  667. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SET_FORMAT(TEXT, "txt");
  668. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  669. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SET_FORMAT(BINARY, "bin");
  670. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  671. else if (!strcmp(argv[argPos+1], "binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
  672. else
  673. fputs("Unknown format specified.\n", stderr);
  674. argPos += 2;
  675. continue;
  676. }
  677. ARG_CASE("-size", 2) {
  678. unsigned w, h;
  679. if (!(parseUnsigned(w, argv[argPos+1]) && parseUnsigned(h, argv[argPos+2]) && w && h))
  680. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  681. width = w, height = h;
  682. argPos += 3;
  683. continue;
  684. }
  685. ARG_CASE("-autoframe", 0) {
  686. autoFrame = true;
  687. argPos += 1;
  688. continue;
  689. }
  690. ARG_CASE("-range", 1) {
  691. double r;
  692. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  693. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  694. rangeMode = RANGE_UNIT;
  695. range = r;
  696. argPos += 2;
  697. continue;
  698. }
  699. ARG_CASE("-pxrange", 1) {
  700. double r;
  701. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  702. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  703. rangeMode = RANGE_PX;
  704. pxRange = r;
  705. argPos += 2;
  706. continue;
  707. }
  708. ARG_CASE("-scale", 1) {
  709. double s;
  710. if (!(parseDouble(s, argv[argPos+1]) && s > 0))
  711. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  712. scale = s;
  713. scaleSpecified = true;
  714. argPos += 2;
  715. continue;
  716. }
  717. ARG_CASE("-ascale", 2) {
  718. double sx, sy;
  719. if (!(parseDouble(sx, argv[argPos+1]) && parseDouble(sy, argv[argPos+2]) && sx > 0 && sy > 0))
  720. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  721. scale.set(sx, sy);
  722. scaleSpecified = true;
  723. argPos += 3;
  724. continue;
  725. }
  726. ARG_CASE("-translate", 2) {
  727. double tx, ty;
  728. if (!(parseDouble(tx, argv[argPos+1]) && parseDouble(ty, argv[argPos+2])))
  729. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  730. translate.set(tx, ty);
  731. argPos += 3;
  732. continue;
  733. }
  734. ARG_CASE("-angle", 1) {
  735. double at;
  736. if (!parseAngle(at, argv[argPos+1]))
  737. 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.");
  738. angleThreshold = at;
  739. argPos += 2;
  740. continue;
  741. }
  742. ARG_CASE("-errorcorrection", 1) {
  743. if (!strcmp(argv[argPos+1], "disabled") || !strcmp(argv[argPos+1], "0") || !strcmp(argv[argPos+1], "none")) {
  744. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  745. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  746. } else if (!strcmp(argv[argPos+1], "default") || !strcmp(argv[argPos+1], "auto") || !strcmp(argv[argPos+1], "auto-mixed") || !strcmp(argv[argPos+1], "mixed")) {
  747. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  748. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
  749. } else if (!strcmp(argv[argPos+1], "auto-fast") || !strcmp(argv[argPos+1], "fast")) {
  750. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  751. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  752. } else if (!strcmp(argv[argPos+1], "auto-full") || !strcmp(argv[argPos+1], "full")) {
  753. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  754. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  755. } else if (!strcmp(argv[argPos+1], "distance") || !strcmp(argv[argPos+1], "distance-fast") || !strcmp(argv[argPos+1], "indiscriminate") || !strcmp(argv[argPos+1], "indiscriminate-fast")) {
  756. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  757. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  758. } else if (!strcmp(argv[argPos+1], "distance-full") || !strcmp(argv[argPos+1], "indiscriminate-full")) {
  759. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  760. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  761. } else if (!strcmp(argv[argPos+1], "edge-fast")) {
  762. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  763. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  764. } else if (!strcmp(argv[argPos+1], "edge") || !strcmp(argv[argPos+1], "edge-full")) {
  765. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  766. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  767. } else if (!strcmp(argv[argPos+1], "help")) {
  768. puts(errorCorrectionHelpText);
  769. return 0;
  770. } else
  771. fputs("Unknown error correction mode. Use -errorcorrection help for more information.\n", stderr);
  772. explicitErrorCorrectionMode = true;
  773. argPos += 2;
  774. continue;
  775. }
  776. ARG_CASE("-errordeviationratio", 1) {
  777. double edr;
  778. if (!(parseDouble(edr, argv[argPos+1]) && edr > 0))
  779. ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");
  780. generatorConfig.errorCorrection.minDeviationRatio = edr;
  781. argPos += 2;
  782. continue;
  783. }
  784. ARG_CASE("-errorimproveratio", 1) {
  785. double eir;
  786. if (!(parseDouble(eir, argv[argPos+1]) && eir > 0))
  787. ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");
  788. generatorConfig.errorCorrection.minImproveRatio = eir;
  789. argPos += 2;
  790. continue;
  791. }
  792. ARG_CASE("-coloringstrategy", 1) {
  793. if (!strcmp(argv[argPos+1], "simple")) edgeColoring = edgeColoringSimple;
  794. else if (!strcmp(argv[argPos+1], "inktrap")) edgeColoring = edgeColoringInkTrap;
  795. else if (!strcmp(argv[argPos+1], "distance")) edgeColoring = edgeColoringByDistance;
  796. else
  797. fputs("Unknown coloring strategy specified.\n", stderr);
  798. argPos += 2;
  799. continue;
  800. }
  801. ARG_CASE("-edgecolors", 1) {
  802. static const char *allowed = " ?,cmwyCMWY";
  803. for (int i = 0; argv[argPos+1][i]; ++i) {
  804. for (int j = 0; allowed[j]; ++j)
  805. if (argv[argPos+1][i] == allowed[j])
  806. goto EDGE_COLOR_VERIFIED;
  807. 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.");
  808. EDGE_COLOR_VERIFIED:;
  809. }
  810. edgeAssignment = argv[argPos+1];
  811. argPos += 2;
  812. continue;
  813. }
  814. ARG_CASE("-distanceshift", 1) {
  815. double ds;
  816. if (!parseDouble(ds, argv[argPos+1]))
  817. ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");
  818. outputDistanceShift = (float) ds;
  819. argPos += 2;
  820. continue;
  821. }
  822. ARG_CASE("-exportshape", 1) {
  823. shapeExport = argv[argPos+1];
  824. argPos += 2;
  825. continue;
  826. }
  827. ARG_CASE("-testrender", 3) {
  828. unsigned w, h;
  829. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  830. ABORT("Invalid arguments for test render. Use -testrender <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  831. testRender = argv[argPos+1];
  832. testWidth = w, testHeight = h;
  833. argPos += 4;
  834. continue;
  835. }
  836. ARG_CASE("-testrendermulti", 3) {
  837. unsigned w, h;
  838. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  839. ABORT("Invalid arguments for test render. Use -testrendermulti <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  840. testRenderMulti = argv[argPos+1];
  841. testWidthM = w, testHeightM = h;
  842. argPos += 4;
  843. continue;
  844. }
  845. ARG_CASE("-yflip", 0) {
  846. yFlip = true;
  847. argPos += 1;
  848. continue;
  849. }
  850. ARG_CASE("-printmetrics", 0) {
  851. printMetrics = true;
  852. argPos += 1;
  853. continue;
  854. }
  855. ARG_CASE("-estimateerror", 0) {
  856. estimateError = true;
  857. argPos += 1;
  858. continue;
  859. }
  860. ARG_CASE("-keeporder", 0) {
  861. orientation = KEEP;
  862. argPos += 1;
  863. continue;
  864. }
  865. ARG_CASE("-reverseorder", 0) {
  866. orientation = REVERSE;
  867. argPos += 1;
  868. continue;
  869. }
  870. ARG_CASE("-guessorder", 0) {
  871. orientation = GUESS;
  872. argPos += 1;
  873. continue;
  874. }
  875. ARG_CASE("-seed", 1) {
  876. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  877. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  878. argPos += 2;
  879. continue;
  880. }
  881. ARG_CASE("-version", 0) {
  882. puts(versionText);
  883. return 0;
  884. }
  885. ARG_CASE("-help", 0) {
  886. puts(helpText);
  887. return 0;
  888. }
  889. fprintf(stderr, "Unknown setting or insufficient parameters: %s\n", argv[argPos]);
  890. suggestHelp = true;
  891. ++argPos;
  892. }
  893. if (suggestHelp)
  894. fprintf(stderr, "Use -help for more information.\n");
  895. // Load input
  896. Vector2 svgDims;
  897. double glyphAdvance = 0;
  898. if (!inputType || !input) {
  899. #ifdef MSDFGEN_EXTENSIONS
  900. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  901. #else
  902. ABORT("No input specified! See -help.");
  903. #endif
  904. }
  905. if (mode == MULTI_AND_TRUE && (format == BMP || (format == AUTO && output && cmpExtension(output, ".bmp"))))
  906. ABORT("Incompatible image format. A BMP file cannot contain alpha channel, which is required in mtsdf mode.");
  907. Shape shape;
  908. switch (inputType) {
  909. #ifdef MSDFGEN_EXTENSIONS
  910. case SVG: {
  911. if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
  912. ABORT("Failed to load shape from SVG file.");
  913. break;
  914. }
  915. case FONT: case VAR_FONT: {
  916. if (!glyphIndexSpecified && !unicode)
  917. ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a Unicode index (65, 0x41), a character in apostrophes ('A'), or a glyph index prefixed by g (g36, g0x24).");
  918. FreetypeHandle *ft = initializeFreetype();
  919. if (!ft)
  920. return -1;
  921. FontHandle *font = inputType == VAR_FONT ? loadVarFont(ft, input) : loadFont(ft, input);
  922. if (!font) {
  923. deinitializeFreetype(ft);
  924. ABORT("Failed to load font file.");
  925. }
  926. if (unicode)
  927. getGlyphIndex(glyphIndex, font, unicode);
  928. if (!loadGlyph(shape, font, glyphIndex, &glyphAdvance)) {
  929. destroyFont(font);
  930. deinitializeFreetype(ft);
  931. ABORT("Failed to load glyph from font file.");
  932. }
  933. destroyFont(font);
  934. deinitializeFreetype(ft);
  935. break;
  936. }
  937. #endif
  938. case DESCRIPTION_ARG: {
  939. if (!readShapeDescription(input, shape, &skipColoring))
  940. ABORT("Parse error in shape description.");
  941. break;
  942. }
  943. case DESCRIPTION_STDIN: {
  944. if (!readShapeDescription(stdin, shape, &skipColoring))
  945. ABORT("Parse error in shape description.");
  946. break;
  947. }
  948. case DESCRIPTION_FILE: {
  949. FILE *file = fopen(input, "r");
  950. if (!file)
  951. ABORT("Failed to load shape description file.");
  952. if (!readShapeDescription(file, shape, &skipColoring))
  953. ABORT("Parse error in shape description.");
  954. fclose(file);
  955. break;
  956. }
  957. default:;
  958. }
  959. // Validate and normalize shape
  960. if (!shape.validate())
  961. ABORT("The geometry of the loaded shape is invalid.");
  962. switch (geometryPreproc) {
  963. case NO_PREPROCESS:
  964. break;
  965. case WINDING_PREPROCESS:
  966. shape.orientContours();
  967. break;
  968. case FULL_PREPROCESS:
  969. #ifdef MSDFGEN_USE_SKIA
  970. if (!resolveShapeGeometry(shape))
  971. fputs("Shape geometry preprocessing failed, skipping.\n", stderr);
  972. else if (skipColoring) {
  973. skipColoring = false;
  974. fputs("Note: Input shape coloring won't be preserved due to geometry preprocessing.\n", stderr);
  975. }
  976. #else
  977. ABORT("Shape geometry preprocessing (-preprocess) is not available in this version because the Skia library is not present.");
  978. #endif
  979. break;
  980. }
  981. shape.normalize();
  982. if (yFlip)
  983. shape.inverseYAxis = !shape.inverseYAxis;
  984. double avgScale = .5*(scale.x+scale.y);
  985. Shape::Bounds bounds = { };
  986. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  987. bounds = shape.getBounds();
  988. // Auto-frame
  989. if (autoFrame) {
  990. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  991. Vector2 frame(width, height);
  992. double m = .5+(double) outputDistanceShift;
  993. if (!scaleSpecified) {
  994. if (rangeMode == RANGE_UNIT)
  995. l -= m*range, b -= m*range, r += m*range, t += m*range;
  996. else
  997. frame -= 2*m*pxRange;
  998. }
  999. if (l >= r || b >= t)
  1000. l = 0, b = 0, r = 1, t = 1;
  1001. if (frame.x <= 0 || frame.y <= 0)
  1002. ABORT("Cannot fit the specified pixel range.");
  1003. Vector2 dims(r-l, t-b);
  1004. if (scaleSpecified)
  1005. translate = .5*(frame/scale-dims)-Vector2(l, b);
  1006. else {
  1007. if (dims.x*frame.y < dims.y*frame.x) {
  1008. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  1009. scale = avgScale = frame.y/dims.y;
  1010. } else {
  1011. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  1012. scale = avgScale = frame.x/dims.x;
  1013. }
  1014. }
  1015. if (rangeMode == RANGE_PX && !scaleSpecified)
  1016. translate += m*pxRange/scale;
  1017. }
  1018. if (rangeMode == RANGE_PX)
  1019. range = pxRange/min(scale.x, scale.y);
  1020. // Print metrics
  1021. if (mode == METRICS || printMetrics) {
  1022. FILE *out = stdout;
  1023. if (mode == METRICS && outputSpecified)
  1024. out = fopen(output, "w");
  1025. if (!out)
  1026. ABORT("Failed to write output file.");
  1027. if (shape.inverseYAxis)
  1028. fprintf(out, "inverseY = true\n");
  1029. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  1030. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  1031. if (svgDims.x != 0 && svgDims.y != 0)
  1032. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  1033. if (glyphAdvance != 0)
  1034. fprintf(out, "advance = %.12g\n", glyphAdvance);
  1035. if (autoFrame) {
  1036. if (!scaleSpecified)
  1037. fprintf(out, "scale = %.12g\n", avgScale);
  1038. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  1039. }
  1040. if (rangeMode == RANGE_PX)
  1041. fprintf(out, "range = %.12g\n", range);
  1042. if (mode == METRICS && outputSpecified)
  1043. fclose(out);
  1044. }
  1045. // Compute output
  1046. Projection projection(scale, translate);
  1047. Bitmap<float, 1> sdf;
  1048. Bitmap<float, 3> msdf;
  1049. Bitmap<float, 4> mtsdf;
  1050. MSDFGeneratorConfig postErrorCorrectionConfig(generatorConfig);
  1051. if (scanlinePass) {
  1052. if (explicitErrorCorrectionMode && generatorConfig.errorCorrection.distanceCheckMode != ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {
  1053. const char *fallbackModeName = "unknown";
  1054. switch (generatorConfig.errorCorrection.mode) {
  1055. case ErrorCorrectionConfig::DISABLED: fallbackModeName = "disabled"; break;
  1056. case ErrorCorrectionConfig::INDISCRIMINATE: fallbackModeName = "distance-fast"; break;
  1057. case ErrorCorrectionConfig::EDGE_PRIORITY: fallbackModeName = "auto-fast"; break;
  1058. case ErrorCorrectionConfig::EDGE_ONLY: fallbackModeName = "edge-fast"; break;
  1059. }
  1060. fprintf(stderr, "Selected error correction mode not compatible with scanline pass, falling back to %s.\n", fallbackModeName);
  1061. }
  1062. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  1063. postErrorCorrectionConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  1064. }
  1065. switch (mode) {
  1066. case SINGLE: {
  1067. sdf = Bitmap<float, 1>(width, height);
  1068. if (legacyMode)
  1069. generateSDF_legacy(sdf, shape, range, scale, translate);
  1070. else
  1071. generateSDF(sdf, shape, projection, range, generatorConfig);
  1072. break;
  1073. }
  1074. case PSEUDO: {
  1075. sdf = Bitmap<float, 1>(width, height);
  1076. if (legacyMode)
  1077. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  1078. else
  1079. generatePseudoSDF(sdf, shape, projection, range, generatorConfig);
  1080. break;
  1081. }
  1082. case MULTI: {
  1083. if (!skipColoring)
  1084. edgeColoring(shape, angleThreshold, coloringSeed);
  1085. if (edgeAssignment)
  1086. parseColoring(shape, edgeAssignment);
  1087. msdf = Bitmap<float, 3>(width, height);
  1088. if (legacyMode)
  1089. generateMSDF_legacy(msdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1090. else
  1091. generateMSDF(msdf, shape, projection, range, generatorConfig);
  1092. break;
  1093. }
  1094. case MULTI_AND_TRUE: {
  1095. if (!skipColoring)
  1096. edgeColoring(shape, angleThreshold, coloringSeed);
  1097. if (edgeAssignment)
  1098. parseColoring(shape, edgeAssignment);
  1099. mtsdf = Bitmap<float, 4>(width, height);
  1100. if (legacyMode)
  1101. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1102. else
  1103. generateMTSDF(mtsdf, shape, projection, range, generatorConfig);
  1104. break;
  1105. }
  1106. default:;
  1107. }
  1108. if (orientation == GUESS) {
  1109. // Get sign of signed distance outside bounds
  1110. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  1111. double distance = SimpleTrueShapeDistanceFinder::oneShotDistance(shape, p);
  1112. orientation = distance <= 0 ? KEEP : REVERSE;
  1113. }
  1114. if (orientation == REVERSE) {
  1115. switch (mode) {
  1116. case SINGLE:
  1117. case PSEUDO:
  1118. invertColor<1>(sdf);
  1119. break;
  1120. case MULTI:
  1121. invertColor<3>(msdf);
  1122. break;
  1123. case MULTI_AND_TRUE:
  1124. invertColor<4>(mtsdf);
  1125. break;
  1126. default:;
  1127. }
  1128. }
  1129. if (scanlinePass) {
  1130. switch (mode) {
  1131. case SINGLE:
  1132. case PSEUDO:
  1133. distanceSignCorrection(sdf, shape, projection, fillRule);
  1134. break;
  1135. case MULTI:
  1136. distanceSignCorrection(msdf, shape, projection, fillRule);
  1137. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1138. break;
  1139. case MULTI_AND_TRUE:
  1140. distanceSignCorrection(mtsdf, shape, projection, fillRule);
  1141. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1142. break;
  1143. default:;
  1144. }
  1145. }
  1146. if (outputDistanceShift) {
  1147. float *pixel = NULL, *pixelsEnd = NULL;
  1148. switch (mode) {
  1149. case SINGLE:
  1150. case PSEUDO:
  1151. pixel = (float *) sdf;
  1152. pixelsEnd = pixel+1*sdf.width()*sdf.height();
  1153. break;
  1154. case MULTI:
  1155. pixel = (float *) msdf;
  1156. pixelsEnd = pixel+3*msdf.width()*msdf.height();
  1157. break;
  1158. case MULTI_AND_TRUE:
  1159. pixel = (float *) mtsdf;
  1160. pixelsEnd = pixel+4*mtsdf.width()*mtsdf.height();
  1161. break;
  1162. default:;
  1163. }
  1164. while (pixel < pixelsEnd)
  1165. *pixel++ += outputDistanceShift;
  1166. }
  1167. // Save output
  1168. if (shapeExport) {
  1169. FILE *file = fopen(shapeExport, "w");
  1170. if (file) {
  1171. writeShapeDescription(file, shape);
  1172. fclose(file);
  1173. } else
  1174. fputs("Failed to write shape export file.\n", stderr);
  1175. }
  1176. const char *error = NULL;
  1177. switch (mode) {
  1178. case SINGLE:
  1179. case PSEUDO:
  1180. if ((error = writeOutput<1>(sdf, output, format))) {
  1181. fprintf(stderr, "%s\n", error);
  1182. return 1;
  1183. }
  1184. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1185. simulate8bit(sdf);
  1186. if (estimateError) {
  1187. double sdfError = estimateSDFError(sdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1188. printf("SDF error ~ %e\n", sdfError);
  1189. }
  1190. if (testRenderMulti) {
  1191. Bitmap<float, 3> render(testWidthM, testHeightM);
  1192. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1193. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1194. fputs("Failed to write test render file.\n", stderr);
  1195. }
  1196. if (testRender) {
  1197. Bitmap<float, 1> render(testWidth, testHeight);
  1198. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1199. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1200. fputs("Failed to write test render file.\n", stderr);
  1201. }
  1202. break;
  1203. case MULTI:
  1204. if ((error = writeOutput<3>(msdf, output, format))) {
  1205. fprintf(stderr, "%s\n", error);
  1206. return 1;
  1207. }
  1208. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1209. simulate8bit(msdf);
  1210. if (estimateError) {
  1211. double sdfError = estimateSDFError(msdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1212. printf("SDF error ~ %e\n", sdfError);
  1213. }
  1214. if (testRenderMulti) {
  1215. Bitmap<float, 3> render(testWidthM, testHeightM);
  1216. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1217. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1218. fputs("Failed to write test render file.\n", stderr);
  1219. }
  1220. if (testRender) {
  1221. Bitmap<float, 1> render(testWidth, testHeight);
  1222. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1223. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1224. fputs("Failed to write test render file.\n", stderr);
  1225. }
  1226. break;
  1227. case MULTI_AND_TRUE:
  1228. if ((error = writeOutput<4>(mtsdf, output, format))) {
  1229. fprintf(stderr, "%s\n", error);
  1230. return 1;
  1231. }
  1232. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1233. simulate8bit(mtsdf);
  1234. if (estimateError) {
  1235. double sdfError = estimateSDFError(mtsdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1236. printf("SDF error ~ %e\n", sdfError);
  1237. }
  1238. if (testRenderMulti) {
  1239. Bitmap<float, 4> render(testWidthM, testHeightM);
  1240. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1241. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1242. fputs("Failed to write test render file.\n", stderr);
  1243. }
  1244. if (testRender) {
  1245. Bitmap<float, 1> render(testWidth, testHeight);
  1246. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1247. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1248. fputs("Failed to write test render file.\n", stderr);
  1249. }
  1250. break;
  1251. default:;
  1252. }
  1253. return 0;
  1254. }
  1255. #endif