Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 86 additions & 39 deletions src/core/refine-brush.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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`),
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down
203 changes: 11 additions & 192 deletions src/core/refine-detect.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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';

Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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) {
Expand Down
Loading
Loading