From bdc852238c22ae3fd9f1a93070ca9e1ee8796185 Mon Sep 17 00:00:00 2001 From: takuto-NA <183465875+takuto-NA@users.noreply.github.com> Date: Mon, 9 Nov 2026 19:34:58 +0900 Subject: [PATCH] Fix fillet fitting and tangent continuity --- packages/maker.js/package.json | 1 + packages/maker.js/src/core/fillet.ts | 255 ++++++++++++------ packages/maker.js/test/fillet.js | 390 +++++++++++++++++++++++++++ 3 files changed, 560 insertions(+), 86 deletions(-) create mode 100644 packages/maker.js/test/fillet.js diff --git a/packages/maker.js/package.json b/packages/maker.js/package.json index d7a9ddd54..7dc18339d 100644 --- a/packages/maker.js/package.json +++ b/packages/maker.js/package.json @@ -15,6 +15,7 @@ "prebuild": "npm run gen-cascades", "build": "tsc -p target && node ./target/build.js", "test": "mocha --timeout 15000", + "test-fillet": "mocha --timeout 15000 test/fillet.js", "prepublish": "node ./target/prepublish.js" }, "maintainers": [ diff --git a/packages/maker.js/src/core/fillet.ts b/packages/maker.js/src/core/fillet.ts index 36903134c..3b0f50365 100644 --- a/packages/maker.js/src/core/fillet.ts +++ b/packages/maker.js/src/core/fillet.ts @@ -23,6 +23,7 @@ namespace MakerJs.path { */ interface IFilletResult { filletAngle: number; + tangent?: IPoint; clipPath: () => void; } @@ -43,7 +44,13 @@ namespace MakerJs.path { * @private */ function getPointProperties(pathToInspect: IPath): IPointProperty[] { - var points = point.fromPathEnds(pathToInspect); + var points = pathToInspect.type === pathType.Arc + ? [(pathToInspect).startAngle, (pathToInspect).endAngle].map(a => { + var arc = pathToInspect; + var radians = angle.toRadians(a); + return point.add(arc.origin, [arc.radius * Math.cos(radians), arc.radius * Math.sin(radians)]); + }) + : point.fromPathEnds(pathToInspect); if (points) { function pointProperty(index: number): IPointProperty { @@ -69,7 +76,11 @@ namespace MakerJs.path { var pathAProperties = getPointProperties(pathA); var pathBProperties = getPointProperties(pathB); + if (!pathAProperties || !pathBProperties) return null; + var result: IMatchPointProperty[] = null; + var matchingDistance = options && options.pointMatchingDistance != null ? options.pointMatchingDistance : .0001; + var closestDistance = Infinity; function makeMatch(pathContext: IPath, pointProperties: IPointProperty[], index: number): IMatchPointProperty { return { @@ -82,7 +93,9 @@ namespace MakerJs.path { } function check(iA: number, iB: number) { - if (measure.isPointEqual(pathAProperties[iA].point, pathBProperties[iB].point, .0001)) { + var distance = measure.pointDistance(pathAProperties[iA].point, pathBProperties[iB].point); + if (distance <= matchingDistance && distance < closestDistance) { + closestDistance = distance; result = [ makeMatch(pathA, pathAProperties, iA), makeMatch(pathB, pathBProperties, iB) @@ -92,7 +105,10 @@ namespace MakerJs.path { return false; } - check(0, 0) || check(0, 1) || check(1, 0) || check(1, 1); + check(0, 0); + check(0, 1); + check(1, 0); + check(1, 1); return result; } @@ -127,53 +143,82 @@ namespace MakerJs.path { /** * @private */ - function cloneAndBreakPath(pathToShard: IPath, shardPoint: IPoint): IPath[] { - var shardStart = path.clone(pathToShard); - var shardEnd = breakAtPoint(shardStart, shardPoint); - return [shardStart, shardEnd]; + function getFilletTangent(context: IMatchPointProperty): IPoint { + if (context.path.type === pathType.Line) { + var delta = point.subtract(context.oppositePoint, context.point); + var length = measure.pointDistance(context.point, context.oppositePoint); + return [delta[0] / length, delta[1] / length]; + } + return arcTangent(context.path[context.propertyName], context.isStart); } /** * @private */ - var guidePathMap: { [pathType: string]: (pathContext: IPath, filletRadius: number, nearPoint: IPoint, shardPoint: IPoint, isStart: boolean) => IPath } = {}; - - guidePathMap[pathType.Arc] = function (arc: IPathArc, filletRadius: number, nearPoint: IPoint, shardPoint: IPoint, isStart: boolean) { - var guideRadius = arc.radius; - - //see if the guideline should be external or internal to the context arc. - var guideArcShard = cloneAndBreakPath(arc, shardPoint)[isStart ? 0 : 1]; - if (guideArcShard) { - if (measure.isArcConcaveTowardsPoint(guideArcShard, nearPoint)) { - guideRadius -= filletRadius; - } else { - guideRadius += filletRadius; - } - - if (round(guideRadius) <= 0) return null; + function arcTangent(degrees: number, isStart: boolean): IPoint { + var radians = angle.toRadians(degrees); + var sign = isStart ? 1 : -1; + return [-sign * Math.sin(radians), sign * Math.cos(radians)]; + } - return new paths.Arc(arc.origin, guideRadius, arc.startAngle, arc.endAngle); + /** + * @private + */ + function getGuidePath(context: IMatchPointProperty, filletRadius: number, side: number): IPath { + if (context.path.type === pathType.Arc) { + var arc = context.path; + var guideRadius = arc.radius - side * (context.isStart ? 1 : -1) * filletRadius; + return guideRadius > 0 ? new paths.Circle(arc.origin, guideRadius) : null; } - - return null; - }; - - guidePathMap[pathType.Line] = function (line: IPathLine, filletRadius: number, nearPoint: IPoint, shardPoint: IPoint, isStart: boolean) { - return new paths.Parallel(line, filletRadius, nearPoint); + var tangent = getFilletTangent(context); + var offset: IPoint = [-tangent[1] * side * filletRadius, tangent[0] * side * filletRadius]; + var line = context.path; + return new paths.Line(point.add(line.origin, offset), point.add(line.end, offset)); } /** + * Intersect the supporting guides without rounding coordinates to a fixed drawing unit. + * The resulting tangent points are checked against the original finite paths below. * @private */ - function getGuidePath(context: IMatchPointProperty, filletRadius: number, nearPoint: IPoint): IPath { - var result: IPath = null; - - var fn = guidePathMap[context.path.type]; - if (fn) { - result = fn(context.path, filletRadius, nearPoint, context.shardPoint, context.isStart); + function intersectFilletGuides(a: IPath, b: IPath): IPoint[] { + function cross(u: IPoint, v: IPoint): number { + return u[0] * v[1] - u[1] * v[0]; } - - return result; + function along(origin: IPoint, direction: IPoint, distance: number): IPoint { + return [origin[0] + direction[0] * distance, origin[1] + direction[1] * distance]; + } + function direction(line: IPathLine): IPoint { + var delta = point.subtract(line.end, line.origin); + var length = measure.pointDistance(line.origin, line.end); + return [delta[0] / length, delta[1] / length]; + } + if (a.type === pathType.Line && b.type === pathType.Line) { + var u = direction(a), v = direction(b); + var determinant = cross(u, v); + if (Math.abs(determinant) < 1e-12) return []; + return [along(a.origin, u, cross(point.subtract(b.origin, a.origin), v) / determinant)]; + } + if (a.type === pathType.Line || b.type === pathType.Line) { + var line = (a.type === pathType.Line ? a : b); + var circle = (a.type === pathType.Line ? b : a); + var unit = direction(line); + var delta = point.subtract(circle.origin, line.origin); + var perpendicular = cross(delta, unit); + if (Math.abs(perpendicular) > circle.radius) return []; + var projection = delta[0] * unit[0] + delta[1] * unit[1]; + var halfChord = Math.sqrt(Math.max(0, (circle.radius - Math.abs(perpendicular)) * (circle.radius + Math.abs(perpendicular)))); + return [along(line.origin, unit, projection - halfChord), along(line.origin, unit, projection + halfChord)]; + } + var c1 = a, c2 = b; + var distance = measure.pointDistance(c1.origin, c2.origin); + if (!distance || distance > c1.radius + c2.radius || distance < Math.abs(c1.radius - c2.radius)) return []; + var unit: IPoint = [(c2.origin[0] - c1.origin[0]) / distance, (c2.origin[1] - c1.origin[1]) / distance]; + var chordDistance = ((c1.radius - c2.radius) * (c1.radius + c2.radius) / distance + distance) / 2; + var halfChord = Math.sqrt(Math.max(0, (c1.radius - chordDistance) * (c1.radius + chordDistance))); + var middle = along(c1.origin, unit, chordDistance); + var normal: IPoint = [-unit[1], unit[0]]; + return [along(middle, normal, halfChord), along(middle, normal, -halfChord)]; } /** @@ -185,34 +230,37 @@ namespace MakerJs.path { var guideLine = new paths.Line(arc.origin, filletCenter); var guideLineAngle = angle.ofLineInDegrees(guideLine); var filletAngle = guideLineAngle; + var isStart = propertyName === 'startAngle'; + var travel = angle.noRevolutions(isStart ? guideLineAngle - arc.startAngle : arc.endAngle - guideLineAngle); + if (!(travel > 0 && travel < angle.ofArcSpan(arc))) return null; + var clipAngle = isStart ? arc.startAngle + travel : arc.endAngle - travel; //the context is an arc and the fillet is an arc so they will be tangent. If the fillet is external to the arc then the tangent is opposite. - if (!measure.isArcConcaveTowardsPoint(arc, filletCenter)) { + if (measure.pointDistance(arc.origin, filletCenter) > arc.radius) { filletAngle += 180; } return { filletAngle: angle.noRevolutions(filletAngle), + tangent: arcTangent(clipAngle, isStart), clipPath: function () { - arc[propertyName] = guideLineAngle; + arc[propertyName] = clipAngle; } }; }; filletResultMap[pathType.Line] = function (line: IPathLine, propertyName: string, filletRadius: number, filletCenter: IPoint) { - //make a small vertical line - var guideLine = new paths.Line([0, 0], [0, 1]); - - //rotate this vertical line the same angle as the line context. It will be perpendicular. - var lineAngle = angle.ofLineInDegrees(line); - path.rotate(guideLine, lineAngle, [0, 0]); - path.moveRelative(guideLine, filletCenter); - - //get the intersection point of the slopes of the context line and the perpendicular line. This is where the fillet meets the line. - var intersectionPoint = point.fromSlopeIntersection(line, guideLine); - if (intersectionPoint) { + var delta = point.subtract(line.end, line.origin); + var centerDelta = point.subtract(filletCenter, line.origin); + var lengthSquared = delta[0] * delta[0] + delta[1] * delta[1]; + var ratio = (centerDelta[0] * delta[0] + centerDelta[1] * delta[1]) / lengthSquared; + if (ratio > 0 && ratio < 1) { + var intersectionPoint: IPoint = [line.origin[0] + ratio * delta[0], line.origin[1] + ratio * delta[1]]; + var sign = propertyName === 'origin' ? 1 : -1; + var length = Math.sqrt(lengthSquared); return { filletAngle: angle.ofPointInDegrees(filletCenter, intersectionPoint), + tangent: [sign * delta[0] / length, sign * delta[1] / length], clipPath: function () { line[propertyName] = intersectionPoint; } @@ -233,7 +281,7 @@ namespace MakerJs.path { result = fn(context.path, context.propertyName, filletRadius, filletCenter); } - if (!testFilletResult(context, result)) { + if (!testFilletResult(context, result, filletCenter, filletRadius)) { result = null; } @@ -261,7 +309,7 @@ namespace MakerJs.path { /** * @private */ - function testFilletResult(context: IMatchPointProperty, result: IFilletResult): boolean { + function testFilletResult(context: IMatchPointProperty, result: IFilletResult, filletCenter?: IPoint, filletRadius?: number): boolean { var test = false; if (result) { @@ -275,6 +323,15 @@ namespace MakerJs.path { test = true; } + if (test && filletCenter) { + //Large coordinate / radius ratios can lose the small offset which + //makes the circles tangent. Never return a disconnected fillet. + var endpoint = getPointProperties(context.path)[context.isStart ? 0 : 1].point; + var radians = angle.toRadians(result.filletAngle); + var filletPoint = point.add(filletCenter, [filletRadius * Math.cos(radians), filletRadius * Math.sin(radians)]); + test = measure.pointDistance(endpoint, filletPoint) <= filletRadius * 1e-7; + } + //revert the clipping we just did. context.path[context.propertyName] = originalValue; } @@ -316,7 +373,7 @@ namespace MakerJs.path { extendObject(opts, options); //first find the common point - var commonProperty = getMatchingPointProperties(lineA, lineB, options); + var commonProperty = getMatchingPointProperties(lineA, lineB, opts); if (commonProperty) { //get the ratio comparison of the two lines @@ -364,17 +421,33 @@ namespace MakerJs.path { } /** - * Adds a round corner to the inside angle between 2 paths. The paths must meet at one point. + * Adds a round corner to the inside angle between 2 lines or arcs. The paths must meet at one endpoint. * * @param pathA First path to fillet, which will be modified to fit the fillet. * @param pathB Second path to fillet, which will be modified to fit the fillet. * @param filletRadius Radius of the fillet. - * @param options Optional IPointMatchOptions object to specify pointMatchingDistance. - * @returns Arc path object of the new fillet. + * @param options Optional IPointMatchOptions object to specify pointMatchingDistance (default .005 drawing units). + * @returns Arc path object with a span below 180 degrees, or null if it cannot fit or numerical precision is insufficient. On failure the paths are unchanged. */ export function fillet(pathA: IPath, pathB: IPath, filletRadius: number, options?: IPointMatchOptions): IPathArc { - if (pathA && pathB && filletRadius && filletRadius > 0) { + function validPath(p: IPath): boolean { + function finitePoint(value: IPoint): boolean { + return isPoint(value) && isFinite(value[0]) && isFinite(value[1]); + } + if (!p || !finitePoint(p.origin)) return false; + if (isPathLine(p)) { + return finitePoint((p).end) && measure.pathLength(p) > 0; + } + if (isPathArc(p)) { + var arc = p; + return isFinite(arc.radius) && arc.radius > 0 && isFinite(arc.startAngle) && isFinite(arc.endAngle) + && angle.ofArcSpan(arc) > 0 && angle.ofArcSpan(arc) < 360; + } + return false; + } + + if (pathA !== pathB && validPath(pathA) && validPath(pathB) && isNumber(filletRadius) && isFinite(filletRadius) && filletRadius > 0) { var opts: IPointMatchOptions = { pointMatchingDistance: .005 @@ -382,58 +455,59 @@ namespace MakerJs.path { extendObject(opts, options); //first find the common point - var commonProperty = getMatchingPointProperties(pathA, pathB, options); + if (!(opts.pointMatchingDistance >= 0) || !isFinite(opts.pointMatchingDistance)) return null; + var commonProperty = getMatchingPointProperties(pathA, pathB, opts); if (commonProperty) { - - //since arcs can curl beyond, we need a local reference point. - //An intersection with a circle of the same radius as the desired fillet should suffice. - if (!populateShardPointsFromReferenceCircle(filletRadius, commonProperty[0].point, commonProperty, opts)) { - return null; + var tangentA = getFilletTangent(commonProperty[0]); + var tangentB = getFilletTangent(commonProperty[1]); + var cross = tangentA[0] * tangentB[1] - tangentA[1] * tangentB[0]; + var side: number; + if (Math.abs(cross) < 1e-12) { + //Opposed tangents already form a smooth join. Equal outward + //tangents can form a cusp; curvature determines its inside. + if (tangentA[0] * tangentB[0] + tangentA[1] * tangentB[1] < 0) return null; + var curvatures = commonProperty.map(context => context.path.type === pathType.Arc + ? (context.isStart ? 1 : -1) / (context.path).radius : 0); + var curvatureDifference = curvatures[1] - curvatures[0]; + if (!curvatureDifference) return null; + side = curvatureDifference > 0 ? 1 : -1; + } else { + side = cross > 0 ? 1 : -1; } //get "parallel" guidelines var guidePaths: IPath[] = []; for (var i = 0; i < 2; i++) { - var otherPathShardPoint = commonProperty[1 - i].shardPoint; - if (!otherPathShardPoint) { - return null; - } - var guidePath = getGuidePath(commonProperty[i], filletRadius, otherPathShardPoint); + var guidePath = getGuidePath(commonProperty[i], filletRadius, i === 0 ? side : -side); + if (!guidePath) return null; guidePaths.push(guidePath); } - //the center of the fillet is the point where the guidelines intersect. - var intersectionPoint = intersection(guidePaths[0], guidePaths[1]); - if (intersectionPoint) { - - var center: IPoint; - - //if guidelines intersect in more than one place, choose the closest one. - if (intersectionPoint.intersectionPoints.length == 1) { - center = intersectionPoint.intersectionPoints[0]; - } else { - center = point.closest(commonProperty[0].point, intersectionPoint.intersectionPoints); - } + //Try the nearest center first, but a second intersection may be the one which fits. + var centers = intersectFilletGuides(guidePaths[0], guidePaths[1]); + centers.sort((a, b) => measure.pointDistance(commonProperty[0].point, a) - measure.pointDistance(commonProperty[0].point, b)); + for (var c = 0; c < centers.length; c++) { + var center = centers[c]; + if (!isFinite(center[0]) || !isFinite(center[1])) continue; //get the angles of the fillet and a function which clips the path to the fillet. var results: IFilletResult[] = []; for (var i = 0; i < 2; i++) { var result = getFilletResult(commonProperty[i], filletRadius, center); - if (!result) { - return null; - } + if (!result) break; results.push(result); } + if (results.length !== 2) continue; //the two paths may actually be on the same line - if (round(results[0].filletAngle - results[1].filletAngle) == 0) return null; + if (measure.isAngleEqual(results[0].filletAngle, results[1].filletAngle, .0000001)) continue; var filletArc = new paths.Arc(center, filletRadius, results[0].filletAngle, results[1].filletAngle); var filletSpan = angle.ofArcSpan(filletArc); //the algorithm is only valid for fillet less than 180 degrees - if (filletSpan == 180) { - return null; + if (round(filletSpan) == 180) { + continue; } if (filletSpan > 180) { @@ -442,6 +516,15 @@ namespace MakerJs.path { filletArc.endAngle = results[0].filletAngle; } + //Both paths must lead away from the fillet, rather than folding back into it. + var smooth = true; + for (var i = 0; i < 2; i++) { + var intoFillet = arcTangent(results[i].filletAngle, filletArc.startAngle === results[i].filletAngle); + var tangent = results[i].tangent; + if (intoFillet[0] * tangent[0] + intoFillet[1] * tangent[1] >= 0) smooth = false; + } + if (!smooth) continue; + //clip the paths and return the fillet arc. results[0].clipPath(); results[1].clipPath(); diff --git a/packages/maker.js/test/fillet.js b/packages/maker.js/test/fillet.js new file mode 100644 index 000000000..df3397601 --- /dev/null +++ b/packages/maker.js/test/fillet.js @@ -0,0 +1,390 @@ +var assert = require('assert'); +var makerjs = require('../dist/index.js'); + +// Check geometry with unrounded trigonometry. Use Maker.js's angle normalization +// convention, but bypass the point helpers' rounding to 1e-7 drawing units. +function polar(degrees, radius) { + var a = makerjs.angle.toRadians(degrees); + return [Math.cos(a) * radius, Math.sin(a) * radius]; +} + +function add(a, b) { return [a[0] + b[0], a[1] + b[1]]; } +function subtract(a, b) { return [a[0] - b[0], a[1] - b[1]]; } +function length(v) { return Math.hypot(v[0], v[1]); } +function distance(a, b) { return length(subtract(a, b)); } +function dot(a, b) { return a[0] * b[0] + a[1] * b[1]; } +function clone(value) { return makerjs.cloneObject(value); } +function ends(p) { + return p.type === 'line' ? [p.origin, p.end] : + [p.startAngle, p.endAngle].map(a => add(p.origin, polar(a, p.radius))); +} +function span(arc) { + var result = (arc.endAngle - arc.startAngle) % 360; + return result < 0 ? result + 360 : result; +} +function pathLength(p) { + return p.type === 'line' ? distance(p.origin, p.end) : span(p) * Math.PI / 180 * p.radius; +} +function tangentAway(p, endpoint) { + if (p.type === 'line') return subtract(ends(p)[1 - endpoint], ends(p)[endpoint]); + var radial = polar(endpoint === 0 ? p.startAngle : p.endAngle, 1); + return endpoint === 0 ? [-radial[1], radial[0]] : [radial[1], -radial[0]]; +} + +function assertFillet(before, after, fillet, radius, tolerance) { + assert.ok(fillet, 'expected a fillet'); + assert.strictEqual(fillet.radius, radius); + assert.ok(span(fillet) > 0 && span(fillet) < 180, 'fillet must have a nonzero span below 180 degrees'); + ends(fillet).forEach(p => p.forEach(n => assert.ok(Number.isFinite(n), 'finite endpoint'))); + var used = []; + after.forEach((p, i) => { + var best = { distance: Infinity }; + ends(p).forEach((a, j) => ends(fillet).forEach((b, k) => { + var d = distance(a, b); + if (d < best.distance) best = { distance: d, pathEnd: j, filletEnd: k }; + })); + assert.ok(best.distance <= tolerance, 'disconnected fillet: gap=' + best.distance); + used.push(best.filletEnd); + assert.deepStrictEqual(ends(p)[1 - best.pathEnd], ends(before[i])[1 - best.pathEnd], 'opposite endpoint changed'); + assert.ok(pathLength(p) > 0 && pathLength(p) < pathLength(before[i]), 'path must be shortened'); + if (p.type === 'line') { + var original = subtract(before[i].end, before[i].origin); + var t = dot(subtract(ends(p)[best.pathEnd], before[i].origin), original) / dot(original, original); + assert.ok(t > 0 && t < 1, 'tangent point must stay inside the line segment'); + } else { + assert.strictEqual(p.radius, before[i].radius); + assert.deepStrictEqual(p.origin, before[i].origin); + // Preserve the original angular interval, including its revolution count. + var removed = best.pathEnd === 0 ? p.startAngle - before[i].startAngle : before[i].endAngle - p.endAngle; + assert.ok(removed > 0 && removed < span(before[i]), 'arc trimmed past its opposite endpoint'); + } + var away = tangentAway(p, best.pathEnd); + var into = tangentAway(fillet, best.filletEnd); + var alignment = dot(away, into) / length(away) / length(into); + assert.ok(alignment < -1 + 1e-8, 'tangent discontinuity or cusp: dot=' + alignment); + }); + assert.notStrictEqual(used[0], used[1], 'both paths connected to the same fillet endpoint'); +} + +function assertRejected(a, b, radius, options) { + var before = clone([a, b]); + assert.strictEqual(makerjs.path.fillet(a, b, radius, options), null); + assert.deepStrictEqual([a, b], before, 'failed fillet modified its inputs'); +} + +function randomSource(seed) { + return function () { + seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0; + return seed / 4294967296; + }; +} + +// The join is an exact endpoint, with a specified tangent pointing away from it. +function makePath(kind, join, degrees, atStart, size, arcSpan, revolutions) { + if (kind === 'line') { + var far = add(join, polar(degrees, size)); + return new makerjs.paths.Line(atStart ? join.slice() : far, atStart ? far : join.slice()); + } + var center = add(join, polar(degrees + (atStart ? 90 : -90), size)); + var a = degrees + (atStart ? -90 : 90) + revolutions * 360; + return new makerjs.paths.Arc(center, size, atStart ? a : a - arcSpan, atStart ? a + arcSpan : a); +} + +describe('Fillets', function () { + it('trims all four line endpoint combinations to an analytic right-angle fillet', function () { + [false, true].forEach(aStart => [false, true].forEach(bStart => { + var a = makePath('line', [0, 0], 0, aStart, 10); + var b = makePath('line', [0, 0], 90, bStart, 10); + var before = clone([a, b]); + var f = makerjs.path.fillet(a, b, 2); + assertFillet(before, [a, b], f, 2, 1e-12); + assert.ok(distance(f.origin, [2, 2]) < 1e-12); + })); + }); + + it('supports a radius larger than a short line when the tangent point still fits', function () { + var a = makePath('line', [0, 0], 0, true, 1); + var b = makePath('line', [0, 0], 170, false, 1); + var before = clone([a, b]); + assertFillet(before, [a, b], makerjs.path.fillet(a, b, 2), 2, 1e-12); + }); + + it('handles nearly parallel lines at both ends of the angular range', function () { + [.001, .1, 179.9, 179.999].forEach(degrees => { + var radius = degrees < 90 ? .00001 : 1000; + var a = makePath('line', [0, 0], 0, false, 10); + var b = makePath('line', [0, 0], degrees, true, 10); + var before = clone([a, b]); + var f = makerjs.path.fillet(a, b, radius); + assertFillet(before, [a, b], f, radius, 1e-9); + var trim = radius / Math.tan(degrees * Math.PI / 360); + assert.ok(distance(f.origin, [trim, radius]) < 1e-8); + }); + }); + + it('rejects a fillet which consumes an arc or has a collapsed inner guide', function () { + [5, 6, 10, 11].forEach(radius => { + assertRejected(new makerjs.paths.Arc([0, 0], 10, 0, 90), new makerjs.paths.Line([10, 0], [0, 0]), radius); + }); + }); + + it('preserves path metadata and gives the same fillet when arguments are swapped', function () { + var a = makePath('arc', [17, -23], 25, false, 40, 270, -2); + var b = makePath('line', [17, -23], 130, true, 100); + a.layer = 'cut'; + a.userData = { id: 42 }; + b.layer = 'engrave'; + var before = clone([a, b]), reversed = clone([b, a]); + var f = makerjs.path.fillet(a, b, 1); + var g = makerjs.path.fillet(reversed[0], reversed[1], 1); + assertFillet(before, [a, b], f, 1, 1e-11); + assertFillet(before.slice().reverse(), reversed, g, 1, 1e-11); + assert.ok(distance(f.origin, g.origin) < 1e-11); + assert.ok(distance(ends(f)[0], ends(g)[0]) < 1e-11); + assert.strictEqual(a.layer, 'cut'); + assert.deepStrictEqual(a.userData, { id: 42 }); + assert.strictEqual(b.layer, 'engrave'); + }); + + it('uses pointMatchingDistance, including the default and an exact zero', function () { + function pair() { return [new makerjs.paths.Line([0, 0], [10, 0]), new makerjs.paths.Line([0, .001], [0, 10])]; } + [undefined, { pointMatchingDistance: .002 }].forEach(options => { + var paths = pair(), before = clone(paths); + assertFillet(before, paths, makerjs.path.fillet(paths[0], paths[1], 1, options), 1, 1e-12); + }); + [0, .0005].forEach(t => assertRejected(...pair(), 1, { pointMatchingDistance: t })); + var paths = [new makerjs.paths.Line([0, 0], [10, 0]), new makerjs.paths.Line([0, 0], [0, 10])]; + assert.ok(makerjs.path.fillet(...paths, 1, { pointMatchingDistance: 0 })); + }); + + it('selects the closest join when all endpoints fall inside the matching tolerance', function () { + var a = new makerjs.paths.Line([.0001, 0], [0, 0]); + var b = new makerjs.paths.Line([0, 0], [0, .0001]); + var before = clone([a, b]); + assertFillet(before, [a, b], makerjs.path.fillet(a, b, .00001), .00001, 1e-15); + }); + + it('rejects a fillet which consumes or passes a line endpoint', function () { + [1, 1.01, 2, 100].forEach(radius => { + assertRejected(new makerjs.paths.Line([0, 0], [1, 0]), new makerjs.paths.Line([0, 0], [0, 10]), radius); + }); + }); + + it('rejects disconnected, collinear and tangent paths without mutation', function () { + var a = new makerjs.paths.Line([0, 0], [10, 0]); + [new makerjs.paths.Line([20, 0], [20, 10]), + new makerjs.paths.Line([0, 0], [-10, 0]), + new makerjs.paths.Line([0, 0], [5, 0]), + new makerjs.paths.Arc([0, -10], 10, 90, 180)].forEach(b => assertRejected(clone(a), b, 1)); + }); + + it('preserves the documented cusp fillets between arcs and between an arc and a line', function () { + [false, true].forEach(line => [false, true].forEach(swap => { + var a = new makerjs.paths.Arc([0, 50], 50, 270, 0); + var b = line ? new makerjs.paths.Line([50, 50], [50, 0]) : new makerjs.paths.Arc([100, 50], 50, 180, 270); + var paths = swap ? [b, a] : [a, b], before = clone(paths); + var f = makerjs.path.fillet(paths[0], paths[1], 2); + assertFillet(before, paths, f, 2, 1e-11); + assert.ok(distance(f.origin, line ? [48, 30] : [50, 50 - Math.sqrt(204)]) < 1e-11); + })); + }); + + it('rejects invalid radii and matching tolerances without mutation', function () { + var a = new makerjs.paths.Line([0, 0], [10, 0]), b = new makerjs.paths.Line([0, 0], [0, 10]); + [undefined, null, 0, -1, NaN, Infinity, -Infinity, '1'].forEach(r => assertRejected(clone(a), clone(b), r)); + [-1, NaN, Infinity].forEach(t => assertRejected(clone(a), clone(b), 1, { pointMatchingDistance: t })); + assertRejected(a, a, 1); + }); + + it('rejects unsupported, nonfinite and degenerate paths without throwing', function () { + var invalid = [null, undefined, {}, new makerjs.paths.Circle([0, 0], 10), + { type: 'bezier-seed', origin: [0, 0], end: [10, 0], controls: [[5, 1]] }, + new makerjs.paths.Line([0, 0], [0, 0]), new makerjs.paths.Line([0, 0], [Infinity, 0]), + new makerjs.paths.Line([NaN, 0], [10, 0]), new makerjs.paths.Arc([0, 0], 0, 0, 90), + new makerjs.paths.Arc([0, 0], -1, 0, 90), new makerjs.paths.Arc([0, 0], Infinity, 0, 90), + new makerjs.paths.Arc([0, 0], 10, NaN, 90), new makerjs.paths.Arc([0, 0], 10, 0, Infinity), + new makerjs.paths.Arc([0, 0], 10, 0, 0), new makerjs.paths.Arc([0, 0], 10, 0, 360)]; + invalid.forEach(a => { + var b = new makerjs.paths.Line([0, 0], [10, 0]); + assertRejected(a, b, 1); + assertRejected(b, a, 1); + }); + }); + + it('avoids the folding fillet found on a major arc by the seeded stress test', function () { + var a = new makerjs.paths.Line([-140.12877756709292, -655.370787645818], [-164.41924936857933, -720.2658384062112]); + var b = new makerjs.paths.Arc([-169.07033634642136, -660.6537840270322], 29.419787139631808, -322.4799134233036, 10.344883210491265); + var before = clone([a, b]); + var f = makerjs.path.fillet(a, b, 25.10584803055972); + if (f) assertFillet(before, [a, b], f, f.radius, 1e-10); + else assert.deepStrictEqual([a, b], before); + }); + + it('leaves ill-conditioned arcs unchanged when tangent accuracy cannot be maintained', function () { + var a = new makerjs.paths.Arc([-5535980.026299062, -5291100.871746648], 7657860.228979131, 763.7043460272253, 822.9875443855208); + var b = new makerjs.paths.Arc([-10979958361.778435, 36479559877.26404], 38096164826.203705, -791.2097676715003, -433.2487657603603); + assertRejected(a, b, 1); + }); + + // Reproduce any failure with the seed, case index and complete original inputs + // printed by the assertion. Increase this environment variable for a longer run. + var cases = Number(process.env.MAKERJS_FILLET_STRESS_CASES || 3000); + assert.ok(Number.isInteger(cases) && cases > 0, 'MAKERJS_FILLET_STRESS_CASES must be a positive integer'); + [['line', 'line'], ['line', 'arc'], ['arc', 'arc']].forEach(kinds => { + [0x51f17e, 0xc0ffee].forEach(seed => { + [false, true].forEach(large => { + it('stress tests ' + kinds.join('/') + ', seed=' + seed + ', ' + (large ? 'boundary radii' : 'known fitting radii'), function () { + var random = randomSource(seed), accepted = 0, rejected = 0; + for (var i = 0; i < cases; i++) { + var scale = [1e-6, .001, 1, 1000, 1e6][i % 5]; + var join = polar(random() * 360, random() * 1000 * scale); + var direction = random() * 360; + var turn = (15 + random() * 150) * (random() < .5 ? 1 : -1); + var paths = kinds.map((kind, j) => makePath(kind, join, direction + j * turn, + random() < .5, (20 + random() * 100) * scale, 20 + random() * 330, Math.floor(random() * 7) - 3)); + var radius = (large ? .1 + random() * 100 : .01 + random() * .04) * scale; + if (i % 2) paths.reverse(); + var before = clone(paths); + try { + var f = makerjs.path.fillet(paths[0], paths[1], radius); + if (f) { + assertFillet(before, paths, f, radius, scale * 1e-8); + accepted++; + } else { + assert.ok(large, 'a sufficiently small fillet must fit'); + assert.deepStrictEqual(paths, before, 'failed fillet modified its inputs'); + rejected++; + } + } catch (e) { + e.message += '\n' + JSON.stringify({ seed, caseIndex: i, paths: before, radius }); + throw e; + } + } + assert.ok(accepted > 0); + if (large) assert.ok(rejected > 0, 'must exercise both successful and rejected fillets'); + }); + }); + }); + }); + + [['line', 'arc'], ['arc', 'arc']].forEach(kinds => { + it('stress tests equal outward tangents for ' + kinds.join('/'), function () { + var seed = 0xc05f17, random = randomSource(seed); + for (var i = 0; i < cases; i++) { + var scale = [1e-6, .001, 1, 1000, 1e6][i % 5]; + var join = polar(random() * 360, random() * 100 * scale); + var direction = random() * 360; + var paths = kinds.map((kind, j) => makePath(kind, join, direction, random() < .5, + (j ? 80 + random() * 40 : 20 + random() * 20) * scale, 90 + random() * 180, Math.floor(random() * 7) - 3)); + if (i % 2) paths.reverse(); + var radius = (.01 + random() * .04) * scale; + var before = clone(paths); + try { + assertFillet(before, paths, makerjs.path.fillet(paths[0], paths[1], radius), radius, scale * 1e-8); + } catch (e) { + e.message += '\n' + JSON.stringify({ seed, caseIndex: i, paths: before, radius }); + throw e; + } + } + }); + + it('stress tests extreme size ratios for ' + kinds.join('/'), function () { + var seed = 0xabad1dea, random = randomSource(seed), accepted = 0, rejected = 0; + for (var i = 0; i < cases; i++) { + var direction = random() * 360; + var paths = kinds.map((kind, j) => makePath(kind, [0, 0], direction + j * (.001 + random() * 179.998), + random() < .5, Math.pow(10, -3 + random() * 15), .01 + random() * 359.98, Math.floor(random() * 7) - 3)); + var before = clone(paths); + try { + var f = makerjs.path.fillet(paths[0], paths[1], 1); + if (f) { + assertFillet(before, paths, f, 1, 1e-6); + accepted++; + } else { + assert.deepStrictEqual(paths, before); + rejected++; + } + } catch (e) { + e.message += '\n' + JSON.stringify({ seed, caseIndex: i, paths: before, radius: 1 }); + throw e; + } + } + assert.ok(accepted > 0 && rejected > 0); + }); + }); + + function mixedLoop() { + return { paths: { + a: new makerjs.paths.Arc([0, 0], 10, 0, 90), + b: new makerjs.paths.Line([0, 10], [0, 30]), + c: new makerjs.paths.Arc([0, 40], 10, 270, 360), + d: new makerjs.paths.Line([10, 40], [30, 40]), + e: new makerjs.paths.Arc([40, 40], 10, 180, 270), + f: new makerjs.paths.Line([40, 30], [40, 10]), + g: new makerjs.paths.Arc([40, 0], 10, 90, 180), + h: new makerjs.paths.Line([30, 0], [10, 0]) + } }; + } + + it('fillets a closed mixed Arc/Line chain across nested model origins', function () { + var loop = mixedLoop(); + Object.keys(loop.paths).forEach((key, i) => { + var offset = [i * 17, i * -31]; + var p = makerjs.path.clone(loop.paths[key], offset.map(n => -n)); + loop.models = loop.models || {}; + loop.models[key] = { origin: offset, paths: { p } }; + }); + delete loop.paths; + loop.origin = [1000, -2000]; + var chain = makerjs.model.findSingleChain(loop); + assert.ok(chain.endless); + var fillets = makerjs.chain.fillet(chain, 1); + assert.strictEqual(Object.keys(fillets.paths).length, 8); + var result = { models: { loop, fillets } }; + var chains = makerjs.model.findChains(result, { pointMatchingDistance: 1e-6 }); + assert.strictEqual(chains.length, 1); + assert.ok(chains[0].endless); + assert.strictEqual(chains[0].links.length, 16); + var svg = makerjs.exporter.toSVG(result), dxf = makerjs.exporter.toDXF(result); + assert.ok(!/NaN|Infinity/.test(svg + dxf)); + assert.ok(svg.includes(' fillets.paths[k].radius); + assert.ok(radii.includes(.5) && radii.includes(1)); + var chains = makerjs.model.findChains({ models: { loop, fillets } }); + assert.strictEqual(chains.length, 1); + assert.ok(chains[0].endless); + }); + + it('keeps a long open chain connected after sequential Arc/Line fillets', function () { + var model = { paths: {} }, join = [0, 0], count = 2000; + for (var i = 0; i < count; i++) { + var p = makePath(i % 2 ? 'arc' : 'line', join, i % 2 ? 30 : -30, true, 50, 60, 0); + model.paths['p' + i] = p; + join = ends(p)[1]; + } + var chain = makerjs.model.findSingleChain(model); + assert.strictEqual(chain.links.length, count); + var fillets = makerjs.chain.fillet(chain, .1); + assert.strictEqual(Object.keys(fillets.paths).length, count - 1); + var chains = makerjs.model.findChains({ models: { model, fillets } }, { pointMatchingDistance: 1e-6 }); + assert.strictEqual(chains.length, 1); + assert.ok(!chains[0].endless); + assert.strictEqual(chains[0].links.length, count * 2 - 1); + }); + + it('preserves dogbone behavior after changing shared endpoint matching', function () { + var a = new makerjs.paths.Line([0, 0], [10, 0]), b = new makerjs.paths.Line([0, 0], [0, 10]); + var f = makerjs.path.dogbone(a, b, 1); + assert.ok(f && span(f) >= 180); + assert.ok(distance(f.origin, [Math.SQRT1_2, Math.SQRT1_2]) < 1e-7); + ends(f).forEach(p => assert.ok(Math.min(distance(p, a.origin), distance(p, b.origin)) < 2e-7)); + }); +});