formacad 0.1.0 → 0.2.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/README.md +32 -21
- package/build/cli/src/forma.js +276 -15
- package/build/cli/src/forma.js.map +1 -1
- package/build/cli/src/mcp.d.ts +1 -0
- package/build/cli/src/mcp.js +495 -0
- package/build/cli/src/mcp.js.map +1 -0
- package/build/cli/src/preview.d.ts +31 -3
- package/build/cli/src/preview.js +235 -76
- package/build/cli/src/preview.js.map +1 -1
- package/build/core/src/export2d.d.ts +3 -0
- package/build/core/src/export2d.js +48 -0
- package/build/core/src/export2d.js.map +1 -1
- package/build/core/src/geometry.d.ts +1 -0
- package/build/core/src/geometry.js +1 -1
- package/build/core/src/geometry.js.map +1 -1
- package/build/core/src/gltf.d.ts +6 -0
- package/build/core/src/gltf.js +154 -0
- package/build/core/src/gltf.js.map +1 -0
- package/build/core/src/importers.d.ts +1 -0
- package/build/core/src/importers.js +314 -0
- package/build/core/src/importers.js.map +1 -1
- package/build/core/src/index.d.ts +17 -6
- package/build/core/src/index.js +79 -7
- package/build/core/src/index.js.map +1 -1
- package/build/core/src/interp.d.ts +37 -1
- package/build/core/src/interp.js +1048 -62
- package/build/core/src/interp.js.map +1 -1
- package/build/core/src/lexer.js +1 -1
- package/build/core/src/lexer.js.map +1 -1
- package/build/core/src/modeling.d.ts +18 -0
- package/build/core/src/modeling.js +483 -0
- package/build/core/src/modeling.js.map +1 -0
- package/build/core/src/parser.js +82 -12
- package/build/core/src/parser.js.map +1 -1
- package/build/core/src/scad/colors.d.ts +1 -0
- package/build/core/src/scad/colors.js +37 -0
- package/build/core/src/scad/colors.js.map +1 -0
- package/build/core/src/scad/convert.d.ts +33 -0
- package/build/core/src/scad/convert.js +2842 -0
- package/build/core/src/scad/convert.js.map +1 -0
- package/build/core/src/scad/parser.d.ts +239 -0
- package/build/core/src/scad/parser.js +578 -0
- package/build/core/src/scad/parser.js.map +1 -0
- package/build/core/src/scad/sources.d.ts +39 -0
- package/build/core/src/scad/sources.js +171 -0
- package/build/core/src/scad/sources.js.map +1 -0
- package/build/core/src/surface.d.ts +21 -0
- package/build/core/src/surface.js +253 -0
- package/build/core/src/surface.js.map +1 -0
- package/build/core/src/values.d.ts +31 -1
- package/build/core/src/values.js +72 -1
- package/build/core/src/values.js.map +1 -1
- package/package.json +2 -1
package/build/core/src/interp.js
CHANGED
|
@@ -4,20 +4,22 @@ import { FormaError } from './errors.js';
|
|
|
4
4
|
import { lex, UNITS } from './lexer.js';
|
|
5
5
|
import { Parser } from './parser.js';
|
|
6
6
|
import { suggest } from './difflib.js';
|
|
7
|
-
import { bboxOf, convexHull2d, convexHull3d, csgIntersectMany, csgSubtract, csgSubtractMany, csgUnion, fan, makePoly, matMul, openEdges, pointInOutline, prism2d, primBox, primCone, primSphere, primTorus, pyRound, quality, rotAxis, rotX, rotY, rotZ, segmentsFor, signedArea, sliceZ, stretchZ, cleanOutline, volume, } from './geometry.js';
|
|
7
|
+
import { bboxOf, convexHull2d, convexHull3d, csgIntersectMany, csgSubtract, csgSubtractMany, csgUnion, fan, makePoly, matDet, matMul, openEdges, pointInOutline, prism2d, primBox, primCone, primSphere, primTorus, pyRound, quality, rotAxis, rotX, rotY, rotZ, segmentsFor, signedArea, sliceZ, stretchZ, cleanOutline, volume, } from './geometry.js';
|
|
8
8
|
import { manifoldContoursToPrism, manifoldHull3d, manifoldMinkowski, manifoldOffset2d, manifoldProject, manifoldSlice } from './manifold.js';
|
|
9
9
|
import { applyBevel2d, applyBevel3d, EDGE_SELECTORS } from './bevel.js';
|
|
10
|
+
import { loft3d, SHELL_FACES, shell3d, sweep3d } from './modeling.js';
|
|
10
11
|
import { getBundledFont, layoutText, parseTtfBytes } from './ttf.js';
|
|
11
12
|
import { getStdSource, listStdModules } from './std.js';
|
|
12
13
|
import { basename, dirname, extname, join, readText, stem } from './host.js';
|
|
13
|
-
import { read3mf, readObj, readStl, readSvg } from './importers.js';
|
|
14
|
-
import {
|
|
14
|
+
import { read3mf, readDxf, readObj, readStl, readSvg } from './importers.js';
|
|
15
|
+
import { buildSurfaceMesh, decodePngGray, downsampleGrid, MAX_SURFACE_MESH_CELLS, MAX_SURFACE_MESH_RES, parseHeightText, } from './surface.js';
|
|
16
|
+
import { BBox, BUILTIN_LAYERS, Builtin, Closure, Component, dimExp, Enum, Env, EXP_DIM, flattenShapes, FontValue, RandomValue, RangeValue, StructInstance, StructType, FunctionValue, LayerValue, Module, Q, Shape, show, typename, } from './values.js';
|
|
15
17
|
export const COLORS = {
|
|
16
18
|
white: '#f4f6f8', black: '#1d1f22', red: '#d64541', orange: '#f08a24', yellow: '#f4d03f',
|
|
17
19
|
green: '#3fa34d', blue: '#3a78c9', purple: '#8e5bc5', pink: '#f29bb8', brown: '#7b4a2e',
|
|
18
20
|
gray: '#8a9099', grey: '#8a9099', silver: '#c4cad2', gold: '#d4a72c',
|
|
19
21
|
};
|
|
20
|
-
export const SHAPE_METHODS = ['at', 'move', 'rotate', 'scale', 'resize', 'mirror', 'color', 'layer', 'extrude', 'revolve', 'offset', 'slice', 'project', 'fillet', 'chamfer'];
|
|
22
|
+
export const SHAPE_METHODS = ['at', 'move', 'rotate', 'scale', 'resize', 'mirror', 'transform', 'align', 'above', 'below', 'leftOf', 'rightOf', 'inFrontOf', 'behind', 'color', 'layer', 'extrude', 'revolve', 'offset', 'slice', 'project', 'fillet', 'chamfer', 'shell', 'sweep'];
|
|
21
23
|
const REQUIRED = Symbol('required');
|
|
22
24
|
const radians = (d) => (d * Math.PI) / 180;
|
|
23
25
|
const degrees = (r) => (r * 180) / Math.PI;
|
|
@@ -189,6 +191,7 @@ export function qArith(op, a, b, pos) {
|
|
|
189
191
|
export class Interp {
|
|
190
192
|
host;
|
|
191
193
|
overrides;
|
|
194
|
+
rawOverrides;
|
|
192
195
|
modules = new Map();
|
|
193
196
|
loading = [];
|
|
194
197
|
moduleDepth = 0;
|
|
@@ -209,18 +212,22 @@ export class Interp {
|
|
|
209
212
|
constructor(opts) {
|
|
210
213
|
this.host = opts.host;
|
|
211
214
|
this.overrides = opts.overrides ?? new Map();
|
|
215
|
+
this.rawOverrides = opts.rawOverrides ?? new Map();
|
|
212
216
|
const table = {
|
|
213
|
-
Box: this.bBox, Circle: this.bCircle, Cone: this.bCone, Cylinder: this.bCylinder, Difference: this.bDifference,
|
|
214
|
-
Extrude: this.bExtrude, Font: this.bFont, ForEach: this.bForEach, Hull: this.bHull, Import: this.bImport,
|
|
215
|
-
Intersection: this.bIntersection, Layer: this.bLayer, Minkowski: this.bMinkowski, Offset: this.bOffset,
|
|
217
|
+
Bezier: this.bBezier, Box: this.bBox, Circle: this.bCircle, Cone: this.bCone, Cylinder: this.bCylinder, Difference: this.bDifference,
|
|
218
|
+
Extrude: this.bExtrude, Font: this.bFont, ForEach: this.bForEach, Helix: this.bHelix, Hull: this.bHull, Import: this.bImport,
|
|
219
|
+
Intersection: this.bIntersection, Layer: this.bLayer, Loft: this.bLoft, Minkowski: this.bMinkowski, Offset: this.bOffset,
|
|
216
220
|
Polygon: this.bPolygon, Polyhedron: this.bPolyhedron, Project: this.bProject,
|
|
217
|
-
Rect: this.bRect, Revolve: this.bRevolve, Slice: this.bSlice,
|
|
218
|
-
Sphere: this.bSphere, Text: this.bText, Torus: this.bTorus, Union: this.bUnion,
|
|
221
|
+
Random: this.bRandom, Rect: this.bRect, Revolve: this.bRevolve, Slice: this.bSlice,
|
|
222
|
+
Sphere: this.bSphere, Spline: this.bSpline, Surface: this.bSurface, Text: this.bText, Torus: this.bTorus, Union: this.bUnion,
|
|
219
223
|
abs: this.bAbs, acos: this.bAcos, asin: this.bAsin, assert: this.bAssert, atan: this.bAtan, atan2: this.bAtan2,
|
|
220
|
-
ceil: this.bCeil, concat: this.bConcat, cos: this.bCos, cross: this.bCross, dot: this.bDot, exp: this.bExp,
|
|
221
|
-
floor: this.bFloor,
|
|
224
|
+
ceil: this.bCeil, chr: this.bChr, concat: this.bConcat, cos: this.bCos, cross: this.bCross, dot: this.bDot, exp: this.bExp,
|
|
225
|
+
floor: this.bFloor, isAngle: this.bIsAngle, isArea: this.bIsArea, isBool: this.bIsBool, isFunction: this.bIsFunction,
|
|
226
|
+
isLength: this.bIsLength, isList: this.bIsList, isNumber: this.bIsNumber, isShape: this.bIsShape, isString: this.bIsString,
|
|
227
|
+
isVolume: this.bIsVolume,
|
|
228
|
+
log: this.bLog, log10: this.bLog10, max: this.bMax, min: this.bMin, norm: this.bNorm, ord: this.bOrd,
|
|
222
229
|
pow: this.bPow, print: this.bPrint, round: this.bRound, sign: this.bSign, sin: this.bSin, sqrt: this.bSqrt,
|
|
223
|
-
stride: this.bStride, tan: this.bTan,
|
|
230
|
+
stride: this.bStride, tan: this.bTan, typeOf: this.bTypeOf,
|
|
224
231
|
};
|
|
225
232
|
for (const [name, fn] of Object.entries(table))
|
|
226
233
|
this.builtins.vars.set(name, new Builtin(name, fn.bind(this)));
|
|
@@ -235,7 +242,7 @@ export class Interp {
|
|
|
235
242
|
// ---- running -------------------------------------------------------------------------
|
|
236
243
|
run(prog, allow2d = false) {
|
|
237
244
|
const declared = prog.filter((st) => st[0] === 'param').map((st) => st[2]);
|
|
238
|
-
for (const name of this.overrides.keys()) {
|
|
245
|
+
for (const name of new Set([...this.overrides.keys(), ...this.rawOverrides.keys()])) {
|
|
239
246
|
if (!declared.includes(name))
|
|
240
247
|
throw new FormaError(`-D ${name}: there is no 'param ${name}' in the file${suggest(name, declared)}`);
|
|
241
248
|
}
|
|
@@ -425,7 +432,22 @@ export class Interp {
|
|
|
425
432
|
}
|
|
426
433
|
else if (kind === 'param') {
|
|
427
434
|
const name = st[2];
|
|
428
|
-
const
|
|
435
|
+
const defVal = this.eval(st[3], env);
|
|
436
|
+
let val;
|
|
437
|
+
if (this.overrides.has(name)) {
|
|
438
|
+
val = this.overrides.get(name);
|
|
439
|
+
}
|
|
440
|
+
else if (this.rawOverrides.has(name)) {
|
|
441
|
+
if (typeof defVal === 'string') {
|
|
442
|
+
val = this.rawOverrides.get(name);
|
|
443
|
+
}
|
|
444
|
+
else {
|
|
445
|
+
throw new FormaError(`-D ${name}: can't read value '${this.rawOverrides.get(name)}'`, pos);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
else {
|
|
449
|
+
val = defVal;
|
|
450
|
+
}
|
|
429
451
|
const constraint = st[4] ?? null;
|
|
430
452
|
if (constraint) {
|
|
431
453
|
if (constraint.kind === 'range') {
|
|
@@ -451,7 +473,64 @@ export class Interp {
|
|
|
451
473
|
if (val.v < lo.v || val.v > hi.v) {
|
|
452
474
|
throw new FormaError(`param '${name}' = ${show(val)} is outside ${show(lo)}...${show(hi)}`, pos);
|
|
453
475
|
}
|
|
454
|
-
|
|
476
|
+
let animateMeta;
|
|
477
|
+
if (constraint.animate) {
|
|
478
|
+
const anim = constraint.animate;
|
|
479
|
+
if (anim.closure)
|
|
480
|
+
throw new FormaError(`param '${name}': .animate() does not take a block`, anim.pos);
|
|
481
|
+
const allowed = ['duration', 'frames', 'loop', 'ease'];
|
|
482
|
+
const seen = new Set();
|
|
483
|
+
let duration = 3;
|
|
484
|
+
let frames = 24;
|
|
485
|
+
let loop = 'cycle';
|
|
486
|
+
let ease = 'linear';
|
|
487
|
+
for (const [lbl, expr, apos] of anim.args) {
|
|
488
|
+
if (!lbl)
|
|
489
|
+
throw new FormaError(`param '${name}': .animate() expects named arguments (duration:, frames:, loop:, ease:)`, apos);
|
|
490
|
+
if (!allowed.includes(lbl)) {
|
|
491
|
+
throw new FormaError(`param '${name}': unknown .animate() option '${lbl}'${suggest(lbl, allowed)}`, apos);
|
|
492
|
+
}
|
|
493
|
+
if (seen.has(lbl))
|
|
494
|
+
throw new FormaError(`param '${name}': duplicate .animate() option '${lbl}'`, apos);
|
|
495
|
+
seen.add(lbl);
|
|
496
|
+
const av = this.eval(expr, env);
|
|
497
|
+
if (lbl === 'duration') {
|
|
498
|
+
if (!(av instanceof Q) || av.dim !== null || av.v <= 0) {
|
|
499
|
+
throw new FormaError(`param '${name}': .animate(duration:) must be a positive number of seconds`, apos);
|
|
500
|
+
}
|
|
501
|
+
duration = av.v;
|
|
502
|
+
}
|
|
503
|
+
else if (lbl === 'frames') {
|
|
504
|
+
if (!(av instanceof Q) || av.dim !== null || !Number.isInteger(av.v) || av.v < 2 || av.v > 600) {
|
|
505
|
+
throw new FormaError(`param '${name}': .animate(frames:) must be a whole number from 2 to 600`, apos);
|
|
506
|
+
}
|
|
507
|
+
frames = av.v;
|
|
508
|
+
}
|
|
509
|
+
else if (lbl === 'loop') {
|
|
510
|
+
const loops = ['cycle', 'bounce', 'once'];
|
|
511
|
+
if (!(av instanceof Enum) || !loops.includes(av.name)) {
|
|
512
|
+
const hint = av instanceof Enum ? suggest(av.name, loops) : '';
|
|
513
|
+
throw new FormaError(`param '${name}': .animate(loop:) must be .cycle, .bounce, or .once${hint}`, apos);
|
|
514
|
+
}
|
|
515
|
+
loop = av.name;
|
|
516
|
+
}
|
|
517
|
+
else if (lbl === 'ease') {
|
|
518
|
+
const eases = ['linear', 'in', 'out', 'inOut'];
|
|
519
|
+
if (!(av instanceof Enum) || !eases.includes(av.name)) {
|
|
520
|
+
const hint = av instanceof Enum ? suggest(av.name, eases) : '';
|
|
521
|
+
throw new FormaError(`param '${name}': .animate(ease:) must be .linear, .in, .out, or .inOut${hint}`, apos);
|
|
522
|
+
}
|
|
523
|
+
ease = av.name;
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
animateMeta = { duration, frames, loop, ease };
|
|
527
|
+
}
|
|
528
|
+
const meta = { min: show(lo), max: show(hi) };
|
|
529
|
+
if (stepStr)
|
|
530
|
+
meta.step = stepStr;
|
|
531
|
+
if (animateMeta)
|
|
532
|
+
meta.animate = animateMeta;
|
|
533
|
+
this.paramMeta.set(name, meta);
|
|
455
534
|
}
|
|
456
535
|
else if (constraint.kind === 'options') {
|
|
457
536
|
const opts = this.eval(constraint.expr, env);
|
|
@@ -467,6 +546,10 @@ export class Interp {
|
|
|
467
546
|
this.paramMeta.set(name, { options: opts.map(show) });
|
|
468
547
|
}
|
|
469
548
|
}
|
|
549
|
+
if (typeof defVal === 'string' || typeof val === 'string') {
|
|
550
|
+
const existing = this.paramMeta.get(name) ?? {};
|
|
551
|
+
this.paramMeta.set(name, { ...existing, type: 'string' });
|
|
552
|
+
}
|
|
470
553
|
this.params.set(name, val);
|
|
471
554
|
env.define(name, val, pos);
|
|
472
555
|
}
|
|
@@ -476,6 +559,25 @@ export class Interp {
|
|
|
476
559
|
else if (kind === 'func') {
|
|
477
560
|
env.define(st[2], new FunctionValue(st[2], st[3], st[4], env, pos), pos);
|
|
478
561
|
}
|
|
562
|
+
else if (kind === 'struct') {
|
|
563
|
+
const sname = st[2];
|
|
564
|
+
const fields = st[3];
|
|
565
|
+
const seen = new Set();
|
|
566
|
+
for (const [fname, , fpos] of fields) {
|
|
567
|
+
if (seen.has(fname))
|
|
568
|
+
throw new FormaError(`struct '${sname}' already has a field '${fname}'`, fpos);
|
|
569
|
+
seen.add(fname);
|
|
570
|
+
}
|
|
571
|
+
const methods = new Map();
|
|
572
|
+
for (const m of st[4]) {
|
|
573
|
+
const mname = m[2];
|
|
574
|
+
if (seen.has(mname) || methods.has(mname)) {
|
|
575
|
+
throw new FormaError(`struct '${sname}' already has a member '${mname}'`, m[1]);
|
|
576
|
+
}
|
|
577
|
+
methods.set(mname, new FunctionValue(mname, m[3], m[4], env, m[1]));
|
|
578
|
+
}
|
|
579
|
+
env.define(sname, new StructType(sname, fields, methods, env, pos), pos);
|
|
580
|
+
}
|
|
479
581
|
else if (kind === 'return') {
|
|
480
582
|
if (this.funcDepth === 0)
|
|
481
583
|
throw new FormaError("'return' can only be used inside a func", pos);
|
|
@@ -497,6 +599,9 @@ export class Interp {
|
|
|
497
599
|
}
|
|
498
600
|
else if (kind === 'for') {
|
|
499
601
|
const seq = this.eval(st[3], env);
|
|
602
|
+
if (seq instanceof RangeValue) {
|
|
603
|
+
throw new FormaError(`'for' needs a whole-number range like 0..<4, or use stride(from: ${seq.lo}, to: ${seq.hi}, by: ...)`, pos);
|
|
604
|
+
}
|
|
500
605
|
if (!isList(seq))
|
|
501
606
|
throw new FormaError(`'for' needs a list or range like 0..<4, got ${typename(seq)}`, pos);
|
|
502
607
|
for (const item of seq) {
|
|
@@ -576,15 +681,19 @@ export class Interp {
|
|
|
576
681
|
}
|
|
577
682
|
case 'range': {
|
|
578
683
|
const lo = this.eval(e[2], env), hi = this.eval(e[3], env);
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
684
|
+
if (!isQ(lo) || !isQ(hi))
|
|
685
|
+
throw new FormaError('ranges need numbers or quantities, like 0..<4 or 2mm...10mm', pos);
|
|
686
|
+
if (lo.dim !== hi.dim) {
|
|
687
|
+
throw new FormaError(`range bounds must have the same units: ${typename(lo)} (${lo}) vs ${typename(hi)} (${hi})`, pos);
|
|
582
688
|
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
689
|
+
if (lo.dim === null && isWhole(lo.v) && isWhole(hi.v)) {
|
|
690
|
+
const out = [];
|
|
691
|
+
const end = hi.v + (e[4] ? 1 : 0);
|
|
692
|
+
for (let i = lo.v; i < end; i++)
|
|
693
|
+
out.push(new Q(i));
|
|
694
|
+
return out;
|
|
695
|
+
}
|
|
696
|
+
return new RangeValue(lo, hi, Boolean(e[4]));
|
|
588
697
|
}
|
|
589
698
|
case 'bin': {
|
|
590
699
|
const op = e[2];
|
|
@@ -605,6 +714,7 @@ export class Interp {
|
|
|
605
714
|
return this.arith(op, a, b, pos);
|
|
606
715
|
}
|
|
607
716
|
case 'member': return this.getMember(this.eval(e[2], env), e[3], pos);
|
|
717
|
+
case 'closure': return new Closure(e[2], e[3], env, pos);
|
|
608
718
|
case 'call': {
|
|
609
719
|
const callee = e[2], args = e[3], closure = e[4];
|
|
610
720
|
const argv = args.map(([lbl, x, p]) => [lbl, this.eval(x, env), p]);
|
|
@@ -711,6 +821,23 @@ export class Interp {
|
|
|
711
821
|
return obj[i];
|
|
712
822
|
}
|
|
713
823
|
}
|
|
824
|
+
if (obj instanceof StructInstance) {
|
|
825
|
+
if (obj.fields.has(name))
|
|
826
|
+
return obj.fields.get(name);
|
|
827
|
+
const mnames = ['with', ...obj.type.methods.keys()];
|
|
828
|
+
if (mnames.includes(name))
|
|
829
|
+
throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
|
|
830
|
+
const fnames = [...obj.fields.keys()];
|
|
831
|
+
throw new FormaError(`${obj.type.name} has no field '${name}'${suggest(name, [...fnames, ...mnames])}. Fields: ${fnames.join(', ') || 'none'}`, pos);
|
|
832
|
+
}
|
|
833
|
+
if (obj instanceof RandomValue) {
|
|
834
|
+
if (name === 'seed')
|
|
835
|
+
return new Q(obj.seed);
|
|
836
|
+
const rm = ['next', 'int', 'bool', 'pick', 'list'];
|
|
837
|
+
if (rm.includes(name))
|
|
838
|
+
throw new FormaError(`'${name}' is a method — call it like .${name}(...)`, pos);
|
|
839
|
+
throw new FormaError(`a random generator has no property '${name}'${suggest(name, ['seed', ...rm])}`, pos);
|
|
840
|
+
}
|
|
714
841
|
if (typeof obj === 'string') {
|
|
715
842
|
const chars = Array.from(obj);
|
|
716
843
|
if (name === 'count')
|
|
@@ -735,10 +862,39 @@ export class Interp {
|
|
|
735
862
|
return fn.fn(argv, clo, pos);
|
|
736
863
|
if (fn instanceof FunctionValue)
|
|
737
864
|
return this.callFunction(fn, argv, clo, pos);
|
|
865
|
+
if (fn instanceof Closure) {
|
|
866
|
+
if (clo !== null)
|
|
867
|
+
throw new FormaError("a closure doesn't take a { } block", pos);
|
|
868
|
+
const a = new Args('closure', argv, pos, fn.params, fn.params);
|
|
869
|
+
const vals = fn.params.map((pname) => a.raw(pname));
|
|
870
|
+
return this.closureValue(fn, vals);
|
|
871
|
+
}
|
|
738
872
|
if (fn instanceof Component)
|
|
739
873
|
return this.callComponent(fn, argv, clo, pos);
|
|
874
|
+
if (fn instanceof StructType)
|
|
875
|
+
return this.constructStruct(fn, argv, clo, pos);
|
|
740
876
|
throw new FormaError(`${typename(fn)} can't be called like a function`, pos);
|
|
741
877
|
}
|
|
878
|
+
constructStruct(st, argv, clo, pos) {
|
|
879
|
+
if (clo !== null)
|
|
880
|
+
throw new FormaError(`struct '${st.name}' doesn't take a { } block`, pos);
|
|
881
|
+
const names = st.fields.map((f) => f[0]);
|
|
882
|
+
const a = new Args(st.name, argv, pos, names, names);
|
|
883
|
+
const evalEnv = new Env(st.env);
|
|
884
|
+
const values = new Map();
|
|
885
|
+
for (const [fname, def] of st.fields) {
|
|
886
|
+
let val;
|
|
887
|
+
if (a.has(fname))
|
|
888
|
+
val = a.raw(fname);
|
|
889
|
+
else if (def !== null)
|
|
890
|
+
val = this.eval(def, evalEnv);
|
|
891
|
+
else
|
|
892
|
+
throw new FormaError(`${st.name} needs '${fname}:'`, pos);
|
|
893
|
+
values.set(fname, val);
|
|
894
|
+
evalEnv.define(fname, val, pos);
|
|
895
|
+
}
|
|
896
|
+
return new StructInstance(st, values);
|
|
897
|
+
}
|
|
742
898
|
bindParams(comp, argv, pos) {
|
|
743
899
|
const names = comp.params.map((p) => p[0]);
|
|
744
900
|
const a = new Args(comp.name, argv, pos, names, names);
|
|
@@ -948,6 +1104,167 @@ export class Interp {
|
|
|
948
1104
|
return new Shape(polys);
|
|
949
1105
|
}
|
|
950
1106
|
// ---- builtins: combining -----------------------------------------------------------------
|
|
1107
|
+
bRandom(argv, clo, pos) {
|
|
1108
|
+
if (clo !== null)
|
|
1109
|
+
throw new FormaError("Random doesn't take a { } block", pos);
|
|
1110
|
+
const a = new Args('Random', argv, pos, ['seed'], ['seed']);
|
|
1111
|
+
const seed = a.number('seed', 0);
|
|
1112
|
+
return new RandomValue(seed);
|
|
1113
|
+
}
|
|
1114
|
+
randomBounds(method, argv, pos, defLo = new Q(0), defHi = new Q(1)) {
|
|
1115
|
+
const a = new Args(method, argv, pos, ['in', 'min', 'max'], ['in']);
|
|
1116
|
+
if (a.has('in')) {
|
|
1117
|
+
if (a.has('min') || a.has('max'))
|
|
1118
|
+
throw new FormaError(`${method}: use either in: or min:/max:, not both`, pos);
|
|
1119
|
+
const r = a.raw('in');
|
|
1120
|
+
const rpos = a.at('in');
|
|
1121
|
+
if (r instanceof RangeValue) {
|
|
1122
|
+
if (r.lo.v > r.hi.v)
|
|
1123
|
+
throw new FormaError(`${method}: range min (${r.lo}) must not exceed max (${r.hi})`, rpos);
|
|
1124
|
+
return [r.lo, r.hi];
|
|
1125
|
+
}
|
|
1126
|
+
if (isList(r) && r.length >= 2 && isQ(r[0]) && isQ(r[r.length - 1])) {
|
|
1127
|
+
const lo = r[0], hi = r[r.length - 1];
|
|
1128
|
+
if (lo.dim !== hi.dim)
|
|
1129
|
+
throw new FormaError(`${method}: range bounds must have matching units`, rpos);
|
|
1130
|
+
return [lo, hi];
|
|
1131
|
+
}
|
|
1132
|
+
throw new FormaError(`${method}: in: expects a range like 2mm...10mm or 1...6`, rpos);
|
|
1133
|
+
}
|
|
1134
|
+
if (a.has('min') || a.has('max')) {
|
|
1135
|
+
const lo = a.raw('min', defLo), hi = a.raw('max', defHi);
|
|
1136
|
+
if (!isQ(lo) || !isQ(hi) || lo.dim !== hi.dim) {
|
|
1137
|
+
throw new FormaError(`${method}: min: and max: must be numbers or quantities with matching units`, pos);
|
|
1138
|
+
}
|
|
1139
|
+
if (lo.v > hi.v)
|
|
1140
|
+
throw new FormaError(`${method}: min (${lo}) must not exceed max (${hi})`, pos);
|
|
1141
|
+
return [lo, hi];
|
|
1142
|
+
}
|
|
1143
|
+
return [defLo, defHi];
|
|
1144
|
+
}
|
|
1145
|
+
bSurface(argv, clo, pos) {
|
|
1146
|
+
const a = new Args('Surface', argv, pos, ['file', 'heights', 'width', 'depth', 'height', 'base', 'cols', 'rows', 'invert', 'center', 'maxRes'], ['file']);
|
|
1147
|
+
const base = a.length('base', 1);
|
|
1148
|
+
if (base < 0)
|
|
1149
|
+
throw new FormaError('Surface: base: must not be negative', a.at('base'));
|
|
1150
|
+
const center = a.flag('center', true);
|
|
1151
|
+
const invert = a.flag('invert', false);
|
|
1152
|
+
// Mode 1: math closure Surface(width:, depth:, cols:, rows:, base:) { x, y in ... }
|
|
1153
|
+
if (clo !== null) {
|
|
1154
|
+
if (a.has('file') || a.has('heights')) {
|
|
1155
|
+
throw new FormaError("Surface: don't pass file/heights when using a { x, y in ... } block", pos);
|
|
1156
|
+
}
|
|
1157
|
+
const width = a.positive('width', a.length('width', 50));
|
|
1158
|
+
const depth = a.positive('depth', a.length('depth', width));
|
|
1159
|
+
const cols = Math.trunc(a.number('cols', 32));
|
|
1160
|
+
const rows = Math.trunc(a.number('rows', cols));
|
|
1161
|
+
if (cols < 2 || rows < 2)
|
|
1162
|
+
throw new FormaError('Surface: cols: and rows: must be at least 2', pos);
|
|
1163
|
+
if (cols > MAX_SURFACE_MESH_RES || rows > MAX_SURFACE_MESH_RES || cols * rows > MAX_SURFACE_MESH_CELLS) {
|
|
1164
|
+
throw new FormaError(`Surface: mesh grid ${cols}x${rows} exceeds the ${MAX_SURFACE_MESH_CELLS.toLocaleString('en')} sample limit (max ${MAX_SURFACE_MESH_RES} per side)`, pos);
|
|
1165
|
+
}
|
|
1166
|
+
const x0 = center ? -width / 2 : 0;
|
|
1167
|
+
const y0 = center ? -depth / 2 : 0;
|
|
1168
|
+
const vals = new Float64Array(cols * rows);
|
|
1169
|
+
let maxV = -Infinity;
|
|
1170
|
+
for (let r = 0; r < rows; r++) {
|
|
1171
|
+
const y = y0 + (r / (rows - 1)) * depth;
|
|
1172
|
+
for (let c = 0; c < cols; c++) {
|
|
1173
|
+
const x = x0 + (c / (cols - 1)) * width;
|
|
1174
|
+
const v = this.lenOf(this.closureValue(clo, [new Q(x, 'len'), new Q(y, 'len')]), 'Surface', clo.pos);
|
|
1175
|
+
vals[r * cols + c] = v;
|
|
1176
|
+
if (v > maxV)
|
|
1177
|
+
maxV = v;
|
|
1178
|
+
}
|
|
1179
|
+
}
|
|
1180
|
+
const polys = buildSurfaceMesh(cols, rows, (c, r) => {
|
|
1181
|
+
const v = vals[r * cols + c];
|
|
1182
|
+
return base + (invert ? maxV - v : v);
|
|
1183
|
+
}, width, depth, center);
|
|
1184
|
+
return new Shape(polys);
|
|
1185
|
+
}
|
|
1186
|
+
// Mode 2: inline 2D heights: [[...], ...]
|
|
1187
|
+
if (a.has('heights')) {
|
|
1188
|
+
if (a.has('file'))
|
|
1189
|
+
throw new FormaError('Surface: pass either a file or heights:, not both', pos);
|
|
1190
|
+
const raw = a.raw('heights');
|
|
1191
|
+
const hpos = a.at('heights');
|
|
1192
|
+
if (!isList(raw) || raw.length < 2)
|
|
1193
|
+
throw new FormaError('Surface: heights: needs a 2D list of at least 2x2 values', hpos);
|
|
1194
|
+
const rows = raw.length;
|
|
1195
|
+
if (!isList(raw[0]) || raw[0].length < 2)
|
|
1196
|
+
throw new FormaError('Surface: each row in heights: needs at least 2 values', hpos);
|
|
1197
|
+
const cols = raw[0].length;
|
|
1198
|
+
const vals = new Float64Array(cols * rows);
|
|
1199
|
+
let maxV = -Infinity;
|
|
1200
|
+
for (let r = 0; r < rows; r++) {
|
|
1201
|
+
const row = raw[r];
|
|
1202
|
+
if (!isList(row) || row.length !== cols) {
|
|
1203
|
+
throw new FormaError(`Surface: heights: row ${r} has different length than row 0 (${cols})`, hpos);
|
|
1204
|
+
}
|
|
1205
|
+
for (let c = 0; c < cols; c++) {
|
|
1206
|
+
const v = this.lenOf(row[c], 'Surface heights', hpos);
|
|
1207
|
+
vals[r * cols + c] = v;
|
|
1208
|
+
if (v > maxV)
|
|
1209
|
+
maxV = v;
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
const width = a.positive('width', a.length('width', (cols - 1) * 1));
|
|
1213
|
+
const depth = a.positive('depth', a.length('depth', (rows - 1) * 1));
|
|
1214
|
+
const polys = buildSurfaceMesh(cols, rows, (c, r) => {
|
|
1215
|
+
const v = vals[r * cols + c];
|
|
1216
|
+
return base + (invert ? maxV - v : v);
|
|
1217
|
+
}, width, depth, center);
|
|
1218
|
+
return new Shape(polys);
|
|
1219
|
+
}
|
|
1220
|
+
// Mode 3: PNG or DAT/CSV file
|
|
1221
|
+
const rel = a.raw('file');
|
|
1222
|
+
if (typeof rel !== 'string') {
|
|
1223
|
+
throw new FormaError('Surface needs a PNG/DAT file path, heights: [[...]], or a { x, y in ... } block', pos);
|
|
1224
|
+
}
|
|
1225
|
+
const dir = (this.callEnv && this.callEnv.vars.has(' dir') ? this.callEnv.vars.get(' dir') : this.globals.vars.get(' dir'));
|
|
1226
|
+
const full = join(dir, rel);
|
|
1227
|
+
if (!this.host.isFile(full))
|
|
1228
|
+
throw new FormaError(`Surface: can't find '${rel}' (looked for ${full})`, a.at('file'));
|
|
1229
|
+
const rawMaxRes = Math.trunc(a.number('maxRes', 160));
|
|
1230
|
+
if (rawMaxRes > MAX_SURFACE_MESH_RES) {
|
|
1231
|
+
throw new FormaError(`Surface: maxRes: ${rawMaxRes} exceeds the ${MAX_SURFACE_MESH_RES} limit`, a.at('maxRes'));
|
|
1232
|
+
}
|
|
1233
|
+
const maxRes = Math.max(8, rawMaxRes);
|
|
1234
|
+
const ext = extname(full).toLowerCase();
|
|
1235
|
+
if (ext === '.png') {
|
|
1236
|
+
const grid = downsampleGrid(decodePngGray(this.host.readBytes(full), pos), maxRes);
|
|
1237
|
+
const width = a.positive('width', a.length('width', grid.width));
|
|
1238
|
+
const depth = a.positive('depth', a.length('depth', width * (grid.height / grid.width)));
|
|
1239
|
+
const height = a.positive('height', a.length('height', 5));
|
|
1240
|
+
const polys = buildSurfaceMesh(grid.width, grid.height, (c, r) => {
|
|
1241
|
+
// Flip Y so row 0 (top of PNG) maps to +Y
|
|
1242
|
+
const lum = grid.data[(grid.height - 1 - r) * grid.width + c];
|
|
1243
|
+
return base + (invert ? 1 - lum : lum) * height;
|
|
1244
|
+
}, width, depth, center);
|
|
1245
|
+
return new Shape(polys);
|
|
1246
|
+
}
|
|
1247
|
+
const grid = downsampleGrid(parseHeightText(readText(this.host, full), pos), maxRes);
|
|
1248
|
+
const width = a.positive('width', a.length('width', grid.width));
|
|
1249
|
+
const depth = a.positive('depth', a.length('depth', grid.height));
|
|
1250
|
+
let minV = Infinity, maxV = -Infinity;
|
|
1251
|
+
for (let i = 0; i < grid.data.length; i++) {
|
|
1252
|
+
if (grid.data[i] < minV)
|
|
1253
|
+
minV = grid.data[i];
|
|
1254
|
+
if (grid.data[i] > maxV)
|
|
1255
|
+
maxV = grid.data[i];
|
|
1256
|
+
}
|
|
1257
|
+
const hasHeight = a.has('height');
|
|
1258
|
+
const targetH = hasHeight ? a.positive('height', a.length('height')) : 0;
|
|
1259
|
+
const span = maxV - minV;
|
|
1260
|
+
const polys = buildSurfaceMesh(grid.width, grid.height, (c, r) => {
|
|
1261
|
+
const rawV = grid.data[(grid.height - 1 - r) * grid.width + c];
|
|
1262
|
+
const norm = span > 1e-12 ? (rawV - minV) / span : 0;
|
|
1263
|
+
const h = hasHeight ? (invert ? 1 - norm : norm) * targetH : (invert ? maxV - rawV : rawV);
|
|
1264
|
+
return base + h;
|
|
1265
|
+
}, width, depth, center);
|
|
1266
|
+
return new Shape(polys);
|
|
1267
|
+
}
|
|
951
1268
|
bUnion(argv, clo, pos) {
|
|
952
1269
|
const shapes = this.children('Union', argv, clo, pos);
|
|
953
1270
|
const active = shapes.filter((s) => s.layer.exportable || s.layer.overlay);
|
|
@@ -1017,6 +1334,161 @@ export class Interp {
|
|
|
1017
1334
|
}
|
|
1018
1335
|
return layer;
|
|
1019
1336
|
}
|
|
1337
|
+
bHelix(argv, clo, pos) {
|
|
1338
|
+
if (clo !== null)
|
|
1339
|
+
throw new FormaError("Helix doesn't take a { } block", pos);
|
|
1340
|
+
const a = new Args('Helix', argv, pos, ['r', 'd', 'pitch', 'turns', 'height', 'segments', 'leftHand']);
|
|
1341
|
+
const r = a.radius();
|
|
1342
|
+
if (r <= 0)
|
|
1343
|
+
throw new FormaError('Helix: radius must be greater than 0', pos);
|
|
1344
|
+
let pitch = a.has('pitch') ? a.length('pitch') : null;
|
|
1345
|
+
let turns = a.has('turns') ? a.number('turns') : null;
|
|
1346
|
+
const height = a.has('height') ? a.length('height') : null;
|
|
1347
|
+
if (pitch !== null && pitch <= 0)
|
|
1348
|
+
throw new FormaError('Helix: pitch: must be greater than 0', a.at('pitch'));
|
|
1349
|
+
if (turns !== null && turns <= 0)
|
|
1350
|
+
throw new FormaError('Helix: turns: must be greater than 0', a.at('turns'));
|
|
1351
|
+
if (height !== null && height <= 0)
|
|
1352
|
+
throw new FormaError('Helix: height: must be greater than 0', a.at('height'));
|
|
1353
|
+
if (pitch !== null && turns !== null) {
|
|
1354
|
+
// use both
|
|
1355
|
+
}
|
|
1356
|
+
else if (height !== null && turns !== null) {
|
|
1357
|
+
pitch = height / turns;
|
|
1358
|
+
}
|
|
1359
|
+
else if (height !== null && pitch !== null) {
|
|
1360
|
+
turns = height / pitch;
|
|
1361
|
+
}
|
|
1362
|
+
else if (pitch !== null) {
|
|
1363
|
+
turns = 1;
|
|
1364
|
+
}
|
|
1365
|
+
else if (height !== null) {
|
|
1366
|
+
turns = 1;
|
|
1367
|
+
pitch = height;
|
|
1368
|
+
}
|
|
1369
|
+
else {
|
|
1370
|
+
throw new FormaError('Helix needs pitch: and/or height: (for example Helix(r: 12mm, pitch: 5mm, turns: 4))', pos);
|
|
1371
|
+
}
|
|
1372
|
+
const segPerTurn = a.has('segments') ? Math.max(6, Math.round(a.number('segments'))) : segmentsFor(r);
|
|
1373
|
+
const totalSteps = Math.max(4, Math.round(segPerTurn * turns));
|
|
1374
|
+
const dir = a.flag('leftHand', false) ? -1 : 1;
|
|
1375
|
+
const totalH = pitch * turns;
|
|
1376
|
+
const pts = [];
|
|
1377
|
+
for (let i = 0; i <= totalSteps; i++) {
|
|
1378
|
+
const frac = i / totalSteps;
|
|
1379
|
+
const ang = dir * 2 * Math.PI * turns * frac;
|
|
1380
|
+
pts.push([new Q(r * Math.cos(ang), 'len'), new Q(r * Math.sin(ang), 'len'), new Q(totalH * frac, 'len')]);
|
|
1381
|
+
}
|
|
1382
|
+
return pts;
|
|
1383
|
+
}
|
|
1384
|
+
parseCurvePoints(raw, name, pos) {
|
|
1385
|
+
if (!isList(raw) || raw.length < 2) {
|
|
1386
|
+
throw new FormaError(`${name}: points: needs a list of at least 2 points`, pos);
|
|
1387
|
+
}
|
|
1388
|
+
const first = raw[0];
|
|
1389
|
+
if (!isList(first) || (first.length !== 2 && first.length !== 3)) {
|
|
1390
|
+
throw new FormaError(`${name}: points must be [x, y] or [x, y, z]`, pos);
|
|
1391
|
+
}
|
|
1392
|
+
const dims = first.length;
|
|
1393
|
+
const pts = [];
|
|
1394
|
+
for (let i = 0; i < raw.length; i++) {
|
|
1395
|
+
const p = raw[i];
|
|
1396
|
+
if (!isList(p) || p.length !== dims) {
|
|
1397
|
+
throw new FormaError(`${name}: point ${i} must have ${dims} coordinates`, pos);
|
|
1398
|
+
}
|
|
1399
|
+
const coords = [];
|
|
1400
|
+
for (let c = 0; c < dims; c++) {
|
|
1401
|
+
const v = p[c];
|
|
1402
|
+
if (!isQ(v) || (v.dim !== 'len' && v.dim !== null)) {
|
|
1403
|
+
throw new FormaError(`${name}: point ${i} coordinate must be a length, got ${typename(v)}`, pos);
|
|
1404
|
+
}
|
|
1405
|
+
coords.push(v.v);
|
|
1406
|
+
}
|
|
1407
|
+
pts.push(coords);
|
|
1408
|
+
}
|
|
1409
|
+
return { pts, dims };
|
|
1410
|
+
}
|
|
1411
|
+
bBezier(argv, clo, pos) {
|
|
1412
|
+
if (clo !== null)
|
|
1413
|
+
throw new FormaError("Bezier doesn't take a { } block", pos);
|
|
1414
|
+
const a = new Args('Bezier', argv, pos, ['points', 'segments'], ['points', 'segments']);
|
|
1415
|
+
const { pts, dims } = this.parseCurvePoints(a.raw('points'), 'Bezier', a.at('points'));
|
|
1416
|
+
const segs = a.has('segments') ? Math.max(2, Math.round(a.number('segments'))) : 24;
|
|
1417
|
+
const out = [];
|
|
1418
|
+
for (let k = 0; k <= segs; k++) {
|
|
1419
|
+
const t = k / segs;
|
|
1420
|
+
let cur = pts;
|
|
1421
|
+
while (cur.length > 1) {
|
|
1422
|
+
const next = [];
|
|
1423
|
+
for (let i = 0; i < cur.length - 1; i++) {
|
|
1424
|
+
const p = [];
|
|
1425
|
+
for (let c = 0; c < dims; c++)
|
|
1426
|
+
p.push(cur[i][c] * (1 - t) + cur[i + 1][c] * t);
|
|
1427
|
+
next.push(p);
|
|
1428
|
+
}
|
|
1429
|
+
cur = next;
|
|
1430
|
+
}
|
|
1431
|
+
out.push(cur[0].map((v) => new Q(v, 'len')));
|
|
1432
|
+
}
|
|
1433
|
+
return out;
|
|
1434
|
+
}
|
|
1435
|
+
bSpline(argv, clo, pos) {
|
|
1436
|
+
if (clo !== null)
|
|
1437
|
+
throw new FormaError("Spline doesn't take a { } block", pos);
|
|
1438
|
+
const a = new Args('Spline', argv, pos, ['points', 'segments', 'closed'], ['points', 'segments']);
|
|
1439
|
+
const { pts, dims } = this.parseCurvePoints(a.raw('points'), 'Spline', a.at('points'));
|
|
1440
|
+
const closed = a.flag('closed', false);
|
|
1441
|
+
const sub = a.has('segments') ? Math.max(2, Math.round(a.number('segments'))) : 8;
|
|
1442
|
+
const m = pts.length;
|
|
1443
|
+
if (closed && m < 3)
|
|
1444
|
+
throw new FormaError('Spline(closed: true) needs at least 3 points', pos);
|
|
1445
|
+
const cr = (p0, p1, p2, p3, t) => {
|
|
1446
|
+
const t2 = t * t, t3 = t2 * t;
|
|
1447
|
+
return 0.5 * ((2 * p1) + (-p0 + p2) * t + (2 * p0 - 5 * p1 + 4 * p2 - p3) * t2 + (-p0 + 3 * p1 - 3 * p2 + p3) * t3);
|
|
1448
|
+
};
|
|
1449
|
+
const out = [];
|
|
1450
|
+
const spans = closed ? m : m - 1;
|
|
1451
|
+
for (let s = 0; s < spans; s++) {
|
|
1452
|
+
const p0 = closed ? pts[(s - 1 + m) % m] : pts[Math.max(0, s - 1)];
|
|
1453
|
+
const p1 = pts[s];
|
|
1454
|
+
const p2 = pts[(s + 1) % m];
|
|
1455
|
+
const p3 = closed ? pts[(s + 2) % m] : pts[Math.min(m - 1, s + 2)];
|
|
1456
|
+
const steps = !closed && s === spans - 1 ? sub + 1 : sub;
|
|
1457
|
+
for (let k = 0; k < steps; k++) {
|
|
1458
|
+
const t = k / sub;
|
|
1459
|
+
const coord = [];
|
|
1460
|
+
for (let c = 0; c < dims; c++)
|
|
1461
|
+
coord.push(new Q(cr(p0[c], p1[c], p2[c], p3[c], t), 'len'));
|
|
1462
|
+
out.push(coord);
|
|
1463
|
+
}
|
|
1464
|
+
}
|
|
1465
|
+
return out;
|
|
1466
|
+
}
|
|
1467
|
+
bLoft(argv, clo, pos) {
|
|
1468
|
+
if (clo === null)
|
|
1469
|
+
throw new FormaError('Loft needs a { } block with 2 or more 2D profiles', pos);
|
|
1470
|
+
const a = new Args('Loft', argv, pos, ['height', 'smooth', 'segments']);
|
|
1471
|
+
const smooth = a.flag('smooth', false);
|
|
1472
|
+
const segments = a.number('segments', null);
|
|
1473
|
+
const height = a.has('height') ? a.length('height') : null;
|
|
1474
|
+
if (height !== null && height <= 0)
|
|
1475
|
+
throw new FormaError('Loft: height: must be greater than 0', a.at('height'));
|
|
1476
|
+
const shapes = this.children('Loft', [], clo, pos);
|
|
1477
|
+
if (shapes.length < 2)
|
|
1478
|
+
throw new FormaError('Loft needs at least 2 2D profiles inside { }', pos);
|
|
1479
|
+
for (const s of shapes) {
|
|
1480
|
+
if (!s.is2d)
|
|
1481
|
+
throw new FormaError('Loft profiles must be 2D shapes (like Circle, Rect, or Polygon)', pos);
|
|
1482
|
+
}
|
|
1483
|
+
const allZeroZ = shapes.every((s) => Math.abs(s.pos[2]) < 1e-6);
|
|
1484
|
+
const profiles = shapes.map((s, idx) => {
|
|
1485
|
+
const z = height !== null && allZeroZ ? (height * idx) / (shapes.length - 1) : s.pos[2];
|
|
1486
|
+
const polys2d = s.derive({ pos: [s.pos[0], s.pos[1], 0] }).world();
|
|
1487
|
+
return { polys2d, z };
|
|
1488
|
+
});
|
|
1489
|
+
const polys = loft3d(profiles, smooth, segments, pos);
|
|
1490
|
+
return new Shape(polys, undefined, undefined, shapes[0].color ?? null);
|
|
1491
|
+
}
|
|
1020
1492
|
bHull(argv, clo, pos) {
|
|
1021
1493
|
const shapes = this.children('Hull', argv, clo, pos);
|
|
1022
1494
|
if (!shapes.length)
|
|
@@ -1478,8 +1950,8 @@ export class Interp {
|
|
|
1478
1950
|
if (rel.endsWith('.forma'))
|
|
1479
1951
|
throw new FormaError(`to use code from another file, write at the top: import "${rel}"`, pos);
|
|
1480
1952
|
const ext = extname(rel).toLowerCase();
|
|
1481
|
-
if (!['.stl', '.obj', '.svg', '.3mf'].includes(ext)) {
|
|
1482
|
-
throw new FormaError(`Import reads .stl, .obj, .3mf and .
|
|
1953
|
+
if (!['.stl', '.obj', '.svg', '.dxf', '.3mf'].includes(ext)) {
|
|
1954
|
+
throw new FormaError(`Import reads .stl, .obj, .3mf, .svg and .dxf; '${basename(rel)}' is not supported yet`, pos);
|
|
1483
1955
|
}
|
|
1484
1956
|
if (a.has('object') && ext !== '.3mf')
|
|
1485
1957
|
throw new FormaError('Import: object: is only for .3mf files', a.at('object'));
|
|
@@ -1489,13 +1961,20 @@ export class Interp {
|
|
|
1489
1961
|
if (!this.host.isFile(full))
|
|
1490
1962
|
throw new FormaError(`can't find '${rel}' (looked for ${full})`, pos);
|
|
1491
1963
|
let shape;
|
|
1492
|
-
if (ext === '.svg') {
|
|
1964
|
+
if (ext === '.svg' || ext === '.dxf') {
|
|
1493
1965
|
if (a.has('up'))
|
|
1494
|
-
throw new FormaError(
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1966
|
+
throw new FormaError(`Import: up: is for 3D files; a ${ext.slice(1).toUpperCase()} is flat`, a.at('up'));
|
|
1967
|
+
if (ext === '.svg') {
|
|
1968
|
+
const dpi = a.number('dpi', 96);
|
|
1969
|
+
if (dpi <= 0)
|
|
1970
|
+
throw new FormaError('Import: dpi: must be greater than 0', a.at('dpi'));
|
|
1971
|
+
shape = this.outlinesToShape(readSvg(this.host, full, pos, dpi), basename(full), pos);
|
|
1972
|
+
}
|
|
1973
|
+
else {
|
|
1974
|
+
if (a.has('dpi'))
|
|
1975
|
+
throw new FormaError('Import: dpi: is only for SVG files', a.at('dpi'));
|
|
1976
|
+
shape = this.outlinesToShape(readDxf(this.host, full, pos), basename(full), pos);
|
|
1977
|
+
}
|
|
1499
1978
|
}
|
|
1500
1979
|
else {
|
|
1501
1980
|
if (a.has('dpi'))
|
|
@@ -1532,9 +2011,7 @@ export class Interp {
|
|
|
1532
2011
|
}
|
|
1533
2012
|
return shape;
|
|
1534
2013
|
}
|
|
1535
|
-
|
|
1536
|
-
const elements = readSvg(this.host, full, pos, dpi);
|
|
1537
|
-
const name = basename(full);
|
|
2014
|
+
outlinesToShape(elements, name, pos) {
|
|
1538
2015
|
const parts = [];
|
|
1539
2016
|
for (const [label, outlines] of elements) {
|
|
1540
2017
|
const rings = [];
|
|
@@ -1720,6 +2197,107 @@ export class Interp {
|
|
|
1720
2197
|
}
|
|
1721
2198
|
return out;
|
|
1722
2199
|
}
|
|
2200
|
+
bChr(argv, c, pos) {
|
|
2201
|
+
if (c !== null)
|
|
2202
|
+
throw new FormaError("chr doesn't take a { } block", pos);
|
|
2203
|
+
const a = new Args('chr', argv, pos, ['code'], ['code']);
|
|
2204
|
+
const n = a.number('code');
|
|
2205
|
+
if (!isWhole(n) || n < 0 || n > 0x10ffff) {
|
|
2206
|
+
throw new FormaError('chr: code must be a whole Unicode code point (0 to 1114111)', a.at('code'));
|
|
2207
|
+
}
|
|
2208
|
+
return String.fromCodePoint(n);
|
|
2209
|
+
}
|
|
2210
|
+
bOrd(argv, c, pos) {
|
|
2211
|
+
if (c !== null)
|
|
2212
|
+
throw new FormaError("ord doesn't take a { } block", pos);
|
|
2213
|
+
const a = new Args('ord', argv, pos, ['text'], ['text']);
|
|
2214
|
+
const s = a.raw('text');
|
|
2215
|
+
if (typeof s !== 'string' || s.length === 0) {
|
|
2216
|
+
throw new FormaError('ord needs a non-empty text string, like ord("A")', a.at('text'));
|
|
2217
|
+
}
|
|
2218
|
+
return new Q(s.codePointAt(0));
|
|
2219
|
+
}
|
|
2220
|
+
singleValueArg(name, argv, c, pos) {
|
|
2221
|
+
if (c !== null)
|
|
2222
|
+
throw new FormaError(`${name} doesn't take a { } block`, pos);
|
|
2223
|
+
const a = new Args(name, argv, pos, ['value'], ['value']);
|
|
2224
|
+
return a.raw('value');
|
|
2225
|
+
}
|
|
2226
|
+
bTypeOf(argv, c, pos) {
|
|
2227
|
+
const v = this.singleValueArg('typeOf', argv, c, pos);
|
|
2228
|
+
if (v instanceof Q) {
|
|
2229
|
+
if (v.dim === null)
|
|
2230
|
+
return 'Number';
|
|
2231
|
+
if (v.dim === 'len')
|
|
2232
|
+
return 'Length';
|
|
2233
|
+
if (v.dim === 'area')
|
|
2234
|
+
return 'Area';
|
|
2235
|
+
if (v.dim === 'vol')
|
|
2236
|
+
return 'Volume';
|
|
2237
|
+
return 'Angle';
|
|
2238
|
+
}
|
|
2239
|
+
if (typeof v === 'string')
|
|
2240
|
+
return 'String';
|
|
2241
|
+
if (typeof v === 'boolean')
|
|
2242
|
+
return 'Bool';
|
|
2243
|
+
if (isList(v))
|
|
2244
|
+
return 'List';
|
|
2245
|
+
if (v instanceof Shape)
|
|
2246
|
+
return 'Shape';
|
|
2247
|
+
if (v instanceof Enum)
|
|
2248
|
+
return 'Enum';
|
|
2249
|
+
if (v instanceof FontValue)
|
|
2250
|
+
return 'Font';
|
|
2251
|
+
if (v instanceof LayerValue)
|
|
2252
|
+
return 'Layer';
|
|
2253
|
+
if (v instanceof RangeValue)
|
|
2254
|
+
return 'Range';
|
|
2255
|
+
if (v instanceof RandomValue)
|
|
2256
|
+
return 'Random';
|
|
2257
|
+
if (v instanceof StructInstance)
|
|
2258
|
+
return v.type.name;
|
|
2259
|
+
if (v instanceof FunctionValue || v instanceof Builtin || v instanceof Closure)
|
|
2260
|
+
return 'Function';
|
|
2261
|
+
if (v instanceof Component)
|
|
2262
|
+
return 'Component';
|
|
2263
|
+
return typename(v);
|
|
2264
|
+
}
|
|
2265
|
+
bIsNumber(argv, c, pos) {
|
|
2266
|
+
const v = this.singleValueArg('isNumber', argv, c, pos);
|
|
2267
|
+
return v instanceof Q && v.dim === null;
|
|
2268
|
+
}
|
|
2269
|
+
bIsLength(argv, c, pos) {
|
|
2270
|
+
const v = this.singleValueArg('isLength', argv, c, pos);
|
|
2271
|
+
return v instanceof Q && v.dim === 'len';
|
|
2272
|
+
}
|
|
2273
|
+
bIsAngle(argv, c, pos) {
|
|
2274
|
+
const v = this.singleValueArg('isAngle', argv, c, pos);
|
|
2275
|
+
return v instanceof Q && v.dim === 'angle';
|
|
2276
|
+
}
|
|
2277
|
+
bIsArea(argv, c, pos) {
|
|
2278
|
+
const v = this.singleValueArg('isArea', argv, c, pos);
|
|
2279
|
+
return v instanceof Q && v.dim === 'area';
|
|
2280
|
+
}
|
|
2281
|
+
bIsVolume(argv, c, pos) {
|
|
2282
|
+
const v = this.singleValueArg('isVolume', argv, c, pos);
|
|
2283
|
+
return v instanceof Q && v.dim === 'vol';
|
|
2284
|
+
}
|
|
2285
|
+
bIsString(argv, c, pos) {
|
|
2286
|
+
return typeof this.singleValueArg('isString', argv, c, pos) === 'string';
|
|
2287
|
+
}
|
|
2288
|
+
bIsBool(argv, c, pos) {
|
|
2289
|
+
return typeof this.singleValueArg('isBool', argv, c, pos) === 'boolean';
|
|
2290
|
+
}
|
|
2291
|
+
bIsFunction(argv, c, pos) {
|
|
2292
|
+
const v = this.singleValueArg('isFunction', argv, c, pos);
|
|
2293
|
+
return v instanceof Closure || v instanceof FunctionValue || v instanceof Builtin;
|
|
2294
|
+
}
|
|
2295
|
+
bIsList(argv, c, pos) {
|
|
2296
|
+
return isList(this.singleValueArg('isList', argv, c, pos));
|
|
2297
|
+
}
|
|
2298
|
+
bIsShape(argv, c, pos) {
|
|
2299
|
+
return this.singleValueArg('isShape', argv, c, pos) instanceof Shape;
|
|
2300
|
+
}
|
|
1723
2301
|
// ---- methods ---------------------------------------------------------------------------------
|
|
1724
2302
|
callMethod(obj, name, argv, clo, pos) {
|
|
1725
2303
|
if (obj instanceof Module) {
|
|
@@ -1740,20 +2318,207 @@ export class Interp {
|
|
|
1740
2318
|
}
|
|
1741
2319
|
throw new FormaError(`a font has no method '${name}'${suggest(name, ['text'])}`, pos);
|
|
1742
2320
|
}
|
|
1743
|
-
if (isList(obj) && (name === 'map' || name === 'filter'
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
}
|
|
1756
|
-
|
|
2321
|
+
if (isList(obj) && (name === 'map' || name === 'filter' || name === 'contains' || name === 'firstIndex'
|
|
2322
|
+
|| name === 'find' || name === 'reverse' || name === 'sort' || name === 'reduce' || name === 'join')) {
|
|
2323
|
+
if (name === 'map') {
|
|
2324
|
+
if (clo !== null && !argv.length)
|
|
2325
|
+
return obj.map((x) => this.closureValue(clo, [x]));
|
|
2326
|
+
if (clo === null && argv.length === 1 && !argv[0][0]) {
|
|
2327
|
+
const fn = argv[0][1];
|
|
2328
|
+
if (fn instanceof Closure || fn instanceof FunctionValue || fn instanceof Builtin) {
|
|
2329
|
+
return obj.map((x) => this.call(fn, [[null, x, pos]], null, pos));
|
|
2330
|
+
}
|
|
2331
|
+
}
|
|
2332
|
+
throw new FormaError('.map needs a block or function: list.map { item in ... }', pos);
|
|
2333
|
+
}
|
|
2334
|
+
if (name === 'filter') {
|
|
2335
|
+
const pred = (x) => {
|
|
2336
|
+
if (clo !== null && !argv.length)
|
|
2337
|
+
return this.closureValue(clo, [x]);
|
|
2338
|
+
if (clo === null && argv.length === 1 && !argv[0][0]) {
|
|
2339
|
+
const fn = argv[0][1];
|
|
2340
|
+
if (fn instanceof Closure || fn instanceof FunctionValue || fn instanceof Builtin) {
|
|
2341
|
+
return this.call(fn, [[null, x, pos]], null, pos);
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
throw new FormaError('.filter needs a block or function: list.filter { item in ... }', pos);
|
|
2345
|
+
};
|
|
2346
|
+
if (clo === null && !(argv.length === 1 && !argv[0][0])) {
|
|
2347
|
+
throw new FormaError('.filter needs a block or function: list.filter { item in ... }', pos);
|
|
2348
|
+
}
|
|
2349
|
+
const out = [];
|
|
2350
|
+
for (const x of obj) {
|
|
2351
|
+
const keepIt = pred(x);
|
|
2352
|
+
if (typeof keepIt !== 'boolean')
|
|
2353
|
+
throw new FormaError(`.filter block must give true/false, got ${typename(keepIt)}`, clo ? clo.pos : pos);
|
|
2354
|
+
if (keepIt)
|
|
2355
|
+
out.push(x);
|
|
2356
|
+
}
|
|
2357
|
+
return out;
|
|
2358
|
+
}
|
|
2359
|
+
if (name === 'contains') {
|
|
2360
|
+
if (clo !== null)
|
|
2361
|
+
throw new FormaError(".contains doesn't take a { } block", pos);
|
|
2362
|
+
const a = new Args('.contains', argv, pos, ['of', 'value'], ['of']);
|
|
2363
|
+
const target = a.has('of') ? a.raw('of') : a.raw('value');
|
|
2364
|
+
return obj.some((x) => pyEquals(x, target));
|
|
2365
|
+
}
|
|
2366
|
+
if (name === 'firstIndex') {
|
|
2367
|
+
if (clo !== null) {
|
|
2368
|
+
if (argv.length)
|
|
2369
|
+
throw new FormaError('.firstIndex with a block takes no arguments: list.firstIndex { x in ... }', pos);
|
|
2370
|
+
for (let i = 0; i < obj.length; i++) {
|
|
2371
|
+
const ok = this.closureValue(clo, [obj[i]]);
|
|
2372
|
+
if (typeof ok !== 'boolean')
|
|
2373
|
+
throw new FormaError(`.firstIndex block must give true/false, got ${typename(ok)}`, clo.pos);
|
|
2374
|
+
if (ok)
|
|
2375
|
+
return new Q(i);
|
|
2376
|
+
}
|
|
2377
|
+
return new Q(-1);
|
|
2378
|
+
}
|
|
2379
|
+
const a = new Args('.firstIndex', argv, pos, ['of', 'value'], ['of']);
|
|
2380
|
+
const target = a.has('of') ? a.raw('of') : a.raw('value');
|
|
2381
|
+
const idx = obj.findIndex((x) => pyEquals(x, target));
|
|
2382
|
+
return new Q(idx);
|
|
2383
|
+
}
|
|
2384
|
+
if (name === 'find') {
|
|
2385
|
+
if (clo === null)
|
|
2386
|
+
throw new FormaError('.find needs a block: list.find { item in ... }', pos);
|
|
2387
|
+
const a = new Args('.find', argv, pos, ['default'], ['default']);
|
|
2388
|
+
for (const x of obj) {
|
|
2389
|
+
const ok = this.closureValue(clo, [x]);
|
|
2390
|
+
if (typeof ok !== 'boolean')
|
|
2391
|
+
throw new FormaError(`.find block must give true/false, got ${typename(ok)}`, clo.pos);
|
|
2392
|
+
if (ok)
|
|
2393
|
+
return x;
|
|
2394
|
+
}
|
|
2395
|
+
if (a.has('default'))
|
|
2396
|
+
return a.raw('default');
|
|
2397
|
+
throw new FormaError('.find: no matching item found (pass default: ... or check with .contains / .firstIndex)', pos);
|
|
2398
|
+
}
|
|
2399
|
+
if (name === 'reverse') {
|
|
2400
|
+
if (clo !== null || argv.length)
|
|
2401
|
+
throw new FormaError('.reverse() takes no arguments', pos);
|
|
2402
|
+
return [...obj].reverse();
|
|
2403
|
+
}
|
|
2404
|
+
if (name === 'sort') {
|
|
2405
|
+
if (argv.length)
|
|
2406
|
+
throw new FormaError('.sort takes no arguments (use .sort() or .sort { a, b in a < b })', pos);
|
|
2407
|
+
const copy = [...obj];
|
|
2408
|
+
if (clo !== null) {
|
|
2409
|
+
copy.sort((x, y) => {
|
|
2410
|
+
const before = this.closureValue(clo, [x, y]);
|
|
2411
|
+
if (typeof before !== 'boolean')
|
|
2412
|
+
throw new FormaError(`.sort block must give true/false, got ${typename(before)}`, clo.pos);
|
|
2413
|
+
if (before)
|
|
2414
|
+
return -1;
|
|
2415
|
+
const after = this.closureValue(clo, [y, x]);
|
|
2416
|
+
if (typeof after !== 'boolean')
|
|
2417
|
+
throw new FormaError(`.sort block must give true/false, got ${typename(after)}`, clo.pos);
|
|
2418
|
+
return after ? 1 : 0;
|
|
2419
|
+
});
|
|
2420
|
+
return copy;
|
|
2421
|
+
}
|
|
2422
|
+
if (copy.length <= 1)
|
|
2423
|
+
return copy;
|
|
2424
|
+
if (copy.every((x) => typeof x === 'string')) {
|
|
2425
|
+
return copy.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
2426
|
+
}
|
|
2427
|
+
if (copy.every((x) => isQ(x))) {
|
|
2428
|
+
const dim = copy[0].dim;
|
|
2429
|
+
if (!copy.every((x) => x.dim === dim)) {
|
|
2430
|
+
throw new FormaError('.sort() cannot mix different units in one list', pos);
|
|
2431
|
+
}
|
|
2432
|
+
return copy.sort((a, b) => a.v - b.v);
|
|
2433
|
+
}
|
|
2434
|
+
throw new FormaError('.sort() without a block works on numbers, quantities of the same unit, or text (pass { a, b in ... } for custom sorting)', pos);
|
|
2435
|
+
}
|
|
2436
|
+
if (name === 'reduce') {
|
|
2437
|
+
if (clo === null)
|
|
2438
|
+
throw new FormaError('.reduce needs a block: list.reduce(0) { acc, item in acc + item }', pos);
|
|
2439
|
+
const a = new Args('.reduce', argv, pos, ['initial'], ['initial']);
|
|
2440
|
+
let acc = a.raw('initial');
|
|
2441
|
+
for (const x of obj)
|
|
2442
|
+
acc = this.closureValue(clo, [acc, x]);
|
|
2443
|
+
return acc;
|
|
2444
|
+
}
|
|
2445
|
+
// join
|
|
2446
|
+
if (clo !== null)
|
|
2447
|
+
throw new FormaError(".join doesn't take a { } block", pos);
|
|
2448
|
+
const a = new Args('.join', argv, pos, ['by', 'sep'], ['by']);
|
|
2449
|
+
const sep = a.has('by') ? a.raw('by') : a.has('sep') ? a.raw('sep') : '';
|
|
2450
|
+
if (typeof sep !== 'string')
|
|
2451
|
+
throw new FormaError('.join separator must be text, like .join(", ")', pos);
|
|
2452
|
+
return obj.map(show).join(sep);
|
|
2453
|
+
}
|
|
2454
|
+
if (obj instanceof StructInstance) {
|
|
2455
|
+
if (clo !== null)
|
|
2456
|
+
throw new FormaError(`.${name} on ${obj.type.name} doesn't take a { } block`, pos);
|
|
2457
|
+
if (name === 'with') {
|
|
2458
|
+
const names = obj.type.fields.map((f) => f[0]);
|
|
2459
|
+
const a = new Args(`${obj.type.name}.with`, argv, pos, names);
|
|
2460
|
+
const next = new Map(obj.fields);
|
|
2461
|
+
for (const fname of names) {
|
|
2462
|
+
if (a.has(fname))
|
|
2463
|
+
next.set(fname, a.raw(fname));
|
|
2464
|
+
}
|
|
2465
|
+
return new StructInstance(obj.type, next);
|
|
2466
|
+
}
|
|
2467
|
+
const method = obj.type.methods.get(name);
|
|
2468
|
+
if (!method) {
|
|
2469
|
+
const avail = ['with', ...obj.type.methods.keys()];
|
|
2470
|
+
throw new FormaError(`${obj.type.name} has no method '${name}'${suggest(name, avail)}. Available: ${avail.join(', ')}`, pos);
|
|
2471
|
+
}
|
|
2472
|
+
const boundEnv = new Env(method.env);
|
|
2473
|
+
boundEnv.define('self', obj, pos);
|
|
2474
|
+
for (const [k, v] of obj.fields)
|
|
2475
|
+
boundEnv.define(k, v, pos);
|
|
2476
|
+
const boundFn = new FunctionValue(method.name, method.params, method.body, boundEnv, method.pos);
|
|
2477
|
+
return this.callFunction(boundFn, argv, null, pos);
|
|
2478
|
+
}
|
|
2479
|
+
if (obj instanceof RandomValue) {
|
|
2480
|
+
if (clo !== null)
|
|
2481
|
+
throw new FormaError(`.${name} on Random doesn't take a { } block`, pos);
|
|
2482
|
+
if (name === 'next') {
|
|
2483
|
+
const [lo, hi] = this.randomBounds('.next', argv, pos);
|
|
2484
|
+
return new Q(lo.v + obj.nextUnit() * (hi.v - lo.v), lo.dim);
|
|
2485
|
+
}
|
|
2486
|
+
if (name === 'int') {
|
|
2487
|
+
const [lo, hi] = this.randomBounds('.int', argv, pos, new Q(0), new Q(1));
|
|
2488
|
+
if (lo.dim !== null || hi.dim !== null || !isWhole(lo.v) || !isWhole(hi.v)) {
|
|
2489
|
+
throw new FormaError(`.int needs whole plain numbers, like .int(in: 1...6), got ${lo}...${hi}`, pos);
|
|
2490
|
+
}
|
|
2491
|
+
const span = hi.v - lo.v + 1;
|
|
2492
|
+
return new Q(lo.v + Math.floor(obj.nextUnit() * span));
|
|
2493
|
+
}
|
|
2494
|
+
if (name === 'bool') {
|
|
2495
|
+
const a = new Args('.bool', argv, pos, ['chance'], ['chance']);
|
|
2496
|
+
const chance = a.number('chance', 0.5);
|
|
2497
|
+
if (chance < 0 || chance > 1)
|
|
2498
|
+
throw new FormaError('.bool: chance: must be between 0 and 1', pos);
|
|
2499
|
+
return obj.nextUnit() < chance;
|
|
2500
|
+
}
|
|
2501
|
+
if (name === 'pick') {
|
|
2502
|
+
const a = new Args('.pick', argv, pos, ['from', 'list'], ['from']);
|
|
2503
|
+
const raw = a.has('from') ? a.raw('from') : a.raw('list');
|
|
2504
|
+
if (!isList(raw) || raw.length === 0)
|
|
2505
|
+
throw new FormaError('.pick needs a non-empty list, like .pick([.red, .blue])', pos);
|
|
2506
|
+
return raw[Math.floor(obj.nextUnit() * raw.length)];
|
|
2507
|
+
}
|
|
2508
|
+
if (name === 'list') {
|
|
2509
|
+
const a = new Args('.list', argv, pos, ['count', 'in', 'min', 'max'], ['count', 'in']);
|
|
2510
|
+
const count = a.number('count');
|
|
2511
|
+
if (!isWhole(count) || count < 0)
|
|
2512
|
+
throw new FormaError('.list: count: must be a whole number >= 0', a.at('count'));
|
|
2513
|
+
const subArgv = argv.filter(([lbl], idx) => lbl !== 'count' && !(lbl === null && idx === 0));
|
|
2514
|
+
const [lo, hi] = this.randomBounds('.list', subArgv, pos);
|
|
2515
|
+
const out = [];
|
|
2516
|
+
for (let i = 0; i < count; i++)
|
|
2517
|
+
out.push(new Q(lo.v + obj.nextUnit() * (hi.v - lo.v), lo.dim));
|
|
2518
|
+
return out;
|
|
2519
|
+
}
|
|
2520
|
+
const rm = ['next', 'int', 'bool', 'pick', 'list'];
|
|
2521
|
+
throw new FormaError(`Random has no method '${name}'${suggest(name, rm)}. Available: ${rm.join(', ')}`, pos);
|
|
1757
2522
|
}
|
|
1758
2523
|
if (typeof obj === 'string') {
|
|
1759
2524
|
if (clo !== null)
|
|
@@ -1816,18 +2581,13 @@ export class Interp {
|
|
|
1816
2581
|
const sm = ['upper', 'lower', 'trim', 'split', 'replace', 'chars', 'contains', 'startsWith', 'endsWith'];
|
|
1817
2582
|
throw new FormaError(`text has no method '${name}'${suggest(name, sm)}. Available: ${sm.join(', ')}`, pos);
|
|
1818
2583
|
}
|
|
1819
|
-
if (isList(obj) && name === 'join') {
|
|
1820
|
-
if (clo !== null)
|
|
1821
|
-
throw new FormaError(".join doesn't take a { } block", pos);
|
|
1822
|
-
const a = new Args('.join', argv, pos, ['by', 'sep'], ['by']);
|
|
1823
|
-
const sep = a.has('by') ? a.raw('by') : a.has('sep') ? a.raw('sep') : '';
|
|
1824
|
-
if (typeof sep !== 'string')
|
|
1825
|
-
throw new FormaError('.join separator must be text, like .join(", ")', pos);
|
|
1826
|
-
return obj.map(show).join(sep);
|
|
1827
|
-
}
|
|
1828
2584
|
if (!(obj instanceof Shape)) {
|
|
1829
|
-
if (isList(obj)
|
|
1830
|
-
|
|
2585
|
+
if (isList(obj)) {
|
|
2586
|
+
if (obj.length && obj.every((x) => x instanceof Shape) && SHAPE_METHODS.includes(name)) {
|
|
2587
|
+
return obj.map((x) => this.callMethod(x, name, argv, clo, pos));
|
|
2588
|
+
}
|
|
2589
|
+
const lm = ['map', 'filter', 'contains', 'firstIndex', 'find', 'reverse', 'sort', 'reduce', 'join'];
|
|
2590
|
+
throw new FormaError(`a list has no method '${name}'${suggest(name, lm)}. Available: ${lm.join(', ')}`, pos);
|
|
1831
2591
|
}
|
|
1832
2592
|
throw new FormaError(`${typename(obj)} has no method '${name}'`, pos);
|
|
1833
2593
|
}
|
|
@@ -1837,12 +2597,100 @@ export class Interp {
|
|
|
1837
2597
|
const flat = obj.is2d;
|
|
1838
2598
|
if (name === 'at' || name === 'move') {
|
|
1839
2599
|
const a = new Args('.' + name, argv, pos, ['x', 'y', 'z'], ['x', 'y', 'z']);
|
|
1840
|
-
if (flat && a.has('z'))
|
|
1841
|
-
throw new FormaError('a 2D shape has no z — extrude it first, then move it up', a.at('z'));
|
|
1842
2600
|
const d = [a.length('x', 0), a.length('y', 0), a.length('z', 0)];
|
|
1843
2601
|
const p = obj.pos;
|
|
1844
2602
|
return obj.derive({ pos: [p[0] + d[0], p[1] + d[1], p[2] + d[2]] });
|
|
1845
2603
|
}
|
|
2604
|
+
if (name === 'above' || name === 'below' || name === 'leftOf' || name === 'rightOf' || name === 'inFrontOf' || name === 'behind') {
|
|
2605
|
+
if (clo !== null)
|
|
2606
|
+
throw new FormaError(`.${name} doesn't take a { } block`, pos);
|
|
2607
|
+
const a = new Args('.' + name, argv, pos, ['to', 'gap'], ['to', 'gap']);
|
|
2608
|
+
const target = a.raw('to');
|
|
2609
|
+
if (!(target instanceof Shape))
|
|
2610
|
+
throw new FormaError(`.${name} needs another shape, like lid.${name}(base)`, a.at('to'));
|
|
2611
|
+
if ((name === 'above' || name === 'below') && (flat || target.is2d)) {
|
|
2612
|
+
throw new FormaError(`.${name} needs 3D shapes (2D shapes are flat in Z)`, pos);
|
|
2613
|
+
}
|
|
2614
|
+
const gap = a.length('gap', 0);
|
|
2615
|
+
const bbA = bboxOf(obj.world());
|
|
2616
|
+
const bbB = bboxOf(target.world());
|
|
2617
|
+
if (!bbA || !bbB)
|
|
2618
|
+
throw new FormaError(`.${name}: shape is empty`, pos);
|
|
2619
|
+
let dx = 0, dy = 0, dz = 0;
|
|
2620
|
+
if (name === 'above')
|
|
2621
|
+
dz = bbB[1][2] + gap - bbA[0][2];
|
|
2622
|
+
else if (name === 'below')
|
|
2623
|
+
dz = bbB[0][2] - gap - bbA[1][2];
|
|
2624
|
+
else if (name === 'rightOf')
|
|
2625
|
+
dx = bbB[1][0] + gap - bbA[0][0];
|
|
2626
|
+
else if (name === 'leftOf')
|
|
2627
|
+
dx = bbB[0][0] - gap - bbA[1][0];
|
|
2628
|
+
else if (name === 'behind')
|
|
2629
|
+
dy = bbB[1][1] + gap - bbA[0][1];
|
|
2630
|
+
else if (name === 'inFrontOf')
|
|
2631
|
+
dy = bbB[0][1] - gap - bbA[1][1];
|
|
2632
|
+
return obj.derive({ pos: [obj.pos[0] + dx, obj.pos[1] + dy, obj.pos[2] + dz] });
|
|
2633
|
+
}
|
|
2634
|
+
if (name === 'align') {
|
|
2635
|
+
if (clo !== null)
|
|
2636
|
+
throw new FormaError(".align doesn't take a { } block", pos);
|
|
2637
|
+
const a = new Args('.align', argv, pos, ['to', 'x', 'y', 'z', 'gap'], ['to']);
|
|
2638
|
+
const target = a.raw('to');
|
|
2639
|
+
if (!(target instanceof Shape))
|
|
2640
|
+
throw new FormaError('.align needs another shape: part.align(x: .center, z: .top, to: base)', a.at('to'));
|
|
2641
|
+
if (!a.has('x') && !a.has('y') && !a.has('z')) {
|
|
2642
|
+
throw new FormaError('.align needs at least one axis (x:, y:, or z:)', pos);
|
|
2643
|
+
}
|
|
2644
|
+
if (a.has('z') && (flat || target.is2d)) {
|
|
2645
|
+
throw new FormaError('.align: z: is only for 3D shapes', a.at('z'));
|
|
2646
|
+
}
|
|
2647
|
+
const gap = a.length('gap', 0);
|
|
2648
|
+
const bbA = bboxOf(obj.world());
|
|
2649
|
+
const bbB = bboxOf(target.world());
|
|
2650
|
+
if (!bbA || !bbB)
|
|
2651
|
+
throw new FormaError('.align: shape is empty', pos);
|
|
2652
|
+
let dx = 0, dy = 0, dz = 0;
|
|
2653
|
+
if (a.has('x')) {
|
|
2654
|
+
const mode = this.parseEnumOption(a.raw('x'), ['left', 'center', 'right', 'leftOf', 'rightOf'], '.align: x:', a.at('x'));
|
|
2655
|
+
if (mode === 'left')
|
|
2656
|
+
dx = bbB[0][0] + gap - bbA[0][0];
|
|
2657
|
+
else if (mode === 'right')
|
|
2658
|
+
dx = bbB[1][0] - gap - bbA[1][0];
|
|
2659
|
+
else if (mode === 'center')
|
|
2660
|
+
dx = (bbB[0][0] + bbB[1][0]) / 2 - (bbA[0][0] + bbA[1][0]) / 2;
|
|
2661
|
+
else if (mode === 'leftOf')
|
|
2662
|
+
dx = bbB[0][0] - gap - bbA[1][0];
|
|
2663
|
+
else
|
|
2664
|
+
dx = bbB[1][0] + gap - bbA[0][0];
|
|
2665
|
+
}
|
|
2666
|
+
if (a.has('y')) {
|
|
2667
|
+
const mode = this.parseEnumOption(a.raw('y'), ['front', 'center', 'back', 'inFrontOf', 'behind'], '.align: y:', a.at('y'));
|
|
2668
|
+
if (mode === 'front')
|
|
2669
|
+
dy = bbB[0][1] + gap - bbA[0][1];
|
|
2670
|
+
else if (mode === 'back')
|
|
2671
|
+
dy = bbB[1][1] - gap - bbA[1][1];
|
|
2672
|
+
else if (mode === 'center')
|
|
2673
|
+
dy = (bbB[0][1] + bbB[1][1]) / 2 - (bbA[0][1] + bbA[1][1]) / 2;
|
|
2674
|
+
else if (mode === 'inFrontOf')
|
|
2675
|
+
dy = bbB[0][1] - gap - bbA[1][1];
|
|
2676
|
+
else
|
|
2677
|
+
dy = bbB[1][1] + gap - bbA[0][1];
|
|
2678
|
+
}
|
|
2679
|
+
if (a.has('z')) {
|
|
2680
|
+
const mode = this.parseEnumOption(a.raw('z'), ['bottom', 'center', 'top', 'below', 'above'], '.align: z:', a.at('z'));
|
|
2681
|
+
if (mode === 'bottom')
|
|
2682
|
+
dz = bbB[0][2] + gap - bbA[0][2];
|
|
2683
|
+
else if (mode === 'top')
|
|
2684
|
+
dz = bbB[1][2] - gap - bbA[1][2];
|
|
2685
|
+
else if (mode === 'center')
|
|
2686
|
+
dz = (bbB[0][2] + bbB[1][2]) / 2 - (bbA[0][2] + bbA[1][2]) / 2;
|
|
2687
|
+
else if (mode === 'below')
|
|
2688
|
+
dz = bbB[0][2] - gap - bbA[1][2];
|
|
2689
|
+
else
|
|
2690
|
+
dz = bbB[1][2] + gap - bbA[0][2];
|
|
2691
|
+
}
|
|
2692
|
+
return obj.derive({ pos: [obj.pos[0] + dx, obj.pos[1] + dy, obj.pos[2] + dz] });
|
|
2693
|
+
}
|
|
1846
2694
|
if (name === 'rotate') {
|
|
1847
2695
|
const a = new Args('.rotate', argv, pos, ['x', 'y', 'z', 'by', 'around']);
|
|
1848
2696
|
if (!argv.length)
|
|
@@ -1970,6 +2818,63 @@ export class Interp {
|
|
|
1970
2818
|
const S = [0, 1, 2].map((i) => [0, 1, 2].map((j) => (i === j ? (i === ax ? -1 : 1) : 0)));
|
|
1971
2819
|
return obj.derive({ M: matMul(S, obj.M) });
|
|
1972
2820
|
}
|
|
2821
|
+
if (name === 'transform') {
|
|
2822
|
+
const a = new Args('.transform', argv, pos, ['matrix'], ['matrix']);
|
|
2823
|
+
const raw = a.raw('matrix');
|
|
2824
|
+
const mpos = a.at('matrix');
|
|
2825
|
+
if (!isList(raw) || (raw.length !== 3 && raw.length !== 4)) {
|
|
2826
|
+
throw new FormaError('.transform(matrix:) needs a 3×4 or 4×4 list of rows', mpos);
|
|
2827
|
+
}
|
|
2828
|
+
const A = [];
|
|
2829
|
+
const t = [0, 0, 0];
|
|
2830
|
+
for (let r = 0; r < 3; r++) {
|
|
2831
|
+
const row = raw[r];
|
|
2832
|
+
if (!isList(row) || row.length !== 4) {
|
|
2833
|
+
throw new FormaError(`.transform: row ${r} must be a list of 4 values`, mpos);
|
|
2834
|
+
}
|
|
2835
|
+
const mRow = [];
|
|
2836
|
+
for (let c = 0; c < 3; c++) {
|
|
2837
|
+
const cell = row[c];
|
|
2838
|
+
if (!isQ(cell) || cell.dim !== null || !Number.isFinite(cell.v)) {
|
|
2839
|
+
throw new FormaError(`.transform: matrix[${r}][${c}] must be a dimensionless number, got ${typename(cell)}`, mpos);
|
|
2840
|
+
}
|
|
2841
|
+
mRow.push(cell.v);
|
|
2842
|
+
}
|
|
2843
|
+
const tr = row[3];
|
|
2844
|
+
if (!isQ(tr) || !Number.isFinite(tr.v) || (tr.dim !== 'len' && !(tr.dim === null && tr.v === 0))) {
|
|
2845
|
+
throw new FormaError(`.transform: translation matrix[${r}][3] needs a length (e.g. 10mm or 0), got ${typename(tr)}`, mpos);
|
|
2846
|
+
}
|
|
2847
|
+
t[r] = tr.v;
|
|
2848
|
+
A.push(mRow);
|
|
2849
|
+
}
|
|
2850
|
+
if (raw.length === 4) {
|
|
2851
|
+
const last = raw[3];
|
|
2852
|
+
if (!isList(last) || last.length !== 4) {
|
|
2853
|
+
throw new FormaError('.transform: 4th row must be [0, 0, 0, 1]', mpos);
|
|
2854
|
+
}
|
|
2855
|
+
const exp = [0, 0, 0, 1];
|
|
2856
|
+
for (let c = 0; c < 4; c++) {
|
|
2857
|
+
const cell = last[c];
|
|
2858
|
+
if (!isQ(cell) || cell.dim !== null || Math.abs(cell.v - exp[c]) > 1e-9) {
|
|
2859
|
+
throw new FormaError('.transform: 4th row must be [0, 0, 0, 1] (projective transforms are not supported)', mpos);
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2862
|
+
}
|
|
2863
|
+
const mat3 = A;
|
|
2864
|
+
if (Math.abs(matDet(mat3)) < 1e-12) {
|
|
2865
|
+
throw new FormaError('.transform: matrix is singular (determinant is 0)', mpos);
|
|
2866
|
+
}
|
|
2867
|
+
if (flat && (Math.abs(mat3[2][0]) > 1e-9 || Math.abs(mat3[2][1]) > 1e-9 || Math.abs(t[2]) > 1e-9)) {
|
|
2868
|
+
throw new FormaError('.transform: a 2D shape cannot be tilted or moved in Z — extrude it first', mpos);
|
|
2869
|
+
}
|
|
2870
|
+
const [px, py, pz] = obj.pos;
|
|
2871
|
+
const newPos = [
|
|
2872
|
+
mat3[0][0] * px + mat3[0][1] * py + mat3[0][2] * pz + t[0],
|
|
2873
|
+
mat3[1][0] * px + mat3[1][1] * py + mat3[1][2] * pz + t[1],
|
|
2874
|
+
mat3[2][0] * px + mat3[2][1] * py + mat3[2][2] * pz + t[2],
|
|
2875
|
+
];
|
|
2876
|
+
return obj.derive({ M: matMul(mat3, obj.M), pos: newPos, meta: null });
|
|
2877
|
+
}
|
|
1973
2878
|
if (name === 'color') {
|
|
1974
2879
|
if (!argv.length || argv[0][0] !== null) {
|
|
1975
2880
|
throw new FormaError('.color needs a color, like .color(.orange) or .color("#ff8800", opacity: 0.5)', pos);
|
|
@@ -2008,6 +2913,75 @@ export class Interp {
|
|
|
2008
2913
|
if (name === 'fillet' || name === 'chamfer') {
|
|
2009
2914
|
return this.doBevel(obj, name, argv, pos);
|
|
2010
2915
|
}
|
|
2916
|
+
if (name === 'shell') {
|
|
2917
|
+
if (clo !== null)
|
|
2918
|
+
throw new FormaError(".shell doesn't take a { } block", pos);
|
|
2919
|
+
if (flat)
|
|
2920
|
+
throw new FormaError('.shell is for 3D shapes — extrude it first, or use .offset() for 2D', pos);
|
|
2921
|
+
const a = new Args('.shell', argv, pos, ['wall', 'open'], ['wall', 'open']);
|
|
2922
|
+
const wall = a.length('wall');
|
|
2923
|
+
const openSet = new Set();
|
|
2924
|
+
if (a.has('open')) {
|
|
2925
|
+
const raw = a.raw('open');
|
|
2926
|
+
const items = isList(raw) ? raw : [raw];
|
|
2927
|
+
for (const item of items) {
|
|
2928
|
+
const face = this.parseEnumOption(item, SHELL_FACES, '.shell: open:', a.at('open'));
|
|
2929
|
+
if (face !== 'none')
|
|
2930
|
+
openSet.add(face);
|
|
2931
|
+
}
|
|
2932
|
+
}
|
|
2933
|
+
const shelled = shell3d(obj.polys, wall, openSet, obj.meta, pos);
|
|
2934
|
+
return obj.derive({ polys: shelled, meta: null });
|
|
2935
|
+
}
|
|
2936
|
+
if (name === 'sweep') {
|
|
2937
|
+
if (clo !== null)
|
|
2938
|
+
throw new FormaError(".sweep doesn't take a { } block", pos);
|
|
2939
|
+
if (!flat)
|
|
2940
|
+
throw new FormaError('.sweep is for 2D shapes like Circle or Rect', pos);
|
|
2941
|
+
const a = new Args('.sweep', argv, pos, ['path', 'closed', 'twist', 'scale', 'smooth'], ['path']);
|
|
2942
|
+
const rawPath = a.raw('path');
|
|
2943
|
+
if (!isList(rawPath) || rawPath.length < 2) {
|
|
2944
|
+
throw new FormaError('.sweep: path: must be a list of 3D points like [[0mm, 0mm, 0mm], [0mm, 0mm, 30mm]]', a.at('path'));
|
|
2945
|
+
}
|
|
2946
|
+
const ptLen = (v, label) => {
|
|
2947
|
+
if (isQ(v) && (v.dim === 'len' || v.dim === null))
|
|
2948
|
+
return v.v;
|
|
2949
|
+
throw new FormaError(`${label} must be a length, got ${typename(v)}`, a.at('path'));
|
|
2950
|
+
};
|
|
2951
|
+
const pts = rawPath.map((pt, idx) => {
|
|
2952
|
+
if (!isList(pt) || pt.length !== 3) {
|
|
2953
|
+
throw new FormaError(`.sweep: path point ${idx} must be [x, y, z]`, a.at('path'));
|
|
2954
|
+
}
|
|
2955
|
+
return [
|
|
2956
|
+
ptLen(pt[0], `.sweep: path[${idx}].x`),
|
|
2957
|
+
ptLen(pt[1], `.sweep: path[${idx}].y`),
|
|
2958
|
+
ptLen(pt[2], `.sweep: path[${idx}].z`),
|
|
2959
|
+
];
|
|
2960
|
+
});
|
|
2961
|
+
const closed = a.flag('closed', false);
|
|
2962
|
+
const twistRad = a.has('twist') ? (a.angle('twist') * Math.PI) / 180 : 0;
|
|
2963
|
+
const smooth = a.flag('smooth', false);
|
|
2964
|
+
let scaleEnd = [1, 1];
|
|
2965
|
+
if (a.has('scale')) {
|
|
2966
|
+
const sv = a.raw('scale');
|
|
2967
|
+
if (isQ(sv) && sv.dim === null) {
|
|
2968
|
+
if (sv.v <= 0)
|
|
2969
|
+
throw new FormaError('.sweep: scale: must be greater than 0', a.at('scale'));
|
|
2970
|
+
scaleEnd = [sv.v, sv.v];
|
|
2971
|
+
}
|
|
2972
|
+
else if (isList(sv) && sv.length === 2 && isQ(sv[0]) && sv[0].dim === null && isQ(sv[1]) && sv[1].dim === null) {
|
|
2973
|
+
if (sv[0].v <= 0 || sv[1].v <= 0)
|
|
2974
|
+
throw new FormaError('.sweep: scale: values must be greater than 0', a.at('scale'));
|
|
2975
|
+
scaleEnd = [sv[0].v, sv[1].v];
|
|
2976
|
+
}
|
|
2977
|
+
else {
|
|
2978
|
+
throw new FormaError('.sweep: scale: must be a number or [sx, sy]', a.at('scale'));
|
|
2979
|
+
}
|
|
2980
|
+
}
|
|
2981
|
+
const profilePolys = obj.derive({ pos: [obj.pos[0], obj.pos[1], 0] }).world();
|
|
2982
|
+
const swept = sweep3d(profilePolys, pts, { closed, twistRad, scaleEnd, smooth }, pos);
|
|
2983
|
+
return new Shape(swept, undefined, undefined, obj.color, false, null, obj.layer);
|
|
2984
|
+
}
|
|
2011
2985
|
throw new FormaError(`internal: method '${name}'`, pos);
|
|
2012
2986
|
}
|
|
2013
2987
|
}
|
|
@@ -2015,8 +2989,20 @@ export class Interp {
|
|
|
2015
2989
|
function pyEquals(a, b) {
|
|
2016
2990
|
if (typeof a !== typeof b)
|
|
2017
2991
|
return false;
|
|
2992
|
+
if (isQ(a) && isQ(b))
|
|
2993
|
+
return a.dim === b.dim && Math.abs(a.v - b.v) <= 1e-9;
|
|
2994
|
+
if (a instanceof Enum && b instanceof Enum)
|
|
2995
|
+
return a.name === b.name;
|
|
2996
|
+
if (a instanceof StructInstance && b instanceof StructInstance) {
|
|
2997
|
+
if (a.type !== b.type || a.fields.size !== b.fields.size)
|
|
2998
|
+
return false;
|
|
2999
|
+
for (const [k, v] of a.fields)
|
|
3000
|
+
if (!pyEquals(v, b.fields.get(k)))
|
|
3001
|
+
return false;
|
|
3002
|
+
return true;
|
|
3003
|
+
}
|
|
2018
3004
|
if (isList(a) && isList(b))
|
|
2019
|
-
return a.length === b.length && a.every((x, i) =>
|
|
3005
|
+
return a.length === b.length && a.every((x, i) => pyEquals(x, b[i]));
|
|
2020
3006
|
if (isList(a) !== isList(b))
|
|
2021
3007
|
return false;
|
|
2022
3008
|
if (a !== null && typeof a === 'object' && b !== null && typeof b === 'object' && a.constructor !== b.constructor)
|