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