@toolpath/dfm 0.0.0-stage → 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.
@@ -0,0 +1,1047 @@
1
+ import {
2
+ CRITICAL_COLOR,
3
+ FILE_KIND,
4
+ LENGTH_PLACES,
5
+ RULE_COLORS,
6
+ TYPE_SUBJECT,
7
+ WARNING_COLOR,
8
+ breaks,
9
+ compareColors,
10
+ describeRule,
11
+ dfmFeatures,
12
+ featureLd,
13
+ featureProfile,
14
+ featureTypeLabel,
15
+ hitFigure,
16
+ isDrilled,
17
+ lengthValue,
18
+ llmRulePrompt,
19
+ makeRule,
20
+ metricInfo,
21
+ parseRuleSetFile,
22
+ parseRules,
23
+ partTop,
24
+ peakHeight,
25
+ readReachCurve,
26
+ runStart,
27
+ sameDepth,
28
+ serializeRuleSet,
29
+ trimmedCurve,
30
+ unitLabel,
31
+ worseUpward
32
+ } from "../chunk-5MPHT7BC.js";
33
+
34
+ // src/model/broken-rules.ts
35
+ var byColor = (hits) => [...hits].sort((a, b) => compareColors(a.rule.color, b.rule.color));
36
+ var worstHits = (hits) => {
37
+ const seen = /* @__PURE__ */ new Set();
38
+ return byColor(hits).filter((hit) => {
39
+ if (seen.has(hit.metric.key)) return false;
40
+ seen.add(hit.metric.key);
41
+ return true;
42
+ });
43
+ };
44
+ var brokenRules = (check, tag, units) => worstHits(check.hitsByTag.get(tag.toLowerCase()) ?? []).map((hit) => {
45
+ const figure = hitFigure(hit, units);
46
+ return {
47
+ key: hit.rule.id,
48
+ color: hit.rule.color,
49
+ text: describeRule(hit.rule, units),
50
+ ...figure ? { figure } : {}
51
+ };
52
+ });
53
+ var featureColor = (check, tag, region = null) => {
54
+ const key = tag.toLowerCase();
55
+ const face = region === null ? void 0 : check.paintedFaces.get(region);
56
+ if (face && face.tag.toLowerCase() === key) return face.color;
57
+ const whole = check.paintedWhole.get(key);
58
+ if (whole) return whole.color;
59
+ if (!check.required.has(key)) return void 0;
60
+ return byColor(check.hitsByTag.get(key) ?? [])[0]?.rule.color;
61
+ };
62
+
63
+ // src/model/dfm-flags.ts
64
+ var howCut = (sheet) => {
65
+ const drilled = isDrilled(sheet);
66
+ return { drilled, milled: !drilled };
67
+ };
68
+ var featureIs = (subject, featureType, sheet) => {
69
+ const type = featureType.toLowerCase();
70
+ const kind = sheet?.kind?.toLowerCase() ?? "";
71
+ if (subject.startsWith(TYPE_SUBJECT)) return type === subject.slice(TYPE_SUBJECT.length);
72
+ switch (subject) {
73
+ case "any":
74
+ return true;
75
+ case "milled":
76
+ return howCut(sheet).milled;
77
+ case "drilled":
78
+ return howCut(sheet).drilled;
79
+ case "hole":
80
+ return type.includes("hole") || kind === "hole";
81
+ case "threadedHole":
82
+ return sheet?.threading !== void 0;
83
+ case "pocket":
84
+ return type.includes("pocket") || kind === "pocket";
85
+ case "slot":
86
+ return type.includes("slot") || kind === "tslot";
87
+ case "undercut":
88
+ return kind === "tslot" || type.includes("undercut") || type.includes("tslot");
89
+ case "contour":
90
+ return type.includes("contour") || kind.includes("contour");
91
+ case "wall":
92
+ return type.includes("wall") || kind === "wall";
93
+ case "face":
94
+ return type === "face" || kind === "face";
95
+ case "fillet":
96
+ return type.split("_").includes("fillet") || kind.includes("fillet");
97
+ case "chamfer":
98
+ return type.includes("chamfer") || kind === "chamfer";
99
+ case "boss":
100
+ return type.includes("boss") || kind === "boss";
101
+ case "countersink":
102
+ return type === "sink";
103
+ case "profile":
104
+ return type === "profile" || kind === "profile";
105
+ default:
106
+ return false;
107
+ }
108
+ };
109
+ var at = (record, path) => path.split(".").reduce(
110
+ (value, key) => typeof value === "object" && value !== null ? value[key] : void 0,
111
+ record
112
+ );
113
+ var readPath = (datasheet, metric) => {
114
+ for (const path of metric.path ?? []) {
115
+ const value = at(datasheet, path);
116
+ if (value === void 0 || value === null) continue;
117
+ if (typeof value === "boolean") return value ? 1 : 0;
118
+ if (metric.quantity === "flag") return 1;
119
+ if (typeof value === "number" && Number.isFinite(value)) return value;
120
+ return null;
121
+ }
122
+ return metric.quantity === "flag" && metric.path ? 0 : null;
123
+ };
124
+ var TILT = 1e-6;
125
+ var isTilted = ({ x, y, z }) => [x, y, z].filter((each) => Math.abs(each) > TILT).length > 1;
126
+ var featureMeasure = (metric, features, feature, { sheets, datasheets, regionAreas }) => {
127
+ const tag = feature.tag.toLowerCase();
128
+ const sheet = sheets[tag];
129
+ const datasheet = datasheets[tag];
130
+ const positive = (value) => value !== void 0 && value > 0 ? { value } : null;
131
+ switch (metric.key) {
132
+ case "present":
133
+ return { value: 1 };
134
+ case "tilted":
135
+ return { value: isTilted(feature.machiningDirection) ? 1 : 0 };
136
+ case "faceCount":
137
+ return { value: new Set(feature.regionIdxs).size };
138
+ case "ld": {
139
+ const ld = featureLd(features, feature, sheets);
140
+ return ld ? { value: ld.ratio, drilling: ld.drilling } : null;
141
+ }
142
+ case "featureLd": {
143
+ const ld = featureLd(features, feature, sheets);
144
+ return ld?.featureRatio !== void 0 ? { value: ld.featureRatio, drilling: ld.drilling } : null;
145
+ }
146
+ case "depthBelowTop": {
147
+ const top = partTop(features, sheets, feature.machiningDirection);
148
+ return top !== null && sheet?.zMin !== void 0 ? { value: top - sheet.zMin } : null;
149
+ }
150
+ case "featureDepth":
151
+ return sheet?.zMax !== void 0 && sheet.zMin !== void 0 ? { value: sheet.zMax - sheet.zMin } : null;
152
+ // Zero is no measure at all for these: no bore, no tool, a sharp floor rather than a tiny fillet.
153
+ case "diameter":
154
+ return positive(sheet?.diameter);
155
+ // Zero is a measure here: a sharp corner, which a "radius ≤" rule is most of all about.
156
+ case "cornerRadius":
157
+ return sheet?.cornerRadius === void 0 ? null : { value: sheet.cornerRadius };
158
+ case "maxTool":
159
+ return positive(sheet?.maxTool);
160
+ case "floorFillet":
161
+ return positive(sheet?.filletRadius);
162
+ case "sharpCorner":
163
+ return sheet ? { value: sheet.sharpCorners ? 1 : 0 } : null;
164
+ case "noToolFits":
165
+ return sheet ? { value: sheet.noToolFits ? 1 : 0 } : null;
166
+ case "pinchPoints": {
167
+ const points = at(datasheet, "pinchPoints");
168
+ return Array.isArray(points) ? { value: points.length } : null;
169
+ }
170
+ // A disc under a hundredth is a sharp corner, which `sharpCorner` is for: see `pinchDiameter`.
171
+ case "pinchDiameter":
172
+ return positive(sheet?.pinchDiameter);
173
+ case "reachHeight": {
174
+ const heights = at(datasheet, "reachCurve.verticalOffset");
175
+ const numbers = Array.isArray(heights) ? heights.filter(
176
+ (each) => typeof each === "number" && Number.isFinite(each)
177
+ ) : [];
178
+ return numbers.length > 0 ? { value: Math.max(...numbers) } : null;
179
+ }
180
+ case "surfaceArea": {
181
+ const areas = at(datasheet, "areas");
182
+ if (typeof areas === "object" && areas !== null) {
183
+ const parts = Object.values(areas).filter(
184
+ (each) => typeof each === "number" && Number.isFinite(each)
185
+ );
186
+ if (parts.length > 0) return { value: parts.reduce((sum, each) => sum + each, 0) };
187
+ }
188
+ const faces = [...new Set(feature.regionIdxs)].flatMap(
189
+ (region) => regionAreas.get(region) ?? []
190
+ );
191
+ return faces.length > 0 ? { value: faces.reduce((sum, each) => sum + each, 0) } : null;
192
+ }
193
+ default: {
194
+ if (!datasheet) return null;
195
+ const value = readPath(datasheet, metric);
196
+ return value === null ? null : { value };
197
+ }
198
+ }
199
+ };
200
+ var featureHits = (features, feature, sources, rules) => {
201
+ const sheet = sources.sheets[feature.tag.toLowerCase()];
202
+ return rules.flatMap((rule) => {
203
+ const info = metricInfo(rule.metric);
204
+ if (!info || !featureIs(rule.subject, feature.featureType, sheet)) return [];
205
+ const measured = featureMeasure(info, features, feature, sources);
206
+ if (!measured || !breaks(rule, info.quantity, measured.value)) return [];
207
+ return [{ rule, metric: info, ...measured }];
208
+ });
209
+ };
210
+ var requiredTags = (features) => {
211
+ const owners = /* @__PURE__ */ new Map();
212
+ for (const feature of features) {
213
+ for (const region of new Set(feature.regionIdxs))
214
+ owners.set(region, (owners.get(region) ?? 0) + 1);
215
+ }
216
+ return new Set(
217
+ features.filter((feature) => feature.regionIdxs.some((region) => owners.get(region) === 1)).map((feature) => feature.tag.toLowerCase())
218
+ );
219
+ };
220
+ var QUALIFIERS = ["undercut", "filleted", "tslot", "dovetail"];
221
+ var EDGE_TYPES = ["fillet", "chamfer", "sink"];
222
+ var featureComplexity = (featureType) => {
223
+ const words = featureType.toLowerCase().split("_");
224
+ const edge = EDGE_TYPES.some((type) => words.includes(type)) ? 1 : 0;
225
+ return edge + QUALIFIERS.filter((word) => words.includes(word)).length;
226
+ };
227
+ var CONTOUR = "contour_surface";
228
+ var unavoidableFaces = (features, hitsByTag, regionAreas) => {
229
+ const worstColor = (feature) => hitsByTag.get(feature.tag.toLowerCase())?.map((hit) => hit.rule.color).sort(compareColors)[0];
230
+ const areaOf = (feature) => [...new Set(feature.regionIdxs)].reduce(
231
+ (sum, region) => sum + (regionAreas.get(region) ?? 0),
232
+ 0
233
+ );
234
+ const owners = /* @__PURE__ */ new Map();
235
+ for (const feature of features) {
236
+ for (const region of new Set(feature.regionIdxs)) {
237
+ owners.set(region, [...owners.get(region) ?? [], feature]);
238
+ }
239
+ }
240
+ const faces = /* @__PURE__ */ new Map();
241
+ const whole = /* @__PURE__ */ new Map();
242
+ for (const [region, candidates] of owners) {
243
+ const colored = candidates.map((feature) => ({
244
+ feature,
245
+ color: worstColor(feature),
246
+ area: areaOf(feature)
247
+ }));
248
+ const isContour = ({ feature }) => feature.featureType === CONTOUR;
249
+ const machined = colored.filter((each) => !isContour(each));
250
+ const pool = machined.length > 0 ? machined : colored;
251
+ if (pool.some(({ color }) => color === void 0)) continue;
252
+ const contour = colored.filter(isContour).reduce((kept, each) => kept === void 0 || each.area > kept.area ? each : kept, void 0);
253
+ if (contour?.color && colored.every(({ color }) => color !== void 0)) {
254
+ whole.set(contour.feature.tag.toLowerCase(), {
255
+ tag: contour.feature.tag,
256
+ color: contour.color
257
+ });
258
+ continue;
259
+ }
260
+ const best = pool.reduce((kept, each) => {
261
+ const plainer = featureComplexity(kept.feature.featureType) - featureComplexity(each.feature.featureType);
262
+ if (plainer !== 0) return plainer > 0 ? each : kept;
263
+ const milder = compareColors(each.color ?? "", kept.color ?? "");
264
+ return milder > 0 || milder === 0 && each.area > kept.area ? each : kept;
265
+ });
266
+ if (best.color) faces.set(region, { tag: best.feature.tag, color: best.color });
267
+ }
268
+ return { paintedFaces: faces, paintedWhole: whole };
269
+ };
270
+ var withSurroundedFaces = (check, features, adjacency) => {
271
+ const paintedFor = new Map(check.paintedFaces);
272
+ const regionsOf = /* @__PURE__ */ new Map();
273
+ for (const feature of features) {
274
+ const key = feature.tag.toLowerCase();
275
+ regionsOf.set(key, new Set(feature.regionIdxs));
276
+ const whole = check.paintedWhole.get(key);
277
+ if (whole) {
278
+ for (const region of feature.regionIdxs)
279
+ if (!paintedFor.has(region)) paintedFor.set(region, whole);
280
+ }
281
+ }
282
+ const surrounded = /* @__PURE__ */ new Map();
283
+ for (const [region, neighbours] of adjacency) {
284
+ if (paintedFor.has(region)) continue;
285
+ const counts = /* @__PURE__ */ new Map();
286
+ for (const neighbour of neighbours) {
287
+ const paint2 = neighbour === region ? void 0 : paintedFor.get(neighbour);
288
+ if (!paint2) continue;
289
+ const key = paint2.tag.toLowerCase();
290
+ counts.set(key, { paint: paint2, count: (counts.get(key)?.count ?? 0) + 1 });
291
+ }
292
+ const most = Math.max(0, ...[...counts.values()].map(({ count }) => count));
293
+ const [paint] = [...counts].filter(([key, { count }]) => count === most && regionsOf.get(key)?.has(region)).map(([, { paint: paint2 }]) => paint2).sort((a, b) => compareColors(a.color, b.color));
294
+ if (paint) surrounded.set(region, paint);
295
+ }
296
+ if (surrounded.size === 0) return check;
297
+ return { ...check, paintedFaces: new Map([...check.paintedFaces, ...surrounded]) };
298
+ };
299
+ var checkPart = (features, sources, rules) => {
300
+ const required = requiredTags(features);
301
+ const hitsByTag = new Map(
302
+ features.map((feature) => [
303
+ feature.tag.toLowerCase(),
304
+ featureHits(features, feature, sources, rules)
305
+ ])
306
+ );
307
+ const byRule = rules.map((rule) => {
308
+ const hits = features.flatMap((feature) => {
309
+ const tag = feature.tag.toLowerCase();
310
+ const hit = hitsByTag.get(tag)?.find((each) => each.rule.id === rule.id);
311
+ return hit ? [{ tag: feature.tag, value: hit.value, metric: hit.metric, required: required.has(tag) }] : [];
312
+ });
313
+ const [first] = hits;
314
+ const up = first ? worseUpward(rule, first.metric) : true;
315
+ hits.sort((a, b) => up ? b.value - a.value : a.value - b.value);
316
+ return {
317
+ rule,
318
+ tags: hits.filter((hit) => hit.required).map((hit) => hit.tag),
319
+ otherTags: hits.filter((hit) => !hit.required).map((hit) => hit.tag)
320
+ };
321
+ });
322
+ return {
323
+ hitsByTag,
324
+ required,
325
+ byRule,
326
+ ...unavoidableFaces(features, hitsByTag, sources.regionAreas)
327
+ };
328
+ };
329
+
330
+ // src/model/feature-details.ts
331
+ import { MM_PER_INCH } from "@toolpath/tool-support";
332
+ var mm = (value) => `${trim(value, 4)} mm`;
333
+ var tol = (value) => `${trim(value, 6)} mm`;
334
+ var clearanceDerivation = (fit, clearance) => {
335
+ const { bandPath, strict, loose, atStrict, atLoose } = fit;
336
+ const lines = [`\u2300\u2081 = ${bandPath}.ignore.min = ${mm(strict)}`];
337
+ if (loose === void 0 || atStrict === void 0 || atLoose === void 0 || atLoose <= atStrict) {
338
+ lines.push(
339
+ `${bandPath}.deviate.min or a tolerance is missing, so the tolerance cannot be taken out:`,
340
+ `clearance \u2264 \u2300\u2081 = ${mm(clearance)}`
341
+ );
342
+ return lines;
343
+ }
344
+ const growth = (loose - strict) / (atLoose - atStrict);
345
+ lines.push(
346
+ ` at t\u2081 = toleranceBand.atolIgnore = ${tol(atStrict)}`,
347
+ `\u2300\u2082 = ${bandPath}.deviate.min = ${mm(loose)}`,
348
+ ` at t\u2082 = toleranceBand.atolDeviate = ${tol(atLoose)}`
349
+ );
350
+ if (growth <= 0) {
351
+ lines.push("The tool does not grow with tolerance (a gap, not a corner): clearance = \u2300\u2081");
352
+ } else {
353
+ lines.push(
354
+ `k = (\u2300\u2082 \u2212 \u2300\u2081) / (t\u2082 \u2212 t\u2081) = ${trim(growth, 3)}`,
355
+ `slack = k \xD7 t\u2081 = ${mm(growth * atStrict)}, what the tolerance adds to every tool`,
356
+ `clearance = \u2300\u2081 \u2212 slack`
357
+ );
358
+ }
359
+ lines.push(`clearance = ${mm(clearance)}`);
360
+ return lines;
361
+ };
362
+ var trim = (value, places) => String(Number(value.toFixed(places)));
363
+ var formatLength = (mm2, units, inchMark = false) => units === "inch" ? `${trim(mm2 / MM_PER_INCH, LENGTH_PLACES.inch)}${inchMark ? '"' : " in"}` : `${trim(mm2, LENGTH_PLACES.mm)} mm`;
364
+ var SURFACE_TYPES = /* @__PURE__ */ new Set([
365
+ "contour_surface",
366
+ "inner_fillet",
367
+ "outer_fillet",
368
+ "fillet"
369
+ ]);
370
+ var isSurfaceType = (featureType) => SURFACE_TYPES.has(featureType);
371
+ var maxBallDiameter = (sheet) => {
372
+ const { fitToolDiameter: diameter, fitCornerRadius: corner } = sheet;
373
+ if (corner === void 0 || corner <= 0) return void 0;
374
+ return diameter !== void 0 && diameter > 0 ? Math.min(diameter, 2 * corner) : 2 * corner;
375
+ };
376
+ var ROW_ORDER = [
377
+ "featureDepth",
378
+ "diameter",
379
+ "cornerRadius",
380
+ "filletRadius",
381
+ "floorFillet",
382
+ "tipAngle",
383
+ "thread",
384
+ "bevelAngle",
385
+ "finishTool",
386
+ "pinch",
387
+ "fitCornerRadius",
388
+ "maxBull",
389
+ "maxBall",
390
+ "depthBelowTop",
391
+ "ld",
392
+ "featureLd",
393
+ "topLd"
394
+ ];
395
+ var featureMeasurements = ({
396
+ features,
397
+ feature,
398
+ sheets,
399
+ units,
400
+ inchMark = false
401
+ }) => {
402
+ const other = units === "inch" ? "mm" : "inch";
403
+ const length = (mm2) => ({
404
+ value: formatLength(mm2, units, inchMark),
405
+ alt: formatLength(mm2, other, inchMark)
406
+ });
407
+ const sheet = sheets[feature.tag.toLowerCase()];
408
+ const rows = [];
409
+ const top = sheet ? partTop(features, sheets, feature.machiningDirection) : null;
410
+ const bottom = sheet?.zMin;
411
+ const topFrom = top === null ? void 0 : features.find((each) => sheets[each.tag.toLowerCase()]?.extendedZMax === top);
412
+ 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})` : ""}`;
413
+ if (top !== null && bottom !== void 0) {
414
+ rows.push({
415
+ key: "depthBelowTop",
416
+ label: "Depth below top of part",
417
+ milling: true,
418
+ ...length(top - bottom),
419
+ derivation: [topLine, `Top \u2212 zMin = ${mm(top)} \u2212 ${mm(bottom)} = ${mm(top - bottom)}`]
420
+ });
421
+ }
422
+ if (sheet?.zMax !== void 0 && bottom !== void 0) {
423
+ rows.push({
424
+ key: "featureDepth",
425
+ label: "Feature depth",
426
+ ...length(sheet.zMax - bottom),
427
+ derivation: [`zMax \u2212 zMin = ${mm(sheet.zMax)} \u2212 ${mm(bottom)} = ${mm(sheet.zMax - bottom)}`]
428
+ });
429
+ }
430
+ if (sheet?.diameter !== void 0) {
431
+ rows.push({
432
+ key: "diameter",
433
+ label: "Diameter",
434
+ ...length(sheet.diameter),
435
+ derivation: [`facts.diameter = ${mm(sheet.diameter)}`]
436
+ });
437
+ }
438
+ if (sheet?.cornerRadius !== void 0) {
439
+ const radius = length(sheet.cornerRadius);
440
+ rows.push({
441
+ key: "cornerRadius",
442
+ label: sheet.sharpCorners ? "Minimum radius (sharp)" : "Minimum radius",
443
+ // Measured at one tolerance only, it is the most the modelled radius can be, not the radius itself.
444
+ ...sheet.cornerRadiusUnresolved ? { value: `\u2264 ${radius.value}`, alt: `\u2264 ${radius.alt}` } : radius,
445
+ derivation: [
446
+ "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.",
447
+ ...sheet.clearance ? clearanceDerivation(sheet.clearance, 2 * sheet.cornerRadius) : [],
448
+ `R = clearance / 2 = ${mm(sheet.cornerRadius)}${sheet.sharpCorners ? " (under 0.01 mm: sharp)" : ""}`
449
+ ]
450
+ });
451
+ }
452
+ if (!sheet?.sharpCorners) {
453
+ const clearance = sheet?.pinchDiameter ?? (sheet?.cornerRadius !== void 0 ? 2 * sheet.cornerRadius : void 0);
454
+ if (clearance !== void 0) {
455
+ const width = length(clearance);
456
+ const places = sheet?.pinchPlaces;
457
+ const floor = !SURFACE_TYPES.has(feature.featureType) && sheet?.filletRadius !== void 0 && sheet.filletRadius > 0 ? length(sheet.filletRadius) : void 0;
458
+ const atMost = sheet?.cornerRadiusUnresolved ? "\u2264 " : "";
459
+ rows.push({
460
+ key: "pinch",
461
+ label: "Max tool diameter",
462
+ milling: true,
463
+ // Measured at one tolerance only, it is the most the clearance can be, not the clearance itself.
464
+ value: `${atMost}\u2300 ${width.value}${floor ? ` \xB7 R ${floor.value}` : ""}`,
465
+ alt: `${atMost}\u2300 ${width.alt}${floor ? ` \xB7 R ${floor.alt}` : ""}`,
466
+ derivation: [
467
+ "The widest circle that fits where the feature is tightest: twice an inside corner\u2019s radius, or the width of a gap between walls.",
468
+ ...places !== void 0 ? [
469
+ `pinchPoints: where the feature narrows to its tightest clearance, a disc each; ${places} ${places === 1 ? "place" : "places"} that tight, the tightest drawn.`,
470
+ `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.`
471
+ ] : [
472
+ "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."
473
+ ],
474
+ ...sheet?.clearance ? clearanceDerivation(sheet.clearance, clearance) : [],
475
+ ...floor && sheet?.filletRadius !== void 0 ? [
476
+ `A bull nose, its corner radius the floor fillet\u2019s: facts.filletRadius = ${mm(sheet.filletRadius)}`
477
+ ] : []
478
+ ]
479
+ });
480
+ }
481
+ }
482
+ const surface = SURFACE_TYPES.has(feature.featureType);
483
+ if (surface && sheet) {
484
+ const diameter = sheet.fitToolDiameter;
485
+ const corner = sheet.fitCornerRadius;
486
+ const fit = sheet.toolFitPath ?? "facts.toolFit";
487
+ const ball = maxBallDiameter(sheet);
488
+ rows.push({
489
+ key: "finishTool",
490
+ label: "Finishing tool",
491
+ milling: true,
492
+ value: sheet.ballOnly ? "Ball end mill" : "Ball or bull nose",
493
+ derivation: [
494
+ `facts.useOnlyBallToolsForFinish (or facts.three.\u2026) is ${sheet.ballOnly ? "true" : "not true"}`
495
+ ]
496
+ });
497
+ if (corner !== void 0 && corner > 0) {
498
+ rows.push({
499
+ key: "fitCornerRadius",
500
+ label: "Max corner radius",
501
+ milling: true,
502
+ ...length(corner),
503
+ derivation: [
504
+ "The tightest the surface turns inward: a tool with a larger corner radius cannot follow it.",
505
+ `${fit}.cornerRadius = ${mm(corner)}`
506
+ ]
507
+ });
508
+ }
509
+ const sized = diameter !== void 0 && diameter > 0;
510
+ if (!sheet.ballOnly && corner !== void 0 && corner > 0 && (!sized || ball === void 0 || ball < diameter)) {
511
+ const size = sized ? length(diameter) : void 0;
512
+ const radius = length(corner);
513
+ rows.push({
514
+ key: "maxBull",
515
+ label: "Max bull nose",
516
+ milling: true,
517
+ // Drawable only at a diameter the fit gives: "any" is no size to draw.
518
+ ...sized ? { tool: "bull" } : {},
519
+ value: `${size ? `\u2300 ${size.value}` : "any \u2300"} \xB7 R ${radius.value}`,
520
+ alt: `${size ? `\u2300 ${size.alt}` : "any \u2300"} \xB7 R ${radius.alt}`,
521
+ derivation: [
522
+ 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.",
523
+ ...sized ? [`\u2300 = ${fit}.toolDiameter = ${mm(diameter)}`] : [`${fit}.toolDiameter is not reported`],
524
+ `R = ${fit}.cornerRadius = ${mm(corner)}`
525
+ ]
526
+ });
527
+ }
528
+ if (ball !== void 0 && corner !== void 0) {
529
+ const size = length(ball);
530
+ rows.push({
531
+ key: "maxBall",
532
+ label: "Max ball nose",
533
+ milling: true,
534
+ tool: "ball",
535
+ value: `\u2300 ${size.value}`,
536
+ alt: `\u2300 ${size.alt}`,
537
+ derivation: [
538
+ "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:",
539
+ ...diameter !== void 0 && diameter > 0 ? [
540
+ `min(${fit}.toolDiameter, 2 \xD7 ${fit}.cornerRadius)`,
541
+ `= min(${mm(diameter)}, ${mm(2 * corner)}) = ${mm(ball)}`
542
+ ] : [`2 \xD7 ${fit}.cornerRadius = ${mm(ball)} (${fit}.toolDiameter is not reported)`]
543
+ ]
544
+ });
545
+ }
546
+ }
547
+ const ld = featureLd(features, feature, sheets);
548
+ if (ld && top !== null && bottom !== void 0) {
549
+ 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)`;
550
+ const ratioOf = (depth) => {
551
+ const ratio = (depth / ld.across).toFixed(3);
552
+ return ld.atLeast ? `\u2265 ${ratio}` : ratio;
553
+ };
554
+ if (ld.drilling) {
555
+ rows.push({
556
+ key: "ld",
557
+ label: "Drilling L/D",
558
+ milling: true,
559
+ value: ratioOf(top - bottom),
560
+ derivation: [
561
+ `L = depth below top of part = ${mm(top - bottom)}`,
562
+ across,
563
+ `L / D = ${mm(top - bottom)} / ${mm(ld.across)} = ${ld.ratio.toFixed(3)}`
564
+ ]
565
+ });
566
+ } else {
567
+ if (sheet?.zMax !== void 0) {
568
+ rows.push({
569
+ key: "featureLd",
570
+ label: "Feature L/D",
571
+ milling: true,
572
+ value: ratioOf(sheet.zMax - bottom),
573
+ derivation: [
574
+ `L = feature depth = zMax \u2212 zMin = ${mm(sheet.zMax - bottom)}`,
575
+ across,
576
+ `L / D = ${mm(sheet.zMax - bottom)} / ${mm(ld.across)} = ${((sheet.zMax - bottom) / ld.across).toFixed(3)}`
577
+ ]
578
+ });
579
+ }
580
+ rows.push({
581
+ key: "topLd",
582
+ label: "L/D to top of part",
583
+ milling: true,
584
+ value: ratioOf(top - bottom),
585
+ derivation: [
586
+ `L = depth below top of part = ${mm(top - bottom)}`,
587
+ across,
588
+ `L / D = ${mm(top - bottom)} / ${mm(ld.across)} = ${ld.ratio.toFixed(3)}`
589
+ ]
590
+ });
591
+ }
592
+ }
593
+ if (sheet?.tipAngle !== void 0) {
594
+ const flat = Math.abs(sheet.tipAngle - 180) < 0.05;
595
+ rows.push({
596
+ key: "tipAngle",
597
+ label: "Tip angle",
598
+ value: `${trim(sheet.tipAngle, 3)}\xB0${flat ? " (flat)" : ""}`,
599
+ derivation: [
600
+ `facts.fullConeDeg = ${trim(sheet.tipAngle, 3)}\xB0${flat ? " (180\xB0: flat bottom)" : ""}`
601
+ ]
602
+ });
603
+ }
604
+ if (sheet?.threading) {
605
+ rows.push({
606
+ key: "thread",
607
+ label: "Thread",
608
+ value: `${formatLength(sheet.threading.basicDiameter, units, inchMark)} \xD7 ${formatLength(sheet.threading.threadPitch, units, inchMark)} pitch`,
609
+ derivation: [
610
+ `facts.threading.spec.basicDiameter = ${mm(sheet.threading.basicDiameter)}`,
611
+ `facts.threading.spec.threadPitch = ${mm(sheet.threading.threadPitch)}`
612
+ ]
613
+ });
614
+ }
615
+ if (surface) {
616
+ if (sheet?.filletRadius !== void 0 && sheet.filletRadius !== 0) {
617
+ rows.push({
618
+ key: "filletRadius",
619
+ label: "Fillet radius",
620
+ ...length(Math.abs(sheet.filletRadius)),
621
+ derivation: [
622
+ `|facts.filletRadius| = |${mm(sheet.filletRadius)}| (signed: + over an edge, \u2212 into a corner)`
623
+ ]
624
+ });
625
+ }
626
+ } else if (sheet?.filletRadius !== void 0 && sheet.filletRadius > 0) {
627
+ rows.push({
628
+ key: "floorFillet",
629
+ label: "Floor fillet radius",
630
+ ...length(sheet.filletRadius),
631
+ derivation: [`facts.filletRadius = ${mm(sheet.filletRadius)}`]
632
+ });
633
+ }
634
+ if (sheet?.chamferAngle !== void 0) {
635
+ rows.push({
636
+ key: "bevelAngle",
637
+ label: "Chamfer angle",
638
+ value: `${sheet.chamferAngle.toFixed(3)}\xB0`,
639
+ derivation: [`facts.bevel.angleDeg = ${trim(sheet.chamferAngle, 3)}\xB0`]
640
+ });
641
+ }
642
+ return rows.sort((a, b) => ROW_ORDER.indexOf(a.key) - ROW_ORDER.indexOf(b.key));
643
+ };
644
+
645
+ // src/model/pinch.ts
646
+ var asNumber = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
647
+ var recordOf = (value) => typeof value === "object" && value !== null ? value : {};
648
+ var clearanceFit = (datasheet) => {
649
+ const sheet = recordOf(datasheet);
650
+ const facts = recordOf(sheet.facts);
651
+ const chamfer = facts.kind === "Chamfer";
652
+ const band = recordOf(chamfer ? recordOf(facts.three).cd : facts.cd);
653
+ const tolerance = recordOf(sheet.toleranceBand);
654
+ const strict = asNumber(recordOf(band.ignore).min);
655
+ if (strict === void 0) return void 0;
656
+ const bandPath = chamfer ? "facts.three.cd" : "facts.cd";
657
+ const loose = asNumber(recordOf(band.deviate).min);
658
+ const atStrict = asNumber(tolerance.atolIgnore);
659
+ const atLoose = asNumber(tolerance.atolDeviate);
660
+ const source = { bandPath, strict, loose, atStrict, atLoose };
661
+ if (loose === void 0 || atStrict === void 0 || atLoose === void 0 || atLoose <= atStrict)
662
+ return { ...source, slack: 0, resolved: false };
663
+ const growth = (loose - strict) / (atLoose - atStrict);
664
+ const slack = growth > 0 ? Math.min(growth * atStrict, strict) : 0;
665
+ return { ...source, slack, resolved: true };
666
+ };
667
+ var readPinch = (datasheet) => {
668
+ const sheet = recordOf(datasheet);
669
+ const zMin = asNumber(sheet.zMin);
670
+ const zMax = asNumber(sheet.zMax);
671
+ if (zMin === void 0 || zMax === void 0 || !Array.isArray(sheet.pinchPoints)) return null;
672
+ const fit = clearanceFit(datasheet);
673
+ const slack = fit?.slack ?? 0;
674
+ const discs = sheet.pinchPoints.flatMap((point) => {
675
+ const centre = recordOf(recordOf(point).center);
676
+ const x = asNumber(centre.x);
677
+ const y = asNumber(centre.y);
678
+ const diameter = asNumber(recordOf(point).diameter);
679
+ return x === void 0 || y === void 0 || diameter === void 0 || diameter < 0 ? [] : [{ x, y, diameter: Math.max(diameter - slack, 0) }];
680
+ });
681
+ if (discs.length === 0) return null;
682
+ return { discs, zMin, zMax, ...fit && !fit.resolved ? { unresolved: true } : {} };
683
+ };
684
+
685
+ // src/model/feature-sheet.ts
686
+ var SHARP_MM = 0.1;
687
+ var SHARP_RADIUS_MM = 0.01;
688
+ var PINCH_TOOL_MM = 0.01;
689
+ var asNumber2 = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
690
+ var recordOf2 = (value) => typeof value === "object" && value !== null ? value : {};
691
+ var threadingOf = (facts) => {
692
+ const spec = recordOf2(recordOf2(facts.threading).spec);
693
+ const basicDiameter = asNumber2(spec.basicDiameter);
694
+ const threadPitch = asNumber2(spec.threadPitch);
695
+ if (basicDiameter === void 0 || threadPitch === void 0 || threadPitch <= 0) return void 0;
696
+ return { basicDiameter, threadPitch };
697
+ };
698
+ var noToolFits = (band) => {
699
+ const { max } = band;
700
+ if (typeof max === "string") return /^-inf/i.test(max.trim());
701
+ return typeof max === "number" && (max === Number.NEGATIVE_INFINITY || Number.isFinite(max) && max < SHARP_MM);
702
+ };
703
+ var insideCornerRadius = (fit) => Math.max((fit.strict - fit.slack) / 2, 0);
704
+ var pinchCentres = (points) => Array.isArray(points) ? points.flatMap((point) => {
705
+ const centre = recordOf2(recordOf2(point).center);
706
+ const x = asNumber2(centre.x);
707
+ const y = asNumber2(centre.y);
708
+ return x === void 0 || y === void 0 ? [] : [{ x, y }];
709
+ }) : [];
710
+ var ZERO_MM = 5e-5;
711
+ var isCutterlessTslot = (datasheet) => {
712
+ const facts = recordOf2(recordOf2(datasheet).facts);
713
+ if (facts.kind !== "Tslot") return false;
714
+ const leaves = (value) => typeof value === "object" && value !== null ? Object.values(value).flatMap(leaves) : [value];
715
+ const band = leaves(facts.cd);
716
+ return band.length > 0 && band.every((each) => {
717
+ const value = typeof each === "string" && each.trim() !== "" ? Number(each) : each;
718
+ return typeof value === "number" && Math.abs(value) < ZERO_MM;
719
+ });
720
+ };
721
+ var isSharpCorneredFillet = (featureType, datasheet) => {
722
+ if (typeof featureType !== "string" || !featureType.toLowerCase().split("_").includes("fillet"))
723
+ return false;
724
+ const facts = recordOf2(recordOf2(datasheet).facts);
725
+ return facts.hasSharpCorner === true || recordOf2(facts.three).hasSharpCorner === true;
726
+ };
727
+ var isNoReading = (featureType, datasheet) => isCutterlessTslot(datasheet) || isSharpCorneredFillet(featureType, datasheet);
728
+ var featureSheet = (datasheet) => {
729
+ const sheet = recordOf2(datasheet);
730
+ const facts = recordOf2(sheet.facts);
731
+ const kind = typeof facts.kind === "string" ? facts.kind : void 0;
732
+ const band = recordOf2(kind === "Chamfer" ? recordOf2(facts.three).cd : facts.cd);
733
+ const ignoreBand = recordOf2(band.ignore);
734
+ const fit = clearanceFit(datasheet);
735
+ const fields = {
736
+ kind,
737
+ zMin: asNumber2(sheet.zMin),
738
+ zMax: asNumber2(sheet.zMax),
739
+ extendedZMax: asNumber2(sheet.extendedZMax),
740
+ maxTool: asNumber2(ignoreBand.min),
741
+ diameter: kind === "Hole" ? asNumber2(facts.diameter) : void 0,
742
+ tipAngle: kind === "Hole" ? asNumber2(facts.fullConeDeg) : void 0,
743
+ filletRadius: asNumber2(facts.filletRadius),
744
+ // A bevel's angle wherever the facts carry one: a chamfer's, and any other kind that bevels.
745
+ chamferAngle: asNumber2(recordOf2(facts.bevel).angleDeg)
746
+ };
747
+ const toolFitPath = facts.toolFit !== void 0 ? "facts.toolFit" : "facts.three.toolFit";
748
+ const toolFit = recordOf2(facts.toolFit ?? recordOf2(facts.three).toolFit);
749
+ fields.fitToolDiameter = asNumber2(toolFit.toolDiameter);
750
+ fields.fitCornerRadius = asNumber2(toolFit.cornerRadius);
751
+ const ballOnly = (facts.useOnlyBallToolsForFinish ?? recordOf2(facts.three).useOnlyBallToolsForFinish) === true;
752
+ const measured = Object.fromEntries(
753
+ Object.entries(fields).filter(([, value]) => value !== void 0)
754
+ );
755
+ const cramped = Object.keys(ignoreBand).length > 0 && noToolFits(ignoreBand);
756
+ const walled = kind !== "Hole" && sheet.hasWall === true;
757
+ const clearance = walled ? fit : void 0;
758
+ const cornerRadius = clearance ? insideCornerRadius(clearance) : void 0;
759
+ const sharp = cornerRadius !== void 0 && cornerRadius < SHARP_RADIUS_MM && !cramped;
760
+ const threading = kind === "Hole" ? threadingOf(facts) : void 0;
761
+ const pinched = (readPinch(datasheet)?.discs ?? []).filter(
762
+ (disc) => disc.diameter >= PINCH_TOOL_MM
763
+ );
764
+ return {
765
+ ...measured,
766
+ ...pinched.length > 0 ? {
767
+ pinchDiameter: Math.min(...pinched.map((disc) => disc.diameter)),
768
+ pinchPlaces: pinched.length
769
+ } : {},
770
+ ...cornerRadius !== void 0 ? { cornerRadius } : {},
771
+ ...clearance && !clearance.resolved ? { cornerRadiusUnresolved: true } : {},
772
+ ...clearance ? { clearance } : {},
773
+ ...Object.keys(toolFit).length > 0 ? { toolFitPath } : {},
774
+ ...sharp ? { sharpCorners: pinchCentres(sheet.pinchPoints) } : {},
775
+ ...cramped ? { noToolFits: true } : {},
776
+ ...ballOnly ? { ballOnly: true } : {},
777
+ ...threading ? { threading } : {}
778
+ };
779
+ };
780
+
781
+ // src/model/pinch-mark.ts
782
+ import { MM_PER_INCH as MM_PER_INCH2 } from "@toolpath/tool-support";
783
+ var MAX_DRAWN_TOOL_MM = 3 * MM_PER_INCH2;
784
+ var pinchMark = (datasheet, sheet, featureType) => {
785
+ const pinch = readPinch(datasheet);
786
+ const discs = pinch?.discs.filter(
787
+ (disc) => disc.diameter >= PINCH_TOOL_MM && disc.diameter <= MAX_DRAWN_TOOL_MM
788
+ ) ?? [];
789
+ if (!pinch || discs.length === 0) return null;
790
+ const fillet = sheet?.filletRadius;
791
+ const corner = !isSurfaceType(featureType) && fillet !== void 0 && fillet > 0 ? fillet : void 0;
792
+ return { ...pinch, discs, ...corner !== void 0 ? { corner } : {} };
793
+ };
794
+ var pinchLabel = (mark, units) => {
795
+ const length = (mm2) => `${lengthValue(mm2, units)} ${unitLabel(units)}`;
796
+ const tightest = Math.min(...mark.discs.map((disc) => disc.diameter));
797
+ const tool = mark.corner !== void 0 ? `bull nose R ${length(mark.corner)}` : "widest tool";
798
+ const places = mark.discs.length;
799
+ return {
800
+ label: `${mark.unresolved ? "\u2264 " : ""}\u2300 ${length(tightest)}`,
801
+ note: places > 1 ? `${tool} \xB7 ${places} places` : tool
802
+ };
803
+ };
804
+
805
+ // src/model/tool-frame.ts
806
+ var extent = (values) => {
807
+ let low = Infinity;
808
+ let high = -Infinity;
809
+ for (const value of values) {
810
+ if (value < low) low = value;
811
+ if (value > high) high = value;
812
+ }
813
+ return { low, high };
814
+ };
815
+ var dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
816
+ var cross = (a, b) => [
817
+ a[1] * b[2] - a[2] * b[1],
818
+ a[2] * b[0] - a[0] * b[2],
819
+ a[0] * b[1] - a[1] * b[0]
820
+ ];
821
+ var scale = (a, by) => [a[0] * by, a[1] * by, a[2] * by];
822
+ var add = (a, b) => [a[0] + b[0], a[1] + b[1], a[2] + b[2]];
823
+ var unit = (a) => scale(a, 1 / Math.hypot(a[0], a[1], a[2]));
824
+ var ON_DEPTH_MM = 0.05;
825
+ var ON_CORNER_MM = 0.02;
826
+ var POINT_DISC_MM = 0.01;
827
+ var ON_WALL_MM = 0.1;
828
+ var ON_WALL_SHARE = 0.02;
829
+ var WALL_NORMAL_ALONG = 0.7;
830
+ var SAME_PLACE_MM = 0.05;
831
+ var MIN_HEIGHT_MM = 0.05;
832
+ var readTriangles = ({ positions, normals }, origin) => {
833
+ const triangles = [];
834
+ for (let at2 = 0; at2 + 8 < positions.length; at2 += 9) {
835
+ const corner = (k) => [
836
+ (positions[at2 + k] ?? 0) - origin[0],
837
+ (positions[at2 + k + 1] ?? 0) - origin[1],
838
+ (positions[at2 + k + 2] ?? 0) - origin[2]
839
+ ];
840
+ const n = at2 / 9 * 3;
841
+ triangles.push({
842
+ a: corner(0),
843
+ b: corner(3),
844
+ c: corner(6),
845
+ normal: [normals[n] ?? 0, normals[n + 1] ?? 0, normals[n + 2] ?? 0]
846
+ });
847
+ }
848
+ return triangles;
849
+ };
850
+ var pointsOf = (triangles) => triangles.flatMap(({ a, b, c }) => [a, b, c]);
851
+ var flatten = (point, { u, v }) => ({ x: dot(point, u), y: dot(point, v) });
852
+ var wallSegments = (triangles, frame) => triangles.filter(({ normal }) => Math.abs(dot(normal, frame.w)) < WALL_NORMAL_ALONG).flatMap(({ a, b, c, normal }) => {
853
+ const [fa, fb, fc] = [flatten(a, frame), flatten(b, frame), flatten(c, frame)];
854
+ const air = flatten(normal, frame);
855
+ return [
856
+ { p: fa, q: fb, air },
857
+ { p: fb, q: fc, air },
858
+ { p: fc, q: fa, air }
859
+ ];
860
+ });
861
+ var nearestOn = ({ p, q }, at2) => {
862
+ const dx = q.x - p.x;
863
+ const dy = q.y - p.y;
864
+ const length = dx * dx + dy * dy;
865
+ const t = length === 0 ? 0 : Math.min(1, Math.max(0, ((at2.x - p.x) * dx + (at2.y - p.y) * dy) / length));
866
+ return { x: p.x + t * dx, y: p.y + t * dy };
867
+ };
868
+ var nearestWall = (segments, at2) => segments.reduce((best, segment) => {
869
+ const point = nearestOn(segment, at2);
870
+ const distance2 = Math.hypot(point.x - at2.x, point.y - at2.y);
871
+ if (best && distance2 >= best.distance) return best;
872
+ const open = (at2.x - point.x) * segment.air.x + (at2.y - point.y) * segment.air.y >= 0;
873
+ return { point, distance: distance2, open };
874
+ }, null);
875
+ var fitsDiscs = (triangles, frame, discs) => {
876
+ const points = discs.filter((disc) => disc.diameter < POINT_DISC_MM);
877
+ const wide = discs.filter((disc) => disc.diameter >= POINT_DISC_MM);
878
+ if (points.length > 0) {
879
+ const flat = pointsOf(triangles).map((point) => flatten(point, frame));
880
+ const onCorners = points.every(
881
+ (disc) => flat.some((point) => Math.hypot(point.x - disc.x, point.y - disc.y) <= ON_CORNER_MM)
882
+ );
883
+ if (!onCorners) return false;
884
+ }
885
+ if (wide.length === 0) return points.length > 0;
886
+ const segments = wallSegments(triangles, frame);
887
+ if (segments.length === 0) return false;
888
+ let touches = false;
889
+ for (const disc of wide) {
890
+ const nearest = nearestWall(segments, disc);
891
+ if (!nearest || !nearest.open) return false;
892
+ const slack = ON_WALL_MM + ON_WALL_SHARE * disc.diameter;
893
+ const radius = disc.diameter / 2;
894
+ if (nearest.distance < radius - slack) return false;
895
+ if (nearest.distance <= radius + slack) touches = true;
896
+ }
897
+ return touches;
898
+ };
899
+ var placeInFrame = ({ u, v, w }, x, y, z) => add(add(scale(u, x), scale(v, y)), scale(w, z));
900
+ var AXES = [
901
+ [1, 0, 0],
902
+ [0, 1, 0],
903
+ [0, 0, 1]
904
+ ];
905
+ var candidateFrames = (points, zMin, zMax, direction, strict = true) => {
906
+ const along = unit(direction);
907
+ const frames = [];
908
+ for (const sign of [1, -1]) {
909
+ const w = scale(along, sign);
910
+ const { low, high } = extent(points.map((point) => dot(point, w)));
911
+ if (strict && (Math.abs(low - zMin) > ON_DEPTH_MM || Math.abs(high - zMax) > ON_DEPTH_MM)) {
912
+ continue;
913
+ }
914
+ const across = AXES.reduce(
915
+ (best, axis) => Math.abs(dot(axis, w)) < Math.abs(dot(best, w)) ? axis : best
916
+ );
917
+ const u0 = unit(add(across, scale(w, -dot(across, w))));
918
+ const v0 = cross(w, u0);
919
+ for (let quarter = 0; quarter < 4; quarter++) {
920
+ const angle = quarter * Math.PI / 2;
921
+ const u = add(scale(u0, Math.cos(angle)), scale(v0, Math.sin(angle)));
922
+ for (const hand of [1, -1]) frames.push({ u, v: scale(cross(w, u), hand), w });
923
+ }
924
+ }
925
+ return frames;
926
+ };
927
+ var distance = (a, b) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b[2]);
928
+ var exactFrame = (triangles, discs, zMin, zMax, direction) => {
929
+ const fits = candidateFrames(pointsOf(triangles), zMin, zMax, direction).filter(
930
+ (frame) => fitsDiscs(triangles, frame, discs)
931
+ );
932
+ const [first] = fits;
933
+ if (!first) return null;
934
+ const placed = (frame) => discs.map((disc) => placeInFrame(frame, disc.x, disc.y, zMin));
935
+ const firstPlaces = placed(first);
936
+ const agree = fits.every(
937
+ (frame) => placed(frame).every((at2, index) => distance(at2, firstPlaces[index] ?? at2) <= SAME_PLACE_MM)
938
+ );
939
+ return agree ? first : null;
940
+ };
941
+ var discMiss = (triangles, frame, discs) => {
942
+ let miss = 0;
943
+ const points = discs.filter((disc) => disc.diameter < POINT_DISC_MM);
944
+ if (points.length > 0) {
945
+ const flat = pointsOf(triangles).map((point) => flatten(point, frame));
946
+ for (const disc of points) {
947
+ miss += extent(flat.map((point) => Math.hypot(point.x - disc.x, point.y - disc.y))).low;
948
+ }
949
+ }
950
+ const wide = discs.filter((disc) => disc.diameter >= POINT_DISC_MM);
951
+ if (wide.length === 0) return miss;
952
+ const segments = wallSegments(triangles, frame);
953
+ let touch = Infinity;
954
+ for (const disc of wide) {
955
+ const radius = disc.diameter / 2;
956
+ const nearest = nearestWall(segments, disc);
957
+ if (!nearest) return Infinity;
958
+ if (!nearest.open) miss += disc.diameter * 4;
959
+ miss += Math.max(0, radius - nearest.distance);
960
+ touch = Math.min(touch, Math.abs(nearest.distance - radius));
961
+ }
962
+ return miss + touch;
963
+ };
964
+ var bestFrame = (triangles, discs, zMin, zMax, direction) => {
965
+ if (triangles.length === 0 || discs.length === 0) return null;
966
+ const exact = exactFrame(triangles, discs, zMin, zMax, direction);
967
+ if (exact) return { frame: exact, lift: 0 };
968
+ const points = pointsOf(triangles);
969
+ const fitting = candidateFrames(points, zMin, zMax, direction);
970
+ const frames = fitting.length > 0 ? fitting : candidateFrames(points, zMin, zMax, direction, false);
971
+ const best = frames.reduce((was, frame) => {
972
+ const miss = discMiss(triangles, frame, discs);
973
+ return !was || miss < was.miss ? { frame, miss } : was;
974
+ }, null);
975
+ if (!best) return null;
976
+ const { low } = extent(points.map((point) => dot(point, best.frame.w)));
977
+ return { frame: best.frame, lift: fitting.length > 0 ? 0 : low - zMin };
978
+ };
979
+ var asVec = ([x, y, z]) => ({ x, y, z });
980
+ var placePinchTool = (mark, triangles, direction, origin = { x: 0, y: 0, z: 0 }) => {
981
+ const shift = [origin.x, origin.y, origin.z];
982
+ const faces = readTriangles(triangles, shift);
983
+ const found = bestFrame(faces, mark.discs, mark.zMin, mark.zMax, [
984
+ direction.x,
985
+ direction.y,
986
+ direction.z
987
+ ]);
988
+ const disc = mark.discs.reduce(
989
+ (tightest, each) => !tightest || each.diameter < tightest.diameter ? each : tightest,
990
+ null
991
+ );
992
+ if (!found || !disc) return null;
993
+ const { frame, lift } = found;
994
+ const radius = disc.diameter / 2;
995
+ const base = add(placeInFrame(frame, disc.x, disc.y, mark.zMin + lift), shift);
996
+ const contact = nearestWall(wallSegments(faces, frame), disc)?.point;
997
+ const toward = contact ? { x: contact.x - disc.x, y: contact.y - disc.y } : { x: 1, y: 0 };
998
+ const length = Math.hypot(toward.x, toward.y);
999
+ const across = add(
1000
+ scale(frame.u, length > 1e-9 ? toward.x / length : 1),
1001
+ scale(frame.v, length > 1e-9 ? toward.y / length : 0)
1002
+ );
1003
+ return {
1004
+ base: asVec(base),
1005
+ axis: asVec(frame.w),
1006
+ diameter: disc.diameter,
1007
+ height: Math.max(mark.zMax - mark.zMin, MIN_HEIGHT_MM),
1008
+ cornerRadius: Math.min(Math.max(mark.corner ?? 0, 0), radius),
1009
+ across: asVec(across)
1010
+ };
1011
+ };
1012
+ export {
1013
+ CRITICAL_COLOR,
1014
+ FILE_KIND,
1015
+ PINCH_TOOL_MM,
1016
+ RULE_COLORS,
1017
+ WARNING_COLOR,
1018
+ brokenRules,
1019
+ checkPart,
1020
+ compareColors,
1021
+ describeRule,
1022
+ dfmFeatures,
1023
+ featureColor,
1024
+ featureMeasurements,
1025
+ featureProfile,
1026
+ featureSheet,
1027
+ featureTypeLabel,
1028
+ hitFigure,
1029
+ isNoReading,
1030
+ isSurfaceType,
1031
+ llmRulePrompt,
1032
+ makeRule,
1033
+ maxBallDiameter,
1034
+ parseRuleSetFile,
1035
+ parseRules,
1036
+ peakHeight,
1037
+ pinchLabel,
1038
+ pinchMark,
1039
+ placePinchTool,
1040
+ readPinch,
1041
+ readReachCurve,
1042
+ runStart,
1043
+ sameDepth,
1044
+ serializeRuleSet,
1045
+ trimmedCurve,
1046
+ withSurroundedFaces
1047
+ };