@margoengine/loaders 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1198 -3
  4. package/dist/3dm.d.ts +161 -0
  5. package/dist/3dm.js +289 -0
  6. package/dist/3ds.d.ts +124 -0
  7. package/dist/3ds.js +392 -0
  8. package/dist/acclaim.d.ts +90 -0
  9. package/dist/acclaim.js +312 -0
  10. package/dist/amf.d.ts +45 -0
  11. package/dist/amf.js +256 -0
  12. package/dist/babylon.d.ts +197 -0
  13. package/dist/babylon.js +701 -0
  14. package/dist/common.d.ts +7 -0
  15. package/dist/common.js +6 -0
  16. package/dist/dae-animation.d.ts +66 -0
  17. package/dist/dae-animation.js +266 -0
  18. package/dist/dae-common.d.ts +95 -0
  19. package/dist/dae-common.js +226 -0
  20. package/dist/dae-controllers.d.ts +57 -0
  21. package/dist/dae-controllers.js +164 -0
  22. package/dist/dae-pose.d.ts +131 -0
  23. package/dist/dae-pose.js +381 -0
  24. package/dist/dae-scene.d.ts +203 -0
  25. package/dist/dae-scene.js +279 -0
  26. package/dist/dae.d.ts +161 -0
  27. package/dist/dae.js +633 -0
  28. package/dist/detect.d.ts +20 -0
  29. package/dist/detect.js +72 -0
  30. package/dist/dxf.d.ts +81 -0
  31. package/dist/dxf.js +774 -0
  32. package/dist/engine.d.ts +36 -0
  33. package/dist/engine.js +117 -0
  34. package/dist/font-opentype.d.ts +14 -0
  35. package/dist/font-opentype.js +33 -0
  36. package/dist/font-woff.d.ts +23 -0
  37. package/dist/font-woff.js +293 -0
  38. package/dist/font.d.ts +41 -0
  39. package/dist/font.js +26 -0
  40. package/dist/gcode.d.ts +55 -0
  41. package/dist/gcode.js +278 -0
  42. package/dist/geo-model.d.ts +84 -0
  43. package/dist/geo-model.js +220 -0
  44. package/dist/geo-mvt.d.ts +15 -0
  45. package/dist/geo-mvt.js +302 -0
  46. package/dist/geo-shp.d.ts +15 -0
  47. package/dist/geo-shp.js +234 -0
  48. package/dist/geo-xml.d.ts +6 -0
  49. package/dist/geo-xml.js +165 -0
  50. package/dist/geo.d.ts +8 -0
  51. package/dist/geo.js +59 -0
  52. package/dist/geometry.d.ts +60 -0
  53. package/dist/geometry.js +273 -0
  54. package/dist/index.d.ts +54 -0
  55. package/dist/index.js +28 -0
  56. package/dist/kmz.d.ts +78 -0
  57. package/dist/kmz.js +173 -0
  58. package/dist/las.d.ts +92 -0
  59. package/dist/las.js +110 -0
  60. package/dist/ldraw.d.ts +118 -0
  61. package/dist/ldraw.js +474 -0
  62. package/dist/load.d.ts +72 -0
  63. package/dist/load.js +205 -0
  64. package/dist/lottie.d.ts +154 -0
  65. package/dist/lottie.js +893 -0
  66. package/dist/lwo.d.ts +81 -0
  67. package/dist/lwo.js +454 -0
  68. package/dist/lzf.d.ts +13 -0
  69. package/dist/lzf.js +56 -0
  70. package/dist/materialx.d.ts +120 -0
  71. package/dist/materialx.js +563 -0
  72. package/dist/md2.d.ts +52 -0
  73. package/dist/md2.js +112 -0
  74. package/dist/mmcif.d.ts +14 -0
  75. package/dist/mmcif.js +246 -0
  76. package/dist/mmd.d.ts +244 -0
  77. package/dist/mmd.js +958 -0
  78. package/dist/mocap.d.ts +71 -0
  79. package/dist/mocap.js +178 -0
  80. package/dist/molecule-common.d.ts +4 -0
  81. package/dist/molecule-common.js +54 -0
  82. package/dist/mtl.d.ts +120 -0
  83. package/dist/mtl.js +469 -0
  84. package/dist/normals.d.ts +7 -0
  85. package/dist/normals.js +31 -0
  86. package/dist/nrrd.d.ts +63 -0
  87. package/dist/nrrd.js +743 -0
  88. package/dist/nurbs.d.ts +118 -0
  89. package/dist/nurbs.js +265 -0
  90. package/dist/obj.d.ts +143 -0
  91. package/dist/obj.js +456 -0
  92. package/dist/off.d.ts +10 -0
  93. package/dist/off.js +155 -0
  94. package/dist/outline-font.d.ts +87 -0
  95. package/dist/outline-font.js +110 -0
  96. package/dist/outline.d.ts +20 -0
  97. package/dist/outline.js +215 -0
  98. package/dist/pcd.d.ts +34 -0
  99. package/dist/pcd.js +258 -0
  100. package/dist/pdb.d.ts +67 -0
  101. package/dist/pdb.js +126 -0
  102. package/dist/ply.d.ts +35 -0
  103. package/dist/ply.js +392 -0
  104. package/dist/polygon.d.ts +9 -0
  105. package/dist/polygon.js +49 -0
  106. package/dist/prwm.d.ts +24 -0
  107. package/dist/prwm.js +114 -0
  108. package/dist/render.d.ts +27 -0
  109. package/dist/render.js +153 -0
  110. package/dist/sfnt-cff.d.ts +37 -0
  111. package/dist/sfnt-cff.js +749 -0
  112. package/dist/sfnt-layout.d.ts +24 -0
  113. package/dist/sfnt-layout.js +266 -0
  114. package/dist/sfnt-reader.d.ts +28 -0
  115. package/dist/sfnt-reader.js +87 -0
  116. package/dist/sfnt-variation.d.ts +40 -0
  117. package/dist/sfnt-variation.js +318 -0
  118. package/dist/shared/asset-url.js +82 -0
  119. package/dist/shared/crc32.d.ts +2 -0
  120. package/dist/shared/crc32.js +47 -0
  121. package/dist/shared/errors.js +36 -0
  122. package/dist/shared/inflate.js +284 -0
  123. package/dist/shared/normals.js +26 -0
  124. package/dist/shared/scene-scope.js +56 -0
  125. package/dist/shared/trailing-data.js +42 -0
  126. package/dist/stl.d.ts +64 -0
  127. package/dist/stl.js +309 -0
  128. package/dist/svg.d.ts +90 -0
  129. package/dist/svg.js +1007 -0
  130. package/dist/tds.d.ts +2 -0
  131. package/dist/tds.js +2 -0
  132. package/dist/textures.d.ts +42 -0
  133. package/dist/textures.js +53 -0
  134. package/dist/threemf-lattice.d.ts +139 -0
  135. package/dist/threemf-lattice.js +514 -0
  136. package/dist/threemf-materials.d.ts +75 -0
  137. package/dist/threemf-materials.js +314 -0
  138. package/dist/threemf-mesh.d.ts +60 -0
  139. package/dist/threemf-mesh.js +201 -0
  140. package/dist/threemf.d.ts +101 -0
  141. package/dist/threemf.js +415 -0
  142. package/dist/tilt.d.ts +62 -0
  143. package/dist/tilt.js +186 -0
  144. package/dist/tmx.d.ts +151 -0
  145. package/dist/tmx.js +394 -0
  146. package/dist/ttf.d.ts +78 -0
  147. package/dist/ttf.js +568 -0
  148. package/dist/types.d.ts +90 -0
  149. package/dist/types.js +35 -0
  150. package/dist/usd.d.ts +2 -0
  151. package/dist/usd.js +2 -0
  152. package/dist/usd.worker.d.ts +1 -0
  153. package/dist/usdz.d.ts +50 -0
  154. package/dist/usdz.js +646 -0
  155. package/dist/util.d.ts +75 -0
  156. package/dist/util.js +241 -0
  157. package/dist/vdb.d.ts +111 -0
  158. package/dist/vdb.js +663 -0
  159. package/dist/vrml.d.ts +53 -0
  160. package/dist/vrml.js +532 -0
  161. package/dist/vtk-cells.d.ts +29 -0
  162. package/dist/vtk-cells.js +211 -0
  163. package/dist/vtk-legacy.d.ts +57 -0
  164. package/dist/vtk-legacy.js +439 -0
  165. package/dist/vtk-reader.d.ts +19 -0
  166. package/dist/vtk-reader.js +134 -0
  167. package/dist/vtk-xml.d.ts +96 -0
  168. package/dist/vtk-xml.js +578 -0
  169. package/dist/vtk.d.ts +13 -0
  170. package/dist/vtk.js +234 -0
  171. package/dist/woff-glyf.d.ts +17 -0
  172. package/dist/woff-glyf.js +215 -0
  173. package/dist/worker.d.ts +10 -0
  174. package/dist/worker.js +93 -0
  175. package/dist/workers/usd.js +3 -0
  176. package/dist/xfile.d.ts +99 -0
  177. package/dist/xfile.js +706 -0
  178. package/dist/xml.d.ts +107 -0
  179. package/dist/xml.js +843 -0
  180. package/dist/xyz.d.ts +16 -0
  181. package/dist/xyz.js +110 -0
  182. package/dist/zip.d.ts +38 -0
  183. package/dist/zip.js +150 -0
  184. package/package.json +246 -6
