You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2875 lines
74KB

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