1 /*
2 * Copyright (c) 2013-14 Mikko Mononen memon@inside.org
3 *
4 * This software is provided 'as-is', without any express or implied
5 * warranty. In no event will the authors be held liable for any damages
6 * arising from the use of this software.
7 *
8 * Permission is granted to anyone to use this software for any purpose,
9 * including commercial applications, and to alter it and redistribute it
10 * freely, subject to the following restrictions:
11 *
12 * 1. The origin of this software must not be misrepresented; you must not
13 * claim that you wrote the original software. If you use this software
14 * in a product, an acknowledgment in the product documentation would be
15 * appreciated but is not required.
16 * 2. Altered source versions must be plainly marked as such, and must not be
17 * misrepresented as being the original software.
18 * 3. This notice may not be removed or altered from any source distribution.
19 *
20 * The SVG parser is based on Anti-Grain Geometry 2.4 SVG example
21 * Copyright (C) 2002-2004 Maxim Shemanarev (McSeem) (http://www.antigrain.com/)
22 *
23 * Arc calculation code based on canvg (https://code.google.com/p/canvg/)
24 *
25 * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
26 *
27 */
28
29 #ifndef NANOSVG_H
30 #define NANOSVG_H
31
32 #ifdef __cplusplus
33 extern "C" {
34 #endif
35
36 /* NanoSVG is a simple stupid single-header-file SVG parse. The output of the parser is a list of cubic bezier shapes.
37 *
38 * The library suits well for anything from rendering scalable icons in your editor application to prototyping a game.
39 *
40 * NanoSVG supports a wide range of SVG features, but something may be missing, feel free to create a pull request!
41 *
42 * The shapes in the SVG images are transformed by the viewBox and converted to specified units.
43 * That is, you should get the same looking data as your designed in your favorite app.
44 *
45 * NanoSVG can return the paths in few different units. For example if you want to render an image, you may choose
46 * to get the paths in pixels, or if you are feeding the data into a CNC-cutter, you may want to use millimeters.
47 *
48 * The units passed to NanoSVG should be one of: 'px', 'pt', 'pc' 'mm', 'cm', or 'in'.
49 * DPI (dots-per-inch) controls how the unit conversion is done.
50 *
51 * If you don't know or care about the units stuff, "px" and 96 should get you going.
52 */
53
54
55 /* Example Usage:
56 // Load SVG
57 NSVGimage* image;
58 image = nsvgParseFromFile("test.svg", "px", 96);
59 printf("size: %f x %f\n", image->width, image->height);
60 // Use...
61 for (NSVGshape *shape = image->shapes; shape != NULL; shape = shape->next) {
62 for (NSVGpath *path = shape->paths; path != NULL; path = path->next) {
63 for (int i = 0; i < path->npts-1; i += 3) {
64 float* p = &path->pts[i*2];
65 drawCubicBez(p[0],p[1], p[2],p[3], p[4],p[5], p[6],p[7]);
66 }
67 }
68 }
69 // Delete
70 nsvgDelete(image);
71 */
72
73 #ifndef NANOSVG_SCOPE
74 #define NANOSVG_SCOPE
75 #endif
76
77 #ifndef NANOSVG_malloc
78 #define NANOSVG_malloc malloc
79 #endif
80
81 #ifndef NANOSVG_realloc
82 #define NANOSVG_realloc realloc
83 #endif
84
85 #ifndef NANOSVG_free
86 #define NANOSVG_free free
87 #endif
88
89 /* float emulation for MS VC6++ compiler */
90 #if defined(_MSC_VER) && (_MSC_VER == 1200)
91 #define tanf(a) (float)tan(a)
92 #define cosf(a) (float)cos(a)
93 #define sinf(a) (float)sin(a)
94 #define sqrtf(a) (float)sqrt(a)
95 #define fabsf(a) (float)fabs(a)
96 #define acosf(a) (float)acos(a)
97 #define atan2f(a,b) (float)atan2(a,b)
98 #define ceilf(a) (float)ceil(a)
99 #define fmodf(a,b) (float)fmod(a,b)
100 #define floorf(a) (float)floor(a)
101 #endif
102 /* float emulation for MS VC8++ compiler */
103 #if defined(_MSC_VER) && (_MSC_VER == 1400)
104 #define fabsf(a) (float)fabs(a)
105 #endif
106
107 enum NSVGpaintType {
108 NSVG_PAINT_NONE = 0,
109 NSVG_PAINT_COLOR = 1,
110 NSVG_PAINT_LINEAR_GRADIENT = 2,
111 NSVG_PAINT_RADIAL_GRADIENT = 3
112 };
113
114 enum NSVGspreadType {
115 NSVG_SPREAD_PAD = 0,
116 NSVG_SPREAD_REFLECT = 1,
117 NSVG_SPREAD_REPEAT = 2
118 };
119
120 enum NSVGlineJoin {
121 NSVG_JOIN_MITER = 0,
122 NSVG_JOIN_ROUND = 1,
123 NSVG_JOIN_BEVEL = 2
124 };
125
126 enum NSVGlineCap {
127 NSVG_CAP_BUTT = 0,
128 NSVG_CAP_ROUND = 1,
129 NSVG_CAP_SQUARE = 2
130 };
131
132 enum NSVGfillRule {
133 NSVG_FILLRULE_NONZERO = 0,
134 NSVG_FILLRULE_EVENODD = 1
135 };
136
137 enum NSVGflags {
138 NSVG_FLAGS_VISIBLE = 0x01
139 };
140
141 typedef struct NSVGgradientStop {
142 unsigned int color;
143 float offset;
144 } NSVGgradientStop;
145
146 typedef struct NSVGgradient {
147 float xform[6];
148 char spread;
149 float fx, fy;
150 int nstops;
151 NSVGgradientStop stops[1];
152 } NSVGgradient;
153
154 typedef struct NSVGpaint {
155 char type;
156 union {
157 unsigned int color;
158 NSVGgradient* gradient;
159 };
160 } NSVGpaint;
161
162 typedef struct NSVGpath
163 {
164 float* pts; /* Cubic bezier points: x0,y0, [cpx1,cpx1,cpx2,cpy2,x1,y1], ... */
165 int npts; /* Total number of bezier points. */
166 char closed; /* Flag indicating if shapes should be treated as closed. */
167 float bounds[4]; /* Tight bounding box of the shape [minx,miny,maxx,maxy]. */
168 struct NSVGpath* next; /* Pointer to next path, or NULL if last element. */
169 } NSVGpath;
170
171 typedef struct NSVGshape
172 {
173 char id[64]; /* Optional 'id' attr of the shape or its group */
174 NSVGpaint fill; /* Fill paint */
175 NSVGpaint stroke; /* Stroke paint */
176 float opacity; /* Opacity of the shape. */
177 float strokeWidth; /* Stroke width (scaled). */
178 float strokeDashOffset; /* Stroke dash offset (scaled). */
179 float strokeDashArray[8]; /* Stroke dash array (scaled). */
180 char strokeDashCount; /* Number of dash values in dash array. */
181 char strokeLineJoin; /* Stroke join type. */
182 char strokeLineCap; /* Stroke cap type. */
183 float miterLimit; /* Miter limit */
184 char fillRule; /* Fill rule, see NSVGfillRule. */
185 unsigned char flags; /* Logical or of NSVG_FLAGS_* flags */
186 float bounds[4]; /* Tight bounding box of the shape [minx,miny,maxx,maxy]. */
187 NSVGpath* paths; /* Linked list of paths in the image. */
188 struct NSVGshape* next; /* Pointer to next shape, or NULL if last element. */
189 } NSVGshape;
190
191 typedef struct NSVGimage
192 {
193 float width; /* Width of the image. */
194 float height; /* Height of the image. */
195 NSVGshape* shapes; /* Linked list of shapes in the image. */
196 } NSVGimage;
197
198 /* Parses SVG file from a file, returns SVG image as paths. */
199 NANOSVG_SCOPE NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi);
200
201 /* Parses SVG file from a null terminated string, returns SVG image as paths. */
202 /* Important note: changes the string. */
203 NANOSVG_SCOPE NSVGimage* nsvgParse(char* input, const char* units, float dpi);
204
205 /* Deletes list of paths. */
206 NANOSVG_SCOPE void nsvgDelete(NSVGimage* image);
207
208 #ifdef __cplusplus
209 }
210 #endif
211
212 #endif /* NANOSVG_H */
213
214 #ifdef NANOSVG_IMPLEMENTATION
215
216 #include <string.h>
217 #include <stdlib.h>
218 #include <math.h>
219
220 #define NSVG_PI (3.14159265358979323846264338327f)
221 #define NSVG_KAPPA90 (0.5522847493f) /* Length proportional to radius of a cubic bezier handle for 90deg arcs. */
222
223 #define NSVG_ALIGN_MIN 0
224 #define NSVG_ALIGN_MID 1
225 #define NSVG_ALIGN_MAX 2
226 #define NSVG_ALIGN_NONE 0
227 #define NSVG_ALIGN_MEET 1
228 #define NSVG_ALIGN_SLICE 2
229
230 #define NSVG_NOTUSED(v) do { (void)(1 ? (void)0 : ( (void)(v) ) ); } while(0)
231 #define NSVG_RGB(r, g, b) (((unsigned int)r) | ((unsigned int)g << 8) | ((unsigned int)b << 16))
232
233 #ifdef _MSC_VER
234 #pragma warning (disable: 4996) /* Switch off security warnings */
235 #pragma warning (disable: 4100) /* Switch off unreferenced formal parameter warnings */
236 #ifdef __cplusplus
237 #define NSVG_INLINE inline
238 #else
239 #define NSVG_INLINE
240 #endif
241 #if !defined(strtoll) /* old MSVC versions do not have strtoll() */
242 #define strtoll _strtoi64
243 #endif
244 #else
245 #define NSVG_INLINE inline
246 #endif
247
248
nsvg__isspace(char c)249 static int nsvg__isspace(char c)
250 {
251 return strchr(" \t\n\v\f\r", c) != 0;
252 }
253
nsvg__isdigit(char c)254 static int nsvg__isdigit(char c)
255 {
256 return c >= '0' && c <= '9';
257 }
258
nsvg__minf(float a,float b)259 static NSVG_INLINE float nsvg__minf(float a, float b) { return a < b ? a : b; }
nsvg__maxf(float a,float b)260 static NSVG_INLINE float nsvg__maxf(float a, float b) { return a > b ? a : b; }
261
262
263 /* Simple XML parser */
264
265 #define NSVG_XML_TAG 1
266 #define NSVG_XML_CONTENT 2
267 #define NSVG_XML_MAX_ATTRIBS 256
268
nsvg__parseContent(char * s,void (* contentCb)(void * ud,const char * s),void * ud)269 static void nsvg__parseContent(char* s,
270 void (*contentCb)(void* ud, const char* s),
271 void* ud)
272 {
273 /* Trim start white spaces */
274 while (*s && nsvg__isspace(*s)) s++;
275 if (!*s) return;
276
277 if (contentCb)
278 (*contentCb)(ud, s);
279 }
280
nsvg__parseElement(char * s,void (* startelCb)(void * ud,const char * el,const char ** attr),void (* endelCb)(void * ud,const char * el),void * ud)281 static void nsvg__parseElement(char* s,
282 void (*startelCb)(void* ud, const char* el, const char** attr),
283 void (*endelCb)(void* ud, const char* el),
284 void* ud)
285 {
286 const char* attr[NSVG_XML_MAX_ATTRIBS];
287 int nattr = 0;
288 char* cbname;
289 int start = 0;
290 int end = 0;
291 char quote;
292
293 /* Skip white space after the '<' */
294 while (*s && nsvg__isspace(*s)) s++;
295
296 /* Check if the tag is end tag */
297 if (*s == '/') {
298 s++;
299 end = 1;
300 } else {
301 start = 1;
302 }
303
304 /* Skip comments, data and preprocessor stuff. */
305 if (!*s || *s == '?' || *s == '!')
306 return;
307
308 /* Get tag name */
309 cbname = s;
310 while (*s && !nsvg__isspace(*s)) s++;
311 if (*s) { *s++ = '\0'; }
312
313 /* Get attribs */
314 while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) {
315 char* name = NULL;
316 char* value = NULL;
317
318 /* Skip white space before the attrib name */
319 while (*s && nsvg__isspace(*s)) s++;
320 if (!*s) break;
321 if (*s == '/') {
322 end = 1;
323 break;
324 }
325 name = s;
326 /* Find end of the attrib name. */
327 while (*s && !nsvg__isspace(*s) && *s != '=') s++;
328 if (*s) { *s++ = '\0'; }
329 /* Skip until the beginning of the value. */
330 while (*s && *s != '\"' && *s != '\'') s++;
331 if (!*s) break;
332 quote = *s;
333 s++;
334 /* Store value and find the end of it. */
335 value = s;
336 while (*s && *s != quote) s++;
337 if (*s) { *s++ = '\0'; }
338
339 /* Store only well formed attributes */
340 if (name && value) {
341 attr[nattr++] = name;
342 attr[nattr++] = value;
343 }
344 }
345
346 /* List terminator */
347 attr[nattr++] = 0;
348 attr[nattr++] = 0;
349
350 /* Call callbacks. */
351 if (start && startelCb)
352 (*startelCb)(ud, cbname, attr);
353 if (end && endelCb)
354 (*endelCb)(ud, cbname);
355 }
356
357 NANOSVG_SCOPE
nsvg__parseXML(char * input,void (* startelCb)(void * ud,const char * el,const char ** attr),void (* endelCb)(void * ud,const char * el),void (* contentCb)(void * ud,const char * s),void * ud)358 int nsvg__parseXML(char* input,
359 void (*startelCb)(void* ud, const char* el, const char** attr),
360 void (*endelCb)(void* ud, const char* el),
361 void (*contentCb)(void* ud, const char* s),
362 void* ud)
363 {
364 char* s = input;
365 char* mark = s;
366 int state = NSVG_XML_CONTENT;
367 while (*s) {
368 if (*s == '<' && state == NSVG_XML_CONTENT) {
369 /* Start of a tag */
370 *s++ = '\0';
371 nsvg__parseContent(mark, contentCb, ud);
372 mark = s;
373 state = NSVG_XML_TAG;
374 } else if (*s == '>' && state == NSVG_XML_TAG) {
375 /* Start of a content or new tag. */
376 *s++ = '\0';
377 nsvg__parseContent(mark, contentCb, ud);
378 nsvg__parseElement(mark, startelCb, endelCb, ud);
379 mark = s;
380 state = NSVG_XML_CONTENT;
381 } else {
382 s++;
383 }
384 }
385
386 return 1;
387 }
388
389
390 /* Simple SVG parser. */
391
392 #define NSVG_MAX_ATTR 128
393
394 enum NSVGgradientUnits {
395 NSVG_USER_SPACE = 0,
396 NSVG_OBJECT_SPACE = 1
397 };
398
399 #define NSVG_MAX_DASHES 8
400
401 enum NSVGunits {
402 NSVG_UNITS_USER,
403 NSVG_UNITS_PX,
404 NSVG_UNITS_PT,
405 NSVG_UNITS_PC,
406 NSVG_UNITS_MM,
407 NSVG_UNITS_CM,
408 NSVG_UNITS_IN,
409 NSVG_UNITS_PERCENT,
410 NSVG_UNITS_EM,
411 NSVG_UNITS_EX
412 };
413
414 enum NSVGvisible {
415 NSVG_VIS_DISPLAY = 1,
416 NSVG_VIS_VISIBLE = 2
417 };
418
419 typedef struct NSVGcoordinate {
420 float value;
421 int units;
422 } NSVGcoordinate;
423
424 typedef struct NSVGlinearData {
425 NSVGcoordinate x1, y1, x2, y2;
426 } NSVGlinearData;
427
428 typedef struct NSVGradialData {
429 NSVGcoordinate cx, cy, r, fx, fy;
430 } NSVGradialData;
431
432 typedef struct NSVGgradientData
433 {
434 char id[64];
435 char ref[64];
436 char type;
437 union {
438 NSVGlinearData linear;
439 NSVGradialData radial;
440 };
441 char spread;
442 char units;
443 float xform[6];
444 int nstops;
445 NSVGgradientStop* stops;
446 struct NSVGgradientData* next;
447 } NSVGgradientData;
448
449 typedef struct NSVGattrib
450 {
451 char id[64];
452 float xform[6];
453 unsigned int fillColor;
454 unsigned int strokeColor;
455 float opacity;
456 float fillOpacity;
457 float strokeOpacity;
458 char fillGradient[64];
459 char strokeGradient[64];
460 float strokeWidth;
461 float strokeDashOffset;
462 float strokeDashArray[NSVG_MAX_DASHES];
463 int strokeDashCount;
464 char strokeLineJoin;
465 char strokeLineCap;
466 float miterLimit;
467 char fillRule;
468 float fontSize;
469 unsigned int stopColor;
470 float stopOpacity;
471 float stopOffset;
472 char hasFill;
473 char hasStroke;
474 char visible;
475 } NSVGattrib;
476
477 typedef struct NSVGstyles
478 {
479 char* name;
480 char* description;
481 struct NSVGstyles* next;
482 } NSVGstyles;
483
484 typedef struct NSVGparser
485 {
486 NSVGattrib attr[NSVG_MAX_ATTR];
487 int attrHead;
488 float* pts;
489 int npts;
490 int cpts;
491 NSVGpath* plist;
492 NSVGimage* image;
493 NSVGstyles* styles;
494 NSVGgradientData* gradients;
495 NSVGshape* shapesTail;
496 float viewMinx, viewMiny, viewWidth, viewHeight;
497 int alignX, alignY, alignType;
498 float dpi;
499 char pathFlag;
500 char defsFlag;
501 char styleFlag;
502 } NSVGparser;
503
nsvg__xformIdentity(float * t)504 static void nsvg__xformIdentity(float* t)
505 {
506 t[0] = 1.0f; t[1] = 0.0f;
507 t[2] = 0.0f; t[3] = 1.0f;
508 t[4] = 0.0f; t[5] = 0.0f;
509 }
510
nsvg__xformSetTranslation(float * t,float tx,float ty)511 static void nsvg__xformSetTranslation(float* t, float tx, float ty)
512 {
513 t[0] = 1.0f; t[1] = 0.0f;
514 t[2] = 0.0f; t[3] = 1.0f;
515 t[4] = tx; t[5] = ty;
516 }
517
nsvg__xformSetScale(float * t,float sx,float sy)518 static void nsvg__xformSetScale(float* t, float sx, float sy)
519 {
520 t[0] = sx; t[1] = 0.0f;
521 t[2] = 0.0f; t[3] = sy;
522 t[4] = 0.0f; t[5] = 0.0f;
523 }
524
nsvg__xformSetSkewX(float * t,float a)525 static void nsvg__xformSetSkewX(float* t, float a)
526 {
527 t[0] = 1.0f; t[1] = 0.0f;
528 t[2] = tanf(a); t[3] = 1.0f;
529 t[4] = 0.0f; t[5] = 0.0f;
530 }
531
nsvg__xformSetSkewY(float * t,float a)532 static void nsvg__xformSetSkewY(float* t, float a)
533 {
534 t[0] = 1.0f; t[1] = tanf(a);
535 t[2] = 0.0f; t[3] = 1.0f;
536 t[4] = 0.0f; t[5] = 0.0f;
537 }
538
nsvg__xformSetRotation(float * t,float a)539 static void nsvg__xformSetRotation(float* t, float a)
540 {
541 float cs = cosf(a), sn = sinf(a);
542 t[0] = cs; t[1] = sn;
543 t[2] = -sn; t[3] = cs;
544 t[4] = 0.0f; t[5] = 0.0f;
545 }
546
nsvg__xformMultiply(float * t,float * s)547 static void nsvg__xformMultiply(float* t, float* s)
548 {
549 float t0 = t[0] * s[0] + t[1] * s[2];
550 float t2 = t[2] * s[0] + t[3] * s[2];
551 float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
552 t[1] = t[0] * s[1] + t[1] * s[3];
553 t[3] = t[2] * s[1] + t[3] * s[3];
554 t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
555 t[0] = t0;
556 t[2] = t2;
557 t[4] = t4;
558 }
559
nsvg__xformInverse(float * inv,float * t)560 static void nsvg__xformInverse(float* inv, float* t)
561 {
562 double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
563 if (det > -1e-6 && det < 1e-6) {
564 nsvg__xformIdentity(t);
565 return;
566 }
567 invdet = 1.0 / det;
568 inv[0] = (float)(t[3] * invdet);
569 inv[2] = (float)(-t[2] * invdet);
570 inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
571 inv[1] = (float)(-t[1] * invdet);
572 inv[3] = (float)(t[0] * invdet);
573 inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
574 }
575
nsvg__xformPremultiply(float * t,float * s)576 static void nsvg__xformPremultiply(float* t, float* s)
577 {
578 float s2[6];
579 memcpy(s2, s, sizeof(float)*6);
580 nsvg__xformMultiply(s2, t);
581 memcpy(t, s2, sizeof(float)*6);
582 }
583
nsvg__xformPoint(float * dx,float * dy,float x,float y,float * t)584 static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t)
585 {
586 *dx = x*t[0] + y*t[2] + t[4];
587 *dy = x*t[1] + y*t[3] + t[5];
588 }
589
nsvg__xformVec(float * dx,float * dy,float x,float y,float * t)590 static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t)
591 {
592 *dx = x*t[0] + y*t[2];
593 *dy = x*t[1] + y*t[3];
594 }
595
596 #define NSVG_EPSILON (1e-12)
597
nsvg__ptInBounds(float * pt,float * bounds)598 static int nsvg__ptInBounds(float* pt, float* bounds)
599 {
600 return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3];
601 }
602
603
nsvg__evalBezier(double t,double p0,double p1,double p2,double p3)604 static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3)
605 {
606 double it = 1.0-t;
607 return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3;
608 }
609
nsvg__curveBounds(float * bounds,float * curve)610 static void nsvg__curveBounds(float* bounds, float* curve)
611 {
612 int i, j, count;
613 double roots[2], a, b, c, b2ac, t, v;
614 float* v0 = &curve[0];
615 float* v1 = &curve[2];
616 float* v2 = &curve[4];
617 float* v3 = &curve[6];
618
619 /* Start the bounding box by end points */
620 bounds[0] = nsvg__minf(v0[0], v3[0]);
621 bounds[1] = nsvg__minf(v0[1], v3[1]);
622 bounds[2] = nsvg__maxf(v0[0], v3[0]);
623 bounds[3] = nsvg__maxf(v0[1], v3[1]);
624
625 /* Bezier curve fits inside the convex hull of it's control points. */
626 /* If control points are inside the bounds, we're done. */
627 if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds))
628 return;
629
630 /* Add bezier curve inflection points in X and Y. */
631 for (i = 0; i < 2; i++) {
632 a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i];
633 b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i];
634 c = 3.0 * v1[i] - 3.0 * v0[i];
635 count = 0;
636 if (fabs(a) < NSVG_EPSILON) {
637 if (fabs(b) > NSVG_EPSILON) {
638 t = -c / b;
639 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
640 roots[count++] = t;
641 }
642 } else {
643 b2ac = b*b - 4.0*c*a;
644 if (b2ac > NSVG_EPSILON) {
645 t = (-b + sqrt(b2ac)) / (2.0 * a);
646 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
647 roots[count++] = t;
648 t = (-b - sqrt(b2ac)) / (2.0 * a);
649 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
650 roots[count++] = t;
651 }
652 }
653 for (j = 0; j < count; j++) {
654 v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]);
655 bounds[0+i] = nsvg__minf(bounds[0+i], (float)v);
656 bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v);
657 }
658 }
659 }
660
nsvg__createParser(void)661 static NSVGparser* nsvg__createParser(void)
662 {
663 NSVGparser* p;
664 p = (NSVGparser*)NANOSVG_malloc(sizeof(NSVGparser));
665 if (p == NULL) goto error;
666 memset(p, 0, sizeof(NSVGparser));
667
668 p->image = (NSVGimage*)NANOSVG_malloc(sizeof(NSVGimage));
669 if (p->image == NULL) goto error;
670 memset(p->image, 0, sizeof(NSVGimage));
671
672 /* Init style */
673 nsvg__xformIdentity(p->attr[0].xform);
674 memset(p->attr[0].id, 0, sizeof p->attr[0].id);
675 p->attr[0].fillColor = NSVG_RGB(0,0,0);
676 p->attr[0].strokeColor = NSVG_RGB(0,0,0);
677 p->attr[0].opacity = 1;
678 p->attr[0].fillOpacity = 1;
679 p->attr[0].strokeOpacity = 1;
680 p->attr[0].stopOpacity = 1;
681 p->attr[0].strokeWidth = 1;
682 p->attr[0].strokeLineJoin = NSVG_JOIN_MITER;
683 p->attr[0].strokeLineCap = NSVG_CAP_BUTT;
684 p->attr[0].miterLimit = 4;
685 p->attr[0].fillRule = NSVG_FILLRULE_NONZERO;
686 p->attr[0].hasFill = 1;
687 p->attr[0].visible = NSVG_VIS_DISPLAY | NSVG_VIS_VISIBLE;
688
689 return p;
690
691 error:
692 if (p) {
693 if (p->image) NANOSVG_free(p->image);
694 NANOSVG_free(p);
695 }
696 return NULL;
697 }
698
nsvg__deleteStyles(NSVGstyles * style)699 static void nsvg__deleteStyles(NSVGstyles* style) {
700 while (style) {
701 NSVGstyles *next = style->next;
702 if (style->name!= NULL)
703 NANOSVG_free(style->name);
704 if (style->description != NULL)
705 NANOSVG_free(style->description);
706 NANOSVG_free(style);
707 style = next;
708 }
709 }
710
nsvg__deletePaths(NSVGpath * path)711 static void nsvg__deletePaths(NSVGpath* path)
712 {
713 while (path) {
714 NSVGpath *next = path->next;
715 if (path->pts != NULL)
716 NANOSVG_free(path->pts);
717 NANOSVG_free(path);
718 path = next;
719 }
720 }
721
nsvg__deletePaint(NSVGpaint * paint)722 static void nsvg__deletePaint(NSVGpaint* paint)
723 {
724 if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT)
725 NANOSVG_free(paint->gradient);
726 }
727
nsvg__deleteGradientData(NSVGgradientData * grad)728 static void nsvg__deleteGradientData(NSVGgradientData* grad)
729 {
730 NSVGgradientData* next;
731 while (grad != NULL) {
732 next = grad->next;
733 NANOSVG_free(grad->stops);
734 NANOSVG_free(grad);
735 grad = next;
736 }
737 }
738
nsvg__deleteParser(NSVGparser * p)739 static void nsvg__deleteParser(NSVGparser* p)
740 {
741 if (p != NULL) {
742 nsvg__deleteStyles(p->styles);
743 nsvg__deletePaths(p->plist);
744 nsvg__deleteGradientData(p->gradients);
745 nsvgDelete(p->image);
746 NANOSVG_free(p->pts);
747 NANOSVG_free(p);
748 }
749 }
750
nsvg__resetPath(NSVGparser * p)751 static void nsvg__resetPath(NSVGparser* p)
752 {
753 p->npts = 0;
754 }
755
nsvg__addPoint(NSVGparser * p,float x,float y)756 static void nsvg__addPoint(NSVGparser* p, float x, float y)
757 {
758 if (p->npts+1 > p->cpts) {
759 p->cpts = p->cpts ? p->cpts*2 : 8;
760 p->pts = (float*)NANOSVG_realloc(p->pts, p->cpts*2*sizeof(float));
761 if (!p->pts) return;
762 }
763 p->pts[p->npts*2+0] = x;
764 p->pts[p->npts*2+1] = y;
765 p->npts++;
766 }
767
nsvg__moveTo(NSVGparser * p,float x,float y)768 static void nsvg__moveTo(NSVGparser* p, float x, float y)
769 {
770 if (p->npts > 0) {
771 p->pts[(p->npts-1)*2+0] = x;
772 p->pts[(p->npts-1)*2+1] = y;
773 } else {
774 nsvg__addPoint(p, x, y);
775 }
776 }
777
nsvg__lineTo(NSVGparser * p,float x,float y)778 static void nsvg__lineTo(NSVGparser* p, float x, float y)
779 {
780 float px,py, dx,dy;
781 if (p->npts > 0) {
782 px = p->pts[(p->npts-1)*2+0];
783 py = p->pts[(p->npts-1)*2+1];
784 dx = x - px;
785 dy = y - py;
786 nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f);
787 nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f);
788 nsvg__addPoint(p, x, y);
789 }
790 }
791
nsvg__cubicBezTo(NSVGparser * p,float cpx1,float cpy1,float cpx2,float cpy2,float x,float y)792 static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y)
793 {
794 if (p->npts > 0) {
795 nsvg__addPoint(p, cpx1, cpy1);
796 nsvg__addPoint(p, cpx2, cpy2);
797 nsvg__addPoint(p, x, y);
798 }
799 }
800
nsvg__getAttr(NSVGparser * p)801 static NSVGattrib* nsvg__getAttr(NSVGparser* p)
802 {
803 return &p->attr[p->attrHead];
804 }
805
nsvg__pushAttr(NSVGparser * p)806 static void nsvg__pushAttr(NSVGparser* p)
807 {
808 if (p->attrHead < NSVG_MAX_ATTR-1) {
809 p->attrHead++;
810 memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib));
811 }
812 }
813
nsvg__popAttr(NSVGparser * p)814 static void nsvg__popAttr(NSVGparser* p)
815 {
816 if (p->attrHead > 0)
817 p->attrHead--;
818 }
819
nsvg__actualOrigX(NSVGparser * p)820 static float nsvg__actualOrigX(NSVGparser* p)
821 {
822 return p->viewMinx;
823 }
824
nsvg__actualOrigY(NSVGparser * p)825 static float nsvg__actualOrigY(NSVGparser* p)
826 {
827 return p->viewMiny;
828 }
829
nsvg__actualWidth(NSVGparser * p)830 static float nsvg__actualWidth(NSVGparser* p)
831 {
832 return p->viewWidth;
833 }
834
nsvg__actualHeight(NSVGparser * p)835 static float nsvg__actualHeight(NSVGparser* p)
836 {
837 return p->viewHeight;
838 }
839
nsvg__actualLength(NSVGparser * p)840 static float nsvg__actualLength(NSVGparser* p)
841 {
842 float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p);
843 return sqrtf(w*w + h*h) / sqrtf(2.0f);
844 }
845
nsvg__convertToPixels(NSVGparser * p,NSVGcoordinate c,float orig,float length)846 static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length)
847 {
848 NSVGattrib* attr = nsvg__getAttr(p);
849 switch (c.units) {
850 case NSVG_UNITS_USER: return c.value;
851 case NSVG_UNITS_PX: return c.value;
852 case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi;
853 case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi;
854 case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi;
855 case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi;
856 case NSVG_UNITS_IN: return c.value * p->dpi;
857 case NSVG_UNITS_EM: return c.value * attr->fontSize;
858 case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; /* x-height of Helvetica. */
859 case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length;
860 default: return c.value;
861 }
862 return c.value;
863 }
864
nsvg__findGradientData(NSVGparser * p,const char * id)865 static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id)
866 {
867 NSVGgradientData* grad = p->gradients;
868 if (id == NULL || *id == '\0')
869 return NULL;
870 while (grad != NULL) {
871 if (strcmp(grad->id, id) == 0)
872 return grad;
873 grad = grad->next;
874 }
875 return NULL;
876 }
877
nsvg__createGradient(NSVGparser * p,const char * id,const float * localBounds,char * paintType)878 static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, char* paintType)
879 {
880 NSVGattrib* attr = nsvg__getAttr(p);
881 NSVGgradientData* data = NULL;
882 NSVGgradientData* ref = NULL;
883 NSVGgradientStop* stops = NULL;
884 NSVGgradient* grad;
885 float ox, oy, sw, sh, sl;
886 int nstops = 0;
887 int refIter;
888
889 data = nsvg__findGradientData(p, id);
890 if (data == NULL) return NULL;
891
892 /* TODO: use ref to fill in all unset values too. */
893 ref = data;
894 refIter = 0;
895 while (ref != NULL) {
896 NSVGgradientData* nextRef = NULL;
897 if (stops == NULL && ref->stops != NULL) {
898 stops = ref->stops;
899 nstops = ref->nstops;
900 break;
901 }
902 nextRef = nsvg__findGradientData(p, ref->ref);
903 if (nextRef == ref) break; /* prevent infite loops on malformed data */
904 ref = nextRef;
905 refIter++;
906 if (refIter > 32) break; /* prevent infite loops on malformed data */
907 }
908 if (stops == NULL) return NULL;
909
910 grad = (NSVGgradient*)NANOSVG_malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1));
911 if (grad == NULL) return NULL;
912
913 /* The shape width and height. */
914 if (data->units == NSVG_OBJECT_SPACE) {
915 ox = localBounds[0];
916 oy = localBounds[1];
917 sw = localBounds[2] - localBounds[0];
918 sh = localBounds[3] - localBounds[1];
919 } else {
920 ox = nsvg__actualOrigX(p);
921 oy = nsvg__actualOrigY(p);
922 sw = nsvg__actualWidth(p);
923 sh = nsvg__actualHeight(p);
924 }
925 sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f);
926
927 if (data->type == NSVG_PAINT_LINEAR_GRADIENT) {
928 float x1, y1, x2, y2, dx, dy;
929 x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw);
930 y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh);
931 x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw);
932 y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh);
933 /* Calculate transform aligned to the line */
934 dx = x2 - x1;
935 dy = y2 - y1;
936 grad->xform[0] = dy; grad->xform[1] = -dx;
937 grad->xform[2] = dx; grad->xform[3] = dy;
938 grad->xform[4] = x1; grad->xform[5] = y1;
939 } else {
940 float cx, cy, fx, fy, r;
941 cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw);
942 cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh);
943 fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw);
944 fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh);
945 r = nsvg__convertToPixels(p, data->radial.r, 0, sl);
946 /* Calculate transform aligned to the circle */
947 grad->xform[0] = r; grad->xform[1] = 0;
948 grad->xform[2] = 0; grad->xform[3] = r;
949 grad->xform[4] = cx; grad->xform[5] = cy;
950 grad->fx = fx / r;
951 grad->fy = fy / r;
952 }
953
954 nsvg__xformMultiply(grad->xform, data->xform);
955 nsvg__xformMultiply(grad->xform, attr->xform);
956
957 grad->spread = data->spread;
958 memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop));
959 grad->nstops = nstops;
960
961 *paintType = data->type;
962
963 return grad;
964 }
965
nsvg__getAverageScale(float * t)966 static float nsvg__getAverageScale(float* t)
967 {
968 float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
969 float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
970 return (sx + sy) * 0.5f;
971 }
972
nsvg__getLocalBounds(float * bounds,NSVGshape * shape,float * xform)973 static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform)
974 {
975 NSVGpath* path;
976 float curve[4*2], curveBounds[4];
977 int i, first = 1;
978 for (path = shape->paths; path != NULL; path = path->next) {
979 nsvg__xformPoint(&curve[0], &curve[1], path->pts[0], path->pts[1], xform);
980 for (i = 0; i < path->npts-1; i += 3) {
981 nsvg__xformPoint(&curve[2], &curve[3], path->pts[(i+1)*2], path->pts[(i+1)*2+1], xform);
982 nsvg__xformPoint(&curve[4], &curve[5], path->pts[(i+2)*2], path->pts[(i+2)*2+1], xform);
983 nsvg__xformPoint(&curve[6], &curve[7], path->pts[(i+3)*2], path->pts[(i+3)*2+1], xform);
984 nsvg__curveBounds(curveBounds, curve);
985 if (first) {
986 bounds[0] = curveBounds[0];
987 bounds[1] = curveBounds[1];
988 bounds[2] = curveBounds[2];
989 bounds[3] = curveBounds[3];
990 first = 0;
991 } else {
992 bounds[0] = nsvg__minf(bounds[0], curveBounds[0]);
993 bounds[1] = nsvg__minf(bounds[1], curveBounds[1]);
994 bounds[2] = nsvg__maxf(bounds[2], curveBounds[2]);
995 bounds[3] = nsvg__maxf(bounds[3], curveBounds[3]);
996 }
997 curve[0] = curve[6];
998 curve[1] = curve[7];
999 }
1000 }
1001 }
1002
nsvg__addShape(NSVGparser * p)1003 static void nsvg__addShape(NSVGparser* p)
1004 {
1005 NSVGattrib* attr = nsvg__getAttr(p);
1006 float scale = 1.0f;
1007 NSVGshape* shape;
1008 NSVGpath* path;
1009 int i;
1010
1011 if (p->plist == NULL)
1012 return;
1013
1014 shape = (NSVGshape*)NANOSVG_malloc(sizeof(NSVGshape));
1015 if (shape == NULL) goto error;
1016 memset(shape, 0, sizeof(NSVGshape));
1017
1018 memcpy(shape->id, attr->id, sizeof shape->id);
1019 scale = nsvg__getAverageScale(attr->xform);
1020 shape->strokeWidth = attr->strokeWidth * scale;
1021 shape->strokeDashOffset = attr->strokeDashOffset * scale;
1022 shape->strokeDashCount = (char)attr->strokeDashCount;
1023 for (i = 0; i < attr->strokeDashCount; i++)
1024 shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale;
1025 shape->strokeLineJoin = attr->strokeLineJoin;
1026 shape->strokeLineCap = attr->strokeLineCap;
1027 shape->miterLimit = attr->miterLimit;
1028 shape->fillRule = attr->fillRule;
1029 shape->opacity = attr->opacity;
1030
1031 shape->paths = p->plist;
1032 p->plist = NULL;
1033
1034 /* Calculate shape bounds */
1035 shape->bounds[0] = shape->paths->bounds[0];
1036 shape->bounds[1] = shape->paths->bounds[1];
1037 shape->bounds[2] = shape->paths->bounds[2];
1038 shape->bounds[3] = shape->paths->bounds[3];
1039 for (path = shape->paths->next; path != NULL; path = path->next) {
1040 shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]);
1041 shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]);
1042 shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]);
1043 shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]);
1044 }
1045
1046 /* Set fill */
1047 if (attr->hasFill == 0) {
1048 shape->fill.type = NSVG_PAINT_NONE;
1049 } else if (attr->hasFill == 1) {
1050 shape->fill.type = NSVG_PAINT_COLOR;
1051 shape->fill.color = attr->fillColor;
1052 shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24;
1053 } else if (attr->hasFill == 2) {
1054 float inv[6], localBounds[4];
1055 nsvg__xformInverse(inv, attr->xform);
1056 nsvg__getLocalBounds(localBounds, shape, inv);
1057 shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type);
1058 if (shape->fill.gradient == NULL) {
1059 shape->fill.type = NSVG_PAINT_NONE;
1060 }
1061 }
1062
1063 /* Set stroke */
1064 if (attr->hasStroke == 0) {
1065 shape->stroke.type = NSVG_PAINT_NONE;
1066 } else if (attr->hasStroke == 1) {
1067 shape->stroke.type = NSVG_PAINT_COLOR;
1068 shape->stroke.color = attr->strokeColor;
1069 shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24;
1070 } else if (attr->hasStroke == 2) {
1071 float inv[6], localBounds[4];
1072 nsvg__xformInverse(inv, attr->xform);
1073 nsvg__getLocalBounds(localBounds, shape, inv);
1074 shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type);
1075 if (shape->stroke.gradient == NULL)
1076 shape->stroke.type = NSVG_PAINT_NONE;
1077 }
1078
1079 /* Set flags */
1080 shape->flags = ((attr->visible & NSVG_VIS_DISPLAY) && (attr->visible & NSVG_VIS_VISIBLE) ? NSVG_FLAGS_VISIBLE : 0x00);
1081
1082 /* Add to tail */
1083 if (p->image->shapes == NULL)
1084 p->image->shapes = shape;
1085 else
1086 p->shapesTail->next = shape;
1087 p->shapesTail = shape;
1088
1089 return;
1090
1091 error:
1092 if (shape) NANOSVG_free(shape);
1093 }
1094
nsvg__addPath(NSVGparser * p,char closed)1095 static void nsvg__addPath(NSVGparser* p, char closed)
1096 {
1097 NSVGattrib* attr = nsvg__getAttr(p);
1098 NSVGpath* path = NULL;
1099 float bounds[4];
1100 float* curve;
1101 int i;
1102
1103 if (p->npts < 4)
1104 return;
1105
1106 if (closed)
1107 nsvg__lineTo(p, p->pts[0], p->pts[1]);
1108
1109 /* Expect 1 + N*3 points (N = number of cubic bezier segments). */
1110 if ((p->npts % 3) != 1)
1111 return;
1112
1113 path = (NSVGpath*)NANOSVG_malloc(sizeof(NSVGpath));
1114 if (path == NULL) goto error;
1115 memset(path, 0, sizeof(NSVGpath));
1116
1117 path->pts = (float*)NANOSVG_malloc(p->npts*2*sizeof(float));
1118 if (path->pts == NULL) goto error;
1119 path->closed = closed;
1120 path->npts = p->npts;
1121
1122 /* Transform path. */
1123 for (i = 0; i < p->npts; ++i)
1124 nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform);
1125
1126 /* Find bounds */
1127 for (i = 0; i < path->npts-1; i += 3) {
1128 curve = &path->pts[i*2];
1129 nsvg__curveBounds(bounds, curve);
1130 if (i == 0) {
1131 path->bounds[0] = bounds[0];
1132 path->bounds[1] = bounds[1];
1133 path->bounds[2] = bounds[2];
1134 path->bounds[3] = bounds[3];
1135 } else {
1136 path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]);
1137 path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]);
1138 path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]);
1139 path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]);
1140 }
1141 }
1142
1143 path->next = p->plist;
1144 p->plist = path;
1145
1146 return;
1147
1148 error:
1149 if (path != NULL) {
1150 if (path->pts != NULL) NANOSVG_free(path->pts);
1151 NANOSVG_free(path);
1152 }
1153 }
1154
1155 /* We roll our own string to float because the std library one uses locale and messes things up. */
nsvg__atof(const char * s)1156 static double nsvg__atof(const char* s)
1157 {
1158 char* cur = (char*)s;
1159 char* end = NULL;
1160 double res = 0.0, sign = 1.0;
1161 #if defined(_MSC_VER) && (_MSC_VER == 1200)
1162 __int64 intPart = 0, fracPart = 0;
1163 #else
1164 long long intPart = 0, fracPart = 0;
1165 #endif
1166 char hasIntPart = 0, hasFracPart = 0;
1167
1168 /* Parse optional sign */
1169 if (*cur == '+') {
1170 cur++;
1171 } else if (*cur == '-') {
1172 sign = -1;
1173 cur++;
1174 }
1175
1176 /* Parse integer part */
1177 if (nsvg__isdigit(*cur)) {
1178 /* Parse digit sequence */
1179 #if defined(_MSC_VER) && (_MSC_VER == 1200)
1180 intPart = strtol(cur, &end, 10);
1181 #else
1182 intPart = strtoll(cur, &end, 10);
1183 #endif
1184 if (cur != end) {
1185 res = (double)intPart;
1186 hasIntPart = 1;
1187 cur = end;
1188 }
1189 }
1190
1191 /* Parse fractional part. */
1192 if (*cur == '.') {
1193 cur++; /* Skip '.' */
1194 if (nsvg__isdigit(*cur)) {
1195 /* Parse digit sequence */
1196 #if defined(_MSC_VER) && (_MSC_VER == 1200)
1197 fracPart = strtol(cur, &end, 10);
1198 #else
1199 fracPart = strtoll(cur, &end, 10);
1200 #endif
1201 if (cur != end) {
1202 res += (double)fracPart / pow(10.0, (double)(end - cur));
1203 hasFracPart = 1;
1204 cur = end;
1205 }
1206 }
1207 }
1208
1209 /* A valid number should have integer or fractional part. */
1210 if (!hasIntPart && !hasFracPart)
1211 return 0.0;
1212
1213 /* Parse optional exponent */
1214 if (*cur == 'e' || *cur == 'E') {
1215 int expPart = 0;
1216 cur++; /* skip 'E' */
1217 expPart = strtol(cur, &end, 10); /* Parse digit sequence with sign */
1218 if (cur != end) {
1219 res *= pow(10.0, (double)expPart);
1220 }
1221 }
1222
1223 return res * sign;
1224 }
1225
1226
nsvg__parseNumber(const char * s,char * it,const int size)1227 static const char* nsvg__parseNumber(const char* s, char* it, const int size)
1228 {
1229 const int last = size-1;
1230 int i = 0;
1231
1232 /* sign */
1233 if (*s == '-' || *s == '+') {
1234 if (i < last) it[i++] = *s;
1235 s++;
1236 }
1237 /* integer part */
1238 while (*s && nsvg__isdigit(*s)) {
1239 if (i < last) it[i++] = *s;
1240 s++;
1241 }
1242 if (*s == '.') {
1243 /* decimal point */
1244 if (i < last) it[i++] = *s;
1245 s++;
1246 /* fraction part */
1247 while (*s && nsvg__isdigit(*s)) {
1248 if (i < last) it[i++] = *s;
1249 s++;
1250 }
1251 }
1252 /* exponent */
1253 if (*s == 'e' || *s == 'E') {
1254 if (i < last) it[i++] = *s;
1255 s++;
1256 if (*s == '-' || *s == '+') {
1257 if (i < last) it[i++] = *s;
1258 s++;
1259 }
1260 while (*s && nsvg__isdigit(*s)) {
1261 if (i < last) it[i++] = *s;
1262 s++;
1263 }
1264 }
1265 it[i] = '\0';
1266
1267 return s;
1268 }
1269
nsvg__getNextPathItem(const char * s,char * it)1270 static const char* nsvg__getNextPathItem(const char* s, char* it)
1271 {
1272 it[0] = '\0';
1273 /* Skip white spaces and commas */
1274 while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1275 if (!*s) return s;
1276 if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) {
1277 s = nsvg__parseNumber(s, it, 64);
1278 } else {
1279 /* Parse command */
1280 it[0] = *s++;
1281 it[1] = '\0';
1282 return s;
1283 }
1284
1285 return s;
1286 }
1287
nsvg__parseColorHex(const char * str)1288 static unsigned int nsvg__parseColorHex(const char* str)
1289 {
1290 unsigned int c = 0, r = 0, g = 0, b = 0;
1291 int n = 0;
1292 str++; /* skip # */
1293 /* Calculate number of characters. */
1294 while(str[n] && !nsvg__isspace(str[n]))
1295 n++;
1296 if (n == 6) {
1297 sscanf(str, "%x", &c);
1298 } else if (n == 3) {
1299 sscanf(str, "%x", &c);
1300 c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8);
1301 c |= c<<4;
1302 }
1303 r = (c >> 16) & 0xff;
1304 g = (c >> 8) & 0xff;
1305 b = c & 0xff;
1306 return NSVG_RGB(r,g,b);
1307 }
1308
nsvg__parseColorRGB(const char * str)1309 static unsigned int nsvg__parseColorRGB(const char* str)
1310 {
1311 int r = -1, g = -1, b = -1;
1312 char s1[32]="", s2[32]="";
1313 sscanf(str + 4, "%d%[%%, \t]%d%[%%, \t]%d", &r, s1, &g, s2, &b);
1314 if (strchr(s1, '%')) {
1315 return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100);
1316 } else {
1317 return NSVG_RGB(r,g,b);
1318 }
1319 }
1320
1321 typedef struct NSVGNamedColor {
1322 const char* name;
1323 unsigned int color;
1324 } NSVGNamedColor;
1325
1326 NSVGNamedColor nsvg__colors[] = {
1327
1328 { "red", NSVG_RGB(255, 0, 0) },
1329 { "green", NSVG_RGB( 0, 128, 0) },
1330 { "blue", NSVG_RGB( 0, 0, 255) },
1331 { "yellow", NSVG_RGB(255, 255, 0) },
1332 { "cyan", NSVG_RGB( 0, 255, 255) },
1333 { "magenta", NSVG_RGB(255, 0, 255) },
1334 { "black", NSVG_RGB( 0, 0, 0) },
1335 { "grey", NSVG_RGB(128, 128, 128) },
1336 { "gray", NSVG_RGB(128, 128, 128) },
1337 { "white", NSVG_RGB(255, 255, 255) },
1338
1339 #ifdef NANOSVG_ALL_COLOR_KEYWORDS
1340 { "aliceblue", NSVG_RGB(240, 248, 255) },
1341 { "antiquewhite", NSVG_RGB(250, 235, 215) },
1342 { "aqua", NSVG_RGB( 0, 255, 255) },
1343 { "aquamarine", NSVG_RGB(127, 255, 212) },
1344 { "azure", NSVG_RGB(240, 255, 255) },
1345 { "beige", NSVG_RGB(245, 245, 220) },
1346 { "bisque", NSVG_RGB(255, 228, 196) },
1347 { "blanchedalmond", NSVG_RGB(255, 235, 205) },
1348 { "blueviolet", NSVG_RGB(138, 43, 226) },
1349 { "brown", NSVG_RGB(165, 42, 42) },
1350 { "burlywood", NSVG_RGB(222, 184, 135) },
1351 { "cadetblue", NSVG_RGB( 95, 158, 160) },
1352 { "chartreuse", NSVG_RGB(127, 255, 0) },
1353 { "chocolate", NSVG_RGB(210, 105, 30) },
1354 { "coral", NSVG_RGB(255, 127, 80) },
1355 { "cornflowerblue", NSVG_RGB(100, 149, 237) },
1356 { "cornsilk", NSVG_RGB(255, 248, 220) },
1357 { "crimson", NSVG_RGB(220, 20, 60) },
1358 { "darkblue", NSVG_RGB( 0, 0, 139) },
1359 { "darkcyan", NSVG_RGB( 0, 139, 139) },
1360 { "darkgoldenrod", NSVG_RGB(184, 134, 11) },
1361 { "darkgray", NSVG_RGB(169, 169, 169) },
1362 { "darkgreen", NSVG_RGB( 0, 100, 0) },
1363 { "darkgrey", NSVG_RGB(169, 169, 169) },
1364 { "darkkhaki", NSVG_RGB(189, 183, 107) },
1365 { "darkmagenta", NSVG_RGB(139, 0, 139) },
1366 { "darkolivegreen", NSVG_RGB( 85, 107, 47) },
1367 { "darkorange", NSVG_RGB(255, 140, 0) },
1368 { "darkorchid", NSVG_RGB(153, 50, 204) },
1369 { "darkred", NSVG_RGB(139, 0, 0) },
1370 { "darksalmon", NSVG_RGB(233, 150, 122) },
1371 { "darkseagreen", NSVG_RGB(143, 188, 143) },
1372 { "darkslateblue", NSVG_RGB( 72, 61, 139) },
1373 { "darkslategray", NSVG_RGB( 47, 79, 79) },
1374 { "darkslategrey", NSVG_RGB( 47, 79, 79) },
1375 { "darkturquoise", NSVG_RGB( 0, 206, 209) },
1376 { "darkviolet", NSVG_RGB(148, 0, 211) },
1377 { "deeppink", NSVG_RGB(255, 20, 147) },
1378 { "deepskyblue", NSVG_RGB( 0, 191, 255) },
1379 { "dimgray", NSVG_RGB(105, 105, 105) },
1380 { "dimgrey", NSVG_RGB(105, 105, 105) },
1381 { "dodgerblue", NSVG_RGB( 30, 144, 255) },
1382 { "firebrick", NSVG_RGB(178, 34, 34) },
1383 { "floralwhite", NSVG_RGB(255, 250, 240) },
1384 { "forestgreen", NSVG_RGB( 34, 139, 34) },
1385 { "fuchsia", NSVG_RGB(255, 0, 255) },
1386 { "gainsboro", NSVG_RGB(220, 220, 220) },
1387 { "ghostwhite", NSVG_RGB(248, 248, 255) },
1388 { "gold", NSVG_RGB(255, 215, 0) },
1389 { "goldenrod", NSVG_RGB(218, 165, 32) },
1390 { "greenyellow", NSVG_RGB(173, 255, 47) },
1391 { "honeydew", NSVG_RGB(240, 255, 240) },
1392 { "hotpink", NSVG_RGB(255, 105, 180) },
1393 { "indianred", NSVG_RGB(205, 92, 92) },
1394 { "indigo", NSVG_RGB( 75, 0, 130) },
1395 { "ivory", NSVG_RGB(255, 255, 240) },
1396 { "khaki", NSVG_RGB(240, 230, 140) },
1397 { "lavender", NSVG_RGB(230, 230, 250) },
1398 { "lavenderblush", NSVG_RGB(255, 240, 245) },
1399 { "lawngreen", NSVG_RGB(124, 252, 0) },
1400 { "lemonchiffon", NSVG_RGB(255, 250, 205) },
1401 { "lightblue", NSVG_RGB(173, 216, 230) },
1402 { "lightcoral", NSVG_RGB(240, 128, 128) },
1403 { "lightcyan", NSVG_RGB(224, 255, 255) },
1404 { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) },
1405 { "lightgray", NSVG_RGB(211, 211, 211) },
1406 { "lightgreen", NSVG_RGB(144, 238, 144) },
1407 { "lightgrey", NSVG_RGB(211, 211, 211) },
1408 { "lightpink", NSVG_RGB(255, 182, 193) },
1409 { "lightsalmon", NSVG_RGB(255, 160, 122) },
1410 { "lightseagreen", NSVG_RGB( 32, 178, 170) },
1411 { "lightskyblue", NSVG_RGB(135, 206, 250) },
1412 { "lightslategray", NSVG_RGB(119, 136, 153) },
1413 { "lightslategrey", NSVG_RGB(119, 136, 153) },
1414 { "lightsteelblue", NSVG_RGB(176, 196, 222) },
1415 { "lightyellow", NSVG_RGB(255, 255, 224) },
1416 { "lime", NSVG_RGB( 0, 255, 0) },
1417 { "limegreen", NSVG_RGB( 50, 205, 50) },
1418 { "linen", NSVG_RGB(250, 240, 230) },
1419 { "maroon", NSVG_RGB(128, 0, 0) },
1420 { "mediumaquamarine", NSVG_RGB(102, 205, 170) },
1421 { "mediumblue", NSVG_RGB( 0, 0, 205) },
1422 { "mediumorchid", NSVG_RGB(186, 85, 211) },
1423 { "mediumpurple", NSVG_RGB(147, 112, 219) },
1424 { "mediumseagreen", NSVG_RGB( 60, 179, 113) },
1425 { "mediumslateblue", NSVG_RGB(123, 104, 238) },
1426 { "mediumspringgreen", NSVG_RGB( 0, 250, 154) },
1427 { "mediumturquoise", NSVG_RGB( 72, 209, 204) },
1428 { "mediumvioletred", NSVG_RGB(199, 21, 133) },
1429 { "midnightblue", NSVG_RGB( 25, 25, 112) },
1430 { "mintcream", NSVG_RGB(245, 255, 250) },
1431 { "mistyrose", NSVG_RGB(255, 228, 225) },
1432 { "moccasin", NSVG_RGB(255, 228, 181) },
1433 { "navajowhite", NSVG_RGB(255, 222, 173) },
1434 { "navy", NSVG_RGB( 0, 0, 128) },
1435 { "oldlace", NSVG_RGB(253, 245, 230) },
1436 { "olive", NSVG_RGB(128, 128, 0) },
1437 { "olivedrab", NSVG_RGB(107, 142, 35) },
1438 { "orange", NSVG_RGB(255, 165, 0) },
1439 { "orangered", NSVG_RGB(255, 69, 0) },
1440 { "orchid", NSVG_RGB(218, 112, 214) },
1441 { "palegoldenrod", NSVG_RGB(238, 232, 170) },
1442 { "palegreen", NSVG_RGB(152, 251, 152) },
1443 { "paleturquoise", NSVG_RGB(175, 238, 238) },
1444 { "palevioletred", NSVG_RGB(219, 112, 147) },
1445 { "papayawhip", NSVG_RGB(255, 239, 213) },
1446 { "peachpuff", NSVG_RGB(255, 218, 185) },
1447 { "peru", NSVG_RGB(205, 133, 63) },
1448 { "pink", NSVG_RGB(255, 192, 203) },
1449 { "plum", NSVG_RGB(221, 160, 221) },
1450 { "powderblue", NSVG_RGB(176, 224, 230) },
1451 { "purple", NSVG_RGB(128, 0, 128) },
1452 { "rosybrown", NSVG_RGB(188, 143, 143) },
1453 { "royalblue", NSVG_RGB( 65, 105, 225) },
1454 { "saddlebrown", NSVG_RGB(139, 69, 19) },
1455 { "salmon", NSVG_RGB(250, 128, 114) },
1456 { "sandybrown", NSVG_RGB(244, 164, 96) },
1457 { "seagreen", NSVG_RGB( 46, 139, 87) },
1458 { "seashell", NSVG_RGB(255, 245, 238) },
1459 { "sienna", NSVG_RGB(160, 82, 45) },
1460 { "silver", NSVG_RGB(192, 192, 192) },
1461 { "skyblue", NSVG_RGB(135, 206, 235) },
1462 { "slateblue", NSVG_RGB(106, 90, 205) },
1463 { "slategray", NSVG_RGB(112, 128, 144) },
1464 { "slategrey", NSVG_RGB(112, 128, 144) },
1465 { "snow", NSVG_RGB(255, 250, 250) },
1466 { "springgreen", NSVG_RGB( 0, 255, 127) },
1467 { "steelblue", NSVG_RGB( 70, 130, 180) },
1468 { "tan", NSVG_RGB(210, 180, 140) },
1469 { "teal", NSVG_RGB( 0, 128, 128) },
1470 { "thistle", NSVG_RGB(216, 191, 216) },
1471 { "tomato", NSVG_RGB(255, 99, 71) },
1472 { "turquoise", NSVG_RGB( 64, 224, 208) },
1473 { "violet", NSVG_RGB(238, 130, 238) },
1474 { "wheat", NSVG_RGB(245, 222, 179) },
1475 { "whitesmoke", NSVG_RGB(245, 245, 245) },
1476 { "yellowgreen", NSVG_RGB(154, 205, 50) },
1477 #endif
1478 };
1479
nsvg__parseColorName(const char * str)1480 static unsigned int nsvg__parseColorName(const char* str)
1481 {
1482 int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor);
1483
1484 for (i = 0; i < ncolors; i++) {
1485 if (strcmp(nsvg__colors[i].name, str) == 0) {
1486 return nsvg__colors[i].color;
1487 }
1488 }
1489
1490 return NSVG_RGB(128, 128, 128);
1491 }
1492
nsvg__parseColor(const char * str)1493 static unsigned int nsvg__parseColor(const char* str)
1494 {
1495 size_t len = 0;
1496 while(*str == ' ') ++str;
1497 len = strlen(str);
1498 if (len >= 1 && *str == '#')
1499 return nsvg__parseColorHex(str);
1500 else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(')
1501 return nsvg__parseColorRGB(str);
1502 return nsvg__parseColorName(str);
1503 }
1504
nsvg__parseOpacity(const char * str)1505 static float nsvg__parseOpacity(const char* str)
1506 {
1507 float val = 0;
1508 sscanf(str, "%f", &val);
1509 if (val < 0.0f) val = 0.0f;
1510 if (val > 1.0f) val = 1.0f;
1511 return val;
1512 }
1513
nsvg__parseMiterLimit(const char * str)1514 static float nsvg__parseMiterLimit(const char* str)
1515 {
1516 float val = 0;
1517 sscanf(str, "%f", &val);
1518 if (val < 0.0f) val = 0.0f;
1519 return val;
1520 }
1521
nsvg__parseUnits(const char * units)1522 static int nsvg__parseUnits(const char* units)
1523 {
1524 if (units[0] == 'p' && units[1] == 'x')
1525 return NSVG_UNITS_PX;
1526 else if (units[0] == 'p' && units[1] == 't')
1527 return NSVG_UNITS_PT;
1528 else if (units[0] == 'p' && units[1] == 'c')
1529 return NSVG_UNITS_PC;
1530 else if (units[0] == 'm' && units[1] == 'm')
1531 return NSVG_UNITS_MM;
1532 else if (units[0] == 'c' && units[1] == 'm')
1533 return NSVG_UNITS_CM;
1534 else if (units[0] == 'i' && units[1] == 'n')
1535 return NSVG_UNITS_IN;
1536 else if (units[0] == '%')
1537 return NSVG_UNITS_PERCENT;
1538 else if (units[0] == 'e' && units[1] == 'm')
1539 return NSVG_UNITS_EM;
1540 else if (units[0] == 'e' && units[1] == 'x')
1541 return NSVG_UNITS_EX;
1542 return NSVG_UNITS_USER;
1543 }
1544
nsvg__isCoordinate(const char * s)1545 static int nsvg__isCoordinate(const char* s)
1546 {
1547 /* optional sign */
1548 if (*s == '-' || *s == '+')
1549 s++;
1550 /* must have at least one digit, or start by a dot */
1551 return (nsvg__isdigit(*s) || *s == '.');
1552 }
1553
nsvg__parseCoordinateRaw(const char * str)1554 static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str)
1555 {
1556 NSVGcoordinate coord = {0, NSVG_UNITS_USER};
1557 char units[32]="";
1558 sscanf(str, "%f%s", &coord.value, units);
1559 coord.units = nsvg__parseUnits(units);
1560 return coord;
1561 }
1562
nsvg__coord(float v,int units)1563 static NSVGcoordinate nsvg__coord(float v, int units)
1564 {
1565 NSVGcoordinate coord = {v, units};
1566 return coord;
1567 }
1568
nsvg__parseCoordinate(NSVGparser * p,const char * str,float orig,float length)1569 static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length)
1570 {
1571 NSVGcoordinate coord = nsvg__parseCoordinateRaw(str);
1572 return nsvg__convertToPixels(p, coord, orig, length);
1573 }
1574
nsvg__parseTransformArgs(const char * str,float * args,int maxNa,int * na)1575 static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na)
1576 {
1577 const char* end;
1578 const char* ptr;
1579 char it[64];
1580
1581 *na = 0;
1582 ptr = str;
1583 while (*ptr && *ptr != '(') ++ptr;
1584 if (*ptr == 0)
1585 return 1;
1586 end = ptr;
1587 while (*end && *end != ')') ++end;
1588 if (*end == 0)
1589 return 1;
1590
1591 while (ptr < end) {
1592 if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) {
1593 if (*na >= maxNa) return 0;
1594 ptr = nsvg__parseNumber(ptr, it, 64);
1595 args[(*na)++] = (float)nsvg__atof(it);
1596 } else {
1597 ++ptr;
1598 }
1599 }
1600 return (int)(end - str);
1601 }
1602
1603
nsvg__parseMatrix(float * xform,const char * str)1604 static int nsvg__parseMatrix(float* xform, const char* str)
1605 {
1606 float t[6];
1607 int na = 0;
1608 int len = nsvg__parseTransformArgs(str, t, 6, &na);
1609 if (na != 6) return len;
1610 memcpy(xform, t, sizeof(float)*6);
1611 return len;
1612 }
1613
nsvg__parseTranslate(float * xform,const char * str)1614 static int nsvg__parseTranslate(float* xform, const char* str)
1615 {
1616 float args[2];
1617 float t[6];
1618 int na = 0;
1619 int len = nsvg__parseTransformArgs(str, args, 2, &na);
1620 if (na == 1) args[1] = 0.0;
1621
1622 nsvg__xformSetTranslation(t, args[0], args[1]);
1623 memcpy(xform, t, sizeof(float)*6);
1624 return len;
1625 }
1626
nsvg__parseScale(float * xform,const char * str)1627 static int nsvg__parseScale(float* xform, const char* str)
1628 {
1629 float args[2];
1630 int na = 0;
1631 float t[6];
1632 int len = nsvg__parseTransformArgs(str, args, 2, &na);
1633 if (na == 1) args[1] = args[0];
1634 nsvg__xformSetScale(t, args[0], args[1]);
1635 memcpy(xform, t, sizeof(float)*6);
1636 return len;
1637 }
1638
nsvg__parseSkewX(float * xform,const char * str)1639 static int nsvg__parseSkewX(float* xform, const char* str)
1640 {
1641 float args[1];
1642 int na = 0;
1643 float t[6];
1644 int len = nsvg__parseTransformArgs(str, args, 1, &na);
1645 nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI);
1646 memcpy(xform, t, sizeof(float)*6);
1647 return len;
1648 }
1649
nsvg__parseSkewY(float * xform,const char * str)1650 static int nsvg__parseSkewY(float* xform, const char* str)
1651 {
1652 float args[1];
1653 int na = 0;
1654 float t[6];
1655 int len = nsvg__parseTransformArgs(str, args, 1, &na);
1656 nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI);
1657 memcpy(xform, t, sizeof(float)*6);
1658 return len;
1659 }
1660
nsvg__parseRotate(float * xform,const char * str)1661 static int nsvg__parseRotate(float* xform, const char* str)
1662 {
1663 float args[3];
1664 int na = 0;
1665 float m[6];
1666 float t[6];
1667 int len = nsvg__parseTransformArgs(str, args, 3, &na);
1668 if (na == 1)
1669 args[1] = args[2] = 0.0f;
1670 nsvg__xformIdentity(m);
1671
1672 if (na > 1) {
1673 nsvg__xformSetTranslation(t, -args[1], -args[2]);
1674 nsvg__xformMultiply(m, t);
1675 }
1676
1677 nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI);
1678 nsvg__xformMultiply(m, t);
1679
1680 if (na > 1) {
1681 nsvg__xformSetTranslation(t, args[1], args[2]);
1682 nsvg__xformMultiply(m, t);
1683 }
1684
1685 memcpy(xform, m, sizeof(float)*6);
1686
1687 return len;
1688 }
1689
nsvg__parseTransform(float * xform,const char * str)1690 static void nsvg__parseTransform(float* xform, const char* str)
1691 {
1692 float t[6];
1693 int len;
1694 nsvg__xformIdentity(xform);
1695 while (*str)
1696 {
1697 if (strncmp(str, "matrix", 6) == 0)
1698 len = nsvg__parseMatrix(t, str);
1699 else if (strncmp(str, "translate", 9) == 0)
1700 len = nsvg__parseTranslate(t, str);
1701 else if (strncmp(str, "scale", 5) == 0)
1702 len = nsvg__parseScale(t, str);
1703 else if (strncmp(str, "rotate", 6) == 0)
1704 len = nsvg__parseRotate(t, str);
1705 else if (strncmp(str, "skewX", 5) == 0)
1706 len = nsvg__parseSkewX(t, str);
1707 else if (strncmp(str, "skewY", 5) == 0)
1708 len = nsvg__parseSkewY(t, str);
1709 else{
1710 ++str;
1711 continue;
1712 }
1713 if (len != 0) {
1714 str += len;
1715 } else {
1716 ++str;
1717 continue;
1718 }
1719
1720 nsvg__xformPremultiply(xform, t);
1721 }
1722 }
1723
nsvg__parseUrl(char * id,const char * str)1724 static void nsvg__parseUrl(char* id, const char* str)
1725 {
1726 int i = 0;
1727 str += 4; /* "url("; */
1728 if (*str == '#')
1729 str++;
1730 while (i < 63 && *str != ')') {
1731 id[i] = *str++;
1732 i++;
1733 }
1734 id[i] = '\0';
1735 }
1736
nsvg__parseLineCap(const char * str)1737 static char nsvg__parseLineCap(const char* str)
1738 {
1739 if (strcmp(str, "butt") == 0)
1740 return NSVG_CAP_BUTT;
1741 else if (strcmp(str, "round") == 0)
1742 return NSVG_CAP_ROUND;
1743 else if (strcmp(str, "square") == 0)
1744 return NSVG_CAP_SQUARE;
1745 /* TODO: handle inherit. */
1746 return NSVG_CAP_BUTT;
1747 }
1748
nsvg__parseLineJoin(const char * str)1749 static char nsvg__parseLineJoin(const char* str)
1750 {
1751 if (strcmp(str, "miter") == 0)
1752 return NSVG_JOIN_MITER;
1753 else if (strcmp(str, "round") == 0)
1754 return NSVG_JOIN_ROUND;
1755 else if (strcmp(str, "bevel") == 0)
1756 return NSVG_JOIN_BEVEL;
1757 /* TODO: handle inherit. */
1758 return NSVG_JOIN_MITER;
1759 }
1760
nsvg__parseFillRule(const char * str)1761 static char nsvg__parseFillRule(const char* str)
1762 {
1763 if (strcmp(str, "nonzero") == 0)
1764 return NSVG_FILLRULE_NONZERO;
1765 else if (strcmp(str, "evenodd") == 0)
1766 return NSVG_FILLRULE_EVENODD;
1767 /* TODO: handle inherit. */
1768 return NSVG_FILLRULE_NONZERO;
1769 }
1770
nsvg__getNextDashItem(const char * s,char * it)1771 static const char* nsvg__getNextDashItem(const char* s, char* it)
1772 {
1773 int n = 0;
1774 it[0] = '\0';
1775 /* Skip white spaces and commas */
1776 while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1777 /* Advance until whitespace, comma or end. */
1778 while (*s && (!nsvg__isspace(*s) && *s != ',')) {
1779 if (n < 63)
1780 it[n++] = *s;
1781 s++;
1782 }
1783 it[n++] = '\0';
1784 return s;
1785 }
1786
nsvg__parseStrokeDashArray(NSVGparser * p,const char * str,float * strokeDashArray)1787 static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray)
1788 {
1789 char item[64];
1790 int count = 0, i;
1791 float sum = 0.0f;
1792
1793 /* Handle "none" */
1794 if (str[0] == 'n')
1795 return 0;
1796
1797 /* Parse dashes */
1798 while (*str) {
1799 str = nsvg__getNextDashItem(str, item);
1800 if (!*item) break;
1801 if (count < NSVG_MAX_DASHES)
1802 strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p)));
1803 }
1804
1805 for (i = 0; i < count; i++)
1806 sum += strokeDashArray[i];
1807 if (sum <= 1e-6f)
1808 count = 0;
1809
1810 return count;
1811 }
1812
1813 static void nsvg__parseStyle(NSVGparser* p, const char* str);
1814
nsvg__parseAttr(NSVGparser * p,const char * name,const char * value)1815 static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value)
1816 {
1817 float xform[6];
1818 NSVGattrib* attr = nsvg__getAttr(p);
1819 if (!attr) return 0;
1820
1821 if (strcmp(name, "style") == 0) {
1822 nsvg__parseStyle(p, value);
1823 } else if (strcmp(name, "display") == 0) {
1824 if (strcmp(value, "none") == 0)
1825 attr->visible &= ~NSVG_VIS_DISPLAY;
1826 /* Don't reset ->visible on display:inline, one display:none hides the whole subtree */
1827
1828 } else if (strcmp(name, "visibility") == 0) {
1829 if (strcmp(value, "hidden") == 0) {
1830 attr->visible &= ~NSVG_VIS_VISIBLE;
1831 } else if (strcmp(value, "visible") == 0) {
1832 attr->visible |= NSVG_VIS_VISIBLE;
1833 }
1834 } else if (strcmp(name, "fill") == 0) {
1835 if (strcmp(value, "none") == 0) {
1836 attr->hasFill = 0;
1837 } else if (strncmp(value, "url(", 4) == 0) {
1838 attr->hasFill = 2;
1839 nsvg__parseUrl(attr->fillGradient, value);
1840 } else {
1841 attr->hasFill = 1;
1842 attr->fillColor = nsvg__parseColor(value);
1843 }
1844 } else if (strcmp(name, "opacity") == 0) {
1845 attr->opacity = nsvg__parseOpacity(value);
1846 } else if (strcmp(name, "fill-opacity") == 0) {
1847 attr->fillOpacity = nsvg__parseOpacity(value);
1848 } else if (strcmp(name, "stroke") == 0) {
1849 if (strcmp(value, "none") == 0) {
1850 attr->hasStroke = 0;
1851 } else if (strncmp(value, "url(", 4) == 0) {
1852 attr->hasStroke = 2;
1853 nsvg__parseUrl(attr->strokeGradient, value);
1854 } else {
1855 attr->hasStroke = 1;
1856 attr->strokeColor = nsvg__parseColor(value);
1857 }
1858 } else if (strcmp(name, "stroke-width") == 0) {
1859 attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1860 } else if (strcmp(name, "stroke-dasharray") == 0) {
1861 attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray);
1862 } else if (strcmp(name, "stroke-dashoffset") == 0) {
1863 attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1864 } else if (strcmp(name, "stroke-opacity") == 0) {
1865 attr->strokeOpacity = nsvg__parseOpacity(value);
1866 } else if (strcmp(name, "stroke-linecap") == 0) {
1867 attr->strokeLineCap = nsvg__parseLineCap(value);
1868 } else if (strcmp(name, "stroke-linejoin") == 0) {
1869 attr->strokeLineJoin = nsvg__parseLineJoin(value);
1870 } else if (strcmp(name, "stroke-miterlimit") == 0) {
1871 attr->miterLimit = nsvg__parseMiterLimit(value);
1872 } else if (strcmp(name, "fill-rule") == 0) {
1873 attr->fillRule = nsvg__parseFillRule(value);
1874 } else if (strcmp(name, "font-size") == 0) {
1875 attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1876 } else if (strcmp(name, "transform") == 0) {
1877 nsvg__parseTransform(xform, value);
1878 nsvg__xformPremultiply(attr->xform, xform);
1879 } else if (strcmp(name, "stop-color") == 0) {
1880 attr->stopColor = nsvg__parseColor(value);
1881 } else if (strcmp(name, "stop-opacity") == 0) {
1882 attr->stopOpacity = nsvg__parseOpacity(value);
1883 } else if (strcmp(name, "offset") == 0) {
1884 attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f);
1885 } else if (strcmp(name, "id") == 0) {
1886 strncpy(attr->id, value, 63);
1887 attr->id[63] = '\0';
1888 } else if (strcmp(name, "class") == 0) {
1889 NSVGstyles* style = p->styles;
1890 while (style) {
1891 if (strcmp(style->name + 1, value) == 0) {
1892 break;
1893 }
1894 style = style->next;
1895 }
1896 if (style) {
1897 nsvg__parseStyle(p, style->description);
1898 }
1899 } else {
1900 return 0;
1901 }
1902 return 1;
1903 }
1904
nsvg__parseNameValue(NSVGparser * p,const char * start,const char * end)1905 static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end)
1906 {
1907 const char* str;
1908 const char* val;
1909 char name[512];
1910 char value[512];
1911 int n;
1912
1913 str = start;
1914 while (str < end && *str != ':') ++str;
1915
1916 val = str;
1917
1918 /* Right Trim */
1919 while (str > start && (*str == ':' || nsvg__isspace(*str))) --str;
1920 ++str;
1921
1922 n = (int)(str - start);
1923 if (n > 511) n = 511;
1924 if (n) memcpy(name, start, n);
1925 name[n] = 0;
1926
1927 while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val;
1928
1929 n = (int)(end - val);
1930 if (n > 511) n = 511;
1931 if (n) memcpy(value, val, n);
1932 value[n] = 0;
1933
1934 return nsvg__parseAttr(p, name, value);
1935 }
1936
nsvg__parseStyle(NSVGparser * p,const char * str)1937 static void nsvg__parseStyle(NSVGparser* p, const char* str)
1938 {
1939 const char* start;
1940 const char* end;
1941
1942 while (*str) {
1943 /* Left Trim */
1944 while(*str && nsvg__isspace(*str)) ++str;
1945 start = str;
1946 while(*str && *str != ';') ++str;
1947 end = str;
1948
1949 /* Right Trim */
1950 while (end > start && (*end == ';' || nsvg__isspace(*end))) --end;
1951 ++end;
1952
1953 nsvg__parseNameValue(p, start, end);
1954 if (*str) ++str;
1955 }
1956 }
1957
nsvg__parseAttribs(NSVGparser * p,const char ** attr)1958 static void nsvg__parseAttribs(NSVGparser* p, const char** attr)
1959 {
1960 int i;
1961 for (i = 0; attr[i]; i += 2)
1962 {
1963 if (strcmp(attr[i], "style") == 0)
1964 nsvg__parseStyle(p, attr[i + 1]);
1965 else
1966 nsvg__parseAttr(p, attr[i], attr[i + 1]);
1967 }
1968 }
1969
nsvg__getArgsPerElement(char cmd)1970 static int nsvg__getArgsPerElement(char cmd)
1971 {
1972 switch (cmd) {
1973 case 'v':
1974 case 'V':
1975 case 'h':
1976 case 'H':
1977 return 1;
1978 case 'm':
1979 case 'M':
1980 case 'l':
1981 case 'L':
1982 case 't':
1983 case 'T':
1984 return 2;
1985 case 'q':
1986 case 'Q':
1987 case 's':
1988 case 'S':
1989 return 4;
1990 case 'c':
1991 case 'C':
1992 return 6;
1993 case 'a':
1994 case 'A':
1995 return 7;
1996 case 'z':
1997 case 'Z':
1998 return 0;
1999 }
2000 return -1;
2001 }
2002
nsvg__pathMoveTo(NSVGparser * p,float * cpx,float * cpy,float * args,int rel)2003 static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
2004 {
2005 if (rel) {
2006 *cpx += args[0];
2007 *cpy += args[1];
2008 } else {
2009 *cpx = args[0];
2010 *cpy = args[1];
2011 }
2012 nsvg__moveTo(p, *cpx, *cpy);
2013 }
2014
nsvg__pathLineTo(NSVGparser * p,float * cpx,float * cpy,float * args,int rel)2015 static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
2016 {
2017 if (rel) {
2018 *cpx += args[0];
2019 *cpy += args[1];
2020 } else {
2021 *cpx = args[0];
2022 *cpy = args[1];
2023 }
2024 nsvg__lineTo(p, *cpx, *cpy);
2025 }
2026
nsvg__pathHLineTo(NSVGparser * p,float * cpx,float * cpy,float * args,int rel)2027 static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
2028 {
2029 if (rel)
2030 *cpx += args[0];
2031 else
2032 *cpx = args[0];
2033 nsvg__lineTo(p, *cpx, *cpy);
2034 }
2035
nsvg__pathVLineTo(NSVGparser * p,float * cpx,float * cpy,float * args,int rel)2036 static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
2037 {
2038 if (rel)
2039 *cpy += args[0];
2040 else
2041 *cpy = args[0];
2042 nsvg__lineTo(p, *cpx, *cpy);
2043 }
2044
nsvg__pathCubicBezTo(NSVGparser * p,float * cpx,float * cpy,float * cpx2,float * cpy2,float * args,int rel)2045 static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy,
2046 float* cpx2, float* cpy2, float* args, int rel)
2047 {
2048 float x2, y2, cx1, cy1, cx2, cy2;
2049
2050 if (rel) {
2051 cx1 = *cpx + args[0];
2052 cy1 = *cpy + args[1];
2053 cx2 = *cpx + args[2];
2054 cy2 = *cpy + args[3];
2055 x2 = *cpx + args[4];
2056 y2 = *cpy + args[5];
2057 } else {
2058 cx1 = args[0];
2059 cy1 = args[1];
2060 cx2 = args[2];
2061 cy2 = args[3];
2062 x2 = args[4];
2063 y2 = args[5];
2064 }
2065
2066 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
2067
2068 *cpx2 = cx2;
2069 *cpy2 = cy2;
2070 *cpx = x2;
2071 *cpy = y2;
2072 }
2073
nsvg__pathCubicBezShortTo(NSVGparser * p,float * cpx,float * cpy,float * cpx2,float * cpy2,float * args,int rel)2074 static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy,
2075 float* cpx2, float* cpy2, float* args, int rel)
2076 {
2077 float x1, y1, x2, y2, cx1, cy1, cx2, cy2;
2078
2079 x1 = *cpx;
2080 y1 = *cpy;
2081 if (rel) {
2082 cx2 = *cpx + args[0];
2083 cy2 = *cpy + args[1];
2084 x2 = *cpx + args[2];
2085 y2 = *cpy + args[3];
2086 } else {
2087 cx2 = args[0];
2088 cy2 = args[1];
2089 x2 = args[2];
2090 y2 = args[3];
2091 }
2092
2093 cx1 = 2*x1 - *cpx2;
2094 cy1 = 2*y1 - *cpy2;
2095
2096 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
2097
2098 *cpx2 = cx2;
2099 *cpy2 = cy2;
2100 *cpx = x2;
2101 *cpy = y2;
2102 }
2103
nsvg__pathQuadBezTo(NSVGparser * p,float * cpx,float * cpy,float * cpx2,float * cpy2,float * args,int rel)2104 static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy,
2105 float* cpx2, float* cpy2, float* args, int rel)
2106 {
2107 float x1, y1, x2, y2, cx, cy;
2108 float cx1, cy1, cx2, cy2;
2109
2110 x1 = *cpx;
2111 y1 = *cpy;
2112 if (rel) {
2113 cx = *cpx + args[0];
2114 cy = *cpy + args[1];
2115 x2 = *cpx + args[2];
2116 y2 = *cpy + args[3];
2117 } else {
2118 cx = args[0];
2119 cy = args[1];
2120 x2 = args[2];
2121 y2 = args[3];
2122 }
2123
2124 /* Convert to cubic bezier */
2125 cx1 = x1 + 2.0f/3.0f*(cx - x1);
2126 cy1 = y1 + 2.0f/3.0f*(cy - y1);
2127 cx2 = x2 + 2.0f/3.0f*(cx - x2);
2128 cy2 = y2 + 2.0f/3.0f*(cy - y2);
2129
2130 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
2131
2132 *cpx2 = cx;
2133 *cpy2 = cy;
2134 *cpx = x2;
2135 *cpy = y2;
2136 }
2137
nsvg__pathQuadBezShortTo(NSVGparser * p,float * cpx,float * cpy,float * cpx2,float * cpy2,float * args,int rel)2138 static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy,
2139 float* cpx2, float* cpy2, float* args, int rel)
2140 {
2141 float x1, y1, x2, y2, cx, cy;
2142 float cx1, cy1, cx2, cy2;
2143
2144 x1 = *cpx;
2145 y1 = *cpy;
2146 if (rel) {
2147 x2 = *cpx + args[0];
2148 y2 = *cpy + args[1];
2149 } else {
2150 x2 = args[0];
2151 y2 = args[1];
2152 }
2153
2154 cx = 2*x1 - *cpx2;
2155 cy = 2*y1 - *cpy2;
2156
2157 /* Convert to cubix bezier */
2158 cx1 = x1 + 2.0f/3.0f*(cx - x1);
2159 cy1 = y1 + 2.0f/3.0f*(cy - y1);
2160 cx2 = x2 + 2.0f/3.0f*(cx - x2);
2161 cy2 = y2 + 2.0f/3.0f*(cy - y2);
2162
2163 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
2164
2165 *cpx2 = cx;
2166 *cpy2 = cy;
2167 *cpx = x2;
2168 *cpy = y2;
2169 }
2170
nsvg__sqr(float x)2171 static float nsvg__sqr(float x) { return x*x; }
nsvg__vmag(float x,float y)2172 static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); }
2173
nsvg__vecrat(float ux,float uy,float vx,float vy)2174 static float nsvg__vecrat(float ux, float uy, float vx, float vy)
2175 {
2176 return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy));
2177 }
2178
nsvg__vecang(float ux,float uy,float vx,float vy)2179 static float nsvg__vecang(float ux, float uy, float vx, float vy)
2180 {
2181 float r = nsvg__vecrat(ux,uy, vx,vy);
2182 if (r < -1.0f) r = -1.0f;
2183 if (r > 1.0f) r = 1.0f;
2184 return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r);
2185 }
2186
nsvg__pathArcTo(NSVGparser * p,float * cpx,float * cpy,float * args,int rel)2187 static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
2188 {
2189 /* Ported from canvg (https://code.google.com/p/canvg/) */
2190 float rx, ry, rotx;
2191 float x1, y1, x2, y2, cx, cy, dx, dy, d;
2192 float x1p, y1p, cxp, cyp, s, sa, sb;
2193 float ux, uy, vx, vy, a1, da;
2194 float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6];
2195 float sinrx, cosrx;
2196 int fa, fs;
2197 int i, ndivs;
2198 float hda, kappa;
2199
2200 rx = fabsf(args[0]); /* y radius */
2201 ry = fabsf(args[1]); /* x radius */
2202 rotx = args[2] / 180.0f * NSVG_PI; /* x rotation angle */
2203 fa = fabsf(args[3]) > 1e-6 ? 1 : 0; /* Large arc */
2204 fs = fabsf(args[4]) > 1e-6 ? 1 : 0; /* Sweep direction */
2205 x1 = *cpx; /* start point */
2206 y1 = *cpy;
2207 if (rel) { /* end point */
2208 x2 = *cpx + args[5];
2209 y2 = *cpy + args[6];
2210 } else {
2211 x2 = args[5];
2212 y2 = args[6];
2213 }
2214
2215 dx = x1 - x2;
2216 dy = y1 - y2;
2217 d = sqrtf(dx*dx + dy*dy);
2218 if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) {
2219 /* The arc degenerates to a line */
2220 nsvg__lineTo(p, x2, y2);
2221 *cpx = x2;
2222 *cpy = y2;
2223 return;
2224 }
2225
2226 sinrx = sinf(rotx);
2227 cosrx = cosf(rotx);
2228
2229 /* Convert to center point parameterization. */
2230 /* http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes */
2231 /* 1) Compute x1', y1' */
2232 x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f;
2233 y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f;
2234 d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry);
2235 if (d > 1) {
2236 d = sqrtf(d);
2237 rx *= d;
2238 ry *= d;
2239 }
2240 /* 2) Compute cx', cy' */
2241 s = 0.0f;
2242 sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p);
2243 sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p);
2244 if (sa < 0.0f) sa = 0.0f;
2245 if (sb > 0.0f)
2246 s = sqrtf(sa / sb);
2247 if (fa == fs)
2248 s = -s;
2249 cxp = s * rx * y1p / ry;
2250 cyp = s * -ry * x1p / rx;
2251
2252 /* 3) Compute cx,cy from cx',cy' */
2253 cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp;
2254 cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp;
2255
2256 /* 4) Calculate theta1, and delta theta. */
2257 ux = (x1p - cxp) / rx;
2258 uy = (y1p - cyp) / ry;
2259 vx = (-x1p - cxp) / rx;
2260 vy = (-y1p - cyp) / ry;
2261 a1 = nsvg__vecang(1.0f,0.0f, ux,uy); /* Initial angle */
2262 da = nsvg__vecang(ux,uy, vx,vy); /* Delta angle */
2263
2264 /* if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI; */
2265 /* if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0; */
2266
2267 if (fs == 0 && da > 0)
2268 da -= 2 * NSVG_PI;
2269 else if (fs == 1 && da < 0)
2270 da += 2 * NSVG_PI;
2271
2272 /* Approximate the arc using cubic spline segments. */
2273 t[0] = cosrx; t[1] = sinrx;
2274 t[2] = -sinrx; t[3] = cosrx;
2275 t[4] = cx; t[5] = cy;
2276
2277 /* Split arc into max 90 degree segments. */
2278 /* The loop assumes an iteration per end point (including start and end), this +1. */
2279 ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f);
2280 hda = (da / (float)ndivs) / 2.0f;
2281 /* Fix for ticket #179: division by 0: avoid cotangens around 0 (infinite) */
2282 if ((hda < 1e-3f) && (hda > -1e-3f))
2283 hda *= 0.5f;
2284 else
2285 hda = (1.0f - cosf(hda)) / sinf(hda);
2286 kappa = fabsf(4.0f / 3.0f * hda);
2287 if (da < 0.0f)
2288 kappa = -kappa;
2289
2290 for (i = 0; i <= ndivs; i++) {
2291 a = a1 + da * ((float)i/(float)ndivs);
2292 dx = cosf(a);
2293 dy = sinf(a);
2294 nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); /* position */
2295 nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); /* tangent */
2296 if (i > 0)
2297 nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y);
2298 px = x;
2299 py = y;
2300 ptanx = tanx;
2301 ptany = tany;
2302 }
2303
2304 *cpx = x2;
2305 *cpy = y2;
2306 }
2307
nsvg__parsePath(NSVGparser * p,const char ** attr)2308 static void nsvg__parsePath(NSVGparser* p, const char** attr)
2309 {
2310 const char* s = NULL;
2311 char cmd = '\0';
2312 float args[10];
2313 int nargs;
2314 int rargs = 0;
2315 char initPoint;
2316 float cpx, cpy, cpx2, cpy2;
2317 const char* tmp[4];
2318 char closedFlag;
2319 int i;
2320 char item[64];
2321
2322 for (i = 0; attr[i]; i += 2) {
2323 if (strcmp(attr[i], "d") == 0) {
2324 s = attr[i + 1];
2325 } else {
2326 tmp[0] = attr[i];
2327 tmp[1] = attr[i + 1];
2328 tmp[2] = 0;
2329 tmp[3] = 0;
2330 nsvg__parseAttribs(p, tmp);
2331 }
2332 }
2333
2334 if (s) {
2335 nsvg__resetPath(p);
2336 cpx = 0; cpy = 0;
2337 cpx2 = 0; cpy2 = 0;
2338 initPoint = 0;
2339 closedFlag = 0;
2340 nargs = 0;
2341
2342 while (*s) {
2343 s = nsvg__getNextPathItem(s, item);
2344 if (!*item) break;
2345 if (cmd != '\0' && nsvg__isCoordinate(item)) {
2346 if (nargs < 10)
2347 args[nargs++] = (float)nsvg__atof(item);
2348 if (nargs >= rargs) {
2349 switch (cmd) {
2350 case 'm':
2351 case 'M':
2352 nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0);
2353 /* Moveto can be followed by multiple coordinate pairs, */
2354 /* which should be treated as linetos. */
2355 cmd = (cmd == 'm') ? 'l' : 'L';
2356 rargs = nsvg__getArgsPerElement(cmd);
2357 cpx2 = cpx; cpy2 = cpy;
2358 initPoint = 1;
2359 break;
2360 case 'l':
2361 case 'L':
2362 nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0);
2363 cpx2 = cpx; cpy2 = cpy;
2364 break;
2365 case 'H':
2366 case 'h':
2367 nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0);
2368 cpx2 = cpx; cpy2 = cpy;
2369 break;
2370 case 'V':
2371 case 'v':
2372 nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0);
2373 cpx2 = cpx; cpy2 = cpy;
2374 break;
2375 case 'C':
2376 case 'c':
2377 nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0);
2378 break;
2379 case 'S':
2380 case 's':
2381 nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0);
2382 break;
2383 case 'Q':
2384 case 'q':
2385 nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0);
2386 break;
2387 case 'T':
2388 case 't':
2389 nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0);
2390 break;
2391 case 'A':
2392 case 'a':
2393 nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0);
2394 cpx2 = cpx; cpy2 = cpy;
2395 break;
2396 default:
2397 if (nargs >= 2) {
2398 cpx = args[nargs-2];
2399 cpy = args[nargs-1];
2400 cpx2 = cpx; cpy2 = cpy;
2401 }
2402 break;
2403 }
2404 nargs = 0;
2405 }
2406 } else {
2407 cmd = item[0];
2408 if (cmd == 'M' || cmd == 'm') {
2409 /* Commit path. */
2410 if (p->npts > 0)
2411 nsvg__addPath(p, closedFlag);
2412 /* Start new subpath. */
2413 nsvg__resetPath(p);
2414 closedFlag = 0;
2415 nargs = 0;
2416 } else if (initPoint == 0) {
2417 /* Do not allow other commands until initial point has been set (moveTo called once). */
2418 cmd = '\0';
2419 }
2420 if (cmd == 'Z' || cmd == 'z') {
2421 closedFlag = 1;
2422 /* Commit path. */
2423 if (p->npts > 0) {
2424 /* Move current point to first point */
2425 cpx = p->pts[0];
2426 cpy = p->pts[1];
2427 cpx2 = cpx; cpy2 = cpy;
2428 nsvg__addPath(p, closedFlag);
2429 }
2430 /* Start new subpath. */
2431 nsvg__resetPath(p);
2432 nsvg__moveTo(p, cpx, cpy);
2433 closedFlag = 0;
2434 nargs = 0;
2435 }
2436 rargs = nsvg__getArgsPerElement(cmd);
2437 if (rargs == -1) {
2438 /* Command not recognized */
2439 cmd = '\0';
2440 rargs = 0;
2441 }
2442 }
2443 }
2444 /* Commit path. */
2445 if (p->npts)
2446 nsvg__addPath(p, closedFlag);
2447 }
2448
2449 nsvg__addShape(p);
2450 }
2451
nsvg__parseRect(NSVGparser * p,const char ** attr)2452 static void nsvg__parseRect(NSVGparser* p, const char** attr)
2453 {
2454 float x = 0.0f;
2455 float y = 0.0f;
2456 float w = 0.0f;
2457 float h = 0.0f;
2458 float rx = -1.0f; /* marks not set */
2459 float ry = -1.0f;
2460 int i;
2461
2462 for (i = 0; attr[i]; i += 2) {
2463 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2464 if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2465 if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2466 if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p));
2467 if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p));
2468 if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2469 if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2470 }
2471 }
2472
2473 if (rx < 0.0f && ry > 0.0f) rx = ry;
2474 if (ry < 0.0f && rx > 0.0f) ry = rx;
2475 if (rx < 0.0f) rx = 0.0f;
2476 if (ry < 0.0f) ry = 0.0f;
2477 if (rx > w/2.0f) rx = w/2.0f;
2478 if (ry > h/2.0f) ry = h/2.0f;
2479
2480 if (w != 0.0f && h != 0.0f) {
2481 nsvg__resetPath(p);
2482
2483 if (rx < 0.00001f || ry < 0.0001f) {
2484 nsvg__moveTo(p, x, y);
2485 nsvg__lineTo(p, x+w, y);
2486 nsvg__lineTo(p, x+w, y+h);
2487 nsvg__lineTo(p, x, y+h);
2488 } else {
2489 /* Rounded rectangle */
2490 nsvg__moveTo(p, x+rx, y);
2491 nsvg__lineTo(p, x+w-rx, y);
2492 nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry);
2493 nsvg__lineTo(p, x+w, y+h-ry);
2494 nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h);
2495 nsvg__lineTo(p, x+rx, y+h);
2496 nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry);
2497 nsvg__lineTo(p, x, y+ry);
2498 nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y);
2499 }
2500
2501 nsvg__addPath(p, 1);
2502
2503 nsvg__addShape(p);
2504 }
2505 }
2506
nsvg__parseCircle(NSVGparser * p,const char ** attr)2507 static void nsvg__parseCircle(NSVGparser* p, const char** attr)
2508 {
2509 float cx = 0.0f;
2510 float cy = 0.0f;
2511 float r = 0.0f;
2512 int i;
2513
2514 for (i = 0; attr[i]; i += 2) {
2515 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2516 if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2517 if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2518 if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p)));
2519 }
2520 }
2521
2522 if (r > 0.0f) {
2523 nsvg__resetPath(p);
2524
2525 nsvg__moveTo(p, cx+r, cy);
2526 nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r);
2527 nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy);
2528 nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r);
2529 nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy);
2530
2531 nsvg__addPath(p, 1);
2532
2533 nsvg__addShape(p);
2534 }
2535 }
2536
nsvg__parseEllipse(NSVGparser * p,const char ** attr)2537 static void nsvg__parseEllipse(NSVGparser* p, const char** attr)
2538 {
2539 float cx = 0.0f;
2540 float cy = 0.0f;
2541 float rx = 0.0f;
2542 float ry = 0.0f;
2543 int i;
2544
2545 for (i = 0; attr[i]; i += 2) {
2546 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2547 if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2548 if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2549 if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2550 if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2551 }
2552 }
2553
2554 if (rx > 0.0f && ry > 0.0f) {
2555
2556 nsvg__resetPath(p);
2557
2558 nsvg__moveTo(p, cx+rx, cy);
2559 nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry);
2560 nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy);
2561 nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry);
2562 nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy);
2563
2564 nsvg__addPath(p, 1);
2565
2566 nsvg__addShape(p);
2567 }
2568 }
2569
nsvg__parseLine(NSVGparser * p,const char ** attr)2570 static void nsvg__parseLine(NSVGparser* p, const char** attr)
2571 {
2572 float x1 = 0.0;
2573 float y1 = 0.0;
2574 float x2 = 0.0;
2575 float y2 = 0.0;
2576 int i;
2577
2578 for (i = 0; attr[i]; i += 2) {
2579 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2580 if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2581 if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2582 if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2583 if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2584 }
2585 }
2586
2587 nsvg__resetPath(p);
2588
2589 nsvg__moveTo(p, x1, y1);
2590 nsvg__lineTo(p, x2, y2);
2591
2592 nsvg__addPath(p, 0);
2593
2594 nsvg__addShape(p);
2595 }
2596
nsvg__parsePoly(NSVGparser * p,const char ** attr,int closeFlag)2597 static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag)
2598 {
2599 int i;
2600 const char* s;
2601 float args[2];
2602 int nargs, npts = 0;
2603 char item[64];
2604
2605 nsvg__resetPath(p);
2606
2607 for (i = 0; attr[i]; i += 2) {
2608 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2609 if (strcmp(attr[i], "points") == 0) {
2610 s = attr[i + 1];
2611 nargs = 0;
2612 while (*s) {
2613 s = nsvg__getNextPathItem(s, item);
2614 args[nargs++] = (float)nsvg__atof(item);
2615 if (nargs >= 2) {
2616 if (npts == 0)
2617 nsvg__moveTo(p, args[0], args[1]);
2618 else
2619 nsvg__lineTo(p, args[0], args[1]);
2620 nargs = 0;
2621 npts++;
2622 }
2623 }
2624 }
2625 }
2626 }
2627
2628 nsvg__addPath(p, (char)closeFlag);
2629
2630 nsvg__addShape(p);
2631 }
2632
nsvg__parseSVG(NSVGparser * p,const char ** attr)2633 static void nsvg__parseSVG(NSVGparser* p, const char** attr)
2634 {
2635 int i;
2636 for (i = 0; attr[i]; i += 2) {
2637 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2638 if (strcmp(attr[i], "width") == 0) {
2639 p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f);
2640 } else if (strcmp(attr[i], "height") == 0) {
2641 p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 0.0f);
2642 } else if (strcmp(attr[i], "viewBox") == 0) {
2643 sscanf(attr[i + 1], "%f%*[%%, \t]%f%*[%%, \t]%f%*[%%, \t]%f", &p->viewMinx, &p->viewMiny, &p->viewWidth, &p->viewHeight);
2644 } else if (strcmp(attr[i], "preserveAspectRatio") == 0) {
2645 if (strstr(attr[i + 1], "none") != 0) {
2646 /* No uniform scaling */
2647 p->alignType = NSVG_ALIGN_NONE;
2648 } else {
2649 /* Parse X align */
2650 if (strstr(attr[i + 1], "xMin") != 0)
2651 p->alignX = NSVG_ALIGN_MIN;
2652 else if (strstr(attr[i + 1], "xMid") != 0)
2653 p->alignX = NSVG_ALIGN_MID;
2654 else if (strstr(attr[i + 1], "xMax") != 0)
2655 p->alignX = NSVG_ALIGN_MAX;
2656 /* Parse X align */
2657 if (strstr(attr[i + 1], "yMin") != 0)
2658 p->alignY = NSVG_ALIGN_MIN;
2659 else if (strstr(attr[i + 1], "yMid") != 0)
2660 p->alignY = NSVG_ALIGN_MID;
2661 else if (strstr(attr[i + 1], "yMax") != 0)
2662 p->alignY = NSVG_ALIGN_MAX;
2663 /* Parse meet/slice */
2664 p->alignType = NSVG_ALIGN_MEET;
2665 if (strstr(attr[i + 1], "slice") != 0)
2666 p->alignType = NSVG_ALIGN_SLICE;
2667 }
2668 }
2669 }
2670 }
2671 }
2672
nsvg__parseGradient(NSVGparser * p,const char ** attr,char type)2673 static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type)
2674 {
2675 int i;
2676 NSVGgradientData* grad = (NSVGgradientData*)NANOSVG_malloc(sizeof(NSVGgradientData));
2677 if (grad == NULL) return;
2678 memset(grad, 0, sizeof(NSVGgradientData));
2679 grad->units = NSVG_OBJECT_SPACE;
2680 grad->type = type;
2681 if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) {
2682 grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2683 grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2684 grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT);
2685 grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2686 } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) {
2687 grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2688 grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2689 grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2690 }
2691
2692 nsvg__xformIdentity(grad->xform);
2693
2694 for (i = 0; attr[i]; i += 2) {
2695 if (strcmp(attr[i], "id") == 0) {
2696 strncpy(grad->id, attr[i+1], 63);
2697 grad->id[63] = '\0';
2698 } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2699 if (strcmp(attr[i], "gradientUnits") == 0) {
2700 if (strcmp(attr[i+1], "objectBoundingBox") == 0)
2701 grad->units = NSVG_OBJECT_SPACE;
2702 else
2703 grad->units = NSVG_USER_SPACE;
2704 } else if (strcmp(attr[i], "gradientTransform") == 0) {
2705 nsvg__parseTransform(grad->xform, attr[i + 1]);
2706 } else if (strcmp(attr[i], "cx") == 0) {
2707 grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]);
2708 } else if (strcmp(attr[i], "cy") == 0) {
2709 grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]);
2710 } else if (strcmp(attr[i], "r") == 0) {
2711 grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]);
2712 } else if (strcmp(attr[i], "fx") == 0) {
2713 grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]);
2714 } else if (strcmp(attr[i], "fy") == 0) {
2715 grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]);
2716 } else if (strcmp(attr[i], "x1") == 0) {
2717 grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2718 } else if (strcmp(attr[i], "y1") == 0) {
2719 grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2720 } else if (strcmp(attr[i], "x2") == 0) {
2721 grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2722 } else if (strcmp(attr[i], "y2") == 0) {
2723 grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2724 } else if (strcmp(attr[i], "spreadMethod") == 0) {
2725 if (strcmp(attr[i+1], "pad") == 0)
2726 grad->spread = NSVG_SPREAD_PAD;
2727 else if (strcmp(attr[i+1], "reflect") == 0)
2728 grad->spread = NSVG_SPREAD_REFLECT;
2729 else if (strcmp(attr[i+1], "repeat") == 0)
2730 grad->spread = NSVG_SPREAD_REPEAT;
2731 } else if (strcmp(attr[i], "xlink:href") == 0) {
2732 const char *href = attr[i+1];
2733 strncpy(grad->ref, href+1, 62);
2734 grad->ref[62] = '\0';
2735 }
2736 }
2737 }
2738
2739 grad->next = p->gradients;
2740 p->gradients = grad;
2741 }
2742
nsvg__parseGradientStop(NSVGparser * p,const char ** attr)2743 static void nsvg__parseGradientStop(NSVGparser* p, const char** attr)
2744 {
2745 NSVGattrib* curAttr = nsvg__getAttr(p);
2746 NSVGgradientData* grad;
2747 NSVGgradientStop* stop;
2748 int i, idx;
2749
2750 curAttr->stopOffset = 0;
2751 curAttr->stopColor = 0;
2752 curAttr->stopOpacity = 1.0f;
2753
2754 for (i = 0; attr[i]; i += 2) {
2755 nsvg__parseAttr(p, attr[i], attr[i + 1]);
2756 }
2757
2758 /* Add stop to the last gradient. */
2759 grad = p->gradients;
2760 if (grad == NULL) return;
2761
2762 grad->nstops++;
2763 grad->stops = (NSVGgradientStop*)NANOSVG_realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops);
2764 if (grad->stops == NULL) return;
2765
2766 /* Insert */
2767 idx = grad->nstops-1;
2768 for (i = 0; i < grad->nstops-1; i++) {
2769 if (curAttr->stopOffset < grad->stops[i].offset) {
2770 idx = i;
2771 break;
2772 }
2773 }
2774 if (idx != grad->nstops-1) {
2775 for (i = grad->nstops-1; i > idx; i--)
2776 grad->stops[i] = grad->stops[i-1];
2777 }
2778
2779 stop = &grad->stops[idx];
2780 stop->color = curAttr->stopColor;
2781 stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24;
2782 stop->offset = curAttr->stopOffset;
2783 }
2784
nsvg__startElement(void * ud,const char * el,const char ** attr)2785 static void nsvg__startElement(void* ud, const char* el, const char** attr)
2786 {
2787 NSVGparser* p = (NSVGparser*)ud;
2788
2789 if (p->defsFlag) {
2790 /* Skip everything but gradients in defs */
2791 if (strcmp(el, "linearGradient") == 0) {
2792 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2793 } else if (strcmp(el, "radialGradient") == 0) {
2794 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2795 } else if (strcmp(el, "stop") == 0) {
2796 nsvg__parseGradientStop(p, attr);
2797 }
2798 return;
2799 }
2800
2801 if (strcmp(el, "g") == 0) {
2802 nsvg__pushAttr(p);
2803 nsvg__parseAttribs(p, attr);
2804 } else if (strcmp(el, "path") == 0) {
2805 if (p->pathFlag) /* Do not allow nested paths. */
2806 return;
2807 nsvg__pushAttr(p);
2808 nsvg__parsePath(p, attr);
2809 nsvg__popAttr(p);
2810 } else if (strcmp(el, "rect") == 0) {
2811 nsvg__pushAttr(p);
2812 nsvg__parseRect(p, attr);
2813 nsvg__popAttr(p);
2814 } else if (strcmp(el, "circle") == 0) {
2815 nsvg__pushAttr(p);
2816 nsvg__parseCircle(p, attr);
2817 nsvg__popAttr(p);
2818 } else if (strcmp(el, "ellipse") == 0) {
2819 nsvg__pushAttr(p);
2820 nsvg__parseEllipse(p, attr);
2821 nsvg__popAttr(p);
2822 } else if (strcmp(el, "line") == 0) {
2823 nsvg__pushAttr(p);
2824 nsvg__parseLine(p, attr);
2825 nsvg__popAttr(p);
2826 } else if (strcmp(el, "polyline") == 0) {
2827 nsvg__pushAttr(p);
2828 nsvg__parsePoly(p, attr, 0);
2829 nsvg__popAttr(p);
2830 } else if (strcmp(el, "polygon") == 0) {
2831 nsvg__pushAttr(p);
2832 nsvg__parsePoly(p, attr, 1);
2833 nsvg__popAttr(p);
2834 } else if (strcmp(el, "linearGradient") == 0) {
2835 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2836 } else if (strcmp(el, "radialGradient") == 0) {
2837 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2838 } else if (strcmp(el, "stop") == 0) {
2839 nsvg__parseGradientStop(p, attr);
2840 } else if (strcmp(el, "defs") == 0) {
2841 p->defsFlag = 1;
2842 } else if (strcmp(el, "svg") == 0) {
2843 nsvg__parseSVG(p, attr);
2844 } else if (strcmp(el, "style") == 0) {
2845 p->styleFlag = 1;
2846 }
2847 }
2848
nsvg__endElement(void * ud,const char * el)2849 static void nsvg__endElement(void* ud, const char* el)
2850 {
2851 NSVGparser* p = (NSVGparser*)ud;
2852
2853 if (strcmp(el, "g") == 0) {
2854 nsvg__popAttr(p);
2855 } else if (strcmp(el, "path") == 0) {
2856 p->pathFlag = 0;
2857 } else if (strcmp(el, "defs") == 0) {
2858 p->defsFlag = 0;
2859 } else if (strcmp(el, "style") == 0) {
2860 p->styleFlag = 0;
2861 }
2862 }
2863
nsvg__strndup(const char * s,size_t n)2864 static char *nsvg__strndup(const char *s, size_t n)
2865 {
2866 char *result;
2867 size_t len = strlen(s);
2868
2869 if (n < len)
2870 len = n;
2871
2872 result = (char*)NANOSVG_malloc(len+1);
2873 if (!result)
2874 return 0;
2875
2876 result[len] = '\0';
2877 return (char *)memcpy(result, s, len);
2878 }
2879
nsvg__content(void * ud,const char * s)2880 static void nsvg__content(void* ud, const char* s)
2881 {
2882 NSVGparser* p = (NSVGparser*)ud;
2883 if (p->styleFlag) {
2884
2885 int state = 0;
2886 const char* start = NULL;
2887 while (*s) {
2888 char c = *s;
2889 if (nsvg__isspace(c) || c == '{') {
2890 if (state == 1) {
2891 NSVGstyles* next = p->styles;
2892
2893 p->styles = (NSVGstyles*)NANOSVG_malloc(sizeof(NSVGstyles));
2894 p->styles->next = next;
2895 p->styles->name = nsvg__strndup(start, (size_t)(s - start));
2896 start = s + 1;
2897 state = 2;
2898 }
2899 } else if (state == 2 && c == '}') {
2900 p->styles->description = nsvg__strndup(start, (size_t)(s - start));
2901 state = 0;
2902 }
2903 else if (state == 0) {
2904 start = s;
2905 state = 1;
2906 }
2907 s++;
2908 /*
2909 if (*s == '{' && state == NSVG_XML_CONTENT) {
2910 // Start of a tag
2911 *s++ = '\0';
2912 nsvg__parseContent(mark, contentCb, ud);
2913 mark = s;
2914 state = NSVG_XML_TAG;
2915 }
2916 else if (*s == '>' && state == NSVG_XML_TAG) {
2917 // Start of a content or new tag.
2918 *s++ = '\0';
2919 nsvg__parseElement(mark, startelCb, endelCb, ud);
2920 mark = s;
2921 state = NSVG_XML_CONTENT;
2922 }
2923 else {
2924 s++;
2925 }
2926 */
2927 }
2928
2929 }
2930 }
2931
nsvg__imageBounds(NSVGparser * p,float * bounds)2932 static void nsvg__imageBounds(NSVGparser* p, float* bounds)
2933 {
2934 NSVGshape* shape;
2935 shape = p->image->shapes;
2936 if (shape == NULL) {
2937 bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0;
2938 return;
2939 }
2940 bounds[0] = shape->bounds[0];
2941 bounds[1] = shape->bounds[1];
2942 bounds[2] = shape->bounds[2];
2943 bounds[3] = shape->bounds[3];
2944 for (shape = shape->next; shape != NULL; shape = shape->next) {
2945 bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]);
2946 bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]);
2947 bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]);
2948 bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]);
2949 }
2950 }
2951
nsvg__viewAlign(float content,float container,int type)2952 static float nsvg__viewAlign(float content, float container, int type)
2953 {
2954 if (type == NSVG_ALIGN_MIN)
2955 return 0;
2956 else if (type == NSVG_ALIGN_MAX)
2957 return container - content;
2958 /* mid */
2959 return (container - content) * 0.5f;
2960 }
2961
nsvg__scaleGradient(NSVGgradient * grad,float tx,float ty,float sx,float sy)2962 static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy)
2963 {
2964 float t[6];
2965 nsvg__xformSetTranslation(t, tx, ty);
2966 nsvg__xformMultiply (grad->xform, t);
2967
2968 nsvg__xformSetScale(t, sx, sy);
2969 nsvg__xformMultiply (grad->xform, t);
2970 }
2971
nsvg__scaleToViewbox(NSVGparser * p,const char * units)2972 static void nsvg__scaleToViewbox(NSVGparser* p, const char* units)
2973 {
2974 NSVGshape* shape;
2975 NSVGpath* path;
2976 float tx, ty, sx, sy, us, bounds[4], t[6], avgs;
2977 int i;
2978 float* pt;
2979
2980 /* Guess image size if not set completely. */
2981 nsvg__imageBounds(p, bounds);
2982
2983 if (p->viewWidth == 0) {
2984 if (p->image->width > 0) {
2985 p->viewWidth = p->image->width;
2986 } else {
2987 p->viewMinx = bounds[0];
2988 p->viewWidth = bounds[2] - bounds[0];
2989 }
2990 }
2991 if (p->viewHeight == 0) {
2992 if (p->image->height > 0) {
2993 p->viewHeight = p->image->height;
2994 } else {
2995 p->viewMiny = bounds[1];
2996 p->viewHeight = bounds[3] - bounds[1];
2997 }
2998 }
2999 if (p->image->width == 0)
3000 p->image->width = p->viewWidth;
3001 if (p->image->height == 0)
3002 p->image->height = p->viewHeight;
3003
3004 tx = -p->viewMinx;
3005 ty = -p->viewMiny;
3006 sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0;
3007 sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0;
3008 /* Unit scaling */
3009 us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f);
3010
3011 /* Fix aspect ratio */
3012 if (p->alignType == NSVG_ALIGN_MEET) {
3013 /* fit whole image into viewbox */
3014 sx = sy = nsvg__minf(sx, sy);
3015 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
3016 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
3017 } else if (p->alignType == NSVG_ALIGN_SLICE) {
3018 /* fill whole viewbox with image */
3019 sx = sy = nsvg__maxf(sx, sy);
3020 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
3021 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
3022 }
3023
3024 /* Transform */
3025 sx *= us;
3026 sy *= us;
3027 avgs = (sx+sy) / 2.0f;
3028 for (shape = p->image->shapes; shape != NULL; shape = shape->next) {
3029 shape->bounds[0] = (shape->bounds[0] + tx) * sx;
3030 shape->bounds[1] = (shape->bounds[1] + ty) * sy;
3031 shape->bounds[2] = (shape->bounds[2] + tx) * sx;
3032 shape->bounds[3] = (shape->bounds[3] + ty) * sy;
3033 for (path = shape->paths; path != NULL; path = path->next) {
3034 path->bounds[0] = (path->bounds[0] + tx) * sx;
3035 path->bounds[1] = (path->bounds[1] + ty) * sy;
3036 path->bounds[2] = (path->bounds[2] + tx) * sx;
3037 path->bounds[3] = (path->bounds[3] + ty) * sy;
3038 for (i =0; i < path->npts; i++) {
3039 pt = &path->pts[i*2];
3040 pt[0] = (pt[0] + tx) * sx;
3041 pt[1] = (pt[1] + ty) * sy;
3042 }
3043 }
3044
3045 if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
3046 nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy);
3047 memcpy(t, shape->fill.gradient->xform, sizeof(float)*6);
3048 nsvg__xformInverse(shape->fill.gradient->xform, t);
3049 }
3050 if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) {
3051 nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy);
3052 memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6);
3053 nsvg__xformInverse(shape->stroke.gradient->xform, t);
3054 }
3055
3056 shape->strokeWidth *= avgs;
3057 shape->strokeDashOffset *= avgs;
3058 for (i = 0; i < shape->strokeDashCount; i++)
3059 shape->strokeDashArray[i] *= avgs;
3060 }
3061 }
3062
3063 NANOSVG_SCOPE
nsvgParse(char * input,const char * units,float dpi)3064 NSVGimage* nsvgParse(char* input, const char* units, float dpi)
3065 {
3066 NSVGparser* p;
3067 NSVGimage* ret = 0;
3068
3069 p = nsvg__createParser();
3070 if (p == NULL) {
3071 return NULL;
3072 }
3073 p->dpi = dpi;
3074
3075 nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p);
3076
3077 /* Scale to viewBox */
3078 nsvg__scaleToViewbox(p, units);
3079
3080 ret = p->image;
3081 p->image = NULL;
3082
3083 nsvg__deleteParser(p);
3084
3085 return ret;
3086 }
3087
3088 NANOSVG_SCOPE
nsvgParseFromFile(const char * filename,const char * units,float dpi)3089 NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi)
3090 {
3091 FILE* fp = NULL;
3092 size_t size;
3093 char* data = NULL;
3094 NSVGimage* image = NULL;
3095
3096 fp = fopen(filename, "rb");
3097 if (!fp) goto error;
3098 fseek(fp, 0, SEEK_END);
3099 size = ftell(fp);
3100 fseek(fp, 0, SEEK_SET);
3101 data = (char*)NANOSVG_malloc(size+1);
3102 if (data == NULL) goto error;
3103 if (fread(data, 1, size, fp) != size) goto error;
3104 data[size] = '\0'; /* Must be null terminated. */
3105 fclose(fp);
3106 image = nsvgParse(data, units, dpi);
3107 NANOSVG_free(data);
3108
3109 return image;
3110
3111 error:
3112 if (fp) fclose(fp);
3113 if (data) NANOSVG_free(data);
3114 if (image) nsvgDelete(image);
3115 return NULL;
3116 }
3117
3118 NANOSVG_SCOPE
nsvgDelete(NSVGimage * image)3119 void nsvgDelete(NSVGimage* image)
3120 {
3121 NSVGshape *snext, *shape;
3122 if (image == NULL) return;
3123 shape = image->shapes;
3124 while (shape != NULL) {
3125 snext = shape->next;
3126 nsvg__deletePaths(shape->paths);
3127 nsvg__deletePaint(&shape->fill);
3128 nsvg__deletePaint(&shape->stroke);
3129 NANOSVG_free(shape);
3130 shape = snext;
3131 }
3132 NANOSVG_free(image);
3133 }
3134
3135 #endif
3136