@aether-stack-dev/client-sdk 1.3.0 → 1.3.2

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.
package/dist/react.esm.js CHANGED
@@ -3,17 +3,18 @@ import { useState, useRef, useEffect, useCallback, useMemo } from 'react';
3
3
  import { EventEmitter } from 'eventemitter3';
4
4
  import { jsxs, jsx } from 'react/jsx-runtime';
5
5
  import * as THREE from 'three';
6
- import { DataTextureLoader, HalfFloatType, RGBAFormat, RGFormat, LinearSRGBColorSpace, RedFormat, FloatType, LinearFilter, DataUtils } from 'three';
7
6
  import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
8
7
  import { VRMLoaderPlugin, VRMHumanBoneName } from '@pixiv/three-vrm';
9
- import { VRMAnimationLoaderPlugin, createVRMAnimationClip } from '@pixiv/three-vrm-animation';
8
+ import { VRMLookAtQuaternionProxy, VRMAnimationLoaderPlugin, createVRMAnimationClip } from '@pixiv/three-vrm-animation';
10
9
  import { EffectComposer } from 'three/examples/jsm/postprocessing/EffectComposer.js';
11
10
  import { RenderPass } from 'three/examples/jsm/postprocessing/RenderPass.js';
12
11
  import { UnrealBloomPass } from 'three/examples/jsm/postprocessing/UnrealBloomPass.js';
13
12
  import { SSAOPass } from 'three/examples/jsm/postprocessing/SSAOPass.js';
14
13
  import { BokehPass } from 'three/examples/jsm/postprocessing/BokehPass.js';
15
14
  import { OutputPass } from 'three/examples/jsm/postprocessing/OutputPass.js';
16
- import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
15
+ import { HDRLoader } from 'three/examples/jsm/loaders/HDRLoader.js';
16
+ import { EXRLoader } from 'three/examples/jsm/loaders/EXRLoader.js';
17
+ import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
17
18
 
18
19
  const ARKIT_BLENDSHAPES = [
19
20
  'jawOpen', 'jawForward', 'jawLeft', 'jawRight',
@@ -933,3178 +934,76 @@ class FpsMonitor {
933
934
  }
934
935
  }
935
936
 
