@weasel-js/renderer 0.0.0-stage → 1.10.0

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,1487 @@
1
+ import { ownTextureIds, rasterizeTile, drawTileShapes, tileGeometry, tileSize, registerTextureAs, textureRegistry, unregisterTexture } from './chunk-Q4SIHV7Q.js';
2
+ import { defaultOpenFill, pathFromD, boundsOfPath } from '@weasel-js/geom';
3
+ import { tessellate } from '@weasel-js/geom/tessellate';
4
+ import { createReflectable, createEmitter } from '@weasel-js/registry';
5
+ import { resolveStrokeWidth, strokeInsets, tessellateStroke, markerGeneration, screenSpaceKey, markerHeads, metricKey, getMarker, markerKeyOf, markerReadsKey } from '@weasel-js/stroke';
6
+ import { isTileKind, isPatternPaint, tileSpecOf, isTilePaint, patternPlacementOf } from '@weasel-js/paint';
7
+ import { GLYPH_COVERAGE_GLSL } from '@weasel-js/font';
8
+
9
+ // src/cache/uploadPremultiplied.ts
10
+ function uploadPremultiplied(gl, source) {
11
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
12
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
13
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
14
+ }
15
+
16
+ // src/cache/GLImageCache.ts
17
+ var DEFAULT_MAX_TEXTURE_SIDE = 4096;
18
+ var live = /* @__PURE__ */ new Set();
19
+ function releaseImageSource(key) {
20
+ for (const cache7 of live) cache7.release(key);
21
+ }
22
+ function imageSourceInLatestFrame(key) {
23
+ for (const cache7 of live) if (cache7.drewInLatestFrame(key)) return true;
24
+ return false;
25
+ }
26
+ function maxImageTextureSide() {
27
+ let side = Infinity;
28
+ for (const cache7 of live) side = Math.min(side, cache7.maxTextureSide);
29
+ return Number.isFinite(side) ? side : DEFAULT_MAX_TEXTURE_SIDE;
30
+ }
31
+ var GLImageCache = class {
32
+ /** `minification` selects the MIN_FILTER strategy for uploaded textures.
33
+ * `'mipmap'` generates mipmaps and filters LINEAR_MIPMAP_LINEAR: when a
34
+ * large source bitmap is drawn small, bilinear-only minification
35
+ * undersamples and produces moiré. `'auto'` pays for that only on the
36
+ * textures a frame draws small, when it first does. */
37
+ constructor(gl, minification = "linear") {
38
+ this.gl = gl;
39
+ this.minification = minification;
40
+ const reported = gl.getParameter(gl.MAX_TEXTURE_SIZE);
41
+ this.maxTextureSide = typeof reported === "number" && reported > 0 ? reported : DEFAULT_MAX_TEXTURE_SIDE;
42
+ this.finalizer = new FinalizationRegistry((tex) => {
43
+ if (this.textures.delete(tex)) this.pendingDeletes.push(tex);
44
+ });
45
+ live.add(this);
46
+ }
47
+ gl;
48
+ minification;
49
+ /** This context's `MAX_TEXTURE_SIZE`. */
50
+ maxTextureSide;
51
+ map = /* @__PURE__ */ new WeakMap();
52
+ /** Every texture `map` holds, so `dispose` can reach them — a WeakMap
53
+ * cannot be enumerated. */
54
+ textures = /* @__PURE__ */ new Set();
55
+ /**
56
+ * MAG_FILTER each texture currently carries, so a redundant write can be
57
+ * skipped. The batch sets this per flush — the same bitmap can be drawn at
58
+ * both filters in one frame — but filtering is state on the *texture
59
+ * object*, not on the unit, so re-asserting a value it already has is a
60
+ * write to a live texture for no reason.
61
+ */
62
+ magFilters = /* @__PURE__ */ new WeakMap();
63
+ finalizer;
64
+ pendingDeletes = [];
65
+ /** Under `'auto'`, the sources whose mipmaps are built. */
66
+ mipped = /* @__PURE__ */ new WeakSet();
67
+ frame = 0;
68
+ lastDrawn = /* @__PURE__ */ new WeakMap();
69
+ /** Open a frame: what {@link drewInLatestFrame} answers about from here on.
70
+ * The renderer calls this at the top of each `render()`. */
71
+ beginFrame() {
72
+ this.frame++;
73
+ this.drainPendingDeletes();
74
+ }
75
+ /** Whether `key` was uploaded or bound since the last {@link beginFrame}. */
76
+ drewInLatestFrame(key) {
77
+ return this.lastDrawn.get(key) === this.frame;
78
+ }
79
+ /** Delete the textures of sources collected since the last call. */
80
+ drainPendingDeletes() {
81
+ if (this.pendingDeletes.length === 0) return;
82
+ for (const tex of this.pendingDeletes) this.gl.deleteTexture(tex);
83
+ this.pendingDeletes.length = 0;
84
+ }
85
+ /** Delete `key`'s texture, if it has one. */
86
+ release(key) {
87
+ const tex = this.map.get(key);
88
+ if (!tex) return;
89
+ this.gl.deleteTexture(tex);
90
+ this.textures.delete(tex);
91
+ this.finalizer.unregister(key);
92
+ this.map.delete(key);
93
+ this.magFilters.delete(key);
94
+ this.lastDrawn.delete(key);
95
+ this.mipped.delete(key);
96
+ }
97
+ /** Delete every texture this cache uploaded and stop answering
98
+ * {@link releaseImageSource} and {@link maxImageTextureSide}. Idempotent. */
99
+ dispose() {
100
+ for (const tex of this.textures) this.gl.deleteTexture(tex);
101
+ this.drainPendingDeletes();
102
+ this.abandon();
103
+ }
104
+ /** {@link dispose} without the deletes, for a cache whose context was lost:
105
+ * its textures died with it. */
106
+ abandon() {
107
+ this.textures.clear();
108
+ this.pendingDeletes.length = 0;
109
+ live.delete(this);
110
+ }
111
+ upload(key, source, repetition) {
112
+ this.lastDrawn.set(key, this.frame);
113
+ const existing = this.map.get(key);
114
+ if (existing) return existing;
115
+ const gl = this.gl;
116
+ const tex = gl.createTexture();
117
+ if (!tex) throw new Error("GLImageCache: createTexture failed");
118
+ gl.bindTexture(gl.TEXTURE_2D, tex);
119
+ uploadPremultiplied(gl, source);
120
+ gl.texParameteri(
121
+ gl.TEXTURE_2D,
122
+ gl.TEXTURE_MIN_FILTER,
123
+ this.minification === "mipmap" ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR
124
+ );
125
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
126
+ this.magFilters.set(key, gl.LINEAR);
127
+ const [wrapS, wrapT] = wrapModes(gl, repetition);
128
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
129
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
130
+ if (this.minification === "mipmap") gl.generateMipmap(gl.TEXTURE_2D);
131
+ gl.bindTexture(gl.TEXTURE_2D, null);
132
+ this.map.set(key, tex);
133
+ this.textures.add(tex);
134
+ this.finalizer.register(key, tex, key);
135
+ return tex;
136
+ }
137
+ /** Whether `key` would gain from {@link buildMipmaps}: only under `'auto'`,
138
+ * and only until they are built. */
139
+ lacksMipmaps(key) {
140
+ return this.minification === "auto" && !this.mipped.has(key);
141
+ }
142
+ /** Build `key`'s mipmaps and filter minification through them from here
143
+ * on. Its texture must be uploaded. Leaves no texture bound. */
144
+ buildMipmaps(key) {
145
+ const tex = this.map.get(key);
146
+ if (!tex || this.mipped.has(key)) return;
147
+ const gl = this.gl;
148
+ gl.bindTexture(gl.TEXTURE_2D, tex);
149
+ gl.generateMipmap(gl.TEXTURE_2D);
150
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
151
+ gl.bindTexture(gl.TEXTURE_2D, null);
152
+ this.mipped.add(key);
153
+ }
154
+ bind(key, unit) {
155
+ const tex = this.map.get(key);
156
+ if (!tex) throw new Error("GLImageCache: image not uploaded; call upload() first");
157
+ this.lastDrawn.set(key, this.frame);
158
+ const gl = this.gl;
159
+ gl.activeTexture(gl.TEXTURE0 + unit);
160
+ gl.bindTexture(gl.TEXTURE_2D, tex);
161
+ }
162
+ /** Set `key`'s MAG_FILTER, skipping the call when it already holds that
163
+ * value. Its texture must be bound to the active unit — callers pair this
164
+ * with `bind`. */
165
+ setMagFilter(key, filter) {
166
+ if (this.magFilters.get(key) === filter) return;
167
+ this.gl.texParameteri(this.gl.TEXTURE_2D, this.gl.TEXTURE_MAG_FILTER, filter);
168
+ this.magFilters.set(key, filter);
169
+ }
170
+ };
171
+ function wrapModes(gl, rep) {
172
+ switch (rep) {
173
+ case "repeat":
174
+ return [gl.REPEAT, gl.REPEAT];
175
+ case "repeat-x":
176
+ return [gl.REPEAT, gl.CLAMP_TO_EDGE];
177
+ case "repeat-y":
178
+ return [gl.CLAMP_TO_EDGE, gl.REPEAT];
179
+ default:
180
+ return [gl.CLAMP_TO_EDGE, gl.CLAMP_TO_EDGE];
181
+ }
182
+ }
183
+ var cache = /* @__PURE__ */ new WeakMap();
184
+ function getMesh(path) {
185
+ const openFill = defaultOpenFill();
186
+ const cached = cache.get(path);
187
+ if (cached !== void 0 && cached.openFill === openFill) return cached.mesh;
188
+ const mesh = tessellate(path);
189
+ cache.set(path, { mesh, openFill });
190
+ return mesh;
191
+ }
192
+ function _resetCacheForTests() {
193
+ cache = /* @__PURE__ */ new WeakMap();
194
+ }
195
+ var registry = createReflectable();
196
+ var programSourceRegistry = registry.reflection;
197
+ function _resetProgramRegistryForTests() {
198
+ registry.clear();
199
+ }
200
+ function getProgramSource(id) {
201
+ return registry.get(id) ?? null;
202
+ }
203
+ var isDev = () => typeof process !== "undefined" ? process.env.NODE_ENV !== "production" : true;
204
+ function registerProgram(id, vert, frag) {
205
+ if (registry.has(id) && !isDev()) {
206
+ throw new Error(`weasel registerProgram: duplicate program id "${id}". In production, re-registration is not allowed. Pass a unique id or call in dev mode.`);
207
+ }
208
+ registry.set(id, { vert, frag });
209
+ return { id };
210
+ }
211
+ var KINDS = createReflectable();
212
+ var paintDrawKindRegistry = KINDS.reflection;
213
+ function registerPaintDrawKind(entry) {
214
+ if (entry.inPoseFrame === void 0 !== (entry.toBoundsFrame === void 0)) {
215
+ const missing = entry.inPoseFrame === void 0 ? "inPoseFrame" : "toBoundsFrame";
216
+ throw new Error(
217
+ `weasel registerPaintKind: kind "${entry.id}" is missing ${missing}. A kind that converts one frame direction and not the other drifts on the next resize; supply both or neither.`
218
+ );
219
+ }
220
+ for (const [id, src] of Object.entries(entry.programs ?? {})) {
221
+ const have = getProgramSource(id);
222
+ if (!have || have.vert !== src.vert || have.frag !== src.frag) registerProgram(id, src.vert, src.frag);
223
+ }
224
+ return KINDS.push(entry.id, entry);
225
+ }
226
+ function getPaintDrawKind(kind) {
227
+ const id = kind ?? "solid";
228
+ const entry = KINDS.get(id);
229
+ if (!entry && LOADERS.has(id)) void startLoad(id).catch(() => {
230
+ });
231
+ return entry;
232
+ }
233
+ var LOADERS = /* @__PURE__ */ new Map();
234
+ var LOADS = /* @__PURE__ */ new Map();
235
+ function registerPaintDrawKindLoader(id, load) {
236
+ LOADERS.set(id, load);
237
+ return () => {
238
+ if (LOADERS.get(id) === load) LOADERS.delete(id);
239
+ };
240
+ }
241
+ function startLoad(id) {
242
+ const running = LOADS.get(id);
243
+ if (running) return running;
244
+ const load = LOADERS.get(id);
245
+ const done = load().then(
246
+ (entry) => {
247
+ if (entry.id !== id) {
248
+ throw new Error(`weasel: the loader for paint kind "${id}" resolved to "${entry.id}".`);
249
+ }
250
+ if (!KINDS.has(id)) registerPaintDrawKind(entry);
251
+ }
252
+ ).catch((err) => {
253
+ console.error(`weasel: paint kind "${id}" failed to load:`, err);
254
+ throw err;
255
+ });
256
+ LOADS.set(id, done);
257
+ return done;
258
+ }
259
+ function isPaintKindKnown(id) {
260
+ return KINDS.has(id) || LOADERS.has(id);
261
+ }
262
+ function warmPaintKinds(kinds) {
263
+ const ids = kinds ?? [...LOADERS.keys()];
264
+ const loads = [];
265
+ for (const id of ids) {
266
+ if (KINDS.has(id)) continue;
267
+ if (!LOADERS.has(id)) {
268
+ return Promise.reject(new Error(
269
+ `weasel warmPaintKinds: "${id}" is neither registered nor loadable.`
270
+ ));
271
+ }
272
+ loads.push(startLoad(id));
273
+ }
274
+ return Promise.all(loads).then(() => void 0);
275
+ }
276
+ function _resetPaintDrawKindsForTests() {
277
+ KINDS.clear();
278
+ LOADERS.clear();
279
+ LOADS.clear();
280
+ }
281
+ var STROKE_CONFIGS_PER_PATH = 8;
282
+ var PX_WIDTH_TOLERANCE = 1 / 8;
283
+ function quantizeStrokeScale(px, scale) {
284
+ if (!(px > 0) || !(scale > 0) || !Number.isFinite(scale)) return scale;
285
+ const stepsPerOctave = Math.ceil(Math.LN2 / (2 * Math.log1p(PX_WIDTH_TOLERANCE / px)));
286
+ return 2 ** (Math.round(Math.log2(scale) * stepsPerOctave) / stepsPerOctave);
287
+ }
288
+ var cache2 = /* @__PURE__ */ new WeakMap();
289
+ function configKey(stroke, flattenTolerance, spaces) {
290
+ const width = resolveStrokeWidth(stroke.width ?? 1, 1);
291
+ const insets = strokeInsets(stroke, width);
292
+ const ribbon = spaces.ribbon?.metric;
293
+ return [
294
+ width,
295
+ stroke.cap ?? "butt",
296
+ stroke.join ?? "miter",
297
+ stroke.miterLimit ?? "",
298
+ stroke.align ?? "center",
299
+ (stroke.dash ?? []).join(","),
300
+ stroke.varyingWidthJoinThreshold ?? "",
301
+ flattenTolerance ?? "",
302
+ insets.start,
303
+ insets.end,
304
+ metricKey(ribbon),
305
+ metricKey(spaces.start?.metric),
306
+ metricKey(spaces.end?.metric)
307
+ ].join("|");
308
+ }
309
+ function strokeMesh(path, stroke, flattenTolerance, spaces = {}) {
310
+ let byConfig = cache2.get(path);
311
+ if (byConfig === void 0) {
312
+ byConfig = /* @__PURE__ */ new Map();
313
+ cache2.set(path, byConfig);
314
+ }
315
+ const key = configKey(stroke, flattenTolerance, spaces);
316
+ const entry = byConfig.get(key);
317
+ if (entry !== void 0 && entry.vertexWidths === stroke.vertexWidths) {
318
+ return entry.mesh;
319
+ }
320
+ const width = resolveStrokeWidth(stroke.width ?? 1, 1);
321
+ const insets = strokeInsets(stroke, width);
322
+ const mesh = tessellateStroke(path, stroke, {
323
+ flattenTolerance,
324
+ startInset: insetIn(insets.start, spaces.start, spaces.ribbon),
325
+ endInset: insetIn(insets.end, spaces.end, spaces.ribbon),
326
+ metric: spaces.ribbon?.metric
327
+ });
328
+ if (entry === void 0 && byConfig.size >= STROKE_CONFIGS_PER_PATH) byConfig.clear();
329
+ byConfig.set(key, { mesh, vertexWidths: stroke.vertexWidths });
330
+ return mesh;
331
+ }
332
+ function insetIn(length, head, ribbon) {
333
+ return head?.metric === ribbon?.metric ? length : { length, metric: head?.metric ?? null };
334
+ }
335
+ function _resetStrokeMeshCacheForTests() {
336
+ cache2 = /* @__PURE__ */ new WeakMap();
337
+ }
338
+ function fillInPoseFrame(fill, box) {
339
+ if (!isBuiltinKind(fill)) {
340
+ return getPaintDrawKind(fill.kind)?.inPoseFrame?.(fill, box) ?? fill;
341
+ }
342
+ if (isBoundsPattern(fill)) {
343
+ const o = fill.origin ?? { x: 0, y: 0 };
344
+ return { ...fill, origin: { x: box.x + o.x, y: box.y + o.y }, units: "local" };
345
+ }
346
+ if (!isBoundsGradient(fill)) return fill;
347
+ const toBox = (p) => ({
348
+ x: box.x + p.x * box.width,
349
+ y: box.y + p.y * box.height
350
+ });
351
+ if (fill.kind === "linear-gradient") {
352
+ return { ...fill, from: toBox(fill.from), to: toBox(fill.to), units: "local" };
353
+ }
354
+ if (fill.kind === "radial-gradient") {
355
+ const scale = Math.hypot(box.width, box.height) / Math.SQRT2;
356
+ return { ...fill, center: toBox(fill.center), radius: fill.radius * scale, units: "local" };
357
+ }
358
+ return { ...fill, center: toBox(fill.center), units: "local" };
359
+ }
360
+ function fillToBoundsFrame(fill, box) {
361
+ if (!isBuiltinKind(fill)) {
362
+ return getPaintDrawKind(fill.kind)?.toBoundsFrame?.(fill, box) ?? fill;
363
+ }
364
+ if (isPatternPaint(fill)) {
365
+ const o = fill.origin ?? { x: 0, y: 0 };
366
+ return { ...fill, origin: { x: o.x - box.x, y: o.y - box.y }, units: "bounds" };
367
+ }
368
+ const isGradient = fill.kind === "linear-gradient" || fill.kind === "radial-gradient" || fill.kind === "conic-gradient";
369
+ if (!isGradient) return fill;
370
+ if (box.width === 0 || box.height === 0) return fill;
371
+ const fromBox = (p) => ({
372
+ x: (p.x - box.x) / box.width,
373
+ y: (p.y - box.y) / box.height
374
+ });
375
+ if (fill.kind === "linear-gradient") {
376
+ return { ...fill, from: fromBox(fill.from), to: fromBox(fill.to), units: "bounds" };
377
+ }
378
+ if (fill.kind === "radial-gradient") {
379
+ const scale = Math.hypot(box.width, box.height) / Math.SQRT2;
380
+ return { ...fill, center: fromBox(fill.center), radius: fill.radius / scale, units: "bounds" };
381
+ }
382
+ return { ...fill, center: fromBox(fill.center), units: "bounds" };
383
+ }
384
+ function isBoundsPattern(fill) {
385
+ return isPatternPaint(fill) && fill.units === "bounds";
386
+ }
387
+ function isBoundsGradient(fill) {
388
+ if (fill === void 0) return false;
389
+ const kind = fill.kind;
390
+ if (kind !== "linear-gradient" && kind !== "radial-gradient" && kind !== "conic-gradient") {
391
+ return false;
392
+ }
393
+ return fill.units === "bounds";
394
+ }
395
+ function isBuiltinKind(fill) {
396
+ const kind = fill.kind ?? "solid";
397
+ return kind === "solid" || isPatternPaint(fill) || kind === "linear-gradient" || kind === "radial-gradient" || kind === "conic-gradient";
398
+ }
399
+ var PATTERN_TILE_CACHE_LIMIT = 256;
400
+ var ID_PREFIX = "pattern:";
401
+ var cache3 = /* @__PURE__ */ new Map();
402
+ function specId(spec) {
403
+ const bag = spec;
404
+ const sorted = {};
405
+ for (const k of Object.keys(bag).sort()) sorted[k] = bag[k];
406
+ return ID_PREFIX + JSON.stringify(sorted);
407
+ }
408
+ function _resetPatternSpecCacheForTests() {
409
+ cache3.clear();
410
+ }
411
+ function resolvePatternSpec(spec) {
412
+ const tile = tileSpecOf(spec);
413
+ const id = specId(tile);
414
+ const hit = cache3.get(id);
415
+ if (hit !== void 0) {
416
+ markUsed(id);
417
+ return hit;
418
+ }
419
+ return build(id, tile);
420
+ }
421
+ function markUsed(id) {
422
+ const hit = cache3.get(id);
423
+ if (hit === void 0) return;
424
+ cache3.delete(id);
425
+ cache3.set(id, hit);
426
+ }
427
+ function build(id, spec) {
428
+ const bitmap = isTileKind(spec.kind) ? rasterizeTile({
429
+ size: tileSize(spec),
430
+ draw: (oc) => drawTileShapes(oc, tileGeometry(spec))
431
+ }) : null;
432
+ const handle = bitmap ? registerTextureAs(id, bitmap) : null;
433
+ cache3.delete(id);
434
+ cache3.set(id, handle);
435
+ while (cache3.size > PATTERN_TILE_CACHE_LIMIT) evict(cache3.keys().next().value);
436
+ return handle;
437
+ }
438
+ function evict(id) {
439
+ cache3.delete(id);
440
+ const source = textureRegistry.get(id)?.source;
441
+ unregisterTexture({ id });
442
+ if (source && "close" in source) source.close();
443
+ }
444
+ function revive(id) {
445
+ let spec;
446
+ try {
447
+ spec = JSON.parse(id.slice(ID_PREFIX.length));
448
+ } catch {
449
+ return;
450
+ }
451
+ if (typeof spec !== "object" || spec === null || !("kind" in spec)) return;
452
+ build(id, spec);
453
+ }
454
+ ownTextureIds(ID_PREFIX, { revive, touched: markUsed });
455
+ function resolveFillPattern(fill) {
456
+ if (!isTilePaint(fill)) return fill;
457
+ const texture = resolvePatternSpec(fill);
458
+ return texture ? { kind: "texture", texture, ...patternPlacementOf(fill) } : null;
459
+ }
460
+
461
+ // src/patterns/commandPaint.ts
462
+ function commandPaint(paint, box) {
463
+ return resolveFillPattern(fillInPoseFrame(paint, box));
464
+ }
465
+ function commandFill(fill, box) {
466
+ if (fill.paint == null) return null;
467
+ const paint = commandPaint(fill.paint, box);
468
+ if (paint === null) return null;
469
+ return paint === fill.paint ? fill : { ...fill, paint };
470
+ }
471
+ function commandStroke(stroke, box) {
472
+ if (stroke.paint == null) return null;
473
+ const paint = commandPaint(stroke.paint, box);
474
+ if (paint === null) return null;
475
+ return paint === stroke.paint ? stroke : { ...stroke, paint };
476
+ }
477
+ function resolvePaint(p, stroke, fallback, head) {
478
+ const v = p ?? fallback;
479
+ if (v === "none") return void 0;
480
+ if (v === "line") return stroke.paint;
481
+ return commandPaint(v, boundsOfPath(head)) ?? void 0;
482
+ }
483
+ function headCommands(heads, stroke) {
484
+ const out = [];
485
+ for (const { entry, path, size, space } of heads) {
486
+ const fill = resolvePaint(entry.fill, stroke, "line", path);
487
+ const width = entry.outline ? entry.outline.width * size : 0;
488
+ const outline = entry.outline ? { paint: resolvePaint(entry.outline.paint, stroke, "line", path), width: space ? { px: width * space.pxPerUnit } : width } : null;
489
+ if (fill === void 0 && (outline === null || outline.paint === void 0)) continue;
490
+ out.push({
491
+ kind: "path",
492
+ path,
493
+ ...fill ? { fill: { paint: fill } } : {},
494
+ ...outline && outline.paint ? { stroke: { paint: outline.paint, width: outline.width, cap: "round", join: "round" } } : {}
495
+ });
496
+ }
497
+ return out;
498
+ }
499
+ var byValue = /* @__PURE__ */ new WeakMap();
500
+ var byStroke = /* @__PURE__ */ new WeakMap();
501
+ var refKey = (ref) => ref === void 0 ? "" : typeof ref === "string" ? ref : `${ref.key}@${String(ref.size ?? "")}`;
502
+ function readsKey(stroke) {
503
+ let key = "";
504
+ for (const ref of [stroke.markerStart, stroke.markerMid, stroke.markerEnd]) {
505
+ const entry = ref === void 0 ? void 0 : getMarker(markerKeyOf(ref));
506
+ if (entry === void 0) {
507
+ key += "/";
508
+ continue;
509
+ }
510
+ const reads2 = markerReadsKey(entry, stroke);
511
+ if (reads2 === null) return null;
512
+ key += `${reads2}/`;
513
+ }
514
+ return key;
515
+ }
516
+ function mapFor(path, source, reads2) {
517
+ if (reads2 !== null) {
518
+ let map2 = byValue.get(path);
519
+ if (map2 === void 0) byValue.set(path, map2 = /* @__PURE__ */ new Map());
520
+ return map2;
521
+ }
522
+ let strokes = byStroke.get(path);
523
+ if (strokes === void 0) byStroke.set(path, strokes = /* @__PURE__ */ new WeakMap());
524
+ let map = strokes.get(source);
525
+ if (map === void 0) strokes.set(source, map = /* @__PURE__ */ new Map());
526
+ return map;
527
+ }
528
+ function cachedMarkerCommands(path, source, stroke, strokeWidth, flattenTolerance, spaces = {}) {
529
+ if (stroke.markerStart === void 0 && stroke.markerMid === void 0 && stroke.markerEnd === void 0) {
530
+ return [];
531
+ }
532
+ const reads2 = readsKey(stroke);
533
+ const map = mapFor(path, source, reads2);
534
+ const key = [
535
+ strokeWidth,
536
+ flattenTolerance ?? "",
537
+ markerGeneration(),
538
+ refKey(stroke.markerStart),
539
+ refKey(stroke.markerMid),
540
+ refKey(stroke.markerEnd),
541
+ reads2 ?? "",
542
+ screenSpaceKey(spaces.start),
543
+ screenSpaceKey(spaces.mid),
544
+ screenSpaceKey(spaces.end)
545
+ ].join("|");
546
+ let entry = map.get(key);
547
+ if (entry === void 0) {
548
+ const heads = markerHeads(path, stroke, strokeWidth, flattenTolerance, spaces);
549
+ entry = { heads, paint: stroke.paint, cmds: headCommands(heads, stroke) };
550
+ if (map.size >= STROKE_CONFIGS_PER_PATH) map.clear();
551
+ map.set(key, entry);
552
+ } else if (entry.paint !== stroke.paint) {
553
+ entry.paint = stroke.paint;
554
+ entry.cmds = headCommands(entry.heads, stroke);
555
+ }
556
+ return entry.cmds;
557
+ }
558
+ function _resetMarkerCommandCacheForTests() {
559
+ byValue = /* @__PURE__ */ new WeakMap();
560
+ byStroke = /* @__PURE__ */ new WeakMap();
561
+ }
562
+ var OUTLINE_FLATTEN_TOLERANCE = 1 / 4096;
563
+ var OUTLINE_MESH_CACHE_LIMIT = 2048;
564
+ var cache4 = /* @__PURE__ */ new Map();
565
+ function outlineMesh(key, d) {
566
+ const cached = cache4.get(key);
567
+ if (cached !== void 0) return cached;
568
+ if (cache4.size >= OUTLINE_MESH_CACHE_LIMIT) cache4 = /* @__PURE__ */ new Map();
569
+ const mesh = tessellate(pathFromD(d), { flattenTolerance: OUTLINE_FLATTEN_TOLERANCE });
570
+ cache4.set(key, mesh);
571
+ return mesh;
572
+ }
573
+ function _resetOutlineMeshCacheForTests() {
574
+ cache4 = /* @__PURE__ */ new Map();
575
+ }
576
+ var OUTLINE_STROKE_MESH_CACHE_LIMIT = 2048;
577
+ var WIDTH_QUANTUM = 1 / 1024;
578
+ var cache5 = /* @__PURE__ */ new Map();
579
+ function quantizeEmWidth(emWidth) {
580
+ return Math.round(emWidth / WIDTH_QUANTUM) * WIDTH_QUANTUM;
581
+ }
582
+ function outlineStrokeMesh(glyphKey, d, emWidth, stroke, metric) {
583
+ if (!(emWidth > 0)) return null;
584
+ const key = [
585
+ glyphKey,
586
+ emWidth,
587
+ stroke.join ?? "miter",
588
+ stroke.cap ?? "butt",
589
+ stroke.miterLimit ?? "",
590
+ stroke.align ?? "center",
591
+ (stroke.dash ?? []).join(","),
592
+ metricKey(metric)
593
+ ].join("|");
594
+ const cached = cache5.get(key);
595
+ if (cached !== void 0) return cached.indices.length === 0 ? null : cached;
596
+ if (cache5.size >= OUTLINE_STROKE_MESH_CACHE_LIMIT) cache5 = /* @__PURE__ */ new Map();
597
+ const mesh = tessellateStroke(
598
+ pathFromD(d),
599
+ { ...stroke, width: emWidth },
600
+ { flattenTolerance: OUTLINE_FLATTEN_TOLERANCE, metric }
601
+ );
602
+ cache5.set(key, mesh);
603
+ return mesh.indices.length === 0 ? null : mesh;
604
+ }
605
+ function _resetOutlineStrokeMeshCacheForTests() {
606
+ cache5 = /* @__PURE__ */ new Map();
607
+ }
608
+
609
+ // src/shaders/straightRgb.ts
610
+ var STRAIGHT_RGB_GLSL = (
611
+ /* glsl */
612
+ `
613
+ vec3 straightRgb(vec4 premultiplied) {
614
+ return premultiplied.rgb / max(premultiplied.a, 0.0001);
615
+ }
616
+ `
617
+ );
618
+
619
+ // src/shaders/batchFill.ts
620
+ var BATCH_TEXTURE_SLOTS = 8;
621
+ var WHITE_SLOT = 0;
622
+ var PAINT_MODE_PLAIN = 0;
623
+ var PAINT_MODE_RADIAL = 3;
624
+ var PAINT_MODE_CONIC = 4;
625
+ var PAINT_MODE_IMAGE = 5;
626
+ var INV_TAU = (1 / (2 * Math.PI)).toFixed(10);
627
+ function packSlot(slot, mode) {
628
+ return slot + BATCH_TEXTURE_SLOTS * mode;
629
+ }
630
+ var BATCH_ATTRIBUTE_LOCATIONS = {
631
+ a_position: 0,
632
+ a_vertexColor: 1,
633
+ a_uv: 2,
634
+ a_post: 3,
635
+ a_texSlot: 4
636
+ };
637
+ var L = BATCH_ATTRIBUTE_LOCATIONS;
638
+ function sampleChain(slots) {
639
+ const arms = [];
640
+ for (let i = 1; i < slots; i++) {
641
+ arms.push(` if (slot == ${i}) return texture(u_samplers[${i}], uv);`);
642
+ }
643
+ return arms.join("\n");
644
+ }
645
+ var BATCH_VERT_SRC = (
646
+ /* glsl */
647
+ `#version 300 es
648
+ layout(location = ${L.a_position}) in vec2 a_position;
649
+ layout(location = ${L.a_vertexColor}) in vec4 a_vertexColor;
650
+ layout(location = ${L.a_uv}) in vec2 a_uv;
651
+ layout(location = ${L.a_post}) in float a_post;
652
+ layout(location = ${L.a_texSlot}) in float a_texSlot;
653
+ uniform mat3 u_proj;
654
+ uniform mat3 u_model;
655
+ out vec4 v_vertexColor;
656
+ out vec2 v_uv;
657
+ out float v_post;
658
+ flat out int v_texSlot;
659
+ flat out float v_paintMode;
660
+ void main() {
661
+ vec3 screen = u_model * vec3(a_position, 1.0);
662
+ vec3 clip = u_proj * vec3(screen.xy, 1.0);
663
+ gl_Position = vec4(clip.xy, 0.0, 1.0);
664
+ v_vertexColor = a_vertexColor;
665
+ v_uv = a_uv;
666
+ v_post = a_post;
667
+ // slot + 8 * mode, unpacked \u2014 see the file header for why they share a float.
668
+ int packed = int(a_texSlot + 0.5);
669
+ v_texSlot = packed % ${BATCH_TEXTURE_SLOTS};
670
+ v_paintMode = float(packed / ${BATCH_TEXTURE_SLOTS});
671
+ }
672
+ `
673
+ );
674
+ var BATCH_FRAG_SRC = (
675
+ /* glsl */
676
+ `#version 300 es
677
+ precision highp float;
678
+ in vec4 v_vertexColor;
679
+ in vec2 v_uv;
680
+ in float v_post;
681
+ flat in int v_texSlot;
682
+ flat in float v_paintMode;
683
+ uniform sampler2D u_samplers[${BATCH_TEXTURE_SLOTS}];
684
+ uniform vec4 u_color;
685
+ uniform float u_alpha;
686
+ uniform float u_synthBold;
687
+ uniform vec2 u_fieldScale[${BATCH_TEXTURE_SLOTS}];
688
+ uniform mat4 u_colorMatrix;
689
+ uniform vec4 u_colorBias;
690
+ out vec4 outColor;
691
+
692
+ vec4 sampleSlot(int slot, vec2 uv) {
693
+ ${sampleChain(BATCH_TEXTURE_SLOTS)}
694
+ return texture(u_samplers[0], uv);
695
+ }
696
+ ${GLYPH_COVERAGE_GLSL}
697
+ ${STRAIGHT_RGB_GLSL}
698
+ void main() {
699
+ float isGrad = step(2.5, v_paintMode) * step(v_paintMode, ${PAINT_MODE_CONIC + 0.5});
700
+ // A radial or conic vertex carries a gradient-space coordinate rather than a
701
+ // texture coordinate, and its atlas row rather than an alpha. The sample is
702
+ // split across the branch rather than the coordinate selected before it: an
703
+ // arm that reads v_uv straight is a fetch the hardware can schedule against a
704
+ // varying, and one reading a coordinate the shader computed is not. Selecting
705
+ // the coordinate first and sampling once costs 29-54% of a fragment that is
706
+ // not a gradient; splitting it is within the measurement's own spread of free
707
+ // (tests/perf/fill-rate.spec.ts, teitou, 2026-10-05).
708
+ //
709
+ // Branching at all is safe here where it would not be around the glyph math:
710
+ // v_paintMode is flat, so every fragment of a quad takes the same arm, and
711
+ // nothing in either arm is a derivative.
712
+ vec4 texel;
713
+ if (isGrad > 0.5) {
714
+ float t = v_paintMode > ${PAINT_MODE_CONIC - 0.5}
715
+ ? fract(atan(v_uv.y, v_uv.x) * ${INV_TAU})
716
+ : length(v_uv);
717
+ texel = sampleSlot(v_texSlot, vec2(t, v_post));
718
+ } else {
719
+ texel = sampleSlot(v_texSlot, v_uv);
720
+ }
721
+ // At 0 the mix is the texel itself, so a solid still gets its color exactly.
722
+ texel.rgb = mix(texel.rgb, straightRgb(texel), step(${PAINT_MODE_IMAGE - 0.5}, v_paintMode));
723
+ float isGlyph = step(0.5, v_paintMode) * step(v_paintMode, 2.5);
724
+ // Unconditional, and multiplied out afterwards rather than branched around:
725
+ // see the file header.
726
+ float coverage = glyphCoverage(texel, v_paintMode, u_synthBold, v_uv, u_fieldScale[v_texSlot]);
727
+ // A glyph's texel is a distance field, so it takes no part in the color; a
728
+ // plain vertex multiplies its texel in as it always did.
729
+ vec4 src = mix(texel, vec4(1.0), isGlyph) * u_color * v_vertexColor;
730
+ vec4 mapped = clamp(u_colorMatrix * src + u_colorBias, 0.0, 1.0);
731
+ float a = mapped.a * u_alpha * mix(v_post, 1.0, isGrad) * mix(1.0, coverage, isGlyph);
732
+ outColor = vec4(mapped.rgb * a, a);
733
+ }
734
+ `
735
+ );
736
+ var BATCH_FILL_UNIFORMS = [
737
+ "u_proj",
738
+ "u_model",
739
+ "u_samplers",
740
+ "u_color",
741
+ "u_alpha",
742
+ "u_synthBold",
743
+ "u_fieldScale",
744
+ "u_colorMatrix",
745
+ "u_colorBias"
746
+ ];
747
+ var BATCH_FILL_ATTRIBUTES = [
748
+ "a_position",
749
+ "a_vertexColor",
750
+ "a_uv",
751
+ "a_post",
752
+ "a_texSlot"
753
+ ];
754
+
755
+ // src/batchClip.ts
756
+ function axisAlignedClipRect(path, m) {
757
+ if (path.kind !== "rect") return null;
758
+ const keepsAxes = m[1] === 0 && m[3] === 0 || m[0] === 0 && m[4] === 0;
759
+ if (!keepsAxes) return null;
760
+ const ax = m[0] * path.x + m[3] * path.y + m[6];
761
+ const ay = m[1] * path.x + m[4] * path.y + m[7];
762
+ const x1 = path.x + path.width;
763
+ const y1 = path.y + path.height;
764
+ const bx = m[0] * x1 + m[3] * y1 + m[6];
765
+ const by = m[1] * x1 + m[4] * y1 + m[7];
766
+ return {
767
+ x0: Math.min(ax, bx),
768
+ y0: Math.min(ay, by),
769
+ x1: Math.max(ax, bx),
770
+ y1: Math.max(ay, by)
771
+ };
772
+ }
773
+ function intersectClipRects(a, b) {
774
+ return {
775
+ x0: Math.max(a.x0, b.x0),
776
+ y0: Math.max(a.y0, b.y0),
777
+ x1: Math.min(a.x1, b.x1),
778
+ y1: Math.min(a.y1, b.y1)
779
+ };
780
+ }
781
+ function clipConvexPolygon(src, n, stride, rect, dst, tmp) {
782
+ let count = clipEdge(src, n, stride, 0, rect.x0, 1, tmp);
783
+ count = clipEdge(tmp, count, stride, 0, rect.x1, -1, dst);
784
+ count = clipEdge(dst, count, stride, 1, rect.y0, 1, tmp);
785
+ return clipEdge(tmp, count, stride, 1, rect.y1, -1, dst);
786
+ }
787
+ function clipEdge(src, n, stride, axis, at, sign, out) {
788
+ if (n === 0) return 0;
789
+ let m = 0;
790
+ let prev = n - 1;
791
+ let prevIn = sign * (src[prev * stride + axis] - at) >= 0;
792
+ for (let cur = 0; cur < n; cur++) {
793
+ const curIn = sign * (src[cur * stride + axis] - at) >= 0;
794
+ if (curIn !== prevIn) {
795
+ const a = prev * stride;
796
+ const b = cur * stride;
797
+ const t = (at - src[a + axis]) / (src[b + axis] - src[a + axis]);
798
+ const o = m * stride;
799
+ for (let k = 0; k < stride; k++) out[o + k] = src[a + k] + t * (src[b + k] - src[a + k]);
800
+ out[o + axis] = at;
801
+ m++;
802
+ }
803
+ if (curIn) {
804
+ const o = m * stride;
805
+ const c = cur * stride;
806
+ for (let k = 0; k < stride; k++) out[o + k] = src[c + k];
807
+ m++;
808
+ }
809
+ prev = cur;
810
+ prevIn = curIn;
811
+ }
812
+ return m;
813
+ }
814
+
815
+ // src/drawBatch.ts
816
+ var MAX_VERTICES_PER_BATCH = 32768;
817
+ var FLOATS_PER_VERTEX = 10;
818
+ var INITIAL_VERTICES = 256;
819
+ var INITIAL_INDICES = 384;
820
+ var WHITE_U = 0.5;
821
+ var WHITE_V = 0.5;
822
+ var PLAIN_WHITE = packSlot(WHITE_SLOT, PAINT_MODE_PLAIN);
823
+ var SOLID_RING_SIZE = 64;
824
+ var BATCH_TIERS = [
825
+ { vertices: 16, indices: 24 },
826
+ { vertices: 1024, indices: 3072 }
827
+ ];
828
+ var SOLID_RING_SLOT_VERTICES = BATCH_TIERS[BATCH_TIERS.length - 1].vertices;
829
+ var SOLID_LARGE_RING_SIZE = 4;
830
+ function doubledTo(from, need) {
831
+ let capacity = from;
832
+ while (capacity < need) capacity *= 2;
833
+ return capacity;
834
+ }
835
+ function quadIndices(quads) {
836
+ const out = new Uint32Array(quads * 6);
837
+ for (let q = 0; q < quads; q++) {
838
+ const b = q * 4;
839
+ const j = q * 6;
840
+ out[j] = b;
841
+ out[j + 1] = b + 1;
842
+ out[j + 2] = b + 2;
843
+ out[j + 3] = b;
844
+ out[j + 4] = b + 2;
845
+ out[j + 5] = b + 3;
846
+ }
847
+ return out;
848
+ }
849
+ var DrawBatch = class {
850
+ gl;
851
+ aPos;
852
+ aColor;
853
+ aUv;
854
+ aPost;
855
+ aSlot;
856
+ /** One ring per tier, cycled per flush. Slots are created on first use, so a
857
+ * renderer that flushes rarely allocates as few as it flushes. */
858
+ rings = BATCH_TIERS.map(() => new Array(SOLID_RING_SIZE).fill(void 0));
859
+ nextInRing = BATCH_TIERS.map(() => 0);
860
+ /** The same, for flushes past the largest tier; these sets grow to fit. */
861
+ largeRing = new Array(SOLID_LARGE_RING_SIZE).fill(void 0);
862
+ nextLarge = 0;
863
+ verts = new Float32Array(INITIAL_VERTICES * FLOATS_PER_VERTEX);
864
+ idx = new Uint32Array(INITIAL_INDICES);
865
+ nVerts = 0;
866
+ nIdx = 0;
867
+ /** Whether the staged run is quads alone, so its indices are the canonical
868
+ * pattern and a slot already holding that pattern needs no upload. */
869
+ pureRects = true;
870
+ /** The rect every push is cut to, or `null`. A push returns `false`, having
871
+ * staged nothing, for geometry it cannot cut exactly; see `clipQuad`. */
872
+ clip = null;
873
+ /** Polygon scratch for `clip`: a quad cut by four edges has at most eight
874
+ * corners. */
875
+ polyIn = new Float32Array(8 * FLOATS_PER_VERTEX);
876
+ polyOut = new Float32Array(8 * FLOATS_PER_VERTEX);
877
+ polyTmp = new Float32Array(8 * FLOATS_PER_VERTEX);
878
+ constructor(gl, prog) {
879
+ const aPos = prog.attribute("a_position");
880
+ const aColor = prog.attribute("a_vertexColor");
881
+ const aUv = prog.attribute("a_uv");
882
+ const aPost = prog.attribute("a_post");
883
+ const aSlot = prog.attribute("a_texSlot");
884
+ if (aPos === void 0 || aColor === void 0 || aUv === void 0 || aPost === void 0 || aSlot === void 0) {
885
+ throw new Error(
886
+ "DrawBatch: batch program is missing a_position / a_vertexColor / a_uv / a_post / a_texSlot"
887
+ );
888
+ }
889
+ this.gl = gl;
890
+ this.aPos = aPos;
891
+ this.aColor = aColor;
892
+ this.aUv = aUv;
893
+ this.aPost = aPost;
894
+ this.aSlot = aSlot;
895
+ }
896
+ get length() {
897
+ return this.nIdx;
898
+ }
899
+ /** Whether staging `vertices` more would put the run past the per-flush cap. */
900
+ wouldOverflow(vertices) {
901
+ return this.nVerts + vertices > MAX_VERTICES_PER_BATCH;
902
+ }
903
+ /**
904
+ * Append one rect's four corners through `m`, all carrying `rgba` (straight
905
+ * alpha).
906
+ */
907
+ pushRect(x, y, w, h, m, r, g, b, a) {
908
+ this.reserve(4, 6);
909
+ let i = this.nVerts * FLOATS_PER_VERTEX;
910
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
911
+ const x1 = x + w;
912
+ const y1 = y + h;
913
+ const ax = ma * x + mc * y + mtx, ay = mb * x + md * y + mty;
914
+ const bx = ma * x1 + mc * y + mtx, by = mb * x1 + md * y + mty;
915
+ const cx = ma * x1 + mc * y1 + mtx, cy = mb * x1 + md * y1 + mty;
916
+ const dx = ma * x + mc * y1 + mtx, dy = mb * x + md * y1 + mty;
917
+ const P = PLAIN_WHITE;
918
+ i = this.writeVertex(i, ax, ay, r, g, b, a, WHITE_U, WHITE_V, 1, P);
919
+ i = this.writeVertex(i, bx, by, r, g, b, a, WHITE_U, WHITE_V, 1, P);
920
+ i = this.writeVertex(i, cx, cy, r, g, b, a, WHITE_U, WHITE_V, 1, P);
921
+ this.writeVertex(i, dx, dy, r, g, b, a, WHITE_U, WHITE_V, 1, P);
922
+ this.pushQuadIndices();
923
+ return this.clip === null || this.clipQuad(this.nVerts - 4, this.nIdx - 6, this.clip);
924
+ }
925
+ /**
926
+ * Append one image quad: the destination rect `(x, y, w, h)` mapped through
927
+ * `m`, sampling `(u0, v0)`-`(u1, v1)`, every corner carrying `post` as the
928
+ * after-the-color-matrix alpha factor and `rgb` as the scale on its texel.
929
+ * `slot` is the texture unit the corners sample.
930
+ *
931
+ * Corners wind top-left, top-right, bottom-right, bottom-left — the same
932
+ * winding `pushRect` uses, which is what lets a run of mixed rects and quads
933
+ * keep the canonical index pattern.
934
+ */
935
+ pushQuad(x, y, w, h, m, u0, v0, u1, v1, post, slot, r = 1, g = 1, b = 1) {
936
+ this.reserve(4, 6);
937
+ let i = this.nVerts * FLOATS_PER_VERTEX;
938
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
939
+ const x1 = x + w;
940
+ const y1 = y + h;
941
+ const ax = ma * x + mc * y + mtx, ay = mb * x + md * y + mty;
942
+ const bx = ma * x1 + mc * y + mtx, by = mb * x1 + md * y + mty;
943
+ const cx = ma * x1 + mc * y1 + mtx, cy = mb * x1 + md * y1 + mty;
944
+ const dx = ma * x + mc * y1 + mtx, dy = mb * x + md * y1 + mty;
945
+ const P = packSlot(slot, PAINT_MODE_IMAGE);
946
+ i = this.writeVertex(i, ax, ay, r, g, b, 1, u0, v0, post, P);
947
+ i = this.writeVertex(i, bx, by, r, g, b, 1, u1, v0, post, P);
948
+ i = this.writeVertex(i, cx, cy, r, g, b, 1, u1, v1, post, P);
949
+ this.writeVertex(i, dx, dy, r, g, b, 1, u0, v1, post, P);
950
+ this.pushQuadIndices();
951
+ return this.clip === null || this.clipQuad(this.nVerts - 4, this.nIdx - 6, this.clip);
952
+ }
953
+ /**
954
+ * Append one glyph quad: the box `(x0, y0)`-`(x1, y1)` mapped through `m`,
955
+ * sampling `(u0, v0)`-`(u1, v1)` of the font atlas at `slot`, painted in
956
+ * `rgba`.
957
+ *
958
+ * `mode` says which channels of that atlas carry the distance field, and
959
+ * rides the vertices packed into the slot. The synthetic-bold threshold does
960
+ * not: it is `u_synthBold`, and the caller breaks the run when it changes.
961
+ *
962
+ * A synthetic oblique is sheared here, before `m`; `tanItalic` is 0 for an
963
+ * upright face. Corners wind as `pushQuad`'s do.
964
+ */
965
+ pushGlyph(x0, y0, x1, y1, baselineY, tanItalic, m, u0, v0, u1, v1, r, g, b, a, slot, mode) {
966
+ this.reserve(4, 6);
967
+ let i = this.nVerts * FLOATS_PER_VERTEX;
968
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
969
+ const topShift = (baselineY - y0) * tanItalic;
970
+ const botShift = (baselineY - y1) * tanItalic;
971
+ const tx0 = x0 + topShift, tx1 = x1 + topShift;
972
+ const bx0 = x0 + botShift, bx1 = x1 + botShift;
973
+ const ax = ma * tx0 + mc * y0 + mtx, ay = mb * tx0 + md * y0 + mty;
974
+ const bx = ma * tx1 + mc * y0 + mtx, by = mb * tx1 + md * y0 + mty;
975
+ const cx = ma * bx1 + mc * y1 + mtx, cy = mb * bx1 + md * y1 + mty;
976
+ const dx = ma * bx0 + mc * y1 + mtx, dy = mb * bx0 + md * y1 + mty;
977
+ const P = packSlot(slot, mode);
978
+ i = this.writeVertex(i, ax, ay, r, g, b, a, u0, v0, 1, P);
979
+ i = this.writeVertex(i, bx, by, r, g, b, a, u1, v0, 1, P);
980
+ i = this.writeVertex(i, cx, cy, r, g, b, a, u1, v1, 1, P);
981
+ this.writeVertex(i, dx, dy, r, g, b, a, u0, v1, 1, P);
982
+ this.pushQuadIndices();
983
+ return this.clip === null || this.clipQuad(this.nVerts - 4, this.nIdx - 6, this.clip);
984
+ }
985
+ /**
986
+ * Append one rect filled by a gradient: the corners of `(x, y, w, h)` mapped
987
+ * through `m`, sampling the ramp atlas at `slot`.
988
+ *
989
+ * `uv` gives each channel of `a_uv` as an affine function of the coordinates
990
+ * the corners arrive in. `mode` says whether that is a ramp position or a
991
+ * gradient-space coordinate, and `post` carries the atlas row for the modes
992
+ * that read it — see `shaders/batchFill.ts`. Values outside 0..1 clamp to
993
+ * the atlas's edge texel.
994
+ */
995
+ pushGradientRect(x, y, w, h, m, uv, post, slot, mode, r, g, b, a) {
996
+ this.reserve(4, 6);
997
+ let i = this.nVerts * FLOATS_PER_VERTEX;
998
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
999
+ const x1 = x + w;
1000
+ const y1 = y + h;
1001
+ const P = packSlot(slot, mode);
1002
+ const corner = (cx, cy) => {
1003
+ const at = i;
1004
+ i = this.writeVertex(
1005
+ at,
1006
+ ma * cx + mc * cy + mtx,
1007
+ mb * cx + md * cy + mty,
1008
+ r,
1009
+ g,
1010
+ b,
1011
+ a,
1012
+ uv.ux * cx + uv.uy * cy + uv.u0,
1013
+ uv.vx * cx + uv.vy * cy + uv.v0,
1014
+ post,
1015
+ P
1016
+ );
1017
+ return i;
1018
+ };
1019
+ corner(x, y);
1020
+ corner(x1, y);
1021
+ corner(x1, y1);
1022
+ corner(x, y1);
1023
+ this.pushQuadIndices();
1024
+ return this.clip === null || this.clipQuad(this.nVerts - 4, this.nIdx - 6, this.clip);
1025
+ }
1026
+ /** `pushMesh` for a mesh filled by a gradient — see `pushGradientRect` for
1027
+ * what `uv`, `post` and `mode` carry. */
1028
+ pushGradientMesh(mesh, m, uv, post, slot, mode, r, g, b, a) {
1029
+ const src = mesh.vertices;
1030
+ const srcIdx = mesh.indices;
1031
+ const n = src.length >> 1;
1032
+ this.reserve(n, srcIdx.length);
1033
+ this.pureRects = false;
1034
+ const v = this.verts;
1035
+ let i = this.nVerts * FLOATS_PER_VERTEX;
1036
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
1037
+ const P = packSlot(slot, mode);
1038
+ for (let k = 0; k < n; k++) {
1039
+ const x = src[k * 2];
1040
+ const y = src[k * 2 + 1];
1041
+ v[i++] = ma * x + mc * y + mtx;
1042
+ v[i++] = mb * x + md * y + mty;
1043
+ v[i++] = r;
1044
+ v[i++] = g;
1045
+ v[i++] = b;
1046
+ v[i++] = a;
1047
+ v[i++] = uv.ux * x + uv.uy * y + uv.u0;
1048
+ v[i++] = uv.vx * x + uv.vy * y + uv.v0;
1049
+ v[i++] = post;
1050
+ v[i++] = P;
1051
+ }
1052
+ const base = this.nVerts;
1053
+ const out = this.idx;
1054
+ let j = this.nIdx;
1055
+ for (let k = 0; k < srcIdx.length; k++) out[j++] = base + srcIdx[k];
1056
+ this.nVerts += n;
1057
+ this.nIdx += srcIdx.length;
1058
+ return this.clip === null || this.clipMesh(base, this.nIdx - srcIdx.length, this.clip);
1059
+ }
1060
+ /**
1061
+ * Append a tessellated mesh through `m`, all vertices carrying `rgba`. The
1062
+ * mesh's own indices are rebased onto the staged vertices, which is why the
1063
+ * index buffer is uploaded per flush rather than written once.
1064
+ */
1065
+ pushMesh(mesh, m, r, g, b, a) {
1066
+ const src = mesh.vertices;
1067
+ const srcIdx = mesh.indices;
1068
+ const n = src.length >> 1;
1069
+ this.reserve(n, srcIdx.length);
1070
+ this.pureRects = false;
1071
+ const v = this.verts;
1072
+ let i = this.nVerts * FLOATS_PER_VERTEX;
1073
+ const ma = m[0], mb = m[1], mc = m[3], md = m[4], mtx = m[6], mty = m[7];
1074
+ for (let k = 0; k < n; k++) {
1075
+ const x = src[k * 2];
1076
+ const y = src[k * 2 + 1];
1077
+ v[i++] = ma * x + mc * y + mtx;
1078
+ v[i++] = mb * x + md * y + mty;
1079
+ v[i++] = r;
1080
+ v[i++] = g;
1081
+ v[i++] = b;
1082
+ v[i++] = a;
1083
+ v[i++] = WHITE_U;
1084
+ v[i++] = WHITE_V;
1085
+ v[i++] = 1;
1086
+ v[i++] = PLAIN_WHITE;
1087
+ }
1088
+ const base = this.nVerts;
1089
+ const out = this.idx;
1090
+ let j = this.nIdx;
1091
+ for (let k = 0; k < srcIdx.length; k++) out[j++] = base + srcIdx[k];
1092
+ this.nVerts += n;
1093
+ this.nIdx += srcIdx.length;
1094
+ return this.clip === null || this.clipMesh(base, this.nIdx - srcIdx.length, this.clip);
1095
+ }
1096
+ /** Upload the staged geometry into the next set of buffers and bind its VAO.
1097
+ * Returns the index count for the caller's `drawElements`. */
1098
+ uploadAndBind() {
1099
+ const gl = this.gl;
1100
+ const tier = BATCH_TIERS.findIndex(
1101
+ (t) => this.nVerts <= t.vertices && this.nIdx <= t.indices
1102
+ );
1103
+ const set = tier < 0 ? this.nextLargeSlot() : this.nextRingSlot(tier);
1104
+ gl.bindVertexArray(set.vao);
1105
+ gl.bindBuffer(gl.ARRAY_BUFFER, set.vbo);
1106
+ gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.verts, 0, this.nVerts * FLOATS_PER_VERTEX);
1107
+ if (!this.pureRects) {
1108
+ gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, this.idx, 0, this.nIdx);
1109
+ set.canonicalQuads = 0;
1110
+ } else if (set.canonicalQuads < this.nVerts >> 2) {
1111
+ const quads = Math.min(set.vertexCapacity >> 2, Math.floor(set.indexCapacity / 6));
1112
+ gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, quadIndices(quads));
1113
+ set.canonicalQuads = quads;
1114
+ }
1115
+ return this.nIdx;
1116
+ }
1117
+ reset() {
1118
+ this.nVerts = 0;
1119
+ this.nIdx = 0;
1120
+ this.pureRects = true;
1121
+ }
1122
+ dispose() {
1123
+ for (const set of [...this.rings.flat(), ...this.largeRing]) {
1124
+ if (set) this.deleteSet(set);
1125
+ }
1126
+ for (const ring of this.rings) ring.fill(void 0);
1127
+ this.largeRing.fill(void 0);
1128
+ }
1129
+ writeVertex(i, x, y, r, g, b, a, u, v, post, packed) {
1130
+ const out = this.verts;
1131
+ out[i] = x;
1132
+ out[i + 1] = y;
1133
+ out[i + 2] = r;
1134
+ out[i + 3] = g;
1135
+ out[i + 4] = b;
1136
+ out[i + 5] = a;
1137
+ out[i + 6] = u;
1138
+ out[i + 7] = v;
1139
+ out[i + 8] = post;
1140
+ out[i + 9] = packed;
1141
+ return i + FLOATS_PER_VERTEX;
1142
+ }
1143
+ /**
1144
+ * Fit the quad just written at `v0` to `rect`: keep it if it lies inside,
1145
+ * drop it if it misses, and cut it if it crosses — but only if its edges
1146
+ * run along the axes. Cutting a slanted edge moves its endpoint off the
1147
+ * subpixel grid the rasterizer snaps to, and the shortened edge then covers
1148
+ * different samples than the whole one did; along an axis the cut edge is
1149
+ * the same line exactly. So a slanted quad that crosses is rolled back and
1150
+ * refused, for the caller to clip through the stencil instead.
1151
+ */
1152
+ clipQuad(v0, i0, rect) {
1153
+ const v = this.verts;
1154
+ const at = v0 * FLOATS_PER_VERTEX;
1155
+ const F = FLOATS_PER_VERTEX;
1156
+ const ax = v[at], ay = v[at + 1], bx = v[at + F], by = v[at + F + 1];
1157
+ const cx = v[at + 2 * F], cy = v[at + 2 * F + 1], dx = v[at + 3 * F], dy = v[at + 3 * F + 1];
1158
+ const minX = Math.min(ax, bx, cx, dx), maxX = Math.max(ax, bx, cx, dx);
1159
+ const minY = Math.min(ay, by, cy, dy), maxY = Math.max(ay, by, cy, dy);
1160
+ if (minX >= rect.x0 && maxX <= rect.x1 && minY >= rect.y0 && maxY <= rect.y1) return true;
1161
+ this.nVerts = v0;
1162
+ this.nIdx = i0;
1163
+ if (maxX <= rect.x0 || minX >= rect.x1 || maxY <= rect.y0 || minY >= rect.y1) return true;
1164
+ const alongAxes = ay === by && bx === cx && cy === dy && dx === ax || ax === bx && by === cy && cx === dx && dy === ay;
1165
+ if (!alongAxes) return false;
1166
+ this.polyIn.set(v.subarray(at, at + 4 * F));
1167
+ const n = clipConvexPolygon(this.polyIn, 4, F, rect, this.polyOut, this.polyTmp);
1168
+ this.appendFan(this.polyOut, n);
1169
+ return true;
1170
+ }
1171
+ /** `clipQuad` for a mesh staged from `v0`. A mesh's edges are slanted in
1172
+ * general, so one that crosses is refused rather than cut. */
1173
+ clipMesh(v0, i0, rect) {
1174
+ const v = this.verts;
1175
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
1176
+ for (let i = v0 * FLOATS_PER_VERTEX; i < this.nVerts * FLOATS_PER_VERTEX; i += FLOATS_PER_VERTEX) {
1177
+ const x = v[i];
1178
+ const y = v[i + 1];
1179
+ if (x < minX) minX = x;
1180
+ if (x > maxX) maxX = x;
1181
+ if (y < minY) minY = y;
1182
+ if (y > maxY) maxY = y;
1183
+ }
1184
+ if (minX >= rect.x0 && maxX <= rect.x1 && minY >= rect.y0 && maxY <= rect.y1) return true;
1185
+ this.nVerts = v0;
1186
+ this.nIdx = i0;
1187
+ return maxX <= rect.x0 || minX >= rect.x1 || maxY <= rect.y0 || minY >= rect.y1;
1188
+ }
1189
+ /** Append the `n`-corner convex polygon in `poly` as a triangle fan. */
1190
+ appendFan(poly, n) {
1191
+ if (n < 3) return;
1192
+ this.reserve(n, (n - 2) * 3);
1193
+ if (n !== 4) this.pureRects = false;
1194
+ const base = this.nVerts;
1195
+ this.verts.set(poly.subarray(0, n * FLOATS_PER_VERTEX), base * FLOATS_PER_VERTEX);
1196
+ let j = this.nIdx;
1197
+ for (let k = 1; k < n - 1; k++) {
1198
+ this.idx[j++] = base;
1199
+ this.idx[j++] = base + k;
1200
+ this.idx[j++] = base + k + 1;
1201
+ }
1202
+ this.nVerts += n;
1203
+ this.nIdx = j;
1204
+ }
1205
+ /** Two triangles over the four corners just written. */
1206
+ pushQuadIndices() {
1207
+ const base = this.nVerts;
1208
+ let j = this.nIdx;
1209
+ this.idx[j++] = base;
1210
+ this.idx[j++] = base + 1;
1211
+ this.idx[j++] = base + 2;
1212
+ this.idx[j++] = base;
1213
+ this.idx[j++] = base + 2;
1214
+ this.idx[j++] = base + 3;
1215
+ this.nVerts += 4;
1216
+ this.nIdx += 6;
1217
+ }
1218
+ /** Grow the CPU arrays so `vertices` / `indices` more fit. */
1219
+ reserve(vertices, indices) {
1220
+ const needVerts = (this.nVerts + vertices) * FLOATS_PER_VERTEX;
1221
+ if (needVerts > this.verts.length) {
1222
+ const grown = new Float32Array(doubledTo(this.verts.length, needVerts));
1223
+ grown.set(this.verts);
1224
+ this.verts = grown;
1225
+ }
1226
+ const needIdx = this.nIdx + indices;
1227
+ if (needIdx > this.idx.length) {
1228
+ const grown = new Uint32Array(doubledTo(this.idx.length, needIdx));
1229
+ grown.set(this.idx);
1230
+ this.idx = grown;
1231
+ }
1232
+ }
1233
+ nextRingSlot(tier) {
1234
+ const ring = this.rings[tier];
1235
+ const slot = this.nextInRing[tier];
1236
+ this.nextInRing[tier] = (slot + 1) % ring.length;
1237
+ const existing = ring[slot];
1238
+ if (existing) return existing;
1239
+ const set = this.createSet(BATCH_TIERS[tier].vertices, BATCH_TIERS[tier].indices);
1240
+ ring[slot] = set;
1241
+ return set;
1242
+ }
1243
+ nextLargeSlot() {
1244
+ const gl = this.gl;
1245
+ const slot = this.nextLarge;
1246
+ this.nextLarge = (slot + 1) % SOLID_LARGE_RING_SIZE;
1247
+ let set = this.largeRing[slot];
1248
+ if (!set) {
1249
+ set = this.createSet(
1250
+ doubledTo(SOLID_RING_SLOT_VERTICES, this.nVerts),
1251
+ doubledTo(BATCH_TIERS[BATCH_TIERS.length - 1].indices, this.nIdx)
1252
+ );
1253
+ this.largeRing[slot] = set;
1254
+ return set;
1255
+ }
1256
+ if (this.nVerts > set.vertexCapacity) {
1257
+ set.vertexCapacity = doubledTo(set.vertexCapacity, this.nVerts);
1258
+ gl.bindBuffer(gl.ARRAY_BUFFER, set.vbo);
1259
+ gl.bufferData(gl.ARRAY_BUFFER, set.vertexCapacity * FLOATS_PER_VERTEX * 4, gl.DYNAMIC_DRAW);
1260
+ }
1261
+ if (this.nIdx > set.indexCapacity) {
1262
+ set.indexCapacity = doubledTo(set.indexCapacity, this.nIdx);
1263
+ gl.bindVertexArray(set.vao);
1264
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, set.ibo);
1265
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, set.indexCapacity * 4, gl.DYNAMIC_DRAW);
1266
+ gl.bindVertexArray(null);
1267
+ set.canonicalQuads = 0;
1268
+ }
1269
+ return set;
1270
+ }
1271
+ createSet(vertices, indices) {
1272
+ const gl = this.gl;
1273
+ const vao = gl.createVertexArray();
1274
+ const vbo = gl.createBuffer();
1275
+ const ibo = gl.createBuffer();
1276
+ if (!vao || !vbo || !ibo) throw new Error("DrawBatch: failed to create GL objects");
1277
+ const stride = FLOATS_PER_VERTEX * 4;
1278
+ gl.bindVertexArray(vao);
1279
+ gl.bindBuffer(gl.ARRAY_BUFFER, vbo);
1280
+ gl.bufferData(gl.ARRAY_BUFFER, vertices * stride, gl.DYNAMIC_DRAW);
1281
+ gl.enableVertexAttribArray(this.aPos);
1282
+ gl.vertexAttribPointer(this.aPos, 2, gl.FLOAT, false, stride, 0);
1283
+ gl.enableVertexAttribArray(this.aColor);
1284
+ gl.vertexAttribPointer(this.aColor, 4, gl.FLOAT, false, stride, 8);
1285
+ gl.enableVertexAttribArray(this.aUv);
1286
+ gl.vertexAttribPointer(this.aUv, 2, gl.FLOAT, false, stride, 24);
1287
+ gl.enableVertexAttribArray(this.aPost);
1288
+ gl.vertexAttribPointer(this.aPost, 1, gl.FLOAT, false, stride, 32);
1289
+ gl.enableVertexAttribArray(this.aSlot);
1290
+ gl.vertexAttribPointer(this.aSlot, 1, gl.FLOAT, false, stride, 36);
1291
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, ibo);
1292
+ gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices * 4, gl.DYNAMIC_DRAW);
1293
+ gl.bindVertexArray(null);
1294
+ return { vao, vbo, ibo, vertexCapacity: vertices, indexCapacity: indices, canonicalQuads: 0 };
1295
+ }
1296
+ deleteSet(set) {
1297
+ const gl = this.gl;
1298
+ gl.deleteBuffer(set.vbo);
1299
+ gl.deleteBuffer(set.ibo);
1300
+ gl.deleteVertexArray(set.vao);
1301
+ }
1302
+ };
1303
+ var MAX_VECTOR_RASTER_PIXELS = 4096 * 4096;
1304
+ var SHRINK_SLACK = 4;
1305
+ var FALLBACK_WIDTH = 300;
1306
+ var FALLBACK_HEIGHT = 150;
1307
+ var DEFAULT_BUDGET_BYTES = 256 * 1024 * 1024;
1308
+ var cache6 = /* @__PURE__ */ new Map();
1309
+ var budgetBytes = DEFAULT_BUDGET_BYTES;
1310
+ var reads = 0;
1311
+ var readsAtLastPass = 0;
1312
+ var ready = createEmitter();
1313
+ var decodedVectors = /* @__PURE__ */ new Map();
1314
+ function isVectorImageSrc(src) {
1315
+ if (/^data:image\/svg\+xml[;,]/i.test(src)) return true;
1316
+ if (/^(data|blob):/i.test(src)) return false;
1317
+ return /\.svgz?$/i.test(src.replace(/[?#].*$/, ""));
1318
+ }
1319
+ function requireDom() {
1320
+ if (typeof Image === "undefined" || typeof createImageBitmap === "undefined") {
1321
+ throw new Error("weasel imageCache: no DOM image loader in this environment");
1322
+ }
1323
+ }
1324
+ async function decodeImage(src) {
1325
+ const img = new Image();
1326
+ img.crossOrigin = "anonymous";
1327
+ img.src = src;
1328
+ await img.decode();
1329
+ return img;
1330
+ }
1331
+ function decodeVector(src) {
1332
+ let decoded = decodedVectors.get(src);
1333
+ if (!decoded) {
1334
+ decoded = decodeImage(src);
1335
+ decodedVectors.set(src, decoded);
1336
+ decoded.catch(() => decodedVectors.delete(src));
1337
+ }
1338
+ return decoded;
1339
+ }
1340
+ async function rasterizeVector(src, size) {
1341
+ const img = await decodeVector(src);
1342
+ const width = size?.width ?? (img.naturalWidth || FALLBACK_WIDTH);
1343
+ const height = size?.height ?? (img.naturalHeight || FALLBACK_HEIGHT);
1344
+ const canvas = typeof OffscreenCanvas !== "undefined" ? new OffscreenCanvas(width, height) : Object.assign(document.createElement("canvas"), { width, height });
1345
+ const c2d = canvas.getContext("2d");
1346
+ if (!c2d) throw new Error("weasel imageCache: no 2D context to rasterize an SVG");
1347
+ c2d.drawImage(img, 0, 0, width, height);
1348
+ return createImageBitmap(canvas);
1349
+ }
1350
+ var defaultLoader = async (src, size) => {
1351
+ requireDom();
1352
+ if (isVectorImageSrc(src)) return rasterizeVector(src, size);
1353
+ return createImageBitmap(await decodeImage(src));
1354
+ };
1355
+ var loader = defaultLoader;
1356
+ function notify() {
1357
+ ready.emit();
1358
+ }
1359
+ var bytesOf = (bitmap) => bitmap ? bitmap.width * bitmap.height * 4 : 0;
1360
+ function enforceBudget(landed) {
1361
+ let total = 0;
1362
+ for (const entry of cache6.values()) total += bytesOf(entry.bitmap);
1363
+ if (total > budgetBytes) {
1364
+ const idle = [...cache6].filter(([src, entry]) => src !== landed && entry.bitmap !== void 0 && entry.readAt <= readsAtLastPass && !imageSourceInLatestFrame(entry.bitmap));
1365
+ idle.sort((a, b) => a[1].readAt - b[1].readAt);
1366
+ for (const [src, entry] of idle) {
1367
+ if (total <= budgetBytes) break;
1368
+ total -= bytesOf(entry.bitmap);
1369
+ releaseImage(src);
1370
+ }
1371
+ }
1372
+ readsAtLastPass = reads;
1373
+ }
1374
+ function setImageCacheBudget(bytes) {
1375
+ const previous = budgetBytes;
1376
+ budgetBytes = bytes;
1377
+ return previous;
1378
+ }
1379
+ function startLoad2(src) {
1380
+ const entry = { status: "loading", readAt: ++reads };
1381
+ cache6.set(src, entry);
1382
+ loader(src).then(
1383
+ (bitmap) => {
1384
+ if (cache6.get(src) !== entry) return;
1385
+ cache6.set(src, {
1386
+ status: "ready",
1387
+ bitmap,
1388
+ readAt: entry.readAt,
1389
+ ...isVectorImageSrc(src) ? { vector: { natural: { width: bitmap.width, height: bitmap.height }, scale: 1, failed: /* @__PURE__ */ new Set(), floor: 0 } } : {}
1390
+ });
1391
+ enforceBudget(src);
1392
+ notify();
1393
+ },
1394
+ () => {
1395
+ if (cache6.get(src) !== entry) return;
1396
+ cache6.set(src, { status: "error", readAt: entry.readAt });
1397
+ notify();
1398
+ }
1399
+ );
1400
+ }
1401
+ function rasterScaleFor(natural, drawnAt) {
1402
+ const need = Math.max(drawnAt.width / natural.width, drawnAt.height / natural.height);
1403
+ if (!(need > 0) || !Number.isFinite(need)) return void 0;
1404
+ const side = maxImageTextureSide();
1405
+ const cap = Math.min(
1406
+ side / natural.width,
1407
+ side / natural.height,
1408
+ Math.sqrt(MAX_VECTOR_RASTER_PIXELS / (natural.width * natural.height))
1409
+ );
1410
+ return Math.min(2 ** Math.ceil(Math.log2(need)), cap);
1411
+ }
1412
+ function maybeReraster(src, entry, v, drawnAt) {
1413
+ if (v.pending !== void 0) return;
1414
+ const wanted = rasterScaleFor(v.natural, drawnAt);
1415
+ if (wanted === void 0) return;
1416
+ const grow = wanted > v.scale;
1417
+ if (grow && v.shrunkTo === v.scale) v.floor = Math.max(v.floor, wanted);
1418
+ const target = grow ? wanted : Math.max(wanted, v.floor);
1419
+ if (!grow && target * SHRINK_SLACK > v.scale) return;
1420
+ for (const f of v.failed) if (target === f || grow && f > v.scale && target >= f) return;
1421
+ v.pending = target;
1422
+ const size = {
1423
+ width: Math.max(1, Math.round(v.natural.width * target)),
1424
+ height: Math.max(1, Math.round(v.natural.height * target))
1425
+ };
1426
+ loader(src, size).then(
1427
+ (bitmap) => {
1428
+ if (cache6.get(src) !== entry) return;
1429
+ v.pending = void 0;
1430
+ const old = entry.bitmap;
1431
+ entry.bitmap = bitmap;
1432
+ v.shrunkTo = grow ? void 0 : target;
1433
+ v.scale = target;
1434
+ if (old && old !== bitmap) releaseImageSource(old);
1435
+ enforceBudget(src);
1436
+ notify();
1437
+ },
1438
+ () => {
1439
+ if (cache6.get(src) !== entry) return;
1440
+ v.pending = void 0;
1441
+ v.failed.add(target);
1442
+ }
1443
+ );
1444
+ }
1445
+ function getImageBitmap(src, drawnAt) {
1446
+ const entry = cache6.get(src);
1447
+ if (!entry) {
1448
+ startLoad2(src);
1449
+ return void 0;
1450
+ }
1451
+ entry.readAt = ++reads;
1452
+ if (drawnAt && entry.vector) maybeReraster(src, entry, entry.vector, drawnAt);
1453
+ return entry.bitmap;
1454
+ }
1455
+ function imageStatus(src) {
1456
+ return cache6.get(src)?.status ?? "idle";
1457
+ }
1458
+ function releaseImage(src) {
1459
+ const entry = cache6.get(src);
1460
+ cache6.delete(src);
1461
+ decodedVectors.delete(src);
1462
+ if (entry?.bitmap) releaseImageSource(entry.bitmap);
1463
+ }
1464
+ function retryImage(src) {
1465
+ if (cache6.get(src)?.status !== "error") return;
1466
+ startLoad2(src);
1467
+ notify();
1468
+ }
1469
+ function subscribeImageReady(cb) {
1470
+ return ready.subscribe(cb);
1471
+ }
1472
+ function __setImageLoaderForTests(fn) {
1473
+ loader = fn;
1474
+ }
1475
+ function _resetImageCacheForTests() {
1476
+ cache6.clear();
1477
+ ready = createEmitter();
1478
+ decodedVectors.clear();
1479
+ loader = defaultLoader;
1480
+ budgetBytes = DEFAULT_BUDGET_BYTES;
1481
+ reads = 0;
1482
+ readsAtLastPass = 0;
1483
+ }
1484
+
1485
+ export { BATCH_ATTRIBUTE_LOCATIONS, BATCH_FILL_ATTRIBUTES, BATCH_FILL_UNIFORMS, BATCH_FRAG_SRC, BATCH_TEXTURE_SLOTS, BATCH_VERT_SRC, DrawBatch, FLOATS_PER_VERTEX, GLImageCache, PAINT_MODE_CONIC, PAINT_MODE_PLAIN, PAINT_MODE_RADIAL, STRAIGHT_RGB_GLSL, __setImageLoaderForTests, _resetCacheForTests, _resetImageCacheForTests, _resetMarkerCommandCacheForTests, _resetOutlineMeshCacheForTests, _resetOutlineStrokeMeshCacheForTests, _resetPaintDrawKindsForTests, _resetPatternSpecCacheForTests, _resetProgramRegistryForTests, _resetStrokeMeshCacheForTests, axisAlignedClipRect, cachedMarkerCommands, commandFill, commandPaint, commandStroke, fillInPoseFrame, fillToBoundsFrame, getImageBitmap, getMesh, getPaintDrawKind, getProgramSource, imageStatus, intersectClipRects, isPaintKindKnown, isVectorImageSrc, outlineMesh, outlineStrokeMesh, paintDrawKindRegistry, programSourceRegistry, quantizeEmWidth, quantizeStrokeScale, registerPaintDrawKind, registerPaintDrawKindLoader, registerProgram, releaseImage, releaseImageSource, resolveFillPattern, resolvePatternSpec, retryImage, setImageCacheBudget, strokeMesh, subscribeImageReady, uploadPremultiplied, warmPaintKinds };
1486
+ //# sourceMappingURL=chunk-LFD47OV2.js.map
1487
+ //# sourceMappingURL=chunk-LFD47OV2.js.map