diff --git a/src/doc/types.ts b/src/doc/types.ts index 3bf0258..aac4387 100644 --- a/src/doc/types.ts +++ b/src/doc/types.ts @@ -145,6 +145,8 @@ export interface SketchConstraint { atExpr?: (string | null)[]; /** pattern: "turn" - the copy is the original turned `value` degrees round `at`; else moved by `at`. */ turn?: boolean; + /** dim: put on by Lock (a locked circle keeps its size) - Unlock takes it off with the lock. */ + held?: boolean; } export interface SketchFeature extends FeatureBase { diff --git a/src/sketch/constraints.ts b/src/sketch/constraints.ts index 90a6114..dd21285 100644 --- a/src/sketch/constraints.ts +++ b/src/sketch/constraints.ts @@ -4,7 +4,7 @@ // from wandering (so the result is the smallest change that satisfies them). import type { ConstraintType, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../doc/types"; -import { arcFrom3, entityCorners } from "./curves"; +import { arcFrom3, entityCorners, entityPolylines } from "./curves"; // ------------------------------------------------------------- parameters @@ -36,18 +36,28 @@ function params(e: SketchEntity): number[] { } } -/** Length per unit of each parameter (1 for coordinates, the radius for angles). */ -function pullScale(e: SketchEntity, p: number[]): number[] { +/** + * A shape with a size of its own (a rectangle, an ellipse, a polygon) keeps it sooner than its place: asked to bring + * a corner somewhere, it goes there - it is not squashed towards it. (Each counted the same, a rectangle whose corner + * was put on a point 60 away came out 0.00001 tall, and an ellipse flat.) + */ +const STIFF = 4; + +/** + * Length per unit of each parameter (1 for coordinates, the radius for angles). `stiff`: how much sooner a shape + * keeps its size and its way round than its place (1 while it is dragged: a corner pulled is the shape pulled about). + */ +function pullScale(e: SketchEntity, p: number[], stiff: number): number[] { const r = (v: number) => Math.max(Math.abs(v), 1e-9); switch (e.kind) { case "arc": - return p.length === 5 ? [1, 1, 1, r(p[2]), r(p[2])] : p.map(() => 1); + return p.length === 5 ? [1, 1, stiff, stiff * r(p[2]), stiff * r(p[2])] : p.map(() => 1); case "ellipse": - return [1, 1, 1, 1, r(Math.max(e.rx, e.ry))]; + return [1, 1, stiff, stiff, r(Math.max(e.rx, e.ry))]; case "rect": - return [1, 1, 1, 1, r(Math.hypot(e.w, e.h) / 2)]; + return [1, 1, stiff, stiff, r(Math.hypot(e.w, e.h) / 2)]; case "polygon": - return [1, 1, 1, r(e.radius)]; + return [1, 1, stiff, r(e.radius)]; default: return p.map(() => 1); } @@ -185,7 +195,7 @@ function residuals(c: SketchConstraint, get: Lookup): number[] { if (a && b) return [a[0] - b[0], a[1] - b[1]]; // Point on a curve. const e = E(0); - if (a && e) return [distToEntity(a, e)]; + if (a && e) return distToEntity(a, e); return []; } case "horizontal": @@ -223,8 +233,21 @@ function residuals(c: SketchConstraint, get: Lookup): number[] { if (line && round) return [distPointLine(round.c, line.a, line.b) - round.r]; if (r1 && r2) { const d = Math.hypot(r1.c[0] - r2.c[0], r1.c[1] - r2.c[1]); - // External tangency unless one contains the other. - return [Math.min(Math.abs(d - (r1.r + r2.r)), Math.abs(d - Math.abs(r1.r - r2.r)))]; + // Touching from outside, or one inside the other: whichever is nearer. (With its sign: the smaller of the two + // sizes has a kink right at the answer, and the last of the way there was crept.) + const out = d - (r1.r + r2.r); + const ins = d - Math.abs(r1.r - r2.r); + return [Math.abs(out) < Math.abs(ins) ? out : ins]; + } + // A line and an ellipse: the line is as far from the centre as the ellipse reaches that way. + const ell = e1.kind === "ellipse" ? e1 : e2.kind === "ellipse" ? e2 : null; + if (line && ell) { + const l = Math.hypot(line.b[0] - line.a[0], line.b[1] - line.a[1]) || 1; + const n: Vec2 = [(line.b[1] - line.a[1]) / l, -(line.b[0] - line.a[0]) / l]; + const cs = Math.cos(ell.rotation); + const sn = Math.sin(ell.rotation); + const reach = Math.hypot(ell.rx * (n[0] * cs + n[1] * sn), ell.ry * (-n[0] * sn + n[1] * cs)); + return [distPointLine(ell.center, line.a, line.b) - reach]; } return []; } @@ -322,11 +345,48 @@ function distPointLineSigned(p: Vec2, a: Vec2, b: Vec2): number { return ((p[0] - a[0]) * dy - (p[1] - a[1]) * dx) / l; } -function distToEntity(p: Vec2, e: SketchEntity): number { - if (e.kind === "line") return distPointLineSigned(p, e.a, e.b); +function distToEntity(p: Vec2, e: SketchEntity): number[] { + if (e.kind === "line") return [distPointLineSigned(p, e.a, e.b)]; const r = roundOf(e); - if (r) return Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r; - return 0; + if (r) return [Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r]; + if (e.kind === "ellipse") { + // In the ellipse's own frame, how far out the point is as a share of the way to it (1: on it). + const dx = p[0] - e.center[0]; + const dy = p[1] - e.center[1]; + const cs = Math.cos(e.rotation); + const sn = Math.sin(e.rotation); + const k = Math.hypot((dx * cs + dy * sn) / Math.max(e.rx, 1e-12), (-dx * sn + dy * cs) / Math.max(e.ry, 1e-12)); + return [(k - 1) * Math.min(e.rx, e.ry)]; + } + // A rectangle, a polygon, a polyline, a spline: from the nearest place on it (a spline: as it is drawn) to the + // point, across and up. Two numbers that change evenly as the point goes round a corner, so it gets there from + // anywhere and the last of the way is not crept. (It was 0 for all of these: a point "put on" a rectangle's edge + // was taken and stayed where it was.) + const runs: Vec2[][] = e.kind === "rect" || e.kind === "polygon" ? [closedRun(entityCorners(e))] : e.kind === "polyline" ? [e.closed ? closedRun(e.points) : e.points] : entityPolylines(e); + let best = Infinity; + let out = [0, 0]; + for (const run of runs) + for (let i = 0; i + 1 < run.length; i++) { + const a = run[i]; + const b = run[i + 1]; + const ux = b[0] - a[0]; + const uy = b[1] - a[1]; + const l2 = ux * ux + uy * uy; + if (l2 < 1e-24) continue; + const s = ((p[0] - a[0]) * ux + (p[1] - a[1]) * uy) / l2; + const c = Math.max(0, Math.min(1, s)); + const vx = p[0] - a[0] - c * ux; + const vy = p[1] - a[1] - c * uy; + const d = Math.hypot(vx, vy); + if (d >= best) continue; + best = d; + out = [vx, vy]; + } + return out; +} + +function closedRun(pts: Vec2[]): Vec2[] { + return pts.length ? [...pts, pts[0]] : pts; } // ------------------------------------------------------------------ solver @@ -430,9 +490,44 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So const p = params(e); offsets.push(x0.length); counts.push(p.length); - per.push(...pullScale(e, p)); + per.push(...pullScale(e, p, opts.drag?.length ? 1 : STIFF)); x0.push(...p); } + // A line asked to lie a way it is far from (Vertical on one nearly level; an angle 130 degrees off): turned there + // about its middle first, its length kept. Left to the steps alone it got there by shrinking - shorter is the + // shortest way to "upright" - and a line given a far angle ended a speck. + if (!opts.drag?.length) { + const at = new Map(movers.map((e, i) => [e.id, i])); + for (const c of live) { + const pair = (c.type === "parallel" || c.type === "perpendicular") && c.curves?.length === 2; + // (Parallel, Perpendicular: the second line is the one turned - the first if only that one may move.) + const which = pair ? (at.has(c.curves![1]) ? 1 : 0) : 0; + const i = (pair || c.curves?.length === 1) && !c.pts?.length ? at.get(c.curves![which]) : undefined; + const e = i === undefined ? undefined : movers[i]; + if (i === undefined || e?.kind !== "line") continue; + const now = Math.atan2(e.b[1] - e.a[1], e.b[0] - e.a[0]); + let want: number | null = null; + if (pair) { + const o = entities.find((x) => x.id === c.curves![1 - which]); + if (o?.kind !== "line") continue; + const base = Math.atan2(o.b[1] - o.a[1], o.b[0] - o.a[0]) + (c.type === "perpendicular" ? Math.PI / 2 : 0); + // (Either way along it will do: the nearer.) + want = Math.abs(wrap(base - now)) <= Math.PI / 2 ? base : base + Math.PI; + } + if (c.type === "dim" && c.prop === "angle" && c.value !== undefined) want = (c.value * Math.PI) / 180; + else if (c.type === "horizontal") want = Math.abs(wrap(now)) < Math.PI / 2 ? 0 : Math.PI; + else if (c.type === "vertical") want = wrap(now) > 0 ? Math.PI / 2 : -Math.PI / 2; + if (want === null || Math.abs(wrap(want - now)) < Math.PI / 6) continue; + const o = offsets[i]; + const mx = (e.a[0] + e.b[0]) / 2; + const my = (e.a[1] + e.b[1]) / 2; + const h = Math.hypot(e.b[0] - e.a[0], e.b[1] - e.a[1]) / 2; + x0[o] = mx - h * Math.cos(want); + x0[o + 1] = my - h * Math.sin(want); + x0[o + 2] = mx + h * Math.cos(want); + x0[o + 3] = my + h * Math.sin(want); + } + } const byId = new Map(entities.map((e) => [e.id, e])); const build = (x: number[]) => { const m = new Map(byId); @@ -509,7 +604,7 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So // (The pull pass only has to get near: once a step gains next to nothing // it stops - it used to run all 30 steps every frame, as the pull never // reaches zero; the exact pass stops once the constraints are met.) - xs = lm(xs, 1e-3, true, t, Math.min(30, it), 1e-6, false, 1e-7); + xs = lm(xs, 3e-4, true, t, Math.min(30, it), 1e-6, false, 1e-7); xs = lm(xs, 1e-8, false, t, it, 1e-10, true, 1e-9); } else { // A noticeable pull first (smallest change), then almost none (exact constraints). @@ -665,8 +760,15 @@ function solveGroup(entities: SketchEntity[], live: SketchConstraint[], opts: So for (let a = 0; a < n; a++) for (let b = a + 1; b < n; b++) A[b][a] = A[a][b]; let improved = false; let gain = 0; + // Damped the same in every direction (each parameter in its own length): the step is then the shortest one + // that does it. Damped by each parameter's own share (Marquardt's way), a sketch with room to spare - most + // are - stepped furthest in the direction that helped least: a line given a length drew its ends together + // sideways until it stood upright, and stopped there, the length not met. + let mean = 0; + for (let i = 0; i < n; i++) mean += A[i][i] / (per[i] * per[i]); + mean = mean / Math.max(1, n) || 1; for (let tries = 0; tries < 8; tries++) { - const diag = A.map((rowA, i) => rowA[i] * (1 + lambda) + 1e-12); + const diag = A.map((rowA, i) => rowA[i] + lambda * mean * per[i] * per[i] + 1e-12); let dx = solveSPD(A, diag, g); if (!dx) { const M = A.map((rowA, i) => rowA.map((v, j) => (i === j ? diag[i] : v))); @@ -954,7 +1056,9 @@ export function applicable(type: ConstraintType, pts: PointRef[], curves: Sketch case "equal": return curves.length === 2 && (lines.length === 2 || rounds.length === 2); case "tangent": - return curves.length === 2 && rounds.length >= 1; + // A circle or an arc with a line or another of them; a line with an ellipse. (It was offered for a circle with + // anything - a rectangle, a spline, an ellipse - and taken, and did nothing.) + return curves.length === 2 && (rounds.length === 2 || (rounds.length === 1 && lines.length === 1) || (lines.length === 1 && curves.some((e) => e.kind === "ellipse"))); case "concentric": return curves.length === 2 && curves.every((e) => e.kind !== "line" && e.kind !== "spline" && e.kind !== "polyline"); case "midpoint": diff --git a/src/tools/sketch.ts b/src/tools/sketch.ts index 324ce09..45dba44 100644 --- a/src/tools/sketch.ts +++ b/src/tools/sketch.ts @@ -272,6 +272,9 @@ interface DragRef { at: Vec2; } +/** A name as a title: "distance dimension" is "Distance dimension". */ +const titled = (s: string) => s.charAt(0).toUpperCase() + s.slice(1); + const refKey = (r: PointRef) => `${r.e}:${r.p}`; /** @@ -794,7 +797,7 @@ export class SketchTool implements Tool { continue; } const have = existingConstraints(b.type, this.constraints, this.selPts, curves); - const built = have.length ? [] : buildConstraints(b.type, this.selPts, curves); + const built = have.length ? [] : buildConstraints(b.type, this.selPts, curves, this.entities); if (!have.length && !built.length) continue; // H/V says which one it is (the line's nearer to one or the other). const t = b.type === "hv" ? (have[0] ?? built[0]).type : b.type; @@ -977,7 +980,7 @@ export class SketchTool implements Tool { return this.selectionChanged(); } const curves = this.pickedCurves(); - let cs = buildConstraints(type, this.selPts, curves); + let cs = buildConstraints(type, this.selPts, curves, this.entities); // Lock holds points where they are now. if (type === "fix") cs = cs.map((c) => (c.type === "fix" ? { ...c, at: pointOf(this.entities.find((e) => e.id === c.pts![0].e)!, c.pts![0].p) ?? [0, 0] } : c)); if (!cs.length) return this.app.ui.toast("That constraint doesn't fit the selection"); @@ -988,7 +991,8 @@ export class SketchTool implements Tool { const kept = type === "equal" ? this.constraints.filter((c) => !(c.type === "dim" && c.curves?.length === 1 && others.has(c.curves[0]) && ["length", "radius", "diameter"].includes(c.prop ?? ""))) : this.constraints; // It goes in: the existing constraints in its way (an angle, a parallel...) give way and are named. const res = addForUser(this.entities, kept, cs, first); - if (!res.ok) return this.app.ui.toast("Locked points stop that - unlock them first (select, then Unlock)", "error"); + // (Said as it is: locks in the way, or - with none - the shape itself.) + if (!res.ok) return this.app.ui.toast(this.constraints.some((c) => c.type === "fix") ? "Locked points stop that - unlock them first (select, then Unlock)" : "That can't be done with the shape as it is constrained - take a constraint off it first", "error"); this.commit(res.result.entities, res.constraints); if (this.app.store.problems.length) this.app.ui.toast(this.app.store.problems[0], "error"); else if (res.removed.length) this.app.ui.toast(`Replaced ${[...new Set(res.removed.map(constraintName))].join(", ")}`); @@ -1009,7 +1013,7 @@ export class SketchTool implements Tool { if (c.type === "dim" || c.type === "distance") { const kind = c.prop === "angle" ? "angle" : "length"; this.app.ui.showPanel({ - title: `${c.prop ?? "distance"} dimension`, + title: titled(`${c.prop ?? "distance"} dimension`), items: [ { type: "number", @@ -1026,7 +1030,7 @@ export class SketchTool implements Tool { }); this.app.ui.focusPanel(); } else { - this.app.ui.showPanel({ title: `${c.type} constraint`, items: [], actions: [del], onDone: () => this.deselectConstraint() }); + this.app.ui.showPanel({ title: titled(c.type === "fix" ? "lock" : c.type === "symmetric" ? "symmetry" : `${c.type} constraint`), items: [], actions: [del], onDone: () => this.deselectConstraint() }); } } diff --git a/src/tools/sketchConstraints.ts b/src/tools/sketchConstraints.ts index 5df44c8..1b22915 100644 --- a/src/tools/sketchConstraints.ts +++ b/src/tools/sketchConstraints.ts @@ -40,13 +40,22 @@ const GLYPH: Partial> = { }; /** Constraints for a button press, from the current selection (empty if it doesn't fit). */ -export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[]): SketchConstraint[] { +export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], curves: SketchEntity[], all?: SketchEntity[]): SketchConstraint[] { if (type === "hv") { if (curves.length === 1 && curves[0].kind === "line" && !pts.length) { const l = curves[0]; const horiz = Math.abs(l.b[0] - l.a[0]) >= Math.abs(l.b[1] - l.a[1]); return [{ id: uid(), type: horiz ? "horizontal" : "vertical", curves: [l.id] }]; } + // Two points (a circle's centre and a corner, two ends): level with each other, or one above the other - + // whichever they are nearer to. (The solver had it; no button gave it.) + if (pts.length === 2 && !curves.length && all) { + const [a, b] = pts.map((r) => { + const e = all.find((x) => x.id === r.e); + return e ? pointOf(e, r.p) : null; + }); + if (a && b && Math.hypot(a[0] - b[0], a[1] - b[1]) > 1e-9) return [{ id: uid(), type: Math.abs(b[0] - a[0]) >= Math.abs(b[1] - a[1]) ? "horizontal" : "vertical", pts }]; + } return []; } if (!applicable(type, pts, curves)) return []; @@ -64,7 +73,7 @@ export function buildConstraints(type: ConstraintType | "hv", pts: PointRef[], c case "fix": { // Locking a curve holds all of its points (and a circle's size). const all = [...pts, ...curves.flatMap((e) => pointsOf(e).map((q) => ({ e: e.id, p: q.p })))]; - const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius }] : [])); + const sizes = curves.flatMap((e): SketchConstraint[] => (e.kind === "circle" ? [{ id: uid(), type: "dim", curves: [e.id], prop: "diameter", value: 2 * e.radius, held: true }] : [])); return [...all.map((p) => ({ id: uid(), type, pts: [p] })), ...sizes]; } default: @@ -103,6 +112,8 @@ export function existingConstraints(type: ConstraintType | "hv", constraints: Sk // A point counts as selected when it is, or when its curve is. const ptIn = (p: PointRef) => ptKeys.has(`${p.e}:${p.p}`) || ids.has(p.e); return constraints.filter((c) => { + // (The size Lock put on a circle goes with its lock; it was left behind, and the circle unlocked kept its size.) + if (type === "fix" && c.type === "dim" && c.held && c.curves?.length === 1 && ids.has(c.curves[0])) return true; if (!types.includes(c.type)) return false; const cv = c.curves ?? []; const cp = c.pts ?? []; diff --git a/tests/constraintmatrix.test.ts b/tests/constraintmatrix.test.ts new file mode 100644 index 0000000..e065ed2 --- /dev/null +++ b/tests/constraintmatrix.test.ts @@ -0,0 +1,226 @@ +// Run: npx tsx tests/constraintmatrix.test.ts +// Every constraint on every kind of curve it is offered for: once it is taken, it has to be TRUE - measured here +// from the curves themselves, not by the solver's own residuals (a constraint whose residual is always 0 "solves" +// and does nothing). And one constraint on free curves can always be met: none may be refused. +import type { ConstraintType, PointRef, SketchConstraint, SketchEntity, Vec2 } from "../src/doc/types"; +import { addForUser, applicable, pointOf, pointsOf, sizeOf, solve } from "../src/sketch/constraints"; +import { arcFrom3, entityPolylines } from "../src/sketch/curves"; + +let seed = 7; +const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296); +const R = (lo: number, hi: number) => lo + (hi - lo) * rnd(); +const P = (): Vec2 => [R(-40, 40), R(-40, 40)]; + +const KINDS = ["line", "arc", "circle", "ellipse", "ellarc", "rect", "polygon", "spline", "polyline"] as const; +type Kind = (typeof KINDS)[number]; + +function make(kind: Kind, id: string): SketchEntity { + const c = P(); + switch (kind) { + case "line": { + const a = R(0, 6.28); + const l = R(8, 30); + return { id, kind: "line", a: c, b: [c[0] + l * Math.cos(a), c[1] + l * Math.sin(a)] }; + } + case "arc": { + const r = R(5, 20); + const a0 = R(0, 6.28); + const sw = R(0.6, 4) * (rnd() < 0.5 ? -1 : 1); + const at = (t: number): Vec2 => [c[0] + r * Math.cos(t), c[1] + r * Math.sin(t)]; + return { id, kind: "arc", a: at(a0), m: at(a0 + sw / 2), b: at(a0 + sw) }; + } + case "circle": + return { id, kind: "circle", center: c, radius: R(4, 18) }; + case "ellipse": + return { id, kind: "ellipse", center: c, rx: R(8, 20), ry: R(3, 7), rotation: R(0, 3.14) }; + case "ellarc": + return { id, kind: "ellipse", center: c, rx: R(8, 20), ry: R(3, 7), rotation: R(0, 3.14), a0: R(0, 6.28), sweep: R(1, 4) }; + case "rect": + return { id, kind: "rect", center: c, w: R(6, 30), h: R(6, 30), rotation: R(0, 3.14) }; + case "polygon": + return { id, kind: "polygon", center: c, radius: R(6, 18), sides: 3 + Math.floor(rnd() * 5), angle: R(0, 6.28) }; + case "spline": + return { id, kind: "spline", points: [c, [c[0] + 10, c[1] + R(-8, 8)], [c[0] + 20, c[1] + R(-8, 8)], [c[0] + 30, c[1] + R(-8, 8)]], closed: false, mode: "fit" }; + case "polyline": + return { id, kind: "polyline", points: [c, [c[0] + 10, c[1] + R(-8, 8)], [c[0] + 20, c[1] + R(-8, 8)]], closed: false }; + } +} + +// ---- measured from the curves themselves +const dPL = (p: Vec2, a: Vec2, b: Vec2) => Math.abs((p[0] - a[0]) * (b[1] - a[1]) - (p[1] - a[1]) * (b[0] - a[0])) / Math.hypot(b[0] - a[0], b[1] - a[1]); +const dPS = (p: Vec2, a: Vec2, b: Vec2) => { + const dx = b[0] - a[0]; + const dy = b[1] - a[1]; + const t = Math.max(0, Math.min(1, ((p[0] - a[0]) * dx + (p[1] - a[1]) * dy) / (dx * dx + dy * dy || 1))); + return Math.hypot(p[0] - a[0] - t * dx, p[1] - a[1] - t * dy); +}; +const round = (e: SketchEntity) => (e.kind === "circle" ? { c: e.center, r: e.radius } : e.kind === "arc" ? (() => { const a = arcFrom3(e.a, e.m, e.b)!; return { c: a.c, r: a.r }; })() : null); +/** A whole ellipse's points (its own formula), finely. */ +const ellPts = (e: Extract, n = 20000): Vec2[] => + Array.from({ length: n }, (_, i) => { + const t = (i / n) * 2 * Math.PI; + const x = e.rx * Math.cos(t); + const y = e.ry * Math.sin(t); + return [e.center[0] + x * Math.cos(e.rotation) - y * Math.sin(e.rotation), e.center[1] + x * Math.sin(e.rotation) + y * Math.cos(e.rotation)] as Vec2; + }); +/** How far a point is from the curve as it is drawn (a line, a circle and an ellipse: the whole of it, as CAD does). */ +function distTo(p: Vec2, e: SketchEntity): number { + if (e.kind === "line") return dPL(p, e.a, e.b); + const r = round(e); + if (r) return Math.abs(Math.hypot(p[0] - r.c[0], p[1] - r.c[1]) - r.r); + if (e.kind === "ellipse") { + const q = ellPts(e, 4000); + return Math.min(...q.map((a, i) => dPS(p, a, q[(i + 1) % q.length]))); + } + let best = Infinity; + for (const poly of entityPolylines(e)) for (let i = 0; i + 1 < poly.length; i++) best = Math.min(best, dPS(p, poly[i], poly[i + 1])); + return best; +} +const dir = (e: SketchEntity) => (e.kind === "line" ? ([e.b[0] - e.a[0], e.b[1] - e.a[1]] as Vec2) : null); +const centre = (e: SketchEntity): Vec2 | null => ("center" in e ? e.center : (round(e)?.c ?? null)); + +const TOL = 1e-5; +/** Is the constraint true of these curves? (null: nothing here knows how to measure it - a finding by itself.) */ +function holds(c: SketchConstraint, es: SketchEntity[]): boolean | null { + const get = (id: string) => es.find((e) => e.id === id)!; + const pt = (r: PointRef) => pointOf(get(r.e), r.p)!; + const cv = (c.curves ?? []).map(get); + const pts = (c.pts ?? []).map(pt); + switch (c.type) { + case "coincident": + if (pts.length === 2) return Math.hypot(pts[0][0] - pts[1][0], pts[0][1] - pts[1][1]) < TOL; + return distTo(pts[0], cv[0]) < (cv[0].kind === "ellipse" ? 1e-4 : TOL); + case "horizontal": + case "vertical": { + const k = c.type === "horizontal" ? 1 : 0; + if (cv.length) return Math.abs(dir(cv[0])![k]) < TOL; + return Math.abs(pts[0][k] - pts[1][k]) < TOL; + } + case "parallel": + case "perpendicular": { + const [u, v] = cv.map((e) => dir(e)!); + const lu = Math.hypot(...u); + const lv = Math.hypot(...v); + return Math.abs(c.type === "parallel" ? (u[0] * v[1] - u[1] * v[0]) / lu / lv : (u[0] * v[0] + u[1] * v[1]) / lu / lv) < TOL; + } + case "equal": { + const s = (e: SketchEntity) => (e.kind === "line" ? sizeOf(e, "length")! : round(e)!.r); + return Math.abs(s(cv[0]) - s(cv[1])) < TOL; + } + case "tangent": { + const line = cv.find((e) => e.kind === "line"); + const rs = cv.map(round).filter((x) => !!x) as { c: Vec2; r: number }[]; + const ell = cv.find((e) => e.kind === "ellipse") as Extract | undefined; + if (line && rs.length === 1) return Math.abs(dPL(rs[0].c, (line as any).a, (line as any).b) - rs[0].r) < TOL; + if (rs.length === 2) { + const d = Math.hypot(rs[0].c[0] - rs[1].c[0], rs[0].c[1] - rs[1].c[1]); + return Math.min(Math.abs(d - rs[0].r - rs[1].r), Math.abs(d - Math.abs(rs[0].r - rs[1].r))) < TOL; + } + if (line && ell) { + // The line touches the ellipse: the nearest it comes is 0, and it does not cross (all of it on one side). + const l = line as Extract; + const sd = ellPts(ell, 4000).map((q) => ((q[0] - l.a[0]) * (l.b[1] - l.a[1]) - (q[1] - l.a[1]) * (l.b[0] - l.a[0])) / Math.hypot(l.b[0] - l.a[0], l.b[1] - l.a[1])); + const lo = Math.min(...sd); + const hi = Math.max(...sd); + return Math.min(Math.abs(lo), Math.abs(hi)) < 1e-3 && lo * hi > -1e-3; + } + return null; + } + case "concentric": { + const [a, b] = cv.map(centre); + return !!a && !!b && Math.hypot(a[0] - b[0], a[1] - b[1]) < TOL; + } + case "midpoint": { + const l = cv[0] as Extract; + return Math.hypot(pts[0][0] - (l.a[0] + l.b[0]) / 2, pts[0][1] - (l.a[1] + l.b[1]) / 2) < TOL; + } + case "symmetric": { + const l = cv[0] as Extract; + const d = dir(l)!; + const n = Math.hypot(...d); + const m: Vec2 = [(pts[0][0] + pts[1][0]) / 2, (pts[0][1] + pts[1][1]) / 2]; + return dPL(m, l.a, l.b) < TOL && Math.abs(((pts[1][0] - pts[0][0]) * d[0] + (pts[1][1] - pts[0][1]) * d[1]) / n) < TOL; + } + case "distance": + if (pts.length === 2) return Math.abs(Math.hypot(pts[0][0] - pts[1][0], pts[0][1] - pts[1][1]) - c.value!) < TOL; + return Math.abs(dPL(pts[0], (cv[0] as any).a, (cv[0] as any).b) - c.value!) < TOL; + case "fix": + return Math.hypot(pts[0][0] - c.at![0], pts[0][1] - c.at![1]) < TOL; + case "dim": { + const s = sizeOf(cv[0], c.prop!); + return s !== null && Math.abs(s - c.value!) < TOL; + } + } + return null; +} + +const findings = new Map(); +const detail = new Map(); +let cur = ""; +const note = (s: string) => { + findings.set(s, (findings.get(s) ?? 0) + 1); + if (!detail.has(s)) detail.set(s, cur); +}; +let tried = 0; +let good = 0; +let slowest = 0; + +function run(label: string, es: SketchEntity[], c: SketchConstraint): void { + tried++; + const t0 = performance.now(); + const r = addForUser(es, [], [c], c.curves?.[0] ?? c.pts?.[0]?.e); + slowest = Math.max(slowest, performance.now() - t0); + cur = JSON.stringify({ es, c, err: r.result.error, out: r.result.entities }); + if (r.result.entities.some((e) => pointsOf(e).some((q) => !Number.isFinite(q.at[0]) || !Number.isFinite(q.at[1])))) return note(`${label}: not a number`); + if (!r.ok) return note(`${label}: refused`); + const h = holds(c, r.result.entities); + if (h === null) return note(`${label}: offered, and nothing can say whether it is true`); + if (!h) return note(`${label}: taken, and not true`); + // And it stays true when solved again from there (nothing drifts). + const again = solve(r.result.entities, [c]); + if (!again.ok || !holds(c, again.entities)) return note(`${label}: lost when solved again`); + good++; +} + +const N = 25; +const id = () => `c${tried}`; +const pick = (e: SketchEntity): PointRef => { + const ps = pointsOf(e); + return { e: e.id, p: ps[Math.floor(rnd() * ps.length)].p }; +}; + +for (const k1 of KINDS) + for (const k2 of KINDS) + for (let n = 0; n < N; n++) { + const a = make(k1, "A"); + const b = make(k2, "B"); + const es = [a, b]; + // two curves + for (const type of ["parallel", "perpendicular", "equal", "tangent", "concentric"] as ConstraintType[]) if (applicable(type, [], es)) run(`${type} ${k1}+${k2}`, es, { id: id(), type, curves: ["A", "B"] }); + // a point of one, and the other curve + const pa = pick(a); + for (const type of ["coincident", "midpoint"] as ConstraintType[]) if (applicable(type, [pa], [b])) run(`${type} point of ${k1} on ${k2}`, es, { id: id(), type, pts: [pa], curves: ["B"] }); + if (applicable("distance", [pa], [b])) run(`distance point of ${k1} to ${k2}`, es, { id: id(), type: "distance", pts: [pa], curves: ["B"], value: R(2, 25) }); + // two points + const pb = pick(b); + if (applicable("coincident", [pa, pb], [])) run(`coincident ${k1}.${pa.p}+${k2}.${pb.p}`, es, { id: id(), type: "coincident", pts: [pa, pb] }); + for (const type of ["horizontal", "vertical"] as ConstraintType[]) if (applicable(type, [pa, pb], [])) run(`${type} points ${k1}+${k2}`, es, { id: id(), type, pts: [pa, pb] }); + if (applicable("distance", [pa, pb], [])) run(`distance points ${k1}+${k2}`, es, { id: id(), type: "distance", pts: [pa, pb], value: R(2, 40) }); + // two points about a line + const l = make("line", "L"); + if (applicable("symmetric", [pa, pb], [l])) run(`symmetric ${k1}+${k2}`, [a, b, l], { id: id(), type: "symmetric", pts: [pa, pb], curves: ["L"] }); + } + +for (const k of KINDS) + for (let n = 0; n < N; n++) { + const a = make(k, "A"); + for (const type of ["horizontal", "vertical"] as ConstraintType[]) if (applicable(type, [], [a])) run(`${type} ${k}`, [a], { id: id(), type, curves: ["A"] }); + for (const q of pointsOf(a)) run(`lock ${k}.${q.p.replace(/\d+/, "")}`, [a], { id: id(), type: "fix", pts: [{ e: "A", p: q.p }], at: P() }); + for (const prop of ["length", "radius", "diameter", "w", "h", "rx", "ry", "dx", "dy", "angle"]) if (sizeOf(a, prop) !== null) run(`size ${prop} of ${k}`, [a], { id: id(), type: "dim", curves: ["A"], prop, value: prop === "angle" ? R(-170, 170) : R(3, 35) }); + } + +const list = [...findings].sort((x, y) => x[0].localeCompare(y[0])); +for (const [s, n] of list) console.log(` ${String(n).padStart(4)} x ${s}`); +console.log(`${good} of ${tried} true once taken; slowest ${slowest.toFixed(1)} ms; ${list.length} kinds of finding`); +if (process.env.SHOW) for (const [s, d] of detail) if (s.includes(process.env.SHOW)) console.log(s + " >> " + d); +if (list.length) process.exit(1);