@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/tmx.js ADDED
@@ -0,0 +1,394 @@
1
+ import { LoaderError } from './types.js';
2
+ import { resolvePath, throwIfAborted, toBytes } from './util.js';
3
+ import { decodeXML, readXMLTree } from './xml.js';
4
+ import { inflate } from './zip.js';
5
+ const F = 'TMX';
6
+ /** Cells per tile layer (4096 x 4096). */
7
+ const MAX_TILES = 1 << 24;
8
+ const GID = 0x0fffffff;
9
+ const kid = (e, name) => e?.children.find((c) => c.name === name);
10
+ const kids = (e, name) => e?.children.filter((c) => c.name === name) ?? [];
11
+ const text = (input) => (typeof input === 'string' ? input : decodeXML(input));
12
+ function number(value, fallback, what) {
13
+ if (value === undefined)
14
+ return fallback;
15
+ const result = Number(value);
16
+ if (!Number.isFinite(result) || value.trim() === '')
17
+ throw new LoaderError(F, 'syntax', `${what} must be a number, got "${value.slice(0, 32)}"`);
18
+ return result;
19
+ }
20
+ function integer(value, fallback, what, min = 0) {
21
+ const result = number(value, fallback, what);
22
+ if (!Number.isSafeInteger(result) || result < min)
23
+ throw new LoaderError(F, 'syntax', `${what} must be an integer of at least ${min}, got "${value}"`);
24
+ return result;
25
+ }
26
+ const flipsOf = (gid) => (gid >>> 31) | (((gid >>> 30) & 1) << 1) | (((gid >>> 29) & 1) << 2);
27
+ function readProperties(e) {
28
+ const properties = Object.create(null);
29
+ for (const p of kids(kid(e, 'properties'), 'property')) {
30
+ const name = p.attributes.name;
31
+ if (name === undefined)
32
+ continue;
33
+ const raw = p.attributes.value ?? p.text, type = p.attributes.type;
34
+ properties[name] =
35
+ type === 'int' || type === 'float'
36
+ ? number(raw, 0, `property "${name}"`)
37
+ : type === 'bool'
38
+ ? raw === 'true'
39
+ : raw;
40
+ }
41
+ return properties;
42
+ }
43
+ function readTileset(e, from) {
44
+ const a = e.attributes, what = `tileset "${a.name ?? ''}"`;
45
+ const tileset = {
46
+ tilewidth: integer(a.tilewidth, 0, `${what} tilewidth`, 1),
47
+ tileheight: integer(a.tileheight, 0, `${what} tileheight`, 1),
48
+ spacing: integer(a.spacing, 0, `${what} spacing`),
49
+ margin: integer(a.margin, 0, `${what} margin`),
50
+ columns: 0,
51
+ tilecount: 0,
52
+ tileoffset: { x: 0, y: 0 },
53
+ properties: readProperties(e),
54
+ };
55
+ const offset = kid(e, 'tileoffset');
56
+ if (offset)
57
+ tileset.tileoffset = {
58
+ x: number(offset.attributes.x, 0, `${what} tileoffset x`),
59
+ y: number(offset.attributes.y, 0, `${what} tileoffset y`),
60
+ };
61
+ if (a.name !== undefined)
62
+ tileset.name = a.name;
63
+ const image = kid(e, 'image');
64
+ if (image?.attributes.source !== undefined)
65
+ tileset.image = {
66
+ path: resolvePath(from, image.attributes.source),
67
+ width: integer(image.attributes.width, 0, `${what} image width`),
68
+ height: integer(image.attributes.height, 0, `${what} image height`),
69
+ };
70
+ const { tilewidth, tileheight, spacing, margin } = tileset, fit = (size, tile) => Math.max(0, Math.floor((size - 2 * margin + spacing) / (tile + spacing)));
71
+ tileset.columns = integer(a.columns, tileset.image ? fit(tileset.image.width, tilewidth) : 0, `${what} columns`);
72
+ tileset.tilecount = integer(a.tilecount, tileset.image ? tileset.columns * fit(tileset.image.height, tileheight) : 0, `${what} tilecount`);
73
+ return tileset;
74
+ }
75
+ function base64(value, what) {
76
+ let binary;
77
+ try {
78
+ binary = atob(value.replace(/\s+/g, ''));
79
+ }
80
+ catch {
81
+ throw new LoaderError(F, 'syntax', `${what} is not valid base64`);
82
+ }
83
+ const bytes = new Uint8Array(binary.length);
84
+ for (let i = 0; i < binary.length; i++)
85
+ bytes[i] = binary.charCodeAt(i);
86
+ return bytes;
87
+ }
88
+ /** Decodes a `<data>` or `<chunk>` of `count` cells into raw gids (flip bits included). */
89
+ async function decodeCells(e, encoding, compression, count, what, signal) {
90
+ const cells = new Uint32Array(count);
91
+ if (encoding === 'csv') {
92
+ const values = e.text.split(/[\s,]+/).filter(Boolean);
93
+ if (values.length !== count)
94
+ throw new LoaderError(F, 'syntax', `${what} has ${values.length} csv values, expected ${count}`);
95
+ for (let i = 0; i < count; i++) {
96
+ const gid = Number(values[i]);
97
+ if (!Number.isInteger(gid) || gid < 0 || gid > 0xffffffff)
98
+ throw new LoaderError(F, 'syntax', `${what} has the invalid gid "${values[i].slice(0, 16)}"`);
99
+ cells[i] = gid;
100
+ }
101
+ }
102
+ else if (encoding === 'base64') {
103
+ let bytes = base64(e.text, what);
104
+ if (compression)
105
+ bytes = await inflate(bytes, count * 4, what, signal, compression === 'zlib' ? 'deflate' : 'gzip', F);
106
+ if (bytes.length !== count * 4)
107
+ throw new LoaderError(F, 'syntax', `${what} holds ${bytes.length} bytes, expected ${count * 4}`);
108
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
109
+ for (let i = 0; i < count; i++)
110
+ cells[i] = view.getUint32(i * 4, true);
111
+ }
112
+ else if (encoding === undefined) {
113
+ const tiles = kids(e, 'tile');
114
+ if (tiles.length !== count)
115
+ throw new LoaderError(F, 'syntax', `${what} has ${tiles.length} <tile>s, expected ${count}`);
116
+ for (let i = 0; i < count; i++) {
117
+ const gid = number(tiles[i].attributes.gid, 0, `${what} tile gid`);
118
+ if (!Number.isInteger(gid) || gid < 0 || gid > 0xffffffff)
119
+ throw new LoaderError(F, 'syntax', `${what} has the invalid gid "${tiles[i].attributes.gid}"`);
120
+ cells[i] = gid;
121
+ }
122
+ }
123
+ else
124
+ throw new LoaderError(F, 'unsupported', `${what} uses the unknown encoding "${encoding.slice(0, 16)}"`);
125
+ return cells;
126
+ }
127
+ async function readTileLayer(e, common, map, signal) {
128
+ const what = `layer "${common.name}"`, data = kid(e, 'data');
129
+ if (!data)
130
+ throw new LoaderError(F, 'syntax', `${what} has no <data>`);
131
+ const { encoding, compression } = data.attributes;
132
+ if (compression === 'zstd')
133
+ throw new LoaderError(F, 'unsupported', `${what} uses zstd compression; save the map with zlib, gzip or no compression`);
134
+ if (compression !== undefined && compression !== 'zlib' && compression !== 'gzip')
135
+ throw new LoaderError(F, 'unsupported', `${what} uses the unknown compression "${compression.slice(0, 16)}"`);
136
+ const chunks = kids(data, 'chunk').map((c) => ({
137
+ element: c,
138
+ x: integer(c.attributes.x, 0, `${what} chunk x`, -Number.MAX_SAFE_INTEGER),
139
+ y: integer(c.attributes.y, 0, `${what} chunk y`, -Number.MAX_SAFE_INTEGER),
140
+ width: integer(c.attributes.width, 0, `${what} chunk width`),
141
+ height: integer(c.attributes.height, 0, `${what} chunk height`),
142
+ }));
143
+ let x = 0, y = 0, width = integer(e.attributes.width, map.width, `${what} width`), height = integer(e.attributes.height, map.height, `${what} height`);
144
+ if (map.infinite && !chunks.length)
145
+ width = height = 0;
146
+ else if (chunks.length) {
147
+ // reduce, not Math.min(...spread): a large map has more chunks than a call takes arguments.
148
+ x = chunks.reduce((m, c) => Math.min(m, c.x), Infinity);
149
+ y = chunks.reduce((m, c) => Math.min(m, c.y), Infinity);
150
+ width = chunks.reduce((m, c) => Math.max(m, c.x + c.width), -Infinity) - x;
151
+ height = chunks.reduce((m, c) => Math.max(m, c.y + c.height), -Infinity) - y;
152
+ }
153
+ if (width * height > MAX_TILES)
154
+ throw new LoaderError(F, 'limit', `${what} spans ${width} x ${height} cells, more than the limit of ${MAX_TILES}`);
155
+ let raw;
156
+ if (!width || !height)
157
+ raw = new Uint32Array(0);
158
+ else if (!chunks.length)
159
+ raw = await decodeCells(data, encoding, compression, width * height, `${what} data`, signal);
160
+ else {
161
+ raw = new Uint32Array(width * height);
162
+ for (const c of chunks) {
163
+ const cells = await decodeCells(c.element, encoding, compression, c.width * c.height, `${what} chunk ${c.x},${c.y}`, signal);
164
+ for (let row = 0; row < c.height; row++)
165
+ raw.set(cells.subarray(row * c.width, (row + 1) * c.width), (c.y - y + row) * width + (c.x - x));
166
+ }
167
+ }
168
+ const gids = new Uint32Array(raw.length), flips = new Uint8Array(raw.length);
169
+ for (let i = 0; i < raw.length; i++) {
170
+ gids[i] = raw[i] & GID;
171
+ flips[i] = flipsOf(raw[i]);
172
+ }
173
+ return { type: 'tile', ...common, x, y, width, height, gids, flips };
174
+ }
175
+ function readObject(e) {
176
+ const a = e.attributes, what = `object ${a.id ?? a.name ?? ''}`;
177
+ const object = {
178
+ name: a.name ?? '',
179
+ type: a.type ?? a.class ?? '',
180
+ x: number(a.x, 0, `${what} x`),
181
+ y: number(a.y, 0, `${what} y`),
182
+ width: number(a.width, 0, `${what} width`),
183
+ height: number(a.height, 0, `${what} height`),
184
+ rotation: number(a.rotation, 0, `${what} rotation`),
185
+ visible: a.visible !== '0',
186
+ properties: readProperties(e),
187
+ };
188
+ if (a.id !== undefined)
189
+ object.id = integer(a.id, 0, `${what} id`);
190
+ if (a.gid !== undefined) {
191
+ const gid = integer(a.gid, 0, `${what} gid`);
192
+ if (gid > 0xffffffff)
193
+ throw new LoaderError(F, 'syntax', `${what} gid ${gid} is not a 32-bit id`);
194
+ object.gid = gid & GID;
195
+ object.flips = flipsOf(gid);
196
+ }
197
+ return object;
198
+ }
199
+ /**
200
+ * Parses a Tiled TMX map (orthogonal; other orientations throw `unsupported`): map attributes, embedded and external
201
+ * (TSX, through `resolve`) tilesets merged when their image and grid match, tile layers in csv, base64 (plain, zlib or
202
+ * gzip; zstd throws `unsupported`) or legacy `<tile>` data and infinite-map chunks, GID flip bits split into `flips`,
203
+ * object layers, custom properties, and group layers flattened with their offsets, visibility and opacity combined.
204
+ * Turn a tile layer into geometry with `tmxLayerQuads`.
205
+ */
206
+ export async function parseTMX(input, options = {}) {
207
+ const { resolve, signal } = options;
208
+ throwIfAborted(signal, F);
209
+ if (resolve !== undefined && typeof resolve !== 'function')
210
+ throw new TypeError('TMX resolve option is not a function; pass (path) => Promise<Uint8Array | string>');
211
+ const root = readXMLTree(typeof input === 'string' ? input : decodeXML(toBytes(input, F)), F, {
212
+ external: options.external,
213
+ }).children[0];
214
+ if (root?.name !== 'map')
215
+ throw new LoaderError(F, 'header', `root element is <${root?.name ?? ''}>, not <map>`);
216
+ const a = root.attributes, orientation = a.orientation ?? 'orthogonal';
217
+ if (orientation !== 'orthogonal')
218
+ throw new LoaderError(F, 'unsupported', `${orientation.slice(0, 16)} maps are not supported; only orthogonal ones`);
219
+ const map = {
220
+ orientation,
221
+ renderorder: a.renderorder ?? 'right-down',
222
+ width: integer(a.width, 0, 'map width'),
223
+ height: integer(a.height, 0, 'map height'),
224
+ tilewidth: integer(a.tilewidth, 0, 'map tilewidth', 1),
225
+ tileheight: integer(a.tileheight, 0, 'map tileheight', 1),
226
+ infinite: a.infinite === '1',
227
+ tilesets: [],
228
+ tilesetRefs: [],
229
+ layers: [],
230
+ properties: readProperties(root),
231
+ warnings: [],
232
+ };
233
+ const sources = new Map(), merged = new Map();
234
+ for (const e of kids(root, 'tileset')) {
235
+ const firstgid = integer(e.attributes.firstgid, 0, 'tileset firstgid', 1);
236
+ let element = e, source;
237
+ if (e.attributes.source !== undefined) {
238
+ source = resolvePath('', e.attributes.source);
239
+ let tsx = sources.get(source);
240
+ if (!tsx) {
241
+ if (!resolve)
242
+ throw new LoaderError(F, 'fetch', `tileset "${source}" is external; pass resolve(path) to read it`);
243
+ let content;
244
+ try {
245
+ content = await resolve(source);
246
+ }
247
+ catch (error) {
248
+ throwIfAborted(signal, F);
249
+ throw new LoaderError(F, 'fetch', `tileset "${source}" could not be read (${error?.message ?? error})`);
250
+ }
251
+ throwIfAborted(signal, F);
252
+ tsx = readXMLTree(text(content), 'TSX', { external: options.external }).children[0];
253
+ if (tsx?.name !== 'tileset')
254
+ throw new LoaderError(F, 'header', `tileset "${source}" root element is <${tsx?.name ?? ''}>, not <tileset>`);
255
+ sources.set(source, tsx);
256
+ }
257
+ element = tsx;
258
+ }
259
+ const tileset = readTileset(element, source ?? '');
260
+ if (source !== undefined)
261
+ tileset.source = source;
262
+ if (!tileset.image)
263
+ map.warnings.push(`tileset "${tileset.name ?? source ?? firstgid}" has no atlas image (image collections are not imported)`);
264
+ const key = tileset.image
265
+ ? [
266
+ tileset.image.path,
267
+ tileset.tilewidth,
268
+ tileset.tileheight,
269
+ tileset.spacing,
270
+ tileset.margin,
271
+ tileset.tileoffset.x,
272
+ tileset.tileoffset.y,
273
+ ].join('|')
274
+ : undefined;
275
+ let index = key === undefined ? undefined : merged.get(key);
276
+ if (index === undefined) {
277
+ index = map.tilesets.push(tileset) - 1;
278
+ if (key !== undefined)
279
+ merged.set(key, index);
280
+ }
281
+ map.tilesetRefs.push({ firstgid, tileset: index });
282
+ }
283
+ map.tilesetRefs.sort((p, q) => p.firstgid - q.firstgid);
284
+ const walk = async (parent, outer) => {
285
+ for (const e of parent.children) {
286
+ if (e.name !== 'layer' && e.name !== 'objectgroup' && e.name !== 'group' && e.name !== 'imagelayer')
287
+ continue;
288
+ const b = e.attributes, name = b.name ?? '', inherited = {
289
+ visible: outer.visible && b.visible !== '0',
290
+ opacity: outer.opacity * number(b.opacity, 1, `layer "${name}" opacity`),
291
+ offsetx: outer.offsetx + number(b.offsetx, 0, `layer "${name}" offsetx`),
292
+ offsety: outer.offsety + number(b.offsety, 0, `layer "${name}" offsety`),
293
+ };
294
+ if (e.name === 'group') {
295
+ await walk(e, inherited);
296
+ continue;
297
+ }
298
+ if (e.name === 'imagelayer') {
299
+ map.warnings.push(`image layer "${name}" is not imported`);
300
+ continue;
301
+ }
302
+ const common = { name, ...inherited, properties: readProperties(e) };
303
+ if (b.id !== undefined)
304
+ common.id = integer(b.id, 0, `layer "${name}" id`);
305
+ map.layers.push(e.name === 'layer'
306
+ ? await readTileLayer(e, common, map, signal)
307
+ : { type: 'object', ...common, objects: kids(e, 'object').map(readObject) });
308
+ }
309
+ };
310
+ await walk(root, { visible: true, opacity: 1, offsetx: 0, offsety: 0 });
311
+ return map;
312
+ }
313
+ /**
314
+ * Turns a tile layer into quads on the XZ plane, facing +Y: map column x runs along +X and row y along +Z, one cell
315
+ * `tileSize` wide, layer pixel offsets scaled by the map's tile size. Tiles larger than a cell grow from its
316
+ * bottom-left corner, as Tiled draws them, moved by the tileset's `<tileoffset>`. UVs (Margo's convention, v = 0 at the top of the image) cover each tile's
317
+ * atlas rectangle, honoring spacing and margin, with the diagonal, horizontal and vertical flips applied in Tiled's
318
+ * order.
319
+ */
320
+ export function tmxLayerQuads(map, layer, options = {}) {
321
+ const size = options.tileSize ?? 1;
322
+ if (!(size > 0) || !Number.isFinite(size))
323
+ throw new RangeError(`tileSize must be a positive number, got ${size}`);
324
+ if (!layer || layer.type !== 'tile' || layer.gids.length !== layer.width * layer.height)
325
+ throw new TypeError('tmxLayerQuads needs a tile layer from parseTMX; pass map.layers[i] with type "tile"');
326
+ const refs = map.tilesetRefs, owner = new Uint32Array(layer.gids.length), counts = new Uint32Array(map.tilesets.length);
327
+ let quads = 0;
328
+ for (let cell = 0; cell < layer.gids.length; cell++) {
329
+ const gid = layer.gids[cell];
330
+ if (!gid)
331
+ continue;
332
+ let r = refs.length - 1;
333
+ while (r >= 0 && refs[r].firstgid > gid)
334
+ r--;
335
+ if (r < 0)
336
+ throw new LoaderError(F, 'range', `layer "${layer.name}" gid ${gid} belongs to no tileset`);
337
+ const tileset = map.tilesets[refs[r].tileset];
338
+ if (!tileset.image?.width || !tileset.image.height || !tileset.columns)
339
+ throw new LoaderError(F, 'unsupported', `tileset "${tileset.name ?? ''}" has no atlas image size; save it with Tiled 1.0 or later`);
340
+ if (gid - refs[r].firstgid >= tileset.tilecount)
341
+ throw new LoaderError(F, 'range', `layer "${layer.name}" gid ${gid} is past the end of tileset "${tileset.name ?? ''}"`);
342
+ owner[cell] = r;
343
+ counts[refs[r].tileset]++;
344
+ quads++;
345
+ }
346
+ const positions = new Float32Array(quads * 12), normals = new Float32Array(quads * 12), uvs = new Float32Array(quads * 8), indices = new Uint32Array(quads * 6), cells = new Uint32Array(quads), groups = [], next = new Uint32Array(map.tilesets.length);
347
+ for (let t = 0, start = 0; t < counts.length; start += counts[t++]) {
348
+ next[t] = start;
349
+ if (counts[t]) {
350
+ const group = { start: start * 6, count: counts[t] * 6, tileset: t };
351
+ if (map.tilesets[t].name !== undefined)
352
+ group.name = map.tilesets[t].name;
353
+ groups.push(group);
354
+ }
355
+ }
356
+ const ox = (layer.offsetx / map.tilewidth) * size, oz = (layer.offsety / map.tileheight) * size;
357
+ // Corner order TL, BL, BR, TR as (sx, sy) inside the tile, sy down.
358
+ const corners = [0, 0, 0, 1, 1, 1, 1, 0];
359
+ for (let cell = 0; cell < layer.gids.length; cell++) {
360
+ const gid = layer.gids[cell];
361
+ if (!gid)
362
+ continue;
363
+ const ref = refs[owner[cell]], tileset = map.tilesets[ref.tileset], image = tileset.image, q = next[ref.tileset]++, local = gid - ref.firstgid, px = tileset.margin + (local % tileset.columns) * (tileset.tilewidth + tileset.spacing), py = tileset.margin + Math.floor(local / tileset.columns) * (tileset.tileheight + tileset.spacing), flip = layer.flips[cell],
364
+ // TMX Map Format, <tileoffset>: the tileset's pixel offset (y down) moves every tile drawn from it.
365
+ x0 = (layer.x + (cell % layer.width)) * size + ox + (tileset.tileoffset.x / map.tilewidth) * size, z1 = (layer.y + Math.floor(cell / layer.width) + 1) * size + oz + (tileset.tileoffset.y / map.tileheight) * size, w = (tileset.tilewidth / map.tilewidth) * size, h = (tileset.tileheight / map.tileheight) * size;
366
+ cells[q] = cell;
367
+ for (let k = 0; k < 4; k++) {
368
+ let sx = corners[k * 2], sy = corners[k * 2 + 1];
369
+ positions[q * 12 + k * 3] = x0 + sx * w;
370
+ positions[q * 12 + k * 3 + 2] = z1 - (1 - sy) * h;
371
+ normals[q * 12 + k * 3 + 1] = 1;
372
+ // The displayed corner shows the texel D(H(V(corner))): undo the flips in reverse order.
373
+ if (flip & 2)
374
+ sy = 1 - sy;
375
+ if (flip & 1)
376
+ sx = 1 - sx;
377
+ if (flip & 4)
378
+ [sx, sy] = [sy, sx];
379
+ uvs[q * 8 + k * 2] = (px + sx * tileset.tilewidth) / image.width;
380
+ uvs[q * 8 + k * 2 + 1] = (py + sy * tileset.tileheight) / image.height;
381
+ }
382
+ indices.set([0, 1, 2, 0, 2, 3].map((i) => q * 4 + i), q * 6);
383
+ }
384
+ return {
385
+ kind: 'mesh',
386
+ positions,
387
+ normals,
388
+ uvs,
389
+ indices,
390
+ faceSizes: new Uint32Array(quads).fill(4),
391
+ groups,
392
+ cells,
393
+ };
394
+ }
package/dist/ttf.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { type BinaryInput } from './util.js';
2
+ import type { OutlineCommand } from './outline.js';
3
+ import { OutlineFont, type OutlineFontSource } from './outline-font.js';
4
+ import { BinaryReader } from './sfnt-reader.js';
5
+ import type { FontVariationAxis } from './sfnt-variation.js';
6
+ import { type VariationDelta } from './sfnt-layout.js';
7
+ /** Options of `parseTTF`. */
8
+ export interface TTFParseOptions {
9
+ /** Font to read from a TrueType collection (`.ttc`), 0-based. Default 0. Ignored for single fonts. */
10
+ fontIndex?: number;
11
+ /**
12
+ * Instance of a variable font: axis tag to value in the font's `fvar` user units (for example `{ wght: 700 }`),
13
+ * clamped to the axis range. Omitted axes use their defaults; a tag the font does not have throws. Default {}.
14
+ */
15
+ variations?: Readonly<Record<string, number>>;
16
+ /**
17
+ * The CFF, CFF2 and font-variation readers, from `@margoengine/loaders/font-opentype` (`openType`). Without them
18
+ * `parseTTF` reads TrueType outlines and the default instance of a variable font, and a CFF font or a `variations`
19
+ * instance throws a `LoaderError` with code `'unsupported'` naming this option. Default none.
20
+ */
21
+ openType?: OpenTypeReaders;
22
+ }
23
+ /** The CFF, CFF2 and variation readers `parseTTF` takes as `openType`; get them from `@margoengine/loaders/font-opentype`. */
24
+ export interface OpenTypeReaders {
25
+ readonly name: 'opentype';
26
+ }
27
+ /** The variation state the glyph decoder uses: axes, the instance, gvar point deltas and HVAR advances. */
28
+ export interface VariationState {
29
+ readonly axes: FontVariationAxis[];
30
+ readonly coordinates: number[];
31
+ readonly hasGlyphVariations: boolean;
32
+ advance(glyph: number): number | undefined;
33
+ deltas(glyph: number, points: readonly (readonly number[])[], ends: readonly number[], composite?: boolean): [number[], number[]];
34
+ }
35
+ /** What `openType` holds (internal: only `@margoengine/loaders/font-opentype` builds it). */
36
+ export interface OpenTypeReaderSet extends OpenTypeReaders {
37
+ cff(table: BinaryReader, cff2: boolean, glyphCount: number, unitsPerEm: number, coordinates: readonly number[]): {
38
+ commands(glyph: number): OutlineCommand[];
39
+ };
40
+ variations(tables: Map<string, BinaryReader>, glyphCount: number, values: Readonly<Record<string, number>>): VariationState;
41
+ /** The deltas of GDEF's item variation store at `coordinates`; undefined when GDEF holds none. */
42
+ layoutDeltas(gdef: BinaryReader, coordinates: readonly number[]): VariationDelta | undefined;
43
+ }
44
+ /** What `parseTTFSource` reads: an `OutlineFontSource` plus the font's variation state and raw tables. */
45
+ export interface TTFFontSource extends OutlineFontSource {
46
+ /** The variation axes of a variable font (`fvar`), empty for a static font. */
47
+ readonly variationAxes: readonly FontVariationAxis[];
48
+ /** The instance's normalized coordinate on each axis, -1 to 1 (0 is the default instance). */
49
+ readonly variationCoordinates: readonly number[];
50
+ /** The bytes of an sfnt table by tag, such as `'GPOS'`, `'GSUB'` or `'kern'`, or undefined when the font has none. */
51
+ table(tag: string): Uint8Array | undefined;
52
+ /**
53
+ * Kerning between two glyph indices in font units: the GPOS `kern` feature of `script` (default 'latn'; then DFLT,
54
+ * then latn), with its variation deltas on a variable instance, else the `kern` table's pair; 0 when neither has it.
55
+ */
56
+ kerning(left: number, right: number, script?: string): number;
57
+ }
58
+ /**
59
+ * Reads an OpenType font (`.ttf`, `.otf`, or one font of a `.ttc` collection) into an `OutlineFontSource`, from the
60
+ * OpenType specification's tables: `head`, `hhea`, `maxp`, `hmtx`; TrueType `loca` and `glyf` (simple and composite
61
+ * glyphs with offsets, scales, 2x2 transforms, point matching and ROUND_XY_TO_GRID) or CFF (`'CFF '`, Type 2
62
+ * charstrings with subroutines and `endchar` accents) and CFF2 outlines (Font DICT selection and blends); variable
63
+ * fonts through `fvar`, `avar`, `gvar` (with interpolation of untouched points and phantom-point advances), `HVAR`
64
+ * and the CFF2 ItemVariationStore; `cmap` formats 4 and 12; GPOS pair kerning (the `kern` feature, with its variation
65
+ * deltas) or `kern` format 0 pairs; and the family and style names.
66
+ * Glyphs decode lazily. `parseTTF` wraps the result in an `OutlineFont`; use this function when only the parser is
67
+ * needed. WOFF and WOFF2 throw a `LoaderError` with code `'unsupported'` naming `@margoengine/loaders/font-woff`,
68
+ * which decodes them; malformed tables throw `'header'`, `'truncated'`, `'range'` or `'limit'`.
69
+ */
70
+ export declare function parseTTFSource(input: BinaryInput, options?: TTFParseOptions): TTFFontSource;
71
+ /**
72
+ * Parses an OpenType font (`.ttf`, `.otf`, or one font of a `.ttc` collection) into an `OutlineFont`: TrueType or
73
+ * CFF/CFF2 outlines, variable fonts at `options.variations`, `cmap` formats 4 and 12, GPOS or `kern` pair kerning and
74
+ * the family and style names (see `parseTTFSource` for the tables read). Glyphs decode lazily. WOFF and WOFF2 throw a
75
+ * `LoaderError` with code `'unsupported'` (`parseWOFF` of `@margoengine/loaders/font-woff` reads them); malformed
76
+ * tables throw `'header'`, `'truncated'`, `'range'` or `'limit'`.
77
+ */
78
+ export declare function parseTTF(input: BinaryInput, options?: TTFParseOptions): OutlineFont;