main.cpp 55 KB

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