2
0

main.cpp 54 KB

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