@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
@@ -0,0 +1,284 @@
1
+ // zlib (RFC 1950) and DEFLATE (RFC 1951) decoder, written from the two RFCs: EXR ZIP and ZIPS chunks
2
+ // (@margoengine/environment) and PNG image data (@margoengine/decoders/png), whose decompressed size is known up front
3
+ // and fills one buffer of exactly that size. With a `{ limit }` option the size need not be stored: the buffer grows
4
+ // up to that limit. inflateRaw serves containers that must know where a raw stream ends (gzip members and deflated
5
+ // DICOM data sets in @margoengine/sciviz/formats). Every input read, output write and back reference is bounds checked, and damaged data throws
6
+ // MargoError 'failed'.
7
+ import { fault } from './errors.js';
8
+
9
+ const damaged = (problem) => fault('failed', `Compressed data ${problem}; the file is damaged, export it again`);
10
+
11
+ // Every `groupShift`-sized group of symbols adds one extra bit (after the first two groups, which have none), and each
12
+ // base is the previous base plus the span the previous symbol's extra bits cover. That rule rebuilds both RFC 1951
13
+ // section 3.2.5 tables: lengths 3, 4, ... 227 for symbols 257..284 and distances 1, 2, ... 24577 for 0..29. Length
14
+ // symbol 285 breaks the pattern (exactly 258, no extra bits), passed as `lastBase`.
15
+ function symbolRanges(count, groupShift, first, lastBase) {
16
+ const base = new Uint16Array(count),
17
+ extra = new Uint8Array(count);
18
+ for (let i = 0, value = first; i < count; i++) {
19
+ extra[i] = Math.max(0, (i >> groupShift) - 1);
20
+ base[i] = value;
21
+ value += 1 << extra[i];
22
+ }
23
+ if (lastBase !== undefined) {
24
+ base[count - 1] = lastBase;
25
+ extra[count - 1] = 0;
26
+ }
27
+ return [base, extra];
28
+ }
29
+ const LENGTHS = /* @__PURE__ */ symbolRanges(29, 2, 3, 258);
30
+ const DISTANCES = /* @__PURE__ */ symbolRanges(30, 1, 1);
31
+ const LENGTH_258 = 28;
32
+ const END_OF_BLOCK = 256;
33
+ // RFC 1951 section 3.2.7: order in which the code length alphabet's own code lengths are stored.
34
+ const CODE_LENGTH_ORDER = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
35
+ const MAX_BITS = 15;
36
+
37
+ /**
38
+ * The decoding table for the canonical code RFC 1951 section 3.2.2 assigns to these code lengths: one entry per
39
+ * pattern of the next `width` stream bits (first stream bit lowest), `symbol << 4 | code length`, 0 for patterns no
40
+ * code starts with.
41
+ */
42
+ function huffmanTable(lengths) {
43
+ const perLength = new Uint16Array(MAX_BITS + 1);
44
+ let width = 1;
45
+ for (const length of lengths)
46
+ if (length) {
47
+ perLength[length]++;
48
+ width = Math.max(width, length);
49
+ }
50
+ // Kraft sum: more codes of some length than the shorter ones leave room for cannot be decoded. An incomplete set is
51
+ // accepted (RFC 1951 allows a lone distance code); its unused patterns stay 0 and throw only if the data uses them.
52
+ for (let length = 1, room = 1; length <= MAX_BITS; length++) {
53
+ room = room * 2 - perLength[length];
54
+ if (room < 0) throw damaged('has an over-subscribed Huffman code');
55
+ }
56
+ const nextCode = new Uint16Array(MAX_BITS + 1);
57
+ for (let length = 1, code = 0; length <= MAX_BITS; length++) {
58
+ code = (code + (length > 1 ? perLength[length - 1] : 0)) << 1;
59
+ nextCode[length] = code;
60
+ }
61
+ const entries = new Int32Array(1 << width);
62
+ for (let symbol = 0; symbol < lengths.length; symbol++) {
63
+ const length = lengths[symbol];
64
+ if (!length) continue;
65
+ // Codes are defined most significant bit first but arrive first bit lowest, so the table is indexed reversed.
66
+ const code = nextCode[length]++;
67
+ let reversed = 0;
68
+ for (let bit = 0; bit < length; bit++) reversed |= ((code >> bit) & 1) << (length - 1 - bit);
69
+ const entry = (symbol << 4) | length;
70
+ for (let index = reversed; index < entries.length; index += 1 << length) entries[index] = entry;
71
+ }
72
+ return [entries, width];
73
+ }
74
+
75
+ // The fixed literal/length and distance codes of block type 1 (RFC 1951 section 3.2.6), built on first use.
76
+ let fixedTables;
77
+
78
+ /** One zlib stream being inflated; fields and steps are private so the minifier shortens their names. */
79
+ class Inflater {
80
+ #input;
81
+ #limit;
82
+ #limitHint;
83
+ #output;
84
+ #position;
85
+ #held = 0;
86
+ #count = 0;
87
+ #written = 0;
88
+ constructor(input, size, start = 2) {
89
+ this.#input = input;
90
+ this.#position = start;
91
+ this.#limit = size.limit;
92
+ this.#limitHint = size.limitHint ?? 'raise limit to allow more decompressed bytes';
93
+ // A growable buffer starts no larger than its limit, so a limit under 1 KiB holds as well as a larger one.
94
+ this.#output = new Uint8Array(this.#limit === undefined ? size : Math.min(1024, this.#limit));
95
+ }
96
+ // The stream is read least significant bit first, holding up to 32 bits ahead.
97
+ #refill() {
98
+ while (this.#count <= 24 && this.#position < this.#input.length) {
99
+ this.#held |= this.#input[this.#position++] << this.#count;
100
+ this.#count += 8;
101
+ }
102
+ }
103
+ /** The next `n` bits (0..16) as an unsigned number. */
104
+ #bits(n) {
105
+ if (this.#count < n) {
106
+ this.#refill();
107
+ if (this.#count < n) throw damaged('ends early while reading DEFLATE bits');
108
+ }
109
+ const value = this.#held & ((1 << n) - 1);
110
+ this.#held >>>= n;
111
+ this.#count -= n;
112
+ return value;
113
+ }
114
+ /** The next symbol of a Huffman code. */
115
+ #symbol(table) {
116
+ if (this.#count < table[1]) this.#refill();
117
+ const entry = table[0][this.#held & (table[0].length - 1)],
118
+ length = entry & 15;
119
+ if (entry === 0) throw damaged('uses a Huffman code its block does not define');
120
+ if (length > this.#count) throw damaged('ends early while reading a DEFLATE Huffman code');
121
+ this.#held >>>= length;
122
+ this.#count -= length;
123
+ return entry >> 4;
124
+ }
125
+ /** Drops the bits left in the current byte and returns the position of the next whole byte. */
126
+ #align() {
127
+ this.#position -= this.#count >> 3;
128
+ this.#held = this.#count = 0;
129
+ return this.#position;
130
+ }
131
+ /** Room in the output for `need` bytes: a growable buffer doubles, up to the limit. */
132
+ #room(need) {
133
+ const output = this.#output,
134
+ limit = this.#limit;
135
+ if (need <= output.length) return output;
136
+ if (limit === undefined)
137
+ throw damaged(`inflates to at least ${need} bytes, above the expected ${output.length} bytes`);
138
+ if (need > limit)
139
+ throw fault(
140
+ 'failed',
141
+ `Compressed data needs at least ${need} bytes, above the limit ${limit} bytes; ${this.#limitHint}`,
142
+ );
143
+ const bigger = new Uint8Array(Math.min(limit, Math.max(output.length * 2, need)));
144
+ bigger.set(output);
145
+ return (this.#output = bigger);
146
+ }
147
+ /** One Huffman-coded block. */
148
+ #block(literals, distances) {
149
+ let output = this.#output,
150
+ written = this.#written;
151
+ for (;;) {
152
+ const next = this.#symbol(literals);
153
+ if (next < END_OF_BLOCK) {
154
+ if (written >= output.length) output = this.#room(written + 1);
155
+ output[written++] = next;
156
+ continue;
157
+ }
158
+ if (next === END_OF_BLOCK) return (this.#written = written);
159
+ const lengthSymbol = next - 257;
160
+ if (lengthSymbol > LENGTH_258) throw damaged(`uses the reserved length symbol ${next}`);
161
+ const length = LENGTHS[0][lengthSymbol] + this.#bits(LENGTHS[1][lengthSymbol]),
162
+ distanceSymbol = this.#symbol(distances);
163
+ if (distanceSymbol >= 30) throw damaged(`uses the reserved distance symbol ${distanceSymbol}`);
164
+ const distance = DISTANCES[0][distanceSymbol] + this.#bits(DISTANCES[1][distanceSymbol]);
165
+ if (distance > written)
166
+ throw damaged(`refers back ${distance} bytes with only ${written} bytes written, before the start of its data`);
167
+ if (written + length > output.length) output = this.#room(written + length);
168
+ // Front to back, one byte at a time: a distance shorter than the length repeats the bytes just written.
169
+ for (let from = written - distance, stop = written + length; written < stop; ) output[written++] = output[from++];
170
+ }
171
+ }
172
+ /** Code lengths of a dynamic block's two codes (RFC 1951 section 3.2.7), themselves Huffman coded. */
173
+ #dynamic() {
174
+ const literalCount = this.#bits(5) + 257,
175
+ distanceCount = this.#bits(5) + 1,
176
+ codeLengthCount = this.#bits(4) + 4;
177
+ if (literalCount > 286) throw damaged(`declares ${literalCount} literal/length codes (at most 286)`);
178
+ const codeLengthLengths = new Uint8Array(19);
179
+ for (let i = 0; i < codeLengthCount; i++) codeLengthLengths[CODE_LENGTH_ORDER[i]] = this.#bits(3);
180
+ const codeLengthCode = huffmanTable(codeLengthLengths);
181
+ // One run of lengths covers both codes; repeats may cross from the literal lengths into the distance lengths.
182
+ const lengths = new Uint8Array(literalCount + distanceCount);
183
+ for (let filled = 0; filled < lengths.length; ) {
184
+ const next = this.#symbol(codeLengthCode);
185
+ if (next < 16) {
186
+ lengths[filled++] = next;
187
+ continue;
188
+ }
189
+ let value = 0,
190
+ repeat;
191
+ if (next === 16) {
192
+ if (filled === 0) throw damaged('repeats a code length before the first one');
193
+ value = lengths[filled - 1];
194
+ repeat = 3 + this.#bits(2);
195
+ } else repeat = next === 17 ? 3 + this.#bits(3) : 11 + this.#bits(7);
196
+ if (repeat > lengths.length - filled) throw damaged('repeats code lengths past the declared count');
197
+ lengths.fill(value, filled, filled + repeat);
198
+ filled += repeat;
199
+ }
200
+ if (!lengths[END_OF_BLOCK]) throw damaged('has a block without an end-of-block code');
201
+ this.#block(huffmanTable(lengths.subarray(0, literalCount)), huffmanTable(lengths.subarray(literalCount)));
202
+ }
203
+ /**
204
+ * Decodes every block and checks the trailer; see {@link inflateZlib}. A `raw` stream (no zlib header or trailer)
205
+ * returns its bytes and the position after its final block instead; see {@link inflateRaw}.
206
+ */
207
+ run(size, checkAdler, raw) {
208
+ const input = this.#input;
209
+ if (!raw) {
210
+ if (input.length < 2) throw damaged('is too short for a zlib header');
211
+ const method = input[0],
212
+ flags = input[1];
213
+ // RFC 1950: compression method 8 (deflate), window of at most 32 KiB, header check, no preset dictionary.
214
+ if ((method & 15) !== 8) throw damaged(`declares zlib compression method ${method & 15}, not DEFLATE (8)`);
215
+ if (method >> 4 > 7) throw damaged(`declares zlib window size ${method >> 4}, above the maximum 7`);
216
+ if (((method << 8) | flags) % 31 !== 0) throw damaged('fails its zlib header check');
217
+ if (flags & 0x20)
218
+ throw fault(
219
+ 'unsupported',
220
+ 'Compressed data needs a preset dictionary; recompress it without a preset dictionary',
221
+ );
222
+ }
223
+ let final = 0;
224
+ do {
225
+ final = this.#bits(1);
226
+ const type = this.#bits(2);
227
+ if (type === 0) {
228
+ // Stored block: byte aligned LEN, NLEN (its one's complement), then LEN raw bytes.
229
+ let at = this.#align();
230
+ if (input.length - at < 4) throw damaged('ends early in its stored block length header');
231
+ const length = input[at] | (input[at + 1] << 8),
232
+ check = input[at + 2] | (input[at + 3] << 8);
233
+ if ((length ^ 0xffff) !== check) throw damaged('has a stored block whose length check fails');
234
+ at += 4;
235
+ if (length > input.length - at) throw damaged('ends early in its stored block data');
236
+ this.#room(this.#written + length).set(input.subarray(at, at + length), this.#written);
237
+ this.#written += length;
238
+ this.#position = at + length;
239
+ } else if (type === 1) {
240
+ fixedTables ??= [
241
+ huffmanTable(new Uint8Array(288).fill(8, 0, 144).fill(9, 144, 256).fill(7, 256, 280).fill(8, 280, 288)),
242
+ huffmanTable(new Uint8Array(32).fill(5)),
243
+ ];
244
+ this.#block(fixedTables[0], fixedTables[1]);
245
+ } else if (type === 2) this.#dynamic();
246
+ else throw damaged('uses the reserved block type 3');
247
+ } while (!final);
248
+ if (this.#limit === undefined && this.#written !== size)
249
+ throw damaged(`inflates to ${this.#written} bytes, not the expected ${size} bytes`);
250
+ const output = this.#output.subarray(0, this.#written);
251
+ const at = this.#align();
252
+ if (raw) return { output, end: at };
253
+ // RFC 1950 trailer: the Adler-32 of the decompressed bytes, big-endian, after the last block's final byte.
254
+ if (input.length - at < 4) throw damaged('ends before its Adler-32 checksum');
255
+ const stored = ((input[at] << 24) | (input[at + 1] << 16) | (input[at + 2] << 8) | input[at + 3]) >>> 0;
256
+ if (checkAdler && adler32(output) !== stored) throw damaged('fails its Adler-32 checksum');
257
+ return output;
258
+ }
259
+ }
260
+
261
+ /** Inflates zlib `input`; see inflate.d.ts. */
262
+ export const inflateZlib = (input, size, checkAdler = true) => new Inflater(input, size).run(size, checkAdler);
263
+
264
+ /** Inflates the raw DEFLATE stream at `start` of `input`; see inflate.d.ts. */
265
+ export const inflateRaw = (input, start, size) => new Inflater(input, size, start).run(size, false, true);
266
+
267
+ /**
268
+ * Adler-32 (RFC 1950 section 8.2): two sums modulo 65521. 5552 bytes is the longest run after which the second sum
269
+ * still fits in 32 unsigned bits, so the sums stay 32-bit integers (twice as fast as doubles) and are reduced per run.
270
+ */
271
+ function adler32(bytes) {
272
+ let a = 1,
273
+ b = 0;
274
+ for (let start = 0; start < bytes.length; start += 5552) {
275
+ const end = Math.min(bytes.length, start + 5552);
276
+ for (let i = start; i < end; i++) {
277
+ a = (a + bytes[i]) | 0;
278
+ b = (b + a) | 0;
279
+ }
280
+ a %= 65521;
281
+ b = (b >>> 0) % 65521;
282
+ }
283
+ return ((b << 16) | a) >>> 0;
284
+ }
@@ -0,0 +1,26 @@
1
+ // Area-weighted vertex normal accumulation for indexed triangles: the loaders' computeVertexNormals and the exporters'
2
+ // generated normals.
3
+
4
+ /** Adds each triangle's unnormalized face normal (length twice its area) to its three vertices in `out` (xyz each). */
5
+ export function accumulateNormals(positions, indices, out) {
6
+ for (let t = 0; t + 2 < indices.length; t += 3) {
7
+ const a = indices[t] * 3,
8
+ b = indices[t + 1] * 3,
9
+ c = indices[t + 2] * 3;
10
+ const ux = positions[b] - positions[a],
11
+ uy = positions[b + 1] - positions[a + 1],
12
+ uz = positions[b + 2] - positions[a + 2];
13
+ const vx = positions[c] - positions[a],
14
+ vy = positions[c + 1] - positions[a + 1],
15
+ vz = positions[c + 2] - positions[a + 2];
16
+ const nx = uy * vz - uz * vy,
17
+ ny = uz * vx - ux * vz,
18
+ nz = ux * vy - uy * vx;
19
+ for (const v of [a, b, c]) {
20
+ out[v] += nx;
21
+ out[v + 1] += ny;
22
+ out[v + 2] += nz;
23
+ }
24
+ }
25
+ return out;
26
+ }
@@ -0,0 +1,56 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ let serial = 0;
5
+ const unique = (engine, base) => {
6
+ let name = base + serial++;
7
+ while (engine.plugins?.has(name)) name += ':';
8
+ return name;
9
+ };
10
+
11
+ /**
12
+ * The scene set up or drawn right now (the default scene otherwise), kept for work that finishes after an await. Call it
13
+ * before the first await of a loader; `run(work)` then calls `work` with that scene active, so the meshes and plugins it
14
+ * makes belong to it and not to whatever scene is active when the load finishes.
15
+ */
16
+ export function captureScene(engine) {
17
+ let scene;
18
+ if (typeof engine?.sceneOf === 'function') {
19
+ // The active scene's plugins all map back to it; with none, a probe plugin learns it from the engine.
20
+ for (const plugin of engine.plugins?.values() ?? []) if ((scene = engine.sceneOf(plugin))) break;
21
+ if (!scene) {
22
+ const probe = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),
23
+ name: unique(engine, 'scene-scope:'),
24
+ setup() {
25
+ scene = engine.sceneOf(probe);
26
+ },
27
+ };
28
+ engine.use(probe);
29
+ engine.removePlugin(probe.name);
30
+ }
31
+ }
32
+ return sceneScope(engine, scene);
33
+ }
34
+
35
+ /**
36
+ * A scope over `scene` itself, for work that belongs to a scene known from an object (the scene a plugin or model is in)
37
+ * and not from the scene active now. With no scene, `run` just calls the work.
38
+ */
39
+ export function sceneScope(engine, scene) {
40
+ return {
41
+ scene,
42
+ run(work) {
43
+ if (!scene) return work();
44
+ let result;
45
+ const scope = {coreRequirement:/*@__PURE__*/__margoCoreRequirement("1.0.0",import.meta.url),
46
+ name: unique(engine, 'scene-scope:'),
47
+ setup() {
48
+ result = work();
49
+ },
50
+ };
51
+ scene.use(scope);
52
+ scene.removePlugin(scope.name);
53
+ return result;
54
+ },
55
+ };
56
+ }
@@ -0,0 +1,45 @@
1
+ // Data after the end of a compressed stream (bug 39, measured 2026-10-28). The Compression Streams standard makes
2
+ // DecompressionStream reject it, and current browsers and Node 24 do; Node 22.12 accepts it for 'deflate' and
3
+ // 'deflate-raw' (and a trailing zero byte after 'gzip'), and Node 22.22 for 'deflate-raw', so a parser on those
4
+ // runtimes would take a malformed file that the
5
+ // same parser rejects everywhere else. hasTrailingData tells, for bytes that already decoded, whether they hold data
6
+ // after the stream's end: on a runtime that rejects trailing data (probed once per format) the decode itself already
7
+ // failed, so it answers false; on one that accepts it, it decodes the bytes without their last byte, which succeeds
8
+ // exactly when the stream ended before that byte. The fbx readers use it.
9
+
10
+ /** The smallest valid stream of each format (an empty payload). */
11
+ const EMPTY = {
12
+ deflate: [0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01],
13
+ 'deflate-raw': [0x03, 0x00],
14
+ gzip: [0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0],
15
+ };
16
+ const lenient = new Map();
17
+
18
+ // Read with a stream reader, never through a Response: Firefox reports a page error when a Response's body stream
19
+ // fails, even though arrayBuffer()'s rejection is caught, and the probe below fails a stream on purpose (KB5076).
20
+ async function decodes(bytes, format) {
21
+ const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream(format)).getReader();
22
+ try {
23
+ while (!(await reader.read()).done);
24
+ return true;
25
+ } catch {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ /** Whether this runtime's DecompressionStream accepts data after the end of a `format` stream (cached). */
31
+ export function acceptsTrailingData(format) {
32
+ if (!(format in EMPTY)) throw new TypeError(`format must be deflate, deflate-raw or gzip (got ${format})`);
33
+ let probe = lenient.get(format);
34
+ if (!probe) {
35
+ probe = decodes(new Uint8Array([...EMPTY[format], 0]), format);
36
+ lenient.set(format, probe);
37
+ }
38
+ return probe;
39
+ }
40
+
41
+ /** For `bytes` that decoded as `format`: whether data follows the end of the compressed stream. */
42
+ export async function hasTrailingData(bytes, format) {
43
+ if (!(await acceptsTrailingData(format)) || bytes.byteLength === 0) return false;
44
+ return decodes(bytes.subarray(0, bytes.byteLength - 1), format);
45
+ }
package/dist/stl.d.ts ADDED
@@ -0,0 +1,64 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** Options of parseSTL: the shared size limits (ParseLimits), welding and an abort signal. */
4
+ export interface STLOptions extends ParseLimits {
5
+ /**
6
+ * `false` (default) keeps every triangle's three corners as written, like the file: three vertices per triangle,
7
+ * one flat normal per triangle repeated on its corners, and `indices` counting 0, 1, 2, ... `true` merges corners
8
+ * with identical positions (and identical facet colors) into one vertex, which cuts the vertex count to about a
9
+ * sixth for a closed surface and replaces the flat normals with smooth, area-weighted ones.
10
+ */
11
+ weld?: boolean;
12
+ /** Aborts the parse; it then throws a `LoaderError` with code `'aborted'`. Checked every 16,384 triangles. */
13
+ signal?: AbortSignal;
14
+ /**
15
+ * Which binary colour extension the 16-bit facet attributes use. `'auto'` (default): Materialise Magics when the
16
+ * 80-byte header holds `COLOR=`, otherwise VisCAM / SolidView. `'viscam'`: bit 15 set marks a facet colour, red in
17
+ * bits 10 to 14 and blue in 0 to 4. `'materialise'`: bit 15 clear marks a facet colour, red in bits 0 to 4 and blue
18
+ * in 10 to 14, and a set bit 15 takes the part colour of the header; use it for a Magics file without `COLOR=`.
19
+ */
20
+ colorVariant?: 'auto' | 'viscam' | 'materialise';
21
+ }
22
+ /** An RGBA colour from a Materialise header, each channel 0 to 1 (the file's bytes divided by 255). */
23
+ export type STLColor = [r: number, g: number, b: number, a: number];
24
+ /** The part colour and material a Materialise Magics header (`COLOR=` and `,MATERIAL=`) declares. */
25
+ export interface STLMaterialise {
26
+ /** `COLOR=`: the whole part's colour, used by facets whose bit 15 is set when no material is given. */
27
+ color?: STLColor;
28
+ /** `,MATERIAL=` diffuse colour; preferred over `color` for the part colour, as Magics does. */
29
+ diffuse?: STLColor;
30
+ /** `,MATERIAL=` specular highlight colour. */
31
+ specular?: STLColor;
32
+ /** `,MATERIAL=` ambient colour. */
33
+ ambient?: STLColor;
34
+ }
35
+ /** What parseSTL returns: the mesh and, for a Materialise colour file, its header colours. */
36
+ export interface STLGeometry extends LoadedGeometry {
37
+ /** Set when the file was read as Materialise Magics colour (`colorVariant`), with the header's part colours. */
38
+ materialise?: STLMaterialise;
39
+ }
40
+ /**
41
+ * Parses a binary or ASCII STL file into plain typed arrays, the way a basic STL loader does: no GPU objects, no
42
+ * parts, no normal smoothing. The flavor is detected from the data: a file whose length is exactly
43
+ * `84 + 50 * triangles` is binary even when it starts with `solid`; otherwise text starting with `solid` and holding
44
+ * facets is ASCII.
45
+ *
46
+ * - `positions`: three vertices per triangle, in file order (Float32).
47
+ * - `normals`: the facet normal from the file repeated on the triangle's corners; a facet whose stored normal is zero
48
+ * or not finite (many writers leave it zero) gets the flat normal computed from its corners.
49
+ * - `colors`: for binary files using a colour extension, as sRGB 0 to 1. VisCAM / SolidView (bit 15 of the 16-bit
50
+ * attribute set marks a facet colour; facets without one get 0.8 gray) or Materialise Magics, read when the header
51
+ * holds `COLOR=` or `colorVariant` says so (bit 15 clear marks a facet colour; the others take the header's part
52
+ * colour, the `,MATERIAL=` diffuse before `COLOR=`, or 0.8 gray). ASCII files and uncolored binary files have none.
53
+ * - `materialise`: the header's `COLOR=` and `,MATERIAL=` colours (RGBA 0 to 1) of a Materialise file.
54
+ * - `indices`: 0, 1, 2, ... (or the weld's indices with `weld: true`).
55
+ *
56
+ * @throws LoaderError with code `'header'` (too short to be STL), `'truncated'` (binary data shorter than its
57
+ * triangle count, or an ASCII file cut inside a facet), `'syntax'` (a malformed ASCII facet or number), `'limit'`
58
+ * (past `maxTriangles` or `maxVertices`; raise them) or `'aborted'` (the `signal` fired); `'range'` for a bad limit or
59
+ * `colorVariant`.
60
+ * @example
61
+ * const mesh = parseSTL(await (await fetch('/part.stl')).arrayBuffer());
62
+ * mesh.positions.length / 9; // triangles
63
+ */
64
+ export declare function parseSTL(input: BinaryInput, options?: STLOptions): STLGeometry;