3D engine that AI agents drive
Add unsubdivide and circularize edits and Blender golden cases for poke, dual, tris to quads and symmetrize (part of #703)
Nguyen Xuan Andc9f148cb8e4
diff --git a/changes/703-rest.size.md b/changes/703-rest.size.mdnew file mode 100644index 00000000..ed001425--- /dev/null+++ b/changes/703-rest.size.md@@ -0,0 +1,3 @@+- entry:mesh: unsubdivide (a role search that tells a Catmull-Clark level apart from other quad meshes, with errors that name the quad) and circularize (loop walk, best plane, circle fit) are agent-facing modeling edits, about 2 KB gzip for both.+- scene:agent-scene+lazy: unsubdivide and circularize are agent-facing modeling edits, loaded lazily with the mesh engine.+- goal:agent-scene: the core bundle grows a few bytes gzip for the two edit names in the shared operation table.diff --git a/changes/703.md b/changes/703.mdnew file mode 100644index 00000000..45595160--- /dev/null+++ b/changes/703.md@@ -0,0 +1 @@+- `mesh_edit` gains `unsubdivide` and `circularize`, and poke, dual, tris to quads and symmetrize now have Blender golden cases (#703).diff --git a/docs/mesh.md b/docs/mesh.mdindex 931b5909..1241d9ff 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -410,6 +410,9 @@ lower index, so the same input always gives the same bytes. Faces they keep carr| `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. |+| `unsubdivide` | none | none | Reverses one Catmull-Clark level: the original vertices and the coarse faces they make (n-gons too) are kept, every face point and edge point is dropped. The survivors stay where they are, so the smoothing is not undone. Fails, naming the quad that breaks the pattern, when the mesh has a non-quad face or is not one level of subdivision. |+| `circularize` | `verts`, `factor` (0 to 1, default 1), `regular` (default true) | none | LoopTools Circle: each closed loop of selected vertices (every vertex with exactly two selected neighbours) lands on a circle in the loop's best plane, centred on its average point, with the average distance as radius. `regular` spaces the vertices evenly from the first; otherwise each keeps its own angle. Topology is unchanged. |+`dual` and `symmetrize` leave a closed surface closed. `extrude_edges` on interior edges adds a fin, so a closedmesh is no longer closed afterwards. `extrude_vertices` is not offered: a mesh derives its edges from faces and cannothold a loose edge. The size of `poke`, `split_edges` and `extrude_edges` is checked before they allocate. The `meshEdit.<op>`diff --git a/docs/parity.md b/docs/parity.mdindex 81a3a177..6d1d9aff 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -47,7 +47,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Modeling > Meshes > Primitives | partial | Box, cylinder, sphere and torus. There is no plane, grid, cone, ico sphere or monkey primitive. | | || Modeling > Meshes > Tools | partial | The operations behind extrude and loop cut exist as edits. Spin is covered only by `lathe`. | | #41 || Modeling > Meshes > Selecting | partial | Rules: all, tag, normal, inside, faces, and, or, not, grow, boundary. There is no loop, linked, similar or sharp edge selection. | | #41 |-| Modeling > Meshes > Editing | partial | 32 edits, including extrude, inset, bevel, loop cut, boolean, merge, bisect, bridge, fill, grid fill, dissolve, edge subdivision, a knife by projected polyline, poke, dual, tris to quads, symmetrize, scale elements and extrude edges. All but the knife and the six newest match Blender on fixtures (those six have unit tests; Blender cases are open in #703); the knife is compared only with a straight plane cut. | [Blender results](../tests/fixtures/blender/golden.json) | #41 |+| Modeling > Meshes > Editing | partial | 36 edits, including extrude, inset, bevel, loop cut, boolean, merge, bisect, bridge, fill, grid fill, dissolve, edge subdivision, a knife by projected polyline, poke, dual, tris to quads, symmetrize, scale elements, extrude edges, split edges, delete loose, flatten, unsubdivide and circularize. Poke, dual, tris to quads, symmetrize and the older edits match Blender on fixtures; scale elements, extrude edges, split edges, delete loose, flatten, unsubdivide and circularize have unit tests only (unsubdivide keeps the surviving vertices in place like Blender, and circularize follows LoopTools, which is an add-on with no headless reference); the knife is compared only with a straight plane cut. | [Blender results](../tests/fixtures/blender/golden.json) | #41 || Modeling > Meshes > Properties | partial | `smoothAngle` and face tags. There is no sharp edge attribute or crease. | | #39 || Modeling > Meshes > UVs | partial | `uv_unwrap` with LSCM, axis charts and shelf packing. Patterns can not use the result yet. | | #50 || Modeling > Meshes > Mesh Analysis | partial | `lintMesh` reports topology problems. With `{ geometry: true }` (always on in `mesh_inspect`) it also warns of crossing parts, a solid cutting itself, thin walls, floating parts and near-symmetry, using the BVH within face budgets. Checks are heuristics on parts, not Blender's exact Select Non-Manifold or Intersect checks. | [tests/mesh-lint-geometry.test.js](../tests/mesh-lint-geometry.test.js), [src/mesh-lint-geometry.js](../src/mesh-lint-geometry.js) | #66 |diff --git a/scripts/blender-golden.py b/scripts/blender-golden.pyindex 430d6467..d3963fae 100644--- a/scripts/blender-golden.py+++ b/scripts/blender-golden.py@@ -295,7 +295,27 @@ def sculpt(bm, edit):vertex.co = point+def poke(bm, edit):+ bmesh.ops.poke(bm, faces=selected_faces(bm, edit["select"]), offset=edit.get("offset", 0), center_mode="MEAN", use_relative_offset=edit.get("relative", False))+++# 67js joins by the angle between face normals only, so the shape limit is opened fully.+def tris_to_quads(bm, edit):+ bmesh.ops.join_triangles(bm, faces=selected_faces(bm, edit["select"]), angle_face_threshold=radians(edit.get("angle", 40)), angle_shape_threshold=radians(180))+++# Blender's direction "-X" copies the negative half over the positive one, so keeping the positive half is "X".+def symmetrize(bm, edit):+ axis = edit.get("axis", "x").upper()+ direction = axis if edit.get("keep", "positive") == "positive" else "-" + axis+ geometry = list(bm.verts) + list(bm.edges) + list(bm.faces)+ bmesh.ops.symmetrize(bm, input=geometry, direction=direction, dist=edit.get("distance", 1e-4))++BMESH_OPERATIONS = {+ "poke": poke,+ "tris_to_quads": tris_to_quads,+ "symmetrize": symmetrize,"sculpt": sculpt,"extrude_face_region": extrude_face_region,"extrude_individual": extrude_individual,@@ -559,7 +579,21 @@ def add_wave(mesh_object, edit, _inputs):bpy.context.scene.frame_set(int(edit.get("time", 0)))+def add_dual(mesh_object, _edit, _inputs):+ tree = bpy.data.node_groups.new("DualMesh", "GeometryNodeTree")+ tree.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry")+ tree.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry")+ group_input = tree.nodes.new("NodeGroupInput")+ group_output = tree.nodes.new("NodeGroupOutput")+ dual = tree.nodes.new("GeometryNodeDualMesh")+ tree.links.new(group_input.outputs[0], dual.inputs["Mesh"])+ tree.links.new(dual.outputs["Dual Mesh"], group_output.inputs[0])+ modifier = mesh_object.modifiers.new("DualMesh", "NODES")+ modifier.node_group = tree++MODIFIERS = {+ "dual": add_dual,"wave": add_wave,"screw": add_screw,"wireframe": add_wireframe,diff --git a/src/mesh-operations.js b/src/mesh-operations.jsindex 434ba43e..3b359192 100644--- a/src/mesh-operations.js+++ b/src/mesh-operations.js@@ -66,6 +66,8 @@ export const MESH_EDIT_OPERATIONS = /* @__PURE__ */ Object.freeze({split_edges: { fields: ['edges', 'name'], tags: [] },delete_loose: { fields: [], tags: [] },flatten: { fields: ['verts', 'normal', 'factor'], tags: [] },+ unsubdivide: { fields: [], tags: [] },+ circularize: { fields: ['verts', 'factor', 'regular'], 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.jsindex e47285ae..81a948e2 100644--- a/src/mesh-reshape-edits.js+++ b/src/mesh-reshape-edits.js@@ -1,5 +1,6 @@import { selectVertices } from './mesh-dissolve.js';-import { splitEdges, deleteLoose, flattenVertices } from './mesh-reshape-more.js';+import { splitEdges, deleteLoose, flattenVertices, circularizeVertices } from './mesh-reshape-more.js';+import { unsubdivideMesh } from './mesh-unsubdivide.js';import { selectEdges, edgeFaces } from './mesh-bevel.js';import { selectFaces, countSelected } from './mesh-select.js';import { invalidField } from './field-error.js';@@ -10,7 +11,7 @@ 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', 'split_edges', 'delete_loose', 'flatten']);+export const RESHAPE_OPERATIONS = Object.freeze(['poke', 'dual', 'tris_to_quads', 'symmetrize', 'scale_elements', 'extrude_edges', 'split_edges', 'delete_loose', 'flatten', 'unsubdivide', 'circularize']);const SYMMETRIZE_SIDES = Object.freeze(['positive', 'negative']);const MAX_SCALE = 1000;@@ -48,6 +49,12 @@ export function normalizeReshapeEdit(edit, normalized, index, { finiteNumber, ve}normalized.factor = edit.factor === undefined ? 1 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1 });break;+ case 'circularize':+ normalized.verts = editRuleObject(edit.verts, index, 'verts', VERTEX_RULE_HINT);+ normalized.factor = edit.factor === undefined ? 1 : finiteNumber(edit.factor, index, 'factor', { minimum: 0, maximum: 1 });+ if (edit.regular !== undefined && typeof edit.regular !== 'boolean') throw editField(index, 'regular', edit.regular, 'true or false');+ normalized.regular = edit.regular ?? true;+ break;case 'extrude_edges':normalized.edges = editRuleObject(edit.edges, index, 'edges', EDGE_RULE_HINT);normalized.offset = vector(edit.offset, index, 'offset');@@ -127,6 +134,14 @@ export function runReshapeEdit(mesh, edit) {const outcome = flattenVertices(mesh, selectVertices(mesh, edit.verts), { normal: edit.normal, factor: edit.factor });return { mesh: outcome.mesh, result: { flattenedVertices: outcome.flattenedVertices } };}+ case 'unsubdivide': {+ const outcome = unsubdivideMesh(mesh);+ return { mesh: outcome.mesh, result: { coarseFaces: outcome.coarseFaces, removedVertices: outcome.removedVertices } };+ }+ case 'circularize': {+ const outcome = circularizeVertices(mesh, selectVertices(mesh, edit.verts), { factor: edit.factor, regular: edit.regular });+ return { mesh: outcome.mesh, result: { circularizedVertices: outcome.circularizedVertices } };+ }}throw new TypeError(`Not a reshaping edit: ${edit.op}`);}diff --git a/src/mesh-reshape-more.js b/src/mesh-reshape-more.jsindex fa519722..afac867f 100644--- a/src/mesh-reshape-more.js+++ b/src/mesh-reshape-more.js@@ -123,3 +123,100 @@ export function flattenVertices(mesh, vertexMask, { normal = null, factor = 1 }});return { mesh: flattened, flattenedVertices: count };}++function crossProduct(first, second) {+ return [first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]];+}++function dotProduct(first, second) {+ return first[0] * second[0] + first[1] * second[1] + first[2] * second[2];+}++/** The selected vertices as closed loops: every vertex has exactly two selected neighbours along an edge. */+function selectedLoops(mesh, vertexMask) {+ const neighbors = new Map();+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ if (!vertexMask[first] || !vertexMask[second]) continue;+ for (const [vertex, other] of [[first, second], [second, first]]) {+ if (!neighbors.has(vertex)) neighbors.set(vertex, []);+ neighbors.get(vertex).push(other);+ }+ }+ const loops = [];+ const visited = new Set();+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!vertexMask[vertex]) continue;+ const around = neighbors.get(vertex) ?? [];+ if (around.length !== 2) {+ throw new RangeError(`Vertex ${vertex} has ${around.length} selected neighbours; circularize needs closed loops where each vertex has exactly 2. Select only the vertices of the loop, such as { "vertices": [0, 1, 2, 3] }.`);+ }+ if (visited.has(vertex)) continue;+ const loop = [vertex];+ visited.add(vertex);+ let previous = vertex;+ let current = Math.min(...around);+ while (current !== vertex) {+ loop.push(current);+ visited.add(current);+ const [one, two] = neighbors.get(current);+ if (one === undefined || two === undefined) throw new RangeError('The selected vertices do not form closed loops.');+ const next = one === previous ? two : one;+ previous = current;+ current = next;+ }+ if (loop.length < 3) throw new RangeError(`The loop through vertex ${vertex} has ${loop.length} vertices; circularize needs at least 3.`);+ loops.push(loop);+ }+ if (loops.length === 0) throw new RangeError('The rule selects no vertex. Use a loop such as { "vertices": [0, 1, 2, 3] }.');+ return loops;+}++/**+ * Turn each selected vertex loop into a circle after LoopTools Circle. The circle lies in the loop's best plane (the+ * Newell normal), centred on the average point, with the average distance as its radius. `regular` spaces the vertices+ * evenly from the first one; otherwise each keeps its own angle. `factor` 1 lands on the circle and 0 changes nothing.+ */+export function circularizeVertices(mesh, vertexMask, { factor = 1, regular = true } = {}) {+ const positions = Float32Array.from(mesh.positions);+ let circularizedVertices = 0;+ for (const loop of selectedLoops(mesh, vertexMask)) {+ const points = loop.map(vertex => positionOf(mesh, vertex));+ const center = [0, 1, 2].map(axis => points.reduce((sum, point) => sum + point[axis], 0) / points.length);+ const offsets = points.map(point => point.map((value, axis) => value - center[axis]));+ const normal = [0, 0, 0];+ offsets.forEach((offset, index) => {+ const area = crossProduct(offset, offsets[(index + 1) % offsets.length]);+ for (let axis = 0; axis < 3; axis++) normal[axis] += area[axis];+ });+ const normalLength = Math.hypot(...normal);+ if (normalLength === 0) throw new RangeError(`The loop through vertex ${loop[0]} is degenerate (no plane); circularize needs a loop that encloses an area.`);+ const unit = normal.map(value => value / normalLength);+ const inPlane = offsets.map(offset => {+ const height = dotProduct(offset, unit);+ return offset.map((value, axis) => value - unit[axis] * height);+ });+ const radius = inPlane.reduce((sum, offset) => sum + Math.hypot(...offset), 0) / inPlane.length;+ const firstLength = Math.hypot(...inPlane[0]);+ if (firstLength === 0) throw new RangeError(`Vertex ${loop[0]} sits on the loop's centre; circularize cannot tell its direction.`);+ const along = inPlane[0].map(value => value / firstLength);+ const across = crossProduct(unit, along);+ loop.forEach((vertex, index) => {+ const angle = regular+ ? index * 2 * Math.PI / loop.length+ : Math.atan2(dotProduct(inPlane[index], across), dotProduct(inPlane[index], along));+ for (let axis = 0; axis < 3; axis++) {+ const target = center[axis] + radius * (Math.cos(angle) * along[axis] + Math.sin(angle) * across[axis]);+ const current = positions[vertex * 3 + axis];+ positions[vertex * 3 + axis] = current + (target - current) * factor;+ }+ circularizedVertices++;+ });+ }+ const circular = createMeshData({+ positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes: mesh.attributes,+ });+ return { mesh: circular, circularizedVertices };+}diff --git a/src/mesh-unsubdivide.js b/src/mesh-unsubdivide.jsnew file mode 100644index 00000000..045e63bb--- /dev/null+++ b/src/mesh-unsubdivide.js@@ -0,0 +1,164 @@+import { MeshBuilder } from './mesh-stack.js';++// Unsubdivide: reverse one level of Catmull-Clark subdivision where the topology allows it.+//+// One level turns every coarse face into quads that each hold one face point, two edge points and one original vertex,+// in that cyclic order. So the vertices fall into three roles, and the original vertices (with the coarse faces made of+// them) are what is left. The surviving vertices stay where they are: the smoothing is not undone, so a subdivide+// followed by an unsubdivide gives the coarse topology with vertices pulled slightly inward, like Blender's Un-Subdivide.++const EDGE_POINT = 0;+const FACE_POINT = 1;+const ORIGINAL = 2;+const NO_ROLE = -1;++function cornersOf(mesh, face) {+ return Array.from(mesh.cornerVertices.subarray(mesh.faceOffsets[face], mesh.faceOffsets[face + 1]));+}++function neighborLists(mesh) {+ const neighbors = Array.from({ length: mesh.vertexCount }, () => []);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ neighbors[first].push(second);+ neighbors[second].push(first);+ }+ return neighbors;+}++function facesOfVertex(mesh) {+ const faces = Array.from({ length: mesh.vertexCount }, () => []);+ for (let face = 0; face < mesh.faceCount; face++) {+ for (const vertex of cornersOf(mesh, face)) faces[vertex].push(face);+ }+ return faces;+}++/** Walk the vertices of one connected piece in index order, 2-coloring them by edge. Returns null when an edge joins equal colors. */+function bipartitePiece(start, neighbors, color) {+ const piece = [start];+ color[start] = 0;+ for (let index = 0; index < piece.length; index++) {+ const vertex = piece[index];+ for (const other of neighbors[vertex]) {+ if (color[other] === -1) {+ color[other] = 1 - color[vertex];+ piece.push(other);+ } else if (color[other] === color[vertex]) {+ return null;+ }+ }+ }+ return piece;+}++/** Give the vertices that are not edge points the role face point or original so that every quad has one of each. */+function assignFaceAndOriginal(mesh, piece, faceLists, roles, seedRole) {+ const seed = piece.find(vertex => roles[vertex] === NO_ROLE);+ if (seed === undefined) return 'it has no vertex besides the edge points';+ const queue = [seed];+ roles[seed] = seedRole;+ for (let index = 0; index < queue.length; index++) {+ const vertex = queue[index];+ for (const face of faceLists[vertex]) {+ const corners = cornersOf(mesh, face);+ const opposite = corners[(corners.indexOf(vertex) + 2) % 4];+ if (roles[opposite] === NO_ROLE) {+ roles[opposite] = roles[vertex] === FACE_POINT ? ORIGINAL : FACE_POINT;+ queue.push(opposite);+ } else if (roles[opposite] === roles[vertex]) {+ return `quad ${face} joins two vertices of the same kind across its diagonal`;+ }+ }+ }+ return null;+}++/** The coarse face around one face point: the original vertex of each quad around it, in winding order. Returns { error } on failure. */+function coarseFaceAround(mesh, facePoint, faceLists, roles) {+ const quads = faceLists[facePoint].map(face => {+ const corners = cornersOf(mesh, face);+ const start = corners.indexOf(facePoint);+ const [, edgeBefore, original, edgeAfter] = [0, 1, 2, 3].map(offset => corners[(start + offset) % 4]);+ const fits = roles[edgeBefore] === EDGE_POINT && roles[original] === ORIGINAL && roles[edgeAfter] === EDGE_POINT;+ return { face, edgeBefore, original, edgeAfter, fits };+ });+ const misfit = quads.find(quad => !quad.fits);+ if (misfit) return { error: `quad ${misfit.face} around vertex ${facePoint} is not face point, edge point, original vertex, edge point` };+ const byEdgeBefore = new Map(quads.map(quad => [quad.edgeBefore, quad]));+ if (byEdgeBefore.size !== quads.length) return { error: `the quads around vertex ${facePoint} share an edge point twice` };+ const polygon = [];+ let quad = quads[0];+ do {+ polygon.push(quad.original);+ quad = byEdgeBefore.get(quad.edgeAfter);+ } while (quad && quad !== quads[0] && polygon.length <= quads.length);+ if (quad !== quads[0] || polygon.length !== quads.length) return { error: `the quads around vertex ${facePoint} do not close into one ring` };+ if (polygon.length < 3 || new Set(polygon).size !== polygon.length) return { error: `vertex ${facePoint} would make a coarse face of fewer than 3 distinct vertices` };+ return { polygon, quadCount: quads.length };+}++function tryRoles(mesh, piece, edgeClass, seedRole, faceLists, color) {+ const roles = new Int8Array(mesh.vertexCount).fill(NO_ROLE);+ const ascending = [...piece].sort((first, second) => first - second);+ for (const vertex of ascending) {+ if (color[vertex] === edgeClass) roles[vertex] = EDGE_POINT;+ }+ const failure = assignFaceAndOriginal(mesh, piece, faceLists, roles, seedRole);+ if (failure) return { error: failure };+ const polygons = [];+ let quadsCovered = 0;+ for (const vertex of ascending) {+ if (roles[vertex] !== FACE_POINT) continue;+ const outcome = coarseFaceAround(mesh, vertex, faceLists, roles);+ if (outcome.error) return outcome;+ polygons.push(outcome.polygon);+ quadsCovered += outcome.quadCount;+ }+ const quadsInPiece = new Set(piece.flatMap(vertex => faceLists[vertex])).size;+ if (quadsCovered !== quadsInPiece) return { error: 'some quads have no face point' };+ return { polygons };+}++function coarsePolygonsOfPiece(mesh, piece, faceLists, color) {+ const seedClass = color[piece[0]];+ const firstError = [];+ for (const edgeClass of [1 - seedClass, seedClass]) {+ for (const seedRole of [ORIGINAL, FACE_POINT]) {+ const outcome = tryRoles(mesh, piece, edgeClass, seedRole, faceLists, color);+ if (outcome.polygons) return outcome.polygons;+ firstError.push(outcome.error);+ }+ }+ return { error: firstError[0] };+}++/**+ * Reverse one Catmull-Clark level. Needs a mesh made only of quads that came from one subdivision (every coarse face+ * becomes one face, every original vertex survives at its place). Throws a RangeError that names the quad that breaks it.+ */+export function unsubdivideMesh(mesh) {+ const triangleOrPolygon = Array.from({ length: mesh.faceCount }, (_, face) => face)+ .find(face => mesh.faceOffsets[face + 1] - mesh.faceOffsets[face] !== 4);+ if (triangleOrPolygon !== undefined) {+ throw new RangeError(`Face ${triangleOrPolygon} is not a quad; unsubdivide reverses Catmull-Clark subdivision, which leaves only quads. Run tris_to_quads first, or use a mesh from the subdivide edit.`);+ }+ const neighbors = neighborLists(mesh);+ const faceLists = facesOfVertex(mesh);+ const color = new Int8Array(mesh.vertexCount).fill(-1);+ const allPolygons = [];+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (color[vertex] !== -1 || neighbors[vertex].length === 0) continue;+ const piece = bipartitePiece(vertex, neighbors, color);+ if (!piece) throw new RangeError(`The edges around vertex ${vertex} form an odd cycle, so the mesh is not a subdivided surface (a subdivided mesh alternates edge points and the rest). Unsubdivide needs one level of Catmull-Clark output.`);+ const polygons = coarsePolygonsOfPiece(mesh, piece, faceLists, color);+ if (polygons.error) throw new RangeError(`The mesh is not one level of Catmull-Clark subdivision: ${polygons.error}. Unsubdivide only reverses that exact pattern.`);+ allPolygons.push(...polygons);+ }+ const survivors = [...new Set(allPolygons.flat())].sort((first, second) => first - second);+ const builder = new MeshBuilder(mesh);+ const remap = new Map(survivors.map(vertex => [vertex, builder.addVertex(mesh.positions[vertex * 3], mesh.positions[vertex * 3 + 1], mesh.positions[vertex * 3 + 2])]));+ for (const polygon of allPolygons) builder.addFace(polygon.map(vertex => remap.get(vertex)));+ return { mesh: builder.build(), coarseFaces: allPolygons.length, removedVertices: mesh.vertexCount - survivors.length };+}diff --git a/tests/fixtures/blender/cases.json b/tests/fixtures/blender/cases.jsonindex ce2ed760..bf2c624d 100644--- a/tests/fixtures/blender/cases.json+++ b/tests/fixtures/blender/cases.json@@ -9,6 +9,14 @@"vertices": [[-0.5,-0.5,-0.5],[0.5,-0.5,-0.5],[0.5,0.5,-0.5],[-0.5,0.5,-0.5],[-0.5,-0.5,0.5],[0.5,-0.5,0.5],[0.5,0.5,0.5],[-0.5,0.5,0.5]],"faces": [[0,3,2,1],[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7]]},+ "cube-triangulated": {+ "vertices": [[-0.5,-0.5,-0.5],[0.5,-0.5,-0.5],[0.5,0.5,-0.5],[-0.5,0.5,-0.5],[-0.5,-0.5,0.5],[0.5,-0.5,0.5],[0.5,0.5,0.5],[-0.5,0.5,0.5]],+ "faces": [[0,3,2],[0,2,1],[4,5,6],[4,6,7],[0,1,5],[0,5,4],[1,2,6],[1,6,5],[2,3,7],[2,7,6],[3,0,4],[3,4,7]]+ },+ "cube-skewed": {+ "vertices": [[-0.5,-0.5,-0.5],[0.5,-0.5,-0.5],[0.5,1,-0.5],[-0.5,0.5,-0.5],[-0.5,-0.5,0.5],[0.5,-0.5,0.5],[0.5,1,0.5],[-0.5,0.5,0.5]],+ "faces": [[0,3,2,1],[4,5,6,7],[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7]]+ },"cube-touching-plane": {"vertices": [[0,-0.5,-0.5],[1,-0.5,-0.5],[1,0.5,-0.5],[0,0.5,-0.5],[0,-0.5,0.5],[1,-0.5,0.5],[1,0.5,0.5],[0,0.5,0.5]],"faces": [[0,3,2,1],[4,5,6,7],[0,1,5,4],[1,2,6,5],[2,3,7,6],[3,0,4,7]]@@ -115,6 +123,16 @@{ "id": "subdivide-edges-grid-along", "input": "grid", "edit": {"op":"subdivide_edges","edges":{"along":[1,0,0]},"cuts":2} },{ "id": "grid-fill-grid-hole", "input": "grid-hole", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[0.9,0.9,-1],"max":[3.1,3.1,1]}}}} },{ "id": "grid-fill-cylinder-open", "input": "cylinder-open", "edit": {"op":"grid_fill","edges":{"open":{"inside":{"min":[-2,-2,0.9],"max":[2,2,1.1]}}}} },+ { "id": "poke-cube-top", "input": "cube", "edit": {"op":"poke","select":{"faces":[1]},"offset":0.25} },+ { "id": "poke-cube-top-relative", "input": "cube", "edit": {"op":"poke","select":{"faces":[1]},"offset":0.5,"relative":true} },+ { "id": "poke-cube-all", "input": "cube", "edit": {"op":"poke","select":{"faces":[0,1,2,3,4,5]},"offset":0.1} },+ { "id": "dual-cube", "input": "cube", "edit": {"op":"dual"} },+ { "id": "dual-cylinder", "input": "cylinder", "edit": {"op":"dual"} },+ { "id": "tris-to-quads-cube", "input": "cube-triangulated", "edit": {"op":"tris_to_quads","select":{"faces":[0,1,2,3,4,5,6,7,8,9,10,11]},"angle":40} },+ { "id": "tris-to-quads-cube-one-side", "input": "cube-triangulated", "edit": {"op":"tris_to_quads","select":{"faces":[2,3]},"angle":40} },+ { "id": "symmetrize-cube-skewed-positive", "input": "cube-skewed", "edit": {"op":"symmetrize","axis":"x","keep":"positive"} },+ { "id": "symmetrize-cube-skewed-negative", "input": "cube-skewed", "edit": {"op":"symmetrize","axis":"x","keep":"negative"} },+ { "id": "symmetrize-cube-skewed-y", "input": "cube-skewed", "edit": {"op":"symmetrize","axis":"y","keep":"negative"} },{ "id": "knife-project-cube-line", "input": "cube", "edit": {"op":"knife_project","path":[[-1,0,0],[1,0,0]],"direction":[0,0,-1]} },{ "id": "set-position-grid-shear", "input": "grid", "edit": {"op":"set_position","offset":{"vec":[{"mul":[{"attr":"position","component":"y"},0.5]},0,{"mul":[{"attr":"position","component":"x"},{"attr":"position","component":"x"}]}]}} },{ "id": "set-position-cube-scale-sum", "input": "cube", "edit": {"op":"set_position","offset":{"vec":[{"sub":[{"attr":"position","component":"z"},{"attr":"position","component":"x"}]},{"add":[{"mul":[{"attr":"position","component":"y"},2]},0.25]},0]}} },diff --git a/tests/fixtures/blender/golden.json b/tests/fixtures/blender/golden.jsonindex 71be2bd9..f4bef5b2 100644--- a/tests/fixtures/blender/golden.json+++ b/tests/fixtures/blender/golden.json@@ -22813,6 +22813,629 @@]]},+ "poke-cube-top": {+ "vertexCount": 9,+ "edgeCount": 16,+ "faceCount": 9,+ "faceSizes": {+ "3": 4,+ "4": 5+ },+ "volume": 1.083333,+ "area": 6.118034,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.0,+ 0.0,+ 0.75+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "poke-cube-top-relative": {+ "vertexCount": 9,+ "edgeCount": 16,+ "faceCount": 9,+ "faceSizes": {+ "3": 4,+ "4": 5+ },+ "volume": 1.117851,+ "area": 6.224745,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.0,+ 0.0,+ 0.85355+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "poke-cube-all": {+ "vertexCount": 14,+ "edgeCount": 36,+ "faceCount": 24,+ "faceSizes": {+ "3": 24+ },+ "volume": 1.2,+ "area": 6.118823,+ "positions": [+ [+ -0.6,+ 0.0,+ 0.0+ ],+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.0,+ -0.6,+ 0.0+ ],+ [+ 0.0,+ 0.0,+ -0.6+ ],+ [+ 0.0,+ 0.0,+ 0.6+ ],+ [+ 0.0,+ 0.6,+ 0.0+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ],+ [+ 0.6,+ 0.0,+ 0.0+ ]+ ]+ },+ "dual-cube": {+ "vertexCount": 6,+ "edgeCount": 12,+ "faceCount": 8,+ "faceSizes": {+ "3": 8+ },+ "volume": 0.166667,+ "area": 1.732051,+ "positions": [+ [+ -0.5,+ 0.0,+ 0.0+ ],+ [+ 0.0,+ -0.5,+ 0.0+ ],+ [+ 0.0,+ 0.0,+ -0.5+ ],+ [+ 0.0,+ 0.0,+ 0.5+ ],+ [+ 0.0,+ 0.5,+ 0.0+ ],+ [+ 0.5,+ 0.0,+ 0.0+ ]+ ]+ },+ "dual-cylinder": {+ "vertexCount": 10,+ "edgeCount": 24,+ "faceCount": 16,+ "faceSizes": {+ "3": 16+ },+ "volume": 1.609476,+ "area": 7.437319,+ "positions": [+ [+ -0.85355,+ -0.35355,+ 0.0+ ],+ [+ -0.85355,+ 0.35355,+ 0.0+ ],+ [+ -0.35355,+ -0.85355,+ 0.0+ ],+ [+ -0.35355,+ 0.85355,+ 0.0+ ],+ [+ 0.0,+ -0.0,+ -1.0+ ],+ [+ 0.0,+ 0.0,+ 1.0+ ],+ [+ 0.35355,+ -0.85355,+ 0.0+ ],+ [+ 0.35355,+ 0.85355,+ 0.0+ ],+ [+ 0.85355,+ -0.35355,+ 0.0+ ],+ [+ 0.85355,+ 0.35355,+ 0.0+ ]+ ]+ },+ "tris-to-quads-cube": {+ "vertexCount": 8,+ "edgeCount": 12,+ "faceCount": 6,+ "faceSizes": {+ "4": 6+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "tris-to-quads-cube-one-side": {+ "vertexCount": 8,+ "edgeCount": 17,+ "faceCount": 11,+ "faceSizes": {+ "3": 10,+ "4": 1+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "symmetrize-cube-skewed-positive": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 10,+ "faceSizes": {+ "4": 10+ },+ "volume": 1.375,+ "area": 7.868034,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 1.0,+ -0.5+ ],+ [+ -0.5,+ 1.0,+ 0.5+ ],+ [+ 0.0,+ -0.5,+ -0.5+ ],+ [+ 0.0,+ -0.5,+ 0.5+ ],+ [+ 0.0,+ 0.75,+ -0.5+ ],+ [+ 0.0,+ 0.75,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 1.0,+ -0.5+ ],+ [+ 0.5,+ 1.0,+ 0.5+ ]+ ]+ },+ "symmetrize-cube-skewed-negative": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 10,+ "faceSizes": {+ "4": 10+ },+ "volume": 1.125,+ "area": 6.368034,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.0,+ -0.5,+ -0.5+ ],+ [+ 0.0,+ -0.5,+ 0.5+ ],+ [+ 0.0,+ 0.75,+ -0.5+ ],+ [+ 0.0,+ 0.75,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },+ "symmetrize-cube-skewed-y": {+ "vertexCount": 12,+ "edgeCount": 20,+ "faceCount": 10,+ "faceSizes": {+ "4": 10+ },+ "volume": 1.0,+ "area": 6.0,+ "positions": [+ [+ -0.5,+ -0.5,+ -0.5+ ],+ [+ -0.5,+ -0.5,+ 0.5+ ],+ [+ -0.5,+ 0.0,+ -0.5+ ],+ [+ -0.5,+ 0.0,+ 0.5+ ],+ [+ -0.5,+ 0.5,+ -0.5+ ],+ [+ -0.5,+ 0.5,+ 0.5+ ],+ [+ 0.5,+ -0.5,+ -0.5+ ],+ [+ 0.5,+ -0.5,+ 0.5+ ],+ [+ 0.5,+ 0.0,+ -0.5+ ],+ [+ 0.5,+ 0.0,+ 0.5+ ],+ [+ 0.5,+ 0.5,+ -0.5+ ],+ [+ 0.5,+ 0.5,+ 0.5+ ]+ ]+ },"knife-project-cube-line": {"vertexCount": 12,"edgeCount": 20,diff --git a/tests/mesh-reshape.test.js b/tests/mesh-reshape.test.jsindex 09712523..defce46b 100644--- a/tests/mesh-reshape.test.js+++ b/tests/mesh-reshape.test.js@@ -233,3 +233,61 @@ test('flatten validates its fields', () => {assert.throws(() => normalizeMeshEdits([{ op: 'flatten', verts: { all: true }, factor: 2 }]), /edits\[0\]\.factor/);assert.throws(() => run(cube(), [{ op: 'flatten', verts: { vertices: [0] } }]), /Pass normal/);});++test('unsubdivide reverses one Catmull-Clark level and is deterministic', () => {+ const subdivided = run(cube(), [{ op: 'subdivide', levels: 1 }]).mesh;+ assert.deepEqual([subdivided.vertexCount, subdivided.faceCount], [26, 24]);+ const { mesh, results } = run(subdivided, [{ op: 'unsubdivide' }]);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);+ assert.deepEqual([results[0].coarseFaces, results[0].removedVertices], [6, 18]);+ assertClosed(mesh);+ sameBytes(mesh, run(subdivided, [{ op: 'unsubdivide' }]).mesh);+ const twice = run(cube(), [{ op: 'subdivide', levels: 2 }, { op: 'unsubdivide' }]).mesh;+ assert.deepEqual([twice.vertexCount, twice.faceCount], [26, 24]);+ assertClosed(twice);+});++test('unsubdivide recovers a coarse n-gon and an open boundary', () => {+ const prism = meshFromGeometry(cylinder(6, 0, 1));+ const back = run(prism, [{ op: 'subdivide', levels: 1 }, { op: 'unsubdivide' }]).mesh;+ assert.equal(back.faceCount, prism.faceCount);+ assert.equal(back.vertexCount, prism.vertexCount);+ const open = run(cube(), [{ op: 'delete', select: { tag: 'top' } }, { op: 'subdivide', levels: 1 }, { op: 'unsubdivide' }]).mesh;+ assert.deepEqual([open.vertexCount, open.faceCount], [8, 5]);+});++test('unsubdivide says why a mesh cannot be reversed', () => {+ assert.throws(() => run(cube(), [{ op: 'unsubdivide' }]), /not one level of Catmull-Clark subdivision/);+ assert.throws(() => run(cube(), [{ op: 'poke', select: { all: true } }, { op: 'unsubdivide' }]), /is not a quad.*tris_to_quads/);+});++function topCorners(mesh) {+ const corners = [];+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (mesh.positions[vertex * 3 + 1] > 0) corners.push(vertex);+ }+ return corners;+}++test('circularize puts a loop on a circle and keeps the topology', () => {+ const stretched = run(cube(), [{ op: 'translate', select: { tag: 'top' }, offset: [0.3, 0, 0] }]).mesh;+ const corners = topCorners(stretched);+ const circularize = [{ op: 'circularize', verts: { vertices: corners } }];+ const { mesh, results } = run(stretched, circularize);+ assert.equal(results[0].circularizedVertices, 4);+ assert.deepEqual([mesh.vertexCount, mesh.faceCount], [8, 6]);+ assertClosed(mesh);+ const center = [0, 1, 2].map(axis => corners.reduce((sum, vertex) => sum + mesh.positions[vertex * 3 + axis], 0) / 4);+ const distances = corners.map(vertex => Math.hypot(...[0, 1, 2].map(axis => mesh.positions[vertex * 3 + axis] - center[axis])));+ for (const distance of distances) assert.ok(Math.abs(distance - distances[0]) < 1e-5);+ assert.ok(Math.abs(mesh.positions[corners[0] * 3 + 1] - stretched.positions[corners[0] * 3 + 1]) < 1e-6);+ sameBytes(mesh, run(stretched, circularize).mesh);+});++test('circularize validates its fields and its loop', () => {+ assert.throws(() => normalizeMeshEdits([{ op: 'circularize' }]), /edits\[0\]\.verts/);+ assert.throws(() => normalizeMeshEdits([{ op: 'circularize', verts: { all: true }, factor: 2 }]), /edits\[0\]\.factor/);+ assert.throws(() => normalizeMeshEdits([{ op: 'circularize', verts: { all: true }, regular: 'yes' }]), /edits\[0\]\.regular/);+ assert.throws(() => run(cube(), [{ op: 'circularize', verts: { all: true } }]), /selected neighbours/);+ assert.throws(() => run(cube(), [{ op: 'circularize', verts: { vertices: [0, 1] } }]), /selected neighbours/);+});