main.cpp 33 KB

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