@margoengine/loaders 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
package/dist/vdb.js ADDED
@@ -0,0 +1,663 @@
1
+ // OpenVDB `.vdb` sparse volumes: file versions 222 and later, uncompressed, zlib or Blosc-LZ4 grids, any tree depth.
2
+ import { LoaderError } from './types.js';
3
+ import { latin1, throwIfAborted, toBytes } from './util.js';
4
+ import { inflate } from './zip.js';
5
+ const F = 'VDB';
6
+ const MIN_VERSION = 222;
7
+ const COMPRESS_ZIP = 1;
8
+ const COMPRESS_ACTIVE_MASK = 2;
9
+ const COMPRESS_BLOSC = 4;
10
+ const LITTLE = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
11
+ // What precedes a node's values, saying how its inactive values were left out. Kind 1 has no name here: every inactive
12
+ // value is minus the background, which is what any kind without its own values starts from.
13
+ const NO_MASK_OR_INACTIVE = 0;
14
+ const NO_MASK_ONE_INACTIVE = 2;
15
+ const MASK_NO_INACTIVE = 3;
16
+ const MASK_ONE_INACTIVE = 4;
17
+ const MASK_TWO_INACTIVE = 5;
18
+ const NO_MASK_ALL_VALUES = 6;
19
+ const CODECS = {
20
+ float: scalar('float', 4, (n) => new Float32Array(n), (v, at) => v.getFloat32(at, true)),
21
+ double: scalar('double', 8, (n) => new Float64Array(n), (v, at) => v.getFloat64(at, true)),
22
+ int32: scalar('int32', 4, (n) => new Int32Array(n), (v, at) => v.getInt32(at, true)),
23
+ int64: scalar('int64', 8, (n) => new Float64Array(n), (v, at) => Number(v.getBigInt64(at, true))),
24
+ vec3i: {
25
+ ...scalar('vec3i', 4, (n) => new Int32Array(n), (v, at) => v.getInt32(at, true)),
26
+ components: 3,
27
+ },
28
+ vec3s: {
29
+ ...scalar('vec3s', 4, (n) => new Float32Array(n), (v, at) => v.getFloat32(at, true)),
30
+ components: 3,
31
+ },
32
+ vec3d: {
33
+ ...scalar('vec3d', 8, (n) => new Float64Array(n), (v, at) => v.getFloat64(at, true)),
34
+ components: 3,
35
+ },
36
+ };
37
+ const HALF_TYPES = new Set(['float', 'double', 'vec3s', 'vec3d']);
38
+ function scalar(valueType, size, make, read) {
39
+ return { valueType, components: 1, size, make, read };
40
+ }
41
+ /** IEEE 754 binary16 bits to a number. */
42
+ function halfToNumber(bits) {
43
+ const sign = bits & 0x8000 ? -1 : 1, exponent = (bits >> 10) & 31, fraction = bits & 1023;
44
+ if (exponent === 31)
45
+ return fraction ? Number.NaN : sign * Number.POSITIVE_INFINITY;
46
+ if (exponent === 0)
47
+ return sign * fraction * 2 ** -24;
48
+ return sign * (1 + fraction / 1024) * 2 ** (exponent - 15);
49
+ }
50
+ /** Bounds-checked little-endian reads over the whole file. */
51
+ class Reader {
52
+ constructor(bytes) {
53
+ this.bytes = bytes;
54
+ this.pos = 0;
55
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
56
+ }
57
+ need(count, what) {
58
+ if (!Number.isSafeInteger(count) || count < 0 || this.pos + count > this.bytes.length)
59
+ throw new LoaderError(F, 'truncated', `${what} runs past the end of the file`);
60
+ }
61
+ take(count, what) {
62
+ this.need(count, what);
63
+ const part = this.bytes.subarray(this.pos, this.pos + count);
64
+ this.pos += count;
65
+ return part;
66
+ }
67
+ u8(what) {
68
+ this.need(1, what);
69
+ return this.bytes[this.pos++];
70
+ }
71
+ i8(what) {
72
+ return (this.u8(what) << 24) >> 24;
73
+ }
74
+ u32(what) {
75
+ this.need(4, what);
76
+ this.pos += 4;
77
+ return this.view.getUint32(this.pos - 4, true);
78
+ }
79
+ i32(what) {
80
+ this.need(4, what);
81
+ this.pos += 4;
82
+ return this.view.getInt32(this.pos - 4, true);
83
+ }
84
+ i64(what) {
85
+ this.need(8, what);
86
+ this.pos += 8;
87
+ const value = this.view.getBigInt64(this.pos - 8, true);
88
+ if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER))
89
+ throw new LoaderError(F, 'range', `${what} is too large`);
90
+ return Number(value);
91
+ }
92
+ f64(what) {
93
+ this.need(8, what);
94
+ this.pos += 8;
95
+ return this.view.getFloat64(this.pos - 8, true);
96
+ }
97
+ text(what) {
98
+ return new TextDecoder().decode(this.take(this.u32(what), what));
99
+ }
100
+ coord(what) {
101
+ return [this.i32(what), this.i32(what), this.i32(what)];
102
+ }
103
+ seek(at, what) {
104
+ if (!Number.isSafeInteger(at) || at < 0 || at > this.bytes.length)
105
+ throw new LoaderError(F, 'truncated', `${what} points past the end of the file`);
106
+ this.pos = at;
107
+ }
108
+ }
109
+ const countBits = (mask) => {
110
+ let count = 0;
111
+ for (let byte of mask)
112
+ for (; byte; byte &= byte - 1)
113
+ count++;
114
+ return count;
115
+ };
116
+ const bit = (mask, index) => (mask[index >> 3] & (1 << (index & 7))) !== 0;
117
+ /** One metadata block: a count, then name, type name, payload size and payload for each. */
118
+ function readMeta(reader) {
119
+ const meta = Object.create(null), count = reader.u32('metadata count');
120
+ reader.need(count * 12, 'metadata');
121
+ for (let i = 0; i < count; i++) {
122
+ const name = reader.text('metadata name'), type = reader.text('metadata type'), size = reader.u32('metadata size'), end = reader.pos + size;
123
+ reader.need(size, `metadata ${name}`);
124
+ meta[name] = metaValue(reader, type, size);
125
+ reader.pos = end;
126
+ }
127
+ return meta;
128
+ }
129
+ function metaValue(reader, type, size) {
130
+ const need = { bool: 1, int32: 4, int64: 8, float: 4, double: 8, vec3i: 12, vec3s: 12, vec3d: 24 }[type];
131
+ if (type === 'string')
132
+ return new TextDecoder().decode(reader.take(size, 'metadata text'));
133
+ if (need === undefined || size !== need)
134
+ return reader.bytes.slice(reader.pos, reader.pos + size);
135
+ const { view, pos } = reader;
136
+ switch (type) {
137
+ case 'bool':
138
+ return reader.bytes[pos] !== 0;
139
+ case 'int32':
140
+ return view.getInt32(pos, true);
141
+ case 'int64':
142
+ return Number(view.getBigInt64(pos, true));
143
+ case 'float':
144
+ return view.getFloat32(pos, true);
145
+ case 'double':
146
+ return view.getFloat64(pos, true);
147
+ case 'vec3i':
148
+ return [0, 4, 8].map((at) => view.getInt32(pos + at, true));
149
+ case 'vec3s':
150
+ return [0, 4, 8].map((at) => view.getFloat32(pos + at, true));
151
+ default:
152
+ return [0, 8, 16].map((at) => view.getFloat64(pos + at, true));
153
+ }
154
+ }
155
+ /** The grid's linear map as a column-major 4x4, or null for a map that has no matrix. */
156
+ function readTransform(reader) {
157
+ const type = reader.text('transform type'), vector = () => [
158
+ reader.f64('transform'),
159
+ reader.f64('transform'),
160
+ reader.f64('transform'),
161
+ ], matrix = new Float64Array(16);
162
+ matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1;
163
+ switch (type) {
164
+ case 'AffineMap':
165
+ case 'UnitaryMap':
166
+ // Stored row by row for row vectors, which is the same 16 numbers as column-major for column vectors.
167
+ for (let i = 0; i < 16; i++)
168
+ matrix[i] = reader.f64('transform');
169
+ return matrix;
170
+ case 'TranslationMap':
171
+ matrix.set(vector(), 12);
172
+ return matrix;
173
+ case 'ScaleTranslateMap':
174
+ case 'UniformScaleTranslateMap':
175
+ case 'ScaleMap':
176
+ case 'UniformScaleMap': {
177
+ if (type.endsWith('TranslateMap'))
178
+ matrix.set(vector(), 12);
179
+ const scale = vector();
180
+ // Voxel size, inverse scale, inverse square scale and inverse doubled scale all follow from the scale.
181
+ reader.take(4 * 24, 'transform');
182
+ [matrix[0], matrix[5], matrix[10]] = scale;
183
+ return matrix;
184
+ }
185
+ default:
186
+ return null;
187
+ }
188
+ }
189
+ /** Decodes an LZ4 block into `output`, which it must fill exactly. */
190
+ function lz4(input, output, subject) {
191
+ const corrupt = () => new LoaderError(F, 'zip', `${subject} has corrupt LZ4 data`);
192
+ let from = 0, to = 0;
193
+ while (from < input.length) {
194
+ const token = input[from++];
195
+ let literals = token >> 4;
196
+ if (literals === 15)
197
+ for (let more = 255; more === 255; literals += more) {
198
+ if (from >= input.length)
199
+ throw corrupt();
200
+ more = input[from++];
201
+ }
202
+ if (from + literals > input.length || to + literals > output.length)
203
+ throw corrupt();
204
+ output.set(input.subarray(from, from + literals), to);
205
+ from += literals;
206
+ to += literals;
207
+ if (from === input.length)
208
+ break;
209
+ if (from + 2 > input.length)
210
+ throw corrupt();
211
+ const offset = input[from] | (input[from + 1] << 8);
212
+ from += 2;
213
+ let length = (token & 15) + 4;
214
+ if ((token & 15) === 15)
215
+ for (let more = 255; more === 255; length += more) {
216
+ if (from >= input.length)
217
+ throw corrupt();
218
+ more = input[from++];
219
+ }
220
+ if (offset === 0 || offset > to || to + length > output.length)
221
+ throw corrupt();
222
+ // One byte at a time: a match may overlap what it writes.
223
+ for (let i = 0; i < length; i++, to++)
224
+ output[to] = output[to - offset];
225
+ }
226
+ if (to !== output.length)
227
+ throw corrupt();
228
+ }
229
+ /** Decodes one Blosc 1 chunk of `size` bytes: LZ4 blocks or a stored copy, with byte shuffle undone. */
230
+ function blosc(chunk, size, subject) {
231
+ const corrupt = (why) => new LoaderError(F, 'zip', `${subject}: ${why}`);
232
+ if (chunk.length < 16)
233
+ throw corrupt('Blosc header cut short');
234
+ const view = new DataView(chunk.buffer, chunk.byteOffset, chunk.byteLength), flags = chunk[2], typeSize = chunk[3], bytes = view.getUint32(4, true), blockSize = view.getUint32(8, true), shuffled = (flags & 1) !== 0, stored = (flags & 2) !== 0, single = (flags & 16) !== 0;
235
+ if (bytes !== size)
236
+ throw corrupt(`Blosc chunk holds ${bytes} bytes, expected ${size}`);
237
+ if (flags & 4)
238
+ throw new LoaderError(F, 'unsupported', `${subject} uses Blosc bit shuffle`);
239
+ if (stored) {
240
+ if (chunk.length < 16 + size)
241
+ throw corrupt('Blosc copy cut short');
242
+ return chunk.slice(16, 16 + size);
243
+ }
244
+ if (flags >> 5 !== 1)
245
+ throw new LoaderError(F, 'unsupported', `${subject} uses a Blosc codec other than LZ4`);
246
+ if (blockSize === 0 || typeSize === 0)
247
+ throw corrupt('Blosc block or type size is zero');
248
+ const blocks = Math.ceil(size / blockSize), output = new Uint8Array(size), scratch = new Uint8Array(Math.min(blockSize, size));
249
+ if (16 + blocks * 4 > chunk.length)
250
+ throw corrupt('Blosc offsets cut short');
251
+ for (let block = 0; block < blocks; block++) {
252
+ const length = Math.min(blockSize, size - block * blockSize),
253
+ // A short last block is never split.
254
+ splits = !single && length === blockSize ? typeSize : 1, part = length / splits, target = shuffled ? scratch : output.subarray(block * blockSize);
255
+ let at = view.getUint32(16 + block * 4, true);
256
+ for (let split = 0; split < splits; split++) {
257
+ if (at + 4 > chunk.length)
258
+ throw corrupt('Blosc block cut short');
259
+ const packed = view.getUint32(at, true);
260
+ at += 4;
261
+ if (at + packed > chunk.length)
262
+ throw corrupt('Blosc block cut short');
263
+ const slice = target.subarray(split * part, (split + 1) * part);
264
+ if (packed === part)
265
+ slice.set(chunk.subarray(at, at + packed));
266
+ else
267
+ lz4(chunk.subarray(at, at + packed), slice, subject);
268
+ at += packed;
269
+ }
270
+ if (!shuffled)
271
+ continue;
272
+ const whole = length - (length % typeSize), count = whole / typeSize, out = output.subarray(block * blockSize);
273
+ for (let i = 0; i < count; i++)
274
+ for (let byte = 0; byte < typeSize; byte++)
275
+ out[i * typeSize + byte] = scratch[byte * count + i];
276
+ out.set(scratch.subarray(whole, length), whole);
277
+ }
278
+ return output;
279
+ }
280
+ /** Reads the values of one node into `target` at `start`. */
281
+ class ValueReader {
282
+ constructor(reader, codec, half, compression, background, signal) {
283
+ this.reader = reader;
284
+ this.codec = codec;
285
+ this.half = half;
286
+ this.compression = compression;
287
+ this.background = background;
288
+ this.signal = signal;
289
+ }
290
+ /** One full-precision value, as stored for backgrounds, tiles and inactive values. */
291
+ value(what) {
292
+ const { reader, codec } = this, out = [];
293
+ reader.need(codec.size * codec.components, what);
294
+ for (let i = 0; i < codec.components; i++, reader.pos += codec.size)
295
+ out.push(codec.read(reader.view, reader.pos));
296
+ return out;
297
+ }
298
+ /** `count` values through the grid's compression: the bytes, as stored, of half or full precision. */
299
+ async raw(count) {
300
+ const { reader, codec, compression, half } = this, size = count * codec.components * (half ? 2 : codec.size);
301
+ // The half-value stream omits empty arrays; full-precision streams retain their compressed-size prefix.
302
+ if (size === 0 && half)
303
+ return { view: new DataView(new ArrayBuffer(0)), base: 0 };
304
+ let bytes;
305
+ if (compression & (COMPRESS_BLOSC | COMPRESS_ZIP)) {
306
+ const packed = reader.i64('compressed size');
307
+ if (packed <= 0) {
308
+ if (-packed !== size)
309
+ throw new LoaderError(F, 'range', `stored block of ${-packed} bytes, expected ${size}`);
310
+ bytes = reader.take(size, 'stored block');
311
+ }
312
+ else if (compression & COMPRESS_BLOSC)
313
+ bytes = blosc(reader.take(packed, 'Blosc chunk'), size, 'a node');
314
+ else
315
+ bytes = await inflate(reader.take(packed, 'zlib block'), size, 'a node', this.signal, 'deflate', F);
316
+ }
317
+ else
318
+ bytes = reader.take(size, 'values');
319
+ return { view: new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength), base: 0 };
320
+ }
321
+ /** Reads `length` values, active ones per `mask`, restoring the inactive ones the file left out. */
322
+ async node(target, start, length, mask) {
323
+ const { reader, codec, half, compression, background } = this, { components } = codec, kind = reader.i8('value kind');
324
+ if (kind < NO_MASK_OR_INACTIVE || kind > NO_MASK_ALL_VALUES)
325
+ throw new LoaderError(F, 'syntax', `unknown value kind ${kind}`);
326
+ let inactive0 = kind === NO_MASK_OR_INACTIVE ? background : background.map((v) => -v), inactive1 = background;
327
+ if (kind === NO_MASK_ONE_INACTIVE || kind === MASK_ONE_INACTIVE || kind === MASK_TWO_INACTIVE) {
328
+ inactive0 = this.value('inactive value');
329
+ if (kind === MASK_TWO_INACTIVE)
330
+ inactive1 = this.value('inactive value');
331
+ }
332
+ let selection = null;
333
+ if (kind === MASK_NO_INACTIVE || kind === MASK_ONE_INACTIVE || kind === MASK_TWO_INACTIVE)
334
+ selection = reader.take(length >> 3, 'selection mask');
335
+ const packed = (compression & COMPRESS_ACTIVE_MASK) !== 0 && kind !== NO_MASK_ALL_VALUES, count = packed ? countBits(mask) : length, { view } = await this.raw(count), step = half ? 2 : codec.size, read = half ? (at) => halfToNumber(view.getUint16(at, true)) : (at) => codec.read(view, at);
336
+ let from = 0;
337
+ for (let i = 0; i < length; i++) {
338
+ const at = start + i * components;
339
+ if (!packed || bit(mask, i)) {
340
+ for (let c = 0; c < components; c++, from += step)
341
+ target[at + c] = read(from);
342
+ continue;
343
+ }
344
+ const fill = selection && bit(selection, i) ? inactive1 : inactive0;
345
+ for (let c = 0; c < components; c++)
346
+ target[at + c] = fill[c];
347
+ }
348
+ }
349
+ }
350
+ /** Reads a tree's topology, then its leaf values, into a grid's leaves and tiles. */
351
+ class TreeReader {
352
+ constructor(values, dims, signal) {
353
+ this.values = values;
354
+ this.dims = dims;
355
+ this.signal = signal;
356
+ this.leaves = [];
357
+ this.tiles = [];
358
+ // Log2 of a node's edge in voxels, for the root's children downward.
359
+ this.spans = dims.map((_, level) => dims.slice(level).reduce((sum, dim) => sum + dim, 0));
360
+ }
361
+ tile(origin, size, value, active) {
362
+ const { background } = this.values;
363
+ if (!active && value.every((v, i) => Object.is(v, background[i])))
364
+ return;
365
+ this.tiles.push({
366
+ origin,
367
+ size,
368
+ value: value.length === 1 ? value[0] : value,
369
+ active,
370
+ });
371
+ }
372
+ async topology() {
373
+ const { values } = this, { reader } = values, tiles = reader.u32('root tile count'), children = reader.u32('root child count'), span = 2 ** this.spans[0];
374
+ reader.need(tiles * 12 + children * 12, 'root node');
375
+ for (let i = 0; i < tiles; i++) {
376
+ const origin = reader.coord('root tile'), value = values.value('root tile'), active = reader.u8('root tile') !== 0;
377
+ this.tile(origin, span, value, active);
378
+ }
379
+ for (let i = 0; i < children; i++)
380
+ await this.child(reader.coord('root child'), 0);
381
+ }
382
+ async child(origin, level) {
383
+ const { reader } = this.values, dim = this.dims[level], total = 2 ** (dim * 3);
384
+ if (level === this.dims.length - 1) {
385
+ this.leaves.push({ origin, mask: reader.take(total >> 3, 'leaf mask').slice() });
386
+ return;
387
+ }
388
+ throwIfAborted(this.signal, F);
389
+ const children = reader.take(total >> 3, 'child mask'), active = reader.take(total >> 3, 'tile mask'), { codec, background } = this.values, tileValues = codec.make(total * codec.components);
390
+ await this.values.node(tileValues, 0, total, active);
391
+ const shift = this.spans[level + 1], size = 2 ** shift, low = 2 ** dim - 1, at = (i) => [
392
+ origin[0] + (i >> (2 * dim)) * size,
393
+ origin[1] + ((i >> dim) & low) * size,
394
+ origin[2] + (i & low) * size,
395
+ ];
396
+ for (let i = 0; i < total; i++) {
397
+ if (bit(children, i))
398
+ continue;
399
+ const value = background.map((_, c) => tileValues[i * codec.components + c]);
400
+ this.tile(at(i), size, value, bit(active, i));
401
+ }
402
+ for (let i = 0; i < total; i++)
403
+ if (bit(children, i))
404
+ await this.child(at(i), level + 1);
405
+ }
406
+ /** The values of every leaf, in the order the topology listed them. */
407
+ async buffers(pool, perLeaf) {
408
+ const { values } = this, { reader } = values, length = 2 ** (this.dims[this.dims.length - 1] * 3);
409
+ for (const [index, leaf] of this.leaves.entries()) {
410
+ if (index % 256 === 0)
411
+ throwIfAborted(this.signal, F);
412
+ reader.take(length >> 3, 'leaf mask');
413
+ await values.node(pool, index * perLeaf, length, leaf.mask);
414
+ }
415
+ }
416
+ }
417
+ const key = (x, y, z) => `${x},${y},${z}`;
418
+ function makeGrid(fields, codec, dims) {
419
+ const { leaves, tiles, matrix, components, background } = fields, leafDim = dims[dims.length - 1], leafEdge = 2 ** leafDim, tileSizes = [...new Set(tiles.map((tile) => tile.size))].sort((a, b) => a - b);
420
+ let leafAt, tileAt;
421
+ const lookup = (x, y, z) => {
422
+ leafAt ??= new Map(leaves.map((leaf) => [key(...leaf.origin), leaf]));
423
+ tileAt ??= new Map(tiles.map((tile) => [`${tile.size}:${key(...tile.origin)}`, tile]));
424
+ const down = (v, size) => Math.floor(v / size) * size, leaf = leafAt.get(key(down(x, leafEdge), down(y, leafEdge), down(z, leafEdge)));
425
+ if (leaf)
426
+ return leaf;
427
+ for (const size of tileSizes) {
428
+ const tile = tileAt.get(`${size}:${key(down(x, size), down(y, size), down(z, size))}`);
429
+ if (tile)
430
+ return tile;
431
+ }
432
+ return undefined;
433
+ };
434
+ const leafIndex = (leaf, x, y, z) => (((x - leaf.origin[0]) << leafDim) | (y - leaf.origin[1])) * leafEdge + (z - leaf.origin[2]);
435
+ let box = null, activeVoxels = 0;
436
+ const grow = (lo, hi) => {
437
+ box ??= [lo[0], lo[1], lo[2], hi[0], hi[1], hi[2]];
438
+ for (let axis = 0; axis < 3; axis++) {
439
+ box[axis] = Math.min(box[axis], lo[axis]);
440
+ box[axis + 3] = Math.max(box[axis + 3], hi[axis]);
441
+ }
442
+ };
443
+ for (const tile of tiles)
444
+ if (tile.active) {
445
+ activeVoxels += tile.size ** 3;
446
+ grow(tile.origin, tile.origin.map((v) => v + tile.size - 1));
447
+ }
448
+ for (const leaf of leaves) {
449
+ const { origin, mask } = leaf;
450
+ for (let i = 0; i < leafEdge ** 3; i++) {
451
+ if (!bit(mask, i))
452
+ continue;
453
+ activeVoxels++;
454
+ const voxel = [
455
+ origin[0] + (i >> (2 * leafDim)),
456
+ origin[1] + ((i >> leafDim) & (leafEdge - 1)),
457
+ origin[2] + (i & (leafEdge - 1)),
458
+ ];
459
+ grow(voxel, voxel);
460
+ }
461
+ }
462
+ const toWorld = (x, y, z) => [
463
+ matrix[0] * x + matrix[4] * y + matrix[8] * z + matrix[12],
464
+ matrix[1] * x + matrix[5] * y + matrix[9] * z + matrix[13],
465
+ matrix[2] * x + matrix[6] * y + matrix[10] * z + matrix[14],
466
+ ];
467
+ const column = (at) => Math.hypot(matrix[at], matrix[at + 1], matrix[at + 2]);
468
+ return {
469
+ ...fields,
470
+ voxelSize: [column(0), column(4), column(8)],
471
+ box,
472
+ activeVoxels,
473
+ at(x, y, z) {
474
+ const found = lookup(x, y, z);
475
+ if (!found)
476
+ return background;
477
+ if ('size' in found)
478
+ return found.value;
479
+ const at = leafIndex(found, x, y, z) * components;
480
+ return components === 1 ? found.values[at] : [found.values[at], found.values[at + 1], found.values[at + 2]];
481
+ },
482
+ isActive(x, y, z) {
483
+ const found = lookup(x, y, z);
484
+ if (!found)
485
+ return false;
486
+ return 'size' in found ? found.active : bit(found.mask, leafIndex(found, x, y, z));
487
+ },
488
+ dense(options = {}) {
489
+ const area = options.box ?? box;
490
+ if (!area)
491
+ throw new LoaderError(F, 'range', `grid ${fields.name} has no active voxels; pass a box`);
492
+ if (area.length !== 6 || !area.every(Number.isInteger) || [0, 1, 2].some((a) => area[a] > area[a + 3]))
493
+ throw new LoaderError(F, 'range', 'box must be six integers, each minimum no more than its maximum');
494
+ const dimsOut = [area[3] - area[0] + 1, area[4] - area[1] + 1, area[5] - area[2] + 1], total = dimsOut[0] * dimsOut[1] * dimsOut[2] * components;
495
+ if (total > (options.maxValues ?? 536_870_912))
496
+ throw new LoaderError(F, 'limit', `a box of ${total} values is over the limit`);
497
+ const data = codec.make(total), fill = typeof background === 'number' ? [background] : background;
498
+ for (let i = 0; i < total; i += components)
499
+ for (let c = 0; c < components; c++)
500
+ data[i + c] = fill[c];
501
+ const put = (x, y, z, read) => {
502
+ const at = ((z - area[2]) * dimsOut[1] + (y - area[1])) * dimsOut[0] + (x - area[0]);
503
+ for (let c = 0; c < components; c++)
504
+ data[at * components + c] = read(c);
505
+ };
506
+ // Leaves after tiles, though the two never overlap in a valid file.
507
+ for (const tile of tiles) {
508
+ const value = typeof tile.value === 'number' ? [tile.value] : tile.value, read = (c) => value[c];
509
+ for (let z = Math.max(area[2], tile.origin[2]); z <= Math.min(area[5], tile.origin[2] + tile.size - 1); z++)
510
+ for (let y = Math.max(area[1], tile.origin[1]); y <= Math.min(area[4], tile.origin[1] + tile.size - 1); y++)
511
+ for (let x = Math.max(area[0], tile.origin[0]); x <= Math.min(area[3], tile.origin[0] + tile.size - 1); x++)
512
+ put(x, y, z, read);
513
+ }
514
+ for (const leaf of leaves) {
515
+ const [ox, oy, oz] = leaf.origin;
516
+ for (let z = Math.max(area[2], oz); z <= Math.min(area[5], oz + leafEdge - 1); z++)
517
+ for (let y = Math.max(area[1], oy); y <= Math.min(area[4], oy + leafEdge - 1); y++)
518
+ for (let x = Math.max(area[0], ox); x <= Math.min(area[3], ox + leafEdge - 1); x++) {
519
+ const at = leafIndex(leaf, x, y, z) * components;
520
+ put(x, y, z, (c) => leaf.values[at + c]);
521
+ }
522
+ }
523
+ const bounds = [
524
+ Number.POSITIVE_INFINITY,
525
+ Number.NEGATIVE_INFINITY,
526
+ Number.POSITIVE_INFINITY,
527
+ Number.NEGATIVE_INFINITY,
528
+ Number.POSITIVE_INFINITY,
529
+ Number.NEGATIVE_INFINITY,
530
+ ];
531
+ for (let corner = 0; corner < 8; corner++) {
532
+ const point = toWorld(area[corner & 1 ? 3 : 0], area[corner & 2 ? 4 : 1], area[corner & 4 ? 5 : 2]);
533
+ for (let axis = 0; axis < 3; axis++) {
534
+ bounds[axis * 2] = Math.min(bounds[axis * 2], point[axis]);
535
+ bounds[axis * 2 + 1] = Math.max(bounds[axis * 2 + 1], point[axis]);
536
+ }
537
+ }
538
+ return { data, dims: dimsOut, components, box: [...area], bounds };
539
+ },
540
+ };
541
+ }
542
+ /** The tree type's value type, node sizes and whether it stored halves, or the reason it cannot be read. */
543
+ function treeType(type) {
544
+ const match = /^Tree_([a-z0-9]+)((?:_\d+)+)(_HalfFloat)?$/.exec(type);
545
+ if (!match)
546
+ return `tree type ${type} is not one this reader knows`;
547
+ const codec = CODECS[match[1]];
548
+ if (!codec)
549
+ return `value type ${match[1]} is not decoded`;
550
+ const dims = match[2].slice(1).split('_').map(Number);
551
+ if (dims.length < 2 || dims.some((dim) => dim < 1 || dim > 10))
552
+ return `node sizes of ${type} are out of range`;
553
+ if (match[3] && !HALF_TYPES.has(match[1]))
554
+ return `half storage of ${match[1]} is not a float type`;
555
+ return { codec, dims, half: match[3] !== undefined };
556
+ }
557
+ /**
558
+ * Reads an OpenVDB `.vdb` file into sparse grids: leaves and tiles as stored, with `at()` for lookups and `dense()` for
559
+ * the arrays a volume renderer takes. Reads file versions 222 and later (OpenVDB 2.0 onward).
560
+ *
561
+ * @throws LoaderError code `header` when the bytes are not a VDB file, `unsupported` for an older version or a Blosc
562
+ * codec other than LZ4, `truncated`, `range` or `syntax` for a damaged file, `limit` over `maxValues`, `zip` for bad
563
+ * compressed data, `aborted` when `signal` fires.
564
+ */
565
+ export async function parseVDB(input, options = {}) {
566
+ const { signal } = options;
567
+ throwIfAborted(signal, F);
568
+ const bytes = toBytes(input, F), reader = new Reader(bytes), maxValues = options.maxValues ?? 536_870_912;
569
+ if (!LITTLE)
570
+ throw new LoaderError(F, 'unsupported', 'a big-endian host is not supported');
571
+ if (bytes.length < 8 || latin1(bytes, 0, 8) !== ' BDV\0\0\0\0')
572
+ throw new LoaderError(F, 'header', 'not an OpenVDB file');
573
+ reader.pos = 8;
574
+ const version = reader.u32('version');
575
+ if (version < MIN_VERSION)
576
+ throw new LoaderError(F, 'unsupported', `file version ${version} is before ${MIN_VERSION}`);
577
+ const library = [reader.u32('library version'), reader.u32('library version')], offsets = reader.u8('grid offset flag') !== 0, uuid = latin1(reader.take(36, 'uuid')), meta = readMeta(reader);
578
+ if (!offsets)
579
+ throw new LoaderError(F, 'unsupported', 'a stream with no grid offsets is not supported');
580
+ const gridCount = reader.u32('grid count');
581
+ reader.need(gridCount * 36, 'grid descriptors');
582
+ const descriptors = [];
583
+ for (let i = 0; i < gridCount; i++) {
584
+ const name = reader.text('grid name').split('\x1e')[0], type = reader.text('grid type'), parent = reader.text('grid parent').split('\x1e')[0], gridAt = reader.i64('grid offset'), blockAt = reader.i64('block offset');
585
+ // A grid's bytes follow its descriptor, and the next descriptor follows them.
586
+ reader.seek(reader.i64('end offset'), `grid ${name}`);
587
+ descriptors.push({ name, type, parent, gridAt, blockAt });
588
+ }
589
+ const grids = [], skipped = [], wanted = options.grids && new Set(options.grids);
590
+ let used = 0;
591
+ for (const { name, type, parent, gridAt, blockAt } of descriptors) {
592
+ throwIfAborted(signal, F);
593
+ const skip = (reason) => void skipped.push({ name, type, reason });
594
+ if (wanted && !wanted.has(name)) {
595
+ skip('not in options.grids');
596
+ continue;
597
+ }
598
+ const tree = treeType(type);
599
+ if (typeof tree === 'string') {
600
+ skip(tree);
601
+ continue;
602
+ }
603
+ reader.seek(gridAt, `grid ${name}`);
604
+ const { codec, dims, half } = tree, compression = reader.u32('compression'), gridMeta = readMeta(reader), matrix = readTransform(reader);
605
+ if (!matrix) {
606
+ skip('its transform has no matrix');
607
+ continue;
608
+ }
609
+ const gridClass = typeof gridMeta.class === 'string' ? gridMeta.class : 'unknown';
610
+ if (parent) {
611
+ const source = grids.find((grid) => grid.name === parent);
612
+ if (!source) {
613
+ skip(`its parent grid ${parent} was not read`);
614
+ continue;
615
+ }
616
+ const { leaves, tiles, background } = source;
617
+ grids.push(makeGrid({
618
+ name,
619
+ type,
620
+ valueType: codec.valueType,
621
+ half,
622
+ components: codec.components,
623
+ gridClass,
624
+ background,
625
+ matrix,
626
+ leaves,
627
+ tiles,
628
+ meta: gridMeta,
629
+ }, codec, dims));
630
+ continue;
631
+ }
632
+ if (reader.i32('buffer count') !== 1)
633
+ throw new LoaderError(F, 'unsupported', `grid ${name} holds several buffers`);
634
+ const probe = new ValueReader(reader, codec, half, compression, [], signal), background = probe.value('background'), values = new ValueReader(reader, codec, half, compression, background, signal), walker = new TreeReader(values, dims, signal);
635
+ await walker.topology();
636
+ const perLeaf = 2 ** (dims[dims.length - 1] * 3) * codec.components;
637
+ used += walker.leaves.length * perLeaf;
638
+ if (used > maxValues)
639
+ throw new LoaderError(F, 'limit', `${used} leaf values are over the limit of ${maxValues}`);
640
+ const pool = codec.make(walker.leaves.length * perLeaf);
641
+ reader.seek(blockAt, `grid ${name} values`);
642
+ await walker.buffers(pool, perLeaf);
643
+ const leaves = walker.leaves.map(({ origin, mask }, index) => ({
644
+ origin,
645
+ mask,
646
+ values: pool.subarray(index * perLeaf, (index + 1) * perLeaf),
647
+ }));
648
+ grids.push(makeGrid({
649
+ name,
650
+ type,
651
+ valueType: codec.valueType,
652
+ half,
653
+ components: codec.components,
654
+ gridClass,
655
+ background: background.length === 1 ? background[0] : background,
656
+ matrix,
657
+ leaves,
658
+ tiles: walker.tiles,
659
+ meta: gridMeta,
660
+ }, codec, dims));
661
+ }
662
+ return { version, library, uuid, meta, grids, skipped };
663
+ }