@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
package/dist/lwo.d.ts ADDED
@@ -0,0 +1,81 @@
1
+ import { type LoadedGeometry, type LoadedGroup, type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** Options of {@link parseLWO}: the shared size limits. */
4
+ export interface LWOOptions extends ParseLimits {
5
+ }
6
+ /** One still image of an LWO2 `CLIP`. */
7
+ export interface LWOImage {
8
+ /** The clip's number, which a surface's image map points at. */
9
+ clip: number;
10
+ /** The path as written, in LightWave's form such as `Images:wall.jpg` or `D:/maps/wall.tga`. */
11
+ path: string;
12
+ }
13
+ /** One image layer of a {@link LWOSurface}. */
14
+ export interface LWOImageMap {
15
+ /** What the image drives: `COLR`, `DIFF`, `LUMI`, `SPEC`, `GLOS`, `REFL`, `TRAN`, `RIND`, `TRNL` or `BUMP`. */
16
+ channel: string;
17
+ /** The image's path, absent when the map names a clip the file does not hold. */
18
+ path?: string;
19
+ projection: 'planar' | 'cylindrical' | 'spherical' | 'cubic' | 'front' | 'uv';
20
+ /** The name of the map in {@link LWOModel.uvMaps} a `uv` projection reads. */
21
+ uvMap?: string;
22
+ /** False when the layer is switched off in the file. */
23
+ enabled: boolean;
24
+ }
25
+ /** One `SURF` of a {@link LWOModel}: the name is the `name` of the groups that use it. */
26
+ export interface LWOSurface {
27
+ name: string;
28
+ /** Base colour `[r, g, b]`, when the file gives one. */
29
+ color?: [number, number, number];
30
+ maps: LWOImageMap[];
31
+ }
32
+ /** One bone: a two-point `BONE` polygon, a skelegon. Coordinates are those of `positions`. */
33
+ export interface LWOBone {
34
+ /** The name a `BONE` tag gives it. */
35
+ name?: string;
36
+ start: [number, number, number];
37
+ end: [number, number, number];
38
+ /** Index in `bones` of the bone whose end is this one's start, -1 at a root. */
39
+ parent: number;
40
+ /** The name of its map in {@link LWOModel.weightMaps}. */
41
+ weightMap?: string;
42
+ /** The name of its layer. */
43
+ layer: string;
44
+ }
45
+ /** What {@link parseLWO} returns: one mesh with a group per layer and surface. Coordinates are in metres, Y up. */
46
+ export interface LWOModel extends LoadedGeometry {
47
+ kind: 'mesh';
48
+ groups: LoadedGroup[];
49
+ /** Every `TXUV` map by name, one uv per vertex; `uvs` is each layer's first. */
50
+ uvMaps: Record<string, Float32Array>;
51
+ /** Every `WGHT` map by name, one weight per vertex, 0 where the map has no value. */
52
+ weightMaps: Record<string, Float32Array>;
53
+ /** The still images of the file's clips; `loadTextures` from `@margoengine/loaders/textures` reads them. */
54
+ images: LWOImage[];
55
+ surfaces: LWOSurface[];
56
+ bones: LWOBone[];
57
+ /** Things the parser moved past, each listed once. */
58
+ warnings: string[];
59
+ }
60
+ /**
61
+ * Reads a LightWave `.lwo` object, LWO2 or LWOB: every layer's points and face polygons, `SURF` colours and image maps,
62
+ * every `TXUV` and `WGHT` map with its discontinuous `VMAD` values, which split a vertex along a seam, and `BONE`
63
+ * skelegons with their names and weight maps. Polygons are fan-triangulated. There is one group per layer and surface.
64
+ * Patch and subdivision polygons come in as their control cage, with a warning. Curves and clips that are not still
65
+ * images are skipped with a warning. `loadTextures` from `@margoengine/loaders/textures` reads the files in `images`.
66
+ *
67
+ * @param input The file's bytes.
68
+ * @param options The shared size limits.
69
+ * @returns The merged mesh.
70
+ * @throws LoaderError with code `header`, `truncated`, `range`, `limit` or `syntax` (no polygons).
71
+ *
72
+ * @example
73
+ * ```ts
74
+ * import { parseLWO } from '@margoengine/loaders/lwo';
75
+ *
76
+ * const bytes = await (await fetch('/models/lamp.lwo')).arrayBuffer();
77
+ * const { groups, surfaces, uvMaps, bones, warnings } = parseLWO(bytes);
78
+ * console.log(groups[0].name, surfaces[0]?.maps[0]?.path, Object.keys(uvMaps), bones.length, warnings);
79
+ * ```
80
+ */
81
+ export declare function parseLWO(input: BinaryInput, options?: LWOOptions): LWOModel;
package/dist/lwo.js ADDED
@@ -0,0 +1,454 @@
1
+ // LightWave .lwo objects: LWO2 and the older LWOB, with layers, polygons, surfaces, image maps, UV maps, bones and weights.
2
+ import { LoaderError } from './types.js';
3
+ import { CornerWelder, floats, latin1, limits, toBytes, triangulate, uints } from './util.js';
4
+ const F = 'LWO';
5
+ const NONE = 0xffffffff;
6
+ class Reader {
7
+ constructor(bytes, start, end) {
8
+ this.bytes = bytes;
9
+ this.end = end;
10
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11
+ this.pos = start;
12
+ }
13
+ get done() {
14
+ return this.pos >= this.end;
15
+ }
16
+ need(size) {
17
+ if (this.pos + size > this.end)
18
+ throw new LoaderError(F, 'truncated', 'a chunk ends early');
19
+ }
20
+ u16() {
21
+ this.need(2);
22
+ this.pos += 2;
23
+ return this.view.getUint16(this.pos - 2);
24
+ }
25
+ i16() {
26
+ this.need(2);
27
+ this.pos += 2;
28
+ return this.view.getInt16(this.pos - 2);
29
+ }
30
+ u32() {
31
+ this.need(4);
32
+ this.pos += 4;
33
+ return this.view.getUint32(this.pos - 4);
34
+ }
35
+ f32() {
36
+ this.need(4);
37
+ this.pos += 4;
38
+ return this.view.getFloat32(this.pos - 4);
39
+ }
40
+ id() {
41
+ this.need(4);
42
+ this.pos += 4;
43
+ return latin1(this.bytes, this.pos - 4, this.pos);
44
+ }
45
+ /** A zero-ended name padded to an even length. */
46
+ name() {
47
+ const start = this.pos;
48
+ while (this.pos < this.end && this.bytes[this.pos])
49
+ this.pos++;
50
+ if (this.pos >= this.end)
51
+ throw new LoaderError(F, 'truncated', 'a name has no end');
52
+ const text = latin1(this.bytes, start, this.pos);
53
+ this.pos += (this.pos - start) % 2 ? 1 : 2;
54
+ return text;
55
+ }
56
+ /** A variable-length index: two bytes, or four when the first byte is 0xFF. */
57
+ index() {
58
+ this.need(2);
59
+ if (this.bytes[this.pos] !== 0xff)
60
+ return this.u16();
61
+ return this.u32() & 0xffffff;
62
+ }
63
+ }
64
+ const emptyLayer = (name) => ({
65
+ name,
66
+ points: new Float32Array(0),
67
+ polygons: [],
68
+ bones: [],
69
+ maps: new Map(),
70
+ });
71
+ const PROJECTIONS = ['planar', 'cylindrical', 'spherical', 'cubic', 'front', 'uv'];
72
+ /** Reads a sub-chunk head, checks it against its chunk and returns the sub-chunk's id, its end, and where the next starts. */
73
+ function part(reader, end) {
74
+ const id = reader.id(), size = reader.u16(), stop = reader.pos + size;
75
+ if (stop > end)
76
+ throw new LoaderError(F, 'truncated', `surface part ${id} runs past its chunk`);
77
+ return [id, stop, stop + (size % 2)];
78
+ }
79
+ /** A `BLOK`: its header says what kind of layer it is, and only image maps are kept. */
80
+ function readBlock(reader, end) {
81
+ const map = { channel: 'COLR', projection: 'planar', enabled: true };
82
+ let image = false;
83
+ while (reader.pos + 6 <= end) {
84
+ const [id, stop, next] = part(reader, end);
85
+ if (id === 'IMAP') {
86
+ image = true;
87
+ reader.name();
88
+ while (reader.pos + 6 <= stop) {
89
+ const [field, , after] = part(reader, stop);
90
+ if (field === 'CHAN')
91
+ map.channel = reader.id();
92
+ else if (field === 'ENAB')
93
+ map.enabled = reader.u16() !== 0;
94
+ reader.pos = after;
95
+ }
96
+ }
97
+ else if (id === 'PROJ')
98
+ map.projection = PROJECTIONS[reader.u16()] ?? 'planar';
99
+ else if (id === 'IMAG')
100
+ map.clip = reader.index();
101
+ else if (id === 'VMAP')
102
+ map.uvMap = reader.name();
103
+ reader.pos = next;
104
+ }
105
+ return image ? map : undefined;
106
+ }
107
+ // LWOB names each texture by what it drives, and `TIMG` then gives its file.
108
+ const OLD_CHANNELS = {
109
+ CTEX: 'COLR',
110
+ DTEX: 'DIFF',
111
+ STEX: 'SPEC',
112
+ RTEX: 'REFL',
113
+ TTEX: 'TRAN',
114
+ LTEX: 'LUMI',
115
+ BTEX: 'BUMP',
116
+ };
117
+ function readSurface(reader, version) {
118
+ const surface = { name: reader.name(), maps: [] };
119
+ if (version === 2)
120
+ reader.name();
121
+ let old;
122
+ while (reader.pos + 6 <= reader.end) {
123
+ const [id, stop, next] = part(reader, reader.end);
124
+ if (id === 'COLR') {
125
+ if (version === 2)
126
+ surface.color = [reader.f32(), reader.f32(), reader.f32()];
127
+ else {
128
+ const { bytes, pos } = reader;
129
+ surface.color = [bytes[pos] / 255, bytes[pos + 1] / 255, bytes[pos + 2] / 255];
130
+ }
131
+ }
132
+ else if (id === 'BLOK') {
133
+ const map = readBlock(reader, stop);
134
+ if (map)
135
+ surface.maps.push(map);
136
+ }
137
+ else if (OLD_CHANNELS[id] && version === 1) {
138
+ const kind = reader.name().toLowerCase();
139
+ old = {
140
+ channel: OLD_CHANNELS[id],
141
+ projection: PROJECTIONS.find((name) => kind.startsWith(name.slice(0, 5))) ?? 'planar',
142
+ enabled: true,
143
+ };
144
+ }
145
+ else if (id === 'TIMG' && old) {
146
+ const path = reader.name();
147
+ if (path !== '(none)')
148
+ surface.maps.push({ ...old, path });
149
+ }
150
+ reader.pos = next;
151
+ }
152
+ return surface;
153
+ }
154
+ /**
155
+ * Reads a LightWave `.lwo` object, LWO2 or LWOB: every layer's points and face polygons, `SURF` colours and image maps,
156
+ * every `TXUV` and `WGHT` map with its discontinuous `VMAD` values, which split a vertex along a seam, and `BONE`
157
+ * skelegons with their names and weight maps. Polygons are fan-triangulated. There is one group per layer and surface.
158
+ * Patch and subdivision polygons come in as their control cage, with a warning. Curves and clips that are not still
159
+ * images are skipped with a warning. `loadTextures` from `@margoengine/loaders/textures` reads the files in `images`.
160
+ *
161
+ * @param input The file's bytes.
162
+ * @param options The shared size limits.
163
+ * @returns The merged mesh.
164
+ * @throws LoaderError with code `header`, `truncated`, `range`, `limit` or `syntax` (no polygons).
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * import { parseLWO } from '@margoengine/loaders/lwo';
169
+ *
170
+ * const bytes = await (await fetch('/models/lamp.lwo')).arrayBuffer();
171
+ * const { groups, surfaces, uvMaps, bones, warnings } = parseLWO(bytes);
172
+ * console.log(groups[0].name, surfaces[0]?.maps[0]?.path, Object.keys(uvMaps), bones.length, warnings);
173
+ * ```
174
+ */
175
+ export function parseLWO(input, options = {}) {
176
+ const bytes = toBytes(input, F), { maxVertices, maxTriangles } = limits(options, F);
177
+ if (bytes.length < 12)
178
+ throw new LoaderError(F, 'header', 'the file is too small');
179
+ const top = new Reader(bytes, 0, bytes.length);
180
+ if (top.id() !== 'FORM')
181
+ throw new LoaderError(F, 'header', 'missing the FORM header');
182
+ const end = Math.min(top.u32() + 8, bytes.length), form = top.id();
183
+ if (form !== 'LWO2' && form !== 'LWOB')
184
+ throw new LoaderError(F, 'header', `form type ${form.slice(0, 4)} is not LWO2 or LWOB`);
185
+ const version = form === 'LWO2' ? 2 : 1, layers = [], tags = [], images = [], surfaces = [], warnings = new Set();
186
+ let layer = emptyLayer(''), total = 0,
187
+ // PTAG and VMAD count from the start of the POLS before them, which may not be the layer's first.
188
+ recent = { type: 'FACE', base: 0 };
189
+ layers.push(layer);
190
+ const nextLayer = (name) => {
191
+ layers.push((layer = emptyLayer(name)));
192
+ recent = { type: 'FACE', base: 0 };
193
+ };
194
+ for (let pos = 12; pos + 8 <= end;) {
195
+ const head = new Reader(bytes, pos, end), id = head.id(), size = head.u32(), start = pos + 8, stop = start + size;
196
+ if (stop > end)
197
+ throw new LoaderError(F, 'truncated', `chunk ${id} runs past the file`);
198
+ pos = stop + (size % 2);
199
+ const chunk = new Reader(bytes, start, stop);
200
+ switch (id) {
201
+ case 'TAGS':
202
+ case 'SRFS':
203
+ while (!chunk.done)
204
+ tags.push(chunk.name());
205
+ break;
206
+ case 'LAYR': {
207
+ chunk.u16();
208
+ chunk.u16();
209
+ chunk.need(12);
210
+ chunk.pos += 12;
211
+ const name = chunk.name();
212
+ // The points before the first LAYR belong to that layer, so an empty opening layer is replaced.
213
+ if (layer.points.length || layer.polygons.length)
214
+ nextLayer(name);
215
+ else
216
+ layer.name = name;
217
+ break;
218
+ }
219
+ case 'PNTS': {
220
+ if (size % 12)
221
+ throw new LoaderError(F, 'syntax', 'PNTS is not whole points');
222
+ const count = size / 12;
223
+ total += count;
224
+ if (total > maxVertices)
225
+ throw new LoaderError(F, 'limit', `point count exceeds the limit of ${maxVertices}`);
226
+ if (layer.points.length)
227
+ nextLayer(layer.name);
228
+ layer.points = new Float32Array(size / 4);
229
+ for (let i = 0; i < layer.points.length; i++)
230
+ layer.points[i] = chunk.f32();
231
+ break;
232
+ }
233
+ case 'POLS': {
234
+ if (version === 2) {
235
+ const type = chunk.id(),
236
+ // Patches and subdivision polygons are faces of a control cage: without subdividing, the cage is the shape.
237
+ face = type === 'FACE' || type === 'PTCH' || type === 'SUBD';
238
+ recent = { type: face ? 'FACE' : type, base: type === 'BONE' ? layer.bones.length : layer.polygons.length };
239
+ if (!face && type !== 'BONE') {
240
+ warnings.add(`${type} polygons are not read`);
241
+ break;
242
+ }
243
+ if (face && type !== 'FACE')
244
+ warnings.add(`${type} polygons are read as their control cage`);
245
+ while (!chunk.done) {
246
+ const count = chunk.u16() & 0x3ff, corners = [];
247
+ for (let i = 0; i < count; i++)
248
+ corners.push(chunk.index());
249
+ if (face)
250
+ layer.polygons.push({ corners, surface: -1 });
251
+ else if (count === 2)
252
+ layer.bones.push({ corners });
253
+ else
254
+ throw new LoaderError(F, 'range', `a bone has ${count} points, not 2`);
255
+ }
256
+ }
257
+ else
258
+ while (!chunk.done) {
259
+ const count = chunk.u16(), corners = [];
260
+ for (let i = 0; i < count; i++)
261
+ corners.push(chunk.u16());
262
+ let surface = chunk.i16();
263
+ // A negative surface means detail polygons follow, under a count of their own.
264
+ if (surface < 0) {
265
+ surface = -surface;
266
+ chunk.u16();
267
+ }
268
+ layer.polygons.push({ corners, surface: surface - 1 });
269
+ }
270
+ break;
271
+ }
272
+ case 'PTAG': {
273
+ const type = chunk.id(), bones = type === 'BONE' || type === 'BNWT';
274
+ if (recent.type !== (bones ? 'BONE' : 'FACE') || (type !== 'SURF' && !bones))
275
+ break;
276
+ while (!chunk.done) {
277
+ const polygon = chunk.index(), tag = chunk.u16(), target = (bones ? layer.bones : layer.polygons)[recent.base + polygon];
278
+ if (!target)
279
+ throw new LoaderError(F, 'range', `PTAG names polygon ${polygon}, which does not exist`);
280
+ if (type === 'SURF')
281
+ target.surface = tag;
282
+ else if (type === 'BONE')
283
+ target.tag = tag;
284
+ else
285
+ target.weightTag = tag;
286
+ }
287
+ break;
288
+ }
289
+ case 'VMAP':
290
+ case 'VMAD': {
291
+ const type = chunk.id(), dimension = chunk.u16(), name = chunk.name();
292
+ if (!(type === 'TXUV' && dimension === 2) && !(type === 'WGHT' && dimension === 1))
293
+ break;
294
+ const key = `${type}:${name}`;
295
+ let map = layer.maps.get(key);
296
+ if (!map)
297
+ layer.maps.set(key, (map = { kind: type, name, points: new Map(), seams: new Map() }));
298
+ if (type === 'TXUV')
299
+ layer.firstUV ??= key;
300
+ const from = recent.type === 'FACE' ? recent.base : 0;
301
+ while (!chunk.done) {
302
+ const point = chunk.index(), polygon = id === 'VMAD' ? from + chunk.index() : -1, value = type === 'TXUV' ? [chunk.f32(), 1 - chunk.f32()] : [chunk.f32()];
303
+ if (id === 'VMAP')
304
+ map.points.set(point, value);
305
+ else {
306
+ let seam = map.seams.get(polygon);
307
+ if (!seam)
308
+ map.seams.set(polygon, (seam = new Map()));
309
+ seam.set(point, value);
310
+ }
311
+ }
312
+ break;
313
+ }
314
+ case 'SURF':
315
+ surfaces.push(readSurface(chunk, version));
316
+ break;
317
+ case 'CLIP': {
318
+ const clip = chunk.u32();
319
+ while (chunk.pos + 6 <= chunk.end) {
320
+ const [kind, , next] = part(chunk, chunk.end);
321
+ if (kind === 'STIL')
322
+ images.push({ clip, path: chunk.name() });
323
+ else if (kind === 'ISEQ' || kind === 'ANIM' || kind === 'XREF' || kind === 'STCC')
324
+ warnings.add(`${kind} clips are not read`);
325
+ chunk.pos = next;
326
+ }
327
+ break;
328
+ }
329
+ }
330
+ }
331
+ const positions = floats(), uvs = floats(), indices = uints(), groups = [], bones = [], textured = layers.some((entry) => entry.firstUV), outputs = new Map();
332
+ for (const entry of layers)
333
+ for (const [key, { kind, name }] of entry.maps)
334
+ if (!outputs.has(key))
335
+ outputs.set(key, { kind, name, size: kind === 'TXUV' ? 2 : 1, values: floats() });
336
+ for (const entry of layers) {
337
+ const pointCount = entry.points.length / 3, base = positions.length / 3, welder = new CornerWelder(pointCount), maps = [...entry.maps.values()], seamed = maps.some((map) => map.seams.size),
338
+ // The values one corner holds apart from its point, one per map; corners that agree share a row, so a vertex.
339
+ rows = [], rowOf = new Map(), bySurface = new Map(), numbered = new Map();
340
+ entry.polygons.forEach((polygon, i) => {
341
+ numbered.set(polygon, i);
342
+ let list = bySurface.get(polygon.surface);
343
+ if (!list)
344
+ bySurface.set(polygon.surface, (list = []));
345
+ list.push(polygon);
346
+ });
347
+ const cornerRow = (polygon, point) => {
348
+ if (!seamed)
349
+ return NONE;
350
+ const row = maps.map((map) => map.seams.get(polygon)?.get(point)), key = row.map((value) => value?.join() ?? '').join(';');
351
+ if (!row.some(Boolean))
352
+ return NONE;
353
+ let id = rowOf.get(key);
354
+ if (id === undefined) {
355
+ id = rows.push(row) - 1;
356
+ rowOf.set(key, id);
357
+ }
358
+ return id;
359
+ };
360
+ for (const [surface, polygons] of bySurface) {
361
+ const start = indices.length;
362
+ for (const polygon of polygons) {
363
+ const number = numbered.get(polygon);
364
+ const corners = polygon.corners.map((point) => {
365
+ if (!(point < pointCount))
366
+ throw new LoaderError(F, 'range', `polygon index ${point} is outside 0..${pointCount - 1}`);
367
+ return welder.weld(point, cornerRow(number, point), NONE, NONE);
368
+ });
369
+ if (base + welder.count > maxVertices)
370
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
371
+ const before = indices.length;
372
+ triangulate(indices, corners.length, (c) => corners[c], welder.count, F, maxTriangles);
373
+ for (let i = before; i < indices.length; i++)
374
+ indices.array[i] += base;
375
+ }
376
+ if (indices.length === start)
377
+ continue;
378
+ const name = tags[surface], group = { start, count: indices.length - start, name: name ?? entry.name }, color = name === undefined ? undefined : surfaces.find((item) => item.name === name)?.color;
379
+ if (entry.name)
380
+ group.objectId = entry.name;
381
+ if (color)
382
+ group.color = [...color, 1];
383
+ groups.push(group);
384
+ }
385
+ const keys = welder.keys.array, slots = new Map([...entry.maps.keys()].map((key, i) => [key, i]));
386
+ for (let v = 0; v < welder.count; v++) {
387
+ const point = keys[v * 4], row = keys[v * 4 + 1], at = point * 3;
388
+ // LightWave is left-handed with clockwise fronts: negating z gives right-handed, counter-clockwise fronts.
389
+ positions.push3(entry.points[at], entry.points[at + 1], -entry.points[at + 2]);
390
+ for (const [key, { size, values }] of outputs) {
391
+ const slot = slots.get(key), map = slot === undefined ? undefined : maps[slot], value = (row === NONE || slot === undefined ? undefined : rows[row][slot]) ?? map?.points.get(point);
392
+ for (let c = 0; c < size; c++)
393
+ values.push(value?.[c] ?? 0);
394
+ if (key === entry.firstUV) {
395
+ uvs.push(value?.[0] ?? 0);
396
+ uvs.push(value?.[1] ?? 0);
397
+ }
398
+ }
399
+ if (textured && !entry.firstUV) {
400
+ uvs.push(0);
401
+ uvs.push(0);
402
+ }
403
+ }
404
+ const first = bones.length, place = (point) => {
405
+ if (!(point < pointCount))
406
+ throw new LoaderError(F, 'range', `bone point ${point} is outside 0..${pointCount - 1}`);
407
+ return [entry.points[point * 3], entry.points[point * 3 + 1], -entry.points[point * 3 + 2]];
408
+ }, tips = new Map(entry.bones.map((bone, i) => [bone.corners[1], first + i]));
409
+ entry.bones.forEach((bone, i) => {
410
+ const out = {
411
+ start: place(bone.corners[0]),
412
+ end: place(bone.corners[1]),
413
+ parent: tips.get(bone.corners[0]) ?? -1,
414
+ layer: entry.name,
415
+ };
416
+ // A loop of bones has no root: the bone that closes it stands alone, so every chain ends.
417
+ for (let up = out.parent; up >= 0; up = bones[up]?.parent ?? -1)
418
+ if (up === first + i) {
419
+ out.parent = -1;
420
+ break;
421
+ }
422
+ if (bone.tag !== undefined && tags[bone.tag] !== undefined)
423
+ out.name = tags[bone.tag];
424
+ if (bone.weightTag !== undefined && tags[bone.weightTag] !== undefined)
425
+ out.weightMap = tags[bone.weightTag];
426
+ bones.push(out);
427
+ });
428
+ }
429
+ if (!indices.length)
430
+ throw new LoaderError(F, 'syntax', 'the file has no polygons');
431
+ const byClip = new Map(images.map(({ clip, path }) => [clip, path])), mapsOf = (kind) => Object.fromEntries([...outputs.values()].filter((map) => map.kind === kind).map(({ name, values }) => [name, values.result()]));
432
+ for (const surface of surfaces)
433
+ for (const map of surface.maps) {
434
+ const path = map.clip === undefined ? undefined : byClip.get(map.clip);
435
+ if (path !== undefined)
436
+ map.path = path;
437
+ delete map.clip;
438
+ }
439
+ const model = {
440
+ kind: 'mesh',
441
+ positions: positions.result(),
442
+ indices: indices.result(),
443
+ groups,
444
+ uvMaps: mapsOf('TXUV'),
445
+ weightMaps: mapsOf('WGHT'),
446
+ images,
447
+ surfaces,
448
+ bones,
449
+ warnings: [...warnings],
450
+ };
451
+ if (textured)
452
+ model.uvs = uvs.result();
453
+ return model;
454
+ }
package/dist/lzf.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Decompresses LZF data (the format PCL writes for PCD `DATA binary_compressed`) into exactly `outputLength` bytes.
3
+ * `format` names the calling format in errors (default 'LZF'). Every literal run and back reference is bounds checked.
4
+ *
5
+ * The stream is a sequence of items, each led by a control byte. Below 32 it is a literal run of control + 1 bytes.
6
+ * Otherwise the top 3 bits are a length field (7 means one more length byte follows), the low 5 bits are the high
7
+ * part of a 13-bit distance whose low byte comes next; the match copies length field + 2 bytes from distance + 1
8
+ * bytes back. There is no header or end marker: the stream ends with the input.
9
+ *
10
+ * @throws LoaderError with code `'range'` for a bad `outputLength` or a run or reference outside the output, and
11
+ * `'truncated'` when the input ends inside an item or before `outputLength` bytes were produced.
12
+ */
13
+ export declare function decompressLZF(input: Uint8Array, outputLength: number, format?: string): Uint8Array;
package/dist/lzf.js ADDED
@@ -0,0 +1,56 @@
1
+ import { LoaderError } from './types.js';
2
+ /**
3
+ * Decompresses LZF data (the format PCL writes for PCD `DATA binary_compressed`) into exactly `outputLength` bytes.
4
+ * `format` names the calling format in errors (default 'LZF'). Every literal run and back reference is bounds checked.
5
+ *
6
+ * The stream is a sequence of items, each led by a control byte. Below 32 it is a literal run of control + 1 bytes.
7
+ * Otherwise the top 3 bits are a length field (7 means one more length byte follows), the low 5 bits are the high
8
+ * part of a 13-bit distance whose low byte comes next; the match copies length field + 2 bytes from distance + 1
9
+ * bytes back. There is no header or end marker: the stream ends with the input.
10
+ *
11
+ * @throws LoaderError with code `'range'` for a bad `outputLength` or a run or reference outside the output, and
12
+ * `'truncated'` when the input ends inside an item or before `outputLength` bytes were produced.
13
+ */
14
+ export function decompressLZF(input, outputLength, format = 'LZF') {
15
+ if (!Number.isSafeInteger(outputLength) || outputLength < 0)
16
+ throw new LoaderError(format, 'range', `invalid LZF output length ${outputLength}`);
17
+ const out = new Uint8Array(outputLength);
18
+ const end = input.length;
19
+ let read = 0;
20
+ let write = 0;
21
+ while (read < end) {
22
+ const control = input[read++];
23
+ if (control < 32) {
24
+ // Literal run of 1 to 32 bytes.
25
+ const run = control + 1;
26
+ if (write + run > outputLength)
27
+ throw new LoaderError(format, 'range', 'LZF literal run overflows the output');
28
+ if (read + run > end)
29
+ throw new LoaderError(format, 'truncated', 'LZF literal run overflows the input');
30
+ out.set(input.subarray(read, read + run), write);
31
+ read += run;
32
+ write += run;
33
+ continue;
34
+ }
35
+ // Back reference: 3-bit length field (7 = extended), 13-bit distance.
36
+ let field = control >> 5;
37
+ const needed = field === 7 ? 2 : 1;
38
+ if (read + needed > end)
39
+ throw new LoaderError(format, 'truncated', 'LZF back reference overflows the input');
40
+ if (field === 7)
41
+ field += input[read++];
42
+ const distance = ((control & 31) << 8) + input[read++] + 1;
43
+ const length = field + 2;
44
+ if (write + length > outputLength)
45
+ throw new LoaderError(format, 'range', 'LZF back reference overflows the output');
46
+ let from = write - distance;
47
+ if (from < 0)
48
+ throw new LoaderError(format, 'range', 'LZF back reference points before the output');
49
+ // Byte by byte, front to back, so a distance shorter than the length repeats the most recent bytes.
50
+ for (const stop = write + length; write < stop;)
51
+ out[write++] = out[from++];
52
+ }
53
+ if (write !== outputLength)
54
+ throw new LoaderError(format, 'truncated', `LZF produced ${write} bytes, expected ${outputLength}`);
55
+ return out;
56
+ }