wasmhost: SVG icons with clip paths and masks (nanosvg drew them as black boxes)
CI / test (push) Failing after 18s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DPL5hiNfjrw2edja7LiRLB
This commit is contained in:
Claude committed 2026-11-25 20:09:39 +00:00
1 parent b4b9ba0e10
commit 2774516abf
3 files changed
+262 -4

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
# nanosvg
[nanosvg](https://github.com/memononen/nanosvg) (zlib licence, LICENSE.txt), used by the MoonBit
host (`wasmhost/bin/raster_stub.c`) to draw SVG icons. Upstream draws neither clip paths nor
masks: it drew their shapes, so many icon themes' icons came out with black boxes. Local changes
to `nanosvg.h`, all marked "Chandra":
- The shapes of a `<clipPath>` or `<mask>` are kept, flagged `NSVG_FLAGS_CLIP` (and
`NSVG_FLAGS_MASK`) with the clip's id in `clipOf`, and never drawn. A shape under
`clip-path` / `mask` names its clip in `clipId`.
- `nsvg__placeClips` moves each clip into the user space of the element using it.
- The content of `<symbol>`, `<pattern>`, `<marker>` and `<filter>` is skipped; a shape under
`filter="url(...)"` is flagged `NSVG_FLAGS_FILTERED`.
`nanosvgrast.h` is unchanged: `render_svg` in raster_stub.c draws runs of shapes and cuts
each to its clip's coverage (a mask's by luminance times alpha). On 370 icons from the Adwaita,
hicolor, Humanity and ubuntu-mono themes this matches resvg's rendering to within
anti-aliasing, except for a few icons that use luminance masks with filters.
+159 -3
View File
@@ -103,7 +103,10 @@ enum NSVGfillRule {
}; };
enum NSVGflags { enum NSVGflags {
NSVG_FLAGS_VISIBLE = 0x01 NSVG_FLAGS_VISIBLE = 0x01,
NSVG_FLAGS_CLIP = 0x02, // Chandra: part of the <clipPath> or <mask> named by `clipOf` (never drawn)
NSVG_FLAGS_MASK = 0x04, // Chandra: ... of a <mask> (its luminance and alpha count, not just its shape)
NSVG_FLAGS_FILTERED = 0x08 // Chandra: under a filter="url(...)" (filters are not drawn)
}; };
enum NSVGpaintOrder { enum NSVGpaintOrder {
@@ -162,6 +165,9 @@ typedef struct NSVGshape
char fillGradient[64]; // Optional 'id' of fill gradient char fillGradient[64]; // Optional 'id' of fill gradient
char strokeGradient[64]; // Optional 'id' of stroke gradient char strokeGradient[64]; // Optional 'id' of stroke gradient
float xform[6]; // Root transformation for fill/stroke gradient float xform[6]; // Root transformation for fill/stroke gradient
char clipId[64]; // Chandra: 'id' of the clip path or mask applied to the shape ("" none)
float clipXform[6]; // Chandra: the user space that clip is in (see nsvg__placeClips)
char clipOf[64]; // Chandra: with NSVG_FLAGS_CLIP, the clip path or mask it belongs to
NSVGpath* paths; // Linked list of paths in the image. NSVGpath* paths; // Linked list of paths in the image.
struct NSVGshape* next; // Pointer to next shape, or NULL if last element. struct NSVGshape* next; // Pointer to next shape, or NULL if last element.
} NSVGshape; } NSVGshape;
@@ -445,6 +451,10 @@ typedef struct NSVGattrib
char hasFill; char hasFill;
char hasStroke; char hasStroke;
char visible; char visible;
char clipId[64]; // Chandra: clip-path / mask url id
char filtered; // Chandra: a filter applies (not drawn; see NSVG_FLAGS_FILTERED)
char clipPending; // Chandra: clip-path set on this element, clipXform not taken yet
float clipXform[6]; // Chandra: the user space of the element that set clip-path
unsigned char paintOrder; unsigned char paintOrder;
} NSVGattrib; } NSVGattrib;
@@ -473,6 +483,11 @@ typedef struct NSVGparser
char pathFlag; char pathFlag;
char defsFlag; char defsFlag;
char styleFlag; char styleFlag;
// Chandra: the <clipPath> / <mask> being parsed ("" outside one), and the depth inside an
// element whose content is never drawn directly (<symbol>, <pattern>, <marker>, <filter>).
char clipOf[64];
char clipIsMask;
int skipDepth;
} NSVGparser; } NSVGparser;
static void nsvg__xformIdentity(float* t) static void nsvg__xformIdentity(float* t)
@@ -994,6 +1009,9 @@ static void nsvg__addShape(NSVGparser* p)
memcpy(shape->fillGradient, attr->fillGradient, sizeof shape->fillGradient); memcpy(shape->fillGradient, attr->fillGradient, sizeof shape->fillGradient);
memcpy(shape->strokeGradient, attr->strokeGradient, sizeof shape->strokeGradient); memcpy(shape->strokeGradient, attr->strokeGradient, sizeof shape->strokeGradient);
memcpy(shape->xform, attr->xform, sizeof shape->xform); memcpy(shape->xform, attr->xform, sizeof shape->xform);
memcpy(shape->clipId, attr->clipId, sizeof shape->clipId);
memcpy(shape->clipXform, attr->clipPending ? attr->xform : attr->clipXform, sizeof shape->clipXform);
memcpy(shape->clipOf, p->clipOf, sizeof shape->clipOf);
scale = nsvg__getAverageScale(attr->xform); scale = nsvg__getAverageScale(attr->xform);
shape->strokeWidth = attr->strokeWidth * scale; shape->strokeWidth = attr->strokeWidth * scale;
shape->strokeDashOffset = attr->strokeDashOffset * scale; shape->strokeDashOffset = attr->strokeDashOffset * scale;
@@ -1045,7 +1063,12 @@ static void nsvg__addShape(NSVGparser* p)
} }
// Set flags // Set flags
shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00); shape->flags = (attr->visible ? NSVG_FLAGS_VISIBLE : 0x00) | (attr->filtered ? NSVG_FLAGS_FILTERED : 0x00);
if (p->clipOf[0]) {
// A clip shape: kept with the others (scaled to the viewBox alike) but never drawn.
shape->flags = NSVG_FLAGS_CLIP | (p->clipIsMask ? NSVG_FLAGS_MASK : 0) | (attr->filtered ? NSVG_FLAGS_FILTERED : 0);
shape->clipId[0] = '\0';
}
// Add to tail // Add to tail
if (p->image->shapes == NULL) if (p->image->shapes == NULL)
@@ -1869,6 +1892,13 @@ static int nsvg__parseAttr(NSVGparser* p, const char* name, const char* value)
attr->visible = 0; attr->visible = 0;
// Don't reset ->visible on display:inline, one display:none hides the whole subtree // Don't reset ->visible on display:inline, one display:none hides the whole subtree
} else if (strcmp(name, "clip-path") == 0 || strcmp(name, "mask") == 0) {
if (strncmp(value, "url(", 4) == 0) {
nsvg__parseUrl(attr->clipId, value);
attr->clipPending = 1;
}
} else if (strcmp(name, "filter") == 0) {
attr->filtered = strncmp(value, "url(", 4) == 0;
} else if (strcmp(name, "fill") == 0) { } else if (strcmp(name, "fill") == 0) {
if (strcmp(value, "none") == 0) { if (strcmp(value, "none") == 0) {
attr->hasFill = 0; attr->hasFill = 0;
@@ -2837,7 +2867,35 @@ static void nsvg__startElement(void* ud, const char* el, const char** attr)
{ {
NSVGparser* p = (NSVGparser*)ud; NSVGparser* p = (NSVGparser*)ud;
if (p->defsFlag) { if (p->skipDepth > 0) {
p->skipDepth++;
return;
}
if (strcmp(el, "symbol") == 0 || strcmp(el, "pattern") == 0 || strcmp(el, "marker") == 0 ||
strcmp(el, "filter") == 0) {
p->skipDepth = 1;
return;
}
if ((strcmp(el, "clipPath") == 0 || strcmp(el, "mask") == 0) && !p->clipOf[0]) {
// Its shapes are collected as clip shapes under its id (a mask is taken as the shape of
// what it lets through).
int i;
nsvg__pushAttr(p);
p->clipIsMask = strcmp(el, "mask") == 0;
for (i = 0; attr[i]; i += 2) {
if (strcmp(attr[i], "id") == 0) {
strncpy(p->clipOf, attr[i+1], 63);
p->clipOf[63] = '\0';
} else if (strcmp(attr[i], "transform") == 0) {
nsvg__parseAttr(p, attr[i], attr[i+1]);
}
}
if (!p->clipOf[0]) strcpy(p->clipOf, "#"); // no id: nothing can use it
nsvg__getAttr(p)->clipId[0] = '\0';
return;
}
if (p->defsFlag && !p->clipOf[0]) {
// Skip everything but gradients and styles in defs // Skip everything but gradients and styles in defs
if (strcmp(el, "linearGradient") == 0) { if (strcmp(el, "linearGradient") == 0) {
nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT); nsvg__parseGradient(p, attr, NSVG_PAINT_LINEAR_GRADIENT);
@@ -2852,8 +2910,16 @@ static void nsvg__startElement(void* ud, const char* el, const char** attr)
} }
if (strcmp(el, "g") == 0) { if (strcmp(el, "g") == 0) {
NSVGattrib* a;
nsvg__pushAttr(p); nsvg__pushAttr(p);
a = nsvg__getAttr(p);
a->clipPending = 0;
nsvg__parseAttribs(p, attr); nsvg__parseAttribs(p, attr);
if (a->clipPending) {
// A group's clip is in the group's user space, whatever its children's transforms.
memcpy(a->clipXform, a->xform, sizeof a->clipXform);
a->clipPending = 0;
}
} else if (strcmp(el, "path") == 0) { } else if (strcmp(el, "path") == 0) {
if (p->pathFlag) // Do not allow nested paths. if (p->pathFlag) // Do not allow nested paths.
return; return;
@@ -2903,6 +2969,16 @@ static void nsvg__endElement(void* ud, const char* el)
{ {
NSVGparser* p = (NSVGparser*)ud; NSVGparser* p = (NSVGparser*)ud;
if (p->skipDepth > 0) {
p->skipDepth--;
return;
}
if ((strcmp(el, "clipPath") == 0 || strcmp(el, "mask") == 0) && p->clipOf[0]) {
p->clipOf[0] = '\0';
nsvg__popAttr(p);
return;
}
if (strcmp(el, "g") == 0) { if (strcmp(el, "g") == 0) {
nsvg__popAttr(p); nsvg__popAttr(p);
} else if (strcmp(el, "path") == 0) { } else if (strcmp(el, "path") == 0) {
@@ -3170,6 +3246,83 @@ static void nsvg__createGradients(NSVGparser* p)
} }
} }
// Chandra: clip shapes are parsed where their <clipPath> is, but a clip is in the user space of
// the element using it (clipPathUnits="userSpaceOnUse"). Each shape whose clip-path was set
// under a transform gets its own transformed copy of that clip's shapes, named "<id>#<n>".
static int nsvg__isIdentity(const float* t)
{
return t[0] == 1.0f && t[1] == 0.0f && t[2] == 0.0f && t[3] == 1.0f && t[4] == 0.0f && t[5] == 0.0f;
}
static void nsvg__placeClips(NSVGparser* p)
{
struct { char from[64]; float xf[6]; char id[64]; } placed[64];
int nplaced = 0, i;
NSVGshape *shape, *last = NULL, *end;
for (shape = p->image->shapes; shape != NULL; shape = shape->next) last = shape;
end = last;
for (shape = p->image->shapes; shape != NULL; shape = shape == end ? NULL : shape->next) {
NSVGshape* c;
int found = -1;
if (!shape->clipId[0] || (shape->flags & NSVG_FLAGS_CLIP) || nsvg__isIdentity(shape->clipXform))
continue;
for (i = 0; i < nplaced; i++)
if (strcmp(placed[i].from, shape->clipId) == 0 && memcmp(placed[i].xf, shape->clipXform, sizeof placed[i].xf) == 0)
found = i;
if (found < 0) {
if (nplaced == 64) continue;
found = nplaced++;
memcpy(placed[found].from, shape->clipId, 64);
memcpy(placed[found].xf, shape->clipXform, sizeof placed[found].xf);
snprintf(placed[found].id, 64, "%.40s#%d", shape->clipId, found);
for (c = p->image->shapes; c != NULL; c = c == end ? NULL : c->next) {
NSVGshape* d;
NSVGpath *path, **tail;
if (!(c->flags & NSVG_FLAGS_CLIP) || strcmp(c->clipOf, shape->clipId) != 0) continue;
d = (NSVGshape*)malloc(sizeof(NSVGshape));
if (d == NULL) continue;
memcpy(d, c, sizeof(NSVGshape));
d->next = NULL;
memcpy(d->clipOf, placed[found].id, 64);
nsvg__xformMultiply(d->xform, shape->clipXform);
d->paths = NULL;
tail = &d->paths;
for (path = c->paths; path != NULL; path = path->next) {
NSVGpath* q = nsvgDuplicatePath(path);
int k;
if (q == NULL) continue;
q->next = NULL;
for (k = 0; k < q->npts; k++)
nsvg__xformPoint(&q->pts[k*2], &q->pts[k*2+1], q->pts[k*2], q->pts[k*2+1], shape->clipXform);
q->bounds[0] = q->bounds[2] = q->pts[0];
q->bounds[1] = q->bounds[3] = q->pts[1];
for (k = 1; k < q->npts; k++) {
q->bounds[0] = nsvg__minf(q->bounds[0], q->pts[k*2]);
q->bounds[1] = nsvg__minf(q->bounds[1], q->pts[k*2+1]);
q->bounds[2] = nsvg__maxf(q->bounds[2], q->pts[k*2]);
q->bounds[3] = nsvg__maxf(q->bounds[3], q->pts[k*2+1]);
}
*tail = q;
tail = &q->next;
}
if (d->paths == NULL) { free(d); continue; }
d->bounds[0] = d->paths->bounds[0]; d->bounds[1] = d->paths->bounds[1];
d->bounds[2] = d->paths->bounds[2]; d->bounds[3] = d->paths->bounds[3];
for (path = d->paths->next; path != NULL; path = path->next) {
d->bounds[0] = nsvg__minf(d->bounds[0], path->bounds[0]);
d->bounds[1] = nsvg__minf(d->bounds[1], path->bounds[1]);
d->bounds[2] = nsvg__maxf(d->bounds[2], path->bounds[2]);
d->bounds[3] = nsvg__maxf(d->bounds[3], path->bounds[3]);
}
last->next = d;
last = d;
}
}
memcpy(shape->clipId, placed[found].id, 64);
}
p->shapesTail = last;
}
NSVGimage* nsvgParse(char* input, const char* units, float dpi) NSVGimage* nsvgParse(char* input, const char* units, float dpi)
{ {
NSVGparser* p; NSVGparser* p;
@@ -3183,6 +3336,9 @@ NSVGimage* nsvgParse(char* input, const char* units, float dpi)
nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p); nsvg__parseXML(input, nsvg__startElement, nsvg__endElement, nsvg__content, p);
// Chandra: put clip paths in the user space of the shapes using them.
nsvg__placeClips(p);
// Create gradients after all definitions have been parsed // Create gradients after all definitions have been parsed
nsvg__createGradients(p); nsvg__createGradients(p);
+85 -1
View File
@@ -390,13 +390,97 @@ int32_t rs_image_svg(moonbit_bytes_t data) {
return id; return id;
} }
/* Rasterise just the shapes `list[0..n)` (relinked into a list for the call) into `dst`, which
* nanosvg clears first: straight (not premultiplied) RGBA. */
static void svg_raster_list(NSVGrasterizer *rast, NSVGimage *svg, NSVGshape **list, int n, float dx, float dy,
float k, uint8_t *dst, int w, int h) {
NSVGshape **next = malloc(sizeof *next * (size_t)(n ? n : 1));
for (int i = 0; i < n; i++) { next[i] = list[i]->next; list[i]->next = i + 1 < n ? list[i + 1] : NULL; }
NSVGimage part = { svg->width, svg->height, n ? list[0] : NULL };
nsvgRasterize(rast, &part, dx, dy, k, dst, w, h, w * 4);
for (int i = 0; i < n; i++) list[i]->next = next[i];
free(next);
}
/* The coverage of clip path or mask `id` as w * h alpha bytes: a clip path's shapes filled
* opaque; a mask's shapes as drawn, by luminance times alpha (content under a filter counts as
* white: the masks Inkscape writes turn theirs white with a colour-matrix filter). */
static uint8_t *svg_clip_mask(NSVGrasterizer *rast, NSVGimage *svg, NSVGshape **all, int n, const char *id,
float dx, float dy, float k, int w, int h) {
NSVGshape **clip = malloc(sizeof *clip * (size_t)n);
NSVGpaint *fill = malloc(sizeof *fill * (size_t)n), *stroke = malloc(sizeof *stroke * (size_t)n);
int m = 0;
for (int i = 0; i < n; i++)
if ((all[i]->flags & NSVG_FLAGS_CLIP) && strcmp(all[i]->clipOf, id) == 0) clip[m++] = all[i];
if (!m) { free(clip); free(fill); free(stroke); return NULL; } /* no such clip: not clipped */
unsigned char *flags = malloc((size_t)m + 1);
for (int i = 0; i < m; i++) {
fill[i] = clip[i]->fill; stroke[i] = clip[i]->stroke; flags[i] = clip[i]->flags;
int is_mask = clip[i]->flags & NSVG_FLAGS_MASK;
if (!is_mask || (clip[i]->flags & NSVG_FLAGS_FILTERED)) {
/* White, keeping a mask's alpha (a plain colour's; a gradient's counts as opaque). */
unsigned a = is_mask && clip[i]->fill.type == NSVG_PAINT_COLOR ? clip[i]->fill.color >> 24 : 0xff;
if (clip[i]->fill.type != NSVG_PAINT_NONE || !is_mask) { clip[i]->fill.type = NSVG_PAINT_COLOR; clip[i]->fill.color = (a << 24) | 0xffffffu; }
if (!is_mask) clip[i]->stroke.type = NSVG_PAINT_NONE;
else if (clip[i]->stroke.type == NSVG_PAINT_COLOR) clip[i]->stroke.color |= 0xffffffu;
}
clip[i]->flags = (unsigned char)(clip[i]->flags | NSVG_FLAGS_VISIBLE);
}
uint8_t *rgba = malloc((size_t)w * h * 4), *mask = malloc((size_t)w * h);
svg_raster_list(rast, svg, clip, m, dx, dy, k, rgba, w, h);
for (size_t i = 0; i < (size_t)w * h; i++) {
const uint8_t *q = rgba + i * 4;
unsigned lum = (54u * q[0] + 183u * q[1] + 19u * q[2]) >> 8; /* Rec. 709 luminance */
mask[i] = (uint8_t)(q[3] * lum / 255);
}
for (int i = 0; i < m; i++) { clip[i]->fill = fill[i]; clip[i]->stroke = stroke[i]; clip[i]->flags = flags[i]; }
free(flags);
free(rgba); free(clip); free(fill); free(stroke);
return mask;
}
/* `src` over `dst`, both straight RGBA, with src's alpha scaled by `mask` (NULL: none). */
static void svg_over(uint8_t *dst, const uint8_t *src, const uint8_t *mask, size_t npx) {
for (size_t i = 0; i < npx; i++) {
const uint8_t *s = src + i * 4;
uint8_t *d = dst + i * 4;
unsigned sa = mask ? (unsigned)s[3] * mask[i] / 255 : s[3];
if (!sa) continue;
unsigned da = d[3], oa = sa + da * (255 - sa) / 255;
for (int c = 0; c < 3; c++) d[c] = (uint8_t)((s[c] * sa + d[c] * da * (255 - sa) / 255) / oa);
d[3] = (uint8_t)oa;
}
}
/* The SVG drawn into a new w x h straight RGBA buffer, fitted and centred. Shapes under a
* clip-path (or mask) are drawn in runs, each cut to its clip's coverage (nanosvg itself has no
* clipping; the vendored parser collects the clip shapes, see NSVG_FLAGS_CLIP). */
static uint8_t *render_svg(NSVGimage *svg, int w, int h) { static uint8_t *render_svg(NSVGimage *svg, int w, int h) {
static NSVGrasterizer *rast; static NSVGrasterizer *rast;
if (!rast) rast = nsvgCreateRasterizer(); if (!rast) rast = nsvgCreateRasterizer();
uint8_t *out = calloc((size_t)w * h, 4); uint8_t *out = calloc((size_t)w * h, 4);
float k = fminf((float)w / svg->width, (float)h / svg->height); float k = fminf((float)w / svg->width, (float)h / svg->height);
float dx = ((float)w - svg->width * k) / 2.0f, dy = ((float)h - svg->height * k) / 2.0f; float dx = ((float)w - svg->width * k) / 2.0f, dy = ((float)h - svg->height * k) / 2.0f;
nsvgRasterize(rast, svg, dx, dy, k, out, w, h, w * 4); /* straight (not premultiplied) RGBA */ int n = 0, clipped = 0;
for (NSVGshape *sh = svg->shapes; sh; sh = sh->next) { n++; if (sh->clipId[0] && (sh->flags & NSVG_FLAGS_VISIBLE)) clipped = 1; }
if (!clipped) {
nsvgRasterize(rast, svg, dx, dy, k, out, w, h, w * 4);
return out;
}
NSVGshape **all = malloc(sizeof *all * (size_t)n);
int i = 0;
for (NSVGshape *sh = svg->shapes; sh; sh = sh->next) all[i++] = sh;
uint8_t *tmp = malloc((size_t)w * h * 4);
for (int a = 0; a < n;) {
int b = a + 1;
while (b < n && strcmp(all[b]->clipId, all[a]->clipId) == 0) b++;
svg_raster_list(rast, svg, all + a, b - a, dx, dy, k, tmp, w, h);
uint8_t *mask = all[a]->clipId[0] ? svg_clip_mask(rast, svg, all, n, all[a]->clipId, dx, dy, k, w, h) : NULL;
svg_over(out, tmp, mask, (size_t)w * h);
free(mask);
a = b;
}
free(tmp); free(all);
return out; return out;
} }