@weasel-js/paint-kinds 0.0.0-stage → 1.19.1

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,1664 @@
1
+ // ../geom/src/scalar.ts
2
+ /** The reciprocal of the largest condition number a matrix may have and still invert, and the fraction of a
3
+ * quantity's own scale below which it counts as zero. Dimensionless, so a uniformly tiny matrix still inverts
4
+ * while a large one whose determinant is only rounding does not. */
5
+ const SINGULAR_RATIO = 1e-12;
6
+ /** Whether a matrix whose 1-norm is `norm`, and its inverse's `inverseNorm`, is well enough conditioned to
7
+ * invert: their product, the matrix's condition number, stays under `1 / SINGULAR_RATIO`. Both `invert`s use
8
+ * it, so 2D and 3D refuse the same matrices. `NaN` and `Infinity` count as refused. */
9
+ function invertible(norm, inverseNorm) {
10
+ return norm * inverseNorm < 1 / SINGULAR_RATIO;
11
+ }
12
+ /** `n` rounded to `places` decimals and written as JavaScript writes it, for a number in a file: SVG path data,
13
+ * an attribute. A non-finite `n` writes `'0'`. */
14
+ function trimNumber(n, places = 6) {
15
+ if (!Number.isFinite(n)) return "0";
16
+ const k = 10 ** places;
17
+ const rounded = Math.round(n * k) / k;
18
+ return String(Number.isFinite(rounded) ? rounded : n);
19
+ }
20
+ function minOf(items, of) {
21
+ let least = Infinity;
22
+ let i = 0;
23
+ for (const item of items) least = Math.min(least, of ? of(item, i++) : item);
24
+ return least;
25
+ }
26
+ function maxOf(items, of) {
27
+ let most = -Infinity;
28
+ let i = 0;
29
+ for (const item of items) most = Math.max(most, of ? of(item, i++) : item);
30
+ return most;
31
+ }
32
+ // ../geom/src/angle.ts
33
+ /** Multiply degrees by this to get radians. */
34
+ const DEG_TO_RAD = Math.PI / 180;
35
+ // ../geom/src/affine.ts
36
+ /**
37
+ * 2D affine transforms in canvas/DOMMatrix order: [a, b, c, d, e, f].
38
+ * x' = a·x + c·y + e
39
+ * y' = b·x + d·y + f
40
+ * Represented as a readonly 6-tuple (f64). The affine tier of the kernel.
41
+ *
42
+ * `glMat3.ts` beside this file holds the renderer's matrix: a 9-element
43
+ * column-major array (a full 3×3) laid out for `uniformMatrix3fv`. Its
44
+ * *logical element order* is identical to ours.
45
+ */
46
+ /** Inverse, or null when the matrix is singular, non-finite, or too ill-conditioned to invert meaningfully
47
+ * (`invertible`). */
48
+ function invert$1(m) {
49
+ const id = 1 / (m[0] * m[3] - m[1] * m[2]);
50
+ const a = m[3] * id;
51
+ const b = -m[1] * id;
52
+ const c = -m[2] * id;
53
+ const d = m[0] * id;
54
+ if (!invertible(Math.max(Math.abs(m[0]) + Math.abs(m[1]), Math.abs(m[2]) + Math.abs(m[3])), Math.max(Math.abs(a) + Math.abs(b), Math.abs(c) + Math.abs(d)))) return null;
55
+ if (!Number.isFinite(m[4]) || !Number.isFinite(m[5])) return null;
56
+ return [
57
+ a,
58
+ b,
59
+ c,
60
+ d,
61
+ -(m[4] * a + m[5] * c),
62
+ -(m[4] * b + m[5] * d)
63
+ ];
64
+ }
65
+ // ../geom/src/glMat3.ts
66
+ /**
67
+ * 2D affine matrix utilities. Column-major 9 elements, matching
68
+ * `WebGL2RenderingContext.uniformMatrix3fv` element order so an upload needs
69
+ * no transpose flag.
70
+ *
71
+ * Layout (column-major):
72
+ * [m00, m10, 0,
73
+ * m01, m11, 0,
74
+ * tx, ty, 1]
75
+ */
76
+ function create(a, b, c, d, tx, ty) {
77
+ return new Float64Array([
78
+ a,
79
+ b,
80
+ 0,
81
+ c,
82
+ d,
83
+ 0,
84
+ tx,
85
+ ty,
86
+ 1
87
+ ]);
88
+ }
89
+ function identity() {
90
+ return create(1, 0, 0, 1, 0, 0);
91
+ }
92
+ function multiply(out, m) {
93
+ const a = out[0], b = out[1];
94
+ const c = out[3], d = out[4];
95
+ const tx = out[6], ty = out[7];
96
+ const ma = m[0], mb = m[1];
97
+ const mc = m[3], md = m[4];
98
+ const mtx = m[6], mty = m[7];
99
+ return create(a * ma + c * mb, b * ma + d * mb, a * mc + c * md, b * mc + d * md, a * mtx + c * mty + tx, b * mtx + d * mty + ty);
100
+ }
101
+ /** `m · T(tx, ty)`: composes onto `m`, where `@weasel-js/geom`'s `translate`
102
+ * constructs a fresh matrix. */
103
+ function translated(m, tx, ty) {
104
+ return multiply(m, create(1, 0, 0, 1, tx, ty));
105
+ }
106
+ /** `m · S(sx, sy)`: composes onto `m`, where geom's `scale` constructs one. */
107
+ function scaled(m, sx, sy) {
108
+ return multiply(m, create(sx, 0, 0, sy, 0, 0));
109
+ }
110
+ /** This layout read as the kernel's 6-element affine. The two carry the same
111
+ * logical order, so the conversion is a repack and nothing else. */
112
+ function toAffine(m) {
113
+ return [
114
+ m[0],
115
+ m[1],
116
+ m[3],
117
+ m[4],
118
+ m[6],
119
+ m[7]
120
+ ];
121
+ }
122
+ /** The kernel's affine in this layout. The inverse of {@link toAffine}. */
123
+ function fromAffine(a) {
124
+ return create(a[0], a[1], a[2], a[3], a[4], a[5]);
125
+ }
126
+ /** Inverse of an affine matrix, or `null` when `@weasel-js/geom`'s `invert`
127
+ * finds it singular — the same rule, read through this layout. */
128
+ function invert(m) {
129
+ const inv = invert$1(toAffine(m));
130
+ return inv && fromAffine(inv);
131
+ }
132
+ /** A float32 copy of `m`, for `uniformMatrix3fv` or a shader uniform value. */
133
+ function toUniform(m) {
134
+ return Float32Array.from(m);
135
+ }
136
+ function apply(m, x, y) {
137
+ const a = m[0], b = m[1];
138
+ const c = m[3], d = m[4];
139
+ const tx = m[6], ty = m[7];
140
+ return [a * x + c * y + tx, b * x + d * y + ty];
141
+ }
142
+ /**
143
+ * Map screen pixel coords (0..width on X, 0..height on Y, top-left origin)
144
+ * into clip space (-1..1 on X, 1..-1 on Y — note Y flip so screen-down
145
+ * matches clip-down).
146
+ */
147
+ function screenToClip(width, height) {
148
+ return create(2 / width, 0, 0, -2 / height, -1, 1);
149
+ }
150
+ /**
151
+ * Uniform-equivalent scale factor: the square root of the absolute
152
+ * determinant of the linear part, i.e. the geometric mean of the two axis
153
+ * scales. Rotation-invariant. Under non-uniform scale it is between the two
154
+ * axes and exact on neither — the same compromise `meanScale` documents.
155
+ */
156
+ function meanScaleOf(m) {
157
+ return Math.sqrt(Math.abs(m[0] * m[4] - m[1] * m[3]));
158
+ }
159
+ /** The least any direction is scaled by the linear part — its smaller singular
160
+ * value. What a screen length is worth in world units, at most. */
161
+ function minScaleOf(m) {
162
+ const sum = m[0] * m[0] + m[1] * m[1] + m[3] * m[3] + m[4] * m[4];
163
+ const det = m[0] * m[4] - m[1] * m[3];
164
+ const max = Math.sqrt((sum + Math.sqrt(Math.max(0, sum * sum - 4 * det * det))) / 2);
165
+ return max > 0 ? Math.abs(det) / max : 0;
166
+ }
167
+ /** The renderer's 3x3 matrix operations, as one namespace. These work on the
168
+ * 9-element form the GL uniform upload wants — distinct from the 6-element
169
+ * `Affine`, though the logical element order is the same. */
170
+ const mat3 = {
171
+ identity,
172
+ toAffine,
173
+ fromAffine,
174
+ multiply,
175
+ translated,
176
+ scaled,
177
+ invert,
178
+ toUniform,
179
+ apply,
180
+ screenToClip,
181
+ meanScaleOf,
182
+ minScaleOf
183
+ };
184
+ // ../paint/src/hue.ts
185
+ /** `h` degrees in `[0, 360)`. */
186
+ const wrapDeg = (h) => (h % 360 + 360) % 360;
187
+ // ../paint/src/lerp.ts
188
+ /** geom's `lerp`, which this package cannot import: exactly `b` at `t = 1`, and finite where `b - a` would overflow. */
189
+ function lerp(a, b, t) {
190
+ if (t === 1) return b;
191
+ if (a === b) return a;
192
+ const d = b - a;
193
+ return Number.isFinite(d) ? a + d * t : a * (1 - t) + b * t;
194
+ }
195
+ // ../paint/src/hex.ts
196
+ const HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
197
+ /**
198
+ * The kit's one hex color reader: `#rgb`, `#rgba`, `#rrggbb`, or `#rrggbbaa`,
199
+ * in any case, as four 0..255 channels with alpha last (255 when the color
200
+ * names none). `null` for anything else, a missing `#` included.
201
+ */
202
+ function parseHexBytes(input) {
203
+ if (!HEX.test(input)) return null;
204
+ const digits = input.slice(1);
205
+ const long = digits.length <= 4 ? digits.replace(/./g, "$&$&") : digits;
206
+ const byte = (i) => Number.parseInt(long.slice(i, i + 2), 16);
207
+ return [
208
+ byte(0),
209
+ byte(2),
210
+ byte(4),
211
+ long.length === 8 ? byte(6) : 255
212
+ ];
213
+ }
214
+ /** The kit's one hex color writer: a 0..255 channel as two hex digits, rounded and clamped; NaN as 0. */
215
+ function byteHex(v) {
216
+ return (Math.max(0, Math.min(255, Math.round(v))) || 0).toString(16).padStart(2, "0");
217
+ }
218
+ // ../paint/src/hsl.ts
219
+ /** HSL to sRGB. Hue in degrees, any number of turns; saturation, lightness and output all 0..1. */
220
+ function hslToSrgb(h, s, l) {
221
+ if (s === 0) return [
222
+ l,
223
+ l,
224
+ l
225
+ ];
226
+ const q = l < .5 ? l * (1 + s) : l + s - l * s;
227
+ const p = 2 * l - q;
228
+ const turn = h / 360;
229
+ const hk = turn >= 0 && turn < 1 ? turn : turn - Math.floor(turn);
230
+ return [
231
+ hueToChannel(p, q, hk + 1 / 3),
232
+ hueToChannel(p, q, hk),
233
+ hueToChannel(p, q, hk - 1 / 3)
234
+ ];
235
+ }
236
+ function hueToChannel(p, q, t) {
237
+ if (t < 0) t += 1;
238
+ if (t > 1) t -= 1;
239
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
240
+ if (t < 1 / 2) return q;
241
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
242
+ return p;
243
+ }
244
+ // ../paint/src/shortArc.ts
245
+ const TWO_PI = Math.PI * 2;
246
+ /** `dh` radians as the shorter arc, in [-π, π]: a half turn keeps its sign. NaN for NaN and ±∞.
247
+ * geom's `wrapAngle(dh, 'sign')`, kept here because paint does not depend on geom. */
248
+ function shortArc(dh) {
249
+ const r = dh % TWO_PI;
250
+ return r > Math.PI ? r - TWO_PI : r < -Math.PI ? r + TWO_PI : r;
251
+ }
252
+ // ../paint/src/colorSpaces.ts
253
+ const SRGB_TO_LINEAR = (() => {
254
+ const lut = /* @__PURE__ */ new Float64Array(256);
255
+ for (let i = 0; i < 256; i++) {
256
+ const c = i / 255;
257
+ lut[i] = c <= .04045 ? c / 12.92 : Math.pow((c + .055) / 1.055, 2.4);
258
+ }
259
+ return lut;
260
+ })();
261
+ function linearToSrgbByte(c) {
262
+ if (c <= 0) return 0;
263
+ if (c >= 1) return 255;
264
+ const v = c <= .0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - .055;
265
+ return Math.round(v * 255);
266
+ }
267
+ /** 0..1 float channel to the 8-bit index the LUTs are cut for. Rounds and
268
+ * clamps; `& 0xff` would truncate, and wrap anything out of range. */
269
+ const f2u = (v) => Math.max(0, Math.min(255, Math.round(v * 255)));
270
+ /**
271
+ * Convert a 0..1 float sRGB triple to OKLab — the renderer's own color space,
272
+ * and what a caller holding a `parseColor` result has. Rounds into the u8
273
+ * grid the way every other float→u8 crossing in this file does, rather than
274
+ * leaving each caller to pick a convention.
275
+ */
276
+ function srgbFloatToOklab(r, g, b) {
277
+ return srgbU8ToOklab(f2u(r), f2u(g), f2u(b));
278
+ }
279
+ /** Convert an 8-bit sRGB triple to OKLab. Channels are indices into a 256-entry
280
+ * LUT: pass integers, or `srgbFloatToOklab` for 0..1 floats. */
281
+ function srgbU8ToOklab(r, g, b) {
282
+ return linearSrgbToOklab(SRGB_TO_LINEAR[r & 255], SRGB_TO_LINEAR[g & 255], SRGB_TO_LINEAR[b & 255]);
283
+ }
284
+ /** Linear-light sRGB (0..1 floats, unclamped) to OKLab. */
285
+ function linearSrgbToOklab(rl, gl, bl) {
286
+ const l = .4122214708 * rl + .5363325363 * gl + .0514459929 * bl;
287
+ const m = .2119034982 * rl + .6806995451 * gl + .1073969566 * bl;
288
+ const s = .0883024619 * rl + .2817188376 * gl + .6299787005 * bl;
289
+ const lp = Math.cbrt(l);
290
+ const mp = Math.cbrt(m);
291
+ const sp = Math.cbrt(s);
292
+ return [
293
+ .2104542553 * lp + .793617785 * mp - .0040720468 * sp,
294
+ 1.9779984951 * lp - 2.428592205 * mp + .4505937099 * sp,
295
+ .0259040371 * lp + .7827717662 * mp - .808675766 * sp
296
+ ];
297
+ }
298
+ /** OKLab to linear-light sRGB. Not gamut-clipped: out-of-gamut colors come
299
+ * back with channels outside 0..1. */
300
+ function oklabToLinearSrgb(L, A, B) {
301
+ const lp = L + .3963377774 * A + .2158037573 * B;
302
+ const mp = L - .1055613458 * A - .0638541728 * B;
303
+ const sp = L - .0894841775 * A - 1.291485548 * B;
304
+ const l = lp * lp * lp;
305
+ const m = mp * mp * mp;
306
+ const s = sp * sp * sp;
307
+ return [
308
+ 4.0767416621 * l - 3.3077115913 * m + .2309699292 * s,
309
+ -1.2684380046 * l + 2.6097574011 * m - .3413193965 * s,
310
+ -.0041960863 * l - .7034186147 * m + 1.707614701 * s
311
+ ];
312
+ }
313
+ function inGamut(rl, gl, bl) {
314
+ return rl >= -1e-6 && rl <= 1.000001 && gl >= -1e-6 && gl <= 1.000001 && bl >= -1e-6 && bl <= 1.000001;
315
+ }
316
+ function clipToGamut(L, A, B) {
317
+ let [rl, gl, bl] = oklabToLinearSrgb(L, A, B);
318
+ if (inGamut(rl, gl, bl)) return [
319
+ rl,
320
+ gl,
321
+ bl
322
+ ];
323
+ let lo = 0;
324
+ let hi = 1;
325
+ for (let i = 0; i < 5; i++) {
326
+ const t = (lo + hi) / 2;
327
+ [rl, gl, bl] = oklabToLinearSrgb(L, A * t, B * t);
328
+ if (inGamut(rl, gl, bl)) lo = t;
329
+ else hi = t;
330
+ }
331
+ [rl, gl, bl] = oklabToLinearSrgb(L, A * lo, B * lo);
332
+ return [
333
+ rl,
334
+ gl,
335
+ bl
336
+ ];
337
+ }
338
+ /** Convert OKLab back to an 8-bit sRGB triple, clamped into gamut. */
339
+ function oklabToSrgbU8(L, A, B) {
340
+ const [rl, gl, bl] = clipToGamut(L, A, B);
341
+ return [
342
+ linearToSrgbByte(rl),
343
+ linearToSrgbByte(gl),
344
+ linearToSrgbByte(bl)
345
+ ];
346
+ }
347
+ /** Blend two 8-bit sRGB colors through OKLab. Perceptually even, and it does
348
+ * not pass through the muddy midpoints an sRGB blend produces between
349
+ * complementary hues. */
350
+ function lerpOklab(from, to, t) {
351
+ return [
352
+ lerp(from[0], to[0], t),
353
+ lerp(from[1], to[1], t),
354
+ lerp(from[2], to[2], t)
355
+ ];
356
+ }
357
+ /** Convert OKLab (L, a, b) to OKLCh (L, C, h). h is in radians, range [-π, π]. */
358
+ function oklabToOklch(L, A, B) {
359
+ return [
360
+ L,
361
+ Math.hypot(A, B),
362
+ Math.atan2(B, A)
363
+ ];
364
+ }
365
+ /** Convert OKLCh (L, C, h) to OKLab (L, a, b). h is in radians. */
366
+ function oklchToOklab(L, C, h) {
367
+ return [
368
+ L,
369
+ C * Math.cos(h),
370
+ C * Math.sin(h)
371
+ ];
372
+ }
373
+ /** Lerp OKLCh values with shortest-arc hue interpolation. Lightness and
374
+ * chroma lerp linearly. When chroma is near zero on either endpoint, hue
375
+ * is taken from the other endpoint (avoids hue snap-from-undefined).
376
+ * h inputs are in radians. */
377
+ function lerpOklch(from, to, t) {
378
+ const [L1, C1, h1Raw] = from;
379
+ const [L2, C2, h2Raw] = to;
380
+ const C_EPS = 1e-4;
381
+ const h1 = C1 < C_EPS ? h2Raw : h1Raw;
382
+ const dh = shortArc((C2 < C_EPS ? h1Raw : h2Raw) - h1);
383
+ return [
384
+ lerp(L1, L2, t),
385
+ lerp(C1, C2, t),
386
+ h1 + dh * t
387
+ ];
388
+ }
389
+ const u2f = (v) => v / 255;
390
+ /** Lerp a flat RGBA color array `from` toward `to`. Inputs are 0..1
391
+ * floats (the renderer's color space); outputs are 0..1 floats too.
392
+ * Alpha is always linearly lerped; RGB channels are lerped in the
393
+ * requested color space. OKLab / OKLCh paths bounce through u8 because
394
+ * the gamma-correction LUT and gamut-clip routines are byte-keyed —
395
+ * the round-trip is lossy at <1% per channel, well under the visible
396
+ * threshold for these animations. */
397
+ function lerpColorArray(from, to, t, space = "rgb") {
398
+ if (from.length !== to.length) throw new Error(`lerpColorArray: length mismatch (from=${from.length}, to=${to.length})`);
399
+ if (from.length % 4 !== 0) throw new Error(`lerpColorArray: length ${from.length} not divisible by 4`);
400
+ const out = new Array(from.length);
401
+ const n = from.length / 4;
402
+ if (space === "rgb") {
403
+ for (let i = 0; i < from.length; i++) out[i] = lerp(from[i], to[i], t);
404
+ return out;
405
+ }
406
+ if (space === "oklch") {
407
+ for (let i = 0; i < n; i++) {
408
+ const k = i * 4;
409
+ const fLab = srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2]));
410
+ const tLab = srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2]));
411
+ const midLch = lerpOklch(oklabToOklch(fLab[0], fLab[1], fLab[2]), oklabToOklch(tLab[0], tLab[1], tLab[2]), t);
412
+ const midLab = oklchToOklab(midLch[0], midLch[1], midLch[2]);
413
+ const [r, g, b] = oklabToSrgbU8(midLab[0], midLab[1], midLab[2]);
414
+ out[k] = u2f(r);
415
+ out[k + 1] = u2f(g);
416
+ out[k + 2] = u2f(b);
417
+ out[k + 3] = lerp(from[k + 3], to[k + 3], t);
418
+ }
419
+ return out;
420
+ }
421
+ for (let i = 0; i < n; i++) {
422
+ const k = i * 4;
423
+ const mid = lerpOklab(srgbU8ToOklab(f2u(from[k]), f2u(from[k + 1]), f2u(from[k + 2])), srgbU8ToOklab(f2u(to[k]), f2u(to[k + 1]), f2u(to[k + 2])), t);
424
+ const [r, g, b] = oklabToSrgbU8(mid[0], mid[1], mid[2]);
425
+ out[k] = u2f(r);
426
+ out[k + 1] = u2f(g);
427
+ out[k + 2] = u2f(b);
428
+ out[k + 3] = lerp(from[k + 3], to[k + 3], t);
429
+ }
430
+ return out;
431
+ }
432
+ /** Linear-light channel to sRGB encoding (0..1). Unclamped. */
433
+ function linearToSrgb(c) {
434
+ const a = Math.abs(c);
435
+ const v = a <= .0031308 ? a * 12.92 : 1.055 * Math.pow(a, 1 / 2.4) - .055;
436
+ return c < 0 ? -v : v;
437
+ }
438
+ // ../paint/src/color.ts
439
+ /**
440
+ * Parse a CSS color string into [r, g, b, a] with 0..1 components.
441
+ *
442
+ * Supported forms:
443
+ * - Hex: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa` (any case)
444
+ * - `rgb()` / `rgba()` with integer, float, or percent R/G/B; number or
445
+ * percent alpha; commas or modern space-separated `R G B / A` syntax
446
+ * - `hsl()` / `hsla()` with hue as a unitless number (deg) or with `deg`,
447
+ * `rad`, `grad`, `turn` units; saturation/lightness as percent (or
448
+ * unitless 0..100, as CSS Color 4 reads it); same alpha rules and separator rules
449
+ * as `rgb()`
450
+ * - The 148 CSS named colors plus `transparent`
451
+ * - `color(srgb …)` and `color(srgb-linear …)`; `oklab()` and `oklch()`, clamped into sRGB
452
+ *
453
+ * Not supported: `lab()`, `lch()`, other `color()` spaces, `currentColor`, system
454
+ * colors. Throws on anything unrecognized.
455
+ *
456
+ * Results are cached by input-string identity and shared, which is why the
457
+ * tuple is read-only: renderer hot paths call this per frame.
458
+ */
459
+ function parseColor(input) {
460
+ const cached = CACHE.get(input);
461
+ if (cached !== void 0) return cached;
462
+ const result = parseColorUncached(input);
463
+ if (CACHE.size >= CACHE_MAX) CACHE.clear();
464
+ CACHE.set(input, result);
465
+ return result;
466
+ }
467
+ const CACHE = /* @__PURE__ */ new Map();
468
+ const CACHE_MAX = 1024;
469
+ function parseColorUncached(input) {
470
+ const s = input.trim();
471
+ if (s.startsWith("#")) return parseHex(s);
472
+ const lower = s.toLowerCase();
473
+ if (Object.hasOwn(NAMED_COLORS, lower)) return NAMED_COLORS[lower];
474
+ if (lower.startsWith("rgb")) {
475
+ const parsed = parseRgbFunction(lower);
476
+ if (parsed) return parsed;
477
+ }
478
+ if (lower.startsWith("hsl")) {
479
+ const parsed = parseHslFunction(lower);
480
+ if (parsed) return parsed;
481
+ }
482
+ if (lower.startsWith("color(")) {
483
+ const parsed = parseColorFunction(lower);
484
+ if (parsed) return parsed;
485
+ }
486
+ if (lower.startsWith("ok")) {
487
+ const parsed = parseOkFunction(lower);
488
+ if (parsed) return parsed;
489
+ }
490
+ throw new Error(`parseColor: unrecognized color "${input}"`);
491
+ }
492
+ /**
493
+ * Format [r, g, b, a] (0..1 components) as a hex string. Emits `#rrggbb` when
494
+ * alpha is exactly 1 (or omitted), otherwise `#rrggbbaa`.
495
+ */
496
+ function rgbaToHex(rgba) {
497
+ const [r, g, b] = rgba;
498
+ const a = rgba.length === 4 ? rgba[3] : 1;
499
+ const f = (n) => byteHex(n * 255);
500
+ const base = `#${f(r)}${f(g)}${f(b)}`;
501
+ return a >= 1 ? base : `${base}${f(a)}`;
502
+ }
503
+ function parseHex(s) {
504
+ const bytes = parseHexBytes(s);
505
+ if (!bytes) throw new Error(`parseColor: invalid hex "${s}"`);
506
+ return [
507
+ bytes[0] / 255,
508
+ bytes[1] / 255,
509
+ bytes[2] / 255,
510
+ bytes[3] / 255
511
+ ];
512
+ }
513
+ /** Match `name( body )` and return the trimmed body, or null. */
514
+ function unwrapFn(s, name) {
515
+ if (!s.startsWith(name + "(") || !s.endsWith(")")) return null;
516
+ return s.slice(name.length + 1, -1).trim();
517
+ }
518
+ /**
519
+ * Split a function body into the value tokens (3 channels + optional alpha).
520
+ * Supports both legacy `r, g, b[, a]` and modern `r g b[ / a]` separators.
521
+ * Returns null if the token count is wrong.
522
+ */
523
+ function splitChannels(body) {
524
+ if (body.includes(",")) {
525
+ const parts = body.split(",").map((p) => p.trim());
526
+ if (parts.length !== 3 && parts.length !== 4) return null;
527
+ return {
528
+ rgb: [
529
+ parts[0],
530
+ parts[1],
531
+ parts[2]
532
+ ],
533
+ alpha: parts.length === 4 ? parts[3] : null
534
+ };
535
+ }
536
+ const slash = body.indexOf("/");
537
+ const head = (slash === -1 ? body : body.slice(0, slash)).trim();
538
+ const alpha = slash === -1 ? null : body.slice(slash + 1).trim();
539
+ const parts = head.split(/\s+/);
540
+ if (parts.length !== 3) return null;
541
+ if (alpha !== null && alpha === "") return null;
542
+ return {
543
+ rgb: [
544
+ parts[0],
545
+ parts[1],
546
+ parts[2]
547
+ ],
548
+ alpha
549
+ };
550
+ }
551
+ const CSS_NUMBER = /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/;
552
+ /** A CSS `<number>` token, or null: `Number` alone reads `''` as 0 and accepts `0x10`. */
553
+ function cssNumber(tok) {
554
+ if (!CSS_NUMBER.test(tok)) return null;
555
+ const n = Number(tok);
556
+ return Number.isFinite(n) ? n : null;
557
+ }
558
+ /** Parse a channel value: integer, float, or percent. Returns 0..1 (with `max` as the integer scale). */
559
+ function parseChannel(tok, max) {
560
+ const percent = tok.endsWith("%");
561
+ const n = cssNumber(percent ? tok.slice(0, -1) : tok);
562
+ return n === null ? null : clamp01(n / (percent ? 100 : max));
563
+ }
564
+ /** Alpha may be a number 0..1 or a percent; absent is opaque. */
565
+ function parseAlpha(tok) {
566
+ return tok === null ? 1 : parseChannel(tok, 1);
567
+ }
568
+ function parseRgbFunction(s) {
569
+ const body = unwrapFn(s, "rgba") ?? unwrapFn(s, "rgb");
570
+ if (body === null) return null;
571
+ const channels = splitChannels(body);
572
+ if (!channels) return null;
573
+ const r = parseChannel(channels.rgb[0], 255);
574
+ const g = parseChannel(channels.rgb[1], 255);
575
+ const b = parseChannel(channels.rgb[2], 255);
576
+ const a = parseAlpha(channels.alpha);
577
+ if (r === null || g === null || b === null || a === null) return null;
578
+ return [
579
+ r,
580
+ g,
581
+ b,
582
+ a
583
+ ];
584
+ }
585
+ function parseHslFunction(s) {
586
+ const body = unwrapFn(s, "hsla") ?? unwrapFn(s, "hsl");
587
+ if (body === null) return null;
588
+ const channels = splitChannels(body);
589
+ if (!channels) return null;
590
+ const h = parseHue(channels.rgb[0]);
591
+ const sat = parseChannel(channels.rgb[1], 100);
592
+ const lit = parseChannel(channels.rgb[2], 100);
593
+ const a = parseAlpha(channels.alpha);
594
+ if (h === null || sat === null || lit === null || a === null) return null;
595
+ const [r, g, b] = hslToSrgb(h, sat, lit);
596
+ return [
597
+ r,
598
+ g,
599
+ b,
600
+ a
601
+ ];
602
+ }
603
+ /** `color(srgb …)` or `color(srgb-linear …)`, channels as numbers 0..1 or percents. */
604
+ function parseColorFunction(s) {
605
+ const body = unwrapFn(s, "color");
606
+ const space = body?.match(/^(srgb-linear|srgb)\s+/);
607
+ if (!body || !space || body.includes(",")) return null;
608
+ const channels = splitChannels(body.slice(space[0].length));
609
+ if (!channels) return null;
610
+ const rgb = channels.rgb.map((tok) => parseChannel(tok, 1));
611
+ const a = parseAlpha(channels.alpha);
612
+ if (rgb.some((c) => c === null) || a === null) return null;
613
+ const [r, g, b] = space[1] === "srgb" ? rgb : rgb.map((c) => linearToSrgb(c));
614
+ return [
615
+ clamp01(r),
616
+ clamp01(g),
617
+ clamp01(b),
618
+ a
619
+ ];
620
+ }
621
+ /** `oklab(L a b)` or `oklch(L C h)`, clamped into sRGB. L is 0..1 or a percent; a, b and C are numbers. */
622
+ function parseOkFunction(s) {
623
+ const lch = unwrapFn(s, "oklch");
624
+ const body = lch ?? unwrapFn(s, "oklab");
625
+ if (body === null || body.includes(",")) return null;
626
+ const channels = splitChannels(body);
627
+ if (!channels) return null;
628
+ const L = parsePercentOrNumber(channels.rgb[0]);
629
+ const second = cssNumber(channels.rgb[1]);
630
+ const third = lch !== null ? parseHue(channels.rgb[2]) : cssNumber(channels.rgb[2]);
631
+ const alpha = parseAlpha(channels.alpha);
632
+ if (L === null || second === null || third === null || alpha === null) return null;
633
+ const [, A, B] = lch !== null ? oklchToOklab(L, Math.max(0, second), third * (Math.PI / 180)) : [
634
+ L,
635
+ second,
636
+ third
637
+ ];
638
+ const [r, g, b] = oklabToLinearSrgb(L, A, B).map((c) => clamp01(linearToSrgb(c)));
639
+ return [
640
+ r,
641
+ g,
642
+ b,
643
+ alpha
644
+ ];
645
+ }
646
+ /** Parse a hue token:`<number>`, `<number>deg`, `<number>rad`, `<number>grad`, `<number>turn`. Returns degrees 0..360 (modulo). */
647
+ function parseHue(tok) {
648
+ const unit = /(deg|grad|rad|turn)$/.exec(tok)?.[1];
649
+ const n = cssNumber(unit === void 0 ? tok : tok.slice(0, -unit.length));
650
+ if (n === null) return null;
651
+ const deg = unit === "grad" ? n * .9 : unit === "rad" ? n * (180 / Math.PI) : unit === "turn" ? n * 360 : n;
652
+ return wrapDeg(deg);
653
+ }
654
+ /** An OKLab lightness: a percent or a unitless number 0..1. */
655
+ function parsePercentOrNumber(tok) {
656
+ return parseChannel(tok, 1);
657
+ }
658
+ function clamp01(n) {
659
+ return n < 0 ? 0 : n > 1 ? 1 : n;
660
+ }
661
+ const NAMED_COLORS = (() => {
662
+ const hex = {
663
+ aliceblue: 15792383,
664
+ antiquewhite: 16444375,
665
+ aqua: 65535,
666
+ aquamarine: 8388564,
667
+ azure: 15794175,
668
+ beige: 16119260,
669
+ bisque: 16770244,
670
+ black: 0,
671
+ blanchedalmond: 16772045,
672
+ blue: 255,
673
+ blueviolet: 9055202,
674
+ brown: 10824234,
675
+ burlywood: 14596231,
676
+ cadetblue: 6266528,
677
+ chartreuse: 8388352,
678
+ chocolate: 13789470,
679
+ coral: 16744272,
680
+ cornflowerblue: 6591981,
681
+ cornsilk: 16775388,
682
+ crimson: 14423100,
683
+ cyan: 65535,
684
+ darkblue: 139,
685
+ darkcyan: 35723,
686
+ darkgoldenrod: 12092939,
687
+ darkgray: 11119017,
688
+ darkgreen: 25600,
689
+ darkgrey: 11119017,
690
+ darkkhaki: 12433259,
691
+ darkmagenta: 9109643,
692
+ darkolivegreen: 5597999,
693
+ darkorange: 16747520,
694
+ darkorchid: 10040012,
695
+ darkred: 9109504,
696
+ darksalmon: 15308410,
697
+ darkseagreen: 9419919,
698
+ darkslateblue: 4734347,
699
+ darkslategray: 3100495,
700
+ darkslategrey: 3100495,
701
+ darkturquoise: 52945,
702
+ darkviolet: 9699539,
703
+ deeppink: 16716947,
704
+ deepskyblue: 49151,
705
+ dimgray: 6908265,
706
+ dimgrey: 6908265,
707
+ dodgerblue: 2003199,
708
+ firebrick: 11674146,
709
+ floralwhite: 16775920,
710
+ forestgreen: 2263842,
711
+ fuchsia: 16711935,
712
+ gainsboro: 14474460,
713
+ ghostwhite: 16316671,
714
+ gold: 16766720,
715
+ goldenrod: 14329120,
716
+ gray: 8421504,
717
+ green: 32768,
718
+ greenyellow: 11403055,
719
+ grey: 8421504,
720
+ honeydew: 15794160,
721
+ hotpink: 16738740,
722
+ indianred: 13458524,
723
+ indigo: 4915330,
724
+ ivory: 16777200,
725
+ khaki: 15787660,
726
+ lavender: 15132410,
727
+ lavenderblush: 16773365,
728
+ lawngreen: 8190976,
729
+ lemonchiffon: 16775885,
730
+ lightblue: 11393254,
731
+ lightcoral: 15761536,
732
+ lightcyan: 14745599,
733
+ lightgoldenrodyellow: 16448210,
734
+ lightgray: 13882323,
735
+ lightgreen: 9498256,
736
+ lightgrey: 13882323,
737
+ lightpink: 16758465,
738
+ lightsalmon: 16752762,
739
+ lightseagreen: 2142890,
740
+ lightskyblue: 8900346,
741
+ lightslategray: 7833753,
742
+ lightslategrey: 7833753,
743
+ lightsteelblue: 11584734,
744
+ lightyellow: 16777184,
745
+ lime: 65280,
746
+ limegreen: 3329330,
747
+ linen: 16445670,
748
+ magenta: 16711935,
749
+ maroon: 8388608,
750
+ mediumaquamarine: 6737322,
751
+ mediumblue: 205,
752
+ mediumorchid: 12211667,
753
+ mediumpurple: 9662683,
754
+ mediumseagreen: 3978097,
755
+ mediumslateblue: 8087790,
756
+ mediumspringgreen: 64154,
757
+ mediumturquoise: 4772300,
758
+ mediumvioletred: 13047173,
759
+ midnightblue: 1644912,
760
+ mintcream: 16121850,
761
+ mistyrose: 16770273,
762
+ moccasin: 16770229,
763
+ navajowhite: 16768685,
764
+ navy: 128,
765
+ oldlace: 16643558,
766
+ olive: 8421376,
767
+ olivedrab: 7048739,
768
+ orange: 16753920,
769
+ orangered: 16729344,
770
+ orchid: 14315734,
771
+ palegoldenrod: 15657130,
772
+ palegreen: 10025880,
773
+ paleturquoise: 11529966,
774
+ palevioletred: 14381203,
775
+ papayawhip: 16773077,
776
+ peachpuff: 16767673,
777
+ peru: 13468991,
778
+ pink: 16761035,
779
+ plum: 14524637,
780
+ powderblue: 11591910,
781
+ purple: 8388736,
782
+ rebeccapurple: 6697881,
783
+ red: 16711680,
784
+ rosybrown: 12357519,
785
+ royalblue: 4286945,
786
+ saddlebrown: 9127187,
787
+ salmon: 16416882,
788
+ sandybrown: 16032864,
789
+ seagreen: 3050327,
790
+ seashell: 16774638,
791
+ sienna: 10506797,
792
+ silver: 12632256,
793
+ skyblue: 8900331,
794
+ slateblue: 6970061,
795
+ slategray: 7372944,
796
+ slategrey: 7372944,
797
+ snow: 16775930,
798
+ springgreen: 65407,
799
+ steelblue: 4620980,
800
+ tan: 13808780,
801
+ teal: 32896,
802
+ thistle: 14204888,
803
+ tomato: 16737095,
804
+ turquoise: 4251856,
805
+ violet: 15631086,
806
+ wheat: 16113331,
807
+ white: 16777215,
808
+ whitesmoke: 16119285,
809
+ yellow: 16776960,
810
+ yellowgreen: 10145074
811
+ };
812
+ const rgba = (n) => [
813
+ (n >> 16 & 255) / 255,
814
+ (n >> 8 & 255) / 255,
815
+ (n & 255) / 255,
816
+ 1
817
+ ];
818
+ return {
819
+ transparent: [
820
+ 0,
821
+ 0,
822
+ 0,
823
+ 0
824
+ ],
825
+ ...Object.fromEntries(Object.entries(hex).map(([name, n]) => [name, rgba(n)]))
826
+ };
827
+ })();
828
+ // ../renderer/src/meshPaint/surface.ts
829
+ /** Corner `i` of the boundary walk. */
830
+ function patchCorner(patch, i) {
831
+ return patch.points[(i & 3) * 3];
832
+ }
833
+ /** `true` when the patch carries the four interior points a tensor patch adds. */
834
+ function isTensorPatch(patch) {
835
+ return patch.points.length >= 16;
836
+ }
837
+ /** A patch is twelve boundary points, or sixteen with the interior. Anything
838
+ * else cannot be evaluated, and saying so here beats painting nonsense. */
839
+ function isValidPatch(patch) {
840
+ return patch.points.length === 12 || patch.points.length === 16;
841
+ }
842
+ function bezier(p0, p1, p2, p3, t) {
843
+ const s = 1 - t;
844
+ const a = s * s * s;
845
+ const b = 3 * s * s * t;
846
+ const c = 3 * s * t * t;
847
+ const d = t * t * t;
848
+ return {
849
+ x: a * p0.x + b * p1.x + c * p2.x + d * p3.x,
850
+ y: a * p0.y + b * p1.y + c * p2.y + d * p3.y
851
+ };
852
+ }
853
+ /** The edge leaving corner `i`, as its four control points. */
854
+ function edge(patch, i) {
855
+ const p = patch.points;
856
+ const a = (i & 3) * 3;
857
+ return [
858
+ p[a],
859
+ p[a + 1],
860
+ p[a + 2],
861
+ p[(i + 1 & 3) * 3]
862
+ ];
863
+ }
864
+ /**
865
+ * The patch surface at `(u, v)`, both in `0..1`.
866
+ *
867
+ * `u` runs along the edge leaving corner 0 and `v` along the edge leaving
868
+ * corner 1, so `(0,0)` is corner 0, `(1,0)` corner 1, `(1,1)` corner 2 and
869
+ * `(0,1)` corner 3 — the same walk `colors` is in.
870
+ */
871
+ function evalPatch(patch, u, v) {
872
+ return isTensorPatch(patch) ? evalTensor(patch, u, v) : evalCoons(patch, u, v);
873
+ }
874
+ function evalCoons(patch, u, v) {
875
+ const [b0, b1, b2, b3] = edge(patch, 0);
876
+ const [r0, r1, r2, r3] = edge(patch, 1);
877
+ const [t0, t1, t2, t3] = edge(patch, 2);
878
+ const [l0, l1, l2, l3] = edge(patch, 3);
879
+ const bottom = bezier(b0, b1, b2, b3, u);
880
+ const top = bezier(t0, t1, t2, t3, 1 - u);
881
+ const right = bezier(r0, r1, r2, r3, v);
882
+ const left = bezier(l0, l1, l2, l3, 1 - v);
883
+ const c0 = patchCorner(patch, 0);
884
+ const c1 = patchCorner(patch, 1);
885
+ const c2 = patchCorner(patch, 2);
886
+ const c3 = patchCorner(patch, 3);
887
+ const ruledU = (a, b) => (1 - v) * a + v * b;
888
+ const ruledV = (a, b) => (1 - u) * a + u * b;
889
+ const corner = (k0, k1, k2, k3) => (1 - u) * (1 - v) * k0 + u * (1 - v) * k1 + u * v * k2 + (1 - u) * v * k3;
890
+ return {
891
+ x: ruledU(bottom.x, top.x) + ruledV(left.x, right.x) - corner(c0.x, c1.x, c2.x, c3.x),
892
+ y: ruledU(bottom.y, top.y) + ruledV(left.y, right.y) - corner(c0.y, c1.y, c2.y, c3.y)
893
+ };
894
+ }
895
+ /** The bicubic control net a tensor patch's sixteen points make, as
896
+ * `net[i][j]` with `i` along `u` and `j` along `v`. */
897
+ function tensorNet(patch) {
898
+ const p = patch.points;
899
+ return [
900
+ [
901
+ p[0],
902
+ p[11],
903
+ p[10],
904
+ p[9]
905
+ ],
906
+ [
907
+ p[1],
908
+ p[12],
909
+ p[15],
910
+ p[8]
911
+ ],
912
+ [
913
+ p[2],
914
+ p[13],
915
+ p[14],
916
+ p[7]
917
+ ],
918
+ [
919
+ p[3],
920
+ p[4],
921
+ p[5],
922
+ p[6]
923
+ ]
924
+ ];
925
+ }
926
+ const BERNSTEIN = (t) => {
927
+ const s = 1 - t;
928
+ return [
929
+ s * s * s,
930
+ 3 * s * s * t,
931
+ 3 * s * t * t,
932
+ t * t * t
933
+ ];
934
+ };
935
+ function evalTensor(patch, u, v) {
936
+ const net = tensorNet(patch);
937
+ const bu = BERNSTEIN(u);
938
+ const bv = BERNSTEIN(v);
939
+ let x = 0;
940
+ let y = 0;
941
+ for (let i = 0; i < 4; i++) for (let j = 0; j < 4; j++) {
942
+ const w = bu[i] * bv[j];
943
+ x += w * net[i][j].x;
944
+ y += w * net[i][j].y;
945
+ }
946
+ return {
947
+ x,
948
+ y
949
+ };
950
+ }
951
+ /** Axis-aligned bounds of a patch, sampled on a grid: control points alone
952
+ * bound a Bézier but not tightly. */
953
+ function patchBounds(patch, steps = 8) {
954
+ let minX = Infinity;
955
+ let minY = Infinity;
956
+ let maxX = -Infinity;
957
+ let maxY = -Infinity;
958
+ for (let i = 0; i <= steps; i++) for (let j = 0; j <= steps; j++) {
959
+ const p = evalPatch(patch, i / steps, j / steps);
960
+ if (p.x < minX) minX = p.x;
961
+ if (p.y < minY) minY = p.y;
962
+ if (p.x > maxX) maxX = p.x;
963
+ if (p.y > maxY) maxY = p.y;
964
+ }
965
+ return {
966
+ x: minX,
967
+ y: minY,
968
+ width: maxX - minX,
969
+ height: maxY - minY
970
+ };
971
+ }
972
+ /** Texels a rasterized cell spans at most. The rasterizer interpolates color
973
+ * linearly inside a cell and draws a curved edge as its chord, so this is
974
+ * what keeps a perceptual blend perceptual and an edge curved at any size. */
975
+ const TEXELS_PER_CELL = 10;
976
+ /** Quads per patch on a side, never fewer than 24. */
977
+ function gridFor(size) {
978
+ return Math.max(24, Math.ceil(size / TEXELS_PER_CELL));
979
+ }
980
+ /** The union of every patch's bounds, or `null` when nothing is drawable. */
981
+ function meshBounds(patches) {
982
+ let minX = Infinity;
983
+ let minY = Infinity;
984
+ let maxX = -Infinity;
985
+ let maxY = -Infinity;
986
+ for (const patch of patches) {
987
+ if (!isValidPatch(patch)) continue;
988
+ const b = patchBounds(patch);
989
+ minX = Math.min(minX, b.x);
990
+ minY = Math.min(minY, b.y);
991
+ maxX = Math.max(maxX, b.x + b.width);
992
+ maxY = Math.max(maxY, b.y + b.height);
993
+ }
994
+ if (!Number.isFinite(minX) || maxX <= minX || maxY <= minY) return null;
995
+ return {
996
+ x: minX,
997
+ y: minY,
998
+ width: maxX - minX,
999
+ height: maxY - minY
1000
+ };
1001
+ }
1002
+ /**
1003
+ * Corner colors blended at `(u, v)` in `space`. Three lerps rather than four
1004
+ * weights, because a perceptual space has no meaningful four-way mix — OKLCh's
1005
+ * hue is an arc, which only two endpoints define.
1006
+ */
1007
+ function colorAt(corners, u, v, space) {
1008
+ return lerpColorArray(lerpColorArray(corners[0], corners[1], u, space), lerpColorArray(corners[3], corners[2], u, space), v, space);
1009
+ }
1010
+ /**
1011
+ * Rasterize `patches` into a square bitmap covering their union, or `null`
1012
+ * when no patch is drawable.
1013
+ */
1014
+ function bakeMesh(patches, space = "rgb", size = 256) {
1015
+ const box = meshBounds(patches);
1016
+ if (!box) return null;
1017
+ const pixels = new Uint8ClampedArray(size * size * 4);
1018
+ const grid = gridFor(size);
1019
+ const toTexel = (p) => ({
1020
+ x: (p.x - box.x) / box.width * (size - 1) + .5,
1021
+ y: (p.y - box.y) / box.height * (size - 1) + .5
1022
+ });
1023
+ for (const patch of patches) {
1024
+ if (!isValidPatch(patch)) continue;
1025
+ const corners = patch.colors.map((c) => parseColor(c));
1026
+ for (let i = 0; i < grid; i++) for (let j = 0; j < grid; j++) {
1027
+ const u0 = i / grid;
1028
+ const u1 = (i + 1) / grid;
1029
+ const v0 = j / grid;
1030
+ const v1 = (j + 1) / grid;
1031
+ const quad = [
1032
+ {
1033
+ at: toTexel(evalPatch(patch, u0, v0)),
1034
+ color: colorAt(corners, u0, v0, space)
1035
+ },
1036
+ {
1037
+ at: toTexel(evalPatch(patch, u1, v0)),
1038
+ color: colorAt(corners, u1, v0, space)
1039
+ },
1040
+ {
1041
+ at: toTexel(evalPatch(patch, u1, v1)),
1042
+ color: colorAt(corners, u1, v1, space)
1043
+ },
1044
+ {
1045
+ at: toTexel(evalPatch(patch, u0, v1)),
1046
+ color: colorAt(corners, u0, v1, space)
1047
+ }
1048
+ ];
1049
+ fillTriangle(pixels, size, quad[0], quad[1], quad[2]);
1050
+ fillTriangle(pixels, size, quad[0], quad[2], quad[3]);
1051
+ }
1052
+ }
1053
+ return {
1054
+ pixels,
1055
+ size,
1056
+ box
1057
+ };
1058
+ }
1059
+ /**
1060
+ * One triangle, barycentric, colors interpolated across it. A pixel exactly on
1061
+ * an edge two cells share is claimed by both — harmless, because both carry
1062
+ * the same color there.
1063
+ */
1064
+ function fillTriangle(pixels, size, a, b, c) {
1065
+ const minX = Math.max(0, Math.floor(Math.min(a.at.x, b.at.x, c.at.x)));
1066
+ const maxX = Math.min(size - 1, Math.ceil(Math.max(a.at.x, b.at.x, c.at.x)));
1067
+ const minY = Math.max(0, Math.floor(Math.min(a.at.y, b.at.y, c.at.y)));
1068
+ const maxY = Math.min(size - 1, Math.ceil(Math.max(a.at.y, b.at.y, c.at.y)));
1069
+ if (maxX < minX || maxY < minY) return;
1070
+ const area = (b.at.x - a.at.x) * (c.at.y - a.at.y) - (c.at.x - a.at.x) * (b.at.y - a.at.y);
1071
+ if (Math.abs(area) < 1e-9) return;
1072
+ for (let y = minY; y <= maxY; y++) for (let x = minX; x <= maxX; x++) {
1073
+ const px = x + .5;
1074
+ const py = y + .5;
1075
+ const w0 = ((b.at.x - px) * (c.at.y - py) - (c.at.x - px) * (b.at.y - py)) / area;
1076
+ const w1 = ((c.at.x - px) * (a.at.y - py) - (a.at.x - px) * (c.at.y - py)) / area;
1077
+ const w2 = 1 - w0 - w1;
1078
+ if (w0 < -1e-6 || w1 < -1e-6 || w2 < -1e-6) continue;
1079
+ const k = (y * size + x) * 4;
1080
+ for (let ch = 0; ch < 4; ch++) pixels[k + ch] = (w0 * a.color[ch] + w1 * b.color[ch] + w2 * c.color[ch]) * 255;
1081
+ }
1082
+ }
1083
+ /** The largest bake, whatever the context allows: 16 MiB of RGBA, and a bake
1084
+ * that already takes a noticeable moment on the CPU. */
1085
+ const MESH_BAKE_MAX = 2048;
1086
+ /** Bytes of baked texture one renderer keeps before evicting the least
1087
+ * recently drawn. */
1088
+ const MESH_BAKE_CACHE_BYTES = 67108864;
1089
+ /**
1090
+ * The bake side for a paint drawn `devicePx` device pixels across, on a
1091
+ * context accepting `maxTextureSize`: the next power of two at or above it,
1092
+ * clamped to `[MESH_BAKE_MIN, MESH_BAKE_MAX]` and to the context. A size that
1093
+ * cannot be measured gets `MESH_BAKE_SIZE`.
1094
+ */
1095
+ function meshBakeSize(devicePx, maxTextureSize) {
1096
+ const ceiling = Math.min(MESH_BAKE_MAX, floorPow2(maxTextureSize));
1097
+ if (Number.isNaN(devicePx)) return Math.min(256, ceiling);
1098
+ if (devicePx <= 32) return Math.min(32, ceiling);
1099
+ if (devicePx >= ceiling) return ceiling;
1100
+ return Math.min(ceiling, 2 ** Math.ceil(Math.log2(devicePx)));
1101
+ }
1102
+ function floorPow2(n) {
1103
+ if (!(n >= 1)) return 32;
1104
+ if (!Number.isFinite(n)) return MESH_BAKE_MAX;
1105
+ return 2 ** Math.floor(Math.log2(n));
1106
+ }
1107
+ /**
1108
+ * Bakes keyed by paint and bake size, least recently used first out.
1109
+ *
1110
+ * The paint is held weakly, so a paint nobody draws any more does not pin its
1111
+ * key; its texture stays until eviction reaches it, which the bounds keep
1112
+ * finite. `free` runs for every value that leaves, by eviction, replacement or
1113
+ * `clear`.
1114
+ */
1115
+ var MeshBakeCache = class {
1116
+ free;
1117
+ budgetBytes;
1118
+ maxEntries;
1119
+ byPaint = /* @__PURE__ */ new WeakMap();
1120
+ /** Insertion order is recency: a hit is deleted and re-added. */
1121
+ order = /* @__PURE__ */ new Set();
1122
+ held = 0;
1123
+ constructor(free, budgetBytes = MESH_BAKE_CACHE_BYTES, maxEntries = 256) {
1124
+ this.free = free;
1125
+ this.budgetBytes = budgetBytes;
1126
+ this.maxEntries = maxEntries;
1127
+ }
1128
+ /** Bytes the held bakes occupy, as RGBA8. */
1129
+ get bytes() {
1130
+ return this.held;
1131
+ }
1132
+ /** Bakes held. */
1133
+ get size() {
1134
+ return this.order.size;
1135
+ }
1136
+ get(paint, size) {
1137
+ const entry = this.byPaint.get(paint)?.get(size);
1138
+ if (!entry) return void 0;
1139
+ this.order.delete(entry);
1140
+ this.order.add(entry);
1141
+ return entry.value;
1142
+ }
1143
+ set(paint, size, value) {
1144
+ let bySize = this.byPaint.get(paint);
1145
+ if (!bySize) {
1146
+ bySize = /* @__PURE__ */ new Map();
1147
+ this.byPaint.set(paint, bySize);
1148
+ }
1149
+ const old = bySize.get(size);
1150
+ if (old) this.drop(old);
1151
+ const entry = {
1152
+ value,
1153
+ size,
1154
+ bySize
1155
+ };
1156
+ bySize.set(size, entry);
1157
+ this.order.add(entry);
1158
+ this.held += size * size * 4;
1159
+ this.evict(entry);
1160
+ }
1161
+ /** Free every bake. The cache stays usable. */
1162
+ clear() {
1163
+ for (const entry of [...this.order]) this.drop(entry);
1164
+ }
1165
+ /** Oldest first until both bounds hold, never evicting `keep` — the bake
1166
+ * the caller is about to draw. */
1167
+ evict(keep) {
1168
+ for (const entry of this.order) {
1169
+ if (this.held <= this.budgetBytes && this.order.size <= this.maxEntries) return;
1170
+ if (entry !== keep) this.drop(entry);
1171
+ }
1172
+ }
1173
+ drop(entry) {
1174
+ if (!this.order.delete(entry)) return;
1175
+ entry.bySize.delete(entry.size);
1176
+ this.held -= entry.size * entry.size * 4;
1177
+ this.free(entry.value);
1178
+ }
1179
+ };
1180
+ // ../renderer/src/meshPaint/meshShader.ts
1181
+ /**
1182
+ * GLSL ES 3.0 sources for the mesh-gradient paint.
1183
+ *
1184
+ * Everything outside the bake's box is transparent: a mesh covers the area its
1185
+ * patches cover, not the whole shape it is filling, and a clamped read would
1186
+ * otherwise smear its border colors across the rest.
1187
+ *
1188
+ * `u_meshSize` is the bake's box in paint space, measured from its corner,
1189
+ * which `u_worldInv` puts at zero; the bake maps that box onto texel
1190
+ * *centers*, which is the half-texel the uv rescale accounts for. Output is PREMULTIPLIED alpha.
1191
+ */
1192
+ /** The id this program is registered under. */
1193
+ const MESH_PROGRAM_ID = "kit:mesh-gradient";
1194
+ const MESH_VERT_SRC = `#version 300 es
1195
+ in vec2 a_position;
1196
+ uniform mat3 u_proj;
1197
+ uniform mat3 u_model;
1198
+ uniform vec2 u_origin;
1199
+ uniform mat3 u_worldInv;
1200
+ out vec2 v_world;
1201
+ void main() {
1202
+ vec3 screen = u_model * vec3(a_position - u_origin, 1.0);
1203
+ vec3 clip = u_proj * vec3(screen.xy, 1.0);
1204
+ gl_Position = vec4(clip.xy, 0.0, 1.0);
1205
+ vec3 world = u_worldInv * vec3(screen.xy, 1.0);
1206
+ v_world = world.xy;
1207
+ }
1208
+ `;
1209
+ const MESH_FRAG_SRC = `#version 300 es
1210
+ precision highp float;
1211
+ in vec2 v_world;
1212
+ uniform sampler2D u_sampler;
1213
+ uniform vec2 u_meshSize;
1214
+ uniform float u_opacity;
1215
+ uniform float u_alpha;
1216
+ out vec4 outColor;
1217
+ void main() {
1218
+ vec2 t = v_world / max(u_meshSize, vec2(0.0001));
1219
+ if (t.x < 0.0 || t.x > 1.0 || t.y < 0.0 || t.y > 1.0) {
1220
+ outColor = vec4(0.0);
1221
+ return;
1222
+ }
1223
+ vec2 texels = vec2(textureSize(u_sampler, 0));
1224
+ vec2 uv = (t * (texels - 1.0) + 0.5) / texels;
1225
+ vec4 texel = texture(u_sampler, uv);
1226
+ float a = texel.a * u_opacity * u_alpha;
1227
+ outColor = vec4(texel.rgb * a, a);
1228
+ }
1229
+ `;
1230
+ // ../renderer/src/gpu/webgpu/wgsl/common.ts
1231
+ /** Pieces the kit's WGSL programs are assembled from. */
1232
+ /**
1233
+ * Element types for a uniform array whose GLSL element is a `float` or a
1234
+ * `vec2`: WGSL's uniform address space wants a 16-byte array stride, so each
1235
+ * element sits in a struct padded to 16. Read one as `u.u_alpha[i].v`; set
1236
+ * the array by its GLSL name, flat, as GL takes it.
1237
+ */
1238
+ const SLOT_STRUCTS = {
1239
+ F32Slot: "struct F32Slot { @size(16) v: f32 }",
1240
+ Vec2Slot: "struct Vec2Slot { @size(16) v: vec2f }"
1241
+ };
1242
+ /**
1243
+ * The viewport fold: a backend whose viewports must lie inside their target
1244
+ * clamps one that reaches past it, and maps clip space from the viewport asked
1245
+ * for onto the one it set by this scale (`xy`) and offset (`zw`), per draw.
1246
+ * Every vertex entry point passes its position through `weasel_clip`.
1247
+ */
1248
+ const NDC_WGSL = `
1249
+ @group(2) @binding(0) var<uniform> weasel_ndc: vec4f;
1250
+ fn weasel_clip(p: vec4f) -> vec4f {
1251
+ return vec4f(p.xy * weasel_ndc.xy + weasel_ndc.zw, p.zw);
1252
+ }
1253
+ `;
1254
+ /**
1255
+ * `struct Uniforms` at `@group(0) @binding(0)` as `u`, holding `members`
1256
+ * (`name: type` each, the GLSL uniform names) and, where `ids` is on,
1257
+ * `u_weaselId`, beside `NDC_WGSL`. A member named twice is declared once.
1258
+ */
1259
+ function uniformsWgsl(members, ids = true) {
1260
+ const seen = /* @__PURE__ */ new Map();
1261
+ for (const m of [...members, ...ids ? ["u_weaselId: vec4f"] : []]) {
1262
+ const name = m.slice(0, m.indexOf(":")).trim();
1263
+ if (!seen.has(name)) seen.set(name, m.trim());
1264
+ }
1265
+ const body = [...seen.values()];
1266
+ return `${Object.entries(SLOT_STRUCTS).filter(([name]) => body.some((m) => m.includes(`<${name},`))).map(([, decl]) => `${decl}\n`).join("")}struct Uniforms {\n${body.map((m) => ` ${m},`).join("\n")}\n}
1267
+ @group(0) @binding(0) var<uniform> u: Uniforms;
1268
+ ${NDC_WGSL}`;
1269
+ }
1270
+ /** A group-1 texture `name` at `binding`, beside its sampler at `binding + 1`. */
1271
+ function textureWgsl(name, binding) {
1272
+ return `@group(1) @binding(${binding}) var ${name}: texture_2d<f32>;
1273
+ @group(1) @binding(${binding + 1}) var ${name}_sampler: sampler;
1274
+ `;
1275
+ }
1276
+ /** What a path program's vertex stage reads. */
1277
+ const PATH_VERTEX_MEMBERS = [
1278
+ "u_proj: mat3x3f",
1279
+ "u_model: mat3x3f",
1280
+ "u_origin: vec2f"
1281
+ ];
1282
+ /** A path vertex in screen space, and a screen point in clip space. */
1283
+ const PATH_VERTEX_WGSL = `
1284
+ fn screenOf(a_position: vec2f) -> vec2f {
1285
+ return (u.u_model * vec3f(a_position - u.u_origin, 1.0)).xy;
1286
+ }
1287
+
1288
+ fn clipOf(screen: vec2f) -> vec4f {
1289
+ let clip = u.u_proj * vec3f(screen, 1.0);
1290
+ return weasel_clip(vec4f(clip.xy, 0.0, 1.0));
1291
+ }
1292
+ `;
1293
+ // ../renderer/src/gpu/webgpu/wgsl/idOut.ts
1294
+ /** The id output every WGSL fragment entry writes beside its color, the
1295
+ * counterpart of `withIdOutput`'s GLSL rewrite: `id.rgb` is the id's three
1296
+ * bytes, `id.a` the least alpha a fragment claims its pixel with. A draw
1297
+ * outside an id frame has no target at location 1, and the write is dropped. */
1298
+ const ID_OUT_WGSL = `
1299
+ struct WeaselOut {
1300
+ @location(0) color: vec4f,
1301
+ @location(1) id: vec4f,
1302
+ }
1303
+
1304
+ fn weasel_out(color: vec4f, id: vec4f) -> WeaselOut {
1305
+ var o: WeaselOut;
1306
+ o.color = color;
1307
+ o.id = select(vec4f(0.0), vec4f(id.rgb, 1.0), color.a > 0.0 && color.a >= id.a);
1308
+ return o;
1309
+ }
1310
+ `;
1311
+ // ../renderer/src/gpu/webgpu/wgsl/paintVertex.ts
1312
+ /** The vertex stage every paint drawn over a path shares, gradients, patterns
1313
+ * and the mesh: the path's vertex in clip space, and `u_worldInv` of its
1314
+ * screen point as the paint-space point `v_world`. */
1315
+ const PAINT_VERTEX_MEMBERS = [...PATH_VERTEX_MEMBERS, "u_worldInv: mat3x3f"];
1316
+ const PAINT_VERTEX_WGSL = `${ID_OUT_WGSL}${PATH_VERTEX_WGSL}
1317
+ struct VOut {
1318
+ @builtin(position) position: vec4f,
1319
+ @location(0) v_world: vec2f,
1320
+ }
1321
+
1322
+ @vertex fn vs(@location(0) a_position: vec2f) -> VOut {
1323
+ var o: VOut;
1324
+ let screen = screenOf(a_position);
1325
+ o.position = clipOf(screen);
1326
+ o.v_world = (u.u_worldInv * vec3f(screen, 1.0)).xy;
1327
+ return o;
1328
+ }
1329
+ `;
1330
+ // ../renderer/src/gpu/webgpu/wgsl/meshPaint.ts
1331
+ /** `meshPaint/meshShader.ts` (`kit:mesh-gradient`) in WGSL: the straight-RGBA
1332
+ * bake over `u_meshSize`, transparent outside it. */
1333
+ const MESH_WGSL = `${uniformsWgsl([
1334
+ ...PAINT_VERTEX_MEMBERS,
1335
+ "u_meshSize: vec2f",
1336
+ "u_opacity: f32",
1337
+ "u_alpha: f32"
1338
+ ])}
1339
+ ${PAINT_VERTEX_WGSL}${textureWgsl("u_sampler", 0)}
1340
+ @fragment fn fs(in: VOut) -> WeaselOut {
1341
+ let t = in.v_world / max(u.u_meshSize, vec2f(0.0001));
1342
+ let texels = vec2f(textureDimensions(u_sampler));
1343
+ let uv = (t * (texels - 1.0) + 0.5) / texels;
1344
+ // Sampled before the box test: WGSL takes no implicit derivative past a branch on a varying.
1345
+ let texel = textureSample(u_sampler, u_sampler_sampler, uv);
1346
+ let outside = any(t < vec2f(0.0)) || any(t > vec2f(1.0));
1347
+ let a = texel.a * u.u_opacity * u.u_alpha;
1348
+ return weasel_out(select(vec4f(texel.rgb * a, a), vec4f(0.0), outside), u.u_weaselId);
1349
+ }
1350
+ `;
1351
+ // ../renderer/src/meshPaint/meshPaint.ts
1352
+ /** The kind's id, as `Paint['fill']` carries it. */
1353
+ const MESH_GRADIENT_KIND = "mesh-gradient";
1354
+ function asMesh$1(fill) {
1355
+ return fill;
1356
+ }
1357
+ function asFill$1(mesh) {
1358
+ return mesh;
1359
+ }
1360
+ /**
1361
+ * `color` moved in OKLCh — lightness, chroma and hue by the given deltas, with
1362
+ * its alpha kept. The seed's corners come from one color, and they have to
1363
+ * differ enough to read as a mesh rather than as a flat fill.
1364
+ */
1365
+ function shifted(color, dL, cScale, dHueDeg) {
1366
+ const [r, g, b, a] = parseColor(color);
1367
+ const [L, A, B] = srgbFloatToOklab(r, g, b);
1368
+ const [, C, h] = oklabToOklch(L, A, B);
1369
+ const [nL, nA, nB] = oklchToOklab(Math.min(1, Math.max(0, L + dL)), Math.max(0, C * cScale), h + dHueDeg * DEG_TO_RAD);
1370
+ const [nr, ng, nb] = oklabToSrgbU8(nL, nA, nB);
1371
+ return rgbaToHex([
1372
+ nr / 255,
1373
+ ng / 255,
1374
+ nb / 255,
1375
+ a
1376
+ ]);
1377
+ }
1378
+ /** A one-patch square covering the unit box, its four corners four readings of
1379
+ * `color` — a mesh seeded from a solid has to show *something* curved, or
1380
+ * switching kind looks like nothing happened. */
1381
+ function seedMeshPatch(color) {
1382
+ const corners = [
1383
+ {
1384
+ x: 0,
1385
+ y: 0
1386
+ },
1387
+ {
1388
+ x: 1,
1389
+ y: 0
1390
+ },
1391
+ {
1392
+ x: 1,
1393
+ y: 1
1394
+ },
1395
+ {
1396
+ x: 0,
1397
+ y: 1
1398
+ }
1399
+ ];
1400
+ const points = [];
1401
+ for (let i = 0; i < 4; i++) {
1402
+ const a = corners[i];
1403
+ const b = corners[(i + 1) % 4];
1404
+ const nx = (b.y - a.y) * .125;
1405
+ const ny = -(b.x - a.x) * .125;
1406
+ points.push(a, {
1407
+ x: a.x + (b.x - a.x) / 3 + nx,
1408
+ y: a.y + (b.y - a.y) / 3 + ny
1409
+ }, {
1410
+ x: a.x + 2 * (b.x - a.x) / 3 + nx,
1411
+ y: a.y + 2 * (b.y - a.y) / 3 + ny
1412
+ });
1413
+ }
1414
+ return {
1415
+ kind: MESH_GRADIENT_KIND,
1416
+ patches: [{
1417
+ points,
1418
+ colors: [
1419
+ color,
1420
+ shifted(color, .14, .85, 0),
1421
+ shifted(color, -.06, 1.1, 38),
1422
+ shifted(color, -.16, 1, -22)
1423
+ ]
1424
+ }],
1425
+ units: "bounds"
1426
+ };
1427
+ }
1428
+ /** The straight-edged patch covering `[x0, x1] × [0, 1]`, in walk order. */
1429
+ function bandPatch(x0, x1, left, right) {
1430
+ const corners = [
1431
+ {
1432
+ x: x0,
1433
+ y: 0
1434
+ },
1435
+ {
1436
+ x: x1,
1437
+ y: 0
1438
+ },
1439
+ {
1440
+ x: x1,
1441
+ y: 1
1442
+ },
1443
+ {
1444
+ x: x0,
1445
+ y: 1
1446
+ }
1447
+ ];
1448
+ const points = [];
1449
+ for (let i = 0; i < 4; i++) {
1450
+ const a = corners[i];
1451
+ const b = corners[(i + 1) % 4];
1452
+ points.push(a, {
1453
+ x: a.x + (b.x - a.x) / 3,
1454
+ y: a.y + (b.y - a.y) / 3
1455
+ }, {
1456
+ x: a.x + 2 * (b.x - a.x) / 3,
1457
+ y: a.y + 2 * (b.y - a.y) / 3
1458
+ });
1459
+ }
1460
+ return {
1461
+ points,
1462
+ colors: [
1463
+ left,
1464
+ right,
1465
+ right,
1466
+ left
1467
+ ]
1468
+ };
1469
+ }
1470
+ /**
1471
+ * A stop list as a mesh: one full-height band per gap between neighboring
1472
+ * stops, colored left to right. The bands blend exactly the way the ramp
1473
+ * does, so a horizontal gradient survives the switch unchanged. A zero-width
1474
+ * gap is a hard break and gets no band.
1475
+ */
1476
+ function meshFromStops(stops) {
1477
+ const sorted = [...stops].sort((a, b) => a.offset - b.offset);
1478
+ if (sorted.length === 1) sorted.push({
1479
+ offset: 1,
1480
+ color: sorted[0].color
1481
+ });
1482
+ if (sorted.length === 0) return seedMeshPatch("#000000ff");
1483
+ const patches = [];
1484
+ for (let i = 0; i < sorted.length - 1; i++) {
1485
+ const a = sorted[i];
1486
+ const b = sorted[i + 1];
1487
+ if (b.offset > a.offset) patches.push(bandPatch(a.offset, b.offset, a.color, b.color));
1488
+ }
1489
+ return {
1490
+ kind: MESH_GRADIENT_KIND,
1491
+ patches,
1492
+ units: "bounds"
1493
+ };
1494
+ }
1495
+ /**
1496
+ * A mesh read as a stop list: every patch's top edge — corner 0 to corner 1 —
1497
+ * placed by its `x` across the mesh's horizontal extent. The inverse of
1498
+ * `meshFromStops`, and for any other mesh the ramp across its top.
1499
+ */
1500
+ function meshStops(mesh) {
1501
+ const valid = mesh.patches.filter(isValidPatch);
1502
+ if (valid.length === 0) return [];
1503
+ const xs = valid.flatMap((p) => [p.points[0].x, p.points[3].x]);
1504
+ const lo = minOf(xs);
1505
+ const span = maxOf(xs) - lo;
1506
+ const offsetOf = (x) => span > 0 ? (x - lo) / span : 0;
1507
+ const stops = [];
1508
+ const seen = /* @__PURE__ */ new Set();
1509
+ for (const patch of valid) for (const [point, color] of [[patch.points[0], patch.colors[0]], [patch.points[3], patch.colors[1]]]) {
1510
+ const offset = offsetOf(point.x);
1511
+ const key = `${offset} ${color}`;
1512
+ if (seen.has(key)) continue;
1513
+ seen.add(key);
1514
+ stops.push({
1515
+ offset,
1516
+ color
1517
+ });
1518
+ }
1519
+ return stops.sort((a, b) => a.offset - b.offset);
1520
+ }
1521
+ /** Every patch mapped through `move`. */
1522
+ function mapPatches(mesh, move) {
1523
+ return mesh.patches.map((patch) => ({
1524
+ ...patch,
1525
+ points: patch.points.map(move)
1526
+ }));
1527
+ }
1528
+ /** The paint a pose-frame copy was made from. A copy is rebuilt whenever its
1529
+ * node's pose changes, and bakes the same texels as its source. */
1530
+ const BAKE_SOURCE = /* @__PURE__ */ new WeakMap();
1531
+ const CACHES = /* @__PURE__ */ new WeakMap();
1532
+ function cacheFor(ctx) {
1533
+ let cache = CACHES.get(ctx.resources);
1534
+ if (!cache) {
1535
+ const made = new MeshBakeCache((texture) => ctx.deleteTexture(texture));
1536
+ ctx.resources.onRelease(() => {
1537
+ made.clear();
1538
+ CACHES.delete(ctx.resources);
1539
+ });
1540
+ CACHES.set(ctx.resources, made);
1541
+ cache = made;
1542
+ }
1543
+ return cache;
1544
+ }
1545
+ /** Device pixels the larger side of `box` covers when drawn in `units`. */
1546
+ function devicePixelsOf(ctx, mesh, box) {
1547
+ const m = ctx.spaceToDevice(mesh.units);
1548
+ if (!m) return NaN;
1549
+ return Math.max(box.width * Math.hypot(m[0], m[1]), box.height * Math.hypot(m[3], m[4]));
1550
+ }
1551
+ function bakeFor(ctx, mesh) {
1552
+ const box = meshBounds(mesh.patches);
1553
+ if (!box) return null;
1554
+ const size = meshBakeSize(devicePixelsOf(ctx, mesh, box), ctx.maxTextureSize);
1555
+ const cache = cacheFor(ctx);
1556
+ const key = BAKE_SOURCE.get(mesh) ?? mesh;
1557
+ const hit = cache.get(key, size);
1558
+ if (hit) return {
1559
+ texture: hit,
1560
+ box
1561
+ };
1562
+ const baked = bakeMesh(mesh.patches, mesh.interpolate ?? "rgb", size);
1563
+ if (!baked) return null;
1564
+ const texture = ctx.createTexture(baked.size, baked.size, baked.pixels);
1565
+ cache.set(key, size, texture);
1566
+ return {
1567
+ texture,
1568
+ box
1569
+ };
1570
+ }
1571
+ function bindMesh(ctx, fill) {
1572
+ const mesh = asMesh$1(fill);
1573
+ if (!mesh.patches.some(isValidPatch)) return null;
1574
+ const entry = bakeFor(ctx, mesh);
1575
+ if (!entry) return null;
1576
+ const { box } = entry;
1577
+ const inverse = ctx.spaceInverse(mesh.units, box);
1578
+ if (!inverse) return null;
1579
+ return {
1580
+ program: MESH_PROGRAM_ID,
1581
+ uniforms: {
1582
+ u_worldInv: mat3.toUniform(inverse),
1583
+ u_sampler: entry.texture,
1584
+ u_meshSize: [box.width, box.height],
1585
+ u_opacity: mesh.opacity ?? 1,
1586
+ u_alpha: ctx.alpha
1587
+ }
1588
+ };
1589
+ }
1590
+ /** The kind's draw half, shader program included. Core adds the editor's
1591
+ * slots and registers the whole entry. */
1592
+ const meshDrawKind = {
1593
+ id: MESH_GRADIENT_KIND,
1594
+ programs: { [MESH_PROGRAM_ID]: {
1595
+ glsl: {
1596
+ vert: MESH_VERT_SRC,
1597
+ frag: MESH_FRAG_SRC
1598
+ },
1599
+ wgsl: { frag: MESH_WGSL }
1600
+ } },
1601
+ bind: bindMesh,
1602
+ inPoseFrame: (fill, box) => {
1603
+ const mesh = asMesh$1(fill);
1604
+ if (mesh.units !== "bounds") return fill;
1605
+ const posed = asFill$1({
1606
+ ...mesh,
1607
+ patches: mapPatches(mesh, (p) => ({
1608
+ x: box.x + p.x * box.width,
1609
+ y: box.y + p.y * box.height
1610
+ })),
1611
+ units: "local"
1612
+ });
1613
+ BAKE_SOURCE.set(posed, fill);
1614
+ return posed;
1615
+ },
1616
+ toBoundsFrame: (fill, box) => {
1617
+ const mesh = asMesh$1(fill);
1618
+ if (mesh.units === "bounds" || box.width === 0 || box.height === 0) return fill;
1619
+ return asFill$1({
1620
+ ...mesh,
1621
+ patches: mapPatches(mesh, (p) => ({
1622
+ x: (p.x - box.x) / box.width,
1623
+ y: (p.y - box.y) / box.height
1624
+ })),
1625
+ units: "bounds"
1626
+ });
1627
+ }
1628
+ };
1629
+ /**
1630
+ * The `<defs>` entry for a mesh paint, in weasel's own namespace.
1631
+ *
1632
+ * Not SVG's abandoned `<meshgradient>`: that vocabulary only reaches Coons
1633
+ * patches, shares patch edges implicitly — a reader that gets the sharing
1634
+ * wrong tears the surface rather than failing outright — and has exactly one
1635
+ * implementation in the world. Ours writes every patch's points in full.
1636
+ * `@weasel-js/svg` puts the paint fallback color beside the reference, so a
1637
+ * foreign renderer paints flat instead of nothing.
1638
+ */
1639
+ function meshGradientXml(id, mesh) {
1640
+ const P = "wzl";
1641
+ return `<${P}:meshGradient id="${id}" gradientUnits="${mesh.units === "bounds" ? "objectBoundingBox" : "userSpaceOnUse"}"${mesh.interpolate && mesh.interpolate !== "rgb" ? ` interpolate="${mesh.interpolate}"` : ""}>${mesh.patches.map((patch) => {
1642
+ const points = patch.points.map((p) => `${trimNumber(p.x)},${trimNumber(p.y)}`).join(" ");
1643
+ const colors = patch.colors.join(" ");
1644
+ return `<${P}:patch points="${points}" colors="${colors}"/>`;
1645
+ }).join("")}</${P}:meshGradient>`;
1646
+ }
1647
+ // src/meshKind.ts
1648
+ const asMesh = (fill) => fill;
1649
+ const asFill = (mesh) => mesh;
1650
+ /** The `mesh-gradient` kind's registry entry. `./registerMesh` registers it;
1651
+ * the paint-kind registry loads it on demand otherwise. */
1652
+ const meshGradientKind = {
1653
+ ...meshDrawKind,
1654
+ label: "Mesh",
1655
+ icon: "paint-kinds:mesh",
1656
+ seed: (color) => asFill(seedMeshPatch(color)),
1657
+ colorOf: (paint) => asMesh(paint).patches?.[0]?.colors?.[0],
1658
+ stopsOf: (paint) => meshStops(asMesh(paint)),
1659
+ fromStops: (stops) => asFill(meshFromStops(stops)),
1660
+ toSvg: (id, fill) => meshGradientXml(id, asMesh(fill))
1661
+ };
1662
+ export { meshGradientKind };
1663
+
1664
+ //# sourceMappingURL=meshKindLazy.js.map