Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add split_edges, delete_loose and flatten mesh edits

Nguyen Xuan Ande30e4e5caa3
diff --git a/changes/703.size.md b/changes/703.size.md
index 5b7122c6..e05a2115 100644
--- a/changes/703.size.md
+++ b/changes/703.size.md
@@ -1,5 +1,2 @@
-- entry:mesh: poke, dual, tris to quads, symmetrize, scale elements and extrude edges are modeling edits agents lacked (2815 bytes gzip); the lead approved growth for modeling capabilities
-- scene:agent-scene: the six edit names and their validators ship in the core bundle (75 bytes gzip)
-- scene:agent-scene+lazy: the same edits ship in the lazy bundle (2823 bytes gzip)
-- goal:agent-scene: the capability is worth 75 bytes gzip over the goal; lead approved growth for modeling features
-- tool:mesh_edit: six new op names in the op enum (76 bytes); field detail stays in the meshEdit.<op> capabilities topic
+- scene:agent-scene+lazy: split_edges, delete_loose and flatten are agent-facing modeling edits (about 0.8 KB gzip for three edits, loaded lazily with the mesh engine).
+- goal:agent-scene: the core bundle grows 26 bytes gzip for the three edit names in the shared operation table; the geometry loads lazily.
diff --git a/changes/issue-703-rest.md b/changes/issue-703-rest.md
new file mode 100644
index 00000000..2afd54f1
--- /dev/null
+++ b/changes/issue-703-rest.md
@@ -0,0 +1 @@
+- `mesh_edit` gains `split_edges`, `delete_loose` and `flatten`; `unsubdivide`, `circularize` and `extrude_vertices` (not representable: a mesh has no loose edge) stay open on #703 (#703).
diff --git a/docs/mesh.md b/docs/mesh.md
index 620ef51c..999c4182 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -398,10 +398,13 @@ lower index, so the same input always gives the same bytes. Faces they keep carr
| `symmetrize` | `axis` (default x), `keep` (`positive` or `negative`), `distance` | `mirrored` | Cuts faces that cross the plane through the origin, drops the other half and mirrors the kept half. Left and right (top and bottom, front and back) tags swap on the mirrored half. |
| `scale_elements` | `select`, `scale` (above 0) | none | Scales each group of selected faces that share a vertex about the group's average vertex position. Unselected neighbours follow along shared vertices. |
| `extrude_edges` | `edges`, `offset` | `side` | Copies the vertices of the selected edges, moves the copies by `offset` and joins each edge to its copy with a quad. Select a surface boundary with `{ "open": true }`. |
+| `split_edges` | `edges` | none | Opens the surface along the selected edges: the faces on each side stop sharing the edge's vertices, which are copied once per group of faces that still meet around them. Faces keep their tags and attributes; the result has boundary edges. |
+| `delete_loose` | none | none | Removes every vertex that no face uses (the lint problem `loose-vertex`). Fails when there is none. |
+| `flatten` | `verts`, `normal`, `factor` (0 to 1, default 1) | none | Moves the selected vertices toward the plane through their average point. `normal` is the plane direction; without it the area-weighted normal of the faces whose vertices are all selected is used. |
`dual` and `symmetrize` leave a closed surface closed. `extrude_edges` on interior edges adds a fin, so a closed
mesh is no longer closed afterwards. `extrude_vertices` is not offered: a mesh derives its edges from faces and cannot
-hold a loose edge. The size of `poke` and `extrude_edges` is checked before they allocate. The `meshEdit.<op>`
+hold a loose edge. The size of `poke`, `split_edges` and `extrude_edges` is checked before they allocate. The `meshEdit.<op>`
capabilities topic lists the exact fields.
### Subdivide
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index edc34d1b..434ba43e 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -63,6 +63,9 @@ export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({
symmetrize: { fields: ['name', 'axis', 'keep', 'distance'], tags: ['mirrored'] },
scale_elements: { fields: ['select', 'scale'], tags: [] },
extrude_edges: { fields: ['edges', 'name', 'offset'], tags: ['side'] },
+ split_edges: { fields: ['edges', 'name'], tags: [] },
+ delete_loose: { fields: [], tags: [] },
+ flatten: { fields: ['verts', 'normal', 'factor'], tags: [] },
set_position: { fields: ['select', 'position', 'offset'], tags: [] },
displace: { fields: ['select', 'field', 'strength', 'midlevel', 'direction', 'group'], tags: [] },
vertex_group: { fields: ['select', 'name', 'weight', 'field', 'gradient'], tags: [] },
diff --git a/src/mesh-reshape-edits.js b/src/mesh-reshape-edits.js
index a2cebfdb..e47285ae 100644
--- a/src/mesh-reshape-edits.js
+++ b/src/mesh-reshape-edits.js
@@ -1,3 +1,5 @@
+import { selectVertices } from './mesh-dissolve.js';
+import { splitEdges, deleteLoose, flattenVertices } from './mesh-reshape-more.js';
import { selectEdges, edgeFaces } from './mesh-bevel.js';
import { selectFaces, countSelected } from './mesh-select.js';
import { invalidField } from './field-error.js';
@@ -8,10 +10,11 @@ import { pokeFaces, dualMesh, trisToQuads, symmetrizeMesh, scaleElements, extrud
// The reshaping edits as recipe operations: validation of their fields and running them on MeshData. The geometry
// lives in mesh-reshape.js; this file only connects it to the edit log.
-export const RESHAPE_OPERATIONS = Object.freeze(['poke', 'dual', 'tris_to_quads', 'symmetrize', 'scale_elements', 'extrude_edges']);
+export const RESHAPE_OPERATIONS = Object.freeze(['poke', 'dual', 'tris_to_quads', 'symmetrize', 'scale_elements', 'extrude_edges', 'split_edges', 'delete_loose', 'flatten']);
const SYMMETRIZE_SIDES = Object.freeze(['positive', 'negative']);
const MAX_SCALE = 1000;
+const VERTEX_RULE_HINT = 'a vertex rule such as { "all": true }, { "vertices": [0, 1] }, { "valence": 4 } or { "inside": { "min": [x, y, z], "max": [x, y, z] } }';
/** Fill in `normalized` for a reshaping edit, throwing a TypeError that names the edit when a field is wrong. */
export function normalizeReshapeEdit(edit, normalized, index, { finiteNumber, vector }) {
@@ -34,6 +37,17 @@ export function normalizeReshapeEdit(edit, normalized, index, { finiteNumber, ve
case 'scale_elements':
normalized.scale = finiteNumber(edit.scale, index, 'scale', { minimum: 0, maximum: MAX_SCALE, exclusiveMinimum: true });
break;
+ case 'split_edges':
+ normalized.edges = editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);
+ break;
+ case 'flatten':
+ normalized.verts = editRuleObject(edit.verts, index, 'verts', VERTEX_RULE_HINT);
+ if (edit.normal !== undefined) {
+ normalized.normal = vector(edit.normal, index, 'normal');
+ if (normalized.normal.every(component => component === 0)) throw editField(index, 'normal', edit.normal, 'a direction that is not all zeros, such as [0, 1, 0]');
+ }
+ normalized.factor = edit.factor === undefined ? 1 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1 });
+ break;
case 'extrude_edges':
normalized.edges = editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);
normalized.offset = vector(edit.offset, index, 'offset');
@@ -54,6 +68,12 @@ export function checkReshapeBudget(mesh, edit, limits, index) {
throw editField(index, 'select', edit.select, `a rule that keeps the mesh within ${limits.maxFaces} faces (this edit would make ${faces}), such as { "tag": "top" }`, RangeError);
}
}
+ if (edit.op === 'split_edges') {
+ const edges = countSelected(selectEdges(mesh, edit.edges, edgeFaces(mesh)));
+ if (mesh.vertexCount + edges * 2 > limits.maxVertices) {
+ throw editField(index, 'edges', edit.edges, `a rule that keeps the mesh within ${limits.maxVertices} vertices (this edit would add up to ${edges * 2}), such as { "angle": 30 }`, RangeError);
+ }
+ }
if (edit.op === 'extrude_edges') {
const edges = countSelected(selectEdges(mesh, edit.edges, edgeFaces(mesh)));
if (mesh.faceCount + edges > limits.maxFaces || mesh.vertexCount + edges * 2 > limits.maxVertices) {
@@ -95,6 +115,18 @@ export function runReshapeEdit(mesh, edit) {
const outcome = extrudeEdges(mesh, selectEdges(mesh, edit.edges, edgeFaces(mesh)), { offset: edit.offset, name: edit.name });
return { mesh: outcome.mesh, result: { extrudedEdges: outcome.extrudedEdges } };
}
+ case 'split_edges': {
+ const outcome = splitEdges(mesh, selectEdges(mesh, edit.edges, edgeFaces(mesh)));
+ return { mesh: outcome.mesh, result: { splitEdges: outcome.splitEdges, addedVertices: outcome.addedVertices } };
+ }
+ case 'delete_loose': {
+ const outcome = deleteLoose(mesh);
+ return { mesh: outcome.mesh, result: { removedVertices: outcome.removedVertices } };
+ }
+ case 'flatten': {
+ const outcome = flattenVertices(mesh, selectVertices(mesh, edit.verts), { normal: edit.normal, factor: edit.factor });
+ return { mesh: outcome.mesh, result: { flattenedVertices: outcome.flattenedVertices } };
+ }
}
throw new TypeError(`Not a reshaping edit: ${edit.op}`);
}
diff --git a/src/mesh-reshape-more.js b/src/mesh-reshape-more.js
new file mode 100644
index 00000000..fa519722
--- /dev/null
+++ b/src/mesh-reshape-more.js
@@ -0,0 +1,125 @@
+import { createMeshData } from './mesh-data.js';
+import { faceNormals } from './mesh-normals.js';
+import { facePolygons, buildPolygonMesh, edgeFaces } from './mesh-polygons.js';
+import { UnionFind } from './mesh-topology.js';
+
+// Split edges, delete loose vertices and flatten vertices after Blender's split edges, delete loose and flatten.
+// Every edit is deterministic: elements are visited in index order.
+
+function positionOf(mesh, vertex) {
+ return [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];
+}
+
+// Corners that sit on the same vertex of a shared edge belong to one fan of faces.
+function joinCornersOfEdge(mesh, corners, groups) {
+ const first = corners[0];
+ for (const other of corners.slice(1)) {
+ const sameDirection = mesh.cornerVertices[first.from] === mesh.cornerVertices[other.from];
+ groups.union(first.from, sameDirection ? other.from : other.to);
+ groups.union(first.to, sameDirection ? other.to : other.from);
+ }
+}
+
+/**
+ * Split the selected edges: the faces on the two sides of each selected edge stop sharing its vertices, so the surface
+ * opens along it. A vertex is copied once for every group of faces that still meet around it through an edge that is
+ * not selected; the first group keeps the original vertex. Faces keep their corner order, tags and attributes.
+ */
+export function splitEdges(mesh, edgeMask) {
+ const table = edgeFaces(mesh);
+ const groups = new UnionFind(mesh.cornerVertices.length);
+ const cornersOfEdge = Array.from({ length: mesh.edgeCount }, () => []);
+ for (let face = 0; face < mesh.faceCount; face++) {
+ const start = mesh.faceOffsets[face];
+ const end = mesh.faceOffsets[face + 1];
+ for (let corner = start; corner < end; corner++) {
+ cornersOfEdge[mesh.cornerEdges[corner]].push({ from: corner, to: corner + 1 === end ? start : corner + 1 });
+ }
+ }
+ let splitCount = 0;
+ for (let edge = 0; edge < mesh.edgeCount; edge++) {
+ if (!edgeMask[edge]) {
+ joinCornersOfEdge(mesh, cornersOfEdge[edge], groups);
+ } else if (table.faces[edge].length > 1) {
+ splitCount++;
+ }
+ }
+ if (splitCount === 0) throw new RangeError('The rule selects no edge shared by two faces. Select interior edges, such as { "angle": 30 } or { "all": true }.');
+ const extraPositions = [];
+ const vertexOfGroup = new Map();
+ const seenVertices = new Set();
+ const polygons = facePolygons(mesh);
+ for (const polygon of polygons) {
+ polygon.vertices = polygon.sourceCorners.map(corner => {
+ const vertex = mesh.cornerVertices[corner];
+ const group = groups.find(corner);
+ if (!vertexOfGroup.has(group)) {
+ if (seenVertices.has(vertex)) {
+ extraPositions.push(positionOf(mesh, vertex));
+ vertexOfGroup.set(group, mesh.vertexCount + extraPositions.length - 1);
+ } else {
+ seenVertices.add(vertex);
+ vertexOfGroup.set(group, vertex);
+ }
+ }
+ return vertexOfGroup.get(group);
+ });
+ }
+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), splitEdges: splitCount, addedVertices: extraPositions.length };
+}
+
+/** Drop every vertex that no face uses. Faces, tags and attributes stay as they are. */
+export function deleteLoose(mesh) {
+ const used = new Uint8Array(mesh.vertexCount);
+ for (const vertex of mesh.cornerVertices) used[vertex] = 1;
+ const removedVertices = used.reduce((count, flag) => count + (flag ? 0 : 1), 0);
+ if (removedVertices === 0) throw new RangeError('The mesh has no loose vertex. mesh_lint lists loose vertices as loose-vertex.');
+ return { mesh: buildPolygonMesh(mesh, facePolygons(mesh)), removedVertices };
+}
+
+function averageSelectedFaceNormal(mesh, vertexMask) {
+ const { normals, areas } = faceNormals(mesh);
+ const total = [0, 0, 0];
+ for (let face = 0; face < mesh.faceCount; face++) {
+ let allSelected = true;
+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
+ if (!vertexMask[mesh.cornerVertices[corner]]) allSelected = false;
+ }
+ if (!allSelected) continue;
+ for (let axis = 0; axis < 3; axis++) total[axis] += normals[face * 3 + axis] * areas[face];
+ }
+ return total;
+}
+
+/**
+ * Move the selected vertices toward the plane through their average point. `normal` is the plane direction; without
+ * one it is the area-weighted average normal of the faces whose corners are all selected. `factor` 1 lands every
+ * vertex on the plane and 0 leaves it where it is.
+ */
+export function flattenVertices(mesh, vertexMask, { normal = null, factor = 1 } = {}) {
+ const center = [0, 0, 0];
+ let count = 0;
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ if (!vertexMask[vertex]) continue;
+ count++;
+ for (let axis = 0; axis < 3; axis++) center[axis] += mesh.positions[vertex * 3 + axis];
+ }
+ if (count === 0) throw new RangeError('The rule selects no vertex. Use { "all": true } or { "vertices": [0, 1, 2, 3] }.');
+ for (let axis = 0; axis < 3; axis++) center[axis] /= count;
+ const planeNormal = normal ?? averageSelectedFaceNormal(mesh, vertexMask);
+ const planeLength = Math.hypot(...planeNormal);
+ if (planeLength === 0) throw new RangeError('No plane direction: no face has all of its vertices selected. Pass normal, such as [0, 1, 0].');
+ const unit = planeNormal.map(value => value / planeLength);
+ const positions = Float32Array.from(mesh.positions);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ if (!vertexMask[vertex]) continue;
+ let distance = 0;
+ for (let axis = 0; axis < 3; axis++) distance += (mesh.positions[vertex * 3 + axis] - center[axis]) * unit[axis];
+ for (let axis = 0; axis < 3; axis++) positions[vertex * 3 + axis] -= unit[axis] * distance * factor;
+ }
+ const flattened = createMeshData({
+ positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,
+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes: mesh.attributes,
+ });
+ return { mesh: flattened, flattenedVertices: count };
+}
diff --git a/tests/mesh-reshape.test.js b/tests/mesh-reshape.test.js
index 772e51a3..09712523 100644
--- a/tests/mesh-reshape.test.js
+++ b/tests/mesh-reshape.test.js
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { box, cylinder } from '../src/geometry.js';
-import { editMesh, validateTopology, meshFromGeometry, lintMesh, tagCounts, applyMeshEdits } from '../src/mesh.js';
+import { createMeshData, editMesh, validateTopology, meshFromGeometry, lintMesh, tagCounts, applyMeshEdits } from '../src/mesh.js';
import { normalizeMeshEdits, MESH_EDIT_OPERATIONS } from '../src/mesh-recipe.js';
const cube = () => meshFromGeometry(box(0, 1));
@@ -182,3 +182,54 @@ test('a poke that would pass the face limit is refused before it allocates', ()
const big = meshFromGeometry(cylinder(64, 0, 1));
assert.throws(() => applyMeshEdits(big, [{ op: 'poke' }], { maxFaces: 100 }), /edits\[0\]\.select.*within 100 faces/s);
});
+
+test('split_edges opens the surface along the chosen edges and is deterministic', () => {
+ const { mesh, results } = run(cube(), [{ op: 'split_edges', edges: { all: true } }]);
+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [24, 6]);
+ assert.equal(results[0].addedVertices, 16);
+ assert.equal(tagCounts(mesh).top, 1);
+ assert.equal(lintMesh(mesh).parts.closed, 0);
+ assert.ok(Math.abs(volume(mesh) - 1) < 1e-9);
+ sameBytes(mesh, run(cube(), [{ op: 'split_edges', edges: { all: true } }]).mesh);
+});
+
+test('split_edges refuses a rule with no shared edge', () => {
+ assert.throws(() => run(openCube(), [{ op: 'split_edges', edges: { open: true } }]), /selects no edge shared by two faces/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'split_edges' }]), /edits\[0\]\.edges/);
+});
+
+test('delete_loose drops vertices no face uses', () => {
+ const base = cube();
+ const withLoose = createMeshData({
+ positions: Float32Array.from([...base.positions, 5, 5, 5]),
+ faceOffsets: base.faceOffsets, cornerVertices: base.cornerVertices,
+ edgeVertices: base.edgeVertices, cornerEdges: base.cornerEdges, attributes: base.attributes,
+ });
+ assert.equal(lintMesh(withLoose).problems.some(problem => problem.kind === 'loose-vertex'), true);
+ const { mesh, results } = run(withLoose, [{ op: 'delete_loose' }]);
+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);
+ assert.equal(results[0].removedVertices, 1);
+ assertClosed(mesh);
+ assert.throws(() => run(cube(), [{ op: 'delete_loose' }]), /no loose vertex/);
+});
+
+test('flatten moves the selected vertices onto a plane', () => {
+ const bumped = run(cube(), [{ op: 'translate', select: { tag: 'top' }, offset: [0, 0.2, 0] }]).mesh;
+ const flatten = [{ op: 'flatten', verts: { all: true }, normal: [0, 1, 0] }];
+ const { mesh, results } = run(bumped, flatten);
+ assert.equal(results[0].flattenedVertices, 8);
+ const heights = new Set();
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) heights.add(mesh.positions[vertex * 3 + 1].toFixed(5));
+ assert.equal(heights.size, 1);
+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);
+ sameBytes(mesh, run(bumped, flatten).mesh);
+ const half = run(cube(), [{ op: 'flatten', verts: { all: true }, normal: [0, 1, 0], factor: 0.5 }]).mesh;
+ assert.ok(Math.abs(Math.abs(half.positions[1]) - 0.25) < 1e-6);
+});
+
+test('flatten validates its fields', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'flatten' }]), /edits\[0\]\.verts/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'flatten', verts: { all: true }, normal: [0, 0, 0] }]), /edits\[0\]\.normal/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'flatten', verts: { all: true }, factor: 2 }]), /edits\[0\]\.factor/);
+ assert.throws(() => run(cube(), [{ op: 'flatten', verts: { vertices: [0] } }]), /Pass normal/);
+});