2 * Copyright (c) 2013-14 Mikko Mononen memon@inside.org
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.
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:
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.
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/)
23 * Arc calculation code based on canvg (https://code.google.com/p/canvg/)
25 * Bounding box calculation based on http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
32 * In the original software, The nanosvg implementation was included in the header file.
33 * We have separated the implementation to source file here.
41 #define NSVG_PI (3.14159265358979323846264338327f)
42 #define NSVG_KAPPA90 (0.5522847493f) // Lenght proportional to radius of a cubic bezier handle for 90deg arcs.
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
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))
54 #define NSVG_INLINE inline
57 static int nsvg__isspace(char c)
59 return strchr(" \t\n\v\f\r", c) != 0;
62 static int nsvg__isdigit(char c)
64 return c >= '0' && c <= '9';
67 static int nsvg__isnum(char c)
69 return strchr("0123456789+-.eE", c) != 0;
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; }
78 #define NSVG_XML_TAG 1
79 #define NSVG_XML_CONTENT 2
80 #define NSVG_XML_MAX_ATTRIBS 256
82 static void nsvg__parseContent(char* s,
83 void (*contentCb)(void* ud, const char* s),
86 // Trim start white spaces
87 while (*s && nsvg__isspace(*s)) s++;
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),
99 const char* attr[NSVG_XML_MAX_ATTRIBS];
107 * In the original file, 's' is not compared to NULL value before it is dereferenced.
114 // Skip white space after the '<'
115 while (*s && nsvg__isspace(*s)) s++;
117 // Check if the tag is end tag
125 // Skip comments, data and preprocessor stuff.
126 if (!*s || *s == '?' || *s == '!')
131 while (*s && !nsvg__isspace(*s)) s++;
132 if (*s) { *s++ = '\0'; }
135 while (!end && *s && nattr < NSVG_XML_MAX_ATTRIBS-3) {
139 // Skip white space before the attrib name
140 while (*s && nsvg__isspace(*s)) s++;
147 // Find end of the attrib name.
148 while (*s && !nsvg__isspace(*s) && *s != '=') s++;
149 if (*s) { *s++ = '\0'; }
150 // Skip until the beginning of the value.
151 while (*s && *s != '\"' && *s != '\'') s++;
155 // Store value and find the end of it.
157 while (*s && *s != quote) s++;
158 if (*s) { *s++ = '\0'; }
160 // Store only well formed attributes
162 attr[nattr++] = name;
163 attr[nattr++] = value;
172 if (start && startelCb)
173 (*startelCb)(ud, name, attr);
175 (*endelCb)(ud, name);
178 int nsvg__parseXML(char* input,
179 void (*startelCb)(void* ud, const char* el, const char** attr),
180 void (*endelCb)(void* ud, const char* el),
181 void (*contentCb)(void* ud, const char* s),
186 int state = NSVG_XML_CONTENT;
188 if (*s == '<' && state == NSVG_XML_CONTENT) {
191 nsvg__parseContent(mark, contentCb, ud);
193 state = NSVG_XML_TAG;
194 } else if (*s == '>' && state == NSVG_XML_TAG) {
195 // Start of a content or new tag.
197 nsvg__parseElement(mark, startelCb, endelCb, ud);
199 state = NSVG_XML_CONTENT;
209 /* Simple SVG parser. */
211 #define NSVG_MAX_ATTR 128
213 enum NSVGgradientUnits {
215 NSVG_OBJECT_SPACE = 1
218 #define NSVG_MAX_DASHES 8
233 typedef struct NSVGcoordinate {
238 typedef struct NSVGlinearData {
239 NSVGcoordinate x1, y1, x2, y2;
242 typedef struct NSVGradialData {
243 NSVGcoordinate cx, cy, r, fx, fy;
246 typedef struct NSVGgradientData
251 * In the original file, using char type (without signed or unsigned) can be interpreted
252 * as 'unsigned char' in some build environments, like ARM architecture.
253 * To prevent the unexpected behavior, we replace 'char type' with 'signed char type' here.
257 NSVGlinearData linear;
258 NSVGradialData radial;
262 * In the original file, using char type (without signed or unsigned) can be interpreted
263 * as 'unsigned char' in some build environments, like ARM architecture.
264 * To prevent the unexpected behavior, we replace 'char units' with 'signed char units' here.
269 NSVGgradientStop* stops;
270 struct NSVGgradientData* next;
273 typedef struct NSVGattrib
277 unsigned int fillColor;
278 unsigned int strokeColor;
282 char fillGradient[64];
283 char strokeGradient[64];
285 float strokeDashOffset;
286 float strokeDashArray[NSVG_MAX_DASHES];
293 unsigned int stopColor;
301 typedef struct NSVGparser
303 NSVGattrib attr[NSVG_MAX_ATTR];
310 NSVGgradientData* gradients;
311 NSVGshape* shapesTail;
312 float viewMinx, viewMiny, viewWidth, viewHeight;
313 int alignX, alignY, alignType;
319 static void nsvg__xformIdentity(float* t)
321 t[0] = 1.0f; t[1] = 0.0f;
322 t[2] = 0.0f; t[3] = 1.0f;
323 t[4] = 0.0f; t[5] = 0.0f;
326 static void nsvg__xformSetTranslation(float* t, float tx, float ty)
328 t[0] = 1.0f; t[1] = 0.0f;
329 t[2] = 0.0f; t[3] = 1.0f;
330 t[4] = tx; t[5] = ty;
333 static void nsvg__xformSetScale(float* t, float sx, float sy)
335 t[0] = sx; t[1] = 0.0f;
336 t[2] = 0.0f; t[3] = sy;
337 t[4] = 0.0f; t[5] = 0.0f;
340 static void nsvg__xformSetSkewX(float* t, float a)
342 t[0] = 1.0f; t[1] = 0.0f;
343 t[2] = tanf(a); t[3] = 1.0f;
344 t[4] = 0.0f; t[5] = 0.0f;
347 static void nsvg__xformSetSkewY(float* t, float a)
349 t[0] = 1.0f; t[1] = tanf(a);
350 t[2] = 0.0f; t[3] = 1.0f;
351 t[4] = 0.0f; t[5] = 0.0f;
354 static void nsvg__xformSetRotation(float* t, float a)
356 float cs = cosf(a), sn = sinf(a);
357 t[0] = cs; t[1] = sn;
358 t[2] = -sn; t[3] = cs;
359 t[4] = 0.0f; t[5] = 0.0f;
362 static void nsvg__xformMultiply(float* t, float* s)
364 float t0 = t[0] * s[0] + t[1] * s[2];
365 float t2 = t[2] * s[0] + t[3] * s[2];
366 float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
367 t[1] = t[0] * s[1] + t[1] * s[3];
368 t[3] = t[2] * s[1] + t[3] * s[3];
369 t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
375 static void nsvg__xformInverse(float* inv, float* t)
377 double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
378 if (det > -1e-6 && det < 1e-6) {
379 nsvg__xformIdentity(t);
383 inv[0] = (float)(t[3] * invdet);
384 inv[2] = (float)(-t[2] * invdet);
385 inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
386 inv[1] = (float)(-t[1] * invdet);
387 inv[3] = (float)(t[0] * invdet);
388 inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
391 static void nsvg__xformPremultiply(float* t, float* s)
394 memcpy(s2, s, sizeof(float)*6);
395 nsvg__xformMultiply(s2, t);
396 memcpy(t, s2, sizeof(float)*6);
399 static void nsvg__xformPoint(float* dx, float* dy, float x, float y, float* t)
401 *dx = x*t[0] + y*t[2] + t[4];
402 *dy = x*t[1] + y*t[3] + t[5];
405 static void nsvg__xformVec(float* dx, float* dy, float x, float y, float* t)
407 *dx = x*t[0] + y*t[2];
408 *dy = x*t[1] + y*t[3];
411 #define NSVG_EPSILON (1e-12)
413 static int nsvg__ptInBounds(float* pt, float* bounds)
415 return pt[0] >= bounds[0] && pt[0] <= bounds[2] && pt[1] >= bounds[1] && pt[1] <= bounds[3];
419 static double nsvg__evalBezier(double t, double p0, double p1, double p2, double p3)
422 return it*it*it*p0 + 3.0*it*it*t*p1 + 3.0*it*t*t*p2 + t*t*t*p3;
425 static void nsvg__curveBounds(float* bounds, float* curve)
428 double roots[2], a, b, c, b2ac, t, v;
429 float* v0 = &curve[0];
430 float* v1 = &curve[2];
431 float* v2 = &curve[4];
432 float* v3 = &curve[6];
434 // Start the bounding box by end points
435 bounds[0] = nsvg__minf(v0[0], v3[0]);
436 bounds[1] = nsvg__minf(v0[1], v3[1]);
437 bounds[2] = nsvg__maxf(v0[0], v3[0]);
438 bounds[3] = nsvg__maxf(v0[1], v3[1]);
440 // Bezier curve fits inside the convex hull of it's control points.
441 // If control points are inside the bounds, we're done.
442 if (nsvg__ptInBounds(v1, bounds) && nsvg__ptInBounds(v2, bounds))
445 // Add bezier curve inflection points in X and Y.
446 for (i = 0; i < 2; i++) {
447 a = -3.0 * v0[i] + 9.0 * v1[i] - 9.0 * v2[i] + 3.0 * v3[i];
448 b = 6.0 * v0[i] - 12.0 * v1[i] + 6.0 * v2[i];
449 c = 3.0 * v1[i] - 3.0 * v0[i];
451 if (fabs(a) < NSVG_EPSILON) {
452 if (fabs(b) > NSVG_EPSILON) {
454 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
458 b2ac = b*b - 4.0*c*a;
459 if (b2ac > NSVG_EPSILON) {
460 t = (-b + sqrt(b2ac)) / (2.0 * a);
461 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
463 t = (-b - sqrt(b2ac)) / (2.0 * a);
464 if (t > NSVG_EPSILON && t < 1.0-NSVG_EPSILON)
468 for (j = 0; j < count; j++) {
469 v = nsvg__evalBezier(roots[j], v0[i], v1[i], v2[i], v3[i]);
470 bounds[0+i] = nsvg__minf(bounds[0+i], (float)v);
471 bounds[2+i] = nsvg__maxf(bounds[2+i], (float)v);
476 static NSVGparser* nsvg__createParser()
479 p = (NSVGparser*)malloc(sizeof(NSVGparser));
480 if (p == NULL) goto error;
481 memset(p, 0, sizeof(NSVGparser));
483 p->image = (NSVGimage*)malloc(sizeof(NSVGimage));
484 if (p->image == NULL) goto error;
485 memset(p->image, 0, sizeof(NSVGimage));
488 nsvg__xformIdentity(p->attr[0].xform);
489 memset(p->attr[0].id, 0, sizeof p->attr[0].id);
490 p->attr[0].fillColor = NSVG_RGB(0,0,0);
491 p->attr[0].strokeColor = NSVG_RGB(0,0,0);
492 p->attr[0].opacity = 1;
493 p->attr[0].fillOpacity = 1;
494 p->attr[0].strokeOpacity = 1;
495 p->attr[0].stopOpacity = 1;
496 p->attr[0].strokeWidth = 1;
497 p->attr[0].strokeLineJoin = NSVG_JOIN_MITER;
498 p->attr[0].strokeLineCap = NSVG_CAP_BUTT;
499 p->attr[0].miterLimit = 4;
500 p->attr[0].fillRule = NSVG_FILLRULE_NONZERO;
501 p->attr[0].hasFill = 1;
502 p->attr[0].visible = 1;
508 if (p->image) free(p->image);
514 static void nsvg__deletePaths(NSVGpath* path)
517 NSVGpath *next = path->next;
518 if (path->pts != NULL)
525 static void nsvg__deletePaint(NSVGpaint* paint)
527 if (paint->type == NSVG_PAINT_LINEAR_GRADIENT || paint->type == NSVG_PAINT_RADIAL_GRADIENT)
528 free(paint->gradient);
531 static void nsvg__deleteGradientData(NSVGgradientData* grad)
533 NSVGgradientData* next;
534 while (grad != NULL) {
542 static void nsvg__deleteParser(NSVGparser* p)
545 nsvg__deletePaths(p->plist);
546 nsvg__deleteGradientData(p->gradients);
547 nsvgDelete(p->image);
553 static void nsvg__resetPath(NSVGparser* p)
558 static void nsvg__addPoint(NSVGparser* p, float x, float y)
560 if (p->npts+1 > p->cpts) {
561 p->cpts = p->cpts ? p->cpts*2 : 8;
562 p->pts = (float*)realloc(p->pts, p->cpts*2*sizeof(float));
565 p->pts[p->npts*2+0] = x;
566 p->pts[p->npts*2+1] = y;
570 static void nsvg__moveTo(NSVGparser* p, float x, float y)
573 p->pts[(p->npts-1)*2+0] = x;
574 p->pts[(p->npts-1)*2+1] = y;
576 nsvg__addPoint(p, x, y);
580 static void nsvg__lineTo(NSVGparser* p, float x, float y)
584 px = p->pts[(p->npts-1)*2+0];
585 py = p->pts[(p->npts-1)*2+1];
588 nsvg__addPoint(p, px + dx/3.0f, py + dy/3.0f);
589 nsvg__addPoint(p, x - dx/3.0f, y - dy/3.0f);
590 nsvg__addPoint(p, x, y);
594 static void nsvg__cubicBezTo(NSVGparser* p, float cpx1, float cpy1, float cpx2, float cpy2, float x, float y)
596 nsvg__addPoint(p, cpx1, cpy1);
597 nsvg__addPoint(p, cpx2, cpy2);
598 nsvg__addPoint(p, x, y);
601 static NSVGattrib* nsvg__getAttr(NSVGparser* p)
603 return &p->attr[p->attrHead];
606 static void nsvg__pushAttr(NSVGparser* p)
608 if (p->attrHead < NSVG_MAX_ATTR-1) {
610 memcpy(&p->attr[p->attrHead], &p->attr[p->attrHead-1], sizeof(NSVGattrib));
614 static void nsvg__popAttr(NSVGparser* p)
620 static float nsvg__actualOrigX(NSVGparser* p)
625 static float nsvg__actualOrigY(NSVGparser* p)
630 static float nsvg__actualWidth(NSVGparser* p)
635 static float nsvg__actualHeight(NSVGparser* p)
637 return p->viewHeight;
640 static float nsvg__actualLength(NSVGparser* p)
642 float w = nsvg__actualWidth(p), h = nsvg__actualHeight(p);
643 return sqrtf(w*w + h*h) / sqrtf(2.0f);
646 static float nsvg__convertToPixels(NSVGparser* p, NSVGcoordinate c, float orig, float length)
648 NSVGattrib* attr = nsvg__getAttr(p);
650 case NSVG_UNITS_USER: return c.value;
651 case NSVG_UNITS_PX: return c.value;
652 case NSVG_UNITS_PT: return c.value / 72.0f * p->dpi;
653 case NSVG_UNITS_PC: return c.value / 6.0f * p->dpi;
654 case NSVG_UNITS_MM: return c.value / 25.4f * p->dpi;
655 case NSVG_UNITS_CM: return c.value / 2.54f * p->dpi;
656 case NSVG_UNITS_IN: return c.value * p->dpi;
657 case NSVG_UNITS_EM: return c.value * attr->fontSize;
658 case NSVG_UNITS_EX: return c.value * attr->fontSize * 0.52f; // x-height of Helvetica.
659 case NSVG_UNITS_PERCENT: return orig + c.value / 100.0f * length;
660 default: return c.value;
665 static NSVGgradientData* nsvg__findGradientData(NSVGparser* p, const char* id)
667 NSVGgradientData* grad = p->gradients;
669 if (strcmp(grad->id, id) == 0)
677 * In the original file, using char type (without signed or unsigned) can be interpreted
678 * as 'unsigned char' in some build environments, like ARM architecture.
679 * To prevent the unexpected behavior, we replace 'char paintType' with 'signed char paintType' here.
681 static NSVGgradient* nsvg__createGradient(NSVGparser* p, const char* id, const float* localBounds, signed char* paintType)
683 NSVGattrib* attr = nsvg__getAttr(p);
684 NSVGgradientData* data = NULL;
685 NSVGgradientData* ref = NULL;
686 NSVGgradientStop* stops = NULL;
688 float ox, oy, sw, sh, sl;
691 data = nsvg__findGradientData(p, id);
692 if (data == NULL) return NULL;
694 // TODO: use ref to fill in all unset values too.
696 while (ref != NULL) {
697 if (stops == NULL && ref->stops != NULL) {
699 nstops = ref->nstops;
702 ref = nsvg__findGradientData(p, ref->ref);
704 if (stops == NULL) return NULL;
706 grad = (NSVGgradient*)malloc(sizeof(NSVGgradient) + sizeof(NSVGgradientStop)*(nstops-1));
707 if (grad == NULL) return NULL;
709 // The shape width and height.
710 if (data->units == NSVG_OBJECT_SPACE) {
713 sw = localBounds[2] - localBounds[0];
714 sh = localBounds[3] - localBounds[1];
716 ox = nsvg__actualOrigX(p);
717 oy = nsvg__actualOrigY(p);
718 sw = nsvg__actualWidth(p);
719 sh = nsvg__actualHeight(p);
721 sl = sqrtf(sw*sw + sh*sh) / sqrtf(2.0f);
723 if (data->type == NSVG_PAINT_LINEAR_GRADIENT) {
724 float x1, y1, x2, y2, dx, dy;
725 x1 = nsvg__convertToPixels(p, data->linear.x1, ox, sw);
726 y1 = nsvg__convertToPixels(p, data->linear.y1, oy, sh);
727 x2 = nsvg__convertToPixels(p, data->linear.x2, ox, sw);
728 y2 = nsvg__convertToPixels(p, data->linear.y2, oy, sh);
729 // Calculate transform aligned to the line
732 grad->xform[0] = dy; grad->xform[1] = -dx;
733 grad->xform[2] = dx; grad->xform[3] = dy;
734 grad->xform[4] = x1; grad->xform[5] = y1;
736 float cx, cy, fx, fy, r;
737 cx = nsvg__convertToPixels(p, data->radial.cx, ox, sw);
738 cy = nsvg__convertToPixels(p, data->radial.cy, oy, sh);
739 fx = nsvg__convertToPixels(p, data->radial.fx, ox, sw);
740 fy = nsvg__convertToPixels(p, data->radial.fy, oy, sh);
741 r = nsvg__convertToPixels(p, data->radial.r, 0, sl);
742 // Calculate transform aligned to the circle
743 grad->xform[0] = r; grad->xform[1] = 0;
744 grad->xform[2] = 0; grad->xform[3] = r;
745 grad->xform[4] = cx; grad->xform[5] = cy;
750 nsvg__xformMultiply(grad->xform, data->xform);
751 nsvg__xformMultiply(grad->xform, attr->xform);
753 grad->spread = data->spread;
754 memcpy(grad->stops, stops, nstops*sizeof(NSVGgradientStop));
755 grad->nstops = nstops;
757 *paintType = data->type;
762 static float nsvg__getAverageScale(float* t)
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;
769 static void nsvg__getLocalBounds(float* bounds, NSVGshape *shape, float* xform)
772 float curve[4*2], curveBounds[4];
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);
782 bounds[0] = curveBounds[0];
783 bounds[1] = curveBounds[1];
784 bounds[2] = curveBounds[2];
785 bounds[3] = curveBounds[3];
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]);
799 static void nsvg__addShape(NSVGparser* p)
801 NSVGattrib* attr = nsvg__getAttr(p);
807 if (p->plist == NULL)
810 shape = (NSVGshape*)malloc(sizeof(NSVGshape));
813 * In the original file, if shape is NULL it goto error below 'return' and free shape memory.
814 * But, the error is only visited when shape is NULL, so there is not needed to free it.
816 if (shape == NULL) return;
817 memset(shape, 0, sizeof(NSVGshape));
819 memcpy(shape->id, attr->id, sizeof shape->id);
820 scale = nsvg__getAverageScale(attr->xform);
821 shape->strokeWidth = attr->strokeWidth * scale;
822 shape->strokeDashOffset = attr->strokeDashOffset * scale;
823 shape->strokeDashCount = (char)attr->strokeDashCount;
824 for (i = 0; i < attr->strokeDashCount; i++)
825 shape->strokeDashArray[i] = attr->strokeDashArray[i] * scale;
826 shape->strokeLineJoin = attr->strokeLineJoin;
827 shape->strokeLineCap = attr->strokeLineCap;
828 shape->miterLimit = attr->miterLimit;
829 shape->fillRule = attr->fillRule;
830 shape->opacity = attr->opacity;
832 shape->paths = p->plist;
835 // Calculate shape bounds
836 shape->bounds[0] = shape->paths->bounds[0];
837 shape->bounds[1] = shape->paths->bounds[1];
838 shape->bounds[2] = shape->paths->bounds[2];
839 shape->bounds[3] = shape->paths->bounds[3];
840 for (path = shape->paths->next; path != NULL; path = path->next) {
841 shape->bounds[0] = nsvg__minf(shape->bounds[0], path->bounds[0]);
842 shape->bounds[1] = nsvg__minf(shape->bounds[1], path->bounds[1]);
843 shape->bounds[2] = nsvg__maxf(shape->bounds[2], path->bounds[2]);
844 shape->bounds[3] = nsvg__maxf(shape->bounds[3], path->bounds[3]);
848 if (attr->hasFill == 0) {
849 shape->fill.type = NSVG_PAINT_NONE;
850 } else if (attr->hasFill == 1) {
851 shape->fill.type = NSVG_PAINT_COLOR;
852 shape->fill.color = attr->fillColor;
853 shape->fill.color |= (unsigned int)(attr->fillOpacity*255) << 24;
854 } else if (attr->hasFill == 2) {
855 shape->opacity *= attr->fillOpacity;
856 float inv[6], localBounds[4];
857 nsvg__xformInverse(inv, attr->xform);
858 nsvg__getLocalBounds(localBounds, shape, inv);
859 shape->fill.gradient = nsvg__createGradient(p, attr->fillGradient, localBounds, &shape->fill.type);
860 if (shape->fill.gradient == NULL) {
861 shape->fill.type = NSVG_PAINT_NONE;
866 if (attr->hasStroke == 0) {
867 shape->stroke.type = NSVG_PAINT_NONE;
868 } else if (attr->hasStroke == 1) {
869 shape->stroke.type = NSVG_PAINT_COLOR;
870 shape->stroke.color = attr->strokeColor;
871 shape->stroke.color |= (unsigned int)(attr->strokeOpacity*255) << 24;
872 } else if (attr->hasStroke == 2) {
873 float inv[6], localBounds[4];
874 nsvg__xformInverse(inv, attr->xform);
875 nsvg__getLocalBounds(localBounds, shape, inv);
876 shape->stroke.gradient = nsvg__createGradient(p, attr->strokeGradient, localBounds, &shape->stroke.type);
877 if (shape->stroke.gradient == NULL)
878 shape->stroke.type = NSVG_PAINT_NONE;
882 shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00);
885 if (p->image->shapes == NULL)
886 p->image->shapes = shape;
888 p->shapesTail->next = shape;
889 p->shapesTail = shape;
894 static void nsvg__addPath(NSVGparser* p, char closed)
896 NSVGattrib* attr = nsvg__getAttr(p);
897 NSVGpath* path = NULL;
906 nsvg__lineTo(p, p->pts[0], p->pts[1]);
908 path = (NSVGpath*)malloc(sizeof(NSVGpath));
909 if (path == NULL) goto error;
910 memset(path, 0, sizeof(NSVGpath));
912 path->pts = (float*)malloc(p->npts*2*sizeof(float));
913 if (path->pts == NULL) goto error;
914 path->closed = closed;
915 path->npts = p->npts;
918 for (i = 0; i < p->npts; ++i)
919 nsvg__xformPoint(&path->pts[i*2], &path->pts[i*2+1], p->pts[i*2], p->pts[i*2+1], attr->xform);
922 for (i = 0; i < path->npts-1; i += 3) {
923 curve = &path->pts[i*2];
924 nsvg__curveBounds(bounds, curve);
926 path->bounds[0] = bounds[0];
927 path->bounds[1] = bounds[1];
928 path->bounds[2] = bounds[2];
929 path->bounds[3] = bounds[3];
931 path->bounds[0] = nsvg__minf(path->bounds[0], bounds[0]);
932 path->bounds[1] = nsvg__minf(path->bounds[1], bounds[1]);
933 path->bounds[2] = nsvg__maxf(path->bounds[2], bounds[2]);
934 path->bounds[3] = nsvg__maxf(path->bounds[3], bounds[3]);
938 path->next = p->plist;
945 if (path->pts != NULL) free(path->pts);
950 // We roll our own string to float because the std library one uses locale and messes things up.
951 static double nsvg__atof(const char* s)
953 char* cur = (char*)s;
955 double res = 0.0, sign = 1.0;
956 long long intPart = 0, fracPart = 0;
957 char hasIntPart = 0, hasFracPart = 0;
959 // Parse optional sign
962 } else if (*cur == '-') {
967 // Parse integer part
968 if (nsvg__isdigit(*cur)) {
969 // Parse digit sequence
970 intPart = (double)strtoll(cur, &end, 10);
972 res = (double)intPart;
978 // Parse fractional part.
981 if (nsvg__isdigit(*cur)) {
982 // Parse digit sequence
983 fracPart = strtoll(cur, &end, 10);
985 res += (double)fracPart / pow(10.0, (double)(end - cur));
992 // A valid number should have integer or fractional part.
993 if (!hasIntPart && !hasFracPart)
996 // Parse optional exponent
997 if (*cur == 'e' || *cur == 'E') {
1000 expPart = strtol(cur, &end, 10); // Parse digit sequence with sign
1002 res *= pow(10.0, (double)expPart);
1010 static const char* nsvg__parseNumber(const char* s, char* it, const int size)
1012 const int last = size-1;
1016 if (*s == '-' || *s == '+') {
1017 if (i < last) it[i++] = *s;
1021 while (*s && nsvg__isdigit(*s)) {
1022 if (i < last) it[i++] = *s;
1027 if (i < last) it[i++] = *s;
1030 while (*s && nsvg__isdigit(*s)) {
1031 if (i < last) it[i++] = *s;
1036 if (*s == 'e' || *s == 'E') {
1037 if (i < last) it[i++] = *s;
1039 if (*s == '-' || *s == '+') {
1040 if (i < last) it[i++] = *s;
1043 while (*s && nsvg__isdigit(*s)) {
1044 if (i < last) it[i++] = *s;
1053 static const char* nsvg__getNextPathItem(const char* s, char* it)
1056 // Skip white spaces and commas
1057 while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1059 if (*s == '-' || *s == '+' || *s == '.' || nsvg__isdigit(*s)) {
1060 s = nsvg__parseNumber(s, it, 64);
1071 static unsigned int nsvg__parseColorHex(const char* str)
1073 unsigned int c = 0, r = 0, g = 0, b = 0;
1076 // Calculate number of characters.
1077 while(str[n] && !nsvg__isspace(str[n]))
1080 sscanf(str, "%x", &c);
1081 } else if (n == 3) {
1082 sscanf(str, "%x", &c);
1083 c = (c&0xf) | ((c&0xf0) << 4) | ((c&0xf00) << 8);
1086 r = (c >> 16) & 0xff;
1087 g = (c >> 8) & 0xff;
1089 return NSVG_RGB(r,g,b);
1092 static unsigned int nsvg__parseColorRGB(const char* str)
1094 int r = -1, g = -1, b = -1;
1095 char s1[33]="", s2[33]="";
1097 * In the original file, the formatted data reading did not specify the string with width limitation.
1098 * To prevent the possible overflow, we replace '%s' with '%32s' here.
1100 sscanf(str + 4, "%d%32[%%, \t]%d%32[%%, \t]%d", &r, s1, &g, s2, &b);
1101 if (strchr(s1, '%')) {
1102 return NSVG_RGB((r*255)/100,(g*255)/100,(b*255)/100);
1104 return NSVG_RGB(r,g,b);
1108 typedef struct NSVGNamedColor {
1113 NSVGNamedColor nsvg__colors[] = {
1115 { "red", NSVG_RGB(255, 0, 0) },
1116 { "green", NSVG_RGB( 0, 128, 0) },
1117 { "blue", NSVG_RGB( 0, 0, 255) },
1118 { "yellow", NSVG_RGB(255, 255, 0) },
1119 { "cyan", NSVG_RGB( 0, 255, 255) },
1120 { "magenta", NSVG_RGB(255, 0, 255) },
1121 { "black", NSVG_RGB( 0, 0, 0) },
1122 { "grey", NSVG_RGB(128, 128, 128) },
1123 { "gray", NSVG_RGB(128, 128, 128) },
1124 { "white", NSVG_RGB(255, 255, 255) },
1126 { "aliceblue", NSVG_RGB(240, 248, 255) },
1127 { "antiquewhite", NSVG_RGB(250, 235, 215) },
1128 { "aqua", NSVG_RGB( 0, 255, 255) },
1129 { "aquamarine", NSVG_RGB(127, 255, 212) },
1130 { "azure", NSVG_RGB(240, 255, 255) },
1131 { "beige", NSVG_RGB(245, 245, 220) },
1132 { "bisque", NSVG_RGB(255, 228, 196) },
1133 { "blanchedalmond", NSVG_RGB(255, 235, 205) },
1134 { "blueviolet", NSVG_RGB(138, 43, 226) },
1135 { "brown", NSVG_RGB(165, 42, 42) },
1136 { "burlywood", NSVG_RGB(222, 184, 135) },
1137 { "cadetblue", NSVG_RGB( 95, 158, 160) },
1138 { "chartreuse", NSVG_RGB(127, 255, 0) },
1139 { "chocolate", NSVG_RGB(210, 105, 30) },
1140 { "coral", NSVG_RGB(255, 127, 80) },
1141 { "cornflowerblue", NSVG_RGB(100, 149, 237) },
1142 { "cornsilk", NSVG_RGB(255, 248, 220) },
1143 { "crimson", NSVG_RGB(220, 20, 60) },
1144 { "darkblue", NSVG_RGB( 0, 0, 139) },
1145 { "darkcyan", NSVG_RGB( 0, 139, 139) },
1146 { "darkgoldenrod", NSVG_RGB(184, 134, 11) },
1147 { "darkgray", NSVG_RGB(169, 169, 169) },
1148 { "darkgreen", NSVG_RGB( 0, 100, 0) },
1149 { "darkgrey", NSVG_RGB(169, 169, 169) },
1150 { "darkkhaki", NSVG_RGB(189, 183, 107) },
1151 { "darkmagenta", NSVG_RGB(139, 0, 139) },
1152 { "darkolivegreen", NSVG_RGB( 85, 107, 47) },
1153 { "darkorange", NSVG_RGB(255, 140, 0) },
1154 { "darkorchid", NSVG_RGB(153, 50, 204) },
1155 { "darkred", NSVG_RGB(139, 0, 0) },
1156 { "darksalmon", NSVG_RGB(233, 150, 122) },
1157 { "darkseagreen", NSVG_RGB(143, 188, 143) },
1158 { "darkslateblue", NSVG_RGB( 72, 61, 139) },
1159 { "darkslategray", NSVG_RGB( 47, 79, 79) },
1160 { "darkslategrey", NSVG_RGB( 47, 79, 79) },
1161 { "darkturquoise", NSVG_RGB( 0, 206, 209) },
1162 { "darkviolet", NSVG_RGB(148, 0, 211) },
1163 { "deeppink", NSVG_RGB(255, 20, 147) },
1164 { "deepskyblue", NSVG_RGB( 0, 191, 255) },
1165 { "dimgray", NSVG_RGB(105, 105, 105) },
1166 { "dimgrey", NSVG_RGB(105, 105, 105) },
1167 { "dodgerblue", NSVG_RGB( 30, 144, 255) },
1168 { "firebrick", NSVG_RGB(178, 34, 34) },
1169 { "floralwhite", NSVG_RGB(255, 250, 240) },
1170 { "forestgreen", NSVG_RGB( 34, 139, 34) },
1171 { "fuchsia", NSVG_RGB(255, 0, 255) },
1172 { "gainsboro", NSVG_RGB(220, 220, 220) },
1173 { "ghostwhite", NSVG_RGB(248, 248, 255) },
1174 { "gold", NSVG_RGB(255, 215, 0) },
1175 { "goldenrod", NSVG_RGB(218, 165, 32) },
1176 { "greenyellow", NSVG_RGB(173, 255, 47) },
1177 { "honeydew", NSVG_RGB(240, 255, 240) },
1178 { "hotpink", NSVG_RGB(255, 105, 180) },
1179 { "indianred", NSVG_RGB(205, 92, 92) },
1180 { "indigo", NSVG_RGB( 75, 0, 130) },
1181 { "ivory", NSVG_RGB(255, 255, 240) },
1182 { "khaki", NSVG_RGB(240, 230, 140) },
1183 { "lavender", NSVG_RGB(230, 230, 250) },
1184 { "lavenderblush", NSVG_RGB(255, 240, 245) },
1185 { "lawngreen", NSVG_RGB(124, 252, 0) },
1186 { "lemonchiffon", NSVG_RGB(255, 250, 205) },
1187 { "lightblue", NSVG_RGB(173, 216, 230) },
1188 { "lightcoral", NSVG_RGB(240, 128, 128) },
1189 { "lightcyan", NSVG_RGB(224, 255, 255) },
1190 { "lightgoldenrodyellow", NSVG_RGB(250, 250, 210) },
1191 { "lightgray", NSVG_RGB(211, 211, 211) },
1192 { "lightgreen", NSVG_RGB(144, 238, 144) },
1193 { "lightgrey", NSVG_RGB(211, 211, 211) },
1194 { "lightpink", NSVG_RGB(255, 182, 193) },
1195 { "lightsalmon", NSVG_RGB(255, 160, 122) },
1196 { "lightseagreen", NSVG_RGB( 32, 178, 170) },
1197 { "lightskyblue", NSVG_RGB(135, 206, 250) },
1198 { "lightslategray", NSVG_RGB(119, 136, 153) },
1199 { "lightslategrey", NSVG_RGB(119, 136, 153) },
1200 { "lightsteelblue", NSVG_RGB(176, 196, 222) },
1201 { "lightyellow", NSVG_RGB(255, 255, 224) },
1202 { "lime", NSVG_RGB( 0, 255, 0) },
1203 { "limegreen", NSVG_RGB( 50, 205, 50) },
1204 { "linen", NSVG_RGB(250, 240, 230) },
1205 { "maroon", NSVG_RGB(128, 0, 0) },
1206 { "mediumaquamarine", NSVG_RGB(102, 205, 170) },
1207 { "mediumblue", NSVG_RGB( 0, 0, 205) },
1208 { "mediumorchid", NSVG_RGB(186, 85, 211) },
1209 { "mediumpurple", NSVG_RGB(147, 112, 219) },
1210 { "mediumseagreen", NSVG_RGB( 60, 179, 113) },
1211 { "mediumslateblue", NSVG_RGB(123, 104, 238) },
1212 { "mediumspringgreen", NSVG_RGB( 0, 250, 154) },
1213 { "mediumturquoise", NSVG_RGB( 72, 209, 204) },
1214 { "mediumvioletred", NSVG_RGB(199, 21, 133) },
1215 { "midnightblue", NSVG_RGB( 25, 25, 112) },
1216 { "mintcream", NSVG_RGB(245, 255, 250) },
1217 { "mistyrose", NSVG_RGB(255, 228, 225) },
1218 { "moccasin", NSVG_RGB(255, 228, 181) },
1219 { "navajowhite", NSVG_RGB(255, 222, 173) },
1220 { "navy", NSVG_RGB( 0, 0, 128) },
1221 { "oldlace", NSVG_RGB(253, 245, 230) },
1222 { "olive", NSVG_RGB(128, 128, 0) },
1223 { "olivedrab", NSVG_RGB(107, 142, 35) },
1224 { "orange", NSVG_RGB(255, 165, 0) },
1225 { "orangered", NSVG_RGB(255, 69, 0) },
1226 { "orchid", NSVG_RGB(218, 112, 214) },
1227 { "palegoldenrod", NSVG_RGB(238, 232, 170) },
1228 { "palegreen", NSVG_RGB(152, 251, 152) },
1229 { "paleturquoise", NSVG_RGB(175, 238, 238) },
1230 { "palevioletred", NSVG_RGB(219, 112, 147) },
1231 { "papayawhip", NSVG_RGB(255, 239, 213) },
1232 { "peachpuff", NSVG_RGB(255, 218, 185) },
1233 { "peru", NSVG_RGB(205, 133, 63) },
1234 { "pink", NSVG_RGB(255, 192, 203) },
1235 { "plum", NSVG_RGB(221, 160, 221) },
1236 { "powderblue", NSVG_RGB(176, 224, 230) },
1237 { "purple", NSVG_RGB(128, 0, 128) },
1238 { "rosybrown", NSVG_RGB(188, 143, 143) },
1239 { "royalblue", NSVG_RGB( 65, 105, 225) },
1240 { "saddlebrown", NSVG_RGB(139, 69, 19) },
1241 { "salmon", NSVG_RGB(250, 128, 114) },
1242 { "sandybrown", NSVG_RGB(244, 164, 96) },
1243 { "seagreen", NSVG_RGB( 46, 139, 87) },
1244 { "seashell", NSVG_RGB(255, 245, 238) },
1245 { "sienna", NSVG_RGB(160, 82, 45) },
1246 { "silver", NSVG_RGB(192, 192, 192) },
1247 { "skyblue", NSVG_RGB(135, 206, 235) },
1248 { "slateblue", NSVG_RGB(106, 90, 205) },
1249 { "slategray", NSVG_RGB(112, 128, 144) },
1250 { "slategrey", NSVG_RGB(112, 128, 144) },
1251 { "snow", NSVG_RGB(255, 250, 250) },
1252 { "springgreen", NSVG_RGB( 0, 255, 127) },
1253 { "steelblue", NSVG_RGB( 70, 130, 180) },
1254 { "tan", NSVG_RGB(210, 180, 140) },
1255 { "teal", NSVG_RGB( 0, 128, 128) },
1256 { "thistle", NSVG_RGB(216, 191, 216) },
1257 { "tomato", NSVG_RGB(255, 99, 71) },
1258 { "turquoise", NSVG_RGB( 64, 224, 208) },
1259 { "violet", NSVG_RGB(238, 130, 238) },
1260 { "wheat", NSVG_RGB(245, 222, 179) },
1261 { "whitesmoke", NSVG_RGB(245, 245, 245) },
1262 { "yellowgreen", NSVG_RGB(154, 205, 50) },
1265 static unsigned int nsvg__parseColorName(const char* str)
1267 int i, ncolors = sizeof(nsvg__colors) / sizeof(NSVGNamedColor);
1269 for (i = 0; i < ncolors; i++) {
1270 if (strcmp(nsvg__colors[i].name, str) == 0) {
1271 return nsvg__colors[i].color;
1275 return NSVG_RGB(128, 128, 128);
1278 static unsigned int nsvg__parseColor(const char* str)
1281 while(*str == ' ') ++str;
1283 if (len >= 1 && *str == '#')
1284 return nsvg__parseColorHex(str);
1285 else if (len >= 4 && str[0] == 'r' && str[1] == 'g' && str[2] == 'b' && str[3] == '(')
1286 return nsvg__parseColorRGB(str);
1287 return nsvg__parseColorName(str);
1290 static float nsvg__parseOpacity(const char* str)
1292 float val = nsvg__atof(str);
1293 if (val < 0.0f) val = 0.0f;
1294 if (val > 1.0f) val = 1.0f;
1298 static float nsvg__parseMiterLimit(const char* str)
1300 float val = nsvg__atof(str);
1301 if (val < 0.0f) val = 0.0f;
1305 static int nsvg__parseUnits(const char* units)
1307 if (units[0] == 'p' && units[1] == 'x')
1308 return NSVG_UNITS_PX;
1309 else if (units[0] == 'p' && units[1] == 't')
1310 return NSVG_UNITS_PT;
1311 else if (units[0] == 'p' && units[1] == 'c')
1312 return NSVG_UNITS_PC;
1313 else if (units[0] == 'm' && units[1] == 'm')
1314 return NSVG_UNITS_MM;
1315 else if (units[0] == 'c' && units[1] == 'm')
1316 return NSVG_UNITS_CM;
1317 else if (units[0] == 'i' && units[1] == 'n')
1318 return NSVG_UNITS_IN;
1319 else if (units[0] == '%')
1320 return NSVG_UNITS_PERCENT;
1321 else if (units[0] == 'e' && units[1] == 'm')
1322 return NSVG_UNITS_EM;
1323 else if (units[0] == 'e' && units[1] == 'x')
1324 return NSVG_UNITS_EX;
1325 return NSVG_UNITS_USER;
1328 static NSVGcoordinate nsvg__parseCoordinateRaw(const char* str)
1330 NSVGcoordinate coord = {0, NSVG_UNITS_USER};
1332 coord.units = nsvg__parseUnits(nsvg__parseNumber(str, buf, 64));
1333 coord.value = nsvg__atof(buf);
1337 static NSVGcoordinate nsvg__coord(float v, int units)
1339 NSVGcoordinate coord = {v, units};
1343 static float nsvg__parseCoordinate(NSVGparser* p, const char* str, float orig, float length)
1345 NSVGcoordinate coord = nsvg__parseCoordinateRaw(str);
1346 return nsvg__convertToPixels(p, coord, orig, length);
1349 static int nsvg__parseTransformArgs(const char* str, float* args, int maxNa, int* na)
1357 while (*ptr && *ptr != '(') ++ptr;
1361 while (*end && *end != ')') ++end;
1366 if (*ptr == '-' || *ptr == '+' || *ptr == '.' || nsvg__isdigit(*ptr)) {
1367 if (*na >= maxNa) return 0;
1368 ptr = nsvg__parseNumber(ptr, it, 64);
1369 args[(*na)++] = (float)nsvg__atof(it);
1374 return (int)(end - str);
1378 static int nsvg__parseMatrix(float* xform, const char* str)
1382 int len = nsvg__parseTransformArgs(str, t, 6, &na);
1383 if (na != 6) return len;
1384 memcpy(xform, t, sizeof(float)*6);
1388 static int nsvg__parseTranslate(float* xform, const char* str)
1393 int len = nsvg__parseTransformArgs(str, args, 2, &na);
1394 if (na == 1) args[1] = 0.0;
1396 nsvg__xformSetTranslation(t, args[0], args[1]);
1397 memcpy(xform, t, sizeof(float)*6);
1401 static int nsvg__parseScale(float* xform, const char* str)
1406 int len = nsvg__parseTransformArgs(str, args, 2, &na);
1407 if (na == 1) args[1] = args[0];
1408 nsvg__xformSetScale(t, args[0], args[1]);
1409 memcpy(xform, t, sizeof(float)*6);
1413 static int nsvg__parseSkewX(float* xform, const char* str)
1418 int len = nsvg__parseTransformArgs(str, args, 1, &na);
1419 nsvg__xformSetSkewX(t, args[0]/180.0f*NSVG_PI);
1420 memcpy(xform, t, sizeof(float)*6);
1424 static int nsvg__parseSkewY(float* xform, const char* str)
1429 int len = nsvg__parseTransformArgs(str, args, 1, &na);
1430 nsvg__xformSetSkewY(t, args[0]/180.0f*NSVG_PI);
1431 memcpy(xform, t, sizeof(float)*6);
1435 static int nsvg__parseRotate(float* xform, const char* str)
1441 int len = nsvg__parseTransformArgs(str, args, 3, &na);
1443 args[1] = args[2] = 0.0f;
1444 nsvg__xformIdentity(m);
1447 nsvg__xformSetTranslation(t, -args[1], -args[2]);
1448 nsvg__xformMultiply(m, t);
1451 nsvg__xformSetRotation(t, args[0]/180.0f*NSVG_PI);
1452 nsvg__xformMultiply(m, t);
1455 nsvg__xformSetTranslation(t, args[1], args[2]);
1456 nsvg__xformMultiply(m, t);
1459 memcpy(xform, m, sizeof(float)*6);
1464 static void nsvg__parseTransform(float* xform, const char* str)
1467 nsvg__xformIdentity(xform);
1470 if (strncmp(str, "matrix", 6) == 0)
1471 str += nsvg__parseMatrix(t, str);
1472 else if (strncmp(str, "translate", 9) == 0)
1473 str += nsvg__parseTranslate(t, str);
1474 else if (strncmp(str, "scale", 5) == 0)
1475 str += nsvg__parseScale(t, str);
1476 else if (strncmp(str, "rotate", 6) == 0)
1477 str += nsvg__parseRotate(t, str);
1478 else if (strncmp(str, "skewX", 5) == 0)
1479 str += nsvg__parseSkewX(t, str);
1480 else if (strncmp(str, "skewY", 5) == 0)
1481 str += nsvg__parseSkewY(t, str);
1487 nsvg__xformPremultiply(xform, t);
1491 static void nsvg__parseUrl(char* id, const char* str)
1494 str += 4; // "url(";
1497 while (i < 63 && *str != ')') {
1504 static char nsvg__parseLineCap(const char* str)
1506 if (strcmp(str, "butt") == 0)
1507 return NSVG_CAP_BUTT;
1508 else if (strcmp(str, "round") == 0)
1509 return NSVG_CAP_ROUND;
1510 else if (strcmp(str, "square") == 0)
1511 return NSVG_CAP_SQUARE;
1512 // TODO: handle inherit.
1513 return NSVG_CAP_BUTT;
1516 static char nsvg__parseLineJoin(const char* str)
1518 if (strcmp(str, "miter") == 0)
1519 return NSVG_JOIN_MITER;
1520 else if (strcmp(str, "round") == 0)
1521 return NSVG_JOIN_ROUND;
1522 else if (strcmp(str, "bevel") == 0)
1523 return NSVG_JOIN_BEVEL;
1524 // TODO: handle inherit.
1525 return NSVG_CAP_BUTT;
1528 static char nsvg__parseFillRule(const char* str)
1530 if (strcmp(str, "nonzero") == 0)
1531 return NSVG_FILLRULE_NONZERO;
1532 else if (strcmp(str, "evenodd") == 0)
1533 return NSVG_FILLRULE_EVENODD;
1534 // TODO: handle inherit.
1535 return NSVG_FILLRULE_NONZERO;
1538 static const char* nsvg__getNextDashItem(const char* s, char* it)
1542 // Skip white spaces and commas
1543 while (*s && (nsvg__isspace(*s) || *s == ',')) s++;
1544 // Advance until whitespace, comma or end.
1545 while (*s && (!nsvg__isspace(*s) && *s != ',')) {
1554 static int nsvg__parseStrokeDashArray(NSVGparser* p, const char* str, float* strokeDashArray)
1566 str = nsvg__getNextDashItem(str, item);
1568 if (count < NSVG_MAX_DASHES)
1569 strokeDashArray[count++] = fabsf(nsvg__parseCoordinate(p, item, 0.0f, nsvg__actualLength(p)));
1572 for (i = 0; i < count; i++)
1573 sum += strokeDashArray[i];
1580 static void nsvg__parseStyle(NSVGparser* p, const char* str);
1582 static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value)
1585 NSVGattrib* attr = nsvg__getAttr(p);
1586 if (!attr) return 0;
1588 if (strcmp(name, "style") == 0) {
1589 nsvg__parseStyle(p, value);
1590 } else if (strcmp(name, "display") == 0) {
1591 if (strcmp(value, "none") == 0)
1593 // Don't reset ->visible on display:inline, one display:none hides the whole subtree
1595 } else if (strcmp(name, "fill") == 0) {
1596 if (strcmp(value, "none") == 0) {
1598 } else if (strncmp(value, "url(", 4) == 0) {
1600 nsvg__parseUrl(attr->fillGradient, value);
1603 attr->fillColor = nsvg__parseColor(value);
1605 } else if (strcmp(name, "opacity") == 0) {
1606 attr->opacity = nsvg__parseOpacity(value);
1607 } else if (strcmp(name, "fill-opacity") == 0) {
1608 attr->fillOpacity = nsvg__parseOpacity(value);
1609 } else if (strcmp(name, "stroke") == 0) {
1610 if (strcmp(value, "none") == 0) {
1611 attr->hasStroke = 0;
1612 } else if (strncmp(value, "url(", 4) == 0) {
1613 attr->hasStroke = 2;
1614 nsvg__parseUrl(attr->strokeGradient, value);
1616 attr->hasStroke = 1;
1617 attr->strokeColor = nsvg__parseColor(value);
1619 } else if (strcmp(name, "stroke-width") == 0) {
1620 attr->strokeWidth = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1621 } else if (strcmp(name, "stroke-dasharray") == 0) {
1622 attr->strokeDashCount = nsvg__parseStrokeDashArray(p, value, attr->strokeDashArray);
1623 } else if (strcmp(name, "stroke-dashoffset") == 0) {
1624 attr->strokeDashOffset = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1625 } else if (strcmp(name, "stroke-opacity") == 0) {
1626 attr->strokeOpacity = nsvg__parseOpacity(value);
1627 } else if (strcmp(name, "stroke-linecap") == 0) {
1628 attr->strokeLineCap = nsvg__parseLineCap(value);
1629 } else if (strcmp(name, "stroke-linejoin") == 0) {
1630 attr->strokeLineJoin = nsvg__parseLineJoin(value);
1631 } else if (strcmp(name, "stroke-miterlimit") == 0) {
1632 attr->miterLimit = nsvg__parseMiterLimit(value);
1633 } else if (strcmp(name, "fill-rule") == 0) {
1634 attr->fillRule = nsvg__parseFillRule(value);
1635 } else if (strcmp(name, "font-size") == 0) {
1636 attr->fontSize = nsvg__parseCoordinate(p, value, 0.0f, nsvg__actualLength(p));
1637 } else if (strcmp(name, "transform") == 0) {
1638 nsvg__parseTransform(xform, value);
1639 nsvg__xformPremultiply(attr->xform, xform);
1640 } else if (strcmp(name, "stop-color") == 0) {
1641 attr->stopColor = nsvg__parseColor(value);
1642 } else if (strcmp(name, "stop-opacity") == 0) {
1643 attr->stopOpacity = nsvg__parseOpacity(value);
1644 } else if (strcmp(name, "offset") == 0) {
1645 attr->stopOffset = nsvg__parseCoordinate(p, value, 0.0f, 1.0f);
1646 } else if (strcmp(name, "id") == 0) {
1647 strncpy(attr->id, value, 63);
1648 attr->id[63] = '\0';
1655 static int nsvg__parseNameValue(NSVGparser* p, const char* start, const char* end)
1664 while (str < end && *str != ':') ++str;
1669 while (str > start && (*str == ':' || nsvg__isspace(*str))) --str;
1672 n = (int)(str - start);
1673 if (n > 511) n = 511;
1674 if (n) memcpy(name, start, n);
1677 while (val < end && (*val == ':' || nsvg__isspace(*val))) ++val;
1679 n = (int)(end - val);
1680 if (n > 511) n = 511;
1681 if (n) memcpy(value, val, n);
1684 return nsvg__parseAttr(p, name, value);
1687 static void nsvg__parseStyle(NSVGparser* p, const char* str)
1694 while(*str && nsvg__isspace(*str)) ++str;
1696 while(*str && *str != ';') ++str;
1700 while (end > start && (*end == ';' || nsvg__isspace(*end))) --end;
1703 nsvg__parseNameValue(p, start, end);
1708 static void nsvg__parseAttribs(NSVGparser* p, const char** attr)
1711 for (i = 0; attr[i]; i += 2)
1713 if (strcmp(attr[i], "style") == 0)
1714 nsvg__parseStyle(p, attr[i + 1]);
1716 nsvg__parseAttr(p, attr[i], attr[i + 1]);
1720 static int nsvg__getArgsPerElement(char cmd)
1750 static void nsvg__pathMoveTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1759 nsvg__moveTo(p, *cpx, *cpy);
1762 static void nsvg__pathLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1771 nsvg__lineTo(p, *cpx, *cpy);
1774 static void nsvg__pathHLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1780 nsvg__lineTo(p, *cpx, *cpy);
1783 static void nsvg__pathVLineTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1789 nsvg__lineTo(p, *cpx, *cpy);
1792 static void nsvg__pathCubicBezTo(NSVGparser* p, float* cpx, float* cpy,
1793 float* cpx2, float* cpy2, float* args, int rel)
1795 float x2, y2, cx1, cy1, cx2, cy2;
1798 cx1 = *cpx + args[0];
1799 cy1 = *cpy + args[1];
1800 cx2 = *cpx + args[2];
1801 cy2 = *cpy + args[3];
1802 x2 = *cpx + args[4];
1803 y2 = *cpy + args[5];
1813 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1821 static void nsvg__pathCubicBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1822 float* cpx2, float* cpy2, float* args, int rel)
1824 float x1, y1, x2, y2, cx1, cy1, cx2, cy2;
1829 cx2 = *cpx + args[0];
1830 cy2 = *cpy + args[1];
1831 x2 = *cpx + args[2];
1832 y2 = *cpy + args[3];
1843 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1851 static void nsvg__pathQuadBezTo(NSVGparser* p, float* cpx, float* cpy,
1852 float* cpx2, float* cpy2, float* args, int rel)
1854 float x1, y1, x2, y2, cx, cy;
1855 float cx1, cy1, cx2, cy2;
1860 cx = *cpx + args[0];
1861 cy = *cpy + args[1];
1862 x2 = *cpx + args[2];
1863 y2 = *cpy + args[3];
1871 // Convert to cubic bezier
1872 cx1 = x1 + 2.0f/3.0f*(cx - x1);
1873 cy1 = y1 + 2.0f/3.0f*(cy - y1);
1874 cx2 = x2 + 2.0f/3.0f*(cx - x2);
1875 cy2 = y2 + 2.0f/3.0f*(cy - y2);
1877 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1885 static void nsvg__pathQuadBezShortTo(NSVGparser* p, float* cpx, float* cpy,
1886 float* cpx2, float* cpy2, float* args, int rel)
1888 float x1, y1, x2, y2, cx, cy;
1889 float cx1, cy1, cx2, cy2;
1894 x2 = *cpx + args[0];
1895 y2 = *cpy + args[1];
1904 // Convert to cubix bezier
1905 cx1 = x1 + 2.0f/3.0f*(cx - x1);
1906 cy1 = y1 + 2.0f/3.0f*(cy - y1);
1907 cx2 = x2 + 2.0f/3.0f*(cx - x2);
1908 cy2 = y2 + 2.0f/3.0f*(cy - y2);
1910 nsvg__cubicBezTo(p, cx1,cy1, cx2,cy2, x2,y2);
1918 static float nsvg__sqr(float x) { return x*x; }
1919 static float nsvg__vmag(float x, float y) { return sqrtf(x*x + y*y); }
1921 static float nsvg__vecrat(float ux, float uy, float vx, float vy)
1923 return (ux*vx + uy*vy) / (nsvg__vmag(ux,uy) * nsvg__vmag(vx,vy));
1926 static float nsvg__vecang(float ux, float uy, float vx, float vy)
1928 float r = nsvg__vecrat(ux,uy, vx,vy);
1929 if (r < -1.0f) r = -1.0f;
1930 if (r > 1.0f) r = 1.0f;
1931 return ((ux*vy < uy*vx) ? -1.0f : 1.0f) * acosf(r);
1934 static void nsvg__pathArcTo(NSVGparser* p, float* cpx, float* cpy, float* args, int rel)
1936 // Ported from canvg (https://code.google.com/p/canvg/)
1938 float x1, y1, x2, y2, cx, cy, dx, dy, d;
1939 float x1p, y1p, cxp, cyp, s, sa, sb;
1940 float ux, uy, vx, vy, a1, da;
1941 float x, y, tanx, tany, a, px = 0, py = 0, ptanx = 0, ptany = 0, t[6];
1947 rx = fabsf(args[0]); // y radius
1948 ry = fabsf(args[1]); // x radius
1949 rotx = args[2] / 180.0f * NSVG_PI; // x rotation angle
1950 fa = fabsf(args[3]) > 1e-6 ? 1 : 0; // Large arc
1951 fs = fabsf(args[4]) > 1e-6 ? 1 : 0; // Sweep direction
1952 x1 = *cpx; // start point
1954 if (rel) { // end point
1955 x2 = *cpx + args[5];
1956 y2 = *cpy + args[6];
1964 d = sqrtf(dx*dx + dy*dy);
1965 if (d < 1e-6f || rx < 1e-6f || ry < 1e-6f) {
1966 // The arc degenerates to a line
1967 nsvg__lineTo(p, x2, y2);
1976 // Convert to center point parameterization.
1977 // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
1978 // 1) Compute x1', y1'
1979 x1p = cosrx * dx / 2.0f + sinrx * dy / 2.0f;
1980 y1p = -sinrx * dx / 2.0f + cosrx * dy / 2.0f;
1981 d = nsvg__sqr(x1p)/nsvg__sqr(rx) + nsvg__sqr(y1p)/nsvg__sqr(ry);
1987 // 2) Compute cx', cy'
1989 sa = nsvg__sqr(rx)*nsvg__sqr(ry) - nsvg__sqr(rx)*nsvg__sqr(y1p) - nsvg__sqr(ry)*nsvg__sqr(x1p);
1990 sb = nsvg__sqr(rx)*nsvg__sqr(y1p) + nsvg__sqr(ry)*nsvg__sqr(x1p);
1991 if (sa < 0.0f) sa = 0.0f;
1996 cxp = s * rx * y1p / ry;
1997 cyp = s * -ry * x1p / rx;
1999 // 3) Compute cx,cy from cx',cy'
2000 cx = (x1 + x2)/2.0f + cosrx*cxp - sinrx*cyp;
2001 cy = (y1 + y2)/2.0f + sinrx*cxp + cosrx*cyp;
2003 // 4) Calculate theta1, and delta theta.
2004 ux = (x1p - cxp) / rx;
2005 uy = (y1p - cyp) / ry;
2006 vx = (-x1p - cxp) / rx;
2007 vy = (-y1p - cyp) / ry;
2008 a1 = nsvg__vecang(1.0f,0.0f, ux,uy); // Initial angle
2009 da = nsvg__vecang(ux,uy, vx,vy); // Delta angle
2011 // if (vecrat(ux,uy,vx,vy) <= -1.0f) da = NSVG_PI;
2012 // if (vecrat(ux,uy,vx,vy) >= 1.0f) da = 0;
2014 if (fs == 0 && da > 0)
2016 else if (fs == 1 && da < 0)
2019 // Approximate the arc using cubic spline segments.
2020 t[0] = cosrx; t[1] = sinrx;
2021 t[2] = -sinrx; t[3] = cosrx;
2022 t[4] = cx; t[5] = cy;
2024 // Split arc into max 90 degree segments.
2025 // The loop assumes an iteration per end point (including start and end), this +1.
2026 ndivs = (int)(fabsf(da) / (NSVG_PI*0.5f) + 1.0f);
2027 hda = (da / (float)ndivs) / 2.0f;
2028 kappa = fabsf(4.0f / 3.0f * (1.0f - cosf(hda)) / sinf(hda));
2032 for (i = 0; i <= ndivs; i++) {
2033 a = a1 + da * ((float)i/(float)ndivs);
2036 nsvg__xformPoint(&x, &y, dx*rx, dy*ry, t); // position
2037 nsvg__xformVec(&tanx, &tany, -dy*rx * kappa, dx*ry * kappa, t); // tangent
2039 nsvg__cubicBezTo(p, px+ptanx,py+ptany, x-tanx, y-tany, x, y);
2050 static void nsvg__parsePath(NSVGparser* p, const char** attr)
2052 const char* s = NULL;
2057 float cpx, cpy, cpx2, cpy2;
2063 for (i = 0; attr[i]; i += 2) {
2064 if (strcmp(attr[i], "d") == 0) {
2068 tmp[1] = attr[i + 1];
2071 nsvg__parseAttribs(p, tmp);
2083 s = nsvg__getNextPathItem(s, item);
2085 if (nsvg__isnum(item[0])) {
2087 args[nargs++] = (float)nsvg__atof(item);
2088 if (nargs >= rargs) {
2092 nsvg__pathMoveTo(p, &cpx, &cpy, args, cmd == 'm' ? 1 : 0);
2093 // Moveto can be followed by multiple coordinate pairs,
2094 // which should be treated as linetos.
2095 cmd = (cmd == 'm') ? 'l' : 'L';
2096 rargs = nsvg__getArgsPerElement(cmd);
2097 cpx2 = cpx; cpy2 = cpy;
2101 nsvg__pathLineTo(p, &cpx, &cpy, args, cmd == 'l' ? 1 : 0);
2102 cpx2 = cpx; cpy2 = cpy;
2106 nsvg__pathHLineTo(p, &cpx, &cpy, args, cmd == 'h' ? 1 : 0);
2107 cpx2 = cpx; cpy2 = cpy;
2111 nsvg__pathVLineTo(p, &cpx, &cpy, args, cmd == 'v' ? 1 : 0);
2112 cpx2 = cpx; cpy2 = cpy;
2116 nsvg__pathCubicBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'c' ? 1 : 0);
2120 nsvg__pathCubicBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 's' ? 1 : 0);
2124 nsvg__pathQuadBezTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 'q' ? 1 : 0);
2128 nsvg__pathQuadBezShortTo(p, &cpx, &cpy, &cpx2, &cpy2, args, cmd == 't' ? 1 : 0);
2132 nsvg__pathArcTo(p, &cpx, &cpy, args, cmd == 'a' ? 1 : 0);
2133 cpx2 = cpx; cpy2 = cpy;
2137 cpx = args[nargs-2];
2138 cpy = args[nargs-1];
2139 cpx2 = cpx; cpy2 = cpy;
2147 rargs = nsvg__getArgsPerElement(cmd);
2148 if (cmd == 'M' || cmd == 'm') {
2151 nsvg__addPath(p, closedFlag);
2152 // Start new subpath.
2156 } else if (cmd == 'Z' || cmd == 'z') {
2160 // Move current point to first point
2163 cpx2 = cpx; cpy2 = cpy;
2164 nsvg__addPath(p, closedFlag);
2166 // Start new subpath.
2168 nsvg__moveTo(p, cpx, cpy);
2176 nsvg__addPath(p, closedFlag);
2182 static void nsvg__parseRect(NSVGparser* p, const char** attr)
2188 float rx = -1.0f; // marks not set
2192 for (i = 0; attr[i]; i += 2) {
2193 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2194 if (strcmp(attr[i], "x") == 0) x = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2195 if (strcmp(attr[i], "y") == 0) y = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2196 if (strcmp(attr[i], "width") == 0) w = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p));
2197 if (strcmp(attr[i], "height") == 0) h = nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p));
2198 if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2199 if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2203 if (rx < 0.0f && ry > 0.0f) rx = ry;
2204 if (ry < 0.0f && rx > 0.0f) ry = rx;
2205 if (rx < 0.0f) rx = 0.0f;
2206 if (ry < 0.0f) ry = 0.0f;
2207 if (rx > w/2.0f) rx = w/2.0f;
2208 if (ry > h/2.0f) ry = h/2.0f;
2210 if (w != 0.0f && h != 0.0f) {
2213 if (rx < 0.00001f || ry < 0.0001f) {
2214 nsvg__moveTo(p, x, y);
2215 nsvg__lineTo(p, x+w, y);
2216 nsvg__lineTo(p, x+w, y+h);
2217 nsvg__lineTo(p, x, y+h);
2219 // Rounded rectangle
2220 nsvg__moveTo(p, x+rx, y);
2221 nsvg__lineTo(p, x+w-rx, y);
2222 nsvg__cubicBezTo(p, x+w-rx*(1-NSVG_KAPPA90), y, x+w, y+ry*(1-NSVG_KAPPA90), x+w, y+ry);
2223 nsvg__lineTo(p, x+w, y+h-ry);
2224 nsvg__cubicBezTo(p, x+w, y+h-ry*(1-NSVG_KAPPA90), x+w-rx*(1-NSVG_KAPPA90), y+h, x+w-rx, y+h);
2225 nsvg__lineTo(p, x+rx, y+h);
2226 nsvg__cubicBezTo(p, x+rx*(1-NSVG_KAPPA90), y+h, x, y+h-ry*(1-NSVG_KAPPA90), x, y+h-ry);
2227 nsvg__lineTo(p, x, y+ry);
2228 nsvg__cubicBezTo(p, x, y+ry*(1-NSVG_KAPPA90), x+rx*(1-NSVG_KAPPA90), y, x+rx, y);
2231 nsvg__addPath(p, 1);
2237 static void nsvg__parseCircle(NSVGparser* p, const char** attr)
2244 for (i = 0; attr[i]; i += 2) {
2245 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2246 if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2247 if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2248 if (strcmp(attr[i], "r") == 0) r = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualLength(p)));
2255 nsvg__moveTo(p, cx+r, cy);
2256 nsvg__cubicBezTo(p, cx+r, cy+r*NSVG_KAPPA90, cx+r*NSVG_KAPPA90, cy+r, cx, cy+r);
2257 nsvg__cubicBezTo(p, cx-r*NSVG_KAPPA90, cy+r, cx-r, cy+r*NSVG_KAPPA90, cx-r, cy);
2258 nsvg__cubicBezTo(p, cx-r, cy-r*NSVG_KAPPA90, cx-r*NSVG_KAPPA90, cy-r, cx, cy-r);
2259 nsvg__cubicBezTo(p, cx+r*NSVG_KAPPA90, cy-r, cx+r, cy-r*NSVG_KAPPA90, cx+r, cy);
2261 nsvg__addPath(p, 1);
2267 static void nsvg__parseEllipse(NSVGparser* p, const char** attr)
2275 for (i = 0; attr[i]; i += 2) {
2276 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2277 if (strcmp(attr[i], "cx") == 0) cx = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2278 if (strcmp(attr[i], "cy") == 0) cy = nsvg__parseCoordinate(p, attr[i+1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2279 if (strcmp(attr[i], "rx") == 0) rx = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualWidth(p)));
2280 if (strcmp(attr[i], "ry") == 0) ry = fabsf(nsvg__parseCoordinate(p, attr[i+1], 0.0f, nsvg__actualHeight(p)));
2284 if (rx > 0.0f && ry > 0.0f) {
2288 nsvg__moveTo(p, cx+rx, cy);
2289 nsvg__cubicBezTo(p, cx+rx, cy+ry*NSVG_KAPPA90, cx+rx*NSVG_KAPPA90, cy+ry, cx, cy+ry);
2290 nsvg__cubicBezTo(p, cx-rx*NSVG_KAPPA90, cy+ry, cx-rx, cy+ry*NSVG_KAPPA90, cx-rx, cy);
2291 nsvg__cubicBezTo(p, cx-rx, cy-ry*NSVG_KAPPA90, cx-rx*NSVG_KAPPA90, cy-ry, cx, cy-ry);
2292 nsvg__cubicBezTo(p, cx+rx*NSVG_KAPPA90, cy-ry, cx+rx, cy-ry*NSVG_KAPPA90, cx+rx, cy);
2294 nsvg__addPath(p, 1);
2300 static void nsvg__parseLine(NSVGparser* p, const char** attr)
2308 for (i = 0; attr[i]; i += 2) {
2309 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2310 if (strcmp(attr[i], "x1") == 0) x1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2311 if (strcmp(attr[i], "y1") == 0) y1 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2312 if (strcmp(attr[i], "x2") == 0) x2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigX(p), nsvg__actualWidth(p));
2313 if (strcmp(attr[i], "y2") == 0) y2 = nsvg__parseCoordinate(p, attr[i + 1], nsvg__actualOrigY(p), nsvg__actualHeight(p));
2319 nsvg__moveTo(p, x1, y1);
2320 nsvg__lineTo(p, x2, y2);
2322 nsvg__addPath(p, 0);
2327 static void nsvg__parsePoly(NSVGparser* p, const char** attr, int closeFlag)
2332 int nargs, npts = 0;
2337 for (i = 0; attr[i]; i += 2) {
2338 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2339 if (strcmp(attr[i], "points") == 0) {
2343 s = nsvg__getNextPathItem(s, item);
2344 args[nargs++] = (float)nsvg__atof(item);
2347 nsvg__moveTo(p, args[0], args[1]);
2349 nsvg__lineTo(p, args[0], args[1]);
2358 nsvg__addPath(p, (char)closeFlag);
2363 static void nsvg__parseSVG(NSVGparser* p, const char** attr)
2366 for (i = 0; attr[i]; i += 2) {
2367 if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2368 if (strcmp(attr[i], "width") == 0) {
2369 p->image->width = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f);
2370 } else if (strcmp(attr[i], "height") == 0) {
2371 p->image->height = nsvg__parseCoordinate(p, attr[i + 1], 0.0f, 1.0f);
2372 } else if (strcmp(attr[i], "viewBox") == 0) {
2373 const char *s = attr[i + 1];
2375 s = nsvg__parseNumber(s, buf, 64);
2376 p->viewMinx = nsvg__atof(buf);
2377 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2379 s = nsvg__parseNumber(s, buf, 64);
2380 p->viewMiny = nsvg__atof(buf);
2381 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2383 s = nsvg__parseNumber(s, buf, 64);
2384 p->viewWidth = nsvg__atof(buf);
2385 while (*s && (nsvg__isspace(*s) || *s == '%' || *s == ',')) s++;
2387 s = nsvg__parseNumber(s, buf, 64);
2388 p->viewHeight = nsvg__atof(buf);
2389 } else if (strcmp(attr[i], "preserveAspectRatio") == 0) {
2390 if (strstr(attr[i + 1], "none") != 0) {
2391 // No uniform scaling
2392 p->alignType = NSVG_ALIGN_NONE;
2395 if (strstr(attr[i + 1], "xMin") != 0)
2396 p->alignX = NSVG_ALIGN_MIN;
2397 else if (strstr(attr[i + 1], "xMid") != 0)
2398 p->alignX = NSVG_ALIGN_MID;
2399 else if (strstr(attr[i + 1], "xMax") != 0)
2400 p->alignX = NSVG_ALIGN_MAX;
2402 if (strstr(attr[i + 1], "yMin") != 0)
2403 p->alignY = NSVG_ALIGN_MIN;
2404 else if (strstr(attr[i + 1], "yMid") != 0)
2405 p->alignY = NSVG_ALIGN_MID;
2406 else if (strstr(attr[i + 1], "yMax") != 0)
2407 p->alignY = NSVG_ALIGN_MAX;
2409 p->alignType = NSVG_ALIGN_MEET;
2410 if (strstr(attr[i + 1], "slice") != 0)
2411 p->alignType = NSVG_ALIGN_SLICE;
2418 static void nsvg__parseGradient(NSVGparser* p, const char** attr, char type)
2421 NSVGgradientData* grad = (NSVGgradientData*)malloc(sizeof(NSVGgradientData));
2422 if (grad == NULL) return;
2423 memset(grad, 0, sizeof(NSVGgradientData));
2424 grad->units = NSVG_OBJECT_SPACE;
2426 if (grad->type == NSVG_PAINT_LINEAR_GRADIENT) {
2427 grad->linear.x1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2428 grad->linear.y1 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2429 grad->linear.x2 = nsvg__coord(100.0f, NSVG_UNITS_PERCENT);
2430 grad->linear.y2 = nsvg__coord(0.0f, NSVG_UNITS_PERCENT);
2431 } else if (grad->type == NSVG_PAINT_RADIAL_GRADIENT) {
2432 grad->radial.cx = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2433 grad->radial.cy = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2434 grad->radial.r = nsvg__coord(50.0f, NSVG_UNITS_PERCENT);
2437 nsvg__xformIdentity(grad->xform);
2439 for (i = 0; attr[i]; i += 2) {
2440 if (strcmp(attr[i], "id") == 0) {
2441 strncpy(grad->id, attr[i+1], 63);
2442 grad->id[63] = '\0';
2443 } else if (!nsvg__parseAttr(p, attr[i], attr[i + 1])) {
2444 if (strcmp(attr[i], "gradientUnits") == 0) {
2445 if (strcmp(attr[i+1], "objectBoundingBox") == 0)
2446 grad->units = NSVG_OBJECT_SPACE;
2448 grad->units = NSVG_USER_SPACE;
2449 } else if (strcmp(attr[i], "gradientTransform") == 0) {
2450 nsvg__parseTransform(grad->xform, attr[i + 1]);
2451 } else if (strcmp(attr[i], "cx") == 0) {
2452 grad->radial.cx = nsvg__parseCoordinateRaw(attr[i + 1]);
2453 } else if (strcmp(attr[i], "cy") == 0) {
2454 grad->radial.cy = nsvg__parseCoordinateRaw(attr[i + 1]);
2455 } else if (strcmp(attr[i], "r") == 0) {
2456 grad->radial.r = nsvg__parseCoordinateRaw(attr[i + 1]);
2457 } else if (strcmp(attr[i], "fx") == 0) {
2458 grad->radial.fx = nsvg__parseCoordinateRaw(attr[i + 1]);
2459 } else if (strcmp(attr[i], "fy") == 0) {
2460 grad->radial.fy = nsvg__parseCoordinateRaw(attr[i + 1]);
2461 } else if (strcmp(attr[i], "x1") == 0) {
2462 grad->linear.x1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2463 } else if (strcmp(attr[i], "y1") == 0) {
2464 grad->linear.y1 = nsvg__parseCoordinateRaw(attr[i + 1]);
2465 } else if (strcmp(attr[i], "x2") == 0) {
2466 grad->linear.x2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2467 } else if (strcmp(attr[i], "y2") == 0) {
2468 grad->linear.y2 = nsvg__parseCoordinateRaw(attr[i + 1]);
2469 } else if (strcmp(attr[i], "spreadMethod") == 0) {
2470 if (strcmp(attr[i+1], "pad") == 0)
2471 grad->spread = NSVG_SPREAD_PAD;
2472 else if (strcmp(attr[i+1], "reflect") == 0)
2473 grad->spread = NSVG_SPREAD_REFLECT;
2474 else if (strcmp(attr[i+1], "repeat") == 0)
2475 grad->spread = NSVG_SPREAD_REPEAT;
2476 } else if (strcmp(attr[i], "xlink:href") == 0) {
2477 const char *href = attr[i+1];
2478 strncpy(grad->ref, href+1, 62);
2479 grad->ref[62] = '\0';
2484 grad->next = p->gradients;
2485 p->gradients = grad;
2488 static void nsvg__parseGradientStop(NSVGparser* p, const char** attr)
2490 NSVGattrib* curAttr = nsvg__getAttr(p);
2491 NSVGgradientData* grad;
2492 NSVGgradientStop* stop;
2495 curAttr->stopOffset = 0;
2496 curAttr->stopColor = 0;
2497 curAttr->stopOpacity = 1.0f;
2499 for (i = 0; attr[i]; i += 2) {
2500 nsvg__parseAttr(p, attr[i], attr[i + 1]);
2503 // Add stop to the last gradient.
2504 grad = p->gradients;
2505 if (grad == NULL) return;
2508 grad->stops = (NSVGgradientStop*)realloc(grad->stops, sizeof(NSVGgradientStop)*grad->nstops);
2509 if (grad->stops == NULL) return;
2512 idx = grad->nstops-1;
2513 for (i = 0; i < grad->nstops-1; i++) {
2514 if (curAttr->stopOffset < grad->stops[i].offset) {
2519 if (idx != grad->nstops-1) {
2520 for (i = grad->nstops-1; i > idx; i--)
2521 grad->stops[i] = grad->stops[i-1];
2524 stop = &grad->stops[idx];
2525 stop->color = curAttr->stopColor;
2526 stop->color |= (unsigned int)(curAttr->stopOpacity*255) << 24;
2527 stop->offset = curAttr->stopOffset;
2530 static void nsvg__startElement(void* ud, const char* el, const char** attr)
2532 NSVGparser* p = (NSVGparser*)ud;
2535 // Skip everything but gradients in defs
2536 if (strcmp(el, "linearGradient") == 0) {
2537 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2538 } else if (strcmp(el, "radialGradient") == 0) {
2539 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2540 } else if (strcmp(el, "stop") == 0) {
2541 nsvg__parseGradientStop(p, attr);
2546 if (strcmp(el, "g") == 0) {
2548 nsvg__parseAttribs(p, attr);
2549 } else if (strcmp(el, "path") == 0) {
2550 if (p->pathFlag) // Do not allow nested paths.
2553 nsvg__parsePath(p, attr);
2555 } else if (strcmp(el, "rect") == 0) {
2557 nsvg__parseRect(p, attr);
2559 } else if (strcmp(el, "circle") == 0) {
2561 nsvg__parseCircle(p, attr);
2563 } else if (strcmp(el, "ellipse") == 0) {
2565 nsvg__parseEllipse(p, attr);
2567 } else if (strcmp(el, "line") == 0) {
2569 nsvg__parseLine(p, attr);
2571 } else if (strcmp(el, "polyline") == 0) {
2573 nsvg__parsePoly(p, attr, 0);
2575 } else if (strcmp(el, "polygon") == 0) {
2577 nsvg__parsePoly(p, attr, 1);
2579 } else if (strcmp(el, "linearGradient") == 0) {
2580 nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
2581 } else if (strcmp(el, "radialGradient") == 0) {
2582 nsvg__parseGradient(p, attr, NSVG_PAINT_RADIAL_GRADIENT);
2583 } else if (strcmp(el, "stop") == 0) {
2584 nsvg__parseGradientStop(p, attr);
2585 } else if (strcmp(el, "defs") == 0) {
2587 } else if (strcmp(el, "svg") == 0) {
2588 nsvg__parseSVG(p, attr);
2592 static void nsvg__endElement(void* ud, const char* el)
2594 NSVGparser* p = (NSVGparser*)ud;
2596 if (strcmp(el, "g") == 0) {
2598 } else if (strcmp(el, "path") == 0) {
2600 } else if (strcmp(el, "defs") == 0) {
2605 static void nsvg__content(void* ud, const char* s)
2612 static void nsvg__imageBounds(NSVGparser* p, float* bounds)
2615 shape = p->image->shapes;
2616 if (shape == NULL) {
2617 bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0;
2620 bounds[0] = shape->bounds[0];
2621 bounds[1] = shape->bounds[1];
2622 bounds[2] = shape->bounds[2];
2623 bounds[3] = shape->bounds[3];
2624 for (shape = shape->next; shape != NULL; shape = shape->next) {
2625 bounds[0] = nsvg__minf(bounds[0], shape->bounds[0]);
2626 bounds[1] = nsvg__minf(bounds[1], shape->bounds[1]);
2627 bounds[2] = nsvg__maxf(bounds[2], shape->bounds[2]);
2628 bounds[3] = nsvg__maxf(bounds[3], shape->bounds[3]);
2632 static float nsvg__viewAlign(float content, float container, int type)
2634 if (type == NSVG_ALIGN_MIN)
2636 else if (type == NSVG_ALIGN_MAX)
2637 return container - content;
2639 return (container - content) * 0.5f;
2642 static void nsvg__scaleGradient(NSVGgradient* grad, float tx, float ty, float sx, float sy)
2645 nsvg__xformSetTranslation(t, tx, ty);
2646 nsvg__xformMultiply (grad->xform, t);
2648 nsvg__xformSetScale(t, sx, sy);
2649 nsvg__xformMultiply (grad->xform, t);
2652 static void nsvg__scaleToViewbox(NSVGparser* p, const char* units)
2656 float tx, ty, sx, sy, us, bounds[4], t[6], avgs;
2660 // Guess image size if not set completely.
2661 nsvg__imageBounds(p, bounds);
2663 if (p->viewWidth == 0) {
2664 if (p->image->width > 0) {
2665 p->viewWidth = p->image->width;
2667 p->viewMinx = bounds[0];
2668 p->viewWidth = bounds[2] - bounds[0];
2671 if (p->viewHeight == 0) {
2672 if (p->image->height > 0) {
2673 p->viewHeight = p->image->height;
2675 p->viewMiny = bounds[1];
2676 p->viewHeight = bounds[3] - bounds[1];
2681 * We have sample images with the width and height set to 1, whereas the viewbox aspect ratio
2682 * is not square. Use the viewbox in this case.
2684 if (p->image->width <= 1)
2685 p->image->width = p->viewWidth;
2686 if (p->image->height <= 1)
2687 p->image->height = p->viewHeight;
2691 sx = p->viewWidth > 0 ? p->image->width / p->viewWidth : 0;
2692 sy = p->viewHeight > 0 ? p->image->height / p->viewHeight : 0;
2694 us = 1.0f / nsvg__convertToPixels(p, nsvg__coord(1.0f, nsvg__parseUnits(units)), 0.0f, 1.0f);
2697 if (p->alignType == NSVG_ALIGN_MEET) {
2698 // fit whole image into viewbox
2699 sx = sy = nsvg__minf(sx, sy);
2700 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2701 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2702 } else if (p->alignType == NSVG_ALIGN_SLICE) {
2703 // fill whole viewbox with image
2704 sx = sy = nsvg__maxf(sx, sy);
2705 tx += nsvg__viewAlign(p->viewWidth*sx, p->image->width, p->alignX) / sx;
2706 ty += nsvg__viewAlign(p->viewHeight*sy, p->image->height, p->alignY) / sy;
2712 avgs = (sx+sy) / 2.0f;
2713 for (shape = p->image->shapes; shape != NULL; shape = shape->next) {
2714 shape->bounds[0] = (shape->bounds[0] + tx) * sx;
2715 shape->bounds[1] = (shape->bounds[1] + ty) * sy;
2716 shape->bounds[2] = (shape->bounds[2] + tx) * sx;
2717 shape->bounds[3] = (shape->bounds[3] + ty) * sy;
2718 for (path = shape->paths; path != NULL; path = path->next) {
2719 path->bounds[0] = (path->bounds[0] + tx) * sx;
2720 path->bounds[1] = (path->bounds[1] + ty) * sy;
2721 path->bounds[2] = (path->bounds[2] + tx) * sx;
2722 path->bounds[3] = (path->bounds[3] + ty) * sy;
2723 for (i =0; i < path->npts; i++) {
2724 pt = &path->pts[i*2];
2725 pt[0] = (pt[0] + tx) * sx;
2726 pt[1] = (pt[1] + ty) * sy;
2730 if (shape->fill.type == NSVG_PAINT_LINEAR_GRADIENT || shape->fill.type == NSVG_PAINT_RADIAL_GRADIENT) {
2731 nsvg__scaleGradient(shape->fill.gradient, tx,ty, sx,sy);
2732 memcpy(t, shape->fill.gradient->xform, sizeof(float)*6);
2733 nsvg__xformInverse(shape->fill.gradient->xform, t);
2735 if (shape->stroke.type == NSVG_PAINT_LINEAR_GRADIENT || shape->stroke.type == NSVG_PAINT_RADIAL_GRADIENT) {
2736 nsvg__scaleGradient(shape->stroke.gradient, tx,ty, sx,sy);
2737 memcpy(t, shape->stroke.gradient->xform, sizeof(float)*6);
2738 nsvg__xformInverse(shape->stroke.gradient->xform, t);
2741 shape->strokeWidth *= avgs;
2742 shape->strokeDashOffset *= avgs;
2743 for (i = 0; i < shape->strokeDashCount; i++)
2744 shape->strokeDashArray[i] *= avgs;
2748 NSVGimage* nsvgParse(char* input, const char* units, float dpi)
2753 p = nsvg__createParser();
2759 nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p);
2762 nsvg__scaleToViewbox(p, units);
2767 nsvg__deleteParser(p);
2772 NSVGimage* nsvgParseFromFile(const char* filename, const char* units, float dpi)
2778 NSVGimage* image = NULL;
2780 fp = fopen(filename, "rb");
2781 if (!fp) goto error;
2782 fseek(fp, 0, SEEK_END);
2785 * In the original file, unsigned long type 'size' gets a return value. But, the return value of 'ftell()' is
2786 * signed long type. To prevent interpreting an unexpected large value, we put the comparitive condition here.
2788 if( value < 0 ) goto error;
2790 fseek(fp, 0, SEEK_SET);
2791 data = (char*)malloc(size+1);
2792 if (data == NULL) goto error;
2793 if (fread(data, 1, size, fp) != size) goto error;
2794 data[size] = '\0'; // Must be null terminated.
2796 image = nsvgParse(data, units, dpi);
2803 if (data) free(data);
2805 * In the original file, image has null check and free it here. But because image has data after all of the 'goto error',
2806 * 'free(image)' was unreachable. So, we removed it.
2811 void nsvgDelete(NSVGimage* image)
2813 if (image == NULL) return;
2814 NSVGshape *snext, *shape;
2815 shape = image->shapes;
2816 while (shape != NULL) {
2817 snext = shape->next;
2818 nsvg__deletePaths(shape->paths);
2819 nsvg__deletePaint(&shape->fill);
2820 nsvg__deletePaint(&shape->stroke);