main.cpp 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216
  1. /*
  2. * MULTI-CHANNEL SIGNED DISTANCE FIELD GENERATOR v1.9 (2021-05-28) - standalone console program
  3. * --------------------------------------------------------------------------------------------
  4. * A utility by Viktor Chlumsky, (c) 2014 - 2021
  5. *
  6. */
  7. #ifdef MSDFGEN_STANDALONE
  8. #define _USE_MATH_DEFINES
  9. #define _CRT_SECURE_NO_WARNINGS
  10. #include <cstdio>
  11. #include <cmath>
  12. #include <cstring>
  13. #include <string>
  14. #include "msdfgen.h"
  15. #include "msdfgen-ext.h"
  16. #include "core/ShapeDistanceFinder.h"
  17. #define SDF_ERROR_ESTIMATE_PRECISION 19
  18. #define DEFAULT_ANGLE_THRESHOLD 3.
  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. BINARY_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. char c;
  39. return sscanf(arg, "%u%c", &value, &c) == 1;
  40. }
  41. static bool parseUnsignedDecOrHex(unsigned &value, const char *arg) {
  42. if (arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
  43. char c;
  44. return sscanf(arg+2, "%x%c", &value, &c) == 1;
  45. }
  46. return parseUnsigned(value, arg);
  47. }
  48. static bool parseUnsignedLL(unsigned long long &value, const char *arg) {
  49. char c;
  50. return sscanf(arg, "%llu%c", &value, &c) == 1;
  51. }
  52. static bool parseDouble(double &value, const char *arg) {
  53. char c;
  54. return sscanf(arg, "%lf%c", &value, &c) == 1;
  55. }
  56. static bool parseUnicode(unicode_t &unicode, const char *arg) {
  57. unsigned uuc;
  58. if (parseUnsignedDecOrHex(uuc, arg)) {
  59. unicode = uuc;
  60. return true;
  61. }
  62. if (arg[0] == '\'' && arg[1] && arg[2] == '\'' && !arg[3]) {
  63. unicode = (unicode_t) (unsigned char) arg[1];
  64. return true;
  65. }
  66. return false;
  67. }
  68. static bool parseAngle(double &value, const char *arg) {
  69. char c1, c2;
  70. int result = sscanf(arg, "%lf%c%c", &value, &c1, &c2);
  71. if (result == 1)
  72. return true;
  73. if (result == 2 && (c1 == 'd' || c1 == 'D')) {
  74. value *= M_PI/180;
  75. return true;
  76. }
  77. return false;
  78. }
  79. static void parseColoring(Shape &shape, const char *edgeAssignment) {
  80. unsigned c = 0, e = 0;
  81. if (shape.contours.size() < c) return;
  82. Contour *contour = &shape.contours[c];
  83. bool change = false;
  84. bool clear = true;
  85. for (const char *in = edgeAssignment; *in; ++in) {
  86. switch (*in) {
  87. case ',':
  88. if (change)
  89. ++e;
  90. if (clear)
  91. while (e < contour->edges.size()) {
  92. contour->edges[e]->color = WHITE;
  93. ++e;
  94. }
  95. ++c, e = 0;
  96. if (shape.contours.size() <= c) return;
  97. contour = &shape.contours[c];
  98. change = false;
  99. clear = true;
  100. break;
  101. case '?':
  102. clear = false;
  103. break;
  104. case 'C': case 'M': case 'W': case 'Y': case 'c': case 'm': case 'w': case 'y':
  105. if (change) {
  106. ++e;
  107. change = false;
  108. }
  109. if (e < contour->edges.size()) {
  110. contour->edges[e]->color = EdgeColor(
  111. (*in == 'C' || *in == 'c')*CYAN|
  112. (*in == 'M' || *in == 'm')*MAGENTA|
  113. (*in == 'Y' || *in == 'y')*YELLOW|
  114. (*in == 'W' || *in == 'w')*WHITE);
  115. change = true;
  116. }
  117. break;
  118. }
  119. }
  120. }
  121. static FontHandle * loadVarFont(FreetypeHandle *library, const char *filename) {
  122. std::string buffer;
  123. while (*filename && *filename != '?')
  124. buffer.push_back(*filename++);
  125. FontHandle *font = loadFont(library, buffer.c_str());
  126. if (*filename++ == '?') {
  127. do {
  128. buffer.clear();
  129. while (*filename && *filename != '=')
  130. buffer.push_back(*filename++);
  131. if (*filename == '=') {
  132. double value = 0;
  133. int skip = 0;
  134. if (sscanf(++filename, "%lf%n", &value, &skip) == 1) {
  135. setFontVariationAxis(library, font, buffer.c_str(), value);
  136. filename += skip;
  137. }
  138. }
  139. } while (*filename++ == '&');
  140. }
  141. return font;
  142. }
  143. template <int N>
  144. static void invertColor(const BitmapRef<float, N> &bitmap) {
  145. const float *end = bitmap.pixels+N*bitmap.width*bitmap.height;
  146. for (float *p = bitmap.pixels; p < end; ++p)
  147. *p = 1.f-*p;
  148. }
  149. static bool writeTextBitmap(FILE *file, const float *values, int cols, int rows) {
  150. for (int row = 0; row < rows; ++row) {
  151. for (int col = 0; col < cols; ++col) {
  152. int v = clamp(int((*values++)*0x100), 0xff);
  153. fprintf(file, col ? " %02X" : "%02X", v);
  154. }
  155. fprintf(file, "\n");
  156. }
  157. return true;
  158. }
  159. static bool writeTextBitmapFloat(FILE *file, const float *values, int cols, int rows) {
  160. for (int row = 0; row < rows; ++row) {
  161. for (int col = 0; col < cols; ++col) {
  162. fprintf(file, col ? " %.9g" : "%.9g", *values++);
  163. }
  164. fprintf(file, "\n");
  165. }
  166. return true;
  167. }
  168. static bool writeBinBitmap(FILE *file, const float *values, int count) {
  169. for (int pos = 0; pos < count; ++pos) {
  170. unsigned char v = clamp(int((*values++)*0x100), 0xff);
  171. fwrite(&v, 1, 1, file);
  172. }
  173. return true;
  174. }
  175. #ifdef __BIG_ENDIAN__
  176. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  177. #else
  178. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  179. #endif
  180. {
  181. return (int) fwrite(values, sizeof(float), count, file) == count;
  182. }
  183. #ifdef __BIG_ENDIAN__
  184. static bool writeBinBitmapFloat(FILE *file, const float *values, int count)
  185. #else
  186. static bool writeBinBitmapFloatBE(FILE *file, const float *values, int count)
  187. #endif
  188. {
  189. for (int pos = 0; pos < count; ++pos) {
  190. const unsigned char *b = reinterpret_cast<const unsigned char *>(values++);
  191. for (int i = sizeof(float)-1; i >= 0; --i)
  192. fwrite(b+i, 1, 1, file);
  193. }
  194. return true;
  195. }
  196. static bool cmpExtension(const char *path, const char *ext) {
  197. for (const char *a = path+strlen(path)-1, *b = ext+strlen(ext)-1; b >= ext; --a, --b)
  198. if (a < path || toupper(*a) != toupper(*b))
  199. return false;
  200. return true;
  201. }
  202. template <int N>
  203. static const char * writeOutput(const BitmapConstRef<float, N> &bitmap, const char *filename, Format &format) {
  204. if (filename) {
  205. if (format == AUTO) {
  206. if (cmpExtension(filename, ".png")) format = PNG;
  207. else if (cmpExtension(filename, ".bmp")) format = BMP;
  208. else if (cmpExtension(filename, ".tif") || cmpExtension(filename, ".tiff")) format = TIFF;
  209. else if (cmpExtension(filename, ".txt")) format = TEXT;
  210. else if (cmpExtension(filename, ".bin")) format = BINARY;
  211. else
  212. return "Could not deduce format from output file name.";
  213. }
  214. switch (format) {
  215. case PNG: return savePng(bitmap, filename) ? NULL : "Failed to write output PNG image.";
  216. case BMP: return saveBmp(bitmap, filename) ? NULL : "Failed to write output BMP image.";
  217. case TIFF: return saveTiff(bitmap, filename) ? NULL : "Failed to write output TIFF image.";
  218. case TEXT: case TEXT_FLOAT: {
  219. FILE *file = fopen(filename, "w");
  220. if (!file) return "Failed to write output text file.";
  221. if (format == TEXT)
  222. writeTextBitmap(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  223. else if (format == TEXT_FLOAT)
  224. writeTextBitmapFloat(file, bitmap.pixels, N*bitmap.width, bitmap.height);
  225. fclose(file);
  226. return NULL;
  227. }
  228. case BINARY: case BINARY_FLOAT: case BINARY_FLOAT_BE: {
  229. FILE *file = fopen(filename, "wb");
  230. if (!file) return "Failed to write output binary file.";
  231. if (format == BINARY)
  232. writeBinBitmap(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  233. else if (format == BINARY_FLOAT)
  234. writeBinBitmapFloat(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  235. else if (format == BINARY_FLOAT_BE)
  236. writeBinBitmapFloatBE(file, bitmap.pixels, N*bitmap.width*bitmap.height);
  237. fclose(file);
  238. return NULL;
  239. }
  240. default:;
  241. }
  242. } else {
  243. if (format == AUTO || format == TEXT)
  244. writeTextBitmap(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  245. else if (format == TEXT_FLOAT)
  246. writeTextBitmapFloat(stdout, bitmap.pixels, N*bitmap.width, bitmap.height);
  247. else
  248. return "Unsupported format for standard output.";
  249. }
  250. return NULL;
  251. }
  252. #if defined(MSDFGEN_USE_SKIA) && defined(MSDFGEN_USE_OPENMP)
  253. #define TITLE_SUFFIX " with Skia & OpenMP"
  254. #define EXTRA_UNDERLINE "-------------------"
  255. #elif defined(MSDFGEN_USE_SKIA)
  256. #define TITLE_SUFFIX " with Skia"
  257. #define EXTRA_UNDERLINE "----------"
  258. #elif defined(MSDFGEN_USE_OPENMP)
  259. #define TITLE_SUFFIX " with OpenMP"
  260. #define EXTRA_UNDERLINE "------------"
  261. #else
  262. #define TITLE_SUFFIX
  263. #define EXTRA_UNDERLINE
  264. #endif
  265. static const char *helpText =
  266. "\n"
  267. "Multi-channel signed distance field generator by Viktor Chlumsky v" MSDFGEN_VERSION TITLE_SUFFIX "\n"
  268. "---------------------------------------------------------------------" EXTRA_UNDERLINE "\n"
  269. " Usage: msdfgen"
  270. #ifdef _WIN32
  271. ".exe"
  272. #endif
  273. " <mode> <input specification> <options>\n"
  274. "\n"
  275. "MODES\n"
  276. " sdf - Generate conventional monochrome (true) signed distance field.\n"
  277. " psdf - Generate monochrome signed pseudo-distance field.\n"
  278. " msdf - Generate multi-channel signed distance field. This is used by default if no mode is specified.\n"
  279. " mtsdf - Generate combined multi-channel and true signed distance field in the alpha channel.\n"
  280. " metrics - Report shape metrics only.\n"
  281. "\n"
  282. "INPUT SPECIFICATION\n"
  283. " -defineshape <definition>\n"
  284. "\tDefines input shape using the ad-hoc text definition.\n"
  285. " -font <filename.ttf> <character code>\n"
  286. "\tLoads a single glyph from the specified font file.\n"
  287. "\tFormat of character code is '?', 63, 0x3F (Unicode value), or g34 (glyph index).\n"
  288. " -shapedesc <filename.txt>\n"
  289. "\tLoads text shape description from a file.\n"
  290. " -stdin\n"
  291. "\tReads text shape description from the standard input.\n"
  292. " -svg <filename.svg>\n"
  293. "\tLoads the last vector path found in the specified SVG file.\n"
  294. " -varfont <filename and variables> <character code>\n"
  295. "\tLoads a single glyph from a variable font. Specify variable values as x.ttf?var1=0.5&var2=1\n"
  296. "\n"
  297. // Keep alphabetical order!
  298. "OPTIONS\n"
  299. " -angle <angle>\n"
  300. "\tSpecifies the minimum angle between adjacent edges to be considered a corner. Append D for degrees.\n"
  301. " -ascale <x scale> <y scale>\n"
  302. "\tSets the scale used to convert shape units to pixels asymmetrically.\n"
  303. " -autoframe\n"
  304. "\tAutomatically scales (unless specified) and translates the shape to fit.\n"
  305. " -coloringstrategy <simple / inktrap / distance>\n"
  306. "\tSelects the strategy of the edge coloring heuristic.\n"
  307. " -distanceshift <shift>\n"
  308. "\tShifts all normalized distances in the output distance field by this value.\n"
  309. " -edgecolors <sequence>\n"
  310. "\tOverrides automatic edge coloring with the specified color sequence.\n"
  311. " -errorcorrection <mode>\n"
  312. "\tChanges the MSDF/MTSDF error correction mode. Use -errorcorrection help for a list of valid modes.\n"
  313. " -errordeviationratio <ratio>\n"
  314. "\tSets the minimum ratio between the actual and maximum expected distance delta to be considered an error.\n"
  315. " -errorimproveratio <ratio>\n"
  316. "\tSets the minimum ratio between the pre-correction distance error and the post-correction distance error.\n"
  317. " -estimateerror\n"
  318. "\tComputes and prints the distance field's estimated fill error to the standard output.\n"
  319. " -exportshape <filename.txt>\n"
  320. "\tSaves the shape description into a text file that can be edited and loaded using -shapedesc.\n"
  321. " -fillrule <nonzero / evenodd / positive / negative>\n"
  322. "\tSets the fill rule for the scanline pass. Default is nonzero.\n"
  323. " -format <png / bmp / tiff / text / textfloat / bin / binfloat / binfloatbe>\n"
  324. "\tSpecifies the output format of the distance field. Otherwise it is chosen based on output file extension.\n"
  325. " -guessorder\n"
  326. "\tAttempts to detect if shape contours have the wrong winding and generates the SDF with the right one.\n"
  327. " -help\n"
  328. "\tDisplays this help.\n"
  329. " -legacy\n"
  330. "\tUses the original (legacy) distance field algorithms.\n"
  331. #ifdef MSDFGEN_USE_SKIA
  332. " -nopreprocess\n"
  333. "\tDisables path preprocessing which resolves self-intersections and overlapping contours.\n"
  334. #else
  335. " -nooverlap\n"
  336. "\tDisables resolution of overlapping contours.\n"
  337. " -noscanline\n"
  338. "\tDisables the scanline pass, which corrects the distance field's signs according to the selected fill rule.\n"
  339. #endif
  340. " -o <filename>\n"
  341. "\tSets the output file name. The default value is \"output.png\".\n"
  342. #ifdef MSDFGEN_USE_SKIA
  343. " -overlap\n"
  344. "\tSwitches to distance field generator with support for overlapping contours.\n"
  345. #endif
  346. " -printmetrics\n"
  347. "\tPrints relevant metrics of the shape to the standard output.\n"
  348. " -pxrange <range>\n"
  349. "\tSets the width of the range between the lowest and highest signed distance in pixels.\n"
  350. " -range <range>\n"
  351. "\tSets the width of the range between the lowest and highest signed distance in shape units.\n"
  352. " -reverseorder\n"
  353. "\tGenerates the distance field as if the shape's vertices were in reverse order.\n"
  354. " -scale <scale>\n"
  355. "\tSets the scale used to convert shape units to pixels.\n"
  356. #ifdef MSDFGEN_USE_SKIA
  357. " -scanline\n"
  358. "\tPerforms an additional scanline pass to fix the signs of the distances.\n"
  359. #endif
  360. " -seed <n>\n"
  361. "\tSets the random seed for edge coloring heuristic.\n"
  362. " -size <width> <height>\n"
  363. "\tSets the dimensions of the output image.\n"
  364. " -stdout\n"
  365. "\tPrints the output instead of storing it in a file. Only text formats are supported.\n"
  366. " -testrender <filename.png> <width> <height>\n"
  367. "\tRenders an image preview using the generated distance field and saves it as a PNG file.\n"
  368. " -testrendermulti <filename.png> <width> <height>\n"
  369. "\tRenders an image preview without flattening the color channels.\n"
  370. " -translate <x> <y>\n"
  371. "\tSets the translation of the shape in shape units.\n"
  372. " -windingpreprocess\n"
  373. "\tAttempts to fix only the contour windings assuming no self-intersections and even-odd fill rule.\n"
  374. " -yflip\n"
  375. "\tInverts the Y axis in the output distance field. The default order is bottom to top.\n"
  376. "\n";
  377. static const char *errorCorrectionHelpText =
  378. "\n"
  379. "ERROR CORRECTION MODES\n"
  380. " auto-fast\n"
  381. "\tDetects inversion artifacts and distance errors that do not affect edges by range testing.\n"
  382. " auto-full\n"
  383. "\tDetects inversion artifacts and distance errors that do not affect edges by exact distance evaluation.\n"
  384. " auto-mixed (default)\n"
  385. "\tDetects inversions by distance evaluation and distance errors that do not affect edges by range testing.\n"
  386. " disabled\n"
  387. "\tDisables error correction.\n"
  388. " distance-fast\n"
  389. "\tDetects distance errors by range testing. Does not care if edges and corners are affected.\n"
  390. " distance-full\n"
  391. "\tDetects distance errors by exact distance evaluation. Does not care if edges and corners are affected, slow.\n"
  392. " edge-fast\n"
  393. "\tDetects inversion artifacts only by range testing.\n"
  394. " edge-full\n"
  395. "\tDetects inversion artifacts only by exact distance evaluation.\n"
  396. " help\n"
  397. "\tDisplays this help.\n"
  398. "\n";
  399. int main(int argc, const char * const *argv) {
  400. #define ABORT(msg) { puts(msg); return 1; }
  401. // Parse command line arguments
  402. enum {
  403. NONE,
  404. SVG,
  405. FONT,
  406. VAR_FONT,
  407. DESCRIPTION_ARG,
  408. DESCRIPTION_STDIN,
  409. DESCRIPTION_FILE
  410. } inputType = NONE;
  411. enum {
  412. SINGLE,
  413. PSEUDO,
  414. MULTI,
  415. MULTI_AND_TRUE,
  416. METRICS
  417. } mode = MULTI;
  418. enum {
  419. NO_PREPROCESS,
  420. WINDING_PREPROCESS,
  421. FULL_PREPROCESS
  422. } geometryPreproc = (
  423. #ifdef MSDFGEN_USE_SKIA
  424. FULL_PREPROCESS
  425. #else
  426. NO_PREPROCESS
  427. #endif
  428. );
  429. bool legacyMode = false;
  430. MSDFGeneratorConfig generatorConfig;
  431. generatorConfig.overlapSupport = geometryPreproc == NO_PREPROCESS;
  432. bool scanlinePass = geometryPreproc == NO_PREPROCESS;
  433. FillRule fillRule = FILL_NONZERO;
  434. Format format = AUTO;
  435. const char *input = NULL;
  436. const char *output = "output.png";
  437. const char *shapeExport = NULL;
  438. const char *testRender = NULL;
  439. const char *testRenderMulti = NULL;
  440. bool outputSpecified = false;
  441. bool glyphIndexSpecified = false;
  442. GlyphIndex glyphIndex;
  443. unicode_t unicode = 0;
  444. int svgPathIndex = 0;
  445. int width = 64, height = 64;
  446. int testWidth = 0, testHeight = 0;
  447. int testWidthM = 0, testHeightM = 0;
  448. bool autoFrame = false;
  449. enum {
  450. RANGE_UNIT,
  451. RANGE_PX
  452. } rangeMode = RANGE_PX;
  453. double range = 1;
  454. double pxRange = 2;
  455. Vector2 translate;
  456. Vector2 scale = 1;
  457. bool scaleSpecified = false;
  458. double angleThreshold = DEFAULT_ANGLE_THRESHOLD;
  459. float outputDistanceShift = 0.f;
  460. const char *edgeAssignment = NULL;
  461. bool yFlip = false;
  462. bool printMetrics = false;
  463. bool estimateError = false;
  464. bool skipColoring = false;
  465. enum {
  466. KEEP,
  467. REVERSE,
  468. GUESS
  469. } orientation = KEEP;
  470. unsigned long long coloringSeed = 0;
  471. void (*edgeColoring)(Shape &, double, unsigned long long) = edgeColoringSimple;
  472. bool explicitErrorCorrectionMode = false;
  473. int argPos = 1;
  474. bool suggestHelp = false;
  475. while (argPos < argc) {
  476. const char *arg = argv[argPos];
  477. #define ARG_CASE(s, p) if (!strcmp(arg, s) && argPos+(p) < argc)
  478. #define ARG_MODE(s, m) if (!strcmp(arg, s)) { mode = m; ++argPos; continue; }
  479. #define SET_FORMAT(fmt, ext) do { format = fmt; if (!outputSpecified) output = "output." ext; } while (false)
  480. ARG_MODE("sdf", SINGLE)
  481. ARG_MODE("psdf", PSEUDO)
  482. ARG_MODE("msdf", MULTI)
  483. ARG_MODE("mtsdf", MULTI_AND_TRUE)
  484. ARG_MODE("metrics", METRICS)
  485. ARG_CASE("-svg", 1) {
  486. inputType = SVG;
  487. input = argv[argPos+1];
  488. argPos += 2;
  489. continue;
  490. }
  491. //ARG_CASE -font, -varfont
  492. if (argPos+2 < argc && ((!strcmp(arg, "-font") && (inputType = FONT)) || (!strcmp(arg, "-varfont") && (inputType = VAR_FONT)))) {
  493. input = argv[argPos+1];
  494. const char *charArg = argv[argPos+2];
  495. unsigned gi;
  496. switch (charArg[0]) {
  497. case 'G': case 'g':
  498. if (parseUnsignedDecOrHex(gi, charArg+1)) {
  499. glyphIndex = GlyphIndex(gi);
  500. glyphIndexSpecified = true;
  501. }
  502. break;
  503. case 'U': case 'u':
  504. ++charArg;
  505. default:
  506. parseUnicode(unicode, charArg);
  507. }
  508. argPos += 3;
  509. continue;
  510. }
  511. ARG_CASE("-defineshape", 1) {
  512. inputType = DESCRIPTION_ARG;
  513. input = argv[argPos+1];
  514. argPos += 2;
  515. continue;
  516. }
  517. ARG_CASE("-stdin", 0) {
  518. inputType = DESCRIPTION_STDIN;
  519. input = "stdin";
  520. argPos += 1;
  521. continue;
  522. }
  523. ARG_CASE("-shapedesc", 1) {
  524. inputType = DESCRIPTION_FILE;
  525. input = argv[argPos+1];
  526. argPos += 2;
  527. continue;
  528. }
  529. ARG_CASE("-o", 1) {
  530. output = argv[argPos+1];
  531. outputSpecified = true;
  532. argPos += 2;
  533. continue;
  534. }
  535. ARG_CASE("-stdout", 0) {
  536. output = NULL;
  537. argPos += 1;
  538. continue;
  539. }
  540. ARG_CASE("-legacy", 0) {
  541. legacyMode = true;
  542. argPos += 1;
  543. continue;
  544. }
  545. ARG_CASE("-nopreprocess", 0) {
  546. geometryPreproc = NO_PREPROCESS;
  547. argPos += 1;
  548. continue;
  549. }
  550. ARG_CASE("-windingpreprocess", 0) {
  551. geometryPreproc = WINDING_PREPROCESS;
  552. argPos += 1;
  553. continue;
  554. }
  555. ARG_CASE("-preprocess", 0) {
  556. geometryPreproc = FULL_PREPROCESS;
  557. argPos += 1;
  558. continue;
  559. }
  560. ARG_CASE("-nooverlap", 0) {
  561. generatorConfig.overlapSupport = false;
  562. argPos += 1;
  563. continue;
  564. }
  565. ARG_CASE("-overlap", 0) {
  566. generatorConfig.overlapSupport = true;
  567. argPos += 1;
  568. continue;
  569. }
  570. ARG_CASE("-noscanline", 0) {
  571. scanlinePass = false;
  572. argPos += 1;
  573. continue;
  574. }
  575. ARG_CASE("-scanline", 0) {
  576. scanlinePass = true;
  577. argPos += 1;
  578. continue;
  579. }
  580. ARG_CASE("-fillrule", 1) {
  581. scanlinePass = true;
  582. if (!strcmp(argv[argPos+1], "nonzero")) fillRule = FILL_NONZERO;
  583. else if (!strcmp(argv[argPos+1], "evenodd") || !strcmp(argv[argPos+1], "odd")) fillRule = FILL_ODD;
  584. else if (!strcmp(argv[argPos+1], "positive")) fillRule = FILL_POSITIVE;
  585. else if (!strcmp(argv[argPos+1], "negative")) fillRule = FILL_NEGATIVE;
  586. else
  587. puts("Unknown fill rule specified.");
  588. argPos += 2;
  589. continue;
  590. }
  591. ARG_CASE("-format", 1) {
  592. if (!strcmp(argv[argPos+1], "auto")) format = AUTO;
  593. else if (!strcmp(argv[argPos+1], "png")) SET_FORMAT(PNG, "png");
  594. else if (!strcmp(argv[argPos+1], "bmp")) SET_FORMAT(BMP, "bmp");
  595. else if (!strcmp(argv[argPos+1], "tiff")) SET_FORMAT(TIFF, "tif");
  596. else if (!strcmp(argv[argPos+1], "text") || !strcmp(argv[argPos+1], "txt")) SET_FORMAT(TEXT, "txt");
  597. else if (!strcmp(argv[argPos+1], "textfloat") || !strcmp(argv[argPos+1], "txtfloat")) SET_FORMAT(TEXT_FLOAT, "txt");
  598. else if (!strcmp(argv[argPos+1], "bin") || !strcmp(argv[argPos+1], "binary")) SET_FORMAT(BINARY, "bin");
  599. else if (!strcmp(argv[argPos+1], "binfloat") || !strcmp(argv[argPos+1], "binfloatle")) SET_FORMAT(BINARY_FLOAT, "bin");
  600. else if (!strcmp(argv[argPos+1], "binfloatbe")) SET_FORMAT(BINARY_FLOAT_BE, "bin");
  601. else
  602. puts("Unknown format specified.");
  603. argPos += 2;
  604. continue;
  605. }
  606. ARG_CASE("-size", 2) {
  607. unsigned w, h;
  608. if (!(parseUnsigned(w, argv[argPos+1]) && parseUnsigned(h, argv[argPos+2]) && w && h))
  609. ABORT("Invalid size arguments. Use -size <width> <height> with two positive integers.");
  610. width = w, height = h;
  611. argPos += 3;
  612. continue;
  613. }
  614. ARG_CASE("-autoframe", 0) {
  615. autoFrame = true;
  616. argPos += 1;
  617. continue;
  618. }
  619. ARG_CASE("-range", 1) {
  620. double r;
  621. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  622. ABORT("Invalid range argument. Use -range <range> with a positive real number.");
  623. rangeMode = RANGE_UNIT;
  624. range = r;
  625. argPos += 2;
  626. continue;
  627. }
  628. ARG_CASE("-pxrange", 1) {
  629. double r;
  630. if (!(parseDouble(r, argv[argPos+1]) && r > 0))
  631. ABORT("Invalid range argument. Use -pxrange <range> with a positive real number.");
  632. rangeMode = RANGE_PX;
  633. pxRange = r;
  634. argPos += 2;
  635. continue;
  636. }
  637. ARG_CASE("-scale", 1) {
  638. double s;
  639. if (!(parseDouble(s, argv[argPos+1]) && s > 0))
  640. ABORT("Invalid scale argument. Use -scale <scale> with a positive real number.");
  641. scale = s;
  642. scaleSpecified = true;
  643. argPos += 2;
  644. continue;
  645. }
  646. ARG_CASE("-ascale", 2) {
  647. double sx, sy;
  648. if (!(parseDouble(sx, argv[argPos+1]) && parseDouble(sy, argv[argPos+2]) && sx > 0 && sy > 0))
  649. ABORT("Invalid scale arguments. Use -ascale <x> <y> with two positive real numbers.");
  650. scale.set(sx, sy);
  651. scaleSpecified = true;
  652. argPos += 3;
  653. continue;
  654. }
  655. ARG_CASE("-translate", 2) {
  656. double tx, ty;
  657. if (!(parseDouble(tx, argv[argPos+1]) && parseDouble(ty, argv[argPos+2])))
  658. ABORT("Invalid translate arguments. Use -translate <x> <y> with two real numbers.");
  659. translate.set(tx, ty);
  660. argPos += 3;
  661. continue;
  662. }
  663. ARG_CASE("-angle", 1) {
  664. double at;
  665. if (!parseAngle(at, argv[argPos+1]))
  666. 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.");
  667. angleThreshold = at;
  668. argPos += 2;
  669. continue;
  670. }
  671. ARG_CASE("-errorcorrection", 1) {
  672. if (!strcmp(argv[argPos+1], "disabled") || !strcmp(argv[argPos+1], "0") || !strcmp(argv[argPos+1], "none")) {
  673. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  674. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  675. } else if (!strcmp(argv[argPos+1], "default") || !strcmp(argv[argPos+1], "auto") || !strcmp(argv[argPos+1], "auto-mixed") || !strcmp(argv[argPos+1], "mixed")) {
  676. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  677. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::CHECK_DISTANCE_AT_EDGE;
  678. } else if (!strcmp(argv[argPos+1], "auto-fast") || !strcmp(argv[argPos+1], "fast")) {
  679. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  680. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  681. } else if (!strcmp(argv[argPos+1], "auto-full") || !strcmp(argv[argPos+1], "full")) {
  682. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_PRIORITY;
  683. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  684. } else if (!strcmp(argv[argPos+1], "distance") || !strcmp(argv[argPos+1], "distance-fast") || !strcmp(argv[argPos+1], "indiscriminate") || !strcmp(argv[argPos+1], "indiscriminate-fast")) {
  685. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  686. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  687. } else if (!strcmp(argv[argPos+1], "distance-full") || !strcmp(argv[argPos+1], "indiscriminate-full")) {
  688. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::INDISCRIMINATE;
  689. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  690. } else if (!strcmp(argv[argPos+1], "edge-fast")) {
  691. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  692. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  693. } else if (!strcmp(argv[argPos+1], "edge") || !strcmp(argv[argPos+1], "edge-full")) {
  694. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::EDGE_ONLY;
  695. generatorConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::ALWAYS_CHECK_DISTANCE;
  696. } else if (!strcmp(argv[argPos+1], "help")) {
  697. puts(errorCorrectionHelpText);
  698. return 0;
  699. } else
  700. puts("Unknown error correction mode. Use -errorcorrection help for more information.");
  701. explicitErrorCorrectionMode = true;
  702. argPos += 2;
  703. continue;
  704. }
  705. ARG_CASE("-errordeviationratio", 1) {
  706. double edr;
  707. if (!(parseDouble(edr, argv[argPos+1]) && edr > 0))
  708. ABORT("Invalid error deviation ratio. Use -errordeviationratio <ratio> with a positive real number.");
  709. generatorConfig.errorCorrection.minDeviationRatio = edr;
  710. argPos += 2;
  711. continue;
  712. }
  713. ARG_CASE("-errorimproveratio", 1) {
  714. double eir;
  715. if (!(parseDouble(eir, argv[argPos+1]) && eir > 0))
  716. ABORT("Invalid error improvement ratio. Use -errorimproveratio <ratio> with a positive real number.");
  717. generatorConfig.errorCorrection.minImproveRatio = eir;
  718. argPos += 2;
  719. continue;
  720. }
  721. ARG_CASE("-coloringstrategy", 1) {
  722. if (!strcmp(argv[argPos+1], "simple")) edgeColoring = edgeColoringSimple;
  723. else if (!strcmp(argv[argPos+1], "inktrap")) edgeColoring = edgeColoringInkTrap;
  724. else if (!strcmp(argv[argPos+1], "distance")) edgeColoring = edgeColoringByDistance;
  725. else
  726. puts("Unknown coloring strategy specified.");
  727. argPos += 2;
  728. continue;
  729. }
  730. ARG_CASE("-edgecolors", 1) {
  731. static const char *allowed = " ?,cmwyCMWY";
  732. for (int i = 0; argv[argPos+1][i]; ++i) {
  733. for (int j = 0; allowed[j]; ++j)
  734. if (argv[argPos+1][i] == allowed[j])
  735. goto EDGE_COLOR_VERIFIED;
  736. ABORT("Invalid edge coloring sequence. Use -edgecolors <color sequence> with only the colors C, M, Y, and W. Separate contours by commas and use ? to keep the default assigment for a contour.");
  737. EDGE_COLOR_VERIFIED:;
  738. }
  739. edgeAssignment = argv[argPos+1];
  740. argPos += 2;
  741. continue;
  742. }
  743. ARG_CASE("-distanceshift", 1) {
  744. double ds;
  745. if (!parseDouble(ds, argv[argPos+1]))
  746. ABORT("Invalid distance shift. Use -distanceshift <shift> with a real value.");
  747. outputDistanceShift = (float) ds;
  748. argPos += 2;
  749. continue;
  750. }
  751. ARG_CASE("-exportshape", 1) {
  752. shapeExport = argv[argPos+1];
  753. argPos += 2;
  754. continue;
  755. }
  756. ARG_CASE("-testrender", 3) {
  757. unsigned w, h;
  758. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  759. ABORT("Invalid arguments for test render. Use -testrender <output.png> <width> <height>.");
  760. testRender = argv[argPos+1];
  761. testWidth = w, testHeight = h;
  762. argPos += 4;
  763. continue;
  764. }
  765. ARG_CASE("-testrendermulti", 3) {
  766. unsigned w, h;
  767. if (!parseUnsigned(w, argv[argPos+2]) || !parseUnsigned(h, argv[argPos+3]) || !w || !h)
  768. ABORT("Invalid arguments for test render. Use -testrendermulti <output.png> <width> <height>.");
  769. testRenderMulti = argv[argPos+1];
  770. testWidthM = w, testHeightM = h;
  771. argPos += 4;
  772. continue;
  773. }
  774. ARG_CASE("-yflip", 0) {
  775. yFlip = true;
  776. argPos += 1;
  777. continue;
  778. }
  779. ARG_CASE("-printmetrics", 0) {
  780. printMetrics = true;
  781. argPos += 1;
  782. continue;
  783. }
  784. ARG_CASE("-estimateerror", 0) {
  785. estimateError = true;
  786. argPos += 1;
  787. continue;
  788. }
  789. ARG_CASE("-keeporder", 0) {
  790. orientation = KEEP;
  791. argPos += 1;
  792. continue;
  793. }
  794. ARG_CASE("-reverseorder", 0) {
  795. orientation = REVERSE;
  796. argPos += 1;
  797. continue;
  798. }
  799. ARG_CASE("-guessorder", 0) {
  800. orientation = GUESS;
  801. argPos += 1;
  802. continue;
  803. }
  804. ARG_CASE("-seed", 1) {
  805. if (!parseUnsignedLL(coloringSeed, argv[argPos+1]))
  806. ABORT("Invalid seed. Use -seed <N> with N being a non-negative integer.");
  807. argPos += 2;
  808. continue;
  809. }
  810. ARG_CASE("-help", 0) {
  811. puts(helpText);
  812. return 0;
  813. }
  814. printf("Unknown setting or insufficient parameters: %s\n", arg);
  815. suggestHelp = true;
  816. ++argPos;
  817. }
  818. if (suggestHelp)
  819. printf("Use -help for more information.\n");
  820. // Load input
  821. Vector2 svgDims;
  822. double glyphAdvance = 0;
  823. if (!inputType || !input)
  824. ABORT("No input specified! Use either -svg <file.svg> or -font <file.ttf/otf> <character code>, or see -help.");
  825. if (mode == MULTI_AND_TRUE && (format == BMP || (format == AUTO && output && cmpExtension(output, ".bmp"))))
  826. ABORT("Incompatible image format. A BMP file cannot contain alpha channel, which is required in mtsdf mode.");
  827. Shape shape;
  828. switch (inputType) {
  829. case SVG: {
  830. if (!loadSvgShape(shape, input, svgPathIndex, &svgDims))
  831. ABORT("Failed to load shape from SVG file.");
  832. break;
  833. }
  834. case FONT: case VAR_FONT: {
  835. if (!glyphIndexSpecified && !unicode)
  836. ABORT("No character specified! Use -font <file.ttf/otf> <character code>. Character code can be a Unicode index (65, 0x41), a character in apostrophes ('A'), or a glyph index prefixed by g (g36, g0x24).");
  837. FreetypeHandle *ft = initializeFreetype();
  838. if (!ft)
  839. return -1;
  840. FontHandle *font = inputType == VAR_FONT ? loadVarFont(ft, input) : loadFont(ft, input);
  841. if (!font) {
  842. deinitializeFreetype(ft);
  843. ABORT("Failed to load font file.");
  844. }
  845. if (unicode)
  846. getGlyphIndex(glyphIndex, font, unicode);
  847. if (!loadGlyph(shape, font, glyphIndex, &glyphAdvance)) {
  848. destroyFont(font);
  849. deinitializeFreetype(ft);
  850. ABORT("Failed to load glyph from font file.");
  851. }
  852. destroyFont(font);
  853. deinitializeFreetype(ft);
  854. break;
  855. }
  856. case DESCRIPTION_ARG: {
  857. if (!readShapeDescription(input, shape, &skipColoring))
  858. ABORT("Parse error in shape description.");
  859. break;
  860. }
  861. case DESCRIPTION_STDIN: {
  862. if (!readShapeDescription(stdin, shape, &skipColoring))
  863. ABORT("Parse error in shape description.");
  864. break;
  865. }
  866. case DESCRIPTION_FILE: {
  867. FILE *file = fopen(input, "r");
  868. if (!file)
  869. ABORT("Failed to load shape description file.");
  870. if (!readShapeDescription(file, shape, &skipColoring))
  871. ABORT("Parse error in shape description.");
  872. fclose(file);
  873. break;
  874. }
  875. default:;
  876. }
  877. // Validate and normalize shape
  878. if (!shape.validate())
  879. ABORT("The geometry of the loaded shape is invalid.");
  880. switch (geometryPreproc) {
  881. case NO_PREPROCESS:
  882. break;
  883. case WINDING_PREPROCESS:
  884. shape.orientContours();
  885. break;
  886. case FULL_PREPROCESS:
  887. #ifdef MSDFGEN_USE_SKIA
  888. if (!resolveShapeGeometry(shape))
  889. puts("Shape geometry preprocessing failed, skipping.");
  890. else if (skipColoring) {
  891. skipColoring = false;
  892. puts("Note: Input shape coloring won't be preserved due to geometry preprocessing");
  893. }
  894. #else
  895. ABORT("Shape geometry preprocessing (-preprocess) is not available in this version because the Skia library is not present.");
  896. #endif
  897. break;
  898. }
  899. shape.normalize();
  900. if (yFlip)
  901. shape.inverseYAxis = !shape.inverseYAxis;
  902. double avgScale = .5*(scale.x+scale.y);
  903. Shape::Bounds bounds = { };
  904. if (autoFrame || mode == METRICS || printMetrics || orientation == GUESS)
  905. bounds = shape.getBounds();
  906. // Auto-frame
  907. if (autoFrame) {
  908. double l = bounds.l, b = bounds.b, r = bounds.r, t = bounds.t;
  909. Vector2 frame(width, height);
  910. double m = .5+(double) outputDistanceShift;
  911. if (!scaleSpecified) {
  912. if (rangeMode == RANGE_UNIT)
  913. l -= m*range, b -= m*range, r += m*range, t += m*range;
  914. else
  915. frame -= 2*m*pxRange;
  916. }
  917. if (l >= r || b >= t)
  918. l = 0, b = 0, r = 1, t = 1;
  919. if (frame.x <= 0 || frame.y <= 0)
  920. ABORT("Cannot fit the specified pixel range.");
  921. Vector2 dims(r-l, t-b);
  922. if (scaleSpecified)
  923. translate = .5*(frame/scale-dims)-Vector2(l, b);
  924. else {
  925. if (dims.x*frame.y < dims.y*frame.x) {
  926. translate.set(.5*(frame.x/frame.y*dims.y-dims.x)-l, -b);
  927. scale = avgScale = frame.y/dims.y;
  928. } else {
  929. translate.set(-l, .5*(frame.y/frame.x*dims.x-dims.y)-b);
  930. scale = avgScale = frame.x/dims.x;
  931. }
  932. }
  933. if (rangeMode == RANGE_PX && !scaleSpecified)
  934. translate += m*pxRange/scale;
  935. }
  936. if (rangeMode == RANGE_PX)
  937. range = pxRange/min(scale.x, scale.y);
  938. // Print metrics
  939. if (mode == METRICS || printMetrics) {
  940. FILE *out = stdout;
  941. if (mode == METRICS && outputSpecified)
  942. out = fopen(output, "w");
  943. if (!out)
  944. ABORT("Failed to write output file.");
  945. if (shape.inverseYAxis)
  946. fprintf(out, "inverseY = true\n");
  947. if (bounds.r >= bounds.l && bounds.t >= bounds.b)
  948. fprintf(out, "bounds = %.12g, %.12g, %.12g, %.12g\n", bounds.l, bounds.b, bounds.r, bounds.t);
  949. if (svgDims.x != 0 && svgDims.y != 0)
  950. fprintf(out, "dimensions = %.12g, %.12g\n", svgDims.x, svgDims.y);
  951. if (glyphAdvance != 0)
  952. fprintf(out, "advance = %.12g\n", glyphAdvance);
  953. if (autoFrame) {
  954. if (!scaleSpecified)
  955. fprintf(out, "scale = %.12g\n", avgScale);
  956. fprintf(out, "translate = %.12g, %.12g\n", translate.x, translate.y);
  957. }
  958. if (rangeMode == RANGE_PX)
  959. fprintf(out, "range = %.12g\n", range);
  960. if (mode == METRICS && outputSpecified)
  961. fclose(out);
  962. }
  963. // Compute output
  964. Projection projection(scale, translate);
  965. Bitmap<float, 1> sdf;
  966. Bitmap<float, 3> msdf;
  967. Bitmap<float, 4> mtsdf;
  968. MSDFGeneratorConfig postErrorCorrectionConfig(generatorConfig);
  969. if (scanlinePass) {
  970. if (explicitErrorCorrectionMode && generatorConfig.errorCorrection.distanceCheckMode != ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE) {
  971. const char *fallbackModeName = "unknown";
  972. switch (generatorConfig.errorCorrection.mode) {
  973. case ErrorCorrectionConfig::DISABLED: fallbackModeName = "disabled"; break;
  974. case ErrorCorrectionConfig::INDISCRIMINATE: fallbackModeName = "distance-fast"; break;
  975. case ErrorCorrectionConfig::EDGE_PRIORITY: fallbackModeName = "auto-fast"; break;
  976. case ErrorCorrectionConfig::EDGE_ONLY: fallbackModeName = "edge-fast"; break;
  977. }
  978. printf("Selected error correction mode not compatible with scanline pass, falling back to %s.\n", fallbackModeName);
  979. }
  980. generatorConfig.errorCorrection.mode = ErrorCorrectionConfig::DISABLED;
  981. postErrorCorrectionConfig.errorCorrection.distanceCheckMode = ErrorCorrectionConfig::DO_NOT_CHECK_DISTANCE;
  982. }
  983. switch (mode) {
  984. case SINGLE: {
  985. sdf = Bitmap<float, 1>(width, height);
  986. if (legacyMode)
  987. generateSDF_legacy(sdf, shape, range, scale, translate);
  988. else
  989. generateSDF(sdf, shape, projection, range, generatorConfig);
  990. break;
  991. }
  992. case PSEUDO: {
  993. sdf = Bitmap<float, 1>(width, height);
  994. if (legacyMode)
  995. generatePseudoSDF_legacy(sdf, shape, range, scale, translate);
  996. else
  997. generatePseudoSDF(sdf, shape, projection, range, generatorConfig);
  998. break;
  999. }
  1000. case MULTI: {
  1001. if (!skipColoring)
  1002. edgeColoring(shape, angleThreshold, coloringSeed);
  1003. if (edgeAssignment)
  1004. parseColoring(shape, edgeAssignment);
  1005. msdf = Bitmap<float, 3>(width, height);
  1006. if (legacyMode)
  1007. generateMSDF_legacy(msdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1008. else
  1009. generateMSDF(msdf, shape, projection, range, generatorConfig);
  1010. break;
  1011. }
  1012. case MULTI_AND_TRUE: {
  1013. if (!skipColoring)
  1014. edgeColoring(shape, angleThreshold, coloringSeed);
  1015. if (edgeAssignment)
  1016. parseColoring(shape, edgeAssignment);
  1017. mtsdf = Bitmap<float, 4>(width, height);
  1018. if (legacyMode)
  1019. generateMTSDF_legacy(mtsdf, shape, range, scale, translate, generatorConfig.errorCorrection);
  1020. else
  1021. generateMTSDF(mtsdf, shape, projection, range, generatorConfig);
  1022. break;
  1023. }
  1024. default:;
  1025. }
  1026. if (orientation == GUESS) {
  1027. // Get sign of signed distance outside bounds
  1028. Point2 p(bounds.l-(bounds.r-bounds.l)-1, bounds.b-(bounds.t-bounds.b)-1);
  1029. double distance = SimpleTrueShapeDistanceFinder::oneShotDistance(shape, p);
  1030. orientation = distance <= 0 ? KEEP : REVERSE;
  1031. }
  1032. if (orientation == REVERSE) {
  1033. switch (mode) {
  1034. case SINGLE:
  1035. case PSEUDO:
  1036. invertColor<1>(sdf);
  1037. break;
  1038. case MULTI:
  1039. invertColor<3>(msdf);
  1040. break;
  1041. case MULTI_AND_TRUE:
  1042. invertColor<4>(mtsdf);
  1043. break;
  1044. default:;
  1045. }
  1046. }
  1047. if (scanlinePass) {
  1048. switch (mode) {
  1049. case SINGLE:
  1050. case PSEUDO:
  1051. distanceSignCorrection(sdf, shape, projection, fillRule);
  1052. break;
  1053. case MULTI:
  1054. distanceSignCorrection(msdf, shape, projection, fillRule);
  1055. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1056. break;
  1057. case MULTI_AND_TRUE:
  1058. distanceSignCorrection(mtsdf, shape, projection, fillRule);
  1059. msdfErrorCorrection(msdf, shape, projection, range, postErrorCorrectionConfig);
  1060. break;
  1061. default:;
  1062. }
  1063. }
  1064. if (outputDistanceShift) {
  1065. float *pixel = NULL, *pixelsEnd = NULL;
  1066. switch (mode) {
  1067. case SINGLE:
  1068. case PSEUDO:
  1069. pixel = (float *) sdf;
  1070. pixelsEnd = pixel+1*sdf.width()*sdf.height();
  1071. break;
  1072. case MULTI:
  1073. pixel = (float *) msdf;
  1074. pixelsEnd = pixel+3*msdf.width()*msdf.height();
  1075. break;
  1076. case MULTI_AND_TRUE:
  1077. pixel = (float *) mtsdf;
  1078. pixelsEnd = pixel+4*mtsdf.width()*mtsdf.height();
  1079. break;
  1080. default:;
  1081. }
  1082. while (pixel < pixelsEnd)
  1083. *pixel++ += outputDistanceShift;
  1084. }
  1085. // Save output
  1086. if (shapeExport) {
  1087. FILE *file = fopen(shapeExport, "w");
  1088. if (file) {
  1089. writeShapeDescription(file, shape);
  1090. fclose(file);
  1091. } else
  1092. puts("Failed to write shape export file.");
  1093. }
  1094. const char *error = NULL;
  1095. switch (mode) {
  1096. case SINGLE:
  1097. case PSEUDO:
  1098. error = writeOutput<1>(sdf, output, format);
  1099. if (error)
  1100. ABORT(error);
  1101. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1102. simulate8bit(sdf);
  1103. if (estimateError) {
  1104. double sdfError = estimateSDFError(sdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1105. printf("SDF error ~ %e\n", sdfError);
  1106. }
  1107. if (testRenderMulti) {
  1108. Bitmap<float, 3> render(testWidthM, testHeightM);
  1109. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1110. if (!savePng(render, testRenderMulti))
  1111. puts("Failed to write test render file.");
  1112. }
  1113. if (testRender) {
  1114. Bitmap<float, 1> render(testWidth, testHeight);
  1115. renderSDF(render, sdf, avgScale*range, .5f+outputDistanceShift);
  1116. if (!savePng(render, testRender))
  1117. puts("Failed to write test render file.");
  1118. }
  1119. break;
  1120. case MULTI:
  1121. error = writeOutput<3>(msdf, output, format);
  1122. if (error)
  1123. ABORT(error);
  1124. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1125. simulate8bit(msdf);
  1126. if (estimateError) {
  1127. double sdfError = estimateSDFError(msdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1128. printf("SDF error ~ %e\n", sdfError);
  1129. }
  1130. if (testRenderMulti) {
  1131. Bitmap<float, 3> render(testWidthM, testHeightM);
  1132. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1133. if (!savePng(render, testRenderMulti))
  1134. puts("Failed to write test render file.");
  1135. }
  1136. if (testRender) {
  1137. Bitmap<float, 1> render(testWidth, testHeight);
  1138. renderSDF(render, msdf, avgScale*range, .5f+outputDistanceShift);
  1139. if (!savePng(render, testRender))
  1140. ABORT("Failed to write test render file.");
  1141. }
  1142. break;
  1143. case MULTI_AND_TRUE:
  1144. error = writeOutput<4>(mtsdf, output, format);
  1145. if (error)
  1146. ABORT(error);
  1147. if (is8bitFormat(format) && (testRenderMulti || testRender || estimateError))
  1148. simulate8bit(mtsdf);
  1149. if (estimateError) {
  1150. double sdfError = estimateSDFError(mtsdf, shape, projection, SDF_ERROR_ESTIMATE_PRECISION, fillRule);
  1151. printf("SDF error ~ %e\n", sdfError);
  1152. }
  1153. if (testRenderMulti) {
  1154. Bitmap<float, 4> render(testWidthM, testHeightM);
  1155. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1156. if (!savePng(render, testRenderMulti))
  1157. puts("Failed to write test render file.");
  1158. }
  1159. if (testRender) {
  1160. Bitmap<float, 1> render(testWidth, testHeight);
  1161. renderSDF(render, mtsdf, avgScale*range, .5f+outputDistanceShift);
  1162. if (!savePng(render, testRender))
  1163. ABORT("Failed to write test render file.");
  1164. }
  1165. break;
  1166. default:;
  1167. }
  1168. return 0;
  1169. }
  1170. #endif