3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Keep UVs and vertex groups on points inserted by mesh cut edits (#2524)
Nguyen Xuan Anbe0bcb78f17a
diff --git a/changes/2524.md b/changes/2524.mdnew file mode 100644index 00000000..fdf2b272--- /dev/null+++ b/changes/2524.md@@ -0,0 +1 @@+- `subdivide_edges` no longer fails on a mesh with UVs when it splits all four sides of a quad, and it, `bisect_plane`, `knife_project` and `bridge_edge_loops` now give their new points the blended vertex groups of the points around them (#2524, #2525)diff --git a/changes/2524.size.md b/changes/2524.size.mdnew file mode 100644index 00000000..4bdba0a2--- /dev/null+++ b/changes/2524.size.md@@ -0,0 +1 @@+- scene:agent-scene+lazy: new points of subdivide_edges, bisect_plane, knife_project and bridge_edge_loops keep vertex groups and UVs (340 bytes gzip) instead of zeros and NaNdiff --git a/changes/2528.md b/changes/2528.mdnew file mode 100644index 00000000..9cc34542--- /dev/null+++ b/changes/2528.md@@ -0,0 +1 @@+- A selection rule that lists more faces than the mesh has now says how many it listed (#2528)diff --git a/docs/mesh.md b/docs/mesh.mdindex f62f49a8..3d609b89 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -413,6 +413,7 @@ is crossed more than twice (a concave face); split it first. `bridge_edge_loops`the shortest total distance, then turns them by `twistOffset` vertices. A knife stretch that starts or ends inside a facemakes no cut, and a face that runs along `direction` is not split (its edge points are still inserted). The sizes of`subdivide_edges` are checked before it allocates.+Points these edits insert on an edge (`subdivide_edges`, `bisect_plane`, `knife_project`, `bridge_edge_loops` rows) take the blend of vertex groups and other point attributes of the edge's two ends, and the inner points of a `subdivide_edges` grid blend all four corners. The inner points of `grid_fill` and the bend points of a knife stroke inside a face start at 0.Open boundaries reported by lint (`boundary-edge`) are fixed with `fill_holes`. Names follow `bmesh.ops`(`holes_fill`, `dissolve_*`, `bisect_plane`, `bridge_loops`, `grid_fill`, `subdivide_edges`) where the meaning matches, anddiff --git a/src/mesh-bisect.js b/src/mesh-bisect.jsindex 0e1e4fea..858bf30e 100644--- a/src/mesh-bisect.js+++ b/src/mesh-bisect.js@@ -57,7 +57,7 @@ function planeSigns(mesh, point, normal, distance) {}/** One point per mesh edge whose ends lie on opposite sides of the plane. */-function crossingPoints(mesh, signs, offsets, extraPositions) {+function crossingPoints(mesh, signs, offsets, extraPositions, extraSources) {const points = new Map();for (let edge = 0; edge < mesh.edgeCount; edge++) {const first = mesh.edgeVertices[edge * 2];@@ -65,6 +65,7 @@ function crossingPoints(mesh, signs, offsets, extraPositions) {if (signs[first] * signs[second] !== -1) continue;const fraction = offsets[first] / (offsets[first] - offsets[second]);extraPositions.push(lerp(positionOf(mesh, [], first), positionOf(mesh, [], second), fraction));+ extraSources.push({ from: first, to: second, t: fraction });points.set(edge, { vertex: mesh.vertexCount + extraPositions.length - 1, from: first, fraction });}return points;@@ -182,7 +183,8 @@ export function bisectPlane(mesh, { point, normal, distance = 1e-4, clearInner =const planeNormal = unit(normal);const { signs, offsets } = planeSigns(mesh, point, planeNormal, distance);const extraPositions = [];- const points = crossingPoints(mesh, signs, offsets, extraPositions);+ const extraSources = [];+ const points = crossingPoints(mesh, signs, offsets, extraPositions, extraSources);const pieces = [];let cutFaces = 0;facePolygons(mesh).forEach((polygon, index) => {@@ -211,21 +213,22 @@ export function bisectPlane(mesh, { point, normal, distance = 1e-4, clearInner =const innerCaps = clearInner ? { caps: [], open: 0 } : capsOf(inner);const outerCaps = clearOuter ? { caps: [], open: 0 } : capsOf(outer);if (!clearInner && !clearOuter) {- separateOuterShell(mesh, [...outer.map(({ polygon }) => polygon), ...outerCaps.caps], onPlane, extraPositions);+ separateOuterShell(mesh, [...outer.map(({ polygon }) => polygon), ...outerCaps.caps], onPlane, extraPositions, extraSources);}polygons.push(...innerCaps.caps, ...outerCaps.caps);capped = innerCaps.caps.length + outerCaps.caps.length;unfilled = innerCaps.open + outerCaps.open;}- return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), cutFaces, capped, unfilled, newVertices: points.size };+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions, extraSources), cutFaces, capped, unfilled, newVertices: points.size };}// With both halves kept and capped, the outer half gets its own copies of the vertices on the plane.-function separateOuterShell(mesh, outerPolygons, onPlane, extraPositions) {+function separateOuterShell(mesh, outerPolygons, onPlane, extraPositions, extraSources) {const copies = new Map();const copyOf = vertex => {if (!copies.has(vertex)) {extraPositions.push(positionOf(mesh, extraPositions, vertex));+ extraSources.push(vertex < mesh.vertexCount ? vertex : extraSources[vertex - mesh.vertexCount]);copies.set(vertex, mesh.vertexCount + extraPositions.length - 1);}return copies.get(vertex);diff --git a/src/mesh-bridge.js b/src/mesh-bridge.jsindex 7a5eaf3c..7dcaf88c 100644--- a/src/mesh-bridge.js+++ b/src/mesh-bridge.js@@ -12,8 +12,9 @@ function position(mesh, extraPositions, vertex) {const lerp = (first, second, fraction) => first.map((value, axis) => value + (second[axis] - value) * fraction);const distanceSquared = (first, second) => first.reduce((sum, value, axis) => sum + (value - second[axis]) ** 2, 0);-function newVertex(mesh, extraPositions, point) {+function newVertex(mesh, extraPositions, point, extraSources = null, source = -1) {extraPositions.push(point);+ extraSources?.push(source);return mesh.vertexCount + extraPositions.length - 1;}@@ -62,10 +63,12 @@ export function bridgeEdgeLoops(mesh, edgeMask, { segments = 1, twist = 0, nameconst shift = closed ? (bestShift(mesh, near, farReversed) + (twist % edgeCount) + edgeCount) % edgeCount : 0;const far = near.map((_, index) => farReversed[(index + shift) % farReversed.length]);const extraPositions = [];+ const extraSources = [];const rows = [near];for (let row = 1; row < segments; row++) {rows.push(near.map((vertex, index) => newVertex(mesh, extraPositions, lerp(position(mesh, extraPositions, vertex), position(mesh, extraPositions, far[index]), row / segments),+ extraSources, { from: vertex, to: far[index], t: row / segments },)));}rows.push(far);@@ -77,7 +80,7 @@ export function bridgeEdgeLoops(mesh, edgeMask, { segments = 1, twist = 0, namepolygons.push(strip([rows[row][next], rows[row][index], rows[row + 1][index], rows[row + 1][next]], sourceFace, `${name}.bridge`));}}- return { mesh: buildPolygonMesh(mesh, polygons, extraPositions), loopEdges: edgeCount, strips: segments * edgeCount };+ return { mesh: buildPolygonMesh(mesh, polygons, extraPositions, extraSources), loopEdges: edgeCount, strips: segments * edgeCount };}function faceNextCorner(mesh, corner) {diff --git a/src/mesh-edgesplit.js b/src/mesh-edgesplit.jsindex 6e3714ae..b5f138b1 100644--- a/src/mesh-edgesplit.js+++ b/src/mesh-edgesplit.js@@ -19,18 +19,25 @@ export function edgeSplitSize(mesh, edgeMask, cuts) {export function subdivideEdges(mesh, edgeMask, { cuts = 1, name = 'subdivide' } = {}) {const extraPositions = [];+ const extraSources = [];const base = mesh.vertexCount;const vertexPoint = vertex => [mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2]];- const addPoint = point => {+ const addPoint = (point, source = -1) => {extraPositions.push(point);+ extraSources.push(source);return base + extraPositions.length - 1;};const edgePoints = new Map();for (let edge = 0; edge < mesh.edgeCount; edge++) {if (!edgeMask[edge]) continue;- const start = vertexPoint(mesh.edgeVertices[edge * 2]);- const end = vertexPoint(mesh.edgeVertices[edge * 2 + 1]);- edgePoints.set(edge, Array.from({ length: cuts }, (_, index) => addPoint(lerp(start, end, (index + 1) / (cuts + 1)))));+ const from = mesh.edgeVertices[edge * 2];+ const to = mesh.edgeVertices[edge * 2 + 1];+ const start = vertexPoint(from);+ const end = vertexPoint(to);+ edgePoints.set(edge, Array.from({ length: cuts }, (_, index) => {+ const fraction = (index + 1) / (cuts + 1);+ return addPoint(lerp(start, end, fraction), { from, to, t: fraction });+ }));}const pointPosition = vertex => (vertex >= base ? extraPositions[vertex - base] : vertexPoint(vertex));const fractions = Array.from({ length: cuts }, (_, index) => (index + 1) / (cuts + 1));@@ -56,7 +63,7 @@ export function subdivideEdges(mesh, edgeMask, { cuts = 1, name = 'subdivide' }const pieces = size === 4 ? splitQuad(polygon, splitSides, pointsAfter, pointPosition, addPoint, cuts) : null;output.push(...(pieces ?? insertPoints(polygon, pointsAfter)).map(piece => ({ ...piece, tags: [...polygon.tags, `${name}.split`] })));}- return { mesh: buildPolygonMesh(mesh, output, extraPositions), splitEdges: edgePoints.size, splitFaces };+ return { mesh: buildPolygonMesh(mesh, output, extraPositions, extraSources), splitEdges: edgePoints.size, splitFaces };}function insertPoints(polygon, pointsAfter) {@@ -138,7 +145,8 @@ function gridFaces(quad, bottom, top, along, pointPosition, addPoint, cuts) {for (let row = 1; row < rows - 1; row++) {const columnFraction = column / (rows - 1);const t = row / (rows - 1);- grid[column][row] = addPoint(lerp(lerp(pa, pb, columnFraction), lerp(pd, pc, columnFraction), t));+ const weights = [[vertexA, (1 - columnFraction) * (1 - t)], [vertexB, columnFraction * (1 - t)], [vertexC, columnFraction * t], [vertexD, (1 - columnFraction) * t]];+ grid[column][row] = addPoint(lerp(lerp(pa, pb, columnFraction), lerp(pd, pc, columnFraction), t), { weights });}}const cells = [];diff --git a/src/mesh-knife.js b/src/mesh-knife.jsindex 6514d3ef..ed04fc87 100644--- a/src/mesh-knife.js+++ b/src/mesh-knife.js@@ -38,7 +38,7 @@ function insidePolygon(point, polygon) {}/** Where each mesh edge meets the projected line: { t, vertex, s, inserted } sorted by t from the edge's first vertex. */-function edgeCrossings(mesh, flat, vertexPoint, line, extraPositions) {+function edgeCrossings(mesh, flat, vertexPoint, line, extraPositions, extraSources) {const crossings = new Map();for (let edge = 0; edge < mesh.edgeCount; edge++) {const first = mesh.edgeVertices[edge * 2];@@ -62,6 +62,7 @@ function edgeCrossings(mesh, flat, vertexPoint, line, extraPositions) {else if (clamped > 1 - SNAP) found.push({ t: 1, vertex: second, s: distanceAlongLine, inserted: false });else {extraPositions.push(lerp(vertexPoint(first), vertexPoint(second), clamped));+ extraSources.push({ from: first, to: second, t: clamped });found.push({ t: clamped, vertex: mesh.vertexCount + extraPositions.length - 1, s: distanceAlongLine, inserted: true });}}@@ -135,21 +136,22 @@ export function knifeCut(mesh, { path, direction, name = 'knife' }) {}const line = { points, lengths };const extraPositions = [];- const crossings = edgeCrossings(mesh, flat, vertexPoint, line, extraPositions);+ const extraSources = [];+ const crossings = edgeCrossings(mesh, flat, vertexPoint, line, extraPositions, extraSources);const output = [];let cutFaces = 0;for (const polygon of facePolygons(mesh)) {const { outline, events } = outlineWithCrossings(mesh, polygon, crossings);- const parts = splitFace(mesh, polygon, outline, events, { basis, line, flat, vertexPoint, extraPositions, name });+ const parts = splitFace(mesh, polygon, outline, events, { basis, line, flat, vertexPoint, extraPositions, extraSources, name });if (parts.length > 1) cutFaces++;output.push(...parts);}if (cutFaces === 0) throw new RangeError('The line does not cross any face when projected along the direction. Check path and direction against the mesh bounds.');- return { mesh: buildPolygonMesh(mesh, output, extraPositions), cutFaces, newVertices: extraPositions.length };+ return { mesh: buildPolygonMesh(mesh, output, extraPositions, extraSources), cutFaces, newVertices: extraPositions.length };}function splitFace(mesh, polygon, outline, events, context) {- const { basis, line, flat, vertexPoint, extraPositions, name } = context;+ const { basis, line, flat, vertexPoint, extraPositions, extraSources, name } = context;const corners3d = polygon.vertices.map(vertexPoint);const normal = faceNormal(corners3d);if (Math.abs(dot(normal, basis.along)) < 1e-9 * Math.hypot(...normal)) return [outline];@@ -171,6 +173,7 @@ function splitFace(mesh, polygon, outline, events, context) {line.lengths.forEach((length, vertexIndex) => {if (length <= from.s + 1e-9 || length >= to.s - 1e-9) return;extraPositions.push(liftOntoFace(line.points[vertexIndex], basis, centre, normal));+ extraSources.push(-1);inner.push(mesh.vertexCount + extraPositions.length - 1);});parts = parts.flatMap(part => {diff --git a/src/mesh-polygons.js b/src/mesh-polygons.jsindex f9e47c14..8c244f47 100644--- a/src/mesh-polygons.js+++ b/src/mesh-polygons.js@@ -23,7 +23,8 @@ export function facePolygons(mesh) {/*** Build MeshData from polygons, dropping vertices that no polygon uses. Point attributes follow their vertex; an extra- * vertex copies the values of `extraSources[index]` (a source vertex number) when that is given.+ * vertex copies the values of `extraSources[index]` when that is given: a source vertex number, `{ from, to, t }` to blend+ * two vertices, or `{ weights }` to blend several (see MeshBuilder.addVertex).*/export function buildPolygonMesh(mesh, polygons, extraPositions = [], extraSources = []) {const used = new Set();diff --git a/src/mesh-select.js b/src/mesh-select.jsindex 29d220ca..f621e842 100644--- a/src/mesh-select.js+++ b/src/mesh-select.js@@ -115,7 +115,8 @@ export function selectFaces(mesh, rule) {return mask;}case 'faces': {- if (keys.length !== 1 || !Array.isArray(node.faces) || node.faces.length > mesh.faceCount) throw ruleError('"faces" needs an array of face indices.');+ if (keys.length !== 1 || !Array.isArray(node.faces)) throw ruleError('"faces" needs an array of face indices.');+ if (node.faces.length > mesh.faceCount) throw ruleError(`"faces" lists ${node.faces.length} indices but the mesh has ${mesh.faceCount} faces; list each face once.`);for (const face of node.faces) {if (!Number.isInteger(face) || face < 0 || face >= mesh.faceCount) throw new RangeError(`Face index ${face} is outside 0..${mesh.faceCount - 1}.`);mask[face] = 1;diff --git a/src/mesh-stack.js b/src/mesh-stack.jsindex b5c2a453..57226098 100644--- a/src/mesh-stack.js+++ b/src/mesh-stack.js@@ -28,7 +28,8 @@ export class MeshBuilder {/*** sourceVertex: the source vertex whose point attributes this vertex copies (-1 for none), or { from, to, t } to blend- * two source vertices: floats blend by t, integer and boolean values take `from`.+ * two source vertices (floats blend by t, integer and boolean values take `from`), or { weights: [[vertex, weight], ...] }+ * to blend several (integer and boolean values take the heaviest).*/addVertex(x, y, z, sourceVertex = -1) {this.positions.push(x, y, z);@@ -67,6 +68,10 @@ export class MeshBuilder {data.set(attribute.data.subarray(sourceVertex * size, (sourceVertex + 1) * size), vertex * size);return;}+ if (sourceVertex.weights) {+ blendWeighted(data, attribute, vertex, sourceVertex.weights, blends);+ return;+ }const { from, to, t } = sourceVertex;for (let component = 0; component < size; component++) {const start = attribute.data[from * size + component];@@ -116,6 +121,10 @@ export class MeshBuilder {data.set(attribute.data.subarray(sourceCorner * attribute.size, (sourceCorner + 1) * attribute.size), corner * attribute.size);return;}+ if (sourceCorner.weights) {+ blendWeighted(data, attribute, corner, sourceCorner.weights, blends);+ 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++) {@@ -144,17 +153,17 @@ export class MeshBuilder {}}-/** A corner made from several source corners, each with a weight; integer attributes copy the heaviest one. */-function blendWeighted(data, attribute, corner, weights, blends) {+/** A corner or vertex made from several sources, each with a weight; integer attributes copy the heaviest one. */+function blendWeighted(data, attribute, slot, weights, blends) {const heaviest = weights.reduce((best, entry) => (entry[1] > best[1] ? entry : best));for (let component = 0; component < attribute.size; component++) {if (!blends) {- data[corner * attribute.size + component] = attribute.data[heaviest[0] * attribute.size + component];+ data[slot * attribute.size + component] = attribute.data[heaviest[0] * attribute.size + component];continue;}let sum = 0;for (const [source, weight] of weights) sum += attribute.data[source * attribute.size + component] * weight;- data[corner * attribute.size + component] = sum;+ data[slot * attribute.size + component] = sum;}}diff --git a/tests/mesh-cut-new-points.test.js b/tests/mesh-cut-new-points.test.jsnew file mode 100644index 00000000..2da071bb--- /dev/null+++ b/tests/mesh-cut-new-points.test.js@@ -0,0 +1,55 @@+import './support/load-agent-scene-modules.mjs';+import assert from 'node:assert/strict';+import test from 'node:test';+import { box, torus } from '../src/geometry.js';+import { meshFromGeometry, applyMeshEdits, selectFaces } from '../src/mesh.js';+import { vertexGroupWeights } from '../src/mesh-data.js';++// The group weighs each vertex by its x position (0 at x = -0.5, 1 at x = 0.5), so a point inserted on a straight edge+// or inside a quad must read the same value as its own x.+const GROUP = { op: 'vertex_group', name: 'ramp', select: { all: true }, gradient: { axis: 'x', range: [-0.5, 0.5], weights: [0, 1] } };++function rampedCube() {+ return applyMeshEdits(meshFromGeometry(box(0, 1)), [GROUP]).mesh;+}++function assertGroupFollowsX(mesh) {+ const weights = vertexGroupWeights(mesh, 'ramp');+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ const expected = Math.min(1, Math.max(0, mesh.positions[vertex * 3] + 0.5));+ assert.ok(Math.abs(weights[vertex] - expected) < 1e-4, `vertex ${vertex} at x ${mesh.positions[vertex * 3]} has weight ${weights[vertex]}, expected ${expected}`);+ }+}++test('subdivide_edges keeps UVs finite when all four sides of a quad are split', () => {+ const torusMesh = meshFromGeometry(torus(0.3, 8, 6));+ const { mesh } = applyMeshEdits(torusMesh, [{ op: 'subdivide_edges', edges: { all: true }, cuts: 2 }]);+ assert.ok(mesh.attributes.corner.uv.data.every(Number.isFinite));+ assert.equal(mesh.faceCount, torusMesh.faceCount * 9);+});++test('subdivide_edges blends vertex groups onto edge points and grid points', () => {+ assertGroupFollowsX(applyMeshEdits(rampedCube(), [{ op: 'subdivide_edges', edges: { all: true }, cuts: 2 }]).mesh);+});++test('bisect_plane blends vertex groups onto cut points, with the cap and a separated shell', () => {+ const plane = { op: 'bisect_plane', point: [0.1, 0, 0], normal: [0, 1, 0.3] };+ assertGroupFollowsX(applyMeshEdits(rampedCube(), [plane]).mesh);+ assertGroupFollowsX(applyMeshEdits(rampedCube(), [{ ...plane, fill: true }]).mesh);+});++test('knife_project blends vertex groups onto the points it inserts on edges', () => {+ const knife = { op: 'knife_project', path: [[-1, 0.1, 2], [1, 0.3, 2]], direction: [0, 0, -1] };+ assertGroupFollowsX(applyMeshEdits(rampedCube(), [knife]).mesh);+});++test('bridge_edge_loops blends vertex groups onto its middle rows', () => {+ const edits = [{ op: 'delete', select: { or: [{ tag: 'top' }, { tag: 'bottom' }] } }, { op: 'bridge_edge_loops', edges: { open: true }, segments: 3 }];+ assertGroupFollowsX(applyMeshEdits(rampedCube(), edits).mesh);+});++test('a selection rule listing more faces than the mesh has says so', () => {+ const cube = meshFromGeometry(box(0, 1));+ assert.throws(() => selectFaces(cube, { faces: [0, 0, 0, 0, 0, 0, 0] }), /lists 7 indices but the mesh has 6 faces/);+ assert.throws(() => selectFaces(cube, { faces: 'a' }), /needs an array of face indices/);+});