@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.
Files changed (226) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +4 -0
  3. package/README.md +1665 -2
  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/crease.d.ts +7 -0
  17. package/dist/crease.js +67 -0
  18. package/dist/dae-animation.d.ts +66 -0
  19. package/dist/dae-animation.js +266 -0
  20. package/dist/dae-common.d.ts +95 -0
  21. package/dist/dae-common.js +226 -0
  22. package/dist/dae-controllers.d.ts +57 -0
  23. package/dist/dae-controllers.js +164 -0
  24. package/dist/dae-kinematics.d.ts +65 -0
  25. package/dist/dae-kinematics.js +461 -0
  26. package/dist/dae-pose.d.ts +131 -0
  27. package/dist/dae-pose.js +381 -0
  28. package/dist/dae-scene.d.ts +203 -0
  29. package/dist/dae-scene.js +279 -0
  30. package/dist/dae.d.ts +166 -0
  31. package/dist/dae.js +644 -0
  32. package/dist/detect.d.ts +20 -0
  33. package/dist/detect.js +72 -0
  34. package/dist/dxf-hatch.d.ts +8 -0
  35. package/dist/dxf-hatch.js +346 -0
  36. package/dist/dxf-leaders.d.ts +59 -0
  37. package/dist/dxf-leaders.js +258 -0
  38. package/dist/dxf.d.ts +122 -0
  39. package/dist/dxf.js +985 -0
  40. package/dist/engine.d.ts +41 -0
  41. package/dist/engine.js +120 -0
  42. package/dist/font-opentype.d.ts +14 -0
  43. package/dist/font-opentype.js +33 -0
  44. package/dist/font-woff.d.ts +23 -0
  45. package/dist/font-woff.js +293 -0
  46. package/dist/font.d.ts +41 -0
  47. package/dist/font.js +26 -0
  48. package/dist/gcode.d.ts +92 -0
  49. package/dist/gcode.js +369 -0
  50. package/dist/geo-model.d.ts +84 -0
  51. package/dist/geo-model.js +220 -0
  52. package/dist/geo-mvt.d.ts +15 -0
  53. package/dist/geo-mvt.js +302 -0
  54. package/dist/geo-shp.d.ts +15 -0
  55. package/dist/geo-shp.js +234 -0
  56. package/dist/geo-xml.d.ts +6 -0
  57. package/dist/geo-xml.js +165 -0
  58. package/dist/geo.d.ts +8 -0
  59. package/dist/geo.js +59 -0
  60. package/dist/geometry.d.ts +60 -0
  61. package/dist/geometry.js +273 -0
  62. package/dist/index.d.ts +54 -0
  63. package/dist/index.js +28 -0
  64. package/dist/kmz.d.ts +78 -0
  65. package/dist/kmz.js +173 -0
  66. package/dist/las.d.ts +92 -0
  67. package/dist/las.js +110 -0
  68. package/dist/ldraw.d.ts +118 -0
  69. package/dist/ldraw.js +474 -0
  70. package/dist/load.d.ts +72 -0
  71. package/dist/load.js +205 -0
  72. package/dist/lottie.d.ts +154 -0
  73. package/dist/lottie.js +893 -0
  74. package/dist/lwo.d.ts +81 -0
  75. package/dist/lwo.js +454 -0
  76. package/dist/lzf.d.ts +13 -0
  77. package/dist/lzf.js +56 -0
  78. package/dist/materialx.d.ts +120 -0
  79. package/dist/materialx.js +563 -0
  80. package/dist/md2.d.ts +52 -0
  81. package/dist/md2.js +112 -0
  82. package/dist/mmcif.d.ts +14 -0
  83. package/dist/mmcif.js +246 -0
  84. package/dist/mmd.d.ts +244 -0
  85. package/dist/mmd.js +958 -0
  86. package/dist/mocap.d.ts +71 -0
  87. package/dist/mocap.js +178 -0
  88. package/dist/molecule-common.d.ts +4 -0
  89. package/dist/molecule-common.js +54 -0
  90. package/dist/mtl.d.ts +125 -0
  91. package/dist/mtl.js +550 -0
  92. package/dist/normals.d.ts +7 -0
  93. package/dist/normals.js +31 -0
  94. package/dist/nrrd.d.ts +70 -0
  95. package/dist/nrrd.js +785 -0
  96. package/dist/nurbs.d.ts +118 -0
  97. package/dist/nurbs.js +265 -0
  98. package/dist/obj.d.ts +145 -0
  99. package/dist/obj.js +462 -0
  100. package/dist/off.d.ts +10 -0
  101. package/dist/off.js +155 -0
  102. package/dist/outline-font.d.ts +87 -0
  103. package/dist/outline-font.js +110 -0
  104. package/dist/outline.d.ts +20 -0
  105. package/dist/outline.js +215 -0
  106. package/dist/pcd.d.ts +34 -0
  107. package/dist/pcd.js +258 -0
  108. package/dist/pdb.d.ts +67 -0
  109. package/dist/pdb.js +126 -0
  110. package/dist/ply.d.ts +35 -0
  111. package/dist/ply.js +392 -0
  112. package/dist/polygon.d.ts +9 -0
  113. package/dist/polygon.js +49 -0
  114. package/dist/prwm.d.ts +24 -0
  115. package/dist/prwm.js +114 -0
  116. package/dist/render.d.ts +32 -0
  117. package/dist/render.js +181 -0
  118. package/dist/sfnt-cff.d.ts +37 -0
  119. package/dist/sfnt-cff.js +749 -0
  120. package/dist/sfnt-layout.d.ts +24 -0
  121. package/dist/sfnt-layout.js +266 -0
  122. package/dist/sfnt-reader.d.ts +28 -0
  123. package/dist/sfnt-reader.js +87 -0
  124. package/dist/sfnt-variation.d.ts +40 -0
  125. package/dist/sfnt-variation.js +318 -0
  126. package/dist/shared/asset-url.js +82 -0
  127. package/dist/shared/crc32.d.ts +2 -0
  128. package/dist/shared/crc32.js +47 -0
  129. package/dist/shared/errors.js +36 -0
  130. package/dist/shared/inflate.js +284 -0
  131. package/dist/shared/normals.js +26 -0
  132. package/dist/shared/scene-scope.js +56 -0
  133. package/dist/shared/trailing-data.js +45 -0
  134. package/dist/stl.d.ts +64 -0
  135. package/dist/stl.js +309 -0
  136. package/dist/svg.d.ts +90 -0
  137. package/dist/svg.js +1007 -0
  138. package/dist/tds.d.ts +2 -0
  139. package/dist/tds.js +2 -0
  140. package/dist/textures.d.ts +42 -0
  141. package/dist/textures.js +53 -0
  142. package/dist/threemf-beam-reader.d.ts +19 -0
  143. package/dist/threemf-beam-reader.js +165 -0
  144. package/dist/threemf-beams.d.ts +52 -0
  145. package/dist/threemf-beams.js +268 -0
  146. package/dist/threemf-boolean-read.d.ts +10 -0
  147. package/dist/threemf-boolean-read.js +113 -0
  148. package/dist/threemf-boolean.d.ts +59 -0
  149. package/dist/threemf-boolean.js +20 -0
  150. package/dist/threemf-csg.d.ts +14 -0
  151. package/dist/threemf-csg.js +193 -0
  152. package/dist/threemf-displacement-read.d.ts +8 -0
  153. package/dist/threemf-displacement-read.js +213 -0
  154. package/dist/threemf-displacement.d.ts +71 -0
  155. package/dist/threemf-displacement.js +18 -0
  156. package/dist/threemf-evaluate.d.ts +36 -0
  157. package/dist/threemf-evaluate.js +86 -0
  158. package/dist/threemf-functions.d.ts +33 -0
  159. package/dist/threemf-functions.js +359 -0
  160. package/dist/threemf-lattice-mesh.d.ts +9 -0
  161. package/dist/threemf-lattice-mesh.js +115 -0
  162. package/dist/threemf-lattice.d.ts +139 -0
  163. package/dist/threemf-lattice.js +379 -0
  164. package/dist/threemf-levelset.d.ts +23 -0
  165. package/dist/threemf-levelset.js +105 -0
  166. package/dist/threemf-materials.d.ts +162 -0
  167. package/dist/threemf-materials.js +497 -0
  168. package/dist/threemf-mesh.d.ts +75 -0
  169. package/dist/threemf-mesh.js +422 -0
  170. package/dist/threemf-secure.d.ts +50 -0
  171. package/dist/threemf-secure.js +153 -0
  172. package/dist/threemf-tessellate.d.ts +37 -0
  173. package/dist/threemf-tessellate.js +277 -0
  174. package/dist/threemf-volume-colour.d.ts +25 -0
  175. package/dist/threemf-volume-colour.js +233 -0
  176. package/dist/threemf-volume-sample.d.ts +8 -0
  177. package/dist/threemf-volume-sample.js +65 -0
  178. package/dist/threemf-volumetric-read.d.ts +15 -0
  179. package/dist/threemf-volumetric-read.js +539 -0
  180. package/dist/threemf-volumetric.d.ts +177 -0
  181. package/dist/threemf-volumetric.js +28 -0
  182. package/dist/threemf.d.ts +170 -0
  183. package/dist/threemf.js +609 -0
  184. package/dist/tilt.d.ts +62 -0
  185. package/dist/tilt.js +186 -0
  186. package/dist/tmx.d.ts +151 -0
  187. package/dist/tmx.js +394 -0
  188. package/dist/ttf.d.ts +78 -0
  189. package/dist/ttf.js +568 -0
  190. package/dist/types.d.ts +108 -0
  191. package/dist/types.js +35 -0
  192. package/dist/usd.d.ts +2 -0
  193. package/dist/usd.js +2 -0
  194. package/dist/usd.worker.d.ts +1 -0
  195. package/dist/usdz.d.ts +50 -0
  196. package/dist/usdz.js +646 -0
  197. package/dist/util.d.ts +75 -0
  198. package/dist/util.js +241 -0
  199. package/dist/vdb.d.ts +111 -0
  200. package/dist/vdb.js +663 -0
  201. package/dist/vrml.d.ts +53 -0
  202. package/dist/vrml.js +532 -0
  203. package/dist/vtk-cells.d.ts +29 -0
  204. package/dist/vtk-cells.js +211 -0
  205. package/dist/vtk-legacy.d.ts +57 -0
  206. package/dist/vtk-legacy.js +439 -0
  207. package/dist/vtk-reader.d.ts +19 -0
  208. package/dist/vtk-reader.js +134 -0
  209. package/dist/vtk-xml.d.ts +96 -0
  210. package/dist/vtk-xml.js +578 -0
  211. package/dist/vtk.d.ts +13 -0
  212. package/dist/vtk.js +234 -0
  213. package/dist/woff-glyf.d.ts +17 -0
  214. package/dist/woff-glyf.js +215 -0
  215. package/dist/worker.d.ts +10 -0
  216. package/dist/worker.js +93 -0
  217. package/dist/workers/usd.js +3 -0
  218. package/dist/xfile.d.ts +99 -0
  219. package/dist/xfile.js +706 -0
  220. package/dist/xml.d.ts +107 -0
  221. package/dist/xml.js +843 -0
  222. package/dist/xyz.d.ts +16 -0
  223. package/dist/xyz.js +110 -0
  224. package/dist/zip.d.ts +38 -0
  225. package/dist/zip.js +150 -0
  226. package/package.json +289 -4
