main.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.7 (2020-03-07) - standalone console program
  3. * --------------------------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2020
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #define _USE_MATH_DEFINES
  9. #include <cstdio>
  10. #include <cmath>
  11. #include <cstring>
  12. #include "msdfgen.h"
  13. #include "msdfgen-ext.h"
  14. #ifdef _WIN32
  15. #pragma warning(disable:4996)
  16. #endif
  17. #define SDF_ERROR_ESTIMATE_PRECISION 19
  18. using namespace msdfgen;
  19. enum Format {
  20. AUTO,
  21. PNG,
  22. BMP,
  23. TIFF,
  24. TEXT,
  25. TEXT_FLOAT,
  26. BINARY,
  27. BINARY_FLOAT,
  28. BINARY_FLOAT_BE
  29. };
  30. static bool is8bitFormat(Format format) {
  31. return format == PNG || format == BMP || format == TEXT || format == BINARY;
  32. }
  33. static char toupper(char c) {
  34. return c >= 'a' && c <= 'z' ? c-'a'+'A' : c;
  35. }
  36. static bool parseUnsigned(unsigned &value, const char *arg) {
  37. static char c;
  38. return sscanf(arg, "%u%c", &value, &c) == 1;
  39. }
  40. static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
  41. static char c;
  42. return sscanf(arg, "%llu%c", &value, &c) == 1;
  43. }
  44. static bool parseUnsignedHex(unsigned &value, const char *arg) {
  45. static char c;
  46. return sscanf(arg, "%x%c", &value, &c) == 1;
  47. }
  48. static bool parseDouble(double &value, const char *arg) {
  49. static char c;
  50. return sscanf(arg, "%lf%c", &value, &c) == 1;
  51. }
  52. static bool parseUnicode(unicode_t &unicode, const char *arg) {
  53. unsigned uuc;
  54. if (parseUnsigned(uuc, arg)) {
  55. unicode = uuc;
  56. return true;
  57. }
  58. if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X') && parseUnsignedHex(uuc, arg+2)) {
  59. unicode = uuc;
  60. return true;
  61. }
  62. if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
  63. unicode = arg[1];
  64. return true;
  65. }
  66. return false;
  67. }
  68. static bool parseAngle(double &value, const char *arg) {
  69. char c1, c2;
  70. int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
  71. if (result == 1)
  72. return true;
  73. if (result == 2 && (c1 == 'd' || c1 == 'D')) {
  74. value *= M_PI/180;
  75. return true;
  76. }
  77. return false;
  78. }
  79. static void parseColoring(Shape &shape, const char *edgeAssignment) {
  80. unsigned c = 0, e = 0;
  81. if (shape.contours.size() < c) return;
  82. Contour *contour = &shape.contours[c];
  83. bool change = false;
  84. bool clear = true;
  85. for (const char *in = edgeAssignment; *in; ++in) {
  86. switch (*in) {
  87. case ',':
  88. if (change)
  89. ++e;
  90. if (clear)
  91. while (e < contour->edges.size()) {
  92. contour->edges[e]->color = WHITE;
  93. ++e;
  94. }
  95. ++c, e = 0;
  96. if (shape.contours.size() <= c) return;
  97. contour = &shape.contours[c];
  98. change = false;
  99. clear = true;
  100. break;
  101. case '?':
  102. clear = false;
  103. break;
  104. case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
  105. if (change) {
  106. ++e;
  107. change = false;
  108. }
  109. if (e < contour->edges.size()) {
  110. contour->edges[e]->color = EdgeColor(
  111. (*in == 'C' || *in == 'c')*CYAN|
  112. (*in == 'M' || *in == 'm')*MAGENTA|
  113. (*in == 'Y' || *in == 'y')*YELLOW|
  114. (*in == 'W' || *in == 'w')*WHITE);
  115. change = true;
  116. }
  117. break;
  118. }
  119. }
  120. }
  121. template <int N>
  122. static void invertColor(const BitmapRef<float, N> &bitmap) {
  123. const float *end = bitmap.pixels+N*bitmap.width*bitmap.height;
  124. for (float *p = bitmap.pixels; p < end; ++p)
  125. *p = 1.f-*p;
  126. }
  127. static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
  128. for (int row = 0; row < rows; ++row) {
  129. for (int col = 0; col < cols; ++col) {
  130. int v = clamp(int((*values++)*0x100), 0xff);
  131. fprintf(file, col ? " %02X" : "%02X", v);
  132. }
  133. fprintf(file, "\n");
  134. }
  135. return true;
  136. }
  137. static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
  138. for (int row = 0; row < rows; ++row) {
  139. for (int col = 0; col < cols; ++col) {
  140. fprintf(file, col ? " %g" : "%g", *values++);
  141. }
  142. fprintf(file, "\n");
  143. }
  144. return true;
  145. }
  146. static bool writeBinBitmap(FILE *file, const float *values, int count) {
  147. for (int pos = 0; pos < count; ++pos) {
  148. unsigned char v = clamp(int((*values++)*0x100), 0xff);
  149. fwrite(&v, 1, 1, file);
  150. }
  151. return true;
  152. }
  153. #ifdef __BIG_ENDIAN__
  154. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  155. #else
  156. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  157. #endif
  158. {
  159. return fwrite(values, sizeof(float), count, file) == count;
  160. }
  161. #ifdef __BIG_ENDIAN__
  162. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  163. #else
  164. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  165. #endif
  166. {
  167. for (int pos = 0; pos < count; ++pos) {
  168. const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
  169. for (int i = sizeof(float)-1; i >= 0; --i)
  170. fwrite(b+i, 1, 1, file);
  171. }
  172. return true;
  173. }
  174. static bool cmpExtension(const char *path, const char *ext) {
  175. for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
  176. if (a < path || toupper(*a) != toupper(*b))
  177. return false;
  178. return true;
  179. }
  180. template <int N>
  181. static const char * writeOutput(const BitmapConstRef<float, N> &bitmap, const char *filename, Format format) {
  182. if (filename) {
  183. if (format == AUTO) {
  184. if (cmpExtension(filename, ".png")) format = PNG;
  185. else if (cmpExtension(filename, ".bmp")) format = BMP;
  186. else if (cmpExtension(filename, ".tif") || cmpExtension(filename, ".tiff")) format = TIFF;
  187. else if (cmpExtension(filename, ".txt")) format = TEXT;
  188. else if (cmpExtension(filename, ".bin")) format = BINARY;
  189. else
  190. return "Could not deduce format from output file name.";
  191. }
  192. switch (format) {
  193. case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
  194. case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
  195. case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";
  196. case TEXT: case TEXT_FLOAT: {
  197. FILE *file = fopen(filename, "w");
  198. if (!file) return "Failed to write output text file.";
  199. if (format == TEXT)
  200. writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  201. else if (format == TEXT_FLOAT)
  202. writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  203. fclose(file);
  204. return NULL;
  205. }
  206. case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {
  207. FILE *file = fopen(filename, "wb");
  208. if (!file) return "Failed to write output binary file.";
  209. if (format == BINARY)
  210. writeBinBitmap(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  211. else if (format == BINARY_FLOAT)
  212. writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  213. else if (format == BINARY_FLOAT_BE)
  214. writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  215. fclose(file);
  216. return NULL;
  217. }
  218. default:;
  219. }
  220. } else {
  221. if (format == AUTO || format == TEXT)
  222. writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  223. else if (format == TEXT_FLOAT)
  224. writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  225. else
  226. return "Unsupported format for standard output.";
  227. }
  228. return NULL;
  229. }
  230. static const char *helpText =
  231. "\n"
  232. "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION "\n"
  233. "---------------------------------------------------------------------\n"
  234. " Usage: msdfgen"
  235. #ifdef _WIN32
  236. ".exe"
  237. #endif
  238. " <mode> <input specification> <options>\n"
  239. "\n"
  240. "MODES\n"
  241. " sdf - Generate conventional monochrome (true) signed distance field.\n"
  242. " psdf - Generate monochrome signed pseudo-distance field.\n"
  243. " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
  244. " mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"
  245. " metrics - Report shape metrics only.\n"
  246. "\n"
  247. "INPUT SPECIFICATION\n"
  248. " -defineshape <definition>\n"
  249. "\tDefines input shape using the ad-hoc text definition.\n"
  250. " -font <filename.ttf> <character code>\n"
  251. "\tLoads a single glyph from the specified font file. Format of character code is '?', 63 or 0x3F.\n"
  252. " -shapedesc <filename.txt>\n"
  253. "\tLoads text shape description from a file.\n"
  254. " -stdin\n"
  255. "\tReads text shape description from the standard input.\n"
  256. " -svg <filename.svg>\n"
  257. "\tLoads the last vector path found in the specified SVG file.\n"
  258. "\n"
  259. "OPTIONS\n"
  260. " -angle <angle>\n"
  261. "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
  262. " -ascale <x scale> <y scale>\n"
  263. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  264. " -autoframe\n"
  265. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  266. " -coloringstrategy <simple / inktrap>\n"
  267. "\tSelects the strategy of the edge coloring heuristic.\n"
  268. " -edgecolors <sequence>\n"
  269. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  270. " -errorcorrection <threshold>\n"
  271. "\tChanges the threshold used to detect and correct potential artifacts. 0 disables error correction.\n"
  272. " -estimateerror\n"
  273. "\tComputes and prints the distance field's estimated fill error to the standard output.\n"
  274. " -exportshape <filename.txt>\n"
  275. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  276. " -fillrule <nonzero / evenodd / positive / negative>\n"
  277. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  278. " -format <png / bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  279. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  280. " -guessorder\n"
  281. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  282. " -help\n"
  283. "\tDisplays this help.\n"
  284. " -legacy\n"
  285. "\tUses the original (legacy) distance field algorithms.\n"
  286. " -nooverlap\n"
  287. "\tDisables resolution of overlapping contours.\n"
  288. " -noscanline\n"
  289. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  290. " -o <filename>\n"
  291. "\tSets the output file name. The default value is \"output.png\".\n"
  292. " -printmetrics\n"
  293. "\tPrints relevant metrics of the shape to the standard output.\n"
  294. " -pxrange <range>\n"
  295. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  296. " -range <range>\n"
  297. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  298. " -reverseorder\n"
  299. "\tGenerates the distance field as if shape vertices were in reverse order.\n"
  300. " -scale <scale>\n"
  301. "\tSets the scale used to convert shape units to pixels.\n"
  302. " -seed <n>\n"
  303. "\tSets the random seed for edge coloring heuristic.\n"
  304. " -size <width> <height>\n"
  305. "\tSets the dimensions of the output image.\n"
  306. " -stdout\n"
  307. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  308. " -testrender <filename.png> <width> <height>\n"
  309. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  310. " -testrendermulti <filename.png> <width> <height>\n"
  311. "\tRenders an image preview without flattening the color channels.\n"
  312. " -translate <x> <y>\n"
  313. "\tSets the translation of the shape in shape units.\n"
  314. " -yflip\n"
  315. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  316. "\n";
  317. int main(int argc, const char * const *argv) {
  318. #define ABORT(msg) { puts(msg); return 1; }
  319. // Parse command line arguments
  320. enum {
  321. NONE,
  322. SVG,
  323. FONT,
  324. DESCRIPTION_ARG,
  325. DESCRIPTION_STDIN,
  326. DESCRIPTION_FILE
  327. } inputType = NONE;
  328. enum {
  329. SINGLE,
  330. PSEUDO,
  331. MULTI,
  332. MULTI_AND_TRUE,
  333. METRICS
  334. } mode = MULTI;
  335. bool legacyMode = false;
  336. bool overlapSupport = true;
  337. bool scanlinePass = true;
  338. FillRule fillRule = FILL_NONZERO;
  339. Format format = AUTO;
  340. const char *input = NULL;
  341. const char *output = "output.png";
  342. const char *shapeExport = NULL;
  343. const char *testRender = NULL;
  344. const char *testRenderMulti = NULL;
  345. bool outputSpecified = false;
  346. unicode_t unicode = 0;
  347. int svgPathIndex = 0;
  348. int width = 64, height = 64;
  349. int testWidth = 0, testHeight = 0;
  350. int testWidthM = 0, testHeightM = 0;
  351. bool autoFrame = false;
  352. enum {
  353. RANGE_UNIT,
  354. RANGE_PX
  355. } rangeMode = RANGE_PX;
  356. double range = 1;
  357. double pxRange = 2;
  358. Vector2 translate;
  359. Vector2 scale = 1;
  360. bool scaleSpecified = false;
  361. double angleThreshold = 3;
  362. double edgeThreshold = MSDFGEN_DEFAULT_ERROR_CORRECTION_THRESHOLD;
  363. bool defEdgeAssignment = true;
  364. const char *edgeAssignment = NULL;
  365. bool yFlip = false;
  366. bool printMetrics = false;
  367. bool estimateError = false;
  368. bool skipColoring = false;
  369. enum {
  370. KEEP,
  371. REVERSE,
  372. GUESS
  373. } orientation = KEEP;
  374. unsigned long long coloringSeed = 0;
  375. void (*edgeColoring)(Shape &, double, unsigned long long) = edgeColoringSimple;
  376. int argPos = 1;
  377. bool suggestHelp = false;
  378. while (argPos < argc) {
  379. const char *arg = argv[argPos];
  380. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  381. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  382. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  383. ARG_MODE("sdf", SINGLE)
  384. ARG_MODE("psdf", PSEUDO)
  385. ARG_MODE("msdf", MULTI)
  386. ARG_MODE("mtsdf", MULTI_AND_TRUE)
  387. ARG_MODE("metrics", METRICS)
  388. ARG_CASE("-svg", 1) {
  389. inputType = SVG;
  390. input = argv[argPos+1];
  391. argPos += 2;
  392. continue;
  393. }
  394. ARG_CASE("-font", 2) {
  395. inputType = FONT;
  396. input = argv[argPos+1];
  397. parseUnicode(unicode, argv[argPos+2]);
  398. argPos += 3;
  399. continue;
  400. }
  401. ARG_CASE("-defineshape", 1) {
  402. inputType = DESCRIPTION_ARG;
  403. input = argv[argPos+1];
  404. argPos += 2;
  405. continue;
  406. }
  407. ARG_CASE("-stdin", 0) {
  408. inputType = DESCRIPTION_STDIN;
  409. input = "stdin";
  410. argPos += 1;
  411. continue;
  412. }
  413. ARG_CASE("-shapedesc", 1) {
  414. inputType = DESCRIPTION_FILE;
  415. input = argv[argPos+1];
  416. argPos += 2;
  417. continue;
  418. }
  419. ARG_CASE("-o", 1) {
  420. output = argv[argPos+1];
  421. outputSpecified = true;
  422. argPos += 2;
  423. continue;
  424. }
  425. ARG_CASE("-stdout", 0) {
  426. output = NULL;
  427. argPos += 1;
  428. continue;
  429. }
  430. ARG_CASE("-legacy", 0) {
  431. legacyMode = true;
  432. argPos += 1;
  433. continue;
  434. }
  435. ARG_CASE("-nooverlap", 0) {
  436. overlapSupport = false;
  437. argPos += 1;
  438. continue;
  439. }
  440. ARG_CASE("-noscanline", 0) {
  441. scanlinePass = false;
  442. argPos += 1;
  443. continue;
  444. }
  445. ARG_CASE("-scanline", 0) {
  446. scanlinePass = true;
  447. argPos += 1;
  448. continue;
  449. }
  450. ARG_CASE("-fillrule", 1) {
  451. if (!strcmp(argv[argPos+1], "nonzero")) fillRule = FILL_NONZERO;
  452. else if (!strcmp(argv[argPos+1], "evenodd") || !strcmp(argv[argPos+1], "odd")) fillRule = FILL_ODD;
  453. else if (!strcmp(argv[argPos+1], "positive")) fillRule = FILL_POSITIVE;
  454. else if (!strcmp(argv[argPos+1], "negative")) fillRule = FILL_NEGATIVE;
  455. else
  456. puts("Unknown fill rule specified.");
  457. argPos += 2;
  458. continue;
  459. }
  460. ARG_CASE("-format", 1) {
  461. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  462. else if (!strcmp(argv[argPos+1], "png")) SET_FORMAT(PNG, "png");
  463. else if (!strcmp(argv[argPos+1], "bmp")) SET_FORMAT(BMP, "bmp");
  464. else if (!strcmp(argv[argPos+1], "tiff")) SET_FORMAT(TIFF, "tif");
  465. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SET_FORMAT(TEXT, "txt");
  466. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  467. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SET_FORMAT(BINARY, "bin");
  468. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  469. else if (!strcmp(argv[argPos+1], "binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
  470. else
  471. puts("Unknown format specified.");
  472. argPos += 2;
  473. continue;
  474. }
  475. ARG_CASE("-size", 2) {
  476. unsigned w, h;
  477. if (!parseUnsigned(w, argv[argPos+1]) || !parseUnsigned(h, argv[argPos+2]) || !w || !h)
  478. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  479. width = w, height = h;
  480. argPos += 3;
  481. continue;
  482. }
  483. ARG_CASE("-autoframe", 0) {
  484. autoFrame = true;
  485. argPos += 1;
  486. continue;
  487. }
  488. ARG_CASE("-range", 1) {
  489. double r;
  490. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  491. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  492. rangeMode = RANGE_UNIT;
  493. range = r;
  494. argPos += 2;
  495. continue;
  496. }
  497. ARG_CASE("-pxrange", 1) {
  498. double r;
  499. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  500. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  501. rangeMode = RANGE_PX;
  502. pxRange = r;
  503. argPos += 2;
  504. continue;
  505. }
  506. ARG_CASE("-scale", 1) {
  507. double s;
  508. if (!parseDouble(s, argv[argPos+1]) || s <= 0)
  509. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  510. scale = s;
  511. scaleSpecified = true;
  512. argPos += 2;
  513. continue;
  514. }
  515. ARG_CASE("-ascale", 2) {
  516. double sx, sy;
  517. if (!parseDouble(sx, argv[argPos+1]) || !parseDouble(sy, argv[argPos+2]) || sx <= 0 || sy <= 0)
  518. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  519. scale.set(sx, sy);
  520. scaleSpecified = true;
  521. argPos += 3;
  522. continue;
  523. }
  524. ARG_CASE("-translate", 2) {
  525. double tx, ty;
  526. if (!parseDouble(tx, argv[argPos+1]) || !parseDouble(ty, argv[argPos+2]))
  527. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  528. translate.set(tx, ty);
  529. argPos += 3;
  530. continue;
  531. }
  532. ARG_CASE("-angle", 1) {
  533. double at;
  534. if (!parseAngle(at, argv[argPos+1]))
  535. 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.");
  536. angleThreshold = at;
  537. argPos += 2;
  538. continue;
  539. }
  540. ARG_CASE("-errorcorrection", 1) {
  541. double et;
  542. if (!parseDouble(et, argv[argPos+1]) || et < 0)
  543. ABORT("Invalid error correction threshold. Use -errorcorrection <threshold> with a real number larger or equal to 1.");
  544. edgeThreshold = et;
  545. argPos += 2;
  546. continue;
  547. }
  548. ARG_CASE("-coloringstrategy", 1) {
  549. if (!strcmp(argv[argPos+1], "simple")) edgeColoring = edgeColoringSimple;
  550. else if (!strcmp(argv[argPos+1], "inktrap")) edgeColoring = edgeColoringInkTrap;
  551. else
  552. puts("Unknown coloring strategy specified.");
  553. argPos += 2;
  554. continue;
  555. }
  556. ARG_CASE("-edgecolors", 1) {
  557. static const char *allowed = " ?,cmwyCMWY";
  558. for (int i = 0; argv[argPos+1][i]; ++i) {
  559. for (int j = 0; allowed[j]; ++j)
  560. if (argv[argPos+1][i] == allowed[j])
  561. goto EDGE_COLOR_VERIFIED;
  562. 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.");
  563. EDGE_COLOR_VERIFIED:;
  564. }
  565. edgeAssignment = argv[argPos+1];
  566. argPos += 2;
  567. continue;
  568. }
  569. ARG_CASE("-exportshape", 1) {
  570. shapeExport = argv[argPos+1];
  571. argPos += 2;
  572. continue;
  573. }
  574. ARG_CASE("-testrender", 3) {
  575. unsigned w, h;
  576. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  577. ABORT("Invalid arguments for test render. Use -testrender <output.png> <width> <height>.");
  578. testRender = argv[argPos+1];
  579. testWidth = w, testHeight = h;
  580. argPos += 4;
  581. continue;
  582. }
  583. ARG_CASE("-testrendermulti", 3) {
  584. unsigned w, h;
  585. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  586. ABORT("Invalid arguments for test render. Use -testrendermulti <output.png> <width> <height>.");
  587. testRenderMulti = argv[argPos+1];
  588. testWidthM = w, testHeightM = h;
  589. argPos += 4;
  590. continue;
  591. }
  592. ARG_CASE("-yflip", 0) {
  593. yFlip = true;
  594. argPos += 1;
  595. continue;
  596. }
  597. ARG_CASE("-printmetrics", 0) {
  598. printMetrics = true;
  599. argPos += 1;
  600. continue;
  601. }
  602. ARG_CASE("-estimateerror", 0) {
  603. estimateError = true;
  604. argPos += 1;
  605. continue;
  606. }
  607. ARG_CASE("-keeporder", 0) {
  608. orientation = KEEP;
  609. argPos += 1;
  610. continue;
  611. }
  612. ARG_CASE("-reverseorder", 0) {
  613. orientation = REVERSE;
  614. argPos += 1;
  615. continue;
  616. }
  617. ARG_CASE("-guessorder", 0) {
  618. orientation = GUESS;
  619. argPos += 1;
  620. continue;
  621. }
  622. ARG_CASE("-seed", 1) {
  623. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  624. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  625. argPos += 2;
  626. continue;
  627. }
  628. ARG_CASE("-help", 0) {
  629. puts(helpText);
  630. return 0;
  631. }
  632. printf("Unknown setting or insufficient parameters: %s\n", arg);
  633. suggestHelp = true;
  634. ++argPos;
  635. }
  636. if (suggestHelp)
  637. printf("Use -help for more information.\n");
  638. edgeThreshold = 0;
  639. // Load input
  640. Vector2 svgDims;
  641. double glyphAdvance = 0;
  642. if (!inputType || !input)
  643. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  644. if (mode == MULTI_AND_TRUE && (format == BMP || format == AUTO && output && cmpExtension(output, ".bmp")))
  645. ABORT("Incompatible image format. A BMP file cannot contain alpha channel, which is required in mtsdf mode.");
  646. Shape shape;
  647. switch (inputType) {
  648. case SVG: {
  649. if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
  650. ABORT("Failed to load shape from SVG file.");
  651. break;
  652. }
  653. case FONT: {
  654. if (!unicode)
  655. ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a number (65, 0x41), or a character in apostrophes ('A').");
  656. FreetypeHandle *ft = initializeFreetype();
  657. if (!ft) return -1;
  658. FontHandle *font = loadFont(ft, input);
  659. if (!font) {
  660. deinitializeFreetype(ft);
  661. ABORT("Failed to load font file.");
  662. }
  663. if (!loadGlyph(shape, font, unicode, &glyphAdvance)) {
  664. destroyFont(font);
  665. deinitializeFreetype(ft);
  666. ABORT("Failed to load glyph from font file.");
  667. }
  668. destroyFont(font);
  669. deinitializeFreetype(ft);
  670. break;
  671. }
  672. case DESCRIPTION_ARG: {
  673. if (!readShapeDescription(input, shape, &skipColoring))
  674. ABORT("Parse error in shape description.");
  675. break;
  676. }
  677. case DESCRIPTION_STDIN: {
  678. if (!readShapeDescription(stdin, shape, &skipColoring))
  679. ABORT("Parse error in shape description.");
  680. break;
  681. }
  682. case DESCRIPTION_FILE: {
  683. FILE *file = fopen(input, "r");
  684. if (!file)
  685. ABORT("Failed to load shape description file.");
  686. if (!readShapeDescription(file, shape, &skipColoring))
  687. ABORT("Parse error in shape description.");
  688. fclose(file);
  689. break;
  690. }
  691. default:;
  692. }
  693. // Validate and normalize shape
  694. if (!shape.validate())
  695. ABORT("The geometry of the loaded shape is invalid.");
  696. shape.normalize();
  697. if (yFlip)
  698. shape.inverseYAxis = !shape.inverseYAxis;
  699. double avgScale = .5*(scale.x+scale.y);
  700. Shape::Bounds bounds = { };
  701. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  702. bounds = shape.getBounds();
  703. // Auto-frame
  704. if (autoFrame) {
  705. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  706. Vector2 frame(width, height);
  707. if (rangeMode == RANGE_UNIT)
  708. l -= .5*range, b -= .5*range, r += .5*range, t += .5*range;
  709. else if (!scaleSpecified)
  710. frame -= pxRange;
  711. if (l >= r || b >= t)
  712. l = 0, b = 0, r = 1, t = 1;
  713. if (frame.x <= 0 || frame.y <= 0)
  714. ABORT("Cannot fit the specified pixel range.");
  715. Vector2 dims(r-l, t-b);
  716. if (scaleSpecified)
  717. translate = .5*(frame/scale-dims)-Vector2(l, b);
  718. else {
  719. if (dims.x*frame.y < dims.y*frame.x) {
  720. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  721. scale = avgScale = frame.y/dims.y;
  722. } else {
  723. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  724. scale = avgScale = frame.x/dims.x;
  725. }
  726. }
  727. if (rangeMode == RANGE_PX && !scaleSpecified)
  728. translate += .5*pxRange/scale;
  729. }
  730. if (rangeMode == RANGE_PX)
  731. range = pxRange/min(scale.x, scale.y);
  732. // Print metrics
  733. if (mode == METRICS || printMetrics) {
  734. FILE *out = stdout;
  735. if (mode == METRICS && outputSpecified)
  736. out = fopen(output, "w");
  737. if (!out)
  738. ABORT("Failed to write output file.");
  739. if (shape.inverseYAxis)
  740. fprintf(out, "inverseY = true\n");
  741. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  742. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  743. if (svgDims.x != 0 && svgDims.y != 0)
  744. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  745. if (glyphAdvance != 0)
  746. fprintf(out, "advance = %.12g\n", glyphAdvance);
  747. if (autoFrame) {
  748. if (!scaleSpecified)
  749. fprintf(out, "scale = %.12g\n", avgScale);
  750. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  751. }
  752. if (rangeMode == RANGE_PX)
  753. fprintf(out, "range = %.12g\n", range);
  754. if (mode == METRICS && outputSpecified)
  755. fclose(out);
  756. }
  757. // Compute output
  758. Bitmap<float, 1> sdf;
  759. Bitmap<float, 3> msdf;
  760. Bitmap<float, 4> mtsdf;
  761. switch (mode) {
  762. case SINGLE: {
  763. sdf = Bitmap<float, 1>(width, height);
  764. if (legacyMode)
  765. generateSDF_legacy(sdf, shape, range, scale, translate);
  766. else
  767. generateSDF(sdf, shape, range, scale, translate, overlapSupport);
  768. break;
  769. }
  770. case PSEUDO: {
  771. sdf = Bitmap<float, 1>(width, height);
  772. if (legacyMode)
  773. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  774. else
  775. generatePseudoSDF(sdf, shape, range, scale, translate, overlapSupport);
  776. break;
  777. }
  778. case MULTI: {
  779. if (!skipColoring)
  780. edgeColoring(shape, angleThreshold, coloringSeed);
  781. if (edgeAssignment)
  782. parseColoring(shape, edgeAssignment);
  783. msdf = Bitmap<float, 3>(width, height);
  784. if (legacyMode)
  785. generateMSDF_legacy(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold);
  786. else
  787. generateMSDF(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold, overlapSupport);
  788. break;
  789. }
  790. case MULTI_AND_TRUE: {
  791. if (!skipColoring)
  792. edgeColoring(shape, angleThreshold, coloringSeed);
  793. if (edgeAssignment)
  794. parseColoring(shape, edgeAssignment);
  795. mtsdf = Bitmap<float, 4>(width, height);
  796. if (legacyMode)
  797. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold);
  798. else
  799. generateMTSDF(mtsdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold, overlapSupport);
  800. break;
  801. }
  802. default:;
  803. }
  804. if (orientation == GUESS) {
  805. // Get sign of signed distance outside bounds
  806. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  807. double dummy;
  808. SignedDistance minDistance;
  809. for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
  810. for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
  811. SignedDistance distance = (*edge)->signedDistance(p, dummy);
  812. if (distance < minDistance)
  813. minDistance = distance;
  814. }
  815. orientation = minDistance.distance <= 0 ? KEEP : REVERSE;
  816. }
  817. if (orientation == REVERSE) {
  818. switch (mode) {
  819. case SINGLE:
  820. case PSEUDO:
  821. invertColor<1>(sdf);
  822. break;
  823. case MULTI:
  824. invertColor<3>(msdf);
  825. break;
  826. case MULTI_AND_TRUE:
  827. invertColor<4>(mtsdf);
  828. break;
  829. default:;
  830. }
  831. }
  832. if (scanlinePass) {
  833. switch (mode) {
  834. case SINGLE:
  835. case PSEUDO:
  836. distanceSignCorrection(sdf, shape, scale, translate, fillRule);
  837. break;
  838. case MULTI:
  839. distanceSignCorrection(msdf, shape, scale, translate, fillRule);
  840. if (edgeThreshold > 0)
  841. msdfErrorCorrection(msdf, edgeThreshold/(scale*range));
  842. msdfInterpolationErrorCorrection(msdf, shape, range, scale, translate, overlapSupport);
  843. break;
  844. case MULTI_AND_TRUE:
  845. distanceSignCorrection(mtsdf, shape, scale, translate, fillRule);
  846. if (edgeThreshold > 0)
  847. msdfErrorCorrection(mtsdf, edgeThreshold/(scale*range));
  848. msdfInterpolationErrorCorrection(mtsdf, shape, range, scale, translate, overlapSupport);
  849. break;
  850. default:;
  851. }
  852. }
  853. // Save output
  854. if (shapeExport) {
  855. FILE *file = fopen(shapeExport, "w");
  856. if (file) {
  857. writeShapeDescription(file, shape);
  858. fclose(file);
  859. } else
  860. puts("Failed to write shape export file.");
  861. }
  862. const char *error = NULL;
  863. switch (mode) {
  864. case SINGLE:
  865. case PSEUDO:
  866. error = writeOutput<1>(sdf, output, format);
  867. if (error)
  868. ABORT(error);
  869. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  870. simulate8bit(sdf);
  871. if (estimateError) {
  872. double sdfError = estimateSDFError(sdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  873. printf("SDF error ~ %e\n", sdfError);
  874. }
  875. if (testRenderMulti) {
  876. Bitmap<float, 3> render(testWidthM, testHeightM);
  877. renderSDF(render, sdf, avgScale*range);
  878. if (!savePng(render, testRenderMulti))
  879. puts("Failed to write test render file.");
  880. }
  881. if (testRender) {
  882. Bitmap<float, 1> render(testWidth, testHeight);
  883. renderSDF(render, sdf, avgScale*range);
  884. if (!savePng(render, testRender))
  885. puts("Failed to write test render file.");
  886. }
  887. break;
  888. case MULTI:
  889. error = writeOutput<3>(msdf, output, format);
  890. if (error)
  891. ABORT(error);
  892. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  893. simulate8bit(msdf);
  894. if (estimateError) {
  895. double sdfError = estimateSDFError(msdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  896. printf("SDF error ~ %e\n", sdfError);
  897. }
  898. if (testRenderMulti) {
  899. Bitmap<float, 3> render(testWidthM, testHeightM);
  900. renderSDF(render, msdf, avgScale*range);
  901. if (!savePng(render, testRenderMulti))
  902. puts("Failed to write test render file.");
  903. }
  904. if (testRender) {
  905. Bitmap<float, 1> render(testWidth, testHeight);
  906. renderSDF(render, msdf, avgScale*range);
  907. if (!savePng(render, testRender))
  908. ABORT("Failed to write test render file.");
  909. }
  910. break;
  911. case MULTI_AND_TRUE:
  912. error = writeOutput<4>(mtsdf, output, format);
  913. if (error)
  914. ABORT(error);
  915. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  916. simulate8bit(mtsdf);
  917. if (estimateError) {
  918. double sdfError = estimateSDFError(mtsdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  919. printf("SDF error ~ %e\n", sdfError);
  920. }
  921. if (testRenderMulti) {
  922. Bitmap<float, 4> render(testWidthM, testHeightM);
  923. renderSDF(render, mtsdf, avgScale*range);
  924. if (!savePng(render, testRenderMulti))
  925. puts("Failed to write test render file.");
  926. }
  927. if (testRender) {
  928. Bitmap<float, 1> render(testWidth, testHeight);
  929. renderSDF(render, mtsdf, avgScale*range);
  930. if (!savePng(render, testRender))
  931. ABORT("Failed to write test render file.");
  932. }
  933. break;
  934. default:;
  935. }
  936. return 0;
  937. }
  938. #endif