main.cpp 56 KB

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