@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
@@ -0,0 +1,92 @@
1
+ import { type ParseLimits } from './types.js';
2
+ import { type BinaryInput } from './util.js';
3
+ /** One layer of {@link GCode.layers}. Both arrays hold two xyz points per segment: `mode: 'segments'` of `Line`. */
4
+ export interface GCodeLayer {
5
+ /** The Z of the layer's extruding moves, in millimetres. */
6
+ z: number;
7
+ /** Moves that lay down material. */
8
+ extrusion: Float32Array;
9
+ /** Moves without material that lead into this layer. */
10
+ travel: Float32Array;
11
+ }
12
+ /** Options of {@link parseGCode}: the shared size limits and what P on G2 and G3 counts. */
13
+ export interface GCodeOptions extends ParseLimits {
14
+ /**
15
+ * What P on a G2 or G3 arc counts. `'turns'` (default, LinuxCNC): P is the number of turns, P1 the programmed arc
16
+ * alone, and each step above 1 adds a full circle. `'circles'` (Marlin with `ARC_P_CIRCLES`): P full circles are
17
+ * drawn on top of the programmed arc, so P0 is the arc alone and P1 is one circle more than LinuxCNC's P1.
18
+ */
19
+ arcP?: 'turns' | 'circles';
20
+ }
21
+ /** What {@link parseGCode} returns. Coordinates are the machine's, in millimetres, Z up. */
22
+ export interface GCode {
23
+ /** Layers by rising Z. */
24
+ layers: GCodeLayer[];
25
+ /** Net filament pushed in, the sum of every E move in millimetres, so a retraction and its recovery cancel. */
26
+ filament: number;
27
+ /** Bounds of every segment; zeros when there are none. */
28
+ min: [number, number, number];
29
+ max: [number, number, number];
30
+ /** Things the parser moved past without drawing, each listed once. Empty today: every move it reads is drawn. */
31
+ warnings: string[];
32
+ }
33
+ /**
34
+ * Parses RepRap-flavoured G-code: G0 and G1 with X, Y, Z, E; G2 and G3 arcs by centre offsets (I, J, K) or radius (R),
35
+ * with full circles, turns (P, counted as `arcP` says) and helices, in the plane G17, G18 or G19 selects; G90.1 and
36
+ * G91.1 for absolute and incremental arc centres; G90, G91, M82 and M83 for absolute and relative axes; G92 to set a position; G20 and G21 for units; G28 to home. Other commands are skipped. An arc is
37
+ * drawn as chords within 0.002 mm of it, its E spread evenly along them. `maxVertices` counts two per segment.
38
+ *
39
+ * @param input The file's bytes or text.
40
+ * @param options The shared size limits and `arcP`.
41
+ * @returns The layers, filament use and bounds.
42
+ * @throws LoaderError with code `syntax` for a bad number, an arc without its centre or radius, or a G90.1 arc
43
+ * missing one of its plane's two centre words, `range` for an arc
44
+ * whose end is off its circle (past LinuxCNC's tolerance) or whose radius is shorter than half its chord, and `limit`
45
+ * past `maxVertices`.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * import { parseGCode } from '@margoengine/loaders/gcode';
50
+ *
51
+ * const { layers, filament } = parseGCode('G1 Z0.2\nG1 X10 E1\nG3 X0 Y10 I-10 E2\n');
52
+ * console.log(layers[0].z, layers[0].extrusion.length, filament);
53
+ * ```
54
+ */
55
+ export declare function parseGCode(input: BinaryInput | string, options?: GCodeOptions): GCode;
56
+ /** Options of {@link toolpathBeads}. */
57
+ export interface ToolpathBeadOptions {
58
+ /** Bead width across the path, in the segments' units. Default 0.45 (a 0.4 mm nozzle's usual line). */
59
+ width?: number;
60
+ /** Bead height, the layer height; the bead's top is at the segment's Z. Default 0.2. Clamped to `width`. */
61
+ height?: number;
62
+ /** Chords on each rounded side of the bead, 1 to 16. Default 3. */
63
+ round?: number;
64
+ }
65
+ /** A triangle mesh in the segments' frame (Z up), ready for `new Geometry(positions, normals, indices)`. */
66
+ export interface ToolpathBeadMesh {
67
+ positions: Float32Array;
68
+ normals: Float32Array;
69
+ indices: Uint32Array;
70
+ }
71
+ /**
72
+ * Solid beads along toolpath segments, as a slicer preview draws them: each segment of a {@link GCodeLayer}'s
73
+ * `extrusion` (or `travel`) becomes a prism of the stadium section that extruded filament takes, a rectangle with
74
+ * half-round sides (Comminal, Serdeczny, Pedersen and Spangenberg, "Numerical modeling of the strand deposition flow
75
+ * in extrusion-based additive manufacturing", Additive Manufacturing 20, 68-76, 2018,
76
+ * https://doi.org/10.1016/j.addma.2017.12.013; the same rounded-rectangle area Slic3r's flow math uses), `width`
77
+ * across and `height` tall with its top on the nozzle path, closed at both ends. Segments are two xyz points each, Z
78
+ * up; vertical and zero-length segments draw nothing.
79
+ *
80
+ * @throws RangeError for a segment array whose length is not a multiple of 6, a non-positive width or height, or
81
+ * `round` outside 1..16.
82
+ *
83
+ * @example
84
+ * ```ts
85
+ * import { parseGCode, toolpathBeads } from '@margoengine/loaders/gcode';
86
+ *
87
+ * const { layers } = parseGCode('G1 Z0.2\nG1 X10 E1\nG1 Y10 E2\n');
88
+ * const bead = toolpathBeads(layers[0].extrusion, { width: 0.45, height: 0.2 });
89
+ * console.log(bead.positions.length / 3, bead.indices.length / 3);
90
+ * ```
91
+ */
92
+ export declare function toolpathBeads(segments: ArrayLike<number>, options?: ToolpathBeadOptions): ToolpathBeadMesh;
package/dist/gcode.js ADDED
@@ -0,0 +1,369 @@
1
+ // RepRap G-code toolpaths: G0 and G1 moves and G2 and G3 arcs with E, grouped by Z into layers of line segments.
2
+ //
3
+ // Arcs follow the RepRap G-code wiki (G2 and G3, G17 to G19) and the LinuxCNC G-code reference (5. G2, G3 Arc Move):
4
+ // I, J and K are the centre's offset from the start in the selected plane, R a radius whose sign picks the arc under
5
+ // 180 degrees (positive) or over it (negative), an arc that ends where it starts is a full circle, P counts turns, and
6
+ // the axis normal to the plane moves linearly (a helix). G2 turns clockwise seen from the positive end of that axis.
7
+ // G90.1 makes I, J and K the centre itself and G91.1 (the default) an offset again (LinuxCNC G-code reference). Marlin's
8
+ // G2 and G3 page (marlinfw.org/docs/gcode/G002-G003.html) gives P as complete circles, read with arcP: 'circles'.
9
+ import { LoaderError } from './types.js';
10
+ import { floats, limits, toText } from './util.js';
11
+ const F = 'G-code';
12
+ /** Largest gap between an arc and its chords, in millimetres; a turn takes at least 16 chords. */
13
+ const ARC_TOLERANCE = 0.002;
14
+ /**
15
+ * Parses RepRap-flavoured G-code: G0 and G1 with X, Y, Z, E; G2 and G3 arcs by centre offsets (I, J, K) or radius (R),
16
+ * with full circles, turns (P, counted as `arcP` says) and helices, in the plane G17, G18 or G19 selects; G90.1 and
17
+ * G91.1 for absolute and incremental arc centres; G90, G91, M82 and M83 for absolute and relative axes; G92 to set a position; G20 and G21 for units; G28 to home. Other commands are skipped. An arc is
18
+ * drawn as chords within 0.002 mm of it, its E spread evenly along them. `maxVertices` counts two per segment.
19
+ *
20
+ * @param input The file's bytes or text.
21
+ * @param options The shared size limits and `arcP`.
22
+ * @returns The layers, filament use and bounds.
23
+ * @throws LoaderError with code `syntax` for a bad number, an arc without its centre or radius, or a G90.1 arc
24
+ * missing one of its plane's two centre words, `range` for an arc
25
+ * whose end is off its circle (past LinuxCNC's tolerance) or whose radius is shorter than half its chord, and `limit`
26
+ * past `maxVertices`.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * import { parseGCode } from '@margoengine/loaders/gcode';
31
+ *
32
+ * const { layers, filament } = parseGCode('G1 Z0.2\nG1 X10 E1\nG3 X0 Y10 I-10 E2\n');
33
+ * console.log(layers[0].z, layers[0].extrusion.length, filament);
34
+ * ```
35
+ */
36
+ export function parseGCode(input, options = {}) {
37
+ const text = toText(input, F), { maxVertices } = limits(options, F), circles = options.arcP === 'circles';
38
+ if (options.arcP !== undefined && options.arcP !== 'turns' && !circles)
39
+ throw new LoaderError(F, 'range', `arcP must be 'turns' or 'circles', not ${String(options.arcP).slice(0, 40)}`);
40
+ const byZ = new Map(), warnings = [], position = [0, 0, 0, 0], min = [Infinity, Infinity, Infinity], max = [-Infinity, -Infinity, -Infinity];
41
+ let pending = floats(), relative = false, relativeE = false,
42
+ // G90.1: I, J and K are the centre itself; G91.1 (the default): its offset from the start.
43
+ absoluteCentre = false, unit = 1, filament = 0, vertices = 0, current,
44
+ // The arc plane's first and second axes and its normal: G17 X Y (Z), G18 Z X (Y), G19 Y Z (X).
45
+ plane = [0, 1, 2], lineNumber = 0;
46
+ const axes = 'XYZE';
47
+ // No exponents: G-code has none, and in G1X1E2 the E is the extruder.
48
+ const word = /([A-Za-z])\s*([+-]?(?:\d+\.?\d*|\.\d+))?/g;
49
+ /** Where a move's words take the tool: each axis absolute or relative by its mode. */
50
+ const target = (words) => position.map((at, a) => {
51
+ const value = words[a];
52
+ return value === undefined ? at : (a === 3 ? relativeE : relative) ? at + value : value;
53
+ });
54
+ /** One straight move, extruding when E rises along it. */
55
+ const segment = (from, to) => {
56
+ const pushed = to[3] - from[3];
57
+ filament += pushed; // A retraction takes back what its recovery pushes again.
58
+ if (to[0] === from[0] && to[1] === from[1] && to[2] === from[2])
59
+ return;
60
+ if ((vertices += 2) > maxVertices)
61
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
62
+ for (let a = 0; a < 3; a++) {
63
+ min[a] = Math.min(min[a], from[a], to[a]);
64
+ max[a] = Math.max(max[a], from[a], to[a]);
65
+ }
66
+ const extruding = pushed > 0;
67
+ if (extruding) {
68
+ current = byZ.get(to[2]);
69
+ if (!current)
70
+ byZ.set(to[2], (current = makeLayer(to[2])));
71
+ // Travel seen since the last extrusion leads into this layer.
72
+ current.travel.reserve(pending.length);
73
+ current.travel.array.set(pending.array.subarray(0, pending.length), current.travel.length);
74
+ current.travel.length += pending.length;
75
+ pending = floats();
76
+ }
77
+ const into = extruding && current ? current.extrusion : pending;
78
+ into.reserve(6);
79
+ into.array.set([from[0], from[1], from[2], to[0], to[1], to[2]], into.length);
80
+ into.length += 6;
81
+ };
82
+ /** G2 (clockwise) or G3 as chords; `words` holds I, J, K, R and P. */
83
+ const arc = (ccw, to, words) => {
84
+ const from = position.slice(), [u, v, w] = plane, radius = words[3],
85
+ // Both readings become the number of whole turns past the first.
86
+ p = words[4] ?? (circles ? 0 : 1), extra = circles ? p : p - 1, su = from[u], sv = from[v], eu = to[u], ev = to[v];
87
+ if (!Number.isInteger(p) || extra < 0)
88
+ throw new LoaderError(F, 'syntax', circles
89
+ ? `P must be a whole number of circles, 0 or more, on line ${lineNumber}`
90
+ : `P must be a whole number of turns on line ${lineNumber}`);
91
+ let cu, cv;
92
+ if (radius !== undefined) {
93
+ // Radius form: the centre is on the chord's bisector, left of the chord for a short G3 or a long G2.
94
+ const chord = Math.hypot(eu - su, ev - sv), r = Math.abs(radius);
95
+ if (!chord)
96
+ throw new LoaderError(F, 'syntax', `an R arc must end away from its start on line ${lineNumber}`);
97
+ if (r < chord / 2 - Math.max(0.005, 1e-3 * r))
98
+ throw new LoaderError(F, 'range', `radius ${r} is shorter than half its chord on line ${lineNumber}`);
99
+ const rise = Math.sqrt(Math.max(0, r * r - (chord * chord) / 4)) / chord, side = (ccw ? 1 : -1) * (radius < 0 ? -1 : 1);
100
+ cu = (su + eu) / 2 - side * rise * (ev - sv);
101
+ cv = (sv + ev) / 2 + side * rise * (eu - su);
102
+ }
103
+ else {
104
+ // The offsets in the plane's own order: I J for G17, K I for G18, J K for G19 (words are I, J, K).
105
+ const du = words[u], dv = words[v];
106
+ if (absoluteCentre) {
107
+ // LinuxCNC: with G90.1 both of the plane's centre words must be given.
108
+ if (du === undefined || dv === undefined)
109
+ throw new LoaderError(F, 'syntax', `a G90.1 arc needs both centre words of its plane or R on line ${lineNumber}`);
110
+ cu = du;
111
+ cv = dv;
112
+ }
113
+ else {
114
+ if (du === undefined && dv === undefined)
115
+ throw new LoaderError(F, 'syntax', `an arc needs centre offsets in its plane or R on line ${lineNumber}`);
116
+ cu = su + (du ?? 0);
117
+ cv = sv + (dv ?? 0);
118
+ }
119
+ }
120
+ const r0 = Math.hypot(su - cu, sv - cv), r1 = Math.hypot(eu - cu, ev - cv), off = Math.abs(r1 - r0);
121
+ // LinuxCNC: the end may miss the circle by at most 0.5 mm, and by at most 0.005 mm or 0.1% of the radius.
122
+ if (off > 0.5 || (off > 0.005 && off > 1e-3 * r0))
123
+ throw new LoaderError(F, 'range', `the arc's end is ${off} mm off its circle on line ${lineNumber}`);
124
+ const a0 = Math.atan2(sv - cv, su - cu);
125
+ let sweep = eu === su && ev === sv ? 0 : Math.atan2(ev - cv, eu - cu) - a0;
126
+ // Turn the long way round to keep the direction; an arc that ends where it starts is a full circle.
127
+ if (ccw ? sweep <= 0 : sweep >= 0)
128
+ sweep += ccw ? 2 * Math.PI : -2 * Math.PI;
129
+ sweep += (ccw ? 2 : -2) * Math.PI * extra;
130
+ const step = r0 > ARC_TOLERANCE ? 2 * Math.acos(1 - ARC_TOLERANCE / r0) : Math.PI, chords = Math.max(1, Math.ceil(Math.abs(sweep) / Math.min(step, Math.PI / 8)));
131
+ if (vertices + chords * 2 > maxVertices)
132
+ throw new LoaderError(F, 'limit', `vertex count exceeds the limit of ${maxVertices}`);
133
+ let last = from;
134
+ for (let c = 1; c <= chords; c++) {
135
+ const t = c / chords, point = to.slice();
136
+ if (c < chords) {
137
+ const angle = a0 + sweep * t, r = r0 + (r1 - r0) * t;
138
+ point[u] = cu + r * Math.cos(angle);
139
+ point[v] = cv + r * Math.sin(angle);
140
+ point[w] = from[w] + (to[w] - from[w]) * t;
141
+ point[3] = from[3] + (to[3] - from[3]) * t;
142
+ }
143
+ segment(last, point);
144
+ last = point;
145
+ }
146
+ };
147
+ for (let start = 0; start < text.length;) {
148
+ let end = text.indexOf('\n', start);
149
+ if (end < 0)
150
+ end = text.length;
151
+ const line = text.slice(start, end).replace(/\(.*?\)/g, '');
152
+ start = end + 1;
153
+ lineNumber++;
154
+ const semicolon = line.indexOf(';');
155
+ let body = semicolon >= 0 ? line.slice(0, semicolon) : line;
156
+ const star = body.indexOf('*');
157
+ if (star >= 0)
158
+ body = body.slice(0, star);
159
+ let command = '';
160
+ const values = [undefined, undefined, undefined, undefined],
161
+ // I, J, K, R and P of an arc.
162
+ arcWords = [undefined, undefined, undefined, undefined, undefined];
163
+ word.lastIndex = 0;
164
+ for (let match = word.exec(body); match; match = word.exec(body)) {
165
+ const letter = match[1].toUpperCase();
166
+ if (letter === 'N' && !command)
167
+ continue;
168
+ if (!command) {
169
+ if (match[2] === undefined)
170
+ throw new LoaderError(F, 'syntax', `command without a number on line ${lineNumber}`);
171
+ command = letter + Number(match[2]);
172
+ continue;
173
+ }
174
+ const axis = axes.indexOf(letter);
175
+ if (axis < 0) {
176
+ const at = 'IJKRP'.indexOf(letter);
177
+ if (at < 0 || (command !== 'G2' && command !== 'G3'))
178
+ continue;
179
+ if (match[2] === undefined)
180
+ throw new LoaderError(F, 'syntax', `${letter} has no number on line ${lineNumber}`);
181
+ arcWords[at] = Number(match[2]) * (letter === 'P' ? 1 : unit);
182
+ continue;
183
+ }
184
+ if (match[2] === undefined) {
185
+ if (command === 'G28')
186
+ values[axis] = 0;
187
+ else if (command !== 'G92')
188
+ throw new LoaderError(F, 'syntax', `${letter} has no number on line ${lineNumber}`);
189
+ else
190
+ values[axis] = 0;
191
+ }
192
+ else
193
+ values[axis] = Number(match[2]) * unit;
194
+ }
195
+ switch (command) {
196
+ case 'G90':
197
+ relative = relativeE = false;
198
+ break;
199
+ case 'G91':
200
+ relative = relativeE = true;
201
+ break;
202
+ case 'G90.1':
203
+ absoluteCentre = true;
204
+ break;
205
+ case 'G91.1':
206
+ absoluteCentre = false;
207
+ break;
208
+ case 'M82':
209
+ relativeE = false;
210
+ break;
211
+ case 'M83':
212
+ relativeE = true;
213
+ break;
214
+ case 'G20':
215
+ unit = 25.4;
216
+ break;
217
+ case 'G21':
218
+ unit = 1;
219
+ break;
220
+ case 'G17':
221
+ plane = [0, 1, 2];
222
+ break;
223
+ case 'G18':
224
+ plane = [2, 0, 1];
225
+ break;
226
+ case 'G19':
227
+ plane = [1, 2, 0];
228
+ break;
229
+ case 'G92':
230
+ for (let a = 0; a < 4; a++)
231
+ position[a] = values[a] ?? (values.every((v) => v === undefined) ? 0 : position[a]);
232
+ break;
233
+ case 'G28':
234
+ for (let a = 0; a < 3; a++)
235
+ if (values[a] !== undefined || values.every((v) => v === undefined))
236
+ position[a] = 0;
237
+ break;
238
+ case 'G2':
239
+ case 'G3': {
240
+ const to = target(values);
241
+ arc(command === 'G3', to, arcWords);
242
+ position.splice(0, 4, ...to);
243
+ break;
244
+ }
245
+ case 'G0':
246
+ case 'G1': {
247
+ const from = position.slice();
248
+ position.splice(0, 4, ...target(values));
249
+ segment(from, position);
250
+ break;
251
+ }
252
+ default:
253
+ }
254
+ }
255
+ if (pending.length) {
256
+ const last = current ?? makeLayer(position[2]);
257
+ if (!current)
258
+ byZ.set(position[2], last);
259
+ last.travel.reserve(pending.length);
260
+ last.travel.array.set(pending.array.subarray(0, pending.length), last.travel.length);
261
+ last.travel.length += pending.length;
262
+ }
263
+ const layers = [...byZ.values()]
264
+ .sort((a, b) => a.z - b.z)
265
+ .map((layer) => ({
266
+ z: layer.z,
267
+ extrusion: layer.extrusion.array.slice(0, layer.extrusion.length),
268
+ travel: layer.travel.array.slice(0, layer.travel.length),
269
+ }));
270
+ if (!vertices) {
271
+ min.fill(0);
272
+ max.fill(0);
273
+ }
274
+ return { layers, filament, min, max, warnings };
275
+ }
276
+ function makeLayer(z) {
277
+ return { z, extrusion: floats(), travel: floats() };
278
+ }
279
+ /**
280
+ * Solid beads along toolpath segments, as a slicer preview draws them: each segment of a {@link GCodeLayer}'s
281
+ * `extrusion` (or `travel`) becomes a prism of the stadium section that extruded filament takes, a rectangle with
282
+ * half-round sides (Comminal, Serdeczny, Pedersen and Spangenberg, "Numerical modeling of the strand deposition flow
283
+ * in extrusion-based additive manufacturing", Additive Manufacturing 20, 68-76, 2018,
284
+ * https://doi.org/10.1016/j.addma.2017.12.013; the same rounded-rectangle area Slic3r's flow math uses), `width`
285
+ * across and `height` tall with its top on the nozzle path, closed at both ends. Segments are two xyz points each, Z
286
+ * up; vertical and zero-length segments draw nothing.
287
+ *
288
+ * @throws RangeError for a segment array whose length is not a multiple of 6, a non-positive width or height, or
289
+ * `round` outside 1..16.
290
+ *
291
+ * @example
292
+ * ```ts
293
+ * import { parseGCode, toolpathBeads } from '@margoengine/loaders/gcode';
294
+ *
295
+ * const { layers } = parseGCode('G1 Z0.2\nG1 X10 E1\nG1 Y10 E2\n');
296
+ * const bead = toolpathBeads(layers[0].extrusion, { width: 0.45, height: 0.2 });
297
+ * console.log(bead.positions.length / 3, bead.indices.length / 3);
298
+ * ```
299
+ */
300
+ export function toolpathBeads(segments, options = {}) {
301
+ const width = options.width ?? 0.45, round = options.round ?? 3;
302
+ if (!(width > 0) ||
303
+ !Number.isFinite(width) ||
304
+ !(options.height === undefined || (options.height > 0 && Number.isFinite(options.height))))
305
+ throw new RangeError('Invalid bead size; pass a positive finite width and height');
306
+ if (!Number.isInteger(round) || round < 1 || round > 16)
307
+ throw new RangeError('Invalid bead round; pass an integer 1 to 16');
308
+ if (segments.length % 6)
309
+ throw new RangeError('Invalid toolpath segments; pass two xyz points per segment');
310
+ const height = Math.min(options.height ?? 0.2, width), r = height / 2, flat = width / 2 - r;
311
+ // The section ring in (across, up) with its normals: the right half-round top to bottom, then the left one bottom
312
+ // to top; the flats between them join points whose normals already agree.
313
+ const ring = [];
314
+ for (let i = 0; i <= round; i++) {
315
+ const a = Math.PI / 2 - (i * Math.PI) / round;
316
+ ring.push([flat + r * Math.cos(a), r * Math.sin(a), Math.cos(a), Math.sin(a)]);
317
+ }
318
+ for (let i = 0; i <= round; i++) {
319
+ const a = -Math.PI / 2 - (i * Math.PI) / round;
320
+ ring.push([-flat + r * Math.cos(a), r * Math.sin(a), Math.cos(a), Math.sin(a)]);
321
+ }
322
+ const n = ring.length, perSegment = 2 * n + 2 * n, count = segments.length / 6;
323
+ const positions = new Float32Array(count * perSegment * 3), normals = new Float32Array(count * perSegment * 3), indices = new Uint32Array(count * (2 * n * 3 + 2 * (n - 2) * 3));
324
+ let v = 0, t = 0;
325
+ const put = (x, y, z, nx, ny, nz) => {
326
+ positions[v * 3] = x;
327
+ positions[v * 3 + 1] = y;
328
+ positions[v * 3 + 2] = z;
329
+ normals[v * 3] = nx;
330
+ normals[v * 3 + 1] = ny;
331
+ normals[v * 3 + 2] = nz;
332
+ return v++;
333
+ };
334
+ for (let s = 0; s < segments.length; s += 6) {
335
+ const ax = segments[s], ay = segments[s + 1], az = segments[s + 2];
336
+ const bx = segments[s + 3], by = segments[s + 4], bz = segments[s + 5];
337
+ const dx = bx - ax, dy = by - ay, length = Math.hypot(dx, dy);
338
+ if (!(length > 1e-9 * Math.max(1, width)))
339
+ continue;
340
+ // Across the path (the direction times -Z, so the right side is on the right of travel), up is +Z.
341
+ const ux = dx / length, uy = dy / length, sx = uy, sy = -ux;
342
+ const first = v;
343
+ for (const [px, py, pz] of [
344
+ [ax, ay, az],
345
+ [bx, by, bz],
346
+ ])
347
+ for (const [across, up, na, nu] of ring)
348
+ put(px + sx * across, py + sy * across, pz - r + up, sx * na, sy * na, nu);
349
+ for (let i = 0; i < n; i++) {
350
+ const a0 = first + i, a1 = first + ((i + 1) % n), b0 = a0 + n, b1 = a1 + n;
351
+ indices.set([a0, a1, b0, a1, b1, b0], t);
352
+ t += 6;
353
+ }
354
+ // Flat caps facing back along and forward along the path, as fans over the convex section.
355
+ for (const [end, px, py, pz, sign] of [
356
+ [0, ax, ay, az, -1],
357
+ [1, bx, by, bz, 1],
358
+ ]) {
359
+ const cap = v;
360
+ for (const [across, up] of ring)
361
+ put(px + sx * across, py + sy * across, pz - r + up, ux * sign, uy * sign, 0);
362
+ for (let i = 1; i < n - 1; i++) {
363
+ indices.set(end ? [cap, cap + i, cap + i + 1] : [cap, cap + i + 1, cap + i], t);
364
+ t += 3;
365
+ }
366
+ }
367
+ }
368
+ return { positions: positions.slice(0, v * 3), normals: normals.slice(0, v * 3), indices: indices.slice(0, t) };
369
+ }
@@ -0,0 +1,84 @@
1
+ import { type LoadedGeometry, type ParseLimits } from './types.js';
2
+ import type { XMLExternalOptions } from './xml.js';
3
+ /** A source coordinate; z is optional and extra ordinates remain in source geometry. */
4
+ export type GeoPosition = number[];
5
+ /** GeoJSON-compatible geometry shared by every vector reader. */
6
+ export type GeoGeometry = {
7
+ type: 'Point';
8
+ coordinates: GeoPosition;
9
+ } | {
10
+ type: 'MultiPoint' | 'LineString';
11
+ coordinates: GeoPosition[];
12
+ } | {
13
+ type: 'MultiLineString' | 'Polygon';
14
+ coordinates: GeoPosition[][];
15
+ } | {
16
+ type: 'MultiPolygon';
17
+ coordinates: GeoPosition[][][];
18
+ } | {
19
+ type: 'GeometryCollection';
20
+ geometries: GeoGeometry[];
21
+ };
22
+ /** One source feature and its attributes. */
23
+ export interface GeoFeature {
24
+ type: 'Feature';
25
+ id?: string | number;
26
+ properties: Record<string, unknown> | null;
27
+ geometry: GeoGeometry | null;
28
+ /** MVT source layer name, if present. */
29
+ layer?: string;
30
+ /** MVT layer extent, if present. */
31
+ extent?: number;
32
+ }
33
+ /** Parse and tessellation bounds for vector data. */
34
+ export interface GeoOptions extends ParseLimits, XMLExternalOptions {
35
+ /** Maximum source features. Default 100,000. */
36
+ maxFeatures?: number;
37
+ /** Maximum input bytes. Default 256 MiB. */
38
+ maxBytes?: number;
39
+ /** Geometry collection nesting limit. Default 64. */
40
+ maxDepth?: number;
41
+ /** Cancellation checked at feature and primitive boundaries. */
42
+ signal?: AbortSignal;
43
+ }
44
+ /** One polygon: index rings, with outer ring first and holes following. */
45
+ export interface GeoPolygon {
46
+ feature: number;
47
+ rings: Uint32Array[];
48
+ }
49
+ /** Mixed vector primitives with source precision and renderable triangles. */
50
+ export interface GeoResult {
51
+ features: GeoFeature[];
52
+ /** Owned xyz coordinates in source units, retaining double precision. */
53
+ positions: Float64Array;
54
+ /** Explicit point indices. */
55
+ points: Uint32Array;
56
+ /** Source feature per point. */
57
+ pointFeatures: Uint32Array;
58
+ /** Two indices per line segment, including polygon boundaries. */
59
+ lines: Uint32Array;
60
+ /** Source feature per segment. */
61
+ lineFeatures: Uint32Array;
62
+ /** Source feature per triangle in mesh.indices. */
63
+ triangleFeatures: Uint32Array;
64
+ /** Source polygon boundaries, without the repeated closing vertex. */
65
+ polygons: GeoPolygon[];
66
+ /** Triangles and float32 coordinates for createMeshes/toGeometry; groups address source features. */
67
+ mesh: LoadedGeometry;
68
+ /** Coordinate reference system label. No implicit projection is applied. */
69
+ crs: string;
70
+ }
71
+ export declare const GEO = "Geo";
72
+ export declare function geoLimit(options: GeoOptions, key: 'maxFeatures' | 'maxBytes' | 'maxDepth', fallback: number): number;
73
+ export declare function geoText(input: string | Uint8Array, options: GeoOptions): string;
74
+ export declare function area(ring: GeoPosition[]): number;
75
+ export declare function inside(p: GeoPosition, ring: GeoPosition[]): boolean;
76
+ /**
77
+ * The two ordinates a ring is triangulated in: x and y, the plane of every map polygon, unless the ring stands
78
+ * vertical (a MultiPatch wall), where its x/y outline has no area; then the plane its Newell normal faces.
79
+ */
80
+ export declare function planeAxes(ring: GeoPosition[]): [number, number];
81
+ /** Internal containment grouping, independent of source ring winding or part ordering. */
82
+ export declare function ringPolygons(rings: GeoPosition[][]): GeoPosition[][][];
83
+ /** Internal normalization and tessellation shared by all vector formats. */
84
+ export declare function buildGeo(features: GeoFeature[], options?: GeoOptions, crs?: string): GeoResult;