@geastack/engine 0.1.20 → 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,1150 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ //
3
+ // Implementation of svg_element.h. Included once, from tree_render.cpp, so
4
+ // every target's existing engine source list builds it with no manifest
5
+ // change. Do not include it anywhere else.
6
+
7
+ #if GEA_UI_SVG
8
+
9
+ #include "svg_element.h"
10
+ #include "svg_geometry.h"
11
+
12
+ #include "display.h"
13
+ #include "internal.h"
14
+ #include "tree_internal.h"
15
+ #include "tree_state.h"
16
+
17
+ #include <algorithm>
18
+ #include <atomic>
19
+ #include <climits>
20
+ #include <cstdio>
21
+ #include <cstring>
22
+ #include <string>
23
+ #include <unordered_map>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #if __has_include("freertos/FreeRTOS.h")
28
+ #include "freertos/FreeRTOS.h"
29
+ #include "freertos/task.h"
30
+ #define GEA_SVG_HAS_FREERTOS 1
31
+ #else
32
+ #define GEA_SVG_HAS_FREERTOS 0
33
+ #endif
34
+ #if __has_include("pico.h")
35
+ #include "pico.h"
36
+ #define GEA_SVG_HAS_PICO 1
37
+ #else
38
+ #define GEA_SVG_HAS_PICO 0
39
+ #endif
40
+
41
+ namespace gea::embedded::ui::svg {
42
+
43
+ namespace {
44
+
45
+ enum class Kind : std::uint8_t { None, Svg, Group, Path, Polyline, Polygon, Line, Circle, Ellipse, Rect, Skip };
46
+
47
+ struct TagIds {
48
+ std::int16_t svg, g, path, polyline, polygon, line, circle, ellipse, rect, defs, title, desc, text;
49
+ };
50
+
51
+ const TagIds &tagIds()
52
+ {
53
+ static const TagIds ids = {internTag("svg"), internTag("g"), internTag("path"), internTag("polyline"),
54
+ internTag("polygon"), internTag("line"), internTag("circle"), internTag("ellipse"),
55
+ internTag("rect"), internTag("defs"), internTag("title"), internTag("desc"),
56
+ internTag("text")};
57
+ return ids;
58
+ }
59
+
60
+ // -2 until the first SVG tag is interned: isRoot is then a single compare that
61
+ // can never match, and the tag table is never touched by apps without <svg>.
62
+ std::int16_t g_svgTag = -2;
63
+
64
+ Kind kindOf(std::int16_t tag)
65
+ {
66
+ if (g_svgTag == -2) return Kind::None;
67
+ const TagIds &t = tagIds();
68
+ if (tag == t.svg) return Kind::Svg;
69
+ if (tag == t.g) return Kind::Group;
70
+ if (tag == t.path) return Kind::Path;
71
+ if (tag == t.polyline) return Kind::Polyline;
72
+ if (tag == t.polygon) return Kind::Polygon;
73
+ if (tag == t.line) return Kind::Line;
74
+ if (tag == t.circle) return Kind::Circle;
75
+ if (tag == t.ellipse) return Kind::Ellipse;
76
+ if (tag == t.rect) return Kind::Rect;
77
+ if (tag == t.defs || tag == t.title || tag == t.desc || tag == t.text) return Kind::Skip;
78
+ return Kind::None;
79
+ }
80
+
81
+ bool isSvgTagName(const char *tag)
82
+ {
83
+ static const char *const names[] = {"svg", "g", "path", "polyline", "polygon", "line", "circle",
84
+ "ellipse", "rect", "defs", "title", "desc", "text"};
85
+ for (const char *n : names)
86
+ if (std::strcmp(tag, n) == 0) return true;
87
+ return false;
88
+ }
89
+
90
+ struct Attrs {
91
+ std::vector<std::pair<std::string, std::string>> values;
92
+ std::uint32_t generation = 0;
93
+ const char *get(const char *name) const
94
+ {
95
+ for (const auto &kv : values)
96
+ if (kv.first == name) return kv.second.c_str();
97
+ return nullptr;
98
+ }
99
+ };
100
+
101
+ struct ResolvedPaint {
102
+ bool on = false;
103
+ gea::framework::graphics::pixel::native_t color = 0;
104
+ float alpha = 1.0f;
105
+ };
106
+
107
+ struct Item {
108
+ int node = -1;
109
+ Path geometry;
110
+ EdgeList fillEdges, strokeEdges; // what paint rasterizes, built once per scene
111
+ ResolvedPaint fill, stroke;
112
+ bool evenOdd = false;
113
+ bool hittable = true;
114
+ float halfStroke = 0.0f;
115
+ Bounds fillBounds, strokeBounds;
116
+ // Everything the geometry and edges depend on (attributes, transform,
117
+ // stroke style): an unchanged item keeps them across scene rebuilds, so a
118
+ // frame that moves one shape re-flattens only that shape.
119
+ std::uint64_t geometryKey = 0;
120
+ // The transform's translation when the geometry was built. The key leaves
121
+ // translation out, so a shape that only moved (a scrolling chart) shifts
122
+ // its edges instead of re-flattening and re-stroking.
123
+ float tx = 0.0f, ty = 0.0f;
124
+ };
125
+
126
+ void translateBounds(Bounds &b, float dx, float dy)
127
+ {
128
+ if (b.empty()) return;
129
+ b.x0 += dx;
130
+ b.x1 += dx;
131
+ b.y0 += dy;
132
+ b.y1 += dy;
133
+ }
134
+
135
+ void translateItem(Item &item, float dx, float dy)
136
+ {
137
+ for (EdgeList *edges : {&item.fillEdges, &item.strokeEdges})
138
+ for (Edge &e : *edges) {
139
+ e.a.x += dx;
140
+ e.a.y += dy;
141
+ e.b.x += dx;
142
+ e.b.y += dy;
143
+ e.top += dy;
144
+ e.bottom += dy;
145
+ }
146
+ for (Contour &c : item.geometry.contours)
147
+ for (Point &p : c) {
148
+ p.x += dx;
149
+ p.y += dy;
150
+ }
151
+ translateBounds(item.fillBounds, dx, dy);
152
+ translateBounds(item.strokeBounds, dx, dy);
153
+ item.tx += dx;
154
+ item.ty += dy;
155
+ }
156
+
157
+ struct Scene {
158
+ bool dirty = true;
159
+ bool recorded = false;
160
+ int width = -1, height = -1;
161
+ std::uint64_t signature = 0;
162
+ std::vector<Item> items;
163
+ // Damage of the last rebuild, in svg-local pixels: the old and new bounds
164
+ // of every item whose geometry or paint changed, and of every item that
165
+ // went away. damageFull asks for the whole box (first build, resize,
166
+ // z-order change, or a change to the svg box itself). Consumed once by
167
+ // refresh's dirty collection through damage().
168
+ bool damageValid = false;
169
+ bool damageFull = true;
170
+ Bounds damage;
171
+ // The svg box as last recorded, to tell a scene-only change apart from a
172
+ // change to the box's own paint (background, border, position).
173
+ bool boxChanged = true;
174
+ bool haveBox = false;
175
+ int boxX = 0, boxY = 0;
176
+ alignas(ComputedStyle) unsigned char boxStyle[sizeof(ComputedStyle)] = {};
177
+ // Where paint splits the box's rows between the two cores, as a fraction
178
+ // of its height, steered each paint toward equal time on both.
179
+ float split = 0.5f;
180
+ };
181
+
182
+ std::unordered_map<int, Attrs> g_attrs;
183
+ std::unordered_map<int, Scene> g_scenes;
184
+
185
+ Tree &tree() { return Tree::instance(); }
186
+
187
+ Kind kindOfNode(int node)
188
+ {
189
+ auto &state = treeState();
190
+ if (node < 0 || node >= state.nodeCount || !state.nodeActive[node]) return Kind::None;
191
+ return kindOf(state.nodes[node].tag_id);
192
+ }
193
+
194
+ int rootOf(int node)
195
+ {
196
+ auto &state = treeState();
197
+ for (int n = node; n >= 0 && n < state.nodeCount; n = state.nodes[n].parent)
198
+ if (state.nodes[n].tag_id == g_svgTag) return n;
199
+ return -1;
200
+ }
201
+
202
+ void invalidateRoot(int root)
203
+ {
204
+ auto it = g_scenes.find(root);
205
+ if (it == g_scenes.end()) return;
206
+ it->second.dirty = true;
207
+ auto &state = treeState();
208
+ Node &n = state.nodes[root];
209
+ tree().markNodeDisplayCommandsDirty(root);
210
+ // A first DrawSvg needs a fresh recording; later ones are replaced in place.
211
+ if (!it->second.recorded) tree().markDisplayListContentDirty();
212
+ n.render.dirty = 1;
213
+ #if GEA_CSS_SCROLLING
214
+ n.render.non_scroll_dirty = 1;
215
+ #endif
216
+ }
217
+
218
+ const char *attr(int node, const char *name)
219
+ {
220
+ auto it = g_attrs.find(node);
221
+ return it == g_attrs.end() ? nullptr : it->second.get(name);
222
+ }
223
+
224
+ float attrLength(int node, const char *name, float fallback)
225
+ {
226
+ float v = fallback;
227
+ const char *s = attr(node, name);
228
+ if (s && parseLength(s, v)) return v;
229
+ return fallback;
230
+ }
231
+
232
+ float attrNumber(int node, const char *name, float fallback)
233
+ {
234
+ const char *s = attr(node, name);
235
+ if (!s) return fallback;
236
+ Scanner sc(s);
237
+ float v = fallback;
238
+ if (!sc.number(v)) return fallback;
239
+ if (*sc.rest() == '%') v /= 100.0f;
240
+ return v;
241
+ }
242
+
243
+ // Inherited paint state while walking the svg subtree.
244
+ struct Context {
245
+ Paint fill{PaintKind::Color, Color{0, 0, 0, 255}};
246
+ Paint stroke{PaintKind::None, Color{}};
247
+ float strokeWidth = 1.0f;
248
+ float fillOpacity = 1.0f, strokeOpacity = 1.0f;
249
+ LineCap cap = LineCap::Butt;
250
+ LineJoin join = LineJoin::Miter;
251
+ float miterLimit = 4.0f;
252
+ bool evenOdd = false;
253
+ bool visible = true;
254
+ bool hittable = true;
255
+ float opacity = 1.0f; // group opacity, folded into each shape
256
+ Matrix matrix;
257
+ };
258
+
259
+ ResolvedPaint resolvePaint(const Paint &paint, const Node &node, float opacity)
260
+ {
261
+ ResolvedPaint out;
262
+ if (paint.kind == PaintKind::None || paint.kind == PaintKind::Unset) return out;
263
+ if (paint.kind == PaintKind::CurrentColor) {
264
+ out.color = static_cast<gea::framework::graphics::pixel::native_t>(node.computedStyle().text_color);
265
+ out.alpha = opacity * node.computedStyle().text_alpha / 255.0f;
266
+ } else {
267
+ out.color = gea::framework::graphics::pixel::nativeColor(paint.color.r, paint.color.g, paint.color.b);
268
+ out.alpha = opacity * paint.color.a / 255.0f;
269
+ }
270
+ out.on = out.alpha > 0.002f;
271
+ return out;
272
+ }
273
+
274
+ void applyNodePaint(int id, const Node &node, Context &ctx)
275
+ {
276
+ // Presentation attributes first; CSS (RareStyle) overrides them.
277
+ if (const char *s = attr(id, "fill")) { const Paint p = parsePaint(s); if (p.kind != PaintKind::Unset) ctx.fill = p; }
278
+ if (const char *s = attr(id, "stroke")) { const Paint p = parsePaint(s); if (p.kind != PaintKind::Unset) ctx.stroke = p; }
279
+ if (const char *s = attr(id, "stroke-width")) { float w; if (parseLength(s, w) && w >= 0) ctx.strokeWidth = w; }
280
+ if (attr(id, "fill-opacity")) ctx.fillOpacity = std::clamp(attrNumber(id, "fill-opacity", 1), 0.0f, 1.0f);
281
+ if (attr(id, "stroke-opacity")) ctx.strokeOpacity = std::clamp(attrNumber(id, "stroke-opacity", 1), 0.0f, 1.0f);
282
+ if (attr(id, "stroke-miterlimit")) ctx.miterLimit = std::max(1.0f, attrNumber(id, "stroke-miterlimit", 4));
283
+ if (const char *s = attr(id, "stroke-linecap")) {
284
+ if (!std::strcmp(s, "round")) ctx.cap = LineCap::Round;
285
+ else if (!std::strcmp(s, "square")) ctx.cap = LineCap::Square;
286
+ else if (!std::strcmp(s, "butt")) ctx.cap = LineCap::Butt;
287
+ }
288
+ if (const char *s = attr(id, "stroke-linejoin")) {
289
+ if (!std::strcmp(s, "round")) ctx.join = LineJoin::Round;
290
+ else if (!std::strcmp(s, "bevel")) ctx.join = LineJoin::Bevel;
291
+ else if (!std::strncmp(s, "miter", 5)) ctx.join = LineJoin::Miter;
292
+ }
293
+ if (const char *s = attr(id, "fill-rule")) ctx.evenOdd = !std::strcmp(s, "evenodd");
294
+ if (const char *s = attr(id, "visibility")) ctx.visible = std::strcmp(s, "hidden") != 0 && std::strcmp(s, "collapse") != 0;
295
+ if (const char *s = attr(id, "pointer-events")) ctx.hittable = std::strcmp(s, "none") != 0;
296
+
297
+ const RareStyle &rare = rstyle(node.computedStyle());
298
+ if (rare.svg_fill) ctx.fill = decodePaint(rare.svg_fill);
299
+ if (rare.svg_stroke) ctx.stroke = decodePaint(rare.svg_stroke);
300
+ if (rare.svg_stroke_width >= 0) ctx.strokeWidth = rare.svg_stroke_width / 100.0f;
301
+ if (rare.svg_fill_opacity >= 0) ctx.fillOpacity = rare.svg_fill_opacity / 1000.0f;
302
+ if (rare.svg_stroke_opacity >= 0) ctx.strokeOpacity = rare.svg_stroke_opacity / 1000.0f;
303
+ if (rare.svg_stroke_linecap >= 0) ctx.cap = static_cast<LineCap>(rare.svg_stroke_linecap);
304
+ if (rare.svg_stroke_linejoin >= 0) ctx.join = static_cast<LineJoin>(rare.svg_stroke_linejoin);
305
+ if (rare.svg_fill_rule >= 0) ctx.evenOdd = rare.svg_fill_rule == 1;
306
+ if (node.computedStyle().visibility != 0) ctx.visible = false;
307
+ if (node.computedStyle().pointer_events == 1) ctx.hittable = false;
308
+ }
309
+
310
+ void buildGeometry(int id, Kind kind, const Matrix &m, Path &out)
311
+ {
312
+ PathBuilder b(out, m, 0.2f);
313
+ switch (kind) {
314
+ case Kind::Path:
315
+ if (const char *d = attr(id, "d")) parsePathData(d, b);
316
+ break;
317
+ case Kind::Polyline:
318
+ case Kind::Polygon:
319
+ if (const char *p = attr(id, "points")) addPoints(b, p, kind == Kind::Polygon);
320
+ break;
321
+ case Kind::Line:
322
+ b.moveTo({attrLength(id, "x1", 0), attrLength(id, "y1", 0)});
323
+ b.lineTo({attrLength(id, "x2", 0), attrLength(id, "y2", 0)});
324
+ b.finish();
325
+ break;
326
+ case Kind::Circle: {
327
+ const float r = attrLength(id, "r", 0);
328
+ addEllipse(b, attrLength(id, "cx", 0), attrLength(id, "cy", 0), r, r);
329
+ break;
330
+ }
331
+ case Kind::Ellipse: {
332
+ float rx = attrLength(id, "rx", -1), ry = attrLength(id, "ry", -1);
333
+ if (rx < 0) rx = ry;
334
+ if (ry < 0) ry = rx;
335
+ addEllipse(b, attrLength(id, "cx", 0), attrLength(id, "cy", 0), rx, ry);
336
+ break;
337
+ }
338
+ case Kind::Rect: {
339
+ float rx = attrLength(id, "rx", -1), ry = attrLength(id, "ry", -1);
340
+ if (rx < 0) rx = ry;
341
+ if (ry < 0) ry = rx;
342
+ addRect(b, attrLength(id, "x", 0), attrLength(id, "y", 0), attrLength(id, "width", 0),
343
+ attrLength(id, "height", 0), std::max(rx, 0.0f), std::max(ry, 0.0f));
344
+ break;
345
+ }
346
+ default:
347
+ break;
348
+ }
349
+ }
350
+
351
+ std::uint64_t mixKey(std::uint64_t h, std::uint64_t v)
352
+ {
353
+ h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
354
+ return h;
355
+ }
356
+
357
+ std::uint64_t floatBits(float f)
358
+ {
359
+ std::uint32_t u;
360
+ std::memcpy(&u, &f, sizeof(u));
361
+ return u;
362
+ }
363
+
364
+ // The previous scene's items, consumed as the new scene reuses them.
365
+ bool samePaint(const ResolvedPaint &a, const ResolvedPaint &b)
366
+ {
367
+ return a.on == b.on && (!a.on || (a.color == b.color && a.alpha == b.alpha));
368
+ }
369
+
370
+ // Everything an item can touch on screen, in svg-local pixels.
371
+ void addItemDamage(Bounds &damage, const Item &item)
372
+ {
373
+ constexpr float kAntialias = 2.0f;
374
+ for (const Bounds *b : {&item.fillBounds, &item.strokeBounds}) {
375
+ if (b->empty()) continue;
376
+ damage.add(Point{b->x0 - kAntialias, b->y0 - kAntialias});
377
+ damage.add(Point{b->x1 + kAntialias, b->y1 + kAntialias});
378
+ }
379
+ }
380
+
381
+ // The previous scene's items, consumed as the new scene reuses them; also
382
+ // accumulates the rebuild's damage.
383
+ struct ItemCache {
384
+ std::vector<Item> *items = nullptr;
385
+ std::size_t hint = 0;
386
+ long lastTaken = -1;
387
+ bool full = false;
388
+ Bounds damage;
389
+ Item *take(int node, std::uint64_t key)
390
+ {
391
+ if (!items) return nullptr;
392
+ const std::size_t n = items->size();
393
+ for (std::size_t k = 0; k < n; ++k) {
394
+ const std::size_t index = (hint + k) % n;
395
+ Item &it = (*items)[index];
396
+ if (it.node == node) {
397
+ hint = (index + 1) % n;
398
+ if (it.geometryKey != key) return nullptr;
399
+ // A reused item that moved below one drawn after it changes the
400
+ // stacking of unchanged pixels: repaint everything.
401
+ if (static_cast<long>(index) < lastTaken) full = true;
402
+ lastTaken = static_cast<long>(index);
403
+ return &it;
404
+ }
405
+ }
406
+ return nullptr;
407
+ }
408
+ // The previous item of `node` whose geometry changed: its edge buffers are
409
+ // handed to the rebuilt item, so a shape that changes every frame reuses
410
+ // its allocations instead of regrowing them. Its bounds stay for finish().
411
+ Item *stale(int node)
412
+ {
413
+ if (!items) return nullptr;
414
+ for (Item &it : *items)
415
+ if (it.node == node) return &it;
416
+ return nullptr;
417
+ }
418
+ // Old items nobody reused (removed, hidden or rebuilt) leave damage behind.
419
+ void finish()
420
+ {
421
+ if (!items) return;
422
+ for (const Item &it : *items)
423
+ if (it.node >= 0) addItemDamage(damage, it);
424
+ }
425
+ };
426
+
427
+ void walk(int id, const Context &parent, std::vector<Item> &items, ItemCache &cache)
428
+ {
429
+ const auto &state = treeState();
430
+ const Node &node = state.nodes[id];
431
+ const Kind kind = kindOf(node.tag_id);
432
+ if (kind == Kind::None || kind == Kind::Skip) return;
433
+ if (node.computedStyle().display == kDisplayNone) return;
434
+ if (const char *d = attr(id, "display"); d && !std::strcmp(d, "none")) return;
435
+ Context ctx = parent;
436
+ applyNodePaint(id, node, ctx);
437
+ if (kind != Kind::Svg) {
438
+ Matrix local;
439
+ if (const char *t = attr(id, "transform")) parseTransform(t, local);
440
+ ctx.matrix = ctx.matrix * local;
441
+ float opacity = std::clamp(attrNumber(id, "opacity", 1), 0.0f, 1.0f);
442
+ opacity *= node.computedStyle().opacity / 255.0f;
443
+ ctx.opacity *= opacity;
444
+ }
445
+ if (kind != Kind::Svg && kind != Kind::Group) {
446
+ if (!ctx.visible || ctx.opacity <= 0) return;
447
+ const ResolvedPaint fill =
448
+ kind == Kind::Line ? ResolvedPaint{} : resolvePaint(ctx.fill, node, ctx.opacity * ctx.fillOpacity);
449
+ const ResolvedPaint stroke = resolvePaint(ctx.stroke, node, ctx.opacity * ctx.strokeOpacity);
450
+ const float width = ctx.strokeWidth * ctx.matrix.scale();
451
+ const bool stroked = stroke.on && width > 0;
452
+ auto it = g_attrs.find(id);
453
+ std::uint64_t key = mixKey(0x51ed27ull, (static_cast<std::uint64_t>(id) << 32) |
454
+ (it == g_attrs.end() ? 0u : it->second.generation));
455
+ key = mixKey(key, static_cast<std::uint16_t>(node.tag_id));
456
+ for (float f : {ctx.matrix.a, ctx.matrix.b, ctx.matrix.c, ctx.matrix.d})
457
+ key = mixKey(key, floatBits(f));
458
+ key = mixKey(key, static_cast<std::uint64_t>(fill.on) | static_cast<std::uint64_t>(stroked) << 1 |
459
+ static_cast<std::uint64_t>(ctx.evenOdd) << 2);
460
+ if (stroked)
461
+ key = mixKey(key, floatBits(width) | static_cast<std::uint64_t>(ctx.cap) << 32 |
462
+ static_cast<std::uint64_t>(ctx.join) << 40);
463
+ if (stroked && ctx.join == LineJoin::Miter) key = mixKey(key, floatBits(ctx.miterLimit));
464
+ if (Item *cached = cache.take(id, key)) {
465
+ Item item = std::move(*cached);
466
+ cached->node = -1;
467
+ const float dx = ctx.matrix.e - item.tx, dy = ctx.matrix.f - item.ty;
468
+ if (dx != 0.0f || dy != 0.0f) {
469
+ addItemDamage(cache.damage, item); // where it was
470
+ translateItem(item, dx, dy);
471
+ addItemDamage(cache.damage, item); // where it is
472
+ } else if (!samePaint(item.fill, fill) || !samePaint(item.stroke, stroke)) {
473
+ addItemDamage(cache.damage, item);
474
+ }
475
+ item.fill = fill;
476
+ item.stroke = stroke;
477
+ item.hittable = ctx.hittable;
478
+ if (item.strokeEdges.empty() && !item.fill.on && !item.hittable) return;
479
+ items.push_back(std::move(item));
480
+ return;
481
+ }
482
+ Item item;
483
+ if (Item *old = cache.stale(id)) {
484
+ item.fillEdges.swap(old->fillEdges);
485
+ item.strokeEdges.swap(old->strokeEdges);
486
+ item.fillEdges.clear();
487
+ item.strokeEdges.clear();
488
+ }
489
+ item.node = id;
490
+ item.geometryKey = key;
491
+ item.tx = ctx.matrix.e;
492
+ item.ty = ctx.matrix.f;
493
+ buildGeometry(id, kind, ctx.matrix, item.geometry);
494
+ if (item.geometry.empty()) return;
495
+ item.fill = fill;
496
+ item.stroke = stroke;
497
+ item.evenOdd = ctx.evenOdd;
498
+ item.hittable = ctx.hittable;
499
+ if (stroked) {
500
+ StrokeStyle style;
501
+ style.width = width;
502
+ style.cap = ctx.cap;
503
+ style.join = ctx.join;
504
+ style.miterLimit = ctx.miterLimit;
505
+ // The stroke outline only feeds the rasterizer (hit testing measures
506
+ // distance to the path), so it goes straight to edges.
507
+ strokePathEdges(item.geometry, style, item.strokeEdges, item.strokeBounds);
508
+ item.halfStroke = width / 2;
509
+ }
510
+ if (item.fill.on) {
511
+ item.fillBounds.add(item.geometry.contours);
512
+ buildEdges(item.geometry.contours, item.fillEdges);
513
+ }
514
+ if (item.strokeEdges.empty() && !item.fill.on && !item.hittable) return;
515
+ addItemDamage(cache.damage, item);
516
+ items.push_back(std::move(item));
517
+ return;
518
+ }
519
+ for (int child = node.first_child; child >= 0; child = state.nodes[child].next_sibling) walk(child, ctx, items, cache);
520
+ }
521
+
522
+ void buildScene(int root, Scene &scene, int width, int height)
523
+ {
524
+ std::vector<Item> previous = std::move(scene.items);
525
+ scene.items.clear();
526
+ ItemCache cache;
527
+ // A resized viewport changes every matrix, so nothing would match anyway.
528
+ if (scene.width == width && scene.height == height) cache.items = &previous;
529
+ scene.width = width;
530
+ scene.height = height;
531
+ Context ctx;
532
+ float vb[4];
533
+ if (const char *v = attr(root, "viewBox"); v && parseNumberList(v, vb, 4))
534
+ ctx.matrix = viewBoxTransform(vb, static_cast<float>(width), static_cast<float>(height), attr(root, "preserveAspectRatio"));
535
+ walk(root, ctx, scene.items, cache);
536
+ cache.finish();
537
+ scene.dirty = false;
538
+ scene.damageValid = true;
539
+ scene.damageFull = !cache.items || cache.full;
540
+ scene.damage = cache.damage;
541
+ }
542
+
543
+ std::uint64_t mix(std::uint64_t h, std::uint64_t v)
544
+ {
545
+ h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
546
+ return h;
547
+ }
548
+
549
+ std::uint64_t subtreeSignature(int root)
550
+ {
551
+ const auto &state = treeState();
552
+ std::uint64_t h = 0xcbf29ce484222325ull;
553
+ auto visit = [&](auto &&self, int id) -> void {
554
+ const Node &n = state.nodes[id];
555
+ const auto &s = n.computedStyle();
556
+ const RareStyle &r = rstyle(s);
557
+ h = mix(h, static_cast<std::uint64_t>(id) << 16 | static_cast<std::uint16_t>(n.tag_id));
558
+ auto it = g_attrs.find(id);
559
+ h = mix(h, it == g_attrs.end() ? 0 : it->second.generation);
560
+ h = mix(h, static_cast<std::uint32_t>(r.svg_fill));
561
+ h = mix(h, static_cast<std::uint32_t>(r.svg_stroke));
562
+ h = mix(h, static_cast<std::uint32_t>(r.svg_stroke_width));
563
+ h = mix(h, static_cast<std::uint64_t>(static_cast<std::uint16_t>(r.svg_fill_opacity)) << 16 |
564
+ static_cast<std::uint16_t>(r.svg_stroke_opacity));
565
+ h = mix(h, static_cast<std::uint64_t>(static_cast<std::uint8_t>(r.svg_stroke_linecap)) << 16 |
566
+ static_cast<std::uint64_t>(static_cast<std::uint8_t>(r.svg_stroke_linejoin)) << 8 |
567
+ static_cast<std::uint8_t>(r.svg_fill_rule));
568
+ h = mix(h, static_cast<std::uint64_t>(s.text_color));
569
+ h = mix(h, static_cast<std::uint64_t>(s.text_alpha) << 24 | static_cast<std::uint64_t>(s.opacity) << 16 |
570
+ static_cast<std::uint64_t>(static_cast<std::uint8_t>(s.display)) << 8 |
571
+ static_cast<std::uint64_t>(static_cast<std::uint8_t>(s.visibility)) << 4 |
572
+ static_cast<std::uint8_t>(s.pointer_events));
573
+ if (id != root && kindOf(n.tag_id) == Kind::Svg) return; // nested svg: its own scene
574
+ for (int c = n.first_child; c >= 0; c = state.nodes[c].next_sibling) self(self, c);
575
+ };
576
+ visit(visit, root);
577
+ return h;
578
+ }
579
+
580
+ inline int scratchBank()
581
+ {
582
+ #if GEA_SVG_HAS_FREERTOS
583
+ return xPortGetCoreID() & 1;
584
+ #elif GEA_SVG_HAS_PICO
585
+ return get_core_num() & 1;
586
+ #else
587
+ return 0;
588
+ #endif
589
+ }
590
+
591
+ // Scratch bank of the svg paint worker (banks 0/1 belong to the two cores'
592
+ // inline paints, which may run at once when the renderer splits a region).
593
+ constexpr int kWorkerBank = 2;
594
+
595
+ #if GEA_SVG_HAS_FREERTOS && !CONFIG_FREERTOS_UNICORE
596
+ #define GEA_SVG_PARALLEL_PAINT 1
597
+ #if __has_include("esp_cpu.h")
598
+ #include "esp_cpu.h"
599
+ inline unsigned svgPaintCycles() { return esp_cpu_get_cycle_count(); }
600
+ #else
601
+ // No cycle counter: the split stays at the middle.
602
+ inline unsigned svgPaintCycles() { return 0; }
603
+ #endif
604
+ // One svg's rows split across both cores: the frame core paints the top half
605
+ // while this worker, pinned to the other core, paints the bottom half. It owns
606
+ // its own task (never the display's row worker, whose single job slot may be
607
+ // in flight around us) and its own scratch bank; only the core that created
608
+ // it submits, and only when idle, so a paint that is itself running in a
609
+ // band on the second core simply paints inline.
610
+ struct PaintWorker {
611
+ TaskHandle_t task = nullptr;
612
+ int ownerCore = -1;
613
+ bool attempted = false;
614
+ std::atomic<bool> busy{false};
615
+ std::atomic<bool> done{true};
616
+ void (*fn)(void *, int, int) = nullptr;
617
+ void *ctx = nullptr;
618
+ int y0 = 0, y1 = -1;
619
+ };
620
+ PaintWorker g_paintWorker;
621
+
622
+ void paintWorkerTask(void *)
623
+ {
624
+ for (;;) {
625
+ ulTaskNotifyTake(pdTRUE, portMAX_DELAY);
626
+ g_paintWorker.fn(g_paintWorker.ctx, g_paintWorker.y0, g_paintWorker.y1);
627
+ g_paintWorker.done.store(true, std::memory_order_release);
628
+ }
629
+ }
630
+
631
+ bool paintWorkerSubmit(void (*fn)(void *, int, int), void *ctx, int y0, int y1)
632
+ {
633
+ const int core = static_cast<int>(xPortGetCoreID());
634
+ if (!g_paintWorker.attempted) {
635
+ g_paintWorker.attempted = true;
636
+ g_paintWorker.ownerCore = core;
637
+ // The stack holds only locals (scratch rows live on the heap), so it
638
+ // may sit in PSRAM: internal RAM is the scarce pool on these parts.
639
+ if (xTaskCreatePinnedToCoreWithCaps(paintWorkerTask, "gea_svg", 6144, nullptr, uxTaskPriorityGet(nullptr),
640
+ &g_paintWorker.task, core == 0 ? 1 : 0,
641
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS &&
642
+ xTaskCreatePinnedToCore(paintWorkerTask, "gea_svg", 6144, nullptr, uxTaskPriorityGet(nullptr),
643
+ &g_paintWorker.task, core == 0 ? 1 : 0) != pdPASS)
644
+ g_paintWorker.task = nullptr;
645
+ }
646
+ if (!g_paintWorker.task || core != g_paintWorker.ownerCore) return false;
647
+ if (g_paintWorker.busy.exchange(true, std::memory_order_acq_rel)) return false;
648
+ g_paintWorker.fn = fn;
649
+ g_paintWorker.ctx = ctx;
650
+ g_paintWorker.y0 = y0;
651
+ g_paintWorker.y1 = y1;
652
+ g_paintWorker.done.store(false, std::memory_order_release);
653
+ xTaskNotifyGive(g_paintWorker.task);
654
+ return true;
655
+ }
656
+
657
+ void paintWorkerWait()
658
+ {
659
+ while (!g_paintWorker.done.load(std::memory_order_acquire)) {
660
+ }
661
+ g_paintWorker.busy.store(false, std::memory_order_release);
662
+ }
663
+ #else
664
+ #define GEA_SVG_PARALLEL_PAINT 0
665
+ #endif
666
+
667
+ // Blends a shape's coverage straight into the canvas rows. The rasterizer
668
+ // hands over many short runs per row (every anti-aliased edge is one), so each
669
+ // run is blended here, inline, into a row pointer fetched once per row: on an
670
+ // ESP32-S3 one canvas call costs ~250 cycles before it touches a pixel, more
671
+ // than a typical edge run. Rows the canvas cannot expose directly (rotated,
672
+ // packed, global alpha) go through its per-run entry points instead. Dirty
673
+ // marking is one box for the whole shape.
674
+ struct RowSink {
675
+ using Pixel = gea::framework::graphics::pixel::native_t;
676
+ gea::framework::graphics::Canvas *canvas;
677
+ Pixel color;
678
+ int ox, oy;
679
+ int rowY = INT_MIN;
680
+ Pixel *row = nullptr;
681
+ int cx0 = 0, cx1 = -1;
682
+ int dx0 = INT_MAX, dy0 = INT_MAX, dx1 = INT_MIN, dy1 = INT_MIN;
683
+ Pixel lastBg = 0, lastOut = 0;
684
+ int lastA = -1;
685
+
686
+ bool select(int y)
687
+ {
688
+ if (y != rowY) {
689
+ rowY = y;
690
+ row = canvas->directRow(y, &cx0, &cx1);
691
+ }
692
+ return row != nullptr;
693
+ }
694
+ void touched(int y, int a, int b)
695
+ {
696
+ if (a < dx0) dx0 = a;
697
+ if (b > dx1) dx1 = b;
698
+ if (y < dy0) dy0 = y;
699
+ if (y > dy1) dy1 = y;
700
+ }
701
+ Pixel blendOne(Pixel bg, int a)
702
+ {
703
+ if (bg != lastBg || a != lastA) {
704
+ lastBg = bg;
705
+ lastA = a;
706
+ lastOut = gea::framework::graphics::pixel::blendNative(color, bg, a);
707
+ }
708
+ return lastOut;
709
+ }
710
+ void span(int y, int x, int count, std::uint8_t cov)
711
+ {
712
+ y += oy;
713
+ x += ox;
714
+ if (!select(y)) {
715
+ canvas->blendCoverageSpan(y, x, count, cov, color, false);
716
+ touched(y, x, x + count - 1);
717
+ return;
718
+ }
719
+ const int a = std::max(x, cx0), b = std::min(x + count - 1, cx1);
720
+ if (a > b) return;
721
+ Pixel *p = row + a;
722
+ const int n = b - a + 1;
723
+ if (cov == 255) {
724
+ std::fill_n(p, n, color);
725
+ } else {
726
+ for (int i = 0; i < n; ++i) p[i] = blendOne(p[i], cov);
727
+ }
728
+ touched(y, a, b);
729
+ }
730
+ void coverage(int y, int x, const std::uint8_t *cov, int count)
731
+ {
732
+ y += oy;
733
+ x += ox;
734
+ if (!select(y)) {
735
+ canvas->blendCoverageRow(y, x, count, cov, color, false);
736
+ touched(y, x, x + count - 1);
737
+ return;
738
+ }
739
+ int a = x, b = x + count - 1;
740
+ if (a < cx0) a = cx0;
741
+ if (b > cx1) b = cx1;
742
+ if (a > b) return;
743
+ for (int px = a; px <= b; ++px) {
744
+ const int c = cov[px - x];
745
+ if (c == 0) continue;
746
+ row[px] = c == 255 ? color : blendOne(row[px], c);
747
+ }
748
+ touched(y, a, b);
749
+ }
750
+ void markDirty()
751
+ {
752
+ if (dx0 <= dx1 && dy0 <= dy1) canvas->markDirty(dx0, dy0, dx1, dy1);
753
+ }
754
+ };
755
+
756
+ GEA_SVG_HOT void paintCoverage(gea::framework::graphics::Canvas *canvas, int bank, bool markDirty, const EdgeList &edges,
757
+ const Bounds &bounds, bool evenOdd, const ResolvedPaint &paint, int ox, int oy, int cx0, int cy0,
758
+ int cx1, int cy1)
759
+ {
760
+ if (!canvas || bounds.empty()) return;
761
+ // Pixel rectangle in svg-local coordinates, clipped to the canvas clip.
762
+ const int x0 = std::max(static_cast<int>(std::floor(bounds.x0)) - 1, cx0 - ox);
763
+ const int y0 = std::max(static_cast<int>(std::floor(bounds.y0)) - 1, cy0 - oy);
764
+ const int x1 = std::min(static_cast<int>(std::ceil(bounds.x1)) + 1, cx1 - ox);
765
+ const int y1 = std::min(static_cast<int>(std::ceil(bounds.y1)) + 1, cy1 - oy);
766
+ // One scratch bank per core: a large dirty region replays in two bands on
767
+ // both cores at once (canvas.cpp's occlusion banks follow the same rule).
768
+ static Rasterizer rasters[3];
769
+ static ScratchVector<std::uint8_t> rows[3];
770
+ Rasterizer &raster = rasters[bank];
771
+ ScratchVector<std::uint8_t> &row = rows[bank];
772
+ RowSink sink{canvas, paint.color, ox, oy};
773
+ fillCoverage(
774
+ raster, row, edges, x0, y0, x1, y1, evenOdd, std::min(1.0f, paint.alpha),
775
+ [&](int y, int x, const std::uint8_t *cov, int count) { sink.coverage(y, x, cov, count); },
776
+ [&](int y, int x, int count, std::uint8_t cov) { sink.span(y, x, count, cov); });
777
+ if (markDirty) sink.markDirty();
778
+ }
779
+
780
+ } // namespace
781
+
782
+ bool cssDeclarationValue(StyleDeclaration declaration, const char *value, Property &property, int &encoded)
783
+ {
784
+ if (!value) return false;
785
+ while (*value == ' ' || *value == '\t') ++value;
786
+ std::string v(value);
787
+ if (const auto bang = v.find("!important"); bang != std::string::npos) v.erase(bang);
788
+ while (!v.empty() && (v.back() == ' ' || v.back() == '\t')) v.pop_back();
789
+ auto lower = v;
790
+ for (char &c : lower) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
791
+ // CSS-wide keywords reset to "unset" (inherit through the svg tree).
792
+ const bool wide = lower == "inherit" || lower == "unset" || lower == "initial" || lower == "revert";
793
+ switch (declaration) {
794
+ case StyleDeclaration::SvgFill:
795
+ case StyleDeclaration::SvgStroke: {
796
+ property = declaration == StyleDeclaration::SvgFill ? Property::SvgFill : Property::SvgStroke;
797
+ if (wide) { encoded = 0; return true; }
798
+ const Paint paint = parsePaint(v.c_str());
799
+ if (paint.kind == PaintKind::Unset) return false;
800
+ encoded = encodePaint(paint);
801
+ return true;
802
+ }
803
+ case StyleDeclaration::SvgStrokeWidth: {
804
+ property = Property::SvgStrokeWidth;
805
+ if (wide) { encoded = -1; return true; }
806
+ float w = 0;
807
+ if (!parseLength(v.c_str(), w) || w < 0) return false;
808
+ encoded = static_cast<int>(std::lround(w * 100));
809
+ return true;
810
+ }
811
+ case StyleDeclaration::SvgFillOpacity:
812
+ case StyleDeclaration::SvgStrokeOpacity: {
813
+ property = declaration == StyleDeclaration::SvgFillOpacity ? Property::SvgFillOpacity : Property::SvgStrokeOpacity;
814
+ if (wide) { encoded = -1; return true; }
815
+ Scanner sc(v.c_str());
816
+ float o = 1;
817
+ if (!sc.number(o)) return false;
818
+ if (*sc.rest() == '%') o /= 100.0f;
819
+ encoded = static_cast<int>(std::lround(std::clamp(o, 0.0f, 1.0f) * 1000));
820
+ return true;
821
+ }
822
+ case StyleDeclaration::SvgStrokeLinecap:
823
+ property = Property::SvgStrokeLinecap;
824
+ if (wide) encoded = -1;
825
+ else if (lower == "butt") encoded = static_cast<int>(LineCap::Butt);
826
+ else if (lower == "round") encoded = static_cast<int>(LineCap::Round);
827
+ else if (lower == "square") encoded = static_cast<int>(LineCap::Square);
828
+ else return false;
829
+ return true;
830
+ case StyleDeclaration::SvgStrokeLinejoin:
831
+ property = Property::SvgStrokeLinejoin;
832
+ if (wide) encoded = -1;
833
+ else if (lower == "miter" || lower == "miter-clip" || lower == "arcs") encoded = static_cast<int>(LineJoin::Miter);
834
+ else if (lower == "round") encoded = static_cast<int>(LineJoin::Round);
835
+ else if (lower == "bevel") encoded = static_cast<int>(LineJoin::Bevel);
836
+ else return false;
837
+ return true;
838
+ case StyleDeclaration::SvgFillRule:
839
+ property = Property::SvgFillRule;
840
+ if (wide) encoded = -1;
841
+ else if (lower == "nonzero") encoded = 0;
842
+ else if (lower == "evenodd") encoded = 1;
843
+ else return false;
844
+ return true;
845
+ default:
846
+ return false;
847
+ }
848
+ }
849
+
850
+ bool isRoot(const Node &node) { return node.tag_id == g_svgTag; }
851
+
852
+ bool damage(int root, int &x0, int &y0, int &x1, int &y1)
853
+ {
854
+ auto it = g_scenes.find(root);
855
+ if (it == g_scenes.end()) return false;
856
+ Scene &scene = it->second;
857
+ const bool valid = scene.damageValid && !scene.damageFull && !scene.boxChanged;
858
+ scene.damageValid = false;
859
+ if (!valid) return false;
860
+ if (scene.damage.empty()) {
861
+ x0 = y0 = 0;
862
+ x1 = y1 = -1;
863
+ return true;
864
+ }
865
+ x0 = std::max(0, static_cast<int>(std::floor(scene.damage.x0)));
866
+ y0 = std::max(0, static_cast<int>(std::floor(scene.damage.y0)));
867
+ x1 = std::min(scene.width - 1, static_cast<int>(std::ceil(scene.damage.x1)));
868
+ y1 = std::min(scene.height - 1, static_cast<int>(std::ceil(scene.damage.y1)));
869
+ if (x0 > x1 || y0 > y1) x0 = y0 = 0, x1 = y1 = -1;
870
+ return true;
871
+ }
872
+
873
+ bool isShape(int node)
874
+ {
875
+ if (g_svgTag == -2) return false;
876
+ const Kind kind = kindOfNode(node);
877
+ return kind != Kind::None && kind != Kind::Svg;
878
+ }
879
+
880
+ void noteTagChanged(int node)
881
+ {
882
+ auto &state = treeState();
883
+ if (node < 0 || node >= state.nodeCount) return;
884
+ if (g_svgTag == -2) {
885
+ // Intern the SVG tag set only once an SVG tag actually appears.
886
+ if (!isSvgTagName(tagFromId(state.nodes[node].tag_id))) return;
887
+ g_svgTag = tagIds().svg;
888
+ }
889
+ const Kind kind = kindOf(state.nodes[node].tag_id);
890
+ if (kind == Kind::None) {
891
+ g_scenes.erase(node);
892
+ return;
893
+ }
894
+ if (kind == Kind::Svg) {
895
+ g_scenes[node];
896
+ return;
897
+ }
898
+ // Shapes, groups and metadata take no part in CSS layout: out of flow, no
899
+ // box. Inline (not default) styles, so this holds in every build.
900
+ tree().setStyle(node, Property::Position, 1);
901
+ tree().setStyle(node, Property::Width, 0);
902
+ tree().setStyle(node, Property::Height, 0);
903
+ }
904
+
905
+ bool noteAttribute(int node, const char *name, const char *value)
906
+ {
907
+ if (!name || kindOfNode(node) == Kind::None) return false;
908
+ Attrs &attrs = g_attrs[node];
909
+ auto it = std::find_if(attrs.values.begin(), attrs.values.end(), [&](const auto &kv) { return kv.first == name; });
910
+ if (value) {
911
+ if (it != attrs.values.end()) {
912
+ if (it->second == value) return true;
913
+ it->second = value;
914
+ } else {
915
+ attrs.values.emplace_back(name, value);
916
+ }
917
+ } else if (it != attrs.values.end()) {
918
+ attrs.values.erase(it);
919
+ } else {
920
+ return true;
921
+ }
922
+ // Globally unique, so a reused node id never matches a stale cached item.
923
+ static std::uint32_t serial = 0;
924
+ attrs.generation = ++serial;
925
+ if (kindOfNode(node) == Kind::Svg && (!std::strcmp(name, "width") || !std::strcmp(name, "height"))) {
926
+ // The width/height attributes size the svg box at presentational
927
+ // (lowest) priority: any authored CSS width/height wins.
928
+ float px = 0;
929
+ const bool w = name[0] == 'w';
930
+ const Property p = w ? Property::Width : Property::Height;
931
+ if (value && parseLength(value, px)) {
932
+ // CSS px, like any authored width/height: scaled to device pixels.
933
+ const int device = static_cast<int>(std::lround(px * devicePixelRatio()));
934
+ #if GEA_UI_DEFAULT_STYLES
935
+ tree().setDefaultStyle(node, p, device);
936
+ #else
937
+ tree().setStyle(node, p, device);
938
+ #endif
939
+ }
940
+ }
941
+ noteNodeChanged(node);
942
+ return true;
943
+ }
944
+
945
+ const char *attribute(int node, const char *name) { return name ? attr(node, name) : nullptr; }
946
+
947
+ void noteNodeChanged(int node)
948
+ {
949
+ const int root = rootOf(node);
950
+ if (root >= 0) invalidateRoot(root);
951
+ }
952
+
953
+ void releaseNode(int node)
954
+ {
955
+ if (g_svgTag == -2) return;
956
+ g_attrs.erase(node);
957
+ g_scenes.erase(node);
958
+ }
959
+
960
+ void clearAll()
961
+ {
962
+ g_attrs.clear();
963
+ g_scenes.clear();
964
+ }
965
+
966
+ void validateScenes()
967
+ {
968
+ if (g_scenes.empty()) return;
969
+ auto &state = treeState();
970
+ for (auto it = g_scenes.begin(); it != g_scenes.end();) {
971
+ const int root = it->first;
972
+ if (root >= state.nodeCount || !state.nodeActive[root] || state.nodes[root].tag_id != g_svgTag) {
973
+ it = g_scenes.erase(it);
974
+ continue;
975
+ }
976
+ const std::uint64_t sig = subtreeSignature(root);
977
+ if (sig != it->second.signature) {
978
+ it->second.signature = sig;
979
+ if (it->second.recorded) invalidateRoot(root);
980
+ else it->second.dirty = true;
981
+ }
982
+ ++it;
983
+ }
984
+ #if GEA_SVG_PARALLEL_PAINT
985
+ // Rebuild the changed scenes across both cores now, before the display
986
+ // list records them (record() then finds them built). Building reads the
987
+ // tree, attributes and styles, which nothing mutates during a refresh, and
988
+ // writes only its own scene. Each scene goes to the less loaded core,
989
+ // weighed by its previous edge count; the heaviest go first.
990
+ struct Job {
991
+ int root;
992
+ Scene *scene;
993
+ std::size_t weight;
994
+ };
995
+ Job jobs[16];
996
+ int count = 0;
997
+ for (auto &[root, scene] : g_scenes) {
998
+ if (!scene.dirty || scene.width <= 0 || count == 16) continue;
999
+ const Node &n = state.nodes[root];
1000
+ if (n.layout.width != scene.width || n.layout.height != scene.height) continue;
1001
+ std::size_t weight = 1;
1002
+ for (const Item &item : scene.items) weight += item.fillEdges.size() + item.strokeEdges.size();
1003
+ jobs[count++] = {root, &scene, weight};
1004
+ }
1005
+ if (count < 2) return;
1006
+ std::sort(jobs, jobs + count, [](const Job &a, const Job &b) { return a.weight > b.weight; });
1007
+ Job mine[16], theirs[16];
1008
+ int nMine = 0, nTheirs = 0;
1009
+ std::size_t loadMine = 0, loadTheirs = 0;
1010
+ for (int i = 0; i < count; ++i) {
1011
+ if (loadMine <= loadTheirs) mine[nMine++] = jobs[i], loadMine += jobs[i].weight;
1012
+ else theirs[nTheirs++] = jobs[i], loadTheirs += jobs[i].weight;
1013
+ }
1014
+ auto build = [](void *p, int, int count) {
1015
+ const Job *list = static_cast<const Job *>(p);
1016
+ for (int i = 0; i < count; ++i) buildScene(list[i].root, *list[i].scene, list[i].scene->width, list[i].scene->height);
1017
+ };
1018
+ const bool split = nTheirs > 0 && paintWorkerSubmit(build, theirs, 0, nTheirs);
1019
+ build(mine, 0, nMine);
1020
+ if (split) paintWorkerWait();
1021
+ else build(theirs, 0, nTheirs);
1022
+ #endif
1023
+ }
1024
+
1025
+ void record(const Node &node)
1026
+ {
1027
+ const int id = static_cast<int>(&node - tree().nodes());
1028
+ auto it = g_scenes.find(id);
1029
+ if (it == g_scenes.end()) it = g_scenes.emplace(id, Scene{}).first;
1030
+ Scene &scene = it->second;
1031
+ if (node.layout.width <= 0 || node.layout.height <= 0) return;
1032
+ // Padding bytes can only make this report a change that did not happen,
1033
+ // which costs a full-box repaint, never a missed one.
1034
+ scene.boxChanged = !scene.haveBox || scene.boxX != node.layout.x || scene.boxY != node.layout.y ||
1035
+ std::memcmp(scene.boxStyle, &node.computedStyle(), sizeof(ComputedStyle)) != 0;
1036
+ scene.haveBox = true;
1037
+ scene.boxX = node.layout.x;
1038
+ scene.boxY = node.layout.y;
1039
+ std::memcpy(scene.boxStyle, &node.computedStyle(), sizeof(ComputedStyle));
1040
+ if (scene.dirty || scene.width != node.layout.width || scene.height != node.layout.height) {
1041
+ buildScene(id, scene, node.layout.width, node.layout.height);
1042
+ scene.signature = subtreeSignature(id);
1043
+ }
1044
+ if (scene.items.empty()) return;
1045
+ DisplayCommand *cmd = DisplayList::instance().append();
1046
+ if (!cmd) return;
1047
+ cmd->type = DisplayCommandType::DrawSvg;
1048
+ cmd->bx = node.layout.x;
1049
+ cmd->by = node.layout.y;
1050
+ cmd->bw = node.layout.width;
1051
+ cmd->bh = node.layout.height;
1052
+ cmd->svg = {static_cast<std::int16_t>(id), node.layout.x, node.layout.y, node.layout.width, node.layout.height};
1053
+ scene.recorded = true;
1054
+ }
1055
+
1056
+ void paint(const DisplayCommand &c)
1057
+ {
1058
+ auto it = g_scenes.find(c.svg.nodeId);
1059
+ if (it == g_scenes.end()) return;
1060
+ auto *canvas = gea::platform::display::Display::canvas();
1061
+ if (!canvas) return;
1062
+ int cx0, cy0, cx1, cy1;
1063
+ canvas->currentClip(&cx0, &cy0, &cx1, &cy1);
1064
+ // The svg viewport clips its content (overflow: hidden is SVG's default).
1065
+ cx0 = std::max(cx0, static_cast<int>(c.svg.x));
1066
+ cy0 = std::max(cy0, static_cast<int>(c.svg.y));
1067
+ cx1 = std::min(cx1 + 1, c.svg.x + c.svg.w);
1068
+ cy1 = std::min(cy1 + 1, c.svg.y + c.svg.h);
1069
+ if (cx0 >= cx1 || cy0 >= cy1) return;
1070
+ struct Band {
1071
+ const std::vector<Item> *items;
1072
+ gea::framework::graphics::Canvas *canvas;
1073
+ int ox, oy, cx0, cx1;
1074
+ int bank;
1075
+ bool markDirty;
1076
+ unsigned cycles;
1077
+ };
1078
+ auto paintRows = [](void *p, int y0, int y1) {
1079
+ Band &b = *static_cast<Band *>(p);
1080
+ #if GEA_SVG_PARALLEL_PAINT
1081
+ const unsigned c0 = svgPaintCycles();
1082
+ struct Time { Band &b; unsigned c0; ~Time() { b.cycles = svgPaintCycles() - c0; } } time{b, c0};
1083
+ #endif
1084
+ for (const Item &item : *b.items) {
1085
+ if (item.fill.on)
1086
+ paintCoverage(b.canvas, b.bank, b.markDirty, item.fillEdges, item.fillBounds, item.evenOdd, item.fill, b.ox,
1087
+ b.oy, b.cx0, y0, b.cx1, y1);
1088
+ if (!item.strokeEdges.empty())
1089
+ paintCoverage(b.canvas, b.bank, b.markDirty, item.strokeEdges, item.strokeBounds, false, item.stroke, b.ox,
1090
+ b.oy, b.cx0, y0, b.cx1, y1);
1091
+ }
1092
+ };
1093
+ Band band{&it->second.items, canvas, c.svg.x, c.svg.y, cx0, cx1, scratchBank(), true, 0};
1094
+ #if GEA_SVG_PARALLEL_PAINT
1095
+ // Split tall paints across both cores; rows are disjoint, so the two
1096
+ // halves never touch the same pixels. Neither marks rows dirty (the dirty
1097
+ // rect list is not concurrent); the clipped box is marked once below.
1098
+ // Ink is rarely spread evenly over the rows (a chart's filled area sits
1099
+ // low, a gauge's arc high), so a fixed half split leaves one core waiting
1100
+ // on the other; each paint moves the split row to where the last paint's
1101
+ // measured time would have divided equally.
1102
+ constexpr int kMinSplitRows = 48;
1103
+ if (cy1 - cy0 >= kMinSplitRows && (cx1 - cx0) * (cy1 - cy0) >= 8000) {
1104
+ Scene &scene = it->second;
1105
+ const int rows = cy1 - cy0;
1106
+ const int mid = cy0 + std::clamp(static_cast<int>(rows * scene.split + 0.5f), 1, rows - 1);
1107
+ Band low = band;
1108
+ low.bank = kWorkerBank;
1109
+ low.markDirty = false;
1110
+ band.markDirty = false;
1111
+ if (paintWorkerSubmit(paintRows, &low, mid, cy1)) {
1112
+ paintRows(&band, cy0, mid);
1113
+ paintWorkerWait();
1114
+ canvas->markDirty(cx0, cy0, cx1 - 1, cy1 - 1);
1115
+ const float top = static_cast<float>(band.cycles), bottom = static_cast<float>(low.cycles);
1116
+ const float half = (top + bottom) * 0.5f;
1117
+ if (half > 0) {
1118
+ const int topRows = mid - cy0, bottomRows = cy1 - mid;
1119
+ // Rows each half's cost spreads over evenly, up to the time midpoint.
1120
+ const float at = top >= half ? topRows * (half / top) : topRows + bottomRows * ((half - top) / bottom);
1121
+ const float target = at / rows;
1122
+ scene.split = std::clamp(0.5f * scene.split + 0.5f * target, 0.1f, 0.9f);
1123
+ }
1124
+ return;
1125
+ }
1126
+ band.markDirty = true;
1127
+ }
1128
+ #endif
1129
+ paintRows(&band, cy0, cy1);
1130
+ }
1131
+
1132
+ int hitTest(int rootId, int x, int y)
1133
+ {
1134
+ auto it = g_scenes.find(rootId);
1135
+ if (it == g_scenes.end()) return -1;
1136
+ const Node &root = tree().node(rootId);
1137
+ const Point p{static_cast<float>(x - root.layout.x), static_cast<float>(y - root.layout.y)};
1138
+ constexpr float kSlop = 3.0f; // fingers are wider than hairlines
1139
+ const auto &items = it->second.items;
1140
+ for (auto item = items.rbegin(); item != items.rend(); ++item) {
1141
+ if (!item->hittable) continue;
1142
+ if (item->fill.on && insideFill(item->geometry.contours, p, item->evenOdd)) return item->node;
1143
+ if (!item->strokeEdges.empty() && distanceToPath(item->geometry, p) <= item->halfStroke + kSlop) return item->node;
1144
+ }
1145
+ return -1;
1146
+ }
1147
+
1148
+ } // namespace gea::embedded::ui::svg
1149
+
1150
+ #endif // GEA_UI_SVG