pixi-silk 1.0.2 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,4 @@
1
+ import { silkGl1 } from "../shader-slot.js";
1
2
  import { sdfFromAlpha } from "./edt.js";
2
3
  import { BufferImageSource, DOMAdapter } from "pixi.js";
3
4
  //#region src/text/atlas.ts
@@ -9,6 +10,43 @@ const NO_INK = {
9
10
  w: 0,
10
11
  h: 0
11
12
  };
13
+ /** Width of the colour texture in texels. */
14
+ const COLOR_WIDTH = 512;
15
+ /** Starting height of the colour texture. */
16
+ const COLOR_START = 16;
17
+ /** True when some inked pixel of the box is not black: the glyph comes from a colour font. */
18
+ function hasColor(pixels, w, x0, y0, x1, y1) {
19
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
20
+ const i = (y * w + x) * 4;
21
+ if (pixels[i + 3] > 32 && pixels[i] + pixels[i + 1] + pixels[i + 2] > 48) return true;
22
+ }
23
+ return false;
24
+ }
25
+ /** Object replacement character: stands for inline objects, never baked. */
26
+ const OBJECT = "";
27
+ /** The rows and columns that hold ink in RGBA pixels, as a half-open box, or null when there is none. */
28
+ function inkBox(pixels, w, h) {
29
+ let x0 = w;
30
+ let y0 = h;
31
+ let x1 = 0;
32
+ let y1 = 0;
33
+ for (let y = 0; y < h; y++) {
34
+ const row = y * w * 4;
35
+ for (let x = 0; x < w; x++) {
36
+ if (pixels[row + x * 4 + 3] === 0) continue;
37
+ if (x < x0) x0 = x;
38
+ if (x >= x1) x1 = x + 1;
39
+ if (y < y0) y0 = y;
40
+ y1 = y + 1;
41
+ }
42
+ }
43
+ return x1 > x0 && y1 > y0 ? {
44
+ x0,
45
+ y0,
46
+ x1,
47
+ y1
48
+ } : null;
49
+ }
12
50
  /** CSS `font` shorthand for a spec at a size. */
