@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/geometry.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
import { Geometry } from '@margoengine/core';
|
|
2
|
+
import { LoaderError } from './types.js';
|
|
3
|
+
import { computeVertexNormals, faceNormal } from './normals.js';
|
|
4
|
+
const F = 'Geometry';
|
|
5
|
+
/**
|
|
6
|
+
* Vertex limit of a core `Geometry`: 11,184,810, the most 24-byte vertices one buffer of WebGPU's default 256 MiB
|
|
7
|
+
* `maxBufferSize` holds (core's own check).
|
|
8
|
+
*/
|
|
9
|
+
export const CORE_MAX_VERTICES = 11_184_810;
|
|
10
|
+
/** Most indices of one part {@link splitTriangles} makes: 67,108,864, a 256 MiB index buffer on a default device. */
|
|
11
|
+
const CORE_MAX_INDICES = 67_108_864;
|
|
12
|
+
/** Points {@link pointsToGeometry} keeps by default (6 marker vertices each, about 1,000,000 vertices). */
|
|
13
|
+
const DEFAULT_MAX_POINTS = 166_666;
|
|
14
|
+
function selectTriangles(loaded, group) {
|
|
15
|
+
const indices = loaded.indices;
|
|
16
|
+
if (loaded.kind !== 'mesh' || !indices?.length)
|
|
17
|
+
throw new LoaderError(F, 'unsupported', 'a point cloud has no triangles; use pointsToGeometry');
|
|
18
|
+
if (group === undefined)
|
|
19
|
+
return indices;
|
|
20
|
+
const range = typeof group === 'number' ? loaded.groups?.[group] : group;
|
|
21
|
+
if (!range)
|
|
22
|
+
throw new LoaderError(F, 'range', `group ${String(group)} does not exist`);
|
|
23
|
+
const { start, count } = range;
|
|
24
|
+
if (!Number.isSafeInteger(start) ||
|
|
25
|
+
!Number.isSafeInteger(count) ||
|
|
26
|
+
start < 0 ||
|
|
27
|
+
count <= 0 ||
|
|
28
|
+
count % 3 ||
|
|
29
|
+
start % 3 ||
|
|
30
|
+
start + count > indices.length)
|
|
31
|
+
throw new LoaderError(F, 'range', `group range ${start}+${count} is not a triangle range inside ${indices.length} indices`);
|
|
32
|
+
return indices.subarray(start, start + count);
|
|
33
|
+
}
|
|
34
|
+
function checkIndices(triangles, vertexCount) {
|
|
35
|
+
for (let i = 0; i < triangles.length; i++)
|
|
36
|
+
if (triangles[i] >= vertexCount)
|
|
37
|
+
throw new LoaderError(F, 'range', `index ${triangles[i]} is outside 0..${vertexCount - 1}`);
|
|
38
|
+
}
|
|
39
|
+
function normalsMode(options) {
|
|
40
|
+
const mode = options.normals ?? 'auto';
|
|
41
|
+
if (mode !== 'auto' && mode !== 'smooth' && mode !== 'flat')
|
|
42
|
+
throw new LoaderError(F, 'range', `unknown normals mode "${String(mode)}"`);
|
|
43
|
+
return mode;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Splits a triangle list into consecutive triangle ranges (offsets into `triangles`) that each use at most
|
|
47
|
+
* `limit` distinct vertices (`flat`: 3 per triangle) and at most 67,108,864 indices (a 256 MiB index buffer). Order is
|
|
48
|
+
* kept, so the ranges concatenate to the input.
|
|
49
|
+
*/
|
|
50
|
+
export function splitTriangles(triangles, vertexCount, flat, limit = CORE_MAX_VERTICES) {
|
|
51
|
+
if (!Number.isSafeInteger(limit) || limit < 3)
|
|
52
|
+
throw new LoaderError(F, 'range', 'limit must be an integer of 3 or more');
|
|
53
|
+
const ranges = [];
|
|
54
|
+
if (flat) {
|
|
55
|
+
const step = Math.min(Math.floor(limit / 3) * 3, CORE_MAX_INDICES);
|
|
56
|
+
for (let start = 0; start < triangles.length; start += step)
|
|
57
|
+
ranges.push({ start, count: Math.min(step, triangles.length - start) });
|
|
58
|
+
if (!ranges.length)
|
|
59
|
+
ranges.push({ start: 0, count: 0 });
|
|
60
|
+
return ranges;
|
|
61
|
+
}
|
|
62
|
+
// stamp[v] is the number (from 1) of the range that last counted vertex v.
|
|
63
|
+
const stamp = new Uint32Array(vertexCount);
|
|
64
|
+
let start = 0, used = 0, id = 1;
|
|
65
|
+
for (let t = 0; t < triangles.length; t += 3) {
|
|
66
|
+
const a = triangles[t], b = triangles[t + 1], c = triangles[t + 2];
|
|
67
|
+
const fresh = Number(stamp[a] !== id) + Number(stamp[b] !== id && b !== a) + Number(stamp[c] !== id && c !== a && c !== b);
|
|
68
|
+
if (used + fresh > limit || t - start >= CORE_MAX_INDICES) {
|
|
69
|
+
ranges.push({ start, count: t - start });
|
|
70
|
+
start = t;
|
|
71
|
+
used = 0;
|
|
72
|
+
id++;
|
|
73
|
+
}
|
|
74
|
+
for (const v of [a, b, c])
|
|
75
|
+
if (stamp[v] !== id) {
|
|
76
|
+
stamp[v] = id;
|
|
77
|
+
used++;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
ranges.push({ start, count: triangles.length - start });
|
|
81
|
+
return ranges;
|
|
82
|
+
}
|
|
83
|
+
/** Normals of every source vertex as toGeometry makes them for the whole triangle list, so parts meet without seams. */
|
|
84
|
+
function sharedNormals(loaded, triangles, mode) {
|
|
85
|
+
const normals = computeVertexNormals(loaded.positions, triangles), file = loaded.normals;
|
|
86
|
+
if (mode === 'smooth' || !file)
|
|
87
|
+
return normals;
|
|
88
|
+
for (let v = 0; v < normals.length; v += 3) {
|
|
89
|
+
const x = file[v], y = file[v + 1], z = file[v + 2], length = Math.hypot(x, y, z);
|
|
90
|
+
if (length > 0 && Number.isFinite(length)) {
|
|
91
|
+
normals[v] = x / length;
|
|
92
|
+
normals[v + 1] = y / length;
|
|
93
|
+
normals[v + 2] = z / length;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return normals;
|
|
97
|
+
}
|
|
98
|
+
function flatGeometry(source, triangles) {
|
|
99
|
+
const positions = new Float32Array(triangles.length * 3), normals = new Float32Array(triangles.length * 3), indices = new Uint32Array(triangles.length);
|
|
100
|
+
for (let t = 0; t < triangles.length; t += 3) {
|
|
101
|
+
const n = faceNormal(source, triangles[t], triangles[t + 1], triangles[t + 2]), nx = n[0], ny = n[1], nz = n[2];
|
|
102
|
+
for (let k = 0; k < 3; k++) {
|
|
103
|
+
const v = triangles[t + k] * 3, o = (t + k) * 3;
|
|
104
|
+
positions[o] = source[v];
|
|
105
|
+
positions[o + 1] = source[v + 1];
|
|
106
|
+
positions[o + 2] = source[v + 2];
|
|
107
|
+
normals[o] = nx;
|
|
108
|
+
normals[o + 1] = ny;
|
|
109
|
+
normals[o + 2] = nz;
|
|
110
|
+
indices[t + k] = t + k;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return build(positions, normals, indices);
|
|
114
|
+
}
|
|
115
|
+
/** Compacts `triangles` to the vertices they use; `shared` (normals per source vertex) replaces normal computation. */
|
|
116
|
+
function compactGeometry(loaded, triangles, mode, shared) {
|
|
117
|
+
const source = loaded.positions, vertexCount = source.length / 3;
|
|
118
|
+
const remap = new Int32Array(vertexCount).fill(-1);
|
|
119
|
+
let used = 0;
|
|
120
|
+
for (let i = 0; i < triangles.length; i++)
|
|
121
|
+
if (remap[triangles[i]] < 0)
|
|
122
|
+
remap[triangles[i]] = used++;
|
|
123
|
+
if (used > CORE_MAX_VERTICES)
|
|
124
|
+
throw new LoaderError(F, 'limit', `${used} vertices exceed the core limit of ${CORE_MAX_VERTICES}; toGeometries splits the mesh`);
|
|
125
|
+
const positions = new Float32Array(used * 3), indices = new Uint32Array(triangles.length);
|
|
126
|
+
for (let v = 0; v < vertexCount; v++) {
|
|
127
|
+
const r = remap[v];
|
|
128
|
+
if (r >= 0) {
|
|
129
|
+
positions[r * 3] = source[v * 3];
|
|
130
|
+
positions[r * 3 + 1] = source[v * 3 + 1];
|
|
131
|
+
positions[r * 3 + 2] = source[v * 3 + 2];
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
for (let i = 0; i < triangles.length; i++)
|
|
135
|
+
indices[i] = remap[triangles[i]];
|
|
136
|
+
if (shared) {
|
|
137
|
+
const normals = new Float32Array(used * 3);
|
|
138
|
+
for (let v = 0; v < vertexCount; v++) {
|
|
139
|
+
const r = remap[v];
|
|
140
|
+
if (r >= 0)
|
|
141
|
+
normals.set(shared.subarray(v * 3, v * 3 + 3), r * 3);
|
|
142
|
+
}
|
|
143
|
+
return build(positions, normals, indices);
|
|
144
|
+
}
|
|
145
|
+
let smooth, normals;
|
|
146
|
+
if (mode === 'auto' && loaded.normals) {
|
|
147
|
+
normals = new Float32Array(used * 3);
|
|
148
|
+
for (let v = 0; v < vertexCount; v++) {
|
|
149
|
+
const r = remap[v];
|
|
150
|
+
if (r < 0)
|
|
151
|
+
continue;
|
|
152
|
+
const x = loaded.normals[v * 3], y = loaded.normals[v * 3 + 1], z = loaded.normals[v * 3 + 2], length = Math.hypot(x, y, z);
|
|
153
|
+
if (length > 0 && Number.isFinite(length)) {
|
|
154
|
+
normals[r * 3] = x / length;
|
|
155
|
+
normals[r * 3 + 1] = y / length;
|
|
156
|
+
normals[r * 3 + 2] = z / length;
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
smooth ??= computeVertexNormals(positions, indices);
|
|
160
|
+
normals.set(smooth.subarray(r * 3, r * 3 + 3), r * 3);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
else
|
|
165
|
+
normals = computeVertexNormals(positions, indices);
|
|
166
|
+
return build(positions, normals, indices);
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Converts a loaded mesh (or one of its groups) to a core `Geometry`, compacting unused vertices and computing
|
|
170
|
+
* normals when the file has none. Colors and UVs are dropped because core geometry stores position and normal only.
|
|
171
|
+
* A core `Geometry` holds at most 11,184,810 vertices; {@link toGeometries} splits larger meshes.
|
|
172
|
+
*/
|
|
173
|
+
export function toGeometry(loaded, options = {}) {
|
|
174
|
+
const mode = normalsMode(options), triangles = selectTriangles(loaded, options.group);
|
|
175
|
+
checkIndices(triangles, loaded.positions.length / 3);
|
|
176
|
+
if (mode === 'flat') {
|
|
177
|
+
if (triangles.length > CORE_MAX_VERTICES)
|
|
178
|
+
throw new LoaderError(F, 'limit', `flat shading needs ${triangles.length} vertices, more than the core limit of ${CORE_MAX_VERTICES}; toGeometries splits the mesh`);
|
|
179
|
+
return flatGeometry(loaded.positions, triangles);
|
|
180
|
+
}
|
|
181
|
+
return compactGeometry(loaded, triangles, mode);
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Like {@link toGeometry}, but a mesh (or group) that needs more than the core limit of 11,184,810 vertices (or
|
|
185
|
+
* `options.maxPartVertices`) comes back as several geometries: consecutive triangle ranges in source order, each within
|
|
186
|
+
* that many vertices and 67,108,864 indices.
|
|
187
|
+
* Smooth normals are computed over the whole mesh first, so the parts meet without seams; a vertex on a cut appears
|
|
188
|
+
* in both parts. A mesh under the limit returns one Geometry, the same as toGeometry's.
|
|
189
|
+
*/
|
|
190
|
+
export function toGeometries(loaded, options = {}) {
|
|
191
|
+
const mode = normalsMode(options), triangles = selectTriangles(loaded, options.group), vertexCount = loaded.positions.length / 3, limit = options.maxPartVertices ?? CORE_MAX_VERTICES;
|
|
192
|
+
if (!Number.isSafeInteger(limit) || limit < 3 || limit > CORE_MAX_VERTICES)
|
|
193
|
+
throw new LoaderError(F, 'range', `maxPartVertices must be an integer from 3 to ${CORE_MAX_VERTICES}`);
|
|
194
|
+
checkIndices(triangles, vertexCount);
|
|
195
|
+
const ranges = splitTriangles(triangles, vertexCount, mode === 'flat', limit);
|
|
196
|
+
const part = (r) => triangles.subarray(r.start, r.start + r.count);
|
|
197
|
+
if (mode === 'flat')
|
|
198
|
+
return ranges.map((r) => flatGeometry(loaded.positions, part(r)));
|
|
199
|
+
if (ranges.length === 1)
|
|
200
|
+
return [compactGeometry(loaded, triangles, mode)];
|
|
201
|
+
const shared = sharedNormals(loaded, triangles, mode);
|
|
202
|
+
return ranges.map((r) => compactGeometry(loaded, part(r), mode, shared));
|
|
203
|
+
}
|
|
204
|
+
function build(positions, normals, indices) {
|
|
205
|
+
for (let i = 0; i < positions.length; i++)
|
|
206
|
+
if (!Number.isFinite(positions[i]))
|
|
207
|
+
throw new LoaderError(F, 'range', `vertex ${Math.floor(i / 3)} has a non-finite position`);
|
|
208
|
+
if (positions.length < 9)
|
|
209
|
+
throw new LoaderError(F, 'range', 'geometry needs at least 3 vertices');
|
|
210
|
+
return new Geometry(positions, normals, indices);
|
|
211
|
+
}
|
|
212
|
+
/**
|
|
213
|
+
* Turns a point cloud into one mesh of small octahedra, because core has no point primitive.
|
|
214
|
+
* Per-point colors are dropped (core geometry has no vertex colors).
|
|
215
|
+
*/
|
|
216
|
+
export function pointsToGeometry(loaded, options = {}) {
|
|
217
|
+
const source = loaded.positions, total = Math.floor(source.length / 3);
|
|
218
|
+
const maxPoints = options.maxPoints ?? DEFAULT_MAX_POINTS;
|
|
219
|
+
if (!Number.isSafeInteger(maxPoints) || maxPoints < 1 || maxPoints * 6 > CORE_MAX_VERTICES)
|
|
220
|
+
throw new LoaderError(F, 'range', `maxPoints must be 1 to ${Math.floor(CORE_MAX_VERTICES / 6)}`);
|
|
221
|
+
const finite = new Uint32Array(total);
|
|
222
|
+
let kept = 0, minX = Infinity, minY = Infinity, minZ = Infinity, maxX = -Infinity, maxY = -Infinity, maxZ = -Infinity;
|
|
223
|
+
for (let i = 0; i < total; i++) {
|
|
224
|
+
const x = source[i * 3], y = source[i * 3 + 1], z = source[i * 3 + 2];
|
|
225
|
+
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
|
|
226
|
+
continue;
|
|
227
|
+
finite[kept++] = i;
|
|
228
|
+
if (x < minX)
|
|
229
|
+
minX = x;
|
|
230
|
+
if (y < minY)
|
|
231
|
+
minY = y;
|
|
232
|
+
if (z < minZ)
|
|
233
|
+
minZ = z;
|
|
234
|
+
if (x > maxX)
|
|
235
|
+
maxX = x;
|
|
236
|
+
if (y > maxY)
|
|
237
|
+
maxY = y;
|
|
238
|
+
if (z > maxZ)
|
|
239
|
+
maxZ = z;
|
|
240
|
+
}
|
|
241
|
+
if (!kept)
|
|
242
|
+
throw new LoaderError(F, 'range', 'the point cloud has no finite points');
|
|
243
|
+
const size = options.size ?? (Math.hypot(maxX - minX, maxY - minY, maxZ - minZ) * 0.004 || 0.01);
|
|
244
|
+
if (!(size > 0) || !Number.isFinite(size))
|
|
245
|
+
throw new LoaderError(F, 'range', 'size must be a positive number');
|
|
246
|
+
const count = Math.min(kept, maxPoints), step = kept / count;
|
|
247
|
+
// Octahedron corners in the order +x -x +y -y +z -z; each corner moves one axis by `size` and its normal is that axis.
|
|
248
|
+
const faces = [0, 2, 4, 2, 1, 4, 1, 3, 4, 3, 0, 4, 2, 0, 5, 1, 2, 5, 3, 1, 5, 0, 3, 5];
|
|
249
|
+
const positions = new Float32Array(count * 18), normals = new Float32Array(count * 18), indices = new Uint32Array(count * 24);
|
|
250
|
+
for (let p = 0; p < count; p++) {
|
|
251
|
+
const i = finite[Math.floor(p * step)] * 3, x = source[i], y = source[i + 1], z = source[i + 2], o = p * 18;
|
|
252
|
+
for (let d = 0; d < 18; d += 3) {
|
|
253
|
+
positions[o + d] = x;
|
|
254
|
+
positions[o + d + 1] = y;
|
|
255
|
+
positions[o + d + 2] = z;
|
|
256
|
+
}
|
|
257
|
+
positions[o] = x + size;
|
|
258
|
+
positions[o + 3] = x - size;
|
|
259
|
+
positions[o + 7] = y + size;
|
|
260
|
+
positions[o + 10] = y - size;
|
|
261
|
+
positions[o + 14] = z + size;
|
|
262
|
+
positions[o + 17] = z - size;
|
|
263
|
+
normals[o] = 1;
|
|
264
|
+
normals[o + 3] = -1;
|
|
265
|
+
normals[o + 7] = 1;
|
|
266
|
+
normals[o + 10] = -1;
|
|
267
|
+
normals[o + 14] = 1;
|
|
268
|
+
normals[o + 17] = -1;
|
|
269
|
+
for (let k = 0; k < 24; k++)
|
|
270
|
+
indices[p * 24 + k] = p * 6 + faces[k];
|
|
271
|
+
}
|
|
272
|
+
return build(positions, normals, indices);
|
|
273
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
export { LoaderError } from './types.js';
|
|
2
|
+
export type { LoadedGeometry, LoadedGroup, ParseLimits, LoaderErrorCode, AssetResolver } from './types.js';
|
|
3
|
+
export { parseOBJ, parseMTL } from './obj.js';
|
|
4
|
+
export type { LoadedOBJ, OBJGroup, OBJParseOptions, OBJMaterialLimits, OBJStatement, MTLMaterial, MTLMap, MTLMapOptions, MTLParseOptions, } from './obj.js';
|
|
5
|
+
export { parseDAE, flattenDAE } from './dae.js';
|
|
6
|
+
export type { LoadedDAE, DAEGeometry, DAEGroup, DAEMaterial, DAEChannel, DAENode, DAEInstance, DAEParseOptions, DAETransform, DAESkin, DAEMorph, DAEAnimation, DAEAnimationChannel, DAEClip, DAEInterpolation, DAESampler, } from './dae.js';
|
|
7
|
+
export { sampleDAESampler } from './dae-animation.js';
|
|
8
|
+
export { daeCameraView, daeEngineLights, daeFrame } from './dae-scene.js';
|
|
9
|
+
export type { DAECamera, DAELight, DAECameraView, DAECameraViewOptions, DAELocalLight, DAEDirectionalLight, DAEEngineLights, DAEEngineLightOptions, } from './dae-scene.js';
|
|
10
|
+
export { poseDAE, morphDAE, bindDAESkin, daeKeyframeClip, daeNodeNames } from './dae-pose.js';
|
|
11
|
+
export type { DAEPose, DAEPoseOptions, DAEMeshGeometry, DAEBone, DAESkinBinding, DAESkinBindingOptions, DAEKeyframe, DAEKeyframeTrack, DAEKeyframeClip, DAEKeyframeClipOptions, } from './dae-pose.js';
|
|
12
|
+
export { parseTMX, tmxLayerQuads } from './tmx.js';
|
|
13
|
+
export type { LoadedTMX, TMXParseOptions, TMXTileset, TMXTilesetRef, TMXLayer, TMXLayerCommon, TMXTileLayer, TMXObjectLayer, TMXObject, TMXProperties, TileQuads, TileQuadsGroup, TileQuadsOptions, } from './tmx.js';
|
|
14
|
+
export type { BinaryInput } from './util.js';
|
|
15
|
+
export { parsePLY, parsePLYHeader } from './ply.js';
|
|
16
|
+
export type { PLYOptions, PLYHeader, PLYElement, PLYProperty } from './ply.js';
|
|
17
|
+
export { parse3MF, THREEMF_UNITS } from './threemf.js';
|
|
18
|
+
export { parseDXF } from './dxf.js';
|
|
19
|
+
export type { DXFOptions, DXFResult, DXFLayer, DXFText, DXFSolid, DXFLines, DXFColor, DXFHatchInput, DXFHatchGeometry, DXFHatchReader, } from './dxf.js';
|
|
20
|
+
export type { ThreeMFOptions, ThreeMFResult } from './threemf.js';
|
|
21
|
+
export { parsePCD, parsePCDHeader } from './pcd.js';
|
|
22
|
+
export type { PCDOptions, PCDHeader, PCDField } from './pcd.js';
|
|
23
|
+
export { parsePMD, parsePMX, parseMMD, parseVMD, sampleVMDBone, vmdBezier } from './mmd.js';
|
|
24
|
+
export type { MMDOptions, VMDOptions, LoadedMMD, MMDMaterial, MMDBone, MMDMorph, MMDRigidBody, MMDJoint, LoadedVMD, VMDBoneTrack, VMDMorphTrack, VMDCameraTrack, } from './mmd.js';
|
|
25
|
+
export { parseX } from './xfile.js';
|
|
26
|
+
export type { XOptions, LoadedX, XMesh, XFrame, XBone, XMaterial, XAnimation, XAnimationSet, XTrack } from './xfile.js';
|
|
27
|
+
export { parseBabylon, flattenBabylon } from './babylon.js';
|
|
28
|
+
export type { BabylonOptions, LoadedBabylon, BabylonMesh, BabylonNode, BabylonTransformNode, BabylonMaterial, BabylonMultiMaterial, BabylonTexture, BabylonCamera, BabylonLight, BabylonSkeleton, BabylonBone, BabylonAnimation, FlattenBabylonOptions, } from './babylon.js';
|
|
29
|
+
export { parseTilt, parseTiltSketch } from './tilt.js';
|
|
30
|
+
export type { TiltOptions, TiltStroke, LoadedTilt } from './tilt.js';
|
|
31
|
+
export { parsePRWM } from './prwm.js';
|
|
32
|
+
export type { PRWMOptions, PRWMGeometry } from './prwm.js';
|
|
33
|
+
export { parseOFF } from './off.js';
|
|
34
|
+
export type { OFFOptions } from './off.js';
|
|
35
|
+
export { parseXYZ } from './xyz.js';
|
|
36
|
+
export type { XYZOptions, XYZLayout } from './xyz.js';
|
|
37
|
+
export { parseVTK } from './vtk.js';
|
|
38
|
+
export type { VTKOptions } from './vtk.js';
|
|
39
|
+
export { parseUSDA, parseUSDZ, readUSDA } from './usdz.js';
|
|
40
|
+
export type { USDOptions, USDValue, USDPrim, USDALayer, USDAReadOptions } from './usdz.js';
|
|
41
|
+
export { decompressLZF } from './lzf.js';
|
|
42
|
+
export { readZipDirectory, readZipEntry, crc32 } from './zip.js';
|
|
43
|
+
export type { ZipEntry, ZipOptions } from './zip.js';
|
|
44
|
+
export { computeVertexNormals, faceNormal } from './normals.js';
|
|
45
|
+
export { toGeometry, toGeometries, splitTriangles, pointsToGeometry, CORE_MAX_VERTICES } from './geometry.js';
|
|
46
|
+
export type { ToGeometryOptions, PointsToGeometryOptions } from './geometry.js';
|
|
47
|
+
export { createMeshes } from './engine.js';
|
|
48
|
+
export type { CreateMeshesOptions, LoadedMeshes } from './engine.js';
|
|
49
|
+
export { fetchBytes, fetchResource, isPrivateHost, load, DEFAULT_MAX_BYTES } from './load.js';
|
|
50
|
+
export type { FetchOptions, FetchedResource } from './load.js';
|
|
51
|
+
export { detectFormat, parseAny } from './detect.js';
|
|
52
|
+
export type { LoaderFormat, AnyOptions } from './detect.js';
|
|
53
|
+
export { parseSTL } from './stl.js';
|
|
54
|
+
export type { STLOptions, STLGeometry, STLMaterialise, STLColor } from './stl.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export { LoaderError } from './types.js';
|
|
2
|
+
export { parseOBJ, parseMTL } from './obj.js';
|
|
3
|
+
export { parseDAE, flattenDAE } from './dae.js';
|
|
4
|
+
export { sampleDAESampler } from './dae-animation.js';
|
|
5
|
+
export { daeCameraView, daeEngineLights, daeFrame } from './dae-scene.js';
|
|
6
|
+
export { poseDAE, morphDAE, bindDAESkin, daeKeyframeClip, daeNodeNames } from './dae-pose.js';
|
|
7
|
+
export { parseTMX, tmxLayerQuads } from './tmx.js';
|
|
8
|
+
export { parsePLY, parsePLYHeader } from './ply.js';
|
|
9
|
+
export { parse3MF, THREEMF_UNITS } from './threemf.js';
|
|
10
|
+
export { parseDXF } from './dxf.js';
|
|
11
|
+
export { parsePCD, parsePCDHeader } from './pcd.js';
|
|
12
|
+
export { parsePMD, parsePMX, parseMMD, parseVMD, sampleVMDBone, vmdBezier } from './mmd.js';
|
|
13
|
+
export { parseX } from './xfile.js';
|
|
14
|
+
export { parseBabylon, flattenBabylon } from './babylon.js';
|
|
15
|
+
export { parseTilt, parseTiltSketch } from './tilt.js';
|
|
16
|
+
export { parsePRWM } from './prwm.js';
|
|
17
|
+
export { parseOFF } from './off.js';
|
|
18
|
+
export { parseXYZ } from './xyz.js';
|
|
19
|
+
export { parseVTK } from './vtk.js';
|
|
20
|
+
export { parseUSDA, parseUSDZ, readUSDA } from './usdz.js';
|
|
21
|
+
export { decompressLZF } from './lzf.js';
|
|
22
|
+
export { readZipDirectory, readZipEntry, crc32 } from './zip.js';
|
|
23
|
+
export { computeVertexNormals, faceNormal } from './normals.js';
|
|
24
|
+
export { toGeometry, toGeometries, splitTriangles, pointsToGeometry, CORE_MAX_VERTICES } from './geometry.js';
|
|
25
|
+
export { createMeshes } from './engine.js';
|
|
26
|
+
export { fetchBytes, fetchResource, isPrivateHost, load, DEFAULT_MAX_BYTES } from './load.js';
|
|
27
|
+
export { detectFormat, parseAny } from './detect.js';
|
|
28
|
+
export { parseSTL } from './stl.js';
|
package/dist/kmz.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { type DAEParseOptions } from './dae.js';
|
|
2
|
+
import { type LoadedGeometry } from './types.js';
|
|
3
|
+
import { type BinaryInput } from './util.js';
|
|
4
|
+
import { type ZipOptions } from './zip.js';
|
|
5
|
+
/** Options of {@link parseKMZ}: zip limits, the COLLADA parser's options and an AbortSignal. */
|
|
6
|
+
export interface KMZOptions extends Pick<ZipOptions, 'maxEntries' | 'maxEntryBytes' | 'maxRatio'>, DAEParseOptions {
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
/**
|
|
9
|
+
* Where the scene's (0, 0, 0) sits on the Earth, in degrees and metres above the WGS84 ellipsoid: each model then gets a
|
|
10
|
+
* `matrix`. `'first'` uses the first model's location. Default: no `matrix`, because a map's projection may be the app's.
|
|
11
|
+
*/
|
|
12
|
+
origin?: {
|
|
13
|
+
longitude: number;
|
|
14
|
+
latitude: number;
|
|
15
|
+
altitude?: number;
|
|
16
|
+
} | 'first';
|
|
17
|
+
}
|
|
18
|
+
/** One `<Model>` of a KML document, or a bare `.dae` of an archive with no document. */
|
|
19
|
+
export interface KMZModel {
|
|
20
|
+
/** The name of the placemark, when it has one. */
|
|
21
|
+
name?: string;
|
|
22
|
+
/** The model's path inside the archive. */
|
|
23
|
+
path: string;
|
|
24
|
+
geometry: LoadedGeometry;
|
|
25
|
+
/** `<Location>`: degrees and metres. */
|
|
26
|
+
location?: {
|
|
27
|
+
longitude: number;
|
|
28
|
+
latitude: number;
|
|
29
|
+
altitude: number;
|
|
30
|
+
};
|
|
31
|
+
/** `<Orientation>`, in degrees. */
|
|
32
|
+
orientation?: {
|
|
33
|
+
heading: number;
|
|
34
|
+
tilt: number;
|
|
35
|
+
roll: number;
|
|
36
|
+
};
|
|
37
|
+
/** `<Scale>`. */
|
|
38
|
+
scale?: [number, number, number];
|
|
39
|
+
/** `<altitudeMode>`, `clampToGround` when the file has none. */
|
|
40
|
+
altitudeMode?: string;
|
|
41
|
+
/**
|
|
42
|
+
* With `origin` and a `<Location>`: the column-major 4x4 that puts `geometry` in the scene, which is Y up, in metres,
|
|
43
|
+
* with x east and z south at the origin. Holds the orientation, the scale, and the Earth's curve between the two places.
|
|
44
|
+
*/
|
|
45
|
+
matrix?: number[];
|
|
46
|
+
}
|
|
47
|
+
/** What {@link parseKMZ} returns. */
|
|
48
|
+
export interface KMZResult {
|
|
49
|
+
models: KMZModel[];
|
|
50
|
+
/** Every path in the archive, such as the textures the models name. */
|
|
51
|
+
files: string[];
|
|
52
|
+
/** Reads a file of the archive, by a path from `files`. */
|
|
53
|
+
read(path: string): Promise<Uint8Array>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Reads a `.kmz` archive: the KML document's `<Model>` elements with their COLLADA files, flattened to one mesh each, and
|
|
57
|
+
* where each sits on the Earth. An archive with no KML document gives every `.dae` it holds. Geometry stays in each
|
|
58
|
+
* model's own space. With `origin`, each located model gets a `matrix` that puts it in a Y-up scene around that point, so
|
|
59
|
+
* models of one archive land in the right places; without it `location` and `orientation` are only returned, for an app
|
|
60
|
+
* with a map projection of its own. Altitudes are taken as metres above the ellipsoid, and `clampToGround` models sit at
|
|
61
|
+
* height 0: no terrain or geoid is known here.
|
|
62
|
+
* Placemark points, lines and polygons are not read.
|
|
63
|
+
*
|
|
64
|
+
* @param input The archive's bytes.
|
|
65
|
+
* @param options Zip limits, the COLLADA options, `origin` and an AbortSignal.
|
|
66
|
+
* @returns The models, the archive's paths and a reader for its files.
|
|
67
|
+
* @throws LoaderError with code `header`, `syntax`, `zip`, `limit` or `aborted`, or what `parseDAE` throws.
|
|
68
|
+
*
|
|
69
|
+
* @example
|
|
70
|
+
* ```ts
|
|
71
|
+
* import { parseKMZ } from '@margoengine/loaders/kmz';
|
|
72
|
+
*
|
|
73
|
+
* const bytes = await (await fetch('/maps/tower.kmz')).arrayBuffer();
|
|
74
|
+
* const { models, read } = await parseKMZ(bytes, { origin: 'first' });
|
|
75
|
+
* console.log(models[0].location, models[0].matrix, (await read(models[0].path)).length);
|
|
76
|
+
* ```
|
|
77
|
+
*/
|
|
78
|
+
export declare function parseKMZ(input: BinaryInput, options?: KMZOptions): Promise<KMZResult>;
|
package/dist/kmz.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
// KMZ archives: the KML document's models, with their COLLADA files and where they sit on the Earth.
|
|
2
|
+
import { flattenDAE, parseDAE } from './dae.js';
|
|
3
|
+
import { LoaderError } from './types.js';
|
|
4
|
+
import { resolvePath, throwIfAborted, toBytes } from './util.js';
|
|
5
|
+
import { decodeXML, readXMLTree } from './xml.js';
|
|
6
|
+
import { readZipDirectory, readZipEntry } from './zip.js';
|
|
7
|
+
const F = 'KMZ';
|
|
8
|
+
const find = (element, name) => {
|
|
9
|
+
for (const child of element.children) {
|
|
10
|
+
if (child.name === name)
|
|
11
|
+
return child;
|
|
12
|
+
const nested = find(child, name);
|
|
13
|
+
if (nested)
|
|
14
|
+
return nested;
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
};
|
|
18
|
+
const all = (element, name, out, owner) => {
|
|
19
|
+
for (const child of element.children) {
|
|
20
|
+
if (child.name === name)
|
|
21
|
+
out.push([child, owner]);
|
|
22
|
+
all(child, name, out, child.name === 'Placemark' ? child : owner);
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
function field(element, name, fallback) {
|
|
26
|
+
const text = element.children.find((child) => child.name === name)?.text.trim();
|
|
27
|
+
if (text === undefined || text === '')
|
|
28
|
+
return fallback;
|
|
29
|
+
const value = Number(text);
|
|
30
|
+
if (!Number.isFinite(value))
|
|
31
|
+
throw new LoaderError(F, 'syntax', `<${name}> holds "${text.slice(0, 32)}"`);
|
|
32
|
+
return value;
|
|
33
|
+
}
|
|
34
|
+
const RADIANS = Math.PI / 180,
|
|
35
|
+
// WGS84 (NIMA TR8350.2): semi-major axis in metres and first eccentricity squared.
|
|
36
|
+
A = 6378137, E2 = (1 / 298.257223563) * (2 - 1 / 298.257223563), dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
|
37
|
+
/** A place's Earth-centred position, and its east, up and south axes, the scene's x, y and z there. */
|
|
38
|
+
function frame(longitude, latitude, height) {
|
|
39
|
+
const lon = longitude * RADIANS, lat = latitude * RADIANS, [sinLon, cosLon, sinLat, cosLat] = [Math.sin(lon), Math.cos(lon), Math.sin(lat), Math.cos(lat)], n = A / Math.sqrt(1 - E2 * sinLat * sinLat);
|
|
40
|
+
return {
|
|
41
|
+
at: [(n + height) * cosLat * cosLon, (n + height) * cosLat * sinLon, (n * (1 - E2) + height) * sinLat],
|
|
42
|
+
axes: [
|
|
43
|
+
[-sinLon, cosLon, 0],
|
|
44
|
+
[cosLat * cosLon, cosLat * sinLon, sinLat],
|
|
45
|
+
[sinLat * cosLon, sinLat * sinLon, -cosLat],
|
|
46
|
+
],
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/** KML's altitude taken as metres above the ellipsoid; `clampToGround` ignores it, and there is no terrain to clamp to. */
|
|
50
|
+
const heightOf = ({ location, altitudeMode }) => altitudeMode === 'clampToGround' ? 0 : (location?.altitude ?? 0);
|
|
51
|
+
/** `a * b` of 3x3 matrices, each three columns. */
|
|
52
|
+
const times = (a, b) => b.map((column) => [0, 1, 2].map((r) => a[0][r] * column[0] + a[1][r] * column[1] + a[2][r] * column[2]));
|
|
53
|
+
/**
|
|
54
|
+
* The matrix of one model. KML's model axes are x east, y north, z up, and COLLADA's flatten turned them to x east, y up,
|
|
55
|
+
* z south. KML rolls about y, tilts about x, then turns by heading clockwise from north seen from above; roll and tilt
|
|
56
|
+
* are positive clockwise looking along their axes, which is the right-hand rule.
|
|
57
|
+
*/
|
|
58
|
+
function placed(model, origin) {
|
|
59
|
+
const { longitude, latitude, altitude } = model.location, here = frame(longitude, latitude, heightOf(model)), base = frame(origin.longitude, origin.latitude, origin.altitude ?? 0), offset = [here.at[0] - base.at[0], here.at[1] - base.at[1], here.at[2] - base.at[2]],
|
|
60
|
+
// Columns: this place's east, up and south seen in the origin's axes.
|
|
61
|
+
curve = here.axes.map((axis) => base.axes.map((ref) => dot(axis, ref))), { heading = 0, tilt = 0, roll = 0 } = model.orientation ?? {}, [sx, sy, sz] = model.scale ?? [1, 1, 1], [h, t, r] = [heading * RADIANS, tilt * RADIANS, roll * RADIANS],
|
|
62
|
+
// Turning clockwise about up is -h about the scene's y; about KML's y, which is north, -r about the scene's z.
|
|
63
|
+
turn = [
|
|
64
|
+
[Math.cos(h), 0, Math.sin(h)],
|
|
65
|
+
[0, 1, 0],
|
|
66
|
+
[-Math.sin(h), 0, Math.cos(h)],
|
|
67
|
+
], pitch = [
|
|
68
|
+
[1, 0, 0],
|
|
69
|
+
[0, Math.cos(t), Math.sin(t)],
|
|
70
|
+
[0, -Math.sin(t), Math.cos(t)],
|
|
71
|
+
], lean = [
|
|
72
|
+
[Math.cos(r), -Math.sin(r), 0],
|
|
73
|
+
[Math.sin(r), Math.cos(r), 0],
|
|
74
|
+
[0, 0, 1],
|
|
75
|
+
], rotation = times(curve, times(turn, times(pitch, lean))),
|
|
76
|
+
// KML's y scale is the scene's z, and its z the scene's y.
|
|
77
|
+
scaled = [sx, sz, sy].map((size, i) => rotation[i].map((value) => value * size));
|
|
78
|
+
return [...scaled[0], 0, ...scaled[1], 0, ...scaled[2], 0, ...base.axes.map((axis) => dot(axis, offset)), 1];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Reads a `.kmz` archive: the KML document's `<Model>` elements with their COLLADA files, flattened to one mesh each, and
|
|
82
|
+
* where each sits on the Earth. An archive with no KML document gives every `.dae` it holds. Geometry stays in each
|
|
83
|
+
* model's own space. With `origin`, each located model gets a `matrix` that puts it in a Y-up scene around that point, so
|
|
84
|
+
* models of one archive land in the right places; without it `location` and `orientation` are only returned, for an app
|
|
85
|
+
* with a map projection of its own. Altitudes are taken as metres above the ellipsoid, and `clampToGround` models sit at
|
|
86
|
+
* height 0: no terrain or geoid is known here.
|
|
87
|
+
* Placemark points, lines and polygons are not read.
|
|
88
|
+
*
|
|
89
|
+
* @param input The archive's bytes.
|
|
90
|
+
* @param options Zip limits, the COLLADA options, `origin` and an AbortSignal.
|
|
91
|
+
* @returns The models, the archive's paths and a reader for its files.
|
|
92
|
+
* @throws LoaderError with code `header`, `syntax`, `zip`, `limit` or `aborted`, or what `parseDAE` throws.
|
|
93
|
+
*
|
|
94
|
+
* @example
|
|
95
|
+
* ```ts
|
|
96
|
+
* import { parseKMZ } from '@margoengine/loaders/kmz';
|
|
97
|
+
*
|
|
98
|
+
* const bytes = await (await fetch('/maps/tower.kmz')).arrayBuffer();
|
|
99
|
+
* const { models, read } = await parseKMZ(bytes, { origin: 'first' });
|
|
100
|
+
* console.log(models[0].location, models[0].matrix, (await read(models[0].path)).length);
|
|
101
|
+
* ```
|
|
102
|
+
*/
|
|
103
|
+
export async function parseKMZ(input, options = {}) {
|
|
104
|
+
const bytes = toBytes(input, F);
|
|
105
|
+
throwIfAborted(options.signal, F);
|
|
106
|
+
if (bytes.length < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4b)
|
|
107
|
+
throw new LoaderError(F, 'header', 'not a ZIP archive (missing PK signature)');
|
|
108
|
+
const entries = readZipDirectory(bytes, options), byPath = new Map();
|
|
109
|
+
for (const entry of entries)
|
|
110
|
+
byPath.set(entry.name.replaceAll('\\', '/').toLowerCase(), entry);
|
|
111
|
+
const read = async (path) => {
|
|
112
|
+
const entry = byPath.get(path
|
|
113
|
+
.replaceAll('\\', '/')
|
|
114
|
+
.replace(/^\.?\/+/, '')
|
|
115
|
+
.toLowerCase());
|
|
116
|
+
if (!entry)
|
|
117
|
+
throw new LoaderError(F, 'syntax', `"${path.slice(0, 128)}" is not in the archive`);
|
|
118
|
+
return readZipEntry(bytes, entry, options);
|
|
119
|
+
};
|
|
120
|
+
const load = async (path) => {
|
|
121
|
+
throwIfAborted(options.signal, F);
|
|
122
|
+
return flattenDAE(parseDAE(await read(path), options));
|
|
123
|
+
};
|
|
124
|
+
const document = entries.find((entry) => /(^|\/)doc\.kml$/i.test(entry.name)) ?? entries.find((entry) => /\.kml$/i.test(entry.name));
|
|
125
|
+
const models = [];
|
|
126
|
+
if (document) {
|
|
127
|
+
const tree = readXMLTree(decodeXML(await readZipEntry(bytes, document, options)), F, {
|
|
128
|
+
external: options.external,
|
|
129
|
+
}), found = [];
|
|
130
|
+
all(tree, 'Model', found);
|
|
131
|
+
for (const [model, placemark] of found) {
|
|
132
|
+
const href = find(model, 'href')?.text.trim();
|
|
133
|
+
if (!href)
|
|
134
|
+
throw new LoaderError(F, 'syntax', '<Model> has no <Link> href');
|
|
135
|
+
const path = resolvePath(document.name, href), entry = { path, geometry: await load(path) }, name = placemark?.children.find((child) => child.name === 'name')?.text.trim(), location = model.children.find((child) => child.name === 'Location'), orientation = model.children.find((child) => child.name === 'Orientation'), scale = model.children.find((child) => child.name === 'Scale');
|
|
136
|
+
if (name)
|
|
137
|
+
entry.name = name;
|
|
138
|
+
if (location)
|
|
139
|
+
entry.location = {
|
|
140
|
+
longitude: field(location, 'longitude', 0),
|
|
141
|
+
latitude: field(location, 'latitude', 0),
|
|
142
|
+
altitude: field(location, 'altitude', 0),
|
|
143
|
+
};
|
|
144
|
+
if (orientation)
|
|
145
|
+
entry.orientation = {
|
|
146
|
+
heading: field(orientation, 'heading', 0),
|
|
147
|
+
tilt: field(orientation, 'tilt', 0),
|
|
148
|
+
roll: field(orientation, 'roll', 0),
|
|
149
|
+
};
|
|
150
|
+
if (scale)
|
|
151
|
+
entry.scale = [field(scale, 'x', 1), field(scale, 'y', 1), field(scale, 'z', 1)];
|
|
152
|
+
if (location)
|
|
153
|
+
entry.altitudeMode =
|
|
154
|
+
model.children.find((child) => /^(gx:)?altitudeMode$/.test(child.name))?.text.trim() ||
|
|
155
|
+
location.children.find((child) => /^(gx:)?altitudeMode$/.test(child.name))?.text.trim() ||
|
|
156
|
+
'clampToGround';
|
|
157
|
+
models.push(entry);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
else
|
|
161
|
+
for (const entry of entries)
|
|
162
|
+
if (/\.dae$/i.test(entry.name))
|
|
163
|
+
models.push({ path: entry.name, geometry: await load(entry.name) });
|
|
164
|
+
if (!models.length)
|
|
165
|
+
throw new LoaderError(F, 'syntax', 'the archive holds no model');
|
|
166
|
+
const located = models.filter((model) => model.location), origin = options.origin === 'first' && located[0]
|
|
167
|
+
? { ...located[0].location, altitude: heightOf(located[0]) }
|
|
168
|
+
: options.origin;
|
|
169
|
+
if (origin && origin !== 'first')
|
|
170
|
+
for (const model of located)
|
|
171
|
+
model.matrix = placed(model, origin);
|
|
172
|
+
return { models, files: entries.map((entry) => entry.name), read };
|
|
173
|
+
}
|