3D engine that AI agents drive
feat(mesh): report valence poles, quad quality and topologyScore in mesh lint (#731) (#740)
Nguyen Xuan An33f53c303d1e
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjsindex c06b872a..40123aff 100644--- a/bench/agent-modeling/measure.mjs+++ b/bench/agent-modeling/measure.mjs@@ -391,6 +391,9 @@ export async function measureRecipe(recipe) {const problemKinds = new Set();let uvParts = 0;let worstUvStretch = 0;+ let topologyScoreSum = 0;+ const valence = { regular: 0, poles3: 0, poles5: 0, poles6Plus: 0 };+ const quadQuality = { meanAngleError: 0, maxAngleError: 0, maxAspect: 1, maxWarp: 0 };for (const geometry of geometries) {for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {for (let axis = 0; axis < 3; axis++) {@@ -410,11 +413,24 @@ export async function measureRecipe(recipe) {parts += report.parts.count;closedParts += report.parts.closed;eulerCharacteristic += report.counts.vertices - report.counts.edges + report.counts.faces;+ topologyScoreSum += report.topologyScore;+ valence.regular += report.valence.regular;+ valence.poles3 += report.valence.poles3;+ valence.poles5 += report.valence.poles5;+ valence.poles6Plus += report.valence.poles6Plus;+ quadQuality.meanAngleError += report.quadQuality.meanAngleError;+ quadQuality.maxAngleError = Math.max(quadQuality.maxAngleError, report.quadQuality.maxAngleError);+ quadQuality.maxAspect = Math.max(quadQuality.maxAspect, report.quadQuality.maxAspect);+ quadQuality.maxWarp = Math.max(quadQuality.maxWarp, report.quadQuality.maxWarp);// Spatial warnings are advice, not pass or fail: a mug handle is meant to break symmetry.const gradedProblems = report.problems.filter(problem => !(problem.kind in GEOMETRY_PROBLEMS));for (const problem of gradedProblems) problemKinds.add(problem.kind);lintProblems += gradedProblems.length;}+ if (usedGeometries.length > 0) {+ quadQuality.meanAngleError = Math.round(quadQuality.meanAngleError / usedGeometries.length * 1e4) / 1e4;+ }+ const topologyScore = usedGeometries.length > 0 ? Math.round(topologyScoreSum / usedGeometries.length * 1e4) / 1e4 : 0;const allClosed = closedParts === parts;return {nodes: geometries.length,@@ -433,6 +449,9 @@ export async function measureRecipe(recipe) {size: [0, 1, 2].map(axis => bounds.max[axis] - bounds.min[axis]),lintProblems,problemKinds: [...problemKinds],+ valence,+ quadQuality,+ topologyScore,uv: { parts: uvParts, of: geometries.length, stretch: worstUvStretch },tips: countTips(geometries, bounds),section: (axis, at) => sectionLoops(geometries, axis, at),diff --git a/changes/731.md b/changes/731.mdnew file mode 100644index 00000000..18bca4d6--- /dev/null+++ b/changes/731.md@@ -0,0 +1 @@+- Report interior vertex valence (regular and poles), quad quality metrics and a normalized `topologyScore` in `lintMesh` and `mesh_inspect` (#731).diff --git a/changes/731.size.md b/changes/731.size.mdnew file mode 100644index 00000000..f12c07d8--- /dev/null+++ b/changes/731.size.md@@ -0,0 +1,3 @@+- scene:agent-scene+lazy: valence, quadQuality, topologyScore and quad distortion lint in mesh_inspect (#731)+- result:mesh_inspect: valence, quadQuality and topologyScore fields in mesh reports (#731)+- result:mesh_edit: valence, quadQuality and topologyScore fields in the returned mesh report (#731)diff --git a/docs/mesh.md b/docs/mesh.mdindex 8d84a4af..d6974e9d 100644--- a/docs/mesh.md+++ b/docs/mesh.md@@ -86,8 +86,13 @@ rebuilding the topology.## Lint-`lintMesh(mesh)` returns `{ ok, counts, parts, tags, bounds, problems }`. Each problem has `kind`, `severity`,-`count`, up to eight sample indices and a suggested `fix`:+`lintMesh(mesh, { geometry = false })` returns `{ ok, counts, parts, valence, quadQuality, topologyScore, tags, bounds, problems }`:++- `valence` counts interior vertices by edge degree: `{ regular, poles3, poles5, poles6Plus }` (boundary vertices on open rims are left out).+- `quadQuality` summarizes quad faces: `{ meanAngleError, maxAngleError, maxAspect, maxWarp }` (angles in degrees from $90^\circ$ and across the quad diagonal).+- `topologyScore` is a normalized score in $[0, 1]$ (`0` when `ok` is `false`) combining quad share, interior regular/pole valence and quad angle/planarity health.++Each problem has `kind`, `severity`, `count`, up to eight sample indices and a suggested `fix`:| Kind | Severity | Sample indices || --- | --- | --- |@@ -97,8 +102,10 @@ rebuilding the topology.| `degenerate-face` | error | faces with near-zero area || `boundary-edge` | warning | edges with one face (open surfaces) || `loose-vertex` | warning | vertices used by no face |+| `non-planar-quad` | warning (`geometry: true`) | quads folded by more than 45 degrees across their diagonal |+| `skewed-quad` | warning (`geometry: true`) | quads with a corner more than 60 degrees from a right angle (outside radial pole fans) |-`ok` is false when any error is present. Self-intersections and wall thickness are not checked yet.+`ok` is false when any error is present. With `geometry: true`, spatial checks (`intersecting-parts`, `self-intersection`, `thin-wall`, `floating-part`, `asymmetric`) and quad distortion warnings are included.## Selection and editsdiff --git a/src/agent-mesh.js b/src/agent-mesh.jsindex f5fe3f4d..9ff4bbe4 100644--- a/src/agent-mesh.js+++ b/src/agent-mesh.js@@ -179,6 +179,9 @@ export function meshReport(geometry) {ok: lint.ok,counts: { ...lint.counts, triangles: geometry.indices.length / 3, renderVertices: geometry.positions.length / 3 },faces: faceSizeHistogram(mesh),+ valence: lint.valence,+ quadQuality: lint.quadQuality,+ topologyScore: lint.topologyScore,parts: lint.parts,tags: lint.tags,bounds: roundedBounds(lint.bounds),diff --git a/src/mesh-lint.js b/src/mesh-lint.jsindex fb78f87f..aba70298 100644--- a/src/mesh-lint.js+++ b/src/mesh-lint.js@@ -23,8 +23,139 @@ export const GEOMETRY_PROBLEMS = Object.freeze({'thin-wall': { severity: 'warning', fix: 'The wall behind these faces (sample is face indices) is under 0.5% of the mesh size thick. Thicken it with solidify, or move the faces apart.' },'floating-part': { severity: 'warning', fix: 'This part (sample is part indices) touches no other part. Translate it onto its neighbour, or ignore this if it is meant to stand alone.' },asymmetric: { severity: 'warning', fix: 'The mesh is mirror-symmetric except for the vertices in sample. Rebuild one half and mirror it, or set_position those vertices to their partners.' },+ 'non-planar-quad': { severity: 'warning', fix: 'These quads (sample is face indices) fold by more than 45 degrees across their diagonal and pinch shading. Triangulate them, or flatten their corners.' },+ 'skewed-quad': { severity: 'warning', fix: 'These quads (sample is face indices) have a corner over 60 degrees from a right angle. Dissolve or slide edges so corners stay near 90 degrees.' },});+const NON_PLANAR_QUAD_DEGREES = 45;+const SKEWED_QUAD_DEGREES = 60;++function roundMetric(value) {+ return Math.round(value * 1e4) / 1e4;+}++/**+ * Interior vertex valence and quad shape quality (corner angle deviation from 90 degrees, aspect ratio and diagonal fold).+ * Boundary vertices are excluded from pole counts because an open rim naturally has degree 2 or 3.+ */+export function meshTopologyMetrics(mesh, table = edgeCornerTable(mesh), problems = null) {+ const degree = new Uint32Array(mesh.vertexCount);+ const boundaryVertex = new Uint8Array(mesh.vertexCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ degree[first]++;+ degree[second]++;+ if (table.edgeOffsets[edge + 1] - table.edgeOffsets[edge] !== 2) {+ boundaryVertex[first] = 1;+ boundaryVertex[second] = 1;+ }+ }+ let regular = 0;+ let valence3 = 0;+ let valence5 = 0;+ let valence6Plus = 0;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (degree[vertex] === 0 || boundaryVertex[vertex]) continue;+ if (degree[vertex] === 4) regular++;+ else if (degree[vertex] === 3) valence3++;+ else if (degree[vertex] === 5) valence5++;+ else if (degree[vertex] >= 6) valence6Plus++;+ }+ const positions = mesh.positions;+ let quadCount = 0;+ let meanAngleDeviation = 0;+ let maxAngleDeviation = 0;+ let maxAspectRatio = 1;+ let maxWarpAngle = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ if (mesh.faceOffsets[face + 1] - start !== 4) continue;+ quadCount++;+ const v0 = mesh.cornerVertices[start] * 3;+ const v1 = mesh.cornerVertices[start + 1] * 3;+ const v2 = mesh.cornerVertices[start + 2] * 3;+ const v3 = mesh.cornerVertices[start + 3] * 3;+ const corners = [v0, v1, v2, v3];+ let shortestEdge = Infinity;+ let longestEdge = 0;+ let faceMaxDeviation = 0;+ let faceDeviationSum = 0;+ for (let index = 0; index < 4; index++) {+ const current = corners[index];+ const next = corners[(index + 1) & 3];+ const previous = corners[(index + 3) & 3];+ const nextX = positions[next] - positions[current];+ const nextY = positions[next + 1] - positions[current + 1];+ const nextZ = positions[next + 2] - positions[current + 2];+ const prevX = positions[previous] - positions[current];+ const prevY = positions[previous + 1] - positions[current + 1];+ const prevZ = positions[previous + 2] - positions[current + 2];+ const edgeLength = Math.hypot(nextX, nextY, nextZ);+ if (edgeLength < shortestEdge) shortestEdge = edgeLength;+ if (edgeLength > longestEdge) longestEdge = edgeLength;+ const crossLength = Math.hypot(nextY * prevZ - nextZ * prevY, nextZ * prevX - nextX * prevZ, nextX * prevY - nextY * prevX);+ const angle = Math.atan2(crossLength, nextX * prevX + nextY * prevY + nextZ * prevZ) * 180 / Math.PI;+ const deviation = Math.abs(angle - 90);+ faceDeviationSum += deviation;+ if (deviation > faceMaxDeviation) faceMaxDeviation = deviation;+ }+ meanAngleDeviation += faceDeviationSum / 4;+ if (faceMaxDeviation > maxAngleDeviation) maxAngleDeviation = faceMaxDeviation;+ if (shortestEdge > 1e-12) {+ const aspect = longestEdge / shortestEdge;+ if (aspect > maxAspectRatio) maxAspectRatio = aspect;+ }+ const diagX = positions[v2] - positions[v0];+ const diagY = positions[v2 + 1] - positions[v0 + 1];+ const diagZ = positions[v2 + 2] - positions[v0 + 2];+ const e01x = positions[v1] - positions[v0];+ const e01y = positions[v1 + 1] - positions[v0 + 1];+ const e01z = positions[v1 + 2] - positions[v0 + 2];+ const e03x = positions[v3] - positions[v0];+ const e03y = positions[v3 + 1] - positions[v0 + 1];+ const e03z = positions[v3 + 2] - positions[v0 + 2];+ const n1x = e01y * diagZ - e01z * diagY;+ const n1y = e01z * diagX - e01x * diagZ;+ const n1z = e01x * diagY - e01y * diagX;+ const n2x = diagY * e03z - diagZ * e03y;+ const n2y = diagZ * e03x - diagX * e03z;+ const n2z = diagX * e03y - diagY * e03x;+ const len1 = Math.hypot(n1x, n1y, n1z);+ const len2 = Math.hypot(n2x, n2y, n2z);+ let warpAngle = 0;+ if (len1 > 1e-12 && len2 > 1e-12) {+ const cosine = Math.max(-1, Math.min(1, (n1x * n2x + n1y * n2y + n1z * n2z) / (len1 * len2)));+ warpAngle = Math.acos(cosine) * 180 / Math.PI;+ if (warpAngle > maxWarpAngle) maxWarpAngle = warpAngle;+ }+ if (problems) {+ if (warpAngle > NON_PLANAR_QUAD_DEGREES) addQualityProblem(problems, 'non-planar-quad', face);+ const touchesHighPole = [v0, v1, v2, v3].some(offset => degree[offset / 3] >= 6);+ if (faceMaxDeviation > SKEWED_QUAD_DEGREES && !touchesHighPole) addQualityProblem(problems, 'skewed-quad', face);+ }+ }+ return {+ valence: { regular, poles3: valence3, poles5: valence5, poles6Plus: valence6Plus },+ quadQuality: {+ meanAngleError: quadCount ? roundMetric(meanAngleDeviation / quadCount) : 0,+ maxAngleError: roundMetric(maxAngleDeviation),+ maxAspect: roundMetric(maxAspectRatio),+ maxWarp: roundMetric(maxWarpAngle),+ },+ };+}++function addQualityProblem(problems, kind, element) {+ let problem = problems.get(kind);+ if (!problem) {+ problem = { kind, ...GEOMETRY_PROBLEMS[kind], count: 0, sample: [] };+ problems.set(kind, problem);+ }+ problem.count++;+ if (problem.sample.length < SAMPLE_LIMIT) problem.sample.push(element);+}+function addProblem(problems, kind, element) {let problem = problems.get(kind);if (!problem) {@@ -161,6 +292,7 @@ export function lintMesh(mesh, { geometry = false } = {}) {if (insideOtherPart(mesh, facePart, part)) cavities++;else addProblem(problems, 'inverted-part', part);}+ const topology = meshTopologyMetrics(mesh, table, geometry ? problems : null);const problemList = [...problems.values()];let skippedChecks;if (geometry) {@@ -168,13 +300,32 @@ export function lintMesh(mesh, { geometry = false } = {}) {for (const found of spatial.problems) problemList.push({ ...found, ...GEOMETRY_PROBLEMS[found.kind] });if (spatial.skipped.length) skippedChecks = spatial.skipped;}+ const ok = !problemList.some(problem => problem.severity === 'error');return {- ok: !problemList.some(problem => problem.severity === 'error'),+ ok,counts: { vertices: mesh.vertexCount, edges: mesh.edgeCount, faces: mesh.faceCount, corners: mesh.cornerCount },parts: { count: partCount, closed: closedParts, cavities },+ valence: topology.valence,+ quadQuality: topology.quadQuality,+ topologyScore: computeTopologyScore(mesh, ok, topology),tags: tagCounts(mesh),bounds,problems: problemList,...(skippedChecks ? { skippedChecks } : {}),};}++function computeTopologyScore(mesh, ok, { valence, quadQuality }) {+ if (!ok || mesh.faceCount === 0) return 0;+ let quadCount = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ if (mesh.faceOffsets[face + 1] - mesh.faceOffsets[face] === 4) quadCount++;+ }+ const quadShare = quadCount / mesh.faceCount;+ const interiorVertices = valence.regular + valence.poles3 + valence.poles5 + valence.poles6Plus;+ const regularShare = interiorVertices > 0 ? (valence.regular + 0.5 * valence.poles3 + 0.5 * valence.poles5) / interiorVertices : 1;+ const angleHealth = Math.max(0, 1 - quadQuality.meanAngleError / 60);+ const warpHealth = Math.max(0, 1 - quadQuality.maxWarp / 90);+ const shapeHealth = (angleHealth + warpHealth) / 2;+ return roundMetric(0.5 * quadShare + 0.25 * regularShare + 0.25 * shapeHealth);+}diff --git a/tests/mesh-core.test.js b/tests/mesh-core.test.jsindex ff5fd0c3..88209053 100644--- a/tests/mesh-core.test.js+++ b/tests/mesh-core.test.js@@ -247,6 +247,36 @@ test('lintMesh names open, non-manifold, inverted and loose problems with fixes'assert.ok(lintMesh(flipped).problems.some(problem => problem.kind === 'inconsistent-winding'));});+test('lintMesh reports valence, quad quality, topologyScore and quad distortion warnings', () => {+ const cube = unitCube();+ const cubeReport = lintMesh(cube);+ assert.deepEqual(cubeReport.valence, { regular: 0, poles3: 8, poles5: 0, poles6Plus: 0 });+ assert.deepEqual(cubeReport.quadQuality, { meanAngleError: 0, maxAngleError: 0, maxAspect: 1, maxWarp: 0 });+ assert.equal(cubeReport.topologyScore, 0.875);++ const sheet = grid(3, 3);+ const sheetReport = lintMesh(sheet);+ assert.deepEqual(sheetReport.valence, { regular: 4, poles3: 0, poles5: 0, poles6Plus: 0 }, 'boundary vertices are excluded from interior valence counts');+ assert.equal(sheetReport.topologyScore, 1);++ const sphereMesh = meshFromGeometry(sphere(16, 8));+ const sphereReport = lintMesh(sphereMesh);+ assert.equal(sphereReport.valence.poles6Plus, 2, 'the two UV sphere poles have valence 16');+ assert.equal(sphereReport.valence.regular, 16 * 7, 'interior rings are regular valence-4 vertices');+ assert.ok(sphereReport.topologyScore > 0.7 && sphereReport.topologyScore < 1);++ // Fold one quad across its diagonal and skew another corner past 75 degrees from a right angle.+ const warped = polygonMesh([0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1], [[0, 1, 2, 3]]);+ const warpedGeom = lintMesh(warped, { geometry: true });+ assert.ok(warpedGeom.quadQuality.maxWarp > 45);+ assert.ok(warpedGeom.problems.some(problem => problem.kind === 'non-planar-quad'));++ const skewed = polygonMesh([0, 0, 0, 2, 0, 0, 2.5, 0, 0.1, 0.5, 0, 0.1], [[0, 1, 2, 3]]);+ const skewedGeom = lintMesh(skewed, { geometry: true });+ assert.ok(skewedGeom.quadQuality.maxAngleError > 75);+ assert.ok(skewedGeom.problems.some(problem => problem.kind === 'skewed-quad'));+});+test('gatherRenderPositions follows a deform-only edit', () => {const mesh = meshFromGeometry(sphere(16, 8));const { geometry, renderVertexSource } = extractRender(mesh);