1 //
2 // Copyright (c) 2013 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 // Permission is granted to anyone to use this software for any purpose,
8 // including commercial applications, and to alter it and redistribute it
9 // freely, subject to the following restrictions:
10 // 1. The origin of this software must not be misrepresented; you must not
11 //    claim that you wrote the original software. If you use this software
12 //    in a product, an acknowledgment in the product documentation would be
13 //    appreciated but is not required.
14 // 2. Altered source versions must be plainly marked as such, and must not be
15 //    misrepresented as being the original software.
16 // 3. This notice may not be removed or altered from any source distribution.
17 //
18 
19 #include <stdio.h>
20 #include <math.h>
21 #include "nanovg.h"
22 #define FONTSTASH_IMPLEMENTATION
23 #include "fontstash.h"
24 #define STB_IMAGE_IMPLEMENTATION
25 #include "stb_image.h"
26 
27 #ifdef _MSC_VER
28 #pragma warning(disable: 4100)  // unreferenced formal parameter
29 #pragma warning(disable: 4127)  // conditional expression is constant
30 #pragma warning(disable: 4204)  // nonstandard extension used : non-constant aggregate initializer
31 #pragma warning(disable: 4706)  // assignment within conditional expression
32 #endif
33 
34 #define NVG_INIT_FONTIMAGE_SIZE  512
35 #define NVG_MAX_FONTIMAGE_SIZE   2048
36 #define NVG_MAX_FONTIMAGES       4
37 
38 #define NVG_INIT_COMMANDS_SIZE 256
39 #define NVG_INIT_POINTS_SIZE 128
40 #define NVG_INIT_PATHS_SIZE 16
41 #define NVG_INIT_VERTS_SIZE 256
42 #define NVG_MAX_STATES 32
43 
44 #define NVG_KAPPA90 0.5522847493f	// Length proportional to radius of a cubic bezier handle for 90deg arcs.
45 
46 #define NVG_COUNTOF(arr) (sizeof(arr) / sizeof(0[arr]))
47 
48 
49 enum NVGcommands {
50 	NVG_MOVETO = 0,
51 	NVG_LINETO = 1,
52 	NVG_BEZIERTO = 2,
53 	NVG_CLOSE = 3,
54 	NVG_WINDING = 4,
55 };
56 
57 enum NVGpointFlags
58 {
59 	NVG_PT_CORNER = 0x01,
60 	NVG_PT_LEFT = 0x02,
61 	NVG_PT_BEVEL = 0x04,
62 	NVG_PR_INNERBEVEL = 0x08,
63 };
64 
65 struct NVGstate {
66 	NVGpaint fill;
67 	NVGpaint stroke;
68 	float strokeWidth;
69 	float miterLimit;
70 	int lineJoin;
71 	int lineCap;
72 	float alpha;
73 	float xform[6];
74 	NVGscissor scissor;
75 	float fontSize;
76 	float letterSpacing;
77 	float lineHeight;
78 	float fontBlur;
79 	int textAlign;
80 	int fontId;
81 };
82 typedef struct NVGstate NVGstate;
83 
84 struct NVGpoint {
85 	float x,y;
86 	float dx, dy;
87 	float len;
88 	float dmx, dmy;
89 	unsigned char flags;
90 };
91 typedef struct NVGpoint NVGpoint;
92 
93 struct NVGpathCache {
94 	NVGpoint* points;
95 	int npoints;
96 	int cpoints;
97 	NVGpath* paths;
98 	int npaths;
99 	int cpaths;
100 	NVGvertex* verts;
101 	int nverts;
102 	int cverts;
103 	float bounds[4];
104 };
105 typedef struct NVGpathCache NVGpathCache;
106 
107 struct NVGcontext {
108 	NVGparams params;
109 	float* commands;
110 	int ccommands;
111 	int ncommands;
112 	float commandx, commandy;
113 	NVGstate states[NVG_MAX_STATES];
114 	int nstates;
115 	NVGpathCache* cache;
116 	float tessTol;
117 	float distTol;
118 	float fringeWidth;
119 	float devicePxRatio;
120 	struct FONScontext* fs;
121 	int fontImages[NVG_MAX_FONTIMAGES];
122 	int fontImageIdx;
123 	int drawCallCount;
124 	int fillTriCount;
125 	int strokeTriCount;
126 	int textTriCount;
127 };
128 
nvg__sqrtf(float a)129 static float nvg__sqrtf(float a) { return sqrtf(a); }
nvg__modf(float a,float b)130 static float nvg__modf(float a, float b) { return fmodf(a, b); }
nvg__sinf(float a)131 static float nvg__sinf(float a) { return sinf(a); }
nvg__cosf(float a)132 static float nvg__cosf(float a) { return cosf(a); }
nvg__tanf(float a)133 static float nvg__tanf(float a) { return tanf(a); }
nvg__atan2f(float a,float b)134 static float nvg__atan2f(float a,float b) { return atan2f(a, b); }
nvg__acosf(float a)135 static float nvg__acosf(float a) { return acosf(a); }
136 
nvg__mini(int a,int b)137 static int nvg__mini(int a, int b) { return a < b ? a : b; }
nvg__maxi(int a,int b)138 static int nvg__maxi(int a, int b) { return a > b ? a : b; }
nvg__clampi(int a,int mn,int mx)139 static int nvg__clampi(int a, int mn, int mx) { return a < mn ? mn : (a > mx ? mx : a); }
nvg__minf(float a,float b)140 static float nvg__minf(float a, float b) { return a < b ? a : b; }
nvg__maxf(float a,float b)141 static float nvg__maxf(float a, float b) { return a > b ? a : b; }
nvg__absf(float a)142 static float nvg__absf(float a) { return a >= 0.0f ? a : -a; }
nvg__signf(float a)143 static float nvg__signf(float a) { return a >= 0.0f ? 1.0f : -1.0f; }
nvg__clampf(float a,float mn,float mx)144 static float nvg__clampf(float a, float mn, float mx) { return a < mn ? mn : (a > mx ? mx : a); }
nvg__cross(float dx0,float dy0,float dx1,float dy1)145 static float nvg__cross(float dx0, float dy0, float dx1, float dy1) { return dx1*dy0 - dx0*dy1; }
146 
nvg__normalize(float * x,float * y)147 static float nvg__normalize(float *x, float* y)
148 {
149 	float d = nvg__sqrtf((*x)*(*x) + (*y)*(*y));
150 	if (d > 1e-6f) {
151 		float id = 1.0f / d;
152 		*x *= id;
153 		*y *= id;
154 	}
155 	return d;
156 }
157 
158 
nvg__deletePathCache(NVGpathCache * c)159 static void nvg__deletePathCache(NVGpathCache* c)
160 {
161 	if (c == NULL) return;
162 	if (c->points != NULL) free(c->points);
163 	if (c->paths != NULL) free(c->paths);
164 	if (c->verts != NULL) free(c->verts);
165 	free(c);
166 }
167 
nvg__allocPathCache(void)168 static NVGpathCache* nvg__allocPathCache(void)
169 {
170 	NVGpathCache* c = (NVGpathCache*)malloc(sizeof(NVGpathCache));
171 	if (c == NULL) goto error;
172 	memset(c, 0, sizeof(NVGpathCache));
173 
174 	c->points = (NVGpoint*)malloc(sizeof(NVGpoint)*NVG_INIT_POINTS_SIZE);
175 	if (!c->points) goto error;
176 	c->npoints = 0;
177 	c->cpoints = NVG_INIT_POINTS_SIZE;
178 
179 	c->paths = (NVGpath*)malloc(sizeof(NVGpath)*NVG_INIT_PATHS_SIZE);
180 	if (!c->paths) goto error;
181 	c->npaths = 0;
182 	c->cpaths = NVG_INIT_PATHS_SIZE;
183 
184 	c->verts = (NVGvertex*)malloc(sizeof(NVGvertex)*NVG_INIT_VERTS_SIZE);
185 	if (!c->verts) goto error;
186 	c->nverts = 0;
187 	c->cverts = NVG_INIT_VERTS_SIZE;
188 
189 	return c;
190 error:
191 	nvg__deletePathCache(c);
192 	return NULL;
193 }
194 
nvg__setDevicePixelRatio(NVGcontext * ctx,float ratio)195 static void nvg__setDevicePixelRatio(NVGcontext* ctx, float ratio)
196 {
197 	ctx->tessTol = 0.25f / ratio;
198 	ctx->distTol = 0.01f / ratio;
199 	ctx->fringeWidth = 1.0f / ratio;
200 	ctx->devicePxRatio = ratio;
201 }
202 
nvgCreateInternal(NVGparams * params)203 NVGcontext* nvgCreateInternal(NVGparams* params)
204 {
205 	FONSparams fontParams;
206 	NVGcontext* ctx = (NVGcontext*)malloc(sizeof(NVGcontext));
207 	int i;
208 	if (ctx == NULL) goto error;
209 	memset(ctx, 0, sizeof(NVGcontext));
210 
211 	ctx->params = *params;
212 	for (i = 0; i < NVG_MAX_FONTIMAGES; i++)
213 		ctx->fontImages[i] = 0;
214 
215 	ctx->commands = (float*)malloc(sizeof(float)*NVG_INIT_COMMANDS_SIZE);
216 	if (!ctx->commands) goto error;
217 	ctx->ncommands = 0;
218 	ctx->ccommands = NVG_INIT_COMMANDS_SIZE;
219 
220 	ctx->cache = nvg__allocPathCache();
221 	if (ctx->cache == NULL) goto error;
222 
223 	nvgSave(ctx);
224 	nvgReset(ctx);
225 
226 	nvg__setDevicePixelRatio(ctx, 1.0f);
227 
228 	if (ctx->params.renderCreate(ctx->params.userPtr) == 0) goto error;
229 
230 	// Init font rendering
231 	memset(&fontParams, 0, sizeof(fontParams));
232 	fontParams.width = NVG_INIT_FONTIMAGE_SIZE;
233 	fontParams.height = NVG_INIT_FONTIMAGE_SIZE;
234 	fontParams.flags = FONS_ZERO_TOPLEFT;
235 	fontParams.renderCreate = NULL;
236 	fontParams.renderUpdate = NULL;
237 	fontParams.renderDraw = NULL;
238 	fontParams.renderDelete = NULL;
239 	fontParams.userPtr = NULL;
240 	ctx->fs = fonsCreateInternal(&fontParams);
241 	if (ctx->fs == NULL) goto error;
242 
243 	// Create font texture
244 	ctx->fontImages[0] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, fontParams.width, fontParams.height, 0, NULL);
245 	if (ctx->fontImages[0] == 0) goto error;
246 	ctx->fontImageIdx = 0;
247 
248 	return ctx;
249 
250 error:
251 	nvgDeleteInternal(ctx);
252 	return 0;
253 }
254 
nvgInternalParams(NVGcontext * ctx)255 NVGparams* nvgInternalParams(NVGcontext* ctx)
256 {
257     return &ctx->params;
258 }
259 
nvgDeleteInternal(NVGcontext * ctx)260 void nvgDeleteInternal(NVGcontext* ctx)
261 {
262 	int i;
263 	if (ctx == NULL) return;
264 	if (ctx->commands != NULL) free(ctx->commands);
265 	if (ctx->cache != NULL) nvg__deletePathCache(ctx->cache);
266 
267 	if (ctx->fs)
268 		fonsDeleteInternal(ctx->fs);
269 
270 	for (i = 0; i < NVG_MAX_FONTIMAGES; i++) {
271 		if (ctx->fontImages[i] != 0) {
272 			nvgDeleteImage(ctx, ctx->fontImages[i]);
273 			ctx->fontImages[i] = 0;
274 		}
275 	}
276 
277 	if (ctx->params.renderDelete != NULL)
278 		ctx->params.renderDelete(ctx->params.userPtr);
279 
280 	free(ctx);
281 }
282 
nvgBeginFrame(NVGcontext * ctx,int windowWidth,int windowHeight,float devicePixelRatio)283 void nvgBeginFrame(NVGcontext* ctx, int windowWidth, int windowHeight, float devicePixelRatio)
284 {
285 /*	printf("Tris: draws:%d  fill:%d  stroke:%d  text:%d  TOT:%d\n",
286 		ctx->drawCallCount, ctx->fillTriCount, ctx->strokeTriCount, ctx->textTriCount,
287 		ctx->fillTriCount+ctx->strokeTriCount+ctx->textTriCount);*/
288 
289 	ctx->nstates = 0;
290 	nvgSave(ctx);
291 	nvgReset(ctx);
292 
293 	nvg__setDevicePixelRatio(ctx, devicePixelRatio);
294 
295 	ctx->params.renderViewport(ctx->params.userPtr, windowWidth, windowHeight);
296 
297 	ctx->drawCallCount = 0;
298 	ctx->fillTriCount = 0;
299 	ctx->strokeTriCount = 0;
300 	ctx->textTriCount = 0;
301 }
302 
nvgCancelFrame(NVGcontext * ctx)303 void nvgCancelFrame(NVGcontext* ctx)
304 {
305 	ctx->params.renderCancel(ctx->params.userPtr);
306 }
307 
nvgEndFrame(NVGcontext * ctx)308 void nvgEndFrame(NVGcontext* ctx)
309 {
310 	ctx->params.renderFlush(ctx->params.userPtr);
311 	if (ctx->fontImageIdx != 0) {
312 		int fontImage = ctx->fontImages[ctx->fontImageIdx];
313 		int i, j, iw, ih;
314 		// delete images that smaller than current one
315 		if (fontImage == 0)
316 			return;
317 		nvgImageSize(ctx, fontImage, &iw, &ih);
318 		for (i = j = 0; i < ctx->fontImageIdx; i++) {
319 			if (ctx->fontImages[i] != 0) {
320 				int nw, nh;
321 				nvgImageSize(ctx, ctx->fontImages[i], &nw, &nh);
322 				if (nw < iw || nh < ih)
323 					nvgDeleteImage(ctx, ctx->fontImages[i]);
324 				else
325 					ctx->fontImages[j++] = ctx->fontImages[i];
326 			}
327 		}
328 		// make current font image to first
329 		ctx->fontImages[j++] = ctx->fontImages[0];
330 		ctx->fontImages[0] = fontImage;
331 		ctx->fontImageIdx = 0;
332 		// clear all images after j
333 		for (i = j; i < NVG_MAX_FONTIMAGES; i++)
334 			ctx->fontImages[i] = 0;
335 	}
336 }
337 
nvgRGB(unsigned char r,unsigned char g,unsigned char b)338 NVGcolor nvgRGB(unsigned char r, unsigned char g, unsigned char b)
339 {
340 	return nvgRGBA(r,g,b,255);
341 }
342 
nvgRGBf(float r,float g,float b)343 NVGcolor nvgRGBf(float r, float g, float b)
344 {
345 	return nvgRGBAf(r,g,b,1.0f);
346 }
347 
nvgRGBA(unsigned char r,unsigned char g,unsigned char b,unsigned char a)348 NVGcolor nvgRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a)
349 {
350 	NVGcolor color;
351 	// Use longer initialization to suppress warning.
352 	color.r = r / 255.0f;
353 	color.g = g / 255.0f;
354 	color.b = b / 255.0f;
355 	color.a = a / 255.0f;
356 	return color;
357 }
358 
nvgRGBAf(float r,float g,float b,float a)359 NVGcolor nvgRGBAf(float r, float g, float b, float a)
360 {
361 	NVGcolor color;
362 	// Use longer initialization to suppress warning.
363 	color.r = r;
364 	color.g = g;
365 	color.b = b;
366 	color.a = a;
367 	return color;
368 }
369 
nvgTransRGBA(NVGcolor c,unsigned char a)370 NVGcolor nvgTransRGBA(NVGcolor c, unsigned char a)
371 {
372 	c.a = a / 255.0f;
373 	return c;
374 }
375 
nvgTransRGBAf(NVGcolor c,float a)376 NVGcolor nvgTransRGBAf(NVGcolor c, float a)
377 {
378 	c.a = a;
379 	return c;
380 }
381 
nvgLerpRGBA(NVGcolor c0,NVGcolor c1,float u)382 NVGcolor nvgLerpRGBA(NVGcolor c0, NVGcolor c1, float u)
383 {
384 	int i;
385 	float oneminu;
386 	NVGcolor cint;
387 
388 	u = nvg__clampf(u, 0.0f, 1.0f);
389 	oneminu = 1.0f - u;
390 	for( i = 0; i <4; i++ )
391 	{
392 		cint.rgba[i] = c0.rgba[i] * oneminu + c1.rgba[i] * u;
393 	}
394 
395 	return cint;
396 }
397 
nvgHSL(float h,float s,float l)398 NVGcolor nvgHSL(float h, float s, float l)
399 {
400 	return nvgHSLA(h,s,l,255);
401 }
402 
nvg__hue(float h,float m1,float m2)403 static float nvg__hue(float h, float m1, float m2)
404 {
405 	if (h < 0) h += 1;
406 	if (h > 1) h -= 1;
407 	if (h < 1.0f/6.0f)
408 		return m1 + (m2 - m1) * h * 6.0f;
409 	else if (h < 3.0f/6.0f)
410 		return m2;
411 	else if (h < 4.0f/6.0f)
412 		return m1 + (m2 - m1) * (2.0f/3.0f - h) * 6.0f;
413 	return m1;
414 }
415 
nvgHSLA(float h,float s,float l,unsigned char a)416 NVGcolor nvgHSLA(float h, float s, float l, unsigned char a)
417 {
418 	float m1, m2;
419 	NVGcolor col;
420 	h = nvg__modf(h, 1.0f);
421 	if (h < 0.0f) h += 1.0f;
422 	s = nvg__clampf(s, 0.0f, 1.0f);
423 	l = nvg__clampf(l, 0.0f, 1.0f);
424 	m2 = l <= 0.5f ? (l * (1 + s)) : (l + s - l * s);
425 	m1 = 2 * l - m2;
426 	col.r = nvg__clampf(nvg__hue(h + 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
427 	col.g = nvg__clampf(nvg__hue(h, m1, m2), 0.0f, 1.0f);
428 	col.b = nvg__clampf(nvg__hue(h - 1.0f/3.0f, m1, m2), 0.0f, 1.0f);
429 	col.a = a/255.0f;
430 	return col;
431 }
432 
433 
nvg__getState(NVGcontext * ctx)434 static NVGstate* nvg__getState(NVGcontext* ctx)
435 {
436 	return &ctx->states[ctx->nstates-1];
437 }
438 
nvgTransformIdentity(float * t)439 void nvgTransformIdentity(float* t)
440 {
441 	t[0] = 1.0f; t[1] = 0.0f;
442 	t[2] = 0.0f; t[3] = 1.0f;
443 	t[4] = 0.0f; t[5] = 0.0f;
444 }
445 
nvgTransformTranslate(float * t,float tx,float ty)446 void nvgTransformTranslate(float* t, float tx, float ty)
447 {
448 	t[0] = 1.0f; t[1] = 0.0f;
449 	t[2] = 0.0f; t[3] = 1.0f;
450 	t[4] = tx; t[5] = ty;
451 }
452 
nvgTransformScale(float * t,float sx,float sy)453 void nvgTransformScale(float* t, float sx, float sy)
454 {
455 	t[0] = sx; t[1] = 0.0f;
456 	t[2] = 0.0f; t[3] = sy;
457 	t[4] = 0.0f; t[5] = 0.0f;
458 }
459 
nvgTransformRotate(float * t,float a)460 void nvgTransformRotate(float* t, float a)
461 {
462 	float cs = nvg__cosf(a), sn = nvg__sinf(a);
463 	t[0] = cs; t[1] = sn;
464 	t[2] = -sn; t[3] = cs;
465 	t[4] = 0.0f; t[5] = 0.0f;
466 }
467 
nvgTransformSkewX(float * t,float a)468 void nvgTransformSkewX(float* t, float a)
469 {
470 	t[0] = 1.0f; t[1] = 0.0f;
471 	t[2] = nvg__tanf(a); t[3] = 1.0f;
472 	t[4] = 0.0f; t[5] = 0.0f;
473 }
474 
nvgTransformSkewY(float * t,float a)475 void nvgTransformSkewY(float* t, float a)
476 {
477 	t[0] = 1.0f; t[1] = nvg__tanf(a);
478 	t[2] = 0.0f; t[3] = 1.0f;
479 	t[4] = 0.0f; t[5] = 0.0f;
480 }
481 
nvgTransformMultiply(float * t,const float * s)482 void nvgTransformMultiply(float* t, const float* s)
483 {
484 	float t0 = t[0] * s[0] + t[1] * s[2];
485 	float t2 = t[2] * s[0] + t[3] * s[2];
486 	float t4 = t[4] * s[0] + t[5] * s[2] + s[4];
487 	t[1] = t[0] * s[1] + t[1] * s[3];
488 	t[3] = t[2] * s[1] + t[3] * s[3];
489 	t[5] = t[4] * s[1] + t[5] * s[3] + s[5];
490 	t[0] = t0;
491 	t[2] = t2;
492 	t[4] = t4;
493 }
494 
nvgTransformPremultiply(float * t,const float * s)495 void nvgTransformPremultiply(float* t, const float* s)
496 {
497 	float s2[6];
498 	memcpy(s2, s, sizeof(float)*6);
499 	nvgTransformMultiply(s2, t);
500 	memcpy(t, s2, sizeof(float)*6);
501 }
502 
nvgTransformInverse(float * inv,const float * t)503 int nvgTransformInverse(float* inv, const float* t)
504 {
505 	double invdet, det = (double)t[0] * t[3] - (double)t[2] * t[1];
506 	if (det > -1e-6 && det < 1e-6) {
507 		nvgTransformIdentity(inv);
508 		return 0;
509 	}
510 	invdet = 1.0 / det;
511 	inv[0] = (float)(t[3] * invdet);
512 	inv[2] = (float)(-t[2] * invdet);
513 	inv[4] = (float)(((double)t[2] * t[5] - (double)t[3] * t[4]) * invdet);
514 	inv[1] = (float)(-t[1] * invdet);
515 	inv[3] = (float)(t[0] * invdet);
516 	inv[5] = (float)(((double)t[1] * t[4] - (double)t[0] * t[5]) * invdet);
517 	return 1;
518 }
519 
nvgTransformPoint(float * dx,float * dy,const float * t,float sx,float sy)520 void nvgTransformPoint(float* dx, float* dy, const float* t, float sx, float sy)
521 {
522 	*dx = sx*t[0] + sy*t[2] + t[4];
523 	*dy = sx*t[1] + sy*t[3] + t[5];
524 }
525 
nvgDegToRad(float deg)526 float nvgDegToRad(float deg)
527 {
528 	return deg / 180.0f * NVG_PI;
529 }
530 
nvgRadToDeg(float rad)531 float nvgRadToDeg(float rad)
532 {
533 	return rad / NVG_PI * 180.0f;
534 }
535 
nvg__setPaintColor(NVGpaint * p,NVGcolor color)536 static void nvg__setPaintColor(NVGpaint* p, NVGcolor color)
537 {
538 	memset(p, 0, sizeof(*p));
539 	nvgTransformIdentity(p->xform);
540 	p->radius = 0.0f;
541 	p->feather = 1.0f;
542 	p->innerColor = color;
543 	p->outerColor = color;
544 }
545 
546 
547 // State handling
nvgSave(NVGcontext * ctx)548 void nvgSave(NVGcontext* ctx)
549 {
550 	if (ctx->nstates >= NVG_MAX_STATES)
551 		return;
552 	if (ctx->nstates > 0)
553 		memcpy(&ctx->states[ctx->nstates], &ctx->states[ctx->nstates-1], sizeof(NVGstate));
554 	ctx->nstates++;
555 }
556 
nvgRestore(NVGcontext * ctx)557 void nvgRestore(NVGcontext* ctx)
558 {
559 	if (ctx->nstates <= 1)
560 		return;
561 	ctx->nstates--;
562 }
563 
nvgReset(NVGcontext * ctx)564 void nvgReset(NVGcontext* ctx)
565 {
566 	NVGstate* state = nvg__getState(ctx);
567 	memset(state, 0, sizeof(*state));
568 
569 	nvg__setPaintColor(&state->fill, nvgRGBA(255,255,255,255));
570 	nvg__setPaintColor(&state->stroke, nvgRGBA(0,0,0,255));
571 	state->strokeWidth = 1.0f;
572 	state->miterLimit = 10.0f;
573 	state->lineCap = NVG_BUTT;
574 	state->lineJoin = NVG_MITER;
575 	state->alpha = 1.0f;
576 	nvgTransformIdentity(state->xform);
577 
578 	state->scissor.extent[0] = -1.0f;
579 	state->scissor.extent[1] = -1.0f;
580 
581 	state->fontSize = 16.0f;
582 	state->letterSpacing = 0.0f;
583 	state->lineHeight = 1.0f;
584 	state->fontBlur = 0.0f;
585 	state->textAlign = NVG_ALIGN_LEFT | NVG_ALIGN_BASELINE;
586 	state->fontId = 0;
587 }
588 
589 // State setting
nvgStrokeWidth(NVGcontext * ctx,float width)590 void nvgStrokeWidth(NVGcontext* ctx, float width)
591 {
592 	NVGstate* state = nvg__getState(ctx);
593 	state->strokeWidth = width;
594 }
595 
nvgMiterLimit(NVGcontext * ctx,float limit)596 void nvgMiterLimit(NVGcontext* ctx, float limit)
597 {
598 	NVGstate* state = nvg__getState(ctx);
599 	state->miterLimit = limit;
600 }
601 
nvgLineCap(NVGcontext * ctx,int cap)602 void nvgLineCap(NVGcontext* ctx, int cap)
603 {
604 	NVGstate* state = nvg__getState(ctx);
605 	state->lineCap = cap;
606 }
607 
nvgLineJoin(NVGcontext * ctx,int join)608 void nvgLineJoin(NVGcontext* ctx, int join)
609 {
610 	NVGstate* state = nvg__getState(ctx);
611 	state->lineJoin = join;
612 }
613 
nvgGlobalAlpha(NVGcontext * ctx,float alpha)614 void nvgGlobalAlpha(NVGcontext* ctx, float alpha)
615 {
616 	NVGstate* state = nvg__getState(ctx);
617 	state->alpha = alpha;
618 }
619 
nvgTransform(NVGcontext * ctx,float a,float b,float c,float d,float e,float f)620 void nvgTransform(NVGcontext* ctx, float a, float b, float c, float d, float e, float f)
621 {
622 	NVGstate* state = nvg__getState(ctx);
623 	float t[6] = { a, b, c, d, e, f };
624 	nvgTransformPremultiply(state->xform, t);
625 }
626 
nvgResetTransform(NVGcontext * ctx)627 void nvgResetTransform(NVGcontext* ctx)
628 {
629 	NVGstate* state = nvg__getState(ctx);
630 	nvgTransformIdentity(state->xform);
631 }
632 
nvgTranslate(NVGcontext * ctx,float x,float y)633 void nvgTranslate(NVGcontext* ctx, float x, float y)
634 {
635 	NVGstate* state = nvg__getState(ctx);
636 	float t[6];
637 	nvgTransformTranslate(t, x,y);
638 	nvgTransformPremultiply(state->xform, t);
639 }
640 
nvgRotate(NVGcontext * ctx,float angle)641 void nvgRotate(NVGcontext* ctx, float angle)
642 {
643 	NVGstate* state = nvg__getState(ctx);
644 	float t[6];
645 	nvgTransformRotate(t, angle);
646 	nvgTransformPremultiply(state->xform, t);
647 }
648 
nvgSkewX(NVGcontext * ctx,float angle)649 void nvgSkewX(NVGcontext* ctx, float angle)
650 {
651 	NVGstate* state = nvg__getState(ctx);
652 	float t[6];
653 	nvgTransformSkewX(t, angle);
654 	nvgTransformPremultiply(state->xform, t);
655 }
656 
nvgSkewY(NVGcontext * ctx,float angle)657 void nvgSkewY(NVGcontext* ctx, float angle)
658 {
659 	NVGstate* state = nvg__getState(ctx);
660 	float t[6];
661 	nvgTransformSkewY(t, angle);
662 	nvgTransformPremultiply(state->xform, t);
663 }
664 
nvgScale(NVGcontext * ctx,float x,float y)665 void nvgScale(NVGcontext* ctx, float x, float y)
666 {
667 	NVGstate* state = nvg__getState(ctx);
668 	float t[6];
669 	nvgTransformScale(t, x,y);
670 	nvgTransformPremultiply(state->xform, t);
671 }
672 
nvgCurrentTransform(NVGcontext * ctx,float * xform)673 void nvgCurrentTransform(NVGcontext* ctx, float* xform)
674 {
675 	NVGstate* state = nvg__getState(ctx);
676 	if (xform == NULL) return;
677 	memcpy(xform, state->xform, sizeof(float)*6);
678 }
679 
nvgStrokeColor(NVGcontext * ctx,NVGcolor color)680 void nvgStrokeColor(NVGcontext* ctx, NVGcolor color)
681 {
682 	NVGstate* state = nvg__getState(ctx);
683 	nvg__setPaintColor(&state->stroke, color);
684 }
685 
nvgStrokePaint(NVGcontext * ctx,NVGpaint paint)686 void nvgStrokePaint(NVGcontext* ctx, NVGpaint paint)
687 {
688 	NVGstate* state = nvg__getState(ctx);
689 	state->stroke = paint;
690 	nvgTransformMultiply(state->stroke.xform, state->xform);
691 }
692 
nvgFillColor(NVGcontext * ctx,NVGcolor color)693 void nvgFillColor(NVGcontext* ctx, NVGcolor color)
694 {
695 	NVGstate* state = nvg__getState(ctx);
696 	nvg__setPaintColor(&state->fill, color);
697 }
698 
nvgFillPaint(NVGcontext * ctx,NVGpaint paint)699 void nvgFillPaint(NVGcontext* ctx, NVGpaint paint)
700 {
701 	NVGstate* state = nvg__getState(ctx);
702 	state->fill = paint;
703 	nvgTransformMultiply(state->fill.xform, state->xform);
704 }
705 
nvgCreateImage(NVGcontext * ctx,const char * filename,int imageFlags)706 int nvgCreateImage(NVGcontext* ctx, const char* filename, int imageFlags)
707 {
708 	int w, h, n, image;
709 	unsigned char* img;
710 	stbi_set_unpremultiply_on_load(1);
711 	stbi_convert_iphone_png_to_rgb(1);
712 	img = stbi_load(filename, &w, &h, &n, 4);
713 	if (img == NULL) {
714 //		printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
715 		return 0;
716 	}
717 	image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
718 	stbi_image_free(img);
719 	return image;
720 }
721 
nvgCreateImageMem(NVGcontext * ctx,int imageFlags,const unsigned char * data,int ndata)722 int nvgCreateImageMem(NVGcontext* ctx, int imageFlags, const unsigned char* data, int ndata)
723 {
724 	int w, h, n, image;
725 	unsigned char* img = stbi_load_from_memory(data, ndata, &w, &h, &n, 4);
726 	if (img == NULL) {
727 //		printf("Failed to load %s - %s\n", filename, stbi_failure_reason());
728 		return 0;
729 	}
730 	image = nvgCreateImageRGBA(ctx, w, h, imageFlags, img);
731 	stbi_image_free(img);
732 	return image;
733 }
734 
nvgCreateImageRGBA(NVGcontext * ctx,int w,int h,int imageFlags,const unsigned char * data)735 int nvgCreateImageRGBA(NVGcontext* ctx, int w, int h, int imageFlags, const unsigned char* data)
736 {
737 	return ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_RGBA, w, h, imageFlags, data);
738 }
739 
nvgUpdateImage(NVGcontext * ctx,int image,const unsigned char * data)740 void nvgUpdateImage(NVGcontext* ctx, int image, const unsigned char* data)
741 {
742 	int w, h;
743 	ctx->params.renderGetTextureSize(ctx->params.userPtr, image, &w, &h);
744 	ctx->params.renderUpdateTexture(ctx->params.userPtr, image, 0,0, w,h, data);
745 }
746 
nvgImageSize(NVGcontext * ctx,int image,int * w,int * h)747 void nvgImageSize(NVGcontext* ctx, int image, int* w, int* h)
748 {
749 	ctx->params.renderGetTextureSize(ctx->params.userPtr, image, w, h);
750 }
751 
nvgDeleteImage(NVGcontext * ctx,int image)752 void nvgDeleteImage(NVGcontext* ctx, int image)
753 {
754 	ctx->params.renderDeleteTexture(ctx->params.userPtr, image);
755 }
756 
nvgLinearGradient(NVGcontext * ctx,float sx,float sy,float ex,float ey,NVGcolor icol,NVGcolor ocol)757 NVGpaint nvgLinearGradient(NVGcontext* ctx,
758 								  float sx, float sy, float ex, float ey,
759 								  NVGcolor icol, NVGcolor ocol)
760 {
761 	NVGpaint p;
762 	float dx, dy, d;
763 	const float large = 1e5;
764 	NVG_NOTUSED(ctx);
765 	memset(&p, 0, sizeof(p));
766 
767 	// Calculate transform aligned to the line
768 	dx = ex - sx;
769 	dy = ey - sy;
770 	d = sqrtf(dx*dx + dy*dy);
771 	if (d > 0.0001f) {
772 		dx /= d;
773 		dy /= d;
774 	} else {
775 		dx = 0;
776 		dy = 1;
777 	}
778 
779 	p.xform[0] = dy; p.xform[1] = -dx;
780 	p.xform[2] = dx; p.xform[3] = dy;
781 	p.xform[4] = sx - dx*large; p.xform[5] = sy - dy*large;
782 
783 	p.extent[0] = large;
784 	p.extent[1] = large + d*0.5f;
785 
786 	p.radius = 0.0f;
787 
788 	p.feather = nvg__maxf(1.0f, d);
789 
790 	p.innerColor = icol;
791 	p.outerColor = ocol;
792 
793 	return p;
794 }
795 
nvgRadialGradient(NVGcontext * ctx,float cx,float cy,float inr,float outr,NVGcolor icol,NVGcolor ocol)796 NVGpaint nvgRadialGradient(NVGcontext* ctx,
797 								  float cx, float cy, float inr, float outr,
798 								  NVGcolor icol, NVGcolor ocol)
799 {
800 	NVGpaint p;
801 	float r = (inr+outr)*0.5f;
802 	float f = (outr-inr);
803 	NVG_NOTUSED(ctx);
804 	memset(&p, 0, sizeof(p));
805 
806 	nvgTransformIdentity(p.xform);
807 	p.xform[4] = cx;
808 	p.xform[5] = cy;
809 
810 	p.extent[0] = r;
811 	p.extent[1] = r;
812 
813 	p.radius = r;
814 
815 	p.feather = nvg__maxf(1.0f, f);
816 
817 	p.innerColor = icol;
818 	p.outerColor = ocol;
819 
820 	return p;
821 }
822 
nvgBoxGradient(NVGcontext * ctx,float x,float y,float w,float h,float r,float f,NVGcolor icol,NVGcolor ocol)823 NVGpaint nvgBoxGradient(NVGcontext* ctx,
824 							   float x, float y, float w, float h, float r, float f,
825 							   NVGcolor icol, NVGcolor ocol)
826 {
827 	NVGpaint p;
828 	NVG_NOTUSED(ctx);
829 	memset(&p, 0, sizeof(p));
830 
831 	nvgTransformIdentity(p.xform);
832 	p.xform[4] = x+w*0.5f;
833 	p.xform[5] = y+h*0.5f;
834 
835 	p.extent[0] = w*0.5f;
836 	p.extent[1] = h*0.5f;
837 
838 	p.radius = r;
839 
840 	p.feather = nvg__maxf(1.0f, f);
841 
842 	p.innerColor = icol;
843 	p.outerColor = ocol;
844 
845 	return p;
846 }
847 
848 
nvgImagePattern(NVGcontext * ctx,float cx,float cy,float w,float h,float angle,int image,float alpha)849 NVGpaint nvgImagePattern(NVGcontext* ctx,
850 								float cx, float cy, float w, float h, float angle,
851 								int image, float alpha)
852 {
853 	NVGpaint p;
854 	NVG_NOTUSED(ctx);
855 	memset(&p, 0, sizeof(p));
856 
857 	nvgTransformRotate(p.xform, angle);
858 	p.xform[4] = cx;
859 	p.xform[5] = cy;
860 
861 	p.extent[0] = w;
862 	p.extent[1] = h;
863 
864 	p.image = image;
865 
866 	p.innerColor = p.outerColor = nvgRGBAf(1,1,1,alpha);
867 
868 	return p;
869 }
870 
871 // Scissoring
nvgScissor(NVGcontext * ctx,float x,float y,float w,float h)872 void nvgScissor(NVGcontext* ctx, float x, float y, float w, float h)
873 {
874 	NVGstate* state = nvg__getState(ctx);
875 
876 	w = nvg__maxf(0.0f, w);
877 	h = nvg__maxf(0.0f, h);
878 
879 	nvgTransformIdentity(state->scissor.xform);
880 	state->scissor.xform[4] = x+w*0.5f;
881 	state->scissor.xform[5] = y+h*0.5f;
882 	nvgTransformMultiply(state->scissor.xform, state->xform);
883 
884 	state->scissor.extent[0] = w*0.5f;
885 	state->scissor.extent[1] = h*0.5f;
886 }
887 
nvg__isectRects(float * dst,float ax,float ay,float aw,float ah,float bx,float by,float bw,float bh)888 static void nvg__isectRects(float* dst,
889 							float ax, float ay, float aw, float ah,
890 							float bx, float by, float bw, float bh)
891 {
892 	float minx = nvg__maxf(ax, bx);
893 	float miny = nvg__maxf(ay, by);
894 	float maxx = nvg__minf(ax+aw, bx+bw);
895 	float maxy = nvg__minf(ay+ah, by+bh);
896 	dst[0] = minx;
897 	dst[1] = miny;
898 	dst[2] = nvg__maxf(0.0f, maxx - minx);
899 	dst[3] = nvg__maxf(0.0f, maxy - miny);
900 }
901 
nvgIntersectScissor(NVGcontext * ctx,float x,float y,float w,float h)902 void nvgIntersectScissor(NVGcontext* ctx, float x, float y, float w, float h)
903 {
904 	NVGstate* state = nvg__getState(ctx);
905 	float pxform[6], invxorm[6];
906 	float rect[4];
907 	float ex, ey, tex, tey;
908 
909 	// If no previous scissor has been set, set the scissor as current scissor.
910 	if (state->scissor.extent[0] < 0) {
911 		nvgScissor(ctx, x, y, w, h);
912 		return;
913 	}
914 
915 	// Transform the current scissor rect into current transform space.
916 	// If there is difference in rotation, this will be approximation.
917 	memcpy(pxform, state->scissor.xform, sizeof(float)*6);
918 	ex = state->scissor.extent[0];
919 	ey = state->scissor.extent[1];
920 	nvgTransformInverse(invxorm, state->xform);
921 	nvgTransformMultiply(pxform, invxorm);
922 	tex = ex*nvg__absf(pxform[0]) + ey*nvg__absf(pxform[2]);
923 	tey = ex*nvg__absf(pxform[1]) + ey*nvg__absf(pxform[3]);
924 
925 	// Intersect rects.
926 	nvg__isectRects(rect, pxform[4]-tex,pxform[5]-tey,tex*2,tey*2, x,y,w,h);
927 
928 	nvgScissor(ctx, rect[0], rect[1], rect[2], rect[3]);
929 }
930 
nvgResetScissor(NVGcontext * ctx)931 void nvgResetScissor(NVGcontext* ctx)
932 {
933 	NVGstate* state = nvg__getState(ctx);
934 	memset(state->scissor.xform, 0, sizeof(state->scissor.xform));
935 	state->scissor.extent[0] = -1.0f;
936 	state->scissor.extent[1] = -1.0f;
937 }
938 
nvg__ptEquals(float x1,float y1,float x2,float y2,float tol)939 static int nvg__ptEquals(float x1, float y1, float x2, float y2, float tol)
940 {
941 	float dx = x2 - x1;
942 	float dy = y2 - y1;
943 	return dx*dx + dy*dy < tol*tol;
944 }
945 
nvg__distPtSeg(float x,float y,float px,float py,float qx,float qy)946 static float nvg__distPtSeg(float x, float y, float px, float py, float qx, float qy)
947 {
948 	float pqx, pqy, dx, dy, d, t;
949 	pqx = qx-px;
950 	pqy = qy-py;
951 	dx = x-px;
952 	dy = y-py;
953 	d = pqx*pqx + pqy*pqy;
954 	t = pqx*dx + pqy*dy;
955 	if (d > 0) t /= d;
956 	if (t < 0) t = 0;
957 	else if (t > 1) t = 1;
958 	dx = px + t*pqx - x;
959 	dy = py + t*pqy - y;
960 	return dx*dx + dy*dy;
961 }
962 
nvg__appendCommands(NVGcontext * ctx,float * vals,int nvals)963 static void nvg__appendCommands(NVGcontext* ctx, float* vals, int nvals)
964 {
965 	NVGstate* state = nvg__getState(ctx);
966 	int i;
967 
968 	if (ctx->ncommands+nvals > ctx->ccommands) {
969 		float* commands;
970 		int ccommands = ctx->ncommands+nvals + ctx->ccommands/2;
971 		commands = (float*)realloc(ctx->commands, sizeof(float)*ccommands);
972 		if (commands == NULL) return;
973 		ctx->commands = commands;
974 		ctx->ccommands = ccommands;
975 	}
976 
977 	if ((int)vals[0] != NVG_CLOSE && (int)vals[0] != NVG_WINDING) {
978 		ctx->commandx = vals[nvals-2];
979 		ctx->commandy = vals[nvals-1];
980 	}
981 
982 	// transform commands
983 	i = 0;
984 	while (i < nvals) {
985 		int cmd = (int)vals[i];
986 		switch (cmd) {
987 		case NVG_MOVETO:
988 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
989 			i += 3;
990 			break;
991 		case NVG_LINETO:
992 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
993 			i += 3;
994 			break;
995 		case NVG_BEZIERTO:
996 			nvgTransformPoint(&vals[i+1],&vals[i+2], state->xform, vals[i+1],vals[i+2]);
997 			nvgTransformPoint(&vals[i+3],&vals[i+4], state->xform, vals[i+3],vals[i+4]);
998 			nvgTransformPoint(&vals[i+5],&vals[i+6], state->xform, vals[i+5],vals[i+6]);
999 			i += 7;
1000 			break;
1001 		case NVG_CLOSE:
1002 			i++;
1003 			break;
1004 		case NVG_WINDING:
1005 			i += 2;
1006 			break;
1007 		default:
1008 			i++;
1009 		}
1010 	}
1011 
1012 	memcpy(&ctx->commands[ctx->ncommands], vals, nvals*sizeof(float));
1013 
1014 	ctx->ncommands += nvals;
1015 }
1016 
1017 
nvg__clearPathCache(NVGcontext * ctx)1018 static void nvg__clearPathCache(NVGcontext* ctx)
1019 {
1020 	ctx->cache->npoints = 0;
1021 	ctx->cache->npaths = 0;
1022 }
1023 
nvg__lastPath(NVGcontext * ctx)1024 static NVGpath* nvg__lastPath(NVGcontext* ctx)
1025 {
1026 	if (ctx->cache->npaths > 0)
1027 		return &ctx->cache->paths[ctx->cache->npaths-1];
1028 	return NULL;
1029 }
1030 
nvg__addPath(NVGcontext * ctx)1031 static void nvg__addPath(NVGcontext* ctx)
1032 {
1033 	NVGpath* path;
1034 	if (ctx->cache->npaths+1 > ctx->cache->cpaths) {
1035 		NVGpath* paths;
1036 		int cpaths = ctx->cache->npaths+1 + ctx->cache->cpaths/2;
1037 		paths = (NVGpath*)realloc(ctx->cache->paths, sizeof(NVGpath)*cpaths);
1038 		if (paths == NULL) return;
1039 		ctx->cache->paths = paths;
1040 		ctx->cache->cpaths = cpaths;
1041 	}
1042 	path = &ctx->cache->paths[ctx->cache->npaths];
1043 	memset(path, 0, sizeof(*path));
1044 	path->first = ctx->cache->npoints;
1045 	path->winding = NVG_CCW;
1046 
1047 	ctx->cache->npaths++;
1048 }
1049 
nvg__lastPoint(NVGcontext * ctx)1050 static NVGpoint* nvg__lastPoint(NVGcontext* ctx)
1051 {
1052 	if (ctx->cache->npoints > 0)
1053 		return &ctx->cache->points[ctx->cache->npoints-1];
1054 	return NULL;
1055 }
1056 
nvg__addPoint(NVGcontext * ctx,float x,float y,int flags)1057 static void nvg__addPoint(NVGcontext* ctx, float x, float y, int flags)
1058 {
1059 	NVGpath* path = nvg__lastPath(ctx);
1060 	NVGpoint* pt;
1061 	if (path == NULL) return;
1062 
1063 	if (path->count > 0 && ctx->cache->npoints > 0) {
1064 		pt = nvg__lastPoint(ctx);
1065 		if (nvg__ptEquals(pt->x,pt->y, x,y, ctx->distTol)) {
1066 			pt->flags |= flags;
1067 			return;
1068 		}
1069 	}
1070 
1071 	if (ctx->cache->npoints+1 > ctx->cache->cpoints) {
1072 		NVGpoint* points;
1073 		int cpoints = ctx->cache->npoints+1 + ctx->cache->cpoints/2;
1074 		points = (NVGpoint*)realloc(ctx->cache->points, sizeof(NVGpoint)*cpoints);
1075 		if (points == NULL) return;
1076 		ctx->cache->points = points;
1077 		ctx->cache->cpoints = cpoints;
1078 	}
1079 
1080 	pt = &ctx->cache->points[ctx->cache->npoints];
1081 	memset(pt, 0, sizeof(*pt));
1082 	pt->x = x;
1083 	pt->y = y;
1084 	pt->flags = (unsigned char)flags;
1085 
1086 	ctx->cache->npoints++;
1087 	path->count++;
1088 }
1089 
nvg__closePath(NVGcontext * ctx)1090 static void nvg__closePath(NVGcontext* ctx)
1091 {
1092 	NVGpath* path = nvg__lastPath(ctx);
1093 	if (path == NULL) return;
1094 	path->closed = 1;
1095 }
1096 
nvg__pathWinding(NVGcontext * ctx,int winding)1097 static void nvg__pathWinding(NVGcontext* ctx, int winding)
1098 {
1099 	NVGpath* path = nvg__lastPath(ctx);
1100 	if (path == NULL) return;
1101 	path->winding = winding;
1102 }
1103 
nvg__getAverageScale(float * t)1104 static float nvg__getAverageScale(float *t)
1105 {
1106 	float sx = sqrtf(t[0]*t[0] + t[2]*t[2]);
1107 	float sy = sqrtf(t[1]*t[1] + t[3]*t[3]);
1108 	return (sx + sy) * 0.5f;
1109 }
1110 
nvg__allocTempVerts(NVGcontext * ctx,int nverts)1111 static NVGvertex* nvg__allocTempVerts(NVGcontext* ctx, int nverts)
1112 {
1113 	if (nverts > ctx->cache->cverts) {
1114 		NVGvertex* verts;
1115 		int cverts = (nverts + 0xff) & ~0xff; // Round up to prevent allocations when things change just slightly.
1116 		verts = (NVGvertex*)realloc(ctx->cache->verts, sizeof(NVGvertex)*cverts);
1117 		if (verts == NULL) return NULL;
1118 		ctx->cache->verts = verts;
1119 		ctx->cache->cverts = cverts;
1120 	}
1121 
1122 	return ctx->cache->verts;
1123 }
1124 
nvg__triarea2(float ax,float ay,float bx,float by,float cx,float cy)1125 static float nvg__triarea2(float ax, float ay, float bx, float by, float cx, float cy)
1126 {
1127 	float abx = bx - ax;
1128 	float aby = by - ay;
1129 	float acx = cx - ax;
1130 	float acy = cy - ay;
1131 	return acx*aby - abx*acy;
1132 }
1133 
nvg__polyArea(NVGpoint * pts,int npts)1134 static float nvg__polyArea(NVGpoint* pts, int npts)
1135 {
1136 	int i;
1137 	float area = 0;
1138 	for (i = 2; i < npts; i++) {
1139 		NVGpoint* a = &pts[0];
1140 		NVGpoint* b = &pts[i-1];
1141 		NVGpoint* c = &pts[i];
1142 		area += nvg__triarea2(a->x,a->y, b->x,b->y, c->x,c->y);
1143 	}
1144 	return area * 0.5f;
1145 }
1146 
nvg__polyReverse(NVGpoint * pts,int npts)1147 static void nvg__polyReverse(NVGpoint* pts, int npts)
1148 {
1149 	NVGpoint tmp;
1150 	int i = 0, j = npts-1;
1151 	while (i < j) {
1152 		tmp = pts[i];
1153 		pts[i] = pts[j];
1154 		pts[j] = tmp;
1155 		i++;
1156 		j--;
1157 	}
1158 }
1159 
1160 
nvg__vset(NVGvertex * vtx,float x,float y,float u,float v)1161 static void nvg__vset(NVGvertex* vtx, float x, float y, float u, float v)
1162 {
1163 	vtx->x = x;
1164 	vtx->y = y;
1165 	vtx->u = u;
1166 	vtx->v = v;
1167 }
1168 
nvg__tesselateBezier(NVGcontext * ctx,float x1,float y1,float x2,float y2,float x3,float y3,float x4,float y4,int level,int type)1169 static void nvg__tesselateBezier(NVGcontext* ctx,
1170 								 float x1, float y1, float x2, float y2,
1171 								 float x3, float y3, float x4, float y4,
1172 								 int level, int type)
1173 {
1174 	float x12,y12,x23,y23,x34,y34,x123,y123,x234,y234,x1234,y1234;
1175 	float dx,dy,d2,d3;
1176 
1177 	if (level > 10) return;
1178 
1179 	x12 = (x1+x2)*0.5f;
1180 	y12 = (y1+y2)*0.5f;
1181 	x23 = (x2+x3)*0.5f;
1182 	y23 = (y2+y3)*0.5f;
1183 	x34 = (x3+x4)*0.5f;
1184 	y34 = (y3+y4)*0.5f;
1185 	x123 = (x12+x23)*0.5f;
1186 	y123 = (y12+y23)*0.5f;
1187 
1188 	dx = x4 - x1;
1189 	dy = y4 - y1;
1190 	d2 = nvg__absf(((x2 - x4) * dy - (y2 - y4) * dx));
1191 	d3 = nvg__absf(((x3 - x4) * dy - (y3 - y4) * dx));
1192 
1193 	if ((d2 + d3)*(d2 + d3) < ctx->tessTol * (dx*dx + dy*dy)) {
1194 		nvg__addPoint(ctx, x4, y4, type);
1195 		return;
1196 	}
1197 
1198 /*	if (nvg__absf(x1+x3-x2-x2) + nvg__absf(y1+y3-y2-y2) + nvg__absf(x2+x4-x3-x3) + nvg__absf(y2+y4-y3-y3) < ctx->tessTol) {
1199 		nvg__addPoint(ctx, x4, y4, type);
1200 		return;
1201 	}*/
1202 
1203 	x234 = (x23+x34)*0.5f;
1204 	y234 = (y23+y34)*0.5f;
1205 	x1234 = (x123+x234)*0.5f;
1206 	y1234 = (y123+y234)*0.5f;
1207 
1208 	nvg__tesselateBezier(ctx, x1,y1, x12,y12, x123,y123, x1234,y1234, level+1, 0);
1209 	nvg__tesselateBezier(ctx, x1234,y1234, x234,y234, x34,y34, x4,y4, level+1, type);
1210 }
1211 
nvg__flattenPaths(NVGcontext * ctx)1212 static void nvg__flattenPaths(NVGcontext* ctx)
1213 {
1214 	NVGpathCache* cache = ctx->cache;
1215 //	NVGstate* state = nvg__getState(ctx);
1216 	NVGpoint* last;
1217 	NVGpoint* p0;
1218 	NVGpoint* p1;
1219 	NVGpoint* pts;
1220 	NVGpath* path;
1221 	int i, j;
1222 	float* cp1;
1223 	float* cp2;
1224 	float* p;
1225 	float area;
1226 
1227 	if (cache->npaths > 0)
1228 		return;
1229 
1230 	// Flatten
1231 	i = 0;
1232 	while (i < ctx->ncommands) {
1233 		int cmd = (int)ctx->commands[i];
1234 		switch (cmd) {
1235 		case NVG_MOVETO:
1236 			nvg__addPath(ctx);
1237 			p = &ctx->commands[i+1];
1238 			nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
1239 			i += 3;
1240 			break;
1241 		case NVG_LINETO:
1242 			p = &ctx->commands[i+1];
1243 			nvg__addPoint(ctx, p[0], p[1], NVG_PT_CORNER);
1244 			i += 3;
1245 			break;
1246 		case NVG_BEZIERTO:
1247 			last = nvg__lastPoint(ctx);
1248 			if (last != NULL) {
1249 				cp1 = &ctx->commands[i+1];
1250 				cp2 = &ctx->commands[i+3];
1251 				p = &ctx->commands[i+5];
1252 				nvg__tesselateBezier(ctx, last->x,last->y, cp1[0],cp1[1], cp2[0],cp2[1], p[0],p[1], 0, NVG_PT_CORNER);
1253 			}
1254 			i += 7;
1255 			break;
1256 		case NVG_CLOSE:
1257 			nvg__closePath(ctx);
1258 			i++;
1259 			break;
1260 		case NVG_WINDING:
1261 			nvg__pathWinding(ctx, (int)ctx->commands[i+1]);
1262 			i += 2;
1263 			break;
1264 		default:
1265 			i++;
1266 		}
1267 	}
1268 
1269 	cache->bounds[0] = cache->bounds[1] = 1e6f;
1270 	cache->bounds[2] = cache->bounds[3] = -1e6f;
1271 
1272 	// Calculate the direction and length of line segments.
1273 	for (j = 0; j < cache->npaths; j++) {
1274 		path = &cache->paths[j];
1275 		pts = &cache->points[path->first];
1276 
1277 		// If the first and last points are the same, remove the last, mark as closed path.
1278 		p0 = &pts[path->count-1];
1279 		p1 = &pts[0];
1280 		if (nvg__ptEquals(p0->x,p0->y, p1->x,p1->y, ctx->distTol)) {
1281 			path->count--;
1282 			p0 = &pts[path->count-1];
1283 			path->closed = 1;
1284 		}
1285 
1286 		// Enforce winding.
1287 		if (path->count > 2) {
1288 			area = nvg__polyArea(pts, path->count);
1289 			if (path->winding == NVG_CCW && area < 0.0f)
1290 				nvg__polyReverse(pts, path->count);
1291 			if (path->winding == NVG_CW && area > 0.0f)
1292 				nvg__polyReverse(pts, path->count);
1293 		}
1294 
1295 		for(i = 0; i < path->count; i++) {
1296 			// Calculate segment direction and length
1297 			p0->dx = p1->x - p0->x;
1298 			p0->dy = p1->y - p0->y;
1299 			p0->len = nvg__normalize(&p0->dx, &p0->dy);
1300 			// Update bounds
1301 			cache->bounds[0] = nvg__minf(cache->bounds[0], p0->x);
1302 			cache->bounds[1] = nvg__minf(cache->bounds[1], p0->y);
1303 			cache->bounds[2] = nvg__maxf(cache->bounds[2], p0->x);
1304 			cache->bounds[3] = nvg__maxf(cache->bounds[3], p0->y);
1305 			// Advance
1306 			p0 = p1++;
1307 		}
1308 	}
1309 }
1310 
nvg__curveDivs(float r,float arc,float tol)1311 static int nvg__curveDivs(float r, float arc, float tol)
1312 {
1313 	float da = acosf(r / (r + tol)) * 2.0f;
1314 	return nvg__maxi(2, (int)ceilf(arc / da));
1315 }
1316 
nvg__chooseBevel(int bevel,NVGpoint * p0,NVGpoint * p1,float w,float * x0,float * y0,float * x1,float * y1)1317 static void nvg__chooseBevel(int bevel, NVGpoint* p0, NVGpoint* p1, float w,
1318 							float* x0, float* y0, float* x1, float* y1)
1319 {
1320 	if (bevel) {
1321 		*x0 = p1->x + p0->dy * w;
1322 		*y0 = p1->y - p0->dx * w;
1323 		*x1 = p1->x + p1->dy * w;
1324 		*y1 = p1->y - p1->dx * w;
1325 	} else {
1326 		*x0 = p1->x + p1->dmx * w;
1327 		*y0 = p1->y + p1->dmy * w;
1328 		*x1 = p1->x + p1->dmx * w;
1329 		*y1 = p1->y + p1->dmy * w;
1330 	}
1331 }
1332 
nvg__roundJoin(NVGvertex * dst,NVGpoint * p0,NVGpoint * p1,float lw,float rw,float lu,float ru,int ncap,float fringe)1333 static NVGvertex* nvg__roundJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
1334 										float lw, float rw, float lu, float ru, int ncap, float fringe)
1335 {
1336 	int i, n;
1337 	float dlx0 = p0->dy;
1338 	float dly0 = -p0->dx;
1339 	float dlx1 = p1->dy;
1340 	float dly1 = -p1->dx;
1341 	NVG_NOTUSED(fringe);
1342 
1343 	if (p1->flags & NVG_PT_LEFT) {
1344 		float lx0,ly0,lx1,ly1,a0,a1;
1345 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
1346 		a0 = atan2f(-dly0, -dlx0);
1347 		a1 = atan2f(-dly1, -dlx1);
1348 		if (a1 > a0) a1 -= NVG_PI*2;
1349 
1350 		nvg__vset(dst, lx0, ly0, lu,1); dst++;
1351 		nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1352 
1353 		n = nvg__clampi((int)ceilf(((a0 - a1) / NVG_PI) * ncap), 2, ncap);
1354 		for (i = 0; i < n; i++) {
1355 			float u = i/(float)(n-1);
1356 			float a = a0 + u*(a1-a0);
1357 			float rx = p1->x + cosf(a) * rw;
1358 			float ry = p1->y + sinf(a) * rw;
1359 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1360 			nvg__vset(dst, rx, ry, ru,1); dst++;
1361 		}
1362 
1363 		nvg__vset(dst, lx1, ly1, lu,1); dst++;
1364 		nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1365 
1366 	} else {
1367 		float rx0,ry0,rx1,ry1,a0,a1;
1368 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
1369 		a0 = atan2f(dly0, dlx0);
1370 		a1 = atan2f(dly1, dlx1);
1371 		if (a1 < a0) a1 += NVG_PI*2;
1372 
1373 		nvg__vset(dst, p1->x + dlx0*rw, p1->y + dly0*rw, lu,1); dst++;
1374 		nvg__vset(dst, rx0, ry0, ru,1); dst++;
1375 
1376 		n = nvg__clampi((int)ceilf(((a1 - a0) / NVG_PI) * ncap), 2, ncap);
1377 		for (i = 0; i < n; i++) {
1378 			float u = i/(float)(n-1);
1379 			float a = a0 + u*(a1-a0);
1380 			float lx = p1->x + cosf(a) * lw;
1381 			float ly = p1->y + sinf(a) * lw;
1382 			nvg__vset(dst, lx, ly, lu,1); dst++;
1383 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1384 		}
1385 
1386 		nvg__vset(dst, p1->x + dlx1*rw, p1->y + dly1*rw, lu,1); dst++;
1387 		nvg__vset(dst, rx1, ry1, ru,1); dst++;
1388 
1389 	}
1390 	return dst;
1391 }
1392 
nvg__bevelJoin(NVGvertex * dst,NVGpoint * p0,NVGpoint * p1,float lw,float rw,float lu,float ru,float fringe)1393 static NVGvertex* nvg__bevelJoin(NVGvertex* dst, NVGpoint* p0, NVGpoint* p1,
1394 										float lw, float rw, float lu, float ru, float fringe)
1395 {
1396 	float rx0,ry0,rx1,ry1;
1397 	float lx0,ly0,lx1,ly1;
1398 	float dlx0 = p0->dy;
1399 	float dly0 = -p0->dx;
1400 	float dlx1 = p1->dy;
1401 	float dly1 = -p1->dx;
1402 	NVG_NOTUSED(fringe);
1403 
1404 	if (p1->flags & NVG_PT_LEFT) {
1405 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, lw, &lx0,&ly0, &lx1,&ly1);
1406 
1407 		nvg__vset(dst, lx0, ly0, lu,1); dst++;
1408 		nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1409 
1410 		if (p1->flags & NVG_PT_BEVEL) {
1411 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1412 			nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1413 
1414 			nvg__vset(dst, lx1, ly1, lu,1); dst++;
1415 			nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1416 		} else {
1417 			rx0 = p1->x - p1->dmx * rw;
1418 			ry0 = p1->y - p1->dmy * rw;
1419 
1420 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1421 			nvg__vset(dst, p1->x - dlx0*rw, p1->y - dly0*rw, ru,1); dst++;
1422 
1423 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1424 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1425 
1426 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1427 			nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1428 		}
1429 
1430 		nvg__vset(dst, lx1, ly1, lu,1); dst++;
1431 		nvg__vset(dst, p1->x - dlx1*rw, p1->y - dly1*rw, ru,1); dst++;
1432 
1433 	} else {
1434 		nvg__chooseBevel(p1->flags & NVG_PR_INNERBEVEL, p0, p1, -rw, &rx0,&ry0, &rx1,&ry1);
1435 
1436 		nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1437 		nvg__vset(dst, rx0, ry0, ru,1); dst++;
1438 
1439 		if (p1->flags & NVG_PT_BEVEL) {
1440 			nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1441 			nvg__vset(dst, rx0, ry0, ru,1); dst++;
1442 
1443 			nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1444 			nvg__vset(dst, rx1, ry1, ru,1); dst++;
1445 		} else {
1446 			lx0 = p1->x + p1->dmx * lw;
1447 			ly0 = p1->y + p1->dmy * lw;
1448 
1449 			nvg__vset(dst, p1->x + dlx0*lw, p1->y + dly0*lw, lu,1); dst++;
1450 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1451 
1452 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1453 			nvg__vset(dst, lx0, ly0, lu,1); dst++;
1454 
1455 			nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1456 			nvg__vset(dst, p1->x, p1->y, 0.5f,1); dst++;
1457 		}
1458 
1459 		nvg__vset(dst, p1->x + dlx1*lw, p1->y + dly1*lw, lu,1); dst++;
1460 		nvg__vset(dst, rx1, ry1, ru,1); dst++;
1461 	}
1462 
1463 	return dst;
1464 }
1465 
nvg__buttCapStart(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,float d,float aa)1466 static NVGvertex* nvg__buttCapStart(NVGvertex* dst, NVGpoint* p,
1467 										   float dx, float dy, float w, float d, float aa)
1468 {
1469 	float px = p->x - dx*d;
1470 	float py = p->y - dy*d;
1471 	float dlx = dy;
1472 	float dly = -dx;
1473 	nvg__vset(dst, px + dlx*w - dx*aa, py + dly*w - dy*aa, 0,0); dst++;
1474 	nvg__vset(dst, px - dlx*w - dx*aa, py - dly*w - dy*aa, 1,0); dst++;
1475 	nvg__vset(dst, px + dlx*w, py + dly*w, 0,1); dst++;
1476 	nvg__vset(dst, px - dlx*w, py - dly*w, 1,1); dst++;
1477 	return dst;
1478 }
1479 
nvg__buttCapEnd(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,float d,float aa)1480 static NVGvertex* nvg__buttCapEnd(NVGvertex* dst, NVGpoint* p,
1481 										   float dx, float dy, float w, float d, float aa)
1482 {
1483 	float px = p->x + dx*d;
1484 	float py = p->y + dy*d;
1485 	float dlx = dy;
1486 	float dly = -dx;
1487 	nvg__vset(dst, px + dlx*w, py + dly*w, 0,1); dst++;
1488 	nvg__vset(dst, px - dlx*w, py - dly*w, 1,1); dst++;
1489 	nvg__vset(dst, px + dlx*w + dx*aa, py + dly*w + dy*aa, 0,0); dst++;
1490 	nvg__vset(dst, px - dlx*w + dx*aa, py - dly*w + dy*aa, 1,0); dst++;
1491 	return dst;
1492 }
1493 
1494 
nvg__roundCapStart(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,int ncap,float aa)1495 static NVGvertex* nvg__roundCapStart(NVGvertex* dst, NVGpoint* p,
1496 											float dx, float dy, float w, int ncap, float aa)
1497 {
1498 	int i;
1499 	float px = p->x;
1500 	float py = p->y;
1501 	float dlx = dy;
1502 	float dly = -dx;
1503 	NVG_NOTUSED(aa);
1504 	for (i = 0; i < ncap; i++) {
1505 		float a = i/(float)(ncap-1)*NVG_PI;
1506 		float ax = cosf(a) * w, ay = sinf(a) * w;
1507 		nvg__vset(dst, px - dlx*ax - dx*ay, py - dly*ax - dy*ay, 0,1); dst++;
1508 		nvg__vset(dst, px, py, 0.5f,1); dst++;
1509 	}
1510 	nvg__vset(dst, px + dlx*w, py + dly*w, 0,1); dst++;
1511 	nvg__vset(dst, px - dlx*w, py - dly*w, 1,1); dst++;
1512 	return dst;
1513 }
1514 
nvg__roundCapEnd(NVGvertex * dst,NVGpoint * p,float dx,float dy,float w,int ncap,float aa)1515 static NVGvertex* nvg__roundCapEnd(NVGvertex* dst, NVGpoint* p,
1516 										  float dx, float dy, float w, int ncap, float aa)
1517 {
1518 	int i;
1519 	float px = p->x;
1520 	float py = p->y;
1521 	float dlx = dy;
1522 	float dly = -dx;
1523 	NVG_NOTUSED(aa);
1524 	nvg__vset(dst, px + dlx*w, py + dly*w, 0,1); dst++;
1525 	nvg__vset(dst, px - dlx*w, py - dly*w, 1,1); dst++;
1526 	for (i = 0; i < ncap; i++) {
1527 		float a = i/(float)(ncap-1)*NVG_PI;
1528 		float ax = cosf(a) * w, ay = sinf(a) * w;
1529 		nvg__vset(dst, px, py, 0.5f,1); dst++;
1530 		nvg__vset(dst, px - dlx*ax + dx*ay, py - dly*ax + dy*ay, 0,1); dst++;
1531 	}
1532 	return dst;
1533 }
1534 
1535 
nvg__calculateJoins(NVGcontext * ctx,float w,int lineJoin,float miterLimit)1536 static void nvg__calculateJoins(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
1537 {
1538 	NVGpathCache* cache = ctx->cache;
1539 	int i, j;
1540 	float iw = 0.0f;
1541 
1542 	if (w > 0.0f) iw = 1.0f / w;
1543 
1544 	// Calculate which joins needs extra vertices to append, and gather vertex count.
1545 	for (i = 0; i < cache->npaths; i++) {
1546 		NVGpath* path = &cache->paths[i];
1547 		NVGpoint* pts = &cache->points[path->first];
1548 		NVGpoint* p0 = &pts[path->count-1];
1549 		NVGpoint* p1 = &pts[0];
1550 		int nleft = 0;
1551 
1552 		path->nbevel = 0;
1553 
1554 		for (j = 0; j < path->count; j++) {
1555 			float dlx0, dly0, dlx1, dly1, dmr2, cross, limit;
1556 			dlx0 = p0->dy;
1557 			dly0 = -p0->dx;
1558 			dlx1 = p1->dy;
1559 			dly1 = -p1->dx;
1560 			// Calculate extrusions
1561 			p1->dmx = (dlx0 + dlx1) * 0.5f;
1562 			p1->dmy = (dly0 + dly1) * 0.5f;
1563 			dmr2 = p1->dmx*p1->dmx + p1->dmy*p1->dmy;
1564 			if (dmr2 > 0.000001f) {
1565 				float scale = 1.0f / dmr2;
1566 				if (scale > 600.0f) {
1567 					scale = 600.0f;
1568 				}
1569 				p1->dmx *= scale;
1570 				p1->dmy *= scale;
1571 			}
1572 
1573 			// Clear flags, but keep the corner.
1574 			p1->flags = (p1->flags & NVG_PT_CORNER) ? NVG_PT_CORNER : 0;
1575 
1576 			// Keep track of left turns.
1577 			cross = p1->dx * p0->dy - p0->dx * p1->dy;
1578 			if (cross > 0.0f) {
1579 				nleft++;
1580 				p1->flags |= NVG_PT_LEFT;
1581 			}
1582 
1583 			// Calculate if we should use bevel or miter for inner join.
1584 			limit = nvg__maxf(1.01f, nvg__minf(p0->len, p1->len) * iw);
1585 			if ((dmr2 * limit*limit) < 1.0f)
1586 				p1->flags |= NVG_PR_INNERBEVEL;
1587 
1588 			// Check to see if the corner needs to be beveled.
1589 			if (p1->flags & NVG_PT_CORNER) {
1590 				if ((dmr2 * miterLimit*miterLimit) < 1.0f || lineJoin == NVG_BEVEL || lineJoin == NVG_ROUND) {
1591 					p1->flags |= NVG_PT_BEVEL;
1592 				}
1593 			}
1594 
1595 			if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0)
1596 				path->nbevel++;
1597 
1598 			p0 = p1++;
1599 		}
1600 
1601 		path->convex = (nleft == path->count) ? 1 : 0;
1602 	}
1603 }
1604 
1605 
nvg__expandStroke(NVGcontext * ctx,float w,int lineCap,int lineJoin,float miterLimit)1606 static int nvg__expandStroke(NVGcontext* ctx, float w, int lineCap, int lineJoin, float miterLimit)
1607 {
1608 	NVGpathCache* cache = ctx->cache;
1609 	NVGvertex* verts;
1610 	NVGvertex* dst;
1611 	int cverts, i, j;
1612 	float aa = ctx->fringeWidth;
1613 	int ncap = nvg__curveDivs(w, NVG_PI, ctx->tessTol);	// Calculate divisions per half circle.
1614 
1615 	nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
1616 
1617 	// Calculate max vertex usage.
1618 	cverts = 0;
1619 	for (i = 0; i < cache->npaths; i++) {
1620 		NVGpath* path = &cache->paths[i];
1621 		int loop = (path->closed == 0) ? 0 : 1;
1622 		if (lineJoin == NVG_ROUND)
1623 			cverts += (path->count + path->nbevel*(ncap+2) + 1) * 2; // plus one for loop
1624 		else
1625 			cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
1626 		if (loop == 0) {
1627 			// space for caps
1628 			if (lineCap == NVG_ROUND) {
1629 				cverts += (ncap*2 + 2)*2;
1630 			} else {
1631 				cverts += (3+3)*2;
1632 			}
1633 		}
1634 	}
1635 
1636 	verts = nvg__allocTempVerts(ctx, cverts);
1637 	if (verts == NULL) return 0;
1638 
1639 	for (i = 0; i < cache->npaths; i++) {
1640 		NVGpath* path = &cache->paths[i];
1641 		NVGpoint* pts = &cache->points[path->first];
1642 		NVGpoint* p0;
1643 		NVGpoint* p1;
1644 		int s, e, loop;
1645 		float dx, dy;
1646 
1647 		path->fill = 0;
1648 		path->nfill = 0;
1649 
1650 		// Calculate fringe or stroke
1651 		loop = (path->closed == 0) ? 0 : 1;
1652 		dst = verts;
1653 		path->stroke = dst;
1654 
1655 		if (loop) {
1656 			// Looping
1657 			p0 = &pts[path->count-1];
1658 			p1 = &pts[0];
1659 			s = 0;
1660 			e = path->count;
1661 		} else {
1662 			// Add cap
1663 			p0 = &pts[0];
1664 			p1 = &pts[1];
1665 			s = 1;
1666 			e = path->count-1;
1667 		}
1668 
1669 		if (loop == 0) {
1670 			// Add cap
1671 			dx = p1->x - p0->x;
1672 			dy = p1->y - p0->y;
1673 			nvg__normalize(&dx, &dy);
1674 			if (lineCap == NVG_BUTT)
1675 				dst = nvg__buttCapStart(dst, p0, dx, dy, w, -aa*0.5f, aa);
1676 			else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
1677 				dst = nvg__buttCapStart(dst, p0, dx, dy, w, w-aa, aa);
1678 			else if (lineCap == NVG_ROUND)
1679 				dst = nvg__roundCapStart(dst, p0, dx, dy, w, ncap, aa);
1680 		}
1681 
1682 		for (j = s; j < e; ++j) {
1683 			if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
1684 				if (lineJoin == NVG_ROUND) {
1685 					dst = nvg__roundJoin(dst, p0, p1, w, w, 0, 1, ncap, aa);
1686 				} else {
1687 					dst = nvg__bevelJoin(dst, p0, p1, w, w, 0, 1, aa);
1688 				}
1689 			} else {
1690 				nvg__vset(dst, p1->x + (p1->dmx * w), p1->y + (p1->dmy * w), 0,1); dst++;
1691 				nvg__vset(dst, p1->x - (p1->dmx * w), p1->y - (p1->dmy * w), 1,1); dst++;
1692 			}
1693 			p0 = p1++;
1694 		}
1695 
1696 		if (loop) {
1697 			// Loop it
1698 			nvg__vset(dst, verts[0].x, verts[0].y, 0,1); dst++;
1699 			nvg__vset(dst, verts[1].x, verts[1].y, 1,1); dst++;
1700 		} else {
1701 			// Add cap
1702 			dx = p1->x - p0->x;
1703 			dy = p1->y - p0->y;
1704 			nvg__normalize(&dx, &dy);
1705 			if (lineCap == NVG_BUTT)
1706 				dst = nvg__buttCapEnd(dst, p1, dx, dy, w, -aa*0.5f, aa);
1707 			else if (lineCap == NVG_BUTT || lineCap == NVG_SQUARE)
1708 				dst = nvg__buttCapEnd(dst, p1, dx, dy, w, w-aa, aa);
1709 			else if (lineCap == NVG_ROUND)
1710 				dst = nvg__roundCapEnd(dst, p1, dx, dy, w, ncap, aa);
1711 		}
1712 
1713 		path->nstroke = (int)(dst - verts);
1714 
1715 		verts = dst;
1716 	}
1717 
1718 	return 1;
1719 }
1720 
nvg__expandFill(NVGcontext * ctx,float w,int lineJoin,float miterLimit)1721 static int nvg__expandFill(NVGcontext* ctx, float w, int lineJoin, float miterLimit)
1722 {
1723 	NVGpathCache* cache = ctx->cache;
1724 	NVGvertex* verts;
1725 	NVGvertex* dst;
1726 	int cverts, convex, i, j;
1727 	float aa = ctx->fringeWidth;
1728 	int fringe = w > 0.0f;
1729 
1730 	nvg__calculateJoins(ctx, w, lineJoin, miterLimit);
1731 
1732 	// Calculate max vertex usage.
1733 	cverts = 0;
1734 	for (i = 0; i < cache->npaths; i++) {
1735 		NVGpath* path = &cache->paths[i];
1736 		cverts += path->count + path->nbevel + 1;
1737 		if (fringe)
1738 			cverts += (path->count + path->nbevel*5 + 1) * 2; // plus one for loop
1739 	}
1740 
1741 	verts = nvg__allocTempVerts(ctx, cverts);
1742 	if (verts == NULL) return 0;
1743 
1744 	convex = cache->npaths == 1 && cache->paths[0].convex;
1745 
1746 	for (i = 0; i < cache->npaths; i++) {
1747 		NVGpath* path = &cache->paths[i];
1748 		NVGpoint* pts = &cache->points[path->first];
1749 		NVGpoint* p0;
1750 		NVGpoint* p1;
1751 		float rw, lw, woff;
1752 		float ru, lu;
1753 
1754 		// Calculate shape vertices.
1755 		woff = 0.5f*aa;
1756 		dst = verts;
1757 		path->fill = dst;
1758 
1759 		if (fringe) {
1760 			// Looping
1761 			p0 = &pts[path->count-1];
1762 			p1 = &pts[0];
1763 			for (j = 0; j < path->count; ++j) {
1764 				if (p1->flags & NVG_PT_BEVEL) {
1765 					float dlx0 = p0->dy;
1766 					float dly0 = -p0->dx;
1767 					float dlx1 = p1->dy;
1768 					float dly1 = -p1->dx;
1769 					if (p1->flags & NVG_PT_LEFT) {
1770 						float lx = p1->x + p1->dmx * woff;
1771 						float ly = p1->y + p1->dmy * woff;
1772 						nvg__vset(dst, lx, ly, 0.5f,1); dst++;
1773 					} else {
1774 						float lx0 = p1->x + dlx0 * woff;
1775 						float ly0 = p1->y + dly0 * woff;
1776 						float lx1 = p1->x + dlx1 * woff;
1777 						float ly1 = p1->y + dly1 * woff;
1778 						nvg__vset(dst, lx0, ly0, 0.5f,1); dst++;
1779 						nvg__vset(dst, lx1, ly1, 0.5f,1); dst++;
1780 					}
1781 				} else {
1782 					nvg__vset(dst, p1->x + (p1->dmx * woff), p1->y + (p1->dmy * woff), 0.5f,1); dst++;
1783 				}
1784 				p0 = p1++;
1785 			}
1786 		} else {
1787 			for (j = 0; j < path->count; ++j) {
1788 				nvg__vset(dst, pts[j].x, pts[j].y, 0.5f,1);
1789 				dst++;
1790 			}
1791 		}
1792 
1793 		path->nfill = (int)(dst - verts);
1794 		verts = dst;
1795 
1796 		// Calculate fringe
1797 		if (fringe) {
1798 			lw = w + woff;
1799 			rw = w - woff;
1800 			lu = 0;
1801 			ru = 1;
1802 			dst = verts;
1803 			path->stroke = dst;
1804 
1805 			// Create only half a fringe for convex shapes so that
1806 			// the shape can be rendered without stenciling.
1807 			if (convex) {
1808 				lw = woff;	// This should generate the same vertex as fill inset above.
1809 				lu = 0.5f;	// Set outline fade at middle.
1810 			}
1811 
1812 			// Looping
1813 			p0 = &pts[path->count-1];
1814 			p1 = &pts[0];
1815 
1816 			for (j = 0; j < path->count; ++j) {
1817 				if ((p1->flags & (NVG_PT_BEVEL | NVG_PR_INNERBEVEL)) != 0) {
1818 					dst = nvg__bevelJoin(dst, p0, p1, lw, rw, lu, ru, ctx->fringeWidth);
1819 				} else {
1820 					nvg__vset(dst, p1->x + (p1->dmx * lw), p1->y + (p1->dmy * lw), lu,1); dst++;
1821 					nvg__vset(dst, p1->x - (p1->dmx * rw), p1->y - (p1->dmy * rw), ru,1); dst++;
1822 				}
1823 				p0 = p1++;
1824 			}
1825 
1826 			// Loop it
1827 			nvg__vset(dst, verts[0].x, verts[0].y, lu,1); dst++;
1828 			nvg__vset(dst, verts[1].x, verts[1].y, ru,1); dst++;
1829 
1830 			path->nstroke = (int)(dst - verts);
1831 			verts = dst;
1832 		} else {
1833 			path->stroke = NULL;
1834 			path->nstroke = 0;
1835 		}
1836 	}
1837 
1838 	return 1;
1839 }
1840 
1841 
1842 // Draw
nvgBeginPath(NVGcontext * ctx)1843 void nvgBeginPath(NVGcontext* ctx)
1844 {
1845 	ctx->ncommands = 0;
1846 	nvg__clearPathCache(ctx);
1847 }
1848 
nvgMoveTo(NVGcontext * ctx,float x,float y)1849 void nvgMoveTo(NVGcontext* ctx, float x, float y)
1850 {
1851 	float vals[] = { NVG_MOVETO, x, y };
1852 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1853 }
1854 
nvgLineTo(NVGcontext * ctx,float x,float y)1855 void nvgLineTo(NVGcontext* ctx, float x, float y)
1856 {
1857 	float vals[] = { NVG_LINETO, x, y };
1858 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1859 }
1860 
nvgBezierTo(NVGcontext * ctx,float c1x,float c1y,float c2x,float c2y,float x,float y)1861 void nvgBezierTo(NVGcontext* ctx, float c1x, float c1y, float c2x, float c2y, float x, float y)
1862 {
1863 	float vals[] = { NVG_BEZIERTO, c1x, c1y, c2x, c2y, x, y };
1864 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1865 }
1866 
nvgQuadTo(NVGcontext * ctx,float cx,float cy,float x,float y)1867 void nvgQuadTo(NVGcontext* ctx, float cx, float cy, float x, float y)
1868 {
1869     float x0 = ctx->commandx;
1870     float y0 = ctx->commandy;
1871     float vals[] = { NVG_BEZIERTO,
1872         x0 + 2.0f/3.0f*(cx - x0), y0 + 2.0f/3.0f*(cy - y0),
1873         x + 2.0f/3.0f*(cx - x), y + 2.0f/3.0f*(cy - y),
1874         x, y };
1875     nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1876 }
1877 
nvgArcTo(NVGcontext * ctx,float x1,float y1,float x2,float y2,float radius)1878 void nvgArcTo(NVGcontext* ctx, float x1, float y1, float x2, float y2, float radius)
1879 {
1880 	float x0 = ctx->commandx;
1881 	float y0 = ctx->commandy;
1882 	float dx0,dy0, dx1,dy1, a, d, cx,cy, a0,a1;
1883 	int dir;
1884 
1885 	if (ctx->ncommands == 0) {
1886 		return;
1887 	}
1888 
1889 	// Handle degenerate cases.
1890 	if (nvg__ptEquals(x0,y0, x1,y1, ctx->distTol) ||
1891 		nvg__ptEquals(x1,y1, x2,y2, ctx->distTol) ||
1892 		nvg__distPtSeg(x1,y1, x0,y0, x2,y2) < ctx->distTol*ctx->distTol ||
1893 		radius < ctx->distTol) {
1894 		nvgLineTo(ctx, x1,y1);
1895 		return;
1896 	}
1897 
1898 	// Calculate tangential circle to lines (x0,y0)-(x1,y1) and (x1,y1)-(x2,y2).
1899 	dx0 = x0-x1;
1900 	dy0 = y0-y1;
1901 	dx1 = x2-x1;
1902 	dy1 = y2-y1;
1903 	nvg__normalize(&dx0,&dy0);
1904 	nvg__normalize(&dx1,&dy1);
1905 	a = nvg__acosf(dx0*dx1 + dy0*dy1);
1906 	d = radius / nvg__tanf(a/2.0f);
1907 
1908 //	printf("a=%f° d=%f\n", a/NVG_PI*180.0f, d);
1909 
1910 	if (d > 10000.0f) {
1911 		nvgLineTo(ctx, x1,y1);
1912 		return;
1913 	}
1914 
1915 	if (nvg__cross(dx0,dy0, dx1,dy1) > 0.0f) {
1916 		cx = x1 + dx0*d + dy0*radius;
1917 		cy = y1 + dy0*d + -dx0*radius;
1918 		a0 = nvg__atan2f(dx0, -dy0);
1919 		a1 = nvg__atan2f(-dx1, dy1);
1920 		dir = NVG_CW;
1921 //		printf("CW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
1922 	} else {
1923 		cx = x1 + dx0*d + -dy0*radius;
1924 		cy = y1 + dy0*d + dx0*radius;
1925 		a0 = nvg__atan2f(-dx0, dy0);
1926 		a1 = nvg__atan2f(dx1, -dy1);
1927 		dir = NVG_CCW;
1928 //		printf("CCW c=(%f, %f) a0=%f° a1=%f°\n", cx, cy, a0/NVG_PI*180.0f, a1/NVG_PI*180.0f);
1929 	}
1930 
1931 	nvgArc(ctx, cx, cy, radius, a0, a1, dir);
1932 }
1933 
nvgClosePath(NVGcontext * ctx)1934 void nvgClosePath(NVGcontext* ctx)
1935 {
1936 	float vals[] = { NVG_CLOSE };
1937 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1938 }
1939 
nvgPathWinding(NVGcontext * ctx,int dir)1940 void nvgPathWinding(NVGcontext* ctx, int dir)
1941 {
1942 	float vals[] = { NVG_WINDING, (float)dir };
1943 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
1944 }
1945 
nvgArc(NVGcontext * ctx,float cx,float cy,float r,float a0,float a1,int dir)1946 void nvgArc(NVGcontext* ctx, float cx, float cy, float r, float a0, float a1, int dir)
1947 {
1948 	float a = 0, da = 0, hda = 0, kappa = 0;
1949 	float dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
1950 	float px = 0, py = 0, ptanx = 0, ptany = 0;
1951 	float vals[3 + 5*7 + 100];
1952 	int i, ndivs, nvals;
1953 	int move = ctx->ncommands > 0 ? NVG_LINETO : NVG_MOVETO;
1954 
1955 	// Clamp angles
1956 	da = a1 - a0;
1957 	if (dir == NVG_CW) {
1958 		if (nvg__absf(da) >= NVG_PI*2) {
1959 			da = NVG_PI*2;
1960 		} else {
1961 			while (da < 0.0f) da += NVG_PI*2;
1962 		}
1963 	} else {
1964 		if (nvg__absf(da) >= NVG_PI*2) {
1965 			da = -NVG_PI*2;
1966 		} else {
1967 			while (da > 0.0f) da -= NVG_PI*2;
1968 		}
1969 	}
1970 
1971 	// Split arc into max 90 degree segments.
1972 	ndivs = nvg__maxi(1, nvg__mini((int)(nvg__absf(da) / (NVG_PI*0.5f) + 0.5f), 5));
1973 	hda = (da / (float)ndivs) / 2.0f;
1974 	kappa = nvg__absf(4.0f / 3.0f * (1.0f - nvg__cosf(hda)) / nvg__sinf(hda));
1975 
1976 	if (dir == NVG_CCW)
1977 		kappa = -kappa;
1978 
1979 	nvals = 0;
1980 	for (i = 0; i <= ndivs; i++) {
1981 		a = a0 + da * (i/(float)ndivs);
1982 		dx = nvg__cosf(a);
1983 		dy = nvg__sinf(a);
1984 		x = cx + dx*r;
1985 		y = cy + dy*r;
1986 		tanx = -dy*r*kappa;
1987 		tany = dx*r*kappa;
1988 
1989 		if (i == 0) {
1990 			vals[nvals++] = (float)move;
1991 			vals[nvals++] = x;
1992 			vals[nvals++] = y;
1993 		} else {
1994 			vals[nvals++] = NVG_BEZIERTO;
1995 			vals[nvals++] = px+ptanx;
1996 			vals[nvals++] = py+ptany;
1997 			vals[nvals++] = x-tanx;
1998 			vals[nvals++] = y-tany;
1999 			vals[nvals++] = x;
2000 			vals[nvals++] = y;
2001 		}
2002 		px = x;
2003 		py = y;
2004 		ptanx = tanx;
2005 		ptany = tany;
2006 	}
2007 
2008 	nvg__appendCommands(ctx, vals, nvals);
2009 }
2010 
nvgRect(NVGcontext * ctx,float x,float y,float w,float h)2011 void nvgRect(NVGcontext* ctx, float x, float y, float w, float h)
2012 {
2013 	float vals[] = {
2014 		NVG_MOVETO, x,y,
2015 		NVG_LINETO, x,y+h,
2016 		NVG_LINETO, x+w,y+h,
2017 		NVG_LINETO, x+w,y,
2018 		NVG_CLOSE
2019 	};
2020 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2021 }
2022 
nvgRoundedRect(NVGcontext * ctx,float x,float y,float w,float h,float r)2023 void nvgRoundedRect(NVGcontext* ctx, float x, float y, float w, float h, float r)
2024 {
2025 	if (r < 0.1f) {
2026 		nvgRect(ctx, x,y,w,h);
2027 		return;
2028 	}
2029 	else {
2030 		float rx = nvg__minf(r, nvg__absf(w)*0.5f) * nvg__signf(w), ry = nvg__minf(r, nvg__absf(h)*0.5f) * nvg__signf(h);
2031 		float vals[] = {
2032 			NVG_MOVETO, x, y+ry,
2033 			NVG_LINETO, x, y+h-ry,
2034 			NVG_BEZIERTO, x, y+h-ry*(1-NVG_KAPPA90), x+rx*(1-NVG_KAPPA90), y+h, x+rx, y+h,
2035 			NVG_LINETO, x+w-rx, y+h,
2036 			NVG_BEZIERTO, x+w-rx*(1-NVG_KAPPA90), y+h, x+w, y+h-ry*(1-NVG_KAPPA90), x+w, y+h-ry,
2037 			NVG_LINETO, x+w, y+ry,
2038 			NVG_BEZIERTO, x+w, y+ry*(1-NVG_KAPPA90), x+w-rx*(1-NVG_KAPPA90), y, x+w-rx, y,
2039 			NVG_LINETO, x+rx, y,
2040 			NVG_BEZIERTO, x+rx*(1-NVG_KAPPA90), y, x, y+ry*(1-NVG_KAPPA90), x, y+ry,
2041 			NVG_CLOSE
2042 		};
2043 		nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2044 	}
2045 }
2046 
nvgEllipse(NVGcontext * ctx,float cx,float cy,float rx,float ry)2047 void nvgEllipse(NVGcontext* ctx, float cx, float cy, float rx, float ry)
2048 {
2049 	float vals[] = {
2050 		NVG_MOVETO, cx-rx, cy,
2051 		NVG_BEZIERTO, cx-rx, cy+ry*NVG_KAPPA90, cx-rx*NVG_KAPPA90, cy+ry, cx, cy+ry,
2052 		NVG_BEZIERTO, cx+rx*NVG_KAPPA90, cy+ry, cx+rx, cy+ry*NVG_KAPPA90, cx+rx, cy,
2053 		NVG_BEZIERTO, cx+rx, cy-ry*NVG_KAPPA90, cx+rx*NVG_KAPPA90, cy-ry, cx, cy-ry,
2054 		NVG_BEZIERTO, cx-rx*NVG_KAPPA90, cy-ry, cx-rx, cy-ry*NVG_KAPPA90, cx-rx, cy,
2055 		NVG_CLOSE
2056 	};
2057 	nvg__appendCommands(ctx, vals, NVG_COUNTOF(vals));
2058 }
2059 
nvgCircle(NVGcontext * ctx,float cx,float cy,float r)2060 void nvgCircle(NVGcontext* ctx, float cx, float cy, float r)
2061 {
2062 	nvgEllipse(ctx, cx,cy, r,r);
2063 }
2064 
nvgDebugDumpPathCache(NVGcontext * ctx)2065 void nvgDebugDumpPathCache(NVGcontext* ctx)
2066 {
2067 	const NVGpath* path;
2068 	int i, j;
2069 
2070 	printf("Dumping %d cached paths\n", ctx->cache->npaths);
2071 	for (i = 0; i < ctx->cache->npaths; i++) {
2072 		path = &ctx->cache->paths[i];
2073 		printf(" - Path %d\n", i);
2074 		if (path->nfill) {
2075 			printf("   - fill: %d\n", path->nfill);
2076 			for (j = 0; j < path->nfill; j++)
2077 				printf("%f\t%f\n", path->fill[j].x, path->fill[j].y);
2078 		}
2079 		if (path->nstroke) {
2080 			printf("   - stroke: %d\n", path->nstroke);
2081 			for (j = 0; j < path->nstroke; j++)
2082 				printf("%f\t%f\n", path->stroke[j].x, path->stroke[j].y);
2083 		}
2084 	}
2085 }
2086 
nvgFill(NVGcontext * ctx)2087 void nvgFill(NVGcontext* ctx)
2088 {
2089 	NVGstate* state = nvg__getState(ctx);
2090 	const NVGpath* path;
2091 	NVGpaint fillPaint = state->fill;
2092 	int i;
2093 
2094 	nvg__flattenPaths(ctx);
2095 	if (ctx->params.edgeAntiAlias)
2096 		nvg__expandFill(ctx, ctx->fringeWidth, NVG_MITER, 2.4f);
2097 	else
2098 		nvg__expandFill(ctx, 0.0f, NVG_MITER, 2.4f);
2099 
2100 	// Apply global alpha
2101 	fillPaint.innerColor.a *= state->alpha;
2102 	fillPaint.outerColor.a *= state->alpha;
2103 
2104 	ctx->params.renderFill(ctx->params.userPtr, &fillPaint, &state->scissor, ctx->fringeWidth,
2105 						   ctx->cache->bounds, ctx->cache->paths, ctx->cache->npaths);
2106 
2107 	// Count triangles
2108 	for (i = 0; i < ctx->cache->npaths; i++) {
2109 		path = &ctx->cache->paths[i];
2110 		ctx->fillTriCount += path->nfill-2;
2111 		ctx->fillTriCount += path->nstroke-2;
2112 		ctx->drawCallCount += 2;
2113 	}
2114 }
2115 
nvgStroke(NVGcontext * ctx)2116 void nvgStroke(NVGcontext* ctx)
2117 {
2118 	NVGstate* state = nvg__getState(ctx);
2119 	float scale = nvg__getAverageScale(state->xform);
2120 	float strokeWidth = nvg__clampf(state->strokeWidth * scale, 0.0f, 200.0f);
2121 	NVGpaint strokePaint = state->stroke;
2122 	const NVGpath* path;
2123 	int i;
2124 
2125 	if (strokeWidth < ctx->fringeWidth) {
2126 		// If the stroke width is less than pixel size, use alpha to emulate coverage.
2127 		// Since coverage is area, scale by alpha*alpha.
2128 		float alpha = nvg__clampf(strokeWidth / ctx->fringeWidth, 0.0f, 1.0f);
2129 		strokePaint.innerColor.a *= alpha*alpha;
2130 		strokePaint.outerColor.a *= alpha*alpha;
2131 		strokeWidth = ctx->fringeWidth;
2132 	}
2133 
2134 	// Apply global alpha
2135 	strokePaint.innerColor.a *= state->alpha;
2136 	strokePaint.outerColor.a *= state->alpha;
2137 
2138 	nvg__flattenPaths(ctx);
2139 
2140 	if (ctx->params.edgeAntiAlias)
2141 		nvg__expandStroke(ctx, strokeWidth*0.5f + ctx->fringeWidth*0.5f, state->lineCap, state->lineJoin, state->miterLimit);
2142 	else
2143 		nvg__expandStroke(ctx, strokeWidth*0.5f, state->lineCap, state->lineJoin, state->miterLimit);
2144 
2145 	ctx->params.renderStroke(ctx->params.userPtr, &strokePaint, &state->scissor, ctx->fringeWidth,
2146 							 strokeWidth, ctx->cache->paths, ctx->cache->npaths);
2147 
2148 	// Count triangles
2149 	for (i = 0; i < ctx->cache->npaths; i++) {
2150 		path = &ctx->cache->paths[i];
2151 		ctx->strokeTriCount += path->nstroke-2;
2152 		ctx->drawCallCount++;
2153 	}
2154 }
2155 
2156 // Add fonts
nvgCreateFont(NVGcontext * ctx,const char * name,const char * path)2157 int nvgCreateFont(NVGcontext* ctx, const char* name, const char* path)
2158 {
2159 	return fonsAddFont(ctx->fs, name, path);
2160 }
2161 
nvgCreateFontMem(NVGcontext * ctx,const char * name,const unsigned char * data,int ndata,int freeData)2162 int nvgCreateFontMem(NVGcontext* ctx, const char* name, const unsigned char* data, int ndata, int freeData)
2163 {
2164 	return fonsAddFontMem(ctx->fs, name, data, ndata, freeData);
2165 }
2166 
nvgFindFont(NVGcontext * ctx,const char * name)2167 int nvgFindFont(NVGcontext* ctx, const char* name)
2168 {
2169 	if (name == NULL) return -1;
2170 	return fonsGetFontByName(ctx->fs, name);
2171 }
2172 
2173 // State setting
nvgFontSize(NVGcontext * ctx,float size)2174 void nvgFontSize(NVGcontext* ctx, float size)
2175 {
2176 	NVGstate* state = nvg__getState(ctx);
2177 	state->fontSize = size;
2178 }
2179 
nvgFontBlur(NVGcontext * ctx,float blur)2180 void nvgFontBlur(NVGcontext* ctx, float blur)
2181 {
2182 	NVGstate* state = nvg__getState(ctx);
2183 	state->fontBlur = blur;
2184 }
2185 
nvgTextLetterSpacing(NVGcontext * ctx,float spacing)2186 void nvgTextLetterSpacing(NVGcontext* ctx, float spacing)
2187 {
2188 	NVGstate* state = nvg__getState(ctx);
2189 	state->letterSpacing = spacing;
2190 }
2191 
nvgTextLineHeight(NVGcontext * ctx,float lineHeight)2192 void nvgTextLineHeight(NVGcontext* ctx, float lineHeight)
2193 {
2194 	NVGstate* state = nvg__getState(ctx);
2195 	state->lineHeight = lineHeight;
2196 }
2197 
nvgTextAlign(NVGcontext * ctx,int align)2198 void nvgTextAlign(NVGcontext* ctx, int align)
2199 {
2200 	NVGstate* state = nvg__getState(ctx);
2201 	state->textAlign = align;
2202 }
2203 
nvgFontFaceId(NVGcontext * ctx,int font)2204 void nvgFontFaceId(NVGcontext* ctx, int font)
2205 {
2206 	NVGstate* state = nvg__getState(ctx);
2207 	state->fontId = font;
2208 }
2209 
nvgFontFace(NVGcontext * ctx,const char * font)2210 void nvgFontFace(NVGcontext* ctx, const char* font)
2211 {
2212 	NVGstate* state = nvg__getState(ctx);
2213 	state->fontId = fonsGetFontByName(ctx->fs, font);
2214 }
2215 
nvg__quantize(float a,float d)2216 static float nvg__quantize(float a, float d)
2217 {
2218 	return ((int)(a / d + 0.5f)) * d;
2219 }
2220 
nvg__getFontScale(NVGstate * state)2221 static float nvg__getFontScale(NVGstate* state)
2222 {
2223 	return nvg__minf(nvg__quantize(nvg__getAverageScale(state->xform), 0.01f), 4.0f);
2224 }
2225 
nvg__flushTextTexture(NVGcontext * ctx)2226 static void nvg__flushTextTexture(NVGcontext* ctx)
2227 {
2228 	int dirty[4];
2229 
2230 	if (fonsValidateTexture(ctx->fs, dirty)) {
2231 		int fontImage = ctx->fontImages[ctx->fontImageIdx];
2232 		// Update texture
2233 		if (fontImage != 0) {
2234 			int iw, ih;
2235 			const unsigned char* data = fonsGetTextureData(ctx->fs, &iw, &ih);
2236 			int x = dirty[0];
2237 			int y = dirty[1];
2238 			int w = dirty[2] - dirty[0];
2239 			int h = dirty[3] - dirty[1];
2240 			ctx->params.renderUpdateTexture(ctx->params.userPtr, fontImage, x,y, w,h, data);
2241 		}
2242 	}
2243 }
2244 
nvg__allocTextAtlas(NVGcontext * ctx)2245 static int nvg__allocTextAtlas(NVGcontext* ctx)
2246 {
2247 	int iw, ih;
2248 	nvg__flushTextTexture(ctx);
2249 	if (ctx->fontImageIdx >= NVG_MAX_FONTIMAGES-1)
2250 		return 0;
2251 	// if next fontImage already have a texture
2252 	if (ctx->fontImages[ctx->fontImageIdx+1] != 0)
2253 		nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx+1], &iw, &ih);
2254 	else { // calculate the new font image size and create it.
2255 		nvgImageSize(ctx, ctx->fontImages[ctx->fontImageIdx], &iw, &ih);
2256 		if (iw > ih)
2257 			ih *= 2;
2258 		else
2259 			iw *= 2;
2260 		if (iw > NVG_MAX_FONTIMAGE_SIZE || ih > NVG_MAX_FONTIMAGE_SIZE)
2261 			iw = ih = NVG_MAX_FONTIMAGE_SIZE;
2262 		ctx->fontImages[ctx->fontImageIdx+1] = ctx->params.renderCreateTexture(ctx->params.userPtr, NVG_TEXTURE_ALPHA, iw, ih, 0, NULL);
2263 	}
2264 	++ctx->fontImageIdx;
2265 	fonsResetAtlas(ctx->fs, iw, ih);
2266 	return 1;
2267 }
2268 
nvg__renderText(NVGcontext * ctx,NVGvertex * verts,int nverts)2269 static void nvg__renderText(NVGcontext* ctx, NVGvertex* verts, int nverts)
2270 {
2271 	NVGstate* state = nvg__getState(ctx);
2272 	NVGpaint paint = state->fill;
2273 
2274 	// Render triangles.
2275 	paint.image = ctx->fontImages[ctx->fontImageIdx];
2276 
2277 	// Apply global alpha
2278 	paint.innerColor.a *= state->alpha;
2279 	paint.outerColor.a *= state->alpha;
2280 
2281 	ctx->params.renderTriangles(ctx->params.userPtr, &paint, &state->scissor, verts, nverts);
2282 
2283 	ctx->drawCallCount++;
2284 	ctx->textTriCount += nverts/3;
2285 }
2286 
nvgText(NVGcontext * ctx,float x,float y,const char * string,const char * end)2287 float nvgText(NVGcontext* ctx, float x, float y, const char* string, const char* end)
2288 {
2289 	NVGstate* state = nvg__getState(ctx);
2290 	FONStextIter iter, prevIter;
2291 	FONSquad q;
2292 	NVGvertex* verts;
2293 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2294 	float invscale = 1.0f / scale;
2295 	int cverts = 0;
2296 	int nverts = 0;
2297 
2298 	if (end == NULL)
2299 		end = string + strlen(string);
2300 
2301 	if (state->fontId == FONS_INVALID) return x;
2302 
2303 	fonsSetSize(ctx->fs, state->fontSize*scale);
2304 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2305 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2306 	fonsSetAlign(ctx->fs, state->textAlign);
2307 	fonsSetFont(ctx->fs, state->fontId);
2308 
2309 	cverts = nvg__maxi(2, (int)(end - string)) * 6; // conservative estimate.
2310 	verts = nvg__allocTempVerts(ctx, cverts);
2311 	if (verts == NULL) return x;
2312 
2313 	fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end);
2314 	prevIter = iter;
2315 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2316 		float c[4*2];
2317 		if (iter.prevGlyphIndex == -1) { // can not retrieve glyph?
2318 			if (!nvg__allocTextAtlas(ctx))
2319 				break; // no memory :(
2320 			if (nverts != 0) {
2321 				nvg__renderText(ctx, verts, nverts);
2322 				nverts = 0;
2323 			}
2324 			iter = prevIter;
2325 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2326 			if (iter.prevGlyphIndex == -1) // still can not find glyph?
2327 				break;
2328 		}
2329 		prevIter = iter;
2330 		// Transform corners.
2331 		nvgTransformPoint(&c[0],&c[1], state->xform, q.x0*invscale, q.y0*invscale);
2332 		nvgTransformPoint(&c[2],&c[3], state->xform, q.x1*invscale, q.y0*invscale);
2333 		nvgTransformPoint(&c[4],&c[5], state->xform, q.x1*invscale, q.y1*invscale);
2334 		nvgTransformPoint(&c[6],&c[7], state->xform, q.x0*invscale, q.y1*invscale);
2335 		// Create triangles
2336 		if (nverts+6 <= cverts) {
2337 			nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
2338 			nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
2339 			nvg__vset(&verts[nverts], c[2], c[3], q.s1, q.t0); nverts++;
2340 			nvg__vset(&verts[nverts], c[0], c[1], q.s0, q.t0); nverts++;
2341 			nvg__vset(&verts[nverts], c[6], c[7], q.s0, q.t1); nverts++;
2342 			nvg__vset(&verts[nverts], c[4], c[5], q.s1, q.t1); nverts++;
2343 		}
2344 	}
2345 
2346 	// TODO: add back-end bit to do this just once per frame.
2347 	nvg__flushTextTexture(ctx);
2348 
2349 	nvg__renderText(ctx, verts, nverts);
2350 
2351 	return iter.x;
2352 }
2353 
nvgTextBox(NVGcontext * ctx,float x,float y,float breakRowWidth,const char * string,const char * end)2354 void nvgTextBox(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end)
2355 {
2356 	NVGstate* state = nvg__getState(ctx);
2357 	NVGtextRow rows[2];
2358 	int nrows = 0, i;
2359 	int oldAlign = state->textAlign;
2360 	int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
2361 	int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
2362 	float lineh = 0;
2363 
2364 	if (state->fontId == FONS_INVALID) return;
2365 
2366 	nvgTextMetrics(ctx, NULL, NULL, &lineh);
2367 
2368 	state->textAlign = NVG_ALIGN_LEFT | valign;
2369 
2370 	while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
2371 		for (i = 0; i < nrows; i++) {
2372 			NVGtextRow* row = &rows[i];
2373 			if (haling & NVG_ALIGN_LEFT)
2374 				nvgText(ctx, x, y, row->start, row->end);
2375 			else if (haling & NVG_ALIGN_CENTER)
2376 				nvgText(ctx, x + breakRowWidth*0.5f - row->width*0.5f, y, row->start, row->end);
2377 			else if (haling & NVG_ALIGN_RIGHT)
2378 				nvgText(ctx, x + breakRowWidth - row->width, y, row->start, row->end);
2379 			y += lineh * state->lineHeight;
2380 		}
2381 		string = rows[nrows-1].next;
2382 	}
2383 
2384 	state->textAlign = oldAlign;
2385 }
2386 
nvgTextGlyphPositions(NVGcontext * ctx,float x,float y,const char * string,const char * end,NVGglyphPosition * positions,int maxPositions)2387 int nvgTextGlyphPositions(NVGcontext* ctx, float x, float y, const char* string, const char* end, NVGglyphPosition* positions, int maxPositions)
2388 {
2389 	NVGstate* state = nvg__getState(ctx);
2390 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2391 	float invscale = 1.0f / scale;
2392 	FONStextIter iter, prevIter;
2393 	FONSquad q;
2394 	int npos = 0;
2395 
2396 	if (state->fontId == FONS_INVALID) return 0;
2397 
2398 	if (end == NULL)
2399 		end = string + strlen(string);
2400 
2401 	if (string == end)
2402 		return 0;
2403 
2404 	fonsSetSize(ctx->fs, state->fontSize*scale);
2405 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2406 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2407 	fonsSetAlign(ctx->fs, state->textAlign);
2408 	fonsSetFont(ctx->fs, state->fontId);
2409 
2410 	fonsTextIterInit(ctx->fs, &iter, x*scale, y*scale, string, end);
2411 	prevIter = iter;
2412 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2413 		if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
2414 			iter = prevIter;
2415 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2416 		}
2417 		prevIter = iter;
2418 		positions[npos].str = iter.str;
2419 		positions[npos].x = iter.x * invscale;
2420 		positions[npos].minx = nvg__minf(iter.x, q.x0) * invscale;
2421 		positions[npos].maxx = nvg__maxf(iter.nextx, q.x1) * invscale;
2422 		npos++;
2423 		if (npos >= maxPositions)
2424 			break;
2425 	}
2426 
2427 	return npos;
2428 }
2429 
2430 enum NVGcodepointType {
2431 	NVG_SPACE,
2432 	NVG_NEWLINE,
2433 	NVG_CHAR,
2434 };
2435 
nvgTextBreakLines(NVGcontext * ctx,const char * string,const char * end,float breakRowWidth,NVGtextRow * rows,int maxRows)2436 int nvgTextBreakLines(NVGcontext* ctx, const char* string, const char* end, float breakRowWidth, NVGtextRow* rows, int maxRows)
2437 {
2438 	NVGstate* state = nvg__getState(ctx);
2439 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2440 	float invscale = 1.0f / scale;
2441 	FONStextIter iter, prevIter;
2442 	FONSquad q;
2443 	int nrows = 0;
2444 	float rowStartX = 0;
2445 	float rowWidth = 0;
2446 	float rowMinX = 0;
2447 	float rowMaxX = 0;
2448 	const char* rowStart = NULL;
2449 	const char* rowEnd = NULL;
2450 	const char* wordStart = NULL;
2451 	float wordStartX = 0;
2452 	float wordMinX = 0;
2453 	const char* breakEnd = NULL;
2454 	float breakWidth = 0;
2455 	float breakMaxX = 0;
2456 	int type = NVG_SPACE, ptype = NVG_SPACE;
2457 	unsigned int pcodepoint = 0;
2458 
2459 	if (maxRows == 0) return 0;
2460 	if (state->fontId == FONS_INVALID) return 0;
2461 
2462 	if (end == NULL)
2463 		end = string + strlen(string);
2464 
2465 	if (string == end) return 0;
2466 
2467 	fonsSetSize(ctx->fs, state->fontSize*scale);
2468 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2469 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2470 	fonsSetAlign(ctx->fs, state->textAlign);
2471 	fonsSetFont(ctx->fs, state->fontId);
2472 
2473 	breakRowWidth *= scale;
2474 
2475 	fonsTextIterInit(ctx->fs, &iter, 0, 0, string, end);
2476 	prevIter = iter;
2477 	while (fonsTextIterNext(ctx->fs, &iter, &q)) {
2478 		if (iter.prevGlyphIndex < 0 && nvg__allocTextAtlas(ctx)) { // can not retrieve glyph?
2479 			iter = prevIter;
2480 			fonsTextIterNext(ctx->fs, &iter, &q); // try again
2481 		}
2482 		prevIter = iter;
2483 		switch (iter.codepoint) {
2484 			case 9:			// \t
2485 			case 11:		// \v
2486 			case 12:		// \f
2487 			case 32:		// space
2488 			case 0x00a0:	// NBSP
2489 				type = NVG_SPACE;
2490 				break;
2491 			case 10:		// \n
2492 				type = pcodepoint == 13 ? NVG_SPACE : NVG_NEWLINE;
2493 				break;
2494 			case 13:		// \r
2495 				type = pcodepoint == 10 ? NVG_SPACE : NVG_NEWLINE;
2496 				break;
2497 			case 0x0085:	// NEL
2498 				type = NVG_NEWLINE;
2499 				break;
2500 			default:
2501 				type = NVG_CHAR;
2502 				break;
2503 		}
2504 
2505 		if (type == NVG_NEWLINE) {
2506 			// Always handle new lines.
2507 			rows[nrows].start = rowStart != NULL ? rowStart : iter.str;
2508 			rows[nrows].end = rowEnd != NULL ? rowEnd : iter.str;
2509 			rows[nrows].width = rowWidth * invscale;
2510 			rows[nrows].minx = rowMinX * invscale;
2511 			rows[nrows].maxx = rowMaxX * invscale;
2512 			rows[nrows].next = iter.next;
2513 			nrows++;
2514 			if (nrows >= maxRows)
2515 				return nrows;
2516 			// Set null break point
2517 			breakEnd = rowStart;
2518 			breakWidth = 0.0;
2519 			breakMaxX = 0.0;
2520 			// Indicate to skip the white space at the beginning of the row.
2521 			rowStart = NULL;
2522 			rowEnd = NULL;
2523 			rowWidth = 0;
2524 			rowMinX = rowMaxX = 0;
2525 		} else {
2526 			if (rowStart == NULL) {
2527 				// Skip white space until the beginning of the line
2528 				if (type == NVG_CHAR) {
2529 					// The current char is the row so far
2530 					rowStartX = iter.x;
2531 					rowStart = iter.str;
2532 					rowEnd = iter.next;
2533 					rowWidth = iter.nextx - rowStartX; // q.x1 - rowStartX;
2534 					rowMinX = q.x0 - rowStartX;
2535 					rowMaxX = q.x1 - rowStartX;
2536 					wordStart = iter.str;
2537 					wordStartX = iter.x;
2538 					wordMinX = q.x0 - rowStartX;
2539 					// Set null break point
2540 					breakEnd = rowStart;
2541 					breakWidth = 0.0;
2542 					breakMaxX = 0.0;
2543 				}
2544 			} else {
2545 				float nextWidth = iter.nextx - rowStartX;
2546 
2547 				// track last non-white space character
2548 				if (type == NVG_CHAR) {
2549 					rowEnd = iter.next;
2550 					rowWidth = iter.nextx - rowStartX;
2551 					rowMaxX = q.x1 - rowStartX;
2552 				}
2553 				// track last end of a word
2554 				if (ptype == NVG_CHAR && type == NVG_SPACE) {
2555 					breakEnd = iter.str;
2556 					breakWidth = rowWidth;
2557 					breakMaxX = rowMaxX;
2558 				}
2559 				// track last beginning of a word
2560 				if (ptype == NVG_SPACE && type == NVG_CHAR) {
2561 					wordStart = iter.str;
2562 					wordStartX = iter.x;
2563 					wordMinX = q.x0 - rowStartX;
2564 				}
2565 
2566 				// Break to new line when a character is beyond break width.
2567 				if (type == NVG_CHAR && nextWidth > breakRowWidth) {
2568 					// The run length is too long, need to break to new line.
2569 					if (breakEnd == rowStart) {
2570 						// The current word is longer than the row length, just break it from here.
2571 						rows[nrows].start = rowStart;
2572 						rows[nrows].end = iter.str;
2573 						rows[nrows].width = rowWidth * invscale;
2574 						rows[nrows].minx = rowMinX * invscale;
2575 						rows[nrows].maxx = rowMaxX * invscale;
2576 						rows[nrows].next = iter.str;
2577 						nrows++;
2578 						if (nrows >= maxRows)
2579 							return nrows;
2580 						rowStartX = iter.x;
2581 						rowStart = iter.str;
2582 						rowEnd = iter.next;
2583 						rowWidth = iter.nextx - rowStartX;
2584 						rowMinX = q.x0 - rowStartX;
2585 						rowMaxX = q.x1 - rowStartX;
2586 						wordStart = iter.str;
2587 						wordStartX = iter.x;
2588 						wordMinX = q.x0 - rowStartX;
2589 					} else {
2590 						// Break the line from the end of the last word, and start new line from the beginning of the new.
2591 						rows[nrows].start = rowStart;
2592 						rows[nrows].end = breakEnd;
2593 						rows[nrows].width = breakWidth * invscale;
2594 						rows[nrows].minx = rowMinX * invscale;
2595 						rows[nrows].maxx = breakMaxX * invscale;
2596 						rows[nrows].next = wordStart;
2597 						nrows++;
2598 						if (nrows >= maxRows)
2599 							return nrows;
2600 						rowStartX = wordStartX;
2601 						rowStart = wordStart;
2602 						rowEnd = iter.next;
2603 						rowWidth = iter.nextx - rowStartX;
2604 						rowMinX = wordMinX;
2605 						rowMaxX = q.x1 - rowStartX;
2606 						// No change to the word start
2607 					}
2608 					// Set null break point
2609 					breakEnd = rowStart;
2610 					breakWidth = 0.0;
2611 					breakMaxX = 0.0;
2612 				}
2613 			}
2614 		}
2615 
2616 		pcodepoint = iter.codepoint;
2617 		ptype = type;
2618 	}
2619 
2620 	// Break the line from the end of the last word, and start new line from the beginning of the new.
2621 	if (rowStart != NULL) {
2622 		rows[nrows].start = rowStart;
2623 		rows[nrows].end = rowEnd;
2624 		rows[nrows].width = rowWidth * invscale;
2625 		rows[nrows].minx = rowMinX * invscale;
2626 		rows[nrows].maxx = rowMaxX * invscale;
2627 		rows[nrows].next = end;
2628 		nrows++;
2629 	}
2630 
2631 	return nrows;
2632 }
2633 
nvgTextBounds(NVGcontext * ctx,float x,float y,const char * string,const char * end,float * bounds)2634 float nvgTextBounds(NVGcontext* ctx, float x, float y, const char* string, const char* end, float* bounds)
2635 {
2636 	NVGstate* state = nvg__getState(ctx);
2637 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2638 	float invscale = 1.0f / scale;
2639 	float width;
2640 
2641 	if (state->fontId == FONS_INVALID) return 0;
2642 
2643 	fonsSetSize(ctx->fs, state->fontSize*scale);
2644 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2645 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2646 	fonsSetAlign(ctx->fs, state->textAlign);
2647 	fonsSetFont(ctx->fs, state->fontId);
2648 
2649 	width = fonsTextBounds(ctx->fs, x*scale, y*scale, string, end, bounds);
2650 	if (bounds != NULL) {
2651 		// Use line bounds for height.
2652 		fonsLineBounds(ctx->fs, y*scale, &bounds[1], &bounds[3]);
2653 		bounds[0] *= invscale;
2654 		bounds[1] *= invscale;
2655 		bounds[2] *= invscale;
2656 		bounds[3] *= invscale;
2657 	}
2658 	return width * invscale;
2659 }
2660 
nvgTextBoxBounds(NVGcontext * ctx,float x,float y,float breakRowWidth,const char * string,const char * end,float * bounds)2661 void nvgTextBoxBounds(NVGcontext* ctx, float x, float y, float breakRowWidth, const char* string, const char* end, float* bounds)
2662 {
2663 	NVGstate* state = nvg__getState(ctx);
2664 	NVGtextRow rows[2];
2665 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2666 	float invscale = 1.0f / scale;
2667 	int nrows = 0, i;
2668 	int oldAlign = state->textAlign;
2669 	int haling = state->textAlign & (NVG_ALIGN_LEFT | NVG_ALIGN_CENTER | NVG_ALIGN_RIGHT);
2670 	int valign = state->textAlign & (NVG_ALIGN_TOP | NVG_ALIGN_MIDDLE | NVG_ALIGN_BOTTOM | NVG_ALIGN_BASELINE);
2671 	float lineh = 0, rminy = 0, rmaxy = 0;
2672 	float minx, miny, maxx, maxy;
2673 
2674 	if (state->fontId == FONS_INVALID) {
2675 		if (bounds != NULL)
2676 			bounds[0] = bounds[1] = bounds[2] = bounds[3] = 0.0f;
2677 		return;
2678 	}
2679 
2680 	nvgTextMetrics(ctx, NULL, NULL, &lineh);
2681 
2682 	state->textAlign = NVG_ALIGN_LEFT | valign;
2683 
2684 	minx = maxx = x;
2685 	miny = maxy = y;
2686 
2687 	fonsSetSize(ctx->fs, state->fontSize*scale);
2688 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2689 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2690 	fonsSetAlign(ctx->fs, state->textAlign);
2691 	fonsSetFont(ctx->fs, state->fontId);
2692 	fonsLineBounds(ctx->fs, 0, &rminy, &rmaxy);
2693 	rminy *= invscale;
2694 	rmaxy *= invscale;
2695 
2696 	while ((nrows = nvgTextBreakLines(ctx, string, end, breakRowWidth, rows, 2))) {
2697 		for (i = 0; i < nrows; i++) {
2698 			NVGtextRow* row = &rows[i];
2699 			float rminx, rmaxx, dx = 0;
2700 			// Horizontal bounds
2701 			if (haling & NVG_ALIGN_LEFT)
2702 				dx = 0;
2703 			else if (haling & NVG_ALIGN_CENTER)
2704 				dx = breakRowWidth*0.5f - row->width*0.5f;
2705 			else if (haling & NVG_ALIGN_RIGHT)
2706 				dx = breakRowWidth - row->width;
2707 			rminx = x + row->minx + dx;
2708 			rmaxx = x + row->maxx + dx;
2709 			minx = nvg__minf(minx, rminx);
2710 			maxx = nvg__maxf(maxx, rmaxx);
2711 			// Vertical bounds.
2712 			miny = nvg__minf(miny, y + rminy);
2713 			maxy = nvg__maxf(maxy, y + rmaxy);
2714 
2715 			y += lineh * state->lineHeight;
2716 		}
2717 		string = rows[nrows-1].next;
2718 	}
2719 
2720 	state->textAlign = oldAlign;
2721 
2722 	if (bounds != NULL) {
2723 		bounds[0] = minx;
2724 		bounds[1] = miny;
2725 		bounds[2] = maxx;
2726 		bounds[3] = maxy;
2727 	}
2728 }
2729 
nvgTextMetrics(NVGcontext * ctx,float * ascender,float * descender,float * lineh)2730 void nvgTextMetrics(NVGcontext* ctx, float* ascender, float* descender, float* lineh)
2731 {
2732 	NVGstate* state = nvg__getState(ctx);
2733 	float scale = nvg__getFontScale(state) * ctx->devicePxRatio;
2734 	float invscale = 1.0f / scale;
2735 
2736 	if (state->fontId == FONS_INVALID) return;
2737 
2738 	fonsSetSize(ctx->fs, state->fontSize*scale);
2739 	fonsSetSpacing(ctx->fs, state->letterSpacing*scale);
2740 	fonsSetBlur(ctx->fs, state->fontBlur*scale);
2741 	fonsSetAlign(ctx->fs, state->textAlign);
2742 	fonsSetFont(ctx->fs, state->fontId);
2743 
2744 	fonsVertMetrics(ctx->fs, ascender, descender, lineh);
2745 	if (ascender != NULL)
2746 		*ascender *= invscale;
2747 	if (descender != NULL)
2748 		*descender *= invscale;
2749 	if (lineh != NULL)
2750 		*lineh *= invscale;
2751 }
2752 // vim: ft=c nu noet ts=4
2753