@margoengine/loaders 0.0.0-stage → 0.1.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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1198 -3
- package/dist/3dm.d.ts +161 -0
- package/dist/3dm.js +289 -0
- package/dist/3ds.d.ts +124 -0
- package/dist/3ds.js +392 -0
- package/dist/acclaim.d.ts +90 -0
- package/dist/acclaim.js +312 -0
- package/dist/amf.d.ts +45 -0
- package/dist/amf.js +256 -0
- package/dist/babylon.d.ts +197 -0
- package/dist/babylon.js +701 -0
- package/dist/common.d.ts +7 -0
- package/dist/common.js +6 -0
- package/dist/dae-animation.d.ts +66 -0
- package/dist/dae-animation.js +266 -0
- package/dist/dae-common.d.ts +95 -0
- package/dist/dae-common.js +226 -0
- package/dist/dae-controllers.d.ts +57 -0
- package/dist/dae-controllers.js +164 -0
- package/dist/dae-pose.d.ts +131 -0
- package/dist/dae-pose.js +381 -0
- package/dist/dae-scene.d.ts +203 -0
- package/dist/dae-scene.js +279 -0
- package/dist/dae.d.ts +161 -0
- package/dist/dae.js +633 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- package/dist/dxf.d.ts +81 -0
- package/dist/dxf.js +774 -0
- package/dist/engine.d.ts +36 -0
- package/dist/engine.js +117 -0
- package/dist/font-opentype.d.ts +14 -0
- package/dist/font-opentype.js +33 -0
- package/dist/font-woff.d.ts +23 -0
- package/dist/font-woff.js +293 -0
- package/dist/font.d.ts +41 -0
- package/dist/font.js +26 -0
- package/dist/gcode.d.ts +55 -0
- package/dist/gcode.js +278 -0
- package/dist/geo-model.d.ts +84 -0
- package/dist/geo-model.js +220 -0
- package/dist/geo-mvt.d.ts +15 -0
- package/dist/geo-mvt.js +302 -0
- package/dist/geo-shp.d.ts +15 -0
- package/dist/geo-shp.js +234 -0
- package/dist/geo-xml.d.ts +6 -0
- package/dist/geo-xml.js +165 -0
- package/dist/geo.d.ts +8 -0
- package/dist/geo.js +59 -0
- package/dist/geometry.d.ts +60 -0
- package/dist/geometry.js +273 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +28 -0
- package/dist/kmz.d.ts +78 -0
- package/dist/kmz.js +173 -0
- package/dist/las.d.ts +92 -0
- package/dist/las.js +110 -0
- package/dist/ldraw.d.ts +118 -0
- package/dist/ldraw.js +474 -0
- package/dist/load.d.ts +72 -0
- package/dist/load.js +205 -0
- package/dist/lottie.d.ts +154 -0
- package/dist/lottie.js +893 -0
- package/dist/lwo.d.ts +81 -0
- package/dist/lwo.js +454 -0
- package/dist/lzf.d.ts +13 -0
- package/dist/lzf.js +56 -0
- package/dist/materialx.d.ts +120 -0
- package/dist/materialx.js +563 -0
- package/dist/md2.d.ts +52 -0
- package/dist/md2.js +112 -0
- package/dist/mmcif.d.ts +14 -0
- package/dist/mmcif.js +246 -0
- package/dist/mmd.d.ts +244 -0
- package/dist/mmd.js +958 -0
- package/dist/mocap.d.ts +71 -0
- package/dist/mocap.js +178 -0
- package/dist/molecule-common.d.ts +4 -0
- package/dist/molecule-common.js +54 -0
- package/dist/mtl.d.ts +120 -0
- package/dist/mtl.js +469 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +63 -0
- package/dist/nrrd.js +743 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +143 -0
- package/dist/obj.js +456 -0
- package/dist/off.d.ts +10 -0
- package/dist/off.js +155 -0
- package/dist/outline-font.d.ts +87 -0
- package/dist/outline-font.js +110 -0
- package/dist/outline.d.ts +20 -0
- package/dist/outline.js +215 -0
- package/dist/pcd.d.ts +34 -0
- package/dist/pcd.js +258 -0
- package/dist/pdb.d.ts +67 -0
- package/dist/pdb.js +126 -0
- package/dist/ply.d.ts +35 -0
- package/dist/ply.js +392 -0
- package/dist/polygon.d.ts +9 -0
- package/dist/polygon.js +49 -0
- package/dist/prwm.d.ts +24 -0
- package/dist/prwm.js +114 -0
- package/dist/render.d.ts +27 -0
- package/dist/render.js +153 -0
- package/dist/sfnt-cff.d.ts +37 -0
- package/dist/sfnt-cff.js +749 -0
- package/dist/sfnt-layout.d.ts +24 -0
- package/dist/sfnt-layout.js +266 -0
- package/dist/sfnt-reader.d.ts +28 -0
- package/dist/sfnt-reader.js +87 -0
- package/dist/sfnt-variation.d.ts +40 -0
- package/dist/sfnt-variation.js +318 -0
- package/dist/shared/asset-url.js +82 -0
- package/dist/shared/crc32.d.ts +2 -0
- package/dist/shared/crc32.js +47 -0
- package/dist/shared/errors.js +36 -0
- package/dist/shared/inflate.js +284 -0
- package/dist/shared/normals.js +26 -0
- package/dist/shared/scene-scope.js +56 -0
- package/dist/shared/trailing-data.js +42 -0
- package/dist/stl.d.ts +64 -0
- package/dist/stl.js +309 -0
- package/dist/svg.d.ts +90 -0
- package/dist/svg.js +1007 -0
- package/dist/tds.d.ts +2 -0
- package/dist/tds.js +2 -0
- package/dist/textures.d.ts +42 -0
- package/dist/textures.js +53 -0
- package/dist/threemf-lattice.d.ts +139 -0
- package/dist/threemf-lattice.js +514 -0
- package/dist/threemf-materials.d.ts +75 -0
- package/dist/threemf-materials.js +314 -0
- package/dist/threemf-mesh.d.ts +60 -0
- package/dist/threemf-mesh.js +201 -0
- package/dist/threemf.d.ts +101 -0
- package/dist/threemf.js +415 -0
- package/dist/tilt.d.ts +62 -0
- package/dist/tilt.js +186 -0
- package/dist/tmx.d.ts +151 -0
- package/dist/tmx.js +394 -0
- package/dist/ttf.d.ts +78 -0
- package/dist/ttf.js +568 -0
- package/dist/types.d.ts +90 -0
- package/dist/types.js +35 -0
- package/dist/usd.d.ts +2 -0
- package/dist/usd.js +2 -0
- package/dist/usd.worker.d.ts +1 -0
- package/dist/usdz.d.ts +50 -0
- package/dist/usdz.js +646 -0
- package/dist/util.d.ts +75 -0
- package/dist/util.js +241 -0
- package/dist/vdb.d.ts +111 -0
- package/dist/vdb.js +663 -0
- package/dist/vrml.d.ts +53 -0
- package/dist/vrml.js +532 -0
- package/dist/vtk-cells.d.ts +29 -0
- package/dist/vtk-cells.js +211 -0
- package/dist/vtk-legacy.d.ts +57 -0
- package/dist/vtk-legacy.js +439 -0
- package/dist/vtk-reader.d.ts +19 -0
- package/dist/vtk-reader.js +134 -0
- package/dist/vtk-xml.d.ts +96 -0
- package/dist/vtk-xml.js +578 -0
- package/dist/vtk.d.ts +13 -0
- package/dist/vtk.js +234 -0
- package/dist/woff-glyf.d.ts +17 -0
- package/dist/woff-glyf.js +215 -0
- package/dist/worker.d.ts +10 -0
- package/dist/worker.js +93 -0
- package/dist/workers/usd.js +3 -0
- package/dist/xfile.d.ts +99 -0
- package/dist/xfile.js +706 -0
- package/dist/xml.d.ts +107 -0
- package/dist/xml.js +843 -0
- package/dist/xyz.d.ts +16 -0
- package/dist/xyz.js +110 -0
- package/dist/zip.d.ts +38 -0
- package/dist/zip.js +150 -0
- package/package.json +246 -6
package/dist/ldraw.js
ADDED
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
// LDraw models: line types 0 to 5, colour codes, sub-file references, MPD packs and BFC winding.
|
|
2
|
+
import { LoaderError } from './types.js';
|
|
3
|
+
import { floats, limits, resolvePath, throwIfAborted, toText, uints } from './util.js';
|
|
4
|
+
const F = 'LDraw';
|
|
5
|
+
/** Metres per LDraw unit. */
|
|
6
|
+
const LDU = 0.0004;
|
|
7
|
+
const MAIN = 16;
|
|
8
|
+
const EDGE = 24;
|
|
9
|
+
const DEFAULT_PATHS = ['', 'parts/', 'p/', 'models/', 'unofficial/parts/', 'unofficial/p/'];
|
|
10
|
+
const CONFIG_FILE = 'ldconfig.ldr';
|
|
11
|
+
const IDENTITY = [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0];
|
|
12
|
+
const key = (name) => name.trim().replaceAll('\\', '/').toLowerCase();
|
|
13
|
+
function hex(value) {
|
|
14
|
+
const match = /^(?:#|0x)([0-9a-f]{6})$/i.exec(value);
|
|
15
|
+
if (!match)
|
|
16
|
+
return undefined;
|
|
17
|
+
const number = Number.parseInt(match[1], 16);
|
|
18
|
+
return [(number >> 16) / 255, ((number >> 8) & 255) / 255, (number & 255) / 255];
|
|
19
|
+
}
|
|
20
|
+
const classic = (code, name, value, edge = '#333333') => ({
|
|
21
|
+
code,
|
|
22
|
+
name,
|
|
23
|
+
color: [...hex(value), 1],
|
|
24
|
+
edge: hex(edge),
|
|
25
|
+
});
|
|
26
|
+
function classicPalette() {
|
|
27
|
+
const list = [
|
|
28
|
+
classic(0, 'Black', '#05131D', '#595959'),
|
|
29
|
+
classic(1, 'Blue', '#0055BF'),
|
|
30
|
+
classic(2, 'Green', '#257A3E'),
|
|
31
|
+
classic(3, 'Dark_Turquoise', '#00838F'),
|
|
32
|
+
classic(4, 'Red', '#C91A09'),
|
|
33
|
+
classic(5, 'Dark_Pink', '#C870A0'),
|
|
34
|
+
classic(6, 'Brown', '#583927'),
|
|
35
|
+
classic(7, 'Light_Grey', '#9BA19D'),
|
|
36
|
+
classic(8, 'Dark_Grey', '#6D6E5C'),
|
|
37
|
+
classic(9, 'Light_Blue', '#B4D2E3'),
|
|
38
|
+
classic(10, 'Bright_Green', '#4B9F4A'),
|
|
39
|
+
classic(11, 'Light_Turquoise', '#55A5AF'),
|
|
40
|
+
classic(12, 'Salmon', '#F2705E'),
|
|
41
|
+
classic(13, 'Pink', '#FC97AC'),
|
|
42
|
+
classic(14, 'Yellow', '#F2CD37'),
|
|
43
|
+
classic(15, 'White', '#FFFFFF'),
|
|
44
|
+
];
|
|
45
|
+
return new Map(list.map((entry) => [entry.code, entry]));
|
|
46
|
+
}
|
|
47
|
+
/** Reads a `0 !COLOUR` line into the palette; a line without a code or value is a syntax error. */
|
|
48
|
+
function readColour(words, palette) {
|
|
49
|
+
const after = (word) => {
|
|
50
|
+
const at = words.indexOf(word);
|
|
51
|
+
return at < 0 ? undefined : words[at + 1];
|
|
52
|
+
};
|
|
53
|
+
const code = Number(after('CODE')), value = hex(after('VALUE') ?? ''), edgeWord = after('EDGE') ?? '', alpha = after('ALPHA');
|
|
54
|
+
if (!Number.isSafeInteger(code) || !value)
|
|
55
|
+
throw new LoaderError(F, 'syntax', `bad colour line for "${words[2]}"`);
|
|
56
|
+
const edge = hex(edgeWord) ?? palette.get(Number(edgeWord))?.color.slice(0, 3);
|
|
57
|
+
palette.set(code, {
|
|
58
|
+
code,
|
|
59
|
+
name: words[2],
|
|
60
|
+
color: [...value, alpha === undefined ? 1 : Number(alpha) / 255],
|
|
61
|
+
edge: edge ?? [0.2, 0.2, 0.2],
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function numbers(words, from, count, line, name) {
|
|
65
|
+
if (words.length < from + count)
|
|
66
|
+
throw new LoaderError(F, 'syntax', `line ${line} of ${name.slice(0, 64)} has too few fields`);
|
|
67
|
+
const out = new Array(count);
|
|
68
|
+
for (let i = 0; i < count; i++) {
|
|
69
|
+
const value = Number(words[from + i]);
|
|
70
|
+
if (!Number.isFinite(value))
|
|
71
|
+
throw new LoaderError(F, 'syntax', `line ${line} of ${name.slice(0, 64)} has a bad number`);
|
|
72
|
+
out[i] = value;
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
function colourCode(word, line, name) {
|
|
77
|
+
const value = Number(word);
|
|
78
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
79
|
+
throw new LoaderError(F, 'syntax', `line ${line} of ${name.slice(0, 64)} has a bad colour`);
|
|
80
|
+
return value;
|
|
81
|
+
}
|
|
82
|
+
/** Splits a file into its MPD sub-files; the first is the main one, under `name`. */
|
|
83
|
+
function readFile(text, name, parts, palette, warn) {
|
|
84
|
+
let current, currentName = name, main, certified = false, clockwise = false, clip = true, invertNext = false, skipping = false, lineNumber = 0;
|
|
85
|
+
const open = (fileName) => {
|
|
86
|
+
currentName = fileName;
|
|
87
|
+
current = { commands: [] };
|
|
88
|
+
certified = clockwise = invertNext = skipping = false;
|
|
89
|
+
clip = true;
|
|
90
|
+
const id = key(fileName);
|
|
91
|
+
if (!parts.has(id))
|
|
92
|
+
parts.set(id, current);
|
|
93
|
+
main ??= id;
|
|
94
|
+
};
|
|
95
|
+
for (let start = 0; start < text.length;) {
|
|
96
|
+
let end = text.indexOf('\n', start);
|
|
97
|
+
if (end < 0)
|
|
98
|
+
end = text.length;
|
|
99
|
+
const line = text.slice(start, end).trim();
|
|
100
|
+
start = end + 1;
|
|
101
|
+
lineNumber++;
|
|
102
|
+
if (!line)
|
|
103
|
+
continue;
|
|
104
|
+
const words = line.split(/\s+/);
|
|
105
|
+
if (words[0] === '0') {
|
|
106
|
+
const word = words[1] ?? '';
|
|
107
|
+
if (word === 'FILE') {
|
|
108
|
+
open(words.slice(2).join(' '));
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (word === 'NOFILE') {
|
|
112
|
+
skipping = true;
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
if (word === '!DATA') {
|
|
116
|
+
skipping = true;
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (skipping)
|
|
120
|
+
continue;
|
|
121
|
+
if (!current)
|
|
122
|
+
open(name);
|
|
123
|
+
if (word === '!COLOUR')
|
|
124
|
+
readColour(words, palette);
|
|
125
|
+
else if (word === '!LDRAW_ORG') {
|
|
126
|
+
if (/^(Unofficial_)?(Part|Shortcut)$/i.test(words[2] ?? ''))
|
|
127
|
+
current.part = true;
|
|
128
|
+
}
|
|
129
|
+
else if (word === '!TEXMAP' || word === '!:')
|
|
130
|
+
warn('texture maps are not read');
|
|
131
|
+
else if (word === 'BFC') {
|
|
132
|
+
for (const option of words.slice(2))
|
|
133
|
+
if (option === 'CERTIFY')
|
|
134
|
+
certified = true;
|
|
135
|
+
else if (option === 'NOCERTIFY')
|
|
136
|
+
certified = false;
|
|
137
|
+
else if (option === 'CW')
|
|
138
|
+
clockwise = true;
|
|
139
|
+
else if (option === 'CCW')
|
|
140
|
+
clockwise = false;
|
|
141
|
+
else if (option === 'CLIP')
|
|
142
|
+
clip = true;
|
|
143
|
+
else if (option === 'NOCLIP')
|
|
144
|
+
clip = false;
|
|
145
|
+
else if (option === 'INVERTNEXT')
|
|
146
|
+
invertNext = true;
|
|
147
|
+
}
|
|
148
|
+
else if (current.title === undefined && word && !word.startsWith('!') && !/^(Name|Author):?$/.test(word))
|
|
149
|
+
current.title = words.slice(1).join(' ');
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (skipping)
|
|
153
|
+
continue;
|
|
154
|
+
if (!current)
|
|
155
|
+
open(name);
|
|
156
|
+
const type = Number(words[0]);
|
|
157
|
+
if (type === 1) {
|
|
158
|
+
const [x, y, z, a, b, c, d, e, f, g, h, i] = numbers(words, 2, 12, lineNumber, currentName), file = words.slice(14).join(' ');
|
|
159
|
+
if (!file)
|
|
160
|
+
throw new LoaderError(F, 'syntax', `line ${lineNumber} of ${currentName.slice(0, 64)} names no file`);
|
|
161
|
+
current.commands.push({
|
|
162
|
+
kind: 1,
|
|
163
|
+
code: colourCode(words[1], lineNumber, currentName),
|
|
164
|
+
matrix: [a, b, c, d, e, f, g, h, i, x, y, z],
|
|
165
|
+
file,
|
|
166
|
+
invert: invertNext,
|
|
167
|
+
clip,
|
|
168
|
+
certified,
|
|
169
|
+
});
|
|
170
|
+
invertNext = false;
|
|
171
|
+
}
|
|
172
|
+
else if (type === 2 || type === 3 || type === 4 || type === 5) {
|
|
173
|
+
const count = type === 2 ? 6 : type === 3 ? 9 : 12;
|
|
174
|
+
current.commands.push({
|
|
175
|
+
kind: type,
|
|
176
|
+
code: colourCode(words[1], lineNumber, currentName),
|
|
177
|
+
points: numbers(words, 2, count, lineNumber, currentName),
|
|
178
|
+
reverse: clockwise,
|
|
179
|
+
both: !certified || !clip,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
else
|
|
183
|
+
warn(`line type ${words[0].slice(0, 16)} is not part of LDraw`);
|
|
184
|
+
}
|
|
185
|
+
if (!main)
|
|
186
|
+
open(name);
|
|
187
|
+
return main;
|
|
188
|
+
}
|
|
189
|
+
const determinant = (m) => m[0] * (m[4] * m[8] - m[5] * m[7]) - m[1] * (m[3] * m[8] - m[5] * m[6]) + m[2] * (m[3] * m[7] - m[4] * m[6]);
|
|
190
|
+
/** Applies `child` first, then `parent`. Rows are `a b c`, `d e f`, `g h i`, then the translation. */
|
|
191
|
+
function multiply(parent, child) {
|
|
192
|
+
const out = new Array(12);
|
|
193
|
+
for (let r = 0; r < 3; r++) {
|
|
194
|
+
for (let c = 0; c < 3; c++)
|
|
195
|
+
out[r * 3 + c] = parent[r * 3] * child[c] + parent[r * 3 + 1] * child[3 + c] + parent[r * 3 + 2] * child[6 + c];
|
|
196
|
+
out[9 + r] =
|
|
197
|
+
parent[r * 3] * child[9] + parent[r * 3 + 1] * child[10] + parent[r * 3 + 2] * child[11] + parent[9 + r];
|
|
198
|
+
}
|
|
199
|
+
return out;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* A `resolve` for {@link parseLDraw} that reads parts over HTTP from an LDraw library folder you host. The library is
|
|
203
|
+
* the "Complete" download of ldraw.org, unzipped: `LDConfig.ldr`, `parts/` and `p/` directly below `base`.
|
|
204
|
+
* A status other than 2xx rejects, so `parseLDraw` tries the next search path and lists a part found nowhere in `missing`.
|
|
205
|
+
*
|
|
206
|
+
* @param base The library folder, absolute or relative to the page.
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* import { parseLDraw, resolveFromURL } from '@margoengine/loaders/ldraw';
|
|
210
|
+
*
|
|
211
|
+
* const text = await (await fetch('/models/car.ldr')).text();
|
|
212
|
+
* const model = await parseLDraw(text, { resolve: resolveFromURL('/ldraw/') });
|
|
213
|
+
* console.log(model.missing);
|
|
214
|
+
* ```
|
|
215
|
+
*/
|
|
216
|
+
export function resolveFromURL(base, { fetch: get = globalThis.fetch, signal } = {}) {
|
|
217
|
+
const folder = new URL(String(base).replace(/\/*$/, '/'), globalThis.location?.href);
|
|
218
|
+
return async (path) => {
|
|
219
|
+
const response = await get(new URL(path, folder), { signal });
|
|
220
|
+
if (!response.ok)
|
|
221
|
+
throw new LoaderError(F, 'unsupported', `${path}: HTTP ${response.status}`, { status: response.status });
|
|
222
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Reads an LDraw model (`.ldr`, `.dat` or a multi-part `.mpd`). Sub-file references load through `resolve` and are
|
|
227
|
+
* expanded into one mesh, with a group per colour. Colour 16 takes the parent's colour and 24 its edge colour, `0x2RRGGBB`
|
|
228
|
+
* is a direct colour, and `0 !COLOUR` lines and `LDConfig.ldr` fill the palette. Certified BFC files keep their winding;
|
|
229
|
+
* polygons of an uncertified file are written on both sides, so they draw with back faces culled.
|
|
230
|
+
*
|
|
231
|
+
* @param input The file's bytes or text.
|
|
232
|
+
* @param options The resolver, search paths, units, limits and an AbortSignal.
|
|
233
|
+
* @returns The mesh, its edge and conditional lines, the colours used and any references that could not be read.
|
|
234
|
+
* @throws LoaderError with code `syntax`, `limit`, `range` or `aborted`. A missing part is listed in `missing`, not thrown.
|
|
235
|
+
*
|
|
236
|
+
* @example
|
|
237
|
+
* ```ts
|
|
238
|
+
* import { parseLDraw } from '@margoengine/loaders/ldraw';
|
|
239
|
+
*
|
|
240
|
+
* const model = await parseLDraw('0 BFC CERTIFY CCW\n3 4 0 0 0 10 0 0 0 0 10\n2 24 0 0 0 10 0 0\n');
|
|
241
|
+
* console.log(model.groups[0].color, model.lines.length, model.missing);
|
|
242
|
+
* ```
|
|
243
|
+
*/
|
|
244
|
+
export async function parseLDraw(input, options = {}) {
|
|
245
|
+
const text = toText(input, F), { maxVertices, maxTriangles } = limits(options, F), { resolve, signal } = options, maxDepth = options.maxDepth ?? 64, maxInstances = options.maxInstances ?? 4_000_000, searchPaths = options.searchPaths ?? DEFAULT_PATHS, edges = options.edges ?? true, instanced = options.instanced ?? false, mainColor = options.color ?? 7;
|
|
246
|
+
throwIfAborted(signal, F);
|
|
247
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth < 0)
|
|
248
|
+
throw new LoaderError(F, 'range', 'maxDepth must be a non-negative integer');
|
|
249
|
+
if (!Number.isSafeInteger(maxInstances) || maxInstances < 0)
|
|
250
|
+
throw new LoaderError(F, 'range', 'maxInstances must be a non-negative integer');
|
|
251
|
+
if (options.units !== undefined && options.units !== 'meters' && options.units !== 'file')
|
|
252
|
+
throw new LoaderError(F, 'range', 'units must be "meters" or "file"');
|
|
253
|
+
// These two mean "the colour above", and the model's main colour has nothing above it.
|
|
254
|
+
if (mainColor === MAIN || mainColor === EDGE)
|
|
255
|
+
throw new LoaderError(F, 'range', 'color must be a real colour code');
|
|
256
|
+
const warnings = new Set(), warn = (message) => void warnings.add(message), palette = classicPalette(), parts = new Map(), missing = new Set();
|
|
257
|
+
const read = async (path) => {
|
|
258
|
+
if (!resolve)
|
|
259
|
+
return undefined;
|
|
260
|
+
let content;
|
|
261
|
+
try {
|
|
262
|
+
content = await resolve(path);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
throwIfAborted(signal, F);
|
|
266
|
+
return undefined; // Not at this path: the next search path may have it, and `missing` reports it if none does.
|
|
267
|
+
}
|
|
268
|
+
return toText(content, F);
|
|
269
|
+
};
|
|
270
|
+
if (options.config !== undefined)
|
|
271
|
+
readFile(options.config, CONFIG_FILE, new Map(), palette, warn);
|
|
272
|
+
else if (resolve)
|
|
273
|
+
for (const folder of ['', 'ldraw/']) {
|
|
274
|
+
const config = (await read(`${folder}LDConfig.ldr`)) ?? undefined;
|
|
275
|
+
if (config !== undefined) {
|
|
276
|
+
readFile(config, CONFIG_FILE, new Map(), palette, warn);
|
|
277
|
+
break;
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const main = readFile(text, 'model.ldr', parts, palette, warn);
|
|
281
|
+
// Load every reference, one level of the tree at a time, so the walk below is synchronous.
|
|
282
|
+
const tried = new Set();
|
|
283
|
+
for (let wanted = references(parts, tried); wanted.length; wanted = references(parts, tried)) {
|
|
284
|
+
throwIfAborted(signal, F);
|
|
285
|
+
for (const file of wanted) {
|
|
286
|
+
tried.add(key(file));
|
|
287
|
+
let found, folder = '';
|
|
288
|
+
for (folder of searchPaths) {
|
|
289
|
+
found = await read(resolvePath('', `${folder}${key(file)}`));
|
|
290
|
+
throwIfAborted(signal, F);
|
|
291
|
+
if (found !== undefined)
|
|
292
|
+
break;
|
|
293
|
+
}
|
|
294
|
+
if (found === undefined)
|
|
295
|
+
missing.add(key(file));
|
|
296
|
+
else {
|
|
297
|
+
readFile(found, file, parts, palette, warn);
|
|
298
|
+
const loaded = parts.get(key(file));
|
|
299
|
+
if (loaded && /(^|\/)parts\/$/.test(folder) && !key(file).startsWith('s/'))
|
|
300
|
+
loaded.part = true;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/** Where geometry goes: the main mesh, or a placed part's own. */
|
|
305
|
+
const sink = () => ({
|
|
306
|
+
positions: floats(),
|
|
307
|
+
lines: floats(),
|
|
308
|
+
lineColors: floats(),
|
|
309
|
+
conditional: floats(),
|
|
310
|
+
buckets: new Map(),
|
|
311
|
+
triangles: 0,
|
|
312
|
+
}), whole = sink(), placed = new Map(), used = new Map(), visiting = new Set();
|
|
313
|
+
let out = whole;
|
|
314
|
+
let triangles = 0, instances = 0;
|
|
315
|
+
const color = (code, parent) => {
|
|
316
|
+
if (code === MAIN)
|
|
317
|
+
return color(parent, mainColor);
|
|
318
|
+
if (code === EDGE) {
|
|
319
|
+
const owner = color(parent, mainColor);
|
|
320
|
+
return { code: EDGE, name: 'Edge', color: [...owner.edge, 1], edge: owner.edge };
|
|
321
|
+
}
|
|
322
|
+
const known = palette.get(code);
|
|
323
|
+
if (known)
|
|
324
|
+
return known;
|
|
325
|
+
if (code >= 0x2000000 && code <= 0x2ffffff) {
|
|
326
|
+
const direct = {
|
|
327
|
+
code,
|
|
328
|
+
name: `#${(code & 0xffffff).toString(16).padStart(6, '0')}`,
|
|
329
|
+
color: [((code >> 16) & 255) / 255, ((code >> 8) & 255) / 255, (code & 255) / 255, 1],
|
|
330
|
+
edge: [0.2, 0.2, 0.2],
|
|
331
|
+
};
|
|
332
|
+
palette.set(code, direct);
|
|
333
|
+
return direct;
|
|
334
|
+
}
|
|
335
|
+
warn(`colour ${code} is not in the palette; it draws as light grey`);
|
|
336
|
+
return palette.get(7);
|
|
337
|
+
};
|
|
338
|
+
const point = (to, m, p, at) => to.push3(m[0] * p[at] + m[1] * p[at + 1] + m[2] * p[at + 2] + m[9], m[3] * p[at] + m[4] * p[at + 1] + m[5] * p[at + 2] + m[10], m[6] * p[at] + m[7] * p[at + 1] + m[8] * p[at + 2] + m[11]);
|
|
339
|
+
const polygon = (shape, m, inverted, parent, cull) => {
|
|
340
|
+
const entry = color(shape.code, parent), corners = shape.kind === 3 ? 3 : 4, base = out.positions.length / 3, both = shape.both || !cull, count = (corners - 2) * (both ? 2 : 1);
|
|
341
|
+
if (base + corners > maxVertices)
|
|
342
|
+
throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
|
|
343
|
+
out.triangles += count;
|
|
344
|
+
triangles += count;
|
|
345
|
+
if (triangles > maxTriangles)
|
|
346
|
+
throw new LoaderError(F, 'limit', `triangle count exceeds the limit of ${maxTriangles}`);
|
|
347
|
+
for (let c = 0; c < corners; c++)
|
|
348
|
+
point(out.positions, m, shape.points, c * 3);
|
|
349
|
+
let bucket = out.buckets.get(entry.code);
|
|
350
|
+
if (!bucket)
|
|
351
|
+
out.buckets.set(entry.code, (bucket = uints()));
|
|
352
|
+
used.set(entry.code, entry);
|
|
353
|
+
const flip = shape.reverse !== inverted;
|
|
354
|
+
for (let c = 1; c + 1 < corners; c++) {
|
|
355
|
+
if (both || !flip)
|
|
356
|
+
bucket.push3(base, base + c, base + c + 1);
|
|
357
|
+
if (both || flip)
|
|
358
|
+
bucket.push3(base, base + c + 1, base + c);
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
const line = (shape, m, parent) => {
|
|
362
|
+
const { lines, lineColors, conditional } = out;
|
|
363
|
+
if (shape.kind === 5) {
|
|
364
|
+
if ((conditional.length + lines.length) / 3 + 4 > maxVertices)
|
|
365
|
+
throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
|
|
366
|
+
for (let c = 0; c < 4; c++)
|
|
367
|
+
point(conditional, m, shape.points, c * 3);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
if ((conditional.length + lines.length) / 3 + 2 > maxVertices)
|
|
371
|
+
throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
|
|
372
|
+
const [r, g, b] = color(shape.code, parent).color;
|
|
373
|
+
point(lines, m, shape.points, 0);
|
|
374
|
+
point(lines, m, shape.points, 3);
|
|
375
|
+
lineColors.push3(r, g, b);
|
|
376
|
+
lineColors.push3(r, g, b);
|
|
377
|
+
};
|
|
378
|
+
/**
|
|
379
|
+
* `clipped`: no reference above was made under `NOCLIP`. `certified`: every file above is certified, or the nearest
|
|
380
|
+
* part above is reached through certified files only (the BFC spec lets a certified part cull under any caller).
|
|
381
|
+
*/
|
|
382
|
+
const walk = (part, m, inverted, parent, depth, clipped, certified) => {
|
|
383
|
+
if (depth > maxDepth)
|
|
384
|
+
throw new LoaderError(F, 'limit', `sub-files nest deeper than ${maxDepth}`);
|
|
385
|
+
if (visiting.has(part))
|
|
386
|
+
throw new LoaderError(F, 'syntax', 'a sub-file refers to itself');
|
|
387
|
+
visiting.add(part);
|
|
388
|
+
for (const command of part.commands) {
|
|
389
|
+
if (command.kind === 1) {
|
|
390
|
+
const child = parts.get(key(command.file));
|
|
391
|
+
if (!child)
|
|
392
|
+
continue;
|
|
393
|
+
if (++instances > maxInstances)
|
|
394
|
+
throw new LoaderError(F, 'limit', `the model expands to more than ${maxInstances} sub-file references`);
|
|
395
|
+
const flips = determinant(command.matrix) < 0, next = multiply(m, command.matrix), turned = (inverted !== flips) !== command.invert, code = command.code === MAIN ? parent : command.code === EDGE ? color(EDGE, parent).code : command.code, clips = clipped && command.clip, certifies = child.part === true || (certified && command.certified);
|
|
396
|
+
// A mirrored placement stays in the main mesh: a renderer's winding would not follow a mirrored matrix.
|
|
397
|
+
if (instanced && out === whole && key(command.file).endsWith('.dat') && determinant(next) > 0) {
|
|
398
|
+
const id = `${key(command.file)}|${code}|${turned}|${clips}|${certifies}`;
|
|
399
|
+
let place = placed.get(id);
|
|
400
|
+
if (!place) {
|
|
401
|
+
place = { file: command.file, code, into: sink(), matrices: [] };
|
|
402
|
+
placed.set(id, place);
|
|
403
|
+
out = place.into;
|
|
404
|
+
walk(child, IDENTITY, turned, code, depth + 1, clips, certifies);
|
|
405
|
+
out = whole;
|
|
406
|
+
}
|
|
407
|
+
place.matrices.push(next[0], next[3], next[6], 0, next[1], next[4], next[7], 0, next[2], next[5], next[8], 0, next[9], next[10], next[11], 1);
|
|
408
|
+
}
|
|
409
|
+
else
|
|
410
|
+
walk(child, next, turned, code, depth + 1, clips, certifies);
|
|
411
|
+
}
|
|
412
|
+
else if (command.kind === 3 || command.kind === 4)
|
|
413
|
+
polygon(command, m, inverted, parent, clipped && certified);
|
|
414
|
+
else if (edges)
|
|
415
|
+
line(command, m, parent);
|
|
416
|
+
}
|
|
417
|
+
visiting.delete(part);
|
|
418
|
+
};
|
|
419
|
+
const root = options.units === 'file' ? IDENTITY : [LDU, 0, 0, 0, -LDU, 0, 0, 0, -LDU, 0, 0, 0];
|
|
420
|
+
walk(parts.get(main), root, false, mainColor, 0, true, true);
|
|
421
|
+
const finish = (from) => {
|
|
422
|
+
const indices = new Uint32Array(from.triangles * 3), groups = [];
|
|
423
|
+
let start = 0;
|
|
424
|
+
for (const [code, bucket] of from.buckets) {
|
|
425
|
+
const entry = used.get(code);
|
|
426
|
+
indices.set(bucket.array.subarray(0, bucket.length), start);
|
|
427
|
+
groups.push({
|
|
428
|
+
start,
|
|
429
|
+
count: bucket.length,
|
|
430
|
+
name: entry.name,
|
|
431
|
+
objectId: String(code),
|
|
432
|
+
color: [...entry.color],
|
|
433
|
+
});
|
|
434
|
+
start += bucket.length;
|
|
435
|
+
}
|
|
436
|
+
return {
|
|
437
|
+
positions: from.positions.result(),
|
|
438
|
+
indices,
|
|
439
|
+
groups,
|
|
440
|
+
lines: from.lines.result(),
|
|
441
|
+
lineColors: from.lineColors.result(),
|
|
442
|
+
conditionalLines: from.conditional.result(),
|
|
443
|
+
};
|
|
444
|
+
};
|
|
445
|
+
const model = {
|
|
446
|
+
kind: 'mesh',
|
|
447
|
+
...finish(whole),
|
|
448
|
+
instances: [...placed.values()].map(({ file, code, into, matrices }) => ({
|
|
449
|
+
file,
|
|
450
|
+
code,
|
|
451
|
+
...finish(into),
|
|
452
|
+
matrices: new Float32Array(matrices),
|
|
453
|
+
})),
|
|
454
|
+
palette: [...used.values()],
|
|
455
|
+
missing: [...missing],
|
|
456
|
+
warnings: [...warnings],
|
|
457
|
+
};
|
|
458
|
+
const title = parts.get(main).title;
|
|
459
|
+
if (title !== undefined)
|
|
460
|
+
model.name = title;
|
|
461
|
+
return model;
|
|
462
|
+
}
|
|
463
|
+
/** The referenced files that are neither loaded nor tried yet. */
|
|
464
|
+
function references(parts, tried) {
|
|
465
|
+
const wanted = new Map();
|
|
466
|
+
for (const part of parts.values())
|
|
467
|
+
for (const command of part.commands)
|
|
468
|
+
if (command.kind === 1) {
|
|
469
|
+
const id = key(command.file);
|
|
470
|
+
if (!parts.has(id) && !tried.has(id))
|
|
471
|
+
wanted.set(id, command.file);
|
|
472
|
+
}
|
|
473
|
+
return [...wanted.values()];
|
|
474
|
+
}
|
package/dist/load.d.ts
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
/** Options of fetchBytes and fetchResource: an AbortSignal, the size limit, a custom fetch, RequestInit and guards. */
|
|
2
|
+
export interface FetchOptions {
|
|
3
|
+
signal?: AbortSignal;
|
|
4
|
+
/** Maximum response size in bytes. Default 256 MiB. */
|
|
5
|
+
maxBytes?: number;
|
|
6
|
+
/** Custom fetch, for example one that adds credentials. Default `globalThis.fetch`. */
|
|
7
|
+
fetch?: typeof fetch;
|
|
8
|
+
/** Extra `RequestInit` (headers, credentials, ...). */
|
|
9
|
+
init?: RequestInit;
|
|
10
|
+
/**
|
|
11
|
+
* URL schemes allowed for the link and every redirect, such as `['https:']`. Default: any scheme the fetch takes.
|
|
12
|
+
* Refused with LoaderError code `'url'`.
|
|
13
|
+
*/
|
|
14
|
+
protocols?: readonly string[];
|
|
15
|
+
/**
|
|
16
|
+
* True refuses a link or redirect to this computer or a private network by its host: `localhost` and `*.localhost`
|
|
17
|
+
* (RFC 6761), IPv4 0/8, loopback 127/8, private 10/8, 172.16/12 and 192.168/16 (RFC 1918), shared 100.64/10
|
|
18
|
+
* (RFC 6598), link-local 169.254/16 (RFC 3927), and IPv6 loopback, unspecified, unique local fc00::/7 (RFC 4193),
|
|
19
|
+
* link-local fe80::/10 (RFC 4291) and IPv4-mapped forms of those; also a link with a user name or password.
|
|
20
|
+
* Default false. Refused with code `'url'`. It reads the host as written: a public name whose DNS answer is private
|
|
21
|
+
* is not caught.
|
|
22
|
+
*/
|
|
23
|
+
publicOnly?: boolean;
|
|
24
|
+
/** Your own host test, run on the link and every redirect after `publicOnly`: false refuses (code `'url'`). */
|
|
25
|
+
allowHost?: (hostname: string, url: URL) => boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Redirects followed by hand (`redirect: 'manual'`), each hop checked against `protocols`, `publicOnly` and
|
|
28
|
+
* `allowHost`; one more is refused with code `'limit'`. Default 20 when a guard is set; with no guard the fetch
|
|
29
|
+
* follows redirects itself. A browser hides manual redirects (an opaque response), so there a guarded redirect is
|
|
30
|
+
* refused with `'unsupported'`; Node and other servers follow them.
|
|
31
|
+
*/
|
|
32
|
+
maxRedirects?: number;
|
|
33
|
+
/**
|
|
34
|
+
* Media types accepted, matched against the response's `Content-Type` essence (type/subtype, no parameters):
|
|
35
|
+
* `'text/html'`, or `'text/*'` for a whole type. Default: any. Refused with code `'unsupported'` before the body is
|
|
36
|
+
* read.
|
|
37
|
+
*/
|
|
38
|
+
accept?: readonly string[];
|
|
39
|
+
}
|
|
40
|
+
/** What fetchResource returns: the body, the final URL after redirects, its media type and status, and the hops. */
|
|
41
|
+
export interface FetchedResource {
|
|
42
|
+
bytes: Uint8Array;
|
|
43
|
+
/** The final URL, after redirects. */
|
|
44
|
+
url: string;
|
|
45
|
+
/** The response's `Content-Type` as sent (parameters such as `charset` included), or `''`. */
|
|
46
|
+
type: string;
|
|
47
|
+
status: number;
|
|
48
|
+
/** Redirects followed by hand (0 when the fetch followed them itself). */
|
|
49
|
+
redirects: number;
|
|
50
|
+
}
|
|
51
|
+
/** The default response size limit of fetchBytes: 256 MiB. */
|
|
52
|
+
export declare const DEFAULT_MAX_BYTES: number;
|
|
53
|
+
/**
|
|
54
|
+
* True for a host that names this computer or a private network as written (FetchOptions.publicOnly). WHATWG URL
|
|
55
|
+
* parsing has already turned short and hexadecimal IPv4 forms into dotted quads, and IPv6 into its bracketed,
|
|
56
|
+
* compressed, lower-case text.
|
|
57
|
+
*/
|
|
58
|
+
export declare function isPrivateHost(hostname: string): boolean;
|
|
59
|
+
/** Fetches `url` into memory, enforcing `maxBytes` on both Content-Length and the streamed body. */
|
|
60
|
+
export declare function fetchBytes(url: string | URL, options?: FetchOptions): Promise<Uint8Array>;
|
|
61
|
+
/**
|
|
62
|
+
* Fetches `url` like fetchBytes and also returns the final URL, media type, status and redirects followed. With
|
|
63
|
+
* `protocols`, `publicOnly`, `allowHost` or `maxRedirects` it follows redirects by hand and checks every hop, for links
|
|
64
|
+
* from untrusted sources; `accept` refuses other media types before the body is read. An error the custom `fetch`
|
|
65
|
+
* throws is kept as the LoaderError's `cause`.
|
|
66
|
+
*/
|
|
67
|
+
export declare function fetchResource(url: string | URL, options?: FetchOptions): Promise<FetchedResource>;
|
|
68
|
+
/**
|
|
69
|
+
* Fetches `url` and parses it with `parse`, for example `load('/scan.ply', parsePLY, {signal, maxVertices: 1e6})`.
|
|
70
|
+
* The same options object goes to the parser, so limits and `signal` apply to both steps.
|
|
71
|
+
*/
|
|
72
|
+
export declare function load<T, O extends object = object>(url: string | URL, parse: (input: Uint8Array, options?: O) => T | Promise<T>, options?: O & FetchOptions): Promise<T>;
|