13
51
  function fontString(font, size) {
14
52
  return `${font.style ?? "normal"} ${font.weight ?? 400} ${size}px ${font.family}`;
@@ -43,6 +81,12 @@ var SdfAtlas = class SdfAtlas {
43
81
  version = 0;
44
82
  _data;
45
83
  _source;
84
+ _cData;
85
+ _cSource;
86
+ _cHeight = COLOR_START;
87
+ _cShelves = [];
88
+ _cNextY = 0;
89
+ _cDirty = false;
46
90
  _shaders = /* @__PURE__ */ new Set();
47
91
  _height;
48
92
  _width;
@@ -64,6 +108,19 @@ var SdfAtlas = class SdfAtlas {
64
108
  this._data = new Uint8Array(this._width * this._height);
65
109
  this._ctx = options.context ?? null;
66
110
  this._source = this._createSource();
111
+ this._cData = new Uint8Array(COLOR_WIDTH * this._cHeight * 4);
112
+ this._cSource = this._createColorSource();
113
+ }
114
+ /**
115
+ * The RGBA texture with the colours of colour glyphs (emoji), premultiplied. It starts small and
116
+ * grows like {@link SdfAtlas.source}. Read it again after {@link SdfAtlas.flush}.
117
+ */
118
+ get colorSource() {
119
+ return this._cSource;
120
+ }
121
+ /** How full the atlas is, 0 to 1: the share of its largest texture that holds glyphs. Near 1 it will start over soon. */
122
+ get usage() {
123
+ return Math.min(1, this._nextY / this._maxHeight);
67
124
  }
68
125
  /**
69
126
  * The R8 texture with every glyph. When the atlas grows it moves to a new, taller texture, and
@@ -80,6 +137,9 @@ var SdfAtlas = class SdfAtlas {
80
137
  this._shaders.add(shader);
81
138
  shader.resources.uAtlas = this._source;
82
139
  shader.resources.uAtlasSampler = this._source.style;
140
+ shader.resources.uColorAtlas = this._cSource;
141
+ shader.resources.uColorSampler = this._cSource.style;
142
+ silkGl1.hooks?.syncSizes(shader);
83
143
  }
84
144
  /** @internal Stops updating a shader passed to {@link SdfAtlas.track}. */
85
145
  untrack(shader) {
@@ -93,7 +153,7 @@ var SdfAtlas = class SdfAtlas {
93
153
  metrics(font) {
94
154
  return this._font(font).metrics;
95
155
  }
96
- /** Advance width of one character at {@link SdfAtlas.size}, from `measureText`. */
156
+ /** Advance width of one character, or of a run of joined letters, at {@link SdfAtlas.size}, from `measureText`. */
97
157
  advance(font, char) {
98
158
  const entry = this._font(font);
99
159
  let w = entry.advances.get(char);
@@ -115,7 +175,10 @@ var SdfAtlas = class SdfAtlas {
115
175
  }
116
176
  return k;
117
177
  }
118
- /** The baked glyph of a character, baking it now if needed. Call {@link SdfAtlas.flush} to upload. */
178
+ /**
179
+ * The baked glyph of a character, or of a cluster (a base with its marks, a run of joined Arabic
180
+ * letters), baking it now if needed. Call {@link SdfAtlas.flush} to upload.
181
+ */
119
182
  glyph(font, char) {
120
183
  const entry = this._font(font);
121
184
  let g = entry.glyphs.get(char);
@@ -125,8 +188,49 @@ var SdfAtlas = class SdfAtlas {
125
188
  }
126
189
  return g;
127
190
  }
191
+ /**
192
+ * The box `measureText` reports for a string at {@link SdfAtlas.size}: its ink above and below
193
+ * the baseline, and its advance. Nothing is baked. Stacked marks may reach past it, see
194
+ * {@link SdfAtlas.ink} for the exact ink of one glyph.
195
+ */
196
+ measure(font, text) {
197
+ const m = this._context(this._font(font).css).measureText(text);
198
+ return {
199
+ ascent: m.actualBoundingBoxAscent,
200
+ descent: m.actualBoundingBoxDescent,
201
+ width: m.width
202
+ };
203
+ }
204
+ /**
205
+ * Where a glyph's ink reaches, from its baked pixels, at {@link SdfAtlas.size}: up from the
206
+ * baseline (`ascent`) and down from it (`descent`). Zero for glyphs with no ink. Bakes the glyph.
207
+ */
208
+ ink(font, char) {
209
+ const g = this.glyph(font, char);
210
+ if (g.w === 0) return {
211
+ ascent: 0,
212
+ descent: 0
213
+ };
214
+ return {
215
+ ascent: -(g.top + this.pad),
216
+ descent: g.top + g.h - this.pad
217
+ };
218
+ }
128
219
  /** Uploads the texture if glyphs were baked since the last call. */
129
220
  flush() {
221
+ if (this._cDirty) {
222
+ this._cDirty = false;
223
+ if (this._cSource.resource !== this._cData) {
224
+ const old = this._cSource;
225
+ this._cSource = this._createColorSource();
226
+ for (const shader of this._shaders) {
227
+ shader.resources.uColorAtlas = this._cSource;
228
+ shader.resources.uColorSampler = this._cSource.style;
229
+ silkGl1.hooks?.syncSizes(shader);
230
+ }
231
+ setTimeout(() => old.destroy(), 0);
232
+ } else this._cSource.update();
233
+ }
130
234
  if (!this._dirty) return;
131
235
  this._dirty = false;
132
236
  if (this._source.resource !== this._data) {
@@ -135,6 +239,7 @@ var SdfAtlas = class SdfAtlas {
135
239
  for (const shader of this._shaders) {
136
240
  shader.resources.uAtlas = this._source;
137
241
  shader.resources.uAtlasSampler = this._source.style;
242
+ silkGl1.hooks?.syncSizes(shader);
138
243
  }
139
244
  setTimeout(() => old.destroy(), 0);
140
245
  return;
@@ -147,7 +252,11 @@ var SdfAtlas = class SdfAtlas {
147
252
  this._shelves = [];
148
253
  this._nextY = 0;
149
254
  this._data.fill(0);
255
+ this._cShelves = [];
256
+ this._cNextY = 0;
257
+ this._cData.fill(0);
150
258
  this._dirty = true;
259
+ this._cDirty = true;
151
260
  this.version++;
152
261
  }
153
262
  /** Frees the texture. */
@@ -155,6 +264,7 @@ var SdfAtlas = class SdfAtlas {
155
264
  this._fonts.clear();
156
265
  this._shaders.clear();
157
266
  this._source.destroy();
267
+ this._cSource.destroy();
158
268
  if (SdfAtlas._shared === this) SdfAtlas._shared = null;
159
269
  }
160
270
  _createSource() {
@@ -170,6 +280,51 @@ var SdfAtlas = class SdfAtlas {
170
280
  label: "silk-text-atlas"
171
281
  });
172
282
  }
283
+ _createColorSource() {
284
+ return new BufferImageSource({
285
+ resource: this._cData,
286
+ width: COLOR_WIDTH,
287
+ height: this._cHeight,
288
+ format: "rgba8unorm",
289
+ alphaMode: "premultiplied-alpha",
290
+ scaleMode: "linear",
291
+ addressMode: "clamp-to-edge",
292
+ autoGenerateMipmaps: false,
293
+ label: "silk-text-colors"
294
+ });
295
+ }
296
+ /** Shelf packing in the colour texture, which grows to {@link SdfAtlas} `maxHeight` like the other. */
297
+ _placeColor(w, h) {
298
+ if (w > COLOR_WIDTH) return null;
299
+ for (const shelf of this._cShelves) if (h <= shelf.h && h >= shelf.h * .7 && shelf.x + w <= COLOR_WIDTH) {
300
+ const x = shelf.x;
301
+ shelf.x += w + 1;
302
+ return {
303
+ x,
304
+ y: shelf.y
305
+ };
306
+ }
307
+ while (this._cNextY + h > this._cHeight) {
308
+ if (this._cHeight >= this._maxHeight) return null;
309
+ const height = Math.min(this._maxHeight, this._cHeight * 2);
310
+ const data = new Uint8Array(COLOR_WIDTH * height * 4);
311
+ data.set(this._cData);
312
+ this._cData = data;
313
+ this._cHeight = height;
314
+ this._cDirty = true;
315
+ }
316
+ const shelf = {
317
+ y: this._cNextY,
318
+ h,
319
+ x: w + 1
320
+ };
321
+ this._cShelves.push(shelf);
322
+ this._cNextY += h + 1;
323
+ return {
324
+ x: 0,
325
+ y: shelf.y
326
+ };
327
+ }
173
328
  _context(css) {
174
329
  if (!this._ctx) {
175
330
  const ctx = DOMAdapter.get().createCanvas(256, 256).getContext("2d", { willReadFrequently: true });
@@ -178,6 +333,7 @@ var SdfAtlas = class SdfAtlas {
178
333
  }
179
334
  const ctx = this._ctx;
180
335
  if (ctx.font !== css) ctx.font = css;
336
+ if (ctx.direction !== void 0 && ctx.direction !== "ltr") ctx.direction = "ltr";
181
337
  return ctx;
182
338
  }
183
339
  _font(font) {
@@ -202,35 +358,65 @@ var SdfAtlas = class SdfAtlas {
202
358
  return entry;
203
359
  }
204
360
  _bake(entry, char) {
361
+ if (char.trim() === "" || char === OBJECT) return {
362
+ ...NO_INK,
363
+ left: 0,
364
+ top: 0
365
+ };
205
366
  const ctx = this._context(entry.css);
206
367
  const m = ctx.measureText(char);
207
- const left = Math.ceil(m.actualBoundingBoxLeft);
208
- const right = Math.ceil(m.actualBoundingBoxRight);
209
- const ascent = Math.ceil(m.actualBoundingBoxAscent);
210
- const descent = Math.ceil(m.actualBoundingBoxDescent);
211
368
  const pad = this.pad;
212
- const inkW = left + right;
213
- const inkH = ascent + descent;
214
- if (inkW <= 0 || inkH <= 0 || char.trim() === "") return {
369
+ let slack = Math.ceil(this.size * .5);
370
+ let found = null;
371
+ let penX = 0;
372
+ let baseY = 0;
373
+ for (let attempt = 0; attempt < 3; attempt++) {
374
+ const left = Math.max(0, Math.ceil(m.actualBoundingBoxLeft));
375
+ const right = Math.max(Math.ceil(m.actualBoundingBoxRight), Math.ceil(m.width));
376
+ const ascent = Math.max(0, Math.ceil(m.actualBoundingBoxAscent));
377
+ const descent = Math.max(0, Math.ceil(m.actualBoundingBoxDescent));
378
+ const rw = left + right + 2 * slack;
379
+ const rh = ascent + descent + 2 * slack;
380
+ const canvas = ctx.canvas;
381
+ if (canvas.width < rw || canvas.height < rh) {
382
+ canvas.width = Math.max(canvas.width, rw);
383
+ canvas.height = Math.max(canvas.height, rh);
384
+ ctx.font = entry.css;
385
+ if (ctx.direction !== void 0) ctx.direction = "ltr";
386
+ }
387
+ ctx.textBaseline = "alphabetic";
388
+ ctx.textAlign = "left";
389
+ ctx.fillStyle = "#000";
390
+ ctx.clearRect(0, 0, rw, rh);
391
+ penX = slack + left;
392
+ baseY = slack + ascent;
393
+ ctx.fillText(char, penX, baseY);
394
+ const pixels = ctx.getImageData(0, 0, rw, rh).data;
395
+ const ink = inkBox(pixels, rw, rh);
396
+ if (!ink) return {
397
+ ...NO_INK,
398
+ left: 0,
399
+ top: 0
400
+ };
401
+ found = {
402
+ ...ink,
403
+ pixels,
404
+ rw
405
+ };
406
+ if (ink.x0 > 0 && ink.y0 > 0 && ink.x1 < rw && ink.y1 < rh) break;
407
+ slack *= 2;
408
+ }
409
+ if (!found) return {
215
410
  ...NO_INK,
216
411
  left: 0,
217
412
  top: 0
218
413
  };
219
- const w = inkW + 2 * pad;
220
- const h = inkH + 2 * pad;
221
- const canvas = ctx.canvas;
222
- if (canvas.width < w || canvas.height < h) {
223
- canvas.width = Math.max(canvas.width, w);
224
- canvas.height = Math.max(canvas.height, h);
225
- ctx.font = entry.css;
226
- }
227
- ctx.textBaseline = "alphabetic";
228
- ctx.textAlign = "left";
229
- ctx.fillStyle = "#000";
230
- ctx.clearRect(0, 0, w, h);
231
- ctx.fillText(char, pad + left, pad + ascent);
232
- const pixels = ctx.getImageData(0, 0, w, h).data;
233
- const field = sdfFromAlpha(pixels, w, h, this.radius, this.cutoff, 4);
414
+ const { x0, y0, x1, y1, pixels, rw } = found;
415
+ const w = x1 - x0 + 2 * pad;
416
+ const h = y1 - y0 + 2 * pad;
417
+ const cell = new Uint8Array(w * h);
418
+ for (let row = y0; row < y1; row++) for (let col = x0; col < x1; col++) cell[(row - y0 + pad) * w + col - x0 + pad] = pixels[(row * rw + col) * 4 + 3];
419
+ const field = sdfFromAlpha(cell, w, h, this.radius, this.cutoff, 1);
234
420
  let at = this._place(w, h);
235
421
  if (!at) {
236
422
  console.warn("[pixi-silk] SilkText atlas is full; starting over with the glyphs in use");
@@ -248,14 +434,32 @@ var SdfAtlas = class SdfAtlas {
248
434
  const W = this._width;
249
435
  for (let row = 0; row < h; row++) data.set(field.subarray(row * w, row * w + w), (at.y + row) * W + at.x);
250
436
  this._dirty = true;
251
- return {
437
+ const glyph = {
252
438
  x: at.x,
253
439
  y: at.y,
254
440
  w,
255
441
  h,
256
- left: -(left + pad),
257
- top: -(ascent + pad)
442
+ left: x0 - pad - penX,
443
+ top: y0 - pad - baseY
258
444
  };
445
+ if (hasColor(pixels, rw, x0, y0, x1, y1)) {
446
+ const c = this._placeColor(w, h);
447
+ if (c) {
448
+ const cd = this._cData;
449
+ for (let row = y0; row < y1; row++) for (let col = x0; col < x1; col++) {
450
+ const src = (row * rw + col) * 4;
451
+ const dst = ((c.y + row - y0 + pad) * COLOR_WIDTH + c.x + col - x0 + pad) * 4;
452
+ const a = pixels[src + 3];
453
+ cd[dst] = pixels[src] * a / 255;
454
+ cd[dst + 1] = pixels[src + 1] * a / 255;
455
+ cd[dst + 2] = pixels[src + 2] * a / 255;
456
+ cd[dst + 3] = a;
457
+ }
458
+ this._cDirty = true;
459
+ glyph.color = c;
460
+ }
461
+ }
462
+ return glyph;
259
463
  }
260
464
  /** Shelf packing: rows of similar height, left to right. Grows the texture, or null when it cannot. */
261
465
  _place(w, h) {
@@ -0,0 +1,36 @@
1
+ //#region src/text/bidi.d.ts
2
+ /**
3
+ * Bidirectional text for {@link layoutText}: the Unicode Bidirectional Algorithm (UAX #9).
4
+ *
5
+ * Covered: paragraph direction (P2, P3), and embeddings, overrides and isolates (X1 to X10, U+202A
6
+ * to U+202E and U+2066 to U+2069). Also weak types (W1 to W7), bracket pairs (N0), neutrals (N1,
7
+ * N2), implicit levels (I1, I2), trailing whitespace (L1), reordering (L2) and mirrored brackets (L4).
8
+ */
9
+ /** Base direction of a paragraph. `auto` takes it from the first strong character, left to right when there is none. */
10
+ export type TextDirection = "ltr" | "rtl" | "auto";
11
+ /** Bidi character types used here (UAX #9 table 4, minus the explicit formatting types). */
12
+ export type BidiClass = "L" | "R" | "AL" | "EN" | "ES" | "ET" | "AN" | "CS" | "NSM" | "BN" | "B" | "S" | "WS" | "ON" | "LRE" | "RLE" | "LRO" | "RLO" | "PDF" | "LRI" | "RLI" | "FSI" | "PDI";
13
+ /** The bidi type of one code point. Covers the common scripts. Anything unlisted is `L`, or `ON` for punctuation and symbols. */
14
+ export declare function bidiClass(cp: number): BidiClass;
15
+ /** True when the text holds a right-to-left character or a bidi control, so it needs the bidi pass. */
16
+ export declare function hasRtl(text: string): boolean;
17
+ /** Paragraph level from the first strong type (P2, P3): 1 for `R` or `AL`, 0 for `L` or none. Text inside isolates is skipped. */
18
+ export declare function paragraphLevel(types: readonly BidiClass[], direction?: TextDirection): 0 | 1;
19
+ /**
20
+ * Embedding levels of one paragraph, one per unit, in logical order (UAX #9 rules X1 to X10, W1 to
21
+ * W7, N0 to N2, I1 and I2). `types` are the original types. `chars` are the units' text, used to
22
+ * pair brackets (N0). Even levels run left to right, odd ones right to left. Embedding controls and
23
+ * boundary neutrals take the level of the unit before them.
24
+ */
25
+ export declare function resolveLevels(types: readonly BidiClass[], level: 0 | 1, chars?: readonly string[]): number[];
26
+ /**
27
+ * L1 for one line: whitespace and isolate controls at the end of the line, and before tabs, fall
28
+ * back to the paragraph level. `types` are the original types of the line's units. Changes
29
+ * `levels` in place.
30
+ */
31
+ export declare function resetWhitespace(types: readonly BidiClass[], levels: number[], level: number): void;
32
+ /** L2: the visual order of a line as indices into `levels`, left to right. */
33
+ export declare function visualOrder(levels: readonly number[]): number[];
34
+ /** L4: the mirrored form of a character drawn right to left, such as `)` for `(`, or the character itself. */
35
+ export declare function mirror(char: string): string;
36
+ //#endregion