main.cpp 29 KB

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