main.cpp 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR - standalone console program
  3. * --------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2023
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #define _USE_MATH_DEFINES
  9. #define _CRT_SECURE_NO_WARNINGS
  10. #include <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 pseudo-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. " -ascale <x scale> <y scale>\n"
  361. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  362. " -autoframe\n"
  363. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  364. " -coloringstrategy <simple / inktrap / distance>\n"
  365. "\tSelects the strategy of the edge coloring heuristic.\n"
  366. " -distanceshift <shift>\n"
  367. "\tShifts all normalized distances in the output distance field by this value.\n"
  368. " -edgecolors <sequence>\n"
  369. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  370. " -errorcorrection <mode>\n"
  371. "\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"
  372. " -errordeviationratio <ratio>\n"
  373. "\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"
  374. " -errorimproveratio <ratio>\n"
  375. "\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"
  376. " -estimateerror\n"
  377. "\tComputes and prints the distance field's estimated fill error to the standard output.\n"
  378. " -exportshape <filename.txt>\n"
  379. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  380. " -fillrule <nonzero / evenodd / positive / negative>\n"
  381. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  382. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  383. " -format <png / bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  384. #else
  385. " -format <bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  386. #endif
  387. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  388. " -guessorder\n"
  389. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  390. " -help\n"
  391. "\tDisplays this help.\n"
  392. " -legacy\n"
  393. "\tUses the original (legacy) distance field algorithms.\n"
  394. #ifdef MSDFGEN_USE_SKIA
  395. " -nopreprocess\n"
  396. "\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"
  397. #else
  398. " -nooverlap\n"
  399. "\tDisables resolution of overlapping contours.\n"
  400. " -noscanline\n"
  401. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  402. #endif
  403. " -o <filename>\n"
  404. "\tSets the output file name. The default value is \"output." DEFAULT_IMAGE_EXTENSION "\".\n"
  405. #ifdef MSDFGEN_USE_SKIA
  406. " -overlap\n"
  407. "\tSwitches to distance field generator with support for overlapping contours.\n"
  408. #endif
  409. " -printmetrics\n"
  410. "\tPrints relevant metrics of the shape to the standard output.\n"
  411. " -pxrange <range>\n"
  412. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  413. " -range <range>\n"
  414. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  415. " -reverseorder\n"
  416. "\tGenerates the distance field as if the shape's vertices were in reverse order.\n"
  417. " -scale <scale>\n"
  418. "\tSets the scale used to convert shape units to pixels.\n"
  419. #ifdef MSDFGEN_USE_SKIA
  420. " -scanline\n"
  421. "\tPerforms an additional scanline pass to fix the signs of the distances.\n"
  422. #endif
  423. " -seed <n>\n"
  424. "\tSets the random seed for edge coloring heuristic.\n"
  425. " -size <width> <height>\n"
  426. "\tSets the dimensions of the output image.\n"
  427. " -stdout\n"
  428. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  429. " -testrender <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  430. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  431. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  432. #else
  433. "\tRenders an image preview using the generated distance field and saves it as a TIFF file.\n"
  434. #endif
  435. " -testrendermulti <filename." DEFAULT_IMAGE_EXTENSION "> <width> <height>\n"
  436. "\tRenders an image preview without flattening the color channels.\n"
  437. " -translate <x> <y>\n"
  438. "\tSets the translation of the shape in shape units.\n"
  439. " -version\n"
  440. "\tPrints the version of the program.\n"
  441. " -windingpreprocess\n"
  442. "\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"
  443. " -yflip\n"
  444. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  445. "\n";
  446. static const char *errorCorrectionHelpText =
  447. "\n"
  448. "ERROR CORRECTION MODES\n"
  449. " auto-fast\n"
  450. "\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"
  451. " auto-full\n"
  452. "\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"
  453. " auto-mixed (default)\n"
  454. "\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"
  455. " disabled\n"
  456. "\tDisables error correction.\n"
  457. " distance-fast\n"
  458. "\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"
  459. " distance-full\n"
  460. "\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"
  461. " edge-fast\n"
  462. "\tDetects inversion artifacts only by range testing.\n"
  463. " edge-full\n"
  464. "\tDetects inversion artifacts only by exact distance evaluation.\n"
  465. " help\n"
  466. "\tDisplays this help.\n"
  467. "\n";
  468. int main(int argc, const char *const *argv) {
  469. #define ABORT(msg) do { fputs(msg "\n", stderr); return 1; } while (false)
  470. // Parse command line arguments
  471. enum {
  472. NONE,
  473. SVG,
  474. FONT,
  475. VAR_FONT,
  476. DESCRIPTION_ARG,
  477. DESCRIPTION_STDIN,
  478. DESCRIPTION_FILE
  479. } inputType = NONE;
  480. enum {
  481. SINGLE,
  482. PSEUDO,
  483. MULTI,
  484. MULTI_AND_TRUE,
  485. MULTI7_AND_TRUE,
  486. METRICS
  487. } mode = MULTI;
  488. enum {
  489. NO_PREPROCESS,
  490. WINDING_PREPROCESS,
  491. FULL_PREPROCESS
  492. } geometryPreproc = (
  493. #ifdef MSDFGEN_USE_SKIA
  494. FULL_PREPROCESS
  495. #else
  496. NO_PREPROCESS
  497. #endif
  498. );
  499. bool legacyMode = false;
  500. MSDFGeneratorConfig generatorConfig;
  501. generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;
  502. bool scanlinePass = geometryPreproc == NO_PREPROCESS;
  503. FillRule fillRule = FILL_NONZERO;
  504. Format format = AUTO;
  505. const char *input = NULL;
  506. const char *output = "output." DEFAULT_IMAGE_EXTENSION;
  507. const char *shapeExport = NULL;
  508. const char *testRender = NULL;
  509. const char *testRenderMulti = NULL;
  510. bool outputSpecified = false;
  511. #ifdef MSDFGEN_EXTENSIONS
  512. bool glyphIndexSpecified = false;
  513. GlyphIndex glyphIndex;
  514. unicode_t unicode = 0;
  515. #endif
  516. int width = 64, height = 64;
  517. int testWidth = 0, testHeight = 0;
  518. int testWidthM = 0, testHeightM = 0;
  519. bool autoFrame = false;
  520. enum {
  521. RANGE_UNIT,
  522. RANGE_PX
  523. } rangeMode = RANGE_PX;
  524. double range = 1;
  525. double pxRange = 2;
  526. Vector2 translate;
  527. Vector2 scale = 1;
  528. bool scaleSpecified = false;
  529. double angleThreshold = DEFAULT_ANGLE_THRESHOLD;
  530. float outputDistanceShift = 0.f;
  531. const char *edgeAssignment = NULL;
  532. bool yFlip = false;
  533. bool printMetrics = false;
  534. bool estimateError = false;
  535. bool skipColoring = false;
  536. enum {
  537. KEEP,
  538. REVERSE,
  539. GUESS
  540. } orientation = KEEP;
  541. unsigned long long coloringSeed = 0;
  542. void (*edgeColoring)(Shape &, double, unsigned long long) = edgeColoringSimple;
  543. bool explicitErrorCorrectionMode = false;
  544. int argPos = 1;
  545. bool suggestHelp = false;
  546. while (argPos < argc) {
  547. const char *arg = argv[argPos];
  548. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  549. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  550. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  551. // Accept arguments prefixed with -- instead of -
  552. if (arg[0] == '-' && arg[1] == '-')
  553. ++arg;
  554. ARG_MODE("sdf", SINGLE)
  555. ARG_MODE("psdf", PSEUDO)
  556. ARG_MODE("msdf", MULTI)
  557. ARG_MODE("mtsdf", MULTI_AND_TRUE)
  558. ARG_MODE("7tsdf", MULTI7_AND_TRUE)
  559. ARG_MODE("metrics", METRICS)
  560. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
  561. ARG_CASE("-svg", 1) {
  562. inputType = SVG;
  563. input = argv[argPos+1];
  564. argPos += 2;
  565. continue;
  566. }
  567. #endif
  568. #ifdef MSDFGEN_EXTENSIONS
  569. //ARG_CASE -font, -varfont
  570. if (argPos+2 < argc && (
  571. (!strcmp(arg, "-font") && (inputType = FONT, true))
  572. #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
  573. || (!strcmp(arg, "-varfont") && (inputType = VAR_FONT, true))
  574. #endif
  575. )) {
  576. input = argv[argPos+1];
  577. const char *charArg = argv[argPos+2];
  578. unsigned gi;
  579. switch (charArg[0]) {
  580. case 'G': case 'g':
  581. if (parseUnsignedDecOrHex(gi, charArg+1)) {
  582. glyphIndex = GlyphIndex(gi);
  583. glyphIndexSpecified = true;
  584. }
  585. break;
  586. case 'U': case 'u':
  587. ++charArg;
  588. // fallthrough
  589. default:
  590. parseUnicode(unicode, charArg);
  591. }
  592. argPos += 3;
  593. continue;
  594. }
  595. #else
  596. ARG_CASE("-svg", 1) {
  597. ABORT("SVG input is not available in core-only version.");
  598. }
  599. ARG_CASE("-font", 2) {
  600. ABORT("Font input is not available in core-only version.");
  601. }
  602. ARG_CASE("-varfont", 2) {
  603. ABORT("Variable font input is not available in core-only version.");
  604. }
  605. #endif
  606. ARG_CASE("-defineshape", 1) {
  607. inputType = DESCRIPTION_ARG;
  608. input = argv[argPos+1];
  609. argPos += 2;
  610. continue;
  611. }
  612. ARG_CASE("-stdin", 0) {
  613. inputType = DESCRIPTION_STDIN;
  614. input = "stdin";
  615. argPos += 1;
  616. continue;
  617. }
  618. ARG_CASE("-shapedesc", 1) {
  619. inputType = DESCRIPTION_FILE;
  620. input = argv[argPos+1];
  621. argPos += 2;
  622. continue;
  623. }
  624. ARG_CASE("-o", 1) {
  625. output = argv[argPos+1];
  626. outputSpecified = true;
  627. argPos += 2;
  628. continue;
  629. }
  630. ARG_CASE("-stdout", 0) {
  631. output = NULL;
  632. argPos += 1;
  633. continue;
  634. }
  635. ARG_CASE("-legacy", 0) {
  636. legacyMode = true;
  637. argPos += 1;
  638. continue;
  639. }
  640. ARG_CASE("-nopreprocess", 0) {
  641. geometryPreproc = NO_PREPROCESS;
  642. argPos += 1;
  643. continue;
  644. }
  645. ARG_CASE("-windingpreprocess", 0) {
  646. geometryPreproc = WINDING_PREPROCESS;
  647. argPos += 1;
  648. continue;
  649. }
  650. ARG_CASE("-preprocess", 0) {
  651. geometryPreproc = FULL_PREPROCESS;
  652. argPos += 1;
  653. continue;
  654. }
  655. ARG_CASE("-nooverlap", 0) {
  656. generatorConfig.overlapSupport = false;
  657. argPos += 1;
  658. continue;
  659. }
  660. ARG_CASE("-overlap", 0) {
  661. generatorConfig.overlapSupport = true;
  662. argPos += 1;
  663. continue;
  664. }
  665. ARG_CASE("-noscanline", 0) {
  666. scanlinePass = false;
  667. argPos += 1;
  668. continue;
  669. }
  670. ARG_CASE("-scanline", 0) {
  671. scanlinePass = true;
  672. argPos += 1;
  673. continue;
  674. }
  675. ARG_CASE("-fillrule", 1) {
  676. scanlinePass = true;
  677. if (!strcmp(argv[argPos+1], "nonzero")) fillRule = FILL_NONZERO;
  678. else if (!strcmp(argv[argPos+1], "evenodd") || !strcmp(argv[argPos+1], "odd")) fillRule = FILL_ODD;
  679. else if (!strcmp(argv[argPos+1], "positive")) fillRule = FILL_POSITIVE;
  680. else if (!strcmp(argv[argPos+1], "negative")) fillRule = FILL_NEGATIVE;
  681. else
  682. fputs("Unknown fill rule specified.\n", stderr);
  683. argPos += 2;
  684. continue;
  685. }
  686. ARG_CASE("-format", 1) {
  687. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  688. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_PNG)
  689. else if (!strcmp(argv[argPos+1], "png")) SET_FORMAT(PNG, "png");
  690. #else
  691. else if (!strcmp(argv[argPos+1], "png"))
  692. fputs("PNG format is not available in core-only version.\n", stderr);
  693. #endif
  694. else if (!strcmp(argv[argPos+1], "bmp")) SET_FORMAT(BMP, "bmp");
  695. else if (!strcmp(argv[argPos+1], "tiff") || !strcmp(argv[argPos+1], "tif")) SET_FORMAT(TIFF, "tif");
  696. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SET_FORMAT(TEXT, "txt");
  697. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  698. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SET_FORMAT(BINARY, "bin");
  699. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  700. else if (!strcmp(argv[argPos+1], "binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
  701. else
  702. fputs("Unknown format specified.\n", stderr);
  703. argPos += 2;
  704. continue;
  705. }
  706. ARG_CASE("-size", 2) {
  707. unsigned w, h;
  708. if (!(parseUnsigned(w, argv[argPos+1]) && parseUnsigned(h, argv[argPos+2]) && w && h))
  709. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  710. width = w, height = h;
  711. argPos += 3;
  712. continue;
  713. }
  714. ARG_CASE("-autoframe", 0) {
  715. autoFrame = true;
  716. argPos += 1;
  717. continue;
  718. }
  719. ARG_CASE("-range", 1) {
  720. double r;
  721. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  722. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  723. rangeMode = RANGE_UNIT;
  724. range = r;
  725. argPos += 2;
  726. continue;
  727. }
  728. ARG_CASE("-pxrange", 1) {
  729. double r;
  730. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  731. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  732. rangeMode = RANGE_PX;
  733. pxRange = r;
  734. argPos += 2;
  735. continue;
  736. }
  737. ARG_CASE("-scale", 1) {
  738. double s;
  739. if (!(parseDouble(s, argv[argPos+1]) && s > 0))
  740. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  741. scale = s;
  742. scaleSpecified = true;
  743. argPos += 2;
  744. continue;
  745. }
  746. ARG_CASE("-ascale", 2) {
  747. double sx, sy;
  748. if (!(parseDouble(sx, argv[argPos+1]) && parseDouble(sy, argv[argPos+2]) && sx > 0 && sy > 0))
  749. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  750. scale.set(sx, sy);
  751. scaleSpecified = true;
  752. argPos += 3;
  753. continue;
  754. }
  755. ARG_CASE("-translate", 2) {
  756. double tx, ty;
  757. if (!(parseDouble(tx, argv[argPos+1]) && parseDouble(ty, argv[argPos+2])))
  758. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  759. translate.set(tx, ty);
  760. argPos += 3;
  761. continue;
  762. }
  763. ARG_CASE("-angle", 1) {
  764. double at;
  765. if (!parseAngle(at, argv[argPos+1]))
  766. 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.");
  767. angleThreshold = at;
  768. argPos += 2;
  769. continue;
  770. }
  771. ARG_CASE("-errorcorrection", 1) {
  772. if (!strcmp(argv[argPos+1], "disabled") || !strcmp(argv[argPos+1], "0") || !strcmp(argv[argPos+1], "none")) {
  773. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  774. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  775. } else if (!strcmp(argv[argPos+1], "default") || !strcmp(argv[argPos+1], "auto") || !strcmp(argv[argPos+1], "auto-mixed") || !strcmp(argv[argPos+1], "mixed")) {
  776. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  777. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
  778. } else if (!strcmp(argv[argPos+1], "auto-fast") || !strcmp(argv[argPos+1], "fast")) {
  779. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  780. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  781. } else if (!strcmp(argv[argPos+1], "auto-full") || !strcmp(argv[argPos+1], "full")) {
  782. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  783. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  784. } else if (!strcmp(argv[argPos+1], "distance") || !strcmp(argv[argPos+1], "distance-fast") || !strcmp(argv[argPos+1], "indiscriminate") || !strcmp(argv[argPos+1], "indiscriminate-fast")) {
  785. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  786. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  787. } else if (!strcmp(argv[argPos+1], "distance-full") || !strcmp(argv[argPos+1], "indiscriminate-full")) {
  788. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  789. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  790. } else if (!strcmp(argv[argPos+1], "edge-fast")) {
  791. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  792. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  793. } else if (!strcmp(argv[argPos+1], "edge") || !strcmp(argv[argPos+1], "edge-full")) {
  794. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  795. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  796. } else if (!strcmp(argv[argPos+1], "help")) {
  797. puts(errorCorrectionHelpText);
  798. return 0;
  799. } else
  800. fputs("Unknown error correction mode. Use -errorcorrection help for more information.\n", stderr);
  801. explicitErrorCorrectionMode = true;
  802. argPos += 2;
  803. continue;
  804. }
  805. ARG_CASE("-errordeviationratio", 1) {
  806. double edr;
  807. if (!(parseDouble(edr, argv[argPos+1]) && edr > 0))
  808. ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");
  809. generatorConfig.errorCorrection.minDeviationRatio = edr;
  810. argPos += 2;
  811. continue;
  812. }
  813. ARG_CASE("-errorimproveratio", 1) {
  814. double eir;
  815. if (!(parseDouble(eir, argv[argPos+1]) && eir > 0))
  816. ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");
  817. generatorConfig.errorCorrection.minImproveRatio = eir;
  818. argPos += 2;
  819. continue;
  820. }
  821. ARG_CASE("-coloringstrategy", 1) {
  822. if (!strcmp(argv[argPos+1], "simple")) edgeColoring = edgeColoringSimple;
  823. else if (!strcmp(argv[argPos+1], "inktrap")) edgeColoring = edgeColoringInkTrap;
  824. else if (!strcmp(argv[argPos+1], "distance")) edgeColoring = edgeColoringByDistance;
  825. else
  826. fputs("Unknown coloring strategy specified.\n", stderr);
  827. argPos += 2;
  828. continue;
  829. }
  830. ARG_CASE("-edgecolors", 1) {
  831. static const char *allowed = " ?,cmwyCMWY";
  832. for (int i = 0; argv[argPos+1][i]; ++i) {
  833. for (int j = 0; allowed[j]; ++j)
  834. if (argv[argPos+1][i] == allowed[j])
  835. goto EDGE_COLOR_VERIFIED;
  836. 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.");
  837. EDGE_COLOR_VERIFIED:;
  838. }
  839. edgeAssignment = argv[argPos+1];
  840. argPos += 2;
  841. continue;
  842. }
  843. ARG_CASE("-distanceshift", 1) {
  844. double ds;
  845. if (!parseDouble(ds, argv[argPos+1]))
  846. ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");
  847. outputDistanceShift = (float) ds;
  848. argPos += 2;
  849. continue;
  850. }
  851. ARG_CASE("-exportshape", 1) {
  852. shapeExport = argv[argPos+1];
  853. argPos += 2;
  854. continue;
  855. }
  856. ARG_CASE("-testrender", 3) {
  857. unsigned w, h;
  858. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  859. ABORT("Invalid arguments for test render. Use -testrender <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  860. testRender = argv[argPos+1];
  861. testWidth = w, testHeight = h;
  862. argPos += 4;
  863. continue;
  864. }
  865. ARG_CASE("-testrendermulti", 3) {
  866. unsigned w, h;
  867. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  868. ABORT("Invalid arguments for test render. Use -testrendermulti <output." DEFAULT_IMAGE_EXTENSION "> <width> <height>.");
  869. testRenderMulti = argv[argPos+1];
  870. testWidthM = w, testHeightM = h;
  871. argPos += 4;
  872. continue;
  873. }
  874. ARG_CASE("-yflip", 0) {
  875. yFlip = true;
  876. argPos += 1;
  877. continue;
  878. }
  879. ARG_CASE("-printmetrics", 0) {
  880. printMetrics = true;
  881. argPos += 1;
  882. continue;
  883. }
  884. ARG_CASE("-estimateerror", 0) {
  885. estimateError = true;
  886. argPos += 1;
  887. continue;
  888. }
  889. ARG_CASE("-keeporder", 0) {
  890. orientation = KEEP;
  891. argPos += 1;
  892. continue;
  893. }
  894. ARG_CASE("-reverseorder", 0) {
  895. orientation = REVERSE;
  896. argPos += 1;
  897. continue;
  898. }
  899. ARG_CASE("-guessorder", 0) {
  900. orientation = GUESS;
  901. argPos += 1;
  902. continue;
  903. }
  904. ARG_CASE("-seed", 1) {
  905. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  906. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  907. argPos += 2;
  908. continue;
  909. }
  910. ARG_CASE("-version", 0) {
  911. puts(versionText);
  912. return 0;
  913. }
  914. ARG_CASE("-help", 0) {
  915. puts(helpText);
  916. return 0;
  917. }
  918. fprintf(stderr, "Unknown setting or insufficient parameters: %s\n", argv[argPos]);
  919. suggestHelp = true;
  920. ++argPos;
  921. }
  922. if (suggestHelp)
  923. fprintf(stderr, "Use -help for more information.\n");
  924. // Load input
  925. Shape::Bounds svgViewBox = { };
  926. double glyphAdvance = 0;
  927. if (!inputType || !input) {
  928. #ifdef MSDFGEN_EXTENSIONS
  929. #ifdef MSDFGEN_DISABLE_SVG
  930. ABORT("No input specified! Use -font <file.ttf/otf> <character code> or see -help.");
  931. #else
  932. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  933. #endif
  934. #else
  935. ABORT("No input specified! See -help.");
  936. #endif
  937. }
  938. if (mode == MULTI_AND_TRUE && (format == BMP || (format == AUTO && output && cmpExtension(output, ".bmp"))))
  939. ABORT("Incompatible image format. A BMP file cannot contain alpha channel, which is required in mtsdf mode.");
  940. Shape shape;
  941. switch (inputType) {
  942. #if defined(MSDFGEN_EXTENSIONS) && !defined(MSDFGEN_DISABLE_SVG)
  943. case SVG: {
  944. int svgImportFlags = loadSvgShape(shape, svgViewBox, input);
  945. if (!(svgImportFlags&SVG_IMPORT_SUCCESS_FLAG))
  946. ABORT("Failed to load shape from SVG file.");
  947. if (svgImportFlags&SVG_IMPORT_PARTIAL_FAILURE_FLAG)
  948. fputs("Warning: Failed to load part of SVG file.\n", stderr);
  949. if (svgImportFlags&SVG_IMPORT_INCOMPLETE_FLAG)
  950. fputs("Warning: SVG file contains multiple paths or shapes but this version is only able to load one.\n", stderr);
  951. else if (svgImportFlags&SVG_IMPORT_UNSUPPORTED_FEATURE_FLAG)
  952. fputs("Warning: SVG file likely contains elements that are unsupported.\n", stderr);
  953. if (svgImportFlags&SVG_IMPORT_TRANSFORMATION_IGNORED_FLAG)
  954. fputs("Warning: SVG path transformation ignored.\n", stderr);
  955. break;
  956. }
  957. #endif
  958. #ifdef MSDFGEN_EXTENSIONS
  959. case FONT: case VAR_FONT: {
  960. if (!glyphIndexSpecified && !unicode)
  961. 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).");
  962. FreetypeHandle *ft = initializeFreetype();
  963. if (!ft)
  964. return -1;
  965. FontHandle *font = (
  966. #ifndef MSDFGEN_DISABLE_VARIABLE_FONTS
  967. inputType == VAR_FONT ? loadVarFont(ft, input) :
  968. #endif
  969. loadFont(ft, input)
  970. );
  971. if (!font) {
  972. deinitializeFreetype(ft);
  973. ABORT("Failed to load font file.");
  974. }
  975. if (unicode)
  976. getGlyphIndex(glyphIndex, font, unicode);
  977. if (!loadGlyph(shape, font, glyphIndex, &glyphAdvance)) {
  978. destroyFont(font);
  979. deinitializeFreetype(ft);
  980. ABORT("Failed to load glyph from font file.");
  981. }
  982. destroyFont(font);
  983. deinitializeFreetype(ft);
  984. break;
  985. }
  986. #endif
  987. case DESCRIPTION_ARG: {
  988. if (!readShapeDescription(input, shape, &skipColoring))
  989. ABORT("Parse error in shape description.");
  990. break;
  991. }
  992. case DESCRIPTION_STDIN: {
  993. if (!readShapeDescription(stdin, shape, &skipColoring))
  994. ABORT("Parse error in shape description.");
  995. break;
  996. }
  997. case DESCRIPTION_FILE: {
  998. FILE *file = fopen(input, "r");
  999. if (!file)
  1000. ABORT("Failed to load shape description file.");
  1001. if (!readShapeDescription(file, shape, &skipColoring))
  1002. ABORT("Parse error in shape description.");
  1003. fclose(file);
  1004. break;
  1005. }
  1006. default:;
  1007. }
  1008. // Validate and normalize shape
  1009. if (!shape.validate())
  1010. ABORT("The geometry of the loaded shape is invalid.");
  1011. switch (geometryPreproc) {
  1012. case NO_PREPROCESS:
  1013. break;
  1014. case WINDING_PREPROCESS:
  1015. shape.orientContours();
  1016. break;
  1017. case FULL_PREPROCESS:
  1018. #ifdef MSDFGEN_USE_SKIA
  1019. if (!resolveShapeGeometry(shape))
  1020. fputs("Shape geometry preprocessing failed, skipping.\n", stderr);
  1021. else if (skipColoring) {
  1022. skipColoring = false;
  1023. fputs("Note: Input shape coloring won't be preserved due to geometry preprocessing.\n", stderr);
  1024. }
  1025. #else
  1026. ABORT("Shape geometry preprocessing (-preprocess) is not available in this version because the Skia library is not present.");
  1027. #endif
  1028. break;
  1029. }
  1030. shape.normalize();
  1031. if (yFlip)
  1032. shape.inverseYAxis = !shape.inverseYAxis;
  1033. double avgScale = .5*(scale.x+scale.y);
  1034. Shape::Bounds bounds = { };
  1035. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  1036. bounds = shape.getBounds();
  1037. // Auto-frame
  1038. if (autoFrame) {
  1039. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  1040. Vector2 frame(width, height);
  1041. double m = .5+(double) outputDistanceShift;
  1042. if (!scaleSpecified) {
  1043. if (rangeMode == RANGE_UNIT)
  1044. l -= m*range, b -= m*range, r += m*range, t += m*range;
  1045. else
  1046. frame -= 2*m*pxRange;
  1047. }
  1048. if (l >= r || b >= t)
  1049. l = 0, b = 0, r = 1, t = 1;
  1050. if (frame.x <= 0 || frame.y <= 0)
  1051. ABORT("Cannot fit the specified pixel range.");
  1052. Vector2 dims(r-l, t-b);
  1053. if (scaleSpecified)
  1054. translate = .5*(frame/scale-dims)-Vector2(l, b);
  1055. else {
  1056. if (dims.x*frame.y < dims.y*frame.x) {
  1057. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  1058. scale = avgScale = frame.y/dims.y;
  1059. } else {
  1060. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  1061. scale = avgScale = frame.x/dims.x;
  1062. }
  1063. }
  1064. if (rangeMode == RANGE_PX && !scaleSpecified)
  1065. translate += m*pxRange/scale;
  1066. }
  1067. if (rangeMode == RANGE_PX)
  1068. range = pxRange/min(scale.x, scale.y);
  1069. // Print metrics
  1070. if (mode == METRICS || printMetrics) {
  1071. FILE *out = stdout;
  1072. if (mode == METRICS && outputSpecified)
  1073. out = fopen(output, "w");
  1074. if (!out)
  1075. ABORT("Failed to write output file.");
  1076. if (shape.inverseYAxis)
  1077. fprintf(out, "inverseY = true\n");
  1078. if (svgViewBox.l < svgViewBox.r && svgViewBox.b < svgViewBox.t)
  1079. fprintf(out, "view box = %.17g, %.17g, %.17g, %.17g\n", svgViewBox.l, svgViewBox.b, svgViewBox.r, svgViewBox.t);
  1080. if (bounds.l < bounds.r && bounds.b < bounds.t)
  1081. fprintf(out, "bounds = %.17g, %.17g, %.17g, %.17g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  1082. if (glyphAdvance != 0)
  1083. fprintf(out, "advance = %.17g\n", glyphAdvance);
  1084. if (autoFrame) {
  1085. if (!scaleSpecified)
  1086. fprintf(out, "scale = %.17g\n", avgScale);
  1087. fprintf(out, "translate = %.17g, %.17g\n", translate.x, translate.y);
  1088. }
  1089. if (rangeMode == RANGE_PX)
  1090. fprintf(out, "range = %.17g\n", range);
  1091. if (mode == METRICS && outputSpecified)
  1092. fclose(out);
  1093. }
  1094. // Compute output
  1095. Projection projection(scale, translate);
  1096. Bitmap<float, 1> sdf;
  1097. Bitmap<float, 3> msdf;
  1098. Bitmap<float, 4> mtsdf;
  1099. Bitmap<float, 8> m7tsdf;
  1100. MSDFGeneratorConfig postErrorCorrectionConfig(generatorConfig);
  1101. if (scanlinePass) {
  1102. if (explicitErrorCorrectionMode && generatorConfig.errorCorrection.distanceCheckMode != ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {
  1103. const char *fallbackModeName = "unknown";
  1104. switch (generatorConfig.errorCorrection.mode) {
  1105. case ErrorCorrectionConfig::DISABLED: fallbackModeName = "disabled"; break;
  1106. case ErrorCorrectionConfig::INDISCRIMINATE: fallbackModeName = "distance-fast"; break;
  1107. case ErrorCorrectionConfig::EDGE_PRIORITY: fallbackModeName = "auto-fast"; break;
  1108. case ErrorCorrectionConfig::EDGE_ONLY: fallbackModeName = "edge-fast"; break;
  1109. }
  1110. fprintf(stderr, "Selected error correction mode not compatible with scanline pass, falling back to %s.\n", fallbackModeName);
  1111. }
  1112. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  1113. postErrorCorrectionConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  1114. }
  1115. switch (mode) {
  1116. case SINGLE: {
  1117. sdf = Bitmap<float, 1>(width, height);
  1118. if (legacyMode)
  1119. generateSDF_legacy(sdf, shape, range, scale, translate);
  1120. else
  1121. generateSDF(sdf, shape, projection, range, generatorConfig);
  1122. break;
  1123. }
  1124. case PSEUDO: {
  1125. sdf = Bitmap<float, 1>(width, height);
  1126. if (legacyMode)
  1127. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  1128. else
  1129. generatePseudoSDF(sdf, shape, projection, range, generatorConfig);
  1130. break;
  1131. }
  1132. case MULTI: {
  1133. if (!skipColoring)
  1134. edgeColoring(shape, angleThreshold, coloringSeed);
  1135. if (edgeAssignment)
  1136. parseColoring(shape, edgeAssignment);
  1137. msdf = Bitmap<float, 3>(width, height);
  1138. if (legacyMode)
  1139. generateMSDF_legacy(msdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1140. else
  1141. generateMSDF(msdf, shape, projection, range, generatorConfig);
  1142. break;
  1143. }
  1144. case MULTI_AND_TRUE: {
  1145. if (!skipColoring)
  1146. edgeColoring(shape, angleThreshold, coloringSeed);
  1147. if (edgeAssignment)
  1148. parseColoring(shape, edgeAssignment);
  1149. mtsdf = Bitmap<float, 4>(width, height);
  1150. if (legacyMode)
  1151. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1152. else
  1153. generateMTSDF(mtsdf, shape, projection, range, generatorConfig);
  1154. break;
  1155. }
  1156. case MULTI7_AND_TRUE:
  1157. edgeColoring7Random(shape, angleThreshold, coloringSeed);
  1158. m7tsdf = Bitmap<float, 8>(width, height);
  1159. generate7TSDF(m7tsdf, shape, projection, range, generatorConfig);
  1160. mtsdf = Bitmap<float, 4>(width, 2*height);
  1161. for (float
  1162. *dstLow = mtsdf(0, 0),
  1163. *dstHigh = mtsdf(0, height),
  1164. *src = m7tsdf(0, 0),
  1165. *srcEnd = m7tsdf(0, height);
  1166. src < srcEnd; dstLow += 4, dstHigh += 4, src += 8
  1167. ) {
  1168. dstLow[0] = src[0];
  1169. dstLow[1] = src[1];
  1170. dstLow[2] = src[2];
  1171. dstLow[3] = src[3];
  1172. dstHigh[0] = src[4];
  1173. dstHigh[1] = src[5];
  1174. dstHigh[2] = src[6];
  1175. dstHigh[3] = src[7];
  1176. }
  1177. default:;
  1178. }
  1179. if (orientation == GUESS) {
  1180. // Get sign of signed distance outside bounds
  1181. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  1182. double distance = SimpleTrueShapeDistanceFinder::oneShotDistance(shape, p);
  1183. orientation = distance <= 0 ? KEEP : REVERSE;
  1184. }
  1185. if (orientation == REVERSE) {
  1186. switch (mode) {
  1187. case SINGLE:
  1188. case PSEUDO:
  1189. invertColor<1>(sdf);
  1190. break;
  1191. case MULTI:
  1192. invertColor<3>(msdf);
  1193. break;
  1194. case MULTI_AND_TRUE:
  1195. invertColor<4>(mtsdf);
  1196. break;
  1197. default:;
  1198. }
  1199. }
  1200. if (scanlinePass) {
  1201. switch (mode) {
  1202. case SINGLE:
  1203. case PSEUDO:
  1204. distanceSignCorrection(sdf, shape, projection, fillRule);
  1205. break;
  1206. case MULTI:
  1207. distanceSignCorrection(msdf, shape, projection, fillRule);
  1208. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1209. break;
  1210. case MULTI_AND_TRUE:
  1211. distanceSignCorrection(mtsdf, shape, projection, fillRule);
  1212. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1213. break;
  1214. default:;
  1215. }
  1216. }
  1217. if (outputDistanceShift) {
  1218. float *pixel = NULL, *pixelsEnd = NULL;
  1219. switch (mode) {
  1220. case SINGLE:
  1221. case PSEUDO:
  1222. pixel = (float *) sdf;
  1223. pixelsEnd = pixel+1*sdf.width()*sdf.height();
  1224. break;
  1225. case MULTI:
  1226. pixel = (float *) msdf;
  1227. pixelsEnd = pixel+3*msdf.width()*msdf.height();
  1228. break;
  1229. case MULTI_AND_TRUE:
  1230. pixel = (float *) mtsdf;
  1231. pixelsEnd = pixel+4*mtsdf.width()*mtsdf.height();
  1232. break;
  1233. default:;
  1234. }
  1235. while (pixel < pixelsEnd)
  1236. *pixel++ += outputDistanceShift;
  1237. }
  1238. // Save output
  1239. if (shapeExport) {
  1240. FILE *file = fopen(shapeExport, "w");
  1241. if (file) {
  1242. writeShapeDescription(file, shape);
  1243. fclose(file);
  1244. } else
  1245. fputs("Failed to write shape export file.\n", stderr);
  1246. }
  1247. const char *error = NULL;
  1248. switch (mode) {
  1249. case SINGLE:
  1250. case PSEUDO:
  1251. if ((error = writeOutput<1>(sdf, output, format))) {
  1252. fprintf(stderr, "%s\n", error);
  1253. return 1;
  1254. }
  1255. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1256. simulate8bit(sdf);
  1257. if (estimateError) {
  1258. double sdfError = estimateSDFError(sdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1259. printf("SDF error ~ %e\n", sdfError);
  1260. }
  1261. if (testRenderMulti) {
  1262. Bitmap<float, 3> render(testWidthM, testHeightM);
  1263. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1264. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1265. fputs("Failed to write test render file.\n", stderr);
  1266. }
  1267. if (testRender) {
  1268. Bitmap<float, 1> render(testWidth, testHeight);
  1269. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1270. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1271. fputs("Failed to write test render file.\n", stderr);
  1272. }
  1273. break;
  1274. case MULTI:
  1275. if ((error = writeOutput<3>(msdf, output, format))) {
  1276. fprintf(stderr, "%s\n", error);
  1277. return 1;
  1278. }
  1279. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1280. simulate8bit(msdf);
  1281. if (estimateError) {
  1282. double sdfError = estimateSDFError(msdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1283. printf("SDF error ~ %e\n", sdfError);
  1284. }
  1285. if (testRenderMulti) {
  1286. Bitmap<float, 3> render(testWidthM, testHeightM);
  1287. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1288. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1289. fputs("Failed to write test render file.\n", stderr);
  1290. }
  1291. if (testRender) {
  1292. Bitmap<float, 1> render(testWidth, testHeight);
  1293. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1294. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1295. fputs("Failed to write test render file.\n", stderr);
  1296. }
  1297. break;
  1298. case MULTI_AND_TRUE:
  1299. if ((error = writeOutput<4>(mtsdf, output, format))) {
  1300. fprintf(stderr, "%s\n", error);
  1301. return 1;
  1302. }
  1303. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1304. simulate8bit(mtsdf);
  1305. if (estimateError) {
  1306. double sdfError = estimateSDFError(mtsdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1307. printf("SDF error ~ %e\n", sdfError);
  1308. }
  1309. if (testRenderMulti) {
  1310. Bitmap<float, 4> render(testWidthM, testHeightM);
  1311. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1312. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRenderMulti))
  1313. fputs("Failed to write test render file.\n", stderr);
  1314. }
  1315. if (testRender) {
  1316. Bitmap<float, 1> render(testWidth, testHeight);
  1317. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1318. if (!SAVE_DEFAULT_IMAGE_FORMAT(render, testRender))
  1319. fputs("Failed to write test render file.\n", stderr);
  1320. }
  1321. break;
  1322. case MULTI7_AND_TRUE:
  1323. if ((error = writeOutput<4>(mtsdf, output, format))) {
  1324. fprintf(stderr, "%s\n", error);
  1325. return 1;
  1326. }
  1327. default:;
  1328. }
  1329. return 0;
  1330. }
  1331. #endif