@margoengine/loaders 0.1.0 → 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.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +1666 -1198
- package/dist/crease.d.ts +7 -0
- package/dist/crease.js +67 -0
- package/dist/dae-common.js +1 -1
- package/dist/dae-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -0
- package/dist/dae.d.ts +9 -4
- package/dist/dae.js +16 -5
- package/dist/dxf-hatch.d.ts +8 -0
- package/dist/dxf-hatch.js +346 -0
- package/dist/dxf-leaders.d.ts +59 -0
- package/dist/dxf-leaders.js +258 -0
- package/dist/dxf.d.ts +42 -1
- package/dist/dxf.js +226 -15
- package/dist/engine.d.ts +5 -0
- package/dist/engine.js +3 -0
- package/dist/gcode.d.ts +37 -0
- package/dist/gcode.js +91 -0
- package/dist/geometry.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/mtl.d.ts +8 -3
- package/dist/mtl.js +91 -10
- package/dist/nrrd.d.ts +12 -5
- package/dist/nrrd.js +68 -26
- package/dist/obj.d.ts +3 -1
- package/dist/obj.js +7 -1
- package/dist/render.d.ts +9 -4
- package/dist/render.js +31 -3
- package/dist/shared/asset-url.js +82 -82
- package/dist/shared/crc32.d.ts +2 -2
- package/dist/shared/crc32.js +47 -47
- package/dist/shared/errors.js +36 -36
- package/dist/shared/inflate.js +284 -284
- package/dist/shared/normals.js +26 -26
- package/dist/shared/scene-scope.js +54 -54
- package/dist/shared/trailing-data.js +45 -42
- package/dist/threemf-beam-reader.d.ts +19 -0
- package/dist/threemf-beam-reader.js +165 -0
- package/dist/threemf-beams.d.ts +52 -0
- package/dist/threemf-beams.js +268 -0
- package/dist/threemf-boolean-read.d.ts +10 -0
- package/dist/threemf-boolean-read.js +113 -0
- package/dist/threemf-boolean.d.ts +59 -0
- package/dist/threemf-boolean.js +20 -0
- package/dist/threemf-csg.d.ts +14 -0
- package/dist/threemf-csg.js +193 -0
- package/dist/threemf-displacement-read.d.ts +8 -0
- package/dist/threemf-displacement-read.js +213 -0
- package/dist/threemf-displacement.d.ts +71 -0
- package/dist/threemf-displacement.js +18 -0
- package/dist/threemf-evaluate.d.ts +36 -0
- package/dist/threemf-evaluate.js +86 -0
- package/dist/threemf-functions.d.ts +33 -0
- package/dist/threemf-functions.js +359 -0
- package/dist/threemf-lattice-mesh.d.ts +9 -0
- package/dist/threemf-lattice-mesh.js +115 -0
- package/dist/threemf-lattice.js +10 -145
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +89 -2
- package/dist/threemf-materials.js +194 -11
- package/dist/threemf-mesh.d.ts +21 -6
- package/dist/threemf-mesh.js +266 -45
- package/dist/threemf-secure.d.ts +50 -0
- package/dist/threemf-secure.js +153 -0
- package/dist/threemf-tessellate.d.ts +37 -0
- package/dist/threemf-tessellate.js +277 -0
- package/dist/threemf-volume-colour.d.ts +25 -0
- package/dist/threemf-volume-colour.js +233 -0
- package/dist/threemf-volume-sample.d.ts +8 -0
- package/dist/threemf-volume-sample.js +65 -0
- package/dist/threemf-volumetric-read.d.ts +15 -0
- package/dist/threemf-volumetric-read.js +539 -0
- package/dist/threemf-volumetric.d.ts +177 -0
- package/dist/threemf-volumetric.js +28 -0
- package/dist/threemf.d.ts +73 -4
- package/dist/threemf.js +235 -41
- package/dist/types.d.ts +18 -0
- package/dist/workers/usd.js +1 -1
- package/package.json +291 -246
package/dist/mtl.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Material, createMesh, loadTexture as loadMaterialTexture, } from '@margoengine/materials';
|
|
1
|
+
import { CubeTexture, Material, createMesh, loadTexture as loadMaterialTexture, } from '@margoengine/materials';
|
|
2
2
|
import { SRGBToLinear } from '@margoengine/math/color';
|
|
3
3
|
import { DEFAULT_MAX_BYTES, fetchBytes } from './load.js';
|
|
4
4
|
import { assetURL } from './shared/asset-url.js';
|
|
@@ -8,7 +8,11 @@ import { LoaderError } from './types.js';
|
|
|
8
8
|
import { resolvePath } from './util.js';
|
|
9
9
|
const F = 'MTL';
|
|
10
10
|
/** Map statements with a material slot; every other map key is reported as unused. */
|
|
11
|
-
const SLOTTED_MAPS = new Set(['map_Kd', 'map_Ke', 'map_d', 'bump']);
|
|
11
|
+
const SLOTTED_MAPS = new Set(['map_Kd', 'map_Ke', 'map_d', 'bump', 'map_Ks', 'disp', 'refl']);
|
|
12
|
+
/** Cube reflection faces in cube layer order +X, -X, +Y, -Y, +Z, -Z: front is -Z, the way a camera looks. */
|
|
13
|
+
const FACES = ['cube_right', 'cube_left', 'cube_top', 'cube_bottom', 'cube_back', 'cube_front'];
|
|
14
|
+
/** The specularColor that makes a dielectric's F0 (0.04 at the default index of refraction 1.5) equal to 1. */
|
|
15
|
+
const F0_ONE = 25;
|
|
12
16
|
/** PBR-extension statements read from `extras` (compared in lower case); other extras are reported as unused. */
|
|
13
17
|
const READ_EXTRAS = new Set(['norm', 'pr', 'pm']);
|
|
14
18
|
const clamp01 = (v) => Math.min(1, Math.max(0, v));
|
|
@@ -98,8 +102,17 @@ function materialOptions(m, doubleSided) {
|
|
|
98
102
|
options.roughness = roughnessFromNs(m.Ns);
|
|
99
103
|
const pm = extraNumber(m, 'pm');
|
|
100
104
|
options.metalness = Number.isFinite(pm) ? clamp01(pm) : 0;
|
|
105
|
+
if (isPBR(m))
|
|
106
|
+
return options;
|
|
107
|
+
// Ks is the specular reflectance: KHR_materials_specular holds it as F0 (illum 1 and a black Ks have no highlight).
|
|
108
|
+
if (m.illum === 1 || m.Ks?.every((c) => !(c > 0)))
|
|
109
|
+
options.specularIntensity = 0;
|
|
110
|
+
else if (m.Ks || m.maps?.map_Ks)
|
|
111
|
+
options.specularColor = (m.Ks ? linear3(m.Ks) : [1, 1, 1]).map((c) => c * F0_ONE);
|
|
101
112
|
return options;
|
|
102
113
|
}
|
|
114
|
+
/** A material with the PBR extension's `Pr` or `Pm`: its `Ks` is the fallback for Phong readers. */
|
|
115
|
+
const isPBR = (m) => Number.isFinite(extraNumber(m, 'pr')) || Number.isFinite(extraNumber(m, 'pm'));
|
|
103
116
|
/** The maps a material uses, in slot (and load) order: map, alphaMap, emissiveMap, bump or normal, norm. */
|
|
104
117
|
function mapUses(m, bump) {
|
|
105
118
|
const maps = m.maps ?? {}, uses = [];
|
|
@@ -109,8 +122,11 @@ function mapUses(m, bump) {
|
|
|
109
122
|
};
|
|
110
123
|
add('map', maps.map_Kd, 'srgb');
|
|
111
124
|
add('alphaMap', maps.map_d, 'linear');
|
|
125
|
+
add('displacementMap', maps.disp, 'linear');
|
|
112
126
|
if (m.illum === 0)
|
|
113
127
|
return uses;
|
|
128
|
+
if (m.illum !== 1 && !isPBR(m))
|
|
129
|
+
add('specularColorMap', maps.map_Ks, 'srgb');
|
|
114
130
|
add('emissiveMap', maps.map_Ke, 'srgb');
|
|
115
131
|
add(bump === 'normal' ? 'normalMap' : 'bumpMap', maps.bump, 'linear');
|
|
116
132
|
const norm = extra(m, 'norm');
|
|
@@ -121,19 +137,41 @@ function mapUses(m, bump) {
|
|
|
121
137
|
}
|
|
122
138
|
return uses;
|
|
123
139
|
}
|
|
140
|
+
/**
|
|
141
|
+
* The reflection map of a material: six cube faces in layer order, one latitude-longitude (`-type sphere`, the
|
|
142
|
+
* default) image, or a warning. MTL calls the second a map on the inside of an infinitely large sphere.
|
|
143
|
+
*/
|
|
144
|
+
function reflection(m) {
|
|
145
|
+
const maps = m.maps ?? {};
|
|
146
|
+
if (m.illum === 0 || !maps.refl)
|
|
147
|
+
return undefined;
|
|
148
|
+
const faces = FACES.map((face) => maps[`refl_${face}`]);
|
|
149
|
+
if (faces.every(Boolean))
|
|
150
|
+
return { maps: faces };
|
|
151
|
+
const type = maps.refl.options?.type?.toLowerCase() ?? 'sphere';
|
|
152
|
+
if (type === 'sphere')
|
|
153
|
+
return { maps: [maps.refl] };
|
|
154
|
+
if (!FACES.includes(type))
|
|
155
|
+
return { warning: `refl -type ${type} is not sphere or a cube face; it is not used` };
|
|
156
|
+
const missing = FACES.filter((face) => !maps[`refl_${face}`]);
|
|
157
|
+
return { warning: `refl cube map lacks ${missing.join(', ')}; it is not used` };
|
|
158
|
+
}
|
|
124
159
|
/** What a material says that Margo materials cannot show, as warnings. */
|
|
125
160
|
function unusedWarnings(m) {
|
|
126
161
|
const out = [];
|
|
127
162
|
for (const key of Object.keys(m.maps ?? {}))
|
|
128
|
-
if (!SLOTTED_MAPS.has(key))
|
|
163
|
+
if (!SLOTTED_MAPS.has(key) && !key.startsWith('refl_'))
|
|
129
164
|
out.push(`${key} has no Margo material slot; it is not used`);
|
|
165
|
+
const channel = m.maps?.disp?.options?.imfchan;
|
|
166
|
+
if (channel && channel !== 'r')
|
|
167
|
+
out.push(`disp -imfchan ${channel}: Margo displaces by the red channel`);
|
|
130
168
|
for (const s of m.extras ?? [])
|
|
131
169
|
if (!READ_EXTRAS.has(s.keyword.toLowerCase()))
|
|
132
170
|
out.push(`${s.keyword} has no Margo material equivalent; it is not used`);
|
|
133
171
|
if (m.Ka)
|
|
134
172
|
out.push('Ka (ambient colour) has no Margo material equivalent; it is not used');
|
|
135
|
-
if (m
|
|
136
|
-
out.push('
|
|
173
|
+
if (isPBR(m) && m.maps?.map_Ks)
|
|
174
|
+
out.push('map_Ks is the Phong fallback of a Pr/Pm material; it is not used');
|
|
137
175
|
return out;
|
|
138
176
|
}
|
|
139
177
|
/**
|
|
@@ -141,9 +179,14 @@ function unusedWarnings(m) {
|
|
|
141
179
|
* metallic-roughness: `Kd` is the base colour (sRGB in the file, linear in the material), `d` (else 1 - `Tr`) the
|
|
142
180
|
* opacity, `Ke` the emission (a peak above 1 moves into `emissiveIntensity`), and roughness comes from the Phong
|
|
143
181
|
* exponent `Ns` as (2 / (Ns + 2))^(1/4) (Walter et al. 2007's Blinn-Phong to Beckmann match with glTF's
|
|
144
|
-
* alpha = roughness^2).
|
|
145
|
-
*
|
|
146
|
-
*
|
|
182
|
+
* alpha = roughness^2). `Ks` (and `map_Ks`, times it) is the specular reflectance at normal incidence, held as
|
|
183
|
+
* KHR_materials_specular's `specularColor` and `specularColorMap`; `illum 1` and a black `Ks` have no highlight. The
|
|
184
|
+
* PBR extension's `Pr`, `Pm` and `norm` are read when present, and a material with `Pr` or `Pm` leaves `Ks` out.
|
|
185
|
+
* `illum 0` is unlit. `disp` displaces vertices along their normals (`-mm base gain`: bias and scale). `refl` becomes
|
|
186
|
+
* the material's `envMap`: `-type sphere` a latitude-longitude image, or six `-type cube_*` faces (front is -Z).
|
|
187
|
+
* `map_Kd`, `map_d`, `map_Ke`, `map_Ks`, `disp`, `refl`, `bump` and `norm` load as textures, each (file, colour
|
|
188
|
+
* space, wrap) once; their `-o` and `-s` become the slot's UV transform and `-clamp on` a clamped wrap. A map that
|
|
189
|
+
* fails to load is a warning. `Ka` has no equivalent (ambient light shades the base colour) and is a warning.
|
|
147
190
|
* Rejects with `TypeError` / `RangeError` for bad arguments and with a `LoaderError` (code `'aborted'`) when
|
|
148
191
|
* `signal` aborts; whatever was built is disposed first.
|
|
149
192
|
*/
|
|
@@ -199,7 +242,7 @@ export async function createMTLMaterials(mtl, options = {}) {
|
|
|
199
242
|
}
|
|
200
243
|
};
|
|
201
244
|
// One request per (colour space, wrap, URL), in first-use order.
|
|
202
|
-
const requests = new Map(), assignments = [];
|
|
245
|
+
const requests = new Map(), assignments = [], reflections = [];
|
|
203
246
|
const request = (url, colorSpace, wrap) => {
|
|
204
247
|
const key = `${colorSpace} ${wrap} ${url}`;
|
|
205
248
|
if (requests.has(key))
|
|
@@ -241,10 +284,20 @@ export async function createMTLMaterials(mtl, options = {}) {
|
|
|
241
284
|
assignments.push({ material, slot: use.slot, key: request(url, use.colorSpace, wrap) });
|
|
242
285
|
if (use.slot === 'bumpMap' && Number.isFinite(use.options.bm))
|
|
243
286
|
material.bumpScale = use.options.bm;
|
|
287
|
+
if (use.slot === 'displacementMap' && use.options.mm?.every(Number.isFinite))
|
|
288
|
+
[material.displacementBias, material.displacementScale] = use.options.mm;
|
|
244
289
|
const [ou = 0, ov = 0] = use.options.o ?? [], [su = 1, sv = 1] = use.options.s ?? [];
|
|
245
290
|
if (ou !== 0 || ov !== 0 || su !== 1 || sv !== 1)
|
|
246
291
|
material.setUVTransform({ offset: [ou, ov], scale: [su, sv] }, use.slot);
|
|
247
292
|
}
|
|
293
|
+
const refl = reflection(m);
|
|
294
|
+
if (refl && 'warning' in refl)
|
|
295
|
+
warn(refl.warning);
|
|
296
|
+
else if (refl) {
|
|
297
|
+
const urls = refl.maps.map((map) => urlOf(map.path));
|
|
298
|
+
if (urls.every((url) => url !== undefined))
|
|
299
|
+
reflections.push({ material, keys: urls.map((url) => request(url, 'srgb', 'clamp')) });
|
|
300
|
+
}
|
|
248
301
|
}
|
|
249
302
|
const all = Promise.all([...requests.values()].map((r) => r.promise));
|
|
250
303
|
if (signal) {
|
|
@@ -267,7 +320,35 @@ export async function createMTLMaterials(mtl, options = {}) {
|
|
|
267
320
|
if (texture)
|
|
268
321
|
material[slot] = texture;
|
|
269
322
|
}
|
|
270
|
-
|
|
323
|
+
// One cube map per distinct set of files.
|
|
324
|
+
const cubes = new Map();
|
|
325
|
+
for (const { material, keys } of reflections) {
|
|
326
|
+
const sources = keys.map((key) => requests.get(key)?.texture), id = keys.join('\n');
|
|
327
|
+
if (!sources.every((texture) => texture !== undefined))
|
|
328
|
+
continue;
|
|
329
|
+
if (!cubes.has(id)) {
|
|
330
|
+
try {
|
|
331
|
+
const cube = sources.length === 1
|
|
332
|
+
? new CubeTexture(sources[0])
|
|
333
|
+
: new CubeTexture(sources.map((texture) => texture.source), {
|
|
334
|
+
colorSpace: 'srgb',
|
|
335
|
+
});
|
|
336
|
+
cubes.set(id, cube);
|
|
337
|
+
arrived.push(cube);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
warn(`refl map could not become a cube map (${error.message}); it is left out`);
|
|
341
|
+
cubes.set(id, undefined);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
const cube = cubes.get(id);
|
|
345
|
+
if (cube)
|
|
346
|
+
material.envMap = cube;
|
|
347
|
+
}
|
|
348
|
+
set.textures = [
|
|
349
|
+
...[...requests.values()].flatMap((r) => (r.texture ? [r.texture] : [])),
|
|
350
|
+
...[...cubes.values()].flatMap((cube) => (cube ? [cube] : [])),
|
|
351
|
+
];
|
|
271
352
|
return set;
|
|
272
353
|
}
|
|
273
354
|
catch (error) {
|
package/dist/nrrd.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type AssetResolver } from './types.js';
|
|
2
2
|
import { type BinaryInput } from './util.js';
|
|
3
3
|
/** A sample type of a NRRD file, with the C spellings folded to one name. */
|
|
4
|
-
export type NRRDType = 'int8' | 'uint8' | 'int16' | 'uint16' | 'int32' | 'uint32' | 'int64' | 'uint64' | 'float32' | 'float64';
|
|
4
|
+
export type NRRDType = 'int8' | 'uint8' | 'int16' | 'uint16' | 'int32' | 'uint32' | 'int64' | 'uint64' | 'float32' | 'float64' | 'block';
|
|
5
5
|
/** Samples in the file's own type; 64-bit integers arrive as `Float64Array`, exact up to 2^53. */
|
|
6
6
|
export type NRRDData = Int8Array<ArrayBuffer> | Uint8Array<ArrayBuffer> | Int16Array<ArrayBuffer> | Uint16Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Float64Array<ArrayBuffer>;
|
|
7
7
|
/** Options of {@link parseNRRD}. */
|
|
@@ -14,9 +14,14 @@ export interface NRRDOptions {
|
|
|
14
14
|
}
|
|
15
15
|
/** What {@link parseNRRD} returns. Pass `data`, `dims` and `bounds` to `fig.volume()` of `@margoengine/sciviz`. */
|
|
16
16
|
export interface NRRDVolume {
|
|
17
|
-
/**
|
|
17
|
+
/**
|
|
18
|
+
* Every sample, the first axis fastest. For the `block` type, the opaque blocks as stored: `blockSize` bytes each, in
|
|
19
|
+
* a `Uint8Array`.
|
|
20
|
+
*/
|
|
18
21
|
data: NRRDData;
|
|
19
22
|
type: NRRDType;
|
|
23
|
+
/** Bytes per sample of a `block` file (its `block size` field); absent for every other type. */
|
|
24
|
+
blockSize?: number;
|
|
20
25
|
/** The size of every axis in the file, the fastest first. */
|
|
21
26
|
sizes: number[];
|
|
22
27
|
/** Grid size `[nx, ny, nz]` of the spatial axes, padded with 1 for a 1D or 2D file. */
|
|
@@ -43,13 +48,15 @@ export interface NRRDVolume {
|
|
|
43
48
|
* raw, ascii, hex, gzip and bzip2, with either byte order, `line skip` and `byte skip` (-1 for the end of a raw file)
|
|
44
49
|
* and one or many data files (a printf pattern or a `LIST`, with `subdim`). Data past what the header needs is
|
|
45
50
|
* ignored, and gzip decoding stops there. `space directions`, `space origin`, `spacings` and `kinds` set `dims`, `spacing`, `bounds` and
|
|
46
|
-
* `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`.
|
|
51
|
+
* `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`. A `block` file gives its blocks
|
|
52
|
+
* as bytes with `blockSize`; its encoding cannot be ascii (the format defines no text form for a block) and its bytes
|
|
53
|
+
* are never swapped.
|
|
47
54
|
*
|
|
48
55
|
* @param input The file's bytes.
|
|
49
56
|
* @param options A resolver for detached data, the sample limit and an AbortSignal.
|
|
50
57
|
* @returns The samples in the file's own type and where they sit.
|
|
51
|
-
* @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
|
|
52
|
-
*
|
|
58
|
+
* @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
|
|
59
|
+
* (detached data without `resolve`).
|
|
53
60
|
*
|
|
54
61
|
* @example
|
|
55
62
|
* ```ts
|
package/dist/nrrd.js
CHANGED
|
@@ -468,39 +468,67 @@ async function gunzip(body, size, signal) {
|
|
|
468
468
|
}
|
|
469
469
|
if (p >= body.length)
|
|
470
470
|
throw corrupt('the stream ends early');
|
|
471
|
-
|
|
472
|
-
|
|
471
|
+
// A file of one member ends with its trailer: feeding the DEFLATE data without those 8 bytes gives the decoder
|
|
472
|
+
// nothing past the stream's end, so no runtime fails on it. Other files fall back below.
|
|
473
|
+
const from = length, member = body.subarray(p), first = await inflateMember(at === 0 ? body.subarray(p, body.length - 8) : member, out, from, signal);
|
|
474
|
+
length = first.length;
|
|
473
475
|
if (length >= size)
|
|
474
476
|
break;
|
|
475
477
|
// The member ended before the samples did: find its trailer, the CRC-32 and size of what it gave.
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
478
|
+
let end = trailer(body, p, out.subarray(from, length)), failedAt = first.failedAt, step = FEED;
|
|
479
|
+
// A runtime that drops the output of the chunk holding the stream's end and the bytes after it (Firefox) gave
|
|
480
|
+
// less than the member holds. Inflate it again with that chunk fed in halves, then quarters, and so on, until the
|
|
481
|
+
// chunk that fails holds no byte of the stream and the trailer matches (KB5076): at most 16 more passes, only for data
|
|
482
|
+
// with more after a member.
|
|
483
|
+
while (end < 0 && failedAt >= 0 && step > 1) {
|
|
484
|
+
step >>= 1;
|
|
485
|
+
const again = await inflateMember(member, out, from, signal, failedAt, step);
|
|
486
|
+
length = again.length;
|
|
487
|
+
if (length >= size)
|
|
488
|
+
break;
|
|
489
|
+
end = trailer(body, p, out.subarray(from, length));
|
|
490
|
+
failedAt = again.failedAt;
|
|
491
|
+
}
|
|
492
|
+
if (length >= size)
|
|
493
|
+
break;
|
|
494
|
+
if (end < 0)
|
|
481
495
|
throw corrupt('a member has no matching CRC-32 and size trailer');
|
|
482
496
|
at = end + 8;
|
|
483
497
|
}
|
|
484
498
|
return out.subarray(0, length);
|
|
485
499
|
}
|
|
500
|
+
/** Where the 8-byte trailer (CRC-32, then size) of a member that gave `given` starts, from `p`, or -1. */
|
|
501
|
+
function trailer(body, p, given) {
|
|
502
|
+
const crc = crc32(given), isize = given.length % 2 ** 32;
|
|
503
|
+
for (let end = p; end + 8 <= body.length; end++)
|
|
504
|
+
if (u32le(body, end) === crc && u32le(body, end + 4) === isize)
|
|
505
|
+
return end;
|
|
506
|
+
return -1;
|
|
507
|
+
}
|
|
486
508
|
/**
|
|
487
509
|
* Inflates the DEFLATE data at the start of `data` into `out` from `length`, until `out` is full or the stream ends,
|
|
488
|
-
* and returns the new length
|
|
489
|
-
* fail
|
|
510
|
+
* and returns the new length and, when the decoder failed, where the chunk before the failing one started (-1 when it
|
|
511
|
+
* did not fail). Bytes after the end of the stream (the gzip trailer, what follows) make the decoder fail; Chromium and
|
|
512
|
+
* Node give that chunk's output first, Firefox does not, so from `fine` on the data is fed in chunks of `step` bytes,
|
|
513
|
+
* which the caller narrows until the failing chunk holds no byte of the stream. The caller's trailer check tells either
|
|
514
|
+
* failure apart from damage.
|
|
490
515
|
*/
|
|
491
|
-
async function inflateMember(data, out, length, signal) {
|
|
492
|
-
let fed = 0;
|
|
516
|
+
async function inflateMember(data, out, length, signal, fine = -1, step = FEED) {
|
|
517
|
+
let fed = 0, last = 0, before = 0;
|
|
493
518
|
const input = new ReadableStream({
|
|
494
519
|
pull(controller) {
|
|
495
520
|
if (fed >= data.length)
|
|
496
|
-
controller.close();
|
|
497
|
-
|
|
498
|
-
|
|
521
|
+
return controller.close();
|
|
522
|
+
const size = fine < 0 ? FEED : fed < fine ? Math.min(FEED, fine - fed) : step;
|
|
523
|
+
before = last;
|
|
524
|
+
last = fed;
|
|
525
|
+
controller.enqueue(data.subarray(fed, (fed += size)));
|
|
499
526
|
},
|
|
500
527
|
}, { highWaterMark: 0 });
|
|
501
528
|
const reader = input
|
|
502
529
|
.pipeThrough(new DecompressionStream('deflate-raw'))
|
|
503
530
|
.getReader();
|
|
531
|
+
let failedAt = -1;
|
|
504
532
|
try {
|
|
505
533
|
while (length < out.length) {
|
|
506
534
|
throwIfAborted(signal, F);
|
|
@@ -515,11 +543,13 @@ async function inflateMember(data, out, length, signal) {
|
|
|
515
543
|
catch (error) {
|
|
516
544
|
if (error instanceof LoaderError)
|
|
517
545
|
throw error;
|
|
546
|
+
// The pipe may have pulled one chunk ahead of the one that failed.
|
|
547
|
+
failedAt = before;
|
|
518
548
|
}
|
|
519
549
|
finally {
|
|
520
550
|
void reader.cancel().catch(() => { });
|
|
521
551
|
}
|
|
522
|
-
return length;
|
|
552
|
+
return { length, failedAt };
|
|
523
553
|
}
|
|
524
554
|
async function decode(file, out, offset, count, how) {
|
|
525
555
|
const { type, encoding, byteSkip } = how, size = SIZE[type], length = count * size;
|
|
@@ -650,13 +680,15 @@ function layout(fields, sizes) {
|
|
|
650
680
|
* raw, ascii, hex, gzip and bzip2, with either byte order, `line skip` and `byte skip` (-1 for the end of a raw file)
|
|
651
681
|
* and one or many data files (a printf pattern or a `LIST`, with `subdim`). Data past what the header needs is
|
|
652
682
|
* ignored, and gzip decoding stops there. `space directions`, `space origin`, `spacings` and `kinds` set `dims`, `spacing`, `bounds` and
|
|
653
|
-
* `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`.
|
|
683
|
+
* `matrix`; a leading non-spatial axis is `components` and trailing ones are `frames`. A `block` file gives its blocks
|
|
684
|
+
* as bytes with `blockSize`; its encoding cannot be ascii (the format defines no text form for a block) and its bytes
|
|
685
|
+
* are never swapped.
|
|
654
686
|
*
|
|
655
687
|
* @param input The file's bytes.
|
|
656
688
|
* @param options A resolver for detached data, the sample limit and an AbortSignal.
|
|
657
689
|
* @returns The samples in the file's own type and where they sit.
|
|
658
|
-
* @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
|
|
659
|
-
*
|
|
690
|
+
* @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
|
|
691
|
+
* (detached data without `resolve`).
|
|
660
692
|
*
|
|
661
693
|
* @example
|
|
662
694
|
* ```ts
|
|
@@ -676,9 +708,7 @@ export async function parseNRRD(input, options = {}) {
|
|
|
676
708
|
const missing = ['type', 'dimension', 'sizes', 'encoding'].find((name) => !(name in known));
|
|
677
709
|
if (missing)
|
|
678
710
|
throw new LoaderError(F, 'header', `the required field "${missing}" is missing`);
|
|
679
|
-
|
|
680
|
-
throw new LoaderError(F, 'unsupported', 'the block type has no array form');
|
|
681
|
-
const type = TYPES[fields.type.toLowerCase()];
|
|
711
|
+
const block = fields.type.toLowerCase() === 'block', type = block ? 'uint8' : TYPES[fields.type.toLowerCase()];
|
|
682
712
|
if (!type)
|
|
683
713
|
throw new LoaderError(F, 'header', `unknown type "${fields.type.slice(0, 32)}"`);
|
|
684
714
|
const named = fields.encoding.toLowerCase();
|
|
@@ -699,6 +729,18 @@ export async function parseNRRD(input, options = {}) {
|
|
|
699
729
|
if (total > maxSamples)
|
|
700
730
|
throw new LoaderError(F, 'limit', `the array exceeds the limit of ${maxSamples} samples`);
|
|
701
731
|
}
|
|
732
|
+
const blockSize = block ? integer(known['block size'], 'block size', 0) : 1;
|
|
733
|
+
if (block) {
|
|
734
|
+
if (known['block size'] === undefined)
|
|
735
|
+
throw new LoaderError(F, 'header', 'the required field "block size" is missing');
|
|
736
|
+
if (blockSize < 1)
|
|
737
|
+
throw new LoaderError(F, 'range', `block size ${blockSize} is below 1`);
|
|
738
|
+
if (encoding === 'ascii')
|
|
739
|
+
throw new LoaderError(F, 'header', 'block data cannot be ascii');
|
|
740
|
+
// The same memory bound as the widest numeric type: 8 bytes a sample.
|
|
741
|
+
if (total * blockSize > maxSamples * 8)
|
|
742
|
+
throw new LoaderError(F, 'limit', `the blocks exceed ${maxSamples * 8} bytes (8 per sample of maxSamples)`);
|
|
743
|
+
}
|
|
702
744
|
const endian = fields.endian?.toLowerCase();
|
|
703
745
|
if (endian !== undefined && endian !== 'little' && endian !== 'big')
|
|
704
746
|
throw new LoaderError(F, 'header', `unknown endian "${endian.slice(0, 32)}"`);
|
|
@@ -710,16 +752,16 @@ export async function parseNRRD(input, options = {}) {
|
|
|
710
752
|
if (byteSkip < -1 || (byteSkip === -1 && encoding !== 'raw'))
|
|
711
753
|
throw new LoaderError(F, 'range', `byte skip ${byteSkip} is not allowed with ${encoding} data`);
|
|
712
754
|
const placed = layout(known, sizes);
|
|
713
|
-
const data = allocate(type,
|
|
755
|
+
const elements = total * blockSize, data = allocate(type, elements), how = {
|
|
714
756
|
type,
|
|
715
757
|
encoding,
|
|
716
|
-
swapped: endian !== undefined && (endian === 'little') !== LITTLE,
|
|
758
|
+
swapped: !block && endian !== undefined && (endian === 'little') !== LITTLE,
|
|
717
759
|
lineSkip,
|
|
718
760
|
byteSkip,
|
|
719
761
|
signal,
|
|
720
762
|
}, { files, subdim } = dataFiles(header, dimension);
|
|
721
763
|
if (!files.length)
|
|
722
|
-
await decode(bytes.subarray(header.end), data, 0,
|
|
764
|
+
await decode(bytes.subarray(header.end), data, 0, elements, how);
|
|
723
765
|
else {
|
|
724
766
|
if (!resolve)
|
|
725
767
|
throw new LoaderError(F, 'unsupported', `the data is in "${files[0].slice(0, 64)}"; pass a resolve option`);
|
|
@@ -731,7 +773,7 @@ export async function parseNRRD(input, options = {}) {
|
|
|
731
773
|
const fits = subdim === dimension ? sizes[dimension - 1] % files.length === 0 : files.length === expected;
|
|
732
774
|
if (!fits)
|
|
733
775
|
throw new LoaderError(F, 'range', `${files.length} data files do not fit sizes ${sizes.join(' ')} with subdim ${subdim}`);
|
|
734
|
-
const each =
|
|
776
|
+
const each = elements / files.length;
|
|
735
777
|
for (let i = 0; i < files.length; i++) {
|
|
736
778
|
throwIfAborted(signal, F);
|
|
737
779
|
const content = await resolve(resolvePath('', files[i]));
|
|
@@ -739,5 +781,5 @@ export async function parseNRRD(input, options = {}) {
|
|
|
739
781
|
await decode(file, data, i * each, each, how);
|
|
740
782
|
}
|
|
741
783
|
}
|
|
742
|
-
return { data, type, sizes, ...placed, fields, meta };
|
|
784
|
+
return { data, type: block ? 'block' : type, ...(block ? { blockSize } : {}), sizes, ...placed, fields, meta };
|
|
743
785
|
}
|
package/dist/obj.d.ts
CHANGED
|
@@ -51,7 +51,9 @@ export interface MTLMaterial {
|
|
|
51
51
|
illum?: number;
|
|
52
52
|
/**
|
|
53
53
|
* Texture maps by statement, in a null-prototype object: `map_Kd`, `map_Ka`, `map_Ks`, `map_Ke`, `map_Ns`, `map_d`,
|
|
54
|
-
* `bump` (also written `map_Bump`), `disp`, `decal`, `refl`, and any other `map_*` as written.
|
|
54
|
+
* `bump` (also written `map_Bump`), `disp`, `decal`, `refl`, and any other `map_*` as written. A cube reflection's
|
|
55
|
+
* `refl -type cube_top` (and `cube_bottom`, `_front`, `_back`, `_left`, `_right`) statements are each kept as
|
|
56
|
+
* `refl_cube_top` and so on, beside `refl`, which holds the last `refl` statement.
|
|
55
57
|
*/
|
|
56
58
|
maps: Record<string, MTLMap>;
|
|
57
59
|
/** Statements this reader does not interpret (`Ni`, `Tf`, `Pr`, spectral colors, unknown map options, ...). */
|
package/dist/obj.js
CHANGED
|
@@ -58,6 +58,8 @@ const MAPS = {
|
|
|
58
58
|
decal: 'decal',
|
|
59
59
|
refl: 'refl',
|
|
60
60
|
};
|
|
61
|
+
/** The faces a cube reflection map names with `refl -type`. */
|
|
62
|
+
const CUBE_FACES = ['cube_right', 'cube_left', 'cube_top', 'cube_bottom', 'cube_back', 'cube_front'];
|
|
61
63
|
/** Parses a map statement's options and file name; null when it uses an option outside the MTL specification. */
|
|
62
64
|
function parseMap(tokens, line, from) {
|
|
63
65
|
const options = {}, last = tokens.length - 1;
|
|
@@ -152,8 +154,12 @@ export function parseMTL(input, options = {}) {
|
|
|
152
154
|
break;
|
|
153
155
|
default: {
|
|
154
156
|
const name = Object.hasOwn(MAPS, key) ? MAPS[key] : key.startsWith('map_') ? keyword : undefined, map = name ? parseMap(tokens, line, from) : null;
|
|
155
|
-
if (name && map)
|
|
157
|
+
if (name && map) {
|
|
156
158
|
material.maps[name] = map;
|
|
159
|
+
const face = map.options.type?.toLowerCase();
|
|
160
|
+
if (name === 'refl' && face && CUBE_FACES.includes(face))
|
|
161
|
+
material.maps[`refl_${face}`] = map;
|
|
162
|
+
}
|
|
157
163
|
else
|
|
158
164
|
material.extras.push({ keyword, value: rest, line });
|
|
159
165
|
}
|
package/dist/render.d.ts
CHANGED
|
@@ -4,10 +4,13 @@ import { type PBRModel } from '@margoengine/gltf/pbr-model';
|
|
|
4
4
|
import type { CreateMeshesOptions } from './engine.js';
|
|
5
5
|
import { type LoadedGeometry } from './types.js';
|
|
6
6
|
/**
|
|
7
|
-
* Options for {@link createPBRMeshes}: `parent` (of the model root), `normals`, `
|
|
8
|
-
* `metalness` (default 0) and `doubleSided` (default true) as for `createMeshes`. Colors
|
|
7
|
+
* Options for {@link createPBRMeshes}: `parent` (of the model root), `normals`, `creaseAngle` (default 40),
|
|
8
|
+
* `roughness` (default 0.6), `metalness` (default 0) and `doubleSided` (default true) as for `createMeshes`. Colors
|
|
9
|
+
* multiply in linear light.
|
|
9
10
|
*/
|
|
10
11
|
export interface CreatePBRMeshesOptions extends Pick<CreateMeshesOptions, 'parent' | 'normals' | 'roughness' | 'metalness' | 'doubleSided'> {
|
|
12
|
+
/** As for `createMeshes`: faces within this many degrees are smoothed together. Default 40. */
|
|
13
|
+
creaseAngle?: number;
|
|
11
14
|
/** Linear RGBA material multiplier in [0,1]. Default white, preserving source colors and opacity. */
|
|
12
15
|
baseColorFactor?: readonly [number, number, number, number];
|
|
13
16
|
/** Use the renderer's existing unlit material. Default false. */
|
|
@@ -21,7 +24,9 @@ export interface CreatePBRMeshesOptions extends Pick<CreateMeshesOptions, 'paren
|
|
|
21
24
|
* Uncovered index ranges render with white/opaque fallback. The explicit material factor multiplies RGBA.
|
|
22
25
|
* Returns the renderer's owned model: dispose it once finished; its existing lifecycle restores GPU resources.
|
|
23
26
|
* The input is never modified. A part past 262,144 vertices (gltf/pbr's default `maxPartVertices`) becomes several primitives of one
|
|
24
|
-
* glTF mesh, split as toGeometries splits (normals seam-free).
|
|
25
|
-
*
|
|
27
|
+
* glTF mesh, split as toGeometries splits (normals seam-free). With vertex colors, neighboring groups that differ in
|
|
28
|
+
* color alone are one part, as their corners already carry it (a scan has a group for almost every color). Point
|
|
29
|
+
* clouds, overlapping groups, more than 4096 parts, or an exceeded packed-data budget are refused before any GPU
|
|
30
|
+
* allocation.
|
|
26
31
|
*/
|
|
27
32
|
export declare function createPBRMeshes(engine: EngineKernel, loaded: LoadedGeometry, options?: CreatePBRMeshesOptions): PBRModel;
|
package/dist/render.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { parsePreparedPBR } from '@margoengine/gltf/pbr-model';
|
|
2
2
|
import { SRGBToLinear } from '@margoengine/math/color';
|
|
3
|
+
import { creased } from './crease.js';
|
|
3
4
|
import { splitTriangles, toGeometries } from './geometry.js';
|
|
4
5
|
/**
|
|
5
6
|
* Vertices of one part: gltf/pbr's default `maxPartVertices` (20 MiB of 80-byte vertices, inside every storage binding,
|
|
@@ -25,19 +26,38 @@ function attribute(value, length, name, bounded = false) {
|
|
|
25
26
|
if (!Number.isFinite(v) || (bounded && (v < 0 || v > 1)))
|
|
26
27
|
range(`${name} must contain finite${bounded ? ' [0,1]' : ''} values`);
|
|
27
28
|
}
|
|
29
|
+
/** What makes two groups different parts when vertex colors carry their color: everything but it and their range. */
|
|
30
|
+
const partKey = ({ start: _start, count: _count, color, ...rest }) => JSON.stringify([rest, color?.[3] ?? 1]);
|
|
31
|
+
/** Joins each run of neighboring groups of one {@link partKey} into the first of them, in place. */
|
|
32
|
+
function joinColorGroups(parts) {
|
|
33
|
+
let kept = 0, last = '';
|
|
34
|
+
for (const part of parts) {
|
|
35
|
+
const key = partKey(part);
|
|
36
|
+
if (kept && key === last)
|
|
37
|
+
parts[kept - 1] = { ...parts[kept - 1], count: parts[kept - 1].count + part.count };
|
|
38
|
+
else {
|
|
39
|
+
parts[kept++] = part;
|
|
40
|
+
last = key;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
parts.length = kept;
|
|
44
|
+
}
|
|
28
45
|
/**
|
|
29
46
|
* Renders triangle loader output with exact per-vertex RGB and opacity through optional `gltf/pbr`.
|
|
30
47
|
* Source RGB is sRGB; opacity is linear. Group RGBA supplies only missing vertex channels, independently.
|
|
31
48
|
* Uncovered index ranges render with white/opaque fallback. The explicit material factor multiplies RGBA.
|
|
32
49
|
* Returns the renderer's owned model: dispose it once finished; its existing lifecycle restores GPU resources.
|
|
33
50
|
* The input is never modified. A part past 262,144 vertices (gltf/pbr's default `maxPartVertices`) becomes several primitives of one
|
|
34
|
-
* glTF mesh, split as toGeometries splits (normals seam-free).
|
|
35
|
-
*
|
|
51
|
+
* glTF mesh, split as toGeometries splits (normals seam-free). With vertex colors, neighboring groups that differ in
|
|
52
|
+
* color alone are one part, as their corners already carry it (a scan has a group for almost every color). Point
|
|
53
|
+
* clouds, overlapping groups, more than 4096 parts, or an exceeded packed-data budget are refused before any GPU
|
|
54
|
+
* allocation.
|
|
36
55
|
*/
|
|
37
56
|
export function createPBRMeshes(engine, loaded, options = {}) {
|
|
38
57
|
if (loaded.kind !== 'mesh')
|
|
39
58
|
throw new LoaderError(format, 'unsupported', 'createPBRMeshes requires triangles; use createMeshes for point markers');
|
|
40
|
-
|
|
59
|
+
let count = loaded.positions?.length / 3, indices = loaded.indices, opacity = loaded.attributes?.opacity;
|
|
60
|
+
const mode = options.normals ?? 'auto', factor = options.baseColorFactor ?? [1, 1, 1, 1], roughness = unit(options.roughness ?? 0.6, 'roughness'), metalness = unit(options.metalness ?? 0, 'metalness'), maxBytes = options.maxBytes ?? 256 * 1024 * 1024;
|
|
41
61
|
if (!Number.isInteger(count) || count < 3)
|
|
42
62
|
range('positions must contain at least three xyz vertices');
|
|
43
63
|
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1)
|
|
@@ -63,6 +83,12 @@ export function createPBRMeshes(engine, loaded, options = {}) {
|
|
|
63
83
|
for (const index of indices)
|
|
64
84
|
if (index >= count)
|
|
65
85
|
range(`index ${index} exceeds the vertex count`);
|
|
86
|
+
if (mode === 'auto') {
|
|
87
|
+
loaded = creased(loaded, options.creaseAngle);
|
|
88
|
+
count = loaded.positions.length / 3;
|
|
89
|
+
indices = loaded.indices;
|
|
90
|
+
opacity = loaded.attributes?.opacity;
|
|
91
|
+
}
|
|
66
92
|
const parts = [];
|
|
67
93
|
let end = 0;
|
|
68
94
|
for (const group of loaded.groups ?? []) {
|
|
@@ -89,6 +115,8 @@ export function createPBRMeshes(engine, loaded, options = {}) {
|
|
|
89
115
|
}
|
|
90
116
|
if (end < indices.length)
|
|
91
117
|
parts.push({ start: end, count: indices.length - end });
|
|
118
|
+
if (loaded.colors)
|
|
119
|
+
joinColorGroups(parts);
|
|
92
120
|
if (parts.length > 4096)
|
|
93
121
|
throw new LoaderError(format, 'limit', 'more than 4096 parts; merge or split the asset');
|
|
94
122
|
// Count before preparing any renderer resources. The same source order is used by toGeometry's compaction.
|