@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.
- package/LICENSE +201 -0
- package/NOTICE +4 -0
- package/README.md +1665 -2
- 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/crease.d.ts +7 -0
- package/dist/crease.js +67 -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-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -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 +166 -0
- package/dist/dae.js +644 -0
- package/dist/detect.d.ts +20 -0
- package/dist/detect.js +72 -0
- 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 +122 -0
- package/dist/dxf.js +985 -0
- package/dist/engine.d.ts +41 -0
- package/dist/engine.js +120 -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 +92 -0
- package/dist/gcode.js +369 -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 +125 -0
- package/dist/mtl.js +550 -0
- package/dist/normals.d.ts +7 -0
- package/dist/normals.js +31 -0
- package/dist/nrrd.d.ts +70 -0
- package/dist/nrrd.js +785 -0
- package/dist/nurbs.d.ts +118 -0
- package/dist/nurbs.js +265 -0
- package/dist/obj.d.ts +145 -0
- package/dist/obj.js +462 -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 +32 -0
- package/dist/render.js +181 -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 +45 -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-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.d.ts +139 -0
- package/dist/threemf-lattice.js +379 -0
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +162 -0
- package/dist/threemf-materials.js +497 -0
- package/dist/threemf-mesh.d.ts +75 -0
- package/dist/threemf-mesh.js +422 -0
- 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 +170 -0
- package/dist/threemf.js +609 -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 +108 -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 +289 -4
package/dist/mtl.js
ADDED
|
@@ -0,0 +1,550 @@
|
|
|
1
|
+
import { CubeTexture, Material, createMesh, loadTexture as loadMaterialTexture, } from '@margoengine/materials';
|
|
2
|
+
import { SRGBToLinear } from '@margoengine/math/color';
|
|
3
|
+
import { DEFAULT_MAX_BYTES, fetchBytes } from './load.js';
|
|
4
|
+
import { assetURL } from './shared/asset-url.js';
|
|
5
|
+
import { captureScene } from './shared/scene-scope.js';
|
|
6
|
+
import { DEFAULT_MAX_MATERIAL_BYTES, parseOBJ, } from './obj.js';
|
|
7
|
+
import { LoaderError } from './types.js';
|
|
8
|
+
import { resolvePath } from './util.js';
|
|
9
|
+
const F = 'MTL';
|
|
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', '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;
|
|
16
|
+
/** PBR-extension statements read from `extras` (compared in lower case); other extras are reported as unused. */
|
|
17
|
+
const READ_EXTRAS = new Set(['norm', 'pr', 'pm']);
|
|
18
|
+
const clamp01 = (v) => Math.min(1, Math.max(0, v));
|
|
19
|
+
/** One sRGB channel as written in the file to linear light: non-finite becomes 0, then clamped to [0, 1]. */
|
|
20
|
+
const linear = (v) => SRGBToLinear(Number.isFinite(v) ? clamp01(v) : 0);
|
|
21
|
+
const linear3 = (c) => [linear(c[0]), linear(c[1]), linear(c[2])];
|
|
22
|
+
/** Value of the first extension statement named `keyword` (any case), or undefined. */
|
|
23
|
+
function extra(m, keyword) {
|
|
24
|
+
return m.extras?.find((s) => s.keyword.toLowerCase() === keyword)?.value;
|
|
25
|
+
}
|
|
26
|
+
/** First number of an extension statement's value, or NaN. */
|
|
27
|
+
function extraNumber(m, keyword) {
|
|
28
|
+
const value = extra(m, keyword);
|
|
29
|
+
return value === undefined ? Number.NaN : Number(value.trim().split(/\s+/)[0]);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Roughness from the Phong exponent Ns. Walter, Marschner, Li and Torrance, "Microfacet Models for Refraction
|
|
33
|
+
* through Rough Surfaces" (EGSR 2007) §5.2 match Blinn-Phong exponent Ns to a Beckmann width alpha with
|
|
34
|
+
* alpha^2 = 2 / (Ns + 2); glTF 2.0 metallic-roughness uses alpha = roughness^2, so roughness = (2 / (Ns + 2))^(1/4).
|
|
35
|
+
* Ns 0 gives 1, 10 about 0.64, 100 about 0.37, 1000 about 0.21.
|
|
36
|
+
*/
|
|
37
|
+
const roughnessFromNs = (ns) => clamp01((2 / (Math.max(0, ns) + 2)) ** 0.25);
|
|
38
|
+
/** The folder of the material's library, recovered from a map whose resolved path ends with its file name. */
|
|
39
|
+
function libraryFolder(m) {
|
|
40
|
+
for (const map of Object.values(m.maps ?? {})) {
|
|
41
|
+
const file = resolvePath('_', map.file);
|
|
42
|
+
if (file && map.path.endsWith(file))
|
|
43
|
+
return map.path.slice(0, map.path.length - file.length);
|
|
44
|
+
}
|
|
45
|
+
return '';
|
|
46
|
+
}
|
|
47
|
+
/** Reads a `norm` statement like a map statement: `-bm n`, `-o u [v [w]]`, `-s u [v [w]]`, `-clamp on|off`, file. */
|
|
48
|
+
function parseNorm(value) {
|
|
49
|
+
const tokens = value.trim().split(/\s+/).filter(Boolean), options = {};
|
|
50
|
+
let i = 0;
|
|
51
|
+
const numbers = (fill) => {
|
|
52
|
+
const out = [fill, fill, fill];
|
|
53
|
+
for (let k = 0; k < 3 && i < tokens.length && Number.isFinite(Number(tokens[i])); k++)
|
|
54
|
+
out[k] = Number(tokens[i++]);
|
|
55
|
+
return out;
|
|
56
|
+
};
|
|
57
|
+
while (i < tokens.length && tokens[i].startsWith('-')) {
|
|
58
|
+
const option = tokens[i++];
|
|
59
|
+
if (option === '-bm')
|
|
60
|
+
options.bm = Number(tokens[i++]);
|
|
61
|
+
else if (option === '-o')
|
|
62
|
+
options.o = numbers(0);
|
|
63
|
+
else if (option === '-s')
|
|
64
|
+
options.s = numbers(1);
|
|
65
|
+
else if (option === '-clamp')
|
|
66
|
+
options.clamp = tokens[i++] === 'on';
|
|
67
|
+
else
|
|
68
|
+
i++; // an option this reader does not use: skip its value
|
|
69
|
+
}
|
|
70
|
+
return { file: tokens.slice(i).join(' '), options };
|
|
71
|
+
}
|
|
72
|
+
/** The `new Material` options of one MTL material (section "MTL material format", illumination models included). */
|
|
73
|
+
function materialOptions(m, doubleSided) {
|
|
74
|
+
const unlit = m.illum === 0, options = { doubleSided };
|
|
75
|
+
if (unlit)
|
|
76
|
+
options.shading = 'basic';
|
|
77
|
+
options.color = m.Kd ? linear3(m.Kd) : [1, 1, 1];
|
|
78
|
+
const written = m.d !== undefined ? m.d : m.Tr !== undefined ? 1 - m.Tr : 1, opacity = Number.isFinite(written) ? clamp01(written) : 1;
|
|
79
|
+
options.opacity = opacity;
|
|
80
|
+
if (opacity < 1 || m.maps?.map_d)
|
|
81
|
+
options.transparent = true;
|
|
82
|
+
if (unlit)
|
|
83
|
+
return options;
|
|
84
|
+
const emit = m.Ke ? [...m.Ke] : m.maps?.map_Ke ? [1, 1, 1] : undefined;
|
|
85
|
+
if (emit) {
|
|
86
|
+
const peak = Math.max(emit[0], emit[1], emit[2]);
|
|
87
|
+
if (peak > 1) {
|
|
88
|
+
for (let k = 0; k < 3; k++)
|
|
89
|
+
emit[k] /= peak;
|
|
90
|
+
options.emissive = linear3(emit);
|
|
91
|
+
options.emissiveIntensity = peak;
|
|
92
|
+
}
|
|
93
|
+
else
|
|
94
|
+
options.emissive = linear3(emit);
|
|
95
|
+
}
|
|
96
|
+
const pr = extraNumber(m, 'pr');
|
|
97
|
+
if (Number.isFinite(pr))
|
|
98
|
+
options.roughness = clamp01(pr);
|
|
99
|
+
else if (m.illum === 1 || (m.Ks && m.Ks.every((c) => c <= 0)) || m.Ns === undefined || !Number.isFinite(m.Ns))
|
|
100
|
+
options.roughness = 1;
|
|
101
|
+
else
|
|
102
|
+
options.roughness = roughnessFromNs(m.Ns);
|
|
103
|
+
const pm = extraNumber(m, 'pm');
|
|
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);
|
|
112
|
+
return options;
|
|
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'));
|
|
116
|
+
/** The maps a material uses, in slot (and load) order: map, alphaMap, emissiveMap, bump or normal, norm. */
|
|
117
|
+
function mapUses(m, bump) {
|
|
118
|
+
const maps = m.maps ?? {}, uses = [];
|
|
119
|
+
const add = (slot, map, colorSpace) => {
|
|
120
|
+
if (map)
|
|
121
|
+
uses.push({ slot, path: map.path, options: map.options ?? {}, colorSpace });
|
|
122
|
+
};
|
|
123
|
+
add('map', maps.map_Kd, 'srgb');
|
|
124
|
+
add('alphaMap', maps.map_d, 'linear');
|
|
125
|
+
add('displacementMap', maps.disp, 'linear');
|
|
126
|
+
if (m.illum === 0)
|
|
127
|
+
return uses;
|
|
128
|
+
if (m.illum !== 1 && !isPBR(m))
|
|
129
|
+
add('specularColorMap', maps.map_Ks, 'srgb');
|
|
130
|
+
add('emissiveMap', maps.map_Ke, 'srgb');
|
|
131
|
+
add(bump === 'normal' ? 'normalMap' : 'bumpMap', maps.bump, 'linear');
|
|
132
|
+
const norm = extra(m, 'norm');
|
|
133
|
+
if (norm !== undefined) {
|
|
134
|
+
const { file, options } = parseNorm(norm);
|
|
135
|
+
if (file)
|
|
136
|
+
add('normalMap', { path: resolvePath(`${libraryFolder(m)}_`, file), options }, 'linear');
|
|
137
|
+
}
|
|
138
|
+
return uses;
|
|
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
|
+
}
|
|
159
|
+
/** What a material says that Margo materials cannot show, as warnings. */
|
|
160
|
+
function unusedWarnings(m) {
|
|
161
|
+
const out = [];
|
|
162
|
+
for (const key of Object.keys(m.maps ?? {}))
|
|
163
|
+
if (!SLOTTED_MAPS.has(key) && !key.startsWith('refl_'))
|
|
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`);
|
|
168
|
+
for (const s of m.extras ?? [])
|
|
169
|
+
if (!READ_EXTRAS.has(s.keyword.toLowerCase()))
|
|
170
|
+
out.push(`${s.keyword} has no Margo material equivalent; it is not used`);
|
|
171
|
+
if (m.Ka)
|
|
172
|
+
out.push('Ka (ambient colour) has no Margo material equivalent; it is not used');
|
|
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');
|
|
175
|
+
return out;
|
|
176
|
+
}
|
|
177
|
+
/**
|
|
178
|
+
* Builds one materials `Material` per `newmtl` of `parseMTL` output (or `parseOBJ`'s `materials`), mapped to
|
|
179
|
+
* metallic-roughness: `Kd` is the base colour (sRGB in the file, linear in the material), `d` (else 1 - `Tr`) the
|
|
180
|
+
* opacity, `Ke` the emission (a peak above 1 moves into `emissiveIntensity`), and roughness comes from the Phong
|
|
181
|
+
* exponent `Ns` as (2 / (Ns + 2))^(1/4) (Walter et al. 2007's Blinn-Phong to Beckmann match with glTF's
|
|
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.
|
|
190
|
+
* Rejects with `TypeError` / `RangeError` for bad arguments and with a `LoaderError` (code `'aborted'`) when
|
|
191
|
+
* `signal` aborts; whatever was built is disposed first.
|
|
192
|
+
*/
|
|
193
|
+
export async function createMTLMaterials(mtl, options = {}) {
|
|
194
|
+
if (!Array.isArray(mtl))
|
|
195
|
+
throw new TypeError('createMTLMaterials mtl is not an array of materials; pass parseMTL output or obj.materials');
|
|
196
|
+
const opts = options ?? {}, bump = opts.bump ?? 'height';
|
|
197
|
+
if (bump !== 'height' && bump !== 'normal')
|
|
198
|
+
throw new RangeError(`createMTLMaterials bump ${JSON.stringify(bump)} is not 'height' or 'normal'; pass one of them`);
|
|
199
|
+
if (opts.loadTexture !== undefined && typeof opts.loadTexture !== 'function')
|
|
200
|
+
throw new TypeError('createMTLMaterials loadTexture is not a function; pass (url, options) => Promise<Texture>');
|
|
201
|
+
const load = opts.loadTexture ?? loadMaterialTexture, signal = opts.signal, get = opts.fetch, doubleSided = opts.doubleSided ?? false;
|
|
202
|
+
const materials = new Map(), warnings = [], arrived = [];
|
|
203
|
+
let disposed = false;
|
|
204
|
+
const warn = (message) => {
|
|
205
|
+
if (!warnings.includes(message))
|
|
206
|
+
warnings.push(message);
|
|
207
|
+
};
|
|
208
|
+
const set = {
|
|
209
|
+
materials,
|
|
210
|
+
textures: [],
|
|
211
|
+
warnings,
|
|
212
|
+
dispose() {
|
|
213
|
+
disposed = true;
|
|
214
|
+
for (const material of materials.values())
|
|
215
|
+
material.dispose();
|
|
216
|
+
for (const texture of arrived)
|
|
217
|
+
texture.dispose();
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
const abortError = () => new LoaderError(F, 'aborted', 'aborted while loading textures');
|
|
221
|
+
let base;
|
|
222
|
+
/** The URL of a map path, or undefined (with a warning) when the URL policy refuses it. */
|
|
223
|
+
const urlOf = (path) => {
|
|
224
|
+
if (base === undefined) {
|
|
225
|
+
const from = opts.baseUrl ?? globalThis.location?.href;
|
|
226
|
+
try {
|
|
227
|
+
base = new URL(String(from)).href;
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
throw new TypeError(`createMTLMaterials baseUrl ${JSON.stringify(String(from))} is not an absolute URL; pass the .mtl (or .obj) URL to resolve maps against`);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
// data: URIs make no request; everything else must stay inside the base's directory or an allowed prefix.
|
|
234
|
+
if (/^data:/i.test(path))
|
|
235
|
+
return path;
|
|
236
|
+
try {
|
|
237
|
+
return assetURL(path, base, opts.allowedURLs, 'MTL texture').href;
|
|
238
|
+
}
|
|
239
|
+
catch (error) {
|
|
240
|
+
warn(`${error.message}; its maps are left out`);
|
|
241
|
+
return undefined;
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
// One request per (colour space, wrap, URL), in first-use order.
|
|
245
|
+
const requests = new Map(), assignments = [], reflections = [];
|
|
246
|
+
const request = (url, colorSpace, wrap) => {
|
|
247
|
+
const key = `${colorSpace} ${wrap} ${url}`;
|
|
248
|
+
if (requests.has(key))
|
|
249
|
+
return key;
|
|
250
|
+
const entry = {
|
|
251
|
+
promise: Promise.resolve()
|
|
252
|
+
.then(() => load(url, { colorSpace, wrapS: wrap, wrapT: wrap, signal, ...(get ? { fetch: get } : {}) }))
|
|
253
|
+
.then((texture) => {
|
|
254
|
+
if (disposed) {
|
|
255
|
+
texture.dispose();
|
|
256
|
+
return undefined;
|
|
257
|
+
}
|
|
258
|
+
arrived.push(texture);
|
|
259
|
+
entry.texture = texture;
|
|
260
|
+
return texture;
|
|
261
|
+
}, (error) => {
|
|
262
|
+
if (signal?.aborted)
|
|
263
|
+
throw abortError();
|
|
264
|
+
warn(`texture ${url} could not be loaded (${error?.message ?? error}); its maps are left out`);
|
|
265
|
+
return undefined;
|
|
266
|
+
}),
|
|
267
|
+
};
|
|
268
|
+
requests.set(key, entry);
|
|
269
|
+
return key;
|
|
270
|
+
};
|
|
271
|
+
let stopListening = () => { };
|
|
272
|
+
try {
|
|
273
|
+
for (const m of mtl) {
|
|
274
|
+
if (!m || typeof m.name !== 'string' || materials.has(m.name))
|
|
275
|
+
continue;
|
|
276
|
+
const material = new Material(materialOptions(m, doubleSided));
|
|
277
|
+
materials.set(m.name, material);
|
|
278
|
+
for (const message of unusedWarnings(m))
|
|
279
|
+
warn(message);
|
|
280
|
+
for (const use of mapUses(m, bump)) {
|
|
281
|
+
const wrap = use.options.clamp ? 'clamp' : 'repeat', url = urlOf(use.path);
|
|
282
|
+
if (url === undefined)
|
|
283
|
+
continue;
|
|
284
|
+
assignments.push({ material, slot: use.slot, key: request(url, use.colorSpace, wrap) });
|
|
285
|
+
if (use.slot === 'bumpMap' && Number.isFinite(use.options.bm))
|
|
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;
|
|
289
|
+
const [ou = 0, ov = 0] = use.options.o ?? [], [su = 1, sv = 1] = use.options.s ?? [];
|
|
290
|
+
if (ou !== 0 || ov !== 0 || su !== 1 || sv !== 1)
|
|
291
|
+
material.setUVTransform({ offset: [ou, ov], scale: [su, sv] }, use.slot);
|
|
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
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const all = Promise.all([...requests.values()].map((r) => r.promise));
|
|
303
|
+
if (signal) {
|
|
304
|
+
const aborted = new Promise((_, reject) => {
|
|
305
|
+
const onAbort = () => reject(abortError());
|
|
306
|
+
if (signal.aborted)
|
|
307
|
+
onAbort();
|
|
308
|
+
else {
|
|
309
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
310
|
+
stopListening = () => signal.removeEventListener('abort', onAbort);
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
all.catch(() => { });
|
|
314
|
+
await Promise.race([all, aborted]);
|
|
315
|
+
}
|
|
316
|
+
else
|
|
317
|
+
await all;
|
|
318
|
+
for (const { material, slot, key } of assignments) {
|
|
319
|
+
const texture = requests.get(key)?.texture;
|
|
320
|
+
if (texture)
|
|
321
|
+
material[slot] = texture;
|
|
322
|
+
}
|
|
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
|
+
];
|
|
352
|
+
return set;
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
set.dispose();
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
finally {
|
|
359
|
+
stopListening();
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
/** A unit normal, or +z for a zero or non-finite one (materials meshes reject zero normals). */
|
|
363
|
+
function unit(out, at, x, y, z) {
|
|
364
|
+
const length = Math.hypot(x, y, z);
|
|
365
|
+
if (length > 0 && Number.isFinite(length)) {
|
|
366
|
+
out[at] = x / length;
|
|
367
|
+
out[at + 1] = y / length;
|
|
368
|
+
out[at + 2] = z / length;
|
|
369
|
+
}
|
|
370
|
+
else {
|
|
371
|
+
out[at] = 0;
|
|
372
|
+
out[at + 1] = 0;
|
|
373
|
+
out[at + 2] = 1;
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* Smooth vertex normals per OBJ position: each triangle's area-weighted face normal is summed into the positions its
|
|
378
|
+
* corners came from, so corners split by UV seams share one normal.
|
|
379
|
+
*/
|
|
380
|
+
function smoothNormals(positions, indices, origin) {
|
|
381
|
+
const vertices = positions.length / 3, from = (v) => (origin ? origin[v] : v);
|
|
382
|
+
let slots = 0;
|
|
383
|
+
for (let v = 0; v < vertices; v++)
|
|
384
|
+
slots = Math.max(slots, from(v) + 1);
|
|
385
|
+
const sums = new Float64Array(slots * 3);
|
|
386
|
+
for (let t = 0; t + 2 < indices.length; t += 3) {
|
|
387
|
+
const a = indices[t] * 3, b = indices[t + 1] * 3, c = indices[t + 2] * 3, e1x = positions[b] - positions[a], e1y = positions[b + 1] - positions[a + 1], e1z = positions[b + 2] - positions[a + 2], e2x = positions[c] - positions[a], e2y = positions[c + 1] - positions[a + 1], e2z = positions[c + 2] - positions[a + 2], nx = e1y * e2z - e1z * e2y, ny = e1z * e2x - e1x * e2z, nz = e1x * e2y - e1y * e2x;
|
|
388
|
+
for (const corner of [indices[t], indices[t + 1], indices[t + 2]]) {
|
|
389
|
+
const s = from(corner) * 3;
|
|
390
|
+
sums[s] += nx;
|
|
391
|
+
sums[s + 1] += ny;
|
|
392
|
+
sums[s + 2] += nz;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
const normals = new Float32Array(vertices * 3);
|
|
396
|
+
for (let v = 0; v < vertices; v++) {
|
|
397
|
+
const s = from(v) * 3;
|
|
398
|
+
unit(normals, v * 3, sums[s], sums[s + 1], sums[s + 2]);
|
|
399
|
+
}
|
|
400
|
+
return normals;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Turns a parsed OBJ and its materials into materials-ready geometry plus one material per slot, without a GPU:
|
|
404
|
+
* groups map to materials by their `usemtl` name. Positions and indices are the OBJ's own arrays. Normals are the
|
|
405
|
+
* OBJ's (normalised) or, without them, smooth normals shared across UV seams; zero normals become +z. UVs go back to
|
|
406
|
+
* OBJ's v-up orientation for flipY textures, and vertex colours from sRGB to linear. Throws a `LoaderError` (code
|
|
407
|
+
* `'unsupported'`) for an OBJ without faces and `TypeError` when `materials` is neither a Map nor a set.
|
|
408
|
+
*/
|
|
409
|
+
export function prepareOBJMesh(obj, materials, options = {}) {
|
|
410
|
+
if (!obj || obj.kind !== 'mesh' || !obj.indices)
|
|
411
|
+
throw new LoaderError('OBJ', 'unsupported', 'the OBJ has no faces to draw as a mesh; draw its points with pointsToGeometry instead');
|
|
412
|
+
const lookup = materials instanceof Map
|
|
413
|
+
? materials
|
|
414
|
+
: materials && materials.materials instanceof Map
|
|
415
|
+
? materials.materials
|
|
416
|
+
: undefined;
|
|
417
|
+
if (!lookup)
|
|
418
|
+
throw new TypeError('prepareOBJMesh materials is not a Map or material set; pass createMTLMaterials output');
|
|
419
|
+
const { positions, indices } = obj, vertices = positions.length / 3;
|
|
420
|
+
let normals;
|
|
421
|
+
if (obj.normals) {
|
|
422
|
+
normals = new Float32Array(vertices * 3);
|
|
423
|
+
for (let v = 0; v < vertices; v++)
|
|
424
|
+
unit(normals, v * 3, obj.normals[v * 3], obj.normals[v * 3 + 1], obj.normals[v * 3 + 2]);
|
|
425
|
+
}
|
|
426
|
+
else
|
|
427
|
+
normals = smoothNormals(positions, indices, obj.positionIndices);
|
|
428
|
+
const geometry = { positions, normals, indices };
|
|
429
|
+
if (obj.uvs) {
|
|
430
|
+
const uvs = Float32Array.from(obj.uvs);
|
|
431
|
+
for (let i = 1; i < uvs.length; i += 2)
|
|
432
|
+
uvs[i] = 1 - uvs[i];
|
|
433
|
+
geometry.uvs = uvs;
|
|
434
|
+
}
|
|
435
|
+
if (obj.colors)
|
|
436
|
+
geometry.colors = obj.colors.map((c) => linear(c));
|
|
437
|
+
const slots = [], slotOf = new Map(), groups = [];
|
|
438
|
+
let fallback = options?.fallback;
|
|
439
|
+
const source = obj.groups?.length ? obj.groups : [{ start: 0, count: indices.length, material: undefined }];
|
|
440
|
+
for (const group of source) {
|
|
441
|
+
if (!group.count)
|
|
442
|
+
continue;
|
|
443
|
+
let material = group.material === undefined ? undefined : lookup.get(group.material);
|
|
444
|
+
if (!material)
|
|
445
|
+
material = fallback ??= new Material();
|
|
446
|
+
let index = slotOf.get(material);
|
|
447
|
+
if (index === undefined) {
|
|
448
|
+
index = slots.push(material) - 1;
|
|
449
|
+
slotOf.set(material, index);
|
|
450
|
+
}
|
|
451
|
+
groups.push({ start: group.start, count: group.count, materialIndex: index });
|
|
452
|
+
}
|
|
453
|
+
geometry.groups = groups;
|
|
454
|
+
return { geometry, materials: slots };
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* `prepareOBJMesh`, then materials' `createMesh` with one material slot per OBJ material. Dispose the mesh with
|
|
458
|
+
* `destroy()`; the materials stay owned by their set.
|
|
459
|
+
*/
|
|
460
|
+
export function createOBJMesh(engine, obj, materials, options = {}) {
|
|
461
|
+
const prepared = prepareOBJMesh(obj, materials, options);
|
|
462
|
+
return createMesh(engine, prepared.geometry, prepared.materials, { renderOrder: options?.renderOrder ?? 0 });
|
|
463
|
+
}
|
|
464
|
+
/**
|
|
465
|
+
* Loads a textured OBJ in one call: fetches the OBJ, then each `mtllib` relative to it, builds the materials with
|
|
466
|
+
* `createMTLMaterials` (textures relative to their library) and the mesh with `createOBJMesh`. A library that cannot
|
|
467
|
+
* be read is a warning. The OBJ is untrusted: its `mtllib` files and textures load only from the OBJ's directory or
|
|
468
|
+
* an `allowedURLs` prefix (a library elsewhere throws a `LoaderError` with code `'url'`, a texture elsewhere is a
|
|
469
|
+
* warning), `init` (headers, credentials) goes only to the OBJ's own origin, and the libraries share the
|
|
470
|
+
* `maxMaterialLibraries` and `maxMaterialBytes` budget (code `'limit'`). Throws `TypeError` when `url` is not absolute
|
|
471
|
+
* and there is no page URL, and the `LoaderError` of a failed fetch or parse. When the mesh cannot be built,
|
|
472
|
+
* everything loaded is disposed first.
|
|
473
|
+
*/
|
|
474
|
+
export async function loadOBJ(engine, url, options = {}) {
|
|
475
|
+
const opts = options ?? {};
|
|
476
|
+
let objUrl;
|
|
477
|
+
try {
|
|
478
|
+
objUrl = new URL(String(url), globalThis.location?.href).href;
|
|
479
|
+
}
|
|
480
|
+
catch {
|
|
481
|
+
throw new TypeError(`loadOBJ url ${JSON.stringify(String(url))} is not an absolute URL; pass the full .obj URL`);
|
|
482
|
+
}
|
|
483
|
+
const fetchOptions = {
|
|
484
|
+
signal: opts.signal,
|
|
485
|
+
maxBytes: opts.maxBytes,
|
|
486
|
+
fetch: opts.fetch,
|
|
487
|
+
init: opts.init,
|
|
488
|
+
};
|
|
489
|
+
// The mesh is made after the awaits below: it goes in the scene this call started in.
|
|
490
|
+
const scope = captureScene(engine), bytes = await fetchBytes(objUrl, fetchOptions);
|
|
491
|
+
const origin = new URL(objUrl).origin, perFile = opts.maxBytes ?? DEFAULT_MAX_BYTES, budget = opts.maxMaterialBytes ?? DEFAULT_MAX_MATERIAL_BYTES;
|
|
492
|
+
let spent = 0;
|
|
493
|
+
const obj = await parseOBJ(bytes, {
|
|
494
|
+
resolve: async (path) => {
|
|
495
|
+
let library;
|
|
496
|
+
try {
|
|
497
|
+
library = assetURL(path, objUrl, opts.allowedURLs, 'OBJ mtllib');
|
|
498
|
+
}
|
|
499
|
+
catch (error) {
|
|
500
|
+
throw new LoaderError('OBJ', 'url', error.message);
|
|
501
|
+
}
|
|
502
|
+
// Headers and credentials are the caller's for the OBJ's own origin; an allowed library elsewhere gets none.
|
|
503
|
+
// The fetch stops at whatever is left of the libraries' shared budget.
|
|
504
|
+
const content = await fetchBytes(library, {
|
|
505
|
+
...fetchOptions,
|
|
506
|
+
init: library.origin === origin ? opts.init : undefined,
|
|
507
|
+
maxBytes: Math.max(0, Math.min(perFile, budget - spent)),
|
|
508
|
+
});
|
|
509
|
+
spent += content.length;
|
|
510
|
+
return content;
|
|
511
|
+
},
|
|
512
|
+
signal: opts.signal,
|
|
513
|
+
maxVertices: opts.maxVertices,
|
|
514
|
+
maxTriangles: opts.maxTriangles,
|
|
515
|
+
maxMaterialLibraries: opts.maxMaterialLibraries,
|
|
516
|
+
maxMaterialBytes: opts.maxMaterialBytes,
|
|
517
|
+
});
|
|
518
|
+
const set = await createMTLMaterials(obj.materials, { ...opts, baseUrl: objUrl });
|
|
519
|
+
const ownFallback = opts.fallback ? undefined : new Material(), fallback = opts.fallback ?? ownFallback;
|
|
520
|
+
let mesh;
|
|
521
|
+
try {
|
|
522
|
+
mesh = scope.run(() => createOBJMesh(engine, obj, set, { fallback, renderOrder: opts.renderOrder ?? 0 }));
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
set.dispose();
|
|
526
|
+
ownFallback?.dispose();
|
|
527
|
+
throw error;
|
|
528
|
+
}
|
|
529
|
+
// The materials, textures and fallback made here go with the mesh, also when its scene removes it (removePlugin,
|
|
530
|
+
// scene or engine disposal) before dispose() is called.
|
|
531
|
+
let released = false;
|
|
532
|
+
const release = () => {
|
|
533
|
+
if (released)
|
|
534
|
+
return;
|
|
535
|
+
released = true;
|
|
536
|
+
set.dispose();
|
|
537
|
+
ownFallback?.dispose();
|
|
538
|
+
};
|
|
539
|
+
mesh.onDispose(release);
|
|
540
|
+
return {
|
|
541
|
+
mesh,
|
|
542
|
+
obj,
|
|
543
|
+
materials: set,
|
|
544
|
+
warnings: [...obj.warnings, ...set.warnings],
|
|
545
|
+
dispose() {
|
|
546
|
+
mesh.destroy();
|
|
547
|
+
release();
|
|
548
|
+
},
|
|
549
|
+
};
|
|
550
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Area-weighted smooth vertex normals for an indexed triangle list. Vertices touched by no
|
|
3
|
+
* non-degenerate triangle get (0, 0, 1).
|
|
4
|
+
*/
|
|
5
|
+
export declare function computeVertexNormals(positions: ArrayLike<number>, indices: ArrayLike<number>): Float32Array;
|
|
6
|
+
/** Unit face normal of triangle `a, b, c` (vertex indices), or (0, 0, 1) when degenerate. */
|
|
7
|
+
export declare function faceNormal(positions: ArrayLike<number>, a: number, b: number, c: number): [number, number, number];
|
package/dist/normals.js
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { accumulateNormals } from './shared/normals.js';
|
|
2
|
+
/**
|
|
3
|
+
* Area-weighted smooth vertex normals for an indexed triangle list. Vertices touched by no
|
|
4
|
+
* non-degenerate triangle get (0, 0, 1).
|
|
5
|
+
*/
|
|
6
|
+
export function computeVertexNormals(positions, indices) {
|
|
7
|
+
const normals = accumulateNormals(positions, indices, new Float64Array(positions.length));
|
|
8
|
+
const out = new Float32Array(positions.length);
|
|
9
|
+
for (let v = 0; v < out.length; v += 3) {
|
|
10
|
+
const length = Math.hypot(normals[v], normals[v + 1], normals[v + 2]);
|
|
11
|
+
if (length > 0 && Number.isFinite(length)) {
|
|
12
|
+
out[v] = normals[v] / length;
|
|
13
|
+
out[v + 1] = normals[v + 1] / length;
|
|
14
|
+
out[v + 2] = normals[v + 2] / length;
|
|
15
|
+
}
|
|
16
|
+
else
|
|
17
|
+
out[v + 2] = 1;
|
|
18
|
+
}
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
/** Unit face normal of triangle `a, b, c` (vertex indices), or (0, 0, 1) when degenerate. */
|
|
22
|
+
export function faceNormal(positions, a, b, c) {
|
|
23
|
+
a *= 3;
|
|
24
|
+
b *= 3;
|
|
25
|
+
c *= 3;
|
|
26
|
+
const ux = positions[b] - positions[a], uy = positions[b + 1] - positions[a + 1], uz = positions[b + 2] - positions[a + 2];
|
|
27
|
+
const vx = positions[c] - positions[a], vy = positions[c + 1] - positions[a + 1], vz = positions[c + 2] - positions[a + 2];
|
|
28
|
+
const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
|
|
29
|
+
const length = Math.hypot(nx, ny, nz);
|
|
30
|
+
return length > 0 && Number.isFinite(length) ? [nx / length, ny / length, nz / length] : [0, 0, 1];
|
|
31
|
+
}
|
package/dist/nrrd.d.ts
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { type AssetResolver } from './types.js';
|
|
2
|
+
import { type BinaryInput } from './util.js';
|
|
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' | 'block';
|
|
5
|
+
/** Samples in the file's own type; 64-bit integers arrive as `Float64Array`, exact up to 2^53. */
|
|
6
|
+
export type NRRDData = Int8Array<ArrayBuffer> | Uint8Array<ArrayBuffer> | Int16Array<ArrayBuffer> | Uint16Array<ArrayBuffer> | Int32Array<ArrayBuffer> | Uint32Array<ArrayBuffer> | Float32Array<ArrayBuffer> | Float64Array<ArrayBuffer>;
|
|
7
|
+
/** Options of {@link parseNRRD}. */
|
|
8
|
+
export interface NRRDOptions {
|
|
9
|
+
/** Reads a detached `data file`, by the path written in the header. A `.nhdr` file needs this. Default none. */
|
|
10
|
+
resolve?: AssetResolver;
|
|
11
|
+
/** Maximum samples in the whole array. Default 536,870,912. */
|
|
12
|
+
maxSamples?: number;
|
|
13
|
+
signal?: AbortSignal;
|
|
14
|
+
}
|
|
15
|
+
/** What {@link parseNRRD} returns. Pass `data`, `dims` and `bounds` to `fig.volume()` of `@margoengine/sciviz`. */
|
|
16
|
+
export interface NRRDVolume {
|
|
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
|
+
*/
|
|
21
|
+
data: NRRDData;
|
|
22
|
+
type: NRRDType;
|
|
23
|
+
/** Bytes per sample of a `block` file (its `block size` field); absent for every other type. */
|
|
24
|
+
blockSize?: number;
|
|
25
|
+
/** The size of every axis in the file, the fastest first. */
|
|
26
|
+
sizes: number[];
|
|
27
|
+
/** Grid size `[nx, ny, nz]` of the spatial axes, padded with 1 for a 1D or 2D file. */
|
|
28
|
+
dims: [number, number, number];
|
|
29
|
+
/** Samples per voxel: the product of the leading non-spatial axes, such as an RGB axis. 1 for a scalar volume. */
|
|
30
|
+
components: number;
|
|
31
|
+
/** Volumes in the file: the product of the axes after the spatial ones, such as time. 1 for one volume. */
|
|
32
|
+
frames: number;
|
|
33
|
+
/** Distance between samples along each spatial axis; 1 where the file gives none. */
|
|
34
|
+
spacing: [number, number, number];
|
|
35
|
+
/** `[0, (nx - 1) * sx, 0, (ny - 1) * sy, 0, (nz - 1) * sz]`: the true proportions, in `spacing` units. */
|
|
36
|
+
bounds: [number, number, number, number, number, number];
|
|
37
|
+
/** Column-major 4x4 from voxel index to `space` coordinates, with the file's origin, rotation and flips. */
|
|
38
|
+
matrix: Float64Array<ArrayBuffer>;
|
|
39
|
+
/** The `space` field, such as `left-posterior-superior`, when the file names one. */
|
|
40
|
+
space?: string;
|
|
41
|
+
/** Every header field by lower-case name, as written. Null prototype. */
|
|
42
|
+
fields: Record<string, string>;
|
|
43
|
+
/** `key:=value` pairs with their escapes undone. Null prototype. */
|
|
44
|
+
meta: Record<string, string>;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Reads a NRRD volume from a `.nrrd` file, or a `.nhdr` header with its detached data through `resolve`. Encodings are
|
|
48
|
+
* raw, ascii, hex, gzip and bzip2, with either byte order, `line skip` and `byte skip` (-1 for the end of a raw file)
|
|
49
|
+
* and one or many data files (a printf pattern or a `LIST`, with `subdim`). Data past what the header needs is
|
|
50
|
+
* ignored, and gzip decoding stops there. `space directions`, `space origin`, `spacings` and `kinds` set `dims`, `spacing`, `bounds` and
|
|
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.
|
|
54
|
+
*
|
|
55
|
+
* @param input The file's bytes.
|
|
56
|
+
* @param options A resolver for detached data, the sample limit and an AbortSignal.
|
|
57
|
+
* @returns The samples in the file's own type and where they sit.
|
|
58
|
+
* @throws LoaderError with code `header`, `syntax`, `truncated`, `range`, `limit`, `aborted`, `zip` or `unsupported`
|
|
59
|
+
* (detached data without `resolve`).
|
|
60
|
+
*
|
|
61
|
+
* @example
|
|
62
|
+
* ```ts
|
|
63
|
+
* import { parseNRRD } from '@margoengine/loaders/nrrd';
|
|
64
|
+
*
|
|
65
|
+
* const header = 'NRRD0004\ntype: uint8\ndimension: 3\nsizes: 2 1 1\nspacings: 2 1 1\nencoding: ascii\n\n';
|
|
66
|
+
* const { data, dims, bounds } = await parseNRRD(new TextEncoder().encode(`${header}10 20\n`));
|
|
67
|
+
* console.log(data, dims, bounds);
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
export declare function parseNRRD(input: BinaryInput, options?: NRRDOptions): Promise<NRRDVolume>;
|