@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/dxf.js ADDED
@@ -0,0 +1,985 @@
1
+ // DXF (AutoCAD Drawing Exchange Format), written from Autodesk's published DXF reference: ASCII files and binary files
2
+ // (R13 and later), the HEADER units and version, LAYER table colours and visibility, BLOCKS expanded through INSERT
3
+ // (rows and columns included) and DIMENSION, and the model-space entities a viewer draws. Faces (3DFACE, SOLID, TRACE,
4
+ // polyface and polygon-mesh POLYLINEs, MESH) become one triangle list; curves (LINE, polylines with bulges, ARC,
5
+ // CIRCLE, ELLIPSE, SPLINE) become line segments; ACIS solids (3DSOLID, BODY, REGION) are handed back as SAT text.
6
+ // LEADER and MULTILEADER are read by ./dxf-leaders.ts. HATCH is drawn by the optional reader of ./dxf-hatch.ts.
7
+ import { NurbsCurve } from '@margoengine/geometry/nurbs';
8
+ import { dimensionOverrides, readLeader, readMultiLeader } from './dxf-leaders.js';
9
+ import { LoaderError } from './types.js';
10
+ import { checkCount, latin1, limits, toBytes } from './util.js';
11
+ const F = 'DXF';
12
+ /**
13
+ * Meters per unit for `$INSUNITS` codes 0 to 24 (0: unitless). 21 to 24 are the US survey foot, inch, yard and mile,
14
+ * defined by 1 m = 39.37 survey inches.
15
+ */
16
+ const UNITS = [
17
+ 1,
18
+ 0.0254,
19
+ 0.3048,
20
+ 1609.344,
21
+ 0.001,
22
+ 0.01,
23
+ 1,
24
+ 1000,
25
+ 2.54e-8,
26
+ 2.54e-5,
27
+ 0.9144,
28
+ 1e-10,
29
+ 1e-9,
30
+ 1e-6,
31
+ 0.1,
32
+ 10,
33
+ 100,
34
+ 1e9,
35
+ 149597870700,
36
+ 9.4607304725808e15,
37
+ 3.0856775814913673e16,
38
+ 1200 / 3937,
39
+ 100 / 3937,
40
+ 3600 / 3937,
41
+ 6336000 / 3937,
42
+ ];
43
+ /** The AutoCAD Color Index as sRGB 0..1: 1 to 9 named, 10 to 249 a 24-hue wheel at five values (odd: half saturation), 250 to 255 greys. */
44
+ const ACI = (() => {
45
+ const table = [[0, 0, 0]];
46
+ const named = [
47
+ [1, 0, 0],
48
+ [1, 1, 0],
49
+ [0, 1, 0],
50
+ [0, 1, 1],
51
+ [0, 0, 1],
52
+ [1, 0, 1],
53
+ [1, 1, 1],
54
+ [128 / 255, 128 / 255, 128 / 255],
55
+ [192 / 255, 192 / 255, 192 / 255],
56
+ ];
57
+ table.push(...named);
58
+ const values = [255, 204, 153, 127, 76];
59
+ for (let i = 10; i < 250; i++) {
60
+ const hue = (Math.floor((i - 10) / 10) * 15) / 60, k = (i - 10) % 10, v = values[k >> 1] / 255, low = k & 1 ? v / 2 : 0, sector = Math.floor(hue) % 6, f = hue - Math.floor(hue), rise = low + (v - low) * f, fall = v - (v - low) * f;
61
+ table.push([
62
+ [v, rise, low],
63
+ [fall, v, low],
64
+ [low, v, rise],
65
+ [low, fall, v],
66
+ [rise, low, v],
67
+ [v, low, fall],
68
+ ][sector]);
69
+ }
70
+ for (const g of [51, 91, 132, 173, 214, 255])
71
+ table.push([g / 255, g / 255, g / 255]);
72
+ return table;
73
+ })();
74
+ /** Group code value types for binary DXF, by code. */
75
+ function binaryKind(code) {
76
+ if (code <= 9 || code === 100 || code === 102 || code === 105 || code === 999)
77
+ return 'string';
78
+ if (code < 60 || (code >= 110 && code < 150) || (code >= 210 && code < 240) || (code >= 460 && code < 470))
79
+ return 'double';
80
+ if (code >= 1010 && code < 1060)
81
+ return 'double';
82
+ if (code < 80 || (code >= 170 && code < 180) || (code >= 270 && code < 290) || (code >= 370 && code < 390))
83
+ return 'int16';
84
+ if ((code >= 400 && code < 410) || (code >= 1060 && code < 1071))
85
+ return 'int16';
86
+ if ((code >= 90 && code < 100) || (code >= 420 && code < 430) || (code >= 440 && code < 460) || code === 1071)
87
+ return 'int32';
88
+ if (code >= 160 && code < 170)
89
+ return 'int64';
90
+ if (code >= 290 && code < 300)
91
+ return 'bool';
92
+ if ((code >= 310 && code < 320) || code === 1004)
93
+ return 'binary';
94
+ return 'string';
95
+ }
96
+ /** Group codes and values of the whole file, in order. */
97
+ function readPairs(bytes, decode) {
98
+ const codes = [], values = [], sentinel = 'AutoCAD Binary DXF\r\n\x1a\0';
99
+ if (bytes.length >= 22 && latin1(bytes, 0, 22) === sentinel) {
100
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
101
+ let at = 22;
102
+ // Before R13 a group code is one byte, 255 announcing a two-byte code; the first group, 0 SECTION, tells which.
103
+ const wide = bytes[at + 1] === 0;
104
+ const need = (n) => {
105
+ if (at + n > bytes.length)
106
+ throw new LoaderError(F, 'truncated', `binary DXF ends inside a group at byte ${at}`);
107
+ };
108
+ while (at < bytes.length) {
109
+ need(wide ? 2 : 1);
110
+ let code = wide ? view.getUint16(at, true) : bytes[at];
111
+ at += wide ? 2 : 1;
112
+ if (!wide && code === 255) {
113
+ need(2);
114
+ code = view.getUint16(at, true);
115
+ at += 2;
116
+ }
117
+ let value;
118
+ switch (binaryKind(code)) {
119
+ case 'double':
120
+ need(8);
121
+ value = view.getFloat64(at, true);
122
+ at += 8;
123
+ break;
124
+ case 'int16':
125
+ need(2);
126
+ value = view.getInt16(at, true);
127
+ at += 2;
128
+ break;
129
+ case 'int32':
130
+ need(4);
131
+ value = view.getInt32(at, true);
132
+ at += 4;
133
+ break;
134
+ case 'int64':
135
+ need(8);
136
+ value = Number(view.getBigInt64(at, true));
137
+ at += 8;
138
+ break;
139
+ case 'bool':
140
+ need(1);
141
+ value = bytes[at++];
142
+ break;
143
+ case 'binary': {
144
+ need(1);
145
+ const length = bytes[at++];
146
+ need(length);
147
+ value = '';
148
+ at += length;
149
+ break;
150
+ }
151
+ default: {
152
+ let end = at;
153
+ while (end < bytes.length && bytes[end])
154
+ end++;
155
+ if (end >= bytes.length)
156
+ throw new LoaderError(F, 'truncated', 'binary DXF ends inside a string');
157
+ value = decode(bytes.subarray(at, end));
158
+ at = end + 1;
159
+ }
160
+ }
161
+ codes.push(code);
162
+ values.push(value);
163
+ if (code === 0 && value === 'EOF')
164
+ break;
165
+ }
166
+ return { codes, values };
167
+ }
168
+ const lines = decode(bytes).split(/\r\n|\r|\n/);
169
+ for (let i = 0; i + 1 < lines.length; i += 2) {
170
+ const text = lines[i].trim();
171
+ if (!text) {
172
+ if (lines.slice(i).every((l) => !l.trim()))
173
+ break;
174
+ throw new LoaderError(F, 'syntax', `line ${i + 1}: empty group code`);
175
+ }
176
+ const code = Number(text);
177
+ if (!Number.isInteger(code))
178
+ throw new LoaderError(F, 'syntax', `line ${i + 1}: group code "${text.slice(0, 20)}" is not a number`);
179
+ const value = lines[i + 1];
180
+ codes.push(code);
181
+ values.push(code === 0 || code === 2 || code === 8 ? value.trim() : value);
182
+ if (code === 0 && value.trim() === 'EOF')
183
+ break;
184
+ }
185
+ return { codes, values };
186
+ }
187
+ /** `\U+XXXX` escapes (pre-2007 files) to characters. */
188
+ const unicode = (s) => s.replace(/\\U\+([0-9a-fA-F]{4})/g, (_, h) => String.fromCharCode(parseInt(h, 16)));
189
+ /**
190
+ * The `%%` control codes of text strings (Autodesk, "Control Codes and Special Characters"): degrees, plus/minus,
191
+ * diameter, a percent sign and a character by number; the overscore, underscore and strikethrough toggles are dropped.
192
+ */
193
+ const controlCodes = (s) => s.replace(/%%(%|\d{3}|[cdkopu])/gi, (_, c) => {
194
+ const at = 'cdp%'.indexOf(c.toLowerCase());
195
+ return at >= 0 ? '∅°±%'[at] : c.length > 1 ? String.fromCharCode(Number(c)) : '';
196
+ });
197
+ /** MTEXT's inline formatting codes removed: paragraphs become line breaks. */
198
+ function plainMText(s) {
199
+ return unicode(s)
200
+ .replace(/\\P/g, '\n')
201
+ .replace(/\\[ACcFfHhQqTtWwp][^;\\{}]*;/g, '')
202
+ .replace(/\\S([^;]*)[/#^]([^;]*);/g, '$1/$2')
203
+ .replace(/\\[LlOoKkNX~]/g, (m) => (m === '\\~' ? ' ' : ''))
204
+ .replace(/\\([\\{}])/g, '$1')
205
+ .replace(/[{}]/g, '');
206
+ }
207
+ /** ACIS data of a DXF 3DSOLID: caret escapes undone, then each character but space mapped back (159 - code). */
208
+ function decodeSAT(lines) {
209
+ return lines
210
+ .map((line) => line
211
+ .replace(/\^(.)/g, (_, c) => (c === ' ' ? '^' : String.fromCharCode(c.charCodeAt(0) - 64)))
212
+ .replace(/[^ ]/g, (c) => {
213
+ const code = c.charCodeAt(0);
214
+ return code > 32 && code < 127 ? String.fromCharCode(159 - code) : c;
215
+ }))
216
+ .join('\n');
217
+ }
218
+ const identity = () => Float64Array.of(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
219
+ function mul(a, b) {
220
+ const out = new Float64Array(16);
221
+ for (let c = 0; c < 4; c++)
222
+ for (let r = 0; r < 4; r++)
223
+ out[c * 4 + r] = a[r] * b[c * 4] + a[4 + r] * b[c * 4 + 1] + a[8 + r] * b[c * 4 + 2] + a[12 + r] * b[c * 4 + 3];
224
+ return out;
225
+ }
226
+ const apply = (m, x, y, z) => [
227
+ m[0] * x + m[4] * y + m[8] * z + m[12],
228
+ m[1] * x + m[5] * y + m[9] * z + m[13],
229
+ m[2] * x + m[6] * y + m[10] * z + m[14],
230
+ ];
231
+ const direction = (m, x, y, z) => {
232
+ const v = [
233
+ m[0] * x + m[4] * y + m[8] * z,
234
+ m[1] * x + m[5] * y + m[9] * z,
235
+ m[2] * x + m[6] * y + m[10] * z,
236
+ ], l = Math.hypot(v[0], v[1], v[2]) || 1;
237
+ return [v[0] / l, v[1] / l, v[2] / l];
238
+ };
239
+ const translate = (x, y, z) => Float64Array.of(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1);
240
+ const scaling = (x, y, z) => Float64Array.of(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1);
241
+ const rotateZ = (a) => {
242
+ const c = Math.cos(a), s = Math.sin(a);
243
+ return Float64Array.of(c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
244
+ };
245
+ /** The Arbitrary Axis Algorithm: an entity's object coordinate system from its extrusion direction. */
246
+ function ocs(n) {
247
+ const l = Math.hypot(n[0], n[1], n[2]);
248
+ if (!l || (n[0] === 0 && n[1] === 0 && n[2] > 0))
249
+ return identity();
250
+ const z = [n[0] / l, n[1] / l, n[2] / l], w = Math.abs(z[0]) < 1 / 64 && Math.abs(z[1]) < 1 / 64 ? [0, 1, 0] : [0, 0, 1], x0 = [w[1] * z[2] - w[2] * z[1], w[2] * z[0] - w[0] * z[2], w[0] * z[1] - w[1] * z[0]], xl = Math.hypot(x0[0], x0[1], x0[2]), x = [x0[0] / xl, x0[1] / xl, x0[2] / xl], y = [z[1] * x[2] - z[2] * x[1], z[2] * x[0] - z[0] * x[2], z[0] * x[1] - z[1] * x[0]];
251
+ return Float64Array.of(x[0], x[1], x[2], 0, y[0], y[1], y[2], 0, z[0], z[1], z[2], 0, 0, 0, 0, 1);
252
+ }
253
+ /** An arrowhead's axes: `u` out through the tip, `v` across it in the leader's plane, `w` out of that plane. */
254
+ function arrowAxes({ tip, from, normal }) {
255
+ const m = identity(), u = direction(m, tip[0] - from[0], tip[1] - from[1], tip[2] - from[2]), across = (n) => [
256
+ n[1] * u[2] - n[2] * u[1],
257
+ n[2] * u[0] - n[0] * u[2],
258
+ n[0] * u[1] - n[1] * u[0],
259
+ ];
260
+ let side = across(normal);
261
+ // A leader that runs along its own normal lies in no single plane: any direction across it serves.
262
+ if (Math.hypot(...side) <= 1e-9 * Math.hypot(...normal))
263
+ side = across(Math.abs(u[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0]);
264
+ const v = direction(m, ...side);
265
+ return {
266
+ u,
267
+ v,
268
+ w: [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]],
269
+ };
270
+ }
271
+ /**
272
+ * Reads a DXF drawing (ASCII or binary) into faces, line segments, points, texts and ACIS solids, in
273
+ * meters by default. Throws a {@link LoaderError}: `'syntax'` or `'truncated'` for a malformed file, `'limit'` past a
274
+ * limit, `'range'` for a bad option.
275
+ */
276
+ export function parseDXF(input, options = {}) {
277
+ const bytes = toBytes(input, F), { maxVertices, maxTriangles } = limits(options, F), option = (value, fallback, low, high, label) => {
278
+ if (value === undefined)
279
+ return fallback;
280
+ if (!Number.isInteger(value) || value < low || value > high)
281
+ throw new LoaderError(F, 'range', `${label} must be a whole number from ${low} to ${high}`);
282
+ return value;
283
+ }, arcSegments = option(options.arcSegments, 64, 8, 4096, 'arcSegments'), splineSegments = option(options.splineSegments, 16, 1, 1024, 'splineSegments'), maxSegments = option(options.maxSegments, 8_000_000, 0, 2 ** 31, 'maxSegments'), maxInserts = option(options.maxInserts, 1_000_000, 0, 2 ** 31, 'maxInserts'), maxDepth = option(options.maxDepth, 32, 0, 256, 'maxDepth');
284
+ if (options.units !== undefined && options.units !== 'meters' && options.units !== 'file')
285
+ throw new LoaderError(F, 'range', "units must be 'meters' or 'file'");
286
+ // Text: UTF-8 from AutoCAD 2007 (AC1021) on, the drawing's code page (Windows-1252 assumed) before.
287
+ const head = latin1(bytes, 0, Math.min(bytes.length, 1 << 16)),
288
+ // Text writes the name and value on lines; binary as a zero-ended string, group code 1 (one byte before R13), string.
289
+ version = /\$ACADVER(?:\s*\r?\n\s*1\s*\r?\n|\0\x01\0?)([^\r\n\0]*)/.exec(head)?.[1]?.trim() ?? '', utf8 = version >= 'AC1021', decoder = (() => {
290
+ try {
291
+ return new TextDecoder(utf8 ? 'utf-8' : 'windows-1252');
292
+ }
293
+ catch {
294
+ return undefined;
295
+ }
296
+ })(), decode = (b) => (decoder ? decoder.decode(b) : latin1(b));
297
+ const { codes, values } = readPairs(bytes, decode);
298
+ const num = (v, fallback = 0) => {
299
+ const n = typeof v === 'number' ? v : v === undefined ? Number.NaN : Number(v.trim());
300
+ return Number.isFinite(n) ? n : fallback;
301
+ };
302
+ const str = (v) => (v === undefined ? '' : String(v));
303
+ // --- sections ---------------------------------------------------------------------------------------------------
304
+ const header = new Map(), layers = new Map(), blocks = new Map(),
305
+ /** Block names by the handle of their BLOCK_RECORD, and DIMSTYLE entries by upper-case name. */
306
+ records = new Map(), dimensionStyles = new Map(), model = [];
307
+ const handle = (v) => str(v).trim().toUpperCase();
308
+ /** Entities from pair `i` (a code 0) up to the end of the section or `stop`. */
309
+ const entitiesFrom = (i, stop) => {
310
+ const list = [];
311
+ while (i < codes.length) {
312
+ if (codes[i] !== 0) {
313
+ i++;
314
+ continue;
315
+ }
316
+ const type = str(values[i]).trim().toUpperCase();
317
+ if (stop(type))
318
+ return { list, next: i };
319
+ const entity = { type, codes: [], values: [] };
320
+ i++;
321
+ while (i < codes.length && codes[i] !== 0) {
322
+ entity.codes.push(codes[i]);
323
+ entity.values.push(values[i]);
324
+ i++;
325
+ }
326
+ list.push(entity);
327
+ }
328
+ return { list, next: i };
329
+ };
330
+ for (let i = 0; i < codes.length;) {
331
+ if (!(codes[i] === 0 && str(values[i]).trim() === 'SECTION')) {
332
+ i++;
333
+ continue;
334
+ }
335
+ const name = codes[i + 1] === 2
336
+ ? str(values[i + 1])
337
+ .trim()
338
+ .toUpperCase()
339
+ : '';
340
+ i += 2;
341
+ if (name === 'HEADER') {
342
+ let variable = '';
343
+ for (; i < codes.length && !(codes[i] === 0 && str(values[i]).trim() === 'ENDSEC'); i++)
344
+ if (codes[i] === 9) {
345
+ variable = str(values[i]).trim();
346
+ header.set(variable, new Map());
347
+ }
348
+ else if (variable)
349
+ header.get(variable).set(codes[i], values[i]);
350
+ }
351
+ else if (name === 'TABLES' || name === 'BLOCKS' || name === 'ENTITIES') {
352
+ const { list, next } = entitiesFrom(i, (type) => type === 'ENDSEC');
353
+ i = next;
354
+ if (name === 'TABLES') {
355
+ for (const e of list) {
356
+ const get = (code) => e.values[e.codes.indexOf(code)];
357
+ if (e.type === 'BLOCK_RECORD')
358
+ records.set(handle(get(5)), unicode(str(get(2)).trim()));
359
+ else if (e.type === 'DIMSTYLE')
360
+ dimensionStyles.set(unicode(str(get(2)).trim()).toUpperCase(), e);
361
+ else if (e.type === 'LAYER') {
362
+ const layerName = unicode(str(get(2)).trim()), aci = num(get(62), 7), flags = num(get(70)), rgb = e.codes.includes(420) ? num(get(420)) : undefined;
363
+ layers.set(layerName, {
364
+ name: layerName,
365
+ aci: Math.abs(aci),
366
+ color: rgb === undefined
367
+ ? [...(ACI[Math.abs(aci)] ?? ACI[7])]
368
+ : [((rgb >> 16) & 255) / 255, ((rgb >> 8) & 255) / 255, (rgb & 255) / 255],
369
+ visible: aci >= 0 && !(flags & 1),
370
+ });
371
+ }
372
+ }
373
+ }
374
+ else if (name === 'BLOCKS') {
375
+ let current;
376
+ for (const e of list) {
377
+ if (e.type === 'BLOCK') {
378
+ const get = (code) => e.values[e.codes.indexOf(code)];
379
+ current = {
380
+ name: unicode(str(get(2)).trim()),
381
+ base: [num(get(10)), num(get(20)), num(get(30))],
382
+ entities: [],
383
+ };
384
+ blocks.set(current.name, current);
385
+ }
386
+ else if (e.type === 'ENDBLK')
387
+ current = undefined;
388
+ else
389
+ current?.entities.push(e);
390
+ }
391
+ }
392
+ else
393
+ model.push(...list);
394
+ }
395
+ else
396
+ i++;
397
+ }
398
+ const insUnits = num(header.get('$INSUNITS')?.get(70), 0), unit = UNITS[insUnits] ?? 1, scale = options.units === 'file' ? 1 : unit;
399
+ // --- output -----------------------------------------------------------------------------------------------------
400
+ const faceGroups = new Map(), lineGroups = new Map(), points = [], texts = [], solids = [], skipped = {};
401
+ let faceVertices = 0, segments = 0, inserts = 0;
402
+ const skip = (type) => {
403
+ skipped[type] = (skipped[type] ?? 0) + 1;
404
+ };
405
+ const group = (map, layer, color) => {
406
+ const key = `${layer}\u0000${color.join(',')}`;
407
+ let g = map.get(key);
408
+ if (!g)
409
+ map.set(key, (g = { name: layer, color, positions: [] }));
410
+ return g.positions;
411
+ };
412
+ const triangle = (out, a, b, c) => {
413
+ faceVertices += 3;
414
+ checkCount(faceVertices, maxVertices, F, 'face vertex');
415
+ checkCount(faceVertices / 3, maxTriangles, F, 'triangle');
416
+ out.push(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2]);
417
+ };
418
+ /** A polyline's points as segments (closed adds the last to the first). */
419
+ const polyline = (out, list, closed) => {
420
+ const n = list.length;
421
+ for (let k = 0; k + 1 < n + (closed && n > 2 ? 1 : 0); k++) {
422
+ const a = list[k], b = list[(k + 1) % n];
423
+ segments++;
424
+ if (segments > maxSegments)
425
+ throw new LoaderError(F, 'limit', `line segment count exceeds the limit of ${maxSegments}`);
426
+ out.push(a[0], a[1], a[2], b[0], b[1], b[2]);
427
+ }
428
+ };
429
+ /** Points of an arc about (cx, cy) at height z, from angle a0 through sweep (radians, CCW positive). */
430
+ const arc = (cx, cy, z, r, a0, sweep) => {
431
+ const n = Math.max(1, Math.ceil((arcSegments * Math.abs(sweep)) / (2 * Math.PI))), out = [];
432
+ for (let k = 0; k <= n; k++) {
433
+ const a = a0 + (sweep * k) / n;
434
+ out.push([cx + r * Math.cos(a), cy + r * Math.sin(a), z]);
435
+ }
436
+ return out;
437
+ };
438
+ /** 2D vertices with bulges (polyline arcs) as points, at height z. */
439
+ const bulged = (vertices, closed, z) => {
440
+ const out = [];
441
+ const n = vertices.length;
442
+ for (let k = 0; k < n; k++) {
443
+ const a = vertices[k], last = k === n - 1;
444
+ out.push([a.x, a.y, z]);
445
+ if (last && !closed)
446
+ break;
447
+ const b = vertices[(k + 1) % n];
448
+ if (!a.bulge || (a.x === b.x && a.y === b.y))
449
+ continue;
450
+ const dx = b.x - a.x, dy = b.y - a.y, chord = Math.hypot(dx, dy), theta = 4 * Math.atan(a.bulge), offset = (chord * (1 - a.bulge * a.bulge)) / (4 * a.bulge), cx = (a.x + b.x) / 2 - (dy / chord) * offset, cy = (a.y + b.y) / 2 + (dx / chord) * offset, r = Math.hypot(a.x - cx, a.y - cy), points = arc(cx, cy, z, r, Math.atan2(a.y - cy, a.x - cx), theta);
451
+ out.push(...points.slice(1, -1));
452
+ }
453
+ if (closed && n > 1)
454
+ out.push(out[0]);
455
+ return out;
456
+ };
457
+ /** A NURBS curve sampled per knot span; a curve its numbers cannot make stays its control polygon. */
458
+ const spline = (degree, knots, control, weights) => {
459
+ const n = control.length, p = degree, w = control.map((_, i) => weights[i] ?? 1);
460
+ if (n <= p ||
461
+ p < 1 ||
462
+ knots.length !== n + p + 1 ||
463
+ !(knots[p] < knots[n]) ||
464
+ !w.every((x) => x > 0 && x < Infinity) ||
465
+ knots.some((k, i) => !Number.isFinite(k) || (i > 0 && k < knots[i - 1])))
466
+ return control;
467
+ const curve = new NurbsCurve({ points: control.map((c) => [c[0], c[1], c[2]]), degree: p, knots, weights: w }), out = [];
468
+ for (let span = p; span < n; span++) {
469
+ const t0 = knots[span], t1 = knots[span + 1];
470
+ if (!(t1 > t0))
471
+ continue;
472
+ for (let k = out.length ? 1 : 0; k <= splineSegments; k++)
473
+ out.push(curve.evaluate(t0 + ((t1 - t0) * k) / splineSegments));
474
+ }
475
+ return out.length ? out : control;
476
+ };
477
+ const metric = num(header.get('$MEASUREMENT')?.get(70)) === 1;
478
+ /** The header variable behind each DIMSTYLE code a leader reads: DIMSCALE, DIMASZ, DIMTAD, DIMGAP. */
479
+ const HEADER_DIMENSIONS = {
480
+ 40: ['$DIMSCALE', 40, 1],
481
+ 41: ['$DIMASZ', 40, metric ? 2.5 : 0.18],
482
+ 77: ['$DIMTAD', 70, 0],
483
+ 147: ['$DIMGAP', 40, 0],
484
+ };
485
+ const emit = (e, context) => {
486
+ const attribute = e.type === 'ATTRIB' || e.type === 'ATTDEF',
487
+ // A multiline attribute's MTEXT follows code 101 and repeats codes with other meanings: lookups stop there.
488
+ embedded = attribute ? e.codes.indexOf(101) : -1, first = (code) => {
489
+ const k = e.codes.indexOf(code);
490
+ return k < 0 || (embedded >= 0 && k > embedded) ? undefined : e.values[k];
491
+ }, n = (code, fallback = 0) => num(first(code), fallback);
492
+ if (n(67) === 1) {
493
+ skip(`${e.type} (paper space)`);
494
+ return;
495
+ }
496
+ if (n(60) === 1)
497
+ return;
498
+ const ownLayer = unicode(str(first(8)).trim() || '0'), layerName = ownLayer === '0' && context.depth > 0 ? context.layer : ownLayer, layer = layers.get(layerName);
499
+ if (layer && !layer.visible)
500
+ return;
501
+ const aci = n(62, 256), rgb = first(420), color = rgb !== undefined
502
+ ? [((num(rgb) >> 16) & 255) / 255, ((num(rgb) >> 8) & 255) / 255, (num(rgb) & 255) / 255]
503
+ : aci === 0
504
+ ? context.color
505
+ : aci === 256
506
+ ? (layer?.color ?? ACI[7])
507
+ : (ACI[Math.abs(aci)] ?? ACI[7]), extrusion = [n(210, 0), n(220, 0), n(230, 1)], m = context.matrix, world = (p) => apply(m, p[0], p[1], p[2]), inOCS = (p) => {
508
+ const o = ocs(extrusion);
509
+ return apply(m, ...apply(o, p[0], p[1], p[2]));
510
+ }, faces = () => group(faceGroups, layerName, color), lineOut = () => group(lineGroups, layerName, color);
511
+ switch (e.type) {
512
+ case 'LINE':
513
+ polyline(lineOut(), [world([n(10), n(20), n(30)]), world([n(11), n(21), n(31)])], false);
514
+ return;
515
+ case 'POINT': {
516
+ const p = world([n(10), n(20), n(30)]);
517
+ points.push(p[0], p[1], p[2]);
518
+ return;
519
+ }
520
+ case 'CIRCLE':
521
+ polyline(lineOut(), arc(n(10), n(20), n(30), n(40), 0, 2 * Math.PI).map(inOCS), false);
522
+ return;
523
+ case 'ARC': {
524
+ const a0 = (n(50) * Math.PI) / 180;
525
+ let sweep = (n(51) * Math.PI) / 180 - a0;
526
+ while (sweep <= 0)
527
+ sweep += 2 * Math.PI;
528
+ polyline(lineOut(), arc(n(10), n(20), n(30), n(40), a0, sweep).map(inOCS), false);
529
+ return;
530
+ }
531
+ case 'ELLIPSE': {
532
+ const c = [n(10), n(20), n(30)], major = [n(11), n(21), n(31)], ratio = n(40, 1), z = extrusion, cross = [
533
+ z[1] * major[2] - z[2] * major[1],
534
+ z[2] * major[0] - z[0] * major[2],
535
+ z[0] * major[1] - z[1] * major[0],
536
+ ], cl = Math.hypot(cross[0], cross[1], cross[2]) || 1, ml = Math.hypot(major[0], major[1], major[2]), minor = cross.map((v) => (v / cl) * ml * ratio), t0 = n(41, 0);
537
+ let sweep = n(42, 2 * Math.PI) - t0;
538
+ while (sweep <= 0)
539
+ sweep += 2 * Math.PI;
540
+ const count = Math.max(1, Math.ceil((arcSegments * sweep) / (2 * Math.PI))), list = [];
541
+ for (let k = 0; k <= count; k++) {
542
+ const t = t0 + (sweep * k) / count;
543
+ list.push(world([0, 1, 2].map((a) => c[a] + major[a] * Math.cos(t) + minor[a] * Math.sin(t))));
544
+ }
545
+ polyline(lineOut(), list, false);
546
+ return;
547
+ }
548
+ case 'LWPOLYLINE': {
549
+ const vertices = [];
550
+ for (let k = 0; k < e.codes.length; k++)
551
+ if (e.codes[k] === 10)
552
+ vertices.push({ x: num(e.values[k]), y: 0, bulge: 0 });
553
+ else if (e.codes[k] === 20 && vertices.length)
554
+ vertices[vertices.length - 1].y = num(e.values[k]);
555
+ else if (e.codes[k] === 42 && vertices.length)
556
+ vertices[vertices.length - 1].bulge = num(e.values[k]);
557
+ polyline(lineOut(), bulged(vertices, !!(n(70) & 1), n(38)).map(inOCS), false);
558
+ return;
559
+ }
560
+ case 'POLYLINE':
561
+ // Its vertices travel with it (gathered below as e.vertices).
562
+ polylineEntity(e, n(70), n(30), world, inOCS, faces, lineOut, n);
563
+ return;
564
+ case 'SPLINE': {
565
+ const knots = [], weights = [], control = [], fit = [];
566
+ for (let k = 0; k < e.codes.length; k++) {
567
+ const code = e.codes[k], v = num(e.values[k]);
568
+ if (code === 40)
569
+ knots.push(v);
570
+ else if (code === 41)
571
+ weights.push(v);
572
+ else if (code === 10)
573
+ control.push([v, 0, 0]);
574
+ else if (code === 20 && control.length)
575
+ control[control.length - 1][1] = v;
576
+ else if (code === 30 && control.length)
577
+ control[control.length - 1][2] = v;
578
+ else if (code === 11)
579
+ fit.push([v, 0, 0]);
580
+ else if (code === 21 && fit.length)
581
+ fit[fit.length - 1][1] = v;
582
+ else if (code === 31 && fit.length)
583
+ fit[fit.length - 1][2] = v;
584
+ }
585
+ const list = control.length ? spline(n(71, 3), knots, control, weights) : fit;
586
+ polyline(lineOut(), list.map(world), false);
587
+ return;
588
+ }
589
+ case '3DFACE': {
590
+ const p = [0, 1, 2, 3].map((k) => world([n(10 + k), n(20 + k), n(30 + k)]));
591
+ triangle(faces(), p[0], p[1], p[2]);
592
+ if (p[3].some((v, k) => v !== p[2][k]))
593
+ triangle(faces(), p[0], p[2], p[3]);
594
+ return;
595
+ }
596
+ case 'SOLID':
597
+ case 'TRACE': {
598
+ // Corners 3 and 4 are written in zig-zag order.
599
+ const p = [0, 1, 3, 2].map((k) => inOCS([n(10 + k), n(20 + k), n(30 + k)]));
600
+ triangle(faces(), p[0], p[1], p[2]);
601
+ if (p[2].some((v, k) => v !== p[3][k]))
602
+ triangle(faces(), p[0], p[2], p[3]);
603
+ return;
604
+ }
605
+ case 'MESH': {
606
+ const vertices = [];
607
+ let k = e.codes.indexOf(92);
608
+ if (k < 0)
609
+ return;
610
+ const count = num(e.values[k]);
611
+ checkCount(count, maxVertices, F, 'MESH vertex');
612
+ for (k++; k < e.codes.length && vertices.length < count; k++)
613
+ if (e.codes[k] === 10)
614
+ vertices.push([num(e.values[k]), num(e.values[k + 1]), num(e.values[k + 2])]);
615
+ while (k < e.codes.length && e.codes[k] !== 93)
616
+ k++;
617
+ const size = num(e.values[k]), list = [];
618
+ for (k++; k < e.codes.length && list.length < size && e.codes[k] === 90; k++)
619
+ list.push(num(e.values[k]));
620
+ const at = vertices.map(world);
621
+ for (let f = 0; f < list.length;) {
622
+ const sides = list[f], ids = list.slice(f + 1, f + 1 + sides);
623
+ f += 1 + sides;
624
+ if (ids.length < 3 || ids.some((id) => !(id >= 0 && id < at.length)))
625
+ throw new LoaderError(F, 'range', 'MESH face index outside its vertices');
626
+ for (let t = 1; t + 1 < ids.length; t++)
627
+ triangle(faces(), at[ids[0]], at[ids[t]], at[ids[t + 1]]);
628
+ }
629
+ return;
630
+ }
631
+ case 'TEXT':
632
+ case 'MTEXT':
633
+ case 'ATTRIB':
634
+ case 'ATTDEF': {
635
+ const flags = attribute ? n(70) : 0, definition = e.type === 'ATTDEF';
636
+ // Invisible attributes are not drawn. In a block only a constant definition is: an ATTRIB of each INSERT
637
+ // stands for every other one. A definition outside a block shows its tag.
638
+ if (flags & 1 || (definition && context.depth > 0 && !(flags & 2)))
639
+ return;
640
+ const mtext = e.type === 'MTEXT',
641
+ /** The strings of the 250-character chunks (code 3) after index `from`. */
642
+ chunks = (from) => e.codes.flatMap((c, k) => (k > from && c === 3 ? [str(e.values[k])] : [])).join(''), tail = embedded >= 0 ? e.codes.indexOf(1, embedded) : -1, multiline = tail >= 0 ? chunks(embedded) + str(e.values[tail]) : '', raw = definition && context.depth === 0 ? str(first(2)) : multiline || (mtext ? chunks(-1) : '') + str(first(1)),
643
+ // Attributes keep the vertical justification in code 74, TEXT in 73.
644
+ aligned = !mtext && (n(72) !== 0 || n(attribute ? 74 : 73) !== 0) && first(11) !== undefined, o = ocs(extrusion), local = mtext
645
+ ? [n(10), n(20), n(30)]
646
+ : apply(o, aligned ? n(11) : n(10), aligned ? n(21) : n(20), aligned ? n(31) : n(30)), angle = mtext ? n(50) : (n(50) * Math.PI) / 180, xAxis = mtext && first(11) !== undefined
647
+ ? [n(11), n(21), n(31)]
648
+ : direction(o, Math.cos(angle), Math.sin(angle), 0), position = apply(m, local[0], local[1], local[2]), height = n(40) * Math.hypot(m[4], m[5], m[6]);
649
+ if (attribute && !raw)
650
+ return;
651
+ texts.push({
652
+ text: controlCodes(mtext || multiline ? plainMText(raw) : unicode(raw)),
653
+ position,
654
+ height,
655
+ direction: direction(m, xAxis[0], xAxis[1], xAxis[2]),
656
+ normal: direction(m, ...direction(o, 0, 0, 1)),
657
+ layer: layerName,
658
+ color,
659
+ ...(attribute && { tag: unicode(str(first(2))) }),
660
+ });
661
+ return;
662
+ }
663
+ case 'INSERT':
664
+ case 'DIMENSION': {
665
+ const name = unicode(str(first(2)).trim()), block = blocks.get(name);
666
+ if (!block) {
667
+ if (name)
668
+ skip(`${e.type} of a missing block`);
669
+ return;
670
+ }
671
+ if (context.depth >= maxDepth)
672
+ throw new LoaderError(F, 'limit', `block references nest deeper than maxDepth ${maxDepth} (at "${name}")`);
673
+ const base = translate(-block.base[0], -block.base[1], -block.base[2]);
674
+ if (e.type === 'DIMENSION') {
675
+ // A dimension's anonymous block is drawn in world coordinates.
676
+ inserts++;
677
+ if (inserts > maxInserts)
678
+ throw new LoaderError(F, 'limit', `block references exceed maxInserts ${maxInserts}`);
679
+ for (const child of block.entities)
680
+ emit(child, { matrix: mul(m, base), layer: layerName, color, depth: context.depth + 1 });
681
+ return;
682
+ }
683
+ const o = ocs(extrusion), placed = mul(mul(o, translate(n(10), n(20), n(30))), rotateZ((n(50) * Math.PI) / 180)), scaled = mul(scaling(n(41, 1), n(42, 1), n(43, 1)), base), columns = Math.max(1, n(70, 1)), rows = Math.max(1, n(71, 1));
684
+ for (let r = 0; r < rows; r++)
685
+ for (let c = 0; c < columns; c++) {
686
+ inserts++;
687
+ if (inserts > maxInserts)
688
+ throw new LoaderError(F, 'limit', `block references exceed maxInserts ${maxInserts}`);
689
+ const local = mul(mul(placed, translate(c * n(44), r * n(45), 0)), scaled);
690
+ // Attributes are stored where the first copy shows them, in this INSERT's own space.
691
+ if (e.attributes) {
692
+ const from = apply(placed, 0, 0, 0), to = apply(placed, c * n(44), r * n(45), 0), matrix = mul(m, translate(to[0] - from[0], to[1] - from[1], to[2] - from[2]));
693
+ if ((r || c) && (inserts += e.attributes.length) > maxInserts)
694
+ throw new LoaderError(F, 'limit', `block references exceed maxInserts ${maxInserts}`);
695
+ for (const child of e.attributes)
696
+ emit(child, { matrix, layer: layerName, color, depth: context.depth + 1 });
697
+ }
698
+ for (const child of block.entities)
699
+ emit(child, { matrix: mul(m, local), layer: layerName, color, depth: context.depth + 1 });
700
+ }
701
+ return;
702
+ }
703
+ case 'HATCH': {
704
+ const hatch = options.hatch?.({
705
+ codes: e.codes,
706
+ values: e.values,
707
+ arcSegments,
708
+ arc,
709
+ bulged,
710
+ spline,
711
+ maxVertices,
712
+ maxTriangles: Math.floor(Math.min(maxTriangles - faceVertices / 3, (maxVertices - faceVertices) / 3)),
713
+ maxSegments: maxSegments - segments,
714
+ });
715
+ if (!hatch) {
716
+ skip(e.type);
717
+ return;
718
+ }
719
+ const placed = mul(m, ocs(extrusion)), at = (list, i) => apply(placed, list[i], list[i + 1], hatch.elevation), { triangles: t, segments: s } = hatch, fill = hatch.color ?? color;
720
+ for (let i = 0; i < t.length; i += 6)
721
+ triangle(group(faceGroups, layerName, fill), at(t, i), at(t, i + 2), at(t, i + 4));
722
+ for (let i = 0; i < s.length; i += 4)
723
+ polyline(group(lineGroups, layerName, fill), [at(s, i), at(s, i + 2)], false);
724
+ return;
725
+ }
726
+ case '3DSOLID':
727
+ case 'BODY':
728
+ case 'REGION': {
729
+ const lines = [];
730
+ for (let k = 0; k < e.codes.length; k++)
731
+ if (e.codes[k] === 1)
732
+ lines.push(str(e.values[k]));
733
+ else if (e.codes[k] === 3 && lines.length)
734
+ lines[lines.length - 1] += str(e.values[k]);
735
+ if (!lines.length) {
736
+ // AutoCAD 2013 and later keep the ACIS data as binary SAB in the ACDSDATA section.
737
+ skip(`${e.type} (binary ACIS)`);
738
+ return;
739
+ }
740
+ solids.push({ type: e.type, sat: decodeSAT(lines), transform: [...m], layer: layerName, color });
741
+ return;
742
+ }
743
+ case 'MLINE': {
744
+ // WCS points. Each vertex (codes 11, its segment's direction 12, its miter 13) lists, for every element of
745
+ // the style, a count (74) and that many 41 values: the offset along the miter, then the distances along the
746
+ // segment where the element starts and, from that start, where it breaks and resumes.
747
+ const vertices = [];
748
+ for (let k = 0; k < e.codes.length; k++) {
749
+ const c = e.codes[k], axis = Math.floor(c / 10) - 1, part = (c % 10) - 1;
750
+ if (c === 11)
751
+ vertices.push({ v: [[], [], []], elements: [] });
752
+ const vertex = vertices[vertices.length - 1];
753
+ if (!vertex)
754
+ continue;
755
+ if (c === 74)
756
+ vertex.elements.push([]);
757
+ else if (c === 41)
758
+ vertex.elements[vertex.elements.length - 1]?.push(num(e.values[k]));
759
+ else if (axis >= 0 && axis < 3 && part >= 0 && part < 3)
760
+ vertex.v[part][axis] = num(e.values[k]);
761
+ }
762
+ const count = vertices.length - (n(71) & 2 && vertices.length > 2 ? 0 : 1);
763
+ for (let i = 0; i < count; i++) {
764
+ const a = vertices[i], b = vertices[(i + 1) % vertices.length], [from, along, miter] = a.v;
765
+ a.elements.forEach(([offset, start = 0, ...cuts], element) => {
766
+ if (offset === undefined)
767
+ return;
768
+ const to = b.elements[element]?.[0] ?? offset, at = (t) => world([0, 1, 2].map((x) => (from[x] ?? 0) + (miter[x] ?? 0) * offset + (along[x] ?? 0) * t)), end = world([0, 1, 2].map((x) => (b.v[0][x] ?? 0) + (b.v[2][x] ?? 0) * to)), toggles = [start, ...cuts.map((d) => start + d)];
769
+ for (let t = 0; t < toggles.length; t += 2)
770
+ polyline(lineOut(), [at(toggles[t]), t + 1 < toggles.length ? at(toggles[t + 1]) : end], false);
771
+ });
772
+ }
773
+ return;
774
+ }
775
+ case 'LEADER':
776
+ case 'MULTILEADER':
777
+ case 'MLEADER': {
778
+ const leader = e.type === 'LEADER',
779
+ // A dimension variable comes from the entity's overrides, else its DIMSTYLE, else the header.
780
+ overrides = dimensionOverrides(e.codes, e.values), style = leader ? dimensionStyles.get(unicode(str(first(3)).trim()).toUpperCase()) : undefined, dimension = (code) => {
781
+ const k = style ? style.codes.indexOf(code) : -1, stated = overrides.get(code) ?? (k < 0 ? undefined : style.values[k]);
782
+ if (stated !== undefined || !(code in HEADER_DIMENSIONS))
783
+ return stated;
784
+ const [variable, group, fallback] = HEADER_DIMENSIONS[code];
785
+ return header.get(variable)?.get(group) ?? fallback;
786
+ }, curve = {
787
+ segments: splineSegments,
788
+ most: maxSegments - segments,
789
+ tooMany: () => {
790
+ throw new LoaderError(F, 'limit', `line segment count exceeds the limit of ${maxSegments}`);
791
+ },
792
+ }, multi = leader ? undefined : readMultiLeader(e.codes, e.values, dimension, curve), plan = leader ? readLeader(e.codes, e.values, dimension, curve) : multi;
793
+ if (!plan) {
794
+ skip(`${e.type} (no context data)`);
795
+ return;
796
+ }
797
+ /** Draws a block's entities as part of this entity: an arrowhead or the content. */
798
+ const place = (name, entities, matrix) => {
799
+ if (context.depth >= maxDepth)
800
+ throw new LoaderError(F, 'limit', `block references nest deeper than maxDepth ${maxDepth} (at "${name}")`);
801
+ inserts++;
802
+ if (inserts > maxInserts)
803
+ throw new LoaderError(F, 'limit', `block references exceed maxInserts ${maxInserts}`);
804
+ for (const child of entities)
805
+ emit(child, { matrix, layer: layerName, color, depth: context.depth + 1 });
806
+ };
807
+ for (const path of plan.paths)
808
+ polyline(lineOut(), path.map(world), false);
809
+ // A leader's own arrow block (DIMLDRBLK): a handle in its style or overrides, a name in the header.
810
+ const own = dimension(341), named = own === undefined && !style ? str(header.get('$DIMLDRBLK')?.get(1)).trim() : '';
811
+ for (const arrow of plan.arrows) {
812
+ const stated = leader ? own : arrow.handle, name = stated === undefined ? unicode(named) : records.get(handle(stated)), symbol = name ? blocks.get(name) : undefined, { u, v, w } = arrowAxes(arrow), { tip, size } = arrow;
813
+ if (symbol) {
814
+ // The arrow block is drawn pointing along +X with its tip at the insertion point, one arrow size long.
815
+ const [x, y, z] = [u, v, w].map((axis) => axis.map((c) => c * size)), placed = Float64Array.of(...x, 0, ...y, 0, ...z, 0, ...tip, 1), base = translate(-symbol.base[0], -symbol.base[1], -symbol.base[2]);
816
+ place(name, symbol.entities, mul(mul(m, placed), base));
817
+ continue;
818
+ }
819
+ // The closed filled arrow: as long as the arrow size and a third as wide.
820
+ const corner = (side) => world([0, 1, 2].map((a) => tip[a] - u[a] * size + (v[a] * side * size) / 6));
821
+ triangle(faces(), world(tip), corner(1), corner(-1));
822
+ }
823
+ if (!multi)
824
+ return;
825
+ if (multi.tolerance)
826
+ skip(`${e.type} (tolerance content)`);
827
+ if (multi.text) {
828
+ const { raw, position, height, direction: along, normal } = multi.text;
829
+ texts.push({
830
+ text: controlCodes(plainMText(raw)),
831
+ position: world(position),
832
+ height: height * Math.hypot(m[4], m[5], m[6]),
833
+ direction: direction(m, ...along),
834
+ normal: direction(m, ...normal),
835
+ layer: layerName,
836
+ color,
837
+ });
838
+ }
839
+ if (multi.block) {
840
+ const { position, normal, rotation, scale: size, attributes } = multi.block, name = records.get(handle(multi.block.handle)), content = name === undefined ? undefined : blocks.get(name);
841
+ if (!content) {
842
+ skip(`${e.type} (missing block)`);
843
+ return;
844
+ }
845
+ const placed = mul(mul(translate(...position), ocs(normal)), rotateZ(rotation)), base = translate(-content.base[0], -content.base[1], -content.base[2]), matrix = mul(m, mul(placed, mul(scaling(...size), base))),
846
+ // Each attribute value takes the place and look of its definition in the block.
847
+ filled = attributes.flatMap(([id, value]) => {
848
+ const definition = content.entities.find((d) => d.type === 'ATTDEF' && handle(d.values[d.codes.indexOf(5)]) === handle(id));
849
+ if (!definition)
850
+ return [];
851
+ const embedded = definition.codes.indexOf(101), end = embedded < 0 ? definition.codes.length : embedded, codes = definition.codes.slice(0, end), values = definition.values.slice(0, end), k = codes.indexOf(1);
852
+ if (k < 0) {
853
+ codes.push(1);
854
+ values.push(value);
855
+ }
856
+ else
857
+ values[k] = value;
858
+ return [{ type: 'ATTRIB', codes, values }];
859
+ });
860
+ place(name, [...content.entities, ...filled], matrix);
861
+ }
862
+ return;
863
+ }
864
+ case 'VERTEX':
865
+ case 'SEQEND':
866
+ case 'VIEWPORT':
867
+ return;
868
+ default:
869
+ skip(e.type);
870
+ }
871
+ };
872
+ /** POLYLINE: polyface mesh, polygon mesh, 3D polyline, or 2D polyline (with bulges, in its OCS at its elevation). */
873
+ const polylineEntity = (e, flags, elevation, world, inOCS, faces, lineOut, n) => {
874
+ const vertices = (e.vertices ?? []).map((v) => {
875
+ const get = (code, fallback = 0) => {
876
+ const k = v.codes.indexOf(code);
877
+ return k < 0 ? fallback : num(v.values[k], fallback);
878
+ };
879
+ return {
880
+ p: [get(10), get(20), get(30)],
881
+ bulge: get(42),
882
+ flags: get(70),
883
+ ids: [get(71), get(72), get(73), get(74)],
884
+ };
885
+ });
886
+ if (flags & 64) {
887
+ const positions = vertices.filter((v) => v.flags & 128 && v.flags & 64).map((v) => world(v.p));
888
+ for (const v of vertices)
889
+ if (v.flags & 128 && !(v.flags & 64)) {
890
+ const ids = v.ids.map(Math.abs).filter((id) => id > 0);
891
+ if (ids.some((id) => id > positions.length))
892
+ throw new LoaderError(F, 'range', 'polyface face index outside its vertices');
893
+ for (let t = 1; t + 1 < ids.length; t++)
894
+ triangle(faces(), positions[ids[0] - 1], positions[ids[t] - 1], positions[ids[t + 1] - 1]);
895
+ }
896
+ }
897
+ else if (flags & 16) {
898
+ const rows = n(71), columns = n(72), at = vertices.map((v) => world(v.p));
899
+ if (rows * columns > at.length || rows < 2 || columns < 2)
900
+ throw new LoaderError(F, 'range', `polygon mesh of ${rows} x ${columns} has ${at.length} vertices`);
901
+ const closedM = !!(flags & 1), closedN = !!(flags & 32);
902
+ for (let i = 0; i < rows - (closedM ? 0 : 1); i++)
903
+ for (let j = 0; j < columns - (closedN ? 0 : 1); j++) {
904
+ const a = at[i * columns + j], b = at[i * columns + ((j + 1) % columns)], c = at[((i + 1) % rows) * columns + ((j + 1) % columns)], d = at[((i + 1) % rows) * columns + j];
905
+ triangle(faces(), a, b, c);
906
+ triangle(faces(), a, c, d);
907
+ }
908
+ }
909
+ else if (flags & 8)
910
+ polyline(lineOut(), vertices.map((v) => world(v.p)), !!(flags & 1));
911
+ else
912
+ polyline(lineOut(), bulged(vertices.map((v) => ({ x: v.p[0], y: v.p[1], bulge: v.bulge })), !!(flags & 1), elevation).map(inOCS), false);
913
+ };
914
+ /** Attaches each POLYLINE's VERTEX entities and each INSERT's ATTRIB entities to it, up to SEQEND. */
915
+ const gather = (list) => {
916
+ const out = [];
917
+ for (let k = 0; k < list.length; k++) {
918
+ const e = list[k];
919
+ if (e.type === 'POLYLINE') {
920
+ const vertices = [];
921
+ while (k + 1 < list.length && list[k + 1].type === 'VERTEX')
922
+ vertices.push(list[++k]);
923
+ if (k + 1 < list.length && list[k + 1].type === 'SEQEND')
924
+ k++;
925
+ out.push(Object.assign(e, { vertices }));
926
+ }
927
+ else if (e.type === 'INSERT') {
928
+ out.push(e);
929
+ let j = k + 1;
930
+ while (j < list.length && list[j].type === 'ATTRIB')
931
+ j++;
932
+ if (j > k + 1 && j < list.length && list[j].type === 'SEQEND') {
933
+ out[out.length - 1] = Object.assign(e, { attributes: list.slice(k + 1, j) });
934
+ k = j;
935
+ }
936
+ }
937
+ else
938
+ out.push(e);
939
+ }
940
+ return out;
941
+ };
942
+ for (const block of blocks.values())
943
+ block.entities = gather(block.entities);
944
+ const root = { matrix: scaling(scale, scale, scale), layer: '0', color: ACI[7], depth: 0 };
945
+ for (const e of gather(model))
946
+ emit(e, root);
947
+ // --- assemble ---------------------------------------------------------------------------------------------------
948
+ const facePositions = new Float32Array(faceVertices * 3), meshGroups = [];
949
+ let at = 0;
950
+ for (const g of faceGroups.values()) {
951
+ if (!g.positions.length)
952
+ continue;
953
+ facePositions.set(g.positions, at * 3);
954
+ meshGroups.push({ start: at, count: g.positions.length / 3, name: g.name, color: [...g.color, 1] });
955
+ at += g.positions.length / 3;
956
+ }
957
+ const linePositions = new Float32Array(segments * 6), lineColors = new Float32Array(segments * 6), lineGroupList = [];
958
+ at = 0;
959
+ for (const g of lineGroups.values()) {
960
+ if (!g.positions.length)
961
+ continue;
962
+ const count = g.positions.length / 3;
963
+ linePositions.set(g.positions, at * 3);
964
+ for (let k = 0; k < count; k++)
965
+ lineColors.set(g.color, (at + k) * 3);
966
+ lineGroupList.push({ start: at, count, name: g.name, color: [...g.color, 1] });
967
+ at += count;
968
+ }
969
+ return {
970
+ mesh: {
971
+ kind: 'mesh',
972
+ positions: facePositions,
973
+ indices: Uint32Array.from({ length: facePositions.length / 3 }, (_, k) => k),
974
+ groups: meshGroups,
975
+ },
976
+ lines: { positions: linePositions, colors: lineColors, groups: lineGroupList },
977
+ points: Float32Array.from(points),
978
+ texts,
979
+ layers: [...layers.values()].map(({ name, color, visible }) => ({ name, color, visible })),
980
+ solids,
981
+ unit,
982
+ version,
983
+ skipped,
984
+ };
985
+ }