@@ -0,0 +1,234 @@
1
+ import { LoaderError } from './types.js';
2
+ import { toBytes, throwIfAborted } from './util.js';
3
+ import { buildGeo, geoLimit, GEO, ringPolygons, } from './geo-model.js';
4
+ function dbf(input, options) {
5
+ const bytes = toBytes(input, GEO), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
6
+ if (bytes.length < 33)
7
+ throw new LoaderError(GEO, 'truncated', 'dBASE header is incomplete');
8
+ const records = view.getUint32(4, true), header = view.getUint16(8, true), stride = view.getUint16(10, true);
9
+ if (header < 33 ||
10
+ (header - 33) % 32 ||
11
+ header > bytes.length ||
12
+ bytes[header - 1] !== 13 ||
13
+ stride < 1 ||
14
+ header + records * stride > bytes.length)
15
+ throw new LoaderError(GEO, 'truncated', 'invalid dBASE header or record lengths');
16
+ if (records > geoLimit(options, 'maxFeatures', 100000))
17
+ throw new LoaderError(GEO, 'limit', 'too many dBASE records');
18
+ let decoder;
19
+ try {
20
+ decoder = new TextDecoder(options.encoding ?? 'windows-1252');
21
+ }
22
+ catch {
23
+ throw new LoaderError(GEO, 'unsupported', 'unsupported dBASE encoding; pass a TextDecoder encoding label');
24
+ }
25
+ const fields = [];
26
+ let offset = 1;
27
+ for (let at = 32; at < header - 1; at += 32) {
28
+ const name = decoder.decode(bytes.subarray(at, at + 11)).replace(/\0.*$/, '');
29
+ const type = String.fromCharCode(bytes[at + 11]), length = bytes[at + 16];
30
+ if (!name || !length || fields.some((f) => f.name === name))
31
+ throw new LoaderError(GEO, 'syntax', 'invalid or duplicate dBASE field');
32
+ fields.push({ name, type, length, offset });
33
+ offset += length;
34
+ }
35
+ if (offset !== stride)
36
+ throw new LoaderError(GEO, 'range', 'dBASE field widths do not match record width');
37
+ return Array.from({ length: records }, (_, r) => {
38
+ const start = header + r * stride, properties = Object.create(null);
39
+ if (bytes[start] !== 32 && bytes[start] !== 42)
40
+ throw new LoaderError(GEO, 'syntax', 'invalid dBASE deletion marker');
41
+ for (const field of fields) {
42
+ const at = start + field.offset, raw = decoder
43
+ .decode(bytes.subarray(at, at + field.length))
44
+ .replace(/\0+$/, '')
45
+ .trim();
46
+ let value = raw;
47
+ if (field.type === 'N' || field.type === 'F') {
48
+ if (!raw || /^\*+$/.test(raw))
49
+ value = null;
50
+ else {
51
+ const n = Number(raw);
52
+ if (!Number.isFinite(n))
53
+ throw new LoaderError(GEO, 'syntax', `invalid dBASE number in ${field.name}`);
54
+ value = Number.isInteger(n) && !Number.isSafeInteger(n) ? raw : n;
55
+ }
56
+ }
57
+ else if (field.type === 'L')
58
+ value = /^[YyTt]$/.test(raw) ? true : /^[NnFf]$/.test(raw) ? false : null;
59
+ else if (field.type === 'D')
60
+ value = /^\d{8}$/.test(raw) ? `${raw.slice(0, 4)}-${raw.slice(4, 6)}-${raw.slice(6)}` : null;
61
+ else if (field.type === 'I' && field.length === 4)
62
+ value = view.getInt32(at, true);
63
+ else if ((field.type === 'B' || field.type === 'O') && field.length === 8)
64
+ value = view.getFloat64(at, true);
65
+ properties[field.name] = value;
66
+ }
67
+ return { properties, deleted: bytes[start] === 42 };
68
+ });
69
+ }
70
+ /** Reads Shapefile points, multipoints, polylines, polygons and multipatches, including Z/M and optional dBASE. */
71
+ export function parseShapefile(input, options = {}) {
72
+ throwIfAborted(options.signal, GEO);
73
+ const bytes = toBytes(input, GEO), maxBytes = geoLimit(options, 'maxBytes', 256 << 20), maxFeatures = geoLimit(options, 'maxFeatures', 100000);
74
+ if (bytes.length > maxBytes)
75
+ throw new LoaderError(GEO, 'limit', `Shapefile exceeds ${maxBytes} bytes`);
76
+ if (bytes.length < 100)
77
+ throw new LoaderError(GEO, 'truncated', 'Shapefile header is incomplete');
78
+ const file = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
79
+ if (file.getInt32(0, false) !== 9994 || file.getInt32(28, true) !== 1000)
80
+ throw new LoaderError(GEO, 'header', 'invalid Shapefile identifier or version');
81
+ if (file.getInt32(24, false) * 2 !== bytes.length)
82
+ throw new LoaderError(GEO, 'truncated', 'Shapefile length does not match its header');
83
+ const declared = file.getInt32(32, true), rows = options.dbf ? dbf(options.dbf, options) : undefined, features = [];
84
+ if (![0, 1, 3, 5, 8, 11, 13, 15, 18, 21, 23, 25, 28, 31].includes(declared))
85
+ throw new LoaderError(GEO, 'unsupported', `unsupported Shapefile shape ${declared}`);
86
+ let at = 100, record = 0;
87
+ while (at < bytes.length) {
88
+ if (record >= maxFeatures)
89
+ throw new LoaderError(GEO, 'limit', `Shapefile records exceed ${maxFeatures}`);
90
+ if (at + 8 > bytes.length)
91
+ throw new LoaderError(GEO, 'truncated', 'Shapefile record header is incomplete');
92
+ const id = file.getInt32(at, false), length = file.getInt32(at + 4, false) * 2;
93
+ at += 8;
94
+ if (id < 1 || length < 4 || at + length > bytes.length)
95
+ throw new LoaderError(GEO, 'truncated', 'invalid Shapefile record length or number');
96
+ const v = new DataView(bytes.buffer, bytes.byteOffset + at, length), shape = v.getInt32(0, true);
97
+ if (shape !== 0 && shape !== declared)
98
+ throw new LoaderError(GEO, 'range', 'record shape type differs from file header');
99
+ const need = (end) => {
100
+ if (end > length)
101
+ throw new LoaderError(GEO, 'truncated', 'Shapefile record ends inside geometry');
102
+ };
103
+ const u32 = (offset) => {
104
+ need(offset + 4);
105
+ return v.getUint32(offset, true);
106
+ };
107
+ const double = (offset) => {
108
+ need(offset + 8);
109
+ const n = v.getFloat64(offset, true);
110
+ if (!Number.isFinite(n))
111
+ throw new LoaderError(GEO, 'range', 'Shapefile coordinates must be finite');
112
+ return n;
113
+ };
114
+ let geometry = null;
115
+ if ([1, 11, 21].includes(shape)) {
116
+ const p = [double(4), double(12)];
117
+ let end = 20;
118
+ if (shape === 11) {
119
+ p.push(double(end));
120
+ end += 8;
121
+ }
122
+ if (shape === 21 || (shape === 11 && length >= end + 8)) {
123
+ if (p.length === 2)
124
+ p.push(0);
125
+ p.push(double(end));
126
+ end += 8;
127
+ }
128
+ if (end !== length)
129
+ throw new LoaderError(GEO, 'syntax', 'Shapefile point has trailing data');
130
+ geometry = { type: 'Point', coordinates: p };
131
+ }
132
+ else if ([3, 5, 8, 13, 15, 18, 23, 25, 28, 31].includes(shape)) {
133
+ need(40);
134
+ const multi = [8, 18, 28].includes(shape), parts = multi ? 0 : u32(36), n = u32(multi ? 36 : 40);
135
+ if (n > (options.maxVertices ?? 8000000) || parts > n)
136
+ throw new LoaderError(GEO, 'limit', 'Shapefile point/part count exceeds bounds');
137
+ let cursor = multi ? 40 : 44;
138
+ const starts = [];
139
+ for (let p = 0; p < parts; p++) {
140
+ const index = u32(cursor);
141
+ cursor += 4;
142
+ if (index >= n || (p === 0 && index !== 0) || (p > 0 && index <= starts[p - 1]))
143
+ throw new LoaderError(GEO, 'range', 'invalid Shapefile part offsets');
144
+ starts.push(index);
145
+ }
146
+ if (!multi && !parts && n)
147
+ throw new LoaderError(GEO, 'range', 'nonempty Shapefile needs parts');
148
+ const patchTypes = [];
149
+ if (shape === 31)
150
+ for (let p = 0; p < parts; p++) {
151
+ patchTypes.push(u32(cursor));
152
+ cursor += 4;
153
+ }
154
+ need(cursor + n * 16);
155
+ const coords = Array.from({ length: n }, (_, i) => [
156
+ double(cursor + i * 16),
157
+ double(cursor + i * 16 + 8),
158
+ ]);
159
+ cursor += n * 16;
160
+ if ([13, 15, 18, 31].includes(shape)) {
161
+ need(cursor + 16 + n * 8);
162
+ cursor += 16;
163
+ for (let i = 0; i < n; i++)
164
+ coords[i].push(double(cursor + i * 8));
165
+ cursor += n * 8;
166
+ }
167
+ if ([13, 15, 18, 23, 25, 28, 31].includes(shape) && cursor < length) {
168
+ need(cursor + 16 + n * 8);
169
+ cursor += 16;
170
+ for (let i = 0; i < n; i++) {
171
+ if (coords[i].length === 2)
172
+ coords[i].push(0);
173
+ coords[i].push(double(cursor + i * 8));
174
+ }
175
+ cursor += n * 8;
176
+ }
177
+ if (cursor !== length)
178
+ throw new LoaderError(GEO, 'syntax', 'Shapefile record has trailing geometry data');
179
+ if (multi)
180
+ geometry = { type: 'MultiPoint', coordinates: coords };
181
+ else {
182
+ const pieces = starts.map((start, p) => coords.slice(start, starts[p + 1] ?? n));
183
+ if ([3, 13, 23].includes(shape))
184
+ geometry = { type: 'MultiLineString', coordinates: pieces };
185
+ else if (shape === 31) {
186
+ const polygons = [];
187
+ // Ring sequences (ESRI Shapefile Technical Description, MultiPatch): an Outer Ring and the Inner Rings
188
+ // after it, or a First Ring and the Rings after it, make one polygon; a lone Ring is its own.
189
+ let open, opener = -1;
190
+ for (let p = 0; p < pieces.length; p++) {
191
+ const patch = pieces[p], kind = patchTypes[p];
192
+ if (kind === 0 || kind === 1) {
193
+ if (patch.length < 3)
194
+ throw new LoaderError(GEO, 'range', 'multipatch strips/fans need at least three points');
195
+ for (let i = 2; i < patch.length; i++) {
196
+ const tri = kind === 1
197
+ ? [patch[0], patch[i - 1], patch[i]]
198
+ : i % 2
199
+ ? [patch[i - 1], patch[i - 2], patch[i]]
200
+ : [patch[i - 2], patch[i - 1], patch[i]];
201
+ polygons.push([[...tri, tri[0]]]);
202
+ }
203
+ opener = -1;
204
+ }
205
+ else if (open && ((kind === 3 && opener === 2) || (kind === 5 && opener === 4)))
206
+ open.push(patch);
207
+ else if (kind >= 2 && kind <= 5) {
208
+ polygons.push((open = [patch]));
209
+ opener = kind === 2 || kind === 4 ? kind : -1;
210
+ }
211
+ else
212
+ throw new LoaderError(GEO, 'unsupported', `unknown multipatch part type ${kind}`);
213
+ }
214
+ geometry = { type: 'MultiPolygon', coordinates: polygons };
215
+ }
216
+ else
217
+ geometry = { type: 'MultiPolygon', coordinates: ringPolygons(pieces) };
218
+ }
219
+ }
220
+ else if (shape !== 0)
221
+ throw new LoaderError(GEO, 'unsupported', `unsupported Shapefile shape ${shape}`);
222
+ if (!rows?.[record]?.deleted || options.includeDeleted) {
223
+ const properties = rows?.[record]?.properties ?? Object.create(null);
224
+ if (rows?.[record]?.deleted)
225
+ properties.deleted = true;
226
+ features.push({ type: 'Feature', id, properties, geometry });
227
+ }
228
+ record++;
229
+ at += length;
230
+ }
231
+ if (rows && rows.length !== record)
232
+ throw new LoaderError(GEO, 'range', 'dBASE record count differs from Shapefile');
233
+ return buildGeo(features, options, options.prj ?? 'unspecified');
234
+ }
@@ -0,0 +1,6 @@
1
+ import { type BinaryInput } from './util.js';
2
+ import { type GeoOptions, type GeoResult } from './geo-model.js';
3
+ /** Reads GPX 1.0/1.1 waypoints, routes and separate track segments, keeping elevations and timestamps. */
4
+ export declare function parseGPX(input: BinaryInput | string, options?: GeoOptions): GeoResult;
5
+ /** Reads KML placemarks, holes and MultiGeometry/gx tracks without fetching external links or models. */
6
+ export declare function parseKML(input: BinaryInput | string, options?: GeoOptions): GeoResult;
@@ -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-mesh limit is smaller (a materials mesh 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;