@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/svg.js ADDED
@@ -0,0 +1,1007 @@
1
+ import { geometryData } from '@margoengine/geometry/utils';
2
+ import { outlineShapes } from './outline.js';
3
+ import { LoaderError } from './types.js';
4
+ import { toBytes } from './util.js';
5
+ import { decodeXML, readXMLTree } from './xml.js';
6
+ const F = 'SVG';
7
+ /** Most path commands in one `d` attribute, and in the whole document counting `<use>` copies. */
8
+ const MAX_COMMANDS = 4_000_000;
9
+ /** Deepest chain of `<use>` references followed. */
10
+ const MAX_USE_DEPTH = 32;
11
+ /** Most `href` hops followed from a gradient to the one that holds its stops. */
12
+ const MAX_GRADIENT_HOPS = 8;
13
+ const HALF_PI = Math.PI / 2;
14
+ const IDENTITY = [1, 0, 0, 1, 0, 0];
15
+ /** `m` then `n` in written order: the result maps a point through `n` first. */
16
+ const compose = (m, n) => [
17
+ m[0] * n[0] + m[2] * n[1],
18
+ m[1] * n[0] + m[3] * n[1],
19
+ m[0] * n[2] + m[2] * n[3],
20
+ m[1] * n[2] + m[3] * n[3],
21
+ m[0] * n[4] + m[2] * n[5] + m[4],
22
+ m[1] * n[4] + m[3] * n[5] + m[5],
23
+ ];
24
+ const shift = (x, y) => [1, 0, 0, 1, x, y];
25
+ const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
26
+ const NUMBER = '[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:[eE][+-]?\\d+)?';
27
+ const NUMBERS = new RegExp(NUMBER, 'g');
28
+ const numbers = (text) => (text?.match(NUMBERS) ?? []).map(Number);
29
+ const localName = (name) => name.slice(name.indexOf(':') + 1);
30
+ // ---------------------------------------------------------------------------------------------------------------
31
+ // Colours (CSS Color 3 and 4)
32
+ /** The 148 named colours of CSS Color 4 section 6.1, as name and six hex digits. */
33
+ const NAMED = 'aliceblue f0f8ff antiquewhite faebd7 aqua 00ffff aquamarine 7fffd4 azure f0ffff beige f5f5dc bisque ffe4c4 ' +
34
+ 'black 000000 blanchedalmond ffebcd blue 0000ff blueviolet 8a2be2 brown a52a2a burlywood deb887 cadetblue 5f9ea0 ' +
35
+ 'chartreuse 7fff00 chocolate d2691e coral ff7f50 cornflowerblue 6495ed cornsilk fff8dc crimson dc143c cyan 00ffff ' +
36
+ 'darkblue 00008b darkcyan 008b8b darkgoldenrod b8860b darkgray a9a9a9 darkgreen 006400 darkgrey a9a9a9 ' +
37
+ 'darkkhaki bdb76b darkmagenta 8b008b darkolivegreen 556b2f darkorange ff8c00 darkorchid 9932cc darkred 8b0000 ' +
38
+ 'darksalmon e9967a darkseagreen 8fbc8f darkslateblue 483d8b darkslategray 2f4f4f darkslategrey 2f4f4f ' +
39
+ 'darkturquoise 00ced1 darkviolet 9400d3 deeppink ff1493 deepskyblue 00bfff dimgray 696969 dimgrey 696969 ' +
40
+ 'dodgerblue 1e90ff firebrick b22222 floralwhite fffaf0 forestgreen 228b22 fuchsia ff00ff gainsboro dcdcdc ' +
41
+ 'ghostwhite f8f8ff gold ffd700 goldenrod daa520 gray 808080 green 008000 greenyellow adff2f grey 808080 ' +
42
+ 'honeydew f0fff0 hotpink ff69b4 indianred cd5c5c indigo 4b0082 ivory fffff0 khaki f0e68c lavender e6e6fa ' +
43
+ 'lavenderblush fff0f5 lawngreen 7cfc00 lemonchiffon fffacd lightblue add8e6 lightcoral f08080 lightcyan e0ffff ' +
44
+ 'lightgoldenrodyellow fafad2 lightgray d3d3d3 lightgreen 90ee90 lightgrey d3d3d3 lightpink ffb6c1 ' +
45
+ 'lightsalmon ffa07a lightseagreen 20b2aa lightskyblue 87cefa lightslategray 778899 lightslategrey 778899 ' +
46
+ 'lightsteelblue b0c4de lightyellow ffffe0 lime 00ff00 limegreen 32cd32 linen faf0e6 magenta ff00ff maroon 800000 ' +
47
+ 'mediumaquamarine 66cdaa mediumblue 0000cd mediumorchid ba55d3 mediumpurple 9370db mediumseagreen 3cb371 ' +
48
+ 'mediumslateblue 7b68ee mediumspringgreen 00fa9a mediumturquoise 48d1cc mediumvioletred c71585 ' +
49
+ 'midnightblue 191970 mintcream f5fffa mistyrose ffe4e1 moccasin ffe4b5 navajowhite ffdead navy 000080 ' +
50
+ 'oldlace fdf5e6 olive 808000 olivedrab 6b8e23 orange ffa500 orangered ff4500 orchid da70d6 palegoldenrod eee8aa ' +
51
+ 'palegreen 98fb98 paleturquoise afeeee palevioletred db7093 papayawhip ffefd5 peachpuff ffdab9 peru cd853f ' +
52
+ 'pink ffc0cb plum dda0dd powderblue b0e0e6 purple 800080 rebeccapurple 663399 red ff0000 rosybrown bc8f8f ' +
53
+ 'royalblue 4169e1 saddlebrown 8b4513 salmon fa8072 sandybrown f4a460 seagreen 2e8b57 seashell fff5ee ' +
54
+ 'sienna a0522d silver c0c0c0 skyblue 87ceeb slateblue 6a5acd slategray 708090 slategrey 708090 snow fffafa ' +
55
+ 'springgreen 00ff7f steelblue 4682b4 tan d2b48c teal 008080 thistle d8bfd8 tomato ff6347 turquoise 40e0d0 ' +
56
+ 'violet ee82ee wheat f5deb3 white ffffff whitesmoke f5f5f5 yellow ffff00 yellowgreen 9acd32';
57
+ let namedColours;
58
+ function hexColour(hex) {
59
+ if (!/^[0-9a-f]+$/.test(hex))
60
+ return null;
61
+ const pairs = hex.length === 6 || hex.length === 8;
62
+ if (!pairs && hex.length !== 3 && hex.length !== 4)
63
+ return null;
64
+ const channels = pairs ? hex.length / 2 : hex.length;
65
+ const channel = (i) => parseInt(pairs ? hex.slice(2 * i, 2 * i + 2) : hex[i] + hex[i], 16) / 255;
66
+ return [channel(0), channel(1), channel(2), channels === 4 ? channel(3) : 1];
67
+ }
68
+ /** CSS Color 3 section 4.2.4: one RGB channel from the two HSL helper values and a hue in turns. */
69
+ function hueChannel(m1, m2, h) {
70
+ if (h < 0)
71
+ h += 1;
72
+ if (h > 1)
73
+ h -= 1;
74
+ if (h * 6 < 1)
75
+ return m1 + (m2 - m1) * h * 6;
76
+ if (h * 2 < 1)
77
+ return m2;
78
+ if (h * 3 < 2)
79
+ return m1 + (m2 - m1) * (2 / 3 - h) * 6;
80
+ return m1;
81
+ }
82
+ /** Reads a CSS colour (hex, rgb/rgba, hsl/hsla, a named colour or transparent); null when it is not one. */
83
+ function readColour(value) {
84
+ const text = value.trim().toLowerCase();
85
+ if (text === 'transparent')
86
+ return [0, 0, 0, 0];
87
+ if (text[0] === '#')
88
+ return hexColour(text.slice(1));
89
+ const call = /^(rgba?|hsla?)\(([^)]*)\)$/.exec(text);
90
+ if (call) {
91
+ const parts = call[2].split(/[\s,/]+/).filter(Boolean);
92
+ if (parts.length < 3 || parts.length > 4)
93
+ return null;
94
+ const values = [], percent = [];
95
+ for (const [i, part] of parts.entries()) {
96
+ const match = new RegExp(`^(${NUMBER})(%|deg)?$`).exec(part);
97
+ if (!match || (match[2] === 'deg' && (i > 0 || call[1][0] !== 'h')))
98
+ return null;
99
+ values.push(Number(match[1]));
100
+ percent.push(match[2] === '%');
101
+ }
102
+ const alpha = values.length > 3 ? clamp01(percent[3] ? values[3] / 100 : values[3]) : 1;
103
+ if (call[1][0] === 'r') {
104
+ const c = (i) => clamp01(percent[i] ? values[i] / 100 : values[i] / 255);
105
+ return [c(0), c(1), c(2), alpha];
106
+ }
107
+ const h = (((values[0] % 360) + 360) % 360) / 360, s = clamp01(values[1] / 100), l = clamp01(values[2] / 100);
108
+ const m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s, m1 = l * 2 - m2;
109
+ return [hueChannel(m1, m2, h + 1 / 3), hueChannel(m1, m2, h), hueChannel(m1, m2, h - 1 / 3), alpha];
110
+ }
111
+ if (!namedColours) {
112
+ namedColours = new Map();
113
+ const words = NAMED.split(' ');
114
+ for (let i = 0; i < words.length; i += 2)
115
+ namedColours.set(words[i], words[i + 1]);
116
+ }
117
+ const hex = namedColours.get(text);
118
+ return hex ? hexColour(hex) : null;
119
+ }
120
+ /** A number or a percentage, clamped to 0..1; 1 when the value is missing or invalid. */
121
+ function readOpacity(value) {
122
+ const match = value === undefined ? null : new RegExp(`^(${NUMBER})(%?)$`).exec(value.trim());
123
+ return match ? clamp01(Number(match[1]) / (match[2] ? 100 : 1)) : 1;
124
+ }
125
+ // ---------------------------------------------------------------------------------------------------------------
126
+ // Lengths (CSS Values 3 section 5.2: 96 px per inch; no font context, so em = 16 px and ex = 8 px)
127
+ const UNITS = new Map([
128
+ ['', 1],
129
+ ['px', 1],
130
+ ['pt', 4 / 3],
131
+ ['pc', 16],
132
+ ['mm', 96 / 25.4],
133
+ ['cm', 96 / 2.54],
134
+ ['in', 96],
135
+ ['em', 16],
136
+ ['ex', 8],
137
+ ]);
138
+ const LENGTH = new RegExp(`^\\s*(${NUMBER})\\s*(%|[a-zA-Z]*)\\s*$`);
139
+ /** A length in user units; `reference` is what 100% means; `fallback` when the value is missing or invalid. */
140
+ function readLength(value, reference, fallback) {
141
+ const match = value === undefined ? null : LENGTH.exec(value);
142
+ if (!match)
143
+ return fallback;
144
+ const n = Number(match[1]);
145
+ if (match[2] === '%')
146
+ return (n * reference) / 100;
147
+ const scale = UNITS.get(match[2].toLowerCase());
148
+ return scale === undefined ? fallback : n * scale;
149
+ }
150
+ // ---------------------------------------------------------------------------------------------------------------
151
+ // Transforms (SVG 1.1 section 7.6)
152
+ function readTransform(text, warn) {
153
+ let m = IDENTITY;
154
+ if (!text)
155
+ return m;
156
+ for (const [item, name, args] of text.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)) {
157
+ const v = numbers(args);
158
+ const angle = ((v[0] ?? 0) * Math.PI) / 180;
159
+ let t;
160
+ if (name === 'matrix') {
161
+ if (v.length === 6)
162
+ t = v;
163
+ else
164
+ warn(`transform "${item.slice(0, 60)}" needs 6 numbers; ignored`);
165
+ }
166
+ else if (name === 'translate')
167
+ t = shift(v[0] ?? 0, v[1] ?? 0);
168
+ else if (name === 'scale')
169
+ t = [v[0] ?? 1, 0, 0, v[1] ?? v[0] ?? 1, 0, 0];
170
+ else if (name === 'rotate') {
171
+ const c = Math.cos(angle), s = Math.sin(angle);
172
+ t = [c, s, -s, c, 0, 0];
173
+ if (v.length >= 3)
174
+ t = compose(compose(shift(v[1], v[2]), t), shift(-v[1], -v[2]));
175
+ }
176
+ else if (name === 'skewX')
177
+ t = [1, 0, Math.tan(angle), 1, 0, 0];
178
+ else
179
+ t = [1, Math.tan(angle), 0, 1, 0, 0];
180
+ if (t)
181
+ m = compose(m, t);
182
+ }
183
+ return m;
184
+ }
185
+ // ---------------------------------------------------------------------------------------------------------------
186
+ // Elliptical arcs (SVG 1.1 appendix F.6) as cubic Béziers
187
+ /**
188
+ * Appends the arc from (x1, y1) to (x2, y2) as cubics of at most 90 degrees each. Endpoint to centre conversion
189
+ * follows F.6.5 with the radius correction of F.6.6; each piece uses control points at 4/3 tan(phi / 4) along the
190
+ * unit-circle tangents (Maisonobe 2003, section 3.4.1), mapped through the radii and rotation.
191
+ */
192
+ function appendArc(out, x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
193
+ if (x1 === x2 && y1 === y2)
194
+ return;
195
+ rx = Math.abs(rx);
196
+ ry = Math.abs(ry);
197
+ if (rx === 0 || ry === 0) {
198
+ out.push(['L', x2, y2]);
199
+ return;
200
+ }
201
+ const phi = (rotation * Math.PI) / 180, cos = Math.cos(phi), sin = Math.sin(phi);
202
+ // F.6.5.1: the start point in a frame centred between the end points, aligned with the ellipse axes.
203
+ const hx = (x1 - x2) / 2, hy = (y1 - y2) / 2;
204
+ const px = cos * hx + sin * hy, py = -sin * hx + cos * hy;
205
+ // F.6.6: grow the radii uniformly when no ellipse of this size reaches both points.
206
+ const lambda = (px * px) / (rx * rx) + (py * py) / (ry * ry);
207
+ if (lambda > 1) {
208
+ rx *= Math.sqrt(lambda);
209
+ ry *= Math.sqrt(lambda);
210
+ }
211
+ // F.6.5.2: the centre in that frame.
212
+ const a = rx * rx * py * py, b = ry * ry * px * px;
213
+ const root = Math.sqrt(Math.max(0, (rx * rx * ry * ry - a - b) / (a + b))) * (large === sweep ? -1 : 1);
214
+ const qx = (root * rx * py) / ry, qy = (-root * ry * px) / rx;
215
+ // F.6.5.3: back to user space.
216
+ const cx = cos * qx - sin * qy + (x1 + x2) / 2, cy = sin * qx + cos * qy + (y1 + y2) / 2;
217
+ // F.6.5.5 and F.6.5.6: start angle and signed sweep on the unit circle.
218
+ const start = Math.atan2((py - qy) / ry, (px - qx) / rx);
219
+ let delta = Math.atan2((-py - qy) / ry, (-px - qx) / rx) - start;
220
+ if (sweep && delta < 0)
221
+ delta += 2 * Math.PI;
222
+ else if (!sweep && delta > 0)
223
+ delta -= 2 * Math.PI;
224
+ const pieces = Math.max(1, Math.ceil(Math.abs(delta) / HALF_PI - 1e-9)), step = delta / pieces, k = (4 / 3) * Math.tan(step / 4);
225
+ const map = (ux, uy) => [
226
+ cx + cos * rx * ux - sin * ry * uy,
227
+ cy + sin * rx * ux + cos * ry * uy,
228
+ ];
229
+ for (let i = 0; i < pieces; i++) {
230
+ const a0 = start + i * step, a1 = a0 + step;
231
+ const c0 = Math.cos(a0), s0 = Math.sin(a0), c1 = Math.cos(a1), s1 = Math.sin(a1);
232
+ const p1 = map(c0 - k * s0, s0 + k * c0), p2 = map(c1 + k * s1, s1 - k * c1), end = i === pieces - 1 ? [x2, y2] : map(c1, s1);
233
+ out.push(['C', p1[0], p1[1], p2[0], p2[1], end[0], end[1]]);
234
+ }
235
+ }
236
+ // ---------------------------------------------------------------------------------------------------------------
237
+ // Path data (SVG 1.1 section 8.3, SVG 2 section 9.3)
238
+ const PARAMETERS = { m: 2, l: 2, h: 1, v: 1, c: 6, s: 4, q: 4, t: 2, a: 7, z: 0 };
239
+ const PATH_NUMBER = new RegExp(NUMBER, 'y');
240
+ /** Reads `d` into absolute M, L, Q, C and Z commands, keeping everything before the first error. */
241
+ function readPathData(d, warn) {
242
+ const out = [];
243
+ const length = d.length;
244
+ let i = 0, command = '', groups = 0;
245
+ let x = 0, y = 0, startX = 0, startY = 0;
246
+ let cubic = null, quad = null;
247
+ const skip = () => {
248
+ while (i < length && /[\s,]/.test(d[i]))
249
+ i++;
250
+ };
251
+ const here = () => `"${d.slice(i, i + 16)}"`;
252
+ const stop = (message) => warn(`path data error, the rest of the path is skipped: ${message}`);
253
+ const values = [];
254
+ for (;;) {
255
+ skip();
256
+ if (i >= length)
257
+ break;
258
+ const char = d[i];
259
+ const letter = /[mzlhvcsqta]/i.test(char);
260
+ if (!out.length && !/[Mm]/.test(char)) {
261
+ stop(`path data starts with ${here()}, not a command`);
262
+ break;
263
+ }
264
+ if (letter) {
265
+ command = char;
266
+ i++;
267
+ if (command === 'Z' || command === 'z') {
268
+ out.push(['Z']);
269
+ x = startX;
270
+ y = startY;
271
+ cubic = quad = null;
272
+ continue;
273
+ }
274
+ }
275
+ else if (command === 'Z' || command === 'z') {
276
+ stop(`unexpected ${here()} after Z`);
277
+ break;
278
+ }
279
+ const lower = command.toLowerCase(), relative = command === lower, count = PARAMETERS[lower];
280
+ values.length = 0;
281
+ for (let k = 0; k < count; k++) {
282
+ skip();
283
+ if (lower === 'a' && (k === 3 || k === 4)) {
284
+ if (d[i] !== '0' && d[i] !== '1') {
285
+ stop(`expected an arc flag 0 or 1 at ${here()}`);
286
+ return out;
287
+ }
288
+ values.push(d[i++] === '1' ? 1 : 0);
289
+ continue;
290
+ }
291
+ PATH_NUMBER.lastIndex = i;
292
+ const match = PATH_NUMBER.exec(d);
293
+ if (!match) {
294
+ stop(`expected a number at ${here()}`);
295
+ return out;
296
+ }
297
+ i += match[0].length;
298
+ values.push(Number(match[0]));
299
+ }
300
+ if (++groups > MAX_COMMANDS)
301
+ throw new LoaderError(F, 'limit', `path data has more than ${MAX_COMMANDS} commands; split the drawing`);
302
+ const ox = relative ? x : 0, oy = relative ? y : 0;
303
+ const v = values;
304
+ let nextCubic = null, nextQuad = null;
305
+ switch (lower) {
306
+ case 'm':
307
+ x = startX = v[0] + ox;
308
+ y = startY = v[1] + oy;
309
+ out.push(['M', x, y]);
310
+ // Further pairs after a moveto are linetos.
311
+ command = relative ? 'l' : 'L';
312
+ break;
313
+ case 'l':
314
+ x = v[0] + ox;
315
+ y = v[1] + oy;
316
+ out.push(['L', x, y]);
317
+ break;
318
+ case 'h':
319
+ x = v[0] + ox;
320
+ out.push(['L', x, y]);
321
+ break;
322
+ case 'v':
323
+ y = v[0] + oy;
324
+ out.push(['L', x, y]);
325
+ break;
326
+ case 'c':
327
+ case 's': {
328
+ const first = lower === 'c' ? [v[0] + ox, v[1] + oy] : cubic ? [2 * x - cubic[0], 2 * y - cubic[1]] : [x, y];
329
+ const j = lower === 'c' ? 2 : 0;
330
+ nextCubic = [v[j] + ox, v[j + 1] + oy];
331
+ x = v[j + 2] + ox;
332
+ y = v[j + 3] + oy;
333
+ out.push(['C', first[0], first[1], nextCubic[0], nextCubic[1], x, y]);
334
+ break;
335
+ }
336
+ case 'q':
337
+ case 't': {
338
+ nextQuad = lower === 'q' ? [v[0] + ox, v[1] + oy] : quad ? [2 * x - quad[0], 2 * y - quad[1]] : [x, y];
339
+ const j = lower === 'q' ? 2 : 0;
340
+ x = v[j] + ox;
341
+ y = v[j + 1] + oy;
342
+ out.push(['Q', nextQuad[0], nextQuad[1], x, y]);
343
+ break;
344
+ }
345
+ default: {
346
+ const ex = v[5] + ox, ey = v[6] + oy;
347
+ appendArc(out, x, y, v[0], v[1], v[2], v[3] === 1, v[4] === 1, ex, ey);
348
+ x = ex;
349
+ y = ey;
350
+ }
351
+ }
352
+ cubic = nextCubic;
353
+ quad = nextQuad;
354
+ }
355
+ return out;
356
+ }
357
+ // ---------------------------------------------------------------------------------------------------------------
358
+ // CSS subset: type, class and id selectors
359
+ /** Every property the reader uses; all inherit except `opacity` and `display`. */
360
+ const PROPERTIES = new Set([
361
+ 'fill',
362
+ 'fill-opacity',
363
+ 'fill-rule',
364
+ 'stroke',
365
+ 'stroke-opacity',
366
+ 'stroke-width',
367
+ 'stroke-linejoin',
368
+ 'stroke-linecap',
369
+ 'stroke-miterlimit',
370
+ 'color',
371
+ 'visibility',
372
+ 'opacity',
373
+ 'display',
374
+ ]);
375
+ /** Attributes and properties that change the drawing but are not applied; each draws a warning. */
376
+ const UNAPPLIED = [
377
+ 'clip-path',
378
+ 'mask',
379
+ 'filter',
380
+ 'marker',
381
+ 'marker-start',
382
+ 'marker-mid',
383
+ 'marker-end',
384
+ 'stroke-dasharray',
385
+ ];
386
+ /** `name: value` pairs of a declaration block, names lower-cased, values trimmed, `!important` dropped. */
387
+ function readDeclarations(text) {
388
+ const out = [];
389
+ for (const part of text.split(';')) {
390
+ const colon = part.indexOf(':');
391
+ if (colon < 0)
392
+ continue;
393
+ const name = part.slice(0, colon).trim().toLowerCase();
394
+ const value = part
395
+ .slice(colon + 1)
396
+ .replace(/!\s*important\s*$/i, '')
397
+ .trim();
398
+ if (name)
399
+ out.push([name, value]);
400
+ }
401
+ return out;
402
+ }
403
+ function readStyleSheet(css, rules, warn) {
404
+ css = css.replace(/\/\*[\s\S]*?\*\//g, '');
405
+ let i = 0;
406
+ while (i < css.length) {
407
+ while (i < css.length && /\s/.test(css[i]))
408
+ i++;
409
+ if (i >= css.length)
410
+ break;
411
+ if (css[i] === '@') {
412
+ warn(`CSS @${/^@([\w-]*)/.exec(css.slice(i))?.[1] ?? ''} rule skipped`);
413
+ const semicolon = css.indexOf(';', i), brace = css.indexOf('{', i);
414
+ if (brace >= 0 && (semicolon < 0 || brace < semicolon)) {
415
+ let depth = 0;
416
+ for (i = brace; i < css.length; i++) {
417
+ if (css[i] === '{')
418
+ depth++;
419
+ else if (css[i] === '}' && --depth === 0)
420
+ break;
421
+ }
422
+ i++;
423
+ }
424
+ else
425
+ i = semicolon < 0 ? css.length : semicolon + 1;
426
+ continue;
427
+ }
428
+ const open = css.indexOf('{', i);
429
+ if (open < 0)
430
+ break;
431
+ let close = css.indexOf('}', open);
432
+ if (close < 0)
433
+ close = css.length;
434
+ const declarations = readDeclarations(css.slice(open + 1, close)).filter(([name]) => PROPERTIES.has(name));
435
+ for (const raw of css.slice(i, open).split(',')) {
436
+ const selector = raw.trim();
437
+ const match = /^([a-zA-Z][\w-]*|\*)?((?:[.#][\w-]+)*)$/.exec(selector);
438
+ if (!selector || !match) {
439
+ if (selector)
440
+ warn(`CSS selector "${selector.slice(0, 40)}" is not supported (only type, class and id selectors)`);
441
+ continue;
442
+ }
443
+ const rule = { classes: [], specificity: 0, declarations };
444
+ if (match[1] && match[1] !== '*') {
445
+ rule.type = match[1];
446
+ rule.specificity += 1;
447
+ }
448
+ for (const [, kind, name] of match[2].matchAll(/([.#])([\w-]+)/g)) {
449
+ if (kind === '#') {
450
+ rule.id = name;
451
+ rule.specificity += 10000;
452
+ }
453
+ else {
454
+ rule.classes.push(name);
455
+ rule.specificity += 100;
456
+ }
457
+ }
458
+ rules.push(rule);
459
+ }
460
+ i = close + 1;
461
+ }
462
+ }
463
+ /** Splits commands into subpaths flattened to points; curves become `divisions` equal parameter steps. */
464
+ function flatten(commands, divisions) {
465
+ const out = [];
466
+ let points = [], closed = false, drawn = false, x = 0, y = 0, startX = 0, startY = 0;
467
+ const finish = () => {
468
+ if (drawn && points.length)
469
+ out.push({ points, closed });
470
+ points = [];
471
+ closed = drawn = false;
472
+ };
473
+ const add = (px, py) => {
474
+ const last = points[points.length - 1];
475
+ if (last[0] !== px || last[1] !== py)
476
+ points.push([px, py]);
477
+ x = px;
478
+ y = py;
479
+ drawn = true;
480
+ };
481
+ for (const c of commands) {
482
+ if (c[0] === 'M') {
483
+ finish();
484
+ x = startX = c[1];
485
+ y = startY = c[2];
486
+ points = [[x, y]];
487
+ continue;
488
+ }
489
+ // A drawing command right after Z starts a new subpath at the closed one's start.
490
+ if (!points.length)
491
+ points = [[x, y]];
492
+ if (c[0] === 'Z') {
493
+ closed = drawn = true;
494
+ finish();
495
+ x = startX;
496
+ y = startY;
497
+ }
498
+ else if (c[0] === 'L')
499
+ add(c[1], c[2]);
500
+ else {
501
+ const x0 = x, y0 = y;
502
+ for (let i = 1; i <= divisions; i++) {
503
+ const t = i / divisions, u = 1 - t;
504
+ if (c[0] === 'Q')
505
+ add(u * u * x0 + 2 * u * t * c[1] + t * t * c[3], u * u * y0 + 2 * u * t * c[2] + t * t * c[4]);
506
+ else {
507
+ const b0 = u * u * u, b1 = 3 * u * u * t, b2 = 3 * u * t * t, b3 = t * t * t;
508
+ add(b0 * x0 + b1 * c[1] + b2 * c[3] + b3 * c[5], b0 * y0 + b1 * c[2] + b2 * c[4] + b3 * c[6]);
509
+ }
510
+ }
511
+ }
512
+ }
513
+ finish();
514
+ return out;
515
+ }
516
+ /**
517
+ * Stroke outline of one element's commands as triangles (x, y pairs, three per triangle) in local units. Segments
518
+ * are rectangles; at a turn the inner corners of both rectangles are cut back to the crossing of their inner edges,
519
+ * when both segments are long enough, so that segments and joins tile the stroke without overlap.
520
+ */
521
+ function strokeTriangles(commands, half, divisions, join, cap, miterLimit) {
522
+ const out = [];
523
+ const tri = (a, b, c) => out.push(a[0], a[1], b[0], b[1], c[0], c[1]);
524
+ const pieces = (angle) => Math.max(1, Math.ceil((Math.abs(angle) / HALF_PI) * divisions - 1e-9));
525
+ const fan = (c, from, sweep) => {
526
+ const n = pieces(sweep);
527
+ let previous = [c[0] + half * Math.cos(from), c[1] + half * Math.sin(from)];
528
+ for (let i = 1; i <= n; i++) {
529
+ const a = from + (sweep * i) / n;
530
+ const next = [c[0] + half * Math.cos(a), c[1] + half * Math.sin(a)];
531
+ tri(c, previous, next);
532
+ previous = next;
533
+ }
534
+ };
535
+ const along = (p, d, n, s, t) => [
536
+ p[0] + d[0] * t + n[0] * s,
537
+ p[1] + d[1] * t + n[1] * s,
538
+ ];
539
+ for (const { points, closed: z } of flatten(commands, divisions)) {
540
+ let closed = z;
541
+ const last = points[points.length - 1];
542
+ if (closed && points.length > 1 && last[0] === points[0][0] && last[1] === points[0][1])
543
+ points.pop();
544
+ if (points.length < 3)
545
+ closed = false;
546
+ const count = points.length;
547
+ if (count === 1) {
548
+ // Zero-length subpath: only its caps show (SVG 2, stroke-linecap).
549
+ const p = points[0];
550
+ if (cap === 'round')
551
+ fan(p, 0, 2 * Math.PI);
552
+ else if (cap === 'square') {
553
+ const [x, y] = p;
554
+ tri([x - half, y - half], [x + half, y - half], [x + half, y + half]);
555
+ tri([x - half, y - half], [x + half, y + half], [x - half, y + half]);
556
+ }
557
+ continue;
558
+ }
559
+ const segments = closed ? count : count - 1;
560
+ const dirs = [], normals = [], lengths = [];
561
+ for (let i = 0; i < segments; i++) {
562
+ const a = points[i], b = points[(i + 1) % count];
563
+ const dx = b[0] - a[0], dy = b[1] - a[1], len = Math.hypot(dx, dy);
564
+ dirs.push([dx / len, dy / len]);
565
+ normals.push([-dy / len, dx / len]);
566
+ lengths.push(len);
567
+ }
568
+ // Joins, on the outer side of every turn.
569
+ const turns = [];
570
+ for (let v = 0; v < count; v++) {
571
+ turns.push(null);
572
+ if (!closed && (v === 0 || v === count - 1))
573
+ continue;
574
+ const a = (v - 1 + segments) % segments, b = v;
575
+ const [dax, day] = dirs[a], [dbx, dby] = dirs[b];
576
+ const cross = dax * dby - day * dbx, dot = dax * dbx + day * dby;
577
+ if (Math.abs(cross) < 1e-12 && dot > 0)
578
+ continue;
579
+ const angle = Math.atan2(Math.abs(cross), dot), inner = cross > 0 ? 1 : -1, outer = -inner;
580
+ const p = points[v], na = normals[a], nb = normals[b];
581
+ const oa = along(p, dirs[a], na, outer * half, 0), ob = along(p, dirs[b], nb, outer * half, 0);
582
+ const turn = { inner };
583
+ const reach = half * Math.max(Math.sin(angle), Math.tan(angle / 2));
584
+ if (reach <= lengths[a] / 2 && reach <= lengths[b] / 2)
585
+ turn.trim = along(p, dirs[a], na, inner * half, -half * Math.tan(angle / 2));
586
+ turns[v] = turn;
587
+ if (join === 'round') {
588
+ // The sweep follows the turn; a full reversal sweeps through the forward direction.
589
+ fan(p, Math.atan2(oa[1] - p[1], oa[0] - p[0]), cross > 0 ? angle : -angle);
590
+ continue;
591
+ }
592
+ tri(p, oa, ob);
593
+ const cosHalf = Math.cos(angle / 2), bx = na[0] + nb[0], by = na[1] + nb[1], bl = Math.hypot(bx, by);
594
+ // Miter ratio 1 / sin(theta / 2) with theta the angle between the segments, which is pi minus the turn.
595
+ if (join === 'miter' && bl > 1e-9 && cosHalf > 1e-9 && 1 / cosHalf <= miterLimit) {
596
+ const reachTip = (outer * half) / cosHalf / bl;
597
+ tri(oa, [p[0] + bx * reachTip, p[1] + by * reachTip], ob);
598
+ }
599
+ }
600
+ // Segment bodies: convex polygons fanned from their first corner.
601
+ for (let i = 0; i < segments; i++) {
602
+ const p = points[i], q = points[(i + 1) % count], d = dirs[i], n = normals[i];
603
+ const polygon = [];
604
+ const end = turns[(i + 1) % count], start = turns[i];
605
+ if (!end?.trim)
606
+ polygon.push(along(q, d, n, -half, 0), along(q, d, n, half, 0));
607
+ else if (end.inner > 0)
608
+ polygon.push(along(q, d, n, -half, 0), q, end.trim);
609
+ else
610
+ polygon.push(end.trim, q, along(q, d, n, half, 0));
611
+ if (!start?.trim)
612
+ polygon.push(along(p, d, n, half, 0), along(p, d, n, -half, 0));
613
+ else if (start.inner > 0)
614
+ polygon.push(start.trim, p, along(p, d, n, -half, 0));
615
+ else
616
+ polygon.push(along(p, d, n, half, 0), p, start.trim);
617
+ for (let k = 1; k + 1 < polygon.length; k++)
618
+ tri(polygon[0], polygon[k], polygon[k + 1]);
619
+ }
620
+ if (closed || cap === 'butt')
621
+ continue;
622
+ // Caps beyond both ends of an open subpath.
623
+ for (const [p, d] of [
624
+ [points[0], [-dirs[0][0], -dirs[0][1]]],
625
+ [points[count - 1], dirs[segments - 1]],
626
+ ]) {
627
+ const n = [-d[1], d[0]];
628
+ if (cap === 'round')
629
+ fan(p, Math.atan2(n[1], n[0]), -Math.PI);
630
+ else {
631
+ const a = along(p, d, n, half, 0), b = along(p, d, n, -half, 0), c = along(p, d, n, -half, half), e = along(p, d, n, half, half);
632
+ tri(a, b, c);
633
+ tri(a, c, e);
634
+ }
635
+ }
636
+ }
637
+ return out;
638
+ }
639
+ class DrawnPath {
640
+ #local;
641
+ #matrix;
642
+ constructor(element, id, local, matrix) {
643
+ this.fill = null;
644
+ this.fillOpacity = 1;
645
+ this.fillRule = 'nonzero';
646
+ this.stroke = null;
647
+ this.strokeOpacity = 1;
648
+ this.strokeWidth = 1;
649
+ this.strokeLineJoin = 'miter';
650
+ this.strokeLineCap = 'butt';
651
+ this.strokeMiterLimit = 4;
652
+ this.element = element;
653
+ if (id !== undefined)
654
+ this.id = id;
655
+ this.#local = local;
656
+ this.#matrix = matrix;
657
+ const [a, b, c, d, e, f] = matrix;
658
+ this.commands = local.map((command) => {
659
+ const mapped = command.slice();
660
+ for (let i = 1; i < mapped.length; i += 2) {
661
+ const x = command[i], y = command[i + 1];
662
+ mapped[i] = a * x + c * y + e;
663
+ mapped[i + 1] = b * x + d * y + f;
664
+ }
665
+ return mapped;
666
+ });
667
+ }
668
+ toShapes(options = {}) {
669
+ return outlineShapes(this.commands, this.fillRule, options.flipY ? (x, y) => [x, -y] : undefined);
670
+ }
671
+ toStrokeGeometry(options = {}) {
672
+ const width = options.width ?? this.strokeWidth, divisions = options.divisions ?? 12;
673
+ if (!Number.isFinite(width) || width < 0)
674
+ throw new RangeError(`stroke width ${width} is invalid; pass a finite width of 0 or more`);
675
+ if (!Number.isInteger(divisions) || divisions < 1)
676
+ throw new RangeError(`stroke divisions ${divisions} is invalid; pass an integer of 1 or more`);
677
+ const local = width === 0
678
+ ? []
679
+ : strokeTriangles(this.#local, width / 2, divisions, this.strokeLineJoin, this.strokeLineCap, this.strokeMiterLimit);
680
+ const [a, b, c, d, e, f] = this.#matrix, flip = options.flipY ? -1 : 1;
681
+ const positions = [], uvs = [];
682
+ for (let i = 0; i < local.length; i += 6) {
683
+ const xy = [];
684
+ for (let k = i; k < i + 6; k += 2)
685
+ xy.push(a * local[k] + c * local[k + 1] + e, flip * (b * local[k] + d * local[k + 1] + f));
686
+ const twice = (xy[2] - xy[0]) * (xy[5] - xy[1]) - (xy[4] - xy[0]) * (xy[3] - xy[1]);
687
+ if (!(twice !== 0 && Number.isFinite(twice)))
688
+ continue;
689
+ const order = twice > 0 ? [0, 2, 4] : [0, 4, 2];
690
+ for (const k of order) {
691
+ positions.push(xy[k], xy[k + 1], 0);
692
+ uvs.push(xy[k], xy[k + 1]);
693
+ }
694
+ }
695
+ const vertices = positions.length / 3;
696
+ const normals = new Float32Array(vertices * 3);
697
+ for (let i = 2; i < normals.length; i += 3)
698
+ normals[i] = 1;
699
+ return geometryData(positions, normals, uvs, Array.from({ length: vertices }, (_, i) => i));
700
+ }
701
+ }
702
+ // ---------------------------------------------------------------------------------------------------------------
703
+ // Document walk
704
+ /** Elements never drawn where they stand; their subtrees are skipped silently. */
705
+ const NOT_RENDERED = new Set('defs symbol clipPath mask marker pattern linearGradient radialGradient style title desc metadata script filter foreignObject'.split(' '));
706
+ const SHAPES = new Set('path rect circle ellipse line polyline polygon'.split(' '));
707
+ /**
708
+ * Whether a fill, stroke or color value parses (SVG 2 section 13.2 paint, CSS Color 4): none, currentColor, a colour,
709
+ * a url() reference with an optional fallback, or inherit. `color` takes no none or references.
710
+ */
711
+ function validPaint(value, property) {
712
+ const text = value.trim().toLowerCase();
713
+ if (text === 'inherit' || text === 'currentcolor')
714
+ return true;
715
+ if (property === 'color')
716
+ return readColour(text) !== null;
717
+ if (text === 'none')
718
+ return true;
719
+ const reference = /^url\(\s*(['"]?)[^'")]*\1\s*\)\s*(.*)$/.exec(text);
720
+ if (reference) {
721
+ const fallback = reference[2];
722
+ return !fallback || fallback === 'none' || fallback === 'currentcolor' || readColour(fallback) !== null;
723
+ }
724
+ return readColour(text) !== null;
725
+ }
726
+ /** A computed style: the parent's inheritable values, overridden by the element's own declarations except `inherit`. */
727
+ function inherit(parent, declared) {
728
+ const style = Object.assign(Object.create(null), parent);
729
+ for (const property in declared)
730
+ if (property !== 'opacity' && property !== 'display' && declared[property] !== 'inherit')
731
+ style[property] = declared[property];
732
+ return style;
733
+ }
734
+ /**
735
+ * Reads an SVG document into drawn paths with their computed styles.
736
+ *
737
+ * Supported: `path`, `rect`, `circle`, `ellipse`, `line`, `polyline` and `polygon`, inside `g`, `a`, `switch` (only
738
+ * its first child whose conditions hold) and nested `svg` viewports, plus `use` of elements and `symbol`s.
739
+ * Transforms, presentation attributes, `<style>` rules with type, class and id selectors, and the `style` attribute
740
+ * are applied. {@link SVGPath.toShapes} gives filled shapes with holes from the fill rule, and
741
+ * {@link SVGPath.toStrokeGeometry} gives the stroke as triangles. Coordinates are root user units (the root viewBox
742
+ * is not applied), y down.
743
+ *
744
+ * Not drawn: text, images, clipping, masks, markers, filters and dashes; each is noted in `warnings`. Gradients are
745
+ * drawn as their average stop colour. Bad path data keeps everything before the error. Everything lenient adds a
746
+ * warning instead of throwing.
747
+ *
748
+ * @param input - SVG text, or its bytes (UTF-8, or UTF-16 with a byte order mark).
749
+ * @throws LoaderError `'syntax'` for malformed XML, `'header'` when there is no `<svg>` root, and `'limit'` when one
750
+ * path or the whole document has more than 4,000,000 commands.
751
+ */
752
+ export function parseSVG(input, options = {}) {
753
+ const text = typeof input === 'string' ? input : decodeXML(toBytes(input, F));
754
+ const root = readXMLTree(text, F, { external: options.external }).children.find((element) => localName(element.name) === 'svg');
755
+ if (!root)
756
+ throw new LoaderError(F, 'header', 'the document has no <svg> root element; pass an SVG file');
757
+ const paths = [], warnings = [], ids = new Map(), rules = [];
758
+ const warn = (text) => {
759
+ if (!warnings.includes(text))
760
+ warnings.push(text);
761
+ };
762
+ const byId = (href) => {
763
+ const target = href?.trim();
764
+ return target?.startsWith('#') ? ids.get(target.slice(1)) : undefined;
765
+ };
766
+ // Every id (the first one wins) and every <style> sheet, before drawing starts.
767
+ const index = (element) => {
768
+ const id = element.attributes.id;
769
+ if (id !== undefined && !ids.has(id))
770
+ ids.set(id, element);
771
+ if (localName(element.name) === 'style')
772
+ readStyleSheet(element.text, rules, warn);
773
+ for (const child of element.children)
774
+ index(child);
775
+ };
776
+ index(root);
777
+ // Increasing specificity; ties keep source order (Array.prototype.sort is stable).
778
+ rules.sort((p, q) => p.specificity - q.specificity);
779
+ const result = { paths, warnings };
780
+ const rootAttributes = root.attributes, box = numbers(rootAttributes.viewBox);
781
+ if (box.length === 4)
782
+ result.viewBox = box;
783
+ for (const side of ['width', 'height']) {
784
+ const size = readLength(rootAttributes[side], 100, Number.NaN);
785
+ if (Number.isFinite(size))
786
+ result[side] = size;
787
+ }
788
+ // Percentages refer to the root viewport everywhere, nested viewports included.
789
+ const refWidth = result.viewBox ? box[2] : (result.width ?? 100), refHeight = result.viewBox ? box[3] : (result.height ?? 100), refDiagonal = Math.hypot(refWidth, refHeight) / Math.SQRT2;
790
+ let total = 0;
791
+ /** Declared values of the used properties: presentation attributes, then style rules, then the style attribute. */
792
+ const declare = (element, name) => {
793
+ const attributes = element.attributes, out = Object.create(null);
794
+ // CSS Syntax 3 section 5.4.5 and SVG 2 section 6.7: a declaration whose value does not parse is dropped, so the
795
+ // cascade falls back to the one before it or to inheritance. The colour properties are checked here; the others
796
+ // already fall back to their initial value when unreadable.
797
+ const set = (property, value) => {
798
+ if ((property === 'fill' || property === 'stroke' || property === 'color') && !validPaint(value, property)) {
799
+ warn(`${property} "${value.slice(0, 40)}" is not a colour; the declaration is ignored`);
800
+ return;
801
+ }
802
+ out[property] = value;
803
+ };
804
+ for (const property of PROPERTIES)
805
+ if (attributes[property] !== undefined)
806
+ set(property, attributes[property].trim());
807
+ const classes = (attributes.class ?? '').split(/\s+/);
808
+ for (const rule of rules)
809
+ if ((rule.type === undefined || rule.type === name) &&
810
+ (rule.id === undefined || rule.id === attributes.id) &&
811
+ rule.classes.every((c) => classes.includes(c)))
812
+ for (const [property, value] of rule.declarations)
813
+ set(property, value);
814
+ const inline = readDeclarations(attributes.style ?? '');
815
+ for (const [property, value] of inline)
816
+ if (PROPERTIES.has(property))
817
+ set(property, value);
818
+ for (const property of UNAPPLIED) {
819
+ const value = attributes[property] ?? inline.find(([p]) => p === property)?.[1];
820
+ if (value !== undefined && value.trim() !== 'none')
821
+ warn(`${property} is not applied; <${name}> drawn without it`);
822
+ }
823
+ return out;
824
+ };
825
+ /** Resolves a fill or stroke value to a colour with alpha; null for none. */
826
+ const paint = (value, colour, kind) => {
827
+ if (value === 'none')
828
+ return null;
829
+ if (value.toLowerCase() === 'currentcolor')
830
+ return (colour && readColour(colour)) || [0, 0, 0, 1];
831
+ const reference = /^url\(\s*(['"]?)([^'")]*)\1\s*\)\s*(.*)$/i.exec(value);
832
+ if (!reference) {
833
+ const parsed = readColour(value);
834
+ if (!parsed)
835
+ warn(`${kind} "${value.slice(0, 40)}" is not a colour; drawn as none`);
836
+ return parsed;
837
+ }
838
+ const target = reference[2].trim();
839
+ let element = byId(target);
840
+ // Follow href links through gradients without stops to the one that has them.
841
+ for (let hop = 0; element && hop <= MAX_GRADIENT_HOPS; hop++) {
842
+ const stops = element.children.filter((child) => localName(child.name) === 'stop');
843
+ if (stops.length) {
844
+ const sum = [0, 0, 0, 0];
845
+ for (const stop of stops) {
846
+ const inline = new Map(readDeclarations(stop.attributes.style ?? ''));
847
+ const rgba = readColour(inline.get('stop-color') ?? stop.attributes['stop-color'] ?? 'black') ?? [0, 0, 0, 1];
848
+ rgba[3] *= readOpacity(inline.get('stop-opacity') ?? stop.attributes['stop-opacity']);
849
+ for (let k = 0; k < 4; k++)
850
+ sum[k] += rgba[k] / stops.length;
851
+ }
852
+ warn(`gradient ${target} is drawn as its average stop colour`);
853
+ return sum;
854
+ }
855
+ element = byId(element.attributes.href ?? element.attributes['xlink:href']);
856
+ }
857
+ warn(`${kind} url(${target}) is not a gradient with stops; its fallback is used`);
858
+ return reference[3] ? paint(reference[3].trim(), colour, kind) : null;
859
+ };
860
+ /** The viewBox-to-viewport mapping of a nested svg or a symbol (SVG 1.1 section 7.8), after translate(x, y). */
861
+ const viewport = (element, symbol, size) => {
862
+ const a = element.attributes;
863
+ const x = symbol ? 0 : readLength(a.x, refWidth, 0), y = symbol ? 0 : readLength(a.y, refHeight, 0);
864
+ const vb = numbers(a.viewBox);
865
+ if (vb.length !== 4 || !(vb[2] > 0) || !(vb[3] > 0))
866
+ return shift(x, y);
867
+ // SVG 2 sections 5.6 and 8.2: an absent (auto) width or height of a nested svg or a symbol is 100%.
868
+ const width = readLength(size?.width ?? a.width, refWidth, refWidth), height = readLength(size?.height ?? a.height, refHeight, refHeight);
869
+ const words = (a.preserveAspectRatio ?? '').trim().split(/\s+/);
870
+ if (words[0] === 'defer')
871
+ words.shift();
872
+ const align = words[0] || 'xMidYMid';
873
+ let sx = width / vb[2], sy = height / vb[3], tx = x, ty = y;
874
+ if (align !== 'none') {
875
+ sx = sy = words[1] === 'slice' ? Math.max(sx, sy) : Math.min(sx, sy);
876
+ const spareX = width - vb[2] * sx, spareY = height - vb[3] * sy;
877
+ tx += align.startsWith('xMin') ? 0 : align.startsWith('xMax') ? spareX : spareX / 2;
878
+ ty += align.endsWith('YMin') ? 0 : align.endsWith('YMax') ? spareY : spareY / 2;
879
+ }
880
+ return [sx, 0, 0, sy, tx - vb[0] * sx, ty - vb[1] * sy];
881
+ };
882
+ /** A basic shape's outline in its own coordinates (SVG 1.1 chapter 9). */
883
+ const outline = (a, name) => {
884
+ if (name === 'path')
885
+ return readPathData(a.d ?? '', warn);
886
+ const out = [];
887
+ const length = (key, reference) => readLength(a[key], reference, 0);
888
+ const arc = (x0, y0, rx, ry, x1, y1) => appendArc(out, x0, y0, rx, ry, 0, false, true, x1, y1);
889
+ if (name === 'rect') {
890
+ const x = length('x', refWidth), y = length('y', refHeight), width = length('width', refWidth), height = length('height', refHeight);
891
+ if (!(width > 0 && height > 0))
892
+ return out;
893
+ let rx = a.rx === undefined ? undefined : length('rx', refWidth), ry = a.ry === undefined ? undefined : length('ry', refHeight);
894
+ rx ??= ry ?? 0;
895
+ ry ??= rx;
896
+ rx = Math.min(Math.max(rx, 0), width / 2);
897
+ ry = Math.min(Math.max(ry, 0), height / 2);
898
+ const right = x + width, bottom = y + height;
899
+ if (rx === 0 || ry === 0)
900
+ out.push(['M', x, y], ['L', right, y], ['L', right, bottom], ['L', x, bottom]);
901
+ else {
902
+ // Clockwise on screen from the end of the top-left corner, one quarter arc per corner.
903
+ out.push(['M', x + rx, y], ['L', right - rx, y]);
904
+ arc(right - rx, y, rx, ry, right, y + ry);
905
+ out.push(['L', right, bottom - ry]);
906
+ arc(right, bottom - ry, rx, ry, right - rx, bottom);
907
+ out.push(['L', x + rx, bottom]);
908
+ arc(x + rx, bottom, rx, ry, x, bottom - ry);
909
+ out.push(['L', x, y + ry]);
910
+ arc(x, y + ry, rx, ry, x + rx, y);
911
+ }
912
+ out.push(['Z']);
913
+ }
914
+ else if (name === 'circle' || name === 'ellipse') {
915
+ const cx = length('cx', refWidth), cy = length('cy', refHeight), rx = name === 'circle' ? length('r', refDiagonal) : length('rx', refWidth), ry = name === 'circle' ? rx : length('ry', refHeight);
916
+ if (rx > 0 && ry > 0) {
917
+ out.push(['M', cx + rx, cy]);
918
+ arc(cx + rx, cy, rx, ry, cx - rx, cy);
919
+ arc(cx - rx, cy, rx, ry, cx + rx, cy);
920
+ out.push(['Z']);
921
+ }
922
+ }
923
+ else if (name === 'line')
924
+ out.push(['M', length('x1', refWidth), length('y1', refHeight)], ['L', length('x2', refWidth), length('y2', refHeight)]);
925
+ else {
926
+ const values = numbers(a.points);
927
+ if (values.length % 2)
928
+ warn(`${name} points have an odd count; the last number is ignored`);
929
+ for (let i = 0; i + 1 < values.length; i += 2)
930
+ out.push([i ? 'L' : 'M', values[i], values[i + 1]]);
931
+ if (out.length && name === 'polygon')
932
+ out.push(['Z']);
933
+ }
934
+ return out;
935
+ };
936
+ /** Draws `element` and its subtree. `chain` lists the `<use>` targets that led here; `useSize` marks a use target. */
937
+ const visit = (element, parent, matrix, opacity, chain, useSize) => {
938
+ const name = localName(element.name);
939
+ const symbol = name === 'symbol' && useSize !== undefined;
940
+ if (NOT_RENDERED.has(name) && !symbol)
941
+ return;
942
+ if (name === 'text' || name === 'image')
943
+ return warn(name === 'text'
944
+ ? '<text> is not drawn; convert text to paths first'
945
+ : '<image> is not drawn; raster images are not supported');
946
+ const container = name === 'g' || name === 'a' || name === 'switch' || name === 'svg' || symbol;
947
+ if (!container && name !== 'use' && !SHAPES.has(name))
948
+ return warn(`<${name}> is not a drawable element; skipped`);
949
+ const declared = declare(element, name);
950
+ if (declared.display === 'none')
951
+ return;
952
+ const style = inherit(parent, declared), a = element.attributes;
953
+ opacity *= readOpacity(declared.opacity);
954
+ matrix = compose(matrix, readTransform(a.transform, warn));
955
+ if (name === 'use') {
956
+ const href = a.href ?? a['xlink:href'] ?? '', target = byId(href);
957
+ if (!target)
958
+ return warn(`<use> refers to "${href}", which is not an element of this document`);
959
+ if (chain.includes(target) || chain.length >= MAX_USE_DEPTH)
960
+ return warn(`<use> of ${href.trim()} refers to itself or nests deeper than ${MAX_USE_DEPTH}; skipped`);
961
+ const size = Object.create(null);
962
+ if (a.width !== undefined)
963
+ size.width = a.width;
964
+ if (a.height !== undefined)
965
+ size.height = a.height;
966
+ const offset = shift(readLength(a.x, refWidth, 0), readLength(a.y, refHeight, 0));
967
+ return visit(target, style, compose(matrix, offset), opacity, [...chain, target], size);
968
+ }
969
+ if (container) {
970
+ if (name === 'svg' || symbol)
971
+ matrix = compose(matrix, viewport(element, symbol, useSize));
972
+ // switch draws only its first direct child whose conditions hold (SVG 1.1 section 5.8). No extensions are
973
+ // supported, so a non-empty requiredExtensions fails; every other condition counts as true.
974
+ const children = name === 'switch'
975
+ ? element.children.filter((child) => !child.attributes.requiredExtensions?.trim()).slice(0, 1)
976
+ : element.children;
977
+ for (const child of children)
978
+ visit(child, style, matrix, opacity, chain);
979
+ return;
980
+ }
981
+ const local = outline(a, name);
982
+ if (!local.length || style.visibility === 'hidden' || style.visibility === 'collapse')
983
+ return;
984
+ total += local.length;
985
+ if (total > MAX_COMMANDS)
986
+ throw new LoaderError(F, 'limit', `the document draws more than ${MAX_COMMANDS} commands; simplify it`);
987
+ const path = new DrawnPath(name, a.id, local, matrix);
988
+ const fill = paint(style.fill ?? 'black', style.color, 'fill'), stroke = style.stroke === undefined ? null : paint(style.stroke, style.color, 'stroke');
989
+ path.fill = fill && [fill[0], fill[1], fill[2]];
990
+ path.fillOpacity = opacity * readOpacity(style['fill-opacity']) * (fill ? fill[3] : 1);
991
+ path.fillRule = style['fill-rule'] === 'evenodd' ? 'evenodd' : 'nonzero';
992
+ path.stroke = stroke && [stroke[0], stroke[1], stroke[2]];
993
+ path.strokeOpacity = opacity * readOpacity(style['stroke-opacity']) * (stroke ? stroke[3] : 1);
994
+ path.strokeWidth = Math.max(0, readLength(style['stroke-width'], refDiagonal, 1));
995
+ const join = style['stroke-linejoin'], cap = style['stroke-linecap'];
996
+ path.strokeLineJoin = join === 'round' || join === 'bevel' ? join : 'miter';
997
+ path.strokeLineCap = cap === 'round' || cap === 'square' ? cap : 'butt';
998
+ const limit = Number(style['stroke-miterlimit']?.trim() || Number.NaN);
999
+ path.strokeMiterLimit = limit >= 1 ? limit : 4;
1000
+ paths.push(path);
1001
+ };
1002
+ // The root's own viewport is not applied: drawing stays in its user units.
1003
+ const declared = declare(root, 'svg'), opacity = readOpacity(declared.opacity);
1004
+ for (const child of root.children)
1005
+ visit(child, inherit(Object.create(null), declared), IDENTITY, opacity, []);
1006
+ return result;
1007
+ }