@@ -0,0 +1,165 @@
1
+ import { LoaderError } from './types.js';
2
+ import { toBytes, throwIfAborted } from './util.js';
3
+ import { readXMLTree, decodeXML } from './xml.js';
4
+ import { buildGeo, GEO, geoText, } from './geo-model.js';
5
+ const child = (e, name) => e.children.find((c) => c.name === name);
6
+ const children = (e, name) => e.children.filter((c) => c.name === name);
7
+ const content = (e, name) => child(e, name)?.text.trim();
8
+ const all = (e, name) => e.children.flatMap((c) => [...(c.name === name ? [c] : []), ...all(c, name)]);
9
+ function xml(input, options) {
10
+ throwIfAborted(options.signal, GEO);
11
+ const source = typeof input === 'string' ? geoText(input, options) : decodeXML(toBytes(input, GEO));
12
+ geoText(typeof input === 'string' ? input : toBytes(input, GEO), options);
13
+ const root = readXMLTree(source, GEO, { external: options.external });
14
+ if (root.children.length !== 1)
15
+ throw new LoaderError(GEO, 'syntax', 'vector XML requires exactly one document element');
16
+ return root.children[0];
17
+ }
18
+ function properties(e) {
19
+ const result = Object.create(null);
20
+ for (const name of [
21
+ 'name',
22
+ 'desc',
23
+ 'description',
24
+ 'cmt',
25
+ 'time',
26
+ 'type',
27
+ 'sym',
28
+ 'number',
29
+ 'styleUrl',
30
+ 'altitudeMode',
31
+ ]) {
32
+ const value = content(e, name);
33
+ if (value !== undefined)
34
+ result[name] = value;
35
+ }
36
+ for (const item of all(e, 'Data'))
37
+ if (item.attributes.name)
38
+ result[item.attributes.name] = content(item, 'value') ?? '';
39
+ for (const item of all(e, 'SimpleData'))
40
+ if (item.attributes.name)
41
+ result[item.attributes.name] = item.text.trim();
42
+ return result;
43
+ }
44
+ function coordinate(e) {
45
+ if (!e.attributes.lon?.trim() || !e.attributes.lat?.trim())
46
+ throw new LoaderError(GEO, 'syntax', 'GPX points require lat and lon');
47
+ const lon = Number(e.attributes.lon), lat = Number(e.attributes.lat), ele = content(e, 'ele');
48
+ if (!Number.isFinite(lon) || !Number.isFinite(lat) || lon < -180 || lon > 180 || lat < -90 || lat > 90)
49
+ throw new LoaderError(GEO, 'range', 'GPX lat/lon is out of range');
50
+ return ele === undefined ? [lon, lat] : [lon, lat, Number(ele)];
51
+ }
52
+ function routeGeometry(coords) {
53
+ return coords.length === 0
54
+ ? null
55
+ : coords.length === 1
56
+ ? { type: 'Point', coordinates: coords[0] }
57
+ : { type: 'LineString', coordinates: coords };
58
+ }
59
+ /** Reads GPX 1.0/1.1 waypoints, routes and separate track segments, keeping elevations and timestamps. */
60
+ export function parseGPX(input, options = {}) {
61
+ const root = xml(input, options);
62
+ if (root.name !== 'gpx')
63
+ throw new LoaderError(GEO, 'header', 'expected a gpx document');
64
+ const features = [];
65
+ for (const e of root.children) {
66
+ if (e.name === 'wpt')
67
+ features.push({
68
+ type: 'Feature',
69
+ properties: properties(e),
70
+ geometry: { type: 'Point', coordinates: coordinate(e) },
71
+ });
72
+ else if (e.name === 'rte') {
73
+ const rows = children(e, 'rtept'), props = properties(e);
74
+ props.times = rows.map((p) => content(p, 'time') ?? null);
75
+ features.push({
76
+ type: 'Feature',
77
+ properties: props,
78
+ geometry: routeGeometry(rows.map(coordinate)),
79
+ });
80
+ }
81
+ else if (e.name === 'trk') {
82
+ const segments = children(e, 'trkseg').map((s) => children(s, 'trkpt')), props = properties(e);
83
+ props.times = segments.map((s) => s.map((p) => content(p, 'time') ?? null));
84
+ features.push({
85
+ type: 'Feature',
86
+ properties: props,
87
+ geometry: {
88
+ type: 'GeometryCollection',
89
+ geometries: segments.map((s) => routeGeometry(s.map(coordinate))).filter((g) => g !== null),
90
+ },
91
+ });
92
+ }
93
+ }
94
+ return buildGeo(features, options);
95
+ }
96
+ function kmlCoordinates(e) {
97
+ const text = content(e, 'coordinates');
98
+ if (!text)
99
+ throw new LoaderError(GEO, 'syntax', `KML ${e.name} needs coordinates`);
100
+ return text.split(/\s+/).map((tuple) => {
101
+ const values = tuple.split(',');
102
+ if (values.length < 2 || values.length > 3 || values.some((v) => !v.trim()))
103
+ throw new LoaderError(GEO, 'syntax', 'KML coordinate needs longitude, latitude and optional altitude');
104
+ return values.map(Number);
105
+ });
106
+ }
107
+ function kmlGeometry(e) {
108
+ if (e.name === 'Point') {
109
+ const points = kmlCoordinates(e);
110
+ if (points.length !== 1)
111
+ throw new LoaderError(GEO, 'syntax', 'KML Point needs one coordinate');
112
+ return { type: 'Point', coordinates: points[0] };
113
+ }
114
+ if (e.name === 'LineString' || e.name === 'LinearRing')
115
+ return { type: 'LineString', coordinates: kmlCoordinates(e) };
116
+ if (e.name === 'Polygon') {
117
+ const outer = child(e, 'outerBoundaryIs'), ring = outer && child(outer, 'LinearRing');
118
+ if (!ring)
119
+ throw new LoaderError(GEO, 'syntax', 'KML Polygon needs outerBoundaryIs/LinearRing');
120
+ const rings = [kmlCoordinates(ring)];
121
+ for (const hole of children(e, 'innerBoundaryIs')) {
122
+ const inner = child(hole, 'LinearRing');
123
+ if (!inner)
124
+ throw new LoaderError(GEO, 'syntax', 'KML inner boundary needs LinearRing');
125
+ rings.push(kmlCoordinates(inner));
126
+ }
127
+ return { type: 'Polygon', coordinates: rings };
128
+ }
129
+ if (e.name === 'MultiGeometry')
130
+ return {
131
+ type: 'GeometryCollection',
132
+ geometries: e.children.map(kmlGeometry).filter((g) => g !== null),
133
+ };
134
+ if (e.name === 'Track')
135
+ return routeGeometry(children(e, 'coord').map((c) => c.text.trim().split(/\s+/).map(Number)));
136
+ if (e.name === 'MultiTrack')
137
+ return {
138
+ type: 'GeometryCollection',
139
+ geometries: children(e, 'Track')
140
+ .map(kmlGeometry)
141
+ .filter((g) => g !== null),
142
+ };
143
+ return null;
144
+ }
145
+ /** Reads KML placemarks, holes and MultiGeometry/gx tracks without fetching external links or models. */
146
+ export function parseKML(input, options = {}) {
147
+ const root = xml(input, options);
148
+ if (root.name !== 'kml')
149
+ throw new LoaderError(GEO, 'header', 'expected a kml document');
150
+ const features = all(root, 'Placemark').map((e) => {
151
+ const geometries = e.children.map(kmlGeometry).filter((g) => g !== null), props = properties(e);
152
+ const times = all(e, 'when').map((c) => c.text.trim());
153
+ if (times.length)
154
+ props.times = times;
155
+ const f = {
156
+ type: 'Feature',
157
+ properties: props,
158
+ geometry: geometries.length === 1 ? geometries[0] : geometries.length ? { type: 'GeometryCollection', geometries } : null,
159
+ };
160
+ if (e.attributes.id)
161
+ f.id = e.attributes.id;
162
+ return f;
163
+ });
164
+ return buildGeo(features, options);
165
+ }
package/dist/geo.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ import { type BinaryInput } from './util.js';
2
+ import { type GeoOptions, type GeoResult } from './geo-model.js';
3
+ export type { GeoFeature, GeoGeometry, GeoOptions, GeoPolygon, GeoPosition, GeoResult } from './geo-model.js';
4
+ export { parseGPX, parseKML } from './geo-xml.js';
5
+ export { parseShapefile, type ShapefileOptions } from './geo-shp.js';
6
+ export { parseMVT, type MVTOptions } from './geo-mvt.js';
7
+ /** Reads GeoJSON geometry, Feature or FeatureCollection into mixed vector primitives. No projection is applied. */
8
+ export declare function parseGeoJSON(input: BinaryInput | string | object, options?: GeoOptions): GeoResult;
package/dist/geo.js ADDED
@@ -0,0 +1,59 @@
1
+ import { LoaderError } from './types.js';
2
+ import { toBytes, throwIfAborted } from './util.js';
3
+ import { buildGeo, geoLimit, geoText, GEO, } from './geo-model.js';
4
+ export { parseGPX, parseKML } from './geo-xml.js';
5
+ export { parseShapefile } from './geo-shp.js';
6
+ export { parseMVT } from './geo-mvt.js';
7
+ /** Reads GeoJSON geometry, Feature or FeatureCollection into mixed vector primitives. No projection is applied. */
8
+ export function parseGeoJSON(input, options = {}) {
9
+ throwIfAborted(options.signal, GEO);
10
+ let source;
11
+ try {
12
+ const value = typeof input === 'string'
13
+ ? input
14
+ : input instanceof ArrayBuffer || ArrayBuffer.isView(input)
15
+ ? toBytes(input, GEO)
16
+ : JSON.stringify(input);
17
+ source = JSON.parse(geoText(value, options).replace(/^\uFEFF/, ''));
18
+ }
19
+ catch (error) {
20
+ if (error instanceof LoaderError)
21
+ throw error;
22
+ throw new LoaderError(GEO, 'syntax', `invalid GeoJSON: ${error instanceof Error ? error.message : String(error)}`);
23
+ }
24
+ if (!source || typeof source !== 'object')
25
+ throw new LoaderError(GEO, 'syntax', 'GeoJSON needs an object');
26
+ const object = source;
27
+ const rows = object.type === 'FeatureCollection'
28
+ ? object.features
29
+ : object.type === 'Feature'
30
+ ? [object]
31
+ : [{ type: 'Feature', geometry: object, properties: null }];
32
+ if (!Array.isArray(rows))
33
+ throw new LoaderError(GEO, 'syntax', 'FeatureCollection needs a features array');
34
+ if (rows.length > geoLimit(options, 'maxFeatures', 100000))
35
+ throw new LoaderError(GEO, 'limit', 'too many GeoJSON features');
36
+ const features = rows.map((row) => {
37
+ if (!row || typeof row !== 'object')
38
+ throw new LoaderError(GEO, 'syntax', 'expected a GeoJSON Feature');
39
+ const f = row;
40
+ if (f.geometry !== null && (typeof f.geometry !== 'object' || Array.isArray(f.geometry)))
41
+ throw new LoaderError(GEO, 'syntax', 'Feature geometry must be an object or null');
42
+ if (f.type !== 'Feature' ||
43
+ !Object.hasOwn(f, 'geometry') ||
44
+ !Object.hasOwn(f, 'properties') ||
45
+ (f.properties !== null && (typeof f.properties !== 'object' || Array.isArray(f.properties))))
46
+ throw new LoaderError(GEO, 'syntax', 'Feature requires geometry and object/null properties');
47
+ if (f.id !== undefined && typeof f.id !== 'string' && typeof f.id !== 'number')
48
+ throw new LoaderError(GEO, 'syntax', 'Feature id must be a string or number');
49
+ const feature = {
50
+ type: 'Feature',
51
+ properties: f.properties === null ? null : Object.assign(Object.create(null), f.properties),
52
+ geometry: f.geometry,
53
+ };
54
+ if (f.id !== undefined)
55
+ feature.id = f.id;
56
+ return feature;
57
+ });
58
+ return buildGeo(features, options);
59
+ }
@@ -0,0 +1,60 @@
1
+ import { Geometry } from '@margoengine/core';
2
+ import { type LoadedGeometry, type LoadedGroup } from './types.js';
3
+ /**
4
+ * Vertex limit of a core `Geometry`: 11,184,810, the most 24-byte vertices one buffer of WebGPU's default 256 MiB
5
+ * `maxBufferSize` holds (core's own check).
6
+ */
7
+ export declare const CORE_MAX_VERTICES = 11184810;
8
+ /** Options of toGeometry: how normals are made and which group to build. */
9
+ export interface ToGeometryOptions {
10
+ /**
11
+ * `'auto'` (default) uses the file's normals when present and smooth normals otherwise; `'smooth'` always
12
+ * computes area-weighted vertex normals; `'flat'` splits vertices per triangle and uses face normals.
13
+ */
14
+ normals?: 'auto' | 'smooth' | 'flat';
15
+ /** Build only this group (an entry of `loaded.groups`, or its index). */
16
+ group?: number | LoadedGroup;
17
+ /**
18
+ * `toGeometries` only: most vertices in one part, an integer from 3 to {@link CORE_MAX_VERTICES} (the default).
19
+ * Lower it for a renderer whose per-primitive limit is smaller (gltf/pbr takes 1,000,000).
20
+ */
21
+ maxPartVertices?: number;
22
+ }
23
+ /**
24
+ * Splits a triangle list into consecutive triangle ranges (offsets into `triangles`) that each use at most
25
+ * `limit` distinct vertices (`flat`: 3 per triangle) and at most 67,108,864 indices (a 256 MiB index buffer). Order is
26
+ * kept, so the ranges concatenate to the input.
27
+ */
28
+ export declare function splitTriangles(triangles: Uint32Array, vertexCount: number, flat: boolean, limit?: number): {
29
+ start: number;
30
+ count: number;
31
+ }[];
32
+ /**
33
+ * Converts a loaded mesh (or one of its groups) to a core `Geometry`, compacting unused vertices and computing
34
+ * normals when the file has none. Colors and UVs are dropped because core geometry stores position and normal only.
35
+ * A core `Geometry` holds at most 11,184,810 vertices; {@link toGeometries} splits larger meshes.
36
+ */
37
+ export declare function toGeometry(loaded: LoadedGeometry, options?: ToGeometryOptions): Geometry;
38
+ /**
39
+ * Like {@link toGeometry}, but a mesh (or group) that needs more than the core limit of 11,184,810 vertices (or
40
+ * `options.maxPartVertices`) comes back as several geometries: consecutive triangle ranges in source order, each within
41
+ * that many vertices and 67,108,864 indices.
42
+ * Smooth normals are computed over the whole mesh first, so the parts meet without seams; a vertex on a cut appears
43
+ * in both parts. A mesh under the limit returns one Geometry, the same as toGeometry's.
44
+ */
45
+ export declare function toGeometries(loaded: LoadedGeometry, options?: ToGeometryOptions): Geometry[];
46
+ /** Options of pointsToGeometry: the marker size and the most points kept. */
47
+ export interface PointsToGeometryOptions {
48
+ /** Half-size of each point marker in model units. Default 0.4% of the bounding box diagonal. */
49
+ size?: number;
50
+ /**
51
+ * Evenly subsample to at most this many points, 1 to 1,864,135 (6 vertices each, within the core limit). Default
52
+ * 166,666 (about 1,000,000 vertices, a frame budget).
53
+ */
54
+ maxPoints?: number;
55
+ }
56
+ /**
57
+ * Turns a point cloud into one mesh of small octahedra, because core has no point primitive.
58
+ * Per-point colors are dropped (core geometry has no vertex colors).
59
+ */
60
+ export declare function pointsToGeometry(loaded: LoadedGeometry, options?: PointsToGeometryOptions): Geometry;
@@ -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
+ }
@@ -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 } 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';