936
- /*!
937
- fflate - fast JavaScript compression/decompression
938
- <https://101arrowz.github.io/fflate>
939
- Licensed under MIT. https://github.com/101arrowz/fflate/blob/master/LICENSE
940
- version 0.8.2
941
- */
942
-
943
-
944
- // aliases for shorter compressed code (most minifers don't do this)
945
- var u8 = Uint8Array, u16 = Uint16Array, i32 = Int32Array;
946
- // fixed length extra bits
947
- var fleb = new u8([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, /* unused */ 0, 0, /* impossible */ 0]);
948
- // fixed distance extra bits
949
- var fdeb = new u8([0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, /* unused */ 0, 0]);
950
- // code length index map
951
- var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
952
- // get base, reverse index map from extra bits
953
- var freb = function (eb, start) {
954
- var b = new u16(31);
955
- for (var i = 0; i < 31; ++i) {
956
- b[i] = start += 1 << eb[i - 1];
957
- }
958
- // numbers here are at max 18 bits
959
- var r = new i32(b[30]);
960
- for (var i = 1; i < 30; ++i) {
961
- for (var j = b[i]; j < b[i + 1]; ++j) {
962
- r[j] = ((j - b[i]) << 5) | i;
963
- }
964
- }
965
- return { b: b, r: r };
966
- };
967
- var _a = freb(fleb, 2), fl = _a.b, revfl = _a.r;
968
- // we can ignore the fact that the other numbers are wrong; they never happen anyway
969
- fl[28] = 258, revfl[258] = 28;
970
- var _b = freb(fdeb, 0), fd = _b.b;
971
- // map of value to reverse (assuming 16 bits)
972
- var rev = new u16(32768);
973
- for (var i = 0; i < 32768; ++i) {
974
- // reverse table algorithm from SO
975
- var x = ((i & 0xAAAA) >> 1) | ((i & 0x5555) << 1);
976
- x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2);
977
- x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4);
978
- rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1;
979
- }
980
- // create huffman tree from u8 "map": index -> code length for code index
981
- // mb (max bits) must be at most 15
982
- // TODO: optimize/split up?
983
- var hMap = (function (cd, mb, r) {
984
- var s = cd.length;
985
- // index
986
- var i = 0;
987
- // u16 "map": index -> # of codes with bit length = index
988
- var l = new u16(mb);
989
- // length of cd must be 288 (total # of codes)
990
- for (; i < s; ++i) {
991
- if (cd[i])
992
- ++l[cd[i] - 1];
993
- }
994
- // u16 "map": index -> minimum code for bit length = index
995
- var le = new u16(mb);
996
- for (i = 1; i < mb; ++i) {
997
- le[i] = (le[i - 1] + l[i - 1]) << 1;
998
- }
999
- var co;
1000
- if (r) {
1001
- // u16 "map": index -> number of actual bits, symbol for code
1002
- co = new u16(1 << mb);
1003
- // bits to remove for reverser
1004
- var rvb = 15 - mb;
1005
- for (i = 0; i < s; ++i) {
1006
- // ignore 0 lengths
1007
- if (cd[i]) {
1008
- // num encoding both symbol and bits read
1009
- var sv = (i << 4) | cd[i];
1010
- // free bits
1011
- var r_1 = mb - cd[i];
1012
- // start value
1013
- var v = le[cd[i] - 1]++ << r_1;
1014
- // m is end value
1015
- for (var m = v | ((1 << r_1) - 1); v <= m; ++v) {
1016
- // every 16 bit value starting with the code yields the same result
1017
- co[rev[v] >> rvb] = sv;
1018
- }
1019
- }
1020
- }
1021
- }
1022
- else {
1023
- co = new u16(s);
1024
- for (i = 0; i < s; ++i) {
1025
- if (cd[i]) {
1026
- co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]);
1027
- }
1028
- }
1029
- }
1030
- return co;
1031
- });
1032
- // fixed length tree
1033
- var flt = new u8(288);
1034
- for (var i = 0; i < 144; ++i)
1035
- flt[i] = 8;
1036
- for (var i = 144; i < 256; ++i)
1037
- flt[i] = 9;
1038
- for (var i = 256; i < 280; ++i)
1039
- flt[i] = 7;
1040
- for (var i = 280; i < 288; ++i)
1041
- flt[i] = 8;
1042
- // fixed distance tree
1043
- var fdt = new u8(32);
1044
- for (var i = 0; i < 32; ++i)
1045
- fdt[i] = 5;
1046
- // fixed length map
1047
- var flrm = /*#__PURE__*/ hMap(flt, 9, 1);
1048
- // fixed distance map
1049
- var fdrm = /*#__PURE__*/ hMap(fdt, 5, 1);
1050
- // find max of array
1051
- var max = function (a) {
1052
- var m = a[0];
1053
- for (var i = 1; i < a.length; ++i) {
1054
- if (a[i] > m)
1055
- m = a[i];
1056
- }
1057
- return m;
1058
- };
1059
- // read d, starting at bit p and mask with m
1060
- var bits = function (d, p, m) {
1061
- var o = (p / 8) | 0;
1062
- return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m;
1063
- };
1064
- // read d, starting at bit p continuing for at least 16 bits
1065
- var bits16 = function (d, p) {
1066
- var o = (p / 8) | 0;
1067
- return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7));
1068
- };
1069
- // get end of byte
1070
- var shft = function (p) { return ((p + 7) / 8) | 0; };
1071
- // typed array slice - allows garbage collector to free original reference,
1072
- // while being more compatible than .slice
1073
- var slc = function (v, s, e) {
1074
- if (e == null || e > v.length)
1075
- e = v.length;
1076
- // can't use .constructor in case user-supplied
1077
- return new u8(v.subarray(s, e));
1078
- };
1079
- // error codes
1080
- var ec = [
1081
- 'unexpected EOF',
1082
- 'invalid block type',
1083
- 'invalid length/literal',
1084
- 'invalid distance',
1085
- 'stream finished',
1086
- 'no stream handler',
1087
- ,
1088
- 'no callback',
1089
- 'invalid UTF-8 data',
1090
- 'extra field too long',
1091
- 'date not in range 1980-2099',
1092
- 'filename too long',
1093
- 'stream finishing',
1094
- 'invalid zip data'
1095
- // determined by unknown compression method
1096
- ];
1097
- var err = function (ind, msg, nt) {
1098
- var e = new Error(msg || ec[ind]);
1099
- e.code = ind;
1100
- if (Error.captureStackTrace)
1101
- Error.captureStackTrace(e, err);
1102
- if (!nt)
1103
- throw e;
1104
- return e;
1105
- };
1106
- // expands raw DEFLATE data
1107
- var inflt = function (dat, st, buf, dict) {
1108
- // source length dict length
1109
- var sl = dat.length, dl = 0;
1110
- if (!sl || st.f && !st.l)
1111
- return buf || new u8(0);
1112
- var noBuf = !buf;
1113
- // have to estimate size
1114
- var resize = noBuf || st.i != 2;
1115
- // no state
1116
- var noSt = st.i;
1117
- // Assumes roughly 33% compression ratio average
1118
- if (noBuf)
1119
- buf = new u8(sl * 3);
1120
- // ensure buffer can fit at least l elements
1121
- var cbuf = function (l) {
1122
- var bl = buf.length;
1123
- // need to increase size to fit
1124
- if (l > bl) {
1125
- // Double or set to necessary, whichever is greater
1126
- var nbuf = new u8(Math.max(bl * 2, l));
1127
- nbuf.set(buf);
1128
- buf = nbuf;
1129
- }
1130
- };
1131
- // last chunk bitpos bytes
1132
- var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
1133
- // total bits
1134
- var tbts = sl * 8;
1135
- do {
1136
- if (!lm) {
1137
- // BFINAL - this is only 1 when last chunk is next
1138
- final = bits(dat, pos, 1);
1139
- // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman
1140
- var type = bits(dat, pos + 1, 3);
1141
- pos += 3;
1142
- if (!type) {
1143
- // go to end of byte boundary
1144
- var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l;
1145
- if (t > sl) {
1146
- if (noSt)
1147
- err(0);
1148
- break;
1149
- }
1150
- // ensure size
1151
- if (resize)
1152
- cbuf(bt + l);
1153
- // Copy over uncompressed data
1154
- buf.set(dat.subarray(s, t), bt);
1155
- // Get new bitpos, update byte count
1156
- st.b = bt += l, st.p = pos = t * 8, st.f = final;
1157
- continue;
1158
- }
1159
- else if (type == 1)
1160
- lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
1161
- else if (type == 2) {
1162
- // literal lengths
1163
- var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
1164
- var tl = hLit + bits(dat, pos + 5, 31) + 1;
1165
- pos += 14;
1166
- // length+distance tree
1167
- var ldt = new u8(tl);
1168
- // code length tree
1169
- var clt = new u8(19);
1170
- for (var i = 0; i < hcLen; ++i) {
1171
- // use index map to get real code
1172
- clt[clim[i]] = bits(dat, pos + i * 3, 7);
1173
- }
1174
- pos += hcLen * 3;
1175
- // code lengths bits
1176
- var clb = max(clt), clbmsk = (1 << clb) - 1;
1177
- // code lengths map
1178
- var clm = hMap(clt, clb, 1);
1179
- for (var i = 0; i < tl;) {
1180
- var r = clm[bits(dat, pos, clbmsk)];
1181
- // bits read
1182
- pos += r & 15;
1183
- // symbol
1184
- var s = r >> 4;
1185
- // code length to copy
1186
- if (s < 16) {
1187
- ldt[i++] = s;
1188
- }
1189
- else {
1190
- // copy count
1191
- var c = 0, n = 0;
1192
- if (s == 16)
1193
- n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
1194
- else if (s == 17)
1195
- n = 3 + bits(dat, pos, 7), pos += 3;
1196
- else if (s == 18)
1197
- n = 11 + bits(dat, pos, 127), pos += 7;
1198
- while (n--)
1199
- ldt[i++] = c;
1200
- }
1201
- }
1202
- // length tree distance tree
1203
- var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
1204
- // max length bits
1205
- lbt = max(lt);
1206
- // max dist bits
1207
- dbt = max(dt);
1208
- lm = hMap(lt, lbt, 1);
1209
- dm = hMap(dt, dbt, 1);
1210
- }
1211
- else
1212
- err(1);
1213
- if (pos > tbts) {
1214
- if (noSt)
1215
- err(0);
1216
- break;
1217
- }
1218
- }
1219
- // Make sure the buffer can hold this + the largest possible addition
1220
- // Maximum chunk size (practically, theoretically infinite) is 2^17
1221
- if (resize)
1222
- cbuf(bt + 131072);
1223
- var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
1224
- var lpos = pos;
1225
- for (;; lpos = pos) {
1226
- // bits read, code
1227
- var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
1228
- pos += c & 15;
1229
- if (pos > tbts) {
1230
- if (noSt)
1231
- err(0);
1232
- break;
1233
- }
1234
- if (!c)
1235
- err(2);
1236
- if (sym < 256)
1237
- buf[bt++] = sym;
1238
- else if (sym == 256) {
1239
- lpos = pos, lm = null;
1240
- break;
1241
- }
1242
- else {
1243
- var add = sym - 254;
1244
- // no extra bits needed if less
1245
- if (sym > 264) {
1246
- // index
1247
- var i = sym - 257, b = fleb[i];
1248
- add = bits(dat, pos, (1 << b) - 1) + fl[i];
1249
- pos += b;
1250
- }
1251
- // dist
1252
- var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
1253
- if (!d)
1254
- err(3);
1255
- pos += d & 15;
1256
- var dt = fd[dsym];
1257
- if (dsym > 3) {
1258
- var b = fdeb[dsym];
1259
- dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
1260
- }
1261
- if (pos > tbts) {
1262
- if (noSt)
1263
- err(0);
1264
- break;
1265
- }
1266
- if (resize)
1267
- cbuf(bt + 131072);
1268
- var end = bt + add;
1269
- if (bt < dt) {
1270
- var shift = dl - dt, dend = Math.min(dt, end);
1271
- if (shift + bt < 0)
1272
- err(3);
1273
- for (; bt < dend; ++bt)
1274
- buf[bt] = dict[shift + bt];
1275
- }
1276
- for (; bt < end; ++bt)
1277
- buf[bt] = buf[bt - dt];
1278
- }
1279
- }
1280
- st.l = lm, st.p = lpos, st.b = bt, st.f = final;
1281
- if (lm)
1282
- final = 1, st.m = lbt, st.d = dm, st.n = dbt;
1283
- } while (!final);
1284
- // don't reallocate for streams or user buffers
1285
- return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
1286
- };
1287
- // empty
1288
- var et = /*#__PURE__*/ new u8(0);
1289
- // zlib start
1290
- var zls = function (d, dict) {
1291
- if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31))
1292
- err(6, 'invalid zlib data');
1293
- if ((d[1] >> 5 & 1) == 1)
1294
- err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary');
1295
- return (d[1] >> 3 & 4) + 2;
1296
- };
1297
- /**
1298
- * Expands Zlib data
1299
- * @param data The data to decompress
1300
- * @param opts The decompression options
1301
- * @returns The decompressed version of the data
1302
- */
1303
- function unzlibSync(data, opts) {
1304
- return inflt(data.subarray(zls(data), -4), { i: 2 }, opts, opts);
1305
- }
1306
- // text decoder
1307
- var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder();
1308
- // text decoder stream
1309
- var tds = 0;
1310
- try {
1311
- td.decode(et, { stream: true });
1312
- tds = 1;
1313
- }
1314
- catch (e) { }
1315
-
1316
- // Referred to the original Industrial Light & Magic OpenEXR implementation and the TinyEXR / Syoyo Fujita
1317
- // implementation, so I have preserved their copyright notices.
1318
-
1319
- // /*
1320
- // Copyright (c) 2014 - 2017, Syoyo Fujita
1321
- // All rights reserved.
1322
-
1323
- // Redistribution and use in source and binary forms, with or without
1324
- // modification, are permitted provided that the following conditions are met:
1325
- // * Redistributions of source code must retain the above copyright
1326
- // notice, this list of conditions and the following disclaimer.
1327
- // * Redistributions in binary form must reproduce the above copyright
1328
- // notice, this list of conditions and the following disclaimer in the
1329
- // documentation and/or other materials provided with the distribution.
1330
- // * Neither the name of the Syoyo Fujita nor the
1331
- // names of its contributors may be used to endorse or promote products
1332
- // derived from this software without specific prior written permission.
1333
-
1334
- // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
1335
- // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
1336
- // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1337
- // DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
1338
- // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
1339
- // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
1340
- // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
1341
- // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1342
- // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
1343
- // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1344
- // */
1345
-
1346
- // // TinyEXR contains some OpenEXR code, which is licensed under ------------
1347
-
1348
- // ///////////////////////////////////////////////////////////////////////////
1349
- // //
1350
- // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
1351
- // // Digital Ltd. LLC
1352
- // //
1353
- // // All rights reserved.
1354
- // //
1355
- // // Redistribution and use in source and binary forms, with or without
1356
- // // modification, are permitted provided that the following conditions are
1357
- // // met:
1358
- // // * Redistributions of source code must retain the above copyright
1359
- // // notice, this list of conditions and the following disclaimer.
1360
- // // * Redistributions in binary form must reproduce the above
1361
- // // copyright notice, this list of conditions and the following disclaimer
1362
- // // in the documentation and/or other materials provided with the
1363
- // // distribution.
1364
- // // * Neither the name of Industrial Light & Magic nor the names of
1365
- // // its contributors may be used to endorse or promote products derived
1366
- // // from this software without specific prior written permission.
1367
- // //
1368
- // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1369
- // // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1370
- // // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1371
- // // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
1372
- // // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
1373
- // // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
1374
- // // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
1375
- // // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
1376
- // // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
1377
- // // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1378
- // // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1379
- // //
1380
- // ///////////////////////////////////////////////////////////////////////////
1381
-
1382
- // // End of OpenEXR license -------------------------------------------------
1383
-
1384
-
1385
- /**
1386
- * A loader for the OpenEXR texture format.
1387
- *
1388
- * `EXRLoader` currently supports uncompressed, ZIP(S), RLE, PIZ and DWA/B compression.
1389
- * Supports reading as UnsignedByte, HalfFloat and Float type data texture.
1390
- *
1391
- * ```js
1392
- * const loader = new EXRLoader();
1393
- * const texture = await loader.loadAsync( 'textures/memorial.exr' );
1394
- * ```
1395
- *
1396
- * @augments DataTextureLoader
1397
- * @three_import import { EXRLoader } from 'three/addons/loaders/EXRLoader.js';
1398
- */
1399
- class EXRLoader extends DataTextureLoader {
1400
-
1401
- /**
1402
- * Constructs a new EXR loader.
1403
- *
1404
- * @param {LoadingManager} [manager] - The loading manager.
1405
- */
1406
- constructor( manager ) {
1407
-
1408
- super( manager );
1409
-
1410
- /**
1411
- * The texture type.
1412
- *
1413
- * @type {(HalfFloatType|FloatType)}
1414
- * @default HalfFloatType
1415
- */
1416
- this.type = HalfFloatType;
1417
-
1418
- /**
1419
- * Texture output format.
1420
- *
1421
- * @type {(RGBAFormat|RGFormat|RedFormat)}
1422
- * @default RGBAFormat
1423
- */
1424
- this.outputFormat = RGBAFormat;
1425
-
1426
- }
1427
-
1428
- /**
1429
- * Parses the given EXR texture data.
1430
- *
1431
- * @param {ArrayBuffer} buffer - The raw texture data.
1432
- * @return {DataTextureLoader~TexData} An object representing the parsed texture data.
1433
- */
1434
- parse( buffer ) {
1435
-
1436
- const USHORT_RANGE = ( 1 << 16 );
1437
- const BITMAP_SIZE = ( USHORT_RANGE >> 3 );
1438
-
1439
- const HUF_ENCBITS = 16; // literal (value) bit length
1440
- const HUF_DECBITS = 14; // decoding bit size (>= 8)
1441
-
1442
- const HUF_ENCSIZE = ( 1 << HUF_ENCBITS ) + 1; // encoding table size
1443
- const HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size
1444
- const HUF_DECMASK = HUF_DECSIZE - 1;
1445
-
1446
- const NBITS = 16;
1447
- const A_OFFSET = 1 << ( NBITS - 1 );
1448
- const MOD_MASK = ( 1 << NBITS ) - 1;
1449
-
1450
- const SHORT_ZEROCODE_RUN = 59;
1451
- const LONG_ZEROCODE_RUN = 63;
1452
- const SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN;
1453
-
1454
- const ULONG_SIZE = 8;
1455
- const FLOAT32_SIZE = 4;
1456
- const INT32_SIZE = 4;
1457
- const INT16_SIZE = 2;
1458
- const INT8_SIZE = 1;
1459
-
1460
- const STATIC_HUFFMAN = 0;
1461
- const DEFLATE = 1;
1462
-
1463
- const UNKNOWN = 0;
1464
- const LOSSY_DCT = 1;
1465
- const RLE = 2;
1466
-
1467
- const logBase = Math.pow( 2.7182818, 2.2 );
1468
-
1469
- function reverseLutFromBitmap( bitmap, lut ) {
1470
-
1471
- let k = 0;
1472
-
1473
- for ( let i = 0; i < USHORT_RANGE; ++ i ) {
1474
-
1475
- if ( ( i == 0 ) || ( bitmap[ i >> 3 ] & ( 1 << ( i & 7 ) ) ) ) {
1476
-
1477
- lut[ k ++ ] = i;
1478
-
1479
- }
1480
-
1481
- }
1482
-
1483
- const n = k - 1;
1484
-
1485
- while ( k < USHORT_RANGE ) lut[ k ++ ] = 0;
1486
-
1487
- return n;
1488
-
1489
- }
1490
-
1491
- function hufClearDecTable( hdec ) {
1492
-
1493
- for ( let i = 0; i < HUF_DECSIZE; i ++ ) {
1494
-
1495
- hdec[ i ] = {};
1496
- hdec[ i ].len = 0;
1497
- hdec[ i ].lit = 0;
1498
- hdec[ i ].p = null;
1499
-
1500
- }
1501
-
1502
- }
1503
-
1504
- const getBitsReturn = { l: 0, c: 0, lc: 0 };
1505
-
1506
- function getBits( nBits, c, lc, uInt8Array, inOffset ) {
1507
-
1508
- while ( lc < nBits ) {
1509
-
1510
- c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
1511
- lc += 8;
1512
-
1513
- }
1514
-
1515
- lc -= nBits;
1516
-
1517
- getBitsReturn.l = ( c >> lc ) & ( ( 1 << nBits ) - 1 );
1518
- getBitsReturn.c = c;
1519
- getBitsReturn.lc = lc;
1520
-
1521
- }
1522
-
1523
- const hufTableBuffer = new Array( 59 );
1524
-
1525
- function hufCanonicalCodeTable( hcode ) {
1526
-
1527
- for ( let i = 0; i <= 58; ++ i ) hufTableBuffer[ i ] = 0;
1528
- for ( let i = 0; i < HUF_ENCSIZE; ++ i ) hufTableBuffer[ hcode[ i ] ] += 1;
1529
-
1530
- let c = 0;
1531
-
1532
- for ( let i = 58; i > 0; -- i ) {
1533
-
1534
- const nc = ( ( c + hufTableBuffer[ i ] ) >> 1 );
1535
- hufTableBuffer[ i ] = c;
1536
- c = nc;
1537
-
1538
- }
1539
-
1540
- for ( let i = 0; i < HUF_ENCSIZE; ++ i ) {
1541
-
1542
- const l = hcode[ i ];
1543
- if ( l > 0 ) hcode[ i ] = l | ( hufTableBuffer[ l ] ++ << 6 );
1544
-
1545
- }
1546
-
1547
- }
1548
-
1549
- function hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, hcode ) {
1550
-
1551
- const p = inOffset;
1552
- let c = 0;
1553
- let lc = 0;
1554
-
1555
- for ( ; im <= iM; im ++ ) {
1556
-
1557
- if ( p.value - inOffset.value > ni ) return false;
1558
-
1559
- getBits( 6, c, lc, uInt8Array, p );
1560
-
1561
- const l = getBitsReturn.l;
1562
- c = getBitsReturn.c;
1563
- lc = getBitsReturn.lc;
1564
-
1565
- hcode[ im ] = l;
1566
-
1567
- if ( l == LONG_ZEROCODE_RUN ) {
1568
-
1569
- if ( p.value - inOffset.value > ni ) {
1570
-
1571
- throw new Error( 'Something wrong with hufUnpackEncTable' );
1572
-
1573
- }
1574
-
1575
- getBits( 8, c, lc, uInt8Array, p );
1576
-
1577
- let zerun = getBitsReturn.l + SHORTEST_LONG_RUN;
1578
- c = getBitsReturn.c;
1579
- lc = getBitsReturn.lc;
1580
-
1581
- if ( im + zerun > iM + 1 ) {
1582
-
1583
- throw new Error( 'Something wrong with hufUnpackEncTable' );
1584
-
1585
- }
1586
-
1587
- while ( zerun -- ) hcode[ im ++ ] = 0;
1588
-
1589
- im --;
1590
-
1591
- } else if ( l >= SHORT_ZEROCODE_RUN ) {
1592
-
1593
- let zerun = l - SHORT_ZEROCODE_RUN + 2;
1594
-
1595
- if ( im + zerun > iM + 1 ) {
1596
-
1597
- throw new Error( 'Something wrong with hufUnpackEncTable' );
1598
-
1599
- }
1600
-
1601
- while ( zerun -- ) hcode[ im ++ ] = 0;
1602
-
1603
- im --;
1604
-
1605
- }
1606
-
1607
- }
1608
-
1609
- hufCanonicalCodeTable( hcode );
1610
-
1611
- }
1612
-
1613
- function hufLength( code ) {
1614
-
1615
- return code & 63;
1616
-
1617
- }
1618
-
1619
- function hufCode( code ) {
1620
-
1621
- return code >> 6;
1622
-
1623
- }
1624
-
1625
- function hufBuildDecTable( hcode, im, iM, hdecod ) {
1626
-
1627
- for ( ; im <= iM; im ++ ) {
1628
-
1629
- const c = hufCode( hcode[ im ] );
1630
- const l = hufLength( hcode[ im ] );
1631
-
1632
- if ( c >> l ) {
1633
-
1634
- throw new Error( 'Invalid table entry' );
1635
-
1636
- }
1637
-
1638
- if ( l > HUF_DECBITS ) {
1639
-
1640
- const pl = hdecod[ ( c >> ( l - HUF_DECBITS ) ) ];
1641
-
1642
- if ( pl.len ) {
1643
-
1644
- throw new Error( 'Invalid table entry' );
1645
-
1646
- }
1647
-
1648
- pl.lit ++;
1649
-
1650
- if ( pl.p ) {
1651
-
1652
- const p = pl.p;
1653
- pl.p = new Array( pl.lit );
1654
-
1655
- for ( let i = 0; i < pl.lit - 1; ++ i ) {
1656
-
1657
- pl.p[ i ] = p[ i ];
1658
-
1659
- }
1660
-
1661
- } else {
1662
-
1663
- pl.p = new Array( 1 );
1664
-
1665
- }
1666
-
1667
- pl.p[ pl.lit - 1 ] = im;
1668
-
1669
- } else if ( l ) {
1670
-
1671
- let plOffset = 0;
1672
-
1673
- for ( let i = 1 << ( HUF_DECBITS - l ); i > 0; i -- ) {
1674
-
1675
- const pl = hdecod[ ( c << ( HUF_DECBITS - l ) ) + plOffset ];
1676
-
1677
- if ( pl.len || pl.p ) {
1678
-
1679
- throw new Error( 'Invalid table entry' );
1680
-
1681
- }
1682
-
1683
- pl.len = l;
1684
- pl.lit = im;
1685
-
1686
- plOffset ++;
1687
-
1688
- }
1689
-
1690
- }
1691
-
1692
- }
1693
-
1694
- return true;
1695
-
1696
- }
1697
-
1698
- const getCharReturn = { c: 0, lc: 0 };
1699
-
1700
- function getChar( c, lc, uInt8Array, inOffset ) {
1701
-
1702
- c = ( c << 8 ) | parseUint8Array( uInt8Array, inOffset );
1703
- lc += 8;
1704
-
1705
- getCharReturn.c = c;
1706
- getCharReturn.lc = lc;
1707
-
1708
- }
1709
-
1710
- const getCodeReturn = { c: 0, lc: 0 };
1711
-
1712
- function getCode( po, rlc, c, lc, uInt8Array, inOffset, outBuffer, outBufferOffset, outBufferEndOffset ) {
1713
-
1714
- if ( po == rlc ) {
1715
-
1716
- if ( lc < 8 ) {
1717
-
1718
- getChar( c, lc, uInt8Array, inOffset );
1719
- c = getCharReturn.c;
1720
- lc = getCharReturn.lc;
1721
-
1722
- }
1723
-
1724
- lc -= 8;
1725
-
1726
- let cs = ( c >> lc );
1727
- cs = new Uint8Array( [ cs ] )[ 0 ];
1728
-
1729
- if ( outBufferOffset.value + cs > outBufferEndOffset ) {
1730
-
1731
- return false;
1732
-
1733
- }
1734
-
1735
- const s = outBuffer[ outBufferOffset.value - 1 ];
1736
-
1737
- while ( cs -- > 0 ) {
1738
-
1739
- outBuffer[ outBufferOffset.value ++ ] = s;
1740
-
1741
- }
1742
-
1743
- } else if ( outBufferOffset.value < outBufferEndOffset ) {
1744
-
1745
- outBuffer[ outBufferOffset.value ++ ] = po;
1746
-
1747
- } else {
1748
-
1749
- return false;
1750
-
1751
- }
1752
-
1753
- getCodeReturn.c = c;
1754
- getCodeReturn.lc = lc;
1755
-
1756
- }
1757
-
1758
- function UInt16( value ) {
1759
-
1760
- return ( value & 0xFFFF );
1761
-
1762
- }
1763
-
1764
- function Int16( value ) {
1765
-
1766
- const ref = UInt16( value );
1767
- return ( ref > 0x7FFF ) ? ref - 0x10000 : ref;
1768
-
1769
- }
1770
-
1771
- const wdec14Return = { a: 0, b: 0 };
1772
-
1773
- function wdec14( l, h ) {
1774
-
1775
- const ls = Int16( l );
1776
- const hs = Int16( h );
1777
-
1778
- const hi = hs;
1779
- const ai = ls + ( hi & 1 ) + ( hi >> 1 );
1780
-
1781
- const as = ai;
1782
- const bs = ai - hi;
1783
-
1784
- wdec14Return.a = as;
1785
- wdec14Return.b = bs;
1786
-
1787
- }
1788
-
1789
- function wdec16( l, h ) {
1790
-
1791
- const m = UInt16( l );
1792
- const d = UInt16( h );
1793
-
1794
- const bb = ( m - ( d >> 1 ) ) & MOD_MASK;
1795
- const aa = ( d + bb - A_OFFSET ) & MOD_MASK;
1796
-
1797
- wdec14Return.a = aa;
1798
- wdec14Return.b = bb;
1799
-
1800
- }
1801
-
1802
- function wav2Decode( buffer, j, nx, ox, ny, oy, mx ) {
1803
-
1804
- const w14 = mx < ( 1 << 14 );
1805
- const n = ( nx > ny ) ? ny : nx;
1806
- let p = 1;
1807
- let p2;
1808
- let py;
1809
-
1810
- while ( p <= n ) p <<= 1;
1811
-
1812
- p >>= 1;
1813
- p2 = p;
1814
- p >>= 1;
1815
-
1816
- while ( p >= 1 ) {
1817
-
1818
- py = 0;
1819
- const ey = py + oy * ( ny - p2 );
1820
- const oy1 = oy * p;
1821
- const oy2 = oy * p2;
1822
- const ox1 = ox * p;
1823
- const ox2 = ox * p2;
1824
- let i00, i01, i10, i11;
1825
-
1826
- for ( ; py <= ey; py += oy2 ) {
1827
-
1828
- let px = py;
1829
- const ex = py + ox * ( nx - p2 );
1830
-
1831
- for ( ; px <= ex; px += ox2 ) {
1832
-
1833
- const p01 = px + ox1;
1834
- const p10 = px + oy1;
1835
- const p11 = p10 + ox1;
1836
-
1837
- if ( w14 ) {
1838
-
1839
- wdec14( buffer[ px + j ], buffer[ p10 + j ] );
1840
-
1841
- i00 = wdec14Return.a;
1842
- i10 = wdec14Return.b;
1843
-
1844
- wdec14( buffer[ p01 + j ], buffer[ p11 + j ] );
1845
-
1846
- i01 = wdec14Return.a;
1847
- i11 = wdec14Return.b;
1848
-
1849
- wdec14( i00, i01 );
1850
-
1851
- buffer[ px + j ] = wdec14Return.a;
1852
- buffer[ p01 + j ] = wdec14Return.b;
1853
-
1854
- wdec14( i10, i11 );
1855
-
1856
- buffer[ p10 + j ] = wdec14Return.a;
1857
- buffer[ p11 + j ] = wdec14Return.b;
1858
-
1859
- } else {
1860
-
1861
- wdec16( buffer[ px + j ], buffer[ p10 + j ] );
1862
-
1863
- i00 = wdec14Return.a;
1864
- i10 = wdec14Return.b;
1865
-
1866
- wdec16( buffer[ p01 + j ], buffer[ p11 + j ] );
1867
-
1868
- i01 = wdec14Return.a;
1869
- i11 = wdec14Return.b;
1870
-
1871
- wdec16( i00, i01 );
1872
-
1873
- buffer[ px + j ] = wdec14Return.a;
1874
- buffer[ p01 + j ] = wdec14Return.b;
1875
-
1876
- wdec16( i10, i11 );
1877
-
1878
- buffer[ p10 + j ] = wdec14Return.a;
1879
- buffer[ p11 + j ] = wdec14Return.b;
1880
-
1881
-
1882
- }
1883
-
1884
- }
1885
-
1886
- if ( nx & p ) {
1887
-
1888
- const p10 = px + oy1;
1889
-
1890
- if ( w14 )
1891
- wdec14( buffer[ px + j ], buffer[ p10 + j ] );
1892
- else
1893
- wdec16( buffer[ px + j ], buffer[ p10 + j ] );
1894
-
1895
- i00 = wdec14Return.a;
1896
- buffer[ p10 + j ] = wdec14Return.b;
1897
-
1898
- buffer[ px + j ] = i00;
1899
-
1900
- }
1901
-
1902
- }
1903
-
1904
- if ( ny & p ) {
1905
-
1906
- let px = py;
1907
- const ex = py + ox * ( nx - p2 );
1908
-
1909
- for ( ; px <= ex; px += ox2 ) {
1910
-
1911
- const p01 = px + ox1;
1912
-
1913
- if ( w14 )
1914
- wdec14( buffer[ px + j ], buffer[ p01 + j ] );
1915
- else
1916
- wdec16( buffer[ px + j ], buffer[ p01 + j ] );
1917
-
1918
- i00 = wdec14Return.a;
1919
- buffer[ p01 + j ] = wdec14Return.b;
1920
-
1921
- buffer[ px + j ] = i00;
1922
-
1923
- }
1924
-
1925
- }
1926
-
1927
- p2 = p;
1928
- p >>= 1;
1929
-
1930
- }
1931
-
1932
- return py;
1933
-
1934
- }
1935
-
1936
- function hufDecode( encodingTable, decodingTable, uInt8Array, inOffset, ni, rlc, no, outBuffer, outOffset ) {
1937
-
1938
- let c = 0;
1939
- let lc = 0;
1940
- const outBufferEndOffset = no;
1941
- const inOffsetEnd = Math.trunc( inOffset.value + ( ni + 7 ) / 8 );
1942
-
1943
- while ( inOffset.value < inOffsetEnd ) {
1944
-
1945
- getChar( c, lc, uInt8Array, inOffset );
1946
-
1947
- c = getCharReturn.c;
1948
- lc = getCharReturn.lc;
1949
-
1950
- while ( lc >= HUF_DECBITS ) {
1951
-
1952
- const index = ( c >> ( lc - HUF_DECBITS ) ) & HUF_DECMASK;
1953
- const pl = decodingTable[ index ];
1954
-
1955
- if ( pl.len ) {
1956
-
1957
- lc -= pl.len;
1958
-
1959
- getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
1960
-
1961
- c = getCodeReturn.c;
1962
- lc = getCodeReturn.lc;
1963
-
1964
- } else {
1965
-
1966
- if ( ! pl.p ) {
1967
-
1968
- throw new Error( 'hufDecode issues' );
1969
-
1970
- }
1971
-
1972
- let j;
1973
-
1974
- for ( j = 0; j < pl.lit; j ++ ) {
1975
-
1976
- const l = hufLength( encodingTable[ pl.p[ j ] ] );
1977
-
1978
- while ( lc < l && inOffset.value < inOffsetEnd ) {
1979
-
1980
- getChar( c, lc, uInt8Array, inOffset );
1981
-
1982
- c = getCharReturn.c;
1983
- lc = getCharReturn.lc;
1984
-
1985
- }
1986
-
1987
- if ( lc >= l ) {
1988
-
1989
- if ( hufCode( encodingTable[ pl.p[ j ] ] ) == ( ( c >> ( lc - l ) ) & ( ( 1 << l ) - 1 ) ) ) {
1990
-
1991
- lc -= l;
1992
-
1993
- getCode( pl.p[ j ], rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
1994
-
1995
- c = getCodeReturn.c;
1996
- lc = getCodeReturn.lc;
1997
-
1998
- break;
1999
-
2000
- }
2001
-
2002
- }
2003
-
2004
- }
2005
-
2006
- if ( j == pl.lit ) {
2007
-
2008
- throw new Error( 'hufDecode issues' );
2009
-
2010
- }
2011
-
2012
- }
2013
-
2014
- }
2015
-
2016
- }
2017
-
2018
- const i = ( 8 - ni ) & 7;
2019
-
2020
- c >>= i;
2021
- lc -= i;
2022
-
2023
- while ( lc > 0 ) {
2024
-
2025
- const pl = decodingTable[ ( c << ( HUF_DECBITS - lc ) ) & HUF_DECMASK ];
2026
-
2027
- if ( pl.len ) {
2028
-
2029
- lc -= pl.len;
2030
-
2031
- getCode( pl.lit, rlc, c, lc, uInt8Array, inOffset, outBuffer, outOffset, outBufferEndOffset );
2032
-
2033
- c = getCodeReturn.c;
2034
- lc = getCodeReturn.lc;
2035
-
2036
- } else {
2037
-
2038
- throw new Error( 'hufDecode issues' );
2039
-
2040
- }
2041
-
2042
- }
2043
-
2044
- return true;
2045
-
2046
- }
2047
-
2048
- function hufUncompress( uInt8Array, inDataView, inOffset, nCompressed, outBuffer, nRaw ) {
2049
-
2050
- const outOffset = { value: 0 };
2051
- const initialInOffset = inOffset.value;
2052
-
2053
- const im = parseUint32( inDataView, inOffset );
2054
- const iM = parseUint32( inDataView, inOffset );
2055
-
2056
- inOffset.value += 4;
2057
-
2058
- const nBits = parseUint32( inDataView, inOffset );
2059
-
2060
- inOffset.value += 4;
2061
-
2062
- if ( im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE ) {
2063
-
2064
- throw new Error( 'Something wrong with HUF_ENCSIZE' );
2065
-
2066
- }
2067
-
2068
- const freq = new Array( HUF_ENCSIZE );
2069
- const hdec = new Array( HUF_DECSIZE );
2070
-
2071
- hufClearDecTable( hdec );
2072
-
2073
- const ni = nCompressed - ( inOffset.value - initialInOffset );
2074
-
2075
- hufUnpackEncTable( uInt8Array, inOffset, ni, im, iM, freq );
2076
-
2077
- if ( nBits > 8 * ( nCompressed - ( inOffset.value - initialInOffset ) ) ) {
2078
-
2079
- throw new Error( 'Something wrong with hufUncompress' );
2080
-
2081
- }
2082
-
2083
- hufBuildDecTable( freq, im, iM, hdec );
2084
-
2085
- hufDecode( freq, hdec, uInt8Array, inOffset, nBits, iM, nRaw, outBuffer, outOffset );
2086
-
2087
- }
2088
-
2089
- function applyLut( lut, data, nData ) {
2090
-
2091
- for ( let i = 0; i < nData; ++ i ) {
2092
-
2093
- data[ i ] = lut[ data[ i ] ];
2094
-
2095
- }
2096
-
2097
- }
2098
-
2099
- function predictor( source ) {
2100
-
2101
- for ( let t = 1; t < source.length; t ++ ) {
2102
-
2103
- const d = source[ t - 1 ] + source[ t ] - 128;
2104
- source[ t ] = d;
2105
-
2106
- }
2107
-
2108
- }
2109
-
2110
- function interleaveScalar( source, out ) {
2111
-
2112
- let t1 = 0;
2113
- let t2 = Math.floor( ( source.length + 1 ) / 2 );
2114
- let s = 0;
2115
- const stop = source.length - 1;
2116
-
2117
- while ( true ) {
2118
-
2119
- if ( s > stop ) break;
2120
- out[ s ++ ] = source[ t1 ++ ];
2121
-
2122
- if ( s > stop ) break;
2123
- out[ s ++ ] = source[ t2 ++ ];
2124
-
2125
- }
2126
-
2127
- }
2128
-
2129
- function decodeRunLength( source ) {
2130
-
2131
- let size = source.byteLength;
2132
- const out = new Array();
2133
- let p = 0;
2134
-
2135
- const reader = new DataView( source );
2136
-
2137
- while ( size > 0 ) {
2138
-
2139
- const l = reader.getInt8( p ++ );
2140
-
2141
- if ( l < 0 ) {
2142
-
2143
- const count = - l;
2144
- size -= count + 1;
2145
-
2146
- for ( let i = 0; i < count; i ++ ) {
2147
-
2148
- out.push( reader.getUint8( p ++ ) );
2149
-
2150
- }
2151
-
2152
-
2153
- } else {
2154
-
2155
- const count = l;
2156
- size -= 2;
2157
-
2158
- const value = reader.getUint8( p ++ );
2159
-
2160
- for ( let i = 0; i < count + 1; i ++ ) {
2161
-
2162
- out.push( value );
2163
-
2164
- }
2165
-
2166
- }
2167
-
2168
- }
2169
-
2170
- return out;
2171
-
2172
- }
2173
-
2174
- function lossyDctDecode( cscSet, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) {
2175
-
2176
- let dataView = new DataView( outBuffer.buffer );
2177
-
2178
- const width = channelData[ cscSet.idx[ 0 ] ].width;
2179
- const height = channelData[ cscSet.idx[ 0 ] ].height;
2180
-
2181
- const numComp = 3;
2182
-
2183
- const numFullBlocksX = Math.floor( width / 8.0 );
2184
- const numBlocksX = Math.ceil( width / 8.0 );
2185
- const numBlocksY = Math.ceil( height / 8.0 );
2186
- const leftoverX = width - ( numBlocksX - 1 ) * 8;
2187
- const leftoverY = height - ( numBlocksY - 1 ) * 8;
2188
-
2189
- const currAcComp = { value: 0 };
2190
- const currDcComp = new Array( numComp );
2191
- const dctData = new Array( numComp );
2192
- const halfZigBlock = new Array( numComp );
2193
- const rowBlock = new Array( numComp );
2194
- const rowOffsets = new Array( numComp );
2195
-
2196
- for ( let comp = 0; comp < numComp; ++ comp ) {
2197
-
2198
- rowOffsets[ comp ] = rowPtrs[ cscSet.idx[ comp ] ];
2199
- currDcComp[ comp ] = ( comp < 1 ) ? 0 : currDcComp[ comp - 1 ] + numBlocksX * numBlocksY;
2200
- dctData[ comp ] = new Float32Array( 64 );
2201
- halfZigBlock[ comp ] = new Uint16Array( 64 );
2202
- rowBlock[ comp ] = new Uint16Array( numBlocksX * 64 );
2203
-
2204
- }
2205
-
2206
- for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) {
2207
-
2208
- let maxY = 8;
2209
-
2210
- if ( blocky == numBlocksY - 1 )
2211
- maxY = leftoverY;
2212
-
2213
- let maxX = 8;
2214
-
2215
- for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) {
2216
-
2217
- if ( blockx == numBlocksX - 1 )
2218
- maxX = leftoverX;
2219
-
2220
- for ( let comp = 0; comp < numComp; ++ comp ) {
2221
-
2222
- halfZigBlock[ comp ].fill( 0 );
2223
-
2224
- // set block DC component
2225
- halfZigBlock[ comp ][ 0 ] = dcBuffer[ currDcComp[ comp ] ++ ];
2226
- // set block AC components
2227
- unRleAC( currAcComp, acBuffer, halfZigBlock[ comp ] );
2228
-
2229
- // UnZigZag block to float
2230
- unZigZag( halfZigBlock[ comp ], dctData[ comp ] );
2231
- // decode float dct
2232
- dctInverse( dctData[ comp ] );
2233
-
2234
- }
2235
-
2236
- {
2237
-
2238
- csc709Inverse( dctData );
2239
-
2240
- }
2241
-
2242
- for ( let comp = 0; comp < numComp; ++ comp ) {
2243
-
2244
- convertToHalf( dctData[ comp ], rowBlock[ comp ], blockx * 64 );
2245
-
2246
- }
2247
-
2248
- } // blockx
2249
-
2250
- let offset = 0;
2251
-
2252
- for ( let comp = 0; comp < numComp; ++ comp ) {
2253
-
2254
- const type = channelData[ cscSet.idx[ comp ] ].type;
2255
-
2256
- for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2257
-
2258
- offset = rowOffsets[ comp ][ y ];
2259
-
2260
- for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) {
2261
-
2262
- const src = blockx * 64 + ( ( y & 0x7 ) * 8 );
2263
-
2264
- dataView.setUint16( offset + 0 * INT16_SIZE * type, rowBlock[ comp ][ src + 0 ], true );
2265
- dataView.setUint16( offset + 1 * INT16_SIZE * type, rowBlock[ comp ][ src + 1 ], true );
2266
- dataView.setUint16( offset + 2 * INT16_SIZE * type, rowBlock[ comp ][ src + 2 ], true );
2267
- dataView.setUint16( offset + 3 * INT16_SIZE * type, rowBlock[ comp ][ src + 3 ], true );
2268
-
2269
- dataView.setUint16( offset + 4 * INT16_SIZE * type, rowBlock[ comp ][ src + 4 ], true );
2270
- dataView.setUint16( offset + 5 * INT16_SIZE * type, rowBlock[ comp ][ src + 5 ], true );
2271
- dataView.setUint16( offset + 6 * INT16_SIZE * type, rowBlock[ comp ][ src + 6 ], true );
2272
- dataView.setUint16( offset + 7 * INT16_SIZE * type, rowBlock[ comp ][ src + 7 ], true );
2273
-
2274
- offset += 8 * INT16_SIZE * type;
2275
-
2276
- }
2277
-
2278
- }
2279
-
2280
- // handle partial X blocks
2281
- if ( numFullBlocksX != numBlocksX ) {
2282
-
2283
- for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2284
-
2285
- const offset = rowOffsets[ comp ][ y ] + 8 * numFullBlocksX * INT16_SIZE * type;
2286
- const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 );
2287
-
2288
- for ( let x = 0; x < maxX; ++ x ) {
2289
-
2290
- dataView.setUint16( offset + x * INT16_SIZE * type, rowBlock[ comp ][ src + x ], true );
2291
-
2292
- }
2293
-
2294
- }
2295
-
2296
- }
2297
-
2298
- } // comp
2299
-
2300
- } // blocky
2301
-
2302
- const halfRow = new Uint16Array( width );
2303
- dataView = new DataView( outBuffer.buffer );
2304
-
2305
- // convert channels back to float, if needed
2306
- for ( let comp = 0; comp < numComp; ++ comp ) {
2307
-
2308
- channelData[ cscSet.idx[ comp ] ].decoded = true;
2309
- const type = channelData[ cscSet.idx[ comp ] ].type;
2310
-
2311
- if ( channelData[ comp ].type != 2 ) continue;
2312
-
2313
- for ( let y = 0; y < height; ++ y ) {
2314
-
2315
- const offset = rowOffsets[ comp ][ y ];
2316
-
2317
- for ( let x = 0; x < width; ++ x ) {
2318
-
2319
- halfRow[ x ] = dataView.getUint16( offset + x * INT16_SIZE * type, true );
2320
-
2321
- }
2322
-
2323
- for ( let x = 0; x < width; ++ x ) {
2324
-
2325
- dataView.setFloat32( offset + x * INT16_SIZE * type, decodeFloat16( halfRow[ x ] ), true );
2326
-
2327
- }
2328
-
2329
- }
2330
-
2331
- }
2332
-
2333
- }
2334
-
2335
- function lossyDctChannelDecode( channelIndex, rowPtrs, channelData, acBuffer, dcBuffer, outBuffer ) {
2336
-
2337
- const dataView = new DataView( outBuffer.buffer );
2338
- const cd = channelData[ channelIndex ];
2339
- const width = cd.width;
2340
- const height = cd.height;
2341
-
2342
- const numBlocksX = Math.ceil( width / 8.0 );
2343
- const numBlocksY = Math.ceil( height / 8.0 );
2344
- const numFullBlocksX = Math.floor( width / 8.0 );
2345
- const leftoverX = width - ( numBlocksX - 1 ) * 8;
2346
- const leftoverY = height - ( numBlocksY - 1 ) * 8;
2347
-
2348
- const currAcComp = { value: 0 };
2349
- let currDcComp = 0;
2350
- const dctData = new Float32Array( 64 );
2351
- const halfZigBlock = new Uint16Array( 64 );
2352
- const rowBlock = new Uint16Array( numBlocksX * 64 );
2353
-
2354
- for ( let blocky = 0; blocky < numBlocksY; ++ blocky ) {
2355
-
2356
- let maxY = 8;
2357
-
2358
- if ( blocky == numBlocksY - 1 ) maxY = leftoverY;
2359
-
2360
- for ( let blockx = 0; blockx < numBlocksX; ++ blockx ) {
2361
-
2362
- halfZigBlock.fill( 0 );
2363
- halfZigBlock[ 0 ] = dcBuffer[ currDcComp ++ ];
2364
- unRleAC( currAcComp, acBuffer, halfZigBlock );
2365
- unZigZag( halfZigBlock, dctData );
2366
- dctInverse( dctData );
2367
- convertToHalf( dctData, rowBlock, blockx * 64 );
2368
-
2369
- }
2370
-
2371
- // Write decoded data to output buffer
2372
- for ( let y = 8 * blocky; y < 8 * blocky + maxY; ++ y ) {
2373
-
2374
- let offset = rowPtrs[ channelIndex ][ y ];
2375
-
2376
- for ( let blockx = 0; blockx < numFullBlocksX; ++ blockx ) {
2377
-
2378
- const src = blockx * 64 + ( ( y & 0x7 ) * 8 );
2379
-
2380
- for ( let x = 0; x < 8; ++ x ) {
2381
-
2382
- dataView.setUint16( offset + x * INT16_SIZE * cd.type, rowBlock[ src + x ], true );
2383
-
2384
- }
2385
-
2386
- offset += 8 * INT16_SIZE * cd.type;
2387
-
2388
- }
2389
-
2390
- if ( numBlocksX != numFullBlocksX ) {
2391
-
2392
- const src = numFullBlocksX * 64 + ( ( y & 0x7 ) * 8 );
2393
-
2394
- for ( let x = 0; x < leftoverX; ++ x ) {
2395
-
2396
- dataView.setUint16( offset + x * INT16_SIZE * cd.type, rowBlock[ src + x ], true );
2397
-
2398
- }
2399
-
2400
- }
2401
-
2402
- }
2403
-
2404
- }
2405
-
2406
- cd.decoded = true;
2407
-
2408
- }
2409
-
2410
- function unRleAC( currAcComp, acBuffer, halfZigBlock ) {
2411
-
2412
- let acValue;
2413
- let dctComp = 1;
2414
-
2415
- while ( dctComp < 64 ) {
2416
-
2417
- acValue = acBuffer[ currAcComp.value ];
2418
-
2419
- if ( acValue == 0xff00 ) {
2420
-
2421
- dctComp = 64;
2422
-
2423
- } else if ( acValue >> 8 == 0xff ) {
2424
-
2425
- dctComp += acValue & 0xff;
2426
-
2427
- } else {
2428
-
2429
- halfZigBlock[ dctComp ] = acValue;
2430
- dctComp ++;
2431
-
2432
- }
2433
-
2434
- currAcComp.value ++;
2435
-
2436
- }
2437
-
2438
- }
2439
-
2440
- function unZigZag( src, dst ) {
2441
-
2442
- dst[ 0 ] = decodeFloat16( src[ 0 ] );
2443
- dst[ 1 ] = decodeFloat16( src[ 1 ] );
2444
- dst[ 2 ] = decodeFloat16( src[ 5 ] );
2445
- dst[ 3 ] = decodeFloat16( src[ 6 ] );
2446
- dst[ 4 ] = decodeFloat16( src[ 14 ] );
2447
- dst[ 5 ] = decodeFloat16( src[ 15 ] );
2448
- dst[ 6 ] = decodeFloat16( src[ 27 ] );
2449
- dst[ 7 ] = decodeFloat16( src[ 28 ] );
2450
- dst[ 8 ] = decodeFloat16( src[ 2 ] );
2451
- dst[ 9 ] = decodeFloat16( src[ 4 ] );
2452
-
2453
- dst[ 10 ] = decodeFloat16( src[ 7 ] );
2454
- dst[ 11 ] = decodeFloat16( src[ 13 ] );
2455
- dst[ 12 ] = decodeFloat16( src[ 16 ] );
2456
- dst[ 13 ] = decodeFloat16( src[ 26 ] );
2457
- dst[ 14 ] = decodeFloat16( src[ 29 ] );
2458
- dst[ 15 ] = decodeFloat16( src[ 42 ] );
2459
- dst[ 16 ] = decodeFloat16( src[ 3 ] );
2460
- dst[ 17 ] = decodeFloat16( src[ 8 ] );
2461
- dst[ 18 ] = decodeFloat16( src[ 12 ] );
2462
- dst[ 19 ] = decodeFloat16( src[ 17 ] );
2463
-
2464
- dst[ 20 ] = decodeFloat16( src[ 25 ] );
2465
- dst[ 21 ] = decodeFloat16( src[ 30 ] );
2466
- dst[ 22 ] = decodeFloat16( src[ 41 ] );
2467
- dst[ 23 ] = decodeFloat16( src[ 43 ] );
2468
- dst[ 24 ] = decodeFloat16( src[ 9 ] );
2469
- dst[ 25 ] = decodeFloat16( src[ 11 ] );
2470
- dst[ 26 ] = decodeFloat16( src[ 18 ] );
2471
- dst[ 27 ] = decodeFloat16( src[ 24 ] );
2472
- dst[ 28 ] = decodeFloat16( src[ 31 ] );
2473
- dst[ 29 ] = decodeFloat16( src[ 40 ] );
2474
-
2475
- dst[ 30 ] = decodeFloat16( src[ 44 ] );
2476
- dst[ 31 ] = decodeFloat16( src[ 53 ] );
2477
- dst[ 32 ] = decodeFloat16( src[ 10 ] );
2478
- dst[ 33 ] = decodeFloat16( src[ 19 ] );
2479
- dst[ 34 ] = decodeFloat16( src[ 23 ] );
2480
- dst[ 35 ] = decodeFloat16( src[ 32 ] );
2481
- dst[ 36 ] = decodeFloat16( src[ 39 ] );
2482
- dst[ 37 ] = decodeFloat16( src[ 45 ] );
2483
- dst[ 38 ] = decodeFloat16( src[ 52 ] );
2484
- dst[ 39 ] = decodeFloat16( src[ 54 ] );
2485
-
2486
- dst[ 40 ] = decodeFloat16( src[ 20 ] );
2487
- dst[ 41 ] = decodeFloat16( src[ 22 ] );
2488
- dst[ 42 ] = decodeFloat16( src[ 33 ] );
2489
- dst[ 43 ] = decodeFloat16( src[ 38 ] );
2490
- dst[ 44 ] = decodeFloat16( src[ 46 ] );
2491
- dst[ 45 ] = decodeFloat16( src[ 51 ] );
2492
- dst[ 46 ] = decodeFloat16( src[ 55 ] );
2493
- dst[ 47 ] = decodeFloat16( src[ 60 ] );
2494
- dst[ 48 ] = decodeFloat16( src[ 21 ] );
2495
- dst[ 49 ] = decodeFloat16( src[ 34 ] );
2496
-
2497
- dst[ 50 ] = decodeFloat16( src[ 37 ] );
2498
- dst[ 51 ] = decodeFloat16( src[ 47 ] );
2499
- dst[ 52 ] = decodeFloat16( src[ 50 ] );
2500
- dst[ 53 ] = decodeFloat16( src[ 56 ] );
2501
- dst[ 54 ] = decodeFloat16( src[ 59 ] );
2502
- dst[ 55 ] = decodeFloat16( src[ 61 ] );
2503
- dst[ 56 ] = decodeFloat16( src[ 35 ] );
2504
- dst[ 57 ] = decodeFloat16( src[ 36 ] );
2505
- dst[ 58 ] = decodeFloat16( src[ 48 ] );
2506
- dst[ 59 ] = decodeFloat16( src[ 49 ] );
2507
-
2508
- dst[ 60 ] = decodeFloat16( src[ 57 ] );
2509
- dst[ 61 ] = decodeFloat16( src[ 58 ] );
2510
- dst[ 62 ] = decodeFloat16( src[ 62 ] );
2511
- dst[ 63 ] = decodeFloat16( src[ 63 ] );
2512
-
2513
- }
2514
-
2515
- function dctInverse( data ) {
2516
-
2517
- const a = 0.5 * Math.cos( 3.14159 / 4.0 );
2518
- const b = 0.5 * Math.cos( 3.14159 / 16.0 );
2519
- const c = 0.5 * Math.cos( 3.14159 / 8.0 );
2520
- const d = 0.5 * Math.cos( 3.0 * 3.14159 / 16.0 );
2521
- const e = 0.5 * Math.cos( 5.0 * 3.14159 / 16.0 );
2522
- const f = 0.5 * Math.cos( 3.0 * 3.14159 / 8.0 );
2523
- const g = 0.5 * Math.cos( 7.0 * 3.14159 / 16.0 );
2524
-
2525
- const alpha = new Array( 4 );
2526
- const beta = new Array( 4 );
2527
- const theta = new Array( 4 );
2528
- const gamma = new Array( 4 );
2529
-
2530
- for ( let row = 0; row < 8; ++ row ) {
2531
-
2532
- const rowPtr = row * 8;
2533
-
2534
- alpha[ 0 ] = c * data[ rowPtr + 2 ];
2535
- alpha[ 1 ] = f * data[ rowPtr + 2 ];
2536
- alpha[ 2 ] = c * data[ rowPtr + 6 ];
2537
- alpha[ 3 ] = f * data[ rowPtr + 6 ];
2538
-
2539
- beta[ 0 ] = b * data[ rowPtr + 1 ] + d * data[ rowPtr + 3 ] + e * data[ rowPtr + 5 ] + g * data[ rowPtr + 7 ];
2540
- beta[ 1 ] = d * data[ rowPtr + 1 ] - g * data[ rowPtr + 3 ] - b * data[ rowPtr + 5 ] - e * data[ rowPtr + 7 ];
2541
- beta[ 2 ] = e * data[ rowPtr + 1 ] - b * data[ rowPtr + 3 ] + g * data[ rowPtr + 5 ] + d * data[ rowPtr + 7 ];
2542
- beta[ 3 ] = g * data[ rowPtr + 1 ] - e * data[ rowPtr + 3 ] + d * data[ rowPtr + 5 ] - b * data[ rowPtr + 7 ];
2543
-
2544
- theta[ 0 ] = a * ( data[ rowPtr + 0 ] + data[ rowPtr + 4 ] );
2545
- theta[ 3 ] = a * ( data[ rowPtr + 0 ] - data[ rowPtr + 4 ] );
2546
- theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
2547
- theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
2548
-
2549
- gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
2550
- gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
2551
- gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
2552
- gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
2553
-
2554
- data[ rowPtr + 0 ] = gamma[ 0 ] + beta[ 0 ];
2555
- data[ rowPtr + 1 ] = gamma[ 1 ] + beta[ 1 ];
2556
- data[ rowPtr + 2 ] = gamma[ 2 ] + beta[ 2 ];
2557
- data[ rowPtr + 3 ] = gamma[ 3 ] + beta[ 3 ];
2558
-
2559
- data[ rowPtr + 4 ] = gamma[ 3 ] - beta[ 3 ];
2560
- data[ rowPtr + 5 ] = gamma[ 2 ] - beta[ 2 ];
2561
- data[ rowPtr + 6 ] = gamma[ 1 ] - beta[ 1 ];
2562
- data[ rowPtr + 7 ] = gamma[ 0 ] - beta[ 0 ];
2563
-
2564
- }
2565
-
2566
- for ( let column = 0; column < 8; ++ column ) {
2567
-
2568
- alpha[ 0 ] = c * data[ 16 + column ];
2569
- alpha[ 1 ] = f * data[ 16 + column ];
2570
- alpha[ 2 ] = c * data[ 48 + column ];
2571
- alpha[ 3 ] = f * data[ 48 + column ];
2572
-
2573
- beta[ 0 ] = b * data[ 8 + column ] + d * data[ 24 + column ] + e * data[ 40 + column ] + g * data[ 56 + column ];
2574
- beta[ 1 ] = d * data[ 8 + column ] - g * data[ 24 + column ] - b * data[ 40 + column ] - e * data[ 56 + column ];
2575
- beta[ 2 ] = e * data[ 8 + column ] - b * data[ 24 + column ] + g * data[ 40 + column ] + d * data[ 56 + column ];
2576
- beta[ 3 ] = g * data[ 8 + column ] - e * data[ 24 + column ] + d * data[ 40 + column ] - b * data[ 56 + column ];
2577
-
2578
- theta[ 0 ] = a * ( data[ column ] + data[ 32 + column ] );
2579
- theta[ 3 ] = a * ( data[ column ] - data[ 32 + column ] );
2580
-
2581
- theta[ 1 ] = alpha[ 0 ] + alpha[ 3 ];
2582
- theta[ 2 ] = alpha[ 1 ] - alpha[ 2 ];
2583
-
2584
- gamma[ 0 ] = theta[ 0 ] + theta[ 1 ];
2585
- gamma[ 1 ] = theta[ 3 ] + theta[ 2 ];
2586
- gamma[ 2 ] = theta[ 3 ] - theta[ 2 ];
2587
- gamma[ 3 ] = theta[ 0 ] - theta[ 1 ];
2588
-
2589
- data[ 0 + column ] = gamma[ 0 ] + beta[ 0 ];
2590
- data[ 8 + column ] = gamma[ 1 ] + beta[ 1 ];
2591
- data[ 16 + column ] = gamma[ 2 ] + beta[ 2 ];
2592
- data[ 24 + column ] = gamma[ 3 ] + beta[ 3 ];
2593
-
2594
- data[ 32 + column ] = gamma[ 3 ] - beta[ 3 ];
2595
- data[ 40 + column ] = gamma[ 2 ] - beta[ 2 ];
2596
- data[ 48 + column ] = gamma[ 1 ] - beta[ 1 ];
2597
- data[ 56 + column ] = gamma[ 0 ] - beta[ 0 ];
2598
-
2599
- }
2600
-
2601
- }
2602
-
2603
- function csc709Inverse( data ) {
2604
-
2605
- for ( let i = 0; i < 64; ++ i ) {
2606
-
2607
- const y = data[ 0 ][ i ];
2608
- const cb = data[ 1 ][ i ];
2609
- const cr = data[ 2 ][ i ];
2610
-
2611
- data[ 0 ][ i ] = y + 1.5747 * cr;
2612
- data[ 1 ][ i ] = y - 0.1873 * cb - 0.4682 * cr;
2613
- data[ 2 ][ i ] = y + 1.8556 * cb;
2614
-
2615
- }
2616
-
2617
- }
2618
-
2619
- function convertToHalf( src, dst, idx ) {
2620
-
2621
- for ( let i = 0; i < 64; ++ i ) {
2622
-
2623
- dst[ idx + i ] = DataUtils.toHalfFloat( toLinear( src[ i ] ) );
2624
-
2625
- }
2626
-
2627
- }
2628
-
2629
- function toLinear( float ) {
2630
-
2631
- if ( float <= 1 ) {
2632
-
2633
- return Math.sign( float ) * Math.pow( Math.abs( float ), 2.2 );
2634
-
2635
- } else {
2636
-
2637
- return Math.sign( float ) * Math.pow( logBase, Math.abs( float ) - 1.0 );
2638
-
2639
- }
2640
-
2641
- }
2642
-
2643
- function uncompressRAW( info ) {
2644
-
2645
- return new DataView( info.array.buffer, info.offset.value, info.size );
2646
-
2647
- }
2648
-
2649
- function uncompressRLE( info ) {
2650
-
2651
- const compressed = info.viewer.buffer.slice( info.offset.value, info.offset.value + info.size );
2652
-
2653
- const rawBuffer = new Uint8Array( decodeRunLength( compressed ) );
2654
- const tmpBuffer = new Uint8Array( rawBuffer.length );
2655
-
2656
- predictor( rawBuffer ); // revert predictor
2657
-
2658
- interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
2659
-
2660
- return new DataView( tmpBuffer.buffer );
2661
-
2662
- }
2663
-
2664
- function uncompressZIP( info ) {
2665
-
2666
- const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
2667
-
2668
- const rawBuffer = unzlibSync( compressed );
2669
- const tmpBuffer = new Uint8Array( rawBuffer.length );
2670
-
2671
- predictor( rawBuffer ); // revert predictor
2672
-
2673
- interleaveScalar( rawBuffer, tmpBuffer ); // interleave pixels
2674
-
2675
- return new DataView( tmpBuffer.buffer );
2676
-
2677
- }
2678
-
2679
- function uncompressPIZ( info ) {
2680
-
2681
- const inDataView = info.viewer;
2682
- const inOffset = { value: info.offset.value };
2683
-
2684
- const outBuffer = new Uint16Array( info.columns * info.lines * ( info.inputChannels.length * info.type ) );
2685
- const bitmap = new Uint8Array( BITMAP_SIZE );
2686
-
2687
- // Setup channel info
2688
- let outBufferEnd = 0;
2689
- const pizChannelData = new Array( info.inputChannels.length );
2690
- for ( let i = 0, il = info.inputChannels.length; i < il; i ++ ) {
2691
-
2692
- pizChannelData[ i ] = {};
2693
- pizChannelData[ i ][ 'start' ] = outBufferEnd;
2694
- pizChannelData[ i ][ 'end' ] = pizChannelData[ i ][ 'start' ];
2695
- pizChannelData[ i ][ 'nx' ] = info.columns;
2696
- pizChannelData[ i ][ 'ny' ] = info.lines;
2697
- pizChannelData[ i ][ 'size' ] = info.type;
2698
-
2699
- outBufferEnd += pizChannelData[ i ].nx * pizChannelData[ i ].ny * pizChannelData[ i ].size;
2700
-
2701
- }
2702
-
2703
- // Read range compression data
2704
-
2705
- const minNonZero = parseUint16( inDataView, inOffset );
2706
- const maxNonZero = parseUint16( inDataView, inOffset );
2707
-
2708
- if ( maxNonZero >= BITMAP_SIZE ) {
2709
-
2710
- throw new Error( 'Something is wrong with PIZ_COMPRESSION BITMAP_SIZE' );
2711
-
2712
- }
2713
-
2714
- if ( minNonZero <= maxNonZero ) {
2715
-
2716
- for ( let i = 0; i < maxNonZero - minNonZero + 1; i ++ ) {
2717
-
2718
- bitmap[ i + minNonZero ] = parseUint8( inDataView, inOffset );
2719
-
2720
- }
2721
-
2722
- }
2723
-
2724
- // Reverse LUT
2725
- const lut = new Uint16Array( USHORT_RANGE );
2726
- const maxValue = reverseLutFromBitmap( bitmap, lut );
2727
-
2728
- const length = parseUint32( inDataView, inOffset );
2729
-
2730
- // Huffman decoding
2731
- hufUncompress( info.array, inDataView, inOffset, length, outBuffer, outBufferEnd );
2732
-
2733
- // Wavelet decoding
2734
- for ( let i = 0; i < info.inputChannels.length; ++ i ) {
2735
-
2736
- const cd = pizChannelData[ i ];
2737
-
2738
- for ( let j = 0; j < pizChannelData[ i ].size; ++ j ) {
2739
-
2740
- wav2Decode(
2741
- outBuffer,
2742
- cd.start + j,
2743
- cd.nx,
2744
- cd.size,
2745
- cd.ny,
2746
- cd.nx * cd.size,
2747
- maxValue
2748
- );
2749
-
2750
- }
2751
-
2752
- }
2753
-
2754
- // Expand the pixel data to their original range
2755
- applyLut( lut, outBuffer, outBufferEnd );
2756
-
2757
- // Rearrange the pixel data into the format expected by the caller.
2758
- let tmpOffset = 0;
2759
- const tmpBuffer = new Uint8Array( outBuffer.buffer.byteLength );
2760
- for ( let y = 0; y < info.lines; y ++ ) {
2761
-
2762
- for ( let c = 0; c < info.inputChannels.length; c ++ ) {
2763
-
2764
- const cd = pizChannelData[ c ];
2765
-
2766
- const n = cd.nx * cd.size;
2767
- const cp = new Uint8Array( outBuffer.buffer, cd.end * INT16_SIZE, n * INT16_SIZE );
2768
-
2769
- tmpBuffer.set( cp, tmpOffset );
2770
- tmpOffset += n * INT16_SIZE;
2771
- cd.end += n;
2772
-
2773
- }
2774
-
2775
- }
2776
-
2777
- return new DataView( tmpBuffer.buffer );
2778
-
2779
- }
2780
-
2781
- function uncompressPXR( info ) {
2782
-
2783
- const compressed = info.array.slice( info.offset.value, info.offset.value + info.size );
2784
-
2785
- const rawBuffer = unzlibSync( compressed );
2786
-
2787
- const byteSize = info.inputChannels.length * info.lines * info.columns * info.totalBytes;
2788
- const tmpBuffer = new ArrayBuffer( byteSize );
2789
- const viewer = new DataView( tmpBuffer );
2790
-
2791
- let tmpBufferEnd = 0;
2792
- let writePtr = 0;
2793
- const ptr = new Array( 4 );
2794
-
2795
- for ( let y = 0; y < info.lines; y ++ ) {
2796
-
2797
- for ( let c = 0; c < info.inputChannels.length; c ++ ) {
2798
-
2799
- let pixel = 0;
2800
-
2801
- const type = info.inputChannels[ c ].pixelType;
2802
- switch ( type ) {
2803
-
2804
- case 1:
2805
-
2806
- ptr[ 0 ] = tmpBufferEnd;
2807
- ptr[ 1 ] = ptr[ 0 ] + info.columns;
2808
- tmpBufferEnd = ptr[ 1 ] + info.columns;
2809
-
2810
- for ( let j = 0; j < info.columns; ++ j ) {
2811
-
2812
- const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 8 ) | rawBuffer[ ptr[ 1 ] ++ ];
2813
-
2814
- pixel += diff;
2815
-
2816
- viewer.setUint16( writePtr, pixel, true );
2817
- writePtr += 2;
2818
-
2819
- }
2820
-
2821
- break;
2822
-
2823
- case 2:
2824
-
2825
- ptr[ 0 ] = tmpBufferEnd;
2826
- ptr[ 1 ] = ptr[ 0 ] + info.columns;
2827
- ptr[ 2 ] = ptr[ 1 ] + info.columns;
2828
- tmpBufferEnd = ptr[ 2 ] + info.columns;
2829
-
2830
- for ( let j = 0; j < info.columns; ++ j ) {
2831
-
2832
- const diff = ( rawBuffer[ ptr[ 0 ] ++ ] << 24 ) | ( rawBuffer[ ptr[ 1 ] ++ ] << 16 ) | ( rawBuffer[ ptr[ 2 ] ++ ] << 8 );
2833
-
2834
- pixel += diff;
2835
-
2836
- viewer.setUint32( writePtr, pixel, true );
2837
- writePtr += 4;
2838
-
2839
- }
2840
-
2841
- break;
2842
-
2843
- }
2844
-
2845
- }
2846
-
2847
- }
2848
-
2849
- return viewer;
2850
-
2851
- }
2852
-
2853
- function uncompressDWA( info ) {
2854
-
2855
- const inDataView = info.viewer;
2856
- const inOffset = { value: info.offset.value };
2857
- const outBuffer = new Uint8Array( info.columns * info.lines * ( info.inputChannels.length * info.type * INT16_SIZE ) );
2858
-
2859
- // Read compression header information
2860
- const dwaHeader = {
2861
-
2862
- version: parseInt64( inDataView, inOffset ),
2863
- unknownUncompressedSize: parseInt64( inDataView, inOffset ),
2864
- unknownCompressedSize: parseInt64( inDataView, inOffset ),
2865
- acCompressedSize: parseInt64( inDataView, inOffset ),
2866
- dcCompressedSize: parseInt64( inDataView, inOffset ),
2867
- rleCompressedSize: parseInt64( inDataView, inOffset ),
2868
- rleUncompressedSize: parseInt64( inDataView, inOffset ),
2869
- rleRawSize: parseInt64( inDataView, inOffset ),
2870
- totalAcUncompressedCount: parseInt64( inDataView, inOffset ),
2871
- totalDcUncompressedCount: parseInt64( inDataView, inOffset ),
2872
- acCompression: parseInt64( inDataView, inOffset )
2873
-
2874
- };
2875
-
2876
- if ( dwaHeader.version < 2 )
2877
- throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' version ' + dwaHeader.version + ' is unsupported' );
2878
-
2879
- // Read channel ruleset information
2880
- const channelRules = new Array();
2881
- let ruleSize = parseUint16( inDataView, inOffset ) - INT16_SIZE;
2882
-
2883
- while ( ruleSize > 0 ) {
2884
-
2885
- const name = parseNullTerminatedString( inDataView.buffer, inOffset );
2886
- const value = parseUint8( inDataView, inOffset );
2887
- const compression = ( value >> 2 ) & 3;
2888
- const csc = ( value >> 4 ) - 1;
2889
- const index = new Int8Array( [ csc ] )[ 0 ];
2890
- const type = parseUint8( inDataView, inOffset );
2891
-
2892
- channelRules.push( {
2893
- name: name,
2894
- index: index,
2895
- type: type,
2896
- compression: compression,
2897
- } );
2898
-
2899
- ruleSize -= name.length + 3;
2900
-
2901
- }
2902
-
2903
- // Classify channels
2904
- const channels = EXRHeader.channels;
2905
- const channelData = new Array( info.inputChannels.length );
2906
-
2907
- for ( let i = 0; i < info.inputChannels.length; ++ i ) {
2908
-
2909
- const cd = channelData[ i ] = {};
2910
- const channel = channels[ i ];
2911
-
2912
- cd.name = channel.name;
2913
- cd.compression = UNKNOWN;
2914
- cd.decoded = false;
2915
- cd.type = channel.pixelType;
2916
- cd.pLinear = channel.pLinear;
2917
- cd.width = info.columns;
2918
- cd.height = info.lines;
2919
-
2920
- }
2921
-
2922
- const cscSet = {
2923
- idx: new Array( 3 )
2924
- };
2925
-
2926
- for ( let offset = 0; offset < info.inputChannels.length; ++ offset ) {
2927
-
2928
- const cd = channelData[ offset ];
2929
-
2930
- for ( let i = 0; i < channelRules.length; ++ i ) {
2931
-
2932
- const rule = channelRules[ i ];
2933
-
2934
- if ( cd.name == rule.name ) {
2935
-
2936
- cd.compression = rule.compression;
2937
-
2938
- if ( rule.index >= 0 ) {
2939
-
2940
- cscSet.idx[ rule.index ] = offset;
2941
-
2942
- }
2943
-
2944
- cd.offset = offset;
2945
-
2946
- }
2947
-
2948
- }
2949
-
2950
- }
2951
-
2952
- let acBuffer, dcBuffer, rleBuffer;
2953
-
2954
- // Read DCT - AC component data
2955
- if ( dwaHeader.acCompressedSize > 0 ) {
2956
-
2957
- switch ( dwaHeader.acCompression ) {
2958
-
2959
- case STATIC_HUFFMAN:
2960
-
2961
- acBuffer = new Uint16Array( dwaHeader.totalAcUncompressedCount );
2962
- hufUncompress( info.array, inDataView, inOffset, dwaHeader.acCompressedSize, acBuffer, dwaHeader.totalAcUncompressedCount );
2963
- break;
2964
-
2965
- case DEFLATE:
2966
-
2967
- const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.totalAcUncompressedCount );
2968
- const data = unzlibSync( compressed );
2969
- acBuffer = new Uint16Array( data.buffer );
2970
- inOffset.value += dwaHeader.totalAcUncompressedCount;
2971
- break;
2972
-
2973
- }
2974
-
2975
-
2976
- }
2977
-
2978
- // Read DCT - DC component data
2979
- if ( dwaHeader.dcCompressedSize > 0 ) {
2980
-
2981
- const zlibInfo = {
2982
- array: info.array,
2983
- offset: inOffset,
2984
- size: dwaHeader.dcCompressedSize
2985
- };
2986
- dcBuffer = new Uint16Array( uncompressZIP( zlibInfo ).buffer );
2987
- inOffset.value += dwaHeader.dcCompressedSize;
2988
-
2989
- }
2990
-
2991
- // Read RLE compressed data
2992
- if ( dwaHeader.rleRawSize > 0 ) {
2993
-
2994
- const compressed = info.array.slice( inOffset.value, inOffset.value + dwaHeader.rleCompressedSize );
2995
- const data = unzlibSync( compressed );
2996
- rleBuffer = decodeRunLength( data.buffer );
2997
-
2998
- inOffset.value += dwaHeader.rleCompressedSize;
2999
-
3000
- }
3001
-
3002
- // Prepare outbuffer data offset
3003
- let outBufferEnd = 0;
3004
- const rowOffsets = new Array( channelData.length );
3005
- for ( let i = 0; i < rowOffsets.length; ++ i ) {
3006
-
3007
- rowOffsets[ i ] = new Array();
3008
-
3009
- }
3010
-
3011
- for ( let y = 0; y < info.lines; ++ y ) {
3012
-
3013
- for ( let chan = 0; chan < channelData.length; ++ chan ) {
3014
-
3015
- rowOffsets[ chan ].push( outBufferEnd );
3016
- outBufferEnd += channelData[ chan ].width * info.type * INT16_SIZE;
3017
-
3018
- }
3019
-
3020
- }
3021
-
3022
- // Decode lossy DCT data if we have a valid color space conversion set with the first RGB channel present
3023
- if ( cscSet.idx[ 0 ] !== undefined && channelData[ cscSet.idx[ 0 ] ] ) {
3024
-
3025
- lossyDctDecode( cscSet, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer );
3026
-
3027
- }
3028
-
3029
- // Decode other channels
3030
- for ( let i = 0; i < channelData.length; ++ i ) {
3031
-
3032
- const cd = channelData[ i ];
3033
-
3034
- if ( cd.decoded ) continue;
3035
-
3036
- switch ( cd.compression ) {
3037
-
3038
- case RLE:
3039
-
3040
- let row = 0;
3041
- let rleOffset = 0;
3042
-
3043
- for ( let y = 0; y < info.lines; ++ y ) {
3044
-
3045
- let rowOffsetBytes = rowOffsets[ i ][ row ];
3046
-
3047
- for ( let x = 0; x < cd.width; ++ x ) {
3048
-
3049
- for ( let byte = 0; byte < INT16_SIZE * cd.type; ++ byte ) {
3050
-
3051
- outBuffer[ rowOffsetBytes ++ ] = rleBuffer[ rleOffset + byte * cd.width * cd.height ];
3052
-
3053
- }
3054
-
3055
- rleOffset ++;
3056
-
3057
- }
3058
-
3059
- row ++;
3060
-
3061
- }
3062
-
3063
- break;
3064
-
3065
- case LOSSY_DCT:
3066
-
3067
- lossyDctChannelDecode( i, rowOffsets, channelData, acBuffer, dcBuffer, outBuffer );
3068
-
3069
- break;
3070
-
3071
- default:
3072
- throw new Error( 'EXRLoader.parse: unsupported channel compression' );
3073
-
3074
- }
3075
-
3076
- }
3077
-
3078
- return new DataView( outBuffer.buffer );
3079
-
3080
- }
3081
-
3082
- function parseNullTerminatedString( buffer, offset ) {
3083
-
3084
- const uintBuffer = new Uint8Array( buffer );
3085
- let endOffset = 0;
3086
-
3087
- while ( uintBuffer[ offset.value + endOffset ] != 0 ) {
3088
-
3089
- endOffset += 1;
3090
-
3091
- }
3092
-
3093
- const stringValue = new TextDecoder().decode(
3094
- uintBuffer.slice( offset.value, offset.value + endOffset )
3095
- );
3096
-
3097
- offset.value = offset.value + endOffset + 1;
3098
-
3099
- return stringValue;
3100
-
3101
- }
3102
-
3103
- function parseFixedLengthString( buffer, offset, size ) {
3104
-
3105
- const stringValue = new TextDecoder().decode(
3106
- new Uint8Array( buffer ).slice( offset.value, offset.value + size )
3107
- );
3108
-
3109
- offset.value = offset.value + size;
3110
-
3111
- return stringValue;
3112
-
3113
- }
3114
-
3115
- function parseRational( dataView, offset ) {
3116
-
3117
- const x = parseInt32( dataView, offset );
3118
- const y = parseUint32( dataView, offset );
3119
-
3120
- return [ x, y ];
3121
-
3122
- }
3123
-
3124
- function parseTimecode( dataView, offset ) {
3125
-
3126
- const x = parseUint32( dataView, offset );
3127
- const y = parseUint32( dataView, offset );
3128
-
3129
- return [ x, y ];
3130
-
3131
- }
3132
-
3133
- function parseInt32( dataView, offset ) {
3134
-
3135
- const Int32 = dataView.getInt32( offset.value, true );
3136
-
3137
- offset.value = offset.value + INT32_SIZE;
3138
-
3139
- return Int32;
3140
-
3141
- }
3142
-
3143
- function parseUint32( dataView, offset ) {
3144
-
3145
- const Uint32 = dataView.getUint32( offset.value, true );
3146
-
3147
- offset.value = offset.value + INT32_SIZE;
3148
-
3149
- return Uint32;
3150
-
3151
- }
3152
-
3153
- function parseUint8Array( uInt8Array, offset ) {
3154
-
3155
- const Uint8 = uInt8Array[ offset.value ];
3156
-
3157
- offset.value = offset.value + INT8_SIZE;
3158
-
3159
- return Uint8;
3160
-
3161
- }
3162
-
3163
- function parseUint8( dataView, offset ) {
3164
-
3165
- const Uint8 = dataView.getUint8( offset.value );
3166
-
3167
- offset.value = offset.value + INT8_SIZE;
3168
-
3169
- return Uint8;
3170
-
3171
- }
3172
-
3173
- const parseInt64 = function ( dataView, offset ) {
3174
-
3175
- let int;
3176
-
3177
- if ( 'getBigInt64' in DataView.prototype ) {
3178
-
3179
- int = Number( dataView.getBigInt64( offset.value, true ) );
3180
-
3181
- } else {
3182
-
3183
- int = dataView.getUint32( offset.value + 4, true ) + Number( dataView.getUint32( offset.value, true ) << 32 );
3184
-
3185
- }
3186
-
3187
- offset.value += ULONG_SIZE;
3188
-
3189
- return int;
3190
-
3191
- };
3192
-
3193
- function parseFloat32( dataView, offset ) {
3194
-
3195
- const float = dataView.getFloat32( offset.value, true );
3196
-
3197
- offset.value += FLOAT32_SIZE;
3198
-
3199
- return float;
3200
-
3201
- }
3202
-
3203
- function decodeFloat32( dataView, offset ) {
3204
-
3205
- return DataUtils.toHalfFloat( parseFloat32( dataView, offset ) );
3206
-
3207
- }
3208
-
3209
- // https://stackoverflow.com/questions/5678432/decompressing-half-precision-floats-in-javascript
3210
- function decodeFloat16( binary ) {
3211
-
3212
- const exponent = ( binary & 0x7C00 ) >> 10,
3213
- fraction = binary & 0x03FF;
3214
-
3215
- return ( binary >> 15 ? -1 : 1 ) * (
3216
- exponent ?
3217
- (
3218
- exponent === 0x1F ?
3219
- fraction ? NaN : Infinity :
3220
- Math.pow( 2, exponent - 15 ) * ( 1 + fraction / 0x400 )
3221
- ) :
3222
- 6.103515625e-5 * ( fraction / 0x400 )
3223
- );
3224
-
3225
- }
3226
-
3227
- function parseUint16( dataView, offset ) {
3228
-
3229
- const Uint16 = dataView.getUint16( offset.value, true );
3230
-
3231
- offset.value += INT16_SIZE;
3232
-
3233
- return Uint16;
3234
-
3235
- }
3236
-
3237
- function parseFloat16( buffer, offset ) {
3238
-
3239
- return decodeFloat16( parseUint16( buffer, offset ) );
3240
-
3241
- }
3242
-
3243
- function parseChlist( dataView, buffer, offset, size ) {
3244
-
3245
- const startOffset = offset.value;
3246
- const channels = [];
3247
-
3248
- while ( offset.value < ( startOffset + size - 1 ) ) {
3249
-
3250
- const name = parseNullTerminatedString( buffer, offset );
3251
- const pixelType = parseInt32( dataView, offset );
3252
- const pLinear = parseUint8( dataView, offset );
3253
- offset.value += 3; // reserved, three chars
3254
- const xSampling = parseInt32( dataView, offset );
3255
- const ySampling = parseInt32( dataView, offset );
3256
-
3257
- channels.push( {
3258
- name: name,
3259
- pixelType: pixelType,
3260
- pLinear: pLinear,
3261
- xSampling: xSampling,
3262
- ySampling: ySampling
3263
- } );
3264
-
3265
- }
3266
-
3267
- offset.value += 1;
3268
-
3269
- return channels;
3270
-
3271
- }
3272
-
3273
- function parseChromaticities( dataView, offset ) {
3274
-
3275
- const redX = parseFloat32( dataView, offset );
3276
- const redY = parseFloat32( dataView, offset );
3277
- const greenX = parseFloat32( dataView, offset );
3278
- const greenY = parseFloat32( dataView, offset );
3279
- const blueX = parseFloat32( dataView, offset );
3280
- const blueY = parseFloat32( dataView, offset );
3281
- const whiteX = parseFloat32( dataView, offset );
3282
- const whiteY = parseFloat32( dataView, offset );
3283
-
3284
- return { redX: redX, redY: redY, greenX: greenX, greenY: greenY, blueX: blueX, blueY: blueY, whiteX: whiteX, whiteY: whiteY };
3285
-
3286
- }
3287
-
3288
- function parseCompression( dataView, offset ) {
3289
-
3290
- const compressionCodes = [
3291
- 'NO_COMPRESSION',
3292
- 'RLE_COMPRESSION',
3293
- 'ZIPS_COMPRESSION',
3294
- 'ZIP_COMPRESSION',
3295
- 'PIZ_COMPRESSION',
3296
- 'PXR24_COMPRESSION',
3297
- 'B44_COMPRESSION',
3298
- 'B44A_COMPRESSION',
3299
- 'DWAA_COMPRESSION',
3300
- 'DWAB_COMPRESSION'
3301
- ];
3302
-
3303
- const compression = parseUint8( dataView, offset );
3304
-
3305
- return compressionCodes[ compression ];
3306
-
3307
- }
3308
-
3309
- function parseBox2i( dataView, offset ) {
3310
-
3311
- const xMin = parseInt32( dataView, offset );
3312
- const yMin = parseInt32( dataView, offset );
3313
- const xMax = parseInt32( dataView, offset );
3314
- const yMax = parseInt32( dataView, offset );
3315
-
3316
- return { xMin: xMin, yMin: yMin, xMax: xMax, yMax: yMax };
3317
-
3318
- }
3319
-
3320
- function parseLineOrder( dataView, offset ) {
3321
-
3322
- const lineOrders = [
3323
- 'INCREASING_Y',
3324
- 'DECREASING_Y',
3325
- 'RANDOM_Y',
3326
- ];
3327
-
3328
- const lineOrder = parseUint8( dataView, offset );
3329
-
3330
- return lineOrders[ lineOrder ];
3331
-
3332
- }
3333
-
3334
- function parseEnvmap( dataView, offset ) {
3335
-
3336
- const envmaps = [
3337
- 'ENVMAP_LATLONG',
3338
- 'ENVMAP_CUBE'
3339
- ];
3340
-
3341
- const envmap = parseUint8( dataView, offset );
3342
-
3343
- return envmaps[ envmap ];
3344
-
3345
- }
3346
-
3347
- function parseTiledesc( dataView, offset ) {
3348
-
3349
- const levelModes = [
3350
- 'ONE_LEVEL',
3351
- 'MIPMAP_LEVELS',
3352
- 'RIPMAP_LEVELS',
3353
- ];
3354
-
3355
- const roundingModes = [
3356
- 'ROUND_DOWN',
3357
- 'ROUND_UP',
3358
- ];
3359
-
3360
- const xSize = parseUint32( dataView, offset );
3361
- const ySize = parseUint32( dataView, offset );
3362
- const modes = parseUint8( dataView, offset );
3363
-
3364
- return {
3365
- xSize: xSize,
3366
- ySize: ySize,
3367
- levelMode: levelModes[ modes & 0xf ],
3368
- roundingMode: roundingModes[ modes >> 4 ]
3369
- };
3370
-
3371
- }
3372
-
3373
- function parseV2f( dataView, offset ) {
3374
-
3375
- const x = parseFloat32( dataView, offset );
3376
- const y = parseFloat32( dataView, offset );
3377
-
3378
- return [ x, y ];
3379
-
3380
- }
3381
-
3382
- function parseV3f( dataView, offset ) {
3383
-
3384
- const x = parseFloat32( dataView, offset );
3385
- const y = parseFloat32( dataView, offset );
3386
- const z = parseFloat32( dataView, offset );
3387
-
3388
- return [ x, y, z ];
3389
-
3390
- }
3391
-
3392
- function parseValue( dataView, buffer, offset, type, size ) {
3393
-
3394
- if ( type === 'string' || type === 'stringvector' || type === 'iccProfile' ) {
3395
-
3396
- return parseFixedLengthString( buffer, offset, size );
3397
-
3398
- } else if ( type === 'chlist' ) {
3399
-
3400
- return parseChlist( dataView, buffer, offset, size );
3401
-
3402
- } else if ( type === 'chromaticities' ) {
3403
-
3404
- return parseChromaticities( dataView, offset );
3405
-
3406
- } else if ( type === 'compression' ) {
3407
-
3408
- return parseCompression( dataView, offset );
3409
-
3410
- } else if ( type === 'box2i' ) {
3411
-
3412
- return parseBox2i( dataView, offset );
3413
-
3414
- } else if ( type === 'envmap' ) {
3415
-
3416
- return parseEnvmap( dataView, offset );
3417
-
3418
- } else if ( type === 'tiledesc' ) {
3419
-
3420
- return parseTiledesc( dataView, offset );
3421
-
3422
- } else if ( type === 'lineOrder' ) {
3423
-
3424
- return parseLineOrder( dataView, offset );
3425
-
3426
- } else if ( type === 'float' ) {
3427
-
3428
- return parseFloat32( dataView, offset );
3429
-
3430
- } else if ( type === 'v2f' ) {
3431
-
3432
- return parseV2f( dataView, offset );
3433
-
3434
- } else if ( type === 'v3f' ) {
3435
-
3436
- return parseV3f( dataView, offset );
3437
-
3438
- } else if ( type === 'int' ) {
3439
-
3440
- return parseInt32( dataView, offset );
3441
-
3442
- } else if ( type === 'rational' ) {
3443
-
3444
- return parseRational( dataView, offset );
3445
-
3446
- } else if ( type === 'timecode' ) {
3447
-
3448
- return parseTimecode( dataView, offset );
3449
-
3450
- } else if ( type === 'preview' ) {
3451
-
3452
- offset.value += size;
3453
- return 'skipped';
3454
-
3455
- } else {
3456
-
3457
- offset.value += size;
3458
- return undefined;
3459
-
3460
- }
3461
-
3462
- }
3463
-
3464
- function roundLog2( x, mode ) {
3465
-
3466
- const log2 = Math.log2( x );
3467
- return mode == 'ROUND_DOWN' ? Math.floor( log2 ) : Math.ceil( log2 );
3468
-
3469
- }
3470
-
3471
- function calculateTileLevels( tiledesc, w, h ) {
3472
-
3473
- let num = 0;
3474
-
3475
- switch ( tiledesc.levelMode ) {
3476
-
3477
- case 'ONE_LEVEL':
3478
- num = 1;
3479
- break;
3480
-
3481
- case 'MIPMAP_LEVELS':
3482
- num = roundLog2( Math.max( w, h ), tiledesc.roundingMode ) + 1;
3483
- break;
3484
-
3485
- case 'RIPMAP_LEVELS':
3486
- throw new Error( 'THREE.EXRLoader: RIPMAP_LEVELS tiles currently unsupported.' );
3487
-
3488
- }
3489
-
3490
- return num;
3491
-
3492
- }
3493
-
3494
- function calculateTiles( count, dataSize, size, roundingMode ) {
3495
-
3496
- const tiles = new Array( count );
3497
-
3498
- for ( let i = 0; i < count; i ++ ) {
3499
-
3500
- const b = ( 1 << i );
3501
- let s = ( dataSize / b ) | 0;
3502
-
3503
- if ( roundingMode == 'ROUND_UP' && s * b < dataSize ) s += 1;
3504
-
3505
- const l = Math.max( s, 1 );
3506
-
3507
- tiles[ i ] = ( ( l + size - 1 ) / size ) | 0;
3508
-
3509
- }
3510
-
3511
- return tiles;
3512
-
3513
- }
3514
-
3515
- function parseTiles() {
3516
-
3517
- const EXRDecoder = this;
3518
- const offset = EXRDecoder.offset;
3519
- const tmpOffset = { value: 0 };
3520
-
3521
- for ( let tile = 0; tile < EXRDecoder.tileCount; tile ++ ) {
3522
-
3523
- const tileX = parseInt32( EXRDecoder.viewer, offset );
3524
- const tileY = parseInt32( EXRDecoder.viewer, offset );
3525
- offset.value += 8; // skip levels - only parsing top-level
3526
- EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset );
3527
-
3528
- const startX = tileX * EXRDecoder.blockWidth;
3529
- const startY = tileY * EXRDecoder.blockHeight;
3530
- EXRDecoder.columns = ( startX + EXRDecoder.blockWidth > EXRDecoder.width ) ? EXRDecoder.width - startX : EXRDecoder.blockWidth;
3531
- EXRDecoder.lines = ( startY + EXRDecoder.blockHeight > EXRDecoder.height ) ? EXRDecoder.height - startY : EXRDecoder.blockHeight;
3532
-
3533
- const bytesBlockLine = EXRDecoder.columns * EXRDecoder.totalBytes;
3534
- const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesBlockLine;
3535
- const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
3536
-
3537
- offset.value += EXRDecoder.size;
3538
-
3539
- for ( let line = 0; line < EXRDecoder.lines; line ++ ) {
3540
-
3541
- const lineOffset = line * EXRDecoder.columns * EXRDecoder.totalBytes;
3542
-
3543
- for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
3544
-
3545
- const name = EXRHeader.channels[ channelID ].name;
3546
- const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
3547
- const cOff = EXRDecoder.decodeChannels[ name ];
3548
-
3549
- if ( cOff === undefined ) continue;
3550
-
3551
- tmpOffset.value = lineOffset + lOff;
3552
- const outLineOffset = ( EXRDecoder.height - ( 1 + startY + line ) ) * EXRDecoder.outLineWidth;
3553
-
3554
- for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
3555
-
3556
- const outIndex = outLineOffset + ( x + startX ) * EXRDecoder.outputChannels + cOff;
3557
- EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
3558
-
3559
- }
3560
-
3561
- }
3562
-
3563
- }
3564
-
3565
- }
3566
-
3567
- }
3568
-
3569
- function parseScanline() {
3570
-
3571
- const EXRDecoder = this;
3572
- const offset = EXRDecoder.offset;
3573
- const tmpOffset = { value: 0 };
3574
-
3575
- for ( let scanlineBlockIdx = 0; scanlineBlockIdx < EXRDecoder.height / EXRDecoder.blockHeight; scanlineBlockIdx ++ ) {
3576
-
3577
- const line = parseInt32( EXRDecoder.viewer, offset ) - EXRHeader.dataWindow.yMin; // line_no
3578
- EXRDecoder.size = parseUint32( EXRDecoder.viewer, offset ); // data_len
3579
- EXRDecoder.lines = ( ( line + EXRDecoder.blockHeight > EXRDecoder.height ) ? ( EXRDecoder.height - line ) : EXRDecoder.blockHeight );
3580
-
3581
- const bytesPerLine = EXRDecoder.columns * EXRDecoder.totalBytes;
3582
- const isCompressed = EXRDecoder.size < EXRDecoder.lines * bytesPerLine;
3583
- const viewer = isCompressed ? EXRDecoder.uncompress( EXRDecoder ) : uncompressRAW( EXRDecoder );
3584
-
3585
- offset.value += EXRDecoder.size;
3586
-
3587
- for ( let line_y = 0; line_y < EXRDecoder.blockHeight; line_y ++ ) {
3588
-
3589
- const scan_y = scanlineBlockIdx * EXRDecoder.blockHeight;
3590
- const true_y = line_y + EXRDecoder.scanOrder( scan_y );
3591
- if ( true_y >= EXRDecoder.height ) continue;
3592
-
3593
- const lineOffset = line_y * bytesPerLine;
3594
- const outLineOffset = ( EXRDecoder.height - 1 - true_y ) * EXRDecoder.outLineWidth;
3595
-
3596
- for ( let channelID = 0; channelID < EXRDecoder.inputChannels.length; channelID ++ ) {
3597
-
3598
- const name = EXRHeader.channels[ channelID ].name;
3599
- const lOff = EXRDecoder.channelByteOffsets[ name ] * EXRDecoder.columns;
3600
- const cOff = EXRDecoder.decodeChannels[ name ];
3601
-
3602
- if ( cOff === undefined ) continue;
3603
-
3604
- tmpOffset.value = lineOffset + lOff;
3605
-
3606
- for ( let x = 0; x < EXRDecoder.columns; x ++ ) {
3607
-
3608
- const outIndex = outLineOffset + x * EXRDecoder.outputChannels + cOff;
3609
- EXRDecoder.byteArray[ outIndex ] = EXRDecoder.getter( viewer, tmpOffset );
3610
-
3611
- }
3612
-
3613
- }
3614
-
3615
- }
3616
-
3617
- }
3618
-
3619
- }
3620
-
3621
- function parseHeader( dataView, buffer, offset ) {
3622
-
3623
- const EXRHeader = {};
3624
-
3625
- if ( dataView.getUint32( 0, true ) != 20000630 ) { // magic
3626
-
3627
- throw new Error( 'THREE.EXRLoader: Provided file doesn\'t appear to be in OpenEXR format.' );
3628
-
3629
- }
3630
-
3631
- EXRHeader.version = dataView.getUint8( 4 );
3632
-
3633
- const spec = dataView.getUint8( 5 ); // fullMask
3634
-
3635
- EXRHeader.spec = {
3636
- singleTile: !! ( spec & 2 ),
3637
- longName: !! ( spec & 4 ),
3638
- deepFormat: !! ( spec & 8 ),
3639
- multiPart: !! ( spec & 16 ),
3640
- };
3641
-
3642
- // start of header
3643
-
3644
- offset.value = 8; // start at 8 - after pre-amble
3645
-
3646
- let keepReading = true;
3647
-
3648
- while ( keepReading ) {
3649
-
3650
- const attributeName = parseNullTerminatedString( buffer, offset );
3651
-
3652
- if ( attributeName === '' ) {
3653
-
3654
- keepReading = false;
3655
-
3656
- } else {
3657
-
3658
- const attributeType = parseNullTerminatedString( buffer, offset );
3659
- const attributeSize = parseUint32( dataView, offset );
3660
- const attributeValue = parseValue( dataView, buffer, offset, attributeType, attributeSize );
3661
-
3662
- if ( attributeValue === undefined ) {
3663
-
3664
- console.warn( `THREE.EXRLoader: Skipped unknown header attribute type \'${attributeType}\'.` );
3665
-
3666
- } else {
3667
-
3668
- EXRHeader[ attributeName ] = attributeValue;
3669
-
3670
- }
3671
-
3672
- }
3673
-
3674
- }
3675
-
3676
- if ( ( spec & -7 ) != 0 ) { // unsupported deep-image, multi-part
3677
-
3678
- console.error( 'THREE.EXRHeader:', EXRHeader );
3679
- throw new Error( 'THREE.EXRLoader: Provided file is currently unsupported.' );
3680
-
3681
- }
3682
-
3683
- return EXRHeader;
3684
-
3685
- }
3686
-
3687
- function setupDecoder( EXRHeader, dataView, uInt8Array, offset, outputType, outputFormat ) {
3688
-
3689
- const EXRDecoder = {
3690
- size: 0,
3691
- viewer: dataView,
3692
- array: uInt8Array,
3693
- offset: offset,
3694
- width: EXRHeader.dataWindow.xMax - EXRHeader.dataWindow.xMin + 1,
3695
- height: EXRHeader.dataWindow.yMax - EXRHeader.dataWindow.yMin + 1,
3696
- inputChannels: EXRHeader.channels,
3697
- channelByteOffsets: {},
3698
- shouldExpand: false,
3699
- scanOrder: null,
3700
- totalBytes: null,
3701
- columns: null,
3702
- lines: null,
3703
- type: null,
3704
- uncompress: null,
3705
- getter: null,
3706
- format: null,
3707
- colorSpace: LinearSRGBColorSpace,
3708
- };
3709
-
3710
- switch ( EXRHeader.compression ) {
3711
-
3712
- case 'NO_COMPRESSION':
3713
- EXRDecoder.blockHeight = 1;
3714
- EXRDecoder.uncompress = uncompressRAW;
3715
- break;
3716
-
3717
- case 'RLE_COMPRESSION':
3718
- EXRDecoder.blockHeight = 1;
3719
- EXRDecoder.uncompress = uncompressRLE;
3720
- break;
3721
-
3722
- case 'ZIPS_COMPRESSION':
3723
- EXRDecoder.blockHeight = 1;
3724
- EXRDecoder.uncompress = uncompressZIP;
3725
- break;
3726
-
3727
- case 'ZIP_COMPRESSION':
3728
- EXRDecoder.blockHeight = 16;
3729
- EXRDecoder.uncompress = uncompressZIP;
3730
- break;
3731
-
3732
- case 'PIZ_COMPRESSION':
3733
- EXRDecoder.blockHeight = 32;
3734
- EXRDecoder.uncompress = uncompressPIZ;
3735
- break;
3736
-
3737
- case 'PXR24_COMPRESSION':
3738
- EXRDecoder.blockHeight = 16;
3739
- EXRDecoder.uncompress = uncompressPXR;
3740
- break;
3741
-
3742
- case 'DWAA_COMPRESSION':
3743
- EXRDecoder.blockHeight = 32;
3744
- EXRDecoder.uncompress = uncompressDWA;
3745
- break;
3746
-
3747
- case 'DWAB_COMPRESSION':
3748
- EXRDecoder.blockHeight = 256;
3749
- EXRDecoder.uncompress = uncompressDWA;
3750
- break;
3751
-
3752
- default:
3753
- throw new Error( 'EXRLoader.parse: ' + EXRHeader.compression + ' is unsupported' );
3754
-
3755
- }
3756
-
3757
- const channels = {};
3758
- for ( const channel of EXRHeader.channels ) {
3759
-
3760
- switch ( channel.name ) {
3761
-
3762
- case 'Y':
3763
- case 'R':
3764
- case 'G':
3765
- case 'B':
3766
- case 'A':
3767
- channels[ channel.name ] = true;
3768
- EXRDecoder.type = channel.pixelType;
3769
-
3770
- }
3771
-
3772
- }
3773
-
3774
- // RGB images will be converted to RGBA format, preventing software emulation in select devices.
3775
- let fillAlpha = false;
3776
- let invalidOutput = false;
3777
-
3778
- // Validate if input texture contain supported channels
3779
- if ( channels.R && channels.G && channels.B ) {
3780
-
3781
- EXRDecoder.outputChannels = 4;
3782
-
3783
- } else if ( channels.Y ) {
3784
-
3785
- EXRDecoder.outputChannels = 1;
3786
-
3787
- } else {
3788
-
3789
- throw new Error( 'EXRLoader.parse: file contains unsupported data channels.' );
3790
-
3791
- }
3792
-
3793
- // Setup output texture configuration
3794
- switch ( EXRDecoder.outputChannels ) {
3795
-
3796
- case 4:
3797
-
3798
- if ( outputFormat == RGBAFormat ) {
3799
-
3800
- fillAlpha = ! channels.A;
3801
- EXRDecoder.format = RGBAFormat;
3802
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3803
- EXRDecoder.outputChannels = 4;
3804
- EXRDecoder.decodeChannels = { R: 0, G: 1, B: 2, A: 3 };
3805
-
3806
- } else if ( outputFormat == RGFormat ) {
3807
-
3808
- EXRDecoder.format = RGFormat;
3809
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3810
- EXRDecoder.outputChannels = 2;
3811
- EXRDecoder.decodeChannels = { R: 0, G: 1 };
3812
-
3813
- } else if ( outputFormat == RedFormat ) {
3814
-
3815
- EXRDecoder.format = RedFormat;
3816
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3817
- EXRDecoder.outputChannels = 1;
3818
- EXRDecoder.decodeChannels = { R: 0 };
3819
-
3820
- } else {
3821
-
3822
- invalidOutput = true;
3823
-
3824
- }
3825
-
3826
- break;
3827
-
3828
- case 1:
3829
-
3830
- if ( outputFormat == RGBAFormat ) {
3831
-
3832
- fillAlpha = true;
3833
- EXRDecoder.format = RGBAFormat;
3834
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3835
- EXRDecoder.outputChannels = 4;
3836
- EXRDecoder.shouldExpand = true;
3837
- EXRDecoder.decodeChannels = { Y: 0 };
3838
-
3839
- } else if ( outputFormat == RGFormat ) {
3840
-
3841
- EXRDecoder.format = RGFormat;
3842
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3843
- EXRDecoder.outputChannels = 2;
3844
- EXRDecoder.shouldExpand = true;
3845
- EXRDecoder.decodeChannels = { Y: 0 };
3846
-
3847
- } else if ( outputFormat == RedFormat ) {
3848
-
3849
- EXRDecoder.format = RedFormat;
3850
- EXRDecoder.colorSpace = LinearSRGBColorSpace;
3851
- EXRDecoder.outputChannels = 1;
3852
- EXRDecoder.decodeChannels = { Y: 0 };
3853
-
3854
- } else {
3855
-
3856
- invalidOutput = true;
3857
-
3858
- }
3859
-
3860
- break;
3861
-
3862
- default:
3863
-
3864
- invalidOutput = true;
3865
-
3866
- }
3867
-
3868
- if ( invalidOutput ) throw new Error( 'EXRLoader.parse: invalid output format for specified file.' );
3869
-
3870
- if ( EXRDecoder.type == 1 ) {
3871
-
3872
- // half
3873
- switch ( outputType ) {
3874
-
3875
- case FloatType:
3876
- EXRDecoder.getter = parseFloat16;
3877
- break;
3878
-
3879
- case HalfFloatType:
3880
- EXRDecoder.getter = parseUint16;
3881
- break;
3882
-
3883
- }
3884
-
3885
- } else if ( EXRDecoder.type == 2 ) {
3886
-
3887
- // float
3888
- switch ( outputType ) {
3889
-
3890
- case FloatType:
3891
- EXRDecoder.getter = parseFloat32;
3892
- break;
3893
-
3894
- case HalfFloatType:
3895
- EXRDecoder.getter = decodeFloat32;
3896
-
3897
- }
3898
-
3899
- } else {
3900
-
3901
- throw new Error( 'EXRLoader.parse: unsupported pixelType ' + EXRDecoder.type + ' for ' + EXRHeader.compression + '.' );
3902
-
3903
- }
3904
-
3905
- EXRDecoder.columns = EXRDecoder.width;
3906
- const size = EXRDecoder.width * EXRDecoder.height * EXRDecoder.outputChannels;
3907
-
3908
- switch ( outputType ) {
3909
-
3910
- case FloatType:
3911
- EXRDecoder.byteArray = new Float32Array( size );
3912
-
3913
- // Fill initially with 1s for the alpha value if the texture is not RGBA, RGB values will be overwritten
3914
- if ( fillAlpha )
3915
- EXRDecoder.byteArray.fill( 1, 0, size );
3916
-
3917
- break;
3918
-
3919
- case HalfFloatType:
3920
- EXRDecoder.byteArray = new Uint16Array( size );
3921
-
3922
- if ( fillAlpha )
3923
- EXRDecoder.byteArray.fill( 0x3C00, 0, size ); // Uint16Array holds half float data, 0x3C00 is 1
3924
-
3925
- break;
3926
-
3927
- default:
3928
- console.error( 'THREE.EXRLoader: unsupported type: ', outputType );
3929
- break;
3930
-
3931
- }
3932
-
3933
- let byteOffset = 0;
3934
- for ( const channel of EXRHeader.channels ) {
3935
-
3936
- if ( EXRDecoder.decodeChannels[ channel.name ] !== undefined ) {
3937
-
3938
- EXRDecoder.channelByteOffsets[ channel.name ] = byteOffset;
3939
-
3940
- }
3941
-
3942
- byteOffset += channel.pixelType * 2;
3943
-
3944
- }
3945
-
3946
- EXRDecoder.totalBytes = byteOffset;
3947
- EXRDecoder.outLineWidth = EXRDecoder.width * EXRDecoder.outputChannels;
3948
-
3949
- if ( EXRHeader.lineOrder === 'INCREASING_Y' ) {
3950
-
3951
- EXRDecoder.scanOrder = ( y ) => y;
3952
-
3953
- } else {
3954
-
3955
- EXRDecoder.scanOrder = ( y ) => EXRDecoder.height - 1 - y;
3956
-
3957
- }
3958
-
3959
- if ( EXRHeader.spec.singleTile ) {
3960
-
3961
- EXRDecoder.blockHeight = EXRHeader.tiles.ySize;
3962
- EXRDecoder.blockWidth = EXRHeader.tiles.xSize;
3963
-
3964
- const numXLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
3965
- // const numYLevels = calculateTileLevels( EXRHeader.tiles, EXRDecoder.width, EXRDecoder.height );
3966
-
3967
- const numXTiles = calculateTiles( numXLevels, EXRDecoder.width, EXRHeader.tiles.xSize, EXRHeader.tiles.roundingMode );
3968
- const numYTiles = calculateTiles( numXLevels, EXRDecoder.height, EXRHeader.tiles.ySize, EXRHeader.tiles.roundingMode );
3969
-
3970
- EXRDecoder.tileCount = numXTiles[ 0 ] * numYTiles[ 0 ];
3971
-
3972
- for ( let l = 0; l < numXLevels; l ++ )
3973
- for ( let y = 0; y < numYTiles[ l ]; y ++ )
3974
- for ( let x = 0; x < numXTiles[ l ]; x ++ )
3975
- parseInt64( dataView, offset ); // tileOffset
3976
-
3977
- EXRDecoder.decode = parseTiles.bind( EXRDecoder );
3978
-
3979
- } else {
3980
-
3981
- EXRDecoder.blockWidth = EXRDecoder.width;
3982
- const blockCount = Math.ceil( EXRDecoder.height / EXRDecoder.blockHeight );
3983
-
3984
- for ( let i = 0; i < blockCount; i ++ )
3985
- parseInt64( dataView, offset ); // scanlineOffset
3986
-
3987
- EXRDecoder.decode = parseScanline.bind( EXRDecoder );
3988
-
3989
- }
3990
-
3991
- return EXRDecoder;
3992
-
3993
- }
3994
-
3995
- // start parsing file [START]
3996
- const offset = { value: 0 };
3997
- const bufferDataView = new DataView( buffer );
3998
- const uInt8Array = new Uint8Array( buffer );
3999
-
4000
- // get header information and validate format.
4001
- const EXRHeader = parseHeader( bufferDataView, buffer, offset );
4002
-
4003
- // get input compression information and prepare decoding.
4004
- const EXRDecoder = setupDecoder( EXRHeader, bufferDataView, uInt8Array, offset, this.type, this.outputFormat );
4005
-
4006
- // parse input data
4007
- EXRDecoder.decode();
4008
-
4009
- // output texture post-processing
4010
- if ( EXRDecoder.shouldExpand ) {
4011
-
4012
- const byteArray = EXRDecoder.byteArray;
4013
-
4014
- if ( this.outputFormat == RGBAFormat ) {
4015
-
4016
- for ( let i = 0; i < byteArray.length; i += 4 )
4017
- byteArray[ i + 2 ] = ( byteArray[ i + 1 ] = byteArray[ i ] );
4018
-
4019
- } else if ( this.outputFormat == RGFormat ) {
4020
-
4021
- for ( let i = 0; i < byteArray.length; i += 2 )
4022
- byteArray[ i + 1 ] = byteArray[ i ];
4023
-
4024
- }
4025
-
4026
- }
4027
-
4028
- return {
4029
- header: EXRHeader,
4030
- width: EXRDecoder.width,
4031
- height: EXRDecoder.height,
4032
- data: EXRDecoder.byteArray,
4033
- format: EXRDecoder.format,
4034
- colorSpace: EXRDecoder.colorSpace,
4035
- type: this.type,
4036
- };
4037
-
4038
- }
4039
-
4040
- /**
4041
- * Sets the texture type.
4042
- *
4043
- * @param {(HalfFloatType|FloatType)} value - The texture type to set.
4044
- * @return {EXRLoader} A reference to this loader.
4045
- */
4046
- setDataType( value ) {
4047
-
4048
- this.type = value;
4049
- return this;
4050
-
4051
- }
4052
-
4053
- /**
4054
- * Sets texture output format. Defaults to `RGBAFormat`.
4055
- *
4056
- * @param {(RGBAFormat|RGFormat|RedFormat)} value - Texture output format.
4057
- * @return {EXRLoader} A reference to this loader.
4058
- */
4059
- setOutputFormat( value ) {
4060
-
4061
- this.outputFormat = value;
4062
- return this;
4063
-
4064
- }
4065
-
4066
- load( url, onLoad, onProgress, onError ) {
4067
-
4068
- function onLoadCallback( texture, texData ) {
4069
-
4070
- texture.colorSpace = texData.colorSpace;
4071
- texture.minFilter = LinearFilter;
4072
- texture.magFilter = LinearFilter;
4073
- texture.generateMipmaps = false;
4074
- texture.flipY = false;
4075
-
4076
- if ( onLoad ) onLoad( texture, texData );
4077
-
4078
- }
4079
-
4080
- return super.load( url, onLoadCallback, onProgress, onError );
4081
-
4082
- }
4083
-
937
+ let ktx2Loader = null;
938
+ function getKTX2Loader(renderer) {
939
+ if (!ktx2Loader) {
940
+ ktx2Loader = new KTX2Loader();
941
+ ktx2Loader.setTranscoderPath('/basis/');
942
+ ktx2Loader.detectSupport(renderer);
943
+ }
944
+ return ktx2Loader;
4084
945
  }
