@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/ttf.js ADDED
@@ -0,0 +1,568 @@
1
+ import { LoaderError } from './types.js';
2
+ import { toBytes } from './util.js';
3
+ import { OutlineFont } from './outline-font.js';
4
+ import { BinaryReader } from './sfnt-reader.js';
5
+ import { gposKerning } from './sfnt-layout.js';
6
+ const F = 'TTF';
7
+ /** Nested composite glyphs deeper than this throw (the OpenType maxp table allows at most 16 levels in practice). */
8
+ const MAX_DEPTH = 16;
9
+ /** Points one glyph may expand to through composites. */
10
+ const MAX_POINTS = 1_000_000;
11
+ /** Components one glyph may visit through nested composites, counted over the whole tree. */
12
+ const MAX_COMPONENTS = 4096;
13
+ /** Bounds-checked big-endian reads over the whole file. */
14
+ class Reader {
15
+ constructor(bytes) {
16
+ this.bytes = bytes;
17
+ this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
18
+ }
19
+ check(offset, size, what) {
20
+ if (offset < 0 || offset + size > this.bytes.length)
21
+ throw new LoaderError(F, 'truncated', `${what} at byte ${offset} runs past the end of the ${this.bytes.length}-byte file`);
22
+ }
23
+ u8(o, what = 'data') {
24
+ this.check(o, 1, what);
25
+ return this.view.getUint8(o);
26
+ }
27
+ i8(o, what = 'data') {
28
+ this.check(o, 1, what);
29
+ return this.view.getInt8(o);
30
+ }
31
+ u16(o, what = 'data') {
32
+ this.check(o, 2, what);
33
+ return this.view.getUint16(o);
34
+ }
35
+ i16(o, what = 'data') {
36
+ this.check(o, 2, what);
37
+ return this.view.getInt16(o);
38
+ }
39
+ u32(o, what = 'data') {
40
+ this.check(o, 4, what);
41
+ return this.view.getUint32(o);
42
+ }
43
+ f2dot14(o, what = 'data') {
44
+ return this.i16(o, what) / 16384;
45
+ }
46
+ tag(o) {
47
+ this.check(o, 4, 'table tag');
48
+ return String.fromCharCode(this.bytes[o], this.bytes[o + 1], this.bytes[o + 2], this.bytes[o + 3]);
49
+ }
50
+ }
51
+ const tag = (value) => String.fromCharCode(value >>> 24, (value >>> 16) & 255, (value >>> 8) & 255, value & 255);
52
+ function tables(r, base) {
53
+ const count = r.u16(base + 4, 'table count'), out = new Map();
54
+ for (let i = 0; i < count; i++) {
55
+ const record = base + 12 + i * 16, name = r.tag(record), offset = r.u32(record + 8, 'table record'), length = r.u32(record + 12, 'table record');
56
+ // Tables past the end of the file are dropped here; `need` reports a missing required one.
57
+ if (!out.has(name) && offset + length <= r.bytes.length)
58
+ out.set(name, { offset, length });
59
+ }
60
+ return out;
61
+ }
62
+ function need(all, name, min) {
63
+ const table = all.get(name);
64
+ if (!table)
65
+ throw new LoaderError(F, 'header', `the font has no complete '${name}' table, which TrueType outlines need`);
66
+ if (table.length < min)
67
+ throw new LoaderError(F, 'truncated', `'${name}' table is ${table.length} bytes, shorter than its ${min}-byte header`);
68
+ return table;
69
+ }
70
+ /** Code point to glyph index through the best Unicode cmap subtable (format 12, then 4). */
71
+ function cmapLookup(r, cmap) {
72
+ const count = r.u16(cmap.offset + 2, 'cmap header');
73
+ let best;
74
+ for (let i = 0; i < count; i++) {
75
+ const record = cmap.offset + 4 + i * 8, platform = r.u16(record, 'cmap record'), encoding = r.u16(record + 2, 'cmap record'), offset = cmap.offset + r.u32(record + 4, 'cmap record'), format = r.u16(offset, 'cmap subtable');
76
+ if (format !== 4 && format !== 12)
77
+ continue;
78
+ const unicode = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10)), symbol = platform === 3 && encoding === 0, score = (format === 12 ? 2 : 0) + (unicode ? 4 : symbol ? 1 : 0) + (platform === 3 ? 1 : 0);
79
+ if (!best || score > best.score)
80
+ best = { offset, format, score, symbol };
81
+ }
82
+ if (!best)
83
+ throw new LoaderError(F, 'unsupported', "the font's cmap has no format 4 or 12 subtable; only Unicode cmaps are read");
84
+ const { offset, symbol } = best;
85
+ let lookup;
86
+ if (best.format === 4) {
87
+ const segments = r.u16(offset + 6, 'cmap format 4') / 2, ends = offset + 14, starts = ends + segments * 2 + 2, deltas = starts + segments * 2, ranges = deltas + segments * 2;
88
+ r.check(offset, 16 + segments * 8, 'cmap format 4 segments');
89
+ lookup = (c) => {
90
+ if (c > 0xffff || segments === 0)
91
+ return 0;
92
+ let lo = 0, hi = segments - 1;
93
+ while (lo < hi) {
94
+ const mid = (lo + hi) >> 1;
95
+ if (r.u16(ends + mid * 2) < c)
96
+ lo = mid + 1;
97
+ else
98
+ hi = mid;
99
+ }
100
+ const start = r.u16(starts + lo * 2);
101
+ if (r.u16(ends + lo * 2) < c || start > c)
102
+ return 0;
103
+ const delta = r.u16(deltas + lo * 2), range = r.u16(ranges + lo * 2);
104
+ if (range === 0)
105
+ return (c + delta) & 0xffff;
106
+ const at = ranges + lo * 2 + range + (c - start) * 2;
107
+ // The glyph ID array lies inside this subtable; a pointer past its length names no glyph, not another table's bytes.
108
+ if (at + 2 > offset + r.u16(offset + 2))
109
+ return 0;
110
+ const glyph = r.u16(at);
111
+ return glyph === 0 ? 0 : (glyph + delta) & 0xffff;
112
+ };
113
+ }
114
+ else {
115
+ const groups = r.u32(offset + 12, 'cmap format 12');
116
+ r.check(offset + 16, groups * 12, 'cmap format 12 groups');
117
+ lookup = (c) => {
118
+ if (groups === 0)
119
+ return 0;
120
+ let lo = 0, hi = groups - 1;
121
+ while (lo < hi) {
122
+ const mid = (lo + hi) >> 1;
123
+ if (r.u32(offset + 16 + mid * 12 + 4) < c)
124
+ lo = mid + 1;
125
+ else
126
+ hi = mid;
127
+ }
128
+ const group = offset + 16 + lo * 12, start = r.u32(group);
129
+ if (start > c || r.u32(group + 4) < c)
130
+ return 0;
131
+ return r.u32(group + 8) + (c - start);
132
+ };
133
+ }
134
+ // Symbol fonts (3, 0) map their characters to U+F000-U+F0FF.
135
+ return symbol ? (c) => lookup(c) || (c < 256 ? lookup(0xf000 + c) : 0) : lookup;
136
+ }
137
+ /** Pairs of the 'kern' table's horizontal format 0 subtables (Microsoft and Apple headers), keyed left * 65536 + right. */
138
+ function kernPairs(r, kern) {
139
+ const pairs = new Map();
140
+ if (!kern || kern.length < 4)
141
+ return pairs;
142
+ const add = (at, count, override) => {
143
+ r.check(at, count * 6, 'kern pairs');
144
+ for (let i = 0; i < count; i++) {
145
+ const key = r.u16(at + i * 6) * 65536 + r.u16(at + i * 6 + 2), value = r.i16(at + i * 6 + 4);
146
+ pairs.set(key, override ? value : (pairs.get(key) ?? 0) + value);
147
+ }
148
+ };
149
+ const end = kern.offset + kern.length;
150
+ if (r.u16(kern.offset) === 0) {
151
+ let at = kern.offset + 4;
152
+ for (let t = r.u16(kern.offset + 2); t > 0 && at + 6 <= end; t--) {
153
+ const length = r.u16(at + 2), coverage = r.u16(at + 4), format = coverage >> 8;
154
+ if (format === 0) {
155
+ const count = r.u16(at + 6);
156
+ // Horizontal, not minimum values, not cross-stream.
157
+ if ((coverage & 7) === 1)
158
+ add(at + 14, count, (coverage & 8) !== 0);
159
+ // The 16-bit length overflows for large pair lists; the pair count gives the real size.
160
+ at += 14 + count * 6;
161
+ }
162
+ else
163
+ at += length;
164
+ }
165
+ }
166
+ else if (r.u32(kern.offset) === 0x00010000) {
167
+ let at = kern.offset + 8;
168
+ for (let t = r.u32(kern.offset + 4); t > 0 && at + 8 <= end; t--) {
169
+ const length = r.u32(at), coverage = r.u16(at + 4);
170
+ // Format 0, not vertical, cross-stream or variation.
171
+ if ((coverage & 0xff) === 0 && (coverage & 0xe000) === 0)
172
+ add(at + 16, r.u16(at + 8), false);
173
+ if (length < 8)
174
+ break;
175
+ at += length;
176
+ }
177
+ }
178
+ return pairs;
179
+ }
180
+ /** Family (name ID 1) and style (name ID 2), preferring Windows English, then any Unicode, then Macintosh Roman. */
181
+ function names(r, name) {
182
+ if (!name || name.length < 6)
183
+ return {};
184
+ const count = r.u16(name.offset + 2), strings = name.offset + r.u16(name.offset + 4), best = [];
185
+ for (let i = 0; i < count; i++) {
186
+ const record = name.offset + 6 + i * 12;
187
+ if (record + 12 > name.offset + name.length)
188
+ break;
189
+ const platform = r.u16(record), encoding = r.u16(record + 2), language = r.u16(record + 4), id = r.u16(record + 6), length = r.u16(record + 8), at = strings + r.u16(record + 10);
190
+ if ((id !== 1 && id !== 2) || at + length > r.bytes.length)
191
+ continue;
192
+ const utf16 = platform === 0 || (platform === 3 && (encoding === 1 || encoding === 10)), score = platform === 3 && language === 0x409 ? 4 : utf16 ? 3 : platform === 1 && encoding === 0 ? 1 : 0;
193
+ if (!score || (best[id] && best[id].score >= score))
194
+ continue;
195
+ let text = '';
196
+ if (utf16)
197
+ for (let k = 0; k + 1 < length; k += 2)
198
+ text += String.fromCharCode(r.u16(at + k));
199
+ else
200
+ for (let k = 0; k < length; k++)
201
+ text += String.fromCharCode(r.u8(at + k));
202
+ best[id] = { score, text };
203
+ }
204
+ return { family: best[1]?.text, style: best[2]?.text };
205
+ }
206
+ /** The axes of an `fvar` table (OpenType fvar: VariationAxisRecord tag, min, default and max as 16.16 Fixed). */
207
+ function fvarAxes(r, fvar) {
208
+ if (!fvar || fvar.length < 16 || r.u16(fvar.offset) !== 1)
209
+ return [];
210
+ const first = fvar.offset + r.u16(fvar.offset + 4), count = r.u16(fvar.offset + 8), size = r.u16(fvar.offset + 10), axes = [];
211
+ if (size < 20)
212
+ return [];
213
+ for (let i = 0; i < count; i++) {
214
+ const at = first + i * size;
215
+ if (at + 20 > fvar.offset + fvar.length)
216
+ break;
217
+ axes.push({
218
+ tag: String.fromCharCode(r.u8(at), r.u8(at + 1), r.u8(at + 2), r.u8(at + 3)),
219
+ min: (r.u32(at + 4) | 0) / 65536,
220
+ default: (r.u32(at + 8) | 0) / 65536,
221
+ max: (r.u32(at + 12) | 0) / 65536,
222
+ });
223
+ }
224
+ return axes;
225
+ }
226
+ /** TrueType quadratic B-spline contours to move/line/quadratic commands (implied on-curve midpoints included). */
227
+ function contourCommands(points, out) {
228
+ let first = 0;
229
+ for (const last of points.ends) {
230
+ const n = last - first + 1;
231
+ if (n < 2) {
232
+ first = last + 1;
233
+ continue;
234
+ }
235
+ const x = (k) => points.xs[first + ((k + n) % n)], y = (k) => points.ys[first + ((k + n) % n)], on = (k) => points.on[first + ((k + n) % n)];
236
+ let begin = 0;
237
+ while (begin < n && !on(begin))
238
+ begin++;
239
+ // With no on-curve point the contour starts halfway between the last and first points.
240
+ const startX = begin < n ? x(begin) : (x(-1) + x(0)) / 2, startY = begin < n ? y(begin) : (y(-1) + y(0)) / 2, from = begin < n ? begin + 1 : 0, count = begin < n ? n - 1 : n;
241
+ out.push(['M', startX, startY]);
242
+ let control = null;
243
+ for (let k = 0; k <= count; k++) {
244
+ const closing = k === count, px = closing ? startX : x(from + k), py = closing ? startY : y(from + k), onCurve = closing || on(from + k);
245
+ if (onCurve) {
246
+ if (control)
247
+ out.push(['Q', control[0], control[1], px, py]);
248
+ else if (!closing || px !== startX || py !== startY)
249
+ out.push(['L', px, py]);
250
+ control = null;
251
+ }
252
+ else {
253
+ if (control)
254
+ out.push(['Q', control[0], control[1], (control[0] + px) / 2, (control[1] + py) / 2]);
255
+ control = [px, py];
256
+ }
257
+ }
258
+ out.push(['Z']);
259
+ first = last + 1;
260
+ }
261
+ }
262
+ /**
263
+ * Reads an OpenType font (`.ttf`, `.otf`, or one font of a `.ttc` collection) into an `OutlineFontSource`, from the
264
+ * OpenType specification's tables: `head`, `hhea`, `maxp`, `hmtx`; TrueType `loca` and `glyf` (simple and composite
265
+ * glyphs with offsets, scales, 2x2 transforms, point matching and ROUND_XY_TO_GRID) or CFF (`'CFF '`, Type 2
266
+ * charstrings with subroutines and `endchar` accents) and CFF2 outlines (Font DICT selection and blends); variable
267
+ * fonts through `fvar`, `avar`, `gvar` (with interpolation of untouched points and phantom-point advances), `HVAR`
268
+ * and the CFF2 ItemVariationStore; `cmap` formats 4 and 12; GPOS pair kerning (the `kern` feature, with its variation
269
+ * deltas) or `kern` format 0 pairs; and the family and style names.
270
+ * Glyphs decode lazily. `parseTTF` wraps the result in an `OutlineFont`; use this function when only the parser is
271
+ * needed. WOFF and WOFF2 throw a `LoaderError` with code `'unsupported'` naming `@margoengine/loaders/font-woff`,
272
+ * which decodes them; malformed tables throw `'header'`, `'truncated'`, `'range'` or `'limit'`.
273
+ */
274
+ export function parseTTFSource(input, options = {}) {
275
+ const r = new Reader(toBytes(input, F));
276
+ r.check(0, 12, 'font header');
277
+ let base = 0;
278
+ const signature = r.u32(0);
279
+ if (signature === 0x74746366) {
280
+ const count = r.u32(8, 'collection header'), index = options.fontIndex ?? 0;
281
+ if (!Number.isInteger(index) || index < 0 || index >= count)
282
+ throw new LoaderError(F, 'range', `fontIndex ${index} is outside the collection's ${count} fonts; pick 0 to ${count - 1}`);
283
+ base = r.u32(12 + index * 4, 'collection offsets');
284
+ }
285
+ const version = r.u32(base, 'font header');
286
+ if (version === 0x774f4646 || version === 0x774f4632)
287
+ throw new LoaderError(F, 'unsupported', "WOFF and WOFF2 fonts are compressed; pass decodeWOFF(bytes) from '@margoengine/loaders/font-woff' (or call its parseWOFF)");
288
+ if (version !== 0x00010000 && version !== 0x74727565 && version !== 0x4f54544f)
289
+ throw new LoaderError(F, 'header', `not an OpenType font (signature '${tag(version)}'); pass the bytes of a .ttf or .otf file`);
290
+ const all = tables(r, base), view = (t) => new BinaryReader(r.bytes.subarray(t.offset, t.offset + t.length));
291
+ const kind = all.has('glyf') ? 'glyf' : all.has('CFF2') ? 'CFF2' : all.has('CFF ') ? 'CFF ' : undefined;
292
+ if (!kind)
293
+ throw new LoaderError(F, 'header', "the font has no complete 'glyf', 'CFF ' or 'CFF2' outline table; pass a font with glyph outlines");
294
+ const head = need(all, 'head', 54), hhea = need(all, 'hhea', 36), maxp = need(all, 'maxp', 6), hmtx = need(all, 'hmtx', 4), cmap = need(all, 'cmap', 4);
295
+ if (r.u32(head.offset + 12) !== 0x5f0f3cf5)
296
+ throw new LoaderError(F, 'header', "the 'head' table's magic number is wrong; the file is not a valid font");
297
+ const unitsPerEm = r.u16(head.offset + 18), longOffsets = r.i16(head.offset + 50) === 1, glyphCount = r.u16(maxp.offset + 4), ascender = r.i16(hhea.offset + 4), descender = r.i16(hhea.offset + 6), lineGap = r.i16(hhea.offset + 8), metrics = Math.min(r.u16(hhea.offset + 34), glyphCount);
298
+ if (unitsPerEm === 0)
299
+ throw new LoaderError(F, 'header', "the 'head' table gives 0 units per em");
300
+ if (glyphCount === 0)
301
+ throw new LoaderError(F, 'header', 'the font has no glyphs');
302
+ if (metrics === 0)
303
+ throw new LoaderError(F, 'header', "the 'hhea' table gives no horizontal metrics");
304
+ if (hmtx.length < metrics * 4)
305
+ throw new LoaderError(F, 'truncated', `'hmtx' holds fewer than its ${metrics} advance widths`);
306
+ const readers = options.openType, instance = Object.keys(options.variations ?? {}).length > 0;
307
+ if (!readers && (kind !== 'glyf' || instance))
308
+ throw new LoaderError(F, 'unsupported', `${kind === 'glyf' ? 'variations were requested, and a variable font instance needs' : `this font has ${kind.trim()} outlines, which need`} the OpenType readers; pass { openType } from '@margoengine/loaders/font-opentype' (or call its parseOpenType), or load the font with GlyphFieldFont.load or VectorFont.load of @margoengine/text, which load them for you`);
309
+ let variations;
310
+ if (readers) {
311
+ const variationTables = new Map();
312
+ for (const name of ['fvar', 'avar', 'gvar', 'HVAR']) {
313
+ const t = all.get(name);
314
+ if (t)
315
+ variationTables.set(name, view(t));
316
+ }
317
+ variations = readers.variations(variationTables, glyphCount, options.variations ?? {});
318
+ }
319
+ else {
320
+ // The default instance of a variable font: every gvar and HVAR delta is 0 there, so only the axes are read.
321
+ const axes = fvarAxes(r, all.get('fvar'));
322
+ variations = {
323
+ axes,
324
+ coordinates: axes.map(() => 0),
325
+ hasGlyphVariations: false,
326
+ advance: () => undefined,
327
+ deltas: () => [[], []],
328
+ };
329
+ }
330
+ const cff = kind === 'glyf'
331
+ ? undefined
332
+ : readers.cff(view(all.get(kind)), kind === 'CFF2', glyphCount, unitsPerEm, variations.coordinates);
333
+ const glyf = kind === 'glyf' ? need(all, 'glyf', 0) : undefined, loca = kind === 'glyf' ? need(all, 'loca', 2) : undefined;
334
+ if (loca && loca.length < (glyphCount + 1) * (longOffsets ? 4 : 2))
335
+ throw new LoaderError(F, 'truncated', `'loca' holds fewer than its ${glyphCount + 1} offsets`);
336
+ const location = (index) => longOffsets ? r.u32(loca.offset + index * 4) : r.u16(loca.offset + index * 2) * 2;
337
+ const glyphIndex = cmapLookup(r, cmap), kerning = kernPairs(r, all.get('kern')), { family, style } = names(r, all.get('name'));
338
+ // GPOS is read at the first pair asked for, so a font used for outlines alone never parses it.
339
+ const pairs = new Map();
340
+ let gpos;
341
+ const layoutKerning = (bytes) => {
342
+ const gdef = all.get('GDEF'), varied = variations.coordinates.some((c) => c !== 0);
343
+ return gposKerning(bytes, varied && gdef ? readers.layoutDeltas(view(gdef), variations.coordinates) : undefined);
344
+ };
345
+ const decode = (index, depth, work) => {
346
+ if (depth > MAX_DEPTH)
347
+ throw new LoaderError(F, 'limit', `composite glyphs nest deeper than ${MAX_DEPTH} levels (or refer to themselves)`);
348
+ if (index >= glyphCount)
349
+ throw new LoaderError(F, 'range', `glyph ${index} is outside the font's ${glyphCount} glyphs`);
350
+ const start = location(index), end = location(index + 1), points = { xs: [], ys: [], on: [], ends: [] };
351
+ if (end <= start) {
352
+ // An empty glyph still carries phantom-point deltas for its advance.
353
+ if (variations.hasGlyphVariations) {
354
+ const [dx] = variations.deltas(index, [], []);
355
+ points.advanceDelta = dx[1] - dx[0];
356
+ }
357
+ return points;
358
+ }
359
+ if (end > glyf.length)
360
+ throw new LoaderError(F, 'range', `glyph ${index} ends at byte ${end}, past the ${glyf.length}-byte 'glyf' table`);
361
+ const at = glyf.offset + start, limit = glyf.offset + end, within = (o, size) => {
362
+ if (o + size > limit)
363
+ throw new LoaderError(F, 'truncated', `glyph ${index} runs past its 'loca' length`);
364
+ return o;
365
+ }, contours = r.i16(within(at, 10));
366
+ if (contours >= 0) {
367
+ let p = at + 10, previous = -1;
368
+ for (let c = 0; c < contours; c++, p += 2) {
369
+ const last = r.u16(within(p, 2));
370
+ if (last <= previous && c > 0)
371
+ throw new LoaderError(F, 'range', `glyph ${index} has contour end points out of order`);
372
+ points.ends.push(last);
373
+ previous = last;
374
+ }
375
+ const count = contours ? previous + 1 : 0;
376
+ p += 2 + r.u16(within(p, 2));
377
+ const flags = new Uint8Array(count);
378
+ for (let k = 0; k < count;) {
379
+ const flag = r.u8(within(p++, 1));
380
+ flags[k++] = flag;
381
+ if (flag & 8) {
382
+ let repeat = r.u8(within(p++, 1));
383
+ if (k + repeat > count)
384
+ throw new LoaderError(F, 'range', `glyph ${index} repeats a flag past its points`);
385
+ while (repeat-- > 0)
386
+ flags[k++] = flag;
387
+ }
388
+ }
389
+ for (const [short, same, list] of [
390
+ [2, 16, points.xs],
391
+ [4, 32, points.ys],
392
+ ]) {
393
+ let value = 0;
394
+ for (let k = 0; k < count; k++) {
395
+ const flag = flags[k];
396
+ if (flag & short) {
397
+ const delta = r.u8(within(p++, 1));
398
+ value += flag & same ? delta : -delta;
399
+ }
400
+ else if (!(flag & same)) {
401
+ value += r.i16(within(p, 2));
402
+ p += 2;
403
+ }
404
+ list.push(value);
405
+ }
406
+ }
407
+ for (let k = 0; k < count; k++)
408
+ points.on.push((flags[k] & 1) !== 0);
409
+ if (variations.hasGlyphVariations) {
410
+ const [dx, dy] = variations.deltas(index, points.xs.map((x, k) => [x, points.ys[k]]), points.ends);
411
+ for (let k = 0; k < count; k++) {
412
+ points.xs[k] += dx[k];
413
+ points.ys[k] += dy[k];
414
+ }
415
+ points.advanceDelta = dx[count + 1] - dx[count];
416
+ }
417
+ return points;
418
+ }
419
+ // Composite: components, each with a transform and an offset or matched points. All are read first, because a
420
+ // variable font's gvar moves each component's offset by one delta per component.
421
+ const parts = [];
422
+ let p = at + 10, flags;
423
+ do {
424
+ if (++work.components > MAX_COMPONENTS)
425
+ throw new LoaderError(F, 'limit', `glyph ${index} visits more than ${MAX_COMPONENTS} composite components`);
426
+ flags = r.u16(within(p, 4));
427
+ const glyph = r.u16(p + 2);
428
+ p += 4;
429
+ let arg1, arg2;
430
+ if (flags & 1) {
431
+ arg1 = flags & 2 ? r.i16(within(p, 4)) : r.u16(within(p, 4));
432
+ arg2 = flags & 2 ? r.i16(p + 2) : r.u16(p + 2);
433
+ p += 4;
434
+ }
435
+ else {
436
+ arg1 = flags & 2 ? r.i8(within(p, 2)) : r.u8(within(p, 2));
437
+ arg2 = flags & 2 ? r.i8(p + 1) : r.u8(p + 1);
438
+ p += 2;
439
+ }
440
+ const m = [1, 0, 0, 1];
441
+ if (flags & 8) {
442
+ m[0] = m[3] = r.f2dot14(within(p, 2));
443
+ p += 2;
444
+ }
445
+ else if (flags & 0x40) {
446
+ m[0] = r.f2dot14(within(p, 4));
447
+ m[3] = r.f2dot14(p + 2);
448
+ p += 4;
449
+ }
450
+ else if (flags & 0x80) {
451
+ m[0] = r.f2dot14(within(p, 8));
452
+ m[1] = r.f2dot14(p + 2);
453
+ m[2] = r.f2dot14(p + 4);
454
+ m[3] = r.f2dot14(p + 6);
455
+ p += 8;
456
+ }
457
+ parts.push({ flags, glyph, arg1, arg2, m });
458
+ } while (flags & 0x20);
459
+ let moveX = [], moveY = [];
460
+ if (variations.hasGlyphVariations) {
461
+ [moveX, moveY] = variations.deltas(index, parts.map((part) => (part.flags & 2 ? [part.arg1, part.arg2] : [0, 0])), [], true);
462
+ points.advanceDelta = moveX[parts.length + 1] - moveX[parts.length];
463
+ }
464
+ parts.forEach(({ flags, glyph, arg1, arg2, m: [a, b, c, d] }, part) => {
465
+ const child = decode(glyph, depth + 1, work), offset = points.xs.length;
466
+ // OpenType 'glyf', composite flags: USE_MY_METRICS (0x200) gives the composite this component's advance.
467
+ // A variable font's advance still moves by the composite's own phantom points.
468
+ if (flags & 0x200)
469
+ points.metrics = child.metrics ?? glyph;
470
+ if (offset + child.xs.length > MAX_POINTS)
471
+ throw new LoaderError(F, 'limit', `glyph ${index} expands to more than ${MAX_POINTS} points`);
472
+ for (let k = 0; k < child.xs.length; k++) {
473
+ points.xs.push(a * child.xs[k] + c * child.ys[k]);
474
+ points.ys.push(b * child.xs[k] + d * child.ys[k]);
475
+ points.on.push(child.on[k]);
476
+ }
477
+ let dx, dy;
478
+ if (flags & 2) {
479
+ // SCALED_COMPONENT_OFFSET transforms the offset too; the default (and UNSCALED_COMPONENT_OFFSET) does not.
480
+ const scaled = (flags & 0x800) !== 0 && (flags & 0x1000) === 0;
481
+ dx = scaled ? a * arg1 + c * arg2 : arg1;
482
+ dy = scaled ? b * arg1 + d * arg2 : arg2;
483
+ // ROUND_XY_TO_GRID (0x4) rounds the offset to whole font units.
484
+ if (flags & 4) {
485
+ dx = Math.round(dx);
486
+ dy = Math.round(dy);
487
+ }
488
+ }
489
+ else {
490
+ const matched = offset + arg2;
491
+ if (arg1 >= offset || matched >= points.xs.length)
492
+ throw new LoaderError(F, 'range', `glyph ${index} matches point ${arg1} to ${arg2}, which do not exist`);
493
+ dx = points.xs[arg1] - points.xs[matched];
494
+ dy = points.ys[arg1] - points.ys[matched];
495
+ }
496
+ if (moveX.length) {
497
+ dx += moveX[part];
498
+ dy += moveY[part];
499
+ }
500
+ for (let k = offset; k < points.xs.length; k++) {
501
+ points.xs[k] += dx;
502
+ points.ys[k] += dy;
503
+ }
504
+ for (const last of child.ends)
505
+ points.ends.push(offset + last);
506
+ });
507
+ return points;
508
+ };
509
+ return {
510
+ unitsPerEm,
511
+ ascender,
512
+ descender,
513
+ lineHeight: ascender - descender + lineGap,
514
+ glyphCount,
515
+ familyName: family,
516
+ styleName: style,
517
+ missingGlyph: 0,
518
+ variationAxes: variations.axes,
519
+ variationCoordinates: variations.coordinates,
520
+ table(name) {
521
+ const t = all.get(name);
522
+ return t && r.bytes.subarray(t.offset, t.offset + t.length);
523
+ },
524
+ glyphIndex(c) {
525
+ const index = glyphIndex(c);
526
+ return index > 0 && index < glyphCount ? index : undefined;
527
+ },
528
+ glyph(index) {
529
+ if (!Number.isInteger(index) || index < 0 || index >= glyphCount)
530
+ throw new RangeError(`glyph index ${index} is outside 0..${glyphCount - 1}; pass an index from glyphIndex()`);
531
+ let commands = [], metricsGlyph = index, delta;
532
+ if (cff)
533
+ commands = cff.commands(index);
534
+ else {
535
+ const points = decode(index, 0, { components: 0 });
536
+ contourCommands(points, commands);
537
+ metricsGlyph = points.metrics ?? index;
538
+ delta = points.advanceDelta;
539
+ }
540
+ // HVAR, when present, gives the glyph's advance change; otherwise gvar's phantom points do (TrueType only).
541
+ const varied = variations.advance(index);
542
+ const advance = r.u16(hmtx.offset + Math.min(metricsGlyph, metrics - 1) * 4) + (varied ?? delta ?? 0);
543
+ return { index, advance, commands };
544
+ },
545
+ kerning(left, right, script = 'latn') {
546
+ const legacy = kerning.get(left * 65536 + right) ?? 0, t = all.get('GPOS');
547
+ if (!t)
548
+ return legacy;
549
+ const key = `${script}|${left}|${right}`;
550
+ let value = pairs.get(key);
551
+ if (value === undefined) {
552
+ gpos ??= layoutKerning(r.bytes.subarray(t.offset, t.offset + t.length));
553
+ pairs.set(key, (value = gpos(left, right, script) ?? legacy));
554
+ }
555
+ return value;
556
+ },
557
+ };
558
+ }
559
+ /**
560
+ * Parses an OpenType font (`.ttf`, `.otf`, or one font of a `.ttc` collection) into an `OutlineFont`: TrueType or
561
+ * CFF/CFF2 outlines, variable fonts at `options.variations`, `cmap` formats 4 and 12, GPOS or `kern` pair kerning and
562
+ * the family and style names (see `parseTTFSource` for the tables read). Glyphs decode lazily. WOFF and WOFF2 throw a
563
+ * `LoaderError` with code `'unsupported'` (`parseWOFF` of `@margoengine/loaders/font-woff` reads them); malformed
564
+ * tables throw `'header'`, `'truncated'`, `'range'` or `'limit'`.
565
+ */
566
+ export function parseTTF(input, options = {}) {
567
+ return new OutlineFont(parseTTFSource(input, options));
568
+ }
@@ -0,0 +1,90 @@
1
+ /** A sub-range of `indices` (or of vertices for point clouds) that belongs to one object or one color. */
2
+ export interface LoadedGroup {
3
+ /** First index in `indices` (for point clouds: first vertex). */
4
+ start: number;
5
+ /** Number of indices (a multiple of 3) or, for point clouds, vertices. */
6
+ count: number;
7
+ /** Object or element name from the file, when it has one. */
8
+ name?: string;
9
+ /** Source object id (3MF). */
10
+ objectId?: string;
11
+ /** Uniform sRGB color in [0,1], `[r, g, b, a]`, when the file gives this group one color. */
12
+ color?: [number, number, number, number];
13
+ /** Raw source face properties, including scalar values and owned lists (PLY/OFF). */
14
+ properties?: Record<string, number | number[]>;
15
+ }
16
+ /** The common output of every loader in this package. */
17
+ export interface LoadedGeometry {
18
+ /** `'mesh'` when `indices` holds triangles, `'points'` for point clouds. */
19
+ kind: 'mesh' | 'points';
20
+ /** xyz per vertex. */
21
+ positions: Float32Array;
22
+ /** xyz per vertex, as stored in the file (not renormalized). */
23
+ normals?: Float32Array;
24
+ /** sRGB rgb per vertex in [0,1]. */
25
+ colors?: Float32Array;
26
+ /** uv per vertex. */
27
+ uvs?: Float32Array;
28
+ /** Triangle list, three per triangle. Absent for point clouds. */
29
+ indices?: Uint32Array;
30
+ /**
31
+ * Line segments, two vertex indices each, when the file holds lines beside or instead of faces (PLY `edge`, OBJ `l`,
32
+ * COLLADA `<lines>` and `<linestrips>`). A file of lines and no faces has `kind` `'points'`.
33
+ */
34
+ lineIndices?: Uint32Array;
35
+ /** Per-object or per-color index ranges, in order and non-overlapping. */
36
+ groups?: LoadedGroup[];
37
+ /** Extra per-vertex scalars such as PCD `intensity`, VTK point SCALARS or USD `opacity` (0 to 1). */
38
+ attributes?: Record<string, Float32Array>;
39
+ }
40
+ /**
41
+ * Reads a file a model refers to (an MTL library, a TSX tileset), given its path relative to the folder of the file
42
+ * being parsed. Return the bytes, or the text. In Electron read from disk; in a browser `fetch(new URL(path, base))`.
43
+ */
44
+ export type AssetResolver = (path: string) => Promise<Uint8Array | string>;
45
+ /** Bounds shared by every parser. Counts past these throw a `LoaderError` with code `'limit'`. */
46
+ export interface ParseLimits {
47
+ /** Maximum vertices or points. Default 8,000,000. */
48
+ maxVertices?: number;
49
+ /** Maximum triangles after triangulation. Default 16,000,000. */
50
+ maxTriangles?: number;
51
+ }
52
+ /**
53
+ * Why a LoaderError was thrown: a bad header, truncated data, a size limit, a value out of range, a syntax fault, an unsupported feature, a bad zip, an abort, a failed fetch, or a URL inside the file that leaves the file's directory (`'url'`: add its prefix to `allowedURLs` to load it).
54
+ */
55
+ export type LoaderErrorCode = 'header' | 'truncated' | 'limit' | 'range' | 'syntax' | 'unsupported' | 'zip' | 'aborted' | 'fetch' | 'url';
56
+ /**
57
+ * Thrown for every malformed, truncated, oversized or unsupported input. The message reads `<format>: <message>` and
58
+ * ends with `; see https://margoengine.com/errors#loader-<code>`, the help entry for the code.
59
+ */
60
+ export declare class LoaderError extends Error {
61
+ readonly format: string;
62
+ readonly code: LoaderErrorCode;
63
+ /**
64
+ * The HTTP status of a refused request (`403`, `404`, `429`, `503`...) when the server answered one, so a caller
65
+ * tells a refusal from a network failure without reading the message; undefined for every other error.
66
+ */
67
+ readonly status?: number;
68
+ /**
69
+ * Seconds the server asked the client to wait before trying again: its `Retry-After` header (RFC 9110 10.2.3), given
70
+ * as seconds or as a date, counted from when the answer came. Undefined when the answer had none or it was unreadable.
71
+ */
72
+ readonly retryAfter?: number;
73
+ /**
74
+ * `options.cause`: the error behind this one, such as what a custom `fetch` threw. `options.status` and
75
+ * `options.retryAfter` fill the fields of the same names.
76
+ */
77
+ constructor(format: string, code: LoaderErrorCode, message: string, options?: {
78
+ cause?: unknown;
79
+ status?: number;
80
+ retryAfter?: number;
81
+ });
82
+ }
83
+ /**
84
+ * The status and the `Retry-After` delay of an HTTP answer, for a {@link LoaderError}. Retry-After is delay-seconds
85
+ * (digits) or an HTTP-date (RFC 9110 10.2.3 and 5.6.7); a date gives the whole seconds from `now` to it, 0 when past.
86
+ */
87
+ export declare function httpRefusal(response: Response, now?: number): {
88
+ status: number;
89
+ retryAfter?: number;
90
+ };