Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

feat(modeling): lathe and loft make curved solids from a few points, so an agent can build vases, pipes, handles and hulls

yhh345a88c90984
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c1f89a743..5e25c2c25 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,7 +19,7 @@ published separately; it ships inside the editor.
- **Glyphs can be put on the atlas before they are shown.** The first page of a novel is hundreds of new characters, all landing in one frame. `preloadGlyphs(app, label, text, { budgetMs })` makes them ahead of time, a slice a frame, drawn as that `Text` will draw them, and returns `progress`, `done` and `release()`. On a Snapdragon 8 Elite a book's 2992 characters at 28 px took 145 ms over 25 frames with the worst frame at 9.5 ms, after which the first page's frame went from 49 to 11 ms and no page made a new glyph. Preloaded glyphs hold their atlas pages (4 MB each, a few hundred characters at that size) until `release()`.
- **Voxel GI lights what the camera does not see, and bounces light more than once.** The cache now reads the sun's shadow map back into the world, so a surface the sun lights behind or beside the camera still sends light into the view. Each surface also gives off again the bounce light it received, so a corner or a floor in shade gets light that took two or more bounces to reach it. A ray now brings what it meets at full strength however far it went (it used to fade with distance, 40% at 4 m with 12 cm voxels). Each voxel is weighed by how much of it a surface covers, so a bright patch no longer lights like the whole voxel around it. Together these keep the result close to a path tracer's whatever the voxel size. In a sunlit test room the whole frame carries 0.95 of Cycles' light at the default size and 0.74 at 12 cm voxels; before, it was 0.54 at the default and darker the finer the grid. With the lit patch behind the camera, the walls went from no bounce light to 25–57%. A closed room the sun only lights from outside stays dark. Two inspector controls tune it: **Off-screen Sun Albedo** (the colour the shadow map cannot give, assumed) and **Multi-bounce**. A fine grid no longer drops every voxel: a count truncated by the cache's ageing had kept them below the two samples a ray asks for. The WebGL2 fallback does the same in its own passes: each voxel asks the sun's map whether a sunlit surface stands in it, and traces two rays through last frame's grid for the light it is given. In the test room it carries 1.00 of Cycles' light at the default size (it was 0.56) and 0.80 at 12 cm; with the lit patch behind the camera 0.20 (it was 0). Its voxel pass costs about 1.3 ms more at 720p on a desktop.
-**AI agents can build 3D models in the editor from steps.** The `modeling` tool group writes a `.esmodel`, the steps that build a model (boxes, cylinders and floor plans, then extrude, inset, bevel, slice, array, mirror, paint), and bakes the `.esmesh` a scene draws beside it. Changing one number rebuilds it and whatever draws it follows, Undo takes both files back, and `model_views` shows every side with its silhouette, so an agent can check a shape without a scene. Blockouts, buildings and hard-surface props; and with the `organic` step, creatures, plants and rocks, as one skin over parts that melt into each other, carve, mirror and roughen. A `boolean` step cuts real holes through solids, and a `uv` step or `uvAtlas` lays out how a texture lands.
+**AI agents can build 3D models in the editor from steps.** The `modeling` tool group writes a `.esmodel`, the steps that build a model (boxes, cylinders and floor plans, then extrude, inset, bevel, slice, array, mirror, paint), and bakes the `.esmesh` a scene draws beside it. Changing one number rebuilds it and whatever draws it follows, Undo takes both files back, and `model_views` shows every side with its silhouette, so an agent can check a shape without a scene. Blockouts, buildings and hard-surface props; and with the `organic` step, creatures, plants and rocks, as one skin over parts that melt into each other, carve, mirror and roughen. `lathe` and `loft` make curved solids from a few points: vases, pipes, handles, hulls. A `boolean` step cuts real holes through solids, and a `uv` step or `uvAtlas` lays out how a texture lands.
- **A model of many parts that moves: `CompositeBatch`.** Put it on the root of a ship, a vehicle or a moving platform assembled from many meshes, and while the game runs its parts are drawn in a few draws parented to the root: a mesh repeated four times or more (a deck plank, a rail post) as one instanced set that copies no vertices, every other part merged by draw state into chunks of the root's own space. Moving, turning or scaling the root moves the whole model and merges nothing again. Adding, removing, re-meshing or re-placing a part re-merges only its chunk within half a second (`CompositeBatchingRes.refresh(root)` looks at once), and a part that keeps moving inside the model is let go to draw itself. The root reports what it drew, and so does `get_stats`. On a model of 2,004 parts, the meshes handed to the renderer went from 2,003 to 5 and the CPU frame from 3.3 ms to 1.2–1.4 ms; a model of about a hundred parts costs the same either way. A part under a composite is never also statically batched.
diff --git a/desktop b/desktop
index a8c1bb8eb..ff845a3a6 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit a8c1bb8eb712d441bf8e4b15fe6a3537098383e9
+Subproject commit ff845a3a6b467e141cfdf2703a27d3656e5e56d1
diff --git a/pipeline/src/modeling/modelBake.ts b/pipeline/src/modeling/modelBake.ts
index 9b71270da..83c8c845d 100644
--- a/pipeline/src/modeling/modelBake.ts
+++ b/pipeline/src/modeling/modelBake.ts
@@ -34,6 +34,8 @@ export interface ModelReport {
nonManifoldEdges: number;
/** Faces with no area, which draw nothing and shade badly beside them. */
degenerateFaces: number;
+ /** Edges whose two faces run it the same way: one of them faces the wrong way, whatever the rest of the shell does. */
+ flippedEdges: number;
/** Closed shells whose faces point inward, which render as their own inside. */
insideOutShells: number;
steps: StepReport[];
@@ -193,6 +195,15 @@ export function bakeModel(raw: unknown): BakedModel {
const openEdges = edges.filter((e) => e.faces.length === 1).length;
const nonManifoldEdges = edges.filter((e) => e.faces.length > 2).length;
const degenerateFaces = mesh.faces.filter((f) => faceArea(mesh, f) < 1e-10).length;
+ let flippedEdges = 0;
+ for (const e of edges) {
+ if (e.faces.length !== 2) continue;
+ const runs = (f: number): boolean => {
+ const v = mesh.faces[f]!.v;
+ return v.some((a, i) => a === e.a && v[(i + 1) % v.length] === e.b);
+ };
+ if (runs(e.faces[0]!) === runs(e.faces[1]!)) flippedEdges++;
+ }
const shells = findShells(mesh);
const edgeFaces = new Map<number, boolean>();
for (const e of edges) for (const f of e.faces) if (e.faces.length !== 2) edgeFaces.set(f, true);
@@ -207,6 +218,7 @@ export function bakeModel(raw: unknown): BakedModel {
const warnings: string[] = [];
if (openEdges) warnings.push(`${openEdges} open edge${openEdges > 1 ? 's' : ''}: the surface has holes you can see into`);
if (nonManifoldEdges) warnings.push(`${nonManifoldEdges} edge${nonManifoldEdges > 1 ? 's' : ''} shared by more than two faces, which a later bevel refuses: \`weld\` may have joined things that should stay apart, or on an organic skin two parts just touch, so overlap them or raise blend`);
+ if (flippedEdges) warnings.push(`${flippedEdges} edge${flippedEdges > 1 ? 's' : ''} between faces wound opposite ways: part of the surface faces inward`);
if (degenerateFaces) warnings.push(`${degenerateFaces} face${degenerateFaces > 1 ? 's' : ''} with no area; \`weld\` removes them`);
if (insideOutShells) warnings.push(`${insideOutShells} closed shell${insideOutShells > 1 ? 's are' : ' is'} inside out`);
@@ -225,7 +237,7 @@ export function bakeModel(raw: unknown): BakedModel {
size: roundVec(sub(max, min)),
center: roundVec([(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2]),
},
- tags, openEdges, nonManifoldEdges, degenerateFaces, insideOutShells, steps, warnings,
+ tags, openEdges, nonManifoldEdges, flippedEdges, degenerateFaces, insideOutShells, steps, warnings,
},
};
}
diff --git a/pipeline/src/modeling/modelOps.ts b/pipeline/src/modeling/modelOps.ts
index 04b85aa68..8d70a2cc3 100644
--- a/pipeline/src/modeling/modelOps.ts
+++ b/pipeline/src/modeling/modelOps.ts
@@ -41,7 +41,7 @@ const usedVertices = (mesh: PolyMesh, faces: readonly number[]): Set<number> =>
// ---- Primitives: each appends a shell, leaving what is there alone ------------
-interface Placed { at?: Vec3; tag?: string; color?: readonly number[] }
+export interface Placed { at?: Vec3; tag?: string; color?: readonly number[] }
/** A colour as a face holds it. Refused rather than clamped: past 1 is a sum gone wrong. */
function toColor(c: readonly number[]): NonNullable<Face['color']> {
@@ -51,7 +51,7 @@ function toColor(c: readonly number[]): NonNullable<Face['color']> {
return [c[0]!, c[1]!, c[2]!, c[3] ?? 1];
}
-function append(mesh: PolyMesh, positions: readonly Vec3[], loops: readonly number[][], placed: Placed): PolyMesh {
+export function append(mesh: PolyMesh, positions: readonly Vec3[], loops: readonly number[][], placed: Placed): PolyMesh {
guardSize(mesh.faces.length + loops.length);
const base = mesh.positions.length;
const at = placed.at ?? [0, 0, 0];
diff --git a/pipeline/src/modeling/modelSource.ts b/pipeline/src/modeling/modelSource.ts
index 82839afc4..225c48c4b 100644
--- a/pipeline/src/modeling/modelSource.ts
+++ b/pipeline/src/modeling/modelSource.ts
@@ -16,6 +16,7 @@ import * as ops from './modelOps';
import { organic } from './organic';
import { booleanOp } from './booleans';
import { uvStep } from './modelUv';
+import { lathe, loft } from './surfaces';
import { compact, type Face, type FaceSelector, type PolyMesh, type Vec3 } from './polyMesh';
export const MODEL_SOURCE_VERSION = 1;
@@ -40,7 +41,7 @@ export interface ModelSource {
}
type Kind = 'number' | 'integer' | 'boolean' | 'string' | 'vec3' | 'number|vec3' | 'number|vec2' | 'number|numbers'
- | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2';
+ | 'color' | 'points' | 'faces' | 'edges' | 'axis' | 'pivot' | 'parts' | 'noise' | 'sections' | 'section' | 'vec3s' | 'numbers' | 'operation' | 'uvmode' | 'number|vec2only' | 'vec2';
interface OpSpec {
params: Record<string, Kind>;
@@ -60,6 +61,8 @@ export const MODEL_OPS: Record<string, OpSpec> = {
cone: { params: { radius: 'number', height: 'number', sides: 'integer', ...PLACED }, required: ['radius', 'height'], run: ops.cone as OpSpec['run'], says: 'adds an upright cone' },
sphere: { params: { radius: 'number', rings: 'integer', sides: 'integer', ...PLACED }, required: ['radius'], run: ops.sphere as OpSpec['run'], says: 'adds a sphere' },
prism: { params: { points: 'points', height: 'number', ...PLACED }, required: ['points', 'height'], run: ops.prism as OpSpec['run'], says: 'stands a floor plan of [x, z] points up to `height`' },
+ lathe: { params: { profile: 'points', sides: 'integer', arc: 'number', closed: 'boolean', curve: 'integer', axis: 'axis', ...PLACED }, required: ['profile'], run: lathe as unknown as OpSpec['run'], says: 'turns a half-outline of [distance from axis, height] round an axis: a vase, a glass, a column' },
+ loft: { params: { sections: 'sections', path: 'vec3s', section: 'section', scales: 'numbers', sides: 'integer', closed: 'boolean', curve: 'integer', ...PLACED }, required: [], run: loft as unknown as OpSpec['run'], says: 'joins cross-sections along a path: a pipe, a handle, a bottle, a hull' },
organic: { params: { parts: 'parts', resolution: 'integer', blend: 'number', noise: 'noise', at: 'vec3', tag: 'string', color: 'color' }, required: ['parts'], run: organic as unknown as OpSpec['run'], says: 'adds one continuous skin over a body of parts that melt into each other' },
transform: { params: { faces: 'faces', translate: 'vec3', rotate: 'vec3', scale: 'number|vec3', pivot: 'pivot' }, required: [], run: ops.transform as OpSpec['run'], says: 'moves the vertices of the faces (default all): scaling a top face in makes a roof' },
array: { params: { faces: 'faces', count: 'integer', offset: 'vec3', rotate: 'vec3', pivot: 'pivot', tag: 'string' }, required: ['count'], run: ops.array as OpSpec['run'], says: 'repeats the faces, `count` including the original' },
@@ -156,6 +159,36 @@ const PART_FIELDS: Record<string, (v: unknown) => string | null> = {
noise: checkNoise,
};
+const SECTION_FIELDS: Record<string, (v: unknown) => string | null> = {
+ at: (v) => (isNums(v, 3) ? null : 'must be [x, y, z]'),
+ radius: (v) => (isNum(v) ? null : 'must be a number'),
+ radii: (v) => (isNums(v, 2) ? null : 'must be [across, up]'),
+ size: (v) => (isNums(v, 2) ? null : 'must be [across, up]'),
+ points: (v) => (Array.isArray(v) && v.every((q) => isNums(q, 2)) ? null : 'must be an array of [across, up]'),
+ twist: (v) => (isNum(v) ? null : 'must be degrees'),
+ scale: (v) => (isNum(v) ? null : 'must be a number'),
+};
+
+function checkSection(v: unknown): string | null {
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return 'must be an object';
+ for (const [key, value] of Object.entries(v)) {
+ const check = SECTION_FIELDS[key];
+ if (!check) return `has an unknown field "${key}"; a section takes ${Object.keys(SECTION_FIELDS).join(', ')}`;
+ const bad = check(value);
+ if (bad) return `.${key} ${bad}`;
+ }
+ return null;
+}
+
+function checkSections(v: unknown): string | null {
+ if (!Array.isArray(v)) return 'must be an array of sections';
+ for (let i = 0; i < v.length; i++) {
+ const bad = checkSection(v[i]);
+ if (bad) return `[${i}] ${bad}`;
+ }
+ return null;
+}
+
function checkParts(v: unknown): string | null {
if (!Array.isArray(v) || v.length === 0) return 'must be a non-empty array of parts';
for (let i = 0; i < v.length; i++) {
@@ -187,6 +220,10 @@ const KIND_CHECK: Record<Kind, (v: unknown) => string | null> = {
edges: checkEdges,
axis: (v) => (v === 'x' || v === 'y' || v === 'z' ? null : 'must be x, y or z'),
parts: checkParts,
+ sections: checkSections,
+ section: checkSection,
+ vec3s: (v) => (Array.isArray(v) && v.every((q) => isNums(q, 3)) ? null : 'must be an array of [x, y, z]'),
+ numbers: (v) => (isNums(v) ? null : 'must be an array of numbers'),
operation: (v) => (v === 'subtract' || v === 'union' || v === 'intersect' ? null : 'must be subtract, union or intersect'),
uvmode: (v) => (['box', 'planar', 'cylinder', 'sphere'].includes(v as string) ? null : 'must be box, planar, cylinder or sphere'),
'number|vec2only': (v) => (isNum(v) || isNums(v, 2) ? null : 'must be a number or [u, v]'),
diff --git a/pipeline/src/modeling/modelViews.ts b/pipeline/src/modeling/modelViews.ts
index 66fedc0c3..d7fc2c653 100644
--- a/pipeline/src/modeling/modelViews.ts
+++ b/pipeline/src/modeling/modelViews.ts
@@ -3,7 +3,7 @@
/**
* @file modelViews.ts — a contact sheet of a model, drawn on the CPU.
*
- * Each view is drawn twice: shaded with its polygon edges, and as a bare
+ * Each view is drawn twice: shaded with its hard edges, and as a bare
* silhouette under it. The silhouette is not decoration. Faults in a blockout
* (a limb too thin, a gap, a wrong proportion) have survived every lit view
* and shown at once in outline, because shading gives the eye something else
@@ -15,7 +15,7 @@
* What the model looks like in the game is what `screenshot` is for.
*/
import type { BakedModel } from './modelBake';
-import { add, boundsOf, cross, dot, faceNormal, normalize, selectFaces, sub, type FaceSelector, type Vec3 } from './polyMesh';
+import { add, boundsOf, collectEdges, cross, dot, faceNormal, normalize, selectFaces, sub, type FaceSelector, type Vec3 } from './polyMesh';
export const MODEL_VIEWS = {
front: { right: [1, 0, 0], up: [0, 1, 0], toward: [0, 0, 1] },
@@ -56,7 +56,7 @@ const WIRE = [30, 30, 30] as const;
const GUTTER = [120, 120, 120] as const;
/** Lays the views out as columns over two rows, each panel `panel` pixels square. */
-export function renderModelSheet(model: BakedModel, views: readonly ModelViewName[] = DEFAULT_MODEL_VIEWS, panel = 384, focus?: FaceSelector): ModelSheet {
+export function renderModelSheet(model: BakedModel, views: readonly ModelViewName[] = DEFAULT_MODEL_VIEWS, panel = 384, focus?: FaceSelector, wire = false): ModelSheet {
if (views.length === 0) throw new Error('name at least one view');
for (const v of views) {
if (!(v in MODEL_VIEWS)) throw new Error(`unknown view "${v}"; there are ${Object.keys(MODEL_VIEWS).join(', ')}`);
@@ -93,6 +93,12 @@ export function renderModelSheet(model: BakedModel, views: readonly ModelViewNam
});
for (let i = 0; i < vertexNormals.length; i++) if (vertexNormals[i]) vertexNormals[i] = normalize(vertexNormals[i]!);
const depth = new Float32Array(panel * panel);
+ // The edges a shape actually has. Every polygon edge on a curved surface or a cut's triangles is a net over what is being judged, so that is on request.
+ const FEATURE = Math.cos((30 * Math.PI) / 180);
+ const lines = [...collectEdges(poly).values()].filter((e) => {
+ if (e.faces.every((f) => poly.faces[f]!.smooth)) return false;
+ return wire || e.faces.length !== 2 || dot(normals[e.faces[0]!]!, normals[e.faces[1]!]!) < FEATURE;
+ });
views.forEach((name, column) => {
const basis = MODEL_VIEWS[name];
@@ -144,18 +150,15 @@ export function renderModelSheet(model: BakedModel, views: readonly ModelViewNam
}
// Polygon edges, on top of whatever they are not behind: what tells a person how the surface is built.
const bias = unitsPerPixel * 2;
- for (const face of poly.faces) {
- if (face.smooth) continue;
- for (let i = 0; i < face.v.length; i++) {
- const a = screen[face.v[i]!]!, b = screen[face.v[(i + 1) % face.v.length]!]!;
- const steps = Math.max(1, Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))));
- for (let s = 0; s <= steps; s++) {
- const t = s / steps;
- const x = Math.floor(a[0] + (b[0] - a[0]) * t), y = Math.floor(a[1] + (b[1] - a[1]) * t);
- if (x < 0 || y < 0 || x >= panel || y >= panel) continue;
- if (a[2] + (b[2] - a[2]) * t + bias < depth[y * panel + x]!) continue;
- put(ox + x, y, WIRE);
- }
+ for (const edge of lines) {
+ const a = screen[edge.a]!, b = screen[edge.b]!;
+ const steps = Math.max(1, Math.ceil(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1]))));
+ for (let s = 0; s <= steps; s++) {
+ const t = s / steps;
+ const x = Math.floor(a[0] + (b[0] - a[0]) * t), y = Math.floor(a[1] + (b[1] - a[1]) * t);
+ if (x < 0 || y < 0 || x >= panel || y >= panel) continue;
+ if (a[2] + (b[2] - a[2]) * t + bias < depth[y * panel + x]!) continue;
+ put(ox + x, y, WIRE);
}
}
});
diff --git a/pipeline/src/modeling/surfaces.ts b/pipeline/src/modeling/surfaces.ts
new file mode 100644
index 000000000..0d236c724
--- /dev/null
+++ b/pipeline/src/modeling/surfaces.ts
@@ -0,0 +1,371 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file surfaces.ts — `lathe` and `loft`: curved solids from a handful of numbers.
+ *
+ * A lathe turns a half-outline round an axis: a vase, a glass, a column. A loft
+ * joins cross-sections along a path: a pipe, a handle, a bottle, a hull. `curve`
+ * rounds what is given through its own points, so an agent states the few that
+ * matter and the surface between them follows.
+ */
+import { append, type Placed } from './modelOps';
+import { add, cross, dot, length, normalize, scale, sub, type PolyMesh, type Vec3 } from './polyMesh';
+
+const DEG = Math.PI / 180;
+const EPS = 1e-6;
+
+/**
+ * Catmull-Rom through @p points, `steps` segments for each span; the points themselves stay exactly where they are.
+ * A point given twice stops the curve there, which is how a corner is kept. Works on any tuple length.
+ */
+function curveThrough(points: readonly (readonly number[])[], steps: number, closed: boolean): number[][] {
+ if (steps <= 1 || points.length < 3) return points.map((p) => [...p]);
+ const n = points.length;
+ const at = (i: number): readonly number[] => (closed ? points[((i % n) + n) % n]! : points[Math.max(0, Math.min(n - 1, i))]!);
+ const out: number[][] = [];
+ const spans = closed ? n : n - 1;
+ for (let i = 0; i < spans; i++) {
+ const [p0, p1, p2, p3] = [at(i - 1), at(i), at(i + 1), at(i + 2)];
+ // Nothing to walk between a doubled point's two copies, and either side of it the neighbour's tangent now stops there: the corner.
+ if (p1.every((v, k) => Math.abs(v - p2[k]!) < EPS)) continue;
+ for (let s = 0; s < steps; s++) {
+ const t = s / steps;
+ const [t2, t3] = [t * t, t * t * t];
+ out.push(p1.map((_, k) => 0.5 * (2 * p1[k]! + (p2[k]! - p0[k]!) * t + (2 * p0[k]! - 5 * p1[k]! + 4 * p2[k]! - p3[k]!) * t2
+ + (3 * p1[k]! - p0[k]! - 3 * p2[k]! + p3[k]!) * t3)));
+ }
+ }
+ if (!closed) out.push([...points[n - 1]!]);
+ return out;
+}
+
+const samePoint = (a: readonly number[], b: readonly number[]): boolean => a.every((v, k) => Math.abs(v - b[k]!) < EPS);
+
+function withoutRepeats(points: number[][], closed: boolean): number[][] {
+ const out = points.filter((p, i) => i === 0 || !samePoint(p, points[i - 1]!));
+ if (closed && out.length > 1 && samePoint(out[0]!, out[out.length - 1]!)) out.pop();
+ return out;
+}
+
+/** Winds every loop to agree with its neighbours across their shared edges, each connected piece starting from its first. */
+function agreeing(loops: readonly number[][]): number[][] {
+ const out = loops.map((l) => [...l]);
+ const onEdge = new Map<string, number[]>();
+ out.forEach((loop, f) => loop.forEach((v, i) => {
+ const w = loop[(i + 1) % loop.length]!;
+ const key = v < w ? `${v}:${w}` : `${w}:${v}`;
+ const at = onEdge.get(key);
+ if (at) at.push(f); else onEdge.set(key, [f]);
+ }));
+ const runs = (loop: readonly number[], a: number, b: number): boolean => loop.some((v, i) => v === a && loop[(i + 1) % loop.length] === b);
+ const seen = new Set<number>();
+ for (let start = 0; start < out.length; start++) {
+ if (seen.has(start)) continue;
+ seen.add(start);
+ const queue = [start];
+ while (queue.length) {
+ const f = queue.pop()!;
+ const loop = out[f]!;
+ loop.forEach((v, i) => {
+ const w = loop[(i + 1) % loop.length]!;
+ for (const g of onEdge.get(v < w ? `${v}:${w}` : `${w}:${v}`)!) {
+ if (seen.has(g)) continue;
+ seen.add(g);
+ // A neighbour must run a shared edge the other way.
+ if (runs(out[g]!, v, w)) out[g]!.reverse();
+ queue.push(g);
+ }
+ });
+ }
+ }
+ return out;
+}
+
+/** The loops wound consistently and facing out, whichever way the caller walked its outline. */
+function facingOut(positions: readonly Vec3[], loops: readonly number[][]): number[][] {
+ const wound = agreeing(loops);
+ let v = 0;
+ for (const loop of wound) {
+ for (let i = 1; i + 1 < loop.length; i++) {
+ v += dot(positions[loop[0]!]!, cross(positions[loop[i]!]!, positions[loop[i + 1]!]!));
+ }
+ }
+ return v < 0 ? wound.map((l) => [...l].reverse()) : wound;
+}
+
+export interface LatheParams extends Placed {
+ /** The half-outline, as [distance from the axis, height]. An end at distance 0 closes on the axis. */
+ profile: readonly (readonly [number, number])[];
+ sides?: number;
+ /** How far round, in degrees. Default the whole way. */
+ arc?: number;
+ /** The outline is a loop: a ring or a tyre, with a hole down the axis. */
+ closed?: boolean;
+ /** Segments between given points; 1 keeps them straight. */
+ curve?: number;
+ axis?: 'x' | 'y' | 'z';
+}
+
+export function lathe(mesh: PolyMesh, p: LatheParams): PolyMesh {
+ const sides = p.sides ?? 32;
+ const arc = p.arc ?? 360;
+ const closed = p.closed === true;
+ if (!Number.isInteger(sides) || sides < 3) throw new Error(`sides ${sides} must be a whole number of at least 3`);
+ if (arc <= 0 || arc > 360) throw new Error(`arc ${arc} must be more than 0 and at most 360 degrees`);
+ if (p.profile.length < 2) throw new Error(`a profile needs at least 2 points, not ${p.profile.length}`);
+ if (p.profile.some((q) => q[0] < 0)) throw new Error('a profile point cannot have a negative distance from the axis; [distance, height]');
+
+ const outline = withoutRepeats(curveThrough(p.profile, p.curve ?? 1, closed), closed).map((q) => [Math.max(q[0]!, 0), q[1]!] as const);
+ const count = outline.length;
+ if (count < 2) throw new Error('the profile has no length');
+ const onAxis = outline.map((q) => q[0] < EPS);
+ const whole = arc >= 360;
+ if (closed && onAxis.some(Boolean)) throw new Error('a closed profile cannot touch the axis: it would pinch there');
+ if (onAxis.slice(1, -1).some(Boolean)) {
+ throw new Error('only the two ends of a profile can touch the axis: a point on it mid-way pinches the surface to nothing. Build two lathes, or move it off');
+ }
+ if (count === 2 && onAxis[0] && onAxis[1]) throw new Error('the profile lies along the axis, so turning it makes nothing');
+
+ const steps = whole ? sides : sides + 1;
+ const positions: Vec3[] = [];
+ const ringIndex: number[][] = outline.map(([r, h], i) => {
+ if (onAxis[i]) {
+ positions.push([0, h, 0]);
+ return Array.from({ length: steps }, () => positions.length - 1);
+ }
+ return Array.from({ length: steps }, (_, s) => {
+ const t = (s / sides) * arc * DEG;
+ positions.push([Math.sin(t) * r, h, Math.cos(t) * r]);
+ return positions.length - 1;
+ });
+ });
+
+ const loops: number[][] = [];
+ const rows = closed ? count : count - 1;
+ for (let i = 0; i < rows; i++) {
+ const lower = ringIndex[i]!, upper = ringIndex[(i + 1) % count]!;
+ for (let s = 0; s < sides; s++) {
+ const next = whole ? (s + 1) % sides : s + 1;
+ const loop = [lower[s]!, lower[next]!, upper[next]!, upper[s]!].filter((v, n, all) => v !== all[(n + 1) % all.length]);
+ if (loop.length >= 3) loops.push(loop);
+ }
+ }
+ if (whole) {
+ // An open outline with an end off the axis has a disc there.
+ if (!closed) {
+ if (!onAxis[0]) loops.push([...ringIndex[0]!]);
+ if (!onAxis[count - 1]) loops.push([...ringIndex[count - 1]!]);
+ }
+ } else {
+ // A slice: wedge-shaped ends where the outline stops off the axis, and two flat cut faces, all closing along one axis line.
+ const axisAt = (i: number): number => {
+ if (onAxis[i]) return ringIndex[i]![0]!;
+ positions.push([0, outline[i]![1], 0]);
+ return positions.length - 1;
+ };
+ const firstAxis = closed ? -1 : axisAt(0), lastAxis = closed ? -1 : axisAt(count - 1);
+ if (!closed) {
+ if (!onAxis[0]) loops.push([firstAxis, ...ringIndex[0]!]);
+ if (!onAxis[count - 1]) loops.push([lastAxis, ...ringIndex[count - 1]!]);
+ }
+ const cut = (s: number): number[] => {
+ const loop = outline.map((_, i) => ringIndex[i]![s]!);
+ if (closed) return loop;
+ if (!onAxis[count - 1]) loop.push(lastAxis);
+ if (!onAxis[0]) loop.push(firstAxis);
+ return loop;
+ };
+ loops.push(cut(0), cut(sides));
+ }
+
+ const moved = rotateAxis(positions, p.axis ?? 'y');
+ return append(mesh, moved, facingOut(moved, loops), p);
+}
+
+const rotateAxis = (positions: readonly Vec3[], axis: 'x' | 'y' | 'z'): Vec3[] => {
+ if (axis === 'y') return [...positions];
+ // Rotations, not swaps: a swap would mirror the solid and turn it inside out.
+ return axis === 'x' ? positions.map((q) => [q[1], -q[0], q[2]] as Vec3) : positions.map((q) => [q[0], -q[2], q[1]] as Vec3);
+};
+
+// ---- Loft ------------------------------------------------------------------------
+
+export interface LoftSection {
+ /** Where its centre is. */
+ at?: Vec3;
+ /** A circle. */
+ radius?: number;
+ /** An ellipse: across, and up. */
+ radii?: readonly [number, number];
+ /** A rectangle: across, and up. */
+ size?: readonly [number, number];
+ /** Any outline in the section's plane: [across, up]. */
+ points?: readonly (readonly [number, number])[];
+ /** Turns it about the path, in degrees. */
+ twist?: number;
+ /** Scales it. For a pipe's taper from one `section`. */
+ scale?: number;
+}
+
+export interface LoftParams extends Placed {
+ /** Each with its own `at` and shape. */
+ sections?: readonly LoftSection[];
+ /** Or one shape carried along these points. */
+ path?: readonly Vec3[];
+ section?: LoftSection;
+ /** With `path`: a scale for each of its points. */
+ scales?: readonly number[];
+ /** The points round a section where shapes differ or are round. */
+ sides?: number;
+ /** Joins the last section back to the first: a ring, a tyre. */
+ closed?: boolean;
+ /** Segments between sections; 1 keeps them straight. */
+ curve?: number;
+}
+
+function outlineOf(s: LoftSection, sides: number): { ring: [number, number][]; corners: boolean } {
+ const given = [s.radius !== undefined, s.radii !== undefined, s.size !== undefined, s.points !== undefined].filter(Boolean).length;
+ if (given !== 1) throw new Error(`a section needs exactly one of radius, radii, size, points; this one has ${given}`);
+ let ring: [number, number][];
+ let corners = false;
+ if (s.radius !== undefined || s.radii !== undefined) {
+ const [a, b] = s.radii ?? [s.radius!, s.radius!];
+ if (a <= 0 || b <= 0) throw new Error('a section\'s radius must be positive');
+ ring = Array.from({ length: sides }, (_, i) => {
+ const t = (i / sides) * Math.PI * 2;
+ return [Math.cos(t) * a, Math.sin(t) * b] as [number, number];
+ });
+ } else if (s.size) {
+ const [w, h] = [s.size[0] / 2, s.size[1] / 2];
+ if (w <= 0 || h <= 0) throw new Error('a section\'s size must be positive');
+ ring = [[w, -h], [w, h], [-w, h], [-w, -h]];
+ corners = true;
+ } else {
+ ring = s.points!.map((q) => [q[0], q[1]]);
+ corners = true;
+ if (ring.length < 3) throw new Error(`a section's outline needs at least 3 points, not ${ring.length}`);
+ }
+ // Counter-clockwise, whichever way it was walked: the walls join corner to corner, so all sections must agree.
+ let area = 0;
+ ring.forEach((a, i) => {
+ const b = ring[(i + 1) % ring.length]!;
+ area += a[0] * b[1] - b[0] * a[1];
+ });
+ if (Math.abs(area) < EPS) throw new Error('a section\'s outline encloses no area');
+ if (area < 0) ring.reverse();
+ const k = s.scale ?? 1;
+ if (k <= 0) throw new Error(`a section's scale ${k} must be positive`);
+ const twist = (s.twist ?? 0) * DEG;
+ const [c, n] = [Math.cos(twist), Math.sin(twist)];
+ return { ring: ring.map(([u, v]) => [(c * u - n * v) * k, (n * u + c * v) * k]), corners };
+}
+
+/** @p ring walked at even steps, @p count of them, so differing shapes can be joined corner to corner. */
+function resample(ring: readonly [number, number][], count: number): [number, number][] {
+ if (ring.length === count) return [...ring];
+ const lens = ring.map((a, i) => Math.hypot(ring[(i + 1) % ring.length]![0] - a[0], ring[(i + 1) % ring.length]![1] - a[1]));
+ const total = lens.reduce((a, b) => a + b, 0);
+ const out: [number, number][] = [];
+ let edge = 0, walked = 0;
+ for (let i = 0; i < count; i++) {
+ const want = (i / count) * total;
+ while (edge < ring.length - 1 && walked + lens[edge]! < want) { walked += lens[edge]!; edge++; }
+ const t = lens[edge]! > 0 ? (want - walked) / lens[edge]! : 0;
+ const [a, b] = [ring[edge]!, ring[(edge + 1) % ring.length]!];
+ out.push([a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t]);
+ }
+ return out;
+}
+
+/** The turn of @p ring that lies closest to @p previous: without it, two shapes of different starts join with a wring in them. */
+function aligned(ring: [number, number][], previous: readonly [number, number][]): [number, number][] {
+ let best = 0, bestCost = Infinity;
+ for (let shift = 0; shift < ring.length; shift++) {
+ let cost = 0;
+ for (let i = 0; i < ring.length; i++) {
+ const q = ring[(i + shift) % ring.length]!, r = previous[i]!;
+ cost += (q[0] - r[0]) ** 2 + (q[1] - r[1]) ** 2;
+ }
+ if (cost < bestCost - EPS) { bestCost = cost; best = shift; }
+ }
+ return ring.map((_, i) => ring[(i + best) % ring.length]!);
+}
+
+export function loft(mesh: PolyMesh, p: LoftParams): PolyMesh {
+ const closed = p.closed === true;
+ const sides = p.sides ?? 24;
+ if (!Number.isInteger(sides) || sides < 3) throw new Error(`sides ${sides} must be a whole number of at least 3`);
+ if (p.sections && p.path) throw new Error('give `sections`, or `path` with `section`, not both');
+ if (p.path && !p.section) throw new Error('`path` carries a `section`: give one');
+ if (p.scales && (!p.path || p.scales.length !== p.path.length)) throw new Error('`scales` goes with `path`, one for each of its points');
+
+ const sections: LoftSection[] = p.sections
+ ? p.sections.map((s) => ({ ...s }))
+ : (p.path ?? []).map((at, i) => ({ ...p.section!, at, scale: (p.section!.scale ?? 1) * (p.scales?.[i] ?? 1) }));
+ if (sections.length < 2) throw new Error(`a loft needs at least 2 sections, not ${sections.length}`);
+ if (closed && sections.length < 3) throw new Error('a closed loft needs at least 3 sections');
+
+ const centres = sections.map((s, i) => {
+ if (!s.at) throw new Error(`section ${i} has no \`at\``);
+ return s.at;
+ });
+ centres.forEach((c, i) => {
+ const next = centres[i + 1];
+ if (next && length(sub(next, c)) < EPS) throw new Error(`sections ${i} and ${i + 1} are at the same place, so there is no way along the path between them`);
+ });
+
+ // One corner count for all: as given if every section agrees, else walked evenly.
+ const shapes = sections.map((s, i) => {
+ try {
+ return outlineOf(s, sides);
+ } catch (e) {
+ throw new Error(`section ${i}: ${(e as Error).message}`);
+ }
+ });
+ const counts = new Set(shapes.map((s) => s.ring.length));
+ const corners = counts.size === 1 ? [...counts][0]! : sides;
+ let previous: [number, number][] | null = null;
+ const rings2d = shapes.map(({ ring }) => {
+ let r = resample(ring, corners);
+ if (previous && counts.size !== 1) r = aligned(r, previous);
+ previous = r;
+ return r;
+ });
+
+ // The frame is carried along the path rather than worked out afresh, so a bend does not spin the section about it.
+ const count = sections.length;
+ const tangentAt = (i: number): Vec3 => {
+ const before = closed ? centres[(i + count - 1) % count]! : centres[Math.max(0, i - 1)]!;
+ const after = closed ? centres[(i + 1) % count]! : centres[Math.min(count - 1, i + 1)]!;
+ return normalize(sub(after, before));
+ };
+ const first = tangentAt(0);
+ let right = normalize(cross(Math.abs(first[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0], first));
+ if (Math.abs(first[1]) > 0.99) right = normalize(cross([0, 0, -1], first));
+ const world: number[][][] = sections.map((_, i) => {
+ const t = tangentAt(i);
+ right = normalize(sub(right, scale(t, dot(right, t))));
+ const up = cross(t, right);
+ return rings2d[i]!.map(([u, v]) => [...add(add(centres[i]!, scale(right, u)), scale(up, v))]);
+ });
+
+ // Curved column by column: each corner runs its own smooth line through its sections.
+ const steps = p.curve ?? 1;
+ const columns = Array.from({ length: corners }, (_, c) => curveThrough(world.map((ring) => ring[c]!), steps, closed));
+ const rows = columns[0]!.length;
+ const positions: Vec3[] = [];
+ for (let r = 0; r < rows; r++) for (let c = 0; c < corners; c++) positions.push(columns[c]![r] as unknown as Vec3);
+ const index = (r: number, c: number): number => r * corners + (c % corners);
+
+ const loops: number[][] = [];
+ const spans = closed ? rows : rows - 1;
+ for (let r = 0; r < spans; r++) {
+ const next = (r + 1) % rows;
+ for (let c = 0; c < corners; c++) loops.push([index(r, c), index(r, c + 1), index(next, c + 1), index(next, c)]);
+ }
+ if (!closed) {
+ loops.push(Array.from({ length: corners }, (_, c) => index(0, c)));
+ loops.push(Array.from({ length: corners }, (_, c) => index(rows - 1, c)));
+ }
+ return append(mesh, positions, facingOut(positions, loops), p);
+}
diff --git a/pipeline/tests/modeling-surfaces.test.ts b/pipeline/tests/modeling-surfaces.test.ts
new file mode 100644
index 000000000..5b8c87e1d
--- /dev/null
+++ b/pipeline/tests/modeling-surfaces.test.ts
@@ -0,0 +1,263 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/** Lathe and loft, held to the volume a shape must enclose and a surface that closes and faces out. */
+import { beforeAll, describe, expect, it } from 'vitest';
+import { bakeModel, prepareModeling, renderModelSheet, validateModelSource, type BakedModel, type ModelStep } from '../src/modeling';
+
+beforeAll(() => prepareModeling());
+
+const model = (...steps: ModelStep[]): BakedModel => bakeModel({ version: 1, steps });
+
+function volume(m: BakedModel): number {
+ let v = 0;
+ for (const { v: [a, b, c] } of m.triangles) {
+ const [p, q, r] = [m.poly.positions[a]!, m.poly.positions[b]!, m.poly.positions[c]!];
+ v += p[0] * (q[1] * r[2] - q[2] * r[1]) + p[1] * (q[2] * r[0] - q[0] * r[2]) + p[2] * (q[0] * r[1] - q[1] * r[0]);
+ }
+ return v / 6;
+}
+
+function sound(m: BakedModel): void {
+ expect(m.report.openEdges).toBe(0);
+ expect(m.report.nonManifoldEdges).toBe(0);
+ expect(m.report.flippedEdges).toBe(0);
+ expect(m.report.insideOutShells).toBe(0);
+ expect(m.report.degenerateFaces).toBe(0);
+ expect(m.report.warnings).toEqual([]);
+}
+
+/** The area of a regular n-gon of radius r: what a turned circle really encloses. */
+const ngon = (r: number, n: number): number => (n / 2) * r * r * Math.sin((2 * Math.PI) / n);
+
+describe('lathe', () => {
+ it('a straight outline off the axis is a cylinder with flat ends', () => {
+ const m = model({ op: 'lathe', profile: [[1, 0], [1, 2]], sides: 16 });
+ sound(m);
+ expect(volume(m)).toBeCloseTo(ngon(1, 16) * 2, 5);
+ expect(m.report.bounds.min[1]).toBe(0);
+ expect(m.report.bounds.max[1]).toBe(2);
+ });
+
+ it('an end on the axis closes to a point: a cone', () => {
+ const m = model({ op: 'lathe', profile: [[1, 0], [0, 3]], sides: 16 });
+ sound(m);
+ expect(volume(m)).toBeCloseTo((ngon(1, 16) * 3) / 3, 5);
+ });
+
+ it('both ends on the axis make a solid with no caps: a double cone', () => {
+ const m = model({ op: 'lathe', profile: [[0, 0], [1, 1], [0, 2]], sides: 16 });
+ sound(m);
+ expect(volume(m)).toBeCloseTo((ngon(1, 16) * 2) / 3, 5);
+ });
+
+ it('faces out whichever way the outline was walked', () => {
+ const up = model({ op: 'lathe', profile: [[1, 0], [1, 2]], sides: 16 });
+ const down = model({ op: 'lathe', profile: [[1, 2], [1, 0]], sides: 16 });
+ sound(down);
+ expect(volume(down)).toBeCloseTo(volume(up), 6);
+ });
+
+ it('a cup: up the outside and back down the inside holds only its walls', () => {
+ const m = model({ op: 'lathe', sides: 32, profile: [[0, 0], [1, 0], [1, 2], [0.9, 2], [0.9, 0.1], [0, 0.1]] });
+ sound(m);
+ const area = (r: number): number => ngon(r, 32);
+ expect(volume(m)).toBeCloseTo(area(1) * 2 - area(0.9) * 1.9, 4);
+ });
+
+ it('a closed outline is a ring, with a hole down the axis', () => {
+ const m = model({ op: 'lathe', closed: true, sides: 64, curve: 8, profile: [[1.3, 0], [1, 0.3], [0.7, 0], [1, -0.3]] });
+ sound(m);
+ expect(m.report.bounds.min[0]).toBeLessThan(-1.2);
+ expect(volume(m)).toBeGreaterThan(0);
+ // Nothing near the axis: it is a hole.
+ expect(Math.min(...m.poly.positions.map((p) => Math.hypot(p[0], p[2])))).toBeGreaterThan(0.6);
+ });
+
+ it('part of a turn closes its two cut faces', () => {
+ const half = model({ op: 'lathe', arc: 180, sides: 32, profile: [[1, 0], [1, 2]] });
+ sound(half);
+ expect(volume(half)).toBeCloseTo((32 / 2) * Math.sin(Math.PI / 32) * 2, 4);
+ });
+
+ it('part of a turn of a closed outline too', () => {
+ const m = model({ op: 'lathe', arc: 90, sides: 16, closed: true, profile: [[2, 0], [3, 0], [3, 1], [2, 1]] });
+ sound(m);
+ expect(volume(m)).toBeGreaterThan(0);
+ });
+
+ it('curve rounds through the given points, exactly', () => {
+ const profile: [number, number][] = [[0, 0], [1, 0.5], [0.4, 1.5], [0.6, 2.5], [0, 3]];
+ const m = model({ op: 'lathe', profile, curve: 8, sides: 32 });
+ sound(m);
+ for (const [r, h] of profile) {
+ const hit = m.poly.positions.some((p) => Math.abs(Math.hypot(p[0], p[2]) - r) < 1e-6 && Math.abs(p[1] - h) < 1e-6);
+ expect(hit, `[${r}, ${h}]`).toBe(true);
+ }
+ expect(m.report.faces).toBeGreaterThan(32 * 16);
+ });
+
+ it('a point given twice keeps a corner under curve', () => {
+ const sharp = model({ op: 'lathe', curve: 8, sides: 16, profile: [[0, 0], [1, 0], [1, 0], [1, 1], [0, 1]] });
+ sound(sharp);
+ // The curve stops at the corner rather than rounding it off: the point is on the surface, and the bottom stays flat.
+ expect(sharp.poly.positions.some((p) => Math.abs(Math.hypot(p[0], p[2]) - 1) < 1e-6 && Math.abs(p[1]) < 1e-6)).toBe(true);
+ expect(sharp.report.bounds.min[1]).toBeCloseTo(0, 5);
+ });
+
+ it('stands on any axis, without turning inside out', () => {
+ for (const axis of ['x', 'z']) {
+ const m = model({ op: 'lathe', profile: [[1, 0], [1, 2]], sides: 16, axis });
+ sound(m);
+ expect(volume(m)).toBeCloseTo(ngon(1, 16) * 2, 5);
+ }
+ expect(model({ op: 'lathe', profile: [[1, 0], [1, 2]], axis: 'x' }).report.bounds.size[0]).toBeCloseTo(2, 5);
+ expect(model({ op: 'lathe', profile: [[1, 0], [1, 2]], axis: 'z' }).report.bounds.size[2]).toBeCloseTo(2, 5);
+ });
+
+ it('shades a round wall smooth and keeps a rim hard', () => {
+ const m = model({ op: 'lathe', profile: [[1, 0], [1, 2]], sides: 32 });
+ expect(m.data.vertexCount).toBeLessThan(32 * 8 + 80);
+ });
+
+ it('refuses what it cannot turn, saying why', () => {
+ expect(() => model({ op: 'lathe', profile: [[1, 0]] })).toThrow(/at least 2 points/);
+ expect(() => model({ op: 'lathe', profile: [[-1, 0], [1, 1]] })).toThrow(/negative distance/);
+ expect(() => model({ op: 'lathe', profile: [[1, 0], [0, 1], [1, 2]] })).toThrow(/only the two ends .* can touch the axis/);
+ expect(() => model({ op: 'lathe', profile: [[0, 0], [0, 2]] })).toThrow(/along the axis/);
+ expect(() => model({ op: 'lathe', closed: true, profile: [[0, 0], [1, 0], [1, 1]] })).toThrow(/closed profile cannot touch/);
+ expect(() => model({ op: 'lathe', profile: [[1, 0], [1, 1]], arc: 400 })).toThrow(/arc 400/);
+ expect(() => validateModelSource({ steps: [{ op: 'lathe', profile: [[1, 0], [1, 1]], curv: 3 }] })).toThrow(/unknown field "curv"/);
+ });
+});
+
+describe('loft', () => {
+ it('two rectangles are a box, exactly', () => {
+ const m = model({ op: 'loft', sections: [{ at: [0, 0, 0], size: [2, 1] }, { at: [0, 0, 3], size: [2, 1] }] });
+ sound(m);
+ expect(volume(m)).toBeCloseTo(6, 6);
+ expect(m.report.faces).toBe(6);
+ });
+
+ it('a straight pipe holds its n-gon times its length, along any direction', () => {
+ for (const end of [[0, 3, 0], [3, 0, 0], [0, 0, 3], [2, 2, 1]] as const) {
+ const m = model({ op: 'loft', path: [[0, 0, 0], end as never], section: { radius: 0.5 }, sides: 24 });
+ sound(m);
+ expect(volume(m)).toBeCloseTo(ngon(0.5, 24) * Math.hypot(...end), 5);
+ }
+ });
+
+ it('a taper is a frustum', () => {
+ const m = model({ op: 'loft', path: [[0, 0, 0], [0, 2, 0]], section: { size: [2, 2] }, scales: [1, 0.5] });
+ sound(m);
+ expect(volume(m)).toBeCloseTo((2 * (4 + 1 + 2)) / 3, 5);
+ });
+
+ it('a section differing from the next is joined without a wring', () => {
+ const m = model({ op: 'loft', sides: 32, sections: [{ at: [0, 0, 0], radius: 1 }, { at: [0, 2, 0], size: [2, 2] }] });
+ sound(m);
+ // The walls run nearly straight up: a wrung join would have them lean far round the axis.
+ const pos = m.poly.positions;
+ for (const face of m.poly.faces.filter((f) => f.v.length === 4)) {
+ for (let i = 0; i < 4; i++) {
+ const a = pos[face.v[i]!]!, b = pos[face.v[(i + 1) % 4]!]!;
+ if (Math.abs(a[1] - b[1]) > 1) expect(Math.hypot(a[0] - b[0], a[2] - b[2])).toBeLessThan(0.5);
+ }
+ }
+ });
+
+ it('a pipe round a bend closes and keeps its section', () => {
+ const m = model({ op: 'loft', path: [[0, 0, 0], [0, 2, 0], [2, 2, 0], [2, 2, 2]], section: { radius: 0.2 }, curve: 8, sides: 16 });
+ sound(m);
+ expect(m.report.shells).toBe(1);
+ });
+
+ it('a frame carried along a path does not spin the section: a ribbon stays a ribbon', () => {
+ const m = model({ op: 'loft', path: [[0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3]], section: { size: [2, 0.2] } });
+ expect(m.report.bounds.size[0]).toBeCloseTo(2, 5);
+ expect(m.report.bounds.size[1]).toBeCloseTo(0.2, 5);
+ });
+
+ it('twist turns a section about the path', () => {
+ const m = model({ op: 'loft', sections: [{ at: [0, 0, 0], size: [2, 0.2] }, { at: [0, 0, 1], size: [2, 0.2], twist: 90 }] });
+ sound(m);
+ expect(m.report.bounds.size[0]).toBeCloseTo(2, 5);
+ expect(m.report.bounds.size[1]).toBeCloseTo(2, 5);
+ });
+
+ it('closed joins the end to the start: a ring, with no caps', () => {
+ const path: [number, number, number][] = Array.from({ length: 8 }, (_, i) => [Math.cos((i * Math.PI) / 4) * 2, 0, Math.sin((i * Math.PI) / 4) * 2]);
+ const m = model({ op: 'loft', path, section: { radius: 0.3 }, closed: true, curve: 4, sides: 16 });
+ sound(m);
+ expect(m.report.faces).toBe(8 * 4 * 16);
+ expect(Math.abs(volume(m) - 2 * Math.PI ** 2 * 2 * 0.3 ** 2)).toBeLessThan(0.15);
+ });
+
+ it('any outline can be carried, walked either way', () => {
+ const l: [number, number][] = [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]];
+ const m = model({ op: 'loft', path: [[0, 0, 0], [0, 0, 2]], section: { points: l } });
+ sound(m);
+ expect(volume(m)).toBeCloseTo(6, 5);
+ const back = model({ op: 'loft', path: [[0, 0, 0], [0, 0, 2]], section: { points: [...l].reverse() } });
+ sound(back);
+ expect(volume(back)).toBeCloseTo(6, 5);
+ });
+
+ it('curve passes through the sections it was given', () => {
+ const m = model({ op: 'loft', sections: [{ at: [0, 0, 0], radius: 1 }, { at: [0, 1, 0], radius: 0.4 }, { at: [0, 2, 0], radius: 0.8 }], curve: 6, sides: 16 });
+ sound(m);
+ const at = (h: number): number => Math.max(...m.poly.positions.filter((p) => Math.abs(p[1] - h) < 1e-6).map((p) => Math.hypot(p[0], p[2])));
+ expect(at(1)).toBeCloseTo(0.4, 4);
+ expect(at(2)).toBeCloseTo(0.8, 4);
+ });
+
+ it('a later boolean can cut what it made, and a uv can wrap it', () => {
+ const m = model(
+ { op: 'loft', path: [[0, 0, 0], [0, 3, 0]], section: { radius: 1 }, sides: 24, tag: 'tube' },
+ { op: 'box', size: [0.5, 0.5, 4], at: [0, 1.5, 0], tag: 'cut' },
+ { op: 'boolean', operation: 'subtract', with: 'cut', from: 'tube' },
+ { op: 'uv', faces: 'tube', mode: 'cylinder', axis: 'y' },
+ );
+ expect(m.report.openEdges).toBe(0);
+ expect(volume(m)).toBeLessThan(ngon(1, 24) * 3);
+ });
+
+ it('a silhouette shows the bend it was given', () => {
+ const panel = 96;
+ const m = model({ op: 'loft', path: [[-2, 0, 0], [0, 2, 0], [2, 0, 0]], section: { radius: 0.2 }, curve: 8 });
+ const s = renderModelSheet(m, ['front'], panel);
+ const dark = (x: number, y: number): boolean => s.rgba[((panel + 1 + y) * s.width + x) * 4]! < 60;
+ // An arch: filled over the middle at the top, empty under it.
+ let top = -1;
+ for (let y = 0; y < panel && top < 0; y++) if (dark(panel >> 1, y)) top = y;
+ expect(top).toBeGreaterThan(0);
+ expect(dark(panel >> 1, panel - 25)).toBe(false);
+ });
+
+ it('the sheet draws hard edges and leaves a curved wall clean, with every polygon on request', () => {
+ const panel = 128;
+ const m = model({ op: 'lathe', profile: [[1, 0], [1, 2]], sides: 48 }, { op: 'slice', axis: 'y', at: 1 });
+ const lines = (wire: boolean): number => {
+ const s = renderModelSheet(m, ['front'], panel, undefined, wire);
+ let n = 0;
+ for (let i = 0; i < panel * panel; i++) {
+ const y = Math.floor(i / panel), x = i % panel;
+ if (s.rgba[(y * s.width + x) * 4]! < 45) n++;
+ }
+ return n;
+ };
+ expect(lines(true)).toBeGreaterThan(lines(false) * 3);
+ });
+
+ it('refuses what it cannot join, saying why', () => {
+ expect(() => model({ op: 'loft', sections: [{ at: [0, 0, 0], radius: 1 }] })).toThrow(/at least 2 sections/);
+ expect(() => model({ op: 'loft' })).toThrow(/at least 2 sections/);
+ expect(() => model({ op: 'loft', sections: [{ radius: 1 }, { at: [0, 1, 0], radius: 1 }] })).toThrow(/section 0 has no `at`/);
+ expect(() => model({ op: 'loft', sections: [{ at: [0, 0, 0] }, { at: [0, 1, 0], radius: 1 }] })).toThrow(/section 0: .*exactly one of radius/);
+ expect(() => model({ op: 'loft', sections: [{ at: [0, 0, 0], radius: 1, size: [1, 1] }, { at: [0, 1, 0], radius: 1 }] })).toThrow(/this one has 2/);
+ expect(() => model({ op: 'loft', sections: [{ at: [0, 1, 0], radius: 1 }, { at: [0, 1, 0], radius: 1 }] })).toThrow(/at the same place/);
+ expect(() => model({ op: 'loft', path: [[0, 0, 0], [0, 1, 0]] })).toThrow(/`path` carries a `section`/);
+ expect(() => model({ op: 'loft', path: [[0, 0, 0], [0, 1, 0]], section: { radius: 1 }, scales: [1] })).toThrow(/one for each/);
+ expect(() => model({ op: 'loft', closed: true, sections: [{ at: [0, 0, 0], radius: 1 }, { at: [0, 1, 0], radius: 1 }] })).toThrow(/closed loft needs at least 3/);
+ expect(() => validateModelSource({ steps: [{ op: 'loft', sections: [{ at: [0, 0, 0], radus: 1 }] }] })).toThrow(/\[0\] has an unknown field "radus"; a section takes/);
+ });
+});
diff --git a/pipeline/tests/modeling.test.ts b/pipeline/tests/modeling.test.ts
index 0b7f632bd..26235cb7c 100644
--- a/pipeline/tests/modeling.test.ts
+++ b/pipeline/tests/modeling.test.ts
@@ -299,7 +299,7 @@ describe('the source format', () => {
});
it('refuses an unknown op, listing them', () => {
- expect(() => validateModelSource({ steps: [{ op: 'lathe' }] })).toThrow(/unknown op "lathe"; there are box/);
+ expect(() => validateModelSource({ steps: [{ op: 'sculpt' }] })).toThrow(/unknown op "sculpt"; there are box/);
});
it('refuses a missing required field and a wrong type', () => {
@@ -359,6 +359,22 @@ describe('edits', () => {
});
});
+describe('winding', () => {
+ it('the report names faces wound against their neighbours, which a volume alone can miss', () => {
+ const m = model(cube);
+ expect(m.report.flippedEdges).toBe(0);
+ const every = [
+ model(cube, { op: 'bevel', edges: 'all', width: 0.1 }),
+ model(cube, { op: 'inset', faces: '+z', amount: 0.2 }, { op: 'extrude', faces: '+z', distance: 0.1 }),
+ model({ op: 'box', size: 1, at: [2, 0, 0] }, { op: 'mirror', axis: 'x' }),
+ model({ op: 'box', size: 1, at: [0.5, 0, 0] }, { op: 'mirror', axis: 'x' }, { op: 'weld' }),
+ model({ op: 'cylinder', radius: 1, height: 1 }, { op: 'cone', radius: 1, height: 1, at: [3, 0, 0] }, { op: 'sphere', radius: 1, at: [6, 0, 0] }),
+ model({ op: 'prism', points: [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]], height: 1 }),
+ ];
+ for (const each of every) expect(each.report.flippedEdges).toBe(0);
+ });
+});
+
describe('the bake', () => {
const channel = (m: BakedModel, semantic: number) => m.data.channels.find((c) => c.semantic === semantic);
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 59aa34e40..deef83c4c 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -3866,6 +3866,10 @@ export const NOTED = {
{"note":"A sea seen from above is no longer scored with straight lines."},
"feat(mcp): an agent builds a 3D model in the editor from steps, changes it by one number, and sees every side of it":
{"note":"AI agents can build 3D models in the editor from steps."},
+ "feat(modeling): lathe and loft make curved solids from a few points, so an agent can build vases, pipes, handles and hulls":
+ {"note":"AI agents can build 3D models in the editor from steps."},
+ "feat(mcp): model_write turns outlines and joins sections into curved solids":
+ {"note":"AI agents can build 3D models in the editor from steps."},
"feat(modeling): a boolean step cuts real holes and a uv step aims textures, with an atlas for a texture painted for one model":
{"note":"AI agents can build 3D models in the editor from steps."},
"feat(mcp): model_write cuts holes and lays out textures":