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