main.cpp 47 KB

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