@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
package/dist/pcd.js ADDED
@@ -0,0 +1,258 @@
1
+ import { LoaderError } from './types.js';
2
+ import { checkCount, latin1, limits, splitFields, TextScanner, toBytes } from './util.js';
3
+ import { decompressLZF } from './lzf.js';
4
+ const F = 'PCD';
5
+ const MAX_HEADER = 1 << 16;
6
+ /** Parses only the PCD header. */
7
+ export function parsePCDHeader(input, options = {}) {
8
+ const bytes = toBytes(input, F), limit = limits(options, F);
9
+ const text = latin1(bytes, 0, Math.min(bytes.length, MAX_HEADER));
10
+ const scanner = new TextScanner(text, F);
11
+ const values = {};
12
+ let data;
13
+ for (let line = scanner.line(); line !== null; line = scanner.line()) {
14
+ const trimmed = line.trim();
15
+ if (!trimmed || trimmed.startsWith('#'))
16
+ continue;
17
+ const [key, ...rest] = splitFields(trimmed);
18
+ const upper = key.toUpperCase();
19
+ if (upper === 'DATA') {
20
+ data = rest[0];
21
+ break;
22
+ }
23
+ if (!['VERSION', 'FIELDS', 'COLUMNS', 'SIZE', 'TYPE', 'COUNT', 'WIDTH', 'HEIGHT', 'VIEWPOINT', 'POINTS'].includes(upper))
24
+ throw new LoaderError(F, 'header', `unknown header key "${key.slice(0, 32)}"`);
25
+ values[upper === 'COLUMNS' ? 'FIELDS' : upper] = rest;
26
+ }
27
+ if (data === undefined)
28
+ throw new LoaderError(F, bytes.length >= MAX_HEADER ? 'header' : 'truncated', 'DATA line not found');
29
+ if (data !== 'ascii' && data !== 'binary' && data !== 'binary_compressed')
30
+ throw new LoaderError(F, 'unsupported', `unknown DATA type "${String(data).slice(0, 32)}"`);
31
+ const names = values.FIELDS;
32
+ if (!names?.length)
33
+ throw new LoaderError(F, 'header', 'missing FIELDS');
34
+ const sizes = values.SIZE?.map(Number), types = values.TYPE, counts = values.COUNT?.map(Number) ?? names.map(() => 1);
35
+ if (!sizes ||
36
+ sizes.length !== names.length ||
37
+ !types ||
38
+ types.length !== names.length ||
39
+ counts.length !== names.length)
40
+ throw new LoaderError(F, 'header', 'FIELDS, SIZE, TYPE and COUNT must have the same length');
41
+ const fields = [];
42
+ let rowSize = 0;
43
+ names.forEach((name, i) => {
44
+ const size = sizes[i], type = types[i].toUpperCase(), count = counts[i];
45
+ if (![1, 2, 4, 8].includes(size))
46
+ throw new LoaderError(F, 'header', `invalid SIZE ${size} for ${name}`);
47
+ if (type !== 'I' && type !== 'U' && type !== 'F')
48
+ throw new LoaderError(F, 'header', `invalid TYPE ${type} for ${name}`);
49
+ if (type === 'F' && size !== 4 && size !== 8)
50
+ throw new LoaderError(F, 'header', `float field ${name} must be 4 or 8 bytes`);
51
+ if (!Number.isSafeInteger(count) || count < 1 || count > 4096)
52
+ throw new LoaderError(F, 'header', `invalid COUNT ${count} for ${name}`);
53
+ fields.push({ name, size, type, count, offset: rowSize });
54
+ rowSize += size * count;
55
+ });
56
+ const width = Number(values.WIDTH?.[0] ?? NaN), height = Number(values.HEIGHT?.[0] ?? 1);
57
+ if (!Number.isSafeInteger(width) || width < 0 || !Number.isSafeInteger(height) || height < 0)
58
+ throw new LoaderError(F, 'header', 'invalid WIDTH or HEIGHT');
59
+ const points = checkCount(values.POINTS ? Number(values.POINTS[0]) : width * height, limit.maxVertices, F, 'point');
60
+ if (values.POINTS && width * height !== points)
61
+ throw new LoaderError(F, 'header', `WIDTH x HEIGHT (${width * height}) does not match POINTS (${points})`);
62
+ const viewpoint = values.VIEWPOINT?.map(Number) ?? [0, 0, 0, 1, 0, 0, 0];
63
+ return {
64
+ version: values.VERSION?.[0] ?? '',
65
+ fields,
66
+ width,
67
+ height,
68
+ points,
69
+ viewpoint,
70
+ data,
71
+ rowSize,
72
+ bodyOffset: scanner.pos,
73
+ };
74
+ }
75
+ // A numeric code per field type keeps the point loop on one call site: floats are 0 and 1, then signed and unsigned by size.
76
+ const code = (field) => !field ? 0 : field.type === 'F' ? (field.size === 4 ? 0 : 1) : (field.type === 'I' ? 2 : 6) + Math.log2(field.size);
77
+ function read(view, offset, kind) {
78
+ switch (kind) {
79
+ case 0:
80
+ return view.getFloat32(offset, true);
81
+ case 1:
82
+ return view.getFloat64(offset, true);
83
+ case 2:
84
+ return view.getInt8(offset);
85
+ case 3:
86
+ return view.getInt16(offset, true);
87
+ case 4:
88
+ return view.getInt32(offset, true);
89
+ case 5:
90
+ return Number(view.getBigInt64(offset, true));
91
+ case 6:
92
+ return view.getUint8(offset);
93
+ case 7:
94
+ return view.getUint16(offset, true);
95
+ case 8:
96
+ return view.getUint32(offset, true);
97
+ default:
98
+ return Number(view.getBigUint64(offset, true));
99
+ }
100
+ }
101
+ /**
102
+ * Parses a PCD point cloud with `DATA ascii`, `binary` or `binary_compressed` (LZF).
103
+ * Reads x/y/z, normal_x/y/z, packed rgb or rgba, and intensity (as `attributes.intensity`).
104
+ */
105
+ export function parsePCD(input, options = {}) {
106
+ const bytes = toBytes(input, F), header = parsePCDHeader(bytes, options), count = header.points;
107
+ const field = (name) => header.fields.find((f) => f.name === name);
108
+ const x = field('x'), y = field('y'), z = field('z');
109
+ if (!x || !y || !z)
110
+ throw new LoaderError(F, 'header', 'fields x, y and z are required');
111
+ const nx = field('normal_x'), ny = field('normal_y'), nz = field('normal_z'), rgb = field('rgb') ?? field('rgba'), intensity = field('intensity');
112
+ const hasNormals = !!(nx && ny && nz);
113
+ if (rgb && rgb.size !== 4)
114
+ throw new LoaderError(F, 'header', 'rgb field must be 4 bytes');
115
+ // Budget before allocation: the body must be able to hold POINTS (an ASCII point takes a digit and a line break; an
116
+ // LZF stream expands at most 88x: 3 input bytes per 264-byte back reference), so a short file cannot claim millions.
117
+ const available = bytes.length - header.bodyOffset;
118
+ const needed = header.data === 'ascii'
119
+ ? count * 2 - 1
120
+ : header.data === 'binary'
121
+ ? count * header.rowSize
122
+ : (count * header.rowSize) / 88;
123
+ if (needed > available)
124
+ throw new LoaderError(F, 'truncated', `body is too short for ${count} points`);
125
+ const positions = new Float32Array(count * 3);
126
+ const normals = hasNormals ? new Float32Array(count * 3) : undefined;
127
+ const colors = rgb ? new Float32Array(count * 3) : undefined;
128
+ const intensities = intensity ? new Float32Array(count) : undefined;
129
+ const bits = new DataView(new ArrayBuffer(4));
130
+ const setColor = (i, packed) => {
131
+ colors[i * 3] = ((packed >>> 16) & 255) / 255;
132
+ colors[i * 3 + 1] = ((packed >>> 8) & 255) / 255;
133
+ colors[i * 3 + 2] = (packed & 255) / 255;
134
+ };
135
+ if (header.data === 'ascii') {
136
+ // Token position of each field's first value in a row.
137
+ let column = 0;
138
+ const columns = new Map();
139
+ for (const f of header.fields) {
140
+ columns.set(f, column);
141
+ column += f.count;
142
+ }
143
+ const scanner = new TextScanner(latin1(bytes, header.bodyOffset), F);
144
+ let i = 0, lineNumber = 0;
145
+ for (let line = scanner.line(); line !== null && i < count; line = scanner.line()) {
146
+ lineNumber++;
147
+ const tokens = splitFields(line);
148
+ if (!tokens.length)
149
+ continue;
150
+ if (tokens.length < column)
151
+ throw new LoaderError(F, 'syntax', `data line ${lineNumber} has ${tokens.length} values, expected ${column}`);
152
+ const value = (f) => {
153
+ const token = tokens[columns.get(f)], parsed = Number(token);
154
+ if (Number.isNaN(parsed) && !/^[+-]?nan$/i.test(token))
155
+ throw new LoaderError(F, 'syntax', `invalid number "${token.slice(0, 32)}" on data line ${lineNumber}`);
156
+ return parsed;
157
+ };
158
+ positions[i * 3] = value(x);
159
+ positions[i * 3 + 1] = value(y);
160
+ positions[i * 3 + 2] = value(z);
161
+ if (normals) {
162
+ normals[i * 3] = value(nx);
163
+ normals[i * 3 + 1] = value(ny);
164
+ normals[i * 3 + 2] = value(nz);
165
+ }
166
+ if (rgb) {
167
+ const raw = value(rgb);
168
+ if (rgb.type === 'F') {
169
+ bits.setFloat32(0, raw, true);
170
+ setColor(i, bits.getUint32(0, true));
171
+ }
172
+ else
173
+ setColor(i, raw >>> 0);
174
+ }
175
+ if (intensities)
176
+ intensities[i] = value(intensity);
177
+ i++;
178
+ }
179
+ if (i < count)
180
+ throw new LoaderError(F, 'truncated', `file ends after ${i} of ${count} points`);
181
+ }
182
+ else {
183
+ let body;
184
+ // Byte offset of each field's first value for point i is `base + i * step`: binary is row-major, binary_compressed is column-major.
185
+ const bases = new Map(), compressed = header.data !== 'binary';
186
+ if (header.data === 'binary') {
187
+ if (header.bodyOffset + count * header.rowSize > bytes.length)
188
+ throw new LoaderError(F, 'truncated', `binary data needs ${count * header.rowSize} bytes, file has ${bytes.length - header.bodyOffset}`);
189
+ body = bytes.subarray(header.bodyOffset);
190
+ for (const f of header.fields)
191
+ bases.set(f, f.offset);
192
+ }
193
+ else {
194
+ if (header.bodyOffset + 8 > bytes.length)
195
+ throw new LoaderError(F, 'truncated', 'missing compressed size words');
196
+ const sizes = new DataView(bytes.buffer, bytes.byteOffset + header.bodyOffset, 8);
197
+ const compressed = sizes.getUint32(0, true), uncompressed = sizes.getUint32(4, true);
198
+ if (uncompressed !== count * header.rowSize)
199
+ throw new LoaderError(F, 'header', `uncompressed size ${uncompressed} does not match ${count} points of ${header.rowSize} bytes`);
200
+ if (uncompressed > compressed * 88)
201
+ throw new LoaderError(F, 'range', `${compressed} LZF bytes cannot expand to ${uncompressed}`);
202
+ if (header.bodyOffset + 8 + compressed > bytes.length)
203
+ throw new LoaderError(F, 'truncated', `compressed data needs ${compressed} bytes, file has ${bytes.length - header.bodyOffset - 8}`);
204
+ body = decompressLZF(bytes.subarray(header.bodyOffset + 8, header.bodyOffset + 8 + compressed), uncompressed, F);
205
+ let start = 0;
206
+ for (const f of header.fields) {
207
+ bases.set(f, start);
208
+ start += f.size * f.count * count;
209
+ }
210
+ }
211
+ const view = new DataView(body.buffer, body.byteOffset, body.byteLength);
212
+ const base = (f) => (f ? bases.get(f) : 0), step = (f) => (!f ? 0 : compressed ? f.size * f.count : header.rowSize);
213
+ const bx = base(x), by = base(y), bz = base(z), sx = step(x), sy = step(y), sz = step(z), kx = code(x), ky = code(y), kz = code(z);
214
+ const bnx = base(nx), bny = base(ny), bnz = base(nz), snx = step(nx), sny = step(ny), snz = step(nz), knx = code(nx), kny = code(ny), knz = code(nz);
215
+ const brgb = base(rgb), srgb = step(rgb), bi = base(intensity), si = step(intensity), ki = code(intensity);
216
+ for (let i = 0; i < count; i++) {
217
+ positions[i * 3] = read(view, bx + i * sx, kx);
218
+ positions[i * 3 + 1] = read(view, by + i * sy, ky);
219
+ positions[i * 3 + 2] = read(view, bz + i * sz, kz);
220
+ if (normals) {
221
+ normals[i * 3] = read(view, bnx + i * snx, knx);
222
+ normals[i * 3 + 1] = read(view, bny + i * sny, kny);
223
+ normals[i * 3 + 2] = read(view, bnz + i * snz, knz);
224
+ }
225
+ if (rgb)
226
+ setColor(i, view.getUint32(brgb + i * srgb, true));
227
+ if (intensities)
228
+ intensities[i] = read(view, bi + i * si, ki);
229
+ }
230
+ }
231
+ let kept = count;
232
+ if (!options.keepInvalid) {
233
+ kept = 0;
234
+ for (let i = 0; i < count; i++) {
235
+ if (!Number.isFinite(positions[i * 3]) ||
236
+ !Number.isFinite(positions[i * 3 + 1]) ||
237
+ !Number.isFinite(positions[i * 3 + 2]))
238
+ continue;
239
+ if (kept !== i) {
240
+ positions.copyWithin(kept * 3, i * 3, i * 3 + 3);
241
+ normals?.copyWithin(kept * 3, i * 3, i * 3 + 3);
242
+ colors?.copyWithin(kept * 3, i * 3, i * 3 + 3);
243
+ if (intensities)
244
+ intensities[kept] = intensities[i];
245
+ }
246
+ kept++;
247
+ }
248
+ }
249
+ const trim = (array, size) => kept === count ? array : array.slice(0, kept * size);
250
+ const result = { kind: 'points', positions: trim(positions, 3) };
251
+ if (normals)
252
+ result.normals = trim(normals, 3);
253
+ if (colors)
254
+ result.colors = trim(colors, 3);
255
+ if (intensities)
256
+ result.attributes = { intensity: trim(intensities, 1) };
257
+ return result;
258
+ }
package/dist/pdb.d.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** Options of {@link parsePDB}. `maxVertices` counts atoms. */
4
+ export interface PDBOptions extends ParseLimits {
5
+ /** Add bonds by distance, because standard residues have no CONECT records. Default true. */
6
+ guessBonds?: boolean;
7
+ }
8
+ /** One atom's labels, in the order of `positions`. */
9
+ export interface PDBAtom {
10
+ serial: number;
11
+ /** Original atom id, when the format provides a non-numeric identifier. */
12
+ id?: string;
13
+ /** Residue identifier in the author namespace, including non-numeric mmCIF ids. */
14
+ residueId?: string;
15
+ /** PDB insertion code, blank when absent. */
16
+ insertionCode?: string;
17
+ /** Selected alternate location, blank when absent. */
18
+ alternateLocation?: string;
19
+ /** The atom's name, such as `CA`. */
20
+ name: string;
21
+ /** The element's symbol in capitals. */
22
+ element: string;
23
+ /** The residue's name, such as `ALA`. */
24
+ residue: string;
25
+ /** The residue's sequence number. */
26
+ sequence: number;
27
+ chain: string;
28
+ /** True for a HETATM record. */
29
+ hetero: boolean;
30
+ }
31
+ /** What {@link parsePDB} returns: the atoms as a point cloud in angstroms. */
32
+ export interface PDBMolecule extends LoadedGeometry {
33
+ kind: 'points';
34
+ colors: Float32Array;
35
+ atoms: PDBAtom[];
36
+ /** Covalent radius per atom, in angstroms. */
37
+ radii: Float32Array;
38
+ /** Two atom indices per bond, each bond once. */
39
+ bonds: Uint32Array;
40
+ /** The TITLE records joined, when the file has them. */
41
+ title?: string;
42
+ /** Things the parser moved past, each listed once. */
43
+ warnings: string[];
44
+ }
45
+ /**
46
+ * Reads a Protein Data Bank `.pdb` file: ATOM and HETATM records by their fixed columns, element colours and radii,
47
+ * CONECT bonds, and bonds by distance for the residues the format leaves unconnected. Only the first MODEL loads, and an
48
+ * atom with alternate locations keeps its first.
49
+ *
50
+ * @param input The file's bytes or text.
51
+ * @param options The shared size limits and whether to find bonds by distance.
52
+ * @returns The atoms as a point cloud with colours, labels, radii and bonds.
53
+ * @throws LoaderError with code `syntax` for a bad column or no atoms, or `limit`.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * import { parsePDB } from '@margoengine/loaders/pdb';
58
+ *
59
+ * const text = [
60
+ * 'ATOM 1 O HOH A 1 0.000 0.000 0.000 1.00 0.00 O',
61
+ * 'ATOM 2 H1 HOH A 1 0.960 0.000 0.000 1.00 0.00 H',
62
+ * ].join('\n');
63
+ * const { atoms, bonds } = parsePDB(text);
64
+ * console.log(atoms[0].element, bonds);
65
+ * ```
66
+ */
67
+ export declare function parsePDB(input: BinaryInput | string, options?: PDBOptions): PDBMolecule;
package/dist/pdb.js ADDED
@@ -0,0 +1,126 @@
1
+ // Protein Data Bank .pdb files: ATOM and HETATM records, CONECT bonds and bonds found by distance.
2
+ import { LoaderError } from './types.js';
3
+ import { elementProperties, nearbyPairs } from './molecule-common.js';
4
+ import { floats, limits, toText, uints } from './util.js';
5
+ const F = 'PDB';
6
+ function column(line, start, end, lineNumber, what) {
7
+ const value = Number(line.slice(start, end));
8
+ if (!line.slice(start, end).trim() || !Number.isFinite(value))
9
+ throw new LoaderError(F, 'syntax', `line ${lineNumber} has a bad ${what}`);
10
+ return value;
11
+ }
12
+ function element(line, name) {
13
+ const written = line.slice(76, 78).trim().toUpperCase();
14
+ if (/^[A-Z]{1,2}$/.test(written))
15
+ return written;
16
+ // Older files leave the column empty: the element ends the name's first two columns, so " CA " is carbon, "CA " calcium.
17
+ const letters = name
18
+ .slice(0, 2)
19
+ .replace(/[^A-Za-z]/g, '')
20
+ .toUpperCase();
21
+ return name[0] === ' ' || /\d/.test(name[0]) ? letters.slice(-1) : letters;
22
+ }
23
+ /**
24
+ * Reads a Protein Data Bank `.pdb` file: ATOM and HETATM records by their fixed columns, element colours and radii,
25
+ * CONECT bonds, and bonds by distance for the residues the format leaves unconnected. Only the first MODEL loads, and an
26
+ * atom with alternate locations keeps its first.
27
+ *
28
+ * @param input The file's bytes or text.
29
+ * @param options The shared size limits and whether to find bonds by distance.
30
+ * @returns The atoms as a point cloud with colours, labels, radii and bonds.
31
+ * @throws LoaderError with code `syntax` for a bad column or no atoms, or `limit`.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { parsePDB } from '@margoengine/loaders/pdb';
36
+ *
37
+ * const text = [
38
+ * 'ATOM 1 O HOH A 1 0.000 0.000 0.000 1.00 0.00 O',
39
+ * 'ATOM 2 H1 HOH A 1 0.960 0.000 0.000 1.00 0.00 H',
40
+ * ].join('\n');
41
+ * const { atoms, bonds } = parsePDB(text);
42
+ * console.log(atoms[0].element, bonds);
43
+ * ```
44
+ */
45
+ export function parsePDB(input, options = {}) {
46
+ const text = toText(input, F), { maxVertices } = limits(options, F), positions = floats(), colors = floats(), atoms = [], radii = [], serials = new Map(), connections = [], seen = new Set(), warnings = new Set(), title = [];
47
+ let lineNumber = 0, ended = false;
48
+ if ((text.match(/^MODEL/gm)?.length ?? 0) > 1)
49
+ warnings.add('only the first MODEL is read');
50
+ for (const raw of text.split('\n')) {
51
+ const line = raw.replace(/\r$/, '');
52
+ lineNumber++;
53
+ const record = line.slice(0, 6).trim();
54
+ if (record === 'ENDMDL')
55
+ ended = true;
56
+ else if (record === 'TITLE')
57
+ title.push(line.slice(10).trim());
58
+ // CONECT rows come after the last model, so reading goes on past ENDMDL for them alone.
59
+ else if (ended && record !== 'CONECT')
60
+ continue;
61
+ else if (record === 'ATOM' || record === 'HETATM') {
62
+ const name = line.slice(12, 16), chain = line[21] ?? ' ', sequence = column(line, 22, 26, lineNumber, 'residue number'), id = `${chain} ${sequence} ${line[26] ?? ' '} ${name}`;
63
+ // An atom with alternate locations appears once per location.
64
+ if (line[16] !== ' ' && line[16] !== undefined && seen.has(id))
65
+ continue;
66
+ seen.add(id);
67
+ if (atoms.length >= maxVertices)
68
+ throw new LoaderError(F, 'limit', `atom count exceeds the limit of ${maxVertices}`);
69
+ const symbol = element(line, name), [rgb, radius] = elementProperties(symbol), serial = column(line, 6, 11, lineNumber, 'serial');
70
+ positions.push3(column(line, 30, 38, lineNumber, 'x'), column(line, 38, 46, lineNumber, 'y'), column(line, 46, 54, lineNumber, 'z'));
71
+ colors.push3((rgb >> 16) / 255, ((rgb >> 8) & 255) / 255, (rgb & 255) / 255);
72
+ serials.set(serial, atoms.length);
73
+ radii.push(radius);
74
+ atoms.push({
75
+ serial,
76
+ ...((line[26] ?? '').trim() ? { insertionCode: line[26] } : {}),
77
+ ...((line[16] ?? '').trim() ? { alternateLocation: line[16] } : {}),
78
+ name: name.trim(),
79
+ element: symbol,
80
+ residue: line.slice(17, 20).trim(),
81
+ sequence,
82
+ chain: chain.trim(),
83
+ hetero: record === 'HETATM',
84
+ });
85
+ }
86
+ else if (record === 'CONECT') {
87
+ const from = column(line, 6, 11, lineNumber, 'serial');
88
+ for (let at = 11; at + 5 <= line.length + 4 && at < 31; at += 5)
89
+ if (line.slice(at, at + 5).trim())
90
+ connections.push([from, column(line, at, at + 5, lineNumber, 'serial')]);
91
+ }
92
+ }
93
+ if (!atoms.length)
94
+ throw new LoaderError(F, 'syntax', 'the file has no ATOM or HETATM records');
95
+ const bonds = uints(), known = new Set(), add = (a, b) => {
96
+ const low = Math.min(a, b), high = Math.max(a, b), id = low * atoms.length + high;
97
+ if (low === high || known.has(id))
98
+ return;
99
+ known.add(id);
100
+ bonds.push(low);
101
+ bonds.push(high);
102
+ };
103
+ for (const [from, to] of connections) {
104
+ const a = serials.get(from), b = serials.get(to);
105
+ // A CONECT row may name an atom of a model or an alternate location that was not read.
106
+ if (a === undefined || b === undefined)
107
+ warnings.add('CONECT names atoms that were not read');
108
+ else
109
+ add(a, b);
110
+ }
111
+ const packed = positions.result(), sizes = Float32Array.from(radii);
112
+ if (options.guessBonds ?? true)
113
+ nearbyPairs(packed, sizes, add);
114
+ const result = {
115
+ kind: 'points',
116
+ positions: packed,
117
+ colors: colors.result(),
118
+ atoms,
119
+ radii: sizes,
120
+ bonds: bonds.result(),
121
+ warnings: [...warnings],
122
+ };
123
+ if (title.length)
124
+ result.title = title.join(' ');
125
+ return result;
126
+ }
package/dist/ply.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ type ScalarType = 'int8' | 'uint8' | 'int16' | 'uint16' | 'int32' | 'uint32' | 'float32' | 'float64';
4
+ /** One PLY property: its name, scalar type and, for a list, the count type. */
5
+ export interface PLYProperty {
6
+ name: string;
7
+ type: ScalarType;
8
+ list?: {
9
+ count: ScalarType;
10
+ };
11
+ }
12
+ /** One element of a PLY file (vertex, face, ...): its name, count and properties. */
13
+ export interface PLYElement {
14
+ name: string;
15
+ count: number;
16
+ properties: PLYProperty[];
17
+ }
18
+ /** A parsed PLY header: the data format, the elements, the comments and where the body starts. */
19
+ export interface PLYHeader {
20
+ format: 'ascii' | 'binary_little_endian' | 'binary_big_endian';
21
+ elements: PLYElement[];
22
+ comments: string[];
23
+ bodyOffset: number;
24
+ }
25
+ /** Options of parsePLY: the shared size limits (ParseLimits). */
26
+ export interface PLYOptions extends ParseLimits {
27
+ }
28
+ /** Parses only the PLY header. */
29
+ export declare function parsePLYHeader(input: BinaryInput): PLYHeader;
30
+ /**
31
+ * Parses an ASCII or binary (little or big endian) PLY file.
32
+ * Faces become a triangle fan; a file without faces is returned as a point cloud.
33
+ */
34
+ export declare function parsePLY(input: BinaryInput, options?: PLYOptions): LoadedGeometry;
35
+ export {};