@margoengine/loaders 0.1.0 → 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.
- package/LICENSE +201 -201
- package/NOTICE +4 -4
- package/README.md +1666 -1198
- package/dist/crease.d.ts +7 -0
- package/dist/crease.js +67 -0
- package/dist/dae-common.js +1 -1
- package/dist/dae-kinematics.d.ts +65 -0
- package/dist/dae-kinematics.js +461 -0
- package/dist/dae.d.ts +9 -4
- package/dist/dae.js +16 -5
- package/dist/dxf-hatch.d.ts +8 -0
- package/dist/dxf-hatch.js +346 -0
- package/dist/dxf-leaders.d.ts +59 -0
- package/dist/dxf-leaders.js +258 -0
- package/dist/dxf.d.ts +42 -1
- package/dist/dxf.js +226 -15
- package/dist/engine.d.ts +5 -0
- package/dist/engine.js +3 -0
- package/dist/gcode.d.ts +37 -0
- package/dist/gcode.js +91 -0
- package/dist/geometry.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/mtl.d.ts +8 -3
- package/dist/mtl.js +91 -10
- package/dist/nrrd.d.ts +12 -5
- package/dist/nrrd.js +68 -26
- package/dist/obj.d.ts +3 -1
- package/dist/obj.js +7 -1
- package/dist/render.d.ts +9 -4
- package/dist/render.js +31 -3
- package/dist/shared/asset-url.js +82 -82
- package/dist/shared/crc32.d.ts +2 -2
- package/dist/shared/crc32.js +47 -47
- package/dist/shared/errors.js +36 -36
- package/dist/shared/inflate.js +284 -284
- package/dist/shared/normals.js +26 -26
- package/dist/shared/scene-scope.js +54 -54
- package/dist/shared/trailing-data.js +45 -42
- package/dist/threemf-beam-reader.d.ts +19 -0
- package/dist/threemf-beam-reader.js +165 -0
- package/dist/threemf-beams.d.ts +52 -0
- package/dist/threemf-beams.js +268 -0
- package/dist/threemf-boolean-read.d.ts +10 -0
- package/dist/threemf-boolean-read.js +113 -0
- package/dist/threemf-boolean.d.ts +59 -0
- package/dist/threemf-boolean.js +20 -0
- package/dist/threemf-csg.d.ts +14 -0
- package/dist/threemf-csg.js +193 -0
- package/dist/threemf-displacement-read.d.ts +8 -0
- package/dist/threemf-displacement-read.js +213 -0
- package/dist/threemf-displacement.d.ts +71 -0
- package/dist/threemf-displacement.js +18 -0
- package/dist/threemf-evaluate.d.ts +36 -0
- package/dist/threemf-evaluate.js +86 -0
- package/dist/threemf-functions.d.ts +33 -0
- package/dist/threemf-functions.js +359 -0
- package/dist/threemf-lattice-mesh.d.ts +9 -0
- package/dist/threemf-lattice-mesh.js +115 -0
- package/dist/threemf-lattice.js +10 -145
- package/dist/threemf-levelset.d.ts +23 -0
- package/dist/threemf-levelset.js +105 -0
- package/dist/threemf-materials.d.ts +89 -2
- package/dist/threemf-materials.js +194 -11
- package/dist/threemf-mesh.d.ts +21 -6
- package/dist/threemf-mesh.js +266 -45
- package/dist/threemf-secure.d.ts +50 -0
- package/dist/threemf-secure.js +153 -0
- package/dist/threemf-tessellate.d.ts +37 -0
- package/dist/threemf-tessellate.js +277 -0
- package/dist/threemf-volume-colour.d.ts +25 -0
- package/dist/threemf-volume-colour.js +233 -0
- package/dist/threemf-volume-sample.d.ts +8 -0
- package/dist/threemf-volume-sample.js +65 -0
- package/dist/threemf-volumetric-read.d.ts +15 -0
- package/dist/threemf-volumetric-read.js +539 -0
- package/dist/threemf-volumetric.d.ts +177 -0
- package/dist/threemf-volumetric.js +28 -0
- package/dist/threemf.d.ts +73 -4
- package/dist/threemf.js +235 -41
- package/dist/types.d.ts +18 -0
- package/dist/workers/usd.js +1 -1
- package/package.json +291 -246
package/dist/dxf.js
CHANGED
|
@@ -3,7 +3,9 @@
|
|
|
3
3
|
// (rows and columns included) and DIMENSION, and the model-space entities a viewer draws. Faces (3DFACE, SOLID, TRACE,
|
|
4
4
|
// polyface and polygon-mesh POLYLINEs, MESH) become one triangle list; curves (LINE, polylines with bulges, ARC,
|
|
5
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.
|
|
6
7
|
import { NurbsCurve } from '@margoengine/geometry/nurbs';
|
|
8
|
+
import { dimensionOverrides, readLeader, readMultiLeader } from './dxf-leaders.js';
|
|
7
9
|
import { LoaderError } from './types.js';
|
|
8
10
|
import { checkCount, latin1, limits, toBytes } from './util.js';
|
|
9
11
|
const F = 'DXF';
|
|
@@ -184,6 +186,14 @@ function readPairs(bytes, decode) {
|
|
|
184
186
|
}
|
|
185
187
|
/** `\U+XXXX` escapes (pre-2007 files) to characters. */
|
|
186
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
|
+
});
|
|
187
197
|
/** MTEXT's inline formatting codes removed: paragraphs become line breaks. */
|
|
188
198
|
function plainMText(s) {
|
|
189
199
|
return unicode(s)
|
|
@@ -240,6 +250,24 @@ function ocs(n) {
|
|
|
240
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]];
|
|
241
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);
|
|
242
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
|
+
}
|
|
243
271
|
/**
|
|
244
272
|
* Reads a DXF drawing (ASCII or binary) into faces, line segments, points, texts and ACIS solids, in
|
|
245
273
|
* meters by default. Throws a {@link LoaderError}: `'syntax'` or `'truncated'` for a malformed file, `'limit'` past a
|
|
@@ -273,7 +301,10 @@ export function parseDXF(input, options = {}) {
|
|
|
273
301
|
};
|
|
274
302
|
const str = (v) => (v === undefined ? '' : String(v));
|
|
275
303
|
// --- sections ---------------------------------------------------------------------------------------------------
|
|
276
|
-
const header = new Map(), layers = new Map(), blocks = new Map(),
|
|
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();
|
|
277
308
|
/** Entities from pair `i` (a code 0) up to the end of the section or `stop`. */
|
|
278
309
|
const entitiesFrom = (i, stop) => {
|
|
279
310
|
const list = [];
|
|
@@ -321,9 +352,14 @@ export function parseDXF(input, options = {}) {
|
|
|
321
352
|
const { list, next } = entitiesFrom(i, (type) => type === 'ENDSEC');
|
|
322
353
|
i = next;
|
|
323
354
|
if (name === 'TABLES') {
|
|
324
|
-
for (const e of list)
|
|
325
|
-
|
|
326
|
-
|
|
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;
|
|
327
363
|
layers.set(layerName, {
|
|
328
364
|
name: layerName,
|
|
329
365
|
aci: Math.abs(aci),
|
|
@@ -333,6 +369,7 @@ export function parseDXF(input, options = {}) {
|
|
|
333
369
|
visible: aci >= 0 && !(flags & 1),
|
|
334
370
|
});
|
|
335
371
|
}
|
|
372
|
+
}
|
|
336
373
|
}
|
|
337
374
|
else if (name === 'BLOCKS') {
|
|
338
375
|
let current;
|
|
@@ -437,10 +474,20 @@ export function parseDXF(input, options = {}) {
|
|
|
437
474
|
}
|
|
438
475
|
return out.length ? out : control;
|
|
439
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
|
+
};
|
|
440
485
|
const emit = (e, context) => {
|
|
441
|
-
const
|
|
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) => {
|
|
442
489
|
const k = e.codes.indexOf(code);
|
|
443
|
-
return k < 0 ? undefined : e.values[k];
|
|
490
|
+
return k < 0 || (embedded >= 0 && k > embedded) ? undefined : e.values[k];
|
|
444
491
|
}, n = (code, fallback = 0) => num(first(code), fallback);
|
|
445
492
|
if (n(67) === 1) {
|
|
446
493
|
skip(`${e.type} (paper space)`);
|
|
@@ -582,22 +629,34 @@ export function parseDXF(input, options = {}) {
|
|
|
582
629
|
return;
|
|
583
630
|
}
|
|
584
631
|
case 'TEXT':
|
|
585
|
-
case 'MTEXT':
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
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
|
|
589
645
|
? [n(10), n(20), n(30)]
|
|
590
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
|
|
591
647
|
? [n(11), n(21), n(31)]
|
|
592
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;
|
|
593
651
|
texts.push({
|
|
594
|
-
text: mtext ? plainMText(raw) : unicode(raw),
|
|
652
|
+
text: controlCodes(mtext || multiline ? plainMText(raw) : unicode(raw)),
|
|
595
653
|
position,
|
|
596
654
|
height,
|
|
597
655
|
direction: direction(m, xAxis[0], xAxis[1], xAxis[2]),
|
|
598
656
|
normal: direction(m, ...direction(o, 0, 0, 1)),
|
|
599
657
|
layer: layerName,
|
|
600
658
|
color,
|
|
659
|
+
...(attribute && { tag: unicode(str(first(2))) }),
|
|
601
660
|
});
|
|
602
661
|
return;
|
|
603
662
|
}
|
|
@@ -628,11 +687,42 @@ export function parseDXF(input, options = {}) {
|
|
|
628
687
|
if (inserts > maxInserts)
|
|
629
688
|
throw new LoaderError(F, 'limit', `block references exceed maxInserts ${maxInserts}`);
|
|
630
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
|
+
}
|
|
631
698
|
for (const child of block.entities)
|
|
632
699
|
emit(child, { matrix: mul(m, local), layer: layerName, color, depth: context.depth + 1 });
|
|
633
700
|
}
|
|
634
701
|
return;
|
|
635
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
|
+
}
|
|
636
726
|
case '3DSOLID':
|
|
637
727
|
case 'BODY':
|
|
638
728
|
case 'REGION': {
|
|
@@ -650,10 +740,129 @@ export function parseDXF(input, options = {}) {
|
|
|
650
740
|
solids.push({ type: e.type, sat: decodeSAT(lines), transform: [...m], layer: layerName, color });
|
|
651
741
|
return;
|
|
652
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
|
+
}
|
|
653
864
|
case 'VERTEX':
|
|
654
865
|
case 'SEQEND':
|
|
655
|
-
case 'ATTRIB':
|
|
656
|
-
case 'ATTDEF':
|
|
657
866
|
case 'VIEWPORT':
|
|
658
867
|
return;
|
|
659
868
|
default:
|
|
@@ -702,7 +911,7 @@ export function parseDXF(input, options = {}) {
|
|
|
702
911
|
else
|
|
703
912
|
polyline(lineOut(), bulged(vertices.map((v) => ({ x: v.p[0], y: v.p[1], bulge: v.bulge })), !!(flags & 1), elevation).map(inOCS), false);
|
|
704
913
|
};
|
|
705
|
-
/** Attaches each POLYLINE's VERTEX entities
|
|
914
|
+
/** Attaches each POLYLINE's VERTEX entities and each INSERT's ATTRIB entities to it, up to SEQEND. */
|
|
706
915
|
const gather = (list) => {
|
|
707
916
|
const out = [];
|
|
708
917
|
for (let k = 0; k < list.length; k++) {
|
|
@@ -720,8 +929,10 @@ export function parseDXF(input, options = {}) {
|
|
|
720
929
|
let j = k + 1;
|
|
721
930
|
while (j < list.length && list[j].type === 'ATTRIB')
|
|
722
931
|
j++;
|
|
723
|
-
if (j > k + 1 && j < list.length && list[j].type === 'SEQEND')
|
|
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) });
|
|
724
934
|
k = j;
|
|
935
|
+
}
|
|
725
936
|
}
|
|
726
937
|
else
|
|
727
938
|
out.push(e);
|
package/dist/engine.d.ts
CHANGED
|
@@ -4,6 +4,11 @@ import { type LoadedGeometry } from './types.js';
|
|
|
4
4
|
import { type PointsToGeometryOptions, type ToGeometryOptions } from './geometry.js';
|
|
5
5
|
/** Options of createMeshes: parent, material values, one mesh or one per group, and the geometry options. */
|
|
6
6
|
export interface CreateMeshesOptions extends Pick<ToGeometryOptions, 'normals' | 'maxPartVertices'>, PointsToGeometryOptions {
|
|
7
|
+
/**
|
|
8
|
+
* For a file without normals, with `normals: 'auto'`: faces within this many degrees of each other are smoothed
|
|
9
|
+
* together, so sharper edges stay sharp. 0 is flat, 180 smooths everything. Default 40.
|
|
10
|
+
*/
|
|
11
|
+
creaseAngle?: number;
|
|
7
12
|
/** Parent for every created mesh. */
|
|
8
13
|
parent?: Mesh | null;
|
|
9
14
|
/** Color for meshes without a file color: `#rrggbb` (sRGB) or linear RGB. Default `#b8bcc4`. */
|
package/dist/engine.js
CHANGED
|
@@ -2,6 +2,7 @@ import { PbrMaterial } from '@margoengine/core';
|
|
|
2
2
|
import { LoaderError } from './types.js';
|
|
3
3
|
import { pointsToGeometry, toGeometries } from './geometry.js';
|
|
4
4
|
import { SRGBToLinear as toLinear } from '@margoengine/math/color';
|
|
5
|
+
import { creased } from './crease.js';
|
|
5
6
|
const clamp = (v) => Math.min(1, Math.max(0, Number.isFinite(v) ? v : 0));
|
|
6
7
|
function averageColor(loaded, group) {
|
|
7
8
|
const colors = loaded.colors;
|
|
@@ -36,6 +37,8 @@ export function createMeshes(engine, loaded, options = {}) {
|
|
|
36
37
|
const vertexColors = options.vertexColors ?? 'average';
|
|
37
38
|
if (vertexColors !== 'average' && vertexColors !== 'ignore')
|
|
38
39
|
throw new LoaderError('Engine', 'range', `unknown vertexColors mode "${String(vertexColors)}"`);
|
|
40
|
+
if ((options.normals ?? 'auto') === 'auto')
|
|
41
|
+
loaded = creased(loaded, options.creaseAngle);
|
|
39
42
|
const materials = new Map();
|
|
40
43
|
const material = (color) => {
|
|
41
44
|
const key = typeof color === 'string' ? color.toLowerCase() : color.map((v) => v.toFixed(5)).join(',');
|
package/dist/gcode.d.ts
CHANGED
|
@@ -53,3 +53,40 @@ export interface GCode {
|
|
|
53
53
|
* ```
|
|
54
54
|
*/
|
|
55
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
CHANGED
|
@@ -276,3 +276,94 @@ export function parseGCode(input, options = {}) {
|
|
|
276
276
|
function makeLayer(z) {
|
|
277
277
|
return { z, extrusion: floats(), travel: floats() };
|
|
278
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
|
+
}
|
package/dist/geometry.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export interface ToGeometryOptions {
|
|
|
16
16
|
group?: number | LoadedGroup;
|
|
17
17
|
/**
|
|
18
18
|
* `toGeometries` only: most vertices in one part, an integer from 3 to {@link CORE_MAX_VERTICES} (the default).
|
|
19
|
-
* Lower it for a renderer whose per-
|
|
19
|
+
* Lower it for a renderer whose per-mesh limit is smaller (a materials mesh takes 1,000,000).
|
|
20
20
|
*/
|
|
21
21
|
maxPartVertices?: number;
|
|
22
22
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export { parsePLY, parsePLYHeader } from './ply.js';
|
|
|
16
16
|
export type { PLYOptions, PLYHeader, PLYElement, PLYProperty } from './ply.js';
|
|
17
17
|
export { parse3MF, THREEMF_UNITS } from './threemf.js';
|
|
18
18
|
export { parseDXF } from './dxf.js';
|
|
19
|
-
export type { DXFOptions, DXFResult, DXFLayer, DXFText, DXFSolid, DXFLines, DXFColor } from './dxf.js';
|
|
19
|
+
export type { DXFOptions, DXFResult, DXFLayer, DXFText, DXFSolid, DXFLines, DXFColor, DXFHatchInput, DXFHatchGeometry, DXFHatchReader, } from './dxf.js';
|
|
20
20
|
export type { ThreeMFOptions, ThreeMFResult } from './threemf.js';
|
|
21
21
|
export { parsePCD, parsePCDHeader } from './pcd.js';
|
|
22
22
|
export type { PCDOptions, PCDHeader, PCDField } from './pcd.js';
|
package/dist/mtl.d.ts
CHANGED
|
@@ -58,9 +58,14 @@ export interface MTLMaterialSet {
|
|
|
58
58
|
* metallic-roughness: `Kd` is the base colour (sRGB in the file, linear in the material), `d` (else 1 - `Tr`) the
|
|
59
59
|
* opacity, `Ke` the emission (a peak above 1 moves into `emissiveIntensity`), and roughness comes from the Phong
|
|
60
60
|
* exponent `Ns` as (2 / (Ns + 2))^(1/4) (Walter et al. 2007's Blinn-Phong to Beckmann match with glTF's
|
|
61
|
-
* alpha = roughness^2).
|
|
62
|
-
*
|
|
63
|
-
*
|
|
61
|
+
* alpha = roughness^2). `Ks` (and `map_Ks`, times it) is the specular reflectance at normal incidence, held as
|
|
62
|
+
* KHR_materials_specular's `specularColor` and `specularColorMap`; `illum 1` and a black `Ks` have no highlight. The
|
|
63
|
+
* PBR extension's `Pr`, `Pm` and `norm` are read when present, and a material with `Pr` or `Pm` leaves `Ks` out.
|
|
64
|
+
* `illum 0` is unlit. `disp` displaces vertices along their normals (`-mm base gain`: bias and scale). `refl` becomes
|
|
65
|
+
* the material's `envMap`: `-type sphere` a latitude-longitude image, or six `-type cube_*` faces (front is -Z).
|
|
66
|
+
* `map_Kd`, `map_d`, `map_Ke`, `map_Ks`, `disp`, `refl`, `bump` and `norm` load as textures, each (file, colour
|
|
67
|
+
* space, wrap) once; their `-o` and `-s` become the slot's UV transform and `-clamp on` a clamped wrap. A map that
|
|
68
|
+
* fails to load is a warning. `Ka` has no equivalent (ambient light shades the base colour) and is a warning.
|
|
64
69
|
* Rejects with `TypeError` / `RangeError` for bad arguments and with a `LoaderError` (code `'aborted'`) when
|
|
65
70
|
* `signal` aborts; whatever was built is disposed first.
|
|
66
71
|
*/
|