diff --git a/src/doc/freeformConnect.ts b/src/doc/freeformConnect.ts index 5d5d4ae..e72df29 100644 --- a/src/doc/freeformConnect.ts +++ b/src/doc/freeformConnect.ts @@ -19,7 +19,7 @@ const dist = (a: Vec3, b: Vec3) => Math.hypot(a[0] - b[0], a[1] - b[1], a[2] - b function worldCage(doc: ProjectDoc, body: string): { feature: FreeformFeature; cage: Cage; m: number[] } | null { const ff = freeformBodies(doc.features).get(body); if (!ff || ff.feature.id !== body) return null; - return { feature: ff.feature, m: ff.m, cage: { faces: ff.feature.cage.faces, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } }; + return { feature: ff.feature, m: ff.m, cage: { ...ff.feature.cage, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) } }; } /** The open-border cage edges under the picked body edges (null if one isn't on a border). */ @@ -111,6 +111,6 @@ export function connectEdges(doc: ProjectDoc, picks: PickedEdge[]): ConnectResul */ function store(doc: ProjectDoc, f: FreeformFeature, cage: Cage, m: number[], extra: Partial = {}): ProjectDoc { const inv = invertAffine(m); - const updated: FreeformFeature = { ...f, ...extra, cage: { faces: cage.faces, verts: cage.verts.map((v) => applyAffine(inv, v)) } }; + const updated: FreeformFeature = { ...f, ...extra, cage: { ...cage, verts: cage.verts.map((v) => applyAffine(inv, v)) } }; return { ...doc, features: doc.features.filter((x) => !(x.type === "freeformEdit" && x.target === f.id)).map((x): Feature => (x.id === f.id ? updated : x)) }; } diff --git a/src/doc/freeformCopies.ts b/src/doc/freeformCopies.ts index af7cc2b..a3fdd7c 100644 --- a/src/doc/freeformCopies.ts +++ b/src/doc/freeformCopies.ts @@ -135,6 +135,7 @@ export function detachFreeformCopy(doc: ProjectDoc, bodyId: string, newId: strin verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)), // A mirror turns the shape inside out: wind the quads the other way. faces: ff.feature.cage.faces.map((q) => (flip ? ([q[0], q[3], q[2], q[1]] as typeof q) : ([...q] as typeof q))), + ...(ff.feature.cage.creases ? { creases: structuredClone(ff.feature.cage.creases) } : {}), }, }; const features = [...doc.features]; diff --git a/src/doc/types.ts b/src/doc/types.ts index 23dddd6..3d69eaf 100644 --- a/src/doc/types.ts +++ b/src/doc/types.ts @@ -449,7 +449,7 @@ export interface MoveFaceFeature extends FeatureBase { */ export interface FreeformFeature extends FeatureBase { type: "freeform"; - cage: { verts: Vec3[]; faces: [number, number, number, number][] }; + cage: { verts: Vec3[]; faces: [number, number, number, number][]; creases?: [number, number][] }; /** Made as an open surface on purpose (a sheet): no "not closed" warning. */ surface?: boolean; /** An open freeform becomes a solid this thick (0 / missing: stays a surface). */ diff --git a/src/freeform/cage.ts b/src/freeform/cage.ts index 0c9b04b..7c0321a 100644 --- a/src/freeform/cage.ts +++ b/src/freeform/cage.ts @@ -11,6 +11,14 @@ export interface Cage { verts: Vec3[]; /** Quads, as vertex indices in order around the face. */ faces: [number, number, number, number][]; + /** + * Sharp edges: cage edges the surface keeps a crease along instead of + * rounding over - it follows them as an open border is followed (a smooth + * curve through the edge's points), and where three or more meet, or one + * ends at a corner of the border, the point is a corner. One on its own, + * ending in the middle of the surface, fades out there. + */ + creases?: [number, number][]; } export type CagePrimitive = "box" | "plane" | "cylinder" | "sphere" | "torus"; @@ -181,6 +189,8 @@ export interface Subdivided { grids: number[][][]; /** Size of each grid side in cells (2^levels). */ n: number; + /** The sharp edges at this level (as "a,b" with a < b), where the cage has some. */ + creased?: Set; } const add3 = (a: Vec3, b: Vec3): Vec3 => [a[0] + b[0], a[1] + b[1], a[2] + b[2]]; @@ -192,6 +202,8 @@ const mul3 = (a: Vec3, k: number): Vec3 => [a[0] * k, a[1] * k, a[2] * k]; * corner (a sheet laid over a face: the face's own corners). */ export function subdivide(cage: Cage, levels = 3, sharp?: Set): Subdivided { + // Sharp edges, as they are at each level (each is two at the next). + let creased = new Set((cage.creases ?? []).map(([a, b]) => (a < b ? `${a},${b}` : `${b},${a}`))); let points = cage.verts.map((p) => [...p] as Vec3); let grids = cage.faces.map((f) => [ [f[0], f[3]], @@ -222,7 +234,7 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set): Subdivid for (const [key, fs] of edgeFaces) { const [a, b] = key.split(",").map(Number); const mid = mul3(add3(points[a], points[b]), 0.5); - edgePos.set(key, fs.length === 2 ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid); + edgePos.set(key, fs.length === 2 && !creased.has(key) ? mul3(add3(add3(points[a], points[b]), add3(facePt[fs[0]], facePt[fs[1]])), 0.25) : mid); } // Vertex points. const vFaces = new Map(); @@ -233,11 +245,15 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set): Subdivid const es = vEdges.get(v); const fs = vFaces.get(v); if (!es || !fs) return p; - const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1); + const border = es.filter((k) => edgeFaces.get(k)!.length === 1); + const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : []; + // (A sharp edge is followed as the border is. Three or more at a point, sharp or border: a corner.) + if (crease.length && border.length + crease.length > 2) return p; + const boundary = crease.length ? [...border, ...crease] : border; if (boundary.length >= 2) { // Boundary: a cubic B-spline along the border; a corner (two faces meet at an angle) stays put. // (Told which points are corners: only those - a sheet's own corner on a round edge isn't one.) - if (sharp ? sharp.has(v) : fs.length === 1) return p; + if (!crease.length && (sharp ? sharp.has(v) : fs.length === 1)) return p; const others = boundary.slice(0, 2).map((k) => { const [a, b] = k.split(",").map(Number); return points[a === v ? b : a]; @@ -266,10 +282,20 @@ export function subdivide(cage: Cage, levels = 3, sharp?: Set): Subdivid for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) ng[2 * i + 1][2 * j + 1] = faceIdx[qi++]; return ng; }); + if (creased.size) { + const halves = new Set(); + for (const key of creased) { + const m = edgeIdx.get(key); + if (m === undefined) continue; + const [a, b] = key.split(",").map(Number); + halves.add(ekey(a, m)).add(ekey(m, b)); + } + creased = halves; + } points = next; n = N; } - return { points, grids, n }; + return { points, grids, n, ...(creased.size ? { creased } : {}) }; } /** @@ -303,9 +329,25 @@ export function limitPoints(s: Subdivided, sharp?: Set): Vec3[] { if (edgeCount.get(ekey(v, a)) === 1) border[v].push(a); if (edgeCount.get(ekey(v, b)) === 1) border[v].push(b); } + // Sharp edges: followed as the border is. + const sharpAt = P.map(() => [] as number[]); + for (const key of s.creased ?? []) { + const [a, b] = key.split(",").map(Number); + if (edgeCount.get(key) !== 2) continue; + sharpAt[a].push(b); + sharpAt[b].push(a); + } return P.map((p, v) => { if (!faces[v]) return p; - const bd = [...new Set(border[v])]; + const open = [...new Set(border[v])]; + const cr = sharpAt[v]; + if (cr.length) { + // Two (sharp or border) through the point: on that curve. More: a corner. One, in the middle: it fades out (smooth). + const through = [...new Set([...open, ...cr])]; + if (through.length > 2) return p; + if (through.length === 2) return [0, 1, 2].map((k) => (P[through[0]][k] + 4 * p[k] + P[through[1]][k]) / 6) as Vec3; + } + const bd = open; if (bd.length) { // On an open border: a corner (one face) stays; otherwise the border curve's point. if ((sharp ? sharp.has(v) : faces[v] === 1) || bd.length !== 2) return p; @@ -434,7 +476,7 @@ function compose(a: Rows, b: Rows): Rows { /** The layout key of a cage: its faces (positions don't matter). */ export function layoutKey(cage: Cage): string { - return `${cage.verts.length}|${cage.faces.join(";")}`; + return `${cage.verts.length}|${cage.faces.join(";")}${cage.creases?.length ? `|${cage.creases.join(";")}` : ""}`; } /** @@ -452,11 +494,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan { [f[1], f[2]], ]); let n = 1; + // Sharp edges (see subdivide), as pairs: the numbering of a level's edges changes with it. + let sharpPairs: [number, number][] = (cage.creases ?? []).map(([a, b]) => [a, b]); const addTo = (m: Map, i: number, w: number) => m.set(i, (m.get(i) ?? 0) + w); for (let lvl = 0; lvl < levels; lvl++) { const quads: number[][] = []; for (const g of grids) for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) quads.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]); const ekey = (a: number, b: number) => (a < b ? a * count + b : b * count + a); + const creased = new Set(sharpPairs.map(([a, b]) => ekey(a, b))); // Edges in first-seen order (subdivide numbers its edge points that way). const edgeFaces = new Map(); quads.forEach((q, qi) => { @@ -486,9 +531,12 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan { if (!es.length || !fs.length) { m.set(v, 1); } else { - const boundary = es.filter((k) => edgeFaces.get(k)!.length === 1); - if (boundary.length >= 2) { - if (fs.length === 1) m.set(v, 1); + const border = es.filter((k) => edgeFaces.get(k)!.length === 1); + const crease = creased.size ? es.filter((k) => creased.has(k) && edgeFaces.get(k)!.length === 2) : []; + const boundary = crease.length ? [...border, ...crease] : border; + if (crease.length && boundary.length > 2) m.set(v, 1); + else if (boundary.length >= 2) { + if (!crease.length && fs.length === 1) m.set(v, 1); else { addTo(m, v, 0.75); for (const k of boundary.slice(0, 2)) { @@ -514,7 +562,7 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan { for (const [key, fs] of edgeFaces) { const [a, b] = ends(key); const m = new Map(); - if (fs.length === 2) { + if (fs.length === 2 && !creased.has(key)) { addTo(m, a, 0.25); addTo(m, b, 0.25); for (const f of fs) for (const q of quads[f]) addTo(m, q, 0.0625); @@ -535,6 +583,14 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan { const edgeIdx = new Map(); let e = count; for (const key of edgeFaces.keys()) edgeIdx.set(key, e++); + if (sharpPairs.length) { + const halves: [number, number][] = []; + for (const [a, b] of sharpPairs) { + const mid = edgeIdx.get(ekey(a, b)); + if (mid !== undefined) halves.push([a, mid], [mid, b]); + } + sharpPairs = halves; + } let qi = 0; const N = 2 * n; const faceBase = e; @@ -570,12 +626,24 @@ export function subdivisionPlan(cage: Cage, levels = 3): SubdivPlan { if (edgeCount.get(ek(v, a)) === 1) border[v].push(a); if (edgeCount.get(ek(v, b)) === 1) border[v].push(b); } + const sharpAt: number[][] = Array.from({ length: count }, () => []); + for (const [a, b] of sharpPairs) { + if (edgeCount.get(ek(a, b)) !== 2) continue; + sharpAt[a].push(b); + sharpAt[b].push(a); + } const lim = new RowBuilder(); for (let v = 0; v < count; v++) { const m = new Map(); const bd = [...new Set(border[v])]; const nE = nbE[v].size; - if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1); + const through = sharpAt[v].length ? [...new Set([...bd, ...sharpAt[v]])] : []; + if (through.length > 2) m.set(v, 1); + else if (through.length === 2) { + addTo(m, through[0], 1 / 6); + addTo(m, v, 4 / 6); + addTo(m, through[1], 1 / 6); + } else if (!faces[v] || (bd.length && (faces[v] === 1 || bd.length !== 2)) || (!bd.length && nE !== faces[v])) m.set(v, 1); else if (bd.length) { addTo(m, bd[0], 1 / 6); addTo(m, v, 4 / 6); @@ -706,13 +774,65 @@ export function moveTurnScale(pts: Vec3[], mode: "move" | "turn" | "scale", [x, /** Remove faces; points no face uses any more go too (indices are renumbered). */ export function deleteFaces(cage: Cage, faces: number[]): Cage { const drop = new Set(faces); - return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)) }); + return compact({ verts: cage.verts, faces: cage.faces.filter((_, i) => !drop.has(i)), creases: cage.creases }); } function compact(cage: Cage): Cage { const used = [...new Set(cage.faces.flat())].sort((a, b) => a - b); const map = new Map(used.map((v, i) => [v, i])); - return { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) }; + const out: Cage = { verts: used.map((v) => cage.verts[v]), faces: cage.faces.map((f) => f.map((v) => map.get(v)!) as Cage["faces"][number]) }; + return withCreases(out, (cage.creases ?? []).flatMap(([a, b]) => (map.has(a) && map.has(b) ? [[map.get(a)!, map.get(b)!] as [number, number]] : []))); +} + +/** The cage with these sharp edges - those that are edges of it (none: no list at all). */ +export function withCreases(cage: Cage, creases: [number, number][]): Cage { + const { creases: _old, ...rest } = cage; + if (!creases.length) return rest; + const edges = new Set(); + for (const f of cage.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4])); + const seen = new Set(); + const kept = creases.filter(([a, b]) => edges.has(ekey(a, b)) && !seen.has(ekey(a, b)) && !!seen.add(ekey(a, b))); + return kept.length ? { ...rest, creases: kept } : rest; +} + +/** + * A cage made from another by a tool (a loop added, faces pulled out, a hole + * filled...) with the other's sharp edges on it: each where it still is - the + * same edge, or, where the tool cut it (a loop across it), the pieces of it. + * Found by where the points are: the tools number points as they please. + */ +export function carryCreases(prev: Cage, next: Cage): Cage { + if (next.creases || !prev.creases?.length) return next; + const at = new Map(); + const pos = (p: Vec3) => `${p[0].toFixed(6)},${p[1].toFixed(6)},${p[2].toFixed(6)}`; + next.verts.forEach((p, i) => at.set(pos(p), i)); + const edges = new Set(); + for (const f of next.faces) for (let k = 0; k < 4; k++) edges.add(ekey(f[k], f[(k + 1) % 4])); + const out: [number, number][] = []; + for (const [a, b] of prev.creases) { + const [pa, pb] = [prev.verts[a], prev.verts[b]]; + const [ia, ib] = [at.get(pos(pa)), at.get(pos(pb))]; + if (ia === undefined || ib === undefined) continue; + if (edges.has(ekey(ia, ib))) { + out.push([ia, ib]); + continue; + } + // Cut: the points of the new cage along it, in order, joined where they are edges. + const d: Vec3 = [pb[0] - pa[0], pb[1] - pa[1], pb[2] - pa[2]]; + const l2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]; + if (l2 < 1e-18) continue; + const on: { i: number; t: number }[] = []; + next.verts.forEach((q, i) => { + const w: Vec3 = [q[0] - pa[0], q[1] - pa[1], q[2] - pa[2]]; + const t = (w[0] * d[0] + w[1] * d[1] + w[2] * d[2]) / l2; + if (t < -1e-9 || t > 1 + 1e-9) return; + const off = Math.hypot(w[0] - d[0] * t, w[1] - d[1] * t, w[2] - d[2] * t); + if (off < Math.sqrt(l2) * 1e-6) on.push({ i, t }); + }); + on.sort((x, y) => x.t - y.t); + for (let k = 0; k + 1 < on.length; k++) if (edges.has(ekey(on[k].i, on[k + 1].i))) out.push([on[k].i, on[k + 1].i]); + } + return withCreases(next, out); } const ekey = (a: number, b: number) => (a < b ? `${a},${b}` : `${b},${a}`); @@ -776,7 +896,7 @@ export function refineCage(cage: Cage): Cage { const s = subdivide(cage, 1); const faces: Cage["faces"] = []; for (const g of s.grids) for (let i = 0; i < 2; i++) for (let j = 0; j < 2; j++) faces.push([g[i][j], g[i + 1][j], g[i + 1][j + 1], g[i][j + 1]]); - return compact({ verts: s.points, faces }); + return compact({ verts: s.points, faces, creases: [...(s.creased ?? [])].map((k) => k.split(",").map(Number) as [number, number]) }); } /** @@ -1221,6 +1341,102 @@ const cross3 = (a: Vec3, b: Vec3): Vec3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[ // ------------------------------------------------- adding cage detail +/** + * Take an edge loop out: the loop of edges through a-b (straight on through + * each point four edges meet at, round the shape or from border to border) + * goes, and the two faces either side of each of its edges become one. The + * points of the loop go with it. Null where the loop cannot be followed (a + * point on it where three or five edges meet), or where an edge of it is on + * the border. + */ +/** + * The loop of edges through a-b: straight on through each point four edges + * meet at, round the shape or from border to border. Null where it cannot be + * followed (a point where three or five edges meet) - or, `lenient`, the part + * of it that can. + */ +export function edgeLoopOf(cage: Cage, a: number, b: number, lenient = false): [number, number][] | null { + const efs = edgeFaceMap(cage); + if (!efs.has(ekey(a, b))) return null; + const around = new Map(); + for (const key of efs.keys()) { + const [p, q] = key.split(",").map(Number); + around.set(p, [...(around.get(p) ?? []), q]); + around.set(q, [...(around.get(q) ?? []), p]); + } + // From `from` on through `at`: the edge at `at` that shares no face with the one arrived by. + const onward = (from: number, at: number): number | null | undefined => { + const ns = around.get(at) ?? []; + const border = ns.filter((n) => efs.get(ekey(at, n))!.length === 1); + // (At the border the loop ends: its last point has the two border edges and the one arrived by.) + if (border.length) return ns.length === 3 && border.length === 2 ? null : undefined; + if (ns.length !== 4) return undefined; + const mine = new Set(efs.get(ekey(from, at))); + const next = ns.filter((n) => n !== from && !efs.get(ekey(at, n))!.some((f) => mine.has(f))); + return next.length === 1 ? next[0] : undefined; + }; + const loop: [number, number][] = [[a, b]]; + const seen = new Set([ekey(a, b)]); + let closed = false; + for (const dir of [0, 1]) { + let [from, at] = dir ? [b, a] : [a, b]; + for (let guard = 0; guard < cage.verts.length + 2; guard++) { + const next = onward(from, at); + if (next === undefined) { + if (lenient) break; + return null; + } + if (next === null) break; + if (seen.has(ekey(at, next))) { + closed = true; + break; + } + seen.add(ekey(at, next)); + loop.push([at, next]); + [from, at] = [at, next]; + } + if (closed) break; + } + return loop; +} + +export function removeEdgeLoop(cage: Cage, a: number, b: number): Cage | null { + const efs = edgeFaceMap(cage); + const loop = edgeLoopOf(cage, a, b); + if (!loop) return null; + const gone = new Set(); + const made: Quad[] = []; + for (const [p, q] of loop) { + const fs = efs.get(ekey(p, q))!; + if (fs.length !== 2) return null; + // The face that winds p then q, and the one that winds q then p: p-q-c-d and q-p-e-f. + const turn = (f: Quad, x: number, y: number): Quad | null => { + for (let k = 0; k < 4; k++) if (f[k] === x && f[(k + 1) % 4] === y) return [f[k], f[(k + 1) % 4], f[(k + 2) % 4], f[(k + 3) % 4]]; + return null; + }; + const A = turn(cage.faces[fs[0]], p, q) ?? turn(cage.faces[fs[1]], p, q); + const B = turn(cage.faces[fs[0]], q, p) ?? turn(cage.faces[fs[1]], q, p); + if (!A || !B) return null; + made.push([A[3], B[2], B[3], A[2]]); + gone.add(fs[0]).add(fs[1]); + } + // (A face on both sides of two loop edges - a loop one face wide round a corner - cannot be merged twice.) + if (gone.size !== loop.length * 2) return null; + // Sharp edges the loop crossed: each was cut in two at a point of the loop - with that point gone, it is one again. + const onLoop = new Set(loop.flat()); + const creases: [number, number][] = []; + const cutAt = new Map(); + for (const [p, q] of cage.creases ?? []) { + if (onLoop.has(p) && onLoop.has(q)) continue; + if (onLoop.has(p)) cutAt.set(p, [...(cutAt.get(p) ?? []), q]); + else if (onLoop.has(q)) cutAt.set(q, [...(cutAt.get(q) ?? []), p]); + else creases.push([p, q]); + } + for (const ends of cutAt.values()) if (ends.length === 2) creases.push([ends[0], ends[1]]); + const out = compact({ verts: cage.verts, faces: [...cage.faces.filter((_, i) => !gone.has(i)), ...made], creases }); + return out.faces.length ? out : null; +} + type Quad = Cage["faces"][number]; /** Faces using each edge. */ diff --git a/src/kernel/engine.ts b/src/kernel/engine.ts index a95f153..901779d 100644 --- a/src/kernel/engine.ts +++ b/src/kernel/engine.ts @@ -2065,7 +2065,7 @@ function opAffine(op: Extract["op"]): Affine | n /** Shell a freeform: remove the cage quads under the picked faces, thicken the sheet inward. */ function shellFreeform(ff: { feature: Extract; m: Affine }, faces: Face[], t: number): Shape3D { - const cage = { faces: ff.feature.cage.faces, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) }; + const cage = { ...ff.feature.cage, verts: ff.feature.cage.verts.map((v) => applyAffine(ff.m, v)) }; // Each body face is one cage quad's patch: match by the patch's middle point. const sub3 = subdivide(cage, 3); const mid = sub3.n / 2; @@ -2087,7 +2087,7 @@ function shellFreeform(ff: { feature: Extract; m: /** A freeform's shape with its cage mapped by m (thickness grows with the overall scale). */ function freeformShape(f: Extract, m: Affine): Shape3D { - const cage = { faces: f.cage.faces, verts: f.cage.verts.map((v) => applyAffine(m, v)) }; + const cage = { ...f.cage, verts: f.cage.verts.map((v) => applyAffine(m, v)) }; const det = Math.abs(m[0] * (m[5] * m[10] - m[6] * m[9]) - m[1] * (m[4] * m[10] - m[6] * m[8]) + m[2] * (m[4] * m[9] - m[5] * m[8])); const thicken = f.thickness ? { thickness: f.thickness * Math.cbrt(det || 1), side: f.thickSide ?? "up" } : undefined; return checkedFreeform(cage, thicken); diff --git a/src/tools/freeform.ts b/src/tools/freeform.ts index f31ac4f..115ab09 100644 --- a/src/tools/freeform.ts +++ b/src/tools/freeform.ts @@ -13,6 +13,7 @@ import { LineSegments2 } from "three/examples/jsm/lines/LineSegments2.js"; import { LineSegmentsGeometry } from "three/examples/jsm/lines/LineSegmentsGeometry.js"; import type { FaceFreeformFeature, Feature, FreeformEditFeature, FreeformFeature, PlaneDef, TransformFeature, Vec3 } from "../doc/types"; import { faceCage, facesNormal, liftOnto, onCorners, toFaces } from "../freeform/faceGrid"; +import { carryCreases, edgeLoopOf, removeEdgeLoop, withCreases } from "../freeform/cage"; import { applyPlan, archBridge, planeCage, borderChains, cachedPlan, planIndices, smoothNormals, type SubdivPlan, bridgeChains, bridgeFaces, moveTurnScale, shapeCage, sweepFace, type Chain, boundaryEdges, bridgeLoops, cageEdgeKey, extendBorder, cageEdges, deleteFaces, extrudeFaces, fillHole, holeLoops, insertEdgeLoop, insetFaces, isClosed, primitiveCage, refineCage, selfCrossings, subdivide, type Cage, type CagePrimitive } from "../freeform/cage"; import { add, cross, dot, len, niceStep, norm, scale, sub, xDirFor } from "../geom"; import type { PanelItem } from "../ui/ui"; @@ -87,6 +88,8 @@ export function faceStepNormal(f: FaceFreeformFeature): Vec3 { /** "Pick in a box" (a finger draws the box): on until switched off. */ let boxByFinger = false; +/** Soft: how far round the picked points a move reaches (0: not at all). Kept for the next shape. */ +let softRadius = 0; export class FreeformTool implements Tool { readonly id = "freeform"; @@ -95,12 +98,12 @@ export class FreeformTool implements Tool { private picks: Pick[] = []; private hovered: Pick | null = null; private gimbal: Gimbal | null = null; - private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number; k: Vec3; r0: number } | null = null; + private dragging: { part: GimbalPart; from: ToolPointer; base: Vec3[]; center: Vec3; d: Vec3; ang: number; k: Vec3; r0: number; along?: Vec3; soft?: Map } | null = null; /** What the gimbal up now is for (Move, Turn or Scale: its handles are that one's). */ private gimbalFor = ""; private typing: DragTyping; /** The card's exact values: what they act on (Move, Turn, Scale), and the points as they were before typing. */ - private xform: "move" | "turn" | "scale" = "move"; + private xform: "move" | "turn" | "scale" | "place" = "move"; /** * A finger drawing a box picks the points inside it (seen through: the * ones behind too) - a whole slice of a shape in one go from a side view. @@ -146,6 +149,8 @@ export class FreeformTool implements Tool { * apart while picking. Hidden behind the surface where it turns away. */ private faceEdges: LineSegments2; + /** The cage's sharp edges, drawn over its lines. */ + private creaseLines: LineSegments2; /** Which surface points the face outlines join (pairs), for the layout shown. */ private faceEdgeIdx: Uint32Array = new Uint32Array(0); /** @@ -195,7 +200,7 @@ export class FreeformTool implements Tool { this.existing = from.feature; this.place = placementOf(app.store.features, from.feature.id); const c = structuredClone(from.feature.cage); - this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd) }; + this.cage = { faces: c.faces, verts: c.verts.map(this.place.fwd), ...(c.creases ? { creases: c.creases } : {}) }; this.surfaceSheet = !!from.feature.surface; this.thickness = from.feature.thickness ?? 0; this.thickSide = from.feature.thickSide ?? "up"; @@ -216,6 +221,9 @@ export class FreeformTool implements Tool { this.marks = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(SEL, 4, false)); this.hoverMarks = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(HOVER, 2.5, false)); this.faceEdges = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(0x2f3b52, 1.6, true)); + this.creaseLines = new LineSegments2(new LineSegmentsGeometry(), app.view.lineMaterial(0xff8a3d, 3.2, true)); + this.creaseLines.renderOrder = 12; + this.creaseLines.visible = false; this.markFill.renderOrder = 67; // Zoom to fit frames the cage being shaped (its points: the smooth shape lies inside them). this.dots.userData.fit = true; @@ -270,6 +278,7 @@ export class FreeformTool implements Tool { if (this.sym) queueMicrotask(() => this.drawSymPlane()); this.symMark.renderOrder = 72; this.symMark.visible = false; + view.overlay.add(this.creaseLines); view.overlay.add(this.symPlane, this.symMark, this.surface, this.faceEdges, this.backLines, this.backDots, this.lines, this.dots, this.markFill, this.marks, this.markDots, this.hoverMarks, this.hoverDots); // Editing an existing freeform: hide its finished body while the cage is out. if (this.existing) view.setHidden(new Set([...this.app.store.doc.hidden, this.existing.id])); @@ -359,6 +368,7 @@ export class FreeformTool implements Tool { // (A sprite's geometry is shared by every sprite: only taken off, not disposed.) view.overlay.remove(this.symMark); view.overlay.remove(this.faceEdges); + view.overlay.remove(this.creaseLines); // (They share the front pass's points and lines: disposed with those.) view.overlay.remove(this.backLines, this.backDots); for (const o of [this.symPlane, this.surface, this.lines, this.dots, this.markFill, this.marks, this.markDots, this.hoverMarks, this.hoverDots]) { @@ -372,7 +382,7 @@ export class FreeformTool implements Tool { this.app.ui.setHint(null); this.app.ui.setLabel(0, 0, null); this.typing.hideBox(); - for (const o of [this.marks, this.hoverMarks, this.faceEdges]) { + for (const o of [this.marks, this.hoverMarks, this.faceEdges, this.creaseLines]) { o.geometry.dispose(); view.releaseLineMaterial(o.material); } @@ -412,8 +422,12 @@ export class FreeformTool implements Tool { this.fieldBase = null; // Nothing moved yet: no offset, no turn - and every scale factor 1 (0 flattened the points). this.fieldVals = this.xform === "scale" ? [1, 1, 1, 1] : [0, 0, 0, 1]; - items.push({ type: "choice", options: [{ id: "move", label: "Move" }, { id: "turn", label: "Turn" }, { id: "scale", label: "Scale" }], value: this.xform, onChange: (v) => ((this.xform = v as typeof this.xform), this.panel(), this.placeGimbal()) }); - if (this.xform === "scale") { + items.push({ type: "choice", options: [{ id: "move", label: "Move" }, { id: "turn", label: "Turn" }, { id: "scale", label: "Scale" }, { id: "place", label: "Place at" }], value: this.xform, onChange: (v) => ((this.xform = v as typeof this.xform), this.panel(), this.placeGimbal()) }); + if (this.xform === "place") { + // Where the picked points are (their middle), to type where they should be: X, Y and Z from the origin. + const at = this.centroid(this.selectedVerts()); + for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: a, value: Math.round(at[k] * 1000) / 1000, kind: "length", onInput: (v) => this.placeAt(k, v) }); + } else if (this.xform === "scale") { items.push({ type: "number", label: "All", value: 1, kind: "number", min: 0.01, onInput: (v) => this.setField(3, v) }); for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: a, value: 1, kind: "number", min: 0.01, onInput: (v) => this.setField(k, v) }); } else { @@ -421,6 +435,10 @@ export class FreeformTool implements Tool { for (const [k, a] of ["X", "Y", "Z"].entries()) items.push({ type: "number", label: turn ? `${a}°` : `Δ${a}`, value: 0, kind: turn ? "angle" : "length", onInput: (v) => this.setField(k, v) }); } } + // Soft: the points round the picked ones go along with a move, less the further off they are - a bump raised + // by one point, not a spike. (0: only what is picked moves.) + if (n && !this.face && (!this.live || this.live.kind === "shape" || this.live.kind === "sheet") && (this.xform === "move" || this.xform === "place")) + items.push({ type: "number", label: "Soft", value: softRadius, kind: "length", min: 0, onInput: (v) => (softRadius = Math.max(0, v)) }); // A phone has no mouse to draw a box round the points: a finger draws it while this is on. if (isCoarse && !this.placing && (!this.live || this.live.kind === "shape" || this.live.kind === "sheet")) items.push({ @@ -493,7 +511,57 @@ export class FreeformTool implements Tool { if (faces === 2 && !this.placing) items.push({ type: "button", label: "Bridge faces", icon: "loft", onClick: () => this.bridgeSelectedFaces() }); // One edge picked: a new loop of points across the faces it runs through. const edges = this.picks.filter((p) => p.kind === "edge"); - if (edges.length === 1 && !faces && !this.placing) items.push({ type: "button", label: "Add edge loop", icon: "splitLine", onClick: () => this.addEdgeLoop(edges[0].e) }); + // Edges picked: made sharp - the surface keeps a crease along them instead of rounding over - or smooth again. + if (edges.length && !faces && !this.placing && !this.face) { + const key = (e: [number, number]) => cageEdgeKey(e[0], e[1]); + const sharp = new Set((this.cage.creases ?? []).map(key)); + const picked = edges.map((p) => (p as Extract).e); + const allSharp = picked.every((e) => sharp.has(key(e))); + const many = picked.length > 1; + items.push({ + type: "button", + label: allSharp ? (many ? "Smooth edges" : "Smooth edge") : many ? "Sharp edges" : "Sharp edge", + icon: "chamfer", + onClick: () => { + const drop = new Set(picked.map(key)); + this.setCreases(allSharp ? (this.cage.creases ?? []).filter((e) => !drop.has(key(e))) : [...(this.cage.creases ?? []), ...picked]); + this.app.ui.toast(allSharp ? "Smooth again" : "Sharp: the surface keeps a crease along it (shown orange)"); + }, + }); + // (One edge: the whole loop it is part of, in one tap.) + if (!many) { + const loop = edgeLoopOf(this.cage, picked[0][0], picked[0][1], true) ?? []; + if (loop.length > 1) { + const loopSharp = loop.every((e) => sharp.has(key(e))); + items.push({ + type: "button", + label: loopSharp ? "Smooth loop" : "Sharp loop", + icon: "chamfer", + onClick: () => { + const drop = new Set(loop.map(key)); + this.setCreases(loopSharp ? (this.cage.creases ?? []).filter((e) => !drop.has(key(e))) : [...(this.cage.creases ?? []), ...loop]); + this.app.ui.toast(loopSharp ? "Smooth again" : `Sharp all the way along (${loop.length} edges)`); + }, + }); + } + } + } + if (edges.length === 1 && !faces && !this.placing) { + items.push({ type: "button", label: "Add edge loop", icon: "splitLine", onClick: () => this.addEdgeLoop(edges[0].e) }); + // (The other way: the loop this edge is part of taken out, the faces either side of it made one.) + if (removeEdgeLoop(this.cage, edges[0].e[0], edges[0].e[1])) + items.push({ + type: "button", + label: "Remove edge loop", + icon: "trash", + onClick: () => { + const r = removeEdgeLoop(this.cage, edges[0].e[0], edges[0].e[1]); + if (!r) return this.app.ui.toast("That loop cannot be taken out"); + this.changeCage(r, []); + this.app.ui.toast("Edge loop removed - the faces either side of it are one"); + }, + }); + } // Rim edges of holes picked: one hole → Fill, two facing holes → Bridge. // (Not while the whole shape is being placed: then every point is picked.) const loops = this.placing ? [] : this.pickedLoops(); @@ -648,7 +716,7 @@ export class FreeformTool implements Tool { const next = bridgeChains(this.cage, runs[0], runs[1]); if (!next) return this.app.ui.toast("These edges can't be connected (they touch each other)"); this.remember(); - this.cage = next; + this.cage = carryCreases(this.cage, next); this.picks = []; this.rebuild(); this.selectionChanged(); @@ -658,7 +726,7 @@ export class FreeformTool implements Tool { /** A cage change: the new cage, what's picked after it, and a fresh preview. */ private changeCage(next: Cage, picks: Pick[]): void { this.remember(); - this.cage = next; + this.cage = carryCreases(this.cage, next); this.picks = picks; this.rebuild(); this.selectionChanged(); @@ -770,7 +838,8 @@ export class FreeformTool implements Tool { if (!next) this.app.ui.toast("That would twist the handle - try less arch or more segments"); } if (!next) return false; - this.cage = next; + // (A live step is made again from the cage it began on: that one's sharp edges, each time.) + this.cage = "base" in l ? carryCreases(l.base, next) : next; this.picks = picks; this.rebuild(); this.placeGimbal(); @@ -894,7 +963,7 @@ export class FreeformTool implements Tool { } if (!next) return this.app.ui.toast(loops.length === 2 ? "Bridging needs two holes with the same number of edges" : "That hole can't be filled"); this.remember(); - this.cage = next; + this.cage = carryCreases(this.cage, next); this.picks = []; this.rebuild(); this.selectionChanged(); @@ -1212,11 +1281,30 @@ export class FreeformTool implements Tool { // (Scale: the press's distance from the middle on screen is "as it is" for this drag.) const c = this.app.view.toScreen(this.gimbal.origin); const r0 = c ? Math.max(24, Math.hypot(p.x - c[0], p.y - c[1])) : 60; - this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0, k: [1, 1, 1], r0 }; + this.dragging = { part, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center, d: [0, 0, 0], ang: 0, k: [1, 1, 1], r0, soft: this.softWeights(ids, this.cage.verts) }; this.gimbal.setHot(part); return true; } + /** + * A picked face pressed and dragged by itself (not by the gimbal): pushed in + * or pulled out along its own normal - several picked: along their average. + * (As everywhere else on the model: the thing picked is dragged.) + */ + dragStart(p: ToolPointer): boolean { + if (this.dragging || this.choosingPlane || this.symPicking || this.placing || (this.live && this.live.kind !== "shape" && this.live.kind !== "sheet")) return false; + const hit = this.pickAt(p); + const faces = this.picks.filter((x): x is Extract => x.kind === "face"); + if (hit?.kind !== "face" || !faces.some((x) => x.f === hit.f)) return false; + const n = norm(faces.reduce((s, x) => add(s, this.faceNormalOf(x.f)), [0, 0, 0] as Vec3)); + if (len(n) < 0.5) return false; + const ids = this.selectedVerts(); + this.remember(); + this.fieldBase = null; + this.dragging = { part: { kind: "axis", i: 2 }, from: p, base: this.cage.verts.map((v) => [...v] as Vec3), center: this.centroid(ids), d: [0, 0, 0], ang: 0, k: [1, 1, 1], r0: 60, along: n, soft: this.softWeights(ids, this.cage.verts) }; + return true; + } + drag(p: ToolPointer): void { const dr = this.dragging; if (!dr) return; @@ -1226,6 +1314,12 @@ export class FreeformTool implements Tool { const step = niceStep(view.cam.worldPerPixel(view.height) * 4); const snap = (v: number) => (p.shift ? v : Math.round(v / step) * step); const part = dr.part; + if (dr.along) { + const d = snap(axisDrag(view, dr.center, dr.along, dr.from, p)); + this.apply(scale(dr.along, d), 0); + this.boxAt(p, fmtLen(d)); + return; + } if (this.xform === "scale" && (part.kind === "axis" || part.kind === "center")) { const c = view.toScreen(dr.center); if (!c) return; @@ -1297,7 +1391,9 @@ export class FreeformTool implements Tool { } this.cage.verts[i] = add(q, d); } - this.mirrorMoved(ids); + // (The points round them go along with a move, by their share - not with a turn.) + const soft = dr.soft?.size && !deg ? this.softened(dr.soft, d, dr.base) : []; + this.mirrorMoved([...ids, ...soft]); this.gimbal?.setCenter(this.centroid(ids)); this.rebuild(); } @@ -1464,12 +1560,68 @@ export class FreeformTool implements Tool { if (!this.fieldBase) { this.remember(); this.fieldBase = new Map(ids.map((i) => [i, [...this.cage.verts[i]] as Vec3])); + this.fieldSoft = this.softWeights(ids, this.cage.verts); + this.fieldSoftBase = this.cage.verts.map((p) => [...p] as Vec3); } this.fieldVals[k] = v; + if (this.xform === "place") return; const base = [...this.fieldBase]; const moved = moveTurnScale(base.map(([, p]) => p), this.xform, this.fieldVals as [number, number, number, number]); base.forEach(([i], n) => (this.cage.verts[i] = moved[n])); - this.mirrorMoved(base.map(([i]) => i)); + const soft = this.xform === "move" ? this.softened(this.fieldSoft, [this.fieldVals[0], this.fieldVals[1], this.fieldVals[2]]) : []; + this.mirrorMoved([...base.map(([i]) => i), ...soft]); + this.rebuild(); + this.placeGimbal(); + } + + /** The cage's sharp edges set to these (a step to undo). */ + private setCreases(list: [number, number][]): void { + this.remember(); + this.cage = withCreases(this.cage, list); + this.rebuild(); + this.panel(); + } + + /** The points round the picked ones that go along with a move, each with how much of it (see Soft). */ + private fieldSoft = new Map(); + private fieldSoftBase: Vec3[] = []; + + /** How much of a move each unpicked point within the Soft distance of a picked one takes: 1 beside it, 0 at that distance. */ + private softWeights(ids: number[], verts: Vec3[]): Map { + const out = new Map(); + if (!(softRadius > 0) || this.face) return out; + const picked = new Set(ids); + for (let j = 0; j < verts.length; j++) { + if (picked.has(j)) continue; + let d = Infinity; + for (const i of ids) d = Math.min(d, len(sub(verts[j], verts[i]))); + if (d >= softRadius) continue; + const u = 1 - (d / softRadius) ** 2; + out.set(j, u * u); + } + return out; + } + + /** Move the soft points by their share of `d` from where they were; those moved. */ + private softened(weights: Map, d: Vec3, base: Vec3[] = this.fieldSoftBase): number[] { + for (const [j, w] of weights) if (base[j]) this.cage.verts[j] = add(base[j], scale(d, w)); + return [...weights.keys()]; + } + + /** The picked points put where their middle is at `v` on axis `k` (X, Y or Z from the origin). */ + private placeAt(k: number, v: number): void { + const ids = this.selectedVerts(); + if (!ids.length || !Number.isFinite(v)) return; + if (!this.fieldBase) { + this.remember(); + this.fieldBase = new Map(ids.map((i) => [i, [...this.cage.verts[i]] as Vec3])); + } + const d: Vec3 = [0, 0, 0]; + d[k] = v - this.centroid(ids)[k]; + for (const i of ids) this.cage.verts[i] = add(this.cage.verts[i], d); + const soft = this.softWeights(ids, this.cage.verts); + for (const [j, w] of soft) this.cage.verts[j] = add(this.cage.verts[j], scale(d, w)); + this.mirrorMoved([...ids, ...soft.keys()]); this.rebuild(); this.placeGimbal(); } @@ -1595,6 +1747,7 @@ export class FreeformTool implements Tool { return []; }); const pts = (ps: Pick[]) => ps.flatMap((p) => (p.kind === "vert" && this.cage.verts[p.i] ? [...this.cage.verts[p.i]] : [])); + setLines(this.creaseLines, (this.cage.creases ?? []).flatMap(([a, b]) => (this.cage.verts[a] && this.cage.verts[b] ? [...this.cage.verts[a], ...this.cage.verts[b]] : []))); setLines(this.marks, seg(this.picks)); setPositions(this.markDots, pts(this.picks)); const h = this.hovered ? [this.hovered] : []; @@ -1660,7 +1813,7 @@ export class FreeformTool implements Tool { return f.face.body; } // Stored where it was made: later move steps in History still apply on top. - const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv) }; + const cage = { faces: structuredClone(this.cage.faces), verts: this.cage.verts.map(this.place.inv), ...(this.cage.creases?.length ? { creases: structuredClone(this.cage.creases) } : {}) }; const open = !isClosed(cage); const symmetry = this.sym ? (() => { const o = this.place.inv(this.sym!.origin); diff --git a/src/ui/help.ts b/src/ui/help.ts index 28d23f9..f942251 100644 --- a/src/ui/help.ts +++ b/src/ui/help.ts @@ -35,7 +35,7 @@ const SECTIONS: { title: string; intro?: string; items: Entry[] }[] = [ intro: "Most work starts with a sketch on a plane or a flat face, then Extrude or Revolve turns it into a solid body. Pick the thing first, then its tool, on the line at the bottom: Create (Extrude, Revolve, Sweep, Loft), Modify (Fillet, Chamfer, Shell, Offset Face, Offset Edge, Thread, Wrap & Emboss, and Fix › Fill, Fill to Plane, Repair Body), Combine (Union, Subtract, Intersect, Split Body), Transform (Move › Move/Rotate, Translate, Rotate Around Axis; Scale, Mirror, Pattern), Construct (Plane, Axis, Project as Edge), Freeform and Sketch. More, at the end of the line, has Insert, BIM, Section View, Measure, Variables and Print / Share. A tool started with nothing picked says what to tap. A new project opens straight in a sketch on the floor with Line on.", items: [ { icon: "sketch", name: "Sketch", text: "Pick a plane (tap it, or the XY floor / XZ front / YZ side buttons), one of your construction planes by name, or a flat face, then draw lines, arcs, circles, rectangles… In a straight-on view (Front, Top…) Sketch goes on the face you're looking at. A new sketch starts with Line on. Closed shapes become profiles you can extrude: leave the sketch right after closing one and it is picked, the view turned so you can see it rise - drag the shape itself, or its arrow." }, - { icon: "freeform", name: "Freeform", text: "Smooth organic shapes: start from a box, sphere, cylinder, torus or surface (its size in the card) and pull its control points, edges and faces. Drag a box on empty space to pick the points inside (on a touch screen, switch on Pick in a box first: a finger then draws the box, the points behind picked too - a whole slice from a side view). Cage tools: Extrude faces (Length, Bend, Taper, Steps - a spout in one go), Bridge two faces (a tube, or an arched handle), Inset, Add edge loop, Add detail. Symmetry mirrors every move across X / Y / Z, a tapped edge, or midway between two facing faces picked first; the plane is kept with the shape. A hole: tap its edge → Fill hole, or Thickness… for a solid wall. Points on an open border → Extend surface adds faces beyond them. Connect: pick border edges on one or two surfaces (Shift adds) - two edges get a face between them, two hole rims a tube." }, + { icon: "freeform", name: "Freeform", text: "Smooth organic shapes: start from a box, sphere, cylinder, torus or surface (its size on the line) and pull its control points, edges and faces. Drag a box on empty space to pick the points inside (on a touch screen, switch on Pick in a box first: a finger then draws the box, the points behind picked too - a whole slice from a side view). A picked face is pushed in or pulled out by dragging it. Move, Turn, Scale or Place at (the picked points put at an exact X, Y, Z); Soft makes the points round the picked ones follow a move, less the further off they are. Cage tools: Extrude faces (Length, Bend, Taper, Steps - a spout in one go), Bridge two faces (a tube, or an arched handle), Inset, Add edge loop and Remove edge loop, Add detail. Sharp edge (or Sharp loop) keeps a crease along the picked edges instead of rounding over - shown orange; Smooth edge takes it off. Symmetry mirrors every move across X / Y / Z, a tapped edge, or midway between two facing faces picked first; the plane is kept with the shape. A hole: tap one edge of its rim → Fill hole (two holes: Bridge holes), or Thickness… for a solid wall. Points on an open border → Extend surface adds faces beyond them. Connect: pick border edges on one or two surfaces (Shift adds) - two edges get a face between them, two hole rims a tube." }, { icon: "extrude", name: "Extrude", text: "Pull a profile or a face straight out into a solid: drag the arrow or type a distance. Operation (Auto, New body, Add, Cut, Intersect): Auto goes by direction - on a plane + is a new body and - a cut, on a face out adds and in cuts. From a face, round buttons beside it offer what that direction can do (out: Add, New body; in: Cut, Intersect, New body): the lit one is what it does, tap another to switch. Taper end % sizes the far end: 100 none, 50 half, 0 to a point (a spire, a cone) - type it, or press on the box and drag left / right. All shapes takes every shape of the sketch at once." }, { icon: "revolve", name: "Revolve", text: "Turn a profile around an axis (vases, wheels). Travel moves it along the axis while turning - with more than 360° that makes threads and springs." }, { icon: "sweep", name: "Sweep", text: "Move a profile along a path curve (pipes, handles). End size grows or shrinks it on the way: 2 ends twice as big, 0.5 half (a horn, a tapered handle). Twist turns it round the path as it goes (degrees from start to end: a twisted bar, a drill flute)." }, diff --git a/tests/creases.test.ts b/tests/creases.test.ts new file mode 100644 index 0000000..f3c40d0 --- /dev/null +++ b/tests/creases.test.ts @@ -0,0 +1,78 @@ +// Run: npx tsx tests/creases.test.ts - sharp edges on a freeform cage: the +// surface keeps a crease along them. The quick weights the editor draws with +// give the same points as the rules applied in full; a box with every edge +// sharp is that box exactly; one loop sharp is a cylinder-like end; tools that +// change the cage carry the sharp edges along. +import { check, done, near, after, volume, health } from "./kit"; +import { applyPlan, boxCage, carryCreases, cageEdges, insertEdgeLoop, limitPoints, refineCage, removeEdgeLoop, subdivide, subdivisionPlan, edgeLoopOf, deleteFaces, type Cage } from "../src/freeform/cage"; +import type { Feature } from "../src/doc/types"; + +const same = (cage: Cage, levels = 3) => { + const s = subdivide(cage, levels); + const exact = limitPoints(s); + const quick = applyPlan(subdivisionPlan(cage, levels), cage.verts); + let worst = 0; + exact.forEach((p, i) => (worst = Math.max(worst, Math.abs(p[0] - quick[i * 3]), Math.abs(p[1] - quick[i * 3 + 1]), Math.abs(p[2] - quick[i * 3 + 2])))); + return { worst, n: exact.length, pts: exact }; +}; +const ff = (id: string, cage: Cage): Feature => ({ id, name: id, type: "freeform", cage }) as Feature; + +// A box, one face a side: all twelve edges sharp. +const box = boxCage([40, 30, 20], 1); +const all: Cage = { ...box, creases: cageEdges(box) }; +check("a box has twelve edges", all.creases!.length === 12, all.creases!.length); +const a = same(all); +check("quick and full agree (every edge sharp)", a.worst < 1e-5, a.worst); +const lo = [0, 1, 2].map((k) => Math.min(...a.pts.map((p) => p[k]))); +const hi = [0, 1, 2].map((k) => Math.max(...a.pts.map((p) => p[k]))); +check("... and the surface is the box itself", near(hi[0] - lo[0], 40, 1e-9) && near(hi[1] - lo[1], 30, 1e-9) && near(hi[2] - lo[2], 20, 1e-9), [lo, hi]); +{ + const { body, err } = await after([ff("B", all)], "B"); + check("made a solid: 40 x 30 x 20", !err && near(volume(body), 24000, 24), { err, v: volume(body) }); + check("... closed and sound", !!body && health(body).healthy, body && health(body)); +} +// No sharp edges: as it always was (rounded, smaller). +{ + const s = same(box); + check("quick and full agree (none sharp)", s.worst < 1e-5, s.worst); + const { body } = await after([ff("R", box)], "R"); + check("none sharp: a rounded lump, well under the box", volume(body) < 24000 * 0.75, volume(body)); +} +// Only the top's four edges sharp: a flat top with a crisp rim, the bottom still round. +{ + const fine = boxCage([40, 40, 40], 2); + const z = Math.max(...fine.verts.map((p) => p[2])); + const rim = cageEdges(fine).filter(([p, q]) => near(fine.verts[p][2], z) && near(fine.verts[q][2], z) && (near(Math.abs(fine.verts[p][0]), 20) || near(Math.abs(fine.verts[p][1]), 20)) && (near(Math.abs(fine.verts[q][0]), 20) || near(Math.abs(fine.verts[q][1]), 20)) && (near(fine.verts[p][0], fine.verts[q][0]) ? near(Math.abs(fine.verts[p][0]), 20) : near(Math.abs(fine.verts[p][1]), 20))); + const top: Cage = { ...fine, creases: rim }; + check("the top's rim is eight edges", rim.length === 8, rim.length); + const s = same(top); + check("quick and full agree (a rim sharp)", s.worst < 1e-5, s.worst); + const { body: sharp, err } = await after([ff("T", top)], "T"); + const { body: round } = await after([ff("T0", fine)], "T0"); + check("a sharp rim: more of the box is kept than with none", !err && volume(sharp) > volume(round) * 1.03, { err, sharp: volume(sharp), round: volume(round) }); + check("... closed and sound", !!sharp && health(sharp).healthy, sharp && health(sharp)); + // The loop through one of its edges is the rim's side it is on... the whole loop of edges through it. + const loop = edgeLoopOf(top, rim[0][0], rim[0][1], true); + check("the loop through a rim edge can be followed", !!loop && loop.length >= 2, loop?.length); + + // Tools carry them: a loop added across the rim cuts two of its edges - both halves stay sharp. + const side = cageEdges(top).find(([p, q]) => near(top.verts[p][0], top.verts[q][0]) && near(top.verts[p][1], top.verts[q][1]) && !near(top.verts[p][2], top.verts[q][2]))!; + const cut = insertEdgeLoop(top, side[0], side[1]); + check("a loop round the sides leaves the rim as it was", !!cut && (carryCreases(top, cut!).creases?.length ?? 0) === 8, cut && carryCreases(top, cut).creases?.length); + const across = insertEdgeLoop(top, rim[0][0], rim[0][1]); + const carried = across && carryCreases(top, across); + check("a loop across the rim: its two cut edges are four sharp halves (ten in all)", (carried?.creases?.length ?? 0) === 10, carried?.creases?.length); + check("... and quick and full still agree", !!carried && same(carried).worst < 1e-5, carried && same(carried).worst); + // Taken out again: eight. + const mid = carried!.verts.length - 1; + const loopEdge = cageEdges(carried!).find(([p, q]) => p >= top.verts.length && q >= top.verts.length)!; + const back = removeEdgeLoop(carried!, loopEdge[0], loopEdge[1]); + check("the loop taken out again: the rim's eight", !!back && (back!.creases?.length ?? 0) === 8, { n: back?.creases?.length, mid }); + // Add detail: each sharp edge is two. + const fine2 = refineCage(top); + check("Add detail: sixteen sharp edges, the same shape", (fine2.creases?.length ?? 0) === 16, fine2.creases?.length); + // A face deleted: sharp edges that are still edges stay. + const less = deleteFaces(top, [0]); + check("a face deleted: the sharp edges still there are kept", (less.creases?.length ?? 0) >= 6, less.creases?.length); +} +done();