import-svg.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #define _USE_MATH_DEFINES
  2. #include "import-svg.h"
  3. #include <cstdio>
  4. #include <tinyxml2.h>
  5. #include "../core/arithmetics.hpp"
  6. #ifdef _WIN32
  7. #pragma warning(disable:4996)
  8. #endif
  9. #define ARC_SEGMENTS_PER_PI 2
  10. #define ENDPOINT_SNAP_RANGE_PROPORTION (1/16384.)
  11. namespace msdfgen {
  12. #if defined(_DEBUG) || !NDEBUG
  13. #define REQUIRE(cond) { if (!(cond)) { fprintf(stderr, "SVG Parse Error (%s:%d): " #cond "\n", __FILE__, __LINE__); return false; } }
  14. #else
  15. #define REQUIRE(cond) { if (!(cond)) return false; }
  16. #endif
  17. static void skipExtraChars(const char *&pathDef) {
  18. while (*pathDef == ',' || *pathDef == ' ' || *pathDef == '\t' || *pathDef == '\r' || *pathDef == '\n')
  19. ++pathDef;
  20. }
  21. static bool readNodeType(char &output, const char *&pathDef) {
  22. skipExtraChars(pathDef);
  23. char nodeType = *pathDef;
  24. if (nodeType && nodeType != '+' && nodeType != '-' && nodeType != '.' && nodeType != ',' && (nodeType < '0' || nodeType > '9')) {
  25. ++pathDef;
  26. output = nodeType;
  27. return true;
  28. }
  29. return false;
  30. }
  31. static bool readCoord(Point2 &output, const char *&pathDef) {
  32. skipExtraChars(pathDef);
  33. int shift;
  34. double x, y;
  35. if (sscanf(pathDef, "%lf%lf%n", &x, &y, &shift) == 2 || sscanf(pathDef, "%lf , %lf%n", &x, &y, &shift) == 2) {
  36. output.x = x;
  37. output.y = y;
  38. pathDef += shift;
  39. return true;
  40. }
  41. return false;
  42. }
  43. static bool readDouble(double &output, const char *&pathDef) {
  44. skipExtraChars(pathDef);
  45. int shift;
  46. double v;
  47. if (sscanf(pathDef, "%lf%n", &v, &shift) == 1) {
  48. pathDef += shift;
  49. output = v;
  50. return true;
  51. }
  52. return false;
  53. }
  54. static bool readBool(bool &output, const char *&pathDef) {
  55. skipExtraChars(pathDef);
  56. int shift;
  57. int v;
  58. if (sscanf(pathDef, "%d%n", &v, &shift) == 1) {
  59. pathDef += shift;
  60. output = v != 0;
  61. return true;
  62. }
  63. return false;
  64. }
  65. static double arcAngle(Vector2 u, Vector2 v) {
  66. return nonZeroSign(crossProduct(u, v))*acos(clamp(dotProduct(u, v)/(u.length()*v.length()), -1., +1.));
  67. }
  68. static Vector2 rotateVector(Vector2 v, Vector2 direction) {
  69. return Vector2(direction.x*v.x-direction.y*v.y, direction.y*v.x+direction.x*v.y);
  70. }
  71. static void addArcApproximate(Contour &contour, Point2 startPoint, Point2 endPoint, Vector2 radius, double rotation, bool largeArc, bool sweep) {
  72. if (endPoint == startPoint)
  73. return;
  74. if (radius.x == 0 || radius.y == 0)
  75. return contour.addEdge(new LinearSegment(startPoint, endPoint));
  76. radius.x = fabs(radius.x);
  77. radius.y = fabs(radius.y);
  78. Vector2 axis(cos(rotation), sin(rotation));
  79. Vector2 rm = rotateVector(.5*(startPoint-endPoint), Vector2(axis.x, -axis.y));
  80. Vector2 rm2 = rm*rm;
  81. Vector2 radius2 = radius*radius;
  82. double radiusGap = rm2.x/radius2.x+rm2.y/radius2.y;
  83. if (radiusGap > 1) {
  84. radius *= sqrt(radiusGap);
  85. radius2 = radius*radius;
  86. }
  87. double dq = (radius2.x*rm2.y+radius2.y*rm2.x);
  88. double pq = radius2.x*radius2.y/dq-1;
  89. double q = (largeArc == sweep ? -1 : +1)*sqrt(max(pq, 0.));
  90. Vector2 rc(q*radius.x*rm.y/radius.y, -q*radius.y*rm.x/radius.x);
  91. Point2 center = .5*(startPoint+endPoint)+rotateVector(rc, axis);
  92. double angleStart = arcAngle(Vector2(1, 0), (rm-rc)/radius);
  93. double angleExtent = arcAngle((rm-rc)/radius, (-rm-rc)/radius);
  94. if (!sweep && angleExtent > 0)
  95. angleExtent -= 2*M_PI;
  96. else if (sweep && angleExtent < 0)
  97. angleExtent += 2*M_PI;
  98. int segments = (int) ceil(ARC_SEGMENTS_PER_PI/M_PI*fabs(angleExtent));
  99. double angleIncrement = angleExtent/segments;
  100. double cl = 4/3.*sin(.5*angleIncrement)/(1+cos(.5*angleIncrement));
  101. Point2 prevNode = startPoint;
  102. double angle = angleStart;
  103. for (int i = 0; i < segments; ++i) {
  104. Point2 controlPoint[2];
  105. Vector2 d(cos(angle), sin(angle));
  106. controlPoint[0] = center+rotateVector(Vector2(d.x-cl*d.y, d.y+cl*d.x)*radius, axis);
  107. angle += angleIncrement;
  108. d.set(cos(angle), sin(angle));
  109. controlPoint[1] = center+rotateVector(Vector2(d.x+cl*d.y, d.y-cl*d.x)*radius, axis);
  110. Point2 node = i == segments-1 ? endPoint : center+rotateVector(d*radius, axis);
  111. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  112. prevNode = node;
  113. }
  114. }
  115. static bool buildFromPath(Shape &shape, const char *pathDef, double size) {
  116. char nodeType = '\0';
  117. char prevNodeType = '\0';
  118. Point2 prevNode(0, 0);
  119. bool nodeTypePreread = false;
  120. while (nodeTypePreread || readNodeType(nodeType, pathDef)) {
  121. nodeTypePreread = false;
  122. Contour &contour = shape.addContour();
  123. bool contourStart = true;
  124. Point2 startPoint;
  125. Point2 controlPoint[2];
  126. Point2 node;
  127. while (*pathDef) {
  128. switch (nodeType) {
  129. case 'M': case 'm':
  130. if (!contourStart) {
  131. nodeTypePreread = true;
  132. goto NEXT_CONTOUR;
  133. }
  134. REQUIRE(readCoord(node, pathDef));
  135. if (nodeType == 'm')
  136. node += prevNode;
  137. startPoint = node;
  138. --nodeType; // to 'L' or 'l'
  139. break;
  140. case 'Z': case 'z':
  141. REQUIRE(!contourStart);
  142. goto NEXT_CONTOUR;
  143. case 'L': case 'l':
  144. REQUIRE(readCoord(node, pathDef));
  145. if (nodeType == 'l')
  146. node += prevNode;
  147. contour.addEdge(new LinearSegment(prevNode, node));
  148. break;
  149. case 'H': case 'h':
  150. REQUIRE(readDouble(node.x, pathDef));
  151. if (nodeType == 'h')
  152. node.x += prevNode.x;
  153. contour.addEdge(new LinearSegment(prevNode, node));
  154. break;
  155. case 'V': case 'v':
  156. REQUIRE(readDouble(node.y, pathDef));
  157. if (nodeType == 'v')
  158. node.y += prevNode.y;
  159. contour.addEdge(new LinearSegment(prevNode, node));
  160. break;
  161. case 'Q': case 'q':
  162. REQUIRE(readCoord(controlPoint[0], pathDef));
  163. REQUIRE(readCoord(node, pathDef));
  164. if (nodeType == 'q') {
  165. controlPoint[0] += prevNode;
  166. node += prevNode;
  167. }
  168. contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
  169. break;
  170. case 'T': case 't':
  171. if (prevNodeType == 'Q' || prevNodeType == 'q' || prevNodeType == 'T' || prevNodeType == 't')
  172. controlPoint[0] = node+node-controlPoint[0];
  173. else
  174. controlPoint[0] = node;
  175. REQUIRE(readCoord(node, pathDef));
  176. if (nodeType == 't')
  177. node += prevNode;
  178. contour.addEdge(new QuadraticSegment(prevNode, controlPoint[0], node));
  179. break;
  180. case 'C': case 'c':
  181. REQUIRE(readCoord(controlPoint[0], pathDef));
  182. REQUIRE(readCoord(controlPoint[1], pathDef));
  183. REQUIRE(readCoord(node, pathDef));
  184. if (nodeType == 'c') {
  185. controlPoint[0] += prevNode;
  186. controlPoint[1] += prevNode;
  187. node += prevNode;
  188. }
  189. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  190. break;
  191. case 'S': case 's':
  192. if (prevNodeType == 'C' || prevNodeType == 'c' || prevNodeType == 'S' || prevNodeType == 's')
  193. controlPoint[0] = node+node-controlPoint[1];
  194. else
  195. controlPoint[0] = node;
  196. REQUIRE(readCoord(controlPoint[1], pathDef));
  197. REQUIRE(readCoord(node, pathDef));
  198. if (nodeType == 's') {
  199. controlPoint[1] += prevNode;
  200. node += prevNode;
  201. }
  202. contour.addEdge(new CubicSegment(prevNode, controlPoint[0], controlPoint[1], node));
  203. break;
  204. case 'A': case 'a':
  205. {
  206. Vector2 radius;
  207. double angle;
  208. bool largeArg;
  209. bool sweep;
  210. REQUIRE(readCoord(radius, pathDef));
  211. REQUIRE(readDouble(angle, pathDef));
  212. REQUIRE(readBool(largeArg, pathDef));
  213. REQUIRE(readBool(sweep, pathDef));
  214. REQUIRE(readCoord(node, pathDef));
  215. if (nodeType == 'a')
  216. node += prevNode;
  217. angle *= M_PI/180.0;
  218. addArcApproximate(contour, prevNode, node, radius, angle, largeArg, sweep);
  219. }
  220. break;
  221. default:
  222. REQUIRE(!"Unknown node type");
  223. }
  224. contourStart &= nodeType == 'M' || nodeType == 'm';
  225. prevNode = node;
  226. prevNodeType = nodeType;
  227. readNodeType(nodeType, pathDef);
  228. }
  229. NEXT_CONTOUR:
  230. // Fix contour if it isn't properly closed
  231. if (!contour.edges.empty() && prevNode != startPoint) {
  232. if ((contour.edges.back()->point(1)-contour.edges[0]->point(0)).length() < ENDPOINT_SNAP_RANGE_PROPORTION*size)
  233. contour.edges.back()->moveEndPoint(contour.edges[0]->point(0));
  234. else
  235. contour.addEdge(new LinearSegment(prevNode, startPoint));
  236. }
  237. prevNode = startPoint;
  238. prevNodeType = '\0';
  239. }
  240. return true;
  241. }
  242. bool loadSvgShape(Shape &output, const char *filename, int pathIndex, Vector2 *dimensions) {
  243. tinyxml2::XMLDocument doc;
  244. if (doc.LoadFile(filename))
  245. return false;
  246. tinyxml2::XMLElement *root = doc.FirstChildElement("svg");
  247. if (!root)
  248. return false;
  249. tinyxml2::XMLElement *path = NULL;
  250. if (pathIndex > 0) {
  251. path = root->FirstChildElement("path");
  252. if (!path) {
  253. tinyxml2::XMLElement *g = root->FirstChildElement("g");
  254. if (g)
  255. path = g->FirstChildElement("path");
  256. }
  257. while (path && --pathIndex > 0)
  258. path = path->NextSiblingElement("path");
  259. } else {
  260. path = root->LastChildElement("path");
  261. if (!path) {
  262. tinyxml2::XMLElement *g = root->LastChildElement("g");
  263. if (g)
  264. path = g->LastChildElement("path");
  265. }
  266. while (path && ++pathIndex < 0)
  267. path = path->PreviousSiblingElement("path");
  268. }
  269. if (!path)
  270. return false;
  271. const char *pd = path->Attribute("d");
  272. if (!pd)
  273. return false;
  274. output.contours.clear();
  275. output.inverseYAxis = true;
  276. Vector2 dims(root->DoubleAttribute("width"), root->DoubleAttribute("height"));
  277. if (!dims) {
  278. double left, top;
  279. const char *viewBox = root->Attribute("viewBox");
  280. if (viewBox)
  281. sscanf(viewBox, "%lf %lf %lf %lf", &left, &top, &dims.x, &dims.y);
  282. }
  283. if (dimensions)
  284. *dimensions = dims;
  285. return buildFromPath(output, pd, dims.length());
  286. }
  287. }