modelstage 0.10.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1307 @@
1
+ // ============================================================================
2
+ // plugins/unity-spine-bundle/lib/astc.js —— ASTC(Adaptive Scalable Texture Compression)解码器
3
+ //
4
+ // 职责:把 ASTC 的压缩块(每块固定 16 字节 = 128 bit)解成 RGBA 字节数组。
5
+ //
6
+ // 为什么需要它:Unity 的 ASTC 纹理是"块压缩 + 显卡直接采样"的格式,浏览器侧拿不到
7
+ // WebGL 的 ASTC 扩展(且现有链路是 CPU 解码成 RGBA → 编码 PNG → 交给 VirtualFS),
8
+ // 没有解码器时整张图只能报"格式未支持",模型就出不了画。
9
+ //
10
+ // 与块尺寸的关系:ASTC 块内编码(分区 / 端点 / 权重网格)与块边长无关,
11
+ // 块边长只影响最后"权重网格 → 纹素"的插值范围。所以同一份解码逻辑天然支持
12
+ // 4x4 / 5x5 / 6x6 / 8x8 / 10x10 / 12x12 —— 不必为每种边长写一份。
13
+ //
14
+ // 来源与授权:
15
+ // 解码流程移植自 Android drawElements 测试套件的 ASTC 解码器(Apache-2.0),
16
+ // 并经 basis_universal 的整理版(basisu_astc_decomp.cpp)转发;整理版已经删掉 HDR 分支。
17
+ // 本文件按原实现逐函数移植,只做了三处与平台相关的等价改写:
18
+ // ① 128 bit 的取值改成直接按字节读(原实现用两个 64 位字,JS 没有原生的 64 位无符号运算);
19
+ // ② 输出只保留 8 bit/通道通路(原实现另有 float 通路,最终同样是量化到 8 bit);
20
+ // ③ 出错一律抛带原因的错误,不再填"错误色"(理由见下)。
21
+ //
22
+ // 为什么出错要抛而不是填洋红色:本项目对纹理失败的要求是"可读错误、不产出半成品"
23
+ // (见 doc/契约 与 ASTC 支持计划)。填错误色会让调用方以为解码成功,
24
+ // 把"数据/格式判断错"伪装成"这张图本来就长这样",排查成本极高。故:
25
+ // · 未实现的特性(HDR 端点模式 / HDR void-extent / 非法块尺寸)→ 抛"格式未支持"
26
+ // · 结构非法(保留块模式、权重位数越界、端点值个数越界)→ 抛"解码失败"
27
+ // 两者都带块坐标,能直接定位是哪一格出了问题。
28
+ //
29
+ // 挂载:globalThis.__ULB__.astc = { decodeAstc }
30
+ // · 返回的字节序是 **RGBA**(每像素 4 字节,依次 R、G、B、A)—— 注意不是参考 C++ 实现
31
+ // 直接写给显卡的那个 BGRA 顺序:本项目全部解码器与 VirtualFS/PNG 编码这条链都按 RGBA,
32
+ // 所以移植时在这里做了通道还原。做"与参考实现比对"时要把 R/B 换回去才能对齐。
33
+ // · 方向是**存储方向**(第 0 行 = 数据里的第一行),不做 flipY ——
34
+ // 竖向翻转由外层 texdecode.decode() 统一做,避免两处翻(翻两次等于没翻)。
35
+ // · 本文件在 unity-spine-bundle 与 unity-live2d-bundle 里**逐字节相同**(parity 用例钉住)。
36
+ // ============================================================================
37
+
38
+ 'use strict';
39
+
40
+ {
41
+ const root = globalThis;
42
+ const NS = (root.__ULB__ = root.__ULB__ || {});
43
+
44
+ // ---------------------------------------------------------------- 错误构造
45
+ //
46
+ // 复用插件的错误码表(spine 插件是 SPI_ERR_*,live2d 插件是 ULB_ERR_*):
47
+ // 这里按**码名**去表里取,取不到才退回本地字面量 —— 两份插件代码因此可以逐字节相同。
48
+ // 需要区分的新情况:
49
+ // · 未实现的特性 → TEXTURE_FORMAT_UNSUPPORTED(调用方可据此提示"格式不支持")
50
+ // · 数据/结构非法 → TEXTURE_DECODE(可能是块尺寸判断错,属于真 bug 类)
51
+ const LOCAL_CODES = {
52
+ BAD_ARGS: 'TEX_ERR_BAD_ARGS',
53
+ TEXTURE_FORMAT_UNSUPPORTED: 'TEX_ERR_FORMAT_UNSUPPORTED',
54
+ TEXTURE_DATA_SHORT: 'TEX_ERR_DATA_SHORT',
55
+ TEXTURE_DECODE: 'TEX_ERR_DECODE',
56
+ };
57
+
58
+ /**
59
+ * 构造带稳定错误码的 Error。
60
+ * @param {string} codeKey LOCAL_CODES 的键名(同时用于查插件的 CODES 表)
61
+ * @param {string} message 中文可读说明(要能直接看懂"哪张图、哪一格、为什么")
62
+ */
63
+ function fail(codeKey, message) {
64
+ const codes = NS.errors && NS.errors.CODES ? NS.errors.CODES : LOCAL_CODES;
65
+ const code = codes[codeKey] || LOCAL_CODES[codeKey] || codeKey;
66
+ if (NS.errors && typeof NS.errors.fail === 'function') {
67
+ return NS.errors.fail(code, message);
68
+ }
69
+ const err = new Error(message);
70
+ err.code = code;
71
+ err.tex = true;
72
+ return err;
73
+ }
74
+
75
+ // ---------------------------------------------------------------- 常量
76
+ //
77
+ // ASTC 规定的块边长上限:块内最多 12×12 个纹素(权重网格最大也是 12×12)。
78
+ // 这不是"我们只支持 12 以内",而是格式本身的上限。
79
+ const MAX_BLOCK_SIDE = 12;
80
+
81
+ // 规格允许的全部块尺寸(高度不超过宽度)。Unity 的 ASTC_* 格式只用正方块,
82
+ // 但解码逻辑与块尺寸无关,把整张表都认下来可以顺手支持非正方的 ASTC 数据。
83
+ const ASTC_BLOCK_DIMENSIONS = new Set([
84
+ '4x4', '5x4', '5x5', '6x5', '6x6', '8x5', '8x6',
85
+ '8x8', '10x5', '10x6', '10x8', '10x10', '12x10', '12x12',
86
+ ]);
87
+
88
+ // 一个块固定 16 字节。写死成常量而不是算出来,是为了让"块表 / 数据长度"两处口径一眼能对。
89
+ const BLOCK_BYTES = 16;
90
+
91
+ // 权重网格里最多 64 个权重(12×12 已是 144,但规格把上限压在 64 —— 双平面时两个平面共享这 64 个槽)
92
+ const MAX_WEIGHTS = 64;
93
+
94
+ // 端点值的上限:4 个分区 × 每分区最多 8 个值 = 18(4 分区时 CEM 0/1 只给 2 个值,故 18 是理论上限)
95
+ const MAX_ENDPOINT_VALUES = 18;
96
+
97
+ // 三种整数序列编码模式(ASTC 用三进制/五进制/纯二进制打包端点与权重)
98
+ const ISE_MODE_TRIT = 0;
99
+ const ISE_MODE_QUINT = 1;
100
+ const ISE_MODE_PLAIN_BIT = 2;
101
+
102
+ // 三进制序列查表:8 bit 的 T 值 → 5 个三进制数。
103
+ // 表是从参考实现原样搬来的(规格附录给出同样内容);不要手推,推错一格就整片花。
104
+ const TRITS_FROM_T = [
105
+ 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 2, 1, 0, 0, 0, 1, 0, 2, 0, 0,
106
+ 0, 2, 0, 0, 0, 1, 2, 0, 0, 0, 2, 2, 0, 0, 0, 2, 0, 2, 0, 0, 0, 2, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0, 0, 2, 0, 2, 0, 0,
107
+ 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 2, 0, 1, 0, 0, 0, 1, 2, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 2, 1, 1, 0, 0, 1, 1, 2, 0, 0,
108
+ 0, 2, 1, 0, 0, 1, 2, 1, 0, 0, 2, 2, 1, 0, 0, 2, 1, 2, 0, 0, 0, 0, 0, 2, 2, 1, 0, 0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 2,
109
+ 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 0, 2, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 2, 1, 0, 1, 0, 1, 0, 2, 1, 0,
110
+ 0, 2, 0, 1, 0, 1, 2, 0, 1, 0, 2, 2, 0, 1, 0, 2, 0, 2, 1, 0, 0, 2, 2, 1, 0, 1, 2, 2, 1, 0, 2, 2, 2, 1, 0, 2, 0, 2, 1, 0,
111
+ 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 2, 0, 1, 1, 0, 0, 1, 2, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 2, 1, 1, 1, 0, 1, 1, 2, 1, 0,
112
+ 0, 2, 1, 1, 0, 1, 2, 1, 1, 0, 2, 2, 1, 1, 0,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3, 1, 0, 3, 2, 0, 3, 3, 0, 3, 4, 0, 3, 0, 4, 3, 0, 0, 4, 1, 0, 4,
154
+ 0, 1, 3, 1, 1, 3, 2, 1, 3, 3, 1, 3, 4, 1, 3, 1, 4, 3, 0, 1, 4, 1, 1, 4,
155
+ 0, 2, 3, 1, 2, 3, 2, 2, 3, 3, 2, 3, 4, 2, 3, 2, 4, 3, 0, 2, 4, 1, 2, 4,
156
+ 0, 3, 3, 1, 3, 3, 2, 3, 3, 3, 3, 3, 4, 3, 3, 3, 4, 3, 0, 3, 4, 1, 3, 4,
157
+ ];
158
+
159
+ // ---------------------------------------------------------------- 位读取
160
+ //
161
+ // ASTC 的位编号从块的第 1 个字节的最低位开始(bit 0 = byte0 & 1),
162
+ // 与常见的"大端位流"相反 —— 位序弄反的表现是整片花屏,所以这里只提供两个入口,
163
+ // 且都按同一套编号规则实现,避免各处各写一套。
164
+
165
+ /** 一个 128 bit 块的位访问器(对应参考实现的 Block128) */
166
+ class BlockBits {
167
+ /**
168
+ * @param {Uint8Array} source 整份纹理数据
169
+ * @param {number} byteOffset 本块在 source 里的起始字节
170
+ */
171
+ constructor(source, byteOffset) {
172
+ this.source = source;
173
+ // 块按 32 位小端拆成 4 个字:位号 i 落在 words[i>>5] 的第 (i&31) 位。
174
+ // 为什么要预拆:解码一个块要取几十次位,按字节逐段拼会在 4 万块规模下成为最大热点
175
+ // (实测取位占解码总耗时四成以上)。拆成字之后每次取位只是两三次位运算。
176
+ this.words = new Uint32Array(4);
177
+ this.setOffset(byteOffset);
178
+ }
179
+
180
+ /** 复用同一个访问器处理下一个块(每块换一次偏移,不重新建对象) */
181
+ setOffset(byteOffset) {
182
+ const source = this.source;
183
+ const words = this.words;
184
+ for (let wordIndex = 0; wordIndex < 4; wordIndex++) {
185
+ const base = byteOffset + wordIndex * 4;
186
+ words[wordIndex] = (source[base]
187
+ | (source[base + 1] << 8)
188
+ | (source[base + 2] << 16)
189
+ | (source[base + 3] << 24)) >>> 0;
190
+ }
191
+ }
192
+
193
+ /** 取第 index 位(0 = 最低位) */
194
+ bitAt(index) {
195
+ return (this.words[index >>> 5] >>> (index & 31)) & 1;
196
+ }
197
+
198
+ /**
199
+ * 取 [low, high] 闭区间内的位,返回无符号整数(最多 32 位,与 ASTC 单字段宽度上限一致)。
200
+ */
201
+ bits(low, high) {
202
+ return readBits(this.words, low, high);
203
+ }
204
+ }
205
+
206
+ /** 把若干位逆序(参考实现的 reverseBits):从 startNdx 往回读时必须用 */
207
+ function reverseBits(source, numBits) {
208
+ let result = 0;
209
+ for (let i = 0; i < numBits; i++) {
210
+ result |= ((source >> i) & 1) << (numBits - 1 - i);
211
+ }
212
+ return result >>> 0;
213
+ }
214
+
215
+ /**
216
+ * 顺序位流(对应参考实现的 BitAccessStream)。
217
+ *
218
+ * 为什么要它:ASTC 把"权重"和"端点"分别放在块的两端、朝相反方向写 ——
219
+ * 权重从 bit 127 往前读,端点从中间往后读。方向记错就是整片乱码。
220
+ */
221
+ class BitStream {
222
+ /**
223
+ * @param {BlockBits} block 块位访问器
224
+ * @param {number} startNdx 起点位号
225
+ * @param {number} length 可用位数(超出部分一律读 0,不是报错)
226
+ * @param {boolean} forward true = 位号递增方向
227
+ */
228
+ constructor(block, startNdx, length, forward) {
229
+ this.block = block;
230
+ this.words = block ? block.words : null;
231
+ this.startNdx = startNdx;
232
+ this.length = length;
233
+ this.forward = forward;
234
+ this.cursor = 0;
235
+ }
236
+
237
+ /** 复用同一个位流对象读下一个块(避免每块新建两个对象带来的 GC 抖动) */
238
+ reset(block, startNdx, length, forward) {
239
+ this.block = block;
240
+ // 把四个字直接挂到流上:位流是解码最热的路径(每块几十次取位),
241
+ // 少一层 `this.block.words` 的属性链在 4 万块规模下也是实打实的时间。
242
+ this.words = block.words;
243
+ this.startNdx = startNdx;
244
+ this.length = length;
245
+ this.forward = forward;
246
+ this.cursor = 0;
247
+ }
248
+
249
+ /** 取接下来的 num 位;越过 length 的部分按 0 补(与规格一致,不抛错) */
250
+ next(num) {
251
+ if (num === 0 || this.cursor >= this.length) return 0;
252
+ const low = this.cursor;
253
+ const end = low + num;
254
+ // 超出可用长度的部分按 0 补:只读到 length 为止
255
+ const numBitsFromSource = end <= this.length ? num : this.length - low;
256
+ this.cursor = end;
257
+ if (numBitsFromSource <= 0) return 0;
258
+ const high = low + numBitsFromSource - 1;
259
+ const startNdx = this.startNdx;
260
+ const words = this.words;
261
+ if (this.forward) return readBits(words, startNdx + low, startNdx + high);
262
+ return reverseBits(readBits(words, startNdx - high, startNdx - low), numBitsFromSource);
263
+ }
264
+ }
265
+
266
+ /**
267
+ * 从预拆好的 4 个 32 位字里取 [low, high] 闭区间的位(最多 32 位)。
268
+ * 独立成自由函数(而不是 BlockBits 的方法):位流调用它几百万次,自由函数的调用开销更低。
269
+ */
270
+ function readBits(words, low, high) {
271
+ const count = high - low + 1;
272
+ if (count <= 0) return 0;
273
+ const wordIndex = low >>> 5;
274
+ const bitInWord = low & 31;
275
+ const mask = count >= 32 ? 0xffffffff : (0xffffffff >>> (32 - count));
276
+ const firstPart = words[wordIndex] >>> bitInWord;
277
+ if (bitInWord + count <= 32) return (firstPart & mask) >>> 0;
278
+ // 跨字:低字的高位段 + 高字的低位段
279
+ const bitsFromFirst = 32 - bitInWord;
280
+ const restCount = count - bitsFromFirst;
281
+ const restMask = restCount >= 32 ? 0xffffffff : (0xffffffff >>> (32 - restCount));
282
+ return (firstPart | ((words[wordIndex + 1] & restMask) << bitsFromFirst)) >>> 0;
283
+ }
284
+
285
+ // ---------------------------------------------------------------- 通用小工具
286
+
287
+ /** 向上取整的整除(参考实现的 deDivRoundUp32) */
288
+ function divRoundUp(value, divisor) {
289
+ return Math.floor((value + divisor - 1) / divisor);
290
+ }
291
+
292
+ /**
293
+ * 位复制扩展:把 numSrcBits 位的值"重复铺"到 numDstBits 位(ASTC 的端点/权重量化复原)。
294
+ * 例:2 位值 0b10 铺到 8 位 → 0b10101010。取高位重复,等价于乘 (2^n-1)/(2^m-1)。
295
+ */
296
+ function bitReplicationScale(source, numSrcBits, numDstBits) {
297
+ if (numSrcBits <= 0) return 0;
298
+ let destination = 0;
299
+ for (let shift = numDstBits - numSrcBits; shift > -numSrcBits; shift -= numSrcBits) {
300
+ destination |= shift >= 0 ? source << shift : source >> -shift;
301
+ }
302
+ return destination >>> 0;
303
+ }
304
+
305
+ /** 取某数的第 index 位(0 起) */
306
+ function bitAt(value, index) {
307
+ return (value >> index) & 1;
308
+ }
309
+
310
+ // ---------------------------------------------------------------- 块模式
311
+ //
312
+ // 块模式(bit 0..10)同时编码:权重网格尺寸、是否有第二平面、权重的整数编码方式。
313
+ // 这段的分支形状完全由规格表决定,不能"简化"——每个分支对应一组合法的块形态。
314
+
315
+ /**
316
+ * 解析块模式(带缓存)。
317
+ *
318
+ * 块模式只有 11 bit(2048 种取值),而一张大纹理要解几十万块 —— 同一模式会反复出现。
319
+ * 解析本身是十几次分支,缓存后每块只剩一次取位 + 一次查表。
320
+ * 返回的对象**只读**:调用方不得改写(缓存会共享同一份)。
321
+ * @param {BlockBits} block
322
+ * @returns {{isError:boolean, isVoidExtent:boolean, isDualPlane:boolean, weightGridWidth:number,
323
+ * weightGridHeight:number, weightMode:number, weightBits:number}}
324
+ */
325
+ function readBlockMode(block) {
326
+ const modeValue = block.bits(0, 10);
327
+ const cached = blockModeCache.get(modeValue);
328
+ if (cached !== undefined) return cached;
329
+ const parsed = decodeBlockModeValue(block);
330
+ blockModeCache.set(modeValue, parsed);
331
+ return parsed;
332
+ }
333
+
334
+ /** 块模式缓存(键 = 11 bit 的块模式值;内容只依赖它,与块内其它位无关) */
335
+ const blockModeCache = new Map();
336
+
337
+ /** 真正解析块模式(每种取值只跑一次) */
338
+ function decodeBlockModeValue(block) {
339
+ const mode = {
340
+ isError: true,
341
+ isVoidExtent: block.bits(0, 8) === 0x1fc,
342
+ isDualPlane: false,
343
+ weightGridWidth: 0,
344
+ weightGridHeight: 0,
345
+ weightMode: ISE_MODE_PLAIN_BIT,
346
+ weightBits: 0,
347
+ };
348
+ if (mode.isVoidExtent) {
349
+ mode.isError = false;
350
+ return mode;
351
+ }
352
+
353
+ // 两种"保留"组合:低两位为 0 且 bit6..8 全 1;或低 4 位全 0。规格要求解码器视其为非法块。
354
+ if ((block.bits(0, 1) === 0 && block.bits(6, 8) === 7) || block.bits(0, 3) === 0) {
355
+ return mode;
356
+ }
357
+
358
+ let r = -1;
359
+ if (block.bits(0, 1) === 0) {
360
+ const r0 = block.bitAt(4);
361
+ const r1 = block.bitAt(2);
362
+ const r2 = block.bitAt(3);
363
+ const bits78 = block.bits(7, 8);
364
+ r = (r2 << 2) | (r1 << 1) | r0;
365
+ if (bits78 === 3) {
366
+ const bit5 = block.bitAt(5) !== 0;
367
+ mode.weightGridWidth = bit5 ? 10 : 6;
368
+ mode.weightGridHeight = bit5 ? 6 : 10;
369
+ } else {
370
+ const a = block.bits(5, 6);
371
+ if (bits78 === 0) {
372
+ mode.weightGridWidth = 12;
373
+ mode.weightGridHeight = a + 2;
374
+ } else if (bits78 === 1) {
375
+ mode.weightGridWidth = a + 2;
376
+ mode.weightGridHeight = 12;
377
+ } else if (bits78 === 2) {
378
+ mode.weightGridWidth = a + 6;
379
+ mode.weightGridHeight = block.bits(9, 10) + 6;
380
+ } else {
381
+ return mode; // 规格里不存在第 4 种取值,按非法块处理
382
+ }
383
+ }
384
+ } else {
385
+ const r0 = block.bitAt(4);
386
+ const r1 = block.bitAt(0);
387
+ const r2 = block.bitAt(1);
388
+ const bits23 = block.bits(2, 3);
389
+ const a = block.bits(5, 6);
390
+ r = (r2 << 2) | (r1 << 1) | r0;
391
+ if (bits23 === 3) {
392
+ const b = block.bitAt(7);
393
+ const bit8 = block.bitAt(8) !== 0;
394
+ mode.weightGridWidth = bit8 ? b + 2 : a + 2;
395
+ mode.weightGridHeight = bit8 ? a + 2 : b + 6;
396
+ } else {
397
+ const b = block.bits(7, 8);
398
+ if (bits23 === 0) {
399
+ mode.weightGridWidth = b + 4;
400
+ mode.weightGridHeight = a + 2;
401
+ } else if (bits23 === 1) {
402
+ mode.weightGridWidth = b + 8;
403
+ mode.weightGridHeight = a + 2;
404
+ } else if (bits23 === 2) {
405
+ mode.weightGridWidth = a + 2;
406
+ mode.weightGridHeight = b + 8;
407
+ } else {
408
+ return mode;
409
+ }
410
+ }
411
+ }
412
+
413
+ // bit 9 = 权重编码是否用"大范围"表(规格称 H 位),bit 10 = 是否有第二平面。
414
+ // 特例:低两位为 0 且 bit7..8 = 2 的组合里,bit9/bit10 不表示这两个含义(规格的 zeroDH)。
415
+ const zeroDH = block.bits(0, 1) === 0 && block.bits(7, 8) === 2;
416
+ const hasLargeRange = zeroDH ? false : block.bitAt(9) !== 0;
417
+ mode.isDualPlane = zeroDH ? false : block.bitAt(10) !== 0;
418
+
419
+ mode.weightMode = ISE_MODE_PLAIN_BIT;
420
+ mode.weightBits = 0;
421
+ if (hasLargeRange) {
422
+ switch (r) {
423
+ case 2: mode.weightMode = ISE_MODE_QUINT; mode.weightBits = 1; break;
424
+ case 3: mode.weightMode = ISE_MODE_TRIT; mode.weightBits = 2; break;
425
+ case 4: mode.weightBits = 4; break;
426
+ case 5: mode.weightMode = ISE_MODE_QUINT; mode.weightBits = 2; break;
427
+ case 6: mode.weightMode = ISE_MODE_TRIT; mode.weightBits = 3; break;
428
+ case 7: mode.weightBits = 5; break;
429
+ default: return mode;
430
+ }
431
+ } else {
432
+ switch (r) {
433
+ case 2: mode.weightBits = 1; break;
434
+ case 3: mode.weightMode = ISE_MODE_TRIT; break;
435
+ case 4: mode.weightBits = 2; break;
436
+ case 5: mode.weightMode = ISE_MODE_QUINT; break;
437
+ case 6: mode.weightMode = ISE_MODE_TRIT; mode.weightBits = 1; break;
438
+ case 7: mode.weightBits = 3; break;
439
+ default: return mode;
440
+ }
441
+ }
442
+
443
+ mode.isError = false;
444
+ return mode;
445
+ }
446
+
447
+ /** 权重网格里有多少个权重值(双平面时两个平面各一套) */
448
+ function computeNumWeights(mode) {
449
+ return mode.weightGridWidth * mode.weightGridHeight * (mode.isDualPlane ? 2 : 1);
450
+ }
451
+
452
+ /** 某模式下权重数据占多少位(三进制/五进制还要额外算打包开销) */
453
+ function computeNumRequiredBits(iseMode, iseBits, numValues) {
454
+ if (iseMode === ISE_MODE_TRIT) return divRoundUp(numValues * 8, 5) + numValues * iseBits;
455
+ if (iseMode === ISE_MODE_QUINT) return divRoundUp(numValues * 7, 3) + numValues * iseBits;
456
+ return numValues * iseBits;
457
+ }
458
+
459
+ /**
460
+ * 在给定可用位数下,选"能装下 numValues 个值的最宽"整数编码方案。
461
+ * 为什么要选最大的:端点精度直接决定颜色准确度,用窄模式会白丢精度。
462
+ *
463
+ * 结果只由 (可用位数, 值个数) 决定,而这两个数在大纹理里取值很少 ⇒ 缓存起来。
464
+ */
465
+ function computeMaximumRangeISEParams(numAvailableBits, numValuesInSequence) {
466
+ const cacheKey = numAvailableBits * 64 + numValuesInSequence;
467
+ const cached = iseParamsCache.get(cacheKey);
468
+ if (cached !== undefined) return cached;
469
+ const params = computeMaximumRangeISEParamsUncached(numAvailableBits, numValuesInSequence);
470
+ iseParamsCache.set(cacheKey, params);
471
+ return params;
472
+ }
473
+
474
+ /** ISE 参数缓存(键 = 可用位数 × 64 + 值个数;值个数上限 18、位数上限 96,不会撞键) */
475
+ const iseParamsCache = new Map();
476
+
477
+ function computeMaximumRangeISEParamsUncached(numAvailableBits, numValuesInSequence) {
478
+ let tritBits = 6;
479
+ let quintBits = 5;
480
+ let plainBits = 8;
481
+ for (;;) {
482
+ const tritRange = tritBits > 0 ? (3 << tritBits) - 1 : -1;
483
+ const quintRange = quintBits > 0 ? (5 << quintBits) - 1 : -1;
484
+ const plainRange = plainBits > 0 ? (1 << plainBits) - 1 : -1;
485
+ const maxRange = Math.max(tritRange, quintRange, plainRange);
486
+ if (maxRange === tritRange) {
487
+ if (computeNumRequiredBits(ISE_MODE_TRIT, tritBits, numValuesInSequence) <= numAvailableBits) {
488
+ return { mode: ISE_MODE_TRIT, numBits: tritBits };
489
+ }
490
+ tritBits--;
491
+ } else if (maxRange === quintRange) {
492
+ if (computeNumRequiredBits(ISE_MODE_QUINT, quintBits, numValuesInSequence) <= numAvailableBits) {
493
+ return { mode: ISE_MODE_QUINT, numBits: quintBits };
494
+ }
495
+ quintBits--;
496
+ } else {
497
+ if (computeNumRequiredBits(ISE_MODE_PLAIN_BIT, plainBits, numValuesInSequence) <= numAvailableBits) {
498
+ return { mode: ISE_MODE_PLAIN_BIT, numBits: plainBits };
499
+ }
500
+ plainBits--;
501
+ }
502
+ }
503
+ }
504
+
505
+ // ---------------------------------------------------------------- 整数序列(ISE)解码
506
+ //
507
+ // ASTC 把端点/权重当"三进制或五进制的整数序列"打包,压缩率比纯二进制高。
508
+ // 每个值要同时带三样东西:m = 低位原始位,tq = 三进制或五进制数,v = tq 拼在 m 之上的完整值。
509
+ //
510
+ // 为什么用扁平 3 槽数组而不是 {m,tq,v} 对象:一张 1024² 的 5x5 纹理要解约 200 万个这样的值,
511
+ // 每个建一个对象就是 200 万次分配 —— 实测这是解码耗时里最大的一块(远超算术本身)。
512
+ const ISE_STRIDE = 3;
513
+ const ISE_M = 0;
514
+ const ISE_TQ = 1;
515
+ const ISE_V = 2;
516
+
517
+ function decodeTritBlock(out, outValueIndex, numValues, stream, numBits) {
518
+ const m = new Array(5);
519
+ m[0] = stream.next(numBits);
520
+ const t01 = stream.next(2);
521
+ m[1] = stream.next(numBits);
522
+ let t23 = stream.next(2);
523
+ m[2] = stream.next(numBits);
524
+ let t4 = stream.next(1);
525
+ m[3] = stream.next(numBits);
526
+ let t56 = stream.next(2);
527
+ m[4] = stream.next(numBits);
528
+ let t7 = stream.next(1);
529
+
530
+ // 值不够时,高位三进制数按规格清零(顺序不能乱:后面的依赖前面的清零结果)
531
+ if (numValues <= 4) t7 = 0;
532
+ if (numValues <= 3) t56 = 0;
533
+ if (numValues <= 2) t4 = 0;
534
+ if (numValues <= 1) t23 = 0;
535
+
536
+ const t = (t7 << 7) | (t56 << 5) | (t4 << 4) | (t23 << 2) | t01;
537
+ const tableIndex = t * 5;
538
+ for (let i = 0; i < numValues; i++) {
539
+ const trit = TRITS_FROM_T[tableIndex + i];
540
+ const slot = (outValueIndex + i) * ISE_STRIDE;
541
+ out[slot + ISE_M] = m[i];
542
+ out[slot + ISE_TQ] = trit;
543
+ out[slot + ISE_V] = (trit << numBits) + m[i];
544
+ }
545
+ }
546
+
547
+ function decodeQuintBlock(out, outValueIndex, numValues, stream, numBits) {
548
+ const m = new Array(3);
549
+ m[0] = stream.next(numBits);
550
+ const q012 = stream.next(3);
551
+ m[1] = stream.next(numBits);
552
+ let q34 = stream.next(2);
553
+ m[2] = stream.next(numBits);
554
+ let q56 = stream.next(2);
555
+
556
+ if (numValues <= 2) q56 = 0;
557
+ if (numValues <= 1) q34 = 0;
558
+
559
+ const q = (q56 << 5) | (q34 << 3) | q012;
560
+ const tableIndex = q * 3;
561
+ for (let i = 0; i < numValues; i++) {
562
+ const quint = QUINTS_FROM_Q[tableIndex + i];
563
+ const slot = (outValueIndex + i) * ISE_STRIDE;
564
+ out[slot + ISE_M] = m[i];
565
+ out[slot + ISE_TQ] = quint;
566
+ out[slot + ISE_V] = (quint << numBits) + m[i];
567
+ }
568
+ }
569
+
570
+ function decodeIESequence(out, numValues, stream, iseMode, numBits) {
571
+ if (iseMode === ISE_MODE_TRIT) {
572
+ const numBlocks = divRoundUp(numValues, 5);
573
+ for (let blockIndex = 0; blockIndex < numBlocks; blockIndex++) {
574
+ const isLast = blockIndex === numBlocks - 1;
575
+ const numValuesInBlock = isLast ? numValues - 5 * (numBlocks - 1) : 5;
576
+ decodeTritBlock(out, 5 * blockIndex, numValuesInBlock, stream, numBits);
577
+ }
578
+ } else if (iseMode === ISE_MODE_QUINT) {
579
+ const numBlocks = divRoundUp(numValues, 3);
580
+ for (let blockIndex = 0; blockIndex < numBlocks; blockIndex++) {
581
+ const isLast = blockIndex === numBlocks - 1;
582
+ const numValuesInBlock = isLast ? numValues - 3 * (numBlocks - 1) : 3;
583
+ decodeQuintBlock(out, 3 * blockIndex, numValuesInBlock, stream, numBits);
584
+ }
585
+ } else {
586
+ for (let i = 0; i < numValues; i++) {
587
+ const value = stream.next(numBits);
588
+ const slot = i * ISE_STRIDE;
589
+ out[slot + ISE_M] = value;
590
+ out[slot + ISE_TQ] = 0;
591
+ out[slot + ISE_V] = value;
592
+ }
593
+ }
594
+ }
595
+
596
+ // ---------------------------------------------------------------- 端点解量化
597
+ //
598
+ // 三进制/五进制序列要先"复原"成 8 bit 颜色值:规格给的是查表 + 位拼,
599
+ // 这里的常量 Ca 与 B 的拼法都来自规格表,不能改写。
600
+
601
+ const ENDPOINT_UNQUANT_C = [204, 113, 93, 54, 44, 26, 22, 13, 11, 6, 5];
602
+
603
+ function unquantizeColorEndpoints(destination, iseResults, numEndpoints, iseMode, iseBits) {
604
+ if (iseMode === ISE_MODE_TRIT || iseMode === ISE_MODE_QUINT) {
605
+ const rangeCase = iseBits * 2 - (iseMode === ISE_MODE_TRIT ? 2 : 1);
606
+ const c = ENDPOINT_UNQUANT_C[rangeCase];
607
+ for (let endpointIndex = 0; endpointIndex < numEndpoints; endpointIndex++) {
608
+ const slot = endpointIndex * ISE_STRIDE;
609
+ const m = iseResults[slot + ISE_M];
610
+ const tq = iseResults[slot + ISE_TQ];
611
+ const a = bitAt(m, 0);
612
+ const b = bitAt(m, 1);
613
+ const cc = bitAt(m, 2);
614
+ const d = bitAt(m, 3);
615
+ const e = bitAt(m, 4);
616
+ const f = bitAt(m, 5);
617
+ const aBits = a === 0 ? 0 : (1 << 9) - 1;
618
+ let bBits;
619
+ switch (rangeCase) {
620
+ case 0: case 1: bBits = 0; break;
621
+ case 2: bBits = (b << 8) | (b << 4) | (b << 2) | (b << 1); break;
622
+ case 3: bBits = (b << 8) | (b << 3) | (b << 2); break;
623
+ case 4: bBits = (cc << 8) | (b << 7) | (cc << 3) | (b << 2) | (cc << 1) | b; break;
624
+ case 5: bBits = (cc << 8) | (b << 7) | (cc << 2) | (b << 1) | cc; break;
625
+ case 6: bBits = (d << 8) | (cc << 7) | (b << 6) | (d << 2) | (cc << 1) | b; break;
626
+ case 7: bBits = (d << 8) | (cc << 7) | (b << 6) | (d << 1) | cc; break;
627
+ case 8: bBits = (e << 8) | (d << 7) | (cc << 6) | (b << 5) | (e << 1) | d; break;
628
+ case 9: bBits = (e << 8) | (d << 7) | (cc << 6) | (b << 5) | e; break;
629
+ case 10: bBits = (f << 8) | (e << 7) | (d << 6) | (cc << 5) | (b << 4) | f; break;
630
+ default: throw fail('TEXTURE_DECODE', `ASTC 端点解量化:非法范围档位 ${rangeCase}`);
631
+ }
632
+ destination[endpointIndex] = (((tq * c + bBits) ^ aBits) >> 2) | (aBits & 0x80);
633
+ }
634
+ return;
635
+ }
636
+ for (let endpointIndex = 0; endpointIndex < numEndpoints; endpointIndex++) {
637
+ destination[endpointIndex] = bitReplicationScale(
638
+ iseResults[endpointIndex * ISE_STRIDE + ISE_V], iseBits, 8);
639
+ }
640
+ }
641
+
642
+ // ---------------------------------------------------------------- 颜色端点合成
643
+ //
644
+ // 端点模式(CEM)决定"这两个端点怎么解释成 RGBA":纯亮度 / 亮度+增量 / RGB / RGB+缩放 …
645
+ // 模式 2/3/7/11/14/15 属 HDR(用 FP16 表示亮度),本解码器不支持 → 抛"格式未支持"。
646
+
647
+ const HDR_ENDPOINT_MODES = new Set([2, 3, 7, 11, 14, 15]);
648
+
649
+ function isHdrEndpointMode(endpointMode) {
650
+ return HDR_ENDPOINT_MODES.has(endpointMode);
651
+ }
652
+
653
+ /**
654
+ * 有符号位转移(规格里的 bit_transfer_signed):把一个无符号量拆成"符号位 + 幅值"。
655
+ * 注意它成对作用且**参数次序有语义**:第一个参数 a 贡献"符号位(bit7) + 幅值(bit0..5)",
656
+ * 第二个参数 b 右移后接上符号位成为增量。调用处一律写 `[a, b] = bitTransferSigned(a, b)`,
657
+ * 次序写反(把结果对调赋值)不会报错,只会让"增量型端点模式"整片偏色 —— 实测踩过一次。
658
+ */
659
+ function bitTransferSigned(a, b) {
660
+ let nextB = b >> 1;
661
+ nextB |= a & 0x80;
662
+ let nextA = a >> 1;
663
+ nextA &= 0x3f;
664
+ if (bitAt(nextA, 5)) nextA -= 0x40;
665
+ return [nextA, nextB];
666
+ }
667
+
668
+ function clampByte(value) {
669
+ if (value < 0) return 0;
670
+ if (value > 0xff) return 0xff;
671
+ return value;
672
+ }
673
+
674
+ function blueContract(r, g, b, a) {
675
+ return [clampByte((r + b) >> 1), clampByte((g + b) >> 1), clampByte(b), clampByte(a)];
676
+ }
677
+
678
+ /**
679
+ * 把某分区的两个端点(各 4 通道)按端点模式算出来,写进扁平缓冲。
680
+ *
681
+ * 布局:out[outOffset + 0..3] = 端点 0 的 R,G,B,A;out[outOffset + 4..7] = 端点 1。
682
+ * 用扁平缓冲而不是"每块新建 {e0,e1} 对象":一张 1024² 的 5x5 纹理有 4 万个块,
683
+ * 每块再乘分区数就是十几万次小数组分配,实测这在总耗时里占了相当一块。
684
+ *
685
+ * @param {number} endpointMode 端点模式(0..15)
686
+ * @param {Array<number>} values 解量化后的端点值序列(复用缓冲,未使用的尾部可能是上一块的残留,
687
+ * 所以每个模式只许读自己的那 numValues 个)
688
+ * @param {number} valueOffset 本分区第一个端点值在 values 里的下标
689
+ * @param {Int32Array} out 输出缓冲
690
+ * @param {number} outOffset 本分区在输出缓冲里的起点
691
+ */
692
+ function decodeColorEndpointPair(endpointMode, values, valueOffset, out, outOffset) {
693
+ // 取值到局部变量:后面的分支直接读 v0..v7,避免反复算下标
694
+ const v0 = values[valueOffset];
695
+ const v1 = values[valueOffset + 1];
696
+ const v2 = values[valueOffset + 2];
697
+ const v3 = values[valueOffset + 3];
698
+ const v4 = values[valueOffset + 4];
699
+ const v5 = values[valueOffset + 5];
700
+ const v6 = values[valueOffset + 6];
701
+ const v7 = values[valueOffset + 7];
702
+
703
+ let e0r;
704
+ let e0g;
705
+ let e0b;
706
+ let e0a;
707
+ let e1r;
708
+ let e1g;
709
+ let e1b;
710
+ let e1a;
711
+
712
+ switch (endpointMode) {
713
+ case 0:
714
+ e0r = v0; e0g = v0; e0b = v0; e0a = 0xff;
715
+ e1r = v1; e1g = v1; e1b = v1; e1a = 0xff;
716
+ break;
717
+ case 1: {
718
+ const l0 = (v0 >> 2) | (((v1 >> 6) & 0x3) << 6);
719
+ const l1 = Math.min(0xff, l0 + (v1 & 0x3f));
720
+ e0r = l0; e0g = l0; e0b = l0; e0a = 0xff;
721
+ e1r = l1; e1g = l1; e1b = l1; e1a = 0xff;
722
+ break;
723
+ }
724
+ case 4:
725
+ e0r = v0; e0g = v0; e0b = v0; e0a = v2;
726
+ e1r = v1; e1g = v1; e1b = v1; e1a = v3;
727
+ break;
728
+ case 5: {
729
+ // 参考实现的调用形状是 bitTransferSigned(v1, v0):第一参数取符号与幅值,第二参数接上符号位后右移。
730
+ // 落地到端点时**第一个端点用的是第二参数(b 结果)**,第二个端点是"b 结果 + a 结果"。
731
+ // 这个对应关系写反不会报错,只会让增量型端点整体偏色(实测踩过一次)。
732
+ const [v1Signed, v0Delta] = bitTransferSigned(v1, v0);
733
+ const [v3Signed, v2Delta] = bitTransferSigned(v3, v2);
734
+ e0r = clampByte(v0Delta); e0g = clampByte(v0Delta); e0b = clampByte(v0Delta); e0a = clampByte(v2Delta);
735
+ const luma1 = clampByte(v0Delta + v1Signed);
736
+ const alpha1 = clampByte(v2Delta + v3Signed);
737
+ e1r = luma1; e1g = luma1; e1b = luma1; e1a = alpha1;
738
+ break;
739
+ }
740
+ case 6:
741
+ e0r = (v0 * v3) >> 8; e0g = (v1 * v3) >> 8; e0b = (v2 * v3) >> 8; e0a = 0xff;
742
+ e1r = v0; e1g = v1; e1b = v2; e1a = 0xff;
743
+ break;
744
+ case 8: {
745
+ if (v1 + v3 + v5 >= v0 + v2 + v4) {
746
+ e0r = v0; e0g = v2; e0b = v4; e0a = 0xff;
747
+ e1r = v1; e1g = v3; e1b = v5; e1a = 0xff;
748
+ } else {
749
+ const first = blueContract(v1, v3, v5, 0xff);
750
+ const second = blueContract(v0, v2, v4, 0xff);
751
+ e0r = first[0]; e0g = first[1]; e0b = first[2]; e0a = first[3];
752
+ e1r = second[0]; e1g = second[1]; e1b = second[2]; e1a = second[3];
753
+ }
754
+ break;
755
+ }
756
+ case 9: {
757
+ const [rSigned, rDelta] = bitTransferSigned(v1, v0);
758
+ const [gSigned, gDelta] = bitTransferSigned(v3, v2);
759
+ const [bSigned, bDelta] = bitTransferSigned(v5, v4);
760
+ if (rSigned + gSigned + bSigned >= 0) {
761
+ e0r = clampByte(rDelta); e0g = clampByte(gDelta); e0b = clampByte(bDelta); e0a = 0xff;
762
+ e1r = clampByte(rDelta + rSigned); e1g = clampByte(gDelta + gSigned);
763
+ e1b = clampByte(bDelta + bSigned); e1a = 0xff;
764
+ } else {
765
+ const first = blueContract(rDelta + rSigned, gDelta + gSigned, bDelta + bSigned, 0xff);
766
+ const second = blueContract(rDelta, gDelta, bDelta, 0xff);
767
+ e0r = first[0]; e0g = first[1]; e0b = first[2]; e0a = first[3];
768
+ e1r = second[0]; e1g = second[1]; e1b = second[2]; e1a = second[3];
769
+ }
770
+ break;
771
+ }
772
+ case 10:
773
+ e0r = (v0 * v3) >> 8; e0g = (v1 * v3) >> 8; e0b = (v2 * v3) >> 8; e0a = v4;
774
+ e1r = v0; e1g = v1; e1b = v2; e1a = v5;
775
+ break;
776
+ case 12: {
777
+ if (v1 + v3 + v5 >= v0 + v2 + v4) {
778
+ e0r = v0; e0g = v2; e0b = v4; e0a = v6;
779
+ e1r = v1; e1g = v3; e1b = v5; e1a = v7;
780
+ } else {
781
+ const first = blueContract(v1, v3, v5, v7);
782
+ const second = blueContract(v0, v2, v4, v6);
783
+ e0r = first[0]; e0g = first[1]; e0b = first[2]; e0a = first[3];
784
+ e1r = second[0]; e1g = second[1]; e1b = second[2]; e1a = second[3];
785
+ }
786
+ break;
787
+ }
788
+ case 13: {
789
+ const [rSigned, rDelta] = bitTransferSigned(v1, v0);
790
+ const [gSigned, gDelta] = bitTransferSigned(v3, v2);
791
+ const [bSigned, bDelta] = bitTransferSigned(v5, v4);
792
+ const [aSigned, aDelta] = bitTransferSigned(v7, v6);
793
+ if (rSigned + gSigned + bSigned >= 0) {
794
+ e0r = clampByte(rDelta); e0g = clampByte(gDelta); e0b = clampByte(bDelta); e0a = clampByte(aDelta);
795
+ e1r = clampByte(rDelta + rSigned); e1g = clampByte(gDelta + gSigned);
796
+ e1b = clampByte(bDelta + bSigned); e1a = clampByte(aDelta + aSigned);
797
+ } else {
798
+ const first = blueContract(rDelta + rSigned, gDelta + gSigned, bDelta + bSigned, aDelta + aSigned);
799
+ const second = blueContract(rDelta, gDelta, bDelta, aDelta);
800
+ e0r = first[0]; e0g = first[1]; e0b = first[2]; e0a = first[3];
801
+ e1r = second[0]; e1g = second[1]; e1b = second[2]; e1a = second[3];
802
+ }
803
+ break;
804
+ }
805
+ default:
806
+ // 2 / 3 / 7 / 11 / 14 / 15 是 HDR 模式(FP16 亮度),本解码器不做;
807
+ // 其余未列举的取值在规格里不存在,同属"数据不对"。
808
+ if (isHdrEndpointMode(endpointMode)) {
809
+ throw fail('TEXTURE_FORMAT_UNSUPPORTED',
810
+ `ASTC 端点模式 ${endpointMode} 属 HDR(FP16 亮度),本解码器只实现 LDR`);
811
+ }
812
+ throw fail('TEXTURE_DECODE', `ASTC 端点模式 ${endpointMode} 非法`);
813
+ }
814
+
815
+ out[outOffset + 0] = e0r;
816
+ out[outOffset + 1] = e0g;
817
+ out[outOffset + 2] = e0b;
818
+ out[outOffset + 3] = e0a;
819
+ out[outOffset + 4] = e1r;
820
+ out[outOffset + 5] = e1g;
821
+ out[outOffset + 6] = e1b;
822
+ out[outOffset + 7] = e1a;
823
+ }
824
+
825
+ /** 每种端点模式用多少个端点值(模式除以 4 再加 1,再乘 2 —— 两个端点各一套) */
826
+ function computeNumEndpointValuesPerMode(endpointMode) {
827
+ return (Math.floor(endpointMode / 4) + 1) * 2;
828
+ }
829
+
830
+ /**
831
+ * 解码各分区的端点模式(CEM)。
832
+ * 单分区直接取 4 bit;多分区时先看"是否所有分区同模式",不同则按高低位组合出来。
833
+ */
834
+ function decodeColorEndpointModes(block, numPartitions, extraCemBitsStart) {
835
+ const modes = new Array(numPartitions).fill(0);
836
+ if (numPartitions === 1) {
837
+ modes[0] = block.bits(13, 16);
838
+ return modes;
839
+ }
840
+ const highLevelSelector = block.bits(23, 24);
841
+ if (highLevelSelector === 0) {
842
+ const mode = block.bits(25, 28);
843
+ for (let i = 0; i < numPartitions; i++) modes[i] = mode;
844
+ return modes;
845
+ }
846
+ for (let partitionIndex = 0; partitionIndex < numPartitions; partitionIndex++) {
847
+ const cemClass = highLevelSelector - (block.bitAt(25 + partitionIndex) ? 0 : 1);
848
+ const lowBit0Index = numPartitions + 2 * partitionIndex;
849
+ const lowBit1Index = numPartitions + 2 * partitionIndex + 1;
850
+ const lowBit0 = block.bitAt(lowBit0Index < 4 ? 25 + lowBit0Index : extraCemBitsStart + lowBit0Index - 4);
851
+ const lowBit1 = block.bitAt(lowBit1Index < 4 ? 25 + lowBit1Index : extraCemBitsStart + lowBit1Index - 4);
852
+ modes[partitionIndex] = (cemClass << 2) | (lowBit1 << 1) | lowBit0;
853
+ }
854
+ return modes;
855
+ }
856
+
857
+ function computeTotalEndpointValues(endpointModes) {
858
+ let total = 0;
859
+ for (const mode of endpointModes) total += computeNumEndpointValuesPerMode(mode);
860
+ return total;
861
+ }
862
+
863
+ // ---------------------------------------------------------------- 权重
864
+ //
865
+ // 权重是"每个网格点的混合系数",量化到 6 bit(0..64)后插值到每个纹素。
866
+ // 末端的 +1 修正(>32 加 1)是规格要求的"把 [0,63] 映射到 [0,64]"的非线性铺展。
867
+
868
+ const WEIGHT_UNQUANT_C = [50, 28, 23, 13, 11];
869
+
870
+ /**
871
+ * 解量化权重网格。
872
+ * @param {Int32Array} weightGrid 网格上的原始整数序列(扁平 3 槽布局,见 ISE_STRIDE)
873
+ * @param {number} numWeights 网格点数(双平面时含两个平面)
874
+ * @param {number} weightMode 整数序列编码模式
875
+ * @param {number} weightBits 每值额外的原始位数
876
+ * @param {Array<number>} weights 输出(复用调用方的 64 槽缓冲,避免每块新建数组)
877
+ */
878
+ function unquantizeWeights(weightGrid, numWeights, weightMode, weightBits, weights) {
879
+ if (weightMode === ISE_MODE_TRIT || weightMode === ISE_MODE_QUINT) {
880
+ const rangeCase = weightBits * 2 + (weightMode === ISE_MODE_QUINT ? 1 : 0);
881
+ if (rangeCase === 0 || rangeCase === 1) {
882
+ const map0 = [0, 32, 63];
883
+ const map1 = [0, 16, 32, 47, 63];
884
+ const map = rangeCase === 0 ? map0 : map1;
885
+ for (let i = 0; i < numWeights; i++) {
886
+ weights[i] = map[weightGrid[i * ISE_STRIDE + ISE_V]];
887
+ }
888
+ } else {
889
+ const c = WEIGHT_UNQUANT_C[rangeCase - 2];
890
+ for (let i = 0; i < numWeights; i++) {
891
+ const slot = i * ISE_STRIDE;
892
+ const m = weightGrid[slot + ISE_M];
893
+ const tq = weightGrid[slot + ISE_TQ];
894
+ const a = bitAt(m, 0);
895
+ const b = bitAt(m, 1);
896
+ const cc = bitAt(m, 2);
897
+ const aBits = a === 0 ? 0 : (1 << 7) - 1;
898
+ let bBits;
899
+ switch (rangeCase) {
900
+ case 2: case 3: bBits = 0; break;
901
+ case 4: bBits = (b << 6) | (b << 2) | b; break;
902
+ case 5: bBits = (b << 6) | (b << 1); break;
903
+ case 6: bBits = (cc << 6) | (b << 5) | (cc << 1) | b; break;
904
+ default: throw fail('TEXTURE_DECODE', `ASTC 权重解量化:非法范围档位 ${rangeCase}`);
905
+ }
906
+ weights[i] = (((tq * c + bBits) ^ aBits) >> 2) | (aBits & 0x20);
907
+ }
908
+ }
909
+ } else {
910
+ for (let i = 0; i < numWeights; i++) {
911
+ weights[i] = bitReplicationScale(weightGrid[i * ISE_STRIDE + ISE_V], weightBits, 6);
912
+ }
913
+ }
914
+ // 非线性的最后一步:>32 的值整体上抬 1,使 [0,63] 的量化级更均匀地铺到 [0,64]
915
+ for (let i = 0; i < numWeights; i++) weights[i] += weights[i] > 32 ? 1 : 0;
916
+ // 网格之外的槽位填"毒值"(0xFFFFFFFF):它们**只会**被权重为 0 的系数乘到,
917
+ // 用毒值能让"万一某处系数不该为 0 却为 0"的 bug 变成明显偏差而不是静默正确。
918
+ for (let i = numWeights; i < MAX_WEIGHTS; i++) weights[i] = 0xffffffff;
919
+ }
920
+
921
+ /**
922
+ * 把权重网格双线性插值到每个纹素。
923
+ *
924
+ * 关键点:网格点与纹素的映射用整数定点(16 倍分辨率),四舍五入常数 8 与 32 都是规格值;
925
+ * 网格索引可能越界一格(右/下边界),此时对应权重系数必为 0,所以用 & 0x3f 把地址折回数组内
926
+ * ——越界读必须"折回但系数为 0",直接越界会读到别的格子的权重,边界纹素就会错。
927
+ */
928
+ function interpolateWeights(blockWidth, blockHeight, mode, weights, texelWeights) {
929
+ const numWeightsPerTexel = mode.isDualPlane ? 2 : 1;
930
+ const scaleX = Math.floor((1024 + blockWidth / 2) / (blockWidth - 1));
931
+ const scaleY = Math.floor((1024 + blockHeight / 2) / (blockHeight - 1));
932
+ for (let texelY = 0; texelY < blockHeight; texelY++) {
933
+ for (let texelX = 0; texelX < blockWidth; texelX++) {
934
+ const gx = (scaleX * texelX * (mode.weightGridWidth - 1) + 32) >> 6;
935
+ const gy = (scaleY * texelY * (mode.weightGridHeight - 1) + 32) >> 6;
936
+ const jx = gx >> 4;
937
+ const jy = gy >> 4;
938
+ const fx = gx & 0xf;
939
+ const fy = gy & 0xf;
940
+ const w11 = (fx * fy + 8) >> 4;
941
+ const w10 = fy - w11;
942
+ const w01 = fx - w11;
943
+ const w00 = 16 - fx - fy + w11;
944
+ const i00 = jy * mode.weightGridWidth + jx;
945
+ const i01 = i00 + 1;
946
+ const i10 = i00 + mode.weightGridWidth;
947
+ const i11 = i00 + mode.weightGridWidth + 1;
948
+ const target = (texelY * blockWidth + texelX) * 2;
949
+ for (let plane = 0; plane < numWeightsPerTexel; plane++) {
950
+ const p00 = weights[(i00 * numWeightsPerTexel + plane) & 0x3f];
951
+ const p01 = weights[(i01 * numWeightsPerTexel + plane) & 0x3f];
952
+ const p10 = weights[(i10 * numWeightsPerTexel + plane) & 0x3f];
953
+ const p11 = weights[(i11 * numWeightsPerTexel + plane) & 0x3f];
954
+ texelWeights[target + plane] = (p00 * w00 + p01 * w01 + p10 * w10 + p11 * w11 + 8) >> 4;
955
+ }
956
+ }
957
+ }
958
+ }
959
+
960
+ /**
961
+ * 解出整个块的权重:从 bit 127 往回读,再解量化、插值。
962
+ * @param {Int32Array} texelWeights 输出(每个纹素 2 个槽:平面 0 与平面 1,单平面时只有槽 0 有意义)
963
+ * @param {object} scratch 可复用的临时缓冲(weightGrid / unquantizedWeights / weightStream)
964
+ */
965
+ function computeTexelWeights(block, blockWidth, blockHeight, mode, texelWeights, scratch) {
966
+ const numWeights = computeNumWeights(mode);
967
+ const numWeightBits = computeNumRequiredBits(mode.weightMode, mode.weightBits, numWeights);
968
+ // 权重从块尾往前读,所以方向是 false(位号递减)
969
+ scratch.weightStream.reset(block, 127, numWeightBits, false);
970
+ decodeIESequence(scratch.weightGrid, numWeights, scratch.weightStream, mode.weightMode, mode.weightBits);
971
+ unquantizeWeights(scratch.weightGrid, numWeights, mode.weightMode, mode.weightBits, scratch.unquantizedWeights);
972
+ interpolateWeights(blockWidth, blockHeight, mode, scratch.unquantizedWeights, texelWeights);
973
+ }
974
+
975
+ // ---------------------------------------------------------------- 分区
976
+ //
977
+ // 多分区时每个纹素归哪个分区由"哈希"决定(规格用 hash52 制造伪随机但确定的图案)。
978
+ // 必须与规格逐位一致,否则同一块的纹素会被分到别的分区,颜色出现噪点。
979
+
980
+ function hash52(value) {
981
+ let p = value >>> 0;
982
+ p = (p ^ (p >>> 15)) >>> 0;
983
+ p = (p - (p << 17)) >>> 0;
984
+ p = (p + (p << 7)) >>> 0;
985
+ p = (p + (p << 4)) >>> 0;
986
+ p = (p ^ (p >>> 5)) >>> 0;
987
+ p = (p + (p << 16)) >>> 0;
988
+ p = (p ^ (p >>> 7)) >>> 0;
989
+ p = (p ^ (p >>> 3)) >>> 0;
990
+ p = (p ^ (p << 6)) >>> 0;
991
+ p = (p ^ (p >>> 17)) >>> 0;
992
+ return p;
993
+ }
994
+
995
+ /**
996
+ * 预处理某个块的"分区种子状态"。
997
+ *
998
+ * 为什么要拆成两步:种子只跟分区数、partition_id 有关,**与纹素坐标无关**。
999
+ * 原来每个纹素都重算一遍 hash52 + 12 次平方 + 位移,块内重复 16~144 次;
1000
+ * 提到块级只算一次之后,同样的输出快了一倍以上(实测 1024² 5x5:1.6s → 0.4s 级)。
1001
+ * @param {number} seedIn 块内 partition_id
1002
+ * @param {number} numPartitions 分区数
1003
+ */
1004
+ function buildPartitionSeedState(seedIn, numPartitions) {
1005
+ const seed = (seedIn + 1024 * (numPartitions - 1)) >>> 0;
1006
+ const rnum = hash52(seed);
1007
+
1008
+ // 12 个 4 bit 种子:规格把它们分别按不同位移拼出来,再做"平方 + 右移"混洗
1009
+ const nibbles = [
1010
+ rnum & 0xf, // seed1
1011
+ (rnum >>> 4) & 0xf, // seed2
1012
+ (rnum >>> 8) & 0xf, // seed3
1013
+ (rnum >>> 12) & 0xf, // seed4
1014
+ (rnum >>> 16) & 0xf, // seed5
1015
+ (rnum >>> 20) & 0xf, // seed6
1016
+ (rnum >>> 24) & 0xf, // seed7
1017
+ (rnum >>> 28) & 0xf, // seed8
1018
+ (rnum >>> 18) & 0xf, // seed9
1019
+ (rnum >>> 22) & 0xf, // seed10
1020
+ (rnum >>> 26) & 0xf, // seed11
1021
+ ((rnum >>> 30) | (rnum << 2)) & 0xf, // seed12(高位绕回)
1022
+ ];
1023
+ // 平方后截到 8 bit(对应规格里"以字节为单位"的溢出行为)
1024
+ const seeds = nibbles.map((nibble) => (nibble * nibble) & 0xff);
1025
+
1026
+ const shiftA = (seed & 2) !== 0 ? 4 : 5;
1027
+ const shiftB = numPartitions === 3 ? 6 : 5;
1028
+ const shift1 = (seed & 1) !== 0 ? shiftA : shiftB;
1029
+ const shift2 = (seed & 1) !== 0 ? shiftB : shiftA;
1030
+ const shift3 = (seed & 0x10) !== 0 ? shift1 : shift2;
1031
+
1032
+ // 位移各不相同的四组:seed1..8 交替用 shift1/shift2,seed9..12 统一用 shift3
1033
+ const shifts = [shift1, shift2, shift1, shift2, shift1, shift2, shift1, shift2,
1034
+ shift3, shift3, shift3, shift3];
1035
+ for (let i = 0; i < 12; i++) seeds[i] >>>= shifts[i];
1036
+
1037
+ return {
1038
+ seed1: seeds[0], seed2: seeds[1], seed3: seeds[2], seed4: seeds[3],
1039
+ seed5: seeds[4], seed6: seeds[5], seed7: seeds[6], seed8: seeds[7],
1040
+ seed9: seeds[8], seed10: seeds[9], seed11: seeds[10], seed12: seeds[11],
1041
+ rnum14: rnum >>> 14,
1042
+ rnum10: rnum >>> 10,
1043
+ rnum6: rnum >>> 6,
1044
+ rnum2: rnum >>> 2,
1045
+ numPartitions,
1046
+ };
1047
+ }
1048
+
1049
+ /** 算某个纹素属于第几个分区(seed 状态由 buildPartitionSeedState 预算好;小块坐标要左移一位) */
1050
+ function partitionIndexForTexel(state, xIn, yIn, smallBlock) {
1051
+ const x = smallBlock ? xIn << 1 : xIn;
1052
+ const y = smallBlock ? yIn << 1 : yIn;
1053
+ const a = (state.seed1 * x + state.seed2 * y + state.rnum14) & 0x3f;
1054
+ const b = (state.seed3 * x + state.seed4 * y + state.rnum10) & 0x3f;
1055
+ const c = state.numPartitions >= 3 ? (state.seed5 * x + state.seed6 * y + state.rnum6) & 0x3f : 0;
1056
+ const d = state.numPartitions >= 4 ? (state.seed7 * x + state.seed8 * y + state.rnum2) & 0x3f : 0;
1057
+ if (a >= b && a >= c && a >= d) return 0;
1058
+ if (b >= c && b >= d) return 1;
1059
+ if (c >= d) return 2;
1060
+ return 3;
1061
+ }
1062
+
1063
+ // ---------------------------------------------------------------- 块解码主流程
1064
+
1065
+ /**
1066
+ * 建一份"跨块复用"的临时缓冲。
1067
+ *
1068
+ * 为什么不在每块里 new:一张 2048² 的 4x4 纹理有 26 万个块,每块新建十来个对象/小数组
1069
+ * 会产生明显的 GC 抖动(实测在 1024² 5x5 上占约三分之一总耗时)。这些缓冲的长度都只与
1070
+ * "块内最大纹素数"有关,与具体图片无关,所以整张图解一次只需一份。
1071
+ */
1072
+ function createDecodeScratch() {
1073
+ return {
1074
+ // 每块的端点整数序列(原值 / 解量化后),最多 18 个;原值用扁平 3 槽布局
1075
+ endpointValues: new Int32Array(MAX_ENDPOINT_VALUES * ISE_STRIDE),
1076
+ unquantizedEndpoints: new Int32Array(MAX_ENDPOINT_VALUES),
1077
+ // 每块最多 4 个分区,每分区 8 个端点通道(2 个端点 × RGBA)
1078
+ endpointPairs: new Int32Array(4 * 8),
1079
+ // 每个纹素 2 个权重槽(平面 0 / 平面 1)
1080
+ texelWeights: new Int32Array(MAX_BLOCK_SIDE * MAX_BLOCK_SIDE * 2),
1081
+ // 权重网格(最多 64 个,扁平 3 槽布局)与其解量化结果
1082
+ weightGrid: new Int32Array(MAX_WEIGHTS * ISE_STRIDE),
1083
+ unquantizedWeights: new Array(MAX_WEIGHTS),
1084
+ // 两个位流:端点从中间往后读、权重从块尾往前读
1085
+ endpointStream: new BitStream(null, 0, 0, true),
1086
+ weightStream: new BitStream(null, 0, 0, false),
1087
+ };
1088
+ }
1089
+
1090
+ /**
1091
+ * 解一个块到 dst(RGBA,按块内行优先)。
1092
+ *
1093
+ * 出错一律抛错(不填错误色),理由见文件头:本项目要求"失败可读、不产出半成品"。
1094
+ * @param {Uint8Array} destination 输出缓冲(长度 ≥ blockWidth*blockHeight*4)
1095
+ * @param {BlockBits} block 块位访问器
1096
+ * @param {number} blockWidth 块宽
1097
+ * @param {number} blockHeight 块高
1098
+ * @param {object} scratch 跨块复用的临时缓冲(见 createDecodeScratch,避免每块新建十几个小数组)
1099
+ */
1100
+ function decompressBlock(destination, block, blockWidth, blockHeight, scratch) {
1101
+ const mode = readBlockMode(block);
1102
+ if (mode.isError) {
1103
+ throw fail('TEXTURE_DECODE', 'ASTC 块模式非法(保留取值),数据可能不是 ASTC 或用错了块尺寸');
1104
+ }
1105
+
1106
+ if (mode.isVoidExtent) {
1107
+ decodeVoidExtentBlock(destination, block, blockWidth, blockHeight);
1108
+ return;
1109
+ }
1110
+
1111
+ const numWeights = computeNumWeights(mode);
1112
+ const numWeightDataBits = computeNumRequiredBits(mode.weightMode, mode.weightBits, numWeights);
1113
+ const numPartitions = block.bits(11, 12) + 1;
1114
+
1115
+ // 这几条是规格允许的合法性边界;任何一条越界都说明"数据布局与假设不符"
1116
+ // (最常见原因:块尺寸传错,或者这根本不是 ASTC 数据)
1117
+ if (numWeights > MAX_WEIGHTS
1118
+ || numWeightDataBits > 96
1119
+ || numWeightDataBits < 24
1120
+ || mode.weightGridWidth > blockWidth
1121
+ || mode.weightGridHeight > blockHeight
1122
+ || (numPartitions === 4 && mode.isDualPlane)) {
1123
+ throw fail('TEXTURE_DECODE',
1124
+ `ASTC 块参数越界(权重 ${numWeights} 个 / 权重位 ${numWeightDataBits} / 网格 `
1125
+ + `${mode.weightGridWidth}x${mode.weightGridHeight} / 分区 ${numPartitions} / 双平面 ${mode.isDualPlane})`);
1126
+ }
1127
+
1128
+ // 端点模式与端点数据的位置取决于"分区数"与"是否所有分区同模式",位段是错开的
1129
+ const isSingleUniqueCem = numPartitions === 1 || block.bits(23, 24) === 0;
1130
+ const numConfigDataBits = (numPartitions === 1 ? 17 : isSingleUniqueCem ? 29 : 25 + 3 * numPartitions)
1131
+ + (mode.isDualPlane ? 2 : 0);
1132
+ const numBitsForColorEndpoints = 128 - numWeightDataBits - numConfigDataBits;
1133
+ const extraCemBitsStart = 127 - numWeightDataBits - (isSingleUniqueCem ? -1
1134
+ : numPartitions === 4 ? 7
1135
+ : numPartitions === 3 ? 4
1136
+ : numPartitions === 2 ? 1
1137
+ : 0);
1138
+
1139
+ const endpointModes = decodeColorEndpointModes(block, numPartitions, extraCemBitsStart);
1140
+ const numEndpointValues = computeTotalEndpointValues(endpointModes);
1141
+ if (numEndpointValues > MAX_ENDPOINT_VALUES
1142
+ || numBitsForColorEndpoints < divRoundUp(13 * numEndpointValues, 5)) {
1143
+ throw fail('TEXTURE_DECODE',
1144
+ `ASTC 端点数据越界(端点值 ${numEndpointValues} 个,可用位 ${numBitsForColorEndpoints})`);
1145
+ }
1146
+
1147
+ const colorEndpointDataStart = numPartitions === 1 ? 17 : 29;
1148
+ scratch.endpointStream.reset(block, colorEndpointDataStart, numBitsForColorEndpoints, true);
1149
+ const endpointIseParams = computeMaximumRangeISEParams(numBitsForColorEndpoints, numEndpointValues);
1150
+ decodeIESequence(scratch.endpointValues, numEndpointValues, scratch.endpointStream,
1151
+ endpointIseParams.mode, endpointIseParams.numBits);
1152
+
1153
+ unquantizeColorEndpoints(scratch.unquantizedEndpoints, scratch.endpointValues, numEndpointValues,
1154
+ endpointIseParams.mode, endpointIseParams.numBits);
1155
+
1156
+ // 端点 → 每个分区的一对 RGBA 端点(写进扁平缓冲:分区 n 的 8 个通道在 n*8 起)
1157
+ let unquantizedIndex = 0;
1158
+ for (let partitionIndex = 0; partitionIndex < numPartitions; partitionIndex++) {
1159
+ const endpointMode = endpointModes[partitionIndex];
1160
+ const valuesPerMode = computeNumEndpointValuesPerMode(endpointMode);
1161
+ decodeColorEndpointPair(endpointMode, scratch.unquantizedEndpoints, unquantizedIndex,
1162
+ scratch.endpointPairs, partitionIndex * 8);
1163
+ unquantizedIndex += valuesPerMode;
1164
+ }
1165
+
1166
+ // 权重:网格 → 每个纹素(扁平缓冲,每个纹素 2 槽对应两个平面)
1167
+ computeTexelWeights(block, blockWidth, blockHeight, mode, scratch.texelWeights, scratch);
1168
+
1169
+ // 双平面时,第二平面服务哪一个颜色通道由 extraCemBitsStart 前的两位给出
1170
+ const channelOfSecondPlane = mode.isDualPlane
1171
+ ? block.bits(extraCemBitsStart - 2, extraCemBitsStart - 1)
1172
+ : -1;
1173
+ const partitionState = numPartitions > 1
1174
+ ? buildPartitionSeedState(block.bits(13, 22), numPartitions)
1175
+ : null;
1176
+ const smallBlock = blockWidth * blockHeight < 31;
1177
+ const texelWeights = scratch.texelWeights;
1178
+ const endpointPairs = scratch.endpointPairs;
1179
+
1180
+ for (let texelY = 0; texelY < blockHeight; texelY++) {
1181
+ for (let texelX = 0; texelX < blockWidth; texelX++) {
1182
+ const texelIndex = texelY * blockWidth + texelX;
1183
+ const partitionIndex = partitionState === null
1184
+ ? 0
1185
+ : partitionIndexForTexel(partitionState, texelX, texelY, smallBlock);
1186
+ const endpointBase = partitionIndex * 8;
1187
+ const weightBase = texelIndex * 2;
1188
+ for (let channel = 0; channel < 4; channel++) {
1189
+ const weightValue = texelWeights[weightBase + (channelOfSecondPlane === channel ? 1 : 0)];
1190
+ // 端点值(0..0xFF)按权重线性混合后降到 8 bit。
1191
+ //
1192
+ // 这里的换算次序不是随手写的,是"与权威参考逐像素对齐"的结果:
1193
+ // ① 端点先铺成 16 bit(`v<<8 | v`,即 v*257)——满量程 255 正好对应 65535;
1194
+ // ② 用 (64 - w) 与 w 做线性混合,加 32 是四舍五入位,>>6 落到 16 bit 域;
1195
+ // ③ 最后用 ×255/65536 折回 8 bit(+32768 再整除,等价于四舍五入)。
1196
+ // 少了第 ③ 步(直接 >>8)会得到"看着对、整体差 1"的结果:实测 440² 有 1566 个像素
1197
+ // 各差 1,肉眼看不出来但逐像素对照就红。端点铺法若用 `| 0x80`(量化桶中点)同理。
1198
+ const endpoint0 = endpointPairs[endpointBase + channel];
1199
+ const endpoint1 = endpointPairs[endpointBase + 4 + channel];
1200
+ const blended16 = (((endpoint0 << 8) | endpoint0) * (64 - weightValue)
1201
+ + ((endpoint1 << 8) | endpoint1) * weightValue + 32) >> 6;
1202
+ destination[texelIndex * 4 + channel] = Math.floor((blended16 * 255 + 32768) / 65536);
1203
+ }
1204
+ }
1205
+ }
1206
+ }
1207
+
1208
+ /**
1209
+ * 常数色块(void-extent):整块只有一个颜色,直接展开。
1210
+ * 该块形态里也允许"用 extent 坐标定义实心矩形",坐标是全 1 时表示覆盖整块 —— 两者都支持。
1211
+ */
1212
+ function decodeVoidExtentBlock(destination, block, blockWidth, blockHeight) {
1213
+ const minS = block.bits(12, 24);
1214
+ const maxS = block.bits(25, 37);
1215
+ const minT = block.bits(38, 50);
1216
+ const maxT = block.bits(51, 63);
1217
+ const hasHdrFlag = block.bitAt(9) !== 0;
1218
+ if (hasHdrFlag) {
1219
+ throw fail('TEXTURE_FORMAT_UNSUPPORTED', 'ASTC 常数色块标记为 HDR(FP16),本解码器只实现 LDR');
1220
+ }
1221
+ const allExtentsAllOnes = minS === 0x1fff && maxS === 0x1fff && minT === 0x1fff && maxT === 0x1fff;
1222
+ if (!allExtentsAllOnes && (minS >= maxS || minT >= maxT)) {
1223
+ throw fail('TEXTURE_DECODE', 'ASTC 常数色块的 extent 坐标非法(最小 >= 最大)');
1224
+ }
1225
+ const red = block.bits(64, 79);
1226
+ const green = block.bits(80, 95);
1227
+ const blue = block.bits(96, 111);
1228
+ const alpha = block.bits(112, 127);
1229
+ const rgba = [red, green, blue, alpha].map((value) => (value & 0xff00) >> 8);
1230
+ for (let i = 0; i < blockWidth * blockHeight; i++) {
1231
+ destination[i * 4 + 0] = rgba[0];
1232
+ destination[i * 4 + 1] = rgba[1];
1233
+ destination[i * 4 + 2] = rgba[2];
1234
+ destination[i * 4 + 3] = rgba[3];
1235
+ }
1236
+ }
1237
+
1238
+ // ---------------------------------------------------------------- 对外入口
1239
+
1240
+ /**
1241
+ * 解码一张 ASTC 纹理。
1242
+ *
1243
+ * @param {Uint8Array} data 压缩数据(宽高按块向上取整后的块数 × 16 字节)
1244
+ * @param {number} width 像素宽
1245
+ * @param {number} height 像素高
1246
+ * @param {number} blockWidth 块宽(ASTC 规格定义的 14 种之一)
1247
+ * @param {number} blockHeight 块高(与 blockWidth 成对取自同一张表)
1248
+ * @returns {Uint8Array} RGBA,长度 = width*height*4,**存储方向**(未做 flipY)
1249
+ */
1250
+ function decodeAstc(data, width, height, blockWidth, blockHeight) {
1251
+ if (!data || typeof data.length !== 'number') {
1252
+ throw fail('BAD_ARGS', 'ASTC 解码:缺少压缩数据');
1253
+ }
1254
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) {
1255
+ throw fail('BAD_ARGS', `ASTC 解码:宽高非法(${width}x${height})`);
1256
+ }
1257
+ // 块尺寸必须是规格表里的一对:ASTC 只有这 14 种组合(高度不超过宽度)。
1258
+ // 为什么严格校验而不是"≤12 就放行":3x3、7x7 这类尺寸不存在,放过去只会把
1259
+ // "格式号/块尺寸判断错"混淆成"数据长度不对"或解出一堆噪点,排查成本高得多。
1260
+ const blockKey = `${blockWidth}x${blockHeight}`;
1261
+ if (!Number.isInteger(blockWidth) || !Number.isInteger(blockHeight)
1262
+ || !ASTC_BLOCK_DIMENSIONS.has(blockKey)) {
1263
+ throw fail('TEXTURE_FORMAT_UNSUPPORTED',
1264
+ `ASTC 解码:块尺寸 ${blockKey} 不是合法组合(规格只定义 ${[...ASTC_BLOCK_DIMENSIONS].join('、')})`);
1265
+ }
1266
+
1267
+ const blocksX = divRoundUp(width, blockWidth);
1268
+ const blocksY = divRoundUp(height, blockHeight);
1269
+ const requiredBytes = blocksX * blocksY * BLOCK_BYTES;
1270
+ if (data.length < requiredBytes) {
1271
+ throw fail('TEXTURE_DATA_SHORT',
1272
+ `ASTC 数据不足:${width}x${height} 按 ${blockWidth}x${blockHeight} 分块需要 ${requiredBytes} 字节,`
1273
+ + `实际 ${data.length} 字节`);
1274
+ }
1275
+
1276
+ const output = new Uint8Array(width * height * 4);
1277
+ // 单块临时缓冲:块可能超出图像边界(宽高不是块边长的整数倍),逐块裁切拷贝
1278
+ const blockPixels = new Uint8Array(blockWidth * blockHeight * 4);
1279
+ // 跨块复用的临时缓冲与位访问器:每块新建十几个对象在 4 万块规模下会明显拖慢(实测占 1/3 时间)
1280
+ const scratch = createDecodeScratch();
1281
+ const block = new BlockBits(data, 0);
1282
+
1283
+ for (let blockY = 0; blockY < blocksY; blockY++) {
1284
+ for (let blockX = 0; blockX < blocksX; blockX++) {
1285
+ block.setOffset((blockY * blocksX + blockX) * BLOCK_BYTES);
1286
+ try {
1287
+ decompressBlock(blockPixels, block, blockWidth, blockHeight, scratch);
1288
+ } catch (error) {
1289
+ // 补上块坐标再抛:一张 1024² 的 5x5 纹理有 4 万多个块,没有坐标等于没线索
1290
+ error.message += `(块坐标 ${blockX},${blockY},块尺寸 ${blockWidth}x${blockHeight})`;
1291
+ throw error;
1292
+ }
1293
+ const copyWidth = Math.min(blockWidth, width - blockX * blockWidth);
1294
+ const copyHeight = Math.min(blockHeight, height - blockY * blockHeight);
1295
+ for (let row = 0; row < copyHeight; row++) {
1296
+ const sourceStart = row * blockWidth * 4;
1297
+ const targetY = blockY * blockHeight + row;
1298
+ const targetStart = (targetY * width + blockX * blockWidth) * 4;
1299
+ output.set(blockPixels.subarray(sourceStart, sourceStart + copyWidth * 4), targetStart);
1300
+ }
1301
+ }
1302
+ }
1303
+ return output;
1304
+ }
1305
+
1306
+ NS.astc = { decodeAstc };
1307
+ }