@micjanic/recursive-grid 1.0.4 → 1.0.6

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.
@@ -1,3856 +0,0 @@
1
- import { E as y, U as Pt, T as we, a as Ft, a4 as z, a5 as L, D as H, t as M, a0 as V, M as U, ae as Bt, af as Rt, w as K, $ as j, V as ee, ag as Mt, ah as q, ai as G, F as Ut, v as Le, x as Ee, l as Y, d as He, J as A, a7 as me, R as xe, I as Ve, c as N, B as D, n as Se, S as te, z as re, aj as zt, ak as _e, N as pe, al as Q, s as ve, m as Ye, q as Xe, a9 as $e, ac as Ne, o as kt, p as Gt, aa as At, ab as Dt, ad as Ot, am as It, an as Wt, e as P, ao as Lt } from "./PixiApp-BHmY2ZMg.js";
2
- import { c as se, a as Et, b as Ht, B as Ke } from "./colorToUniform-C2jGzNe1.js";
3
- import { C as X } from "./CanvasPool-D2Uot4VE.js";
4
- class je {
5
- /**
6
- * Initialize the plugin with scope of application instance
7
- * @private
8
- * @param {object} [options] - See application options
9
- */
10
- static init(e) {
11
- Object.defineProperty(
12
- this,
13
- "resizeTo",
14
- {
15
- set(t) {
16
- globalThis.removeEventListener("resize", this.queueResize), this._resizeTo = t, t && (globalThis.addEventListener("resize", this.queueResize), this.resize());
17
- },
18
- get() {
19
- return this._resizeTo;
20
- }
21
- }
22
- ), this.queueResize = () => {
23
- this._resizeTo && (this._cancelResize(), this._resizeId = requestAnimationFrame(() => this.resize()));
24
- }, this._cancelResize = () => {
25
- this._resizeId && (cancelAnimationFrame(this._resizeId), this._resizeId = null);
26
- }, this.resize = () => {
27
- if (!this._resizeTo)
28
- return;
29
- this._cancelResize();
30
- let t, r;
31
- if (this._resizeTo === globalThis.window)
32
- t = globalThis.innerWidth, r = globalThis.innerHeight;
33
- else {
34
- const { clientWidth: i, clientHeight: n } = this._resizeTo;
35
- t = i, r = n;
36
- }
37
- this.renderer.resize(t, r), this.render();
38
- }, this._resizeId = null, this._resizeTo = null, this.resizeTo = e.resizeTo || null;
39
- }
40
- /**
41
- * Clean up the ticker, scoped to application
42
- * @private
43
- */
44
- static destroy() {
45
- globalThis.removeEventListener("resize", this.queueResize), this._cancelResize(), this._cancelResize = null, this.queueResize = null, this.resizeTo = null, this.resize = null;
46
- }
47
- }
48
- je.extension = y.Application;
49
- class qe {
50
- /**
51
- * Initialize the plugin with scope of application instance
52
- * @private
53
- * @param {object} [options] - See application options
54
- */
55
- static init(e) {
56
- e = Object.assign({
57
- autoStart: !0,
58
- sharedTicker: !1
59
- }, e), Object.defineProperty(
60
- this,
61
- "ticker",
62
- {
63
- set(t) {
64
- this._ticker && this._ticker.remove(this.render, this), this._ticker = t, t && t.add(this.render, this, Pt.LOW);
65
- },
66
- get() {
67
- return this._ticker;
68
- }
69
- }
70
- ), this.stop = () => {
71
- this._ticker.stop();
72
- }, this.start = () => {
73
- this._ticker.start();
74
- }, this._ticker = null, this.ticker = e.sharedTicker ? we.shared : new we(), e.autoStart && this.start();
75
- }
76
- /**
77
- * Clean up the ticker, scoped to application.
78
- * @private
79
- */
80
- static destroy() {
81
- if (this._ticker) {
82
- const e = this._ticker;
83
- this.ticker = null, e.destroy();
84
- }
85
- }
86
- }
87
- qe.extension = y.Application;
88
- class Vt extends Ft {
89
- constructor() {
90
- super(...arguments), this.chars = /* @__PURE__ */ Object.create(null), this.lineHeight = 0, this.fontFamily = "", this.fontMetrics = { fontSize: 0, ascent: 0, descent: 0 }, this.baseLineOffset = 0, this.distanceField = { type: "none", range: 0 }, this.pages = [], this.applyFillAsTint = !0, this.baseMeasurementFontSize = 100, this.baseRenderedFontSize = 100;
91
- }
92
- /**
93
- * The name of the font face.
94
- * @deprecated since 8.0.0 Use `fontFamily` instead.
95
- */
96
- get font() {
97
- return z(L, "BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."), this.fontFamily;
98
- }
99
- /**
100
- * The map of base page textures (i.e., sheets of glyphs).
101
- * @deprecated since 8.0.0 Use `pages` instead.
102
- */
103
- get pageTextures() {
104
- return z(L, "BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."), this.pages;
105
- }
106
- /**
107
- * The size of the font face in pixels.
108
- * @deprecated since 8.0.0 Use `fontMetrics.fontSize` instead.
109
- */
110
- get size() {
111
- return z(L, "BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."), this.fontMetrics.fontSize;
112
- }
113
- /**
114
- * The kind of distance field for this font or "none".
115
- * @deprecated since 8.0.0 Use `distanceField.type` instead.
116
- */
117
- get distanceFieldRange() {
118
- return z(L, "BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."), this.distanceField.range;
119
- }
120
- /**
121
- * The range of the distance field in pixels.
122
- * @deprecated since 8.0.0 Use `distanceField.range` instead.
123
- */
124
- get distanceFieldType() {
125
- return z(L, "BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."), this.distanceField.type;
126
- }
127
- destroy(e = !1) {
128
- var t;
129
- this.emit("destroy", this), this.removeAllListeners();
130
- for (const r in this.chars)
131
- (t = this.chars[r].texture) == null || t.destroy();
132
- this.chars = null, e && (this.pages.forEach((r) => r.texture.destroy(!0)), this.pages = null);
133
- }
134
- }
135
- /**
136
- * tiny-lru
137
- *
138
- * @copyright 2025 Jason Mulligan <jason.mulligan@avoidwork.com>
139
- * @license BSD-3-Clause
140
- * @version 11.4.5
141
- */
142
- class Yt {
143
- /**
144
- * Creates a new LRU cache instance.
145
- * Note: Constructor does not validate parameters. Use lru() factory function for parameter validation.
146
- *
147
- * @constructor
148
- * @param {number} [max=0] - Maximum number of items to store. 0 means unlimited.
149
- * @param {number} [ttl=0] - Time to live in milliseconds. 0 means no expiration.
150
- * @param {boolean} [resetTtl=false] - Whether to reset TTL when accessing existing items via get().
151
- * @example
152
- * const cache = new LRU(1000, 60000, true); // 1000 items, 1 minute TTL, reset on access
153
- * @see {@link lru} For parameter validation
154
- * @since 1.0.0
155
- */
156
- constructor(e = 0, t = 0, r = !1) {
157
- this.first = null, this.items = /* @__PURE__ */ Object.create(null), this.last = null, this.max = e, this.resetTtl = r, this.size = 0, this.ttl = t;
158
- }
159
- /**
160
- * Removes all items from the cache.
161
- *
162
- * @method clear
163
- * @memberof LRU
164
- * @returns {LRU} The LRU instance for method chaining.
165
- * @example
166
- * cache.clear();
167
- * console.log(cache.size); // 0
168
- * @since 1.0.0
169
- */
170
- clear() {
171
- return this.first = null, this.items = /* @__PURE__ */ Object.create(null), this.last = null, this.size = 0, this;
172
- }
173
- /**
174
- * Removes an item from the cache by key.
175
- *
176
- * @method delete
177
- * @memberof LRU
178
- * @param {string} key - The key of the item to delete.
179
- * @returns {LRU} The LRU instance for method chaining.
180
- * @example
181
- * cache.set('key1', 'value1');
182
- * cache.delete('key1');
183
- * console.log(cache.has('key1')); // false
184
- * @see {@link LRU#has}
185
- * @see {@link LRU#clear}
186
- * @since 1.0.0
187
- */
188
- delete(e) {
189
- if (this.has(e)) {
190
- const t = this.items[e];
191
- delete this.items[e], this.size--, t.prev !== null && (t.prev.next = t.next), t.next !== null && (t.next.prev = t.prev), this.first === t && (this.first = t.next), this.last === t && (this.last = t.prev);
192
- }
193
- return this;
194
- }
195
- /**
196
- * Returns an array of [key, value] pairs for the specified keys.
197
- * Order follows LRU order (least to most recently used).
198
- *
199
- * @method entries
200
- * @memberof LRU
201
- * @param {string[]} [keys=this.keys()] - Array of keys to get entries for. Defaults to all keys.
202
- * @returns {Array<Array<*>>} Array of [key, value] pairs in LRU order.
203
- * @example
204
- * cache.set('a', 1).set('b', 2);
205
- * console.log(cache.entries()); // [['a', 1], ['b', 2]]
206
- * console.log(cache.entries(['a'])); // [['a', 1]]
207
- * @see {@link LRU#keys}
208
- * @see {@link LRU#values}
209
- * @since 11.1.0
210
- */
211
- entries(e = this.keys()) {
212
- return e.map((t) => [t, this.get(t)]);
213
- }
214
- /**
215
- * Removes the least recently used item from the cache.
216
- *
217
- * @method evict
218
- * @memberof LRU
219
- * @param {boolean} [bypass=false] - Whether to force eviction even when cache is empty.
220
- * @returns {LRU} The LRU instance for method chaining.
221
- * @example
222
- * cache.set('old', 'value').set('new', 'value');
223
- * cache.evict(); // Removes 'old' item
224
- * @see {@link LRU#setWithEvicted}
225
- * @since 1.0.0
226
- */
227
- evict(e = !1) {
228
- if (e || this.size > 0) {
229
- const t = this.first;
230
- delete this.items[t.key], --this.size === 0 ? (this.first = null, this.last = null) : (this.first = t.next, this.first.prev = null);
231
- }
232
- return this;
233
- }
234
- /**
235
- * Returns the expiration timestamp for a given key.
236
- *
237
- * @method expiresAt
238
- * @memberof LRU
239
- * @param {string} key - The key to check expiration for.
240
- * @returns {number|undefined} The expiration timestamp in milliseconds, or undefined if key doesn't exist.
241
- * @example
242
- * const cache = new LRU(100, 5000); // 5 second TTL
243
- * cache.set('key1', 'value1');
244
- * console.log(cache.expiresAt('key1')); // timestamp 5 seconds from now
245
- * @see {@link LRU#get}
246
- * @see {@link LRU#has}
247
- * @since 1.0.0
248
- */
249
- expiresAt(e) {
250
- let t;
251
- return this.has(e) && (t = this.items[e].expiry), t;
252
- }
253
- /**
254
- * Retrieves a value from the cache by key. Updates the item's position to most recently used.
255
- *
256
- * @method get
257
- * @memberof LRU
258
- * @param {string} key - The key to retrieve.
259
- * @returns {*} The value associated with the key, or undefined if not found or expired.
260
- * @example
261
- * cache.set('key1', 'value1');
262
- * console.log(cache.get('key1')); // 'value1'
263
- * console.log(cache.get('nonexistent')); // undefined
264
- * @see {@link LRU#set}
265
- * @see {@link LRU#has}
266
- * @since 1.0.0
267
- */
268
- get(e) {
269
- const t = this.items[e];
270
- if (t !== void 0) {
271
- if (this.ttl > 0 && t.expiry <= Date.now()) {
272
- this.delete(e);
273
- return;
274
- }
275
- return this.moveToEnd(t), t.value;
276
- }
277
- }
278
- /**
279
- * Checks if a key exists in the cache.
280
- *
281
- * @method has
282
- * @memberof LRU
283
- * @param {string} key - The key to check for.
284
- * @returns {boolean} True if the key exists, false otherwise.
285
- * @example
286
- * cache.set('key1', 'value1');
287
- * console.log(cache.has('key1')); // true
288
- * console.log(cache.has('nonexistent')); // false
289
- * @see {@link LRU#get}
290
- * @see {@link LRU#delete}
291
- * @since 9.0.0
292
- */
293
- has(e) {
294
- return e in this.items;
295
- }
296
- /**
297
- * Efficiently moves an item to the end of the LRU list (most recently used position).
298
- * This is an internal optimization method that avoids the overhead of the full set() operation
299
- * when only LRU position needs to be updated.
300
- *
301
- * @method moveToEnd
302
- * @memberof LRU
303
- * @param {Object} item - The cache item with prev/next pointers to reposition.
304
- * @private
305
- * @since 11.3.5
306
- */
307
- moveToEnd(e) {
308
- this.last !== e && (e.prev !== null && (e.prev.next = e.next), e.next !== null && (e.next.prev = e.prev), this.first === e && (this.first = e.next), e.prev = this.last, e.next = null, this.last !== null && (this.last.next = e), this.last = e, this.first === null && (this.first = e));
309
- }
310
- /**
311
- * Returns an array of all keys in the cache, ordered from least to most recently used.
312
- *
313
- * @method keys
314
- * @memberof LRU
315
- * @returns {string[]} Array of keys in LRU order.
316
- * @example
317
- * cache.set('a', 1).set('b', 2);
318
- * cache.get('a'); // Move 'a' to most recent
319
- * console.log(cache.keys()); // ['b', 'a']
320
- * @see {@link LRU#values}
321
- * @see {@link LRU#entries}
322
- * @since 9.0.0
323
- */
324
- keys() {
325
- const e = [];
326
- let t = this.first;
327
- for (; t !== null; )
328
- e.push(t.key), t = t.next;
329
- return e;
330
- }
331
- /**
332
- * Sets a value in the cache and returns any evicted item.
333
- *
334
- * @method setWithEvicted
335
- * @memberof LRU
336
- * @param {string} key - The key to set.
337
- * @param {*} value - The value to store.
338
- * @param {boolean} [resetTtl=this.resetTtl] - Whether to reset the TTL for this operation.
339
- * @returns {Object|null} The evicted item (if any) with shape {key, value, expiry, prev, next}, or null.
340
- * @example
341
- * const cache = new LRU(2);
342
- * cache.set('a', 1).set('b', 2);
343
- * const evicted = cache.setWithEvicted('c', 3); // evicted = {key: 'a', value: 1, ...}
344
- * @see {@link LRU#set}
345
- * @see {@link LRU#evict}
346
- * @since 11.3.0
347
- */
348
- setWithEvicted(e, t, r = this.resetTtl) {
349
- let i = null;
350
- if (this.has(e))
351
- this.set(e, t, !0, r);
352
- else {
353
- this.max > 0 && this.size === this.max && (i = { ...this.first }, this.evict(!0));
354
- let n = this.items[e] = {
355
- expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
356
- key: e,
357
- prev: this.last,
358
- next: null,
359
- value: t
360
- };
361
- ++this.size === 1 ? this.first = n : this.last.next = n, this.last = n;
362
- }
363
- return i;
364
- }
365
- /**
366
- * Sets a value in the cache. Updates the item's position to most recently used.
367
- *
368
- * @method set
369
- * @memberof LRU
370
- * @param {string} key - The key to set.
371
- * @param {*} value - The value to store.
372
- * @param {boolean} [bypass=false] - Internal parameter for setWithEvicted method.
373
- * @param {boolean} [resetTtl=this.resetTtl] - Whether to reset the TTL for this operation.
374
- * @returns {LRU} The LRU instance for method chaining.
375
- * @example
376
- * cache.set('key1', 'value1')
377
- * .set('key2', 'value2')
378
- * .set('key3', 'value3');
379
- * @see {@link LRU#get}
380
- * @see {@link LRU#setWithEvicted}
381
- * @since 1.0.0
382
- */
383
- set(e, t, r = !1, i = this.resetTtl) {
384
- let n = this.items[e];
385
- return r || n !== void 0 ? (n.value = t, r === !1 && i && (n.expiry = this.ttl > 0 ? Date.now() + this.ttl : this.ttl), this.moveToEnd(n)) : (this.max > 0 && this.size === this.max && this.evict(!0), n = this.items[e] = {
386
- expiry: this.ttl > 0 ? Date.now() + this.ttl : this.ttl,
387
- key: e,
388
- prev: this.last,
389
- next: null,
390
- value: t
391
- }, ++this.size === 1 ? this.first = n : this.last.next = n, this.last = n), this;
392
- }
393
- /**
394
- * Returns an array of all values in the cache for the specified keys.
395
- * Order follows LRU order (least to most recently used).
396
- *
397
- * @method values
398
- * @memberof LRU
399
- * @param {string[]} [keys=this.keys()] - Array of keys to get values for. Defaults to all keys.
400
- * @returns {Array<*>} Array of values corresponding to the keys in LRU order.
401
- * @example
402
- * cache.set('a', 1).set('b', 2);
403
- * console.log(cache.values()); // [1, 2]
404
- * console.log(cache.values(['a'])); // [1]
405
- * @see {@link LRU#keys}
406
- * @see {@link LRU#entries}
407
- * @since 11.1.0
408
- */
409
- values(e = this.keys()) {
410
- return e.map((t) => this.get(t));
411
- }
412
- }
413
- function Qe(o = 1e3, e = 0, t = !1) {
414
- if (isNaN(o) || o < 0)
415
- throw new TypeError("Invalid max value");
416
- if (isNaN(e) || e < 0)
417
- throw new TypeError("Invalid ttl value");
418
- if (typeof t != "boolean")
419
- throw new TypeError("Invalid resetTtl value");
420
- return new Yt(o, e, t);
421
- }
422
- const Xt = [
423
- "serif",
424
- "sans-serif",
425
- "monospace",
426
- "cursive",
427
- "fantasy",
428
- "system-ui"
429
- ];
430
- function ie(o) {
431
- const e = typeof o.fontSize == "number" ? `${o.fontSize}px` : o.fontSize;
432
- let t = o.fontFamily;
433
- Array.isArray(o.fontFamily) || (t = o.fontFamily.split(","));
434
- for (let r = t.length - 1; r >= 0; r--) {
435
- let i = t[r].trim();
436
- !/([\"\'])[^\'\"]+\1/.test(i) && !Xt.includes(i) && (i = `"${i}"`), t[r] = i;
437
- }
438
- return `${o.fontStyle} ${o.fontVariant} ${o.fontWeight} ${e} ${t.join(",")}`;
439
- }
440
- const oe = {
441
- // TextMetrics requires getImageData readback for measuring fonts.
442
- willReadFrequently: !0
443
- }, k = class p {
444
- /**
445
- * Checking that we can use modern canvas 2D API.
446
- *
447
- * Note: This is an unstable API, Chrome < 94 use `textLetterSpacing`, later versions use `letterSpacing`.
448
- * @see TextMetrics.experimentalLetterSpacing
449
- * @see https://developer.mozilla.org/en-US/docs/Web/API/ICanvasRenderingContext2D/letterSpacing
450
- * @see https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441
451
- */
452
- static get experimentalLetterSpacingSupported() {
453
- let e = p._experimentalLetterSpacingSupported;
454
- if (e === void 0) {
455
- const t = H.get().getCanvasRenderingContext2D().prototype;
456
- e = p._experimentalLetterSpacingSupported = "letterSpacing" in t || "textLetterSpacing" in t;
457
- }
458
- return e;
459
- }
460
- /**
461
- * @param text - the text that was measured
462
- * @param style - the style that was measured
463
- * @param width - the measured width of the text
464
- * @param height - the measured height of the text
465
- * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style
466
- * @param lineWidths - an array of the line widths for each line matched to `lines`
467
- * @param lineHeight - the measured line height for this style
468
- * @param maxLineWidth - the maximum line width for all measured lines
469
- * @param {FontMetrics} fontProperties - the font properties object from TextMetrics.measureFont
470
- */
471
- constructor(e, t, r, i, n, s, a, u, l) {
472
- this.text = e, this.style = t, this.width = r, this.height = i, this.lines = n, this.lineWidths = s, this.lineHeight = a, this.maxLineWidth = u, this.fontProperties = l;
473
- }
474
- /**
475
- * Measures the supplied string of text and returns a Rectangle.
476
- * @param text - The text to measure.
477
- * @param style - The text style to use for measuring
478
- * @param canvas - optional specification of the canvas to use for measuring.
479
- * @param wordWrap
480
- * @returns Measured width and height of the text.
481
- */
482
- static measureText(e = " ", t, r = p._canvas, i = t.wordWrap) {
483
- var b;
484
- const n = `${e}-${t.styleKey}-wordWrap-${i}`;
485
- if (p._measurementCache.has(n))
486
- return p._measurementCache.get(n);
487
- const s = ie(t), a = p.measureFont(s);
488
- a.fontSize === 0 && (a.fontSize = t.fontSize, a.ascent = t.fontSize);
489
- const u = p.__context;
490
- u.font = s;
491
- const h = (i ? p._wordWrap(e, t, r) : e).split(/(?:\r\n|\r|\n)/), c = new Array(h.length);
492
- let d = 0;
493
- for (let m = 0; m < h.length; m++) {
494
- const T = p._measureText(h[m], t.letterSpacing, u);
495
- c[m] = T, d = Math.max(d, T);
496
- }
497
- const f = ((b = t._stroke) == null ? void 0 : b.width) || 0;
498
- let x = d + f;
499
- t.dropShadow && (x += t.dropShadow.distance);
500
- const _ = t.lineHeight || a.fontSize;
501
- let v = Math.max(_, a.fontSize + f) + (h.length - 1) * (_ + t.leading);
502
- t.dropShadow && (v += t.dropShadow.distance);
503
- const g = new p(
504
- e,
505
- t,
506
- x,
507
- v,
508
- h,
509
- c,
510
- _ + t.leading,
511
- d,
512
- a
513
- );
514
- return p._measurementCache.set(n, g), g;
515
- }
516
- static _measureText(e, t, r) {
517
- let i = !1;
518
- p.experimentalLetterSpacingSupported && (p.experimentalLetterSpacing ? (r.letterSpacing = `${t}px`, r.textLetterSpacing = `${t}px`, i = !0) : (r.letterSpacing = "0px", r.textLetterSpacing = "0px"));
519
- const n = r.measureText(e);
520
- let s = n.width;
521
- const a = -n.actualBoundingBoxLeft;
522
- let l = n.actualBoundingBoxRight - a;
523
- if (s > 0)
524
- if (i)
525
- s -= t, l -= t;
526
- else {
527
- const h = (p.graphemeSegmenter(e).length - 1) * t;
528
- s += h, l += h;
529
- }
530
- return Math.max(s, l);
531
- }
532
- /**
533
- * Applies newlines to a string to have it optimally fit into the horizontal
534
- * bounds set by the Text object's wordWrapWidth property.
535
- * @param text - String to apply word wrapping to
536
- * @param style - the style to use when wrapping
537
- * @param canvas - optional specification of the canvas to use for measuring.
538
- * @returns New string with new lines applied where required
539
- */
540
- static _wordWrap(e, t, r = p._canvas) {
541
- const i = r.getContext("2d", oe);
542
- let n = 0, s = "", a = "";
543
- const u = /* @__PURE__ */ Object.create(null), { letterSpacing: l, whiteSpace: h } = t, c = p._collapseSpaces(h), d = p._collapseNewlines(h);
544
- let f = !c;
545
- const x = t.wordWrapWidth + l, _ = p._tokenize(e);
546
- for (let v = 0; v < _.length; v++) {
547
- let g = _[v];
548
- if (p._isNewline(g)) {
549
- if (!d) {
550
- a += p._addLine(s), f = !c, s = "", n = 0;
551
- continue;
552
- }
553
- g = " ";
554
- }
555
- if (c) {
556
- const m = p.isBreakingSpace(g), T = p.isBreakingSpace(s[s.length - 1]);
557
- if (m && T)
558
- continue;
559
- }
560
- const b = p._getFromCache(g, l, u, i);
561
- if (b > x)
562
- if (s !== "" && (a += p._addLine(s), s = "", n = 0), p.canBreakWords(g, t.breakWords)) {
563
- const m = p.wordWrapSplit(g);
564
- for (let T = 0; T < m.length; T++) {
565
- let S = m[T], B = S, w = 1;
566
- for (; m[T + w]; ) {
567
- const R = m[T + w];
568
- if (!p.canBreakChars(B, R, g, T, t.breakWords))
569
- S += R;
570
- else
571
- break;
572
- B = R, w++;
573
- }
574
- T += w - 1;
575
- const F = p._getFromCache(S, l, u, i);
576
- F + n > x && (a += p._addLine(s), f = !1, s = "", n = 0), s += S, n += F;
577
- }
578
- } else {
579
- s.length > 0 && (a += p._addLine(s), s = "", n = 0);
580
- const m = v === _.length - 1;
581
- a += p._addLine(g, !m), f = !1, s = "", n = 0;
582
- }
583
- else
584
- b + n > x && (f = !1, a += p._addLine(s), s = "", n = 0), (s.length > 0 || !p.isBreakingSpace(g) || f) && (s += g, n += b);
585
- }
586
- return a += p._addLine(s, !1), a;
587
- }
588
- /**
589
- * Convenience function for logging each line added during the wordWrap method.
590
- * @param line - The line of text to add
591
- * @param newLine - Add new line character to end
592
- * @returns A formatted line
593
- */
594
- static _addLine(e, t = !0) {
595
- return e = p._trimRight(e), e = t ? `${e}
596
- ` : e, e;
597
- }
598
- /**
599
- * Gets & sets the widths of calculated characters in a cache object
600
- * @param key - The key
601
- * @param letterSpacing - The letter spacing
602
- * @param cache - The cache
603
- * @param context - The canvas context
604
- * @returns The from cache.
605
- */
606
- static _getFromCache(e, t, r, i) {
607
- let n = r[e];
608
- return typeof n != "number" && (n = p._measureText(e, t, i) + t, r[e] = n), n;
609
- }
610
- /**
611
- * Determines whether we should collapse breaking spaces.
612
- * @param whiteSpace - The TextStyle property whiteSpace
613
- * @returns Should collapse
614
- */
615
- static _collapseSpaces(e) {
616
- return e === "normal" || e === "pre-line";
617
- }
618
- /**
619
- * Determines whether we should collapse newLine chars.
620
- * @param whiteSpace - The white space
621
- * @returns should collapse
622
- */
623
- static _collapseNewlines(e) {
624
- return e === "normal";
625
- }
626
- /**
627
- * Trims breaking whitespaces from string.
628
- * @param text - The text
629
- * @returns Trimmed string
630
- */
631
- static _trimRight(e) {
632
- if (typeof e != "string")
633
- return "";
634
- for (let t = e.length - 1; t >= 0; t--) {
635
- const r = e[t];
636
- if (!p.isBreakingSpace(r))
637
- break;
638
- e = e.slice(0, -1);
639
- }
640
- return e;
641
- }
642
- /**
643
- * Determines if char is a newline.
644
- * @param char - The character
645
- * @returns True if newline, False otherwise.
646
- */
647
- static _isNewline(e) {
648
- return typeof e != "string" ? !1 : p._newlines.includes(e.charCodeAt(0));
649
- }
650
- /**
651
- * Determines if char is a breaking whitespace.
652
- *
653
- * It allows one to determine whether char should be a breaking whitespace
654
- * For example certain characters in CJK langs or numbers.
655
- * It must return a boolean.
656
- * @param char - The character
657
- * @param [_nextChar] - The next character
658
- * @returns True if whitespace, False otherwise.
659
- */
660
- static isBreakingSpace(e, t) {
661
- return typeof e != "string" ? !1 : p._breakingSpaces.includes(e.charCodeAt(0));
662
- }
663
- /**
664
- * Splits a string into words, breaking-spaces and newLine characters
665
- * @param text - The text
666
- * @returns A tokenized array
667
- */
668
- static _tokenize(e) {
669
- const t = [];
670
- let r = "";
671
- if (typeof e != "string")
672
- return t;
673
- for (let i = 0; i < e.length; i++) {
674
- const n = e[i], s = e[i + 1];
675
- if (p.isBreakingSpace(n, s) || p._isNewline(n)) {
676
- r !== "" && (t.push(r), r = ""), n === "\r" && s === `
677
- ` ? (t.push(`\r
678
- `), i++) : t.push(n);
679
- continue;
680
- }
681
- r += n;
682
- }
683
- return r !== "" && t.push(r), t;
684
- }
685
- /**
686
- * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
687
- *
688
- * It allows one to customise which words should break
689
- * Examples are if the token is CJK or numbers.
690
- * It must return a boolean.
691
- * @param _token - The token
692
- * @param breakWords - The style attr break words
693
- * @returns Whether to break word or not
694
- */
695
- static canBreakWords(e, t) {
696
- return t;
697
- }
698
- /**
699
- * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
700
- *
701
- * It allows one to determine whether a pair of characters
702
- * should be broken by newlines
703
- * For example certain characters in CJK langs or numbers.
704
- * It must return a boolean.
705
- * @param _char - The character
706
- * @param _nextChar - The next character
707
- * @param _token - The token/word the characters are from
708
- * @param _index - The index in the token of the char
709
- * @param _breakWords - The style attr break words
710
- * @returns whether to break word or not
711
- */
712
- static canBreakChars(e, t, r, i, n) {
713
- return !0;
714
- }
715
- /**
716
- * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
717
- *
718
- * It is called when a token (usually a word) has to be split into separate pieces
719
- * in order to determine the point to break a word.
720
- * It must return an array of characters.
721
- * @param token - The token to split
722
- * @returns The characters of the token
723
- * @see CanvasTextMetrics.graphemeSegmenter
724
- */
725
- static wordWrapSplit(e) {
726
- return p.graphemeSegmenter(e);
727
- }
728
- /**
729
- * Calculates the ascent, descent and fontSize of a given font-style
730
- * @param font - String representing the style of the font
731
- * @returns Font properties object
732
- */
733
- static measureFont(e) {
734
- if (p._fonts[e])
735
- return p._fonts[e];
736
- const t = p._context;
737
- t.font = e;
738
- const r = t.measureText(p.METRICS_STRING + p.BASELINE_SYMBOL), i = {
739
- ascent: r.actualBoundingBoxAscent,
740
- descent: r.actualBoundingBoxDescent,
741
- fontSize: r.actualBoundingBoxAscent + r.actualBoundingBoxDescent
742
- };
743
- return p._fonts[e] = i, i;
744
- }
745
- /**
746
- * Clear font metrics in metrics cache.
747
- * @param {string} [font] - font name. If font name not set then clear cache for all fonts.
748
- */
749
- static clearMetrics(e = "") {
750
- e ? delete p._fonts[e] : p._fonts = {};
751
- }
752
- /**
753
- * Cached canvas element for measuring text
754
- * TODO: this should be private, but isn't because of backward compat, will fix later.
755
- * @ignore
756
- */
757
- static get _canvas() {
758
- if (!p.__canvas) {
759
- let e;
760
- try {
761
- const t = new OffscreenCanvas(0, 0), r = t.getContext("2d", oe);
762
- if (r != null && r.measureText)
763
- return p.__canvas = t, t;
764
- e = H.get().createCanvas();
765
- } catch {
766
- e = H.get().createCanvas();
767
- }
768
- e.width = e.height = 10, p.__canvas = e;
769
- }
770
- return p.__canvas;
771
- }
772
- /**
773
- * TODO: this should be private, but isn't because of backward compat, will fix later.
774
- * @ignore
775
- */
776
- static get _context() {
777
- return p.__context || (p.__context = p._canvas.getContext("2d", oe)), p.__context;
778
- }
779
- };
780
- k.METRICS_STRING = "|ÉqÅ";
781
- k.BASELINE_SYMBOL = "M";
782
- k.BASELINE_MULTIPLIER = 1.4;
783
- k.HEIGHT_MULTIPLIER = 2;
784
- k.graphemeSegmenter = (() => {
785
- if (typeof (Intl == null ? void 0 : Intl.Segmenter) == "function") {
786
- const o = new Intl.Segmenter();
787
- return (e) => {
788
- const t = o.segment(e), r = [];
789
- let i = 0;
790
- for (const n of t)
791
- r[i++] = n.segment;
792
- return r;
793
- };
794
- }
795
- return (o) => [...o];
796
- })();
797
- k.experimentalLetterSpacing = !1;
798
- k._fonts = {};
799
- k._newlines = [
800
- 10,
801
- // line feed
802
- 13
803
- // carriage return
804
- ];
805
- k._breakingSpaces = [
806
- 9,
807
- // character tabulation
808
- 32,
809
- // space
810
- 8192,
811
- // en quad
812
- 8193,
813
- // em quad
814
- 8194,
815
- // en space
816
- 8195,
817
- // em space
818
- 8196,
819
- // three-per-em space
820
- 8197,
821
- // four-per-em space
822
- 8198,
823
- // six-per-em space
824
- 8200,
825
- // punctuation space
826
- 8201,
827
- // thin space
828
- 8202,
829
- // hair space
830
- 8287,
831
- // medium mathematical space
832
- 12288
833
- // ideographic space
834
- ];
835
- k._measurementCache = Qe(1e3);
836
- let O = k;
837
- const Ce = 1e5;
838
- function ne(o, e, t, r = 0) {
839
- if (o.texture === M.WHITE && !o.fill)
840
- return V.shared.setValue(o.color).setAlpha(o.alpha ?? 1).toHexa();
841
- if (o.fill) {
842
- if (o.fill instanceof Bt) {
843
- const i = o.fill, n = e.createPattern(i.texture.source.resource, "repeat"), s = i.transform.copyTo(U.shared);
844
- return s.scale(
845
- i.texture.frame.width,
846
- i.texture.frame.height
847
- ), n.setTransform(s), n;
848
- } else if (o.fill instanceof Rt) {
849
- const i = o.fill, n = i.type === "linear", s = i.textureSpace === "local";
850
- let a = 1, u = 1;
851
- s && t && (a = t.width + r, u = t.height + r);
852
- let l, h = !1;
853
- if (n) {
854
- const { start: c, end: d } = i;
855
- l = e.createLinearGradient(
856
- c.x * a,
857
- c.y * u,
858
- d.x * a,
859
- d.y * u
860
- ), h = Math.abs(d.x - c.x) < Math.abs((d.y - c.y) * 0.1);
861
- } else {
862
- const { center: c, innerRadius: d, outerCenter: f, outerRadius: x } = i;
863
- l = e.createRadialGradient(
864
- c.x * a,
865
- c.y * u,
866
- d * a,
867
- f.x * a,
868
- f.y * u,
869
- x * a
870
- );
871
- }
872
- if (h && s && t) {
873
- const c = t.lineHeight / u;
874
- for (let d = 0; d < t.lines.length; d++) {
875
- const f = (d * t.lineHeight + r / 2) / u;
876
- i.colorStops.forEach((x) => {
877
- const _ = f + x.offset * c;
878
- l.addColorStop(
879
- // fix to 5 decimal places to avoid floating point precision issues
880
- Math.floor(_ * Ce) / Ce,
881
- V.shared.setValue(x.color).toHex()
882
- );
883
- });
884
- }
885
- } else
886
- i.colorStops.forEach((c) => {
887
- l.addColorStop(c.offset, V.shared.setValue(c.color).toHex());
888
- });
889
- return l;
890
- }
891
- } else {
892
- const i = e.createPattern(o.texture.source.resource, "repeat"), n = o.matrix.copyTo(U.shared);
893
- return n.scale(o.texture.frame.width, o.texture.frame.height), i.setTransform(n), i;
894
- }
895
- return K("FillStyle not recognised", o), "red";
896
- }
897
- const Je = class Ze extends Vt {
898
- /**
899
- * @param options - The options for the dynamic bitmap font.
900
- */
901
- constructor(e) {
902
- super(), this.resolution = 1, this.pages = [], this._padding = 0, this._measureCache = /* @__PURE__ */ Object.create(null), this._currentChars = [], this._currentX = 0, this._currentY = 0, this._currentMaxCharHeight = 0, this._currentPageIndex = -1, this._skipKerning = !1;
903
- const t = { ...Ze.defaultOptions, ...e };
904
- this._textureSize = t.textureSize, this._mipmap = t.mipmap;
905
- const r = t.style.clone();
906
- t.overrideFill && (r._fill.color = 16777215, r._fill.alpha = 1, r._fill.texture = M.WHITE, r._fill.fill = null), this.applyFillAsTint = t.overrideFill;
907
- const i = r.fontSize;
908
- r.fontSize = this.baseMeasurementFontSize;
909
- const n = ie(r);
910
- t.overrideSize ? r._stroke && (r._stroke.width *= this.baseRenderedFontSize / i) : r.fontSize = this.baseRenderedFontSize = i, this._style = r, this._skipKerning = t.skipKerning ?? !1, this.resolution = t.resolution ?? 1, this._padding = t.padding ?? 4, t.textureStyle && (this._textureStyle = t.textureStyle instanceof j ? t.textureStyle : new j(t.textureStyle)), this.fontMetrics = O.measureFont(n), this.lineHeight = r.lineHeight || this.fontMetrics.fontSize || r.fontSize;
911
- }
912
- ensureCharacters(e) {
913
- var v, g;
914
- const t = O.graphemeSegmenter(e).filter((b) => !this._currentChars.includes(b)).filter((b, m, T) => T.indexOf(b) === m);
915
- if (!t.length)
916
- return;
917
- this._currentChars = [...this._currentChars, ...t];
918
- let r;
919
- this._currentPageIndex === -1 ? r = this._nextPage() : r = this.pages[this._currentPageIndex];
920
- let { canvas: i, context: n } = r.canvasAndContext, s = r.texture.source;
921
- const a = this._style;
922
- let u = this._currentX, l = this._currentY, h = this._currentMaxCharHeight;
923
- const c = this.baseRenderedFontSize / this.baseMeasurementFontSize, d = this._padding * c;
924
- let f = !1;
925
- const x = i.width / this.resolution, _ = i.height / this.resolution;
926
- for (let b = 0; b < t.length; b++) {
927
- const m = t[b], T = O.measureText(m, a, i, !1);
928
- T.lineHeight = T.height;
929
- const S = T.width * c, B = Math.ceil((a.fontStyle === "italic" ? 2 : 1) * S), w = T.height * c, F = B + d * 2, R = w + d * 2;
930
- if (f = !1, m !== `
931
- ` && m !== "\r" && m !== " " && m !== " " && (f = !0, h = Math.ceil(Math.max(R, h))), u + F > x && (l += h, h = R, u = 0, l + h > _)) {
932
- s.update();
933
- const I = this._nextPage();
934
- i = I.canvasAndContext.canvas, n = I.canvasAndContext.context, s = I.texture.source, u = 0, l = 0, h = 0;
935
- }
936
- const ae = S / c - (((v = a.dropShadow) == null ? void 0 : v.distance) ?? 0) - (((g = a._stroke) == null ? void 0 : g.width) ?? 0);
937
- if (this.chars[m] = {
938
- id: m.codePointAt(0),
939
- xOffset: -this._padding,
940
- yOffset: -this._padding,
941
- xAdvance: ae,
942
- kerning: {}
943
- }, f) {
944
- this._drawGlyph(
945
- n,
946
- T,
947
- u + d,
948
- l + d,
949
- c,
950
- a
951
- );
952
- const I = s.width * c, $ = s.height * c, C = new ee(
953
- u / I * s.width,
954
- l / $ * s.height,
955
- F / I * s.width,
956
- R / $ * s.height
957
- );
958
- this.chars[m].texture = new M({
959
- source: s,
960
- frame: C
961
- }), u += Math.ceil(F);
962
- }
963
- }
964
- s.update(), this._currentX = u, this._currentY = l, this._currentMaxCharHeight = h, this._skipKerning && this._applyKerning(t, n);
965
- }
966
- /**
967
- * @deprecated since 8.0.0
968
- * The map of base page textures (i.e., sheets of glyphs).
969
- */
970
- get pageTextures() {
971
- return z(L, "BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."), this.pages;
972
- }
973
- _applyKerning(e, t) {
974
- const r = this._measureCache;
975
- for (let i = 0; i < e.length; i++) {
976
- const n = e[i];
977
- for (let s = 0; s < this._currentChars.length; s++) {
978
- const a = this._currentChars[s];
979
- let u = r[n];
980
- u || (u = r[n] = t.measureText(n).width);
981
- let l = r[a];
982
- l || (l = r[a] = t.measureText(a).width);
983
- let h = t.measureText(n + a).width, c = h - (u + l);
984
- c && (this.chars[n].kerning[a] = c), h = t.measureText(n + a).width, c = h - (u + l), c && (this.chars[a].kerning[n] = c);
985
- }
986
- }
987
- }
988
- _nextPage() {
989
- this._currentPageIndex++;
990
- const e = this.resolution, t = X.getOptimalCanvasAndContext(
991
- this._textureSize,
992
- this._textureSize,
993
- e
994
- );
995
- this._setupContext(t.context, this._style, e);
996
- const r = e * (this.baseRenderedFontSize / this.baseMeasurementFontSize), i = new M({
997
- source: new Mt({
998
- resource: t.canvas,
999
- resolution: r,
1000
- alphaMode: "premultiply-alpha-on-upload",
1001
- autoGenerateMipmaps: this._mipmap
1002
- })
1003
- });
1004
- this._textureStyle && (i.source.style = this._textureStyle);
1005
- const n = {
1006
- canvasAndContext: t,
1007
- texture: i
1008
- };
1009
- return this.pages[this._currentPageIndex] = n, n;
1010
- }
1011
- // canvas style!
1012
- _setupContext(e, t, r) {
1013
- t.fontSize = this.baseRenderedFontSize, e.scale(r, r), e.font = ie(t), t.fontSize = this.baseMeasurementFontSize, e.textBaseline = t.textBaseline;
1014
- const i = t._stroke, n = (i == null ? void 0 : i.width) ?? 0;
1015
- if (i && (e.lineWidth = n, e.lineJoin = i.join, e.miterLimit = i.miterLimit, e.strokeStyle = ne(i, e)), t._fill && (e.fillStyle = ne(t._fill, e)), t.dropShadow) {
1016
- const s = t.dropShadow, a = V.shared.setValue(s.color).toArray(), u = s.blur * r, l = s.distance * r;
1017
- e.shadowColor = `rgba(${a[0] * 255},${a[1] * 255},${a[2] * 255},${s.alpha})`, e.shadowBlur = u, e.shadowOffsetX = Math.cos(s.angle) * l, e.shadowOffsetY = Math.sin(s.angle) * l;
1018
- } else
1019
- e.shadowColor = "black", e.shadowBlur = 0, e.shadowOffsetX = 0, e.shadowOffsetY = 0;
1020
- }
1021
- _drawGlyph(e, t, r, i, n, s) {
1022
- const a = t.text, u = t.fontProperties, l = s._stroke, h = ((l == null ? void 0 : l.width) ?? 0) * n, c = r + h / 2, d = i - h / 2, f = u.descent * n, x = t.lineHeight * n;
1023
- let _ = !1;
1024
- s.stroke && h && (_ = !0, e.strokeText(a, c, d + x - f));
1025
- const { shadowBlur: v, shadowOffsetX: g, shadowOffsetY: b } = e;
1026
- s._fill && (_ && (e.shadowBlur = 0, e.shadowOffsetX = 0, e.shadowOffsetY = 0), e.fillText(a, c, d + x - f)), _ && (e.shadowBlur = v, e.shadowOffsetX = g, e.shadowOffsetY = b);
1027
- }
1028
- destroy() {
1029
- super.destroy();
1030
- for (let e = 0; e < this.pages.length; e++) {
1031
- const { canvasAndContext: t, texture: r } = this.pages[e];
1032
- X.returnCanvasAndContext(t), r.destroy(!0);
1033
- }
1034
- this.pages = null;
1035
- }
1036
- };
1037
- Je.defaultOptions = {
1038
- textureSize: 512,
1039
- style: new q(),
1040
- mipmap: !0
1041
- };
1042
- let Pe = Je;
1043
- function et(o, e, t, r) {
1044
- const i = {
1045
- width: 0,
1046
- height: 0,
1047
- offsetY: 0,
1048
- scale: e.fontSize / t.baseMeasurementFontSize,
1049
- lines: [{
1050
- width: 0,
1051
- charPositions: [],
1052
- spaceWidth: 0,
1053
- spacesIndex: [],
1054
- chars: []
1055
- }]
1056
- };
1057
- i.offsetY = t.baseLineOffset;
1058
- let n = i.lines[0], s = null, a = !0;
1059
- const u = {
1060
- width: 0,
1061
- start: 0,
1062
- index: 0,
1063
- // use index to not modify the array as we use it a lot!
1064
- positions: [],
1065
- chars: []
1066
- }, l = t.baseMeasurementFontSize / e.fontSize, h = e.letterSpacing * l, c = e.wordWrapWidth * l, d = e.lineHeight ? e.lineHeight * l : t.lineHeight, f = e.wordWrap && e.breakWords, x = (g) => {
1067
- const b = n.width;
1068
- for (let m = 0; m < u.index; m++) {
1069
- const T = g.positions[m];
1070
- n.chars.push(g.chars[m]), n.charPositions.push(T + b);
1071
- }
1072
- n.width += g.width, a = !1, u.width = 0, u.index = 0, u.chars.length = 0;
1073
- }, _ = () => {
1074
- let g = n.chars.length - 1;
1075
- if (r) {
1076
- let b = n.chars[g];
1077
- for (; b === " "; )
1078
- n.width -= t.chars[b].xAdvance, b = n.chars[--g];
1079
- }
1080
- i.width = Math.max(i.width, n.width), n = {
1081
- width: 0,
1082
- charPositions: [],
1083
- chars: [],
1084
- spaceWidth: 0,
1085
- spacesIndex: []
1086
- }, a = !0, i.lines.push(n), i.height += d;
1087
- }, v = (g) => g - h > c;
1088
- for (let g = 0; g < o.length + 1; g++) {
1089
- let b;
1090
- const m = g === o.length;
1091
- m || (b = o[g]);
1092
- const T = t.chars[b] || t.chars[" "];
1093
- if (/(?:\s)/.test(b) || b === "\r" || b === `
1094
- ` || m) {
1095
- if (!a && e.wordWrap && v(n.width + u.width) ? (_(), x(u), m || n.charPositions.push(0)) : (u.start = n.width, x(u), m || n.charPositions.push(0)), b === "\r" || b === `
1096
- `)
1097
- _();
1098
- else if (!m) {
1099
- const F = T.xAdvance + (T.kerning[s] || 0) + h;
1100
- n.width += F, n.spaceWidth = F, n.spacesIndex.push(n.charPositions.length), n.chars.push(b);
1101
- }
1102
- } else {
1103
- const w = T.kerning[s] || 0, F = T.xAdvance + w + h;
1104
- f && v(n.width + u.width + F) && (x(u), _()), u.positions[u.index++] = u.width + w, u.chars.push(b), u.width += F;
1105
- }
1106
- s = b;
1107
- }
1108
- return _(), e.align === "center" ? $t(i) : e.align === "right" ? Nt(i) : e.align === "justify" && Kt(i), i;
1109
- }
1110
- function $t(o) {
1111
- for (let e = 0; e < o.lines.length; e++) {
1112
- const t = o.lines[e], r = o.width / 2 - t.width / 2;
1113
- for (let i = 0; i < t.charPositions.length; i++)
1114
- t.charPositions[i] += r;
1115
- }
1116
- }
1117
- function Nt(o) {
1118
- for (let e = 0; e < o.lines.length; e++) {
1119
- const t = o.lines[e], r = o.width - t.width;
1120
- for (let i = 0; i < t.charPositions.length; i++)
1121
- t.charPositions[i] += r;
1122
- }
1123
- }
1124
- function Kt(o) {
1125
- const e = o.width;
1126
- for (let t = 0; t < o.lines.length; t++) {
1127
- const r = o.lines[t];
1128
- let i = 0, n = r.spacesIndex[i++], s = 0;
1129
- const a = r.spacesIndex.length, l = (e - r.width) / a;
1130
- for (let h = 0; h < r.charPositions.length; h++)
1131
- h === n && (n = r.spacesIndex[i++], s += l), r.charPositions[h] += s;
1132
- }
1133
- }
1134
- function jt(o) {
1135
- if (o === "")
1136
- return [];
1137
- typeof o == "string" && (o = [o]);
1138
- const e = [];
1139
- for (let t = 0, r = o.length; t < r; t++) {
1140
- const i = o[t];
1141
- if (Array.isArray(i)) {
1142
- if (i.length !== 2)
1143
- throw new Error(`[BitmapFont]: Invalid character range length, expecting 2 got ${i.length}.`);
1144
- if (i[0].length === 0 || i[1].length === 0)
1145
- throw new Error("[BitmapFont]: Invalid character delimiter.");
1146
- const n = i[0].charCodeAt(0), s = i[1].charCodeAt(0);
1147
- if (s < n)
1148
- throw new Error("[BitmapFont]: Invalid character range.");
1149
- for (let a = n, u = s; a <= u; a++)
1150
- e.push(String.fromCharCode(a));
1151
- } else
1152
- e.push(...Array.from(i));
1153
- }
1154
- if (e.length === 0)
1155
- throw new Error("[BitmapFont]: Empty set when resolving characters.");
1156
- return e;
1157
- }
1158
- let J = 0;
1159
- class qt {
1160
- constructor() {
1161
- this.ALPHA = [["a", "z"], ["A", "Z"], " "], this.NUMERIC = [["0", "9"]], this.ALPHANUMERIC = [["a", "z"], ["A", "Z"], ["0", "9"], " "], this.ASCII = [[" ", "~"]], this.defaultOptions = {
1162
- chars: this.ALPHANUMERIC,
1163
- resolution: 1,
1164
- padding: 4,
1165
- skipKerning: !1,
1166
- textureStyle: null
1167
- }, this.measureCache = Qe(1e3);
1168
- }
1169
- /**
1170
- * Get a font for the specified text and style.
1171
- * @param text - The text to get the font for
1172
- * @param style - The style to use
1173
- */
1174
- getFont(e, t) {
1175
- var s;
1176
- let r = `${t.fontFamily}-bitmap`, i = !0;
1177
- if (t._fill.fill && !t._stroke ? (r += t._fill.fill.styleKey, i = !1) : (t._stroke || t.dropShadow) && (r = `${t.styleKey}-bitmap`, i = !1), !G.has(r)) {
1178
- const a = Object.create(t);
1179
- a.lineHeight = 0;
1180
- const u = new Pe({
1181
- style: a,
1182
- overrideFill: i,
1183
- overrideSize: !0,
1184
- ...this.defaultOptions
1185
- });
1186
- J++, J > 50 && K("BitmapText", `You have dynamically created ${J} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``), u.once("destroy", () => {
1187
- J--, G.remove(r);
1188
- }), G.set(
1189
- r,
1190
- u
1191
- );
1192
- }
1193
- const n = G.get(r);
1194
- return (s = n.ensureCharacters) == null || s.call(n, e), n;
1195
- }
1196
- /**
1197
- * Get the layout of a text for the specified style.
1198
- * @param text - The text to get the layout for
1199
- * @param style - The style to use
1200
- * @param trimEnd - Whether to ignore whitespaces at the end of each line
1201
- */
1202
- getLayout(e, t, r = !0) {
1203
- const i = this.getFont(e, t), n = `${e}-${t.styleKey}-${r}`;
1204
- if (this.measureCache.has(n))
1205
- return this.measureCache.get(n);
1206
- const s = O.graphemeSegmenter(e), a = et(s, t, i, r);
1207
- return this.measureCache.set(n, a), a;
1208
- }
1209
- /**
1210
- * Measure the text using the specified style.
1211
- * @param text - The text to measure
1212
- * @param style - The style to use
1213
- * @param trimEnd - Whether to ignore whitespaces at the end of each line
1214
- */
1215
- measureText(e, t, r = !0) {
1216
- return this.getLayout(e, t, r);
1217
- }
1218
- // eslint-disable-next-line max-len
1219
- install(...e) {
1220
- var l, h, c, d;
1221
- let t = e[0];
1222
- typeof t == "string" && (t = {
1223
- name: t,
1224
- style: e[1],
1225
- chars: (l = e[2]) == null ? void 0 : l.chars,
1226
- resolution: (h = e[2]) == null ? void 0 : h.resolution,
1227
- padding: (c = e[2]) == null ? void 0 : c.padding,
1228
- skipKerning: (d = e[2]) == null ? void 0 : d.skipKerning
1229
- }, z(L, "BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));
1230
- const r = t == null ? void 0 : t.name;
1231
- if (!r)
1232
- throw new Error("[BitmapFontManager] Property `name` is required.");
1233
- t = { ...this.defaultOptions, ...t };
1234
- const i = t.style, n = i instanceof q ? i : new q(i), s = t.dynamicFill ?? this._canUseTintForStyle(n), a = new Pe({
1235
- style: n,
1236
- overrideFill: s,
1237
- skipKerning: t.skipKerning,
1238
- padding: t.padding,
1239
- resolution: t.resolution,
1240
- overrideSize: !1,
1241
- textureStyle: t.textureStyle
1242
- }), u = jt(t.chars);
1243
- return a.ensureCharacters(u.join("")), G.set(`${r}-bitmap`, a), a.once("destroy", () => G.remove(`${r}-bitmap`)), a;
1244
- }
1245
- /**
1246
- * Uninstalls a bitmap font from the cache.
1247
- * @param {string} name - The name of the bitmap font to uninstall.
1248
- */
1249
- uninstall(e) {
1250
- const t = `${e}-bitmap`, r = G.get(t);
1251
- r && r.destroy();
1252
- }
1253
- /**
1254
- * Determines if a style can use tinting instead of baking colors into the bitmap.
1255
- * Tinting is more efficient as it allows reusing the same bitmap with different colors.
1256
- * @param style - The text style to evaluate
1257
- * @returns true if the style can use tinting, false if colors must be baked in
1258
- * @private
1259
- */
1260
- _canUseTintForStyle(e) {
1261
- return !e._stroke && (!e.dropShadow || e.dropShadow.color === 0) && !e._fill.fill && e._fill.color === 16777215;
1262
- }
1263
- }
1264
- const Qt = new qt();
1265
- var Jt = `in vec2 aPosition;
1266
- out vec2 vTextureCoord;
1267
-
1268
- uniform vec4 uInputSize;
1269
- uniform vec4 uOutputFrame;
1270
- uniform vec4 uOutputTexture;
1271
-
1272
- vec4 filterVertexPosition( void )
1273
- {
1274
- vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
1275
-
1276
- position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
1277
- position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
1278
-
1279
- return vec4(position, 0.0, 1.0);
1280
- }
1281
-
1282
- vec2 filterTextureCoord( void )
1283
- {
1284
- return aPosition * (uOutputFrame.zw * uInputSize.zw);
1285
- }
1286
-
1287
- void main(void)
1288
- {
1289
- gl_Position = filterVertexPosition();
1290
- vTextureCoord = filterTextureCoord();
1291
- }
1292
- `, Zt = `in vec2 vTextureCoord;
1293
- out vec4 finalColor;
1294
- uniform sampler2D uTexture;
1295
- void main() {
1296
- finalColor = texture(uTexture, vTextureCoord);
1297
- }
1298
- `, Fe = `struct GlobalFilterUniforms {
1299
- uInputSize: vec4<f32>,
1300
- uInputPixel: vec4<f32>,
1301
- uInputClamp: vec4<f32>,
1302
- uOutputFrame: vec4<f32>,
1303
- uGlobalFrame: vec4<f32>,
1304
- uOutputTexture: vec4<f32>,
1305
- };
1306
-
1307
- @group(0) @binding(0) var <uniform> gfu: GlobalFilterUniforms;
1308
- @group(0) @binding(1) var uTexture: texture_2d<f32>;
1309
- @group(0) @binding(2) var uSampler: sampler;
1310
-
1311
- struct VSOutput {
1312
- @builtin(position) position: vec4<f32>,
1313
- @location(0) uv: vec2<f32>
1314
- };
1315
-
1316
- fn filterVertexPosition(aPosition: vec2<f32>) -> vec4<f32>
1317
- {
1318
- var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
1319
-
1320
- position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
1321
- position.y = position.y * (2.0 * gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
1322
-
1323
- return vec4(position, 0.0, 1.0);
1324
- }
1325
-
1326
- fn filterTextureCoord(aPosition: vec2<f32>) -> vec2<f32>
1327
- {
1328
- return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
1329
- }
1330
-
1331
- @vertex
1332
- fn mainVertex(
1333
- @location(0) aPosition: vec2<f32>,
1334
- ) -> VSOutput {
1335
- return VSOutput(
1336
- filterVertexPosition(aPosition),
1337
- filterTextureCoord(aPosition)
1338
- );
1339
- }
1340
-
1341
- @fragment
1342
- fn mainFragment(
1343
- @location(0) uv: vec2<f32>,
1344
- ) -> @location(0) vec4<f32> {
1345
- return textureSample(uTexture, uSampler, uv);
1346
- }
1347
- `;
1348
- class er extends Ut {
1349
- constructor() {
1350
- const e = Le.from({
1351
- vertex: { source: Fe, entryPoint: "mainVertex" },
1352
- fragment: { source: Fe, entryPoint: "mainFragment" },
1353
- name: "passthrough-filter"
1354
- }), t = Ee.from({
1355
- vertex: Jt,
1356
- fragment: Zt,
1357
- name: "passthrough-filter"
1358
- });
1359
- super({
1360
- gpuProgram: e,
1361
- glProgram: t
1362
- });
1363
- }
1364
- }
1365
- class tt {
1366
- constructor(e) {
1367
- this._renderer = e;
1368
- }
1369
- push(e, t, r) {
1370
- this._renderer.renderPipes.batch.break(r), r.add({
1371
- renderPipeId: "filter",
1372
- canBundle: !1,
1373
- action: "pushFilter",
1374
- container: t,
1375
- filterEffect: e
1376
- });
1377
- }
1378
- pop(e, t, r) {
1379
- this._renderer.renderPipes.batch.break(r), r.add({
1380
- renderPipeId: "filter",
1381
- action: "popFilter",
1382
- canBundle: !1
1383
- });
1384
- }
1385
- execute(e) {
1386
- e.action === "pushFilter" ? this._renderer.filter.push(e) : e.action === "popFilter" && this._renderer.filter.pop();
1387
- }
1388
- destroy() {
1389
- this._renderer = null;
1390
- }
1391
- }
1392
- tt.extension = {
1393
- type: [
1394
- y.WebGLPipes,
1395
- y.WebGPUPipes,
1396
- y.CanvasPipes
1397
- ],
1398
- name: "filter"
1399
- };
1400
- const Be = new U();
1401
- function tr(o, e) {
1402
- e.clear();
1403
- const t = e.matrix;
1404
- for (let r = 0; r < o.length; r++) {
1405
- const i = o[r];
1406
- if (i.globalDisplayStatus < 7)
1407
- continue;
1408
- const n = i.renderGroup ?? i.parentRenderGroup;
1409
- n != null && n.isCachedAsTexture ? e.matrix = Be.copyFrom(n.textureOffsetInverseTransform).append(i.worldTransform) : n != null && n._parentCacheAsTextureRenderGroup ? e.matrix = Be.copyFrom(n._parentCacheAsTextureRenderGroup.inverseWorldTransform).append(i.groupTransform) : e.matrix = i.worldTransform, e.addBounds(i.bounds);
1410
- }
1411
- return e.matrix = t, e;
1412
- }
1413
- const rr = new me({
1414
- attributes: {
1415
- aPosition: {
1416
- buffer: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
1417
- format: "float32x2",
1418
- stride: 8,
1419
- offset: 0
1420
- }
1421
- },
1422
- indexBuffer: new Uint32Array([0, 1, 2, 0, 2, 3])
1423
- });
1424
- class ir {
1425
- constructor() {
1426
- this.skip = !1, this.inputTexture = null, this.backTexture = null, this.filters = null, this.bounds = new Ve(), this.container = null, this.blendRequired = !1, this.outputRenderSurface = null, this.globalFrame = { x: 0, y: 0, width: 0, height: 0 }, this.firstEnabledIndex = -1, this.lastEnabledIndex = -1;
1427
- }
1428
- }
1429
- class rt {
1430
- constructor(e) {
1431
- this._filterStackIndex = 0, this._filterStack = [], this._filterGlobalUniforms = new Y({
1432
- uInputSize: { value: new Float32Array(4), type: "vec4<f32>" },
1433
- uInputPixel: { value: new Float32Array(4), type: "vec4<f32>" },
1434
- uInputClamp: { value: new Float32Array(4), type: "vec4<f32>" },
1435
- uOutputFrame: { value: new Float32Array(4), type: "vec4<f32>" },
1436
- uGlobalFrame: { value: new Float32Array(4), type: "vec4<f32>" },
1437
- uOutputTexture: { value: new Float32Array(4), type: "vec4<f32>" }
1438
- }), this._globalFilterBindGroup = new He({}), this.renderer = e;
1439
- }
1440
- /**
1441
- * The back texture of the currently active filter. Requires the filter to have `blendRequired` set to true.
1442
- * @readonly
1443
- */
1444
- get activeBackTexture() {
1445
- var e;
1446
- return (e = this._activeFilterData) == null ? void 0 : e.backTexture;
1447
- }
1448
- /**
1449
- * Pushes a filter instruction onto the filter stack.
1450
- * @param instruction - The instruction containing the filter effect and container.
1451
- * @internal
1452
- */
1453
- push(e) {
1454
- const t = this.renderer, r = e.filterEffect.filters, i = this._pushFilterData();
1455
- i.skip = !1, i.filters = r, i.container = e.container, i.outputRenderSurface = t.renderTarget.renderSurface;
1456
- const n = t.renderTarget.renderTarget.colorTexture.source, s = n.resolution, a = n.antialias;
1457
- if (r.every((f) => !f.enabled)) {
1458
- i.skip = !0;
1459
- return;
1460
- }
1461
- const u = i.bounds;
1462
- if (this._calculateFilterArea(e, u), this._calculateFilterBounds(i, t.renderTarget.rootViewPort, a, s, 1), i.skip)
1463
- return;
1464
- const l = this._getPreviousFilterData(), h = this._findFilterResolution(s);
1465
- let c = 0, d = 0;
1466
- l && (c = l.bounds.minX, d = l.bounds.minY), this._calculateGlobalFrame(
1467
- i,
1468
- c,
1469
- d,
1470
- h,
1471
- n.width,
1472
- n.height
1473
- ), this._setupFilterTextures(i, u, t, l);
1474
- }
1475
- /**
1476
- * Applies filters to a texture.
1477
- *
1478
- * This method takes a texture and a list of filters, applies the filters to the texture,
1479
- * and returns the resulting texture.
1480
- * @param {object} params - The parameters for applying filters.
1481
- * @param {Texture} params.texture - The texture to apply filters to.
1482
- * @param {Filter[]} params.filters - The filters to apply.
1483
- * @returns {Texture} The resulting texture after all filters have been applied.
1484
- * @example
1485
- *
1486
- * ```ts
1487
- * // Create a texture and a list of filters
1488
- * const texture = new Texture(...);
1489
- * const filters = [new BlurFilter(), new ColorMatrixFilter()];
1490
- *
1491
- * // Apply the filters to the texture
1492
- * const resultTexture = filterSystem.applyToTexture({ texture, filters });
1493
- *
1494
- * // Use the resulting texture
1495
- * sprite.texture = resultTexture;
1496
- * ```
1497
- *
1498
- * Key Points:
1499
- * 1. padding is not currently supported here - so clipping may occur with filters that use padding.
1500
- * 2. If all filters are disabled or skipped, the original texture is returned.
1501
- */
1502
- generateFilteredTexture({ texture: e, filters: t }) {
1503
- const r = this._pushFilterData();
1504
- this._activeFilterData = r, r.skip = !1, r.filters = t;
1505
- const i = e.source, n = i.resolution, s = i.antialias;
1506
- if (t.every((f) => !f.enabled))
1507
- return r.skip = !0, e;
1508
- const a = r.bounds;
1509
- if (a.addRect(e.frame), this._calculateFilterBounds(r, a.rectangle, s, n, 0), r.skip)
1510
- return e;
1511
- const u = n;
1512
- this._calculateGlobalFrame(
1513
- r,
1514
- 0,
1515
- 0,
1516
- u,
1517
- i.width,
1518
- i.height
1519
- ), r.outputRenderSurface = A.getOptimalTexture(
1520
- a.width,
1521
- a.height,
1522
- r.resolution,
1523
- r.antialias
1524
- ), r.backTexture = M.EMPTY, r.inputTexture = e, this.renderer.renderTarget.finishRenderPass(), this._applyFiltersToTexture(r, !0);
1525
- const d = r.outputRenderSurface;
1526
- return d.source.alphaMode = "premultiplied-alpha", d;
1527
- }
1528
- /** @internal */
1529
- pop() {
1530
- const e = this.renderer, t = this._popFilterData();
1531
- t.skip || (e.globalUniforms.pop(), e.renderTarget.finishRenderPass(), this._activeFilterData = t, this._applyFiltersToTexture(t, !1), t.blendRequired && A.returnTexture(t.backTexture), A.returnTexture(t.inputTexture));
1532
- }
1533
- /**
1534
- * Copies the last render surface to a texture.
1535
- * @param lastRenderSurface - The last render surface to copy from.
1536
- * @param bounds - The bounds of the area to copy.
1537
- * @param previousBounds - The previous bounds to use for offsetting the copy.
1538
- */
1539
- getBackTexture(e, t, r) {
1540
- const i = e.colorTexture.source._resolution, n = A.getOptimalTexture(
1541
- t.width,
1542
- t.height,
1543
- i,
1544
- !1
1545
- );
1546
- let s = t.minX, a = t.minY;
1547
- r && (s -= r.minX, a -= r.minY), s = Math.floor(s * i), a = Math.floor(a * i);
1548
- const u = Math.ceil(t.width * i), l = Math.ceil(t.height * i);
1549
- return this.renderer.renderTarget.copyToTexture(
1550
- e,
1551
- n,
1552
- { x: s, y: a },
1553
- { width: u, height: l },
1554
- { x: 0, y: 0 }
1555
- ), n;
1556
- }
1557
- /**
1558
- * Applies a filter to a texture.
1559
- * @param filter - The filter to apply.
1560
- * @param input - The input texture.
1561
- * @param output - The output render surface.
1562
- * @param clear - Whether to clear the output surface before applying the filter.
1563
- */
1564
- applyFilter(e, t, r, i) {
1565
- const n = this.renderer, s = this._activeFilterData, u = s.outputRenderSurface === r, l = n.renderTarget.rootRenderTarget.colorTexture.source._resolution, h = this._findFilterResolution(l);
1566
- let c = 0, d = 0;
1567
- if (u) {
1568
- const x = this._findPreviousFilterOffset();
1569
- c = x.x, d = x.y;
1570
- }
1571
- this._updateFilterUniforms(t, r, s, c, d, h, u, i);
1572
- const f = e.enabled ? e : this._getPassthroughFilter();
1573
- this._setupBindGroupsAndRender(f, t, n);
1574
- }
1575
- /**
1576
- * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
1577
- *
1578
- * Use `outputMatrix * vTextureCoord` in the shader.
1579
- * @param outputMatrix - The matrix to output to.
1580
- * @param {Sprite} sprite - The sprite to map to.
1581
- * @returns The mapped matrix.
1582
- */
1583
- calculateSpriteMatrix(e, t) {
1584
- const r = this._activeFilterData, i = e.set(
1585
- r.inputTexture._source.width,
1586
- 0,
1587
- 0,
1588
- r.inputTexture._source.height,
1589
- r.bounds.minX,
1590
- r.bounds.minY
1591
- ), n = t.worldTransform.copyTo(U.shared), s = t.renderGroup || t.parentRenderGroup;
1592
- return s && s.cacheToLocalTransform && n.prepend(s.cacheToLocalTransform), n.invert(), i.prepend(n), i.scale(
1593
- 1 / t.texture.orig.width,
1594
- 1 / t.texture.orig.height
1595
- ), i.translate(t.anchor.x, t.anchor.y), i;
1596
- }
1597
- destroy() {
1598
- var e;
1599
- (e = this._passthroughFilter) == null || e.destroy(!0), this._passthroughFilter = null;
1600
- }
1601
- _getPassthroughFilter() {
1602
- return this._passthroughFilter ?? (this._passthroughFilter = new er()), this._passthroughFilter;
1603
- }
1604
- /**
1605
- * Sets up the bind groups and renders the filter.
1606
- * @param filter - The filter to apply
1607
- * @param input - The input texture
1608
- * @param renderer - The renderer instance
1609
- */
1610
- _setupBindGroupsAndRender(e, t, r) {
1611
- if (r.renderPipes.uniformBatch) {
1612
- const i = r.renderPipes.uniformBatch.getUboResource(this._filterGlobalUniforms);
1613
- this._globalFilterBindGroup.setResource(i, 0);
1614
- } else
1615
- this._globalFilterBindGroup.setResource(this._filterGlobalUniforms, 0);
1616
- this._globalFilterBindGroup.setResource(t.source, 1), this._globalFilterBindGroup.setResource(t.source.style, 2), e.groups[0] = this._globalFilterBindGroup, r.encoder.draw({
1617
- geometry: rr,
1618
- shader: e,
1619
- state: e._state,
1620
- topology: "triangle-list"
1621
- }), r.type === xe.WEBGL && r.renderTarget.finishRenderPass();
1622
- }
1623
- /**
1624
- * Sets up the filter textures including input texture and back texture if needed.
1625
- * @param filterData - The filter data to update
1626
- * @param bounds - The bounds for the texture
1627
- * @param renderer - The renderer instance
1628
- * @param previousFilterData - The previous filter data for back texture calculation
1629
- */
1630
- _setupFilterTextures(e, t, r, i) {
1631
- if (e.backTexture = M.EMPTY, e.inputTexture = A.getOptimalTexture(
1632
- t.width,
1633
- t.height,
1634
- e.resolution,
1635
- e.antialias
1636
- ), e.blendRequired) {
1637
- r.renderTarget.finishRenderPass();
1638
- const n = r.renderTarget.getRenderTarget(e.outputRenderSurface);
1639
- e.backTexture = this.getBackTexture(n, t, i == null ? void 0 : i.bounds);
1640
- }
1641
- r.renderTarget.bind(e.inputTexture, !0), r.globalUniforms.push({
1642
- offset: t
1643
- });
1644
- }
1645
- /**
1646
- * Calculates and sets the global frame for the filter.
1647
- * @param filterData - The filter data to update
1648
- * @param offsetX - The X offset
1649
- * @param offsetY - The Y offset
1650
- * @param globalResolution - The global resolution
1651
- * @param sourceWidth - The source texture width
1652
- * @param sourceHeight - The source texture height
1653
- */
1654
- _calculateGlobalFrame(e, t, r, i, n, s) {
1655
- const a = e.globalFrame;
1656
- a.x = t * i, a.y = r * i, a.width = n * i, a.height = s * i;
1657
- }
1658
- /**
1659
- * Updates the filter uniforms with the current filter state.
1660
- * @param input - The input texture
1661
- * @param output - The output render surface
1662
- * @param filterData - The current filter data
1663
- * @param offsetX - The X offset for positioning
1664
- * @param offsetY - The Y offset for positioning
1665
- * @param resolution - The current resolution
1666
- * @param isFinalTarget - Whether this is the final render target
1667
- * @param clear - Whether to clear the output surface
1668
- */
1669
- _updateFilterUniforms(e, t, r, i, n, s, a, u) {
1670
- const l = this._filterGlobalUniforms.uniforms, h = l.uOutputFrame, c = l.uInputSize, d = l.uInputPixel, f = l.uInputClamp, x = l.uGlobalFrame, _ = l.uOutputTexture;
1671
- a ? (h[0] = r.bounds.minX - i, h[1] = r.bounds.minY - n) : (h[0] = 0, h[1] = 0), h[2] = e.frame.width, h[3] = e.frame.height, c[0] = e.source.width, c[1] = e.source.height, c[2] = 1 / c[0], c[3] = 1 / c[1], d[0] = e.source.pixelWidth, d[1] = e.source.pixelHeight, d[2] = 1 / d[0], d[3] = 1 / d[1], f[0] = 0.5 * d[2], f[1] = 0.5 * d[3], f[2] = e.frame.width * c[2] - 0.5 * d[2], f[3] = e.frame.height * c[3] - 0.5 * d[3];
1672
- const v = this.renderer.renderTarget.rootRenderTarget.colorTexture;
1673
- x[0] = i * s, x[1] = n * s, x[2] = v.source.width * s, x[3] = v.source.height * s, t instanceof M && (t.source.resource = null);
1674
- const g = this.renderer.renderTarget.getRenderTarget(t);
1675
- this.renderer.renderTarget.bind(t, !!u), t instanceof M ? (_[0] = t.frame.width, _[1] = t.frame.height) : (_[0] = g.width, _[1] = g.height), _[2] = g.isRoot ? -1 : 1, this._filterGlobalUniforms.update();
1676
- }
1677
- /**
1678
- * Finds the correct resolution by looking back through the filter stack.
1679
- * @param rootResolution - The fallback root resolution to use
1680
- * @returns The resolution from the previous filter or root resolution
1681
- */
1682
- _findFilterResolution(e) {
1683
- let t = this._filterStackIndex - 1;
1684
- for (; t > 0 && this._filterStack[t].skip; )
1685
- --t;
1686
- return t > 0 && this._filterStack[t].inputTexture ? this._filterStack[t].inputTexture.source._resolution : e;
1687
- }
1688
- /**
1689
- * Finds the offset from the previous non-skipped filter in the stack.
1690
- * @returns The offset coordinates from the previous filter
1691
- */
1692
- _findPreviousFilterOffset() {
1693
- let e = 0, t = 0, r = this._filterStackIndex;
1694
- for (; r > 0; ) {
1695
- r--;
1696
- const i = this._filterStack[r];
1697
- if (!i.skip) {
1698
- e = i.bounds.minX, t = i.bounds.minY;
1699
- break;
1700
- }
1701
- }
1702
- return { x: e, y: t };
1703
- }
1704
- /**
1705
- * Calculates the filter area bounds based on the instruction type.
1706
- * @param instruction - The filter instruction
1707
- * @param bounds - The bounds object to populate
1708
- */
1709
- _calculateFilterArea(e, t) {
1710
- if (e.renderables ? tr(e.renderables, t) : e.filterEffect.filterArea ? (t.clear(), t.addRect(e.filterEffect.filterArea), t.applyMatrix(e.container.worldTransform)) : e.container.getFastGlobalBounds(!0, t), e.container) {
1711
- const i = (e.container.renderGroup || e.container.parentRenderGroup).cacheToLocalTransform;
1712
- i && t.applyMatrix(i);
1713
- }
1714
- }
1715
- _applyFiltersToTexture(e, t) {
1716
- const r = e.inputTexture, i = e.bounds, n = e.filters, s = e.firstEnabledIndex, a = e.lastEnabledIndex;
1717
- if (this._globalFilterBindGroup.setResource(r.source.style, 2), this._globalFilterBindGroup.setResource(e.backTexture.source, 3), s === a)
1718
- n[s].apply(this, r, e.outputRenderSurface, t);
1719
- else {
1720
- let u = e.inputTexture;
1721
- const l = A.getOptimalTexture(
1722
- i.width,
1723
- i.height,
1724
- u.source._resolution,
1725
- !1
1726
- );
1727
- let h = l;
1728
- for (let c = s; c < a; c++) {
1729
- const d = n[c];
1730
- if (!d.enabled)
1731
- continue;
1732
- d.apply(this, u, h, !0);
1733
- const f = u;
1734
- u = h, h = f;
1735
- }
1736
- n[a].apply(this, u, e.outputRenderSurface, t), A.returnTexture(l);
1737
- }
1738
- }
1739
- _calculateFilterBounds(e, t, r, i, n) {
1740
- var g;
1741
- const s = this.renderer, a = e.bounds, u = e.filters;
1742
- let l = 1 / 0, h = 0, c = !0, d = !1, f = !1, x = !0, _ = -1, v = -1;
1743
- for (let b = 0; b < u.length; b++) {
1744
- const m = u[b];
1745
- if (!m.enabled)
1746
- continue;
1747
- if (_ === -1 && (_ = b), v = b, l = Math.min(l, m.resolution === "inherit" ? i : m.resolution), h += m.padding, m.antialias === "off" ? c = !1 : m.antialias === "inherit" && c && (c = r), m.clipToViewport || (x = !1), !!!(m.compatibleRenderers & s.type)) {
1748
- f = !1;
1749
- break;
1750
- }
1751
- if (m.blendRequired && !(((g = s.backBuffer) == null ? void 0 : g.useBackBuffer) ?? !0)) {
1752
- K("Blend filter requires backBuffer on WebGL renderer to be enabled. Set `useBackBuffer: true` in the renderer options."), f = !1;
1753
- break;
1754
- }
1755
- f = !0, d || (d = m.blendRequired);
1756
- }
1757
- if (!f) {
1758
- e.skip = !0;
1759
- return;
1760
- }
1761
- if (x && a.fitBounds(0, t.width / i, 0, t.height / i), a.scale(l).ceil().scale(1 / l).pad((h | 0) * n), !a.isPositive) {
1762
- e.skip = !0;
1763
- return;
1764
- }
1765
- e.antialias = c, e.resolution = l, e.blendRequired = d, e.firstEnabledIndex = _, e.lastEnabledIndex = v;
1766
- }
1767
- _popFilterData() {
1768
- return this._filterStackIndex--, this._filterStack[this._filterStackIndex];
1769
- }
1770
- _getPreviousFilterData() {
1771
- let e, t = this._filterStackIndex - 1;
1772
- for (; t > 0 && (t--, e = this._filterStack[t], !!e.skip); )
1773
- ;
1774
- return e;
1775
- }
1776
- _pushFilterData() {
1777
- let e = this._filterStack[this._filterStackIndex];
1778
- return e || (e = this._filterStack[this._filterStackIndex] = new ir()), this._filterStackIndex++, e;
1779
- }
1780
- }
1781
- rt.extension = {
1782
- type: [
1783
- y.WebGLSystem,
1784
- y.WebGPUSystem
1785
- ],
1786
- name: "filter"
1787
- };
1788
- const it = class nt extends me {
1789
- constructor(...e) {
1790
- let t = e[0] ?? {};
1791
- t instanceof Float32Array && (z(L, "use new MeshGeometry({ positions, uvs, indices }) instead"), t = {
1792
- positions: t,
1793
- uvs: e[1],
1794
- indices: e[2]
1795
- }), t = { ...nt.defaultOptions, ...t };
1796
- const r = t.positions || new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
1797
- let i = t.uvs;
1798
- i || (t.positions ? i = new Float32Array(r.length) : i = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]));
1799
- const n = t.indices || new Uint32Array([0, 1, 2, 0, 2, 3]), s = t.shrinkBuffersToFit, a = new N({
1800
- data: r,
1801
- label: "attribute-mesh-positions",
1802
- shrinkToFit: s,
1803
- usage: D.VERTEX | D.COPY_DST
1804
- }), u = new N({
1805
- data: i,
1806
- label: "attribute-mesh-uvs",
1807
- shrinkToFit: s,
1808
- usage: D.VERTEX | D.COPY_DST
1809
- }), l = new N({
1810
- data: n,
1811
- label: "index-mesh-buffer",
1812
- shrinkToFit: s,
1813
- usage: D.INDEX | D.COPY_DST
1814
- });
1815
- super({
1816
- attributes: {
1817
- aPosition: {
1818
- buffer: a,
1819
- format: "float32x2",
1820
- stride: 8,
1821
- offset: 0
1822
- },
1823
- aUV: {
1824
- buffer: u,
1825
- format: "float32x2",
1826
- stride: 8,
1827
- offset: 0
1828
- }
1829
- },
1830
- indexBuffer: l,
1831
- topology: t.topology
1832
- }), this.batchMode = "auto";
1833
- }
1834
- /** The positions of the mesh. */
1835
- get positions() {
1836
- return this.attributes.aPosition.buffer.data;
1837
- }
1838
- /**
1839
- * Set the positions of the mesh.
1840
- * When setting the positions, its important that the uvs array is at least as long as the positions array.
1841
- * otherwise the geometry will not be valid.
1842
- * @param {Float32Array} value - The positions of the mesh.
1843
- */
1844
- set positions(e) {
1845
- this.attributes.aPosition.buffer.data = e;
1846
- }
1847
- /** The UVs of the mesh. */
1848
- get uvs() {
1849
- return this.attributes.aUV.buffer.data;
1850
- }
1851
- /**
1852
- * Set the UVs of the mesh.
1853
- * Its important that the uvs array you set is at least as long as the positions array.
1854
- * otherwise the geometry will not be valid.
1855
- * @param {Float32Array} value - The UVs of the mesh.
1856
- */
1857
- set uvs(e) {
1858
- this.attributes.aUV.buffer.data = e;
1859
- }
1860
- /** The indices of the mesh. */
1861
- get indices() {
1862
- return this.indexBuffer.data;
1863
- }
1864
- set indices(e) {
1865
- this.indexBuffer.data = e;
1866
- }
1867
- };
1868
- it.defaultOptions = {
1869
- topology: "triangle-list",
1870
- shrinkBuffersToFit: !1
1871
- };
1872
- let be = it, E = null, W = null;
1873
- function nr(o, e) {
1874
- E || (E = H.get().createCanvas(256, 128), W = E.getContext("2d", { willReadFrequently: !0 }), W.globalCompositeOperation = "copy", W.globalAlpha = 1), (E.width < o || E.height < e) && (E.width = Se(o), E.height = Se(e));
1875
- }
1876
- function Re(o, e, t) {
1877
- for (let r = 0, i = 4 * t * e; r < e; ++r, i += 4)
1878
- if (o[i + 3] !== 0)
1879
- return !1;
1880
- return !0;
1881
- }
1882
- function Me(o, e, t, r, i) {
1883
- const n = 4 * e;
1884
- for (let s = r, a = r * n + 4 * t; s <= i; ++s, a += n)
1885
- if (o[a + 3] !== 0)
1886
- return !1;
1887
- return !0;
1888
- }
1889
- function sr(...o) {
1890
- let e = o[0];
1891
- e.canvas || (e = { canvas: o[0], resolution: o[1] });
1892
- const { canvas: t } = e, r = Math.min(e.resolution ?? 1, 1), i = e.width ?? t.width, n = e.height ?? t.height;
1893
- let s = e.output;
1894
- if (nr(i, n), !W)
1895
- throw new TypeError("Failed to get canvas 2D context");
1896
- W.drawImage(
1897
- t,
1898
- 0,
1899
- 0,
1900
- i,
1901
- n,
1902
- 0,
1903
- 0,
1904
- i * r,
1905
- n * r
1906
- );
1907
- const u = W.getImageData(0, 0, i, n).data;
1908
- let l = 0, h = 0, c = i - 1, d = n - 1;
1909
- for (; h < n && Re(u, i, h); )
1910
- ++h;
1911
- if (h === n)
1912
- return ee.EMPTY;
1913
- for (; Re(u, i, d); )
1914
- --d;
1915
- for (; Me(u, i, l, h, d); )
1916
- ++l;
1917
- for (; Me(u, i, c, h, d); )
1918
- --c;
1919
- return ++c, ++d, W.globalCompositeOperation = "source-over", W.strokeRect(l, h, c - l, d - h), W.globalCompositeOperation = "copy", s ?? (s = new ee()), s.set(l / r, h / r, (c - l) / r, (d - h) / r), s;
1920
- }
1921
- const Ue = new ee();
1922
- class ar {
1923
- /**
1924
- * Creates a canvas with the specified text rendered to it.
1925
- *
1926
- * Generates a canvas of appropriate size, renders the text with the provided style,
1927
- * and returns both the canvas/context and a Rectangle representing the text bounds.
1928
- *
1929
- * When trim is enabled in the style, the frame will represent the bounds of the
1930
- * non-transparent pixels, which can be smaller than the full canvas.
1931
- * @param options - The options for generating the text canvas
1932
- * @param options.text - The text to render
1933
- * @param options.style - The style to apply to the text
1934
- * @param options.resolution - The resolution of the canvas (defaults to 1)
1935
- * @param options.padding
1936
- * @returns An object containing the canvas/context and the frame (bounds) of the text
1937
- */
1938
- getCanvasAndContext(e) {
1939
- const { text: t, style: r, resolution: i = 1 } = e, n = r._getFinalPadding(), s = O.measureText(t || " ", r), a = Math.ceil(Math.ceil(Math.max(1, s.width) + n * 2) * i), u = Math.ceil(Math.ceil(Math.max(1, s.height) + n * 2) * i), l = X.getOptimalCanvasAndContext(a, u);
1940
- this._renderTextToCanvas(t, r, n, i, l);
1941
- const h = r.trim ? sr({ canvas: l.canvas, width: a, height: u, resolution: 1, output: Ue }) : Ue.set(0, 0, a, u);
1942
- return {
1943
- canvasAndContext: l,
1944
- frame: h
1945
- };
1946
- }
1947
- /**
1948
- * Returns a canvas and context to the pool.
1949
- *
1950
- * This should be called when you're done with the canvas to allow reuse
1951
- * and prevent memory leaks.
1952
- * @param canvasAndContext - The canvas and context to return to the pool
1953
- */
1954
- returnCanvasAndContext(e) {
1955
- X.returnCanvasAndContext(e);
1956
- }
1957
- /**
1958
- * Renders text to its canvas, and updates its texture.
1959
- * @param text - The text to render
1960
- * @param style - The style of the text
1961
- * @param padding - The padding of the text
1962
- * @param resolution - The resolution of the text
1963
- * @param canvasAndContext - The canvas and context to render the text to
1964
- */
1965
- _renderTextToCanvas(e, t, r, i, n) {
1966
- var m, T, S, B;
1967
- const { canvas: s, context: a } = n, u = ie(t), l = O.measureText(e || " ", t), h = l.lines, c = l.lineHeight, d = l.lineWidths, f = l.maxLineWidth, x = l.fontProperties, _ = s.height;
1968
- if (a.resetTransform(), a.scale(i, i), a.textBaseline = t.textBaseline, (m = t._stroke) != null && m.width) {
1969
- const w = t._stroke;
1970
- a.lineWidth = w.width, a.miterLimit = w.miterLimit, a.lineJoin = w.join, a.lineCap = w.cap;
1971
- }
1972
- a.font = u;
1973
- let v, g;
1974
- const b = t.dropShadow ? 2 : 1;
1975
- for (let w = 0; w < b; ++w) {
1976
- const F = t.dropShadow && w === 0, R = F ? Math.ceil(Math.max(1, _) + r * 2) : 0, ae = R * i;
1977
- if (F) {
1978
- a.fillStyle = "black", a.strokeStyle = "black";
1979
- const C = t.dropShadow, wt = C.color, St = C.alpha;
1980
- a.shadowColor = V.shared.setValue(wt).setAlpha(St).toRgbaString();
1981
- const Ct = C.blur * i, Te = C.distance * i;
1982
- a.shadowBlur = Ct, a.shadowOffsetX = Math.cos(C.angle) * Te, a.shadowOffsetY = Math.sin(C.angle) * Te + ae;
1983
- } else {
1984
- if (a.fillStyle = t._fill ? ne(t._fill, a, l, r * 2) : null, (T = t._stroke) != null && T.width) {
1985
- const C = t._stroke.width * 0.5 + r * 2;
1986
- a.strokeStyle = ne(t._stroke, a, l, C);
1987
- }
1988
- a.shadowColor = "black";
1989
- }
1990
- let I = (c - x.fontSize) / 2;
1991
- c - x.fontSize < 0 && (I = 0);
1992
- const $ = ((S = t._stroke) == null ? void 0 : S.width) ?? 0;
1993
- for (let C = 0; C < h.length; C++)
1994
- v = $ / 2, g = $ / 2 + C * c + x.ascent + I, t.align === "right" ? v += f - d[C] : t.align === "center" && (v += (f - d[C]) / 2), (B = t._stroke) != null && B.width && this._drawLetterSpacing(
1995
- h[C],
1996
- t,
1997
- n,
1998
- v + r,
1999
- g + r - R,
2000
- !0
2001
- ), t._fill !== void 0 && this._drawLetterSpacing(
2002
- h[C],
2003
- t,
2004
- n,
2005
- v + r,
2006
- g + r - R
2007
- );
2008
- }
2009
- }
2010
- /**
2011
- * Render the text with letter-spacing.
2012
- *
2013
- * This method handles rendering text with the correct letter spacing, using either:
2014
- * 1. Native letter spacing if supported by the browser
2015
- * 2. Manual letter spacing calculation if not natively supported
2016
- *
2017
- * For manual letter spacing, it calculates the position of each character
2018
- * based on its width and the desired spacing.
2019
- * @param text - The text to draw
2020
- * @param style - The text style to apply
2021
- * @param canvasAndContext - The canvas and context to draw to
2022
- * @param x - Horizontal position to draw the text
2023
- * @param y - Vertical position to draw the text
2024
- * @param isStroke - Whether to render the stroke (true) or fill (false)
2025
- * @private
2026
- */
2027
- _drawLetterSpacing(e, t, r, i, n, s = !1) {
2028
- const { context: a } = r, u = t.letterSpacing;
2029
- let l = !1;
2030
- if (O.experimentalLetterSpacingSupported && (O.experimentalLetterSpacing ? (a.letterSpacing = `${u}px`, a.textLetterSpacing = `${u}px`, l = !0) : (a.letterSpacing = "0px", a.textLetterSpacing = "0px")), u === 0 || l) {
2031
- s ? a.strokeText(e, i, n) : a.fillText(e, i, n);
2032
- return;
2033
- }
2034
- let h = i;
2035
- const c = O.graphemeSegmenter(e);
2036
- let d = a.measureText(e).width, f = 0;
2037
- for (let x = 0; x < c.length; ++x) {
2038
- const _ = c[x];
2039
- s ? a.strokeText(_, h, n) : a.fillText(_, h, n);
2040
- let v = "";
2041
- for (let g = x + 1; g < c.length; ++g)
2042
- v += c[g];
2043
- f = a.measureText(v).width, h += d - f + u, d = f;
2044
- }
2045
- }
2046
- }
2047
- const ue = new ar(), ze = "http://www.w3.org/2000/svg", ke = "http://www.w3.org/1999/xhtml";
2048
- class st {
2049
- constructor() {
2050
- this.svgRoot = document.createElementNS(ze, "svg"), this.foreignObject = document.createElementNS(ze, "foreignObject"), this.domElement = document.createElementNS(ke, "div"), this.styleElement = document.createElementNS(ke, "style");
2051
- const { foreignObject: e, svgRoot: t, styleElement: r, domElement: i } = this;
2052
- e.setAttribute("width", "10000"), e.setAttribute("height", "10000"), e.style.overflow = "hidden", t.appendChild(e), e.appendChild(r), e.appendChild(i), this.image = H.get().createImage();
2053
- }
2054
- destroy() {
2055
- this.svgRoot.remove(), this.foreignObject.remove(), this.styleElement.remove(), this.domElement.remove(), this.image.src = "", this.image.remove(), this.svgRoot = null, this.foreignObject = null, this.styleElement = null, this.domElement = null, this.image = null, this.canvasAndContext = null;
2056
- }
2057
- }
2058
- let Ge;
2059
- function or(o, e, t, r) {
2060
- r || (r = Ge || (Ge = new st()));
2061
- const { domElement: i, styleElement: n, svgRoot: s } = r;
2062
- i.innerHTML = `<style>${e.cssStyle};</style><div style='padding:0'>${o}</div>`, i.setAttribute("style", "transform-origin: top left; display: inline-block"), t && (n.textContent = t), document.body.appendChild(s);
2063
- const a = i.getBoundingClientRect();
2064
- s.remove();
2065
- const u = e.padding * 2;
2066
- return {
2067
- width: a.width - u,
2068
- height: a.height - u
2069
- };
2070
- }
2071
- class ur {
2072
- constructor() {
2073
- this.batches = [], this.batched = !1;
2074
- }
2075
- destroy() {
2076
- this.batches.forEach((e) => {
2077
- re.return(e);
2078
- }), this.batches.length = 0;
2079
- }
2080
- }
2081
- class at {
2082
- constructor(e, t) {
2083
- this.state = te.for2d(), this.renderer = e, this._adaptor = t, this.renderer.runners.contextChange.add(this);
2084
- }
2085
- contextChange() {
2086
- this._adaptor.contextChange(this.renderer);
2087
- }
2088
- validateRenderable(e) {
2089
- const t = e.context, r = !!e._gpuData, i = this.renderer.graphicsContext.updateGpuContext(t);
2090
- return !!(i.isBatchable || r !== i.isBatchable);
2091
- }
2092
- addRenderable(e, t) {
2093
- const r = this.renderer.graphicsContext.updateGpuContext(e.context);
2094
- e.didViewUpdate && this._rebuild(e), r.isBatchable ? this._addToBatcher(e, t) : (this.renderer.renderPipes.batch.break(t), t.add(e));
2095
- }
2096
- updateRenderable(e) {
2097
- const r = this._getGpuDataForRenderable(e).batches;
2098
- for (let i = 0; i < r.length; i++) {
2099
- const n = r[i];
2100
- n._batcher.updateElement(n);
2101
- }
2102
- }
2103
- execute(e) {
2104
- if (!e.isRenderable)
2105
- return;
2106
- const t = this.renderer, r = e.context;
2107
- if (!t.graphicsContext.getGpuContext(r).batches.length)
2108
- return;
2109
- const n = r.customShader || this._adaptor.shader;
2110
- this.state.blendMode = e.groupBlendMode;
2111
- const s = n.resources.localUniforms.uniforms;
2112
- s.uTransformMatrix = e.groupTransform, s.uRound = t._roundPixels | e._roundPixels, se(
2113
- e.groupColorAlpha,
2114
- s.uColor,
2115
- 0
2116
- ), this._adaptor.execute(this, e);
2117
- }
2118
- _rebuild(e) {
2119
- const t = this._getGpuDataForRenderable(e), r = this.renderer.graphicsContext.updateGpuContext(e.context);
2120
- t.destroy(), r.isBatchable && this._updateBatchesForRenderable(e, t);
2121
- }
2122
- _addToBatcher(e, t) {
2123
- const r = this.renderer.renderPipes.batch, i = this._getGpuDataForRenderable(e).batches;
2124
- for (let n = 0; n < i.length; n++) {
2125
- const s = i[n];
2126
- r.addToBatch(s, t);
2127
- }
2128
- }
2129
- _getGpuDataForRenderable(e) {
2130
- return e._gpuData[this.renderer.uid] || this._initGpuDataForRenderable(e);
2131
- }
2132
- _initGpuDataForRenderable(e) {
2133
- const t = new ur();
2134
- return e._gpuData[this.renderer.uid] = t, t;
2135
- }
2136
- _updateBatchesForRenderable(e, t) {
2137
- const r = e.context, i = this.renderer.graphicsContext.getGpuContext(r), n = this.renderer._roundPixels | e._roundPixels;
2138
- t.batches = i.batches.map((s) => {
2139
- const a = re.get(zt);
2140
- return s.copyTo(a), a.renderable = e, a.roundPixels = n, a;
2141
- });
2142
- }
2143
- destroy() {
2144
- this.renderer = null, this._adaptor.destroy(), this._adaptor = null, this.state = null;
2145
- }
2146
- }
2147
- at.extension = {
2148
- type: [
2149
- y.WebGLPipes,
2150
- y.WebGPUPipes,
2151
- y.CanvasPipes
2152
- ],
2153
- name: "graphics"
2154
- };
2155
- const ot = class ut extends be {
2156
- constructor(...e) {
2157
- super({});
2158
- let t = e[0] ?? {};
2159
- typeof t == "number" && (z(L, "PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"), t = {
2160
- width: t,
2161
- height: e[1],
2162
- verticesX: e[2],
2163
- verticesY: e[3]
2164
- }), this.build(t);
2165
- }
2166
- /**
2167
- * Refreshes plane coordinates
2168
- * @param options - Options to be applied to plane geometry
2169
- */
2170
- build(e) {
2171
- e = { ...ut.defaultOptions, ...e }, this.verticesX = this.verticesX ?? e.verticesX, this.verticesY = this.verticesY ?? e.verticesY, this.width = this.width ?? e.width, this.height = this.height ?? e.height;
2172
- const t = this.verticesX * this.verticesY, r = [], i = [], n = [], s = this.verticesX - 1, a = this.verticesY - 1, u = this.width / s, l = this.height / a;
2173
- for (let c = 0; c < t; c++) {
2174
- const d = c % this.verticesX, f = c / this.verticesX | 0;
2175
- r.push(d * u, f * l), i.push(d / s, f / a);
2176
- }
2177
- const h = s * a;
2178
- for (let c = 0; c < h; c++) {
2179
- const d = c % s, f = c / s | 0, x = f * this.verticesX + d, _ = f * this.verticesX + d + 1, v = (f + 1) * this.verticesX + d, g = (f + 1) * this.verticesX + d + 1;
2180
- n.push(
2181
- x,
2182
- _,
2183
- v,
2184
- _,
2185
- g,
2186
- v
2187
- );
2188
- }
2189
- this.buffers[0].data = new Float32Array(r), this.buffers[1].data = new Float32Array(i), this.indexBuffer.data = new Uint32Array(n), this.buffers[0].update(), this.buffers[1].update(), this.indexBuffer.update();
2190
- }
2191
- };
2192
- ot.defaultOptions = {
2193
- width: 100,
2194
- height: 100,
2195
- verticesX: 10,
2196
- verticesY: 10
2197
- };
2198
- let lr = ot;
2199
- class ye {
2200
- constructor() {
2201
- this.batcherName = "default", this.packAsQuad = !1, this.indexOffset = 0, this.attributeOffset = 0, this.roundPixels = 0, this._batcher = null, this._batch = null, this._textureMatrixUpdateId = -1, this._uvUpdateId = -1;
2202
- }
2203
- get blendMode() {
2204
- return this.renderable.groupBlendMode;
2205
- }
2206
- get topology() {
2207
- return this._topology || this.geometry.topology;
2208
- }
2209
- set topology(e) {
2210
- this._topology = e;
2211
- }
2212
- reset() {
2213
- this.renderable = null, this.texture = null, this._batcher = null, this._batch = null, this.geometry = null, this._uvUpdateId = -1, this._textureMatrixUpdateId = -1;
2214
- }
2215
- /**
2216
- * Sets the texture for the batchable mesh.
2217
- * As it does so, it resets the texture matrix update ID.
2218
- * this is to ensure that the texture matrix is recalculated when the uvs are referenced
2219
- * @param value - The texture to set.
2220
- */
2221
- setTexture(e) {
2222
- this.texture !== e && (this.texture = e, this._textureMatrixUpdateId = -1);
2223
- }
2224
- get uvs() {
2225
- const t = this.geometry.getBuffer("aUV"), r = t.data;
2226
- let i = r;
2227
- const n = this.texture.textureMatrix;
2228
- return n.isSimple || (i = this._transformedUvs, (this._textureMatrixUpdateId !== n._updateID || this._uvUpdateId !== t._updateID) && ((!i || i.length < r.length) && (i = this._transformedUvs = new Float32Array(r.length)), this._textureMatrixUpdateId = n._updateID, this._uvUpdateId = t._updateID, n.multiplyUvs(r, i))), i;
2229
- }
2230
- get positions() {
2231
- return this.geometry.positions;
2232
- }
2233
- get indices() {
2234
- return this.geometry.indices;
2235
- }
2236
- get color() {
2237
- return this.renderable.groupColorAlpha;
2238
- }
2239
- get groupTransform() {
2240
- return this.renderable.groupTransform;
2241
- }
2242
- get attributeSize() {
2243
- return this.geometry.positions.length / 2;
2244
- }
2245
- get indexSize() {
2246
- return this.geometry.indices.length;
2247
- }
2248
- }
2249
- class Ae {
2250
- destroy() {
2251
- }
2252
- }
2253
- class lt {
2254
- constructor(e, t) {
2255
- this.localUniforms = new Y({
2256
- uTransformMatrix: { value: new U(), type: "mat3x3<f32>" },
2257
- uColor: { value: new Float32Array([1, 1, 1, 1]), type: "vec4<f32>" },
2258
- uRound: { value: 0, type: "f32" }
2259
- }), this.localUniformsBindGroup = new He({
2260
- 0: this.localUniforms
2261
- }), this.renderer = e, this._adaptor = t, this._adaptor.init();
2262
- }
2263
- validateRenderable(e) {
2264
- const t = this._getMeshData(e), r = t.batched, i = e.batched;
2265
- if (t.batched = i, r !== i)
2266
- return !0;
2267
- if (i) {
2268
- const n = e._geometry;
2269
- if (n.indices.length !== t.indexSize || n.positions.length !== t.vertexSize)
2270
- return t.indexSize = n.indices.length, t.vertexSize = n.positions.length, !0;
2271
- const s = this._getBatchableMesh(e);
2272
- return s.texture.uid !== e._texture.uid && (s._textureMatrixUpdateId = -1), !s._batcher.checkAndUpdateTexture(
2273
- s,
2274
- e._texture
2275
- );
2276
- }
2277
- return !1;
2278
- }
2279
- addRenderable(e, t) {
2280
- var n, s;
2281
- const r = this.renderer.renderPipes.batch, i = this._getMeshData(e);
2282
- if (e.didViewUpdate && (i.indexSize = (n = e._geometry.indices) == null ? void 0 : n.length, i.vertexSize = (s = e._geometry.positions) == null ? void 0 : s.length), i.batched) {
2283
- const a = this._getBatchableMesh(e);
2284
- a.setTexture(e._texture), a.geometry = e._geometry, r.addToBatch(a, t);
2285
- } else
2286
- r.break(t), t.add(e);
2287
- }
2288
- updateRenderable(e) {
2289
- if (e.batched) {
2290
- const t = this._getBatchableMesh(e);
2291
- t.setTexture(e._texture), t.geometry = e._geometry, t._batcher.updateElement(t);
2292
- }
2293
- }
2294
- execute(e) {
2295
- if (!e.isRenderable)
2296
- return;
2297
- e.state.blendMode = _e(e.groupBlendMode, e.texture._source);
2298
- const t = this.localUniforms;
2299
- t.uniforms.uTransformMatrix = e.groupTransform, t.uniforms.uRound = this.renderer._roundPixels | e._roundPixels, t.update(), se(
2300
- e.groupColorAlpha,
2301
- t.uniforms.uColor,
2302
- 0
2303
- ), this._adaptor.execute(this, e);
2304
- }
2305
- _getMeshData(e) {
2306
- var t, r;
2307
- return (t = e._gpuData)[r = this.renderer.uid] || (t[r] = new Ae()), e._gpuData[this.renderer.uid].meshData || this._initMeshData(e);
2308
- }
2309
- _initMeshData(e) {
2310
- return e._gpuData[this.renderer.uid].meshData = {
2311
- batched: e.batched,
2312
- indexSize: 0,
2313
- vertexSize: 0
2314
- }, e._gpuData[this.renderer.uid].meshData;
2315
- }
2316
- _getBatchableMesh(e) {
2317
- var t, r;
2318
- return (t = e._gpuData)[r = this.renderer.uid] || (t[r] = new Ae()), e._gpuData[this.renderer.uid].batchableMesh || this._initBatchableMesh(e);
2319
- }
2320
- _initBatchableMesh(e) {
2321
- const t = new ye();
2322
- return t.renderable = e, t.setTexture(e._texture), t.transform = e.groupTransform, t.roundPixels = this.renderer._roundPixels | e._roundPixels, e._gpuData[this.renderer.uid].batchableMesh = t, t;
2323
- }
2324
- destroy() {
2325
- this.localUniforms = null, this.localUniformsBindGroup = null, this._adaptor.destroy(), this._adaptor = null, this.renderer = null;
2326
- }
2327
- }
2328
- lt.extension = {
2329
- type: [
2330
- y.WebGLPipes,
2331
- y.WebGPUPipes,
2332
- y.CanvasPipes
2333
- ],
2334
- name: "mesh"
2335
- };
2336
- class cr {
2337
- execute(e, t) {
2338
- const r = e.state, i = e.renderer, n = t.shader || e.defaultShader;
2339
- n.resources.uTexture = t.texture._source, n.resources.uniforms = e.localUniforms;
2340
- const s = i.gl, a = e.getBuffers(t);
2341
- i.shader.bind(n), i.state.set(r), i.geometry.bind(a.geometry, n.glProgram);
2342
- const l = a.geometry.indexBuffer.data.BYTES_PER_ELEMENT === 2 ? s.UNSIGNED_SHORT : s.UNSIGNED_INT;
2343
- s.drawElements(s.TRIANGLES, t.particleChildren.length * 6, l, 0);
2344
- }
2345
- }
2346
- class hr {
2347
- execute(e, t) {
2348
- const r = e.renderer, i = t.shader || e.defaultShader;
2349
- i.groups[0] = r.renderPipes.uniformBatch.getUniformBindGroup(e.localUniforms, !0), i.groups[1] = r.texture.getTextureBindGroup(t.texture);
2350
- const n = e.state, s = e.getBuffers(t);
2351
- r.encoder.draw({
2352
- geometry: s.geometry,
2353
- shader: t.shader || e.defaultShader,
2354
- state: n,
2355
- size: t.particleChildren.length * 6
2356
- });
2357
- }
2358
- }
2359
- function De(o, e = null) {
2360
- const t = o * 6;
2361
- if (t > 65535 ? e || (e = new Uint32Array(t)) : e || (e = new Uint16Array(t)), e.length !== t)
2362
- throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${t}`);
2363
- for (let r = 0, i = 0; r < t; r += 6, i += 4)
2364
- e[r + 0] = i + 0, e[r + 1] = i + 1, e[r + 2] = i + 2, e[r + 3] = i + 0, e[r + 4] = i + 2, e[r + 5] = i + 3;
2365
- return e;
2366
- }
2367
- function dr(o) {
2368
- return {
2369
- dynamicUpdate: Oe(o, !0),
2370
- staticUpdate: Oe(o, !1)
2371
- };
2372
- }
2373
- function Oe(o, e) {
2374
- const t = [];
2375
- t.push(`
2376
-
2377
- var index = 0;
2378
-
2379
- for (let i = 0; i < ps.length; ++i)
2380
- {
2381
- const p = ps[i];
2382
-
2383
- `);
2384
- let r = 0;
2385
- for (const n in o) {
2386
- const s = o[n];
2387
- if (e !== s.dynamic)
2388
- continue;
2389
- t.push(`offset = index + ${r}`), t.push(s.code);
2390
- const a = pe(s.format);
2391
- r += a.stride / 4;
2392
- }
2393
- t.push(`
2394
- index += stride * 4;
2395
- }
2396
- `), t.unshift(`
2397
- var stride = ${r};
2398
- `);
2399
- const i = t.join(`
2400
- `);
2401
- return new Function("ps", "f32v", "u32v", i);
2402
- }
2403
- class fr {
2404
- constructor(e) {
2405
- this._size = 0, this._generateParticleUpdateCache = {};
2406
- const t = this._size = e.size ?? 1e3, r = e.properties;
2407
- let i = 0, n = 0;
2408
- for (const h in r) {
2409
- const c = r[h], d = pe(c.format);
2410
- c.dynamic ? n += d.stride : i += d.stride;
2411
- }
2412
- this._dynamicStride = n / 4, this._staticStride = i / 4, this.staticAttributeBuffer = new Q(t * 4 * i), this.dynamicAttributeBuffer = new Q(t * 4 * n), this.indexBuffer = De(t);
2413
- const s = new me();
2414
- let a = 0, u = 0;
2415
- this._staticBuffer = new N({
2416
- data: new Float32Array(1),
2417
- label: "static-particle-buffer",
2418
- shrinkToFit: !1,
2419
- usage: D.VERTEX | D.COPY_DST
2420
- }), this._dynamicBuffer = new N({
2421
- data: new Float32Array(1),
2422
- label: "dynamic-particle-buffer",
2423
- shrinkToFit: !1,
2424
- usage: D.VERTEX | D.COPY_DST
2425
- });
2426
- for (const h in r) {
2427
- const c = r[h], d = pe(c.format);
2428
- c.dynamic ? (s.addAttribute(c.attributeName, {
2429
- buffer: this._dynamicBuffer,
2430
- stride: this._dynamicStride * 4,
2431
- offset: a * 4,
2432
- format: c.format
2433
- }), a += d.size) : (s.addAttribute(c.attributeName, {
2434
- buffer: this._staticBuffer,
2435
- stride: this._staticStride * 4,
2436
- offset: u * 4,
2437
- format: c.format
2438
- }), u += d.size);
2439
- }
2440
- s.addIndex(this.indexBuffer);
2441
- const l = this.getParticleUpdate(r);
2442
- this._dynamicUpload = l.dynamicUpdate, this._staticUpload = l.staticUpdate, this.geometry = s;
2443
- }
2444
- getParticleUpdate(e) {
2445
- const t = pr(e);
2446
- return this._generateParticleUpdateCache[t] ? this._generateParticleUpdateCache[t] : (this._generateParticleUpdateCache[t] = this.generateParticleUpdate(e), this._generateParticleUpdateCache[t]);
2447
- }
2448
- generateParticleUpdate(e) {
2449
- return dr(e);
2450
- }
2451
- update(e, t) {
2452
- e.length > this._size && (t = !0, this._size = Math.max(e.length, this._size * 1.5 | 0), this.staticAttributeBuffer = new Q(this._size * this._staticStride * 4 * 4), this.dynamicAttributeBuffer = new Q(this._size * this._dynamicStride * 4 * 4), this.indexBuffer = De(this._size), this.geometry.indexBuffer.setDataWithSize(
2453
- this.indexBuffer,
2454
- this.indexBuffer.byteLength,
2455
- !0
2456
- ));
2457
- const r = this.dynamicAttributeBuffer;
2458
- if (this._dynamicUpload(e, r.float32View, r.uint32View), this._dynamicBuffer.setDataWithSize(
2459
- this.dynamicAttributeBuffer.float32View,
2460
- e.length * this._dynamicStride * 4,
2461
- !0
2462
- ), t) {
2463
- const i = this.staticAttributeBuffer;
2464
- this._staticUpload(e, i.float32View, i.uint32View), this._staticBuffer.setDataWithSize(
2465
- i.float32View,
2466
- e.length * this._staticStride * 4,
2467
- !0
2468
- );
2469
- }
2470
- }
2471
- destroy() {
2472
- this._staticBuffer.destroy(), this._dynamicBuffer.destroy(), this.geometry.destroy();
2473
- }
2474
- }
2475
- function pr(o) {
2476
- const e = [];
2477
- for (const t in o) {
2478
- const r = o[t];
2479
- e.push(t, r.code, r.dynamic ? "d" : "s");
2480
- }
2481
- return e.join("_");
2482
- }
2483
- var gr = `varying vec2 vUV;
2484
- varying vec4 vColor;
2485
-
2486
- uniform sampler2D uTexture;
2487
-
2488
- void main(void){
2489
- vec4 color = texture2D(uTexture, vUV) * vColor;
2490
- gl_FragColor = color;
2491
- }`, mr = `attribute vec2 aVertex;
2492
- attribute vec2 aUV;
2493
- attribute vec4 aColor;
2494
-
2495
- attribute vec2 aPosition;
2496
- attribute float aRotation;
2497
-
2498
- uniform mat3 uTranslationMatrix;
2499
- uniform float uRound;
2500
- uniform vec2 uResolution;
2501
- uniform vec4 uColor;
2502
-
2503
- varying vec2 vUV;
2504
- varying vec4 vColor;
2505
-
2506
- vec2 roundPixels(vec2 position, vec2 targetSize)
2507
- {
2508
- return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
2509
- }
2510
-
2511
- void main(void){
2512
- float cosRotation = cos(aRotation);
2513
- float sinRotation = sin(aRotation);
2514
- float x = aVertex.x * cosRotation - aVertex.y * sinRotation;
2515
- float y = aVertex.x * sinRotation + aVertex.y * cosRotation;
2516
-
2517
- vec2 v = vec2(x, y);
2518
- v = v + aPosition;
2519
-
2520
- gl_Position = vec4((uTranslationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);
2521
-
2522
- if(uRound == 1.0)
2523
- {
2524
- gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
2525
- }
2526
-
2527
- vUV = aUV;
2528
- vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uColor;
2529
- }
2530
- `, Ie = `
2531
- struct ParticleUniforms {
2532
- uTranslationMatrix:mat3x3<f32>,
2533
- uColor:vec4<f32>,
2534
- uRound:f32,
2535
- uResolution:vec2<f32>,
2536
- };
2537
-
2538
- fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
2539
- {
2540
- return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
2541
- }
2542
-
2543
- @group(0) @binding(0) var<uniform> uniforms: ParticleUniforms;
2544
-
2545
- @group(1) @binding(0) var uTexture: texture_2d<f32>;
2546
- @group(1) @binding(1) var uSampler : sampler;
2547
-
2548
- struct VSOutput {
2549
- @builtin(position) position: vec4<f32>,
2550
- @location(0) uv : vec2<f32>,
2551
- @location(1) color : vec4<f32>,
2552
- };
2553
- @vertex
2554
- fn mainVertex(
2555
- @location(0) aVertex: vec2<f32>,
2556
- @location(1) aPosition: vec2<f32>,
2557
- @location(2) aUV: vec2<f32>,
2558
- @location(3) aColor: vec4<f32>,
2559
- @location(4) aRotation: f32,
2560
- ) -> VSOutput {
2561
-
2562
- let v = vec2(
2563
- aVertex.x * cos(aRotation) - aVertex.y * sin(aRotation),
2564
- aVertex.x * sin(aRotation) + aVertex.y * cos(aRotation)
2565
- ) + aPosition;
2566
-
2567
- var position = vec4((uniforms.uTranslationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);
2568
-
2569
- if(uniforms.uRound == 1.0) {
2570
- position = vec4(roundPixels(position.xy, uniforms.uResolution), position.zw);
2571
- }
2572
-
2573
- let vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uniforms.uColor;
2574
-
2575
- return VSOutput(
2576
- position,
2577
- aUV,
2578
- vColor,
2579
- );
2580
- }
2581
-
2582
- @fragment
2583
- fn mainFragment(
2584
- @location(0) uv: vec2<f32>,
2585
- @location(1) color: vec4<f32>,
2586
- @builtin(position) position: vec4<f32>,
2587
- ) -> @location(0) vec4<f32> {
2588
-
2589
- var sample = textureSample(uTexture, uSampler, uv) * color;
2590
-
2591
- return sample;
2592
- }`;
2593
- class xr extends ve {
2594
- constructor() {
2595
- const e = Ee.from({
2596
- vertex: mr,
2597
- fragment: gr
2598
- }), t = Le.from({
2599
- fragment: {
2600
- source: Ie,
2601
- entryPoint: "mainFragment"
2602
- },
2603
- vertex: {
2604
- source: Ie,
2605
- entryPoint: "mainVertex"
2606
- }
2607
- });
2608
- super({
2609
- glProgram: e,
2610
- gpuProgram: t,
2611
- resources: {
2612
- // this will be replaced with the texture from the particle container
2613
- uTexture: M.WHITE.source,
2614
- // this will be replaced with the texture style from the particle container
2615
- uSampler: new j({}),
2616
- // this will be replaced with the local uniforms from the particle container
2617
- uniforms: {
2618
- uTranslationMatrix: { value: new U(), type: "mat3x3<f32>" },
2619
- uColor: { value: new V(16777215), type: "vec4<f32>" },
2620
- uRound: { value: 1, type: "f32" },
2621
- uResolution: { value: [0, 0], type: "vec2<f32>" }
2622
- }
2623
- }
2624
- });
2625
- }
2626
- }
2627
- class ct {
2628
- /**
2629
- * @param renderer - The renderer this sprite batch works for.
2630
- * @param adaptor
2631
- */
2632
- constructor(e, t) {
2633
- this.state = te.for2d(), this.localUniforms = new Y({
2634
- uTranslationMatrix: { value: new U(), type: "mat3x3<f32>" },
2635
- uColor: { value: new Float32Array(4), type: "vec4<f32>" },
2636
- uRound: { value: 1, type: "f32" },
2637
- uResolution: { value: [0, 0], type: "vec2<f32>" }
2638
- }), this.renderer = e, this.adaptor = t, this.defaultShader = new xr(), this.state = te.for2d();
2639
- }
2640
- validateRenderable(e) {
2641
- return !1;
2642
- }
2643
- addRenderable(e, t) {
2644
- this.renderer.renderPipes.batch.break(t), t.add(e);
2645
- }
2646
- getBuffers(e) {
2647
- return e._gpuData[this.renderer.uid] || this._initBuffer(e);
2648
- }
2649
- _initBuffer(e) {
2650
- return e._gpuData[this.renderer.uid] = new fr({
2651
- size: e.particleChildren.length,
2652
- properties: e._properties
2653
- }), e._gpuData[this.renderer.uid];
2654
- }
2655
- updateRenderable(e) {
2656
- }
2657
- execute(e) {
2658
- const t = e.particleChildren;
2659
- if (t.length === 0)
2660
- return;
2661
- const r = this.renderer, i = this.getBuffers(e);
2662
- e.texture || (e.texture = t[0].texture);
2663
- const n = this.state;
2664
- i.update(t, e._childrenDirty), e._childrenDirty = !1, n.blendMode = _e(e.blendMode, e.texture._source);
2665
- const s = this.localUniforms.uniforms, a = s.uTranslationMatrix;
2666
- e.worldTransform.copyTo(a), a.prepend(r.globalUniforms.globalUniformData.projectionMatrix), s.uResolution = r.globalUniforms.globalUniformData.resolution, s.uRound = r._roundPixels | e._roundPixels, se(
2667
- e.groupColorAlpha,
2668
- s.uColor,
2669
- 0
2670
- ), this.adaptor.execute(this, e);
2671
- }
2672
- /** Destroys the ParticleRenderer. */
2673
- destroy() {
2674
- this.renderer = null, this.defaultShader && (this.defaultShader.destroy(), this.defaultShader = null);
2675
- }
2676
- }
2677
- class ht extends ct {
2678
- constructor(e) {
2679
- super(e, new cr());
2680
- }
2681
- }
2682
- ht.extension = {
2683
- type: [
2684
- y.WebGLPipes
2685
- ],
2686
- name: "particle"
2687
- };
2688
- class dt extends ct {
2689
- constructor(e) {
2690
- super(e, new hr());
2691
- }
2692
- }
2693
- dt.extension = {
2694
- type: [
2695
- y.WebGPUPipes
2696
- ],
2697
- name: "particle"
2698
- };
2699
- const ft = class pt extends lr {
2700
- constructor(e = {}) {
2701
- e = { ...pt.defaultOptions, ...e }, super({
2702
- width: e.width,
2703
- height: e.height,
2704
- verticesX: 4,
2705
- verticesY: 4
2706
- }), this.update(e);
2707
- }
2708
- /**
2709
- * Updates the NineSliceGeometry with the options.
2710
- * @param options - The options of the NineSliceGeometry.
2711
- */
2712
- update(e) {
2713
- var t, r;
2714
- this.width = e.width ?? this.width, this.height = e.height ?? this.height, this._originalWidth = e.originalWidth ?? this._originalWidth, this._originalHeight = e.originalHeight ?? this._originalHeight, this._leftWidth = e.leftWidth ?? this._leftWidth, this._rightWidth = e.rightWidth ?? this._rightWidth, this._topHeight = e.topHeight ?? this._topHeight, this._bottomHeight = e.bottomHeight ?? this._bottomHeight, this._anchorX = (t = e.anchor) == null ? void 0 : t.x, this._anchorY = (r = e.anchor) == null ? void 0 : r.y, this.updateUvs(), this.updatePositions();
2715
- }
2716
- /** Updates the positions of the vertices. */
2717
- updatePositions() {
2718
- const e = this.positions, {
2719
- width: t,
2720
- height: r,
2721
- _leftWidth: i,
2722
- _rightWidth: n,
2723
- _topHeight: s,
2724
- _bottomHeight: a,
2725
- _anchorX: u,
2726
- _anchorY: l
2727
- } = this, h = i + n, c = t > h ? 1 : t / h, d = s + a, f = r > d ? 1 : r / d, x = Math.min(c, f), _ = u * t, v = l * r;
2728
- e[0] = e[8] = e[16] = e[24] = -_, e[2] = e[10] = e[18] = e[26] = i * x - _, e[4] = e[12] = e[20] = e[28] = t - n * x - _, e[6] = e[14] = e[22] = e[30] = t - _, e[1] = e[3] = e[5] = e[7] = -v, e[9] = e[11] = e[13] = e[15] = s * x - v, e[17] = e[19] = e[21] = e[23] = r - a * x - v, e[25] = e[27] = e[29] = e[31] = r - v, this.getBuffer("aPosition").update();
2729
- }
2730
- /** Updates the UVs of the vertices. */
2731
- updateUvs() {
2732
- const e = this.uvs;
2733
- e[0] = e[8] = e[16] = e[24] = 0, e[1] = e[3] = e[5] = e[7] = 0, e[6] = e[14] = e[22] = e[30] = 1, e[25] = e[27] = e[29] = e[31] = 1;
2734
- const t = 1 / this._originalWidth, r = 1 / this._originalHeight;
2735
- e[2] = e[10] = e[18] = e[26] = t * this._leftWidth, e[9] = e[11] = e[13] = e[15] = r * this._topHeight, e[4] = e[12] = e[20] = e[28] = 1 - t * this._rightWidth, e[17] = e[19] = e[21] = e[23] = 1 - r * this._bottomHeight, this.getBuffer("aUV").update();
2736
- }
2737
- };
2738
- ft.defaultOptions = {
2739
- /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
2740
- width: 100,
2741
- /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
2742
- height: 100,
2743
- /** The width of the left column. */
2744
- leftWidth: 10,
2745
- /** The height of the top row. */
2746
- topHeight: 10,
2747
- /** The width of the right column. */
2748
- rightWidth: 10,
2749
- /** The height of the bottom row. */
2750
- bottomHeight: 10,
2751
- /** The original width of the texture */
2752
- originalWidth: 100,
2753
- /** The original height of the texture */
2754
- originalHeight: 100
2755
- };
2756
- let _r = ft;
2757
- class vr extends ye {
2758
- constructor() {
2759
- super(), this.geometry = new _r();
2760
- }
2761
- destroy() {
2762
- this.geometry.destroy();
2763
- }
2764
- }
2765
- class gt {
2766
- constructor(e) {
2767
- this._renderer = e;
2768
- }
2769
- addRenderable(e, t) {
2770
- const r = this._getGpuSprite(e);
2771
- e.didViewUpdate && this._updateBatchableSprite(e, r), this._renderer.renderPipes.batch.addToBatch(r, t);
2772
- }
2773
- updateRenderable(e) {
2774
- const t = this._getGpuSprite(e);
2775
- e.didViewUpdate && this._updateBatchableSprite(e, t), t._batcher.updateElement(t);
2776
- }
2777
- validateRenderable(e) {
2778
- const t = this._getGpuSprite(e);
2779
- return !t._batcher.checkAndUpdateTexture(
2780
- t,
2781
- e._texture
2782
- );
2783
- }
2784
- _updateBatchableSprite(e, t) {
2785
- t.geometry.update(e), t.setTexture(e._texture);
2786
- }
2787
- _getGpuSprite(e) {
2788
- return e._gpuData[this._renderer.uid] || this._initGPUSprite(e);
2789
- }
2790
- _initGPUSprite(e) {
2791
- const t = e._gpuData[this._renderer.uid] = new vr(), r = t;
2792
- return r.renderable = e, r.transform = e.groupTransform, r.texture = e._texture, r.roundPixels = this._renderer._roundPixels | e._roundPixels, e.didViewUpdate || this._updateBatchableSprite(e, r), t;
2793
- }
2794
- destroy() {
2795
- this._renderer = null;
2796
- }
2797
- }
2798
- gt.extension = {
2799
- type: [
2800
- y.WebGLPipes,
2801
- y.WebGPUPipes,
2802
- y.CanvasPipes
2803
- ],
2804
- name: "nineSliceSprite"
2805
- };
2806
- const br = {
2807
- name: "tiling-bit",
2808
- vertex: {
2809
- header: (
2810
- /* wgsl */
2811
- `
2812
- struct TilingUniforms {
2813
- uMapCoord:mat3x3<f32>,
2814
- uClampFrame:vec4<f32>,
2815
- uClampOffset:vec2<f32>,
2816
- uTextureTransform:mat3x3<f32>,
2817
- uSizeAnchor:vec4<f32>
2818
- };
2819
-
2820
- @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
2821
- @group(2) @binding(1) var uTexture: texture_2d<f32>;
2822
- @group(2) @binding(2) var uSampler: sampler;
2823
- `
2824
- ),
2825
- main: (
2826
- /* wgsl */
2827
- `
2828
- uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
2829
-
2830
- position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
2831
- `
2832
- )
2833
- },
2834
- fragment: {
2835
- header: (
2836
- /* wgsl */
2837
- `
2838
- struct TilingUniforms {
2839
- uMapCoord:mat3x3<f32>,
2840
- uClampFrame:vec4<f32>,
2841
- uClampOffset:vec2<f32>,
2842
- uTextureTransform:mat3x3<f32>,
2843
- uSizeAnchor:vec4<f32>
2844
- };
2845
-
2846
- @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
2847
- @group(2) @binding(1) var uTexture: texture_2d<f32>;
2848
- @group(2) @binding(2) var uSampler: sampler;
2849
- `
2850
- ),
2851
- main: (
2852
- /* wgsl */
2853
- `
2854
-
2855
- var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
2856
- coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
2857
- var unclamped = coord;
2858
- coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
2859
-
2860
- var bias = 0.;
2861
-
2862
- if(unclamped.x == coord.x && unclamped.y == coord.y)
2863
- {
2864
- bias = -32.;
2865
- }
2866
-
2867
- outColor = textureSampleBias(uTexture, uSampler, coord, bias);
2868
- `
2869
- )
2870
- }
2871
- }, yr = {
2872
- name: "tiling-bit",
2873
- vertex: {
2874
- header: (
2875
- /* glsl */
2876
- `
2877
- uniform mat3 uTextureTransform;
2878
- uniform vec4 uSizeAnchor;
2879
-
2880
- `
2881
- ),
2882
- main: (
2883
- /* glsl */
2884
- `
2885
- uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
2886
-
2887
- position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
2888
- `
2889
- )
2890
- },
2891
- fragment: {
2892
- header: (
2893
- /* glsl */
2894
- `
2895
- uniform sampler2D uTexture;
2896
- uniform mat3 uMapCoord;
2897
- uniform vec4 uClampFrame;
2898
- uniform vec2 uClampOffset;
2899
- `
2900
- ),
2901
- main: (
2902
- /* glsl */
2903
- `
2904
-
2905
- vec2 coord = vUV + ceil(uClampOffset - vUV);
2906
- coord = (uMapCoord * vec3(coord, 1.0)).xy;
2907
- vec2 unclamped = coord;
2908
- coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
2909
-
2910
- outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
2911
-
2912
- `
2913
- )
2914
- }
2915
- };
2916
- let le, ce;
2917
- class Tr extends ve {
2918
- constructor() {
2919
- le ?? (le = Ye({
2920
- name: "tiling-sprite-shader",
2921
- bits: [
2922
- Et,
2923
- br,
2924
- Xe
2925
- ]
2926
- })), ce ?? (ce = $e({
2927
- name: "tiling-sprite-shader",
2928
- bits: [
2929
- Ht,
2930
- yr,
2931
- Ne
2932
- ]
2933
- }));
2934
- const e = new Y({
2935
- uMapCoord: { value: new U(), type: "mat3x3<f32>" },
2936
- uClampFrame: { value: new Float32Array([0, 0, 1, 1]), type: "vec4<f32>" },
2937
- uClampOffset: { value: new Float32Array([0, 0]), type: "vec2<f32>" },
2938
- uTextureTransform: { value: new U(), type: "mat3x3<f32>" },
2939
- uSizeAnchor: { value: new Float32Array([100, 100, 0.5, 0.5]), type: "vec4<f32>" }
2940
- });
2941
- super({
2942
- glProgram: ce,
2943
- gpuProgram: le,
2944
- resources: {
2945
- localUniforms: new Y({
2946
- uTransformMatrix: { value: new U(), type: "mat3x3<f32>" },
2947
- uColor: { value: new Float32Array([1, 1, 1, 1]), type: "vec4<f32>" },
2948
- uRound: { value: 0, type: "f32" }
2949
- }),
2950
- tilingUniforms: e,
2951
- uTexture: M.EMPTY.source,
2952
- uSampler: M.EMPTY.source.style
2953
- }
2954
- });
2955
- }
2956
- updateUniforms(e, t, r, i, n, s) {
2957
- const a = this.resources.tilingUniforms, u = s.width, l = s.height, h = s.textureMatrix, c = a.uniforms.uTextureTransform;
2958
- c.set(
2959
- r.a * u / e,
2960
- r.b * u / t,
2961
- r.c * l / e,
2962
- r.d * l / t,
2963
- r.tx / e,
2964
- r.ty / t
2965
- ), c.invert(), a.uniforms.uMapCoord = h.mapCoord, a.uniforms.uClampFrame = h.uClampFrame, a.uniforms.uClampOffset = h.uClampOffset, a.uniforms.uTextureTransform = c, a.uniforms.uSizeAnchor[0] = e, a.uniforms.uSizeAnchor[1] = t, a.uniforms.uSizeAnchor[2] = i, a.uniforms.uSizeAnchor[3] = n, s && (this.resources.uTexture = s.source, this.resources.uSampler = s.source.style);
2966
- }
2967
- }
2968
- class wr extends be {
2969
- constructor() {
2970
- super({
2971
- positions: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
2972
- uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
2973
- indices: new Uint32Array([0, 1, 2, 0, 2, 3])
2974
- });
2975
- }
2976
- }
2977
- function Sr(o, e) {
2978
- const t = o.anchor.x, r = o.anchor.y;
2979
- e[0] = -t * o.width, e[1] = -r * o.height, e[2] = (1 - t) * o.width, e[3] = -r * o.height, e[4] = (1 - t) * o.width, e[5] = (1 - r) * o.height, e[6] = -t * o.width, e[7] = (1 - r) * o.height;
2980
- }
2981
- function Cr(o, e, t, r) {
2982
- let i = 0;
2983
- const n = o.length / e, s = r.a, a = r.b, u = r.c, l = r.d, h = r.tx, c = r.ty;
2984
- for (t *= e; i < n; ) {
2985
- const d = o[t], f = o[t + 1];
2986
- o[t] = s * d + u * f + h, o[t + 1] = a * d + l * f + c, t += e, i++;
2987
- }
2988
- }
2989
- function Pr(o, e) {
2990
- const t = o.texture, r = t.frame.width, i = t.frame.height;
2991
- let n = 0, s = 0;
2992
- o.applyAnchorToTexture && (n = o.anchor.x, s = o.anchor.y), e[0] = e[6] = -n, e[2] = e[4] = 1 - n, e[1] = e[3] = -s, e[5] = e[7] = 1 - s;
2993
- const a = U.shared;
2994
- a.copyFrom(o._tileTransform.matrix), a.tx /= o.width, a.ty /= o.height, a.invert(), a.scale(o.width / r, o.height / i), Cr(e, 2, 0, a);
2995
- }
2996
- const Z = new wr();
2997
- class Fr {
2998
- constructor() {
2999
- this.canBatch = !0, this.geometry = new be({
3000
- indices: Z.indices.slice(),
3001
- positions: Z.positions.slice(),
3002
- uvs: Z.uvs.slice()
3003
- });
3004
- }
3005
- destroy() {
3006
- var e;
3007
- this.geometry.destroy(), (e = this.shader) == null || e.destroy();
3008
- }
3009
- }
3010
- class mt {
3011
- constructor(e) {
3012
- this._state = te.default2d, this._renderer = e;
3013
- }
3014
- validateRenderable(e) {
3015
- const t = this._getTilingSpriteData(e), r = t.canBatch;
3016
- this._updateCanBatch(e);
3017
- const i = t.canBatch;
3018
- if (i && i === r) {
3019
- const { batchableMesh: n } = t;
3020
- return !n._batcher.checkAndUpdateTexture(
3021
- n,
3022
- e.texture
3023
- );
3024
- }
3025
- return r !== i;
3026
- }
3027
- addRenderable(e, t) {
3028
- const r = this._renderer.renderPipes.batch;
3029
- this._updateCanBatch(e);
3030
- const i = this._getTilingSpriteData(e), { geometry: n, canBatch: s } = i;
3031
- if (s) {
3032
- i.batchableMesh || (i.batchableMesh = new ye());
3033
- const a = i.batchableMesh;
3034
- e.didViewUpdate && (this._updateBatchableMesh(e), a.geometry = n, a.renderable = e, a.transform = e.groupTransform, a.setTexture(e._texture)), a.roundPixels = this._renderer._roundPixels | e._roundPixels, r.addToBatch(a, t);
3035
- } else
3036
- r.break(t), i.shader || (i.shader = new Tr()), this.updateRenderable(e), t.add(e);
3037
- }
3038
- execute(e) {
3039
- const { shader: t } = this._getTilingSpriteData(e);
3040
- t.groups[0] = this._renderer.globalUniforms.bindGroup;
3041
- const r = t.resources.localUniforms.uniforms;
3042
- r.uTransformMatrix = e.groupTransform, r.uRound = this._renderer._roundPixels | e._roundPixels, se(
3043
- e.groupColorAlpha,
3044
- r.uColor,
3045
- 0
3046
- ), this._state.blendMode = _e(e.groupBlendMode, e.texture._source), this._renderer.encoder.draw({
3047
- geometry: Z,
3048
- shader: t,
3049
- state: this._state
3050
- });
3051
- }
3052
- updateRenderable(e) {
3053
- const t = this._getTilingSpriteData(e), { canBatch: r } = t;
3054
- if (r) {
3055
- const { batchableMesh: i } = t;
3056
- e.didViewUpdate && this._updateBatchableMesh(e), i._batcher.updateElement(i);
3057
- } else if (e.didViewUpdate) {
3058
- const { shader: i } = t;
3059
- i.updateUniforms(
3060
- e.width,
3061
- e.height,
3062
- e._tileTransform.matrix,
3063
- e.anchor.x,
3064
- e.anchor.y,
3065
- e.texture
3066
- );
3067
- }
3068
- }
3069
- _getTilingSpriteData(e) {
3070
- return e._gpuData[this._renderer.uid] || this._initTilingSpriteData(e);
3071
- }
3072
- _initTilingSpriteData(e) {
3073
- const t = new Fr();
3074
- return t.renderable = e, e._gpuData[this._renderer.uid] = t, t;
3075
- }
3076
- _updateBatchableMesh(e) {
3077
- const t = this._getTilingSpriteData(e), { geometry: r } = t, i = e.texture.source.style;
3078
- i.addressMode !== "repeat" && (i.addressMode = "repeat", i.update()), Pr(e, r.uvs), Sr(e, r.positions);
3079
- }
3080
- destroy() {
3081
- this._renderer = null;
3082
- }
3083
- _updateCanBatch(e) {
3084
- const t = this._getTilingSpriteData(e), r = e.texture;
3085
- let i = !0;
3086
- return this._renderer.type === xe.WEBGL && (i = this._renderer.context.supports.nonPowOf2wrapping), t.canBatch = r.textureMatrix.isSimple && (i || r.source.isPowerOfTwo), t.canBatch;
3087
- }
3088
- }
3089
- mt.extension = {
3090
- type: [
3091
- y.WebGLPipes,
3092
- y.WebGPUPipes,
3093
- y.CanvasPipes
3094
- ],
3095
- name: "tilingSprite"
3096
- };
3097
- const Br = {
3098
- name: "local-uniform-msdf-bit",
3099
- vertex: {
3100
- header: (
3101
- /* wgsl */
3102
- `
3103
- struct LocalUniforms {
3104
- uColor:vec4<f32>,
3105
- uTransformMatrix:mat3x3<f32>,
3106
- uDistance: f32,
3107
- uRound:f32,
3108
- }
3109
-
3110
- @group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
3111
- `
3112
- ),
3113
- main: (
3114
- /* wgsl */
3115
- `
3116
- vColor *= localUniforms.uColor;
3117
- modelMatrix *= localUniforms.uTransformMatrix;
3118
- `
3119
- ),
3120
- end: (
3121
- /* wgsl */
3122
- `
3123
- if(localUniforms.uRound == 1)
3124
- {
3125
- vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
3126
- }
3127
- `
3128
- )
3129
- },
3130
- fragment: {
3131
- header: (
3132
- /* wgsl */
3133
- `
3134
- struct LocalUniforms {
3135
- uColor:vec4<f32>,
3136
- uTransformMatrix:mat3x3<f32>,
3137
- uDistance: f32
3138
- }
3139
-
3140
- @group(2) @binding(0) var<uniform> localUniforms : LocalUniforms;
3141
- `
3142
- ),
3143
- main: (
3144
- /* wgsl */
3145
- `
3146
- outColor = vec4<f32>(calculateMSDFAlpha(outColor, localUniforms.uColor, localUniforms.uDistance));
3147
- `
3148
- )
3149
- }
3150
- }, Rr = {
3151
- name: "local-uniform-msdf-bit",
3152
- vertex: {
3153
- header: (
3154
- /* glsl */
3155
- `
3156
- uniform mat3 uTransformMatrix;
3157
- uniform vec4 uColor;
3158
- uniform float uRound;
3159
- `
3160
- ),
3161
- main: (
3162
- /* glsl */
3163
- `
3164
- vColor *= uColor;
3165
- modelMatrix *= uTransformMatrix;
3166
- `
3167
- ),
3168
- end: (
3169
- /* glsl */
3170
- `
3171
- if(uRound == 1.)
3172
- {
3173
- gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
3174
- }
3175
- `
3176
- )
3177
- },
3178
- fragment: {
3179
- header: (
3180
- /* glsl */
3181
- `
3182
- uniform float uDistance;
3183
- `
3184
- ),
3185
- main: (
3186
- /* glsl */
3187
- `
3188
- outColor = vec4(calculateMSDFAlpha(outColor, vColor, uDistance));
3189
- `
3190
- )
3191
- }
3192
- }, Mr = {
3193
- name: "msdf-bit",
3194
- fragment: {
3195
- header: (
3196
- /* wgsl */
3197
- `
3198
- fn calculateMSDFAlpha(msdfColor:vec4<f32>, shapeColor:vec4<f32>, distance:f32) -> f32 {
3199
-
3200
- // MSDF
3201
- var median = msdfColor.r + msdfColor.g + msdfColor.b -
3202
- min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
3203
- max(msdfColor.r, max(msdfColor.g, msdfColor.b));
3204
-
3205
- // SDF
3206
- median = min(median, msdfColor.a);
3207
-
3208
- var screenPxDistance = distance * (median - 0.5);
3209
- var alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
3210
- if (median < 0.01) {
3211
- alpha = 0.0;
3212
- } else if (median > 0.99) {
3213
- alpha = 1.0;
3214
- }
3215
-
3216
- // Gamma correction for coverage-like alpha
3217
- var luma: f32 = dot(shapeColor.rgb, vec3<f32>(0.299, 0.587, 0.114));
3218
- var gamma: f32 = mix(1.0, 1.0 / 2.2, luma);
3219
- var coverage: f32 = pow(shapeColor.a * alpha, gamma);
3220
-
3221
- return coverage;
3222
-
3223
- }
3224
- `
3225
- )
3226
- }
3227
- }, Ur = {
3228
- name: "msdf-bit",
3229
- fragment: {
3230
- header: (
3231
- /* glsl */
3232
- `
3233
- float calculateMSDFAlpha(vec4 msdfColor, vec4 shapeColor, float distance) {
3234
-
3235
- // MSDF
3236
- float median = msdfColor.r + msdfColor.g + msdfColor.b -
3237
- min(msdfColor.r, min(msdfColor.g, msdfColor.b)) -
3238
- max(msdfColor.r, max(msdfColor.g, msdfColor.b));
3239
-
3240
- // SDF
3241
- median = min(median, msdfColor.a);
3242
-
3243
- float screenPxDistance = distance * (median - 0.5);
3244
- float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);
3245
-
3246
- if (median < 0.01) {
3247
- alpha = 0.0;
3248
- } else if (median > 0.99) {
3249
- alpha = 1.0;
3250
- }
3251
-
3252
- // Gamma correction for coverage-like alpha
3253
- float luma = dot(shapeColor.rgb, vec3(0.299, 0.587, 0.114));
3254
- float gamma = mix(1.0, 1.0 / 2.2, luma);
3255
- float coverage = pow(shapeColor.a * alpha, gamma);
3256
-
3257
- return coverage;
3258
- }
3259
- `
3260
- )
3261
- }
3262
- };
3263
- let he, de;
3264
- class zr extends ve {
3265
- constructor(e) {
3266
- const t = new Y({
3267
- uColor: { value: new Float32Array([1, 1, 1, 1]), type: "vec4<f32>" },
3268
- uTransformMatrix: { value: new U(), type: "mat3x3<f32>" },
3269
- uDistance: { value: 4, type: "f32" },
3270
- uRound: { value: 0, type: "f32" }
3271
- });
3272
- he ?? (he = Ye({
3273
- name: "sdf-shader",
3274
- bits: [
3275
- kt,
3276
- Gt(e),
3277
- Br,
3278
- Mr,
3279
- Xe
3280
- ]
3281
- })), de ?? (de = $e({
3282
- name: "sdf-shader",
3283
- bits: [
3284
- At,
3285
- Dt(e),
3286
- Rr,
3287
- Ur,
3288
- Ne
3289
- ]
3290
- })), super({
3291
- glProgram: de,
3292
- gpuProgram: he,
3293
- resources: {
3294
- localUniforms: t,
3295
- batchSamplers: Ot(e)
3296
- }
3297
- });
3298
- }
3299
- }
3300
- class kr extends It {
3301
- destroy() {
3302
- this.context.customShader && this.context.customShader.destroy(), super.destroy();
3303
- }
3304
- }
3305
- class xt {
3306
- constructor(e) {
3307
- this._renderer = e;
3308
- }
3309
- validateRenderable(e) {
3310
- const t = this._getGpuBitmapText(e);
3311
- return this._renderer.renderPipes.graphics.validateRenderable(t);
3312
- }
3313
- addRenderable(e, t) {
3314
- const r = this._getGpuBitmapText(e);
3315
- We(e, r), e._didTextUpdate && (e._didTextUpdate = !1, this._updateContext(e, r)), this._renderer.renderPipes.graphics.addRenderable(r, t), r.context.customShader && this._updateDistanceField(e);
3316
- }
3317
- updateRenderable(e) {
3318
- const t = this._getGpuBitmapText(e);
3319
- We(e, t), this._renderer.renderPipes.graphics.updateRenderable(t), t.context.customShader && this._updateDistanceField(e);
3320
- }
3321
- _updateContext(e, t) {
3322
- const { context: r } = t, i = Qt.getFont(e.text, e._style);
3323
- r.clear(), i.distanceField.type !== "none" && (r.customShader || (r.customShader = new zr(this._renderer.limits.maxBatchableTextures)));
3324
- const n = O.graphemeSegmenter(e.text), s = e._style;
3325
- let a = i.baseLineOffset;
3326
- const u = et(n, s, i, !0), l = s.padding, h = u.scale;
3327
- let c = u.width, d = u.height + u.offsetY;
3328
- s._stroke && (c += s._stroke.width / h, d += s._stroke.width / h), r.translate(-e._anchor._x * c - l, -e._anchor._y * d - l).scale(h, h);
3329
- const f = i.applyFillAsTint ? s._fill.color : 16777215;
3330
- let x = i.fontMetrics.fontSize, _ = i.lineHeight;
3331
- s.lineHeight && (x = s.fontSize / h, _ = s.lineHeight / h);
3332
- let v = (_ - x) / 2;
3333
- v - i.baseLineOffset < 0 && (v = 0);
3334
- for (let g = 0; g < u.lines.length; g++) {
3335
- const b = u.lines[g];
3336
- for (let m = 0; m < b.charPositions.length; m++) {
3337
- const T = b.chars[m], S = i.chars[T];
3338
- if (S != null && S.texture) {
3339
- const B = S.texture;
3340
- r.texture(
3341
- B,
3342
- f || "black",
3343
- Math.round(b.charPositions[m] + S.xOffset),
3344
- Math.round(a + S.yOffset + v),
3345
- B.orig.width,
3346
- B.orig.height
3347
- );
3348
- }
3349
- }
3350
- a += _;
3351
- }
3352
- }
3353
- _getGpuBitmapText(e) {
3354
- return e._gpuData[this._renderer.uid] || this.initGpuText(e);
3355
- }
3356
- initGpuText(e) {
3357
- const t = new kr();
3358
- return e._gpuData[this._renderer.uid] = t, this._updateContext(e, t), t;
3359
- }
3360
- _updateDistanceField(e) {
3361
- const t = this._getGpuBitmapText(e).context, r = e._style.fontFamily, i = G.get(`${r}-bitmap`), { a: n, b: s, c: a, d: u } = e.groupTransform, l = Math.sqrt(n * n + s * s), h = Math.sqrt(a * a + u * u), c = (Math.abs(l) + Math.abs(h)) / 2, d = i.baseRenderedFontSize / e._style.fontSize, f = c * i.distanceField.range * (1 / d);
3362
- t.customShader.resources.localUniforms.uniforms.uDistance = f;
3363
- }
3364
- destroy() {
3365
- this._renderer = null;
3366
- }
3367
- }
3368
- xt.extension = {
3369
- type: [
3370
- y.WebGLPipes,
3371
- y.WebGPUPipes,
3372
- y.CanvasPipes
3373
- ],
3374
- name: "bitmapText"
3375
- };
3376
- function We(o, e) {
3377
- e.groupTransform = o.groupTransform, e.groupColorAlpha = o.groupColorAlpha, e.groupColor = o.groupColor, e.groupBlendMode = o.groupBlendMode, e.globalDisplayStatus = o.globalDisplayStatus, e.groupTransform = o.groupTransform, e.localDisplayStatus = o.localDisplayStatus, e.groupAlpha = o.groupAlpha, e._roundPixels = o._roundPixels;
3378
- }
3379
- class Gr extends Ke {
3380
- /**
3381
- * Creates an instance of BatchableHTMLText.
3382
- * @param renderer - The renderer instance to be used.
3383
- */
3384
- constructor(e) {
3385
- super(), this.generatingTexture = !1, this.currentKey = "--", this._renderer = e, e.runners.resolutionChange.add(this);
3386
- }
3387
- /** Handles resolution changes for the HTML text. If the text has auto resolution enabled, it triggers a view update. */
3388
- resolutionChange() {
3389
- const e = this.renderable;
3390
- e._autoResolution && e.onViewUpdate();
3391
- }
3392
- /** Destroys the BatchableHTMLText instance. Returns the texture promise to the renderer and cleans up references. */
3393
- destroy() {
3394
- const { htmlText: e } = this._renderer;
3395
- e.getReferenceCount(this.currentKey) === null ? e.returnTexturePromise(this.texturePromise) : e.decreaseReferenceCount(this.currentKey), this._renderer.runners.resolutionChange.remove(this), this.texturePromise = null, this._renderer = null;
3396
- }
3397
- }
3398
- function ge(o, e) {
3399
- const { texture: t, bounds: r } = o, i = e._style._getFinalPadding();
3400
- Wt(r, e._anchor, t);
3401
- const n = e._anchor._x * i * 2, s = e._anchor._y * i * 2;
3402
- r.minX -= i - n, r.minY -= i - s, r.maxX -= i - n, r.maxY -= i - s;
3403
- }
3404
- class _t {
3405
- constructor(e) {
3406
- this._renderer = e;
3407
- }
3408
- validateRenderable(e) {
3409
- const t = this._getGpuText(e), r = e.styleKey;
3410
- return t.currentKey !== r;
3411
- }
3412
- addRenderable(e, t) {
3413
- const r = this._getGpuText(e);
3414
- if (e._didTextUpdate) {
3415
- const i = e._autoResolution ? this._renderer.resolution : e.resolution;
3416
- (r.currentKey !== e.styleKey || e.resolution !== i) && this._updateGpuText(e).catch((n) => {
3417
- console.error(n);
3418
- }), e._didTextUpdate = !1, ge(r, e);
3419
- }
3420
- this._renderer.renderPipes.batch.addToBatch(r, t);
3421
- }
3422
- updateRenderable(e) {
3423
- const t = this._getGpuText(e);
3424
- t._batcher.updateElement(t);
3425
- }
3426
- async _updateGpuText(e) {
3427
- e._didTextUpdate = !1;
3428
- const t = this._getGpuText(e);
3429
- if (t.generatingTexture)
3430
- return;
3431
- const r = t.texturePromise;
3432
- t.texturePromise = null, t.generatingTexture = !0, e._resolution = e._autoResolution ? this._renderer.resolution : e.resolution;
3433
- let i = this._renderer.htmlText.getTexturePromise(e);
3434
- r && (i = i.finally(() => {
3435
- this._renderer.htmlText.decreaseReferenceCount(t.currentKey), this._renderer.htmlText.returnTexturePromise(r);
3436
- })), t.texturePromise = i, t.currentKey = e.styleKey, t.texture = await i;
3437
- const n = e.renderGroup || e.parentRenderGroup;
3438
- n && (n.structureDidChange = !0), t.generatingTexture = !1, ge(t, e);
3439
- }
3440
- _getGpuText(e) {
3441
- return e._gpuData[this._renderer.uid] || this.initGpuText(e);
3442
- }
3443
- initGpuText(e) {
3444
- const t = new Gr(this._renderer);
3445
- return t.renderable = e, t.transform = e.groupTransform, t.texture = M.EMPTY, t.bounds = { minX: 0, maxX: 1, minY: 0, maxY: 0 }, t.roundPixels = this._renderer._roundPixels | e._roundPixels, e._resolution = e._autoResolution ? this._renderer.resolution : e.resolution, e._gpuData[this._renderer.uid] = t, t;
3446
- }
3447
- destroy() {
3448
- this._renderer = null;
3449
- }
3450
- }
3451
- _t.extension = {
3452
- type: [
3453
- y.WebGLPipes,
3454
- y.WebGPUPipes,
3455
- y.CanvasPipes
3456
- ],
3457
- name: "htmlText"
3458
- };
3459
- function Ar() {
3460
- const { userAgent: o } = H.get().getNavigator();
3461
- return /^((?!chrome|android).)*safari/i.test(o);
3462
- }
3463
- const Dr = new Ve();
3464
- function vt(o, e, t, r) {
3465
- const i = Dr;
3466
- i.minX = 0, i.minY = 0, i.maxX = o.width / r | 0, i.maxY = o.height / r | 0;
3467
- const n = A.getOptimalTexture(
3468
- i.width,
3469
- i.height,
3470
- r,
3471
- !1
3472
- );
3473
- return n.source.uploadMethodId = "image", n.source.resource = o, n.source.alphaMode = "premultiply-alpha-on-upload", n.frame.width = e / r, n.frame.height = t / r, n.source.emit("update", n.source), n.updateUvs(), n;
3474
- }
3475
- function Or(o, e) {
3476
- const t = e.fontFamily, r = [], i = {}, n = /font-family:([^;"\s]+)/g, s = o.match(n);
3477
- function a(u) {
3478
- i[u] || (r.push(u), i[u] = !0);
3479
- }
3480
- if (Array.isArray(t))
3481
- for (let u = 0; u < t.length; u++)
3482
- a(t[u]);
3483
- else
3484
- a(t);
3485
- s && s.forEach((u) => {
3486
- const l = u.split(":")[1].trim();
3487
- a(l);
3488
- });
3489
- for (const u in e.tagStyles) {
3490
- const l = e.tagStyles[u].fontFamily;
3491
- a(l);
3492
- }
3493
- return r;
3494
- }
3495
- async function Ir(o) {
3496
- const t = await (await H.get().fetch(o)).blob(), r = new FileReader();
3497
- return await new Promise((n, s) => {
3498
- r.onloadend = () => n(r.result), r.onerror = s, r.readAsDataURL(t);
3499
- });
3500
- }
3501
- async function Wr(o, e) {
3502
- const t = await Ir(e);
3503
- return `@font-face {
3504
- font-family: "${o.fontFamily}";
3505
- font-weight: ${o.fontWeight};
3506
- font-style: ${o.fontStyle};
3507
- src: url('${t}');
3508
- }`;
3509
- }
3510
- const fe = /* @__PURE__ */ new Map();
3511
- async function Lr(o) {
3512
- const e = o.filter((t) => G.has(`${t}-and-url`)).map((t) => {
3513
- if (!fe.has(t)) {
3514
- const { entries: r } = G.get(`${t}-and-url`), i = [];
3515
- r.forEach((n) => {
3516
- const s = n.url, u = n.faces.map((l) => ({ weight: l.weight, style: l.style }));
3517
- i.push(
3518
- ...u.map(
3519
- (l) => Wr(
3520
- {
3521
- fontWeight: l.weight,
3522
- fontStyle: l.style,
3523
- fontFamily: t
3524
- },
3525
- s
3526
- )
3527
- )
3528
- );
3529
- }), fe.set(
3530
- t,
3531
- Promise.all(i).then((n) => n.join(`
3532
- `))
3533
- );
3534
- }
3535
- return fe.get(t);
3536
- });
3537
- return (await Promise.all(e)).join(`
3538
- `);
3539
- }
3540
- function Er(o, e, t, r, i) {
3541
- const { domElement: n, styleElement: s, svgRoot: a } = i;
3542
- n.innerHTML = `<style>${e.cssStyle}</style><div style='padding:0;'>${o}</div>`, n.setAttribute("style", `transform: scale(${t});transform-origin: top left; display: inline-block`), s.textContent = r;
3543
- const { width: u, height: l } = i.image;
3544
- return a.setAttribute("width", u.toString()), a.setAttribute("height", l.toString()), new XMLSerializer().serializeToString(a);
3545
- }
3546
- function Hr(o, e) {
3547
- const t = X.getOptimalCanvasAndContext(
3548
- o.width,
3549
- o.height,
3550
- e
3551
- ), { context: r } = t;
3552
- return r.clearRect(0, 0, o.width, o.height), r.drawImage(o, 0, 0), t;
3553
- }
3554
- function Vr(o, e, t) {
3555
- return new Promise(async (r) => {
3556
- t && await new Promise((i) => setTimeout(i, 100)), o.onload = () => {
3557
- r();
3558
- }, o.src = `data:image/svg+xml;charset=utf8,${encodeURIComponent(e)}`, o.crossOrigin = "anonymous";
3559
- });
3560
- }
3561
- class bt {
3562
- constructor(e) {
3563
- this._activeTextures = {}, this._renderer = e, this._createCanvas = e.type === xe.WEBGPU;
3564
- }
3565
- /**
3566
- * @param options
3567
- * @deprecated Use getTexturePromise instead
3568
- */
3569
- getTexture(e) {
3570
- return this.getTexturePromise(e);
3571
- }
3572
- /**
3573
- * Increases the reference count for a texture.
3574
- * @param text - The HTMLText instance associated with the texture.
3575
- */
3576
- getManagedTexture(e) {
3577
- const t = e.styleKey;
3578
- if (this._activeTextures[t])
3579
- return this._increaseReferenceCount(t), this._activeTextures[t].promise;
3580
- const r = this._buildTexturePromise(e).then((i) => (this._activeTextures[t].texture = i, i));
3581
- return this._activeTextures[t] = {
3582
- texture: null,
3583
- promise: r,
3584
- usageCount: 1
3585
- }, r;
3586
- }
3587
- /**
3588
- * Gets the current reference count for a texture associated with a text key.
3589
- * @param textKey - The unique key identifying the text style configuration
3590
- * @returns The number of Text instances currently using this texture
3591
- */
3592
- getReferenceCount(e) {
3593
- var t;
3594
- return ((t = this._activeTextures[e]) == null ? void 0 : t.usageCount) ?? null;
3595
- }
3596
- _increaseReferenceCount(e) {
3597
- this._activeTextures[e].usageCount++;
3598
- }
3599
- /**
3600
- * Decreases the reference count for a texture.
3601
- * If the count reaches zero, the texture is cleaned up.
3602
- * @param textKey - The key associated with the HTMLText instance.
3603
- */
3604
- decreaseReferenceCount(e) {
3605
- const t = this._activeTextures[e];
3606
- t && (t.usageCount--, t.usageCount === 0 && (t.texture ? this._cleanUp(t.texture) : t.promise.then((r) => {
3607
- t.texture = r, this._cleanUp(t.texture);
3608
- }).catch(() => {
3609
- K("HTMLTextSystem: Failed to clean texture");
3610
- }), this._activeTextures[e] = null));
3611
- }
3612
- /**
3613
- * Returns a promise that resolves to a texture for the given HTMLText options.
3614
- * @param options - The options for the HTMLText.
3615
- * @returns A promise that resolves to a Texture.
3616
- */
3617
- getTexturePromise(e) {
3618
- return this._buildTexturePromise(e);
3619
- }
3620
- async _buildTexturePromise(e) {
3621
- const { text: t, style: r, resolution: i, textureStyle: n } = e, s = re.get(st), a = Or(t, r), u = await Lr(a), l = or(t, r, u, s), h = Math.ceil(Math.ceil(Math.max(1, l.width) + r.padding * 2) * i), c = Math.ceil(Math.ceil(Math.max(1, l.height) + r.padding * 2) * i), d = s.image, f = 2;
3622
- d.width = (h | 0) + f, d.height = (c | 0) + f;
3623
- const x = Er(t, r, i, u, s);
3624
- await Vr(d, x, Ar() && a.length > 0);
3625
- const _ = d;
3626
- let v;
3627
- this._createCanvas && (v = Hr(d, i));
3628
- const g = vt(
3629
- v ? v.canvas : _,
3630
- d.width - f,
3631
- d.height - f,
3632
- i
3633
- );
3634
- return n && (g.source.style = n), this._createCanvas && (this._renderer.texture.initSource(g.source), X.returnCanvasAndContext(v)), re.return(s), g;
3635
- }
3636
- returnTexturePromise(e) {
3637
- e.then((t) => {
3638
- this._cleanUp(t);
3639
- }).catch(() => {
3640
- K("HTMLTextSystem: Failed to clean texture");
3641
- });
3642
- }
3643
- _cleanUp(e) {
3644
- A.returnTexture(e, !0), e.source.resource = null, e.source.uploadMethodId = "unknown";
3645
- }
3646
- destroy() {
3647
- this._renderer = null;
3648
- for (const e in this._activeTextures)
3649
- this._activeTextures[e] && this.returnTexturePromise(this._activeTextures[e].promise);
3650
- this._activeTextures = null;
3651
- }
3652
- }
3653
- bt.extension = {
3654
- type: [
3655
- y.WebGLSystem,
3656
- y.WebGPUSystem,
3657
- y.CanvasSystem
3658
- ],
3659
- name: "htmlText"
3660
- };
3661
- class Yr extends Ke {
3662
- constructor(e) {
3663
- super(), this._renderer = e, e.runners.resolutionChange.add(this);
3664
- }
3665
- resolutionChange() {
3666
- const e = this.renderable;
3667
- e._autoResolution && e.onViewUpdate();
3668
- }
3669
- destroy() {
3670
- const { canvasText: e } = this._renderer;
3671
- e.getReferenceCount(this.currentKey) > 0 ? e.decreaseReferenceCount(this.currentKey) : this.texture && e.returnTexture(this.texture), this._renderer.runners.resolutionChange.remove(this), this._renderer = null;
3672
- }
3673
- }
3674
- class yt {
3675
- constructor(e) {
3676
- this._renderer = e;
3677
- }
3678
- validateRenderable(e) {
3679
- const t = this._getGpuText(e), r = e.styleKey;
3680
- return t.currentKey !== r ? !0 : e._didTextUpdate;
3681
- }
3682
- addRenderable(e, t) {
3683
- const r = this._getGpuText(e);
3684
- if (e._didTextUpdate) {
3685
- const i = e._autoResolution ? this._renderer.resolution : e.resolution;
3686
- (r.currentKey !== e.styleKey || e.resolution !== i) && this._updateGpuText(e), e._didTextUpdate = !1, ge(r, e);
3687
- }
3688
- this._renderer.renderPipes.batch.addToBatch(r, t);
3689
- }
3690
- updateRenderable(e) {
3691
- const t = this._getGpuText(e);
3692
- t._batcher.updateElement(t);
3693
- }
3694
- _updateGpuText(e) {
3695
- const t = this._getGpuText(e);
3696
- t.texture && this._renderer.canvasText.decreaseReferenceCount(t.currentKey), e._resolution = e._autoResolution ? this._renderer.resolution : e.resolution, t.texture = this._renderer.canvasText.getManagedTexture(e), t.currentKey = e.styleKey;
3697
- }
3698
- _getGpuText(e) {
3699
- return e._gpuData[this._renderer.uid] || this.initGpuText(e);
3700
- }
3701
- initGpuText(e) {
3702
- const t = new Yr(this._renderer);
3703
- return t.currentKey = "--", t.renderable = e, t.transform = e.groupTransform, t.bounds = { minX: 0, maxX: 1, minY: 0, maxY: 0 }, t.roundPixels = this._renderer._roundPixels | e._roundPixels, e._gpuData[this._renderer.uid] = t, t;
3704
- }
3705
- destroy() {
3706
- this._renderer = null;
3707
- }
3708
- }
3709
- yt.extension = {
3710
- type: [
3711
- y.WebGLPipes,
3712
- y.WebGPUPipes,
3713
- y.CanvasPipes
3714
- ],
3715
- name: "text"
3716
- };
3717
- class Tt {
3718
- constructor(e) {
3719
- this._activeTextures = {}, this._renderer = e;
3720
- }
3721
- getTexture(e, t, r, i) {
3722
- typeof e == "string" && (z("8.0.0", "CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"), e = {
3723
- text: e,
3724
- style: r,
3725
- resolution: t
3726
- }), e.style instanceof q || (e.style = new q(e.style)), e.textureStyle instanceof j || (e.textureStyle = new j(e.textureStyle)), typeof e.text != "string" && (e.text = e.text.toString());
3727
- const { text: n, style: s, textureStyle: a } = e, u = e.resolution ?? this._renderer.resolution, { frame: l, canvasAndContext: h } = ue.getCanvasAndContext({
3728
- text: n,
3729
- style: s,
3730
- resolution: u
3731
- }), c = vt(h.canvas, l.width, l.height, u);
3732
- if (a && (c.source.style = a), s.trim && (l.pad(s.padding), c.frame.copyFrom(l), c.frame.scale(1 / u), c.updateUvs()), s.filters) {
3733
- const d = this._applyFilters(c, s.filters);
3734
- return this.returnTexture(c), ue.returnCanvasAndContext(h), d;
3735
- }
3736
- return this._renderer.texture.initSource(c._source), ue.returnCanvasAndContext(h), c;
3737
- }
3738
- /**
3739
- * Returns a texture that was created wit the above `getTexture` function.
3740
- * Handy if you are done with a texture and want to return it to the pool.
3741
- * @param texture - The texture to be returned.
3742
- */
3743
- returnTexture(e) {
3744
- const t = e.source;
3745
- t.resource = null, t.uploadMethodId = "unknown", t.alphaMode = "no-premultiply-alpha", A.returnTexture(e, !0);
3746
- }
3747
- /**
3748
- * Renders text to its canvas, and updates its texture.
3749
- * @deprecated since 8.10.0
3750
- */
3751
- renderTextToCanvas() {
3752
- z(
3753
- "8.10.0",
3754
- "CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead"
3755
- );
3756
- }
3757
- /**
3758
- * Gets or creates a managed texture for a Text object. This method handles texture reuse and reference counting.
3759
- * @param text - The Text object that needs a texture
3760
- * @returns A Texture instance that represents the rendered text
3761
- * @remarks
3762
- * This method performs the following:
3763
- * 1. Sets the appropriate resolution based on auto-resolution settings
3764
- * 2. Checks if a texture already exists for the text's style
3765
- * 3. Creates a new texture if needed or returns an existing one
3766
- * 4. Manages reference counting for texture reuse
3767
- */
3768
- getManagedTexture(e) {
3769
- e._resolution = e._autoResolution ? this._renderer.resolution : e.resolution;
3770
- const t = e.styleKey;
3771
- if (this._activeTextures[t])
3772
- return this._increaseReferenceCount(t), this._activeTextures[t].texture;
3773
- const r = this.getTexture({
3774
- text: e.text,
3775
- style: e.style,
3776
- resolution: e._resolution,
3777
- textureStyle: e.textureStyle
3778
- });
3779
- return this._activeTextures[t] = {
3780
- texture: r,
3781
- usageCount: 1
3782
- }, r;
3783
- }
3784
- /**
3785
- * Decreases the reference count for a texture associated with a text key.
3786
- * When the reference count reaches zero, the texture is returned to the pool.
3787
- * @param textKey - The unique key identifying the text style configuration
3788
- * @remarks
3789
- * This method is crucial for memory management, ensuring textures are properly
3790
- * cleaned up when they are no longer needed by any Text instances.
3791
- */
3792
- decreaseReferenceCount(e) {
3793
- const t = this._activeTextures[e];
3794
- t.usageCount--, t.usageCount === 0 && (this.returnTexture(t.texture), this._activeTextures[e] = null);
3795
- }
3796
- /**
3797
- * Gets the current reference count for a texture associated with a text key.
3798
- * @param textKey - The unique key identifying the text style configuration
3799
- * @returns The number of Text instances currently using this texture
3800
- */
3801
- getReferenceCount(e) {
3802
- var t;
3803
- return ((t = this._activeTextures[e]) == null ? void 0 : t.usageCount) ?? 0;
3804
- }
3805
- _increaseReferenceCount(e) {
3806
- this._activeTextures[e].usageCount++;
3807
- }
3808
- /**
3809
- * Applies the specified filters to the given texture.
3810
- *
3811
- * This method takes a texture and a list of filters, applies the filters to the texture,
3812
- * and returns the resulting texture. It also ensures that the alpha mode of the resulting
3813
- * texture is set to 'premultiplied-alpha'.
3814
- * @param {Texture} texture - The texture to which the filters will be applied.
3815
- * @param {Filter[]} filters - The filters to apply to the texture.
3816
- * @returns {Texture} The resulting texture after all filters have been applied.
3817
- */
3818
- _applyFilters(e, t) {
3819
- const r = this._renderer.renderTarget.renderTarget, i = this._renderer.filter.generateFilteredTexture({
3820
- texture: e,
3821
- filters: t
3822
- });
3823
- return this._renderer.renderTarget.bind(r, !1), i;
3824
- }
3825
- destroy() {
3826
- this._renderer = null;
3827
- for (const e in this._activeTextures)
3828
- this._activeTextures[e] && this.returnTexture(this._activeTextures[e].texture);
3829
- this._activeTextures = null;
3830
- }
3831
- }
3832
- Tt.extension = {
3833
- type: [
3834
- y.WebGLSystem,
3835
- y.WebGPUSystem,
3836
- y.CanvasSystem
3837
- ],
3838
- name: "canvasText"
3839
- };
3840
- P.add(je);
3841
- P.add(qe);
3842
- P.add(at);
3843
- P.add(Lt);
3844
- P.add(lt);
3845
- P.add(ht);
3846
- P.add(dt);
3847
- P.add(Tt);
3848
- P.add(yt);
3849
- P.add(xt);
3850
- P.add(bt);
3851
- P.add(_t);
3852
- P.add(mt);
3853
- P.add(gt);
3854
- P.add(rt);
3855
- P.add(tt);
3856
- //# sourceMappingURL=webworkerAll-pikqGfAy.js.map