@moku-labs/game 0.15.144 → 0.15.145

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.
@@ -16,13 +16,26 @@ import { MaxRectsBin, MaxRectsPacker } from "maxrects-packer";
16
16
  const PAGE_SIZE = 2048;
17
17
  /**
18
18
  * The size `maxrects-packer` is given (F188). It lets a bin grow to its size plus the padding, so a
19
- * packer of `PAGE_SIZE` wrote 2050 px pages; one of `PAGE_SIZE - PADDING` never passes
20
- * `PAGE_SIZE`, and holds a frame of up to `PAGE_SIZE - PADDING - 2 × BORDER` per side.
19
+ * packer of `PAGE_SIZE` wrote 2050 px pages; one of `PAGE_SIZE - PADDING` never passes `PAGE_SIZE`.
21
20
  */
22
21
  const PACKER_SIZE = 2046;
23
- /** The largest side of a frame a page holds: 2042 px. */
22
+ /** The largest side of a frame a page holds, inside its border: 2042 px. */
24
23
  const ROOM = 2042;
25
24
  /**
25
+ * Tells whether a member fits a page: both sides at most `ROOM`.
26
+ *
27
+ * @param member - The member.
28
+ * @returns True when a page holds it with its border.
29
+ * @example
30
+ * ```ts
31
+ * fitsPage({ key: "ui.dot", width: 8, height: 8 }); // true
32
+ * fitsPage({ key: "ui.sky", width: 4096, height: 64 }); // false
33
+ * ```
34
+ */
35
+ function fitsPage(member) {
36
+ return member.width <= ROOM && member.height <= ROOM;
37
+ }
38
+ /**
26
39
  * Compares two members the way the packer likes them: the longest side first, a larger area
27
40
  * next, the key last, so the same members give the same layout in any input order.
28
41
  *
@@ -34,17 +47,14 @@ function packingOrder(left, right) {
34
47
  return Math.max(right.width, right.height) - Math.max(left.width, left.height) || right.width * right.height - left.width * left.height || left.key.localeCompare(right.key);
35
48
  }
36
49
  /**
37
- * Tells whether a texture fits a page at all, inside the border.
50
+ * Compares two members by key.
38
51
  *
39
- * @param member - The texture.
40
- * @returns True when both sides fit.
41
- * @example
42
- * ```ts
43
- * fitsPage({ key: "ui.fx-rays", width: 504, height: 512 }); // true
44
- * ```
52
+ * @param left - One member.
53
+ * @param right - Another member.
54
+ * @returns The sort order.
45
55
  */
46
- function fitsPage(member) {
47
- return member.width <= ROOM && member.height <= ROOM;
56
+ function byKey$1(left, right) {
57
+ return left.key.localeCompare(right.key);
48
58
  }
49
59
  /**
50
60
  * Reads the frames of one bin of the packer, sorted by key.
@@ -58,13 +68,14 @@ function framesOf(rects) {
58
68
  x: rect.x,
59
69
  y: rect.y,
60
70
  width: rect.width,
61
- height: rect.height
71
+ height: rect.height,
72
+ ...rect.data.trim
62
73
  })).toSorted((left, right) => left.key.localeCompare(right.key));
63
74
  }
64
75
  /**
65
76
  * Names every texture that fits no page, one sentence each, sorted by key.
66
77
  *
67
- * @param members - The textures of a group.
78
+ * @param members - The textures that do not fit.
68
79
  * @returns One problem per texture that is too large.
69
80
  * @example
70
81
  * ```ts
@@ -72,26 +83,28 @@ function framesOf(rects) {
72
83
  * ```
73
84
  */
74
85
  function unfitProblems(members) {
75
- return members.filter((member) => !fitsPage(member)).toSorted((left, right) => left.key.localeCompare(right.key)).map((member) => `the texture "${member.key}" (${member.width}×${member.height}) fits no ${PAGE_SIZE}×${PAGE_SIZE} page with its 2 px border and 2 px padding.`);
86
+ return members.toSorted(byKey$1).map((member) => `the texture "${member.key}" (${member.width}×${member.height}) fits no ${PAGE_SIZE}×${PAGE_SIZE} page with its 2 px border and 2 px padding.`);
76
87
  }
77
88
  /**
78
- * Lays the members of one atlas group out on pages of at most 2048 × 2048 pixels: 2 px of
79
- * padding between frames and a 2 px border, never trimmed and never rotated, so every frame keeps
80
- * the size of its source and a nine-slice keeps its borders. A texture that fits no page is a
81
- * problem naming its key, never a silent drop; an `fx` group that needs more than one page is a
82
- * problem naming the bundle and the count, because a particle emitter binds one page.
89
+ * Lays the members of one atlas group out on pages of at most `PAGE_SIZE` pixels per side:
90
+ * `PADDING` pixels between frames and a `BORDER` at the page edge, never rotated, so every frame
91
+ * keeps the size of its cut and a nine-slice (never trimmed) keeps its borders. A member that fits
92
+ * no page is a problem naming its key, in any group, never a silent drop: the groups keep a
93
+ * texture that large out of a `main` group (`LOOSE_SIDE`), and an `fx` texture loose would sample
94
+ * the wrong page in silence. An `fx` group that needs more than one page is a problem naming the
95
+ * bundle and the count, because a particle emitter binds one page.
83
96
  *
84
97
  * @param bundle - Name of the bundle, for the messages.
85
98
  * @param group - The atlas group.
86
- * @param members - Its textures, with their sizes.
99
+ * @param members - Its textures, with the sizes that go on the page.
87
100
  * @returns The pages and the problems.
88
101
  * @example
89
102
  * ```ts
90
- * layoutGroup("ui", "main", [{ key: "ui.dot", width: 8, height: 8 }]).pages; // [{ width: 12, height: 12, frames: [{ key: "ui.dot", x: 2, y: 2, width: 8, height: 8 }] }]
103
+ * layoutGroup("ui", "fx", [{ key: "ui.fx-a", width: 32, height: 32 }, { key: "ui.fx-sky", width: 4096, height: 64 }]).problems; // ['the texture "ui.fx-sky" (4096×64) fits no 2048×2048 page with its 2 px border and 2 px padding.']
91
104
  * ```
92
105
  */
93
106
  function layoutGroup(bundle, group, members) {
94
- const problems = unfitProblems(members);
107
+ const problems = unfitProblems(members.filter((entry) => !fitsPage(entry)));
95
108
  const packer = new MaxRectsPacker(PACKER_SIZE, PACKER_SIZE, 2, {
96
109
  smart: true,
97
110
  pot: false,
@@ -99,7 +112,10 @@ function layoutGroup(bundle, group, members) {
99
112
  allowRotation: false,
100
113
  border: 2
101
114
  });
102
- for (const member of members.filter((entry) => fitsPage(entry)).toSorted(packingOrder)) packer.add(member.width, member.height, { key: member.key });
115
+ for (const member of members.filter((entry) => fitsPage(entry)).toSorted(packingOrder)) packer.add(member.width, member.height, {
116
+ key: member.key,
117
+ trim: member.trim
118
+ });
103
119
  const pages = packer.bins.filter((bin) => bin instanceof MaxRectsBin && bin.rects.length > 0).map((bin) => ({
104
120
  width: bin.width,
105
121
  height: bin.height,
@@ -112,7 +128,7 @@ function layoutGroup(bundle, group, members) {
112
128
  };
113
129
  }
114
130
  /** Bytes per pixel of the decoded images: RGBA, 8 bits each. */
115
- const CHANNELS = 4;
131
+ const CHANNELS$1 = 4;
116
132
  /**
117
133
  * Copies the rows of one decoded texture into the pixels of a page, then its edge pixels `EXTRUDE` out into the
118
134
  * padding around it (F105): a frame drawn at a fractional place samples its own edge there, not the page's clear
@@ -126,10 +142,10 @@ const CHANNELS = 4;
126
142
  */
127
143
  function blit(page, size, part) {
128
144
  const { pixels, x, y } = part;
129
- const rowBytes = pixels.width * CHANNELS;
145
+ const rowBytes = pixels.width * CHANNELS$1;
130
146
  for (let row = 0; row < pixels.height; row += 1) {
131
147
  const from = row * rowBytes;
132
- page.set(pixels.data.subarray(from, from + rowBytes), ((y + row) * size.width + x) * CHANNELS);
148
+ page.set(pixels.data.subarray(from, from + rowBytes), ((y + row) * size.width + x) * CHANNELS$1);
133
149
  }
134
150
  if (pixels.width === 0 || pixels.height === 0) return;
135
151
  for (let row = y - 1; row < y + pixels.height + 1; row += 1) {
@@ -139,8 +155,8 @@ function blit(page, size, part) {
139
155
  if (column < 0 || column >= size.width) continue;
140
156
  if (inner && column >= x && column < x + pixels.width) continue;
141
157
  const sourceX = Math.min(Math.max(column - x, 0), pixels.width - 1);
142
- const from = (Math.min(Math.max(row - y, 0), pixels.height - 1) * pixels.width + sourceX) * CHANNELS;
143
- page.set(pixels.data.subarray(from, from + CHANNELS), (row * size.width + column) * CHANNELS);
158
+ const from = (Math.min(Math.max(row - y, 0), pixels.height - 1) * pixels.width + sourceX) * CHANNELS$1;
159
+ page.set(pixels.data.subarray(from, from + CHANNELS$1), (row * size.width + column) * CHANNELS$1);
144
160
  }
145
161
  }
146
162
  }
@@ -158,7 +174,7 @@ function blit(page, size, part) {
158
174
  * ```
159
175
  */
160
176
  function composePage(width, height, parts) {
161
- const pixels = new Uint8Array(width * height * CHANNELS);
177
+ const pixels = new Uint8Array(width * height * CHANNELS$1);
162
178
  for (const part of parts) blit(pixels, {
163
179
  width,
164
180
  height
@@ -190,7 +206,7 @@ function encoderOf(sharp) {
190
206
  const encoded = await sharp(composePage(width, height, parts), { raw: {
191
207
  width,
192
208
  height,
193
- channels: CHANNELS
209
+ channels: CHANNELS$1
194
210
  } }).webp(webpOptions).toBuffer();
195
211
  return new Uint8Array(encoded);
196
212
  },
@@ -217,18 +233,208 @@ async function loadEncoder() {
217
233
  }
218
234
  }
219
235
  //#endregion
236
+ //#region src/plugins/assets/scan/pack/groups.ts
237
+ /**
238
+ * A `main` texture packs when both its header sides are at most this; above it stays loose: it is
239
+ * not laid out at all.
240
+ *
241
+ * F198: the A26 measured the hybrid per-group page size (1024, 2048, 4096) no better than fixed 2048
242
+ * pages (ward after one board visit: GL 378.5 vs 371.2 MB, draw calls 35 both), so pages stay 2048.
243
+ */
244
+ const LOOSE_SIDE = 1018;
245
+ /** The last segment of a key that names a particle texture starts with this. */
246
+ const FX_PREFIX = "fx-";
247
+ /** A folder of particle textures: every texture below it is one. */
248
+ const FX_FOLDER = "fx";
249
+ /** The groups in the order a bundle packs them. */
250
+ const GROUP_ORDER = ["fx", "main"];
251
+ /**
252
+ * Picks the atlas group of one texture. A mipmapped texture stays loose whatever its key: Pixi
253
+ * builds its full chain, and from the second level on the neighbours on a page would bleed into
254
+ * it. A key whose last segment starts with `fx-`, or with a folder segment `fx` between the bundle
255
+ * name and the stem, goes to `fx` whatever its size: the frames of an animation in `fx/` too. Any
256
+ * other texture goes to `main` when no header side is above `LOOSE_SIDE` (1018 px). The header
257
+ * size decides: nothing is decoded before the groups are made, so a cache hit decodes nothing.
258
+ *
259
+ * @param texture - The key, the size and the mipmaps of the texture.
260
+ * @returns The group, or `undefined` when the texture stays loose.
261
+ * @example
262
+ * ```ts
263
+ * groupOf({ key: "ui.fx-rays", width: 504, height: 512 }); // "fx"
264
+ * groupOf({ key: "ui.fx.leaf", width: 64, height: 64 }); // "fx", from assets/fx/leaf.webp of ui
265
+ * groupOf({ key: "ui.fx", width: 64, height: 64 }); // "main": a stem, no folder
266
+ * groupOf({ key: "ui.panel", width: 600, height: 600 }); // "main"
267
+ * groupOf({ key: "ep01.items.cup", width: 336, height: 288, mips: true }); // undefined: loose
268
+ * ```
269
+ */
270
+ function groupOf(texture) {
271
+ if (texture.mips === true) return void 0;
272
+ const segments = texture.key.split(".");
273
+ const name = segments.at(-1) ?? "";
274
+ const folders = segments.slice(1, -1);
275
+ if (name.startsWith(FX_PREFIX) || folders.includes(FX_FOLDER)) return "fx";
276
+ return texture.width <= 1018 && texture.height <= 1018 ? "main" : void 0;
277
+ }
278
+ /**
279
+ * Compares two textures by key, so every list of the plan has one order.
280
+ *
281
+ * @param left - One texture.
282
+ * @param right - Another texture.
283
+ * @returns The sort order.
284
+ */
285
+ function byKey(left, right) {
286
+ return left.key.localeCompare(right.key);
287
+ }
288
+ /**
289
+ * Collects the atlas groups of sorted textures. A group of one is no group: its texture joins the
290
+ * loose ones.
291
+ *
292
+ * @param sorted - The textures of a bundle, sorted by key.
293
+ * @param loose - Where a texture of a group of one goes.
294
+ * @returns Group name to its members, in the order a bundle packs them.
295
+ */
296
+ function collectGroups(sorted, loose) {
297
+ const groups = /* @__PURE__ */ new Map();
298
+ for (const group of GROUP_ORDER) {
299
+ const members = sorted.filter((texture) => groupOf(texture) === group);
300
+ if (members.length > 1) groups.set(group, members);
301
+ else loose.push(...members);
302
+ }
303
+ return groups;
304
+ }
305
+ /**
306
+ * Splits the textures of one bundle into atlas groups and loose files. A group of one stays
307
+ * loose as well: an atlas of one file is one request either way, and costs its padding.
308
+ *
309
+ * @param textures - The textures of the bundle, in any order.
310
+ * @returns The groups and the loose textures, each sorted by key.
311
+ * @example
312
+ * ```ts
313
+ * planGroups([{ key: "orders.card", width: 218, height: 304 }]);
314
+ * // { groups: Map {}, loose: [{ key: "orders.card", width: 218, height: 304 }] }
315
+ * ```
316
+ */
317
+ function planGroups(textures) {
318
+ const sorted = textures.toSorted(byKey);
319
+ const loose = sorted.filter((texture) => groupOf(texture) === void 0);
320
+ return {
321
+ groups: collectGroups(sorted, loose),
322
+ loose: loose.toSorted(byKey)
323
+ };
324
+ }
325
+ /** Bytes per pixel of the decoded images: RGBA. */
326
+ const CHANNELS = 4;
327
+ /** Which byte of a pixel is its alpha. */
328
+ const ALPHA_OFFSET = 3;
329
+ /**
330
+ * Finds the first and the last column and row with a pixel of alpha above 0.
331
+ *
332
+ * @param pixels - The decoded image.
333
+ * @returns The extent, or `undefined` for an image with nothing visible.
334
+ */
335
+ function visibleExtent(pixels) {
336
+ const { width, height, data } = pixels;
337
+ let left = width;
338
+ let top = height;
339
+ let right = -1;
340
+ let bottom = -1;
341
+ for (let row = 0; row < height; row += 1) for (let column = 0; column < width; column += 1) {
342
+ if ((data[(row * width + column) * CHANNELS + ALPHA_OFFSET] ?? 0) === 0) continue;
343
+ left = Math.min(left, column);
344
+ right = Math.max(right, column);
345
+ top = Math.min(top, row);
346
+ bottom = Math.max(bottom, row);
347
+ }
348
+ return right < 0 ? void 0 : {
349
+ left,
350
+ top,
351
+ right,
352
+ bottom
353
+ };
354
+ }
355
+ /**
356
+ * Finds the box of the visible pixels of an image: every pixel with alpha above 0, grown by
357
+ * `TRIM_MARGIN` on each side where the image has room. The margin keeps one transparent row or
358
+ * column at a cut edge, so bilinear sampling at the edge of the sprite and the 1 px edge copy of the
359
+ * page read transparent there, as the uncut image did.
360
+ *
361
+ * @param pixels - The decoded image.
362
+ * @returns The box in the pixels of the image: the whole image when it has no transparent margin,
363
+ * `{ x: 0, y: 0, width: 1, height: 1 }` when nothing is visible.
364
+ * @example
365
+ * ```ts
366
+ * // A 6×4 image with one opaque pixel at (3, 2): the box is that pixel and its margin.
367
+ * const data = new Uint8Array(6 * 4 * 4);
368
+ * data[(2 * 6 + 3) * 4 + 3] = 255;
369
+ * trimBox({ width: 6, height: 4, data }); // { x: 2, y: 1, width: 3, height: 3 }
370
+ * ```
371
+ */
372
+ function trimBox(pixels) {
373
+ const extent = visibleExtent(pixels);
374
+ if (extent === void 0) return {
375
+ x: 0,
376
+ y: 0,
377
+ width: 1,
378
+ height: 1
379
+ };
380
+ const left = Math.max(0, extent.left - 1);
381
+ const top = Math.max(0, extent.top - 1);
382
+ const right = Math.min(pixels.width - 1, extent.right + 1);
383
+ const bottom = Math.min(pixels.height - 1, extent.bottom + 1);
384
+ return {
385
+ x: left,
386
+ y: top,
387
+ width: right - left + 1,
388
+ height: bottom - top + 1
389
+ };
390
+ }
391
+ /**
392
+ * Cuts a box out of an image.
393
+ *
394
+ * @param pixels - The decoded image.
395
+ * @param box - The box to keep, inside the image.
396
+ * @returns A new image of the box: the rows of the box, copied.
397
+ * @example
398
+ * ```ts
399
+ * const data = Uint8Array.from({ length: 3 * 3 * 4 }, (_, index) => index);
400
+ * cropPixels({ width: 3, height: 3, data }, { x: 1, y: 1, width: 1, height: 2 }).data;
401
+ * // Uint8Array [16, 17, 18, 19, 28, 29, 30, 31]
402
+ * ```
403
+ */
404
+ function cropPixels(pixels, box) {
405
+ const rowBytes = box.width * CHANNELS;
406
+ const data = new Uint8Array(rowBytes * box.height);
407
+ for (let row = 0; row < box.height; row += 1) {
408
+ const from = ((box.y + row) * pixels.width + box.x) * CHANNELS;
409
+ data.set(pixels.data.subarray(from, from + rowBytes), row * rowBytes);
410
+ }
411
+ return {
412
+ width: box.width,
413
+ height: box.height,
414
+ data
415
+ };
416
+ }
417
+ //#endregion
220
418
  //#region src/plugins/assets/scan/pack/cache.ts
221
419
  /**
222
420
  * @file assets packer, build time — the content-hash cache. One entry per atlas group and per
223
421
  * encoded loose texture, keyed by everything that decides its bytes: the format of the entry, the
224
- * versions of `sharp` and `maxrects-packer`, the packing constants and the members (key, SHA-256
225
- * of the source, nine). A hit replays the frames and the encoded bytes: no decode, no encode.
422
+ * versions of `sharp` and `maxrects-packer`, the packing constants (the page size, the loose
423
+ * side, the trim margin) and the members (key, SHA-256 of the source, nine). A hit
424
+ * replays the frames, with their trim, and the encoded bytes: no decode, no encode.
226
425
  * Entries are content-addressed, so the cache is never pruned.
227
426
  */
228
427
  /** The cache folder under the working directory. */
229
428
  const CACHE_FOLDER = path.join("node_modules", ".cache", "moku-game-pack");
230
429
  /** Changes when the shape of an entry changes, so an old entry is never read as a new one. */
231
- const FORMAT = "pack-1";
430
+ const FORMAT = "pack-2";
431
+ /** The optional fields of a frame that say where a trimmed texture lay in its original. */
432
+ const TRIM_FIELDS = [
433
+ "offsetX",
434
+ "offsetY",
435
+ "origWidth",
436
+ "origHeight"
437
+ ];
232
438
  /**
233
439
  * Hashes bytes into the hex SHA-256 the cache keys and members use.
234
440
  *
@@ -279,8 +485,10 @@ function cacheKey(input) {
279
485
  kind: input.kind,
280
486
  sharp: input.sharp,
281
487
  packer: packerVersion(),
282
- page: PAGE_SIZE,
488
+ pageSize: PAGE_SIZE,
283
489
  packerSize: PACKER_SIZE,
490
+ looseSide: LOOSE_SIDE,
491
+ trimMargin: 1,
284
492
  border: 2,
285
493
  padding: 2,
286
494
  extrude: 1,
@@ -290,7 +498,8 @@ function cacheKey(input) {
290
498
  }));
291
499
  }
292
500
  /**
293
- * Tells whether a value read from an entry file is one frame.
501
+ * Tells whether a value read from an entry file is one frame: a key and four numbers, and the four
502
+ * trim numbers of a trimmed texture when they are there.
294
503
  *
295
504
  * @param value - Anything the JSON carried.
296
505
  * @returns True for a frame.
@@ -303,7 +512,7 @@ function isFrame(value) {
303
512
  "y",
304
513
  "width",
305
514
  "height"
306
- ].every((field) => typeof frame[field] === "number");
515
+ ].every((field) => typeof frame[field] === "number") && TRIM_FIELDS.every((field) => frame[field] === void 0 || typeof frame[field] === "number");
307
516
  }
308
517
  /**
309
518
  * Reads the JSON file of an entry. A file that is missing, broken or of another shape is a miss.
@@ -1133,88 +1342,6 @@ function copyLoose(bundle, file, bytes) {
1133
1342
  };
1134
1343
  }
1135
1344
  //#endregion
1136
- //#region src/plugins/assets/scan/pack/groups.ts
1137
- /** A texture with a side above this stays loose: packing it would cost more memory than it saves. */
1138
- const LOOSE_SIDE = 512;
1139
- /** The last segment of a key that names a particle texture starts with this. */
1140
- const FX_PREFIX = "fx-";
1141
- /** A folder of particle textures: every texture below it is one. */
1142
- const FX_FOLDER = "fx";
1143
- /** The groups in the order a bundle packs them. */
1144
- const GROUP_ORDER = ["fx", "main"];
1145
- /**
1146
- * Picks the atlas group of one texture. A mipmapped texture stays loose whatever its key: Pixi
1147
- * builds its full chain, and from the second level on the neighbours on a page would bleed into
1148
- * it. A key whose last segment starts with `fx-`, or with a folder segment `fx` between the bundle
1149
- * name and the stem, goes to `fx` whatever its size: the frames of an animation in `fx/` too. Any
1150
- * other texture goes to `main` when no side is above 512 px.
1151
- *
1152
- * @param texture - The key, the size and the mipmaps of the texture.
1153
- * @returns The group, or `undefined` when the texture stays loose.
1154
- * @example
1155
- * ```ts
1156
- * groupOf({ key: "ui.fx-rays", width: 504, height: 512 }); // "fx"
1157
- * groupOf({ key: "ui.fx.leaf", width: 64, height: 64 }); // "fx", from assets/fx/leaf.webp of ui
1158
- * groupOf({ key: "ui.fx", width: 64, height: 64 }); // "main": a stem, no folder
1159
- * groupOf({ key: "ep01.items.cup", width: 336, height: 288, mips: true }); // undefined: loose
1160
- * ```
1161
- */
1162
- function groupOf(texture) {
1163
- if (texture.mips === true) return void 0;
1164
- const segments = texture.key.split(".");
1165
- const name = segments.at(-1) ?? "";
1166
- const folders = segments.slice(1, -1);
1167
- if (name.startsWith(FX_PREFIX) || folders.includes(FX_FOLDER)) return "fx";
1168
- return texture.width <= LOOSE_SIDE && texture.height <= LOOSE_SIDE ? "main" : void 0;
1169
- }
1170
- /**
1171
- * Compares two textures by key, so every list of the plan has one order.
1172
- *
1173
- * @param left - One texture.
1174
- * @param right - Another texture.
1175
- * @returns The sort order.
1176
- */
1177
- function byKey(left, right) {
1178
- return left.key.localeCompare(right.key);
1179
- }
1180
- /**
1181
- * Collects the atlas groups of sorted textures. A group of one is no group: its texture joins the
1182
- * loose ones.
1183
- *
1184
- * @param sorted - The textures of a bundle, sorted by key.
1185
- * @param loose - Where a texture of a group of one goes.
1186
- * @returns Group name to its members, in the order a bundle packs them.
1187
- */
1188
- function collectGroups(sorted, loose) {
1189
- const groups = /* @__PURE__ */ new Map();
1190
- for (const group of GROUP_ORDER) {
1191
- const members = sorted.filter((texture) => groupOf(texture) === group);
1192
- if (members.length > 1) groups.set(group, members);
1193
- else loose.push(...members);
1194
- }
1195
- return groups;
1196
- }
1197
- /**
1198
- * Splits the textures of one bundle into atlas groups and loose files. A group of one stays
1199
- * loose as well: an atlas of one file is one request either way, and costs its padding.
1200
- *
1201
- * @param textures - The textures of the bundle, in any order.
1202
- * @returns The groups and the loose textures, each sorted by key.
1203
- * @example
1204
- * ```ts
1205
- * planGroups([{ key: "orders.card", width: 218, height: 304 }]);
1206
- * // { groups: Map {}, loose: [{ key: "orders.card", width: 218, height: 304 }] }
1207
- * ```
1208
- */
1209
- function planGroups(textures) {
1210
- const sorted = textures.toSorted(byKey);
1211
- const loose = sorted.filter((texture) => groupOf(texture) === void 0);
1212
- return {
1213
- groups: collectGroups(sorted, loose),
1214
- loose: loose.toSorted(byKey)
1215
- };
1216
- }
1217
- //#endregion
1218
1345
  //#region src/plugins/assets/scan/pack/pack.ts
1219
1346
  /** The pack folder keeps a file of this name even when the manifest goes elsewhere. */
1220
1347
  const MANIFEST_NAME = "manifest.json";
@@ -1316,28 +1443,71 @@ async function readTextures(run, bundle) {
1316
1443
  return sources;
1317
1444
  }
1318
1445
  /**
1319
- * Decodes the textures of one layout page and composes the page.
1446
+ * Cuts the transparent margin off a decoded texture, except the margin of a nine-slice: a trimmed
1447
+ * nine-slice would lose its borders, so it keeps its full image.
1448
+ *
1449
+ * @param source - The texture.
1450
+ * @param pixels - Its decoded pixels, at the size of its header.
1451
+ * @returns What goes on the page, with the trim when the image got smaller.
1452
+ */
1453
+ function cutOf(source, pixels) {
1454
+ if (source.file.nine !== void 0) return {
1455
+ source,
1456
+ pixels
1457
+ };
1458
+ const box = trimBox(pixels);
1459
+ if (box.width === pixels.width && box.height === pixels.height) return {
1460
+ source,
1461
+ pixels
1462
+ };
1463
+ return {
1464
+ source,
1465
+ pixels: cropPixels(pixels, box),
1466
+ trim: {
1467
+ offsetX: box.x,
1468
+ offsetY: box.y,
1469
+ origWidth: pixels.width,
1470
+ origHeight: pixels.height
1471
+ }
1472
+ };
1473
+ }
1474
+ /**
1475
+ * Decodes every member of a group once and cuts its margin. A texture whose pixels disagree with the
1476
+ * size of its header is a problem, and is left out.
1477
+ *
1478
+ * @param run - The pack run, which collects the problems.
1479
+ * @param members - The textures of the group.
1480
+ * @returns The cuts of the members that decoded to their header size, in member order.
1481
+ */
1482
+ async function decodeGroup(run, members) {
1483
+ const cuts = [];
1484
+ for (const member of members) {
1485
+ const pixels = await run.encoder.decode(member.bytes);
1486
+ if (pixels.width !== member.width || pixels.height !== member.height) {
1487
+ run.problems.push(`the texture "${member.key}" decodes to ${pixels.width}×${pixels.height}, not the ${member.width}×${member.height} its header says.`);
1488
+ continue;
1489
+ }
1490
+ cuts.push(cutOf(member, pixels));
1491
+ }
1492
+ return cuts;
1493
+ }
1494
+ /**
1495
+ * Composes one layout page from the cut pixels of its frames and encodes it.
1320
1496
  *
1321
1497
  * @param run - The pack run.
1322
1498
  * @param page - The size and the frames of the page.
1323
1499
  * @param page.width - Width of the page.
1324
1500
  * @param page.height - Height of the page.
1325
1501
  * @param page.frames - Where each texture lies.
1326
- * @param sources - The members of the group, by key.
1502
+ * @param cuts - The cut of every member of the group, by key.
1327
1503
  * @returns The page, encoded.
1328
1504
  */
1329
- async function encodePage(run, page, sources) {
1505
+ async function encodePage(run, page, cuts) {
1330
1506
  const parts = [];
1331
1507
  for (const frame of page.frames) {
1332
- const source = sources.get(frame.key);
1333
- if (source === void 0) continue;
1334
- const pixels = await run.encoder.decode(source.bytes);
1335
- if (pixels.width !== frame.width || pixels.height !== frame.height) {
1336
- run.problems.push(`the texture "${frame.key}" decodes to ${pixels.width}×${pixels.height}, not the ${frame.width}×${frame.height} its header says.`);
1337
- continue;
1338
- }
1339
- parts.push({
1340
- pixels,
1508
+ const cut = cuts.get(frame.key);
1509
+ if (cut !== void 0) parts.push({
1510
+ pixels: cut.pixels,
1341
1511
  x: frame.x,
1342
1512
  y: frame.y
1343
1513
  });
@@ -1351,8 +1521,24 @@ async function encodePage(run, page, sources) {
1351
1521
  };
1352
1522
  }
1353
1523
  /**
1354
- * Packs one atlas group into pages: from the cache when every member is unchanged, otherwise laid
1355
- * out, composed and encoded, and stored in the cache when nothing went wrong.
1524
+ * Lists the members of a group as the layout takes them: the size of the cut, and where it lay.
1525
+ *
1526
+ * @param cuts - The cuts of the group.
1527
+ * @returns One member per cut.
1528
+ */
1529
+ function boxedOf(cuts) {
1530
+ return cuts.map((cut) => ({
1531
+ key: cut.source.key,
1532
+ width: cut.pixels.width,
1533
+ height: cut.pixels.height,
1534
+ ...cut.trim === void 0 ? {} : { trim: cut.trim }
1535
+ }));
1536
+ }
1537
+ /**
1538
+ * Packs one atlas group into pages: from the cache when every member is unchanged, otherwise every
1539
+ * member is decoded once and its transparent margin cut, the layout is chosen on the sizes of the
1540
+ * cuts, the pages are composed from them and encoded, and the entry is stored in the cache when
1541
+ * nothing went wrong.
1356
1542
  *
1357
1543
  * @param run - The pack run.
1358
1544
  * @param bundle - Name of the bundle.
@@ -1376,16 +1562,35 @@ async function packGroup(run, bundle, group, members) {
1376
1562
  return cached;
1377
1563
  }
1378
1564
  const open = run.problems.length;
1379
- const layout = layoutGroup(bundle, group, members);
1380
- const sources = new Map(members.map((member) => [member.key, member]));
1565
+ const cuts = await decodeGroup(run, members);
1566
+ const byKey = new Map(cuts.map((cut) => [cut.source.key, cut]));
1381
1567
  const images = [];
1568
+ const layout = layoutGroup(bundle, group, boxedOf(cuts));
1382
1569
  run.problems.push(...layout.problems);
1383
- for (const page of layout.pages) images.push(await encodePage(run, page, sources));
1570
+ for (const page of layout.pages) images.push(await encodePage(run, page, byKey));
1384
1571
  if (run.problems.length === open) await writeCache(run.cache, key, images);
1385
1572
  return images;
1386
1573
  }
1387
1574
  /**
1388
- * Writes the entry of a texture cut out of a page: no `path`, no cost of its own, the frame.
1575
+ * Reads the trim of a frame: where its texture lay in the original, when the texture was cut.
1576
+ *
1577
+ * @param frame - The frame of a page or of the manifest.
1578
+ * @returns The four trim fields, or `undefined` for a texture that is the whole image.
1579
+ */
1580
+ function trimOf(frame) {
1581
+ const { offsetX, offsetY, origWidth, origHeight } = frame;
1582
+ if (offsetX === void 0 || offsetY === void 0 || origWidth === void 0 || origHeight === void 0) return;
1583
+ return {
1584
+ offsetX,
1585
+ offsetY,
1586
+ origWidth,
1587
+ origHeight
1588
+ };
1589
+ }
1590
+ /**
1591
+ * Writes the entry of a texture cut out of a page: no `path`, no cost of its own, the frame. The
1592
+ * frame carries `offsetX`, `offsetY`, `origWidth` and `origHeight` after `height`, only when the
1593
+ * texture was trimmed.
1389
1594
  *
1390
1595
  * @param file - The texture of the scan.
1391
1596
  * @param page - The id of its page.
@@ -1404,7 +1609,8 @@ function packedFile(file, page, frame) {
1404
1609
  x: frame.x,
1405
1610
  y: frame.y,
1406
1611
  width: frame.width,
1407
- height: frame.height
1612
+ height: frame.height,
1613
+ ...trimOf(frame)
1408
1614
  }
1409
1615
  };
1410
1616
  }
@@ -1584,13 +1790,35 @@ function checkTexture(bundle, entry, file, source) {
1584
1790
  if (page === void 0) return [`the texture "${file.key}" names page "${atlas.page}", which bundle "${bundle}" does not list.`];
1585
1791
  const problems = [];
1586
1792
  if (!(atlas.x >= 0 && atlas.y >= 0 && atlas.x + atlas.width <= page.width && atlas.y + atlas.height <= page.height)) problems.push(`the frame of "${file.key}" lies outside page "${page.id}" (${page.width}×${page.height}).`);
1587
- if (atlas.width !== source?.width || atlas.height !== source.height) problems.push(`the frame of "${file.key}" is ${atlas.width}×${atlas.height}, its source ${source?.width ?? 0}×${source?.height ?? 0}.`);
1793
+ problems.push(...checkOriginal(file, atlas, source));
1794
+ return problems;
1795
+ }
1796
+ /**
1797
+ * Checks the original image of a packed texture (F198): its size is the size of its source, a
1798
+ * trimmed frame lies inside it, and a nine-slice is not trimmed.
1799
+ *
1800
+ * @param file - One packed texture.
1801
+ * @param atlas - Its frame.
1802
+ * @param source - The same texture in the scan.
1803
+ * @returns The problems, empty when the original is right.
1804
+ */
1805
+ function checkOriginal(file, atlas, source) {
1806
+ const problems = [];
1807
+ const trim = trimOf(atlas);
1808
+ const width = trim?.origWidth ?? atlas.width;
1809
+ const height = trim?.origHeight ?? atlas.height;
1810
+ if (!(width === source?.width && height === source.height)) problems.push(`the frame of "${file.key}" is ${width}×${height}, its source ${source?.width ?? 0}×${source?.height ?? 0}.`);
1811
+ if (trim === void 0) return problems;
1812
+ if (trim.offsetX + atlas.width > trim.origWidth || trim.offsetY + atlas.height > trim.origHeight) problems.push(`the frame of "${file.key}" lies outside its original (${trim.origWidth}×${trim.origHeight}).`);
1813
+ if (file.nine !== void 0) problems.push(`the texture "${file.key}" has nine-slice borders, so it must not be trimmed.`);
1588
1814
  return problems;
1589
1815
  }
1590
1816
  /**
1591
1817
  * Checks a packed manifest against the scan it came from: every key landed exactly once, as a
1592
- * page frame or a file; every frame names a page of its own bundle, lies inside it and has the
1593
- * size of its source, so `nine` stays valid as it is; a mipmapped texture is never a frame.
1818
+ * page frame or a file; every frame names a page of its own bundle, lies inside it and belongs to an
1819
+ * original of the size of its source (`origWidth ?? width`), so `nine` stays valid as it is; a
1820
+ * trimmed frame lies inside its original, and a texture with `nine` is never trimmed; a mipmapped
1821
+ * texture is never a frame.
1594
1822
  *
1595
1823
  * @param source - The manifest of the scan.
1596
1824
  * @param packed - The packed manifest.
@@ -1740,12 +1968,14 @@ function countLoose(bundles) {
1740
1968
  }
1741
1969
  /**
1742
1970
  * Packs the art of a game for production: per bundle, the textures of the `fx` group and of the
1743
- * `main` group go onto WebP atlas pages (2048 px at most, 2 px padding and border with each frame's
1744
- * edge extruded 1 px into it, never trimmed or rotated), a texture with a side above 512 px and a group of one stay loose files, fonts and
1745
- * sounds are copied, every file name carries the hash of its bytes, and the packed manifest
1746
- * (version 2) names it all. Nothing is written while a problem is open; afterwards the pack folder
1747
- * holds exactly what the manifest references, plus `manifest.json`. Two runs on the same tree and
1748
- * the same `sharp` write the same bytes.
1971
+ * `main` group go onto WebP atlas pages (2048 px at most; 2 px padding and border with each frame's edge extruded 1 px
1972
+ * into it, never rotated), a texture that is not a nine-slice is cropped to its visible pixels and
1973
+ * the manifest keeps where the crop lay in the original (F198). A `main` texture above `LOOSE_SIDE`, a
1974
+ * mipmapped one and a group of one stay loose files; a texture too large for the page is a
1975
+ * problem. Fonts and sounds are copied, every file name carries the hash of its
1976
+ * bytes, and the packed manifest (version 2) names it all. Nothing is written while a problem is
1977
+ * open; afterwards the pack folder holds exactly what the manifest references, plus
1978
+ * `manifest.json`. Two runs on the same tree and the same `sharp` write the same bytes.
1749
1979
  *
1750
1980
  * @param options - The sources, the scanned manifest, the pack folder, the manifest file, the cache.
1751
1981
  * @returns The packed manifest and what was written.