@geastack/engine 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1702 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #pragma once
3
+
4
+ // Inline SVG geometry: everything that turns SVG source text into pixels,
5
+ // with no dependency on the node tree. The engine's <svg> element
6
+ // (svg_element.h) resolves attributes and CSS into calls on this header; the
7
+ // unit tests drive it directly.
8
+ //
9
+ // parse -- path data (M L H V C S Q T A Z, absolute and relative), point
10
+ // lists, transform lists, colours, lengths.
11
+ // flatten -- curves and elliptical arcs become line segments, in device
12
+ // space, to a fixed pixel tolerance.
13
+ // stroke -- a polyline becomes filled polygons (segment quads, joins, caps)
14
+ // that all wind the same way, so a nonzero fill is their union.
15
+ // raster -- exact-area anti-aliased coverage (signed-area accumulation),
16
+ // strip by strip, emitted one coverage row at a time.
17
+
18
+ #include <algorithm>
19
+ #include <cctype>
20
+ #include <cmath>
21
+ #include <cstdint>
22
+ #include <cstdlib>
23
+ #include <cstring>
24
+ #include <string>
25
+ #include <memory>
26
+ #include <new>
27
+ #include <vector>
28
+
29
+ #if defined(ESP_PLATFORM)
30
+ #include <esp_attr.h>
31
+ #include <esp_heap_caps.h>
32
+ #include <esp_memory_utils.h>
33
+ #define GEA_SVG_HOT IRAM_ATTR
34
+ #else
35
+ #define GEA_SVG_HOT
36
+ #endif
37
+
38
+ namespace gea::embedded::ui::svg {
39
+
40
+ // Scratch the rasterizer touches per pixel lives in internal RAM on ESP32: a
41
+ // PSRAM accumulator costs a cache miss per touch and doubles paint time.
42
+ template <typename T>
43
+ struct InternalAllocator {
44
+ using value_type = T;
45
+ InternalAllocator() = default;
46
+ template <typename U>
47
+ InternalAllocator(const InternalAllocator<U> &) {}
48
+ T *allocate(std::size_t n)
49
+ {
50
+ #if defined(ESP_PLATFORM)
51
+ if (void *p = heap_caps_malloc(n * sizeof(T), MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)) return static_cast<T *>(p);
52
+ if (void *p = heap_caps_malloc(n * sizeof(T), MALLOC_CAP_8BIT)) return static_cast<T *>(p);
53
+ throw std::bad_alloc();
54
+ #else
55
+ return std::allocator<T>{}.allocate(n);
56
+ #endif
57
+ }
58
+ void deallocate(T *p, std::size_t n)
59
+ {
60
+ #if defined(ESP_PLATFORM)
61
+ (void)n;
62
+ heap_caps_free(p);
63
+ #else
64
+ std::allocator<T>{}.deallocate(p, n);
65
+ #endif
66
+ }
67
+ template <typename U>
68
+ bool operator==(const InternalAllocator<U> &) const { return true; }
69
+ template <typename U>
70
+ bool operator!=(const InternalAllocator<U> &) const { return false; }
71
+ };
72
+ template <typename T>
73
+ using ScratchVector = std::vector<T, InternalAllocator<T>>;
74
+
75
+ // Data read in order, a few times per paint (a shape's edge list), goes to
76
+ // PSRAM on ESP32: the cache serves sequential reads well, and internal RAM is
77
+ // left to the accumulators, which are touched at random once per cell.
78
+ template <typename T>
79
+ struct ExternalAllocator {
80
+ using value_type = T;
81
+ ExternalAllocator() = default;
82
+ template <typename U>
83
+ ExternalAllocator(const ExternalAllocator<U> &) {}
84
+ T *allocate(std::size_t n)
85
+ {
86
+ #if defined(ESP_PLATFORM)
87
+ if (void *p = heap_caps_malloc(n * sizeof(T), MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)) return static_cast<T *>(p);
88
+ if (void *p = heap_caps_malloc(n * sizeof(T), MALLOC_CAP_8BIT)) return static_cast<T *>(p);
89
+ throw std::bad_alloc();
90
+ #else
91
+ return std::allocator<T>{}.allocate(n);
92
+ #endif
93
+ }
94
+ void deallocate(T *p, std::size_t n)
95
+ {
96
+ #if defined(ESP_PLATFORM)
97
+ (void)n;
98
+ heap_caps_free(p);
99
+ #else
100
+ std::allocator<T>{}.deallocate(p, n);
101
+ #endif
102
+ }
103
+ template <typename U>
104
+ bool operator==(const ExternalAllocator<U> &) const { return true; }
105
+ template <typename U>
106
+ bool operator!=(const ExternalAllocator<U> &) const { return false; }
107
+ };
108
+
109
+ // Grows a zero-filled scratch vector to `need` elements, keeping it in
110
+ // internal RAM. The allocator falls back to PSRAM when internal RAM is short
111
+ // at that moment (during boot, say), and a vector never moves on its own, so
112
+ // one that landed outside retries now and then and moves back in once a block
113
+ // is free. Capacity is reserved up front so the usual sizes never reallocate.
114
+ template <typename V>
115
+ inline void growInternalZeroed(V &v, std::size_t need, std::size_t reserve, int &retry)
116
+ {
117
+ #if defined(ESP_PLATFORM)
118
+ const bool inside = v.capacity() == 0 || esp_ptr_internal(v.data());
119
+ if (v.size() >= need && (inside || (++retry & 63) != 0)) return;
120
+ V fresh;
121
+ fresh.reserve(std::max(need, reserve));
122
+ if (v.size() >= need && !esp_ptr_internal(fresh.data())) return; // no better block yet
123
+ fresh.resize(std::max(need, v.size()), 0);
124
+ v.swap(fresh);
125
+ #else
126
+ (void)reserve;
127
+ (void)retry;
128
+ if (v.size() < need) v.resize(need, 0);
129
+ #endif
130
+ }
131
+
132
+ struct Point {
133
+ float x = 0.0f;
134
+ float y = 0.0f;
135
+ };
136
+
137
+ // Affine transform [a c e; b d f; 0 0 1], the SVG matrix(a b c d e f) order.
138
+ struct Matrix {
139
+ float a = 1.0f, b = 0.0f, c = 0.0f, d = 1.0f, e = 0.0f, f = 0.0f;
140
+
141
+ Point apply(Point p) const { return {a * p.x + c * p.y + e, b * p.x + d * p.y + f}; }
142
+ // this * other: `other` applies first.
143
+ Matrix operator*(const Matrix &o) const
144
+ {
145
+ return {a * o.a + c * o.b, b * o.a + d * o.b, a * o.c + c * o.d, b * o.c + d * o.d, a * o.e + c * o.f + e,
146
+ b * o.e + d * o.f + f};
147
+ }
148
+ // Geometric-mean scale: how much a unit length grows (stroke widths).
149
+ float scale() const { return std::sqrt(std::fabs(a * d - b * c)); }
150
+ static Matrix translate(float x, float y) { return {1, 0, 0, 1, x, y}; }
151
+ static Matrix scaling(float x, float y) { return {x, 0, 0, y, 0, 0}; }
152
+ static Matrix rotate(float degrees)
153
+ {
154
+ const float r = degrees * 3.14159265358979f / 180.0f;
155
+ const float cs = std::cos(r), sn = std::sin(r);
156
+ return {cs, sn, -sn, cs, 0, 0};
157
+ }
158
+ };
159
+
160
+ using Contour = std::vector<Point>;
161
+
162
+ // A flattened path: contours of device-space points, each open or closed.
163
+ struct Path {
164
+ std::vector<Contour> contours;
165
+ std::vector<std::uint8_t> closed;
166
+ bool empty() const { return contours.empty(); }
167
+ void clear() { contours.clear(); closed.clear(); }
168
+ };
169
+
170
+ // ---------------------------------------------------------------------------
171
+ // Number scanning (SVG number grammar: 1e-3, .5.5, -1-2, flags without commas)
172
+
173
+ class Scanner {
174
+ public:
175
+ explicit Scanner(const char *s) : p_(s ? s : "") {}
176
+
177
+ void skipSeparators()
178
+ {
179
+ while (*p_ && (std::isspace(static_cast<unsigned char>(*p_)) || *p_ == ',')) ++p_;
180
+ }
181
+ void skipSpaces()
182
+ {
183
+ while (*p_ && std::isspace(static_cast<unsigned char>(*p_))) ++p_;
184
+ }
185
+ bool atEnd()
186
+ {
187
+ skipSeparators();
188
+ return *p_ == '\0';
189
+ }
190
+ char peek()
191
+ {
192
+ skipSeparators();
193
+ return *p_;
194
+ }
195
+ bool startsNumber()
196
+ {
197
+ skipSeparators();
198
+ const char c = *p_;
199
+ return (c >= '0' && c <= '9') || c == '-' || c == '+' || c == '.';
200
+ }
201
+ bool number(float &out)
202
+ {
203
+ skipSeparators();
204
+ const char *start = p_;
205
+ const char *q = p_;
206
+ if (*q == '+' || *q == '-') ++q;
207
+ bool digits = false;
208
+ while (*q >= '0' && *q <= '9') { ++q; digits = true; }
209
+ if (*q == '.') {
210
+ ++q;
211
+ while (*q >= '0' && *q <= '9') { ++q; digits = true; }
212
+ }
213
+ if (!digits) return false;
214
+ bool exponent = false;
215
+ if (*q == 'e' || *q == 'E') {
216
+ const char *r = q + 1;
217
+ if (*r == '+' || *r == '-') ++r;
218
+ if (*r >= '0' && *r <= '9') {
219
+ while (*r >= '0' && *r <= '9') ++r;
220
+ q = r;
221
+ exponent = true;
222
+ }
223
+ }
224
+ out = exponent ? slowNumber(start, q) : fastNumber(start, q);
225
+ p_ = q;
226
+ return true;
227
+ }
228
+ // Arc flags are a single 0/1 digit and may run into the next number.
229
+ bool flag(bool &out)
230
+ {
231
+ skipSeparators();
232
+ if (*p_ == '0' || *p_ == '1') {
233
+ out = *p_ == '1';
234
+ ++p_;
235
+ return true;
236
+ }
237
+ return false;
238
+ }
239
+ char take() { return *p_ ? *p_++ : '\0'; }
240
+ const char *rest() const { return p_; }
241
+ void advance(std::size_t n) { while (n-- && *p_) ++p_; }
242
+
243
+ private:
244
+ // Path data is re-parsed on every attribute change, so a number must not
245
+ // cost a heap string and a software-double strtod (soft-float on ESP32).
246
+ // Digits accumulate into an integer: a whole number converts straight to
247
+ // float, and a decimal whose digits fit float's 24-bit mantissa is one
248
+ // IEEE float division by an exact power of ten (correctly rounded, like
249
+ // strtod-then-narrow). Anything wider takes the strtod path.
250
+ static float fastNumber(const char *s, const char *end)
251
+ {
252
+ static constexpr float pow10[] = {1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f, 1e7f, 1e8f, 1e9f, 1e10f};
253
+ const char *q = s;
254
+ const bool negative = *q == '-';
255
+ if (*q == '+' || *q == '-') ++q;
256
+ std::uint32_t mantissa = 0;
257
+ int fraction = -1;
258
+ for (; q < end; ++q) {
259
+ if (*q == '.') {
260
+ fraction = 0;
261
+ continue;
262
+ }
263
+ if (mantissa > (1u << 24) / 10) return slowNumber(s, end);
264
+ mantissa = mantissa * 10 + static_cast<std::uint32_t>(*q - '0');
265
+ if (fraction >= 0 && ++fraction > 10) return slowNumber(s, end);
266
+ }
267
+ if (mantissa > (1u << 24)) return slowNumber(s, end);
268
+ float v = static_cast<float>(mantissa);
269
+ if (fraction > 0) v /= pow10[fraction];
270
+ return negative ? -v : v;
271
+ }
272
+ static float slowNumber(const char *s, const char *end)
273
+ {
274
+ char buf[64];
275
+ std::size_t n = static_cast<std::size_t>(end - s);
276
+ if (n >= sizeof buf) n = sizeof buf - 1;
277
+ std::memcpy(buf, s, n);
278
+ buf[n] = '\0';
279
+ return static_cast<float>(std::strtod(buf, nullptr));
280
+ }
281
+
282
+ const char *p_;
283
+ };
284
+
285
+ // A length in user units: "12", "12px", "1.5e1". Percentages and other units
286
+ // are refused (returns false) so the caller keeps its fallback.
287
+ inline bool parseLength(const char *s, float &out)
288
+ {
289
+ if (!s) return false;
290
+ Scanner sc(s);
291
+ float v = 0;
292
+ if (!sc.number(v)) return false;
293
+ sc.skipSpaces();
294
+ const char *rest = sc.rest();
295
+ if (*rest == '\0' || std::strncmp(rest, "px", 2) == 0) {
296
+ out = v;
297
+ return true;
298
+ }
299
+ return false;
300
+ }
301
+
302
+ inline bool parseNumberList(const char *s, float *out, int count)
303
+ {
304
+ Scanner sc(s);
305
+ for (int i = 0; i < count; ++i)
306
+ if (!sc.number(out[i])) return false;
307
+ return true;
308
+ }
309
+
310
+ // ---------------------------------------------------------------------------
311
+ // Colours
312
+
313
+ struct Color {
314
+ std::uint8_t r = 0, g = 0, b = 0, a = 255;
315
+ };
316
+
317
+ enum class PaintKind : std::uint8_t { Unset, None, CurrentColor, Color };
318
+
319
+ struct Paint {
320
+ PaintKind kind = PaintKind::Unset;
321
+ Color color;
322
+ };
323
+
324
+ namespace detail {
325
+ inline int hexDigit(char c)
326
+ {
327
+ if (c >= '0' && c <= '9') return c - '0';
328
+ if (c >= 'a' && c <= 'f') return c - 'a' + 10;
329
+ if (c >= 'A' && c <= 'F') return c - 'A' + 10;
330
+ return -1;
331
+ }
332
+
333
+ inline bool iequalsPrefix(const char *s, const char *word)
334
+ {
335
+ for (; *word; ++s, ++word)
336
+ if (std::tolower(static_cast<unsigned char>(*s)) != *word) return false;
337
+ return true;
338
+ }
339
+
340
+ inline float hueToRgb(float p, float q, float t)
341
+ {
342
+ if (t < 0) t += 1;
343
+ if (t > 1) t -= 1;
344
+ if (t < 1.0f / 6) return p + (q - p) * 6 * t;
345
+ if (t < 0.5f) return q;
346
+ if (t < 2.0f / 3) return p + (q - p) * (2.0f / 3 - t) * 6;
347
+ return p;
348
+ }
349
+
350
+ struct NamedColor {
351
+ const char *name;
352
+ std::uint32_t rgb;
353
+ };
354
+
355
+ // The CSS colour keywords charts and meters actually use.
356
+ inline constexpr NamedColor kNamedColors[] = {
357
+ {"black", 0x000000}, {"white", 0xffffff}, {"red", 0xff0000}, {"green", 0x008000},
358
+ {"blue", 0x0000ff}, {"yellow", 0xffff00}, {"orange", 0xffa500}, {"purple", 0x800080},
359
+ {"gray", 0x808080}, {"grey", 0x808080}, {"silver", 0xc0c0c0}, {"lime", 0x00ff00},
360
+ {"aqua", 0x00ffff}, {"cyan", 0x00ffff}, {"magenta", 0xff00ff}, {"fuchsia", 0xff00ff},
361
+ {"navy", 0x000080}, {"teal", 0x008080}, {"maroon", 0x800000}, {"olive", 0x808000},
362
+ {"pink", 0xffc0cb}, {"brown", 0xa52a2a}, {"gold", 0xffd700}, {"indigo", 0x4b0082},
363
+ {"violet", 0xee82ee}, {"crimson", 0xdc143c}, {"coral", 0xff7f50}, {"tomato", 0xff6347},
364
+ {"salmon", 0xfa8072}, {"skyblue", 0x87ceeb}, {"steelblue", 0x4682b4}, {"darkgray", 0xa9a9a9},
365
+ {"darkgrey", 0xa9a9a9}, {"lightgray", 0xd3d3d3}, {"lightgrey", 0xd3d3d3}, {"dimgray", 0x696969},
366
+ {"dimgrey", 0x696969}, {"darkblue", 0x00008b}, {"darkgreen", 0x006400}, {"darkred", 0x8b0000},
367
+ {"orangered", 0xff4500}, {"limegreen", 0x32cd32}, {"dodgerblue", 0x1e90ff}, {"deepskyblue", 0x00bfff},
368
+ {"slategray", 0x708090}, {"slategrey", 0x708090}, {"whitesmoke", 0xf5f5f5}, {"turquoise", 0x40e0d0},
369
+ {"tan", 0xd2b48c}, {"khaki", 0xf0e68c}, {"plum", 0xdda0dd}, {"orchid", 0xda70d6},
370
+ };
371
+ } // namespace detail
372
+
373
+ // Parses a CSS colour: #rgb #rgba #rrggbb #rrggbbaa, rgb()/rgba() (numbers or
374
+ // percentages, comma or space syntax, `/ alpha`), hsl()/hsla(), the keywords
375
+ // above and `transparent`.
376
+ inline bool parseColor(const char *s, Color &out)
377
+ {
378
+ if (!s) return false;
379
+ while (*s && std::isspace(static_cast<unsigned char>(*s))) ++s;
380
+ if (*s == '#') {
381
+ ++s;
382
+ int digits[8];
383
+ int n = 0;
384
+ while (n < 8 && detail::hexDigit(s[n]) >= 0) {
385
+ digits[n] = detail::hexDigit(s[n]);
386
+ ++n;
387
+ }
388
+ if (detail::hexDigit(s[n]) >= 0) return false;
389
+ if (n == 3 || n == 4) {
390
+ out.r = static_cast<std::uint8_t>(digits[0] * 17);
391
+ out.g = static_cast<std::uint8_t>(digits[1] * 17);
392
+ out.b = static_cast<std::uint8_t>(digits[2] * 17);
393
+ out.a = static_cast<std::uint8_t>(n == 4 ? digits[3] * 17 : 255);
394
+ return true;
395
+ }
396
+ if (n == 6 || n == 8) {
397
+ out.r = static_cast<std::uint8_t>(digits[0] * 16 + digits[1]);
398
+ out.g = static_cast<std::uint8_t>(digits[2] * 16 + digits[3]);
399
+ out.b = static_cast<std::uint8_t>(digits[4] * 16 + digits[5]);
400
+ out.a = static_cast<std::uint8_t>(n == 8 ? digits[6] * 16 + digits[7] : 255);
401
+ return true;
402
+ }
403
+ return false;
404
+ }
405
+ const bool rgb = detail::iequalsPrefix(s, "rgb");
406
+ const bool hsl = detail::iequalsPrefix(s, "hsl");
407
+ if (rgb || hsl) {
408
+ const char *open = std::strchr(s, '(');
409
+ if (!open) return false;
410
+ float v[4] = {0, 0, 0, 1};
411
+ bool pct[4] = {false, false, false, false};
412
+ Scanner sc(open + 1);
413
+ int n = 0;
414
+ while (n < 4) {
415
+ sc.skipSeparators();
416
+ if (sc.peek() == '/') sc.take();
417
+ if (!sc.number(v[n])) break;
418
+ const char *r = sc.rest();
419
+ if (*r == '%') { pct[n] = true; sc.advance(1); }
420
+ else if (std::strncmp(r, "deg", 3) == 0) sc.advance(3);
421
+ ++n;
422
+ }
423
+ if (n < 3) return false;
424
+ auto unit = [](float value, bool percent) { return std::clamp(percent ? value / 100.0f : value, 0.0f, 1.0f); };
425
+ const float alpha = n == 4 ? unit(v[3], pct[3]) : 1.0f;
426
+ if (rgb) {
427
+ auto channel = [](float value, bool percent) {
428
+ return static_cast<std::uint8_t>(std::lround(std::clamp(percent ? value * 2.55f : value, 0.0f, 255.0f)));
429
+ };
430
+ out.r = channel(v[0], pct[0]);
431
+ out.g = channel(v[1], pct[1]);
432
+ out.b = channel(v[2], pct[2]);
433
+ } else {
434
+ const float h = std::fmod(std::fmod(v[0], 360.0f) + 360.0f, 360.0f) / 360.0f;
435
+ const float sat = std::clamp(v[1] / 100.0f, 0.0f, 1.0f);
436
+ const float l = std::clamp(v[2] / 100.0f, 0.0f, 1.0f);
437
+ float r = l, g = l, b = l;
438
+ if (sat > 0) {
439
+ const float q = l < 0.5f ? l * (1 + sat) : l + sat - l * sat;
440
+ const float p = 2 * l - q;
441
+ r = detail::hueToRgb(p, q, h + 1.0f / 3);
442
+ g = detail::hueToRgb(p, q, h);
443
+ b = detail::hueToRgb(p, q, h - 1.0f / 3);
444
+ }
445
+ out.r = static_cast<std::uint8_t>(std::lround(r * 255));
446
+ out.g = static_cast<std::uint8_t>(std::lround(g * 255));
447
+ out.b = static_cast<std::uint8_t>(std::lround(b * 255));
448
+ }
449
+ out.a = static_cast<std::uint8_t>(std::lround(alpha * 255));
450
+ return true;
451
+ }
452
+ std::string word;
453
+ for (const char *q = s; *q && !std::isspace(static_cast<unsigned char>(*q)); ++q)
454
+ word.push_back(static_cast<char>(std::tolower(static_cast<unsigned char>(*q))));
455
+ if (word == "transparent") {
456
+ out = Color{0, 0, 0, 0};
457
+ return true;
458
+ }
459
+ for (const auto &named : detail::kNamedColors) {
460
+ if (word == named.name) {
461
+ out.r = static_cast<std::uint8_t>(named.rgb >> 16);
462
+ out.g = static_cast<std::uint8_t>(named.rgb >> 8);
463
+ out.b = static_cast<std::uint8_t>(named.rgb);
464
+ out.a = 255;
465
+ return true;
466
+ }
467
+ }
468
+ return false;
469
+ }
470
+
471
+ // A fill/stroke value: none | currentColor | <color>. Unparseable is Unset,
472
+ // so the property falls back to inheritance as an invalid declaration would.
473
+ inline Paint parsePaint(const char *s)
474
+ {
475
+ Paint paint;
476
+ if (!s) return paint;
477
+ while (*s && std::isspace(static_cast<unsigned char>(*s))) ++s;
478
+ if (detail::iequalsPrefix(s, "none")) {
479
+ paint.kind = PaintKind::None;
480
+ return paint;
481
+ }
482
+ if (detail::iequalsPrefix(s, "currentcolor")) {
483
+ paint.kind = PaintKind::CurrentColor;
484
+ return paint;
485
+ }
486
+ if (parseColor(s, paint.color)) paint.kind = paint.color.a == 0 ? PaintKind::None : PaintKind::Color;
487
+ return paint;
488
+ }
489
+
490
+ // Paint packed into one style int (RareStyle): 0 unset, 1 none, 2 currentColor,
491
+ // otherwise (alpha7 << 24) | 0xRRGGBB with alpha7 in 1..127.
492
+ inline int encodePaint(const Paint &paint)
493
+ {
494
+ switch (paint.kind) {
495
+ case PaintKind::Unset: return 0;
496
+ case PaintKind::None: return 1;
497
+ case PaintKind::CurrentColor: return 2;
498
+ case PaintKind::Color: break;
499
+ }
500
+ const int alpha7 = (paint.color.a * 126 + 127) / 255 + 1;
501
+ return (alpha7 << 24) | (paint.color.r << 16) | (paint.color.g << 8) | paint.color.b;
502
+ }
503
+
504
+ inline Paint decodePaint(int value)
505
+ {
506
+ Paint paint;
507
+ if (value == 0) return paint;
508
+ if (value == 1) { paint.kind = PaintKind::None; return paint; }
509
+ if (value == 2) { paint.kind = PaintKind::CurrentColor; return paint; }
510
+ const int alpha7 = (value >> 24) & 0x7f;
511
+ paint.kind = PaintKind::Color;
512
+ paint.color.r = static_cast<std::uint8_t>(value >> 16);
513
+ paint.color.g = static_cast<std::uint8_t>(value >> 8);
514
+ paint.color.b = static_cast<std::uint8_t>(value);
515
+ paint.color.a = static_cast<std::uint8_t>(alpha7 >= 127 ? 255 : ((alpha7 - 1) * 255 + 63) / 126);
516
+ return paint;
517
+ }
518
+
519
+ // ---------------------------------------------------------------------------
520
+ // Transforms
521
+
522
+ // Parses a transform list (matrix translate scale rotate skewX skewY) and
523
+ // returns the composed matrix. A malformed list yields identity, as in SVG.
524
+ inline bool parseTransform(const char *s, Matrix &out)
525
+ {
526
+ out = Matrix{};
527
+ if (!s) return true;
528
+ Scanner sc(s);
529
+ Matrix result;
530
+ while (!sc.atEnd()) {
531
+ std::string name;
532
+ while (std::isalpha(static_cast<unsigned char>(sc.peek()))) name.push_back(sc.take());
533
+ sc.skipSpaces();
534
+ if (sc.take() != '(') return false;
535
+ float v[6] = {0, 0, 0, 0, 0, 0};
536
+ int n = 0;
537
+ while (n < 6 && sc.startsNumber() && sc.number(v[n])) ++n;
538
+ sc.skipSeparators();
539
+ if (sc.take() != ')') return false;
540
+ Matrix m;
541
+ if (name == "matrix" && n == 6) m = {v[0], v[1], v[2], v[3], v[4], v[5]};
542
+ else if (name == "translate" && (n == 1 || n == 2)) m = Matrix::translate(v[0], n == 2 ? v[1] : 0);
543
+ else if (name == "scale" && (n == 1 || n == 2)) m = Matrix::scaling(v[0], n == 2 ? v[1] : v[0]);
544
+ else if (name == "rotate" && n == 1) m = Matrix::rotate(v[0]);
545
+ else if (name == "rotate" && n == 3)
546
+ m = Matrix::translate(v[1], v[2]) * Matrix::rotate(v[0]) * Matrix::translate(-v[1], -v[2]);
547
+ else if (name == "skewX" && n == 1) m = {1, 0, std::tan(v[0] * 3.14159265358979f / 180.0f), 1, 0, 0};
548
+ else if (name == "skewY" && n == 1) m = {1, std::tan(v[0] * 3.14159265358979f / 180.0f), 0, 1, 0, 0};
549
+ else return false;
550
+ result = result * m;
551
+ }
552
+ out = result;
553
+ return true;
554
+ }
555
+
556
+ // viewBox="minx miny w h" with preserveAspectRatio, mapped onto a w x h box.
557
+ inline Matrix viewBoxTransform(const float vb[4], float boxW, float boxH, const char *preserveAspectRatio)
558
+ {
559
+ if (vb[2] <= 0 || vb[3] <= 0) return Matrix{};
560
+ float sx = boxW / vb[2];
561
+ float sy = boxH / vb[3];
562
+ std::string par = preserveAspectRatio ? preserveAspectRatio : "";
563
+ if (par.find("none") != std::string::npos)
564
+ return Matrix::scaling(sx, sy) * Matrix::translate(-vb[0], -vb[1]);
565
+ const bool slice = par.find("slice") != std::string::npos;
566
+ const float s = slice ? std::max(sx, sy) : std::min(sx, sy);
567
+ float alignX = 0.5f, alignY = 0.5f;
568
+ if (par.find("xMin") != std::string::npos) alignX = 0;
569
+ if (par.find("xMax") != std::string::npos) alignX = 1;
570
+ if (par.find("YMin") != std::string::npos) alignY = 0;
571
+ if (par.find("YMax") != std::string::npos) alignY = 1;
572
+ const float tx = (boxW - vb[2] * s) * alignX;
573
+ const float ty = (boxH - vb[3] * s) * alignY;
574
+ return Matrix::translate(tx, ty) * Matrix::scaling(s, s) * Matrix::translate(-vb[0], -vb[1]);
575
+ }
576
+
577
+ // ---------------------------------------------------------------------------
578
+ // Path construction and flattening
579
+
580
+ class PathBuilder {
581
+ public:
582
+ // Curves flatten in device space: `toDevice` maps user units to pixels and
583
+ // `tolerance` is the maximum deviation, in pixels, of a chord.
584
+ PathBuilder(Path &out, const Matrix &toDevice, float tolerance = 0.2f)
585
+ : out_(out), m_(toDevice), tol_(std::max(0.01f, tolerance)) {}
586
+
587
+ Point current() const { return cur_; }
588
+ Point start() const { return start_; }
589
+
590
+ void moveTo(Point p)
591
+ {
592
+ finishOpen();
593
+ cur_ = start_ = p;
594
+ out_.contours.push_back(Contour{m_.apply(p)});
595
+ out_.closed.push_back(0);
596
+ open_ = true;
597
+ }
598
+ void lineTo(Point p)
599
+ {
600
+ if (!open_) moveTo(cur_);
601
+ emit(p);
602
+ cur_ = p;
603
+ }
604
+ void cubicTo(Point c1, Point c2, Point p)
605
+ {
606
+ if (!open_) moveTo(cur_);
607
+ const Point d0 = m_.apply(cur_), d1 = m_.apply(c1), d2 = m_.apply(c2), d3 = m_.apply(p);
608
+ const float ddx = std::max(std::fabs(d0.x - 2 * d1.x + d2.x), std::fabs(d1.x - 2 * d2.x + d3.x));
609
+ const float ddy = std::max(std::fabs(d0.y - 2 * d1.y + d2.y), std::fabs(d1.y - 2 * d2.y + d3.y));
610
+ const float dd = std::sqrt(ddx * ddx + ddy * ddy);
611
+ const int n = std::clamp(static_cast<int>(std::ceil(std::sqrt(0.75f * dd / tol_))), 1, 128);
612
+ const Point p0 = cur_;
613
+ for (int i = 1; i <= n; ++i) {
614
+ const float t = static_cast<float>(i) / n, u = 1 - t;
615
+ const float w0 = u * u * u, w1 = 3 * u * u * t, w2 = 3 * u * t * t, w3 = t * t * t;
616
+ emit({w0 * p0.x + w1 * c1.x + w2 * c2.x + w3 * p.x, w0 * p0.y + w1 * c1.y + w2 * c2.y + w3 * p.y});
617
+ }
618
+ cur_ = p;
619
+ }
620
+ void quadTo(Point c, Point p)
621
+ {
622
+ if (!open_) moveTo(cur_);
623
+ const Point d0 = m_.apply(cur_), d1 = m_.apply(c), d2 = m_.apply(p);
624
+ const float dd = std::hypot(d0.x - 2 * d1.x + d2.x, d0.y - 2 * d1.y + d2.y);
625
+ const int n = std::clamp(static_cast<int>(std::ceil(std::sqrt(0.25f * dd / tol_))), 1, 128);
626
+ const Point p0 = cur_;
627
+ for (int i = 1; i <= n; ++i) {
628
+ const float t = static_cast<float>(i) / n, u = 1 - t;
629
+ emit({u * u * p0.x + 2 * u * t * c.x + t * t * p.x, u * u * p0.y + 2 * u * t * c.y + t * t * p.y});
630
+ }
631
+ cur_ = p;
632
+ }
633
+ // SVG elliptical arc (endpoint parameterization, implementation notes F.6.5).
634
+ void arcTo(float rx, float ry, float rotationDeg, bool largeArc, bool sweep, Point p)
635
+ {
636
+ if (!open_) moveTo(cur_);
637
+ const Point p0 = cur_;
638
+ rx = std::fabs(rx);
639
+ ry = std::fabs(ry);
640
+ if ((p0.x == p.x && p0.y == p.y)) return;
641
+ if (rx == 0 || ry == 0) {
642
+ lineTo(p);
643
+ return;
644
+ }
645
+ const float phi = rotationDeg * 3.14159265358979f / 180.0f;
646
+ const float cs = std::cos(phi), sn = std::sin(phi);
647
+ const float dx2 = (p0.x - p.x) / 2, dy2 = (p0.y - p.y) / 2;
648
+ const float x1p = cs * dx2 + sn * dy2;
649
+ const float y1p = -sn * dx2 + cs * dy2;
650
+ const float lambda = (x1p * x1p) / (rx * rx) + (y1p * y1p) / (ry * ry);
651
+ if (lambda > 1) {
652
+ const float s = std::sqrt(lambda);
653
+ rx *= s;
654
+ ry *= s;
655
+ }
656
+ const float num = rx * rx * ry * ry - rx * rx * y1p * y1p - ry * ry * x1p * x1p;
657
+ const float den = rx * rx * y1p * y1p + ry * ry * x1p * x1p;
658
+ float coef = den > 0 ? std::sqrt(std::max(0.0f, num / den)) : 0.0f;
659
+ if (largeArc == sweep) coef = -coef;
660
+ const float cxp = coef * rx * y1p / ry;
661
+ const float cyp = -coef * ry * x1p / rx;
662
+ const float cx = cs * cxp - sn * cyp + (p0.x + p.x) / 2;
663
+ const float cy = sn * cxp + cs * cyp + (p0.y + p.y) / 2;
664
+ auto angle = [](float ux, float uy, float vx, float vy) {
665
+ return std::atan2(ux * vy - uy * vx, ux * vx + uy * vy);
666
+ };
667
+ const float theta1 = angle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry);
668
+ float dtheta = angle((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
669
+ const float twoPi = 2 * 3.14159265358979f;
670
+ if (!sweep && dtheta > 0) dtheta -= twoPi;
671
+ else if (sweep && dtheta < 0) dtheta += twoPi;
672
+ const float radius = std::max(rx, ry) * m_.scale();
673
+ const float step = radius > tol_ ? 2 * std::acos(std::max(-1.0f, 1 - tol_ / radius)) : 3.14159265358979f / 2;
674
+ const int n = std::clamp(static_cast<int>(std::ceil(std::fabs(dtheta) / std::max(step, 0.01f))), 1, 512);
675
+ for (int i = 1; i < n; ++i) {
676
+ const float t = theta1 + dtheta * i / n;
677
+ const float ex = rx * std::cos(t), ey = ry * std::sin(t);
678
+ emit({cs * ex - sn * ey + cx, sn * ex + cs * ey + cy});
679
+ }
680
+ emit(p);
681
+ cur_ = p;
682
+ }
683
+ void close()
684
+ {
685
+ if (!open_) return;
686
+ out_.closed.back() = 1;
687
+ open_ = false;
688
+ cur_ = start_;
689
+ }
690
+ void finish() { finishOpen(); }
691
+
692
+ private:
693
+ void emit(Point userPoint)
694
+ {
695
+ const Point d = m_.apply(userPoint);
696
+ Contour &c = out_.contours.back();
697
+ const Point &last = c.back();
698
+ if (std::fabs(last.x - d.x) < 1e-4f && std::fabs(last.y - d.y) < 1e-4f) return;
699
+ c.push_back(d);
700
+ }
701
+ void finishOpen()
702
+ {
703
+ // A lone moveTo draws nothing and must not leave a one-point contour.
704
+ if (!out_.contours.empty() && out_.contours.back().size() < 2 && !out_.closed.back()) {
705
+ out_.contours.pop_back();
706
+ out_.closed.pop_back();
707
+ }
708
+ open_ = false;
709
+ }
710
+
711
+ Path &out_;
712
+ Matrix m_;
713
+ float tol_;
714
+ Point cur_, start_;
715
+ bool open_ = false;
716
+ };
717
+
718
+ // Path data. Returns false at the first error; everything before it stays
719
+ // drawn, as the SVG error-handling rules require.
720
+ inline bool parsePathData(const char *d, PathBuilder &b)
721
+ {
722
+ Scanner sc(d);
723
+ char cmd = 0;
724
+ Point lastCtrl;
725
+ char prev = 0;
726
+ bool ok = true;
727
+ while (!sc.atEnd()) {
728
+ const char next = sc.peek();
729
+ if (std::isalpha(static_cast<unsigned char>(next))) {
730
+ cmd = sc.take();
731
+ } else if (!cmd || cmd == 'Z' || cmd == 'z') {
732
+ ok = false;
733
+ break;
734
+ }
735
+ const bool rel = std::islower(static_cast<unsigned char>(cmd));
736
+ const Point c = b.current();
737
+ auto abs = [&](float x, float y) { return rel ? Point{c.x + x, c.y + y} : Point{x, y}; };
738
+ float v[7];
739
+ switch (std::toupper(static_cast<unsigned char>(cmd))) {
740
+ case 'M':
741
+ if (!sc.number(v[0]) || !sc.number(v[1])) { ok = false; break; }
742
+ b.moveTo(abs(v[0], v[1]));
743
+ cmd = rel ? 'l' : 'L'; // subsequent pairs are implicit lineTos
744
+ break;
745
+ case 'L':
746
+ if (!sc.number(v[0]) || !sc.number(v[1])) { ok = false; break; }
747
+ b.lineTo(abs(v[0], v[1]));
748
+ break;
749
+ case 'H':
750
+ if (!sc.number(v[0])) { ok = false; break; }
751
+ b.lineTo({rel ? c.x + v[0] : v[0], c.y});
752
+ break;
753
+ case 'V':
754
+ if (!sc.number(v[0])) { ok = false; break; }
755
+ b.lineTo({c.x, rel ? c.y + v[0] : v[0]});
756
+ break;
757
+ case 'C':
758
+ if (!sc.number(v[0]) || !sc.number(v[1]) || !sc.number(v[2]) || !sc.number(v[3]) || !sc.number(v[4]) ||
759
+ !sc.number(v[5])) { ok = false; break; }
760
+ lastCtrl = abs(v[2], v[3]);
761
+ b.cubicTo(abs(v[0], v[1]), lastCtrl, abs(v[4], v[5]));
762
+ break;
763
+ case 'S': {
764
+ if (!sc.number(v[0]) || !sc.number(v[1]) || !sc.number(v[2]) || !sc.number(v[3])) { ok = false; break; }
765
+ const char up = static_cast<char>(std::toupper(static_cast<unsigned char>(prev)));
766
+ const Point c1 = (up == 'C' || up == 'S') ? Point{2 * c.x - lastCtrl.x, 2 * c.y - lastCtrl.y} : c;
767
+ lastCtrl = abs(v[0], v[1]);
768
+ b.cubicTo(c1, lastCtrl, abs(v[2], v[3]));
769
+ break;
770
+ }
771
+ case 'Q':
772
+ if (!sc.number(v[0]) || !sc.number(v[1]) || !sc.number(v[2]) || !sc.number(v[3])) { ok = false; break; }
773
+ lastCtrl = abs(v[0], v[1]);
774
+ b.quadTo(lastCtrl, abs(v[2], v[3]));
775
+ break;
776
+ case 'T': {
777
+ if (!sc.number(v[0]) || !sc.number(v[1])) { ok = false; break; }
778
+ const char up = static_cast<char>(std::toupper(static_cast<unsigned char>(prev)));
779
+ lastCtrl = (up == 'Q' || up == 'T') ? Point{2 * c.x - lastCtrl.x, 2 * c.y - lastCtrl.y} : c;
780
+ b.quadTo(lastCtrl, abs(v[0], v[1]));
781
+ break;
782
+ }
783
+ case 'A': {
784
+ bool large = false, sweep = false;
785
+ if (!sc.number(v[0]) || !sc.number(v[1]) || !sc.number(v[2]) || !sc.flag(large) || !sc.flag(sweep) ||
786
+ !sc.number(v[3]) || !sc.number(v[4])) { ok = false; break; }
787
+ b.arcTo(v[0], v[1], v[2], large, sweep, abs(v[3], v[4]));
788
+ break;
789
+ }
790
+ case 'Z':
791
+ b.close();
792
+ break;
793
+ default:
794
+ ok = false;
795
+ break;
796
+ }
797
+ if (!ok) break;
798
+ prev = cmd;
799
+ }
800
+ b.finish();
801
+ return ok;
802
+ }
803
+
804
+ // polyline/polygon `points`. An odd trailing coordinate is ignored.
805
+ inline void addPoints(PathBuilder &b, const char *points, bool close)
806
+ {
807
+ Scanner sc(points);
808
+ float x = 0, y = 0;
809
+ bool first = true;
810
+ while (sc.number(x) && sc.number(y)) {
811
+ if (first) b.moveTo({x, y});
812
+ else b.lineTo({x, y});
813
+ first = false;
814
+ }
815
+ if (!first && close) b.close();
816
+ b.finish();
817
+ }
818
+
819
+ inline void addEllipse(PathBuilder &b, float cx, float cy, float rx, float ry)
820
+ {
821
+ if (rx <= 0 || ry <= 0) return;
822
+ b.moveTo({cx + rx, cy});
823
+ b.arcTo(rx, ry, 0, false, true, {cx - rx, cy});
824
+ b.arcTo(rx, ry, 0, false, true, {cx + rx, cy});
825
+ b.close();
826
+ b.finish();
827
+ }
828
+
829
+ inline void addRect(PathBuilder &b, float x, float y, float w, float h, float rx, float ry)
830
+ {
831
+ if (w <= 0 || h <= 0) return;
832
+ rx = std::min(std::max(rx, 0.0f), w / 2);
833
+ ry = std::min(std::max(ry, 0.0f), h / 2);
834
+ if (rx <= 0 || ry <= 0) {
835
+ b.moveTo({x, y});
836
+ b.lineTo({x + w, y});
837
+ b.lineTo({x + w, y + h});
838
+ b.lineTo({x, y + h});
839
+ b.close();
840
+ } else {
841
+ b.moveTo({x + rx, y});
842
+ b.lineTo({x + w - rx, y});
843
+ b.arcTo(rx, ry, 0, false, true, {x + w, y + ry});
844
+ b.lineTo({x + w, y + h - ry});
845
+ b.arcTo(rx, ry, 0, false, true, {x + w - rx, y + h});
846
+ b.lineTo({x + rx, y + h});
847
+ b.arcTo(rx, ry, 0, false, true, {x, y + h - ry});
848
+ b.lineTo({x, y + ry});
849
+ b.arcTo(rx, ry, 0, false, true, {x + rx, y});
850
+ b.close();
851
+ }
852
+ b.finish();
853
+ }
854
+
855
+ // ---------------------------------------------------------------------------
856
+ // Stroking
857
+
858
+ enum class LineCap : std::uint8_t { Butt, Round, Square };
859
+ enum class LineJoin : std::uint8_t { Miter, Round, Bevel };
860
+
861
+ struct StrokeStyle {
862
+ float width = 1.0f; // device pixels
863
+ LineCap cap = LineCap::Butt;
864
+ LineJoin join = LineJoin::Miter;
865
+ float miterLimit = 4.0f;
866
+ };
867
+
868
+ namespace detail {
869
+ // Every stroke piece winds the same way, so overlapping pieces add instead of
870
+ // cancelling and the nonzero fill of the set is exactly their union. A piece
871
+ // reaches the sink as points plus `reversed`: when set, the piece is to be
872
+ // read backwards (its edges' directions flipped), which is how it would wind
873
+ // had it been stored reversed. Pieces never touch the heap: a stroke is
874
+ // hundreds of them, and an ESP32 allocation is a microsecond or two.
875
+ template <typename Sink>
876
+ inline void pushPiece(Sink &sink, const Point *piece, int n)
877
+ {
878
+ if (n < 3) return;
879
+ float area = 0;
880
+ for (int i = 0; i < n; ++i) {
881
+ const Point &p = piece[i], &q = piece[(i + 1) % n];
882
+ area += p.x * q.y - q.x * p.y;
883
+ }
884
+ area *= 0.5f;
885
+ if (std::fabs(area) < 1e-6f) return;
886
+ sink(piece, n, area < 0);
887
+ }
888
+ template <typename Sink>
889
+ inline void pushPiece(Sink &sink, std::initializer_list<Point> piece)
890
+ {
891
+ pushPiece(sink, piece.begin(), static_cast<int>(piece.size()));
892
+ }
893
+
894
+ template <typename Sink>
895
+ inline void pushDisc(Sink &sink, Point c, float r)
896
+ {
897
+ const int n = std::clamp(static_cast<int>(std::ceil(r * 1.6f)) + 6, 8, 64);
898
+ Point disc[64];
899
+ for (int i = 0; i < n; ++i) {
900
+ const float t = 2 * 3.14159265358979f * i / n;
901
+ disc[i] = {c.x + r * std::cos(t), c.y + r * std::sin(t)};
902
+ }
903
+ pushPiece(sink, disc, n);
904
+ }
905
+ // The round join's outer wedge: the pie slice from o0 to o1 around p, with
906
+ // just enough arc points to keep each chord within 0.2 px of the circle. (A
907
+ // whole disc per vertex costs ~20 points where a flattened curve's joins need
908
+ // one or two.)
909
+ template <typename Sink>
910
+ inline void pushWedge(Sink &sink, Point p, Point o0, float r, float turn)
911
+ {
912
+ const float step = r > 0.2f ? 2 * std::acos(1 - 0.2f / r) : 1.5707963f;
913
+ const int n = std::clamp(static_cast<int>(std::ceil(std::fabs(turn) / step)), 1, 64);
914
+ Point wedge[66];
915
+ int count = 0;
916
+ wedge[count++] = p;
917
+ const float a0 = std::atan2(o0.y - p.y, o0.x - p.x);
918
+ // o1 is o0 rotated about p by the path's turning angle (both offsets are
919
+ // the segment normals scaled by the same side), so the arc sweeps `turn`.
920
+ const float sweep = turn;
921
+ for (int i = 0; i <= n; ++i) {
922
+ const float t = a0 + sweep * i / n;
923
+ wedge[count++] = {p.x + r * std::cos(t), p.y + r * std::sin(t)};
924
+ }
925
+ pushPiece(sink, wedge, count);
926
+ }
927
+ } // namespace detail
928
+
929
+ // Outlines one device-space polyline as polygons to fill with nonzero, each
930
+ // handed to `sink(points, count, reversed)`.
931
+ //
932
+ // The outline is one polygon per open subpath (and two, outer and inner, per
933
+ // closed one): the left offset forward, the end cap, the right offset back,
934
+ // the start cap -- the construction Skia's stroker fills with nonzero. At a
935
+ // joint the outer side gets the join's own points (miter tip, round arc, or
936
+ // nothing for a bevel) and the inner side pivots through the vertex itself,
937
+ // which keeps the winding positive where the two offsets overlap. Compared
938
+ // with a quad per segment plus a piece per joint and a disc per cap, this
939
+ // hands the rasterizer about half the edges (no quad ends, no overlapping
940
+ // pieces) and the builder a quarter, and its arcs step by a fixed rotation:
941
+ // one cos/sin per stroke instead of two per arc point.
942
+ namespace detail {
943
+ struct ArcStep {
944
+ float step = 1.5707963f;
945
+ explicit ArcStep(float r)
946
+ {
947
+ // Each chord within 0.2 px of the circle, and never coarser than the
948
+ // disc pushDisc draws (small radii need the extra points for area).
949
+ step = r > 0.2f ? 2 * std::acos(1 - 0.2f / r) : 1.5707963f;
950
+ const int disc = std::clamp(static_cast<int>(std::ceil(r * 1.6f)) + 6, 8, 64);
951
+ step = std::min(step, 6.2831853f / static_cast<float>(disc));
952
+ }
953
+ };
954
+ // Points strictly between p+u and p+u rotated by `sweep` (radians, signed),
955
+ // appended to `out`. |u| is the radius.
956
+ template <typename Out>
957
+ inline void arcPoints(Out &out, Point p, Point u, float sweep, float step)
958
+ {
959
+ const int n = std::clamp(static_cast<int>(std::ceil(std::fabs(sweep) / step)), 1, 64);
960
+ if (n < 2) return;
961
+ const float d = sweep / n;
962
+ const float c = std::cos(d), s = std::sin(d);
963
+ float x = u.x, y = u.y;
964
+ for (int i = 1; i < n; ++i) {
965
+ const float nx = x * c - y * s;
966
+ y = x * s + y * c;
967
+ x = nx;
968
+ out.push_back({p.x + x, p.y + y});
969
+ }
970
+ }
971
+ inline float polygonArea2(const Point *p, std::size_t n)
972
+ {
973
+ float area = 0;
974
+ for (std::size_t i = 0; i < n; ++i) {
975
+ const Point &a = p[i], &b = p[i + 1 < n ? i + 1 : 0];
976
+ area += a.x * b.y - b.x * a.y;
977
+ }
978
+ return area;
979
+ }
980
+ } // namespace detail
981
+
982
+ template <typename Sink>
983
+ inline void strokeContour(const Contour &in, bool closed, const StrokeStyle &style, Sink &&sink)
984
+ {
985
+ const float hw = style.width * 0.5f;
986
+ if (hw <= 0 || in.empty()) return;
987
+ ScratchVector<Point> pts;
988
+ pts.reserve(in.size());
989
+ for (const Point &p : in) {
990
+ if (!pts.empty()) {
991
+ const float dx = p.x - pts.back().x, dy = p.y - pts.back().y;
992
+ if (dx * dx + dy * dy <= 1e-8f) continue;
993
+ }
994
+ pts.push_back(p);
995
+ }
996
+ if (closed && pts.size() > 2) {
997
+ const float dx = pts.front().x - pts.back().x, dy = pts.front().y - pts.back().y;
998
+ if (dx * dx + dy * dy <= 1e-8f) pts.pop_back();
999
+ }
1000
+ const std::size_t n = pts.size();
1001
+ if (n == 1) {
1002
+ // Zero-length subpath: round and square caps still paint a dot.
1003
+ if (style.cap == LineCap::Round) detail::pushDisc(sink, pts[0], hw);
1004
+ else if (style.cap == LineCap::Square)
1005
+ detail::pushPiece(sink, {{pts[0].x - hw, pts[0].y - hw}, {pts[0].x + hw, pts[0].y - hw},
1006
+ {pts[0].x + hw, pts[0].y + hw}, {pts[0].x - hw, pts[0].y + hw}});
1007
+ return;
1008
+ }
1009
+ const std::size_t segments = closed ? n : n - 1;
1010
+ // Each segment's left normal, scaled to the half width: solved once, read
1011
+ // by both sides and by the joins on both its ends.
1012
+ ScratchVector<Point> normals(segments);
1013
+ for (std::size_t i = 0; i < segments; ++i) {
1014
+ const Point &a = pts[i], &b = pts[(i + 1) % n];
1015
+ const float dx = b.x - a.x, dy = b.y - a.y;
1016
+ const float k = hw / std::sqrt(dx * dx + dy * dy);
1017
+ normals[i] = Point{-dy * k, dx * k};
1018
+ }
1019
+ const bool roundArcs = style.cap == LineCap::Round || style.join == LineJoin::Round;
1020
+ const float arcStep = roundArcs ? detail::ArcStep(hw).step : 1.5707963f;
1021
+ ScratchVector<Point> out;
1022
+ out.reserve(segments * 4 + 8);
1023
+ // The joint at vertex p between offsets a (arriving) and b (leaving), on
1024
+ // the side whose offsets these are.
1025
+ auto joint = [&](Point p, Point a, Point b, float cross, float dot) {
1026
+ if (dot > 0 && std::fabs(cross) < 1e-4f * dot) { // straight on
1027
+ out.push_back({p.x + b.x, p.y + b.y});
1028
+ return;
1029
+ }
1030
+ // `cross` is the turn as seen from this side's offsets: negative when
1031
+ // the path turns away from them, where they fan apart.
1032
+ const bool outer = cross <= 0;
1033
+ const float side = a.x * b.y - a.y * b.x;
1034
+ out.push_back({p.x + a.x, p.y + a.y});
1035
+ if (!outer) {
1036
+ out.push_back(p);
1037
+ } else if (style.join == LineJoin::Round) {
1038
+ // `a` is the left normal of the arriving direction, so a full
1039
+ // reversal (side 0) sweeps through that direction: -pi.
1040
+ const float turn = std::fabs(cross) < 1e-4f * hw * hw ? -3.14159265f : std::atan2(side, a.x * b.x + a.y * b.y);
1041
+ if (hw * std::fabs(turn) >= 1.0f) detail::arcPoints(out, p, a, turn, arcStep);
1042
+ } else if (style.join == LineJoin::Miter) {
1043
+ const float cosTurn = std::clamp(dot / (hw * hw), -1.0f, 1.0f);
1044
+ const float cosHalf = std::sqrt((1 + cosTurn) * 0.5f);
1045
+ if (cosHalf > 1e-4f && 1.0f / cosHalf <= style.miterLimit) {
1046
+ const Point mid{a.x + b.x, a.y + b.y};
1047
+ const float k = hw / (cosHalf * std::sqrt(mid.x * mid.x + mid.y * mid.y));
1048
+ out.push_back({p.x + mid.x * k, p.y + mid.y * k});
1049
+ }
1050
+ }
1051
+ out.push_back({p.x + b.x, p.y + b.y});
1052
+ };
1053
+ auto cap = [&](Point p, Point u) { // from p+u round to p-u, through the forward side
1054
+ if (style.cap == LineCap::Round) {
1055
+ out.push_back({p.x + u.x, p.y + u.y});
1056
+ detail::arcPoints(out, p, u, -3.14159265f, arcStep);
1057
+ out.push_back({p.x - u.x, p.y - u.y});
1058
+ } else if (style.cap == LineCap::Square) {
1059
+ const Point f{u.y, -u.x}; // forward, half width long
1060
+ out.push_back({p.x + u.x + f.x, p.y + u.y + f.y});
1061
+ out.push_back({p.x - u.x + f.x, p.y - u.y + f.y});
1062
+ } else {
1063
+ out.push_back({p.x + u.x, p.y + u.y});
1064
+ out.push_back({p.x - u.x, p.y - u.y});
1065
+ }
1066
+ };
1067
+ auto turnAt = [&](std::size_t prevSeg, std::size_t nextSeg, float &cross, float &dot) {
1068
+ const Point n0 = normals[prevSeg], n1 = normals[nextSeg];
1069
+ cross = n0.x * n1.y - n0.y * n1.x;
1070
+ dot = n0.x * n1.x + n0.y * n1.y;
1071
+ };
1072
+ if (!closed) {
1073
+ // Left side forward.
1074
+ out.push_back({pts[0].x + normals[0].x, pts[0].y + normals[0].y});
1075
+ for (std::size_t v = 1; v < n - 1; ++v) {
1076
+ float cross, dot;
1077
+ turnAt(v - 1, v, cross, dot);
1078
+ joint(pts[v], normals[v - 1], normals[v], cross, dot);
1079
+ }
1080
+ // End cap, right side back, start cap.
1081
+ cap(pts[n - 1], normals[segments - 1]);
1082
+ for (std::size_t v = n - 2; v >= 1; --v) {
1083
+ float cross, dot;
1084
+ turnAt(v - 1, v, cross, dot);
1085
+ const Point a{-normals[v].x, -normals[v].y}, b{-normals[v - 1].x, -normals[v - 1].y};
1086
+ joint(pts[v], a, b, -cross, dot);
1087
+ }
1088
+ cap(pts[0], Point{-normals[0].x, -normals[0].y});
1089
+ if (style.cap != LineCap::Square) out.pop_back(); // the start cap ends where the outline began
1090
+ const float area = detail::polygonArea2(out.data(), out.size());
1091
+ if (std::fabs(area) > 2e-6f) sink(out.data(), static_cast<int>(out.size()), area < 0);
1092
+ return;
1093
+ }
1094
+ // Closed: the left loop forward and the right loop backward, wound
1095
+ // oppositely, so nonzero fills only the band between them.
1096
+ for (std::size_t v = 0; v < n; ++v) {
1097
+ float cross, dot;
1098
+ const std::size_t prev = (v + segments - 1) % segments;
1099
+ turnAt(prev, v, cross, dot);
1100
+ joint(pts[v], normals[prev], normals[v], cross, dot);
1101
+ }
1102
+ const std::size_t leftCount = out.size();
1103
+ for (std::size_t k = 0; k < n; ++k) {
1104
+ const std::size_t v = n - 1 - k;
1105
+ float cross, dot;
1106
+ const std::size_t prev = (v + segments - 1) % segments;
1107
+ turnAt(prev, v, cross, dot);
1108
+ const Point a{-normals[v].x, -normals[v].y}, b{-normals[prev].x, -normals[prev].y};
1109
+ joint(pts[v], a, b, -cross, dot);
1110
+ }
1111
+ const float area = detail::polygonArea2(out.data(), leftCount) +
1112
+ detail::polygonArea2(out.data() + leftCount, out.size() - leftCount);
1113
+ if (std::fabs(area) <= 2e-6f) return;
1114
+ sink(out.data(), static_cast<int>(leftCount), area < 0);
1115
+ sink(out.data() + leftCount, static_cast<int>(out.size() - leftCount), area < 0);
1116
+ }
1117
+
1118
+ // The stroke outline as polygons (each wound the same way).
1119
+ inline void strokeContour(const Contour &in, bool closed, const StrokeStyle &style, std::vector<Contour> &out)
1120
+ {
1121
+ strokeContour(in, closed, style, [&out](const Point *p, int n, bool reversed) {
1122
+ Contour piece(p, p + n);
1123
+ if (reversed) std::reverse(piece.begin(), piece.end());
1124
+ out.push_back(std::move(piece));
1125
+ });
1126
+ }
1127
+
1128
+ inline void strokePath(const Path &path, const StrokeStyle &style, std::vector<Contour> &out)
1129
+ {
1130
+ for (std::size_t i = 0; i < path.contours.size(); ++i) strokeContour(path.contours[i], path.closed[i] != 0, style, out);
1131
+ }
1132
+
1133
+ // ---------------------------------------------------------------------------
1134
+ // Bounds and hit testing
1135
+
1136
+ struct Bounds {
1137
+ float x0 = 1e30f, y0 = 1e30f, x1 = -1e30f, y1 = -1e30f;
1138
+ bool empty() const { return x0 > x1 || y0 > y1; }
1139
+ void add(Point p)
1140
+ {
1141
+ x0 = std::min(x0, p.x);
1142
+ y0 = std::min(y0, p.y);
1143
+ x1 = std::max(x1, p.x);
1144
+ y1 = std::max(y1, p.y);
1145
+ }
1146
+ void add(const std::vector<Contour> &contours)
1147
+ {
1148
+ for (const auto &c : contours)
1149
+ for (const Point &p : c) add(p);
1150
+ }
1151
+ };
1152
+
1153
+ // Winding number of `p` against closed contours (open ones close implicitly).
1154
+ inline int windingNumber(const std::vector<Contour> &contours, Point p)
1155
+ {
1156
+ int wn = 0;
1157
+ for (const auto &c : contours) {
1158
+ const std::size_t n = c.size();
1159
+ if (n < 2) continue;
1160
+ for (std::size_t i = 0; i < n; ++i) {
1161
+ const Point &a = c[i], &b = c[(i + 1) % n];
1162
+ const float isLeft = (b.x - a.x) * (p.y - a.y) - (p.x - a.x) * (b.y - a.y);
1163
+ if (a.y <= p.y) {
1164
+ if (b.y > p.y && isLeft > 0) ++wn;
1165
+ } else if (b.y <= p.y && isLeft < 0) {
1166
+ --wn;
1167
+ }
1168
+ }
1169
+ }
1170
+ return wn;
1171
+ }
1172
+
1173
+ inline bool insideFill(const std::vector<Contour> &contours, Point p, bool evenOdd)
1174
+ {
1175
+ const int wn = windingNumber(contours, p);
1176
+ return evenOdd ? (wn & 1) != 0 : wn != 0;
1177
+ }
1178
+
1179
+ inline float distanceToPath(const Path &path, Point p)
1180
+ {
1181
+ float best = 1e30f;
1182
+ for (std::size_t ci = 0; ci < path.contours.size(); ++ci) {
1183
+ const Contour &c = path.contours[ci];
1184
+ const std::size_t n = c.size();
1185
+ const std::size_t segs = path.closed[ci] ? n : (n ? n - 1 : 0);
1186
+ for (std::size_t i = 0; i < segs; ++i) {
1187
+ const Point &a = c[i], &b = c[(i + 1) % n];
1188
+ const float dx = b.x - a.x, dy = b.y - a.y;
1189
+ const float len2 = dx * dx + dy * dy;
1190
+ float t = len2 > 0 ? ((p.x - a.x) * dx + (p.y - a.y) * dy) / len2 : 0;
1191
+ t = std::clamp(t, 0.0f, 1.0f);
1192
+ best = std::min(best, std::hypot(a.x + t * dx - p.x, a.y + t * dy - p.y));
1193
+ }
1194
+ if (n == 1) best = std::min(best, std::hypot(c[0].x - p.x, c[0].y - p.y));
1195
+ }
1196
+ return best;
1197
+ }
1198
+
1199
+ // ---------------------------------------------------------------------------
1200
+ // Anti-aliased coverage rasterizer
1201
+
1202
+ // Exact-area coverage over a pixel rectangle, built from signed edge
1203
+ // contributions and resolved by a running sum per row (the font-rs scheme).
1204
+ // Edges are clipped to the rectangle, so it can rasterize any horizontal strip
1205
+ // of a larger shape with no seams between strips.
1206
+ // A shape's edges, flat and sorted by top y: built once per scene build, then
1207
+ // every paint and every strip walks one contiguous array.
1208
+ // `a` is the top end and `b` the bottom; `dir` is the winding the contour
1209
+ // gave it (+1 drawn downwards, -1 upwards). The slopes are solved once here:
1210
+ // a tall edge crosses many strips, and each strip re-clips it.
1211
+ struct Edge {
1212
+ Point a, b;
1213
+ float top, bottom;
1214
+ float dxdy, dydx; // dydx is 0 for a vertical edge (never used then)
1215
+ float dir;
1216
+ };
1217
+ using EdgeList = std::vector<Edge, ExternalAllocator<Edge>>;
1218
+
1219
+ // Collects polygon edges and writes them out sorted by top. Edges are built
1220
+ // in internal scratch and ordered by sorting 8-byte keys (top, index), then
1221
+ // written out once, in order: sorting the 36-byte edges themselves in place,
1222
+ // in PSRAM, cost ~700 cycles per edge on an ESP32-S3.
1223
+ class EdgeBuilder {
1224
+ public:
1225
+ void reserve(std::size_t n)
1226
+ {
1227
+ built_.reserve(n);
1228
+ keys_.reserve(n);
1229
+ }
1230
+ // One closed polygon; `reversed` reads it backwards (flips every edge).
1231
+ void add(const Point *p, int n, bool reversed = false)
1232
+ {
1233
+ for (int i = 0; i < n; ++i) {
1234
+ Point a = p[i], b = p[i + 1 < n ? i + 1 : 0];
1235
+ if (a.y == b.y) continue;
1236
+ float dir = reversed ? -1.0f : 1.0f;
1237
+ if (a.y > b.y) std::swap(a, b), dir = -dir;
1238
+ const float dx = b.x - a.x, dy = b.y - a.y;
1239
+ // The float's bits, flipped so unsigned order is numeric order.
1240
+ std::uint32_t bits;
1241
+ std::memcpy(&bits, &a.y, sizeof bits);
1242
+ bits ^= (bits >> 31) ? 0xffffffffu : 0x80000000u;
1243
+ keys_.push_back(static_cast<std::uint64_t>(bits) << 32 | built_.size());
1244
+ built_.push_back({a, b, a.y, b.y, dx / dy, dx != 0.0f ? dy / dx : 0.0f, dir});
1245
+ }
1246
+ }
1247
+ void finish(EdgeList &edges)
1248
+ {
1249
+ std::sort(keys_.begin(), keys_.end());
1250
+ edges.resize(built_.size());
1251
+ for (std::size_t i = 0; i < keys_.size(); ++i) edges[i] = built_[static_cast<std::uint32_t>(keys_[i])];
1252
+ }
1253
+
1254
+ private:
1255
+ ScratchVector<Edge> built_;
1256
+ ScratchVector<std::uint64_t> keys_;
1257
+ };
1258
+
1259
+ inline void buildEdges(const std::vector<Contour> &contours, EdgeList &edges)
1260
+ {
1261
+ edges.clear();
1262
+ std::size_t total = 0;
1263
+ for (const auto &c : contours)
1264
+ if (c.size() >= 2) total += c.size();
1265
+ if (!total) return;
1266
+ EdgeBuilder builder;
1267
+ builder.reserve(total);
1268
+ for (const auto &c : contours)
1269
+ if (c.size() >= 2) builder.add(c.data(), static_cast<int>(c.size()));
1270
+ builder.finish(edges);
1271
+ }
1272
+
1273
+ // A path's stroke outline straight to edges (what strokePath + buildEdges
1274
+ // make, without the per-piece polygons), and the outline's bounds.
1275
+ inline void strokePathEdges(const Path &path, const StrokeStyle &style, EdgeList &edges, Bounds &bounds)
1276
+ {
1277
+ edges.clear();
1278
+ EdgeBuilder builder;
1279
+ std::size_t points = 0;
1280
+ for (const auto &c : path.contours) points += c.size();
1281
+ builder.reserve(points * 8 + 16);
1282
+ auto sink = [&](const Point *p, int n, bool reversed) {
1283
+ for (int i = 0; i < n; ++i) bounds.add(p[i]);
1284
+ builder.add(p, n, reversed);
1285
+ };
1286
+ for (std::size_t i = 0; i < path.contours.size(); ++i) strokeContour(path.contours[i], path.closed[i] != 0, style, sink);
1287
+ builder.finish(edges);
1288
+ }
1289
+
1290
+ class Rasterizer {
1291
+ public:
1292
+ // The accumulator stays all-zero between uses: row() clears exactly the
1293
+ // cells each row touched, so a strip never re-zeroes its whole area and
1294
+ // work scales with the ink, not the bounding box.
1295
+ GEA_SVG_HOT void reset(int x0, int y0, int width, int height)
1296
+ {
1297
+ x0_ = x0;
1298
+ y0_ = y0;
1299
+ w_ = std::max(0, width);
1300
+ h_ = std::max(0, height);
1301
+ stride_ = w_ + 2;
1302
+ wpr_ = (stride_ + 31) >> 5;
1303
+ const std::size_t cells = static_cast<std::size_t>(stride_) * static_cast<std::size_t>(h_);
1304
+ growInternalZeroed(acc_, cells, kReserveCells, accRetry_);
1305
+ const std::size_t words = static_cast<std::size_t>(wpr_) * static_cast<std::size_t>(h_);
1306
+ growInternalZeroed(bits_, words, kReserveWords, bitsRetry_);
1307
+ }
1308
+ int x() const { return x0_; }
1309
+ int y() const { return y0_; }
1310
+ int width() const { return w_; }
1311
+ int height() const { return h_; }
1312
+
1313
+ // Rasterizes from a prebuilt edge list (not copied; must outlive the use).
1314
+ void useEdges(const EdgeList &edges) { edges_ = &edges; }
1315
+ // Builds this rasterizer's own edge list from contours.
1316
+ void setEdges(const std::vector<Contour> &contours)
1317
+ {
1318
+ buildEdges(contours, ownEdges_);
1319
+ edges_ = &ownEdges_;
1320
+ }
1321
+
1322
+ // Adds the edges that reach the current strip.
1323
+ void addStoredEdges()
1324
+ {
1325
+ if (!edges_) return;
1326
+ const float top = static_cast<float>(y0_), bottom = static_cast<float>(y0_ + h_);
1327
+ for (const Edge &e : *edges_) {
1328
+ if (e.top >= bottom) break;
1329
+ if (e.bottom <= top) continue;
1330
+ addStoredEdge(e);
1331
+ }
1332
+ }
1333
+
1334
+ // Strip-by-strip walk of the stored edges: each strip adds only the edges
1335
+ // still open (kept in an active list) plus the ones it newly reaches, so a
1336
+ // tall shape cut into many short strips never re-scans its whole list.
1337
+ void beginEdgeWalk()
1338
+ {
1339
+ nextEdge_ = 0;
1340
+ active_.clear();
1341
+ }
1342
+ GEA_SVG_HOT void addActiveEdges()
1343
+ {
1344
+ if (!edges_) return;
1345
+ const float top = static_cast<float>(y0_), bottom = static_cast<float>(y0_ + h_);
1346
+ const EdgeList &edges = *edges_;
1347
+ std::size_t kept = 0;
1348
+ for (std::size_t i = 0; i < active_.size(); ++i)
1349
+ if (edges[active_[i]].bottom > top) active_[kept++] = active_[i];
1350
+ active_.resize(kept);
1351
+ while (nextEdge_ < edges.size() && edges[nextEdge_].top < bottom) {
1352
+ if (edges[nextEdge_].bottom > top) active_.push_back(static_cast<std::uint32_t>(nextEdge_));
1353
+ ++nextEdge_;
1354
+ }
1355
+ for (std::uint32_t i : active_) addStoredEdge(edges[i]);
1356
+ }
1357
+
1358
+ // addEdge for a stored edge: the same clipping, from its solved slopes.
1359
+ GEA_SVG_HOT void addStoredEdge(const Edge &e)
1360
+ {
1361
+ if (w_ <= 0 || h_ <= 0) return;
1362
+ const float W = static_cast<float>(w_), H = static_cast<float>(h_);
1363
+ Point a{e.a.x - x0_, e.a.y - y0_}, b{e.b.x - x0_, e.b.y - y0_};
1364
+ if (b.y <= 0 || a.y >= H) return;
1365
+ if (a.y < 0) { a.x -= e.dxdy * a.y; a.y = 0; }
1366
+ if (b.y > H) { b.x = a.x + e.dxdy * (H - a.y); b.y = H; }
1367
+ if (b.y <= a.y) return;
1368
+ const float lo = std::min(a.x, b.x), hi = std::max(a.x, b.x);
1369
+ if (lo >= 0 && hi <= W) {
1370
+ line(a, b, e.dir, e.dxdy);
1371
+ return;
1372
+ }
1373
+ Point pts[4];
1374
+ int count = 0;
1375
+ pts[count++] = a;
1376
+ float ys[2];
1377
+ int nt = 0;
1378
+ if (lo < 0 && hi > 0) ys[nt++] = a.y + (0 - a.x) * e.dydx;
1379
+ if (lo < W && hi > W) ys[nt++] = a.y + (W - a.x) * e.dydx;
1380
+ if (nt == 2 && ys[0] > ys[1]) std::swap(ys[0], ys[1]);
1381
+ for (int i = 0; i < nt; ++i) {
1382
+ const float y = std::clamp(ys[i], a.y, b.y);
1383
+ pts[count++] = {a.x + e.dxdy * (y - a.y), y};
1384
+ }
1385
+ pts[count++] = b;
1386
+ for (int i = 0; i + 1 < count; ++i) {
1387
+ Point p = pts[i], q = pts[i + 1];
1388
+ // A piece beyond a side column is flattened onto it, vertical.
1389
+ const float mid = (p.x + q.x) * 0.5f;
1390
+ const bool outside = mid < 0 || mid > W;
1391
+ p.x = std::clamp(p.x, 0.0f, W);
1392
+ q.x = std::clamp(q.x, 0.0f, W);
1393
+ line(p, q, e.dir, outside ? 0.0f : e.dxdy);
1394
+ }
1395
+ }
1396
+
1397
+ void addContours(const std::vector<Contour> &contours, float dx = 0, float dy = 0)
1398
+ {
1399
+ for (const auto &c : contours) {
1400
+ const std::size_t n = c.size();
1401
+ if (n < 2) continue;
1402
+ for (std::size_t i = 0; i < n; ++i) {
1403
+ const Point &a = c[i], &b = c[(i + 1) % n];
1404
+ addEdge({a.x + dx, a.y + dy}, {b.x + dx, b.y + dy});
1405
+ }
1406
+ }
1407
+ }
1408
+
1409
+ // One edge in device pixels.
1410
+ void addEdge(Point a, Point b)
1411
+ {
1412
+ if (w_ <= 0 || h_ <= 0) return;
1413
+ a.x -= x0_; a.y -= y0_;
1414
+ b.x -= x0_; b.y -= y0_;
1415
+ const float W = static_cast<float>(w_), H = static_cast<float>(h_);
1416
+ if ((a.y <= 0 && b.y <= 0) || (a.y >= H && b.y >= H) || a.y == b.y) return;
1417
+ // Clip to the strip's rows.
1418
+ if (a.y > b.y) std::swap(a, b), dirFlip_ = true;
1419
+ else dirFlip_ = false;
1420
+ if (a.y < 0) { a.x += (b.x - a.x) * (0 - a.y) / (b.y - a.y); a.y = 0; }
1421
+ if (b.y > H) { b.x = a.x + (b.x - a.x) * (H - a.y) / (b.y - a.y); b.y = H; }
1422
+ // Split at the left/right columns: the part outside becomes a vertical
1423
+ // edge on the boundary, which keeps every row's winding exact.
1424
+ Point pts[4];
1425
+ int count = 0;
1426
+ pts[count++] = a;
1427
+ const float lo = std::min(a.x, b.x), hi = std::max(a.x, b.x);
1428
+ float ts[2];
1429
+ int nt = 0;
1430
+ if (lo < 0 && hi > 0) ts[nt++] = (0 - a.x) / (b.x - a.x);
1431
+ if (lo < W && hi > W) ts[nt++] = (W - a.x) / (b.x - a.x);
1432
+ if (nt == 2 && ts[0] > ts[1]) std::swap(ts[0], ts[1]);
1433
+ for (int i = 0; i < nt; ++i) pts[count++] = {a.x + (b.x - a.x) * ts[i], a.y + (b.y - a.y) * ts[i]};
1434
+ pts[count++] = b;
1435
+ for (int i = 0; i + 1 < count; ++i) {
1436
+ Point p = pts[i], q = pts[i + 1];
1437
+ p.x = std::clamp(p.x, 0.0f, W);
1438
+ q.x = std::clamp(q.x, 0.0f, W);
1439
+ line(p, q, dirFlip_ ? -1.0f : 1.0f);
1440
+ }
1441
+ }
1442
+
1443
+ // Coverage of row `row` (0-based within the rectangle), scaled by `alpha`
1444
+ // (0..1). Between the cells an edge touched the accumulator is empty and the
1445
+ // coverage holds, so the row is a sequence of constant runs, found from the
1446
+ // row's touched-cell bitmap without reading the empty cells at all. A run of
1447
+ // kSpanMin or more pixels goes to `span(x, count, coverage)` -- a fill's
1448
+ // interior is one call -- and the short runs at anti-aliased edges are
1449
+ // gathered into `out` and handed to `emit(x, coverage, count)`. Empty runs
1450
+ // emit nothing, so the hole of a ring or the gap between a wave's crossings
1451
+ // costs nothing downstream. Clears the row's accumulator cells and bitmap.
1452
+ static constexpr int kSpanMin = 8;
1453
+ template <typename Emit, typename Span>
1454
+ GEA_SVG_HOT void row(int row, std::uint8_t *out, bool evenOdd, float alpha, Emit &&emit, Span &&span)
1455
+ {
1456
+ const std::size_t r = static_cast<std::size_t>(row);
1457
+ std::uint32_t *bits = &bits_[r * static_cast<std::size_t>(wpr_)];
1458
+ int *a = &acc_[r * static_cast<std::size_t>(stride_)];
1459
+ const int end = w_; // one past the last pixel
1460
+ const int alpha8 = static_cast<int>(alpha * 256.0f + 0.5f); // 0..256
1461
+ int sum = 0;
1462
+ int runX = -1, runV = 0;
1463
+ int seg = -1, segEnd = 0; // pending short runs, contiguous in `out`
1464
+ auto flush = [&](int from, int to, int v) {
1465
+ if (to > end) to = end;
1466
+ const int n = to - from;
1467
+ if (n <= 0) return;
1468
+ if (n >= kSpanMin) {
1469
+ if (seg >= 0) emit(seg, out + seg, segEnd - seg), seg = -1;
1470
+ if (v) span(from, n, static_cast<std::uint8_t>(v));
1471
+ } else {
1472
+ if (seg < 0) seg = from;
1473
+ for (int i = 0; i < n; ++i) out[from + i] = static_cast<std::uint8_t>(v);
1474
+ segEnd = to;
1475
+ }
1476
+ };
1477
+ for (int w = 0; w < wpr_; ++w) {
1478
+ std::uint32_t m = bits[w];
1479
+ if (!m) continue;
1480
+ bits[w] = 0;
1481
+ do {
1482
+ const int c = (w << 5) + __builtin_ctz(m);
1483
+ m &= m - 1;
1484
+ if (runX >= 0) flush(runX, c, runV);
1485
+ sum += a[c];
1486
+ a[c] = 0;
1487
+ int cov = sum < 0 ? -sum : sum; // 65536 = full
1488
+ if (evenOdd) {
1489
+ cov &= 0x1ffff;
1490
+ if (cov > 0x10000) cov = 0x20000 - cov;
1491
+ } else if (cov > 0x10000) {
1492
+ cov = 0x10000;
1493
+ }
1494
+ // 65536 * 256 overflows nothing: cov <= 2^16, alpha8 <= 2^8.
1495
+ runV = static_cast<int>((static_cast<unsigned>(cov) * static_cast<unsigned>(alpha8) * 255u + (1u << 23)) >> 24);
1496
+ runX = c;
1497
+ } while (m);
1498
+ }
1499
+ // The last touched cell's own pixel; past it the row is empty.
1500
+ if (runX >= 0) flush(runX, runX + 1, runV);
1501
+ if (seg >= 0) emit(seg, out + seg, segEnd - seg);
1502
+ }
1503
+
1504
+ template <typename Emit>
1505
+ void row(int row, std::uint8_t *out, bool evenOdd, float alpha, Emit &&emit)
1506
+ {
1507
+ this->row(row, out, evenOdd, alpha, emit, [&](int x, int n, std::uint8_t v) {
1508
+ std::memset(out + x, v, static_cast<std::size_t>(n));
1509
+ emit(x, out + x, n);
1510
+ });
1511
+ }
1512
+
1513
+ private:
1514
+ // Accumulates a top-to-bottom edge already inside [0,w] x [0,h].
1515
+ // Fixed-point accumulation. Coordinates are in 1/256 px and a fully
1516
+ // covered pixel accumulates 65536. Integer arithmetic is single-cycle on
1517
+ // the MCUs this runs on, where a dependent float multiply-add is ~13
1518
+ // cycles; and each row's contributions sum to exactly d * 256, so a closed
1519
+ // shape's winding always returns to zero (no streaks from rounding).
1520
+ static constexpr int kSub = 256;
1521
+
1522
+ void line(Point p0, Point p1, float dir) { line(p0, p1, dir, (p1.x - p0.x) / (p1.y - p0.y)); }
1523
+ // `dxdy` is the piece's slope, passed in when the caller already has it.
1524
+ GEA_SVG_HOT void line(Point p0, Point p1, float dir, float dxdy)
1525
+ {
1526
+ const int y0s = static_cast<int>(p0.y * kSub + 0.5f);
1527
+ const int y1s = static_cast<int>(p1.y * kSub + 0.5f);
1528
+ if (y1s <= y0s) return;
1529
+ const int sign = dir < 0 ? -1 : 1;
1530
+ const int yStart = y0s >> 8;
1531
+ const int yEnd = std::min(h_, (y1s + kSub - 1) >> 8);
1532
+ const int maxX = w_ * kSub;
1533
+ // x in subpixels at subpixel row s: x0 + dxdy * (s - y0s). Each slice's
1534
+ // bottom is the next slice's top, so one evaluation per row.
1535
+ const float xBase = p0.x * kSub + 0.5f;
1536
+ auto xAt = [&](int s) {
1537
+ const int x = static_cast<int>(xBase + dxdy * static_cast<float>(s - y0s));
1538
+ return x < 0 ? 0 : (x > maxX ? maxX : x);
1539
+ };
1540
+ int xNext = xAt(std::max(y0s, yStart * kSub));
1541
+ for (int y = yStart; y < yEnd; ++y) {
1542
+ int *rowAcc = &acc_[static_cast<std::size_t>(y) * static_cast<std::size_t>(stride_)];
1543
+ const int top = std::max(y0s, y * kSub);
1544
+ const int bottom = std::min(y1s, (y + 1) * kSub);
1545
+ if (bottom <= top) continue;
1546
+ // x at this slice's top and bottom, in subpixels.
1547
+ const int xa = xNext;
1548
+ const int xb = xAt(bottom);
1549
+ xNext = xb;
1550
+ const int d = (bottom - top) * sign; // vertical extent, 1/256 px
1551
+ const int total = d * kSub; // this slice's whole contribution
1552
+ const int x0 = xa < xb ? xa : xb, x1 = xa < xb ? xb : xa;
1553
+ const int x0i = x0 >> 8;
1554
+ const int x1i = (x1 + kSub - 1) >> 8;
1555
+ markCells(&bits_[static_cast<std::size_t>(y) * static_cast<std::size_t>(wpr_)], x0i,
1556
+ x0i + 1 > x1i ? x0i + 1 : x1i);
1557
+ if (x1i <= x0i + 1) {
1558
+ // Within one cell: split by the mean x inside it.
1559
+ const int xmf = ((xa + xb) >> 1) - (x0i << 8);
1560
+ const int right = d * xmf;
1561
+ rowAcc[x0i] += total - right;
1562
+ rowAcc[x0i + 1] += right;
1563
+ } else {
1564
+ const int wsub = x1 - x0;
1565
+ const int x0f = x0 - (x0i << 8);
1566
+ const int x1f = x1 - ((x1i - 1) << 8); // (0, 256]
1567
+ // Divisions by wsub go through its reciprocal (2^24 / wsub): an
1568
+ // integer divide is a multi-cycle instruction on these cores and
1569
+ // a row needed up to four. A straight edge's full rows share one
1570
+ // or two widths (rounding), so the last two are kept. A quotient
1571
+ // may come out one low; the remainder below absorbs it, so every
1572
+ // row still sums to exactly `total`.
1573
+ if (wsub != recipW_[0]) {
1574
+ if (wsub == recipW_[1]) {
1575
+ std::swap(recipW_[0], recipW_[1]);
1576
+ std::swap(recip_[0], recip_[1]);
1577
+ } else {
1578
+ recipW_[1] = recipW_[0];
1579
+ recip_[1] = recip_[0];
1580
+ recipW_[0] = wsub;
1581
+ recip_[0] = (1u << 24) / static_cast<unsigned>(wsub);
1582
+ }
1583
+ }
1584
+ const std::uint64_t rcp = recip_[0];
1585
+ auto div = [rcp](unsigned num, int shift) { return static_cast<int>((num * rcp) >> shift); };
1586
+ // Fractions of `total` per cell, in 1/256 (see the float form:
1587
+ // a0 = s(1-x0f)^2/2, middle cells s, am = s x1f^2/2).
1588
+ const int a0 = div(static_cast<unsigned>((kSub - x0f) * (kSub - x0f)), 25);
1589
+ const int am = div(static_cast<unsigned>(x1f * x1f), 25);
1590
+ int assigned = d * a0;
1591
+ rowAcc[x0i] += assigned;
1592
+ if (x1i == x0i + 2) {
1593
+ const int mid = d * (kSub - a0 - am);
1594
+ rowAcc[x0i + 1] += mid;
1595
+ assigned += mid;
1596
+ } else {
1597
+ const int s = div(static_cast<unsigned>(kSub * kSub), 24);
1598
+ const int a1 = div(static_cast<unsigned>(kSub * (kSub + kSub / 2 - x0f)), 24);
1599
+ const int first = d * (a1 - a0);
1600
+ rowAcc[x0i + 1] += first;
1601
+ assigned += first;
1602
+ const int ds = d * s;
1603
+ for (int xi = x0i + 2; xi < x1i - 1; ++xi) {
1604
+ rowAcc[xi] += ds;
1605
+ assigned += ds;
1606
+ }
1607
+ const int a2 = a1 + (x1i - x0i - 3) * s;
1608
+ const int pen = d * (kSub - a2 - am);
1609
+ rowAcc[x1i - 1] += pen;
1610
+ assigned += pen;
1611
+ }
1612
+ rowAcc[x1i] += total - assigned; // exact remainder
1613
+ }
1614
+ }
1615
+ }
1616
+
1617
+ // Sets cells [lo, hi] in a row's touched-cell bitmap.
1618
+ static void markCells(std::uint32_t *bits, int lo, int hi)
1619
+ {
1620
+ const int wl = lo >> 5, wh = hi >> 5;
1621
+ const std::uint32_t first = ~0u << (lo & 31), last = ~0u >> (31 - (hi & 31));
1622
+ if (wl == wh) {
1623
+ bits[wl] |= first & last;
1624
+ return;
1625
+ }
1626
+ bits[wl] |= first;
1627
+ for (int w = wl + 1; w < wh; ++w) bits[w] = ~0u;
1628
+ bits[wh] |= last;
1629
+ }
1630
+
1631
+ int x0_ = 0, y0_ = 0, w_ = 0, h_ = 0, stride_ = 2, wpr_ = 1;
1632
+ int recipW_[2] = {0, 0};
1633
+ unsigned recip_[2] = {0, 0};
1634
+ bool dirFlip_ = false;
1635
+ // fillCoverage's strip budget (2048 cells) plus the two guard columns of
1636
+ // its tallest strips; the bitmap's worst case is a narrow, tall strip.
1637
+ static constexpr std::size_t kReserveCells = 2048 + 64;
1638
+ static constexpr std::size_t kReserveWords = 256;
1639
+ int accRetry_ = 0, bitsRetry_ = 0;
1640
+ ScratchVector<int> acc_;
1641
+ ScratchVector<std::uint32_t> bits_; // one bit per accumulator cell an edge touched
1642
+ ScratchVector<std::uint32_t> active_;
1643
+ std::size_t nextEdge_ = 0;
1644
+ EdgeList ownEdges_;
1645
+ const EdgeList *edges_ = nullptr;
1646
+ };
1647
+
1648
+ // Rasterizes `edges` over the pixel rectangle [x0,x1) x [y0,y1) in strips
1649
+ // sized to a fixed accumulator budget, calling `span(y, x, count, coverage)`
1650
+ // for each long constant run and `emit(y, x, coverage, count)` for the short
1651
+ // anti-aliased runs between them.
1652
+ template <typename Emit, typename Span>
1653
+ GEA_SVG_HOT inline void fillCoverage(Rasterizer &r, ScratchVector<std::uint8_t> &rowBuf, const EdgeList &edges,
1654
+ int x0, int y0, int x1, int y1, bool evenOdd, float alpha, Emit &&emit, Span &&span)
1655
+ {
1656
+ if (x1 <= x0 || y1 <= y0 || alpha <= 0 || edges.empty()) return;
1657
+ const int width = x1 - x0;
1658
+ constexpr int kBudget = 2048; // accumulator cells per strip (8 KB, internal RAM)
1659
+ const int stripRows = std::max(1, kBudget / (width + 2));
1660
+ rowBuf.resize(static_cast<std::size_t>(width));
1661
+ r.useEdges(edges);
1662
+ r.beginEdgeWalk();
1663
+ for (int sy = y0; sy < y1; sy += stripRows) {
1664
+ const int rows = std::min(stripRows, y1 - sy);
1665
+ r.reset(x0, sy, width, rows);
1666
+ r.addActiveEdges();
1667
+ for (int row = 0; row < rows; ++row) {
1668
+ const int y = sy + row;
1669
+ r.row(
1670
+ row, rowBuf.data(), evenOdd, alpha,
1671
+ [&](int x, const std::uint8_t *cov, int count) { emit(y, x0 + x, cov, count); },
1672
+ [&](int x, int count, std::uint8_t cov) { span(y, x0 + x, count, cov); });
1673
+ }
1674
+ }
1675
+ }
1676
+
1677
+ // Same, with every run delivered as coverage bytes.
1678
+ template <typename Emit>
1679
+ inline void fillCoverage(Rasterizer &r, ScratchVector<std::uint8_t> &rowBuf, const EdgeList &edges,
1680
+ int x0, int y0, int x1, int y1, bool evenOdd, float alpha, Emit &&emit)
1681
+ {
1682
+ std::uint8_t *base = nullptr;
1683
+ fillCoverage(
1684
+ r, rowBuf, edges, x0, y0, x1, y1, evenOdd, alpha,
1685
+ [&](int y, int x, const std::uint8_t *cov, int count) { emit(y, x, cov, count); },
1686
+ [&](int y, int x, int count, std::uint8_t cov) {
1687
+ base = rowBuf.data() + (x - x0);
1688
+ std::memset(base, cov, static_cast<std::size_t>(count));
1689
+ emit(y, x, base, count);
1690
+ });
1691
+ }
1692
+
1693
+ template <typename Emit>
1694
+ inline void fillCoverage(Rasterizer &r, ScratchVector<std::uint8_t> &rowBuf, const std::vector<Contour> &contours,
1695
+ int x0, int y0, int x1, int y1, bool evenOdd, float alpha, Emit &&emit)
1696
+ {
1697
+ EdgeList edges;
1698
+ buildEdges(contours, edges);
1699
+ fillCoverage(r, rowBuf, edges, x0, y0, x1, y1, evenOdd, alpha, emit);
1700
+ }
1701
+
1702
+ } // namespace gea::embedded::ui::svg