@toolpath/dfm 0.5.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.
@@ -1,3 +1,23 @@
1
+ // src/model/dfm-metrics.ts
2
+ import { MM_PER_INCH } from "@toolpath/tool-support";
3
+
4
+ // src/model/direction-label.ts
5
+ var EPSILON = 1e-6;
6
+ var trim = (value) => Number.parseFloat(value.toFixed(3)).toString();
7
+ var directionLabel = (direction) => {
8
+ const axes = [
9
+ ["X", direction.x],
10
+ ["Y", direction.y],
11
+ ["Z", direction.z]
12
+ ];
13
+ const nonZero = axes.filter(([, value]) => Math.abs(value) > EPSILON);
14
+ const [axis] = nonZero;
15
+ if (nonZero.length === 1 && axis && Math.abs(Math.abs(axis[1]) - 1) < EPSILON) {
16
+ return `${axis[1] > 0 ? "+" : "\u2212"}${axis[0]}`;
17
+ }
18
+ return axes.map(([, value]) => trim(value)).join(", ");
19
+ };
20
+
1
21
  // src/model/geometry.ts
2
22
  var dfmFeatures = (features) => {
3
23
  const read = features.map(
@@ -59,26 +79,6 @@ var featureLd = (features, feature, sheets) => {
59
79
  };
60
80
  };
61
81
 
62
- // src/model/dfm-metrics.ts
63
- import { MM_PER_INCH } from "@toolpath/tool-support";
64
-
65
- // src/model/direction-label.ts
66
- var EPSILON = 1e-6;
67
- var trim = (value) => Number.parseFloat(value.toFixed(3)).toString();
68
- var directionLabel = (direction) => {
69
- const axes = [
70
- ["X", direction.x],
71
- ["Y", direction.y],
72
- ["Z", direction.z]
73
- ];
74
- const nonZero = axes.filter(([, value]) => Math.abs(value) > EPSILON);
75
- const [axis] = nonZero;
76
- if (nonZero.length === 1 && axis && Math.abs(Math.abs(axis[1]) - 1) < EPSILON) {
77
- return `${axis[1] > 0 ? "+" : "\u2212"}${axis[0]}`;
78
- }
79
- return axes.map(([, value]) => trim(value)).join(", ");
80
- };
81
-
82
82
  // src/model/dfm-metrics.ts
83
83
  var define = ({ start, path, ...spec }) => ({
84
84
  ...spec,
@@ -1100,8 +1100,8 @@ import { MM_PER_INCH as MM_PER_INCH2 } from "@toolpath/tool-support";
1100
1100
  var LENGTH_PLACES = { mm: 3, inch: 3 };
1101
1101
  var FIELD_LENGTH_PLACES = { mm: 3, inch: 4 };
1102
1102
  var UNIT_LABELS = { mm: "mm", inch: "in" };
1103
- var inUnits = (mm, units) => units === "inch" ? mm / MM_PER_INCH2 : mm;
1104
- var lengthValue = (mm, units) => inUnits(mm, units).toFixed(LENGTH_PLACES[units]);
1103
+ var inUnits = (mm2, units) => units === "inch" ? mm2 / MM_PER_INCH2 : mm2;
1104
+ var lengthValue = (mm2, units) => inUnits(mm2, units).toFixed(LENGTH_PLACES[units]);
1105
1105
  var unitLabel = (units) => UNIT_LABELS[units];
1106
1106
 
1107
1107
  // src/model/dfm-rules.ts
@@ -1129,8 +1129,8 @@ var RULE_COLORS = [
1129
1129
  ];
1130
1130
  var compareColors = (a, b) => {
1131
1131
  const rank = (color) => {
1132
- const at = RULE_COLORS.findIndex((each) => each.value === color);
1133
- return at === -1 ? RULE_COLORS.length : at;
1132
+ const at2 = RULE_COLORS.findIndex((each) => each.value === color);
1133
+ return at2 === -1 ? RULE_COLORS.length : at2;
1134
1134
  };
1135
1135
  return rank(a) - rank(b) || (a < b ? -1 : a > b ? 1 : 0);
1136
1136
  };
@@ -1176,7 +1176,7 @@ var quantityUnit = (quantity, units) => {
1176
1176
  return "";
1177
1177
  }
1178
1178
  };
1179
- var withUnit = (value, unit) => unit === "" ? value : unit === "\xB0" || unit === "%" ? `${value}${unit}` : `${value} ${unit}`;
1179
+ var withUnit = (value, unit2) => unit2 === "" ? value : unit2 === "\xB0" || unit2 === "%" ? `${value}${unit2}` : `${value} ${unit2}`;
1180
1180
  var toUnits = (quantity, value, units) => units !== "inch" ? value : quantity === "length" ? value / MM_PER_INCH3 : quantity === "area" ? value / SQUARE_MM_PER_SQUARE_INCH : value;
1181
1181
  var toField = (quantity, value, units) => {
1182
1182
  const shown = toUnits(quantity, value, units);
@@ -1215,8 +1215,8 @@ var describeRule = (rule, units, vocabulary = MILLING_RULES) => {
1215
1215
  if (!info) return subject;
1216
1216
  if (info.quantity === "presence") return `${subject}, ${info.label}`;
1217
1217
  if (info.quantity === "flag") return `${subject} with ${info.label}`;
1218
- const unit = quantityUnit(info.quantity, units);
1219
- const shown = (value) => withUnit(toField(info.quantity, value, units), unit);
1218
+ const unit2 = quantityUnit(info.quantity, units);
1219
+ const shown = (value) => withUnit(toField(info.quantity, value, units), unit2);
1220
1220
  return rule.op === "between" ? `${subject} with ${shown(rule.value)} ${lowOf(rule) === "gt" ? "<" : "\u2264"} ${info.label} ${opSymbol(highOf(rule))} ${shown(upperOf(rule))}` : `${subject} with ${info.label} ${opSymbol(rule.op)} ${shown(rule.value)}`;
1221
1221
  };
1222
1222
  var newRuleId = () => Math.random().toString(36).slice(2, 10);
@@ -1298,6 +1298,985 @@ var parseRule = (raw, vocabulary) => {
1298
1298
  };
1299
1299
  var parseRules = (raw, vocabulary = MILLING_RULES) => Array.isArray(raw) ? raw.flatMap((each) => parseRule(each, vocabulary) ?? []) : null;
1300
1300
 
1301
+ // src/model/dfm-explain.ts
1302
+ var figureless = (hit) => hit.metric.quantity === "flag" || hit.metric.quantity === "presence";
1303
+ var hitFigure = (hit, units) => figureless(hit) ? "" : formatMeasured(hit.metric.quantity, hit.value, units);
1304
+
1305
+ // src/model/broken-rules.ts
1306
+ var byColor = (hits) => [...hits].sort((a, b) => compareColors(a.rule.color, b.rule.color));
1307
+ var worstHits = (hits) => {
1308
+ const seen = /* @__PURE__ */ new Set();
1309
+ return byColor(hits).filter((hit) => {
1310
+ if (seen.has(hit.metric.key)) return false;
1311
+ seen.add(hit.metric.key);
1312
+ return true;
1313
+ });
1314
+ };
1315
+ var brokenRules = (check, tag, units, vocabulary = MILLING_RULES) => worstHits(check.hitsByTag.get(tag.toLowerCase()) ?? []).map((hit) => {
1316
+ const figure = hitFigure(hit, units);
1317
+ return {
1318
+ key: hit.rule.id,
1319
+ color: hit.rule.color,
1320
+ text: describeRule(hit.rule, units, vocabulary),
1321
+ ...figure ? { figure } : {}
1322
+ };
1323
+ });
1324
+ var featureColor = (check, tag, region = null) => {
1325
+ const key = tag.toLowerCase();
1326
+ const face = region === null ? void 0 : check.paintedFaces.get(region);
1327
+ if (face && face.tag.toLowerCase() === key) return face.color;
1328
+ const whole = check.paintedWhole.get(key);
1329
+ if (whole) return whole.color;
1330
+ if (!check.required.has(key)) return void 0;
1331
+ return byColor(check.hitsByTag.get(key) ?? [])[0]?.rule.color;
1332
+ };
1333
+
1334
+ // src/model/dfm-flags.ts
1335
+ var howCut = (sheet) => {
1336
+ const drilled = isDrilled(sheet);
1337
+ return { drilled, milled: !drilled };
1338
+ };
1339
+ var featureIs = (subject, featureType, sheet) => {
1340
+ const type = featureType.toLowerCase();
1341
+ const kind = sheet?.kind?.toLowerCase() ?? "";
1342
+ if (subject.startsWith(TYPE_SUBJECT)) return type === subject.slice(TYPE_SUBJECT.length);
1343
+ switch (subject) {
1344
+ case "any":
1345
+ return true;
1346
+ case "milled":
1347
+ return howCut(sheet).milled;
1348
+ case "drilled":
1349
+ return howCut(sheet).drilled;
1350
+ case "hole":
1351
+ return type.includes("hole") || kind === "hole";
1352
+ case "threadedHole":
1353
+ return sheet?.threading !== void 0;
1354
+ case "pocket":
1355
+ return type.includes("pocket") || kind === "pocket";
1356
+ case "slot":
1357
+ return type.includes("slot") || kind === "tslot";
1358
+ case "undercut":
1359
+ return kind === "tslot" || type.includes("undercut") || type.includes("tslot");
1360
+ case "contour":
1361
+ return type.includes("contour") || kind.includes("contour");
1362
+ case "wall":
1363
+ return type.includes("wall") || kind === "wall";
1364
+ case "face":
1365
+ return type === "face" || kind === "face";
1366
+ case "fillet":
1367
+ return type.split("_").includes("fillet") || kind.includes("fillet");
1368
+ case "chamfer":
1369
+ return type.includes("chamfer") || kind === "chamfer";
1370
+ case "boss":
1371
+ return type.includes("boss") || kind === "boss";
1372
+ case "countersink":
1373
+ return type === "sink";
1374
+ case "profile":
1375
+ return type === "profile" || kind === "profile";
1376
+ default:
1377
+ return false;
1378
+ }
1379
+ };
1380
+ var at = (record2, path) => path.split(".").reduce(
1381
+ (value, key) => typeof value === "object" && value !== null ? value[key] : void 0,
1382
+ record2
1383
+ );
1384
+ var readPath = (datasheet, metric) => {
1385
+ for (const path of metric.path ?? []) {
1386
+ const value = at(datasheet, path);
1387
+ if (value === void 0 || value === null) continue;
1388
+ if (typeof value === "boolean") return value ? 1 : 0;
1389
+ if (metric.quantity === "flag") return 1;
1390
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1391
+ return null;
1392
+ }
1393
+ return metric.quantity === "flag" && metric.path ? 0 : null;
1394
+ };
1395
+ var TILT = 1e-6;
1396
+ var isTilted = ({ x, y, z }) => [x, y, z].filter((each) => Math.abs(each) > TILT).length > 1;
1397
+ var featureMeasure = (metric, features, feature, { sheets, datasheets, regionAreas }) => {
1398
+ const tag = feature.tag.toLowerCase();
1399
+ const sheet = sheets[tag];
1400
+ const datasheet = datasheets[tag];
1401
+ const positive = (value) => value !== void 0 && value > 0 ? { value } : null;
1402
+ switch (metric.key) {
1403
+ case "present":
1404
+ return { value: 1 };
1405
+ case "tilted":
1406
+ return { value: isTilted(feature.machiningDirection) ? 1 : 0 };
1407
+ case "faceCount":
1408
+ return { value: new Set(feature.regionIdxs).size };
1409
+ case "ld": {
1410
+ const ld = featureLd(features, feature, sheets);
1411
+ return ld ? { value: ld.ratio, drilling: ld.drilling } : null;
1412
+ }
1413
+ case "featureLd": {
1414
+ const ld = featureLd(features, feature, sheets);
1415
+ return ld?.featureRatio !== void 0 ? { value: ld.featureRatio, drilling: ld.drilling } : null;
1416
+ }
1417
+ case "depthBelowTop": {
1418
+ const top = partTop(features, sheets, feature.machiningDirection);
1419
+ return top !== null && sheet?.zMin !== void 0 ? { value: top - sheet.zMin } : null;
1420
+ }
1421
+ case "featureDepth":
1422
+ return sheet?.zMax !== void 0 && sheet.zMin !== void 0 ? { value: sheet.zMax - sheet.zMin } : null;
1423
+ // Zero is no measure at all for these: no bore, no tool, a sharp floor rather than a tiny fillet.
1424
+ case "diameter":
1425
+ return positive(sheet?.diameter);
1426
+ // Zero is a measure here: a sharp corner, which a "radius ≤" rule is most of all about.
1427
+ case "cornerRadius":
1428
+ return sheet?.cornerRadius === void 0 ? null : { value: sheet.cornerRadius };
1429
+ case "maxTool":
1430
+ return positive(sheet?.maxTool);
1431
+ case "floorFillet":
1432
+ return positive(sheet?.filletRadius);
1433
+ case "sharpCorner":
1434
+ return sheet ? { value: sheet.sharpCorners ? 1 : 0 } : null;
1435
+ case "noToolFits":
1436
+ return sheet ? { value: sheet.noToolFits ? 1 : 0 } : null;
1437
+ case "pinchPoints": {
1438
+ const points = at(datasheet, "pinchPoints");
1439
+ return Array.isArray(points) ? { value: points.length } : null;
1440
+ }
1441
+ // A disc under a hundredth is a sharp corner, which `sharpCorner` is for: see `pinchDiameter`.
1442
+ case "pinchDiameter":
1443
+ return positive(sheet?.pinchDiameter);
1444
+ case "reachHeight": {
1445
+ const heights = at(datasheet, "reachCurve.verticalOffset");
1446
+ const numbers2 = Array.isArray(heights) ? heights.filter(
1447
+ (each) => typeof each === "number" && Number.isFinite(each)
1448
+ ) : [];
1449
+ return numbers2.length > 0 ? { value: Math.max(...numbers2) } : null;
1450
+ }
1451
+ case "surfaceArea": {
1452
+ const areas = at(datasheet, "areas");
1453
+ if (typeof areas === "object" && areas !== null) {
1454
+ const parts = Object.values(areas).filter(
1455
+ (each) => typeof each === "number" && Number.isFinite(each)
1456
+ );
1457
+ if (parts.length > 0) return { value: parts.reduce((sum, each) => sum + each, 0) };
1458
+ }
1459
+ const faces = [...new Set(feature.regionIdxs)].flatMap(
1460
+ (region) => regionAreas.get(region) ?? []
1461
+ );
1462
+ return faces.length > 0 ? { value: faces.reduce((sum, each) => sum + each, 0) } : null;
1463
+ }
1464
+ default: {
1465
+ if (!datasheet) return null;
1466
+ const value = readPath(datasheet, metric);
1467
+ return value === null ? null : { value };
1468
+ }
1469
+ }
1470
+ };
1471
+ var featureHits = (features, feature, sources, rules) => {
1472
+ const sheet = sources.sheets[feature.tag.toLowerCase()];
1473
+ return rules.flatMap((rule) => {
1474
+ const info = metricInfo(rule.metric);
1475
+ if (!info || !featureIs(rule.subject, feature.featureType, sheet)) return [];
1476
+ const measured = featureMeasure(info, features, feature, sources);
1477
+ if (!measured || !breaks(rule, info.quantity, measured.value)) return [];
1478
+ return [{ rule, metric: info, ...measured }];
1479
+ });
1480
+ };
1481
+ var requiredTags = (features) => {
1482
+ const owners = /* @__PURE__ */ new Map();
1483
+ for (const feature of features) {
1484
+ for (const region of new Set(feature.regionIdxs))
1485
+ owners.set(region, (owners.get(region) ?? 0) + 1);
1486
+ }
1487
+ return new Set(
1488
+ features.filter((feature) => feature.regionIdxs.some((region) => owners.get(region) === 1)).map((feature) => feature.tag.toLowerCase())
1489
+ );
1490
+ };
1491
+ var worstColor = (hits) => hits?.map((hit) => hit.rule.color).sort(compareColors)[0];
1492
+ var ruleResults = (rules, features, hitsByTag, required) => rules.map((rule) => {
1493
+ const hits = features.flatMap((feature) => {
1494
+ const tag = feature.tag.toLowerCase();
1495
+ const hit = hitsByTag.get(tag)?.find((each) => each.rule.id === rule.id);
1496
+ return hit ? [{ tag: feature.tag, value: hit.value, metric: hit.metric, required: required.has(tag) }] : [];
1497
+ });
1498
+ const [first] = hits;
1499
+ const up = first ? worseUpward(rule, first.metric) : true;
1500
+ hits.sort((a, b) => up ? b.value - a.value : a.value - b.value);
1501
+ return {
1502
+ rule,
1503
+ tags: hits.filter((hit) => hit.required).map((hit) => hit.tag),
1504
+ otherTags: hits.filter((hit) => !hit.required).map((hit) => hit.tag)
1505
+ };
1506
+ });
1507
+ var QUALIFIERS = ["undercut", "filleted", "tslot", "dovetail"];
1508
+ var EDGE_TYPES = ["fillet", "chamfer", "sink"];
1509
+ var featureComplexity = (featureType) => {
1510
+ const words = featureType.toLowerCase().split("_");
1511
+ const edge = EDGE_TYPES.some((type) => words.includes(type)) ? 1 : 0;
1512
+ return edge + QUALIFIERS.filter((word) => words.includes(word)).length;
1513
+ };
1514
+ var CONTOUR = "contour_surface";
1515
+ var unavoidableFaces = (features, hitsByTag, regionAreas) => {
1516
+ const areaOf = (feature) => [...new Set(feature.regionIdxs)].reduce(
1517
+ (sum, region) => sum + (regionAreas.get(region) ?? 0),
1518
+ 0
1519
+ );
1520
+ const owners = /* @__PURE__ */ new Map();
1521
+ for (const feature of features) {
1522
+ for (const region of new Set(feature.regionIdxs)) {
1523
+ owners.set(region, [...owners.get(region) ?? [], feature]);
1524
+ }
1525
+ }
1526
+ const faces = /* @__PURE__ */ new Map();
1527
+ const whole = /* @__PURE__ */ new Map();
1528
+ for (const [region, candidates] of owners) {
1529
+ const colored = candidates.map((feature) => ({
1530
+ feature,
1531
+ color: worstColor(hitsByTag.get(feature.tag.toLowerCase())),
1532
+ area: areaOf(feature)
1533
+ }));
1534
+ const isContour = ({ feature }) => feature.featureType === CONTOUR;
1535
+ const machined = colored.filter((each) => !isContour(each));
1536
+ const pool = machined.length > 0 ? machined : colored;
1537
+ if (pool.some(({ color }) => color === void 0)) continue;
1538
+ const contour = colored.filter(isContour).reduce((kept, each) => kept === void 0 || each.area > kept.area ? each : kept, void 0);
1539
+ if (contour?.color && colored.every(({ color }) => color !== void 0)) {
1540
+ whole.set(contour.feature.tag.toLowerCase(), {
1541
+ tag: contour.feature.tag,
1542
+ color: contour.color
1543
+ });
1544
+ continue;
1545
+ }
1546
+ const best = pool.reduce((kept, each) => {
1547
+ const plainer = featureComplexity(kept.feature.featureType) - featureComplexity(each.feature.featureType);
1548
+ if (plainer !== 0) return plainer > 0 ? each : kept;
1549
+ const milder = compareColors(each.color ?? "", kept.color ?? "");
1550
+ return milder > 0 || milder === 0 && each.area > kept.area ? each : kept;
1551
+ });
1552
+ if (best.color) faces.set(region, { tag: best.feature.tag, color: best.color });
1553
+ }
1554
+ return { paintedFaces: faces, paintedWhole: whole };
1555
+ };
1556
+ var withSurroundedFaces = (check, features, adjacency) => {
1557
+ const paintedFor = new Map(check.paintedFaces);
1558
+ const regionsOf2 = /* @__PURE__ */ new Map();
1559
+ for (const feature of features) {
1560
+ const key = feature.tag.toLowerCase();
1561
+ regionsOf2.set(key, new Set(feature.regionIdxs));
1562
+ const whole = check.paintedWhole.get(key);
1563
+ if (whole) {
1564
+ for (const region of feature.regionIdxs)
1565
+ if (!paintedFor.has(region)) paintedFor.set(region, whole);
1566
+ }
1567
+ }
1568
+ const surrounded = /* @__PURE__ */ new Map();
1569
+ for (const [region, neighbours] of adjacency) {
1570
+ if (paintedFor.has(region)) continue;
1571
+ const counts = /* @__PURE__ */ new Map();
1572
+ for (const neighbour of neighbours) {
1573
+ const paint2 = neighbour === region ? void 0 : paintedFor.get(neighbour);
1574
+ if (!paint2) continue;
1575
+ const key = paint2.tag.toLowerCase();
1576
+ counts.set(key, { paint: paint2, count: (counts.get(key)?.count ?? 0) + 1 });
1577
+ }
1578
+ const most = Math.max(0, ...[...counts.values()].map(({ count }) => count));
1579
+ const [paint] = [...counts].filter(([key, { count }]) => count === most && regionsOf2.get(key)?.has(region)).map(([, { paint: paint2 }]) => paint2).sort((a, b) => compareColors(a.color, b.color));
1580
+ if (paint) surrounded.set(region, paint);
1581
+ }
1582
+ if (surrounded.size === 0) return check;
1583
+ return { ...check, paintedFaces: new Map([...check.paintedFaces, ...surrounded]) };
1584
+ };
1585
+ var checkPart = (features, sources, rules) => {
1586
+ const required = requiredTags(features);
1587
+ const hitsByTag = new Map(
1588
+ features.map((feature) => [
1589
+ feature.tag.toLowerCase(),
1590
+ featureHits(features, feature, sources, rules)
1591
+ ])
1592
+ );
1593
+ return {
1594
+ hitsByTag,
1595
+ required,
1596
+ byRule: ruleResults(rules, features, hitsByTag, required),
1597
+ ...unavoidableFaces(features, hitsByTag, sources.regionAreas)
1598
+ };
1599
+ };
1600
+
1601
+ // src/model/pinch.ts
1602
+ var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1603
+ var recordOf = (value) => typeof value === "object" && value !== null ? value : {};
1604
+ var clearanceFit = (datasheet) => {
1605
+ const sheet = recordOf(datasheet);
1606
+ const facts = recordOf(sheet.facts);
1607
+ const chamfer = facts.kind === "Chamfer";
1608
+ const band = recordOf(chamfer ? recordOf(facts.three).cd : facts.cd);
1609
+ const tolerance = recordOf(sheet.toleranceBand);
1610
+ const strict = asNumber(recordOf(band.ignore).min);
1611
+ if (strict === void 0) return void 0;
1612
+ const bandPath = chamfer ? "facts.three.cd" : "facts.cd";
1613
+ const loose = asNumber(recordOf(band.deviate).min);
1614
+ const atStrict = asNumber(tolerance.atolIgnore);
1615
+ const atLoose = asNumber(tolerance.atolDeviate);
1616
+ const source = { bandPath, strict, loose, atStrict, atLoose };
1617
+ if (loose === void 0 || atStrict === void 0 || atLoose === void 0 || atLoose <= atStrict)
1618
+ return { ...source, slack: 0, resolved: false };
1619
+ const growth = (loose - strict) / (atLoose - atStrict);
1620
+ const slack = growth > 0 ? Math.min(growth * atStrict, strict) : 0;
1621
+ return { ...source, slack, resolved: true };
1622
+ };
1623
+ var readPinch = (datasheet) => {
1624
+ const sheet = recordOf(datasheet);
1625
+ const zMin = asNumber(sheet.zMin);
1626
+ const zMax = asNumber(sheet.zMax);
1627
+ if (zMin === void 0 || zMax === void 0 || !Array.isArray(sheet.pinchPoints)) return null;
1628
+ const fit = clearanceFit(datasheet);
1629
+ const slack = fit?.slack ?? 0;
1630
+ const discs = sheet.pinchPoints.flatMap((point) => {
1631
+ const centre = recordOf(recordOf(point).center);
1632
+ const x = asNumber(centre.x);
1633
+ const y = asNumber(centre.y);
1634
+ const diameter = asNumber(recordOf(point).diameter);
1635
+ return x === void 0 || y === void 0 || diameter === void 0 || diameter < 0 ? [] : [{ x, y, diameter: Math.max(diameter - slack, 0) }];
1636
+ });
1637
+ if (discs.length === 0) return null;
1638
+ return { discs, zMin, zMax, ...fit && !fit.resolved ? { unresolved: true } : {} };
1639
+ };
1640
+
1641
+ // src/model/feature-sheet.ts
1642
+ var SHARP_MM = 0.1;
1643
+ var SHARP_RADIUS_MM = 0.01;
1644
+ var PINCH_TOOL_MM = 0.01;
1645
+ var asNumber2 = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
1646
+ var recordOf2 = (value) => typeof value === "object" && value !== null ? value : {};
1647
+ var definedOnly = (fields) => Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== void 0));
1648
+ var undercutOf = (facts) => {
1649
+ const unmeasured = facts.isInvalidGeometry === true || recordOf2(facts.cd).measurementFailed === true ? true : void 0;
1650
+ if (facts.kind === "Tslot")
1651
+ return definedOnly({
1652
+ undercutDepth: asNumber2(facts.undercutDepth),
1653
+ maxEntry: asNumber2(facts.maxEntryCd),
1654
+ isClosed: facts.isClosed === true ? true : void 0,
1655
+ unmeasured
1656
+ });
1657
+ if (facts.kind === "Dovetail")
1658
+ return definedOnly({
1659
+ taperDeg: asNumber2(facts.taperDeg),
1660
+ floorWidth: asNumber2(facts.floorWidth),
1661
+ topOpeningWidth: asNumber2(facts.topOpeningWidth),
1662
+ isExternal: facts.isExternal === true ? true : void 0,
1663
+ unmeasured
1664
+ });
1665
+ return void 0;
1666
+ };
1667
+ var threadingOf = (facts) => {
1668
+ const spec = recordOf2(recordOf2(facts.threading).spec);
1669
+ const basicDiameter = asNumber2(spec.basicDiameter);
1670
+ const threadPitch = asNumber2(spec.threadPitch);
1671
+ if (basicDiameter === void 0 || threadPitch === void 0 || threadPitch <= 0) return void 0;
1672
+ return { basicDiameter, threadPitch };
1673
+ };
1674
+ var noToolFits = (band) => {
1675
+ const { max } = band;
1676
+ if (typeof max === "string") return /^-inf/i.test(max.trim());
1677
+ return typeof max === "number" && (max === Number.NEGATIVE_INFINITY || Number.isFinite(max) && max < SHARP_MM);
1678
+ };
1679
+ var insideCornerRadius = (fit) => Math.max((fit.strict - fit.slack) / 2, 0);
1680
+ var pinchCentres = (points) => Array.isArray(points) ? points.flatMap((point) => {
1681
+ const centre = recordOf2(recordOf2(point).center);
1682
+ const x = asNumber2(centre.x);
1683
+ const y = asNumber2(centre.y);
1684
+ return x === void 0 || y === void 0 ? [] : [{ x, y }];
1685
+ }) : [];
1686
+ var ZERO_MM = 5e-5;
1687
+ var isCutterlessTslot = (datasheet) => {
1688
+ const facts = recordOf2(recordOf2(datasheet).facts);
1689
+ if (facts.kind !== "Tslot") return false;
1690
+ const leaves = (value) => typeof value === "object" && value !== null ? Object.values(value).flatMap(leaves) : [value];
1691
+ const band = leaves(facts.cd);
1692
+ return band.length > 0 && band.every((each) => {
1693
+ const value = typeof each === "string" && each.trim() !== "" ? Number(each) : each;
1694
+ return typeof value === "number" && Math.abs(value) < ZERO_MM;
1695
+ });
1696
+ };
1697
+ var isSharpCorneredFillet = (featureType, datasheet) => {
1698
+ if (typeof featureType !== "string" || !featureType.toLowerCase().split("_").includes("fillet"))
1699
+ return false;
1700
+ const facts = recordOf2(recordOf2(datasheet).facts);
1701
+ return facts.hasSharpCorner === true || recordOf2(facts.three).hasSharpCorner === true;
1702
+ };
1703
+ var isNoReading = (featureType, datasheet) => isCutterlessTslot(datasheet) || isSharpCorneredFillet(featureType, datasheet);
1704
+ var featureSheet = (datasheet) => {
1705
+ const sheet = recordOf2(datasheet);
1706
+ const facts = recordOf2(sheet.facts);
1707
+ const kind = typeof facts.kind === "string" ? facts.kind : void 0;
1708
+ const band = recordOf2(kind === "Chamfer" ? recordOf2(facts.three).cd : facts.cd);
1709
+ const ignoreBand = recordOf2(band.ignore);
1710
+ const fit = clearanceFit(datasheet);
1711
+ const fields = {
1712
+ kind,
1713
+ zMin: asNumber2(sheet.zMin),
1714
+ zMax: asNumber2(sheet.zMax),
1715
+ extendedZMax: asNumber2(sheet.extendedZMax),
1716
+ maxTool: asNumber2(ignoreBand.min),
1717
+ diameter: kind === "Hole" ? asNumber2(facts.diameter) : void 0,
1718
+ tipAngle: kind === "Hole" ? asNumber2(facts.fullConeDeg) : void 0,
1719
+ filletRadius: asNumber2(facts.filletRadius),
1720
+ // A bevel's angle wherever the facts carry one: a chamfer's, and any other kind that bevels.
1721
+ chamferAngle: asNumber2(recordOf2(facts.bevel).angleDeg)
1722
+ };
1723
+ const toolFitPath = facts.toolFit !== void 0 ? "facts.toolFit" : "facts.three.toolFit";
1724
+ const toolFit = recordOf2(facts.toolFit ?? recordOf2(facts.three).toolFit);
1725
+ fields.fitToolDiameter = asNumber2(toolFit.toolDiameter);
1726
+ fields.fitCornerRadius = asNumber2(toolFit.cornerRadius);
1727
+ const ballOnly = (facts.useOnlyBallToolsForFinish ?? recordOf2(facts.three).useOnlyBallToolsForFinish) === true;
1728
+ const measured = Object.fromEntries(
1729
+ Object.entries(fields).filter(([, value]) => value !== void 0)
1730
+ );
1731
+ const cramped = Object.keys(ignoreBand).length > 0 && noToolFits(ignoreBand);
1732
+ const walled = kind !== "Hole" && sheet.hasWall === true;
1733
+ const clearance = walled ? fit : void 0;
1734
+ const cornerRadius = clearance ? insideCornerRadius(clearance) : void 0;
1735
+ const sharp = cornerRadius !== void 0 && cornerRadius < SHARP_RADIUS_MM && !cramped;
1736
+ const threading = kind === "Hole" ? threadingOf(facts) : void 0;
1737
+ const undercut = undercutOf(facts);
1738
+ const pinched = (readPinch(datasheet)?.discs ?? []).filter(
1739
+ (disc) => disc.diameter >= PINCH_TOOL_MM
1740
+ );
1741
+ return {
1742
+ ...measured,
1743
+ ...pinched.length > 0 ? {
1744
+ pinchDiameter: Math.min(...pinched.map((disc) => disc.diameter)),
1745
+ pinchPlaces: pinched.length
1746
+ } : {},
1747
+ ...cornerRadius !== void 0 ? { cornerRadius } : {},
1748
+ ...clearance && !clearance.resolved ? { cornerRadiusUnresolved: true } : {},
1749
+ ...clearance ? { clearance } : {},
1750
+ ...Object.keys(toolFit).length > 0 ? { toolFitPath } : {},
1751
+ ...sharp ? { sharpCorners: pinchCentres(sheet.pinchPoints) } : {},
1752
+ ...cramped ? { noToolFits: true } : {},
1753
+ ...ballOnly ? { ballOnly: true } : {},
1754
+ ...threading ? { threading } : {},
1755
+ ...undercut ? { undercut } : {}
1756
+ };
1757
+ };
1758
+
1759
+ // src/model/feature-details.ts
1760
+ import { MM_PER_INCH as MM_PER_INCH4 } from "@toolpath/tool-support";
1761
+ var mm = (value) => `${trim3(value, 4)} mm`;
1762
+ var tol = (value) => `${trim3(value, 6)} mm`;
1763
+ var clearanceDerivation = (fit, clearance) => {
1764
+ const { bandPath, strict, loose, atStrict, atLoose } = fit;
1765
+ const lines = [`\u2300\u2081 = ${bandPath}.ignore.min = ${mm(strict)}`];
1766
+ if (loose === void 0 || atStrict === void 0 || atLoose === void 0 || atLoose <= atStrict) {
1767
+ lines.push(
1768
+ `${bandPath}.deviate.min or a tolerance is missing, so the tolerance cannot be taken out:`,
1769
+ `clearance \u2264 \u2300\u2081 = ${mm(clearance)}`
1770
+ );
1771
+ return lines;
1772
+ }
1773
+ const growth = (loose - strict) / (atLoose - atStrict);
1774
+ lines.push(
1775
+ ` at t\u2081 = toleranceBand.atolIgnore = ${tol(atStrict)}`,
1776
+ `\u2300\u2082 = ${bandPath}.deviate.min = ${mm(loose)}`,
1777
+ ` at t\u2082 = toleranceBand.atolDeviate = ${tol(atLoose)}`
1778
+ );
1779
+ if (growth <= 0) {
1780
+ lines.push("The tool does not grow with tolerance (a gap, not a corner): clearance = \u2300\u2081");
1781
+ } else {
1782
+ lines.push(
1783
+ `k = (\u2300\u2082 \u2212 \u2300\u2081) / (t\u2082 \u2212 t\u2081) = ${trim3(growth, 3)}`,
1784
+ `slack = k \xD7 t\u2081 = ${mm(growth * atStrict)}, what the tolerance adds to every tool`,
1785
+ `clearance = \u2300\u2081 \u2212 slack`
1786
+ );
1787
+ }
1788
+ lines.push(`clearance = ${mm(clearance)}`);
1789
+ return lines;
1790
+ };
1791
+ var trim3 = (value, places) => String(Number(value.toFixed(places)));
1792
+ var formatLength = (mm2, units, inchMark = false) => units === "inch" ? `${trim3(mm2 / MM_PER_INCH4, LENGTH_PLACES.inch)}${inchMark ? '"' : " in"}` : `${trim3(mm2, LENGTH_PLACES.mm)} mm`;
1793
+ var SURFACE_TYPES = /* @__PURE__ */ new Set([
1794
+ "contour_surface",
1795
+ "inner_fillet",
1796
+ "outer_fillet",
1797
+ "fillet"
1798
+ ]);
1799
+ var isSurfaceType = (featureType) => SURFACE_TYPES.has(featureType);
1800
+ var maxBallDiameter = (sheet) => {
1801
+ const { fitToolDiameter: diameter, fitCornerRadius: corner } = sheet;
1802
+ if (corner === void 0 || corner <= 0) return void 0;
1803
+ return diameter !== void 0 && diameter > 0 ? Math.min(diameter, 2 * corner) : 2 * corner;
1804
+ };
1805
+ var ROW_ORDER = [
1806
+ "featureDepth",
1807
+ "undercutWidth",
1808
+ "floorWidth",
1809
+ "openingWidth",
1810
+ "undercutDepth",
1811
+ "taper",
1812
+ "diameter",
1813
+ "cornerRadius",
1814
+ "filletRadius",
1815
+ "floorFillet",
1816
+ "tipAngle",
1817
+ "thread",
1818
+ "bevelAngle",
1819
+ "finishTool",
1820
+ "undercutCutter",
1821
+ "maxShaft",
1822
+ "pinch",
1823
+ "fitCornerRadius",
1824
+ "maxBull",
1825
+ "maxBall",
1826
+ "depthBelowTop",
1827
+ "ld",
1828
+ "featureLd",
1829
+ "topLd"
1830
+ ];
1831
+ var featureMeasurements = ({
1832
+ features,
1833
+ feature,
1834
+ sheets,
1835
+ units,
1836
+ inchMark = false
1837
+ }) => {
1838
+ const other = units === "inch" ? "mm" : "inch";
1839
+ const length = (mm2) => ({
1840
+ value: formatLength(mm2, units, inchMark),
1841
+ alt: formatLength(mm2, other, inchMark)
1842
+ });
1843
+ const sheet = sheets[feature.tag.toLowerCase()];
1844
+ const rows = [];
1845
+ const undercut = sheet?.undercut;
1846
+ const top = sheet ? partTop(features, sheets, feature.machiningDirection) : null;
1847
+ const bottom = sheet?.zMin;
1848
+ const topFrom = top === null ? void 0 : features.find((each) => sheets[each.tag.toLowerCase()]?.extendedZMax === top);
1849
+ const topLine = top === null ? "" : `Top of part = the highest extendedZMax of the features machined from this direction = ${mm(top)}${topFrom ? ` (${featureTypeLabel(topFrom.featureType)} ${topFrom.tag})` : ""}`;
1850
+ if (top !== null && bottom !== void 0) {
1851
+ rows.push({
1852
+ key: "depthBelowTop",
1853
+ label: "Depth below top of part",
1854
+ milling: true,
1855
+ ...length(top - bottom),
1856
+ derivation: [topLine, `Top \u2212 zMin = ${mm(top)} \u2212 ${mm(bottom)} = ${mm(top - bottom)}`]
1857
+ });
1858
+ }
1859
+ if (sheet?.zMax !== void 0 && bottom !== void 0 && !(undercut && sheet?.kind === "Tslot")) {
1860
+ rows.push({
1861
+ key: "featureDepth",
1862
+ label: "Feature depth",
1863
+ ...length(sheet.zMax - bottom),
1864
+ derivation: [`zMax \u2212 zMin = ${mm(sheet.zMax)} \u2212 ${mm(bottom)} = ${mm(sheet.zMax - bottom)}`]
1865
+ });
1866
+ }
1867
+ if (sheet?.diameter !== void 0) {
1868
+ rows.push({
1869
+ key: "diameter",
1870
+ label: "Diameter",
1871
+ ...length(sheet.diameter),
1872
+ derivation: [`facts.diameter = ${mm(sheet.diameter)}`]
1873
+ });
1874
+ }
1875
+ if (sheet?.cornerRadius !== void 0 && !undercut) {
1876
+ const radius = length(sheet.cornerRadius);
1877
+ rows.push({
1878
+ key: "cornerRadius",
1879
+ label: sheet.sharpCorners ? "Minimum radius (sharp)" : "Minimum radius",
1880
+ // Measured at one tolerance only, it is the most the modelled radius can be, not the radius itself.
1881
+ ...sheet.cornerRadiusUnresolved ? { value: `\u2264 ${radius.value}`, alt: `\u2264 ${radius.alt}` } : radius,
1882
+ derivation: [
1883
+ "The tightest corner between walls: half the minimum clearance, the widest tool that reaches every point with the tolerance it was measured to taken out.",
1884
+ ...sheet.clearance ? clearanceDerivation(sheet.clearance, 2 * sheet.cornerRadius) : [],
1885
+ `R = clearance / 2 = ${mm(sheet.cornerRadius)}${sheet.sharpCorners ? " (under 0.01 mm: sharp)" : ""}`
1886
+ ]
1887
+ });
1888
+ }
1889
+ if (!sheet?.sharpCorners && !undercut) {
1890
+ const clearance = sheet?.pinchDiameter ?? (sheet?.cornerRadius !== void 0 ? 2 * sheet.cornerRadius : void 0);
1891
+ if (clearance !== void 0) {
1892
+ const width = length(clearance);
1893
+ const places = sheet?.pinchPlaces;
1894
+ const floor = !SURFACE_TYPES.has(feature.featureType) && sheet?.filletRadius !== void 0 && sheet.filletRadius > 0 ? length(sheet.filletRadius) : void 0;
1895
+ const atMost = sheet?.cornerRadiusUnresolved ? "\u2264 " : "";
1896
+ rows.push({
1897
+ key: "pinch",
1898
+ label: "Max tool diameter",
1899
+ milling: true,
1900
+ // Measured at one tolerance only, it is the most the clearance can be, not the clearance itself.
1901
+ value: `${atMost}\u2300 ${width.value}${floor ? ` \xB7 R ${floor.value}` : ""}`,
1902
+ alt: `${atMost}\u2300 ${width.alt}${floor ? ` \xB7 R ${floor.alt}` : ""}`,
1903
+ derivation: [
1904
+ "The widest circle that fits where the feature is tightest: twice an inside corner\u2019s radius, or the width of a gap between walls.",
1905
+ ...places !== void 0 ? [
1906
+ `pinchPoints: where the feature narrows to its tightest clearance, a disc each; ${places} ${places === 1 ? "place" : "places"} that tight, the tightest drawn.`,
1907
+ `min(pinchPoints[].diameter) is the cutter band\u2019s min, measured to a tolerance (t) the widest tool grows with: run back to none from two tolerances.`
1908
+ ] : [
1909
+ "No pinch points reported: the cutter band\u2019s min, measured to a tolerance (t) the widest tool grows with, run back to none from two tolerances."
1910
+ ],
1911
+ ...sheet?.clearance ? clearanceDerivation(sheet.clearance, clearance) : [],
1912
+ ...floor && sheet?.filletRadius !== void 0 ? [
1913
+ `A bull nose, its corner radius the floor fillet\u2019s: facts.filletRadius = ${mm(sheet.filletRadius)}`
1914
+ ] : []
1915
+ ]
1916
+ });
1917
+ }
1918
+ }
1919
+ if (sheet && undercut) rows.push(...undercutRows(sheet, undercut, top, length));
1920
+ const surface = SURFACE_TYPES.has(feature.featureType);
1921
+ if (surface && sheet) {
1922
+ const diameter = sheet.fitToolDiameter;
1923
+ const corner = sheet.fitCornerRadius;
1924
+ const fit = sheet.toolFitPath ?? "facts.toolFit";
1925
+ const ball = maxBallDiameter(sheet);
1926
+ rows.push({
1927
+ key: "finishTool",
1928
+ label: "Finishing tool",
1929
+ milling: true,
1930
+ value: sheet.ballOnly ? "Ball end mill" : "Ball or bull nose",
1931
+ derivation: [
1932
+ `facts.useOnlyBallToolsForFinish (or facts.three.\u2026) is ${sheet.ballOnly ? "true" : "not true"}`
1933
+ ]
1934
+ });
1935
+ if (corner !== void 0 && corner > 0) {
1936
+ rows.push({
1937
+ key: "fitCornerRadius",
1938
+ label: "Max corner radius",
1939
+ milling: true,
1940
+ ...length(corner),
1941
+ derivation: [
1942
+ "The tightest the surface turns inward: a tool with a larger corner radius cannot follow it.",
1943
+ `${fit}.cornerRadius = ${mm(corner)}`
1944
+ ]
1945
+ });
1946
+ }
1947
+ const sized = diameter !== void 0 && diameter > 0;
1948
+ if (!sheet.ballOnly && corner !== void 0 && corner > 0 && (!sized || ball === void 0 || ball < diameter)) {
1949
+ const size = sized ? length(diameter) : void 0;
1950
+ const radius = length(corner);
1951
+ rows.push({
1952
+ key: "maxBull",
1953
+ label: "Max bull nose",
1954
+ milling: true,
1955
+ // Drawable only at a diameter the fit gives: "any" is no size to draw.
1956
+ ...sized ? { tool: "bull" } : {},
1957
+ value: `${size ? `\u2300 ${size.value}` : "any \u2300"} \xB7 R ${radius.value}`,
1958
+ alt: `${size ? `\u2300 ${size.alt}` : "any \u2300"} \xB7 R ${radius.alt}`,
1959
+ derivation: [
1960
+ sized ? "The largest full-diameter tool the surface\u2019s shape admits, with the largest corner radius it admits." : "The surface limits only the tool\u2019s corner radius, not its diameter: a bull nose of any size with a corner no larger than this.",
1961
+ ...sized ? [`\u2300 = ${fit}.toolDiameter = ${mm(diameter)}`] : [`${fit}.toolDiameter is not reported`],
1962
+ `R = ${fit}.cornerRadius = ${mm(corner)}`
1963
+ ]
1964
+ });
1965
+ }
1966
+ if (ball !== void 0 && corner !== void 0) {
1967
+ const size = length(ball);
1968
+ rows.push({
1969
+ key: "maxBall",
1970
+ label: "Max ball nose",
1971
+ milling: true,
1972
+ tool: "ball",
1973
+ value: `\u2300 ${size.value}`,
1974
+ alt: `\u2300 ${size.alt}`,
1975
+ derivation: [
1976
+ "A ball\u2019s corner radius is half its diameter, so it must fit under the corner limit, and the diameter limit where there is one:",
1977
+ ...diameter !== void 0 && diameter > 0 ? [
1978
+ `min(${fit}.toolDiameter, 2 \xD7 ${fit}.cornerRadius)`,
1979
+ `= min(${mm(diameter)}, ${mm(2 * corner)}) = ${mm(ball)}`
1980
+ ] : [`2 \xD7 ${fit}.cornerRadius = ${mm(ball)} (${fit}.toolDiameter is not reported)`]
1981
+ ]
1982
+ });
1983
+ }
1984
+ }
1985
+ const ld = undercut ? null : featureLd(features, feature, sheets);
1986
+ if (ld && top !== null && bottom !== void 0) {
1987
+ const across = ld.basis === "bore" ? `D = facts.diameter = ${mm(ld.across)}` : ld.basis === "pinch" ? `D = widest tool (the tightest pinch disc, tolerance taken out) = ${mm(ld.across)}${ld.atLeast ? " (at most, so L/D is at least)" : ""}` : `D = widest tool = 2 \xD7 inside corner radius = ${mm(ld.across)}${ld.atLeast ? " (at most, so L/D is at least)" : ""} (no pinch points reported)`;
1988
+ const ratioOf = (depth) => {
1989
+ const ratio2 = (depth / ld.across).toFixed(3);
1990
+ return ld.atLeast ? `\u2265 ${ratio2}` : ratio2;
1991
+ };
1992
+ if (ld.drilling) {
1993
+ rows.push({
1994
+ key: "ld",
1995
+ label: "Drilling L/D",
1996
+ milling: true,
1997
+ value: ratioOf(top - bottom),
1998
+ derivation: [
1999
+ `L = depth below top of part = ${mm(top - bottom)}`,
2000
+ across,
2001
+ `L / D = ${mm(top - bottom)} / ${mm(ld.across)} = ${ld.ratio.toFixed(3)}`
2002
+ ]
2003
+ });
2004
+ } else {
2005
+ if (sheet?.zMax !== void 0) {
2006
+ rows.push({
2007
+ key: "featureLd",
2008
+ label: "Feature L/D",
2009
+ milling: true,
2010
+ value: ratioOf(sheet.zMax - bottom),
2011
+ derivation: [
2012
+ `L = feature depth = zMax \u2212 zMin = ${mm(sheet.zMax - bottom)}`,
2013
+ across,
2014
+ `L / D = ${mm(sheet.zMax - bottom)} / ${mm(ld.across)} = ${((sheet.zMax - bottom) / ld.across).toFixed(3)}`
2015
+ ]
2016
+ });
2017
+ }
2018
+ rows.push({
2019
+ key: "topLd",
2020
+ label: "L/D to top of part",
2021
+ milling: true,
2022
+ value: ratioOf(top - bottom),
2023
+ derivation: [
2024
+ `L = depth below top of part = ${mm(top - bottom)}`,
2025
+ across,
2026
+ `L / D = ${mm(top - bottom)} / ${mm(ld.across)} = ${ld.ratio.toFixed(3)}`
2027
+ ]
2028
+ });
2029
+ }
2030
+ }
2031
+ if (sheet?.tipAngle !== void 0) {
2032
+ const flat = Math.abs(sheet.tipAngle - 180) < 0.05;
2033
+ rows.push({
2034
+ key: "tipAngle",
2035
+ label: "Tip angle",
2036
+ value: `${trim3(sheet.tipAngle, 3)}\xB0${flat ? " (flat)" : ""}`,
2037
+ derivation: [
2038
+ `facts.fullConeDeg = ${trim3(sheet.tipAngle, 3)}\xB0${flat ? " (180\xB0: flat bottom)" : ""}`
2039
+ ]
2040
+ });
2041
+ }
2042
+ if (sheet?.threading) {
2043
+ rows.push({
2044
+ key: "thread",
2045
+ label: "Thread",
2046
+ value: `${formatLength(sheet.threading.basicDiameter, units, inchMark)} \xD7 ${formatLength(sheet.threading.threadPitch, units, inchMark)} pitch`,
2047
+ derivation: [
2048
+ `facts.threading.spec.basicDiameter = ${mm(sheet.threading.basicDiameter)}`,
2049
+ `facts.threading.spec.threadPitch = ${mm(sheet.threading.threadPitch)}`
2050
+ ]
2051
+ });
2052
+ }
2053
+ if (surface) {
2054
+ if (sheet?.filletRadius !== void 0 && sheet.filletRadius !== 0) {
2055
+ rows.push({
2056
+ key: "filletRadius",
2057
+ label: "Fillet radius",
2058
+ ...length(Math.abs(sheet.filletRadius)),
2059
+ derivation: [
2060
+ `|facts.filletRadius| = |${mm(sheet.filletRadius)}| (signed: + over an edge, \u2212 into a corner)`
2061
+ ]
2062
+ });
2063
+ }
2064
+ } else if (sheet?.filletRadius !== void 0 && sheet.filletRadius > 0) {
2065
+ rows.push({
2066
+ key: "floorFillet",
2067
+ label: "Floor fillet radius",
2068
+ ...length(sheet.filletRadius),
2069
+ derivation: [`facts.filletRadius = ${mm(sheet.filletRadius)}`]
2070
+ });
2071
+ }
2072
+ if (sheet?.chamferAngle !== void 0) {
2073
+ rows.push({
2074
+ key: "bevelAngle",
2075
+ label: "Chamfer angle",
2076
+ value: `${sheet.chamferAngle.toFixed(3)}\xB0`,
2077
+ derivation: [`facts.bevel.angleDeg = ${trim3(sheet.chamferAngle, 3)}\xB0`]
2078
+ });
2079
+ }
2080
+ return rows.sort((a, b) => ROW_ORDER.indexOf(a.key) - ROW_ORDER.indexOf(b.key));
2081
+ };
2082
+ var undercutRows = (sheet, undercut, top, length) => {
2083
+ const rows = [];
2084
+ const tslot = sheet.kind === "Tslot";
2085
+ const { zMin, zMax } = sheet;
2086
+ const { floorWidth: floor, topOpeningWidth: opening } = undercut;
2087
+ const angle = undercut.taperDeg !== void 0 ? `${trim3(undercut.taperDeg, 3)}\xB0` : void 0;
2088
+ if (tslot && zMin !== void 0 && zMax !== void 0) {
2089
+ rows.push({
2090
+ key: "undercutWidth",
2091
+ label: "Undercut width",
2092
+ ...length(zMax - zMin),
2093
+ derivation: [
2094
+ "The groove\u2019s height along the tool: the widest cutter it takes in one pass.",
2095
+ `zMax \u2212 zMin = ${mm(zMax)} \u2212 ${mm(zMin)} = ${mm(zMax - zMin)}`
2096
+ ]
2097
+ });
2098
+ }
2099
+ if (floor !== void 0) {
2100
+ rows.push({
2101
+ key: "floorWidth",
2102
+ label: "Floor width",
2103
+ ...length(floor),
2104
+ derivation: ["The widest clearance over the floor", `facts.floorWidth = ${mm(floor)}`]
2105
+ });
2106
+ }
2107
+ if (opening !== void 0) {
2108
+ rows.push({
2109
+ key: "openingWidth",
2110
+ label: "Opening width",
2111
+ ...length(opening),
2112
+ derivation: [
2113
+ "The clearance through the opening at the top of the groove",
2114
+ `facts.topOpeningWidth = ${mm(opening)}`
2115
+ ]
2116
+ });
2117
+ }
2118
+ let depth = undercut.undercutDepth;
2119
+ let depthLine = depth !== void 0 ? `facts.undercutDepth = ${mm(depth)}` : "";
2120
+ if (depth === void 0 && floor !== void 0 && opening !== void 0) {
2121
+ if (floor > opening && !undercut.isExternal) {
2122
+ depth = (floor - opening) / 2;
2123
+ depthLine = `(facts.floorWidth \u2212 facts.topOpeningWidth) / 2 = (${mm(floor)} \u2212 ${mm(opening)}) / 2 = ${mm(depth)}`;
2124
+ }
2125
+ }
2126
+ if (depth !== void 0) {
2127
+ rows.push({
2128
+ key: "undercutDepth",
2129
+ label: "Undercut depth",
2130
+ ...length(depth),
2131
+ derivation: [
2132
+ "How far the groove runs back from its opening: what the cutter\u2019s head reaches past its shaft.",
2133
+ depthLine
2134
+ ]
2135
+ });
2136
+ }
2137
+ if (angle) {
2138
+ rows.push({
2139
+ key: "taper",
2140
+ label: "Dovetail angle",
2141
+ value: `${angle} from the tool axis`,
2142
+ derivation: [`facts.taperDeg = ${angle}, between the overhanging wall and the tool axis`]
2143
+ });
2144
+ }
2145
+ const cutter = (value, derivation, alt) => ({
2146
+ key: "undercutCutter",
2147
+ label: "Max cutting diameter",
2148
+ milling: true,
2149
+ value,
2150
+ ...alt !== void 0 ? { alt } : {},
2151
+ derivation
2152
+ });
2153
+ if (undercut.unmeasured) {
2154
+ return [
2155
+ ...rows,
2156
+ cutter("Not measured", [
2157
+ "The Engine could not measure the groove (facts.isInvalidGeometry or facts.cd.measurementFailed), so its figures offer no cutter."
2158
+ ])
2159
+ ];
2160
+ }
2161
+ if (sheet.noToolFits) {
2162
+ return [
2163
+ ...rows,
2164
+ cutter("None fits", [
2165
+ "facts.cd.ignore.max is next to nothing: no cutter fits anywhere in the groove."
2166
+ ])
2167
+ ];
2168
+ }
2169
+ const band = sheet.maxTool !== void 0 && sheet.maxTool > 0 ? sheet.maxTool : void 0;
2170
+ const dropIn = undercut.isClosed ? undercut.maxEntry : void 0;
2171
+ const head = band === void 0 ? void 0 : Math.min(band, dropIn ?? Infinity);
2172
+ const opensTo = undercut.maxEntry ?? opening;
2173
+ const behind = head !== void 0 && depth !== void 0 ? head - 2 * depth : void 0;
2174
+ const limits = [opensTo, behind].filter((each) => each !== void 0);
2175
+ const shaft = limits.length > 0 ? Math.max(Math.min(...limits), 0) : void 0;
2176
+ const shaftLines = [
2177
+ "The most the cutter\u2019s shaft can be: what comes down through the opening above the groove, and leaves the head reaching the back of it.",
2178
+ ...opensTo !== void 0 ? [`Opening: ${tslot ? "facts.maxEntryCd" : "facts.topOpeningWidth"} = ${mm(opensTo)}`] : [],
2179
+ ...behind !== void 0 && head !== void 0 && depth !== void 0 ? [
2180
+ `Reach: max cutting diameter \u2212 2 \xD7 undercut depth = ${mm(head)} \u2212 2 \xD7 ${mm(depth)} = ${mm(behind)}`
2181
+ ] : [],
2182
+ ...shaft !== void 0 ? [`Max shaft = ${mm(shaft)}`] : []
2183
+ ];
2184
+ if (head !== void 0 && band !== void 0) {
2185
+ const headLines = [
2186
+ "The biggest head that reaches every point of the groove.",
2187
+ `facts.cd.ignore.min = ${mm(band)}`,
2188
+ ...dropIn !== void 0 ? [
2189
+ `A closed slot: the head comes down through the opening above it, facts.maxEntryCd = ${mm(dropIn)}`
2190
+ ] : [],
2191
+ `\u2300 = ${mm(head)}`
2192
+ ];
2193
+ if (head < SHARP_MM || shaft !== void 0 && shaft < SHARP_MM) {
2194
+ return [
2195
+ ...rows,
2196
+ cutter("None fits", [
2197
+ ...headLines,
2198
+ ...shaft !== void 0 ? shaftLines : [],
2199
+ "No head that fits the groove leaves room for a shaft to carry it."
2200
+ ])
2201
+ ];
2202
+ }
2203
+ const size = length(head);
2204
+ const filletRadius = sheet.filletRadius !== void 0 && sheet.filletRadius > 0 ? sheet.filletRadius : void 0;
2205
+ const fillet = filletRadius !== void 0 ? length(filletRadius) : void 0;
2206
+ const describe = (unit2) => [`\u2300 ${size[unit2]}`, ...angle ? [angle] : [], ...fillet ? [`R ${fillet[unit2]}`] : []].join(
2207
+ " \xB7 "
2208
+ );
2209
+ rows.push(
2210
+ cutter(
2211
+ describe("value"),
2212
+ [
2213
+ ...headLines,
2214
+ ...angle ? [`Angle = facts.taperDeg = ${angle}, from the tool axis`] : [],
2215
+ ...filletRadius !== void 0 ? [`R = facts.filletRadius = ${mm(filletRadius)}, the blend the head\u2019s corners cut`] : []
2216
+ ],
2217
+ describe("alt")
2218
+ )
2219
+ );
2220
+ if (top !== null && zMin !== void 0) {
2221
+ const reach = top - zMin;
2222
+ const ratio2 = (reach / head).toFixed(3);
2223
+ rows.push({
2224
+ key: "topLd",
2225
+ label: "L/D to top of part",
2226
+ milling: true,
2227
+ value: ratio2,
2228
+ derivation: [
2229
+ `L = depth below top of part = ${mm(reach)}`,
2230
+ `D = max cutting diameter = ${mm(head)}`,
2231
+ `L / D = ${mm(reach)} / ${mm(head)} = ${ratio2}`
2232
+ ]
2233
+ });
2234
+ }
2235
+ }
2236
+ if (shaft !== void 0 || tslot) {
2237
+ const size = shaft !== void 0 ? length(shaft) : void 0;
2238
+ rows.push({
2239
+ key: "maxShaft",
2240
+ label: "Max shaft diameter",
2241
+ milling: true,
2242
+ ...size ? { value: `\u2300 ${size.value}`, alt: `\u2300 ${size.alt}` } : { value: "No limit" },
2243
+ derivation: size ? shaftLines : [
2244
+ "facts.maxEntryCd is not reported and the head or undercut depth is not known: nothing limits the shaft."
2245
+ ]
2246
+ });
2247
+ }
2248
+ return rows;
2249
+ };
2250
+
2251
+ // src/model/feature-record.ts
2252
+ var MAX_DATASHEET_FIELDS = 500;
2253
+ var formatLeaf = (value) => typeof value === "number" ? String(Number(value.toFixed(4))) : typeof value === "string" ? value : value === null ? "null" : String(value);
2254
+ var datasheetFields = (datasheet) => {
2255
+ const fields = [];
2256
+ let more = false;
2257
+ const walk = (value, path) => {
2258
+ if (fields.length >= MAX_DATASHEET_FIELDS) {
2259
+ more = true;
2260
+ return;
2261
+ }
2262
+ if (Array.isArray(value)) {
2263
+ if (value.every((each) => typeof each !== "object" || each === null)) {
2264
+ fields.push({ path, value: value.length === 0 ? "[]" : value.map(formatLeaf).join(", ") });
2265
+ } else {
2266
+ value.forEach((each, index) => walk(each, `${path}[${index}]`));
2267
+ }
2268
+ } else if (typeof value === "object" && value !== null) {
2269
+ const entries = Object.entries(value);
2270
+ if (entries.length === 0) fields.push({ path, value: "{}" });
2271
+ for (const [key, each] of entries) walk(each, path ? `${path}.${key}` : key);
2272
+ } else {
2273
+ fields.push({ path, value: formatLeaf(value) });
2274
+ }
2275
+ };
2276
+ if (datasheet !== null && datasheet !== void 0) walk(datasheet, "");
2277
+ return { fields, more };
2278
+ };
2279
+
1301
2280
  // src/model/hole-groups.ts
1302
2281
  var holeSize = (sheets, tag) => {
1303
2282
  const sheet = sheets[tag.toLowerCase()];
@@ -1313,11 +2292,11 @@ var sameDepth = (a, b) => Math.abs(a - b) <= Math.max(DEPTH_FLOOR, Math.max(Math
1313
2292
  var sameDirection2 = (a, b) => Math.abs(a.x - b.x) < TOLERANCE2 && Math.abs(a.y - b.y) < TOLERANCE2 && Math.abs(a.z - b.z) < TOLERANCE2;
1314
2293
  var sameHoleSets = (features, sheets) => {
1315
2294
  const sizes = features.map((feature) => holeSize(sheets, feature.tag));
1316
- const root = features.map((_, at) => at);
1317
- const find = (at) => {
1318
- let top = at;
2295
+ const root = features.map((_, at2) => at2);
2296
+ const find = (at2) => {
2297
+ let top = at2;
1319
2298
  while (root[top] !== top) top = root[top] ?? top;
1320
- root[at] = top;
2299
+ root[at2] = top;
1321
2300
  return top;
1322
2301
  };
1323
2302
  for (let a = 0; a < features.length; a += 1) {
@@ -1331,8 +2310,8 @@ var sameHoleSets = (features, sheets) => {
1331
2310
  }
1332
2311
  }
1333
2312
  const sets = /* @__PURE__ */ new Map();
1334
- features.forEach((feature, at) => {
1335
- const top = find(at);
2313
+ features.forEach((feature, at2) => {
2314
+ const top = find(at2);
1336
2315
  sets.set(top, [...sets.get(top) ?? [], feature]);
1337
2316
  });
1338
2317
  return [...sets.values()];
@@ -1363,9 +2342,286 @@ var featureRows = (tags, features, sheets) => {
1363
2342
  });
1364
2343
  };
1365
2344
 
1366
- // src/model/dfm-explain.ts
1367
- var figureless = (hit) => hit.metric.quantity === "flag" || hit.metric.quantity === "presence";
1368
- var hitFigure = (hit, units) => figureless(hit) ? "" : formatMeasured(hit.metric.quantity, hit.value, units);
2345
+ // src/model/pinch-mark.ts
2346
+ import { MM_PER_INCH as MM_PER_INCH5 } from "@toolpath/tool-support";
2347
+ var MAX_DRAWN_TOOL_MM = 3 * MM_PER_INCH5;
2348
+ var pinchMark = (datasheet, sheet, featureType) => {
2349
+ const pinch = readPinch(datasheet);
2350
+ const discs = pinch?.discs.filter(
2351
+ (disc) => disc.diameter >= PINCH_TOOL_MM && disc.diameter <= MAX_DRAWN_TOOL_MM
2352
+ ) ?? [];
2353
+ if (!pinch || discs.length === 0) return null;
2354
+ const fillet = sheet?.filletRadius;
2355
+ const corner = !isSurfaceType(featureType) && fillet !== void 0 && fillet > 0 ? fillet : void 0;
2356
+ return { ...pinch, discs, ...corner !== void 0 ? { corner } : {} };
2357
+ };
2358
+ var pinchLabel = (mark, units) => {
2359
+ const length = (mm2) => `${lengthValue(mm2, units)} ${unitLabel(units)}`;
2360
+ const tightest = Math.min(...mark.discs.map((disc) => disc.diameter));
2361
+ const tool = mark.corner !== void 0 ? `bull nose R ${length(mark.corner)}` : "widest tool";
2362
+ const places = mark.discs.length;
2363
+ return {
2364
+ label: `${mark.unresolved ? "\u2264 " : ""}\u2300 ${length(tightest)}`,
2365
+ note: places > 1 ? `${tool} \xB7 ${places} places` : tool
2366
+ };
2367
+ };
2368
+
2369
+ // src/model/tool-frame.ts
2370
+ var extent = (values) => {
2371
+ let low = Infinity;
2372
+ let high = -Infinity;
2373
+ for (const value of values) {
2374
+ if (value < low) low = value;
2375
+ if (value > high) high = value;
2376
+ }
2377
+ return { low, high };
2378
+ };
2379
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2380
+ var cross = (a, b) => [
2381
+ a[1] * b[2] - a[2] * b[1],
2382
+ a[2] * b[0] - a[0] * b[2],
2383
+ a[0] * b[1] - a[1] * b[0]
2384
+ ];
2385
+ var scale = (a, by) => [a[0] * by, a[1] * by, a[2] * by];
2386
+ var add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
2387
+ var unit = (a) => scale(a, 1 / Math.hypot(a[0], a[1], a[2]));
2388
+ var ON_DEPTH_MM = 0.05;
2389
+ var ON_CORNER_MM = 0.02;
2390
+ var POINT_DISC_MM = 0.01;
2391
+ var ON_WALL_MM = 0.1;
2392
+ var ON_WALL_SHARE = 0.02;
2393
+ var WALL_NORMAL_ALONG = 0.7;
2394
+ var SAME_PLACE_MM = 0.05;
2395
+ var MIN_HEIGHT_MM = 0.05;
2396
+ var readTriangles = ({ positions, normals }, origin) => {
2397
+ const triangles = [];
2398
+ for (let at2 = 0; at2 + 8 < positions.length; at2 += 9) {
2399
+ const corner = (k) => [
2400
+ (positions[at2 + k] ?? 0) - origin[0],
2401
+ (positions[at2 + k + 1] ?? 0) - origin[1],
2402
+ (positions[at2 + k + 2] ?? 0) - origin[2]
2403
+ ];
2404
+ const n = at2 / 9 * 3;
2405
+ triangles.push({
2406
+ a: corner(0),
2407
+ b: corner(3),
2408
+ c: corner(6),
2409
+ normal: [normals[n] ?? 0, normals[n + 1] ?? 0, normals[n + 2] ?? 0]
2410
+ });
2411
+ }
2412
+ return triangles;
2413
+ };
2414
+ var pointsOf = (triangles) => triangles.flatMap(({ a, b, c }) => [a, b, c]);
2415
+ var flatten = (point, { u, v }) => ({ x: dot(point, u), y: dot(point, v) });
2416
+ var wallSegments = (triangles, frame) => triangles.filter(({ normal }) => Math.abs(dot(normal, frame.w)) < WALL_NORMAL_ALONG).flatMap(({ a, b, c, normal }) => {
2417
+ const [fa, fb, fc] = [flatten(a, frame), flatten(b, frame), flatten(c, frame)];
2418
+ const air = flatten(normal, frame);
2419
+ return [
2420
+ { p: fa, q: fb, air },
2421
+ { p: fb, q: fc, air },
2422
+ { p: fc, q: fa, air }
2423
+ ];
2424
+ });
2425
+ var nearestOn = ({ p, q }, at2) => {
2426
+ const dx = q.x - p.x;
2427
+ const dy = q.y - p.y;
2428
+ const length = dx * dx + dy * dy;
2429
+ const t = length === 0 ? 0 : Math.min(1, Math.max(0, ((at2.x - p.x) * dx + (at2.y - p.y) * dy) / length));
2430
+ return { x: p.x + t * dx, y: p.y + t * dy };
2431
+ };
2432
+ var nearestWall = (segments, at2) => segments.reduce((best, segment) => {
2433
+ const point = nearestOn(segment, at2);
2434
+ const distance2 = Math.hypot(point.x - at2.x, point.y - at2.y);
2435
+ if (best && distance2 >= best.distance) return best;
2436
+ const open = (at2.x - point.x) * segment.air.x + (at2.y - point.y) * segment.air.y >= 0;
2437
+ return { point, distance: distance2, open };
2438
+ }, null);
2439
+ var fitsDiscs = (triangles, frame, discs) => {
2440
+ const points = discs.filter((disc) => disc.diameter < POINT_DISC_MM);
2441
+ const wide = discs.filter((disc) => disc.diameter >= POINT_DISC_MM);
2442
+ if (points.length > 0) {
2443
+ const flat = pointsOf(triangles).map((point) => flatten(point, frame));
2444
+ const onCorners = points.every(
2445
+ (disc) => flat.some((point) => Math.hypot(point.x - disc.x, point.y - disc.y) <= ON_CORNER_MM)
2446
+ );
2447
+ if (!onCorners) return false;
2448
+ }
2449
+ if (wide.length === 0) return points.length > 0;
2450
+ const segments = wallSegments(triangles, frame);
2451
+ if (segments.length === 0) return false;
2452
+ let touches = false;
2453
+ for (const disc of wide) {
2454
+ const nearest = nearestWall(segments, disc);
2455
+ if (!nearest || !nearest.open) return false;
2456
+ const slack = ON_WALL_MM + ON_WALL_SHARE * disc.diameter;
2457
+ const radius = disc.diameter / 2;
2458
+ if (nearest.distance < radius - slack) return false;
2459
+ if (nearest.distance <= radius + slack) touches = true;
2460
+ }
2461
+ return touches;
2462
+ };
2463
+ var placeInFrame = ({ u, v, w }, x, y, z) => add(add(scale(u, x), scale(v, y)), scale(w, z));
2464
+ var AXES = [
2465
+ [1, 0, 0],
2466
+ [0, 1, 0],
2467
+ [0, 0, 1]
2468
+ ];
2469
+ var candidateFrames = (points, zMin, zMax, direction, strict = true) => {
2470
+ const along = unit(direction);
2471
+ const frames = [];
2472
+ for (const sign of [1, -1]) {
2473
+ const w = scale(along, sign);
2474
+ const { low, high } = extent(points.map((point) => dot(point, w)));
2475
+ if (strict && (Math.abs(low - zMin) > ON_DEPTH_MM || Math.abs(high - zMax) > ON_DEPTH_MM)) {
2476
+ continue;
2477
+ }
2478
+ const across = AXES.reduce(
2479
+ (best, axis) => Math.abs(dot(axis, w)) < Math.abs(dot(best, w)) ? axis : best
2480
+ );
2481
+ const u0 = unit(add(across, scale(w, -dot(across, w))));
2482
+ const v0 = cross(w, u0);
2483
+ for (let quarter = 0; quarter < 4; quarter++) {
2484
+ const angle = quarter * Math.PI / 2;
2485
+ const u = add(scale(u0, Math.cos(angle)), scale(v0, Math.sin(angle)));
2486
+ for (const hand of [1, -1]) frames.push({ u, v: scale(cross(w, u), hand), w });
2487
+ }
2488
+ }
2489
+ return frames;
2490
+ };
2491
+ var distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
2492
+ var exactFrame = (triangles, discs, zMin, zMax, direction) => {
2493
+ const fits = candidateFrames(pointsOf(triangles), zMin, zMax, direction).filter(
2494
+ (frame) => fitsDiscs(triangles, frame, discs)
2495
+ );
2496
+ const [first] = fits;
2497
+ if (!first) return null;
2498
+ const placed = (frame) => discs.map((disc) => placeInFrame(frame, disc.x, disc.y, zMin));
2499
+ const firstPlaces = placed(first);
2500
+ const agree = fits.every(
2501
+ (frame) => placed(frame).every((at2, index) => distance(at2, firstPlaces[index] ?? at2) <= SAME_PLACE_MM)
2502
+ );
2503
+ return agree ? first : null;
2504
+ };
2505
+ var discMiss = (triangles, frame, discs) => {
2506
+ let miss = 0;
2507
+ const points = discs.filter((disc) => disc.diameter < POINT_DISC_MM);
2508
+ if (points.length > 0) {
2509
+ const flat = pointsOf(triangles).map((point) => flatten(point, frame));
2510
+ for (const disc of points) {
2511
+ miss += extent(flat.map((point) => Math.hypot(point.x - disc.x, point.y - disc.y))).low;
2512
+ }
2513
+ }
2514
+ const wide = discs.filter((disc) => disc.diameter >= POINT_DISC_MM);
2515
+ if (wide.length === 0) return miss;
2516
+ const segments = wallSegments(triangles, frame);
2517
+ let touch = Infinity;
2518
+ for (const disc of wide) {
2519
+ const radius = disc.diameter / 2;
2520
+ const nearest = nearestWall(segments, disc);
2521
+ if (!nearest) return Infinity;
2522
+ if (!nearest.open) miss += disc.diameter * 4;
2523
+ miss += Math.max(0, radius - nearest.distance);
2524
+ touch = Math.min(touch, Math.abs(nearest.distance - radius));
2525
+ }
2526
+ return miss + touch;
2527
+ };
2528
+ var bestFrame = (triangles, discs, zMin, zMax, direction) => {
2529
+ if (triangles.length === 0 || discs.length === 0) return null;
2530
+ const exact = exactFrame(triangles, discs, zMin, zMax, direction);
2531
+ if (exact) return { frame: exact, lift: 0 };
2532
+ const points = pointsOf(triangles);
2533
+ const fitting = candidateFrames(points, zMin, zMax, direction);
2534
+ const frames = fitting.length > 0 ? fitting : candidateFrames(points, zMin, zMax, direction, false);
2535
+ const best = frames.reduce((was, frame) => {
2536
+ const miss = discMiss(triangles, frame, discs);
2537
+ return !was || miss < was.miss ? { frame, miss } : was;
2538
+ }, null);
2539
+ if (!best) return null;
2540
+ const { low } = extent(points.map((point) => dot(point, best.frame.w)));
2541
+ return { frame: best.frame, lift: fitting.length > 0 ? 0 : low - zMin };
2542
+ };
2543
+ var asVec = ([x, y, z]) => ({ x, y, z });
2544
+ var placePinchTool = (mark, triangles, direction, origin = { x: 0, y: 0, z: 0 }) => {
2545
+ const shift = [origin.x, origin.y, origin.z];
2546
+ const faces = readTriangles(triangles, shift);
2547
+ const found = bestFrame(faces, mark.discs, mark.zMin, mark.zMax, [
2548
+ direction.x,
2549
+ direction.y,
2550
+ direction.z
2551
+ ]);
2552
+ const disc = mark.discs.reduce(
2553
+ (tightest, each) => !tightest || each.diameter < tightest.diameter ? each : tightest,
2554
+ null
2555
+ );
2556
+ if (!found || !disc) return null;
2557
+ const { frame, lift } = found;
2558
+ const radius = disc.diameter / 2;
2559
+ const base = add(placeInFrame(frame, disc.x, disc.y, mark.zMin + lift), shift);
2560
+ const contact = nearestWall(wallSegments(faces, frame), disc)?.point;
2561
+ const toward = contact ? { x: contact.x - disc.x, y: contact.y - disc.y } : { x: 1, y: 0 };
2562
+ const length = Math.hypot(toward.x, toward.y);
2563
+ const across = add(
2564
+ scale(frame.u, length > 1e-9 ? toward.x / length : 1),
2565
+ scale(frame.v, length > 1e-9 ? toward.y / length : 0)
2566
+ );
2567
+ return {
2568
+ base: asVec(base),
2569
+ axis: asVec(frame.w),
2570
+ diameter: disc.diameter,
2571
+ height: Math.max(mark.zMax - mark.zMin, MIN_HEIGHT_MM),
2572
+ cornerRadius: Math.min(Math.max(mark.corner ?? 0, 0), radius),
2573
+ across: asVec(across)
2574
+ };
2575
+ };
2576
+
2577
+ // src/model/reach.ts
2578
+ var numbers = (value) => Array.isArray(value) && value.every((each) => typeof each === "number" && Number.isFinite(each)) ? value : null;
2579
+ var readReachCurve = (datasheet) => {
2580
+ const curve = datasheet?.reachCurve;
2581
+ const offsets = numbers(curve?.horizontalOffset);
2582
+ const heights = numbers(curve?.verticalOffset);
2583
+ if (!offsets || !heights || offsets.length === 0 || offsets.length !== heights.length) return null;
2584
+ return { offsets, heights };
2585
+ };
2586
+ var runStart = ({ offsets }, index) => index === 0 ? 0 : offsets[index - 1] ?? 0;
2587
+ var peakHeight = ({ heights }) => Math.max(0, ...heights);
2588
+ var TAIL_MM = 12.7;
2589
+ var peakSlack = (peak) => Math.max(0.05, peak * 0.01);
2590
+ var peakStart = (curve) => {
2591
+ const peak = peakHeight(curve);
2592
+ const slack = peakSlack(peak);
2593
+ const index = curve.heights.findIndex((height) => height >= peak - slack);
2594
+ return runStart(curve, index === -1 ? 0 : index);
2595
+ };
2596
+ var trimmedCurve = (curve) => {
2597
+ const last = curve.offsets[curve.offsets.length - 1] ?? 0;
2598
+ const extent2 = peakStart(curve) + TAIL_MM;
2599
+ if (extent2 >= last) return { curve, cut: false };
2600
+ const keep = curve.offsets.findIndex((offset) => offset >= extent2);
2601
+ return {
2602
+ curve: {
2603
+ offsets: [...curve.offsets.slice(0, keep), extent2],
2604
+ heights: curve.heights.slice(0, keep + 1)
2605
+ },
2606
+ cut: true
2607
+ };
2608
+ };
2609
+ var featureAcross = (sheet) => {
2610
+ if (sheet?.diameter !== void 0 && sheet.diameter > 0)
2611
+ return { width: sheet.diameter, kind: "diameter" };
2612
+ if (sheet?.pinchDiameter !== void 0 && sheet.pinchDiameter > 0)
2613
+ return { width: sheet.pinchDiameter, kind: "clearance" };
2614
+ return null;
2615
+ };
2616
+ var isThroughType = (featureType) => /(^|_)through(_|$)/.test(featureType.toLowerCase());
2617
+ var featureProfile = (sheet, featureType) => {
2618
+ const depth = sheet?.zMax !== void 0 && sheet.zMin !== void 0 ? sheet.zMax - sheet.zMin : null;
2619
+ return {
2620
+ across: featureAcross(sheet),
2621
+ depth: depth !== null && depth > 0 ? depth : null,
2622
+ through: isThroughType(featureType)
2623
+ };
2624
+ };
1369
2625
 
1370
2626
  // src/model/rule-set-file.ts
1371
2627
  var FILE_KIND = "toolpath-dfm-rules";
@@ -1528,8 +2784,8 @@ var llmRulePrompt = (current = [], vocabulary = MILLING_RULES) => {
1528
2784
  const groups = vocabulary.subjects.filter((each) => !each.value.startsWith(TYPE_SUBJECT));
1529
2785
  const types = vocabulary.subjects.filter((each) => each.value.startsWith(TYPE_SUBJECT));
1530
2786
  const metricLines = vocabulary.metrics.map((metric) => {
1531
- const unit = quantityUnit(metric.quantity, "mm");
1532
- const kind = metric.quantity === "flag" ? 'yes/no \u2014 write `op: "gte"` and `value: 0`; the rule fires whenever it is so' : metric.quantity === "presence" ? 'no measurement \u2014 write `op: "gte"` and `value: 0`; flags every feature of the subject' : `${metric.quantity}${unit ? `, in ${unit}` : ""}; a new rule usually starts around ${metric.start.mm}`;
2787
+ const unit2 = quantityUnit(metric.quantity, "mm");
2788
+ const kind = metric.quantity === "flag" ? 'yes/no \u2014 write `op: "gte"` and `value: 0`; the rule fires whenever it is so' : metric.quantity === "presence" ? 'no measurement \u2014 write `op: "gte"` and `value: 0`; flags every feature of the subject' : `${metric.quantity}${unit2 ? `, in ${unit2}` : ""}; a new rule usually starts around ${metric.start.mm}`;
1533
2789
  const kinds = metric.kinds ? ` Only features of kind ${metric.kinds.join("/")} report it.` : "";
1534
2790
  return `- \`${metric.key}\` \u2014 "${metric.label}" (${kind}). ${metric.hint}.${kinds}`;
1535
2791
  });
@@ -1898,52 +3154,203 @@ var TURNING_RULES = {
1898
3154
  fileName: "dfm-turning-rules.json"
1899
3155
  };
1900
3156
 
1901
- // src/model/reach.ts
1902
- var numbers = (value) => Array.isArray(value) && value.every((each) => typeof each === "number" && Number.isFinite(each)) ? value : null;
1903
- var readReachCurve = (datasheet) => {
1904
- const curve = datasheet?.reachCurve;
1905
- const offsets = numbers(curve?.horizontalOffset);
1906
- const heights = numbers(curve?.verticalOffset);
1907
- if (!offsets || !heights || offsets.length === 0 || offsets.length !== heights.length) return null;
1908
- return { offsets, heights };
3157
+ // src/model/turned-check.ts
3158
+ var regionsOf = (feature) => Array.isArray(feature.regionIdxs) ? feature.regionIdxs : [];
3159
+ var stretchKey = (feature) => {
3160
+ const regions = regionsOf(feature);
3161
+ return regions.length === 0 ? `tag:${feature.featureTag}` : `${feature.featureType}:${[...regions].sort((a, b) => a - b).join(",")}`;
1909
3162
  };
1910
- var runStart = ({ offsets }, index) => index === 0 ? 0 : offsets[index - 1] ?? 0;
1911
- var peakHeight = ({ heights }) => Math.max(0, ...heights);
1912
- var TAIL_MM = 12.7;
1913
- var peakSlack = (peak) => Math.max(0.05, peak * 0.01);
1914
- var peakStart = (curve) => {
1915
- const peak = peakHeight(curve);
1916
- const slack = peakSlack(peak);
1917
- const index = curve.heights.findIndex((height) => height >= peak - slack);
1918
- return runStart(curve, index === -1 ? 0 : index);
3163
+ var isApproach = (value) => value === "PlusZ" || value === "MinusZ";
3164
+ var turnedStretches = (features) => {
3165
+ const groups = /* @__PURE__ */ new Map();
3166
+ for (const feature of features) {
3167
+ const key = stretchKey(feature);
3168
+ groups.set(key, [...groups.get(key) ?? [], feature]);
3169
+ }
3170
+ const merged = [...groups.values()].flatMap((copies) => {
3171
+ const [first] = copies;
3172
+ if (!first) return [];
3173
+ const approaches = [...new Set(copies.map((each) => each.approach).filter(isApproach))];
3174
+ const only = approaches.length === 1 ? approaches[0] : void 0;
3175
+ const z = only === "PlusZ" ? 1 : only === "MinusZ" ? -1 : 0;
3176
+ return [{ first, copies, approaches, machiningDirection: { x: 0, y: 0, z } }];
3177
+ });
3178
+ const numbered = dfmFeatures(
3179
+ merged.map(({ first, machiningDirection }) => ({
3180
+ featureTag: first.featureTag,
3181
+ featureType: first.featureType,
3182
+ machiningDirection,
3183
+ regionIdxs: regionsOf(first)
3184
+ }))
3185
+ );
3186
+ return merged.flatMap(({ copies, approaches }, at2) => {
3187
+ const feature = numbered[at2];
3188
+ return feature ? [{ ...feature, copies, approaches }] : [];
3189
+ });
1919
3190
  };
1920
- var trimmedCurve = (curve) => {
1921
- const last = curve.offsets[curve.offsets.length - 1] ?? 0;
1922
- const extent = peakStart(curve) + TAIL_MM;
1923
- if (extent >= last) return { curve, cut: false };
1924
- const keep = curve.offsets.findIndex((offset) => offset >= extent);
1925
- return {
1926
- curve: {
1927
- offsets: [...curve.offsets.slice(0, keep), extent],
1928
- heights: curve.heights.slice(0, keep + 1)
1929
- },
1930
- cut: true
3191
+ var record = (value) => typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
3192
+ var finite = (value) => typeof value === "number" && Number.isFinite(value) ? value : null;
3193
+ var ratio = (top, bottom) => top !== null && bottom !== null && bottom > 0 ? top / bottom : null;
3194
+ var narrowestStep = (facts) => {
3195
+ const steps = Array.isArray(facts.steps) ? facts.steps : [];
3196
+ const diameters = steps.map((step) => finite(record(step)?.diameter)).filter((each) => each !== null && each > 0);
3197
+ return diameters.length > 0 ? Math.min(...diameters) : null;
3198
+ };
3199
+ var threadSpec = (facts, field) => finite(record(facts.threadSpec)?.[field]) ?? finite(record(record(facts.thread)?.threadSpec)?.[field]);
3200
+ var partEnds = (stretches) => {
3201
+ const zs = stretches.flatMap(
3202
+ (stretch) => stretch.copies.flatMap((copy) => {
3203
+ const sheet = record(copy.datasheet);
3204
+ return [finite(sheet?.zMin), finite(sheet?.zMax)].filter(
3205
+ (each) => each !== null
3206
+ );
3207
+ })
3208
+ );
3209
+ return zs.length > 0 ? { low: Math.min(...zs), high: Math.max(...zs) } : null;
3210
+ };
3211
+ var turnedLd = (sheet, facts, kind, approach, ends) => {
3212
+ if (kind === "AxialHole") return ratio(finite(facts.depth), narrowestStep(facts));
3213
+ const inside = ID_KINDS;
3214
+ if (!kind || !inside.includes(kind) || !ends || !approach) return null;
3215
+ const zMin = finite(sheet.zMin);
3216
+ const zMax = finite(sheet.zMax);
3217
+ const reach = approach === "PlusZ" ? zMin === null ? null : ends.high - zMin : zMax === null ? null : zMax - ends.low;
3218
+ const rMin = finite(sheet.rMin);
3219
+ const bore = finite(sheet.entryDiameter) ?? (rMin === null ? null : 2 * rMin);
3220
+ return ratio(reach, bore);
3221
+ };
3222
+ var HAIR = 1e-3;
3223
+ var FLAT_CONE = 179.5;
3224
+ var copyMeasure = (metric, copy, ends) => {
3225
+ const sheet = record(copy.datasheet);
3226
+ if (!sheet) return null;
3227
+ const facts = record(sheet.facts) ?? {};
3228
+ const kind = typeof facts.kind === "string" ? facts.kind : kindOfType(copy.featureType);
3229
+ const kinds = metric.kinds;
3230
+ if (kinds && !(kind && kinds.includes(kind))) return null;
3231
+ const doubled = (value) => {
3232
+ const radius = finite(value);
3233
+ return radius === null ? null : 2 * radius;
1931
3234
  };
3235
+ switch (metric.key) {
3236
+ case "maxDiameter":
3237
+ return doubled(sheet.rMax);
3238
+ case "minDiameter":
3239
+ return doubled(sheet.rMin);
3240
+ case "length": {
3241
+ const zMin = finite(sheet.zMin);
3242
+ const zMax = finite(sheet.zMax);
3243
+ return zMin === null || zMax === null || zMax - zMin < HAIR ? null : zMax - zMin;
3244
+ }
3245
+ case "ld":
3246
+ return turnedLd(sheet, facts, kind, copy.approach ?? null, ends);
3247
+ case "grooveWidth":
3248
+ return finite(facts.width);
3249
+ case "grooveDepth":
3250
+ case "threadDepth":
3251
+ case "holeDepth":
3252
+ return finite(facts.depth);
3253
+ case "grooveAspect":
3254
+ return ratio(finite(facts.depth), finite(facts.width));
3255
+ case "threadPitch":
3256
+ return finite(facts.pitch) ?? threadSpec(facts, "threadPitch");
3257
+ case "threadDiameter":
3258
+ return threadSpec(facts, "basicDiameter");
3259
+ case "holeDiameter":
3260
+ return narrowestStep(facts);
3261
+ case "holeSteps":
3262
+ return Array.isArray(facts.steps) ? facts.steps.length : null;
3263
+ case "flatBottom": {
3264
+ if (facts.bottom === void 0) return 0;
3265
+ const cone = finite(record(facts.bottom)?.coneDeg);
3266
+ return cone === null ? null : cone >= FLAT_CONE ? 1 : 0;
3267
+ }
3268
+ // Zero is a figure here: a sharp corner, which a "radius ≤" rule is most of all about.
3269
+ case "cornerRadius":
3270
+ return finite(sheet.minConcaveRadius);
3271
+ case "sharpCorner": {
3272
+ const radius = finite(sheet.minConcaveRadius);
3273
+ return radius === null ? 0 : radius <= HAIR ? 1 : 0;
3274
+ }
3275
+ // Absent where nothing stands between the feature and its end: nothing to pass, so clean.
3276
+ case "entryDiameter":
3277
+ return finite(sheet.entryDiameter);
3278
+ case "axialTool":
3279
+ return typeof sheet.mounting === "string" ? sheet.mounting === "Axial" ? 1 : 0 : null;
3280
+ case "tolerance":
3281
+ return finite(record(sheet.toleranceBand)?.atolMax);
3282
+ default:
3283
+ return null;
3284
+ }
1932
3285
  };
1933
- var featureAcross = (sheet) => {
1934
- if (sheet?.diameter !== void 0 && sheet.diameter > 0)
1935
- return { width: sheet.diameter, kind: "diameter" };
1936
- if (sheet?.pinchDiameter !== void 0 && sheet.pinchDiameter > 0)
1937
- return { width: sheet.pinchDiameter, kind: "clearance" };
1938
- return null;
3286
+ var kindOfType = (featureType) => featureType.split("_").map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join("");
3287
+ var stretchFacts = (stretch) => stretch.copies.map((copy) => record(record(copy.datasheet)?.facts)).find((each) => each !== void 0);
3288
+ var stretchIs = (subject, stretch) => {
3289
+ const type = stretch.featureType.toLowerCase();
3290
+ if (subject.startsWith(TYPE_SUBJECT)) return type === subject.slice(TYPE_SUBJECT.length);
3291
+ const facts = stretchFacts(stretch);
3292
+ const kind = typeof facts?.kind === "string" ? facts.kind : kindOfType(type);
3293
+ const hole = kind === "AxialHole";
3294
+ switch (subject) {
3295
+ case "any":
3296
+ return true;
3297
+ case "thread":
3298
+ return kind === "OdThread" || kind === "IdThread" || hole && record(facts?.thread) !== void 0;
3299
+ case "throughHole":
3300
+ return hole && facts?.through === true;
3301
+ case "blindHole":
3302
+ return hole && facts?.through === false;
3303
+ case "threadedHole":
3304
+ return hole && record(facts?.thread) !== void 0;
3305
+ default: {
3306
+ const kinds = subjectInfo(subject, TURNING_RULES)?.kinds;
3307
+ return kinds !== void 0 && kinds.includes(kind);
3308
+ }
3309
+ }
1939
3310
  };
1940
- var isThroughType = (featureType) => /(^|_)through(_|$)/.test(featureType.toLowerCase());
1941
- var featureProfile = (sheet, featureType) => {
1942
- const depth = sheet?.zMax !== void 0 && sheet.zMin !== void 0 ? sheet.zMax - sheet.zMin : null;
3311
+ var stretchHit = (stretch, rule, metric, ends) => {
3312
+ if (metric.quantity === "presence") return { rule, metric, value: 1 };
3313
+ const measured = stretch.copies.filter((copy) => record(copy.datasheet) !== void 0);
3314
+ if (measured.length === 0) return null;
3315
+ const values = [];
3316
+ for (const copy of measured) {
3317
+ const value2 = copyMeasure(metric, copy, ends);
3318
+ if (value2 === null || !breaks(rule, metric.quantity, value2)) return null;
3319
+ values.push(value2);
3320
+ }
3321
+ const value = worseUpward(rule, metric) ? Math.min(...values) : Math.max(...values);
3322
+ return { rule, metric, value };
3323
+ };
3324
+ var checkTurnedPart = (stretches, rules) => {
3325
+ const ends = partEnds(stretches);
3326
+ const hitsByTag = new Map(
3327
+ stretches.map((stretch) => [
3328
+ stretch.tag.toLowerCase(),
3329
+ rules.flatMap((rule) => {
3330
+ const metric = metricInfo(rule.metric, TURNING_RULES);
3331
+ if (!metric || !stretchIs(rule.subject, stretch)) return [];
3332
+ const hit = stretchHit(stretch, rule, metric, ends);
3333
+ return hit ? [hit] : [];
3334
+ })
3335
+ ])
3336
+ );
3337
+ const required = new Set(stretches.map((stretch) => stretch.tag.toLowerCase()));
3338
+ const paintedFaces = /* @__PURE__ */ new Map();
3339
+ for (const stretch of stretches) {
3340
+ const color = worstColor(hitsByTag.get(stretch.tag.toLowerCase()));
3341
+ if (!color) continue;
3342
+ for (const region of stretch.regionIdxs) {
3343
+ const painted = paintedFaces.get(region);
3344
+ if (!painted || compareColors(color, painted.color) < 0)
3345
+ paintedFaces.set(region, { tag: stretch.tag, color });
3346
+ }
3347
+ }
1943
3348
  return {
1944
- across: featureAcross(sheet),
1945
- depth: depth !== null && depth > 0 ? depth : null,
1946
- through: isThroughType(featureType)
3349
+ hitsByTag,
3350
+ required,
3351
+ byRule: ruleResults(rules, stretches, hitsByTag, required),
3352
+ paintedFaces,
3353
+ paintedWhole: /* @__PURE__ */ new Map()
1947
3354
  };
1948
3355
  };
1949
3356
 
@@ -1951,16 +3358,11 @@ export {
1951
3358
  directionLabel,
1952
3359
  dfmFeatures,
1953
3360
  featureTypeLabel,
1954
- partTop,
1955
- isDrilled,
1956
- featureLd,
1957
3361
  PRESENCE_METRIC,
1958
- TYPE_SUBJECT,
3362
+ QUICK_SUBJECTS,
1959
3363
  MILLING_RULES,
1960
- subjectInfo,
1961
3364
  metricInfo,
1962
3365
  metricsForSubject,
1963
- LENGTH_PLACES,
1964
3366
  lengthValue,
1965
3367
  unitLabel,
1966
3368
  OPS,
@@ -1984,22 +3386,37 @@ export {
1984
3386
  withMetric,
1985
3387
  withOp,
1986
3388
  withSubject,
1987
- breaks,
1988
- worseUpward,
1989
3389
  parseRules,
3390
+ hitFigure,
3391
+ brokenRules,
3392
+ featureColor,
3393
+ withSurroundedFaces,
3394
+ checkPart,
3395
+ readPinch,
3396
+ PINCH_TOOL_MM,
3397
+ isNoReading,
3398
+ featureSheet,
3399
+ isSurfaceType,
3400
+ maxBallDiameter,
3401
+ featureMeasurements,
3402
+ MAX_DATASHEET_FIELDS,
3403
+ datasheetFields,
1990
3404
  sameDepth,
1991
3405
  featureRows,
1992
- hitFigure,
3406
+ pinchMark,
3407
+ pinchLabel,
3408
+ placePinchTool,
3409
+ readReachCurve,
3410
+ runStart,
3411
+ peakHeight,
3412
+ trimmedCurve,
3413
+ featureProfile,
1993
3414
  FILE_KIND,
1994
3415
  serializeRuleSet,
1995
3416
  parseRuleSetFile,
1996
3417
  llmRulePrompt,
1997
- ID_KINDS,
1998
3418
  turnedTypeLabel,
1999
3419
  TURNING_RULES,
2000
- readReachCurve,
2001
- runStart,
2002
- peakHeight,
2003
- trimmedCurve,
2004
- featureProfile
3420
+ turnedStretches,
3421
+ checkTurnedPart
2005
3422
  };