main.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.4 (2017-02-09) - standalone console program
  3. * --------------------------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2017
  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. " -keeporder\n"
  278. "\tDisables the detection of shape orientation and keeps it as is.\n"
  279. " -legacy\n"
  280. "\tUses the original (legacy) distance field algorithms.\n"
  281. " -o <filename>\n"
  282. "\tSets the output file name. The default value is \"output.png\".\n"
  283. " -printmetrics\n"
  284. "\tPrints relevant metrics of the shape to the standard output.\n"
  285. " -pxrange <range>\n"
  286. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  287. " -range <range>\n"
  288. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  289. " -scale <scale>\n"
  290. "\tSets the scale used to convert shape units to pixels.\n"
  291. " -size <width> <height>\n"
  292. "\tSets the dimensions of the output image.\n"
  293. " -stdout\n"
  294. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  295. " -testrender <filename.png> <width> <height>\n"
  296. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  297. " -testrendermulti <filename.png> <width> <height>\n"
  298. "\tRenders an image preview without flattening the color channels.\n"
  299. " -translate <x> <y>\n"
  300. "\tSets the translation of the shape in shape units.\n"
  301. " -reverseorder\n"
  302. "\tDisables the detection of shape orientation and reverses the order of its vertices.\n"
  303. " -seed <n>\n"
  304. "\tSets the random seed for edge coloring heuristic.\n"
  305. " -yflip\n"
  306. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  307. "\n";
  308. int main(int argc, const char * const *argv) {
  309. #define ABORT(msg) { puts(msg); return 1; }
  310. // Parse command line arguments
  311. enum {
  312. NONE,
  313. SVG,
  314. FONT,
  315. DESCRIPTION_ARG,
  316. DESCRIPTION_STDIN,
  317. DESCRIPTION_FILE
  318. } inputType = NONE;
  319. enum {
  320. SINGLE,
  321. PSEUDO,
  322. MULTI,
  323. METRICS
  324. } mode = MULTI;
  325. bool legacyMode = false;
  326. Format format = AUTO;
  327. const char *input = NULL;
  328. const char *output = "output.png";
  329. const char *shapeExport = NULL;
  330. const char *testRender = NULL;
  331. const char *testRenderMulti = NULL;
  332. bool outputSpecified = false;
  333. int unicode = 0;
  334. int width = 64, height = 64;
  335. int testWidth = 0, testHeight = 0;
  336. int testWidthM = 0, testHeightM = 0;
  337. bool autoFrame = false;
  338. enum {
  339. RANGE_UNIT,
  340. RANGE_PX
  341. } rangeMode = RANGE_PX;
  342. double range = 1;
  343. double pxRange = 2;
  344. Vector2 translate;
  345. Vector2 scale = 1;
  346. bool scaleSpecified = false;
  347. double angleThreshold = 3;
  348. double edgeThreshold = 1.00000001;
  349. bool defEdgeAssignment = true;
  350. const char *edgeAssignment = NULL;
  351. bool yFlip = false;
  352. bool printMetrics = false;
  353. bool skipColoring = false;
  354. enum {
  355. KEEP,
  356. REVERSE,
  357. GUESS
  358. } orientation = GUESS;
  359. unsigned long long coloringSeed = 0;
  360. int argPos = 1;
  361. bool suggestHelp = false;
  362. while (argPos < argc) {
  363. const char *arg = argv[argPos];
  364. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  365. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  366. #define SETFORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  367. ARG_MODE("sdf", SINGLE)
  368. ARG_MODE("psdf", PSEUDO)
  369. ARG_MODE("msdf", MULTI)
  370. ARG_MODE("metrics", METRICS)
  371. ARG_CASE("-svg", 1) {
  372. inputType = SVG;
  373. input = argv[argPos+1];
  374. argPos += 2;
  375. continue;
  376. }
  377. ARG_CASE("-font", 2) {
  378. inputType = FONT;
  379. input = argv[argPos+1];
  380. parseUnicode(unicode, argv[argPos+2]);
  381. argPos += 3;
  382. continue;
  383. }
  384. ARG_CASE("-defineshape", 1) {
  385. inputType = DESCRIPTION_ARG;
  386. input = argv[argPos+1];
  387. argPos += 2;
  388. continue;
  389. }
  390. ARG_CASE("-stdin", 0) {
  391. inputType = DESCRIPTION_STDIN;
  392. input = "stdin";
  393. argPos += 1;
  394. continue;
  395. }
  396. ARG_CASE("-shapedesc", 1) {
  397. inputType = DESCRIPTION_FILE;
  398. input = argv[argPos+1];
  399. argPos += 2;
  400. continue;
  401. }
  402. ARG_CASE("-o", 1) {
  403. output = argv[argPos+1];
  404. outputSpecified = true;
  405. argPos += 2;
  406. continue;
  407. }
  408. ARG_CASE("-stdout", 0) {
  409. output = NULL;
  410. argPos += 1;
  411. continue;
  412. }
  413. ARG_CASE("-legacy", 0) {
  414. legacyMode = true;
  415. argPos += 1;
  416. continue;
  417. }
  418. ARG_CASE("-format", 1) {
  419. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  420. else if (!strcmp(argv[argPos+1], "png")) SETFORMAT(PNG, "png");
  421. else if (!strcmp(argv[argPos+1], "bmp")) SETFORMAT(BMP, "bmp");
  422. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SETFORMAT(TEXT, "txt");
  423. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SETFORMAT(TEXT_FLOAT, "txt");
  424. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SETFORMAT(BINARY, "bin");
  425. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SETFORMAT(BINARY_FLOAT, "bin");
  426. else if (!strcmp(argv[argPos+1], "binfloatbe")) SETFORMAT(BINART_FLOAT_BE, "bin");
  427. else
  428. puts("Unknown format specified.");
  429. argPos += 2;
  430. continue;
  431. }
  432. ARG_CASE("-size", 2) {
  433. unsigned w, h;
  434. if (!parseUnsigned(w, argv[argPos+1]) || !parseUnsigned(h, argv[argPos+2]) || !w || !h)
  435. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  436. width = w, height = h;
  437. argPos += 3;
  438. continue;
  439. }
  440. ARG_CASE("-autoframe", 0) {
  441. autoFrame = true;
  442. argPos += 1;
  443. continue;
  444. }
  445. ARG_CASE("-range", 1) {
  446. double r;
  447. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  448. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  449. rangeMode = RANGE_UNIT;
  450. range = r;
  451. argPos += 2;
  452. continue;
  453. }
  454. ARG_CASE("-pxrange", 1) {
  455. double r;
  456. if (!parseDouble(r, argv[argPos+1]) || r < 0)
  457. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  458. rangeMode = RANGE_PX;
  459. pxRange = r;
  460. argPos += 2;
  461. continue;
  462. }
  463. ARG_CASE("-scale", 1) {
  464. double s;
  465. if (!parseDouble(s, argv[argPos+1]) || s <= 0)
  466. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  467. scale = s;
  468. scaleSpecified = true;
  469. argPos += 2;
  470. continue;
  471. }
  472. ARG_CASE("-ascale", 2) {
  473. double sx, sy;
  474. if (!parseDouble(sx, argv[argPos+1]) || !parseDouble(sy, argv[argPos+2]) || sx <= 0 || sy <= 0)
  475. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  476. scale.set(sx, sy);
  477. scaleSpecified = true;
  478. argPos += 3;
  479. continue;
  480. }
  481. ARG_CASE("-translate", 2) {
  482. double tx, ty;
  483. if (!parseDouble(tx, argv[argPos+1]) || !parseDouble(ty, argv[argPos+2]))
  484. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  485. translate.set(tx, ty);
  486. argPos += 3;
  487. continue;
  488. }
  489. ARG_CASE("-angle", 1) {
  490. double at;
  491. if (!parseAngle(at, argv[argPos+1]))
  492. 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.");
  493. angleThreshold = at;
  494. argPos += 2;
  495. continue;
  496. }
  497. ARG_CASE("-errorcorrection", 1) {
  498. double et;
  499. if (!parseDouble(et, argv[argPos+1]) || et < 0)
  500. ABORT("Invalid error correction threshold. Use -errorcorrection <threshold> with a real number larger or equal to 1.");
  501. edgeThreshold = et;
  502. argPos += 2;
  503. continue;
  504. }
  505. ARG_CASE("-edgecolors", 1) {
  506. static const char *allowed = " ?,cmyCMY";
  507. for (int i = 0; argv[argPos+1][i]; ++i) {
  508. for (int j = 0; allowed[j]; ++j)
  509. if (argv[argPos+1][i] == allowed[j])
  510. goto ROLL_ARG;
  511. 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.");
  512. ROLL_ARG:;
  513. }
  514. edgeAssignment = argv[argPos+1];
  515. argPos += 2;
  516. continue;
  517. }
  518. ARG_CASE("-exportshape", 1) {
  519. shapeExport = argv[argPos+1];
  520. argPos += 2;
  521. continue;
  522. }
  523. ARG_CASE("-testrender", 3) {
  524. unsigned w, h;
  525. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  526. ABORT("Invalid arguments for test render. Use -testrender <output.png> <width> <height>.");
  527. testRender = argv[argPos+1];
  528. testWidth = w, testHeight = h;
  529. argPos += 4;
  530. continue;
  531. }
  532. ARG_CASE("-testrendermulti", 3) {
  533. unsigned w, h;
  534. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  535. ABORT("Invalid arguments for test render. Use -testrendermulti <output.png> <width> <height>.");
  536. testRenderMulti = argv[argPos+1];
  537. testWidthM = w, testHeightM = h;
  538. argPos += 4;
  539. continue;
  540. }
  541. ARG_CASE("-yflip", 0) {
  542. yFlip = true;
  543. argPos += 1;
  544. continue;
  545. }
  546. ARG_CASE("-printmetrics", 0) {
  547. printMetrics = true;
  548. argPos += 1;
  549. continue;
  550. }
  551. ARG_CASE("-keeporder", 0) {
  552. orientation = KEEP;
  553. argPos += 1;
  554. continue;
  555. }
  556. ARG_CASE("-reverseorder", 0) {
  557. orientation = REVERSE;
  558. argPos += 1;
  559. continue;
  560. }
  561. ARG_CASE("-guessorder", 0) {
  562. orientation = GUESS;
  563. argPos += 1;
  564. continue;
  565. }
  566. ARG_CASE("-seed", 1) {
  567. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  568. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  569. argPos += 2;
  570. continue;
  571. }
  572. ARG_CASE("-help", 0)
  573. ABORT(helpText);
  574. printf("Unknown setting or insufficient parameters: %s\n", arg);
  575. suggestHelp = true;
  576. ++argPos;
  577. }
  578. if (suggestHelp)
  579. printf("Use -help for more information.\n");
  580. // Load input
  581. Vector2 svgDims;
  582. double glyphAdvance = 0;
  583. if (!inputType || !input)
  584. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  585. Shape shape;
  586. switch (inputType) {
  587. case SVG: {
  588. if (!loadSvgShape(shape, input, &svgDims))
  589. ABORT("Failed to load shape from SVG file.");
  590. break;
  591. }
  592. case FONT: {
  593. if (!unicode)
  594. 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').");
  595. FreetypeHandle *ft = initializeFreetype();
  596. if (!ft) return -1;
  597. FontHandle *font = loadFont(ft, input);
  598. if (!font) {
  599. deinitializeFreetype(ft);
  600. ABORT("Failed to load font file.");
  601. }
  602. if (!loadGlyph(shape, font, unicode, &glyphAdvance)) {
  603. destroyFont(font);
  604. deinitializeFreetype(ft);
  605. ABORT("Failed to load glyph from font file.");
  606. }
  607. destroyFont(font);
  608. deinitializeFreetype(ft);
  609. break;
  610. }
  611. case DESCRIPTION_ARG: {
  612. if (!readShapeDescription(input, shape, &skipColoring))
  613. ABORT("Parse error in shape description.");
  614. break;
  615. }
  616. case DESCRIPTION_STDIN: {
  617. if (!readShapeDescription(stdin, shape, &skipColoring))
  618. ABORT("Parse error in shape description.");
  619. break;
  620. }
  621. case DESCRIPTION_FILE: {
  622. FILE *file = fopen(input, "r");
  623. if (!file)
  624. ABORT("Failed to load shape description file.");
  625. if (!readShapeDescription(file, shape, &skipColoring))
  626. ABORT("Parse error in shape description.");
  627. fclose(file);
  628. break;
  629. }
  630. default:
  631. break;
  632. }
  633. // Validate and normalize shape
  634. if (!shape.validate())
  635. ABORT("The geometry of the loaded shape is invalid.");
  636. shape.normalize();
  637. if (yFlip)
  638. shape.inverseYAxis = !shape.inverseYAxis;
  639. double avgScale = .5*(scale.x+scale.y);
  640. struct {
  641. double l, b, r, t;
  642. } bounds = {
  643. LARGE_VALUE, LARGE_VALUE, -LARGE_VALUE, -LARGE_VALUE
  644. };
  645. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  646. shape.bounds(bounds.l, bounds.b, bounds.r, bounds.t);
  647. // Auto-frame
  648. if (autoFrame) {
  649. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  650. Vector2 frame(width, height);
  651. if (rangeMode == RANGE_UNIT)
  652. l -= range, b -= range, r += range, t += range;
  653. else if (!scaleSpecified)
  654. frame -= 2*pxRange;
  655. if (l >= r || b >= t)
  656. l = 0, b = 0, r = 1, t = 1;
  657. if (frame.x <= 0 || frame.y <= 0)
  658. ABORT("Cannot fit the specified pixel range.");
  659. Vector2 dims(r-l, t-b);
  660. if (scaleSpecified)
  661. translate = .5*(frame/scale-dims)-Vector2(l, b);
  662. else {
  663. if (dims.x*frame.y < dims.y*frame.x) {
  664. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  665. scale = avgScale = frame.y/dims.y;
  666. } else {
  667. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  668. scale = avgScale = frame.x/dims.x;
  669. }
  670. }
  671. if (rangeMode == RANGE_PX && !scaleSpecified)
  672. translate += pxRange/scale;
  673. }
  674. if (rangeMode == RANGE_PX)
  675. range = pxRange/min(scale.x, scale.y);
  676. // Print metrics
  677. if (mode == METRICS || printMetrics) {
  678. FILE *out = stdout;
  679. if (mode == METRICS && outputSpecified)
  680. out = fopen(output, "w");
  681. if (!out)
  682. ABORT("Failed to write output file.");
  683. if (shape.inverseYAxis)
  684. fprintf(out, "inverseY = true\n");
  685. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  686. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  687. if (svgDims.x != 0 && svgDims.y != 0)
  688. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  689. if (glyphAdvance != 0)
  690. fprintf(out, "advance = %.12g\n", glyphAdvance);
  691. if (autoFrame) {
  692. if (!scaleSpecified)
  693. fprintf(out, "scale = %.12g\n", avgScale);
  694. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  695. }
  696. if (rangeMode == RANGE_PX)
  697. fprintf(out, "range = %.12g\n", range);
  698. if (mode == METRICS && outputSpecified)
  699. fclose(out);
  700. }
  701. // Compute output
  702. Bitmap<float> sdf;
  703. Bitmap<FloatRGB> msdf;
  704. switch (mode) {
  705. case SINGLE: {
  706. sdf = Bitmap<float>(width, height);
  707. if (legacyMode)
  708. generateSDF_legacy(sdf, shape, range, scale, translate);
  709. else
  710. generateSDF(sdf, shape, range, scale, translate);
  711. break;
  712. }
  713. case PSEUDO: {
  714. sdf = Bitmap<float>(width, height);
  715. if (legacyMode)
  716. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  717. else
  718. generatePseudoSDF(sdf, shape, range, scale, translate);
  719. break;
  720. }
  721. case MULTI: {
  722. if (!skipColoring)
  723. edgeColoringSimple(shape, angleThreshold, coloringSeed);
  724. if (edgeAssignment)
  725. parseColoring(shape, edgeAssignment);
  726. msdf = Bitmap<FloatRGB>(width, height);
  727. if (legacyMode)
  728. generateMSDF_legacy(msdf, shape, range, scale, translate, edgeThreshold);
  729. else
  730. generateMSDF(msdf, shape, range, scale, translate, edgeThreshold);
  731. break;
  732. }
  733. default:
  734. break;
  735. }
  736. if (orientation == GUESS) {
  737. // Get sign of signed distance outside bounds
  738. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  739. double dummy;
  740. SignedDistance minDistance;
  741. for (std::vector<Contour>::const_iterator contour = shape.contours.begin(); contour != shape.contours.end(); ++contour)
  742. for (std::vector<EdgeHolder>::const_iterator edge = contour->edges.begin(); edge != contour->edges.end(); ++edge) {
  743. SignedDistance distance = (*edge)->signedDistance(p, dummy);
  744. if (distance < minDistance)
  745. minDistance = distance;
  746. }
  747. orientation = minDistance.distance <= 0 ? KEEP : REVERSE;
  748. }
  749. if (orientation == REVERSE) {
  750. invertColor(sdf);
  751. invertColor(msdf);
  752. }
  753. // Save output
  754. if (shapeExport) {
  755. FILE *file = fopen(shapeExport, "w");
  756. if (file) {
  757. writeShapeDescription(file, shape);
  758. fclose(file);
  759. } else
  760. puts("Failed to write shape export file.");
  761. }
  762. const char *error = NULL;
  763. switch (mode) {
  764. case SINGLE:
  765. case PSEUDO:
  766. error = writeOutput(sdf, output, format);
  767. if (error)
  768. ABORT(error);
  769. if (testRenderMulti || testRender)
  770. simulate8bit(sdf);
  771. if (testRenderMulti) {
  772. Bitmap<FloatRGB> render(testWidthM, testHeightM);
  773. renderSDF(render, sdf, avgScale*range);
  774. if (!savePng(render, testRenderMulti))
  775. puts("Failed to write test render file.");
  776. }
  777. if (testRender) {
  778. Bitmap<float> render(testWidth, testHeight);
  779. renderSDF(render, sdf, avgScale*range);
  780. if (!savePng(render, testRender))
  781. puts("Failed to write test render file.");
  782. }
  783. break;
  784. case MULTI:
  785. error = writeOutput(msdf, output, format);
  786. if (error)
  787. ABORT(error);
  788. if (testRenderMulti || testRender)
  789. simulate8bit(msdf);
  790. if (testRenderMulti) {
  791. Bitmap<FloatRGB> render(testWidthM, testHeightM);
  792. renderSDF(render, msdf, avgScale*range);
  793. if (!savePng(render, testRenderMulti))
  794. puts("Failed to write test render file.");
  795. }
  796. if (testRender) {
  797. Bitmap<float> render(testWidth, testHeight);
  798. renderSDF(render, msdf, avgScale*range);
  799. if (!savePng(render, testRender))
  800. ABORT("Failed to write test render file.");
  801. }
  802. break;
  803. default:
  804. break;
  805. }
  806. return 0;
  807. }
  808. #endif