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