main.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  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. // Load input
  639. Vector2 svgDims;
  640. double glyphAdvance = 0;
  641. if (!inputType || !input)
  642. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  643. if (mode == MULTI_AND_TRUE && (format == BMP || format == AUTO && output && cmpExtension(output, ".bmp")))
  644. ABORT("Incompatible image format. A BMP file cannot contain alpha channel, which is required in mtsdf mode.");
  645. Shape shape;
  646. switch (inputType) {
  647. case SVG: {
  648. if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
  649. ABORT("Failed to load shape from SVG file.");
  650. break;
  651. }
  652. case FONT: {
  653. if (!unicode)
  654. 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').");
  655. FreetypeHandle *ft = initializeFreetype();
  656. if (!ft) return -1;
  657. FontHandle *font = loadFont(ft, input);
  658. if (!font) {
  659. deinitializeFreetype(ft);
  660. ABORT("Failed to load font file.");
  661. }
  662. if (!loadGlyph(shape, font, unicode, &glyphAdvance)) {
  663. destroyFont(font);
  664. deinitializeFreetype(ft);
  665. ABORT("Failed to load glyph from font file.");
  666. }
  667. destroyFont(font);
  668. deinitializeFreetype(ft);
  669. break;
  670. }
  671. case DESCRIPTION_ARG: {
  672. if (!readShapeDescription(input, shape, &skipColoring))
  673. ABORT("Parse error in shape description.");
  674. break;
  675. }
  676. case DESCRIPTION_STDIN: {
  677. if (!readShapeDescription(stdin, shape, &skipColoring))
  678. ABORT("Parse error in shape description.");
  679. break;
  680. }
  681. case DESCRIPTION_FILE: {
  682. FILE *file = fopen(input, "r");
  683. if (!file)
  684. ABORT("Failed to load shape description file.");
  685. if (!readShapeDescription(file, shape, &skipColoring))
  686. ABORT("Parse error in shape description.");
  687. fclose(file);
  688. break;
  689. }
  690. default:;
  691. }
  692. // Validate and normalize shape
  693. if (!shape.validate())
  694. ABORT("The geometry of the loaded shape is invalid.");
  695. shape.normalize();
  696. if (yFlip)
  697. shape.inverseYAxis = !shape.inverseYAxis;
  698. double avgScale = .5*(scale.x+scale.y);
  699. Shape::Bounds bounds = { };
  700. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  701. bounds = shape.getBounds();
  702. // Auto-frame
  703. if (autoFrame) {
  704. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  705. Vector2 frame(width, height);
  706. if (rangeMode == RANGE_UNIT)
  707. l -= .5*range, b -= .5*range, r += .5*range, t += .5*range;
  708. else if (!scaleSpecified)
  709. frame -= pxRange;
  710. if (l >= r || b >= t)
  711. l = 0, b = 0, r = 1, t = 1;
  712. if (frame.x <= 0 || frame.y <= 0)
  713. ABORT("Cannot fit the specified pixel range.");
  714. Vector2 dims(r-l, t-b);
  715. if (scaleSpecified)
  716. translate = .5*(frame/scale-dims)-Vector2(l, b);
  717. else {
  718. if (dims.x*frame.y < dims.y*frame.x) {
  719. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  720. scale = avgScale = frame.y/dims.y;
  721. } else {
  722. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  723. scale = avgScale = frame.x/dims.x;
  724. }
  725. }
  726. if (rangeMode == RANGE_PX && !scaleSpecified)
  727. translate += .5*pxRange/scale;
  728. }
  729. if (rangeMode == RANGE_PX)
  730. range = pxRange/min(scale.x, scale.y);
  731. // Print metrics
  732. if (mode == METRICS || printMetrics) {
  733. FILE *out = stdout;
  734. if (mode == METRICS && outputSpecified)
  735. out = fopen(output, "w");
  736. if (!out)
  737. ABORT("Failed to write output file.");
  738. if (shape.inverseYAxis)
  739. fprintf(out, "inverseY = true\n");
  740. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  741. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  742. if (svgDims.x != 0 && svgDims.y != 0)
  743. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  744. if (glyphAdvance != 0)
  745. fprintf(out, "advance = %.12g\n", glyphAdvance);
  746. if (autoFrame) {
  747. if (!scaleSpecified)
  748. fprintf(out, "scale = %.12g\n", avgScale);
  749. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  750. }
  751. if (rangeMode == RANGE_PX)
  752. fprintf(out, "range = %.12g\n", range);
  753. if (mode == METRICS && outputSpecified)
  754. fclose(out);
  755. }
  756. // Compute output
  757. Bitmap<float, 1> sdf;
  758. Bitmap<float, 3> msdf;
  759. Bitmap<float, 4> mtsdf;
  760. switch (mode) {
  761. case SINGLE: {
  762. sdf = Bitmap<float, 1>(width, height);
  763. if (legacyMode)
  764. generateSDF_legacy(sdf, shape, range, scale, translate);
  765. else
  766. generateSDF(sdf, shape, range, scale, translate, overlapSupport);
  767. break;
  768. }
  769. case PSEUDO: {
  770. sdf = Bitmap<float, 1>(width, height);
  771. if (legacyMode)
  772. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  773. else
  774. generatePseudoSDF(sdf, shape, range, scale, translate, overlapSupport);
  775. break;
  776. }
  777. case MULTI: {
  778. if (!skipColoring)
  779. edgeColoring(shape, angleThreshold, coloringSeed);
  780. if (edgeAssignment)
  781. parseColoring(shape, edgeAssignment);
  782. msdf = Bitmap<float, 3>(width, height);
  783. if (legacyMode)
  784. generateMSDF_legacy(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold);
  785. else
  786. generateMSDF(msdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold, overlapSupport);
  787. break;
  788. }
  789. case MULTI_AND_TRUE: {
  790. if (!skipColoring)
  791. edgeColoring(shape, angleThreshold, coloringSeed);
  792. if (edgeAssignment)
  793. parseColoring(shape, edgeAssignment);
  794. mtsdf = Bitmap<float, 4>(width, height);
  795. if (legacyMode)
  796. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold);
  797. else
  798. generateMTSDF(mtsdf, shape, range, scale, translate, scanlinePass ? 0 : edgeThreshold, overlapSupport);
  799. break;
  800. }
  801. default:;
  802. }
  803. if (orientation == GUESS) {
  804. // Get sign of signed distance outside bounds
  805. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  806. double dummy;
  807. SignedDistance minDistance;
  808. for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
  809. for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
  810. SignedDistance distance = (*edge)->signedDistance(p, dummy);
  811. if (distance < minDistance)
  812. minDistance = distance;
  813. }
  814. orientation = minDistance.distance <= 0 ? KEEP : REVERSE;
  815. }
  816. if (orientation == REVERSE) {
  817. switch (mode) {
  818. case SINGLE:
  819. case PSEUDO:
  820. invertColor<1>(sdf);
  821. break;
  822. case MULTI:
  823. invertColor<3>(msdf);
  824. break;
  825. case MULTI_AND_TRUE:
  826. invertColor<4>(mtsdf);
  827. break;
  828. default:;
  829. }
  830. }
  831. if (scanlinePass) {
  832. switch (mode) {
  833. case SINGLE:
  834. case PSEUDO:
  835. distanceSignCorrection(sdf, shape, scale, translate, fillRule);
  836. break;
  837. case MULTI:
  838. distanceSignCorrection(msdf, shape, scale, translate, fillRule);
  839. if (edgeThreshold > 0)
  840. msdfErrorCorrection(msdf, edgeThreshold/(scale*range));
  841. break;
  842. case MULTI_AND_TRUE:
  843. distanceSignCorrection(mtsdf, shape, scale, translate, fillRule);
  844. if (edgeThreshold > 0)
  845. msdfErrorCorrection(mtsdf, edgeThreshold/(scale*range));
  846. break;
  847. default:;
  848. }
  849. }
  850. // Save output
  851. if (shapeExport) {
  852. FILE *file = fopen(shapeExport, "w");
  853. if (file) {
  854. writeShapeDescription(file, shape);
  855. fclose(file);
  856. } else
  857. puts("Failed to write shape export file.");
  858. }
  859. const char *error = NULL;
  860. switch (mode) {
  861. case SINGLE:
  862. case PSEUDO:
  863. error = writeOutput<1>(sdf, output, format);
  864. if (error)
  865. ABORT(error);
  866. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  867. simulate8bit(sdf);
  868. if (estimateError) {
  869. double sdfError = estimateSDFError(sdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  870. printf("SDF error ~ %e\n", sdfError);
  871. }
  872. if (testRenderMulti) {
  873. Bitmap<float, 3> render(testWidthM, testHeightM);
  874. renderSDF(render, sdf, avgScale*range);
  875. if (!savePng(render, testRenderMulti))
  876. puts("Failed to write test render file.");
  877. }
  878. if (testRender) {
  879. Bitmap<float, 1> render(testWidth, testHeight);
  880. renderSDF(render, sdf, avgScale*range);
  881. if (!savePng(render, testRender))
  882. puts("Failed to write test render file.");
  883. }
  884. break;
  885. case MULTI:
  886. error = writeOutput<3>(msdf, output, format);
  887. if (error)
  888. ABORT(error);
  889. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  890. simulate8bit(msdf);
  891. if (estimateError) {
  892. double sdfError = estimateSDFError(msdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  893. printf("SDF error ~ %e\n", sdfError);
  894. }
  895. if (testRenderMulti) {
  896. Bitmap<float, 3> render(testWidthM, testHeightM);
  897. renderSDF(render, msdf, avgScale*range);
  898. if (!savePng(render, testRenderMulti))
  899. puts("Failed to write test render file.");
  900. }
  901. if (testRender) {
  902. Bitmap<float, 1> render(testWidth, testHeight);
  903. renderSDF(render, msdf, avgScale*range);
  904. if (!savePng(render, testRender))
  905. ABORT("Failed to write test render file.");
  906. }
  907. break;
  908. case MULTI_AND_TRUE:
  909. error = writeOutput<4>(mtsdf, output, format);
  910. if (error)
  911. ABORT(error);
  912. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  913. simulate8bit(mtsdf);
  914. if (estimateError) {
  915. double sdfError = estimateSDFError(mtsdf, shape, scale, translate, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  916. printf("SDF error ~ %e\n", sdfError);
  917. }
  918. if (testRenderMulti) {
  919. Bitmap<float, 4> render(testWidthM, testHeightM);
  920. renderSDF(render, mtsdf, avgScale*range);
  921. if (!savePng(render, testRenderMulti))
  922. puts("Failed to write test render file.");
  923. }
  924. if (testRender) {
  925. Bitmap<float, 1> render(testWidth, testHeight);
  926. renderSDF(render, mtsdf, avgScale*range);
  927. if (!savePng(render, testRender))
  928. ABORT("Failed to write test render file.");
  929. }
  930. break;
  931. default:;
  932. }
  933. return 0;
  934. }
  935. #endif