4085
-
4086
- function loadEnvironment(renderer, url) {
946
+ function loadEnvironment(renderer, url, onProgress) {
947
+ const cleanUrl = url.split('?')[0].split('#')[0].toLowerCase();
948
+ // For blob URLs, the filename is passed as a hash fragment (e.g. blob:...#file.ktx2)
949
+ const hash = (url.split('#')[1] || '').toLowerCase();
950
+ const hashExt = hash.includes('.') ? '.' + hash.split('.').pop() : '';
951
+ const pmrem = new THREE.PMREMGenerator(renderer);
952
+ pmrem.compileEquirectangularShader();
953
+ const finalize = (texture) => {
954
+ const envMap = pmrem.fromEquirectangular(texture).texture;
955
+ texture.dispose();
956
+ pmrem.dispose();
957
+ return { envMap, dispose: () => envMap.dispose() };
958
+ };
959
+ if (cleanUrl.endsWith('.ktx2') || hashExt === '.ktx2') {
960
+ return new Promise((resolve, reject) => {
961
+ getKTX2Loader(renderer).load(url, (compressedTex) => {
962
+ // Compressed textures can't be flipped by WebGL on upload, so the
963
+ // top-down KTX2 data is inverted vs what PMREM expects. Render to
964
+ // an intermediate target with flipped v to decompress + correct.
965
+ const w = compressedTex.image.width, h = compressedTex.image.height;
966
+ const rt = new THREE.WebGLRenderTarget(w, h, { type: THREE.HalfFloatType });
967
+ const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
968
+ const mat = new THREE.ShaderMaterial({
969
+ uniforms: { tMap: { value: compressedTex } },
970
+ vertexShader: 'varying vec2 vUv; void main(){ vUv=uv; gl_Position=vec4(position,1.); }',
971
+ fragmentShader: 'uniform sampler2D tMap; varying vec2 vUv; void main(){ gl_FragColor=texture2D(tMap,vec2(vUv.x,1.-vUv.y)); }',
972
+ });
973
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
974
+ const sc = new THREE.Scene();
975
+ sc.add(quad);
976
+ const prevRT = renderer.getRenderTarget();
977
+ renderer.setRenderTarget(rt);
978
+ renderer.render(sc, cam);
979
+ renderer.setRenderTarget(prevRT);
980
+ mat.dispose();
981
+ quad.geometry.dispose();
982
+ compressedTex.dispose();
983
+ rt.texture.mapping = THREE.EquirectangularReflectionMapping;
984
+ const envMap = pmrem.fromEquirectangular(rt.texture).texture;
985
+ rt.dispose();
986
+ pmrem.dispose();
987
+ resolve({ envMap, dispose: () => envMap.dispose() });
988
+ }, (e) => { if (onProgress && e.lengthComputable)
989
+ onProgress(e.loaded, e.total); }, reject);
990
+ });
991
+ }
4087
992
  return new Promise((resolve, reject) => {
4088
- const pmrem = new THREE.PMREMGenerator(renderer);
4089
- pmrem.compileEquirectangularShader();
4090
- const onLoad = (texture) => {
4091
- const envMap = pmrem.fromEquirectangular(texture).texture;
4092
- texture.dispose();
4093
- pmrem.dispose();
4094
- resolve({ envMap, dispose: () => envMap.dispose() });
4095
- };
4096
- const cleanUrl = url.split('?')[0].split('#')[0].toLowerCase();
4097
- if (cleanUrl.endsWith('.exr')) {
4098
- new EXRLoader().load(url, onLoad, undefined, reject);
993
+ const onLoad = (texture) => resolve(finalize(texture));
994
+ const handleProgress = (e) => { if (onProgress && e.lengthComputable)
995
+ onProgress(e.loaded, e.total); };
996
+ if (cleanUrl.endsWith('.exr') || hashExt === '.exr') {
997
+ new EXRLoader().load(url, onLoad, handleProgress, reject);
4099
998
  }
4100
999
  else {
4101
- new RGBELoader().load(url, onLoad, undefined, reject);
1000
+ new HDRLoader().load(url, onLoad, handleProgress, reject);
4102
1001
  }
4103
1002
  });
4104
1003
  }
4105
1004
 
4106
1005
  const DEFAULT_MAX_MODEL_SIZE = 30 * 1024 * 1024; // 30MB
4107
- function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https://xwqtyabmavpacejuypyp.supabase.co/storage/v1/object/public/vrm-templates/5705015963733407866.vrm', backgroundColor = 0xffffff, blendshapeMap, expressionOverrides, onModelLoad, maxModelSize = DEFAULT_MAX_MODEL_SIZE, cameraPosition, cameraTarget, cameraFov, lightIntensity, idleAnimationUrl, animationSpeed = 1, animationWeight = 1, animationCrossfade = 0.5, postProcessing, environmentUrl, environmentIntensity, environmentBlur, environmentZoom, onEnvironmentLoad, features, orbitAngle, orbitElevation, avatarRotation, onOrbitChange, }) {
1006
+ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https://xwqtyabmavpacejuypyp.supabase.co/storage/v1/object/public/vrm-templates/5705015963733407866.vrm', backgroundColor = 0xffffff, blendshapeMap, expressionOverrides, onModelLoad, maxModelSize = DEFAULT_MAX_MODEL_SIZE, cameraPosition, cameraTarget, cameraFov, lightIntensity, idleAnimationUrl, animationSpeed = 1, animationWeight = 1, animationCrossfade = 0.5, postProcessing, environmentUrl, environmentIntensity, environmentBlur, environmentZoom, onEnvironmentLoad, onEnvironmentProgress, features, orbitAngle, orbitElevation, avatarRotation, onOrbitChange, cursorFollow = true, preserveDrawingBuffer = false, }) {
4108
1007
  const containerRef = useRef(null);
4109
1008
  const rendererRef = useRef(null);
4110
1009
  const sceneRef = useRef(null);
@@ -4127,6 +1026,8 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4127
1026
  envZoomRef.current = environmentZoom;
4128
1027
  const onEnvLoadRef = useRef(onEnvironmentLoad);
4129
1028
  onEnvLoadRef.current = onEnvironmentLoad;
1029
+ const onEnvProgressRef = useRef(onEnvironmentProgress);
1030
+ onEnvProgressRef.current = onEnvironmentProgress;
4130
1031
  const [loading, setLoading] = useState(true);
4131
1032
  const [error, setError] = useState(null);
4132
1033
  const animationFrameRef = useRef(0);
@@ -4150,6 +1051,9 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4150
1051
  const isA2FActiveRef = useRef(false);
4151
1052
  const idleMorphsRef = useRef([]);
4152
1053
  const springSettleFramesRef = useRef(0);
1054
+ const cursorFollowRef = useRef(cursorFollow);
1055
+ cursorFollowRef.current = cursorFollow;
1056
+ const cursorRef = useRef({ x: 0, y: 0, active: false });
4153
1057
  const applyBlendshapes = useCallback((vrm, shapes) => {
4154
1058
  const arkitMap = {};
4155
1059
  ARKIT_BLENDSHAPES.forEach((name, i) => {
@@ -4174,7 +1078,10 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4174
1078
  trySet('blinkLeft', blinkLeft);
4175
1079
  trySet('blinkRight', blinkRight);
4176
1080
  trySet('ou', funnel);
4177
- vrm.expressionManager.update();
1081
+ try {
1082
+ vrm.expressionManager.update();
1083
+ }
1084
+ catch { }
4178
1085
  }
4179
1086
  vrm.scene.traverse((obj) => {
4180
1087
  if (obj.isMesh) {
@@ -4202,7 +1109,8 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4202
1109
  renderer = new THREE.WebGLRenderer({
4203
1110
  antialias: true,
4204
1111
  alpha: true,
4205
- powerPreference: 'high-performance'
1112
+ powerPreference: 'high-performance',
1113
+ preserveDrawingBuffer,
4206
1114
  });
4207
1115
  }
4208
1116
  catch {
@@ -4290,6 +1198,11 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4290
1198
  if (rArm)
4291
1199
  rArm.rotation.z = 1.0;
4292
1200
  }
1201
+ if (vrm.lookAt) {
1202
+ const proxy = new VRMLookAtQuaternionProxy(vrm.lookAt);
1203
+ proxy.name = 'VRMLookAtQuaternionProxy';
1204
+ vrm.scene.add(proxy);
1205
+ }
4293
1206
  vrm.update(0);
4294
1207
  vrm.springBoneManager?.reset();
4295
1208
  springSettleFramesRef.current = 30;
@@ -4312,13 +1225,17 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4312
1225
  setError(detail);
4313
1226
  setLoading(false);
4314
1227
  });
4315
- const clock = new THREE.Clock();
1228
+ const timer = new THREE.Timer();
4316
1229
  const animate = () => {
4317
1230
  animationFrameRef.current = requestAnimationFrame(animate);
4318
- const delta = clock.getDelta();
1231
+ timer.update();
1232
+ const delta = timer.getDelta();
4319
1233
  animationTimeRef.current += delta;
4320
1234
  if (vrmRef.current) {
4321
- vrmRef.current.update(delta);
1235
+ try {
1236
+ vrmRef.current.update(delta);
1237
+ }
1238
+ catch { }
4322
1239
  if (featuresRef.current?.springBones === false || springSettleFramesRef.current > 0) {
4323
1240
  vrmRef.current.springBoneManager?.reset();
4324
1241
  if (springSettleFramesRef.current > 0)
@@ -4392,13 +1309,18 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4392
1309
  idle.happy += (idle.happyTarget - idle.happy) * 0.02;
4393
1310
  idle.browInner += (idle.browTarget - idle.browInner) * 0.02;
4394
1311
  idle.cheek += (idle.cheekTarget - idle.cheek) * 0.02;
4395
- if (t >= idle.eyeNext) {
1312
+ const cursor = cursorRef.current;
1313
+ if (cursorFollowRef.current && cursor.active) {
1314
+ idle.eyeTargetX = cursor.x * 0.26; // ±15° horizontal (0.26 rad ≈ 15°)
1315
+ idle.eyeTargetY = cursor.y * 0.17; // ±10° vertical (0.17 rad ≈ 10°)
1316
+ }
1317
+ else if (t >= idle.eyeNext) {
4396
1318
  idle.eyeTargetX = (Math.random() - 0.5) * 0.06;
4397
1319
  idle.eyeTargetY = (Math.random() - 0.5) * 0.04;
4398
1320
  idle.eyeNext = t + 1.5 + Math.random() * 3;
4399
1321
  }
4400
- idle.eyeX += (idle.eyeTargetX - idle.eyeX) * 0.03;
4401
- idle.eyeY += (idle.eyeTargetY - idle.eyeY) * 0.03;
1322
+ idle.eyeX += (idle.eyeTargetX - idle.eyeX) * 0.06;
1323
+ idle.eyeY += (idle.eyeTargetY - idle.eyeY) * 0.06;
4402
1324
  const em = vrmRef.current.expressionManager;
4403
1325
  try {
4404
1326
  em.setValue('blink', Math.max(bv, 0));
@@ -4408,7 +1330,10 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4408
1330
  em.setValue('happy', Math.max(idle.happy, 0));
4409
1331
  }
4410
1332
  catch { }
4411
- em.update();
1333
+ try {
1334
+ em.update();
1335
+ }
1336
+ catch { }
4412
1337
  for (const m of idleMorphsRef.current) {
4413
1338
  if (m.brow !== undefined)
4414
1339
  m.inf[m.brow] = idle.browInner;
@@ -4486,7 +1411,16 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4486
1411
  container.removeChild(renderer.domElement);
4487
1412
  }
4488
1413
  };
4489
- }, [width, height, modelUrl, maxModelSize]);
1414
+ }, [modelUrl, maxModelSize, preserveDrawingBuffer]);
1415
+ // Resize renderer + camera without rebuilding scene
1416
+ useEffect(() => {
1417
+ const renderer = rendererRef.current, camera = cameraRef.current;
1418
+ if (!renderer || !camera)
1419
+ return;
1420
+ renderer.setSize(width, height);
1421
+ camera.aspect = width / height;
1422
+ camera.updateProjectionMatrix();
1423
+ }, [width, height]);
4490
1424
  useEffect(() => {
4491
1425
  composerRef.current?.dispose();
4492
1426
  composerRef.current = null;
@@ -4526,7 +1460,14 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4526
1460
  let cancelled = false;
4527
1461
  const loader = new GLTFLoader();
4528
1462
  loader.register((parser) => new VRMAnimationLoaderPlugin(parser));
1463
+ const origWarn = console.warn;
1464
+ console.warn = (...args) => {
1465
+ if (typeof args[0] === 'string' && args[0].includes('specVersion'))
1466
+ return;
1467
+ origWarn.apply(console, args);
1468
+ };
4529
1469
  loader.load(idleAnimationUrl, (gltf) => {
1470
+ console.warn = origWarn;
4530
1471
  if (cancelled || !vrmRef.current)
4531
1472
  return;
4532
1473
  const animations = gltf.userData.vrmAnimations;
@@ -4551,6 +1492,7 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4551
1492
  }
4552
1493
  clipActionRef.current = newAction;
4553
1494
  }, () => { }, (err) => {
1495
+ console.warn = origWarn;
4554
1496
  if (cancelled)
4555
1497
  return;
4556
1498
  console.warn('[VRM] Failed to load animation clip:', err);
@@ -4588,7 +1530,7 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4588
1530
  }
4589
1531
  let cancelled = false;
4590
1532
  const prev = envMapRef.current;
4591
- loadEnvironment(renderer, environmentUrl).then(r => {
1533
+ loadEnvironment(renderer, environmentUrl, (loaded, total) => onEnvProgressRef.current?.(loaded, total)).then(r => {
4592
1534
  if (cancelled) {
4593
1535
  r.dispose();
4594
1536
  return;
@@ -4720,14 +1662,58 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4720
1662
  }
4721
1663
  onOrbitChangeRef.current?.(o.targetAngle, o.targetElevation);
4722
1664
  };
1665
+ const onTouchStart = (e) => {
1666
+ if (e.touches.length !== 1)
1667
+ return;
1668
+ e.preventDefault();
1669
+ const t = e.touches[0];
1670
+ orbitRef.current.dragging = true;
1671
+ orbitRef.current.lastX = t.clientX;
1672
+ orbitRef.current.lastY = t.clientY;
1673
+ };
1674
+ const onTouchMove = (e) => {
1675
+ if (!orbitRef.current.dragging || e.touches.length !== 1)
1676
+ return;
1677
+ e.preventDefault();
1678
+ const t = e.touches[0];
1679
+ const dx = t.clientX - orbitRef.current.lastX;
1680
+ const dy = t.clientY - orbitRef.current.lastY;
1681
+ orbitRef.current.lastX = t.clientX;
1682
+ orbitRef.current.lastY = t.clientY;
1683
+ orbitRef.current.angle -= dx * 0.005;
1684
+ orbitRef.current.targetAngle = orbitRef.current.angle;
1685
+ orbitRef.current.elevation = Math.max(-Math.PI / 3, Math.min(Math.PI / 3, orbitRef.current.elevation + dy * 0.005));
1686
+ orbitRef.current.targetElevation = orbitRef.current.elevation;
1687
+ applyCameraOrbit();
1688
+ onOrbitChangeRef.current?.(orbitRef.current.angle, orbitRef.current.elevation);
1689
+ };
1690
+ const onTouchEnd = () => { orbitRef.current.dragging = false; };
1691
+ const onCursorMove = (e) => {
1692
+ const rect = container.getBoundingClientRect();
1693
+ cursorRef.current.x = ((e.clientX - rect.left) / rect.width) * 2 - 1;
1694
+ cursorRef.current.y = ((e.clientY - rect.top) / rect.height) * 2 - 1;
1695
+ cursorRef.current.active = true;
1696
+ };
1697
+ const onCursorLeave = () => { cursorRef.current.active = false; };
1698
+ container.style.touchAction = 'none';
4723
1699
  container.addEventListener('wheel', onWheel, { passive: false });
4724
1700
  container.addEventListener('mousedown', onMouseDown);
1701
+ container.addEventListener('touchstart', onTouchStart, { passive: false });
1702
+ container.addEventListener('touchmove', onTouchMove, { passive: false });
1703
+ container.addEventListener('touchend', onTouchEnd);
1704
+ container.addEventListener('mousemove', onCursorMove);
1705
+ container.addEventListener('mouseleave', onCursorLeave);
4725
1706
  window.addEventListener('mousemove', onMouseMove);
4726
1707
  window.addEventListener('mouseup', onMouseUp);
4727
1708
  window.addEventListener('keydown', onKeyDown);
4728
1709
  return () => {
4729
1710
  container.removeEventListener('wheel', onWheel);
4730
1711
  container.removeEventListener('mousedown', onMouseDown);
1712
+ container.removeEventListener('touchstart', onTouchStart);
1713
+ container.removeEventListener('touchmove', onTouchMove);
1714
+ container.removeEventListener('touchend', onTouchEnd);
1715
+ container.removeEventListener('mousemove', onCursorMove);
1716
+ container.removeEventListener('mouseleave', onCursorLeave);
4731
1717
  window.removeEventListener('mousemove', onMouseMove);
4732
1718
  window.removeEventListener('mouseup', onMouseUp);
4733
1719
  window.removeEventListener('keydown', onKeyDown);
@@ -4768,7 +1754,10 @@ function VRMAvatar({ blendshapes, width = 400, height = 400, modelUrl = 'https:/
4768
1754
  catch { /* expression doesn't exist on this model */ }
4769
1755
  }
4770
1756
  }
4771
- vrm.expressionManager.update();
1757
+ try {
1758
+ vrm.expressionManager.update();
1759
+ }
1760
+ catch { }
4772
1761
  }, [expressionOverrides, blendshapes]);
4773
1762
  return (jsxs("div", { className: "relative", style: { width, height }, children: [jsx("div", { ref: containerRef, className: "rounded-lg overflow-hidden" }), loading && (jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-gray-800 rounded-lg", children: jsx("div", { className: "text-white text-sm", children: "Loading VRM avatar..." }) })), error && (jsx("div", { className: "absolute inset-0 flex items-center justify-center bg-red-900/50 rounded-lg", children: jsx("div", { className: "text-white text-sm", children: error }) }))] }));
4774
1763
  }