Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add loop cut and extrusion along normals

Nguyen Xuan An88913a78e20e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d90618dc..df4a1824 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,7 @@
- Add `67js/addons/mesh`, a polygon mesh core for agent modeling: compact `MeshData` with attributes on point, edge, face and corner domains, a half-edge `EditMesh` with typed-array disk and radial cycles, `validateTopology`, conversion from renderer geometry with welding, quads and axis face tags, hard-edge corner normals, n-gon triangulation, render extraction and `lintMesh`
- Add semantic face selection and mesh edits (extrude region and individual, inset region and individual, delete, flip normals, translate with proportional falloff, merge by distance, tag) that tag the faces they create
- Add the recipe geometry type `mesh` (a base shape plus a replayable edit log) and the `mesh_edit` MCP tool, which appends or replaces edits atomically and reports each edit's result
+- Add `loop_cut`: edge rings across quads picked by an edge rule (including `along` a direction), evenly spaced cuts or one cut at a factor, band tags, T-junction-free neighbours and interpolated UVs; and `alongNormals` for `extrude_face_region`, which extrudes rings and curved bands as one joined region
- Add edge `bevel` as a mesh edit and stack node: rim, angle, region-border or all-edge selection, width, segments, profile and overlap clamping, with sliding corners and smooth triangular patches where three rounded edges meet
- Add mesh booleans (union, difference, intersect) through Manifold WebAssembly as the `boolean` edit with an inline primitive cutter, tag transfer and polygon rebuilding; `manifold-3d` is an optional peer dependency, which the MCP runtime serves to its preview page when installed
- Add mirror, array and solidify as mesh edits and as a non-destructive modifier stack evaluated after the edits, with every prefix cached, and the `mesh_stack` MCP tool to set the stack or apply its first nodes into the edit log
diff --git a/docs/mesh.md b/docs/mesh.md
index 8a707f15..ca2cf776 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -124,7 +124,7 @@ Edits (names follow Blender's `bmesh.ops` where they match):
| Op | Fields | Creates tags |
| --- | --- | --- |
-| `extrude_face_region` | `select`, `offset`, optional `direction`, `name` | `<name>.cap`, `<name>.side` |
+| `extrude_face_region` | `select`, `offset`, optional `direction` or `alongNormals`, `name` | `<name>.cap`, `<name>.side` |
| `extrude_individual` | same | same, per face |
| `inset_region` | `select`, `thickness`, optional `depth`, `name` | `<name>.cap`, `<name>.rim` |
| `inset_individual` | same | same, per face |
@@ -137,6 +137,8 @@ Edits (names follow Blender's `bmesh.ops` where they match):
- `select` defaults to every face, except for `delete` and `tag`.
- `name` defaults to `<op>-<index>`, for example `extrude-1`.
+- With `alongNormals: true`, each vertex of the region moves along its own normal instead, so a ring of faces around
+ a cylinder grows outward as one joined hoop (Blender's Extrude Faces Along Normals).
- Extrusions move each group of edge-connected faces along that group's own average normal. Faces in one group
that face opposite ways (the four sides of a box) cancel out; use the `_individual` op or pass `direction`.
- Caps keep their earlier tags; side and rim faces start without tags.
@@ -224,7 +226,28 @@ raised centre. The quadratic profile is close to, not exactly, a circular arc, s
differently from Blender's. Edges between strip segments render smooth when the bend per segment is under the mesh's
`smoothAngle`; with 2 segments on a right angle (45 degrees each), raise `smoothAngle` or use 3 or more segments.
-Loop cut is planned next.
+### Loop cut
+
+`loop_cut` adds loops across rings of quads, as Blender's Loop Cut:
+
+| Field | Meaning |
+| --- | --- |
+| `edges` | Edge rule picking the ring to cut across: `{ "along": [x, y, z], "maxAngle": 10 }` picks edges parallel to a direction (`along: [0, 1, 0]` cuts around a box horizontally), or `between`, `angle`, `boundaryOf`, `all` as for bevel |
+| `cuts` | 1 to 16 loops per ring, evenly spaced |
+| `factor` | With one cut, its position from each ring's low side, strictly between 0 and 1 (default 0.5) |
+
+From each selected edge the ring is walked across quads to the opposite edge, until it closes or meets a face that is
+not a quad. Every ring edge is split at the same fractions from the ring's low side (the end of the first seed edge
+with the lower coordinate along it), and every quad in the ring is split into bands tagged `<name>.band-0` (low side)
+to `<name>.band-<cuts>`; bands keep the quad's other tags. Faces beside an open ring get the new points on their
+shared edges, so no T-junctions appear. Corner UVs and colours are interpolated at the new points. Rings that cross
+each other in one edit are refused; cut them in separate edits. The result reports `rings`, `closedRings` and
+`splitEdges`.
+
+A typical sequence: `loop_cut` with `cuts: 2`, then `extrude_individual` or `extrude_face_region` with
+`alongNormals` on `<name>.band-1` to raise a belt around the middle.
+
+Knife and bisect are planned next.
## MCP
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index b32bb04e..9d129be5 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -125,7 +125,7 @@ function primitiveGeometries(identified) {
const selectRule = z.record(z.string(), z.unknown()).describe('Face selection rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10} (degrees), {"inside":{"min":[x,y,z],"max":[x,y,z]}} (face centroids), {"faces":[indices]}, {"and":[rules]}, {"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}. Tags come from the base (top, bottom, side, left, right, front, back) and from earlier edits (<name>.cap, <name>.side, <name>.rim, or a tag op).');
const editName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).optional().describe('Prefix for the tags this edit creates. Defaults to <op>-<index>.');
const meshEdit = z.discriminatedUnion('op', [
- z.strictObject({ op: z.literal('extrude_face_region'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each connected region\'s average normal (negative pushes in).'), direction: vector3.optional().describe('Move along this direction instead of the normal.') }),
+ z.strictObject({ op: z.literal('extrude_face_region'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each connected region\'s average normal (negative pushes in).'), direction: vector3.optional().describe('Move along this direction instead of the normal.'), alongNormals: z.boolean().optional().describe('Move each vertex along its own normal instead, keeping the region joined: use for rings and curved bands.') }),
z.strictObject({ op: z.literal('extrude_individual'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each face\'s own normal.'), direction: vector3.optional() }),
z.strictObject({ op: z.literal('inset_region'), select: selectRule.optional(), name: editName, thickness: finite.describe('Rim width, positive.'), depth: finite.optional().describe('Move the inner faces along the normal afterwards.') }),
z.strictObject({ op: z.literal('inset_individual'), select: selectRule.optional(), name: editName, thickness: finite, depth: finite.optional() }),
@@ -133,6 +133,12 @@ const meshEdit = z.discriminatedUnion('op', [
z.strictObject({ op: z.literal('flip_normals'), select: selectRule.optional() }),
z.strictObject({ op: z.literal('translate'), select: selectRule.optional(), offset: vector3, falloff: z.strictObject({ radius: finite, curve: z.enum(['smooth', 'sphere', 'root', 'sharp', 'linear', 'constant', 'inverseSquare']).optional(), connected: z.boolean().optional().describe('Measure distance along edges instead of straight lines.') }).optional() }),
z.strictObject({ op: z.literal('merge_by_distance'), distance: finite.optional() }),
+ z.strictObject({
+ op: z.literal('loop_cut'), name: editName,
+ edges: z.record(z.string(), z.unknown()).describe('Edge rule that picks the ring to cut across, usually {"along":[x,y,z]} for edges parallel to a direction: {"along":[0,1,0]} cuts around a box horizontally. Also between, angle, boundaryOf or all.'),
+ cuts: z.number().int().min(1).max(16).optional().describe('New loops per ring, evenly spaced. Defaults to 1.'),
+ factor: bounded(0, 1).optional().describe('Single cut only: position from the low side of each ring edge. Defaults to 0.5.'),
+ }).describe('Loop cut across quads. Bands between cuts get <name>.band-0 (low side) to <name>.band-<cuts>.'),
z.strictObject({ op: z.literal('tag'), select: selectRule, name: z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).describe('Tag to add to the selected faces.') }),
z.strictObject({
op: z.literal('boolean'), name: editName,
@@ -286,7 +292,7 @@ export function createAgentMcpServer(runtime, { version = packageMetadata.versio
register('scene_create_asset', 'Create the active scene from a catalog GLB and editable asset recipe. Preserves supported maps, skins, morphs and clips. Dispose the existing scene first.', z.strictObject({ recipe: assetRecipe }), { ...edit, destructiveHint: false }, async argumentsValue => jsonResult(await runtime.createAsset(argumentsValue)));
register('scene_inspect', 'Read revision, counts and selected nodes. Bounds describe authored geometry rather than shader displacement.', z.strictObject({ ...sessionFields, ids: z.array(identifier).max(4096).optional().describe('Selected node IDs. Omit to inspect scene order.'), kind: z.enum(['meshes', 'hierarchy']).optional().describe('Imported assets only: hierarchy exposes stable source-node IDs and joints.'), offset: z.number().int().min(0).max(4096).optional().describe('Imported assets only: pagination offset.'), limit: z.number().int().min(1).max(4096).optional().describe('Maximum returned node records. Defaults to 64.'), includeBounds: z.boolean().optional().describe('Include world geometry bounds. Defaults to false.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspect(argumentsValue)));
register('mesh_inspect', 'Check recipe geometries as polygon meshes: vertex, edge and face counts, triangles/quads/n-gons, connected and closed parts, face tags (top, bottom, side, left, right, front, back), bounds, and lint problems (non-manifold, inconsistent winding, inverted, degenerate, open, loose) with a suggested fix each. Procedural scenes only. Read-only and cached per geometry.', z.strictObject({ ...sessionFields, geometries: z.array(identifier).min(1).max(16).optional().describe('Geometry IDs to check. Omit to check the first 16 geometries.') }), readOnly, async argumentsValue => jsonResult(await runtime.inspectMeshes(argumentsValue)));
- register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, bevel, mirror, array, solidify, and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));
+ register('mesh_edit', 'Append edits to a recipe mesh geometry (or replace its edit log), atomically like scene_apply: extrude, inset, delete, flip, translate with proportional falloff, merge by distance, tag, loop cut, bevel, mirror, array, solidify, and booleans (union, difference, intersect) with a primitive cutter. Edits that select no faces or break limits fail without changing the scene. Returns the new revision, render status and the mesh report with per-edit results (faces selected, tags created, size after).', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), edits: meshEdits.min(1), replace: z.boolean().optional().describe('Replace the whole edit log instead of appending.') }), edit, async argumentsValue => jsonResult(await runtime.editMesh(argumentsValue)));
register('mesh_stack', 'Set the non-destructive modifier stack of a recipe mesh geometry (mirror, array, solidify, bevel), evaluated after its edits with each prefix cached, so changing a late node is cheap. apply: n moves the first n nodes into the edit log, as Blender\'s Apply modifier. Atomic like scene_apply. Returns the revision, render status and mesh report with per-node results.', z.strictObject({ ...sessionFields, expectedRevision, geometry: identifier.describe('ID of a geometry with type mesh.'), stack: meshStack.optional().describe('The whole new stack. Omit to keep the current stack (for example with apply).'), apply: z.number().int().min(0).max(16).optional() }), edit, async argumentsValue => jsonResult(await runtime.setMeshStack(argumentsValue)));
register('scene_apply', 'Atomically edit transforms, look, camera or materials. Procedural scenes support membership and set-motion authoring. Imported assets support set-root, set-asset-node, set-motion and absolute set-animation sampling. Successful batches increment revision once.', z.strictObject({ ...sessionFields, expectedRevision, operations: z.array(operation).min(1).max(256).describe('Node/material/camera/root/animation commands use flat fields. Motion, look patches and add commands contain nested records. Backend validates each scene mode before publication.') }), edit, async argumentsValue => jsonResult(await runtime.apply(argumentsValue)));
register('scene_look', 'Render the active scene as a bounded PNG. Optional authored motionTime seeks without changing revision; null restores the authored base pose. Omit to retain the last preview pose.', z.strictObject({ ...sessionFields, motionTime: z.number().min(0).max(3600).nullable().optional(), width: z.number().int().min(64).max(1024).default(768).describe('PNG width in pixels.'), height: z.number().int().min(64).max(1024).default(512).describe('PNG height in pixels.') }), readOnly, async argumentsValue => {
diff --git a/src/mesh-bevel.js b/src/mesh-bevel.js
index 434a55de..b9a0352e 100644
--- a/src/mesh-bevel.js
+++ b/src/mesh-bevel.js
@@ -17,6 +17,7 @@ import { MeshBuilder } from './mesh-stack.js';
* { "between": [faceRule, faceRule] } edges shared by a face matching the first rule and one matching the second
* { "angle": 30 } edges whose two faces bend by at least this many degrees
* { "boundaryOf": faceRule } edges between a matching face and a non-matching one
+ * { "along": [x, y, z], "maxAngle": 10 } edges parallel to a direction (either way) within maxAngle degrees
* { "all": true } every edge with two faces
* Returns a Uint8Array over MeshData edges.
*/
@@ -25,7 +26,7 @@ export function selectEdges(mesh, rule, table) {
const keys = Object.keys(rule);
const mask = new Uint8Array(mesh.edgeCount);
const facesOf = edge => table.faces[edge];
- if (keys.length !== 1) throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, all.');
+ if (keys.length !== 1 && rule.along === undefined) throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, all.');
if (rule.all === true) {
for (let edge = 0; edge < mesh.edgeCount; edge++) mask[edge] = facesOf(edge).length === 2 ? 1 : 0;
return mask;
@@ -43,6 +44,27 @@ export function selectEdges(mesh, rule, table) {
}
return mask;
}
+ if (rule.along !== undefined) {
+ const extra = keys.filter(key => key !== 'along' && key !== 'maxAngle');
+ if (extra.length) throw new TypeError(`Edge rule along does not take ${extra.join(', ')}.`);
+ if (!Array.isArray(rule.along) || rule.along.length !== 3 || !rule.along.every(Number.isFinite)) throw new TypeError('along needs a direction [x, y, z].');
+ const direction = normalize(rule.along);
+ if (length(direction) === 0) throw new RangeError('along cannot be zero.');
+ const maxAngle = rule.maxAngle ?? 10;
+ if (!Number.isFinite(maxAngle) || maxAngle < 0 || maxAngle > 90) throw new RangeError('maxAngle is degrees from 0 to 90.');
+ const limit = Math.cos(maxAngle * Math.PI / 180) - 1e-9;
+ for (let edge = 0; edge < mesh.edgeCount; edge++) {
+ const first = mesh.edgeVertices[edge * 2] * 3;
+ const second = mesh.edgeVertices[edge * 2 + 1] * 3;
+ const vector = normalize([
+ mesh.positions[second] - mesh.positions[first],
+ mesh.positions[second + 1] - mesh.positions[first + 1],
+ mesh.positions[second + 2] - mesh.positions[first + 2],
+ ]);
+ if (Math.abs(dot(vector, direction)) >= limit) mask[edge] = 1;
+ }
+ return mask;
+ }
if (rule.between !== undefined) {
if (!Array.isArray(rule.between) || rule.between.length !== 2) throw new TypeError('between needs two face rules.');
const first = selectFaces(mesh, rule.between[0]);
@@ -63,7 +85,7 @@ export function selectEdges(mesh, rule, table) {
}
return mask;
}
- throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, all.');
+ throw new TypeError('Edge rule takes exactly one of between, angle, boundaryOf, along, all.');
}
/** Faces of every MeshData edge. */
diff --git a/src/mesh-loopcut.js b/src/mesh-loopcut.js
new file mode 100644
index 00000000..14ae46f0
--- /dev/null
+++ b/src/mesh-loopcut.js
@@ -0,0 +1,161 @@
+import { editMesh } from './mesh-edit.js';
+import { MeshBuilder } from './mesh-stack.js';
+import { selectEdges, edgeFaces } from './mesh-bevel.js';
+
+// Loop cut, as Blender's: an edge ring is walked across quads (from an edge to the opposite edge of each quad), every
+// ring edge is split into cuts + 1 pieces, and each quad of the ring is split into bands between the new points.
+// Faces outside the ring that share a split edge get the new points inserted, so no T-junctions remain.
+
+/**
+ * Edge rings through the seed edges. Each ring lists its edges with the vertex on the "low" side (consistent across
+ * the ring) and the quads it crosses, each with the loop on its entry edge. The low side of a ring is the end of its
+ * first seed edge with the lower coordinate along that edge's direction.
+ */
+function edgeRings(edit, seeds, positionOf) {
+ const loops = edit.loops.arrays;
+ const ringOfEdge = new Map();
+ const ringOfFace = new Map();
+ const rings = [];
+ const isQuad = face => edit.faces.arrays.size[face] === 4;
+ for (const seed of seeds) {
+ if (ringOfEdge.has(seed)) continue;
+ const [first, second] = edit.edgeVertices(seed);
+ const firstPosition = positionOf(first);
+ const secondPosition = positionOf(second);
+ const direction = [0, 1, 2].map(axis => secondPosition[axis] - firstPosition[axis]);
+ const dominant = direction.map(Math.abs).indexOf(Math.max(...direction.map(Math.abs)));
+ const lowVertex = direction[dominant] >= 0 ? first : second;
+ const ring = { index: rings.length, edges: new Map([[seed, lowVertex]]), quads: [], closed: false };
+ ringOfEdge.set(seed, ring.index);
+ // Walk out of the seed through each of its faces; a closed ring comes back to the seed.
+ for (const startLoop of edit.edgeLoops(seed)) {
+ let loop = startLoop;
+ let low = lowVertex;
+ while (isQuad(loops.face[loop])) {
+ const face = loops.face[loop];
+ if (ringOfFace.has(face)) {
+ if (ringOfFace.get(face) === ring.index) {
+ ring.closed = true;
+ break;
+ }
+ throw new RangeError(`Loop cut rings cross at face ${face}. Cut them in separate edits.`);
+ }
+ ringOfFace.set(face, ring.index);
+ ring.quads.push({ face, entryLoop: loop, entryLow: low });
+ // In the quad a->b->c->d with the entry loop on a->b, the opposite loop is c->d; d sits across from a.
+ const opposite = loops.next[loops.next[loop]];
+ const oppositeEdge = loops.edge[opposite];
+ const oppositeLow = loops.vertex[loop] === low ? loops.vertex[loops.next[opposite]] : loops.vertex[opposite];
+ if (ringOfEdge.has(oppositeEdge) && ringOfEdge.get(oppositeEdge) !== ring.index) {
+ throw new RangeError(`Loop cut rings cross at edge ${oppositeEdge}. Cut them in separate edits.`);
+ }
+ ring.edges.set(oppositeEdge, oppositeLow);
+ ringOfEdge.set(oppositeEdge, ring.index);
+ const across = loops.radialNext[opposite];
+ if (across === opposite || edit.edgeFaceCount(oppositeEdge) !== 2) break;
+ loop = across;
+ low = oppositeLow;
+ }
+ }
+ rings.push(ring);
+ }
+ return rings;
+}
+
+/**
+ * Loop-cut the edge rings through the edges an edge rule selects (see selectEdges; `along` picks edges parallel to
+ * a direction, which is usually what "cut around" means). cuts: 1 to 16 new loops per ring, evenly spaced; with one
+ * cut, factor (0 to 1, default 0.5) places it measured from each ring's low side. Bands between the cuts get the tags
+ * `<name>.band-0` (low side) to `<name>.band-<cuts>`; they keep the face's other tags.
+ */
+export function loopCut(mesh, edgeRule, { cuts = 1, factor = 0.5, name = 'loop' } = {}) {
+ const table = edgeFaces(mesh);
+ const seeds = [];
+ selectEdges(mesh, edgeRule, table).forEach((selected, edge) => {
+ if (selected) seeds.push(edge);
+ });
+ if (!seeds.length) throw new RangeError('The edge rule selects no edges to start a loop cut. Check with mesh_inspect; along [0, 1, 0] picks vertical edges.');
+ const edit = editMesh(mesh);
+ const loops = edit.loops.arrays;
+ const positionOf = vertex => edit.vertexPosition(vertex);
+ const rings = edgeRings(edit, seeds, positionOf);
+ const fractions = cuts === 1 ? [factor] : Array.from({ length: cuts }, (_, index) => (index + 1) / (cuts + 1));
+
+ const builder = new MeshBuilder(mesh);
+ const vertexPoint = new Uint32Array(mesh.vertexCount);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) vertexPoint[vertex] = builder.addVertex(...positionOf(vertex));
+ // New points on each split edge, ordered from its low vertex.
+ const edgePoints = new Map();
+ const lowOfEdge = new Map();
+ for (const ring of rings) {
+ for (const [edge, low] of ring.edges) {
+ const high = edit.edgeOtherVertex(edge, low);
+ const start = positionOf(low);
+ const end = positionOf(high);
+ edgePoints.set(edge, fractions.map(t => builder.addVertex(...[0, 1, 2].map(axis => start[axis] + (end[axis] - start[axis]) * t))));
+ lowOfEdge.set(edge, low);
+ }
+ }
+ // Points along a face's edge in the face's own direction, with the fraction of each from the loop's start.
+ const pointsAlong = loop => {
+ const edge = loops.edge[loop];
+ const points = edgePoints.get(edge);
+ if (!points) return [];
+ const forward = loops.vertex[loop] === lowOfEdge.get(edge);
+ return (forward ? points.map((point, index) => ({ point, t: fractions[index] })) : points.map((point, index) => ({ point, t: 1 - fractions[index] })).reverse());
+ };
+ const cornerIndex = loop => mesh.faceOffsets[loops.face[loop]] + edit.faceLoops(loops.face[loop]).indexOf(loop);
+
+ const quadOfRing = new Map();
+ for (const ring of rings) {
+ for (const quad of ring.quads) quadOfRing.set(quad.face, quad);
+ }
+ for (let face = 0; face < mesh.faceCount; face++) {
+ const quad = quadOfRing.get(face);
+ if (!quad) {
+ // Not crossed by a ring: keep the face, inserting points on any split edge.
+ const vertices = [];
+ const sourceCorners = [];
+ for (const loop of edit.faceLoops(face)) {
+ const corner = cornerIndex(loop);
+ vertices.push(vertexPoint[loops.vertex[loop]]);
+ sourceCorners.push(corner);
+ const nextCorner = cornerIndex(loops.next[loop]);
+ for (const { point, t } of pointsAlong(loop)) {
+ vertices.push(point);
+ sourceCorners.push({ from: corner, to: nextCorner, t });
+ }
+ }
+ builder.addFace(vertices, { sourceFace: face, sourceCorners });
+ continue;
+ }
+ // Crossed: split into bands between matching points on the entry edge (a->b) and the opposite edge (c->d).
+ const entry = quad.entryLoop;
+ const sideOne = loops.next[entry];
+ const opposite = loops.next[sideOne];
+ const sideTwo = loops.next[opposite];
+ const along = pointsAlong(entry);
+ const back = pointsAlong(opposite).reverse();
+ const cornerA = cornerIndex(entry);
+ const cornerB = cornerIndex(sideOne);
+ const cornerC = cornerIndex(opposite);
+ const cornerD = cornerIndex(sideTwo);
+ const rail = [{ point: vertexPoint[loops.vertex[entry]], source: cornerA }, ...along.map(({ point, t }) => ({ point, source: { from: cornerA, to: cornerB, t } })), { point: vertexPoint[loops.vertex[sideOne]], source: cornerB }];
+ // The opposite edge runs c->d; reversed, its points run d->c, matching the entry rail a->b.
+ const otherRail = [{ point: vertexPoint[loops.vertex[sideTwo]], source: cornerD }, ...back.map(({ point, t }) => ({ point, source: { from: cornerC, to: cornerD, t } })), { point: vertexPoint[loops.vertex[opposite]], source: cornerC }];
+ const lowAtStart = loops.vertex[entry] === quad.entryLow;
+ for (let step = 0; step + 1 < rail.length; step++) {
+ const band = lowAtStart ? step : rail.length - 2 - step;
+ builder.addFace(
+ [rail[step].point, rail[step + 1].point, otherRail[step + 1].point, otherRail[step].point],
+ { sourceFace: face, sourceCorners: [rail[step].source, rail[step + 1].source, otherRail[step + 1].source, otherRail[step].source], tags: [`${name}.band-${band}`] },
+ );
+ }
+ }
+ return {
+ mesh: builder.build(),
+ rings: rings.length,
+ closedRings: rings.filter(ring => ring.closed).length,
+ splitEdges: edgePoints.size,
+ };
+}
diff --git a/src/mesh-ops.js b/src/mesh-ops.js
index 1c044631..0585c5b1 100644
--- a/src/mesh-ops.js
+++ b/src/mesh-ops.js
@@ -196,7 +196,7 @@ function offsetVector(edit, faces, { offset, direction }) {
return unit.map(value => value * offset);
}
const normal = regionNormal(edit, faces);
- if (normal.every(value => value === 0)) throw new RangeError('The selected faces face opposite ways, so their average normal cancels out. Use extrude_individual or inset_individual, select fewer faces, or pass direction.');
+ if (normal.every(value => value === 0)) throw new RangeError('The selected faces face opposite ways, so their average normal cancels out. For a ring or a curved band use alongNormals: true; otherwise use extrude_individual or inset_individual, select fewer faces, or pass direction.');
return normal.map(value => value * offset);
}
@@ -233,6 +233,13 @@ export function extrudeFaceRegion(edit, mask, options) {
const capFaces = [];
const sideFaces = [];
for (const region of connectedRegions(edit, maskedFaces(edit, mask))) {
+ if (options.alongNormals) {
+ const result = splitRegion(edit, region);
+ moveAlongVertexNormals(edit, result.capFaces, options.offset);
+ capFaces.push(...result.capFaces);
+ sideFaces.push(...result.sideFaces);
+ continue;
+ }
const vector = offsetVector(edit, region, options);
const result = splitRegion(edit, region);
moveVertices(edit, faceVertexSet(edit, result.capFaces), vector);
@@ -242,6 +249,34 @@ export function extrudeFaceRegion(edit, mask, options) {
return { capFaces, sideFaces };
}
+/**
+ * Move the vertices of the given faces along their own normals (the mean of the faces' normals at each vertex),
+ * scaled so flat walls move by the full offset, as Blender's Extrude Faces Along Normals. A ring of faces around a
+ * cylinder grows outward evenly instead of cancelling out.
+ */
+function moveAlongVertexNormals(edit, faces, offset) {
+ const sums = new Map();
+ const faceNormalOf = new Map(faces.map(face => [face, normalize(faceNormalVector(edit, face))]));
+ for (const face of faces) {
+ for (const vertex of edit.faceVertices(face)) {
+ const normal = faceNormalOf.get(face);
+ const entry = sums.get(vertex) ?? { sum: [0, 0, 0], normals: [] };
+ entry.sum = [entry.sum[0] + normal[0], entry.sum[1] + normal[1], entry.sum[2] + normal[2]];
+ entry.normals.push(normal);
+ sums.set(vertex, entry);
+ }
+ }
+ const position = edit.vertices.arrays.position;
+ for (const [vertex, { sum, normals }] of sums) {
+ const direction = normalize(sum);
+ const cosine = Math.max(0.25, Math.min(...normals.map(normal => normal[0] * direction[0] + normal[1] * direction[1] + normal[2] * direction[2])));
+ const distance = offset / cosine;
+ position[vertex * 3] += direction[0] * distance;
+ position[vertex * 3 + 1] += direction[1] * distance;
+ position[vertex * 3 + 2] += direction[2] * distance;
+ }
+}
+
/** Extrude every selected face on its own, each along its own normal (or `direction`). */
export function extrudeIndividual(edit, mask, options) {
const capFaces = [];
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index fb645eb4..b9596336 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -8,6 +8,7 @@ import { meshBoolean, BOOLEAN_OPERATIONS } from './mesh-boolean.js';
import { createMeshData } from './mesh-data.js';
import { mirrorMesh, arrayMesh, solidifyMesh } from './mesh-stack.js';
import { bevelEdges } from './mesh-bevel.js';
+import { loopCut } from './mesh-loopcut.js';
// Replayable edit log for agent recipes. Each edit is plain JSON; names follow Blender's bmesh.ops where they match.
@@ -16,7 +17,7 @@ const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
const MAX_OFFSET = 1e6;
export const MESH_EDIT_OPERATIONS = Object.freeze({
- extrude_face_region: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },
+ extrude_face_region: { fields: ['select', 'name', 'offset', 'direction', 'alongNormals'], tags: ['cap', 'side'] },
extrude_individual: { fields: ['select', 'name', 'offset', 'direction'], tags: ['cap', 'side'] },
inset_region: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },
inset_individual: { fields: ['select', 'name', 'thickness', 'depth'], tags: ['cap', 'rim'] },
@@ -30,6 +31,7 @@ export const MESH_EDIT_OPERATIONS = Object.freeze({
array: { fields: ['name', 'count', 'offset', 'relativeOffset', 'merge'], tags: ['last'] },
solidify: { fields: ['name', 'thickness', 'offset', 'evenThickness'], tags: ['inner', 'rim'] },
bevel: { fields: ['name', 'edges', 'width', 'segments', 'profile', 'clampOverlap'], tags: ['strip', 'corner'] },
+ loop_cut: { fields: ['name', 'edges', 'cuts', 'factor'], tags: ['band-<k>'] },
});
function editError(index, message) {
@@ -74,6 +76,11 @@ export function normalizeMeshEdits(edits) {
case 'extrude_individual':
normalized.offset = finiteNumber(edit.offset, index, 'offset');
if (edit.direction !== undefined) normalized.direction = vector(edit.direction, index, 'direction');
+ if (edit.alongNormals !== undefined) {
+ if (typeof edit.alongNormals !== 'boolean') throw editError(index, 'alongNormals must be boolean');
+ if (edit.alongNormals && edit.direction !== undefined) throw editError(index, 'alongNormals and direction cannot be combined');
+ normalized.alongNormals = edit.alongNormals;
+ }
break;
case 'inset_region':
case 'inset_individual':
@@ -148,6 +155,17 @@ export function normalizeMeshEdits(edits) {
if (edit.clampOverlap !== undefined && typeof edit.clampOverlap !== 'boolean') throw editError(index, 'clampOverlap must be boolean');
normalized.clampOverlap = edit.clampOverlap ?? true;
break;
+ case 'loop_cut':
+ if (!edit.edges || typeof edit.edges !== 'object' || Array.isArray(edit.edges)) {
+ throw editError(index, 'edges must be a rule that picks the ring, for example { "along": [0, 1, 0] } for the vertical edges');
+ }
+ normalized.edges = edit.edges;
+ if (!Number.isInteger(edit.cuts ?? 1) || (edit.cuts ?? 1) < 1 || (edit.cuts ?? 1) > 16) throw editError(index, 'cuts must be an integer from 1 to 16');
+ normalized.cuts = edit.cuts ?? 1;
+ if (edit.factor !== undefined && normalized.cuts !== 1) throw editError(index, 'factor applies only to a single cut');
+ normalized.factor = edit.factor === undefined ? 0.5 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1 });
+ if (normalized.factor === 0 || normalized.factor === 1) throw editError(index, 'factor must be strictly between 0 and 1');
+ break;
case 'merge_by_distance':
normalized.distance = finiteNumber(edit.distance ?? 1e-4, index, 'distance', { minimum: 0, maximum: 1e3 });
break;
@@ -213,6 +231,19 @@ function runEdit(current, edit, index, { resolveCutter }) {
result.removedFaces = merged.removedFaces;
return { mesh: merged.mesh, result };
}
+ if (edit.op === 'loop_cut') {
+ let outcome;
+ try {
+ outcome = loopCut(current, edit.edges, edit);
+ } catch (error) {
+ throw new error.constructor(`Mesh edit ${index} (loop_cut): ${error.message}`);
+ }
+ result.rings = outcome.rings;
+ result.closedRings = outcome.closedRings;
+ result.splitEdges = outcome.splitEdges;
+ result.tags = tagSummary(outcome.mesh, edit.name);
+ return { mesh: outcome.mesh, result };
+ }
if (edit.op === 'bevel') {
let outcome;
try {
diff --git a/src/mesh-stack.js b/src/mesh-stack.js
index 7d64ed92..e4fac2b5 100644
--- a/src/mesh-stack.js
+++ b/src/mesh-stack.js
@@ -32,7 +32,8 @@ export class MeshBuilder {
/**
* vertices: new vertex indices in winding order. sourceCorners / sourceEdges: per corner, the source corner whose
- * attributes it copies and the source edge its outgoing edge copies (-1 for none).
+ * attributes it copies (or { from, to, t } to interpolate between two) and the source edge its outgoing edge copies
+ * (-1 for none).
*/
addFace(vertices, { sourceFace = -1, sourceCorners = null, sourceEdges = null, keepTags = true, tags = [], tagSwap = null } = {}) {
for (let corner = 0; corner < vertices.length; corner++) {
@@ -78,8 +79,20 @@ export class MeshBuilder {
}
for (const [name, attribute] of Object.entries(source.attributes.corner)) {
const data = new attribute.data.constructor(cornerVertices.length * attribute.size);
+ const blends = attribute.data instanceof Float32Array;
this.cornerSources.forEach((sourceCorner, corner) => {
- if (sourceCorner !== -1) data.set(attribute.data.subarray(sourceCorner * attribute.size, (sourceCorner + 1) * attribute.size), corner * attribute.size);
+ if (sourceCorner === -1) return;
+ if (typeof sourceCorner === 'number') {
+ data.set(attribute.data.subarray(sourceCorner * attribute.size, (sourceCorner + 1) * attribute.size), corner * attribute.size);
+ return;
+ }
+ // Interpolated corner: linear for float attributes (UVs, colours), nearest for integer ones.
+ const { from, to, t } = sourceCorner;
+ for (let component = 0; component < attribute.size; component++) {
+ const start = attribute.data[from * attribute.size + component];
+ const end = attribute.data[to * attribute.size + component];
+ data[corner * attribute.size + component] = blends ? start + (end - start) * t : (t < 0.5 ? start : end);
+ }
});
attributes.corner[name] = { data, size: attribute.size };
}
diff --git a/src/mesh.js b/src/mesh.js
index e89d9117..1f4c589a 100644
--- a/src/mesh.js
+++ b/src/mesh.js
@@ -15,6 +15,7 @@ export { applyMeshEdits, normalizeMeshEdits, transformMesh, MESH_EDIT_OPERATIONS
export { evaluateMeshStack, normalizeMeshStack, STACK_OPERATIONS, MAX_STACK_NODES } from './mesh-recipe.js';
export { mirrorMesh, arrayMesh, solidifyMesh, removeCoincidentFaces } from './mesh-stack.js';
export { bevelEdges, selectEdges } from './mesh-bevel.js';
+export { loopCut } from './mesh-loopcut.js';
export { loadMeshBooleans, meshBooleansLoaded, meshBoolean, BOOLEAN_OPERATIONS } from './mesh-boolean.js';
export {
extrudeFaceRegion, extrudeIndividual, insetRegion, insetIndividual, deleteFaces, flipFaces, translateFaces,
diff --git a/tests/mesh-loopcut.test.js b/tests/mesh-loopcut.test.js
new file mode 100644
index 00000000..a688048e
--- /dev/null
+++ b/tests/mesh-loopcut.test.js
@@ -0,0 +1,139 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box, cylinder } from '../src/geometry.js';
+import { lathe } from '../src/modeling.js';
+import { editMesh, validateTopology, meshFromGeometry, lintMesh, tagCounts, facesWithTag, applyMeshEdits, meshBounds } from '../src/mesh.js';
+import { loopCut } from '../src/mesh-loopcut.js';
+import { normalizeMeshEdits } from '../src/mesh-recipe.js';
+import { createAgentScene } from '../src/agent-scene.js';
+
+const cube = () => meshFromGeometry(box(0, 1));
+
+function closed(mesh) {
+ validateTopology(editMesh(mesh));
+ const report = lintMesh(mesh);
+ assert.deepEqual(report.problems, []);
+ assert.equal(report.parts.closed, 1);
+}
+
+function heights(mesh) {
+ const values = new Set();
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) values.add(Math.round(mesh.positions[vertex * 3 + 1] * 1e4) / 1e4);
+ return [...values].sort((left, right) => left - right);
+}
+
+test('one cut around a cube makes one closed ring and two tagged bands', () => {
+ const result = loopCut(cube(), { along: [0, 1, 0] });
+ closed(result.mesh);
+ assert.deepEqual([result.rings, result.closedRings, result.splitEdges], [1, 1, 4]);
+ assert.deepEqual([result.mesh.vertexCount, result.mesh.faceCount], [12, 10]);
+ const tags = tagCounts(result.mesh);
+ assert.equal(tags['loop.band-0'], 4);
+ assert.equal(tags['loop.band-1'], 4);
+ assert.equal(tags.side, 8, 'split faces keep their tags');
+ for (const face of facesWithTag(result.mesh, 'loop.band-0')) {
+ for (let corner = result.mesh.faceOffsets[face]; corner < result.mesh.faceOffsets[face + 1]; corner++) {
+ assert.ok(result.mesh.positions[result.mesh.cornerVertices[corner] * 3 + 1] <= 1e-6, 'band 0 is the low side');
+ }
+ }
+});
+
+test('several cuts space evenly and one cut honours factor from the low side', () => {
+ assert.deepEqual(heights(loopCut(cube(), { along: [0, 1, 0] }, { cuts: 3 }).mesh), [-0.5, -0.25, 0, 0.25, 0.5]);
+ assert.deepEqual(heights(loopCut(cube(), { along: [0, 1, 0] }, { factor: 0.2 }).mesh), [-0.5, -0.3, 0.5]);
+});
+
+test('faces beside an open ring get the new points, so no T-junctions appear', () => {
+ const tall = applyMeshEdits(cube(), [{ op: 'loop_cut', edges: { along: [1, 0, 0] }, name: 'split' }]).mesh;
+ closed(tall);
+ // Cylinder: the wall is a closed ring of quads; the caps are fans that receive the new points on their rims.
+ const can = loopCut(meshFromGeometry(cylinder(12, 0, 1)), { along: [0, 1, 0] }, { cuts: 2 });
+ closed(can.mesh);
+ assert.equal(can.splitEdges, 12);
+});
+
+test('corner UVs are interpolated at the new points', () => {
+ const vase = meshFromGeometry(lathe([[0.4, 0], [0.6, 1]], { segments: 8 }));
+ assert.ok(vase.attributes.corner.uv);
+ const { mesh } = loopCut(vase, { along: [0.2, 1, 0], maxAngle: 20 });
+ const uv = mesh.attributes.corner.uv.data;
+ const middleVs = new Set();
+ for (let corner = 0; corner < mesh.cornerCount; corner++) {
+ const y = mesh.positions[mesh.cornerVertices[corner] * 3 + 1];
+ if (Math.abs(y - 0.5) < 1e-5) middleVs.add(Math.round(uv[corner * 2 + 1] * 1e4) / 1e4);
+ }
+ assert.deepEqual([...middleVs], [0.5], 'new points sit halfway in V as well as in height');
+});
+
+test('cutting then extruding a band makes a closed belt', () => {
+ const { mesh, results } = applyMeshEdits(cube(), [
+ { op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, name: 'belt' },
+ { op: 'extrude_individual', select: { tag: 'belt.band-1' }, offset: 0.05 },
+ ]);
+ closed(mesh);
+ assert.deepEqual(results[0].tags, { 'belt.band-0': 4, 'belt.band-1': 4, 'belt.band-2': 4 });
+ assert.ok(Math.abs(meshBounds(mesh).max[0] - 0.55) < 1e-6);
+});
+
+test('a band around a cylinder extrudes along normals as one joined hoop', () => {
+ const steps = [{ op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, name: 'hoop' }];
+ const base = meshFromGeometry(cylinder(24, 0, 1));
+ assert.throws(() => applyMeshEdits(base, [...steps, { op: 'extrude_face_region', select: { tag: 'hoop.band-1' }, offset: 0.1 }]), /alongNormals: true/);
+ const { mesh, results } = applyMeshEdits(base, [...steps, { op: 'extrude_face_region', select: { tag: 'hoop.band-1' }, offset: 0.1, alongNormals: true, name: 'band' }]);
+ closed(mesh);
+ assert.equal(results[1].tags['band.side'], 48, 'one region: two rims of 24 side quads, not 24 separate boxes');
+ for (const face of facesWithTag(mesh, 'band.cap')) {
+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
+ const vertex = mesh.cornerVertices[corner];
+ const radius = Math.hypot(mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 2]);
+ assert.ok(Math.abs(radius - 1.1) < 0.01, `cap vertex radius ${radius}`);
+ }
+ }
+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_face_region', offset: 1, alongNormals: true, direction: [0, 1, 0] }]), /cannot be combined/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'extrude_individual', offset: 1, alongNormals: true }]), /does not take alongNormals/);
+});
+
+test('loop cut validation and errors are explicit', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut' }]), /edges must be a rule that picks the ring/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 2, factor: 0.3 }]), /factor applies only to a single cut/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'loop_cut', edges: { along: [0, 1, 0] }, factor: 1 }]), /strictly between 0 and 1/);
+ assert.throws(() => loopCut(cube(), { along: [1, 1, 1], maxAngle: 1 }), /selects no edges/);
+ assert.throws(() => loopCut(cube(), { all: true }), /rings cross/);
+});
+
+test('random loop cuts on stretched boxes and cylinders stay closed', () => {
+ let seed = 3;
+ const random = () => {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;
+ return seed / 0x7fffffff;
+ };
+ const axes = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
+ for (let trial = 0; trial < 20; trial++) {
+ let mesh = trial % 2 ? meshFromGeometry(cylinder(8 + Math.floor(random() * 16), 0, 1)) : cube();
+ for (let cut = 0; cut < 3; cut++) {
+ const axis = axes[Math.floor(random() * 3)];
+ try {
+ mesh = loopCut(mesh, { along: axis }, { cuts: 1 + Math.floor(random() * 3) }).mesh;
+ } catch (error) {
+ assert.match(error.message, /selects no edges|rings cross/);
+ }
+ closed(mesh);
+ }
+ }
+});
+
+test('recipe meshes loop cut through mesh_edit-style edits', () => {
+ const scene = createAgentScene({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'pillar', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [
+ { op: 'translate', select: { tag: 'top' }, offset: [0, 2, 0] },
+ { op: 'loop_cut', edges: { along: [0, 1, 0] }, cuts: 4, name: 'ring' },
+ { op: 'extrude_individual', select: { or: [{ tag: 'ring.band-1' }, { tag: 'ring.band-3' }] }, offset: 0.04 },
+ ] }],
+ materials: [{ id: 'stone', color: [0.6, 0.6, 0.55] }],
+ nodes: [{ id: 'pillar', geometry: 'pillar', material: 'stone' }],
+ });
+ const [report] = scene.inspectMeshes().meshes;
+ assert.equal(report.ok, true, JSON.stringify(report.problems));
+ assert.equal(report.edits[1].rings, 1);
+});