diff --git a/src/core/refine-brush.ts b/src/core/refine-brush.ts index 1fd6041..58bb49e 100644 --- a/src/core/refine-brush.ts +++ b/src/core/refine-brush.ts @@ -1,9 +1,11 @@ -import type { GuidePoint } from './refine-band'; +import { type GuidePoint, localEdge } from './refine-band'; import type { EdgeInput } from './refine-edge'; import { fitShape } from './refine-fit'; import { type RefineMesh, type RefineTopology, moveVertex, vertexNormal } from './refine-mesh'; import { nextMark, slotsFor, verticesUnderBrush, walkUnderBrush } from './refine-paint'; +import { nearestOnSurface } from './refine-sketch'; import { smoothScale, smoothTargets } from './refine-smooth'; +import { fitTrace, traceScatter, traceStroke } from './refine-trace'; import type { Vec3 } from './types'; export type RefineBrush = 'crease' | 'flatten' | 'smooth'; @@ -20,8 +22,14 @@ export interface Dab { const collapse = 1e-3; /** Times a vertex's move is halved for a triangle it would fold or collapse before it is dropped. */ const halvings = 6; -/** Most points a crease stroke's guide may have. */ -const maximumGuidePoints = 32; +/** + * A traced edge's points are fitted within this many times the scan's noise, a quarter edge, or this + * many times their own scatter, whichever is most. + */ +const traceNoise = 2.5; +const traceScatterTimes = 2; +/** A stroke closes when it comes back within a radius of its start after this many radii. */ +const closeLength = 6; /** * Projects the vertices under the brush onto local quadric fits of the surface (`smoothTargets`), @@ -101,10 +109,18 @@ export function flattenDab(mesh: RefineMesh, topology: RefineTopology, dab: Dab) } /** - * A freehand stroke as a spline guide: jitter removed, width = radius. Null for a stroke shorter - * than the radius. + * A freehand stroke as a guide on the rounded edge beside it. The stroke's first pass is smoothed, + * then traced onto the middle of the rounding within reach of the brush (`edgeUnderStroke`), so the + * stroke may run on either flank or on the rounding itself. The traced edge is fitted with lines and + * arcs where they hold, splines where they do not, and corners where it turns sharply + * (`fitTrace`). A stroke that ends near where it started closes the guide. Where too little of the + * stroke finds an edge, the smoothed stroke itself is the guide. Width = radius. Null for a stroke + * shorter than the radius. */ export function creaseInput( + mesh: RefineMesh, + topology: RefineTopology, + noise: number, stroke: GuidePoint[], radius: number, strength: number, @@ -121,48 +137,79 @@ export function creaseInput( const along = whole.subarray(0, count); const length = along[count - 1]; if (!(length >= radius)) return null; - // Resampled every radius, each sample a local straight-line fit to the stroke within a radius. - const samples = Math.ceil(length / radius); - const smooth: Vec3[] = []; - for (let j = 0; j <= samples; j++) - smooth.push(lineFitAt(pass, along, (j * length) / samples, radius)); - const stations = [0]; - for (let j = 1; j <= samples; j++) { - const a = smooth[j - 1], - b = smooth[j]; - stations.push(stations[j - 1] + Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2])); - } - const total = stations[samples]; - const points = Math.min(maximumGuidePoints, Math.ceil(length / (4 * radius)) + 3); - const guide: GuidePoint[] = []; - let j = 0, - nearest = 0; - for (let k = 0; k < points; k++) { - const s = (k * total) / (points - 1); - while (j < samples - 1 && stations[j + 1] < s) j++; - const span = stations[j + 1] - stations[j]; - const t = span > 0 ? Math.min(1, Math.max(0, (s - stations[j]) / span)) : 0; - const position = [0, 1, 2].map( - (a) => smooth[j][a] + t * (smooth[j + 1][a] - smooth[j][a]), - ) as Vec3; - // The stroke's own triangle at the same fraction of its length seeds the solve there. - const raw = total > 0 ? (s / total) * length : 0; - while ( - nearest < count - 1 && - Math.abs(along[nearest + 1] - raw) <= Math.abs(along[nearest] - raw) - ) + const step = localEdge(mesh, topology, pass) || radius / 10; + // Evenly spaced, each a local straight-line fit to the stroke within a radius, on the stroke's + // own triangle at the same station. + const samples = Math.max(2, Math.ceil(length / Math.min(radius, Math.max(radius / 3, step)))); + let path: GuidePoint[] = []; + let nearest = 0; + for (let j = 0; j <= samples; j++) { + const s = (j * length) / samples; + while (nearest < count - 1 && Math.abs(along[nearest + 1] - s) <= Math.abs(along[nearest] - s)) nearest++; - guide.push({ triangle: pass[nearest].triangle, position }); + path.push({ triangle: pass[nearest].triangle, position: lineFitAt(pass, along, s, radius) }); } + const end = closingPoint(path, radius); + const closed = end > 0; + if (closed) path = path.slice(0, end); + const found = traceStroke(mesh, topology, path, radius, step); + const edge = found.length ? found : path; + const points = edge.map((p) => p.position); + const traced = fitTrace( + points, + closed, + Math.max(traceNoise * noise, step / 4, traceScatterTimes * traceScatter(points)), + radius, + ); + if (!traced) return null; + // Each control onto the surface, searched from the traced point nearest it. + const onSurface = (p: Vec3): GuidePoint => { + let seed = edge[0], + closest = Infinity; + for (const q of edge) { + const d = Math.hypot(q.position[0] - p[0], q.position[1] - p[1], q.position[2] - p[2]); + if (d < closest) { + closest = d; + seed = q; + } + } + return nearestOnSurface(mesh, topology, { triangle: seed.triangle, position: p }); + }; return { - segments: [{ kind: 'spline', points: guide }], - joints: [], - closed: false, + segments: traced.segments.map(({ kind, points }) => ({ + kind, + points: points.map(onSurface), + })), + joints: traced.joints, + closed: traced.closed, width: radius, strength, }; } +/** + * Where a stroke that comes back round to its start closes: the index of its point nearest the + * start, among those at least `closeLength` radii along, when that is within a radius of it; else 0. + */ +function closingPoint(path: GuidePoint[], radius: number) { + const start = path[0].position; + let travelled = 0, + best = 0, + closest = radius; + for (let i = 1; i < path.length; i++) { + const a = path[i - 1].position, + b = path[i].position; + travelled += Math.hypot(b[0] - a[0], b[1] - a[1], b[2] - a[2]); + if (travelled < closeLength * radius) continue; + const d = Math.hypot(b[0] - start[0], b[1] - start[1], b[2] - start[2]); + if (d < closest) { + closest = d; + best = i; + } + } + return best; +} + /** * Index of the last point of the stroke's first pass over the surface. A point within `radius` of * the stroke laid at least 2 radius of length before it, travelling against that stroke's direction diff --git a/src/core/refine-detect.ts b/src/core/refine-detect.ts index 100c56e..ea7b577 100644 --- a/src/core/refine-detect.ts +++ b/src/core/refine-detect.ts @@ -1,4 +1,3 @@ -import { EigenvalueDecomposition, Matrix } from 'ml-matrix'; import type { GuidePoint } from './refine-band'; import { type GuideKind, drawnCurve } from './refine-curve'; import { VertexNormals, vertexCurvature } from './refine-curvature'; @@ -17,6 +16,16 @@ import { medianEdgeLength, weldedCorner, } from './refine-mesh'; +import { + type Circle, + corners, + fitCircle, + lineRms, + onCircle, + pointAt, + principalAxes, + stations, +} from './refine-polyline'; import type { RegionInput } from './refine-region'; import type { Vec3 } from './types'; @@ -734,196 +743,6 @@ function centredSpine( return out; } -/** Arc length at each point of a polyline. */ -function stations(points: number[], closed: boolean) { - const count = points.length / 3; - const s = new Float64Array(count + (closed ? 1 : 0)); - for (let i = 1; i < s.length; i++) { - const a = (i - 1) * 3, - b = (i % count) * 3; - s[i] = - s[i - 1] + - Math.hypot( - points[b] - points[a], - points[b + 1] - points[a + 1], - points[b + 2] - points[a + 2], - ); - } - return s; -} - -/** Point at arc length `at` along a polyline with `stations` `s`. */ -function pointAt(points: number[], s: Float64Array, at: number, closed: boolean): Vec3 { - const count = points.length / 3; - const total = s[s.length - 1]; - if (closed) at = ((at % total) + total) % total; - else at = Math.min(Math.max(at, 0), total); - let lo = 0, - hi = s.length - 1; - while (hi - lo > 1) { - const mid = (lo + hi) >> 1; - if (s[mid] <= at) lo = mid; - else hi = mid; - } - const f = s[hi] > s[lo] ? (at - s[lo]) / (s[hi] - s[lo]) : 0; - const a = lo * 3, - b = (hi % count) * 3; - return [0, 1, 2].map((k) => points[a + k] + f * (points[b + k] - points[a + k])) as Vec3; -} - -/** Mean of a polyline's points between two arc lengths, sampled evenly. */ -function meanBetween(points: number[], s: Float64Array, from: number, to: number, closed: boolean) { - const mean: Vec3 = [0, 0, 0]; - const samples = 8; - for (let j = 0; j < samples; j++) { - const p = pointAt(points, s, from + ((to - from) * (j + 0.5)) / samples, closed); - for (let k = 0; k < 3; k++) mean[k] += p[k] / samples; - } - return mean; -} - -/** Indices where the polyline turns by more than `splitTurn` over `window` behind and ahead. */ -function corners(points: number[], closed: boolean, window: number) { - const count = points.length / 3; - const s = stations(points, closed); - const total = s[s.length - 1]; - const turn = new Float64Array(count); - for (let i = 0; i < count; i++) { - if (!closed && (s[i] < window || s[i] > total - window)) continue; - // Directions from the mean of the window behind to the middle, and on to the mean ahead. - const before = meanBetween(points, s, s[i] - window, s[i], closed), - here = meanBetween(points, s, s[i] - window / 4, s[i] + window / 4, closed), - after = meanBetween(points, s, s[i], s[i] + window, closed); - const u = [0, 1, 2].map((k) => here[k] - before[k]), - w = [0, 1, 2].map((k) => after[k] - here[k]); - const lu = Math.hypot(u[0], u[1], u[2]), - lw = Math.hypot(w[0], w[1], w[2]); - if (!(lu > 0 && lw > 0)) continue; - const cos = (u[0] * w[0] + u[1] * w[1] + u[2] * w[2]) / (lu * lw); - turn[i] = (Math.acos(Math.min(1, Math.max(-1, cos))) * 180) / Math.PI; - } - // The sharpest point of each run of turning points. - const cuts: number[] = []; - for (let i = 0; i < count; i++) { - if (turn[i] <= splitTurn) continue; - let best = i; - let j = i; - while (j + 1 < count && turn[j + 1] > splitTurn) if (turn[++j] > turn[best]) best = j; - cuts.push(best); - i = j; - } - return cuts; -} - -interface Circle { - rms: number; - centre: Vec3; - radius: number; - /** Unit axes of the circle's plane. */ - u: Vec3; - v: Vec3; -} - -function principalAxes(points: number[]) { - const count = points.length / 3; - const mean: Vec3 = [0, 0, 0]; - for (let i = 0; i < count; i++) for (let k = 0; k < 3; k++) mean[k] += points[i * 3 + k] / count; - const c = new Matrix(3, 3); - for (let i = 0; i < count; i++) - for (let r = 0; r < 3; r++) - for (let q = 0; q < 3; q++) - c.set(r, q, c.get(r, q) + (points[i * 3 + r] - mean[r]) * (points[i * 3 + q] - mean[q])); - const e = new EigenvalueDecomposition(c, { assumeSymmetric: true }); - const order = [0, 1, 2].sort((a, b) => e.realEigenvalues[b] - e.realEigenvalues[a]); - const vectors = order.map((j) => [0, 1, 2].map((r) => e.eigenvectorMatrix.get(r, j)) as Vec3); - return { mean, vectors }; -} - -/** RMS distance of the points from their best line. */ -function lineRms(points: number[]) { - const count = points.length / 3; - const { mean, vectors } = principalAxes(points); - const d = vectors[0]; - let sum = 0; - for (let i = 0; i < count; i++) { - const w = [0, 1, 2].map((k) => points[i * 3 + k] - mean[k]); - const t = w[0] * d[0] + w[1] * d[1] + w[2] * d[2]; - sum += w[0] ** 2 + w[1] ** 2 + w[2] ** 2 - t * t; - } - return Math.sqrt(Math.max(0, sum) / count); -} - -/** Circle in the points' best plane, by least squares on x^2 + y^2 + D x + E y + F. */ -function fitCircle(points: number[]): Circle | null { - const count = points.length / 3; - if (count < 3) return null; - const { mean, vectors } = principalAxes(points); - const [u, v, normal] = vectors; - const a = new Matrix(3, 3), - r = new Matrix(3, 1); - const xy: [number, number][] = []; - for (let i = 0; i < count; i++) { - const w = [0, 1, 2].map((k) => points[i * 3 + k] - mean[k]); - const x = w[0] * u[0] + w[1] * u[1] + w[2] * u[2], - y = w[0] * v[0] + w[1] * v[1] + w[2] * v[2]; - xy.push([x, y]); - const row = [x, y, 1]; - const rhs = -(x * x + y * y); - for (let p = 0; p < 3; p++) { - r.set(p, 0, r.get(p, 0) + row[p] * rhs); - for (let q = 0; q < 3; q++) a.set(p, q, a.get(p, q) + row[p] * row[q]); - } - } - let solution: Matrix; - try { - solution = solve3(a, r); - } catch { - return null; - } - const cx = -solution.get(0, 0) / 2, - cy = -solution.get(1, 0) / 2; - const radius = Math.sqrt(Math.max(0, cx * cx + cy * cy - solution.get(2, 0))); - if (!Number.isFinite(radius) || radius <= 0) return null; - let sum = 0; - xy.forEach(([x, y], i) => { - const h = [0, 1, 2].reduce((acc, k) => acc + (points[i * 3 + k] - mean[k]) * normal[k], 0); - sum += h * h + (Math.hypot(x - cx, y - cy) - radius) ** 2; - }); - const centre = [0, 1, 2].map((k) => mean[k] + cx * u[k] + cy * v[k]) as Vec3; - return { rms: Math.sqrt(sum / count), centre, radius, u, v }; -} - -function solve3(a: Matrix, r: Matrix) { - const m = a.to2DArray(); - const det = (q: number[][]) => - q[0][0] * (q[1][1] * q[2][2] - q[1][2] * q[2][1]) - - q[0][1] * (q[1][0] * q[2][2] - q[1][2] * q[2][0]) + - q[0][2] * (q[1][0] * q[2][1] - q[1][1] * q[2][0]); - const d = det(m); - if (!(Math.abs(d) > 1e-30)) throw new Error('singular'); - const out = new Matrix(3, 1); - for (let k = 0; k < 3; k++) - out.set( - k, - 0, - det(m.map((row, i) => row.map((value, j) => (j === k ? r.get(i, 0) : value)))) / d, - ); - return out; -} - -/** Point on a fitted circle at the angle of `p`. */ -function onCircle(fit: Circle, p: Vec3): Vec3 { - const { centre, radius, u, v } = fit; - const w = [0, 1, 2].map((k) => p[k] - centre[k]); - const angle = Math.atan2( - w[0] * v[0] + w[1] * v[1] + w[2] * v[2], - w[0] * u[0] + w[1] * u[1] + w[2] * u[2], - ); - return [0, 1, 2].map( - (k) => centre[k] + radius * (Math.cos(angle) * u[k] + Math.sin(angle) * v[k]), - ) as Vec3; -} - function closestOnTriangle(p: Vec3, a: Vec3, b: Vec3, c: Vec3): Vec3 { const sub = (x: Vec3, y: Vec3): Vec3 => [x[0] - y[0], x[1] - y[1], x[2] - y[2]]; const dot = (x: Vec3, y: Vec3) => x[0] * y[0] + x[1] * y[1] + x[2] * y[2]; @@ -1111,7 +930,7 @@ function spinePieces( const radius = Math.max(1.5 * halfWidth, 2 * step); const points = centredSpine(context, graph, path, closed, radius); const window = Math.max(2 * halfWidth, turnEdges * step); - const cuts = corners(points, closed, window); + const cuts = corners(points, closed, window, splitTurn); const pieces: number[][] = []; if (!cuts.length) pieces.push(path.map((_, i) => i)); else if (closed) { diff --git a/src/core/refine-paint.ts b/src/core/refine-paint.ts index 6b33f59..a24cac8 100644 --- a/src/core/refine-paint.ts +++ b/src/core/refine-paint.ts @@ -72,7 +72,7 @@ function crossInto(mesh: RefineMesh, t: number, out: Float64Array) { const norm = (x: number, y: number, z = 0) => Math.sqrt(x * x + y * y + z * z); /** Growable binary min-heap of (key, value) pairs. */ -class Heap { +export class Heap { keys: number[] = []; values: number[] = []; get size() { diff --git a/src/core/refine-polyline.ts b/src/core/refine-polyline.ts new file mode 100644 index 0000000..83742a6 --- /dev/null +++ b/src/core/refine-polyline.ts @@ -0,0 +1,200 @@ +import { EigenvalueDecomposition, Matrix } from 'ml-matrix'; +import type { Vec3 } from './types'; + +// Polylines as flat [x, y, z, ...] arrays: arc length, corners, and line and circle fits. + +/** Arc length at each point of a polyline. */ +export function stations(points: number[], closed: boolean) { + const count = points.length / 3; + const s = new Float64Array(count + (closed ? 1 : 0)); + for (let i = 1; i < s.length; i++) { + const a = (i - 1) * 3, + b = (i % count) * 3; + s[i] = + s[i - 1] + + Math.hypot( + points[b] - points[a], + points[b + 1] - points[a + 1], + points[b + 2] - points[a + 2], + ); + } + return s; +} + +/** Point at arc length `at` along a polyline with `stations` `s`. */ +export function pointAt(points: number[], s: Float64Array, at: number, closed: boolean): Vec3 { + const count = points.length / 3; + const total = s[s.length - 1]; + if (closed) at = ((at % total) + total) % total; + else at = Math.min(Math.max(at, 0), total); + let lo = 0, + hi = s.length - 1; + while (hi - lo > 1) { + const mid = (lo + hi) >> 1; + if (s[mid] <= at) lo = mid; + else hi = mid; + } + const f = s[hi] > s[lo] ? (at - s[lo]) / (s[hi] - s[lo]) : 0; + const a = lo * 3, + b = (hi % count) * 3; + return [0, 1, 2].map((k) => points[a + k] + f * (points[b + k] - points[a + k])) as Vec3; +} + +/** Mean of a polyline's points between two arc lengths, sampled evenly. */ +export function meanBetween( + points: number[], + s: Float64Array, + from: number, + to: number, + closed: boolean, +) { + const mean: Vec3 = [0, 0, 0]; + const samples = 8; + for (let j = 0; j < samples; j++) { + const p = pointAt(points, s, from + ((to - from) * (j + 0.5)) / samples, closed); + for (let k = 0; k < 3; k++) mean[k] += p[k] / samples; + } + return mean; +} + +/** Indices where the polyline turns by more than `limit` degrees over `window` behind and ahead. */ +export function corners(points: number[], closed: boolean, window: number, limit: number) { + const count = points.length / 3; + const s = stations(points, closed); + const total = s[s.length - 1]; + const turn = new Float64Array(count); + for (let i = 0; i < count; i++) { + if (!closed && (s[i] < window || s[i] > total - window)) continue; + // Directions from the mean of the window behind to the middle, and on to the mean ahead. + const before = meanBetween(points, s, s[i] - window, s[i], closed), + here = meanBetween(points, s, s[i] - window / 4, s[i] + window / 4, closed), + after = meanBetween(points, s, s[i], s[i] + window, closed); + const u = [0, 1, 2].map((k) => here[k] - before[k]), + w = [0, 1, 2].map((k) => after[k] - here[k]); + const lu = Math.hypot(u[0], u[1], u[2]), + lw = Math.hypot(w[0], w[1], w[2]); + if (!(lu > 0 && lw > 0)) continue; + const cos = (u[0] * w[0] + u[1] * w[1] + u[2] * w[2]) / (lu * lw); + turn[i] = (Math.acos(Math.min(1, Math.max(-1, cos))) * 180) / Math.PI; + } + // The sharpest point of each run of turning points. + const cuts: number[] = []; + for (let i = 0; i < count; i++) { + if (turn[i] <= limit) continue; + let best = i; + let j = i; + while (j + 1 < count && turn[j + 1] > limit) if (turn[++j] > turn[best]) best = j; + cuts.push(best); + i = j; + } + return cuts; +} + +export interface Circle { + rms: number; + centre: Vec3; + radius: number; + /** Unit axes of the circle's plane. */ + u: Vec3; + v: Vec3; +} + +export function principalAxes(points: number[]) { + const count = points.length / 3; + const mean: Vec3 = [0, 0, 0]; + for (let i = 0; i < count; i++) for (let k = 0; k < 3; k++) mean[k] += points[i * 3 + k] / count; + const c = new Matrix(3, 3); + for (let i = 0; i < count; i++) + for (let r = 0; r < 3; r++) + for (let q = 0; q < 3; q++) + c.set(r, q, c.get(r, q) + (points[i * 3 + r] - mean[r]) * (points[i * 3 + q] - mean[q])); + const e = new EigenvalueDecomposition(c, { assumeSymmetric: true }); + const order = [0, 1, 2].sort((a, b) => e.realEigenvalues[b] - e.realEigenvalues[a]); + const vectors = order.map((j) => [0, 1, 2].map((r) => e.eigenvectorMatrix.get(r, j)) as Vec3); + return { mean, vectors }; +} + +/** RMS distance of the points from their best line. */ +export function lineRms(points: number[]) { + const count = points.length / 3; + const { mean, vectors } = principalAxes(points); + const d = vectors[0]; + let sum = 0; + for (let i = 0; i < count; i++) { + const w = [0, 1, 2].map((k) => points[i * 3 + k] - mean[k]); + const t = w[0] * d[0] + w[1] * d[1] + w[2] * d[2]; + sum += w[0] ** 2 + w[1] ** 2 + w[2] ** 2 - t * t; + } + return Math.sqrt(Math.max(0, sum) / count); +} + +/** Circle in the points' best plane, by least squares on x^2 + y^2 + D x + E y + F. */ +export function fitCircle(points: number[]): Circle | null { + const count = points.length / 3; + if (count < 3) return null; + const { mean, vectors } = principalAxes(points); + const [u, v, normal] = vectors; + const a = new Matrix(3, 3), + r = new Matrix(3, 1); + const xy: [number, number][] = []; + for (let i = 0; i < count; i++) { + const w = [0, 1, 2].map((k) => points[i * 3 + k] - mean[k]); + const x = w[0] * u[0] + w[1] * u[1] + w[2] * u[2], + y = w[0] * v[0] + w[1] * v[1] + w[2] * v[2]; + xy.push([x, y]); + const row = [x, y, 1]; + const rhs = -(x * x + y * y); + for (let p = 0; p < 3; p++) { + r.set(p, 0, r.get(p, 0) + row[p] * rhs); + for (let q = 0; q < 3; q++) a.set(p, q, a.get(p, q) + row[p] * row[q]); + } + } + let solution: Matrix; + try { + solution = solve3(a, r); + } catch { + return null; + } + const cx = -solution.get(0, 0) / 2, + cy = -solution.get(1, 0) / 2; + const radius = Math.sqrt(Math.max(0, cx * cx + cy * cy - solution.get(2, 0))); + if (!Number.isFinite(radius) || radius <= 0) return null; + let sum = 0; + xy.forEach(([x, y], i) => { + const h = [0, 1, 2].reduce((acc, k) => acc + (points[i * 3 + k] - mean[k]) * normal[k], 0); + sum += h * h + (Math.hypot(x - cx, y - cy) - radius) ** 2; + }); + const centre = [0, 1, 2].map((k) => mean[k] + cx * u[k] + cy * v[k]) as Vec3; + return { rms: Math.sqrt(sum / count), centre, radius, u, v }; +} + +function solve3(a: Matrix, r: Matrix) { + const m = a.to2DArray(); + const det = (q: number[][]) => + q[0][0] * (q[1][1] * q[2][2] - q[1][2] * q[2][1]) - + q[0][1] * (q[1][0] * q[2][2] - q[1][2] * q[2][0]) + + q[0][2] * (q[1][0] * q[2][1] - q[1][1] * q[2][0]); + const d = det(m); + if (!(Math.abs(d) > 1e-30)) throw new Error('singular'); + const out = new Matrix(3, 1); + for (let k = 0; k < 3; k++) + out.set( + k, + 0, + det(m.map((row, i) => row.map((value, j) => (j === k ? r.get(i, 0) : value)))) / d, + ); + return out; +} + +/** Point on a fitted circle at the angle of `p`. */ +export function onCircle(fit: Circle, p: Vec3): Vec3 { + const { centre, radius, u, v } = fit; + const w = [0, 1, 2].map((k) => p[k] - centre[k]); + const angle = Math.atan2( + w[0] * v[0] + w[1] * v[1] + w[2] * v[2], + w[0] * u[0] + w[1] * u[1] + w[2] * u[2], + ); + return [0, 1, 2].map( + (k) => centre[k] + radius * (Math.cos(angle) * u[k] + Math.sin(angle) * v[k]), + ) as Vec3; +} diff --git a/src/core/refine-trace.ts b/src/core/refine-trace.ts new file mode 100644 index 0000000..7888a2d --- /dev/null +++ b/src/core/refine-trace.ts @@ -0,0 +1,970 @@ +import type { GuidePoint } from './refine-band'; +import type { GuideJoint, GuideKind } from './refine-curve'; +import { type RefineMesh, type RefineTopology, vertexNormal, weldedCorner } from './refine-mesh'; +import { Heap, nextMark } from './refine-paint'; +import { + type Circle, + corners, + fitCircle, + lineRms, + onCircle, + pointAt, + principalAxes, + stations, +} from './refine-polyline'; +import type { Vec3 } from './types'; + +// Tracing a rough stroke onto the rounded edge beside it, then fitting that edge with lines and arcs. + +/** + * The edge's rounding turns most within this many brush radii of the stroke, over the surface; the + * flanks either side of it are read out to `flankReach` radii. + */ +export const traceReach = 1.5; +const flankReach = 2.5; +/** Degrees the surface must turn across the stroke, from flank to flank, for a slice to hold an edge. */ +const minTurn = 20; +/** Share of a reading's slices that must find both flanks for the edge to be traced at the corner. */ +const cornerShare = 0.75; +/** A traced point is dropped when it lies farther across the path than this many times the + * points' scatter from the points either side of it. */ +const strayTimes = 8; +/** Points either side a traced point is compared with. */ +const strayNeighbours = 6; +/** Degrees off a flank's median normal within which a vertex is on that flank. */ +const flankSpread = 25; +/** Degrees past which a vertex's normal faces away from the stroke's surface: the back of the part. */ +const backAngle = 120; +/** Degrees the edge turns within a brush radius to count as a corner. */ +const cornerTurn = 40; +/** Most vertices read across one slice. */ +const sliceVertices = 600; +/** Point spacings a corner or the shortest piece spans at the least. */ +const scaleSpacings = 4; +/** Degrees between two pieces' directions where they meet within which the joint is smooth. */ +const smoothTurn = 25; +/** Costs of a piece in the fewest-pieces fit: an arc is a little dearer than a line. */ +const lineCost = 1; +const arcCost = 1.25; +/** A spline costs this, plus one per `splineReach` brush radii of its length. */ +const splineCost = 3; +const splineReach = 6; +/** Most degrees an arc piece may sweep; a whole ring is a closed path of one arc. */ +const longestSweep = 330; +/** Most points a line or arc is fitted to. */ +const fitPoints = 48; +/** Most points a traced spline may have. */ +const maximumSplinePoints = 32; + +const sub = (a: ArrayLike, b: ArrayLike): Vec3 => [ + a[0] - b[0], + a[1] - b[1], + a[2] - b[2], +]; +const dot = (a: ArrayLike, b: ArrayLike) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const cross = (a: ArrayLike, b: ArrayLike): Vec3 => [ + a[1] * b[2] - a[2] * b[1], + a[2] * b[0] - a[0] * b[2], + a[0] * b[1] - a[1] * b[0], +]; +const length = (a: ArrayLike) => Math.hypot(a[0], a[1], a[2]); +const scale = (a: ArrayLike, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k]; +const unit = (a: ArrayLike): Vec3 => { + const l = length(a); + return l > 0 ? [a[0] / l, a[1] / l, a[2] / l] : [0, 0, 0]; +}; +const mix = (a: ArrayLike, b: ArrayLike, t: number): Vec3 => [ + a[0] + t * (b[0] - a[0]), + a[1] + t * (b[1] - a[1]), + a[2] + t * (b[2] - a[2]), +]; + +/** + * The rounded edge beside a stroke, as points along it, read from the surface beside the stroke + * (`edgeUnderStroke`) on the side of it where most of the stroke finds an edge. The points are where + * the flanks meet, the sharp corner, when most slices have it; else the rounding's middle. Empty + * when less than half the stroke finds an edge. + */ +export function traceStroke( + mesh: RefineMesh, + topology: RefineTopology, + path: GuidePoint[], + radius: number, + step: number, +): GuidePoint[] { + let found = edgeUnderStroke(mesh, topology, path, radius, step).filter((s) => s !== null); + // Where slices found edges on both sides of the stroke, the side most of them found. + const votes = found.reduce((sum, s) => sum + s.side, 0); + if (found.some((s) => s.side === -Math.sign(votes))) + found = edgeUnderStroke(mesh, topology, path, radius, step, votes < 0 ? -1 : 1).filter( + (s) => s !== null, + ); + if (found.length < Math.max(3, path.length / 2)) return []; + const corners = found.filter((s) => s.corner); + const points = + corners.length >= cornerShare * found.length + ? corners.map((s) => s.corner!) + : found.map((s) => s.middle); + return withoutStrays(points, radius, step); +} + +/** + * The points less those that stray from the points either side of them: each is compared with a + * quadratic through up to `strayNeighbours` points before it, and another through those after it, + * so a point on either side of a corner keeps its place, and is dropped when it lies farther across + * the path than `strayTimes` its scatter, or half an edge, from both. + */ +function withoutStrays(points: GuidePoint[], radius: number, step: number): GuidePoint[] { + const p = points.map((q) => q.position); + const flat = p.flat(); + const s = stations(flat, false); + const limit = Math.max(strayTimes * traceScatter(p), step / 2); + const off = (i: number, side: -1 | 1) => { + const near: number[] = []; + for (let j = i + side; j >= 0 && j < p.length && near.length < strayNeighbours; j += side) + if (Math.abs(s[j] - s[i]) <= 2 * radius) near.push(j); + if (near.length < 4) return null; + const predicted = quadraticAt( + near.map((j) => s[j] - s[i]), + near.map((j) => p[j]), + ); + if (!predicted) return null; + const miss = sub(p[i], predicted.at); + return length(sub(miss, scale(predicted.direction, dot(miss, predicted.direction)))); + }; + return points.filter((_, i) => { + const misses = [off(i, -1), off(i, 1)].filter((m) => m !== null); + return !misses.length || Math.min(...misses) <= limit; + }); +} + +/** At 0, the least squares quadratic in `t` through the points, and its unit direction there. */ +function quadraticAt(t: number[], points: Vec3[]) { + // Normal equations for a + b t + c t^2, shared by the three coordinates. + const m = [0, 0, 0, 0, 0]; + for (const x of t) for (let k = 0; k < 5; k++) m[k] += x ** k; + const [s0, s1, s2, s3, s4] = m; + const det = s0 * (s2 * s4 - s3 * s3) - s1 * (s1 * s4 - s3 * s2) + s2 * (s1 * s3 - s2 * s2); + if (!(Math.abs(det) > 1e-18)) return null; + const at: Vec3 = [0, 0, 0], + slope: Vec3 = [0, 0, 0]; + for (let a = 0; a < 3; a++) { + let r0 = 0, + r1 = 0, + r2 = 0; + t.forEach((x, k) => { + r0 += points[k][a]; + r1 += x * points[k][a]; + r2 += x * x * points[k][a]; + }); + // Cramer's rule for a and b. + at[a] = (r0 * (s2 * s4 - s3 * s3) - s1 * (r1 * s4 - s3 * r2) + s2 * (r1 * s3 - s2 * r2)) / det; + slope[a] = + (s0 * (r1 * s4 - s3 * r2) - r0 * (s1 * s4 - s3 * s2) + s2 * (s1 * r2 - r1 * s2)) / det; + } + return { at, direction: unit(slope) }; +} + +/** + * The scatter of points along a path, mm, as the standard deviation of their noise across it: from + * their third differences, which a straight line or a steady curve leaves near zero, with the part + * along the path, from uneven spacing, taken out. 0 for fewer than 4 points. + */ +export function traceScatter(points: Vec3[]): number { + const sizes: number[] = []; + for (let i = 0; i + 3 < points.length; i++) { + const [a, b, c, d] = points.slice(i, i + 4); + const third = [0, 1, 2].map((k) => d[k] - 3 * c[k] + 3 * b[k] - a[k]); + const along = unit(sub(d, a)); + sizes.push(length(sub(third, scale(along, dot(third, along))))); + } + // The median size of a third difference of noise of deviation 1 in two directions. + return sizes.length ? median(sizes) / (Math.sqrt(20) * Math.sqrt(2 * Math.LN2)) : 0; +} + +/** + * Where the rounded edge runs beside a stroke: one `TracedSlice` per point of `path`, or null where + * the surface there does not turn. `path` is the stroke smoothed and evenly spaced, each point with its + * triangle. The surface within `flankReach` brush radii of the path, measured over the surface, is + * read in a slice across each point. Along a slice the vertex normals turn about the path where it + * crosses an edge. The edge taken is the turn nearest the stroke, within `traceReach` radii and on + * `side` of it when that is given. Its middle is where the normals have turned half way, and its + * corner is where lines fitted to the flanks either side meet. Reading the surface rather than the + * stroke finds the edge from either flank. + */ +export function edgeUnderStroke( + mesh: RefineMesh, + topology: RefineTopology, + path: GuidePoint[], + radius: number, + step: number, + side: -1 | 0 | 1 = 0, +): (TracedSlice | null)[] { + const count = path.length; + const found: (TracedSlice | null)[] = path.map(() => null); + if (count < 2 || !(radius > 0)) return found; + const at = path.map((p) => p.position); + const s = new Float64Array(count); + for (let i = 1; i < count; i++) s[i] = s[i - 1] + length(sub(at[i], at[i - 1])); + const total = s[count - 1]; + if (!(total > 0)) return found; + const half = Math.max(total / (count - 1) / 2, radius / 3, 1.5 * step); + const reach = flankReach * radius, + edgeReach = traceReach * radius; + const tangent = at.map((_, i) => + unit(sub(at[Math.min(i + 1, count - 1)], at[Math.max(i - 1, 0)])), + ); + const facing = path.map((p) => faceNormal(mesh, p.triangle)); + const across = facing.map((n, i) => unit(cross(tangent[i], n))); + const back = Math.cos((backAngle * Math.PI) / 180); + + // The vertices within reach of the stroke over the surface, nearest first, and not facing away; + // each with its distance over the surface, signed by the side of the stroke it is on. + const { position } = mesh; + const { neighbourStart, neighbours } = topology; + const { vertex: stamp, mark } = nextMark(mesh, topology); + const best = new Float64Array(mesh.weldedCount).fill(Infinity); + const heap = new Heap(); + for (const { triangle } of path) + for (const k of [0, 1, 2] as const) { + const v = weldedCorner(mesh, triangle, k); + const d = nearestOnPath( + at, + s, + position[v * 3], + position[v * 3 + 1], + position[v * 3 + 2], + ).distance; + if (best[v] <= d) continue; + best[v] = d; + heap.push(d, v); + } + const read: number[] = []; + const station: number[] = []; + const offset: number[] = []; + const normals: number[] = []; + const normal = new Float32Array(3); + while (heap.size) { + const v = heap.pop(); + const d = heap.top; + if (stamp[v] === mark || d > best[v]) continue; + stamp[v] = mark; + if (d > reach) break; + const px = position[v * 3], + py = position[v * 3 + 1], + pz = position[v * 3 + 2]; + const near = nearestOnPath(at, s, px, py, pz); + if (near.beyond > half) continue; + vertexNormal(mesh, topology, v, normal); + if (dot(normal, facing[near.index]) < back) continue; + const { foot, index } = near; + const side = + (px - foot[0]) * across[index][0] + + (py - foot[1]) * across[index][1] + + (pz - foot[2]) * across[index][2]; + read.push(v); + station.push(near.station); + offset.push(side < 0 ? -d : d); + normals.push(normal[0], normal[1], normal[2]); + for (let j = neighbourStart[v]; j < neighbourStart[v + 1]; j++) { + const w = neighbours[j]; + if (stamp[w] === mark) continue; + const e = + d + + Math.sqrt( + (position[w * 3] - px) ** 2 + + (position[w * 3 + 1] - py) ** 2 + + (position[w * 3 + 2] - pz) ** 2, + ); + if (e > reach || best[w] <= e) continue; + best[w] = e; + heap.push(e, w); + } + } + const order = read.map((_, i) => i).sort((a, b) => station[a] - station[b]); + const sorted = Float64Array.from(order, (i) => station[i]); + + const threshold = (minTurn * Math.PI) / 180; + const window = Math.max(radius / 2, 3 * step); + const grid = Math.max(step / 2, window / 16); + for (let i = 0; i < count; i++) { + const lowest = firstAt(sorted, s[i] - half), + highest = firstAt(sorted, s[i] + half); + if (highest - lowest < 6) continue; + // On a dense mesh, an even share of the slice's vertices is plenty to read. + const every = Math.max(1, Math.ceil((highest - lowest) / sliceVertices)); + const slice: number[] = []; + for (let j = lowest; j < highest; j += every) slice.push(order[j]); + // The slice's mean normal across the path, and the direction across it. + const t = tangent[i]; + const mean: Vec3 = [0, 0, 0]; + for (const k of slice) for (let a = 0; a < 3; a++) mean[a] += normals[k * 3 + a]; + const b = unit(sub(mean, scale(t, dot(mean, t)))); + if (!length(b)) continue; + const c = cross(t, b); + slice.sort((x, y) => offset[x] - offset[y]); + const o = Float64Array.from(slice, (k) => offset[k]); + const angle = slice.map((k) => { + const n = [normals[k * 3], normals[k * 3 + 1], normals[k * 3 + 2]]; + return Math.atan2(dot(n, c), dot(n, b)); + }); + // The step in the normals' angle across each place: median ahead less median behind. + const stepAt = (centre: number): Pick | null => { + const behind = angle.slice(firstAt(o, centre - window), firstAt(o, centre - window / 4)); + const ahead = angle.slice(firstAt(o, centre + window / 4), firstAt(o, centre + window)); + if (behind.length < 3 || ahead.length < 3) return null; + const from = median(behind), + to = median(ahead); + return { from, to, turn: Math.abs(to - from) }; + }; + // Each run of places where the surface turns is one edge, centred where it turns most. + const runs: Turn[] = []; + let open = false; + for (let centre = o[0]; centre <= o[o.length - 1]; centre += grid) { + const here = stepAt(centre); + if (!here || here.turn < threshold) { + open = false; + continue; + } + const current = open ? runs[runs.length - 1] : null; + if (!current) runs.push({ ...here, centre, first: centre, last: centre }); + else { + if (here.turn > current.turn) Object.assign(current, here, { centre }); + current.last = centre; + } + open = true; + } + if (!runs.length) continue; + // The edge nearest the stroke, on `side` of it when given, and the flanks either side of it as + // far as the next edge. + let e = -1; + runs.forEach((r, k) => { + const under = r.first <= 0 && r.last >= 0; + if (side && !under && Math.sign(r.centre) !== side) return; + if (Math.abs(r.centre) > edgeReach) return; + if (e < 0 || Math.abs(r.centre) < Math.abs(runs[e].centre)) e = k; + }); + if (e < 0) continue; + const edge = runs[e]; + const behind = flankLine( + slice, + angle, + firstAt(o, e > 0 ? runs[e - 1].last : -Infinity), + firstAt(o, edge.first), + read, + position, + at[i], + b, + c, + step, + ); + const ahead = flankLine( + slice, + angle, + firstAt(o, edge.last), + firstAt(o, e + 1 < runs.length ? runs[e + 1].first : Infinity), + read, + position, + at[i], + b, + c, + step, + ); + // Nearest a point, the triangle of the slice's vertex nearest it. + const onTriangle = (point: Vec3, among: number[]): GuidePoint => { + let seed = read[among[0]], + nearest = Infinity; + for (const k of among) { + const d = length(sub(position.subarray(read[k] * 3, read[k] * 3 + 3), point)); + if (d < nearest) { + nearest = d; + seed = read[k]; + } + } + return { triangle: topology.trianglesOf[topology.triangleStart[seed]], position: point }; + }; + // The middle of the rounding: where, across it, the normals pass half way between the flanks; + // the split that leaves the fewest normals on the wrong side of half way. + const { centre, from, to } = edge; + const middle = (from + to) / 2; + const past = (j: number) => (to > from ? angle[j] > middle : angle[j] < middle); + const lo = firstAt(o, centre - window), + hi = firstAt(o, centre + window); + let wrong = 0; + for (let j = lo; j < hi; j++) if (!past(j)) wrong++; + let fewest = wrong, + first = lo, + last = lo; + for (let j = lo; j < hi; j++) { + wrong += past(j) ? 1 : -1; + if (wrong < fewest) { + fewest = wrong; + first = last = j + 1; + } else if (wrong === fewest) last = j + 1; + } + const split = (first + last) >> 1; + const where = + split <= 0 ? o[0] : split >= o.length ? o[o.length - 1] : (o[split - 1] + o[split]) / 2; + const strip = Math.max(2 * step, grid); + const rounding = slice.filter((_, j) => Math.abs(o[j] - where) <= strip); + if (rounding.length < 2) continue; + const point: Vec3 = [0, 0, 0]; + for (const k of rounding) + for (let a = 0; a < 3; a++) point[a] += position[read[k] * 3 + a] / rounding.length; + const meeting = behind && ahead ? meet(behind, ahead) : null; + found[i] = { + side: edge.first <= 0 && edge.last >= 0 ? 0 : edge.centre < 0 ? -1 : 1, + middle: onTriangle(point, rounding), + corner: + meeting && Math.hypot(meeting[0], meeting[1]) <= reach + ? onTriangle( + [0, 1, 2].map((a) => at[i][a] + meeting[0] * c[a] + meeting[1] * b[a]) as Vec3, + slice, + ) + : null, + }; + } + return found; +} + +/** + * The edge across one slice: the middle of its rounding, on the surface, and where its two flanks + * meet, the sharp corner the rounding stands for, when both flanks could be fitted. + */ +export interface TracedSlice { + /** The side of the path the edge is on, by the sign of the offset across it; 0 when under it. */ + side: -1 | 0 | 1; + middle: GuidePoint; + corner: GuidePoint | null; +} + +/** Where the surface turns across a slice: the step in its normals' angle about the path. */ +interface Turn { + /** The offset across the slice where the step is largest, and the first and last with a step. */ + centre: number; + first: number; + last: number; + from: number; + to: number; + turn: number; +} + +/** A line across a slice, in its (across, up) plane. */ +interface Line2 { + mean: [number, number]; + direction: [number, number]; +} + +/** + * The line through a flank: the slice's vertices `lo` to `hi` (by offset across it) whose normals + * lie near their median's angle, in the slice's (across `c`, up `b`) plane about `origin`, fitted + * twice, the second time without the points the first left farthest off. Null for too few points or + * a flank too short to give a direction. + */ +function flankLine( + slice: number[], + angle: number[], + lo: number, + hi: number, + read: number[], + position: Float64Array, + origin: Vec3, + b: Vec3, + c: Vec3, + step: number, +): Line2 | null { + if (hi - lo < 4) return null; + const level = median(angle.slice(lo, hi)); + const spread = (flankSpread * Math.PI) / 180; + let points: [number, number][] = []; + for (let j = lo; j < hi; j++) { + if (Math.abs(angle[j] - level) > spread) continue; + const d = sub(position.subarray(read[slice[j]] * 3, read[slice[j]] * 3 + 3), origin); + points.push([dot(d, c), dot(d, b)]); + } + for (let pass = 0; pass < 2; pass++) { + if (points.length < 4) return null; + const line = fitLine2(points); + if (!line) return null; + const off = points.map(([x, y]) => + Math.abs((x - line.mean[0]) * line.direction[1] - (y - line.mean[1]) * line.direction[0]), + ); + if (pass === 1) { + const along = points.map( + ([x, y]) => (x - line.mean[0]) * line.direction[0] + (y - line.mean[1]) * line.direction[1], + ); + return Math.max(...along) - Math.min(...along) >= 2 * step ? line : null; + } + const limit = Math.max(3 * median(off), step / 8); + points = points.filter((_, k) => off[k] <= limit); + } + return null; +} + +/** The least squares line through 2D points. */ +function fitLine2(points: [number, number][]): Line2 | null { + let mx = 0, + my = 0; + for (const [x, y] of points) { + mx += x / points.length; + my += y / points.length; + } + let xx = 0, + xy = 0, + yy = 0; + for (const [x, y] of points) { + xx += (x - mx) ** 2; + xy += (x - mx) * (y - my); + yy += (y - my) ** 2; + } + const angle = 0.5 * Math.atan2(2 * xy, xx - yy); + if (!Number.isFinite(angle) || !(xx + yy > 0)) return null; + return { mean: [mx, my], direction: [Math.cos(angle), Math.sin(angle)] }; +} + +/** Where two lines cross, or null where they are nearly parallel. */ +function meet(a: Line2, b: Line2): [number, number] | null { + const [dx, dy] = a.direction, + [ex, ey] = b.direction; + const det = dx * ey - dy * ex; + if (Math.abs(det) < Math.sin((minTurn * Math.PI) / 180 / 2)) return null; + const wx = b.mean[0] - a.mean[0], + wy = b.mean[1] - a.mean[1]; + const t = (wx * ey - wy * ex) / det; + return [a.mean[0] + t * dx, a.mean[1] + t * dy]; +} + +/** Index of the first value of ascending `values` at or above `value`. */ +function firstAt(values: Float64Array, value: number) { + let lo = 0, + hi = values.length; + while (lo < hi) { + const mid = (lo + hi) >> 1; + if (values[mid] < value) lo = mid + 1; + else hi = mid; + } + return lo; +} + +function median(values: number[]) { + const sorted = values.slice().sort((a, b) => a - b); + const m = sorted.length >> 1; + return sorted.length % 2 ? sorted[m] : (sorted[m - 1] + sorted[m]) / 2; +} + +function faceNormal(mesh: RefineMesh, t: number): Vec3 { + const corner = (k: 0 | 1 | 2) => { + const w = weldedCorner(mesh, t, k) * 3; + return mesh.position.subarray(w, w + 3); + }; + const a = corner(0); + return unit(cross(sub(corner(1), a), sub(corner(2), a))); +} + +/** + * The nearest point of a polyline to (x, y, z): its distance, the point, its station, the polyline + * point nearer it, and how far past an end of the polyline (x, y, z) lies along it. + */ +function nearestOnPath(at: Vec3[], s: Float64Array, x: number, y: number, z: number) { + let best = Infinity, + station = 0, + index = 0, + beyond = 0; + const foot: Vec3 = [0, 0, 0]; + for (let i = 0; i + 1 < at.length; i++) { + const a = at[i], + b = at[i + 1]; + const dx = b[0] - a[0], + dy = b[1] - a[1], + dz = b[2] - a[2]; + const span = dx * dx + dy * dy + dz * dz; + const raw = span > 0 ? ((x - a[0]) * dx + (y - a[1]) * dy + (z - a[2]) * dz) / span : 0; + const t = Math.min(1, Math.max(0, raw)); + const fx = a[0] + t * dx, + fy = a[1] + t * dy, + fz = a[2] + t * dz; + const d = (fx - x) ** 2 + (fy - y) ** 2 + (fz - z) ** 2; + if (d < best) { + best = d; + foot[0] = fx; + foot[1] = fy; + foot[2] = fz; + station = s[i] + t * (s[i + 1] - s[i]); + index = t < 0.5 ? i : i + 1; + const past = i === 0 && raw < 0 ? -raw : i + 2 === at.length && raw > 1 ? raw - 1 : 0; + beyond = past * Math.sqrt(span); + } + } + return { distance: Math.sqrt(best), foot, station, index, beyond }; +} + +// --------------------------------------------------------------------------------------------- +// Fitting the traced edge + +export interface TracedSegment { + kind: GuideKind; + /** A line's two ends, an arc's start, middle and end, or a spline's points. */ + points: Vec3[]; +} +export interface TracedPath { + segments: TracedSegment[]; + /** One per joint between consecutive segments, plus one closing joint when `closed`. */ + joints: GuideJoint[]; + closed: boolean; +} + +/** A fitted stretch of the points, `from` to `to` inclusive. */ +interface Piece { + kind: GuideKind; + from: number; + to: number; + line?: { mean: Vec3; direction: Vec3 }; + circle?: Circle; +} + +/** + * The edge through `points`, in pieces: lines and arcs where they fit within `tolerance` RMS, over at + * least a brush radius each, in as few pieces as the costs allow, and splines where none does. + * Where the points turn sharply within a brush radius the path has a corner: the pieces either side + * are fitted clear of it and meet there at a sharp joint. Pieces that meet with one direction join + * smoothly. A closed path that is a circle is one arc. + */ +export function fitTrace( + points: Vec3[], + closed: boolean, + tolerance: number, + radius: number, +): TracedPath | null { + const count = points.length; + if (count < 2) return null; + if (closed && count < 6) closed = false; + const flat = points.flat(); + // The scale of corners and the shortest piece: the brush radius, but some points at the least. + const gaps = points.slice(1).map((p, i) => length(sub(p, points[i]))); + radius = Math.max(radius, scaleSpacings * median(gaps)); + if (closed) { + const circle = fitCircle(flat); + if (circle && circle.rms <= tolerance && circle.radius >= radius) { + const s = stations(flat, true); + const total = s[count]; + return { + segments: [ + { + kind: 'arc', + points: [0, 1, 2].map((k) => onCircle(circle, pointAt(flat, s, (k * total) / 3, true))), + }, + ], + joints: ['smooth'], + closed: true, + }; + } + } + let cuts = corners(flat, closed, radius, cornerTurn); + // `at` runs from the path's start, or on a closed path from a corner or a joint, to its end, which + // on a closed path is its start again. + let at = points; + if (closed) { + let start = cuts[0] ?? 0; + if (!cuts.length) { + // With no corner, start where a first fit puts a joint, so the closing joint is a real one. + const loop = [...points, points[0]]; + const first = fewestPieces(loop, stations(loop.flat(), false), 0, count, tolerance, radius); + start = first.length > 1 ? first[0].to % count : 0; + } + at = [...points.slice(start), ...points.slice(0, start + 1)]; + cuts = cuts.map((c) => (c - start + count) % count); + } + const s = stations(at.flat(), false); + const last = at.length - 1; + const corner = new Set(cuts.filter((c) => c > 0 && c < last)); + const bounds = [0, ...[...corner].sort((a, b) => a - b), last]; + const atCorner = (i: number) => corner.has(i) || (closed && cuts.length > 0); + const pieces: Piece[] = []; + const sharp: boolean[] = []; + for (let r = 0; r + 1 < bounds.length; r++) { + const from = bounds[r], + to = bounds[r + 1]; + // Clear of a corner by a brush radius, where that leaves enough to fit. + let lo = from, + hi = to; + if (atCorner(from)) while (lo < to && s[lo] - s[from] < radius) lo++; + if (atCorner(to)) while (hi > from && s[to] - s[hi] < radius) hi--; + if (hi - lo < 2) { + lo = from; + hi = to; + } + const run = fewestPieces(at, s, lo, hi, tolerance, radius); + run[0].from = from; + run[run.length - 1].to = to; + run.forEach((piece, k) => { + if (pieces.length) sharp.push(k === 0); + pieces.push(piece); + }); + } + if (closed) { + sharp.push(cuts.length > 0); + // A closed path of one segment must be a circle: a ring no arc fits is two splines. + if (pieces.length === 1) { + const middle = last >> 1; + pieces.splice( + 0, + 1, + { kind: 'spline', from: 0, to: middle }, + { + kind: 'spline', + from: middle, + to: last, + }, + ); + sharp.splice(0, 1, false, false); + } + } + return assemble(at, pieces, sharp, closed, radius); +} + +/** + * The pieces over points `lo` to `hi` of `at` in the fewest by cost: each line or arc spans at least + * a brush radius and fits within `tolerance`; a spline spans anything. + */ +function fewestPieces( + at: Vec3[], + s: Float64Array, + lo: number, + hi: number, + tolerance: number, + radius: number, +): Piece[] { + // A run one line or arc fits is that piece, whatever its length. + const whole = fitPiece(at.slice(lo, hi + 1), tolerance, radius); + if (whole) return [{ ...whole, from: lo, to: hi }]; + const n = hi - lo + 1; + const cost = new Float64Array(n).fill(Infinity); + const previous = new Int32Array(n).fill(-1); + const choice: (Piece | null)[] = new Array(n).fill(null); + cost[0] = 0; + for (let j = 1; j < n; j++) { + for (let i = 0; i < j; i++) { + const span = s[lo + j] - s[lo + i]; + // Every piece spans a brush radius, unless the run is shorter. + if (span < radius && !(i === 0 && j === n - 1)) continue; + const spline = cost[i] + splineCost + span / (splineReach * radius); + if (spline < cost[j]) { + cost[j] = spline; + previous[j] = i; + choice[j] = { kind: 'spline', from: lo + i, to: lo + j }; + } + } + for (let i = j - 2; i >= 0; i--) { + if (s[lo + j] - s[lo + i] < radius) continue; + const piece = fitPiece(at.slice(lo + i, lo + j + 1), tolerance, radius); + if (!piece) break; + const total = cost[i] + (piece.kind === 'line' ? lineCost : arcCost); + if (total < cost[j]) { + cost[j] = total; + previous[j] = i; + choice[j] = { ...piece, from: lo + i, to: lo + j }; + } + } + } + const run: Piece[] = []; + for (let j = n - 1; j > 0; j = previous[j]) run.unshift(choice[j]!); + return run; +} + +/** A line, else an arc, through `points` within `tolerance`; null when neither fits. */ +function fitPiece(points: Vec3[], tolerance: number, radius: number): Piece | null { + // A long piece is judged on an even subset of its points, its ends included. + if (points.length > fitPoints) { + const stride = (points.length - 1) / (fitPoints - 1); + points = Array.from({ length: fitPoints }, (_, i) => points[Math.round(i * stride)]); + } + const flat = points.flat(); + if (lineRms(flat) <= tolerance) { + const { mean, vectors } = principalAxes(flat); + return { kind: 'line', from: 0, to: 0, line: { mean, direction: vectors[0] } }; + } + const circle = fitCircle(flat); + if (!circle || circle.rms > tolerance || circle.radius < radius) return null; + if (Math.abs(signedSweep(circle, points)) > (longestSweep * Math.PI) / 180) return null; + return { kind: 'arc', from: 0, to: 0, circle }; +} + +/** Angle of `p` round the circle, from its `u` axis toward `v`. */ +function angleOn(circle: Circle, p: Vec3) { + const w = sub(p, circle.centre); + return Math.atan2(dot(w, circle.v), dot(w, circle.u)); +} + +/** Signed angle the points travel round the circle, start to end. */ +function signedSweep(circle: Circle, points: Vec3[]) { + let sweep = 0; + for (let i = 1; i < points.length; i++) { + let d = angleOn(circle, points[i]) - angleOn(circle, points[i - 1]); + if (d > Math.PI) d -= 2 * Math.PI; + if (d < -Math.PI) d += 2 * Math.PI; + sweep += d; + } + return sweep; +} + +/** The point of an arc half way round from `start` to `end`, the way `points` travel. */ +function arcMiddle(circle: Circle, points: Vec3[], start: Vec3, end: Vec3): Vec3 { + const from = angleOn(circle, start); + let sweep = angleOn(circle, end) - from; + const travel = signedSweep(circle, points); + while (travel >= 0 && sweep < 0) sweep += 2 * Math.PI; + while (travel < 0 && sweep > 0) sweep -= 2 * Math.PI; + const angle = from + sweep / 2; + const { centre, radius, u, v } = circle; + return [0, 1, 2].map( + (k) => centre[k] + radius * (Math.cos(angle) * u[k] + Math.sin(angle) * v[k]), + ) as Vec3; +} + +/** Where a piece's fit passes the point `p`. */ +function onPiece(piece: Piece, p: Vec3): Vec3 { + if (piece.line) { + const { mean, direction } = piece.line; + const t = dot(sub(p, mean), direction); + return [0, 1, 2].map((k) => mean[k] + t * direction[k]) as Vec3; + } + if (piece.circle) return onCircle(piece.circle, p); + return p; +} + +/** A piece's direction at its point nearest `p`, `at` running from its start to its end. */ +function directionAt(piece: Piece, at: Vec3[], p: Vec3): Vec3 { + const forward = sub(at[piece.to], at[piece.from]); + if (piece.line) { + const d = piece.line.direction; + return dot(d, forward) < 0 ? [-d[0], -d[1], -d[2]] : d; + } + if (piece.circle) { + const { centre, u, v } = piece.circle; + const normal = cross(u, v); + let d = unit(cross(normal, sub(p, centre))); + // Turning the way the points do. + const mid = at[(piece.from + piece.to) >> 1]; + const turning = dot(cross(sub(mid, at[piece.from]), sub(at[piece.to], mid)), normal); + if (turning < 0) d = [-d[0], -d[1], -d[2]]; + return d; + } + return unit(forward); +} + +/** Where two pieces meet at a corner: the nearest approach of two lines, else the corner point. */ +function cornerPoint(a: Piece, b: Piece, corner: Vec3, radius: number): Vec3 { + if (!a.line || !b.line) return corner; + const { mean: p, direction: d } = a.line, + { mean: q, direction: e } = b.line; + const w = sub(p, q); + const bb = dot(d, e), + dd = dot(d, w), + ee = dot(e, w); + const denominator = 1 - bb * bb; + if (denominator < 1e-6) return corner; + const t = (bb * ee - dd) / denominator, + u = (ee - bb * dd) / denominator; + const meet = mix( + [p[0] + t * d[0], p[1] + t * d[1], p[2] + t * d[2]], + [q[0] + u * e[0], q[1] + u * e[1], q[2] + u * e[2]], + 0.5, + ); + return length(sub(meet, corner)) <= 2 * radius ? meet : corner; +} + +/** + * Where a line and an arc, or two arcs, touch: the foot of the arc's centre on the line, or the point + * of an arc on the line through both centres. Null when that is not within a brush radius of `near`. + */ +function tangentPoint(a: Piece, b: Piece, near: Vec3, radius: number): Vec3 | null { + let touch: Vec3 | null = null; + const line = a.line ?? b.line, + circle = a.circle ?? b.circle; + if (line && circle) { + const { mean, direction } = line; + const t = dot(sub(circle.centre, mean), direction); + touch = [0, 1, 2].map((k) => mean[k] + t * direction[k]) as Vec3; + } else if (a.circle && b.circle) { + const towards = unit(sub(b.circle.centre, a.circle.centre)); + if (!length(towards)) return null; + const { centre, radius: r } = a.circle; + const [p, q] = [r, -r].map((d) => [0, 1, 2].map((k) => centre[k] + d * towards[k]) as Vec3); + touch = length(sub(p, near)) <= length(sub(q, near)) ? p : q; + } + return touch && length(sub(touch, near)) <= radius ? touch : null; +} + +/** The segments of the fitted pieces, meeting at shared points, with their joints. */ +function assemble( + at: Vec3[], + pieces: Piece[], + sharp: boolean[], + closed: boolean, + radius: number, +): TracedPath { + const n = pieces.length; + // The shared point at each joint; joint k is between pieces k and k + 1 (on a closed path, n - 1 + // closes back to 0). + const meets: Vec3[] = []; + const joints: GuideJoint[] = []; + const jointCount = closed ? n : n - 1; + for (let k = 0; k < jointCount; k++) { + const a = pieces[k], + b = pieces[(k + 1) % n]; + const corner = at[a.to]; + if (sharp[k]) { + meets.push(cornerPoint(a, b, corner, radius)); + joints.push('sharp'); + continue; + } + const meet = + tangentPoint(a, b, corner, radius) ?? mix(onPiece(a, corner), onPiece(b, corner), 0.5); + meets.push(meet); + const turn = Math.acos( + Math.min(1, Math.max(-1, dot(directionAt(a, at, meet), directionAt(b, at, meet)))), + ); + joints.push(turn <= (smoothTurn * Math.PI) / 180 ? 'smooth' : 'sharp'); + } + const segments = pieces.map((piece, k): TracedSegment => { + const start = k > 0 ? meets[k - 1] : closed ? meets[n - 1] : onPiece(piece, at[piece.from]); + const end = k < jointCount ? meets[k] : onPiece(piece, at[piece.to]); + if (piece.kind === 'line') return { kind: 'line', points: [start, end] }; + const flat = at.slice(piece.from, piece.to + 1).flat(); + const local = stations(flat, false); + const span = local[local.length - 1]; + if (piece.kind === 'arc') + return { + kind: 'arc', + points: [ + start, + arcMiddle(piece.circle!, at.slice(piece.from, piece.to + 1), start, end), + end, + ], + }; + const count = Math.min(maximumSplinePoints, Math.ceil(span / (4 * radius)) + 3); + const smooth = smoothed(flat, local, radius / 2); + const inner = Array.from({ length: count - 2 }, (_, i) => + pointAt(smooth, local, ((i + 1) * span) / (count - 1), false), + ); + return { kind: 'spline', points: [start, ...inner, end] }; + }); + return { segments, joints, closed }; +} + +/** Each point of a polyline replaced by the mean of the points within `reach` of it along it. */ +function smoothed(flat: number[], s: Float64Array, reach: number) { + const count = flat.length / 3; + const out: number[] = []; + for (let i = 0; i < count; i++) { + const mean = [0, 0, 0]; + let n = 0; + for (let j = 0; j < count; j++) { + if (Math.abs(s[j] - s[i]) > reach) continue; + n++; + for (let a = 0; a < 3; a++) mean[a] += flat[j * 3 + a]; + } + out.push(...mean.map((m) => m / n)); + } + return out; +} diff --git a/src/core/store.ts b/src/core/store.ts index ad4b9d6..268594e 100644 --- a/src/core/store.ts +++ b/src/core/store.ts @@ -4426,14 +4426,21 @@ export const useEditor = create((set, get) => ({ preview?.computeBoundingSphere(); return; } - const input = refineCode!.brush.creaseInput(stroke.points, stroke.radius, stroke.strength); + const { model } = refine; + const input = refineCode!.brush.creaseInput( + model.mesh, + model.topology, + model.noise, + stroke.points, + stroke.radius, + stroke.strength, + ); if (!input) { get().notify(noEdgeNotice, 'info'); return; } // The brush is the guide's width. Where the rounding is wider, the solver's own width would // reach past the brush, so that guide waits, previewed, for the user to accept it. - const { model } = refine; const feature = (guide: EdgeInput): RefineFeature => ({ id: uid(), state: 'pending', diff --git a/src/docs/assembly-guides.ts b/src/docs/assembly-guides.ts index 1b50ebd..ebfba73 100644 --- a/src/docs/assembly-guides.ts +++ b/src/docs/assembly-guides.ts @@ -707,7 +707,8 @@ export const assemblyGuides: DocArticle[] = [ title: 'Use the brushes', paragraphs: [ 'In Brush mode, choose Crease, Flatten, or Smooth, set Brush radius and Strength, and drag across the surface. [ and ] shrink or grow the brush. Brushes and paint act only on the surface in front of you.', - 'Drag Crease along the rounding. Crease sharpens on release if it can fit the edge within the brush width. If the edge needs a wider fit, Refine leaves a selected pending guide and shows The edge is wider than the brush. Check the preview, then accept it. In Brush mode, choose Accept or press Enter to keep the change. Choose Dismiss or press Delete to remove the guide. Press Esc to deselect it and keep it pending. If the stroke finds no edge, the tool shows the no-edge notice and nothing changes.', + 'Drag Crease along an edge the scan rounded off, on the rounding or beside it on either face, with the rounding inside the brush. The stroke can be rough: Refine finds the rounded edge under it and fits the edge as lines and arcs where they fit, and as a spline where they do not. A straight edge becomes one line, and the end of a slot a line, an arc and a line. Where the edge turns sharply, as at the corner of a box, the guide has a sharp corner. A stroke that comes back round to where it started closes the guide.', + 'Crease sharpens on release if it can fit the edge within the brush width. If the edge needs a wider fit, Refine leaves a selected pending guide and shows The edge is wider than the brush. Check the preview, then accept it. In Brush mode, choose Accept or press Enter to keep the change. Choose Dismiss or press Delete to remove the guide. Press Esc to deselect it and keep it pending. If the stroke finds no edge, the tool shows the no-edge notice and nothing changes.', 'Flatten flattens the surface under the brush, and Smooth smooths it; edges the tool has rebuilt are held. A stroke that changes the surface is one step you can undo within the session. A stroke that finds nothing adds no step. A wide Crease stroke that leaves a pending guide adds one session undo step.', ], }, diff --git a/src/docs/changelog.ts b/src/docs/changelog.ts index 73517e3..8c5a2aa 100644 --- a/src/docs/changelog.ts +++ b/src/docs/changelog.ts @@ -19,6 +19,17 @@ export interface Release { // Newest first. Each title must be unique: it names the release's link. export const releases: Release[] = [ + { + date: '2026-11-24', + title: 'Crease finds the edge', + changes: [ + { + kind: 'improved', + text: 'The Refine Crease brush finds the rounded edge under a rough stroke, drawn on the rounding or beside it on either face. It fits the edge as lines and arcs, with sharp corners where the edge turns, and a stroke that comes back to its start closes the guide.', + guide: 'refine', + }, + ], + }, { date: '2026-11-24', title: 'Guides you can place exactly', diff --git a/tests/unit/refine-brush.test.ts b/tests/unit/refine-brush.test.ts index 97c4bf4..1ccd1df 100644 --- a/tests/unit/refine-brush.test.ts +++ b/tests/unit/refine-brush.test.ts @@ -1,7 +1,8 @@ import { describe, expect, it } from 'vitest'; import { applyEdge, solveEdge } from '../../src/core/refine-edge'; import { creaseInput, flattenDab, smoothDab } from '../../src/core/refine-brush'; -import { cloneRefineMesh, weldedCorner } from '../../src/core/refine-mesh'; +import type { GuidePoint } from '../../src/core/refine-band'; +import { type RefineMesh, cloneRefineMesh, weldedCorner } from '../../src/core/refine-mesh'; import { trianglesUnderBrush, verticesUnderBrush } from '../../src/core/refine-paint'; import type { Vec3 } from '../../src/core/types'; import { chainPieces, modelOf, pointOn } from '../helpers/refine'; @@ -17,9 +18,59 @@ import { rippleAmplitude, } from '../helpers/refine-brush'; import { heightAt } from '../helpers/refine-region'; -import { foldedStrip, rippledSphere, rivetedPlate, softBox, softStep } from '../helpers/soft-edges'; +import { + foldedStrip, + rippledSphere, + rivetedPlate, + slottedPlate, + softBox, + softStep, +} from '../helpers/soft-edges'; const exact = { step: 0.06, ripple: 0, noise: 0 }; + +const crease = ( + model: ReturnType, + stroke: GuidePoint[], + radius: number, + strength: number, +) => creaseInput(model.mesh, model.topology, model.noise, stroke, radius, strength); + +/** Largest distance of a curve's points with |x| <= `within` from softBox([2, 1.5, 1])'s top front edge. */ +function onBoxEdge(curve: ArrayLike, within: number) { + let worst = 0; + for (let k = 0; k < curve.length; k += 3) + if (Math.abs(curve[k]) <= within) + worst = Math.max(worst, Math.hypot(curve[k + 1] - 1.5, curve[k + 2] - 1)); + return worst; +} + +/** Distance from the sharp rim of slottedPlate(1, ...)'s slot, at height 1. */ +function offSlotRim(p: Vec3) { + const [x, , z] = p; + const across = Math.abs(x) <= 1.5 ? Math.abs(z) - 1 : Math.hypot(Math.abs(x) - 1.5, z) - 1; + return Math.hypot(across, p[1] - 1); +} + +/** + * A stroke on slottedPlate(1, ...)'s top, `out` mm from the slot's rim: from x = -1 along z < 0, round + * the end at x = 1.5 and back along z > 0, or, `closed`, on round the other end to where it began. + */ +function slotStroke(mesh: RefineMesh, out: number, closed: boolean) { + const r = 1 + out; + const points: Vec3[] = []; + for (let x = -1; x < 1.5; x += 0.1) points.push([x, 1, -r]); + for (let a = -Math.PI / 2; a < Math.PI / 2; a += 0.1 / r) + points.push([1.5 + r * Math.cos(a), 1, r * Math.sin(a)]); + for (let x = 1.5; x > (closed ? -1.5 : -1); x -= 0.1) points.push([x, 1, r]); + if (closed) { + for (let a = Math.PI / 2; a < (3 * Math.PI) / 2; a += 0.1 / r) + points.push([-1.5 + r * Math.cos(a), 1, r * Math.sin(a)]); + for (let x = -1.5; x <= -0.8; x += 0.1) points.push([x, 1, -r]); + } + return points.map((p) => pointOn(mesh, p)); +} + const brushes = [smoothDab, flattenDab]; describe('Refine brushes', () => { @@ -180,12 +231,11 @@ describe('Refine brushes', () => { expect(broken).toBe(0); }); - it('turns a freehand stroke into a guide that sharpens the edge', () => { + it('turns a freehand stroke along a straight edge into a line that sharpens it', () => { const model = modelOf(softBox([2, 1.5, 1], 0.3)); const stroke = jitteredCrest(model.mesh, -1.2, 1.2, 0.05); // points every 0.1 mm, 0.05 mm of hand jitter - const input = creaseInput(stroke, 0.6, 1)!; - expect(input.segments[0].kind).toBe('spline'); - expect(input.segments[0].points.length).toBeGreaterThanOrEqual(4); + const input = crease(model, stroke, 0.6, 1)!; + expect(input.segments.map((s) => s.kind)).toEqual(['line']); expect(input).toMatchObject({ joints: [], closed: false, width: 0.6, strength: 1 }); const solve = solveEdge(model.mesh, model.topology, input, model.noise)!; const out = cloneRefineMesh(model.mesh, true); @@ -199,39 +249,98 @@ describe('Refine brushes', () => { ); }); - it('gives a stroke ceil(length / (4 radius)) + 3 controls', () => { - const stroke = Array.from({ length: 24 }, (_, i) => ({ - triangle: 0, - position: [0.1 * i, 0.035 * (i % 2 ? 1 : -1), 0] as Vec3, - })); - let length = 0; - for (let i = 1; i < stroke.length; i++) - length += Math.hypot( - ...[0, 1, 2].map((a) => stroke[i].position[a] - stroke[i - 1].position[a]), + for (const [where, z, y] of [ + ['on the face beside the rounding', 0.5, 1.5], + ['on the wall below the rounding', 1, 1], + ] as const) + it(`finds the edge from a stroke ${where}`, () => { + const model = modelOf(softBox([2, 1.5, 1], 0.3)); + const stroke = Array.from({ length: 25 }, (_, i) => + pointOn(model.mesh, [-1.2 + 0.1 * i, y, z]), ); - const input = creaseInput(stroke, 0.6, 0.8)!; - expect(input.segments[0].points).toHaveLength(Math.ceil(length / 2.4) + 3); + const input = crease(model, stroke, 0.6, 1)!; + expect(input.segments.map((s) => s.kind)).toEqual(['line']); + // The guide lies on the rounding, where the solve reads the edge. + for (const { position: p } of input.segments[0].points) + expect(Math.abs(Math.hypot(p[1] - 1.2, p[2] - 0.7) - 0.3)).toBeLessThan(0.03); + const solve = solveEdge(model.mesh, model.topology, input, model.noise)!; + expect(solve).not.toBeNull(); + expect(onBoxEdge(solve.curve.points, 0.8)).toBeLessThan(0.005); + }); + + it('fits a stroke round the end of a slot as a line, an arc and a line', () => { + const model = modelOf(slottedPlate(1, 0.3)); + // On the plate 0.2 mm out from the rounding: down one side, round the end and back. + const stroke = slotStroke(model.mesh, 0.5, false); + const input = crease(model, stroke, 0.6, 1)!; + expect(input.segments.map((s) => s.kind)).toEqual(['line', 'arc', 'line']); + expect(input.joints).toEqual(['smooth', 'smooth']); + const solve = solveEdge(model.mesh, model.topology, input, model.noise)!; + expect(solve).not.toBeNull(); + const curve = solve.curve.points; + for (let k = 0; k < curve.length; k += 3) + if (curve[k] > -0.4) + expect(offSlotRim([curve[k], curve[k + 1], curve[k + 2]])).toBeLessThan(0.02); + }); + + it('closes a stroke that comes back round to its start', () => { + const model = modelOf(slottedPlate(1, 0.3)); + const input = crease(model, slotStroke(model.mesh, 0.5, true), 0.6, 1)!; + expect(input.closed).toBe(true); + expect(input.segments.map((s) => s.kind).sort()).toEqual(['arc', 'arc', 'line', 'line']); + expect(input.joints).toEqual(['smooth', 'smooth', 'smooth', 'smooth']); + expect(solveEdge(model.mesh, model.topology, input, model.noise)).not.toBeNull(); + }); + + it('splits a stroke round a corner into two lines meeting sharply', () => { + const model = modelOf(softBox([2, 1.5, 1], 0.3)); + // Along the top's front edge to the corner at x = 2, then back along its side edge. + const stroke = [ + ...Array.from({ length: 16 }, (_, i) => pointOn(model.mesh, [0.2 + 0.1 * i, 1.5, 0.5])), + ...Array.from({ length: 11 }, (_, i) => pointOn(model.mesh, [1.5, 1.5, 0.4 - 0.1 * i])), + ]; + const input = crease(model, stroke, 0.6, 1)!; + expect(input.segments.map((s) => s.kind)).toEqual(['line', 'line']); + expect(input.joints).toEqual(['sharp']); + const corner = input.segments[0].points[1].position; + expect(Math.hypot(corner[0] - 2, corner[1] - 1.5, corner[2] - 1)).toBeLessThan(0.3); + // The second arm runs on the edge, by the box's other corner. + const end = input.segments[1].points[1].position; + expect(Math.abs(Math.hypot(end[0] - 1.7, end[1] - 1.2) - 0.3)).toBeLessThan(0.03); + const solve = solveEdge(model.mesh, model.topology, input, model.noise)!; + expect(solve).not.toBeNull(); + // The first arm on the box's sharp edge, clear of the corner. Where three faces meet the solve + // itself is unsteady, whoever places the guide, so the second arm is not measured. + const curve = solve.curve.points; + for (let k = 0; k < curve.length; k += 3) + if (curve[k] < 1.4 && curve[k] > 0.6) + expect(Math.hypot(curve[k + 1] - 1.5, curve[k + 2] - 1)).toBeLessThan(0.005); }); it('turns a stroke retraced along a crest into one guide over it', () => { const model = modelOf(softBox([2, 1.5, 1], 0.3, exact)); const forward = jitteredCrest(model.mesh, -1.2, 1.2, 0); - const there = creaseInput(forward, 0.6, 1)!.segments[0].points; - const input = creaseInput([...forward, ...forward.slice(0, -1).reverse()], 0.6, 1)!; - const points = input.segments[0].points; - expect(points).toHaveLength(there.length); - points.forEach((p, i) => { - expect( - Math.hypot(...[0, 1, 2].map((a) => p.position[a] - there[i].position[a])), - ).toBeLessThan(1e-9); - if (i) expect(p.position[0]).toBeGreaterThan(points[i - 1].position[0]); - }); + const there = crease(model, forward, 0.6, 1)!.segments; + const input = crease(model, [...forward, ...forward.slice(0, -1).reverse()], 0.6, 1)!; + expect(input.segments).toEqual(there); expect(solveEdge(model.mesh, model.topology, input, model.noise)).not.toBeNull(); }); + it('keeps the stroke as the guide where it finds no edge', () => { + const model = modelOf(softBox([2, 1.5, 1], 0.3)); + const stroke = Array.from({ length: 13 }, (_, i) => + pointOn(model.mesh, [-0.6 + 0.1 * i, 1.5, 0]), + ); + const input = crease(model, stroke, 0.25, 1)!; + expect(input.segments.map((s) => s.kind)).toEqual(['line']); + for (const { position: p } of input.segments[0].points) + expect(Math.abs(p[2])).toBeLessThan(0.01); + expect(solveEdge(model.mesh, model.topology, input, model.noise)).toBeNull(); + }); + it('ignores a stroke shorter than the radius', () => { const model = modelOf(softBox([2, 1.5, 1], 0.3)); const shortStroke = jitteredCrest(model.mesh, 0, 0.4, 0.02); - expect(creaseInput(shortStroke, 0.6, 1)).toBeNull(); + expect(crease(model, shortStroke, 0.6, 1)).toBeNull(); }); }); diff --git a/tests/unit/refine-trace.test.ts b/tests/unit/refine-trace.test.ts new file mode 100644 index 0000000..ced4f74 --- /dev/null +++ b/tests/unit/refine-trace.test.ts @@ -0,0 +1,171 @@ +import { describe, expect, it } from 'vitest'; +import type { GuidePoint } from '../../src/core/refine-band'; +import { edgeUnderStroke, fitTrace, traceStroke } from '../../src/core/refine-trace'; +import type { Vec3 } from '../../src/core/types'; +import { modelOf, pointOn } from '../helpers/refine'; +import { slottedPlate, softBox } from '../helpers/soft-edges'; + +/** Seeded uniform numbers in [0, 1). */ +function random(seed: number) { + let s = seed; + return () => { + s = (s * 16807) % 2147483647; + return (s - 1) / 2147483646; + }; +} + +const fillet = 0.3; +/** The middle of the rounding of softBox([2, 1.5, 1], 0.3)'s top front edge, in (y, z). */ +const rounding = [1.5 - fillet + fillet * Math.SQRT1_2, 1 - fillet + fillet * Math.SQRT1_2]; + +function pathOn( + mesh: Parameters[0], + at: (x: number) => Vec3, + from = -1.2, + to = 1.2, + spacing = 0.2, +): GuidePoint[] { + const count = Math.round((to - from) / spacing); + return Array.from({ length: count + 1 }, (_, i) => pointOn(mesh, at(from + i * spacing))); +} + +describe('Refine trace: the edge beside a stroke', () => { + const model = modelOf(softBox([2, 1.5, 1], fillet)); + const { mesh, topology } = model; + const step = 0.06; + + for (const [where, at] of [ + ['on the top, 0.2 mm off the rounding', (x: number): Vec3 => [x, 1.5, 0.5]], + ['on the wall, 0.2 mm below the rounding', (x: number): Vec3 => [x, 1.0, 1]], + ['on the rounding', (x: number): Vec3 => [x, rounding[0], rounding[1]]], + ] as const) + it(`traces the sharp corner from a stroke ${where}`, () => { + const path = pathOn(mesh, at); + const traced = traceStroke(mesh, topology, path, 0.6, step); + expect(traced.length).toBeGreaterThanOrEqual(path.length - 2); + for (const { position: p, triangle } of traced) { + expect(Math.hypot(p[1] - 1.5, p[2] - 1)).toBeLessThan(0.05); + expect(triangle).toBeGreaterThanOrEqual(0); + } + }); + + it('finds the middle of the rounding in each slice', () => { + const path = pathOn(mesh, (x) => [x, 1.5, 0.5]); + const found = edgeUnderStroke(mesh, topology, path, 0.6, step).filter((s) => s !== null); + expect(found.length).toBeGreaterThanOrEqual(path.length - 1); + for (const { middle, side } of found) { + const p = middle.position; + expect(Math.hypot(p[1] - rounding[0], p[2] - rounding[1])).toBeLessThan(0.1); + expect(side).toBe(1); + } + }); + + it('finds no edge where the surface within reach is flat', () => { + const path = pathOn(mesh, (x) => [x, 1.5, 0]); + expect(edgeUnderStroke(mesh, topology, path, 0.25, step).every((s) => s === null)).toBe(true); + expect(traceStroke(mesh, topology, path, 0.25, step)).toEqual([]); + }); + + it('keeps to the edge on the side of the stroke most of it finds', () => { + // A plate 1 mm wide round a slot: a stroke along its middle has the slot's rounded rim on one + // side and the plate's sharp outer edge 0.5 mm away on the other. + const plate = modelOf(slottedPlate(1, fillet)); + const path = pathOn(plate.mesh, (x) => [x, 1, -1.45], -1, 1.2); + const traced = traceStroke(plate.mesh, plate.topology, path, 0.6, step); + expect(traced.length).toBeGreaterThanOrEqual(path.length - 2); + // The slot's rim, its sharp corner at z = -1 and height 1. + for (const { position: p } of traced) expect(Math.hypot(p[1] - 1, p[2] + 1)).toBeLessThan(0.05); + }); +}); + +describe('Refine trace: fitting the edge', () => { + const noisy = (points: Vec3[], noise: number, seed = 5) => { + const next = random(seed); + return points.map((p) => p.map((v) => v + (2 * next() - 1) * noise) as Vec3); + }; + const line = (from: Vec3, to: Vec3, spacing = 0.2) => { + const count = Math.round(Math.hypot(...from.map((v, a) => to[a] - v)) / spacing); + return Array.from( + { length: count + 1 }, + (_, i) => from.map((v, a) => v + ((to[a] - v) * i) / count) as Vec3, + ); + }; + const arc = (centre: Vec3, r: number, from: number, to: number, spacing = 0.2) => { + const count = Math.max(2, Math.round((Math.abs(to - from) * r) / spacing)); + return Array.from({ length: count + 1 }, (_, i) => { + const a = from + ((to - from) * i) / count; + return [centre[0] + r * Math.cos(a), 0, centre[2] + r * Math.sin(a)] as Vec3; + }); + }; + + it('fits a straight edge as one line', () => { + const traced = fitTrace(noisy(line([-3, 0, 0], [3, 0, 0]), 0.005), false, 0.01, 0.6)!; + expect(traced.segments.map((s) => s.kind)).toEqual(['line']); + const [a, b] = traced.segments[0].points; + expect(Math.abs(a[0] + 3)).toBeLessThan(0.02); + expect(Math.abs(b[0] - 3)).toBeLessThan(0.02); + expect(traced.closed).toBe(false); + }); + + it('fits a slot end as a line, an arc and a line joined smoothly', () => { + const points = [ + ...line([-2, 0, -1], [1.5, 0, -1]), + ...arc([1.5, 0, 0], 1, -Math.PI / 2, Math.PI / 2).slice(1), + ...line([1.5, 0, 1], [-2, 0, 1]).slice(1), + ]; + const traced = fitTrace(noisy(points, 0.004), false, 0.01, 0.6)!; + expect(traced.segments.map((s) => s.kind)).toEqual(['line', 'arc', 'line']); + expect(traced.joints).toEqual(['smooth', 'smooth']); + const [start, middle, end] = traced.segments[1].points; + expect(Math.hypot(start[0] - 1.5, start[2] + 1)).toBeLessThan(0.15); + expect(Math.hypot(middle[0] - 2.5, middle[2])).toBeLessThan(0.02); + expect(Math.hypot(end[0] - 1.5, end[2] - 1)).toBeLessThan(0.15); + }); + + it('splits an L at its corner into two lines meeting there sharply', () => { + // The corner rounded off over 0.3 mm, as a traced crest is. + const points = [ + ...line([-3, 0, 0], [-0.3, 0, 0]), + ...arc([-0.3, 0, 0.3], 0.3, -Math.PI / 2, 0, 0.1).slice(1), + ...line([0, 0, 0.3], [0, 0, 3]).slice(1), + ]; + const traced = fitTrace(noisy(points, 0.004), false, 0.01, 0.6)!; + expect(traced.segments.map((s) => s.kind)).toEqual(['line', 'line']); + expect(traced.joints).toEqual(['sharp']); + const meet = traced.segments[0].points[1]; + expect(Math.hypot(meet[0], meet[2])).toBeLessThan(0.02); + expect(traced.segments[1].points[0]).toEqual(meet); + }); + + it('fits a closed ring as one closed arc', () => { + const ring = arc([0, 0, 0], 2, 0, 2 * Math.PI).slice(1); + const traced = fitTrace(noisy(ring, 0.004), true, 0.01, 0.6)!; + expect(traced).toMatchObject({ closed: true, joints: ['smooth'] }); + expect(traced.segments.map((s) => s.kind)).toEqual(['arc']); + }); + + it('fits a closed slot as two lines and two arcs', () => { + const loop = [ + ...line([-1.5, 0, -1], [1.5, 0, -1]), + ...arc([1.5, 0, 0], 1, -Math.PI / 2, Math.PI / 2).slice(1), + ...line([1.5, 0, 1], [-1.5, 0, 1]).slice(1), + ...arc([-1.5, 0, 0], 1, Math.PI / 2, (3 * Math.PI) / 2).slice(1, -1), + ]; + // Starting part way along a line, as a stroke may. + const start = loop.slice(5).concat(loop.slice(0, 5)); + const traced = fitTrace(noisy(start, 0.004), true, 0.01, 0.6)!; + expect(traced.closed).toBe(true); + expect(traced.segments.map((s) => s.kind).sort()).toEqual(['arc', 'arc', 'line', 'line']); + expect(traced.joints).toEqual(['smooth', 'smooth', 'smooth', 'smooth']); + }); + + it('fits a wandering edge as one spline', () => { + const points = Array.from({ length: 81 }, (_, i) => { + const x = -4 + i * 0.1; + return [x, 0, 0.4 * Math.sin(1.1 * x) + 0.15 * Math.sin(2.3 * x)] as Vec3; + }); + const traced = fitTrace(points, false, 0.01, 0.6)!; + expect(traced.segments.map((s) => s.kind)).toEqual(['spline']); + expect(traced.segments[0].points.length).toBeGreaterThanOrEqual(4); + }); +});