3D engine that AI agents drive
Add a polygon mesh core for agent modeling
Nguyen Xuan An118119933a7f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f8b2b379..5b00abb4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- 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`+## 0.10.0- Add `67js/addons/terrain` for seeded, chunked heightfields with distance level of detail and `heightAt` for placementdiff --git a/docs/mesh.md b/docs/mesh.mdnew file mode 100644index 00000000..98b7f736--- /dev/null+++ b/docs/mesh.md@@ -0,0 +1,121 @@+# Polygon mesh core++Unreleased. `67js/addons/mesh` is the first phase of agent-oriented polygon modeling+(plan: `.agents/plans/modeling-parity.md`). It holds polygon topology, converts to and from renderer geometry, and+checks meshes. Editing operators (extrude, inset, booleans and so on) build on it in the next phase.++```js+import { box } from '67js';+import { meshFromGeometry, editMesh, meshData, validateTopology, extractRender, lintMesh, facesWithTag } from '67js/addons/mesh';++const mesh = meshFromGeometry(box(0, 1)); // 8 vertices, 12 edges, 6 quads, tagged top/bottom/side/...+lintMesh(mesh).ok; // true: closed, consistently wound, no degenerate faces+facesWithTag(mesh, 'top'); // [face index]++const edit = editMesh(mesh); // half-edge topology for local edits+validateTopology(edit); // { vertices, edges, faces, loops, euler }+const back = meshData(edit); // compact again++const { geometry } = extractRender(back); // positions, normals, uvs, indices for Renderer67+```++## MeshData++`createMeshData({ positions, faceOffsets, cornerVertices, attributes })` returns a frozen mesh in the layout Blender+uses for evaluated meshes:++| Field | Type | Meaning |+| --- | --- | --- |+| `positions` | `Float32Array`, 3 per vertex | Vertex positions |+| `faceOffsets` | `Uint32Array`, faces + 1 | Face `f` owns corners `faceOffsets[f]` to `faceOffsets[f + 1]` |+| `cornerVertices` | `Uint32Array` | Vertex of each corner, in winding order |+| `edgeVertices` | `Uint32Array`, 2 per edge | Derived unique edges |+| `cornerEdges` | `Uint32Array` | Edge from each corner to the next corner of its face |+| `attributes` | `{ point, edge, face, corner }` | Named `{ data, size }` arrays per domain |++Faces are polygons with three or more corners; consecutive corners cannot repeat a vertex. Inputs are not copied.+Attribute arrays may be `Float32Array`, `Uint8Array`, `Uint16Array`, `Uint32Array` or `Int32Array` with 1 to 16+components. Edge attributes need explicit `edgeVertices` and `cornerEdges`, because derived edge order is internal.++Conventions used by the other functions:++- Corner `uv` (size 2) and `color` (size 3) are UV channel zero and vertex colour.+- Edge `sharp` (`Uint8Array`) marks hard edges.+- Face `tag:<name>` (`Uint8Array`, 0 or 1) marks a face as carrying a tag. `meshTags`, `facesWithTag` and+ `tagCounts` read them. A face can carry several tags.++Limits: 4,000,000 vertices and 16,000,000 corners per mesh.++## EditMesh++`editMesh(meshData)` builds a mutable half-edge mesh in BMesh's model, stored in typed arrays:++- Each edge has two endpoint slots; the slots around a vertex form its disk cycle.+- Each face corner is a loop with `next`/`prev` around its face and `radialNext`/`radialPrev` around its edge.+- Polygons of any size and non-manifold edges are representable.++Element indices start equal to the MeshData vertex, edge, face and corner indices. Methods:+`createVertex`, `createFace(vertices)` (creates missing edges), `ensureEdge`, `findEdge`, `removeFace`, `removeEdge`,+`removeVertex`, `vertexEdges`, `vertexDegree`, `edgeLoops`, `edgeFaceCount`, `faceLoops`, `faceVertices`,+`faceNeighbors`, `liveIndices(domain)`, and `ensureAttribute(domain, name, type, size)` for attributes that grow with+the mesh. Removed indices are reused. `meshData(edit)` compacts the result; wire edges are dropped and loose vertices+kept.++`validateTopology(edit)` checks every disk, radial and face cycle and throws a `RangeError` that names the first+broken element.++## Conversion and rendering++`meshFromGeometry(geometry, { weld, quads = true, tags = 'axis' })` converts renderer geometry (indexed triangles+with vertices split at seams):++- Vertices within `weld` merge; the default is 1e-6 of the bounds diagonal.+- UVs and colours become corner attributes, so seams survive welding.+- Edges where the input normals were split become `sharp`, so hard edges survive.+- With `quads`, flat triangle pairs that agree on every attribute join into convex quads, best-shaped first.+- With `tags: 'axis'`, faces whose normal is within 45 degrees of an axis get `top`, `bottom`, `right` (+X),+ `left` (-X), `front` (+Z) or `back` (-Z); the four horizontal ones also get `side`.++`extractRender(mesh, { sharpAngle })` returns `{ geometry, renderVertexSource, cornerRenderVertex, triangleFaces }`.+Corner normals are angle-weighted and smoothed across an edge unless it is `sharp`, a boundary, non-manifold,+inconsistently wound, or bends more than `sharpAngle`. Render vertices split at hard edges and at UV or colour+seams. Quads split along the shorter diagonal and larger polygons use ear clipping in their own plane (up to 4096+corners). After a deform-only change, `gatherRenderPositions(mesh, renderVertexSource)` re-gathers positions without+rebuilding the topology.++`faceNormals`, `cornerNormals`, `triangulateMesh`, `joinTriangles`, `tagFacesByAxis`, `weldVertices` and+`rebuildFromCorners` are exported for operators that need one step.++## 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`:++| Kind | Severity | Sample indices |+| --- | --- | --- |+| `non-manifold-edge` | error | edges used by three or more faces |+| `inconsistent-winding` | error | edges whose two faces wind the same way |+| `inverted-part` | error | closed parts with negative volume |+| `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 |++`ok` is false when any error is present. Self-intersections and wall thickness are not checked yet.++## Measured speed++`node scripts/benchmark-mesh-core.mjs 1000` on a 1000 x 1000 quad grid (one million faces), Node 24, Ryzen 5 5600X,+one thread at below-normal priority on a shared machine, medians of five runs. Runs varied by about 25%.++| Step | Median |+| --- | --- |+| `createMeshData` (derive edges) | 61–63 ms |+| `editMesh` + `meshData` round trip | 234–296 ms |+| `validateTopology` | 188–192 ms |+| `cornerNormals` | 318 ms |+| `extractRender` | 380 ms |+| `lintMesh` | 191–210 ms |+| `meshFromGeometry`, sphere with 1M triangles | 1.3–1.5 s |++The `EditMesh` arrays take about 200 bytes per quad face without attributes. These numbers are this machine only+and say nothing about Blender's speed.diff --git a/package.json b/package.jsonindex 8c346fb9..934e4b7b 100644--- a/package.json+++ b/package.json@@ -40,6 +40,7 @@"docs/sculpt.md","docs/surface.md","docs/mesh-query.md",+ "docs/mesh.md","docs/primitives.md","docs/shrinkwrap.md","docs/vehicle.md",@@ -77,6 +78,7 @@"./addons/sculpt": "./build/sculpt.js","./addons/surface": "./build/surface.js","./addons/mesh-query": "./build/mesh-query.js",+ "./addons/mesh": "./build/mesh.js","./addons/shrinkwrap": "./build/shrinkwrap.js","./addons/surface-attachment": "./build/surface-attachment.js","./addons/physics": "./build/physics.js",diff --git a/scripts/benchmark-mesh-core.mjs b/scripts/benchmark-mesh-core.mjsnew file mode 100644index 00000000..e05e5887--- /dev/null+++ b/scripts/benchmark-mesh-core.mjs@@ -0,0 +1,93 @@+// Speed baseline for the polygon mesh core (P1 of .agents/plans/modeling-parity.md).+// Usage: node scripts/benchmark-mesh-core.mjs [gridSide=1000] [runs=5]+import { mkdir, writeFile } from 'node:fs/promises';+import { constants, cpus, setPriority } from 'node:os';+import { sphere } from '../src/geometry.js';+import { recomputeNormals } from '../src/geometry-normals.js';+import {+ createMeshData, editMesh, meshData, cornerNormals, extractRender, lintMesh, meshFromGeometry, validateTopology,+} from '../src/mesh.js';++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const side = Number(process.argv[2] ?? 1000);+const runs = Number(process.argv[3] ?? 5);++function quadGrid(columns, rows) {+ const positions = new Float32Array((columns + 1) * (rows + 1) * 3);+ for (let row = 0; row <= rows; row++) {+ for (let column = 0; column <= columns; column++) {+ const offset = (row * (columns + 1) + column) * 3;+ positions[offset] = column / columns;+ positions[offset + 1] = Math.sin(column * 0.05) * Math.cos(row * 0.05) * 0.02;+ positions[offset + 2] = -row / rows;+ }+ }+ const faceOffsets = new Uint32Array(columns * rows + 1);+ const cornerVertices = new Uint32Array(columns * rows * 4);+ for (let row = 0; row < rows; row++) {+ for (let column = 0; column < columns; column++) {+ const face = row * columns + column;+ const first = row * (columns + 1) + column;+ faceOffsets[face + 1] = (face + 1) * 4;+ cornerVertices[face * 4] = first;+ cornerVertices[face * 4 + 1] = first + 1;+ cornerVertices[face * 4 + 2] = first + columns + 2;+ cornerVertices[face * 4 + 3] = first + columns + 1;+ }+ }+ return { positions, faceOffsets, cornerVertices };+}++function measure(label, run) {+ const samples = [];+ let result;+ for (let index = 0; index < runs + 1; index++) {+ const started = performance.now();+ result = run();+ const elapsed = performance.now() - started;+ if (index > 0) samples.push(elapsed);+ }+ samples.sort((left, right) => left - right);+ const median = samples[Math.floor(samples.length / 2)];+ console.log(`${label.padEnd(44)} ${median.toFixed(1).padStart(9)} ms`);+ return { label, medianMs: Number(median.toFixed(2)), samplesMs: samples.map(value => Number(value.toFixed(2))), result };+}++const input = quadGrid(side, side);+const results = [];+const created = measure(`createMeshData ${side}x${side} quads`, () => createMeshData(input));+results.push(created);+const mesh = created.result;+const edited = measure('editMesh (MeshData -> EditMesh)', () => editMesh(mesh));+results.push(edited);+results.push(measure('meshData (EditMesh -> MeshData)', () => meshData(edited.result)));+results.push(measure('round trip editMesh + meshData', () => meshData(editMesh(mesh))));+results.push(measure('validateTopology', () => validateTopology(edited.result)));+results.push(measure('cornerNormals (sharpAngle 30 degrees)', () => cornerNormals(mesh, { sharpAngle: Math.PI / 6 })));+const extracted = measure('extractRender', () => extractRender(mesh));+results.push(extracted);+results.push(measure('lintMesh', () => lintMesh(mesh)));++const triangles = sphere(1000, 500);+results.push(measure('meshFromGeometry sphere 1000x500 (~1M tris)', () => meshFromGeometry(triangles)));+results.push(measure('baseline recomputeNormals sphere 1000x500', () => recomputeNormals(triangles, triangles.positions)));++const editCore = edited.result;+let editBytes = 0;+for (const store of [editCore.vertices, editCore.edges, editCore.loops, editCore.faces]) {+ for (const array of Object.values(store.arrays)) editBytes += array.byteLength;+ editBytes += store.removed.byteLength;+}+const report = {+ date: new Date().toISOString(),+ node: process.version,+ cpu: cpus()[0]?.model,+ threads: 1,+ priority: 'below normal',+ grid: { side, faces: mesh.faceCount, vertices: mesh.vertexCount, edges: mesh.edgeCount },+ editMeshBytesPerFace: Number((editBytes / mesh.faceCount).toFixed(1)),+ results: results.map(({ label, medianMs, samplesMs }) => ({ label, medianMs, samplesMs })),+};+console.log(`EditMesh memory: ${report.editMeshBytesPerFace} bytes per face (capacity, without attributes)`);+await mkdir('artifacts', { recursive: true });+await writeFile(`artifacts/mesh-core-benchmark-${side}.json`, JSON.stringify(report, null, 2));diff --git a/scripts/prepare-release.mjs b/scripts/prepare-release.mjsindex 29ee3462..a4c8bceb 100644--- a/scripts/prepare-release.mjs+++ b/scripts/prepare-release.mjs@@ -39,7 +39,7 @@ await copyFile(resolve(root, 'docs/gltf.md'), resolve(root, 'public/gltf.md'));const sourceDocuments = ['scene-graph.md', 'modeling.md', 'animation-curves.md', 'animation-mixer.md','gltf-morph.md', 'morph-targets.md', 'skinning.md', 'physics.md',- 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'primitives.md', 'shrinkwrap.md', 'spume.md',+ 'export-glb.md', 'sculpt.md', 'surface.md', 'mesh-query.md', 'mesh.md','primitives.md', 'shrinkwrap.md', 'spume.md','retarget.md','vehicle.md','vegetation.md', 'terrain.md',diff --git a/scripts/smoke-package.mjs b/scripts/smoke-package.mjsindex 91b75368..a85e6852 100644--- a/scripts/smoke-package.mjs+++ b/scripts/smoke-package.mjs@@ -52,6 +52,7 @@ import { parseGltf } from '67js/addons/gltf';import { sculptGeometry } from '67js/addons/sculpt';import { createSurfacePatch } from '67js/addons/surface';import { createMeshQueryIndex, createMeshPairQuery } from '67js/addons/mesh-query';+import { meshFromGeometry, lintMesh } from '67js/addons/mesh';import { shrinkwrapGeometry } from '67js/addons/shrinkwrap';import { createPhysicsScene, planPhysicsScene } from '67js/addons/physics';assert.equal(VERSION, '${metadata.version}');@@ -87,6 +88,7 @@ assert.notDeepEqual(sculptOutput.positions, sculptSource.positions);const packedPatch = createSurfacePatch({ geometry: sculptSource }, { position: [0, 0, 0.5], size: [0.3, 0.3, 0.1] });assert.ok(packedPatch.indices.length > 0);assert.ok(packedPatch.positions.some((value, index) => index % 3 === 2 && value > 0.5));+assert.equal(lintMesh(meshFromGeometry(box(0))).ok, true);const queryGeometry = box(0);const solidIndex = createMeshQueryIndex(queryGeometry, { solid: true });const queryMatrix = new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]);diff --git a/src/mesh-convert.js b/src/mesh-convert.jsnew file mode 100644index 00000000..013c7eb1--- /dev/null+++ b/src/mesh-convert.js@@ -0,0 +1,433 @@+import { createMeshData, deriveEdges, DOMAINS, meshBounds, TAG_PREFIX } from './mesh-data.js';+import { faceNormals } from './mesh-normals.js';+import { cornerCycles, cornerFaces, edgeCornerTable } from './mesh-topology.js';++const NORMAL_SPLIT_TOLERANCE = 1e-4;+const AXIS_TAGS = Object.freeze([+ { name: 'right', axis: 0, sign: 1, side: true },+ { name: 'left', axis: 0, sign: -1, side: true },+ { name: 'top', axis: 1, sign: 1, side: false },+ { name: 'bottom', axis: 1, sign: -1, side: false },+ { name: 'front', axis: 2, sign: 1, side: true },+ { name: 'back', axis: 2, sign: -1, side: true },+]);++function spatialHash(cellX, cellY, cellZ, mask) {+ return (Math.imul(cellX, 73856093) ^ Math.imul(cellY, 19349663) ^ Math.imul(cellZ, 83492791)) & mask;+}++/**+ * Map each input vertex to a welded vertex. Vertices closer than `tolerance` merge into the first one seen.+ * Uses a hashed uniform grid with cell size equal to the tolerance, so each lookup checks 27 cells.+ */+export function weldVertices(positions, tolerance) {+ const count = positions.length / 3;+ const weldMap = new Uint32Array(count);+ const representatives = [];+ let tableSize = 1;+ while (tableSize < count * 2) tableSize *= 2;+ const mask = tableSize - 1;+ const bucketHead = new Int32Array(tableSize).fill(-1);+ const bucketNext = new Int32Array(count).fill(-1);+ const cellSize = tolerance > 0 ? tolerance : 1;+ const squaredTolerance = tolerance * tolerance;+ const searchRadius = tolerance > 0 ? 1 : 0;+ for (let vertex = 0; vertex < count; vertex++) {+ const x = positions[vertex * 3];+ const y = positions[vertex * 3 + 1];+ const z = positions[vertex * 3 + 2];+ const cellX = Math.floor(x / cellSize);+ const cellY = Math.floor(y / cellSize);+ const cellZ = Math.floor(z / cellSize);+ let match = -1;+ for (let offsetX = -searchRadius; offsetX <= searchRadius && match === -1; offsetX++) {+ for (let offsetY = -searchRadius; offsetY <= searchRadius && match === -1; offsetY++) {+ for (let offsetZ = -searchRadius; offsetZ <= searchRadius && match === -1; offsetZ++) {+ let candidate = bucketHead[spatialHash(cellX + offsetX, cellY + offsetY, cellZ + offsetZ, mask)];+ while (candidate !== -1) {+ const source = representatives[candidate];+ const deltaX = positions[source * 3] - x;+ const deltaY = positions[source * 3 + 1] - y;+ const deltaZ = positions[source * 3 + 2] - z;+ if (deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ <= squaredTolerance) {+ match = candidate;+ break;+ }+ candidate = bucketNext[candidate];+ }+ }+ }+ }+ if (match === -1) {+ match = representatives.length;+ representatives.push(vertex);+ const bucket = spatialHash(cellX, cellY, cellZ, mask);+ bucketNext[match] = bucketHead[bucket];+ bucketHead[bucket] = match;+ }+ weldMap[vertex] = match;+ }+ return { weldMap, representatives };+}++/**+ * Rebuild a mesh from faces described by source corners. Corner attributes follow their source corner, face+ * attributes their source face, and edge attributes are kept for edges that join the same vertex pair as before.+ */+export function rebuildFromCorners(source, faceOffsets, sourceCorners, sourceFaces) {+ const cornerVertices = new Uint32Array(sourceCorners.length);+ for (let corner = 0; corner < sourceCorners.length; corner++) cornerVertices[corner] = source.cornerVertices[sourceCorners[corner]];+ const edges = deriveEdges(source.vertexCount, faceOffsets, cornerVertices);+ const attributes = { point: { ...source.attributes.point }, edge: {}, face: {}, corner: {} };+ for (const [name, attribute] of Object.entries(source.attributes.corner)) {+ attributes.corner[name] = gatherAttribute(attribute, sourceCorners);+ }+ for (const [name, attribute] of Object.entries(source.attributes.face)) {+ attributes.face[name] = gatherAttribute(attribute, sourceFaces);+ }+ const edgeAttributes = Object.entries(source.attributes.edge);+ if (edgeAttributes.length) {+ const sourceEdgeOfNewEdge = new Int32Array(edges.edgeCount).fill(-1);+ const sourceEdges = deriveEdgeLookup(source);+ for (let edge = 0; edge < edges.edgeCount; edge++) {+ sourceEdgeOfNewEdge[edge] = sourceEdges(edges.edgeVertices[edge * 2], edges.edgeVertices[edge * 2 + 1]);+ }+ for (const [name, attribute] of edgeAttributes) {+ const data = new attribute.data.constructor(edges.edgeCount * attribute.size);+ for (let edge = 0; edge < edges.edgeCount; edge++) {+ const sourceEdge = sourceEdgeOfNewEdge[edge];+ if (sourceEdge === -1) continue;+ for (let component = 0; component < attribute.size; component++) {+ data[edge * attribute.size + component] = attribute.data[sourceEdge * attribute.size + component];+ }+ }+ attributes.edge[name] = { data, size: attribute.size };+ }+ }+ return createMeshData({+ positions: source.positions, faceOffsets, cornerVertices,+ edgeVertices: edges.edgeVertices, cornerEdges: edges.cornerEdges, attributes,+ });+}++function gatherAttribute(attribute, sourceIndices) {+ const data = new attribute.data.constructor(sourceIndices.length * attribute.size);+ for (let index = 0; index < sourceIndices.length; index++) {+ for (let component = 0; component < attribute.size; component++) {+ data[index * attribute.size + component] = attribute.data[sourceIndices[index] * attribute.size + component];+ }+ }+ return { data, size: attribute.size };+}++/** Lookup function from a vertex pair to the source edge index, built from per-vertex edge lists. */+function deriveEdgeLookup(mesh) {+ const firstEdge = new Int32Array(mesh.vertexCount).fill(-1);+ const nextEdge = new Int32Array(mesh.edgeCount).fill(-1);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const low = Math.min(mesh.edgeVertices[edge * 2], mesh.edgeVertices[edge * 2 + 1]);+ nextEdge[edge] = firstEdge[low];+ firstEdge[low] = edge;+ }+ return (first, second) => {+ const low = Math.min(first, second);+ const high = Math.max(first, second);+ let edge = firstEdge[low];+ while (edge !== -1) {+ if (Math.max(mesh.edgeVertices[edge * 2], mesh.edgeVertices[edge * 2 + 1]) === high) return edge;+ edge = nextEdge[edge];+ }+ return -1;+ };+}++function attributeList(domainAttributes) {+ return Object.values(domainAttributes);+}++function sameValues(attributes, first, second) {+ for (const attribute of attributes) {+ const size = attribute.size;+ const data = attribute.data;+ for (let component = 0; component < size; component++) {+ if (data[first * size + component] !== data[second * size + component]) return false;+ }+ }+ return true;+}++const cornerScratch = new Float64Array(12);++/**+ * Sum over the four corners of |corner angle - 90 degrees|, or -1 when the quad is not convex+ * (a corner turns against the others). Vertices are a, b, c, d in winding order.+ */+function quadCornerAngleError(positions, a, b, c, d) {+ const quad = [a, b, c, d];+ let error = 0;+ for (let index = 0; index < 4; index++) {+ const previous = quad[(index + 3) & 3] * 3;+ const current = quad[index] * 3;+ const next = quad[(index + 1) & 3] * 3;+ const firstX = positions[previous] - positions[current];+ const firstY = positions[previous + 1] - positions[current + 1];+ const firstZ = positions[previous + 2] - positions[current + 2];+ const secondX = positions[next] - positions[current];+ const secondY = positions[next + 1] - positions[current + 1];+ const secondZ = positions[next + 2] - positions[current + 2];+ const crossX = secondY * firstZ - secondZ * firstY;+ const crossY = secondZ * firstX - secondX * firstZ;+ const crossZ = secondX * firstY - secondY * firstX;+ cornerScratch[index * 3] = crossX;+ cornerScratch[index * 3 + 1] = crossY;+ cornerScratch[index * 3 + 2] = crossZ;+ const crossLength = Math.sqrt(crossX * crossX + crossY * crossY + crossZ * crossZ);+ const angle = Math.atan2(crossLength, firstX * secondX + firstY * secondY + firstZ * secondZ);+ error += Math.abs(angle - Math.PI / 2);+ }+ for (let index = 1; index < 4; index++) {+ const dot = cornerScratch[0] * cornerScratch[index * 3] + cornerScratch[1] * cornerScratch[index * 3 + 1] ++ cornerScratch[2] * cornerScratch[index * 3 + 2];+ if (dot <= 0) return -1;+ }+ return error;+}++const SORT_BUCKETS = 65536;+const MAX_QUAD_ERROR = 2 * Math.PI;++/** Candidate order by error, using a counting sort on quantized errors (ties keep edge order). */+function orderByError(errors, count) {+ const bucketOfCandidate = new Uint32Array(count);+ const bucketStart = new Uint32Array(SORT_BUCKETS + 1);+ for (let candidate = 0; candidate < count; candidate++) {+ const bucket = Math.min(SORT_BUCKETS - 1, Math.floor(errors[candidate] / MAX_QUAD_ERROR * SORT_BUCKETS));+ bucketOfCandidate[candidate] = bucket;+ bucketStart[bucket + 1]++;+ }+ for (let bucket = 0; bucket < SORT_BUCKETS; bucket++) bucketStart[bucket + 1] += bucketStart[bucket];+ const order = new Uint32Array(count);+ for (let candidate = 0; candidate < count; candidate++) {+ order[bucketStart[bucketOfCandidate[candidate]]] = candidate;+ bucketStart[bucketOfCandidate[candidate]]++;+ }+ return order;+}++/**+ * Join pairs of triangles into quads, as Blender's "Triangles to Quads": only across smooth, manifold edges whose two+ * triangles are within maxAngle of coplanar, form a convex quad, and agree on every corner and face attribute.+ * Best-shaped pairs (corners closest to right angles) join first.+ */+export function joinTriangles(mesh, { maxAngle = Math.PI / 180 } = {}) {+ const { normals } = faceNormals(mesh);+ const table = edgeCornerTable(mesh);+ const { nextCorner } = cornerCycles(mesh);+ const facesOfCorners = cornerFaces(mesh);+ const sharp = mesh.attributes.edge.sharp?.data;+ const cornerAttributes = attributeList(mesh.attributes.corner);+ const faceAttributes = attributeList(mesh.attributes.face);+ const cosineLimit = Math.cos(maxAngle);+ const vertices = mesh.cornerVertices;+ // Each candidate stores its error and its first corner; the other three corners follow from the topology.+ const candidateErrors = new Float64Array(mesh.edgeCount);+ const candidateFirstCorner = new Uint32Array(mesh.edgeCount);+ const candidateSecondCorner = new Uint32Array(mesh.edgeCount);+ let candidateCount = 0;+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const offset = table.edgeOffsets[edge];+ if (table.edgeOffsets[edge + 1] - offset !== 2) continue;+ if (sharp && sharp[edge]) continue;+ const first = table.edgeCorners[offset];+ const second = table.edgeCorners[offset + 1];+ const firstFace = facesOfCorners[first];+ const secondFace = facesOfCorners[second];+ if (mesh.faceOffsets[firstFace + 1] - mesh.faceOffsets[firstFace] !== 3) continue;+ if (mesh.faceOffsets[secondFace + 1] - mesh.faceOffsets[secondFace] !== 3) continue;+ if (vertices[first] === vertices[second]) continue;+ const cosine = normals[firstFace * 3] * normals[secondFace * 3] + normals[firstFace * 3 + 1] * normals[secondFace * 3 + 1] ++ normals[firstFace * 3 + 2] * normals[secondFace * 3 + 2];+ if (cosine < cosineLimit) continue;+ if (!sameValues(faceAttributes, firstFace, secondFace)) continue;+ // first runs a->b in its face, second runs b->a. The quad is a, (second's opposite), b, (first's opposite).+ const firstNext = nextCorner[first];+ const firstOpposite = nextCorner[firstNext];+ const secondNext = nextCorner[second];+ const secondOpposite = nextCorner[secondNext];+ if (!sameValues(cornerAttributes, first, secondNext) || !sameValues(cornerAttributes, firstNext, second)) continue;+ if (vertices[firstOpposite] === vertices[secondOpposite]) continue;+ const error = quadCornerAngleError(mesh.positions, vertices[first], vertices[secondOpposite], vertices[firstNext], vertices[firstOpposite]);+ if (error < 0) continue;+ candidateErrors[candidateCount] = error;+ candidateFirstCorner[candidateCount] = first;+ candidateSecondCorner[candidateCount] = second;+ candidateCount++;+ }+ if (!candidateCount) return mesh;+ const order = orderByError(candidateErrors, candidateCount);+ const joined = new Uint8Array(mesh.faceCount);+ // For the lower-numbered face of each joined pair: the first corner of its quad; the partner face is skipped.+ const quadFirstCorner = new Int32Array(mesh.faceCount).fill(-1);+ const quadSecondCorner = new Uint32Array(mesh.faceCount);+ let joinedPairs = 0;+ for (let index = 0; index < candidateCount; index++) {+ const candidate = order[index];+ const first = candidateFirstCorner[candidate];+ const second = candidateSecondCorner[candidate];+ const firstFace = facesOfCorners[first];+ const secondFace = facesOfCorners[second];+ if (joined[firstFace] || joined[secondFace]) continue;+ joined[firstFace] = 1;+ joined[secondFace] = 1;+ const keeper = Math.min(firstFace, secondFace);+ quadFirstCorner[keeper] = first;+ quadSecondCorner[keeper] = second;+ joinedPairs++;+ }+ const faceCount = mesh.faceCount - joinedPairs;+ const faceOffsets = new Uint32Array(faceCount + 1);+ const sourceCorners = new Uint32Array(mesh.cornerCount - joinedPairs * 2);+ const sourceFaces = new Uint32Array(faceCount);+ let outputFace = 0;+ let outputCorner = 0;+ for (let face = 0; face < mesh.faceCount; face++) {+ const first = quadFirstCorner[face];+ if (joined[face] && first === -1) continue;+ if (first !== -1) {+ const firstNext = nextCorner[first];+ sourceCorners[outputCorner] = first;+ sourceCorners[outputCorner + 1] = nextCorner[nextCorner[quadSecondCorner[face]]];+ sourceCorners[outputCorner + 2] = firstNext;+ sourceCorners[outputCorner + 3] = nextCorner[firstNext];+ outputCorner += 4;+ } else {+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {+ sourceCorners[outputCorner] = corner;+ outputCorner++;+ }+ }+ sourceFaces[outputFace] = face;+ outputFace++;+ faceOffsets[outputFace] = outputCorner;+ }+ return rebuildFromCorners(mesh, faceOffsets, sourceCorners, sourceFaces);+}++/**+ * Tag faces by the axis their normal points along (within 45 degrees): top, bottom, right (+X), left (-X),+ * front (+Z), back (-Z); the four horizontal directions also get "side". Existing tags are kept.+ */+export function tagFacesByAxis(mesh) {+ const { normals } = faceNormals(mesh);+ const tagData = new Map();+ const ensure = name => {+ if (!tagData.has(name)) tagData.set(name, mesh.attributes.face[TAG_PREFIX + name]?.data.slice() ?? new Uint8Array(mesh.faceCount));+ return tagData.get(name);+ };+ const threshold = Math.SQRT1_2;+ for (let face = 0; face < mesh.faceCount; face++) {+ for (const tag of AXIS_TAGS) {+ if (normals[face * 3 + tag.axis] * tag.sign < threshold) continue;+ ensure(tag.name)[face] = 1;+ if (tag.side) ensure('side')[face] = 1;+ }+ }+ return withFaceAttributes(mesh, Object.fromEntries([...tagData].map(([name, data]) => [TAG_PREFIX + name, { data, size: 1 }])));+}++/** Copy of a mesh with face attributes added or replaced; topology and other arrays are shared. */+export function withFaceAttributes(mesh, faceAttributes) {+ const attributes = {};+ for (const domain of DOMAINS) attributes[domain] = { ...mesh.attributes[domain] };+ Object.assign(attributes.face, faceAttributes);+ return createMeshData({+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,+ });+}++function differentNormals(normals, first, second) {+ return Math.abs(normals[first * 3] - normals[second * 3]) > NORMAL_SPLIT_TOLERANCE ||+ Math.abs(normals[first * 3 + 1] - normals[second * 3 + 1]) > NORMAL_SPLIT_TOLERANCE ||+ Math.abs(normals[first * 3 + 2] - normals[second * 3 + 2]) > NORMAL_SPLIT_TOLERANCE;+}++/**+ * Convert renderer geometry (indexed triangles with seam-split vertices) into a polygon mesh.+ * Coincident vertices weld within `weld` (default: 1e-6 of the bounds diagonal); UVs and colours become corner+ * attributes; edges where the input normals were split become "sharp" edges so extraction keeps the hard edges.+ * With `quads` (default true), flat triangle pairs join into quads. With `tags: 'axis'` (default), faces are tagged+ * top, bottom, side, right, left, front and back.+ */+export function meshFromGeometry(geometry, { weld, quads = true, tags = 'axis' } = {}) {+ const { positions, normals, indices } = geometry ?? {};+ if (!(positions instanceof Float32Array) || positions.length % 3 !== 0 || positions.length === 0) throw new TypeError('Geometry needs Float32 positions.');+ if (!(indices instanceof Uint32Array) || indices.length % 3 !== 0 || indices.length === 0) throw new TypeError('Geometry needs Uint32 triangle indices.');+ const sourceCount = positions.length / 3;+ for (const index of indices) if (index >= sourceCount) throw new RangeError('Geometry index exceeds the vertex count.');+ if (tags !== 'axis' && tags !== 'none') throw new RangeError('tags must be "axis" or "none".');+ let tolerance = weld;+ if (tolerance === undefined) {+ const sourceBounds = meshBounds({ positions });+ tolerance = Math.hypot(...sourceBounds.max.map((value, axis) => value - sourceBounds.min[axis])) * 1e-6;+ }+ if (!Number.isFinite(tolerance) || tolerance < 0) throw new RangeError('weld must be a nonnegative distance.');+ const { weldMap, representatives } = weldVertices(positions, tolerance);+ const weldedPositions = new Float32Array(representatives.length * 3);+ for (let vertex = 0; vertex < representatives.length; vertex++) {+ weldedPositions.set(positions.subarray(representatives[vertex] * 3, representatives[vertex] * 3 + 3), vertex * 3);+ }+ const keptTriangles = [];+ for (let triangle = 0; triangle < indices.length / 3; triangle++) {+ const first = weldMap[indices[triangle * 3]];+ const second = weldMap[indices[triangle * 3 + 1]];+ const third = weldMap[indices[triangle * 3 + 2]];+ if (first !== second && second !== third && third !== first) keptTriangles.push(triangle);+ }+ if (!keptTriangles.length) throw new RangeError('Every triangle collapses after welding. Reduce weld.');+ const faceCount = keptTriangles.length;+ const faceOffsets = new Uint32Array(faceCount + 1);+ const cornerVertices = new Uint32Array(faceCount * 3);+ const cornerSource = new Uint32Array(faceCount * 3);+ for (let face = 0; face < faceCount; face++) {+ faceOffsets[face + 1] = (face + 1) * 3;+ for (let corner = 0; corner < 3; corner++) {+ const source = indices[keptTriangles[face] * 3 + corner];+ cornerSource[face * 3 + corner] = source;+ cornerVertices[face * 3 + corner] = weldMap[source];+ }+ }+ const edges = deriveEdges(representatives.length, faceOffsets, cornerVertices);+ const cornerAttributes = {};+ if (geometry.uvs instanceof Float32Array && geometry.uvs.length === sourceCount * 2) {+ cornerAttributes.uv = gatherAttribute({ data: geometry.uvs, size: 2 }, cornerSource);+ }+ if (geometry.colors instanceof Float32Array && geometry.colors.length === sourceCount * 3) {+ cornerAttributes.color = gatherAttribute({ data: geometry.colors, size: 3 }, cornerSource);+ }+ const edgeAttributes = {};+ if (normals instanceof Float32Array && normals.length === positions.length) {+ const sharp = new Uint8Array(edges.edgeCount);+ const probe = createMeshData({ positions: weldedPositions, faceOffsets, cornerVertices, edgeVertices: edges.edgeVertices, cornerEdges: edges.cornerEdges });+ const table = edgeCornerTable(probe);+ const { nextCorner } = cornerCycles(probe);+ for (let edge = 0; edge < edges.edgeCount; edge++) {+ const start = table.edgeOffsets[edge];+ if (table.edgeOffsets[edge + 1] - start !== 2) continue;+ const first = table.edgeCorners[start];+ const second = table.edgeCorners[start + 1];+ // Opposite winding: first's start vertex is second's end vertex.+ const pairs = [[first, nextCorner[second]], [nextCorner[first], second]];+ if (pairs.some(([left, right]) => differentNormals(normals, cornerSource[left], cornerSource[right]))) sharp[edge] = 1;+ }+ edgeAttributes.sharp = { data: sharp, size: 1 };+ }+ let mesh = createMeshData({+ positions: weldedPositions, faceOffsets, cornerVertices,+ edgeVertices: edges.edgeVertices, cornerEdges: edges.cornerEdges,+ attributes: { corner: cornerAttributes, edge: edgeAttributes },+ });+ if (quads) mesh = joinTriangles(mesh);+ if (tags === 'axis') mesh = tagFacesByAxis(mesh);+ return mesh;+}diff --git a/src/mesh-data.js b/src/mesh-data.jsnew file mode 100644index 00000000..aaaab6cb--- /dev/null+++ b/src/mesh-data.js@@ -0,0 +1,209 @@+// Compact polygon mesh in Blender's evaluated-mesh layout: positions, face offsets into corner arrays,+// and edges derived once from face boundaries. Attributes live on four domains.++export const DOMAINS = Object.freeze(['point', 'edge', 'face', 'corner']);+export const MAX_MESH_VERTICES = 4_000_000;+export const MAX_MESH_CORNERS = 16_000_000;+export const TAG_PREFIX = 'tag:';++const ATTRIBUTE_TYPES = new Map([+ [Float32Array, 'float32'], [Uint8Array, 'uint8'], [Uint16Array, 'uint16'],+ [Uint32Array, 'uint32'], [Int32Array, 'int32'],+]);++function allFinite(values) {+ for (let index = 0; index < values.length; index++) {+ if (!Number.isFinite(values[index])) return false;+ }+ return true;+}++function domainCount(mesh, domain) {+ if (domain === 'point') return mesh.vertexCount;+ if (domain === 'edge') return mesh.edgeCount;+ if (domain === 'face') return mesh.faceCount;+ return mesh.cornerCount;+}++function validateAttribute(name, attribute, expectedCount) {+ if (!attribute || typeof attribute !== 'object') throw new TypeError(`Attribute ${name} must be { data, size }.`);+ const { data, size } = attribute;+ if (!ATTRIBUTE_TYPES.has(data?.constructor)) throw new TypeError(`Attribute ${name} needs a Float32, Uint8, Uint16, Uint32 or Int32 array.`);+ if (!Number.isInteger(size) || size < 1 || size > 16) throw new RangeError(`Attribute ${name} size must be an integer from 1 to 16.`);+ if (data.length !== expectedCount * size) throw new RangeError(`Attribute ${name} needs ${expectedCount * size} values, not ${data.length}.`);+ if (data instanceof Float32Array && !allFinite(data)) throw new RangeError(`Attribute ${name} contains non-finite values.`);+ return Object.freeze({ data, size });+}++function validateFaces(vertexCount, faceOffsets, cornerVertices) {+ if (!(faceOffsets instanceof Uint32Array) || faceOffsets.length < 2 || faceOffsets[0] !== 0) {+ throw new TypeError('faceOffsets must be a Uint32Array that starts at 0 and has faceCount + 1 entries.');+ }+ if (!(cornerVertices instanceof Uint32Array) || faceOffsets.at(-1) !== cornerVertices.length) {+ throw new TypeError('cornerVertices must be a Uint32Array whose length equals the last face offset.');+ }+ if (cornerVertices.length > MAX_MESH_CORNERS) throw new RangeError(`Meshes support at most ${MAX_MESH_CORNERS} corners.`);+ for (let face = 0; face + 1 < faceOffsets.length; face++) {+ const start = faceOffsets[face];+ const end = faceOffsets[face + 1];+ if (end - start < 3) throw new RangeError(`Face ${face} needs at least three corners.`);+ for (let corner = start; corner < end; corner++) {+ const vertex = cornerVertices[corner];+ if (vertex >= vertexCount) throw new RangeError(`Face ${face} references missing vertex ${vertex}.`);+ const next = corner + 1 === end ? cornerVertices[start] : cornerVertices[corner + 1];+ if (next === vertex) throw new RangeError(`Face ${face} repeats vertex ${vertex} on consecutive corners.`);+ }+ }+}++function validateExplicitEdges(vertexCount, faceOffsets, cornerVertices, edgeVertices, cornerEdges) {+ if (!(edgeVertices instanceof Uint32Array) || edgeVertices.length % 2 !== 0) throw new TypeError('edgeVertices must be a Uint32Array of vertex pairs.');+ if (!(cornerEdges instanceof Uint32Array) || cornerEdges.length !== cornerVertices.length) throw new TypeError('cornerEdges needs one edge per corner.');+ const edgeCount = edgeVertices.length / 2;+ for (let edge = 0; edge < edgeCount; edge++) {+ const first = edgeVertices[edge * 2];+ const second = edgeVertices[edge * 2 + 1];+ if (first >= vertexCount || second >= vertexCount || first === second) throw new RangeError(`Edge ${edge} has invalid vertices.`);+ }+ for (let face = 0; face + 1 < faceOffsets.length; face++) {+ const start = faceOffsets[face];+ const end = faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const edge = cornerEdges[corner];+ if (edge >= edgeCount) throw new RangeError(`Corner ${corner} references missing edge ${edge}.`);+ const vertex = cornerVertices[corner];+ const nextVertex = corner + 1 === end ? cornerVertices[start] : cornerVertices[corner + 1];+ const first = edgeVertices[edge * 2];+ const second = edgeVertices[edge * 2 + 1];+ const matches = (first === vertex && second === nextVertex) || (first === nextVertex && second === vertex);+ if (!matches) throw new RangeError(`Corner ${corner} edge ${edge} does not join its vertices.`);+ }+ }+}++/**+ * Derive unique undirected edges and the edge of every corner (corner to the next corner of its face).+ * Edges are found through per-vertex linked lists, so the cost is linear in corners times vertex degree.+ */+export function deriveEdges(vertexCount, faceOffsets, cornerVertices) {+ const cornerCount = cornerVertices.length;+ const firstEdgeOfVertex = new Int32Array(vertexCount).fill(-1);+ const nextEdgeOfSameVertex = new Int32Array(cornerCount);+ const edgeVertices = new Uint32Array(cornerCount * 2);+ const cornerEdges = new Uint32Array(cornerCount);+ let edgeCount = 0;+ const faceCount = faceOffsets.length - 1;+ for (let face = 0; face < faceCount; face++) {+ const start = faceOffsets[face];+ const end = faceOffsets[face + 1];+ for (let corner = start; corner < end; corner++) {+ const vertex = cornerVertices[corner];+ const nextVertex = corner + 1 === end ? cornerVertices[start] : cornerVertices[corner + 1];+ const low = Math.min(vertex, nextVertex);+ const high = Math.max(vertex, nextVertex);+ let edge = firstEdgeOfVertex[low];+ while (edge !== -1 && edgeVertices[edge * 2 + 1] !== high) edge = nextEdgeOfSameVertex[edge];+ if (edge === -1) {+ edge = edgeCount;+ edgeCount++;+ edgeVertices[edge * 2] = low;+ edgeVertices[edge * 2 + 1] = high;+ nextEdgeOfSameVertex[edge] = firstEdgeOfVertex[low];+ firstEdgeOfVertex[low] = edge;+ }+ cornerEdges[corner] = edge;+ }+ }+ return { edgeVertices: edgeVertices.slice(0, edgeCount * 2), cornerEdges, edgeCount };+}++/**+ * Create an immutable polygon mesh. Inputs are used without copying; callers must not mutate them afterwards.+ * attributes: { point: { name: { data, size } }, edge: {...}, face: {...}, corner: {...} }.+ * Edge attributes are only accepted together with edgeVertices and cornerEdges, because derived edge order is internal.+ */+export function createMeshData({ positions, faceOffsets, cornerVertices, edgeVertices, cornerEdges, attributes = {} }) {+ if (!(positions instanceof Float32Array) || positions.length % 3 !== 0 || positions.length === 0) {+ throw new TypeError('positions must be a nonempty Float32Array of XYZ triples.');+ }+ const vertexCount = positions.length / 3;+ if (vertexCount > MAX_MESH_VERTICES) throw new RangeError(`Meshes support at most ${MAX_MESH_VERTICES} vertices.`);+ if (!allFinite(positions)) throw new RangeError('positions must be finite.');+ validateFaces(vertexCount, faceOffsets, cornerVertices);+ let edges;+ if (edgeVertices && cornerEdges) {+ validateExplicitEdges(vertexCount, faceOffsets, cornerVertices, edgeVertices, cornerEdges);+ edges = { edgeVertices, cornerEdges, edgeCount: edgeVertices.length / 2 };+ } else {+ if (attributes.edge && Object.keys(attributes.edge).length) throw new TypeError('Edge attributes need explicit edgeVertices and cornerEdges.');+ edges = deriveEdges(vertexCount, faceOffsets, cornerVertices);+ }+ const mesh = {+ vertexCount,+ edgeCount: edges.edgeCount,+ faceCount: faceOffsets.length - 1,+ cornerCount: cornerVertices.length,+ positions, faceOffsets, cornerVertices,+ edgeVertices: edges.edgeVertices,+ cornerEdges: edges.cornerEdges,+ };+ const validated = {};+ for (const domain of DOMAINS) {+ const entries = attributes[domain] ?? {};+ const domainAttributes = {};+ for (const [name, attribute] of Object.entries(entries)) {+ domainAttributes[name] = validateAttribute(name, attribute, domainCount(mesh, domain));+ }+ validated[domain] = Object.freeze(domainAttributes);+ }+ for (const name of Object.keys(validated.face)) {+ if (name.startsWith(TAG_PREFIX) && (!(validated.face[name].data instanceof Uint8Array) || validated.face[name].size !== 1)) {+ throw new TypeError(`Tag ${name} must be a Uint8Array face attribute of size 1.`);+ }+ }+ mesh.attributes = Object.freeze(validated);+ return Object.freeze(mesh);+}++/** Names of face tags, without the "tag:" prefix. */+export function meshTags(mesh) {+ return Object.keys(mesh.attributes.face).filter(name => name.startsWith(TAG_PREFIX)).map(name => name.slice(TAG_PREFIX.length));+}++/** Face indices carrying a tag. */+export function facesWithTag(mesh, tag) {+ const attribute = mesh.attributes.face[TAG_PREFIX + tag];+ if (!attribute) throw new RangeError(`Unknown tag ${tag}. Known tags: ${meshTags(mesh).join(', ') || 'none'}.`);+ const faces = [];+ for (let face = 0; face < mesh.faceCount; face++) {+ if (attribute.data[face]) faces.push(face);+ }+ return faces;+}++/** Number of faces carrying each tag. */+export function tagCounts(mesh) {+ const counts = {};+ for (const tag of meshTags(mesh)) {+ const data = mesh.attributes.face[TAG_PREFIX + tag].data;+ let count = 0;+ for (let face = 0; face < mesh.faceCount; face++) count += data[face] ? 1 : 0;+ counts[tag] = count;+ }+ return counts;+}++/** Axis-aligned bounds of the positions. */+export function meshBounds(mesh) {+ const minimum = [Infinity, Infinity, Infinity];+ const maximum = [-Infinity, -Infinity, -Infinity];+ const positions = mesh.positions;+ for (let offset = 0; offset < positions.length; offset += 3) {+ for (let axis = 0; axis < 3; axis++) {+ const value = positions[offset + axis];+ if (value < minimum[axis]) minimum[axis] = value;+ if (value > maximum[axis]) maximum[axis] = value;+ }+ }+ return { min: minimum, max: maximum };+}diff --git a/src/mesh-edit.js b/src/mesh-edit.jsnew file mode 100644index 00000000..9a9f5c88--- /dev/null+++ b/src/mesh-edit.js@@ -0,0 +1,593 @@+import { createMeshData, DOMAINS } from './mesh-data.js';++// Mutable polygon topology in BMesh's model, stored as typed arrays indexed by element number.+//+// Vertex v: position, and one "edge slot" in its disk cycle (-1 when loose).+// Edge e: two endpoint slots, 2e and 2e+1. Slot s belongs to vertex edgeVertex[s]. diskNext/diskPrev link the slots+// around one vertex, which plays the role of BMesh's v1_disk_link and v2_disk_link. edgeLoop is one loop of the+// radial cycle (-1 for a wire edge).+// Loop l: one face corner. loopVertex is the corner's vertex, loopEdge runs from it to the next corner's vertex.+// loopNext/loopPrev walk the face, loopRadialNext/Prev walk the faces sharing loopEdge.+// Face f: one loop and the corner count.+// Removed elements are flagged and recycled through free lists; toMeshData() compacts.++const INITIAL_CAPACITY = 16;++function grow(array, capacity, fill) {+ const next = new array.constructor(capacity);+ next.set(array);+ if (fill !== undefined) next.fill(fill, array.length);+ return next;+}++class ElementStore {+ constructor(fields, capacity) {+ this.fields = fields;+ this.capacity = capacity;+ this.count = 0;+ this.liveCount = 0;+ this.free = [];+ this.removed = new Uint8Array(capacity);+ this.arrays = {};+ for (const [name, { type, width, fill }] of Object.entries(fields)) {+ this.arrays[name] = new type(capacity * width);+ if (fill !== undefined) this.arrays[name].fill(fill);+ }+ this.attributes = new Map();+ }++ ensureCapacity(required) {+ if (required <= this.capacity) return;+ let capacity = this.capacity;+ while (capacity < required) capacity *= 2;+ for (const [name, { width, fill }] of Object.entries(this.fields)) {+ this.arrays[name] = grow(this.arrays[name], capacity * width, fill);+ }+ for (const attribute of this.attributes.values()) {+ attribute.data = grow(attribute.data, capacity * attribute.size);+ }+ this.removed = grow(this.removed, capacity);+ this.capacity = capacity;+ }++ allocate() {+ let index;+ if (this.free.length) {+ index = this.free.pop();+ this.removed[index] = 0;+ } else {+ this.ensureCapacity(this.count + 1);+ index = this.count;+ this.count++;+ }+ for (const attribute of this.attributes.values()) {+ attribute.data.fill(0, index * attribute.size, (index + 1) * attribute.size);+ }+ this.liveCount++;+ return index;+ }++ release(index) {+ this.removed[index] = 1;+ this.free.push(index);+ this.liveCount--;+ }++ isLive(index) {+ return index >= 0 && index < this.count && !this.removed[index];+ }+}++export class EditMesh {+ constructor(capacities = {}) {+ this.vertices = new ElementStore({+ position: { type: Float32Array, width: 3 },+ edgeSlot: { type: Int32Array, width: 1, fill: -1 },+ }, Math.max(INITIAL_CAPACITY, capacities.vertices ?? 0));+ this.edges = new ElementStore({+ vertex: { type: Int32Array, width: 2, fill: -1 },+ diskNext: { type: Int32Array, width: 2, fill: -1 },+ diskPrev: { type: Int32Array, width: 2, fill: -1 },+ loop: { type: Int32Array, width: 1, fill: -1 },+ }, Math.max(INITIAL_CAPACITY, capacities.edges ?? 0));+ this.loops = new ElementStore({+ vertex: { type: Int32Array, width: 1 },+ edge: { type: Int32Array, width: 1 },+ face: { type: Int32Array, width: 1 },+ next: { type: Int32Array, width: 1 },+ prev: { type: Int32Array, width: 1 },+ radialNext: { type: Int32Array, width: 1 },+ radialPrev: { type: Int32Array, width: 1 },+ }, Math.max(INITIAL_CAPACITY, capacities.loops ?? 0));+ this.faces = new ElementStore({+ loop: { type: Int32Array, width: 1, fill: -1 },+ size: { type: Int32Array, width: 1 },+ }, Math.max(INITIAL_CAPACITY, capacities.faces ?? 0));+ }++ storeForDomain(domain) {+ if (domain === 'point') return this.vertices;+ if (domain === 'edge') return this.edges;+ if (domain === 'face') return this.faces;+ if (domain === 'corner') return this.loops;+ throw new RangeError(`Unknown domain ${domain}.`);+ }++ /** Add (or return) a per-element attribute array that grows with the domain. */+ ensureAttribute(domain, name, type = Float32Array, size = 1) {+ const store = this.storeForDomain(domain);+ let attribute = store.attributes.get(name);+ if (attribute) {+ if (attribute.data.constructor !== type || attribute.size !== size) throw new TypeError(`Attribute ${name} already exists with another type or size.`);+ return attribute;+ }+ attribute = { data: new type(store.capacity * size), size };+ store.attributes.set(name, attribute);+ return attribute;+ }++ attribute(domain, name) {+ return this.storeForDomain(domain).attributes.get(name);+ }++ get vertexCount() { return this.vertices.liveCount; }+ get edgeCount() { return this.edges.liveCount; }+ get faceCount() { return this.faces.liveCount; }+ get loopCount() { return this.loops.liveCount; }++ // ----- vertices -----++ createVertex(x, y, z) {+ const vertex = this.vertices.allocate();+ const position = this.vertices.arrays.position;+ position[vertex * 3] = x;+ position[vertex * 3 + 1] = y;+ position[vertex * 3 + 2] = z;+ this.vertices.arrays.edgeSlot[vertex] = -1;+ return vertex;+ }++ vertexPosition(vertex, target = [0, 0, 0]) {+ const position = this.vertices.arrays.position;+ target[0] = position[vertex * 3];+ target[1] = position[vertex * 3 + 1];+ target[2] = position[vertex * 3 + 2];+ return target;+ }++ setVertexPosition(vertex, x, y, z) {+ const position = this.vertices.arrays.position;+ position[vertex * 3] = x;+ position[vertex * 3 + 1] = y;+ position[vertex * 3 + 2] = z;+ }++ // ----- disk cycles -----++ slotVertex(slot) {+ return this.edges.arrays.vertex[slot];+ }++ /** Edges around a vertex, in disk order. */+ vertexEdges(vertex) {+ const result = [];+ const first = this.vertices.arrays.edgeSlot[vertex];+ if (first === -1) return result;+ const diskNext = this.edges.arrays.diskNext;+ let slot = first;+ do {+ result.push(slot >> 1);+ slot = diskNext[slot];+ } while (slot !== first);+ return result;+ }++ vertexDegree(vertex) {+ const first = this.vertices.arrays.edgeSlot[vertex];+ if (first === -1) return 0;+ const diskNext = this.edges.arrays.diskNext;+ let count = 0;+ let slot = first;+ do {+ count++;+ slot = diskNext[slot];+ } while (slot !== first);+ return count;+ }++ /** The edge between two vertices, or -1. Walks the first vertex's disk cycle, as BM_edge_exists does. */+ findEdge(first, second) {+ const start = this.vertices.arrays.edgeSlot[first];+ if (start === -1) return -1;+ const diskNext = this.edges.arrays.diskNext;+ const edgeVertex = this.edges.arrays.vertex;+ let slot = start;+ do {+ if (edgeVertex[slot ^ 1] === second) return slot >> 1;+ slot = diskNext[slot];+ } while (slot !== start);+ return -1;+ }++ linkSlot(slot) {+ const vertex = this.edges.arrays.vertex[slot];+ const edgeSlot = this.vertices.arrays.edgeSlot;+ const diskNext = this.edges.arrays.diskNext;+ const diskPrev = this.edges.arrays.diskPrev;+ const first = edgeSlot[vertex];+ if (first === -1) {+ diskNext[slot] = slot;+ diskPrev[slot] = slot;+ edgeSlot[vertex] = slot;+ return;+ }+ const last = diskPrev[first];+ diskNext[last] = slot;+ diskPrev[slot] = last;+ diskNext[slot] = first;+ diskPrev[first] = slot;+ }++ unlinkSlot(slot) {+ const vertex = this.edges.arrays.vertex[slot];+ const edgeSlot = this.vertices.arrays.edgeSlot;+ const diskNext = this.edges.arrays.diskNext;+ const diskPrev = this.edges.arrays.diskPrev;+ const next = diskNext[slot];+ if (next === slot) {+ edgeSlot[vertex] = -1;+ } else {+ const previous = diskPrev[slot];+ diskNext[previous] = next;+ diskPrev[next] = previous;+ if (edgeSlot[vertex] === slot) edgeSlot[vertex] = next;+ }+ diskNext[slot] = -1;+ diskPrev[slot] = -1;+ }++ // ----- edges -----++ /** Return the edge between two distinct vertices, creating a wire edge when none exists. */+ ensureEdge(first, second) {+ if (first === second) throw new RangeError('An edge needs two distinct vertices.');+ const existing = this.findEdge(first, second);+ if (existing !== -1) return existing;+ const edge = this.edges.allocate();+ this.edges.arrays.vertex[edge * 2] = first;+ this.edges.arrays.vertex[edge * 2 + 1] = second;+ this.edges.arrays.loop[edge] = -1;+ this.linkSlot(edge * 2);+ this.linkSlot(edge * 2 + 1);+ return edge;+ }++ edgeVertices(edge) {+ return [this.edges.arrays.vertex[edge * 2], this.edges.arrays.vertex[edge * 2 + 1]];+ }++ edgeOtherVertex(edge, vertex) {+ const vertices = this.edges.arrays.vertex;+ return vertices[edge * 2] === vertex ? vertices[edge * 2 + 1] : vertices[edge * 2];+ }++ /** Loops in the radial cycle of an edge: one per face using it. */+ edgeLoops(edge) {+ const result = [];+ const first = this.edges.arrays.loop[edge];+ if (first === -1) return result;+ const radialNext = this.loops.arrays.radialNext;+ let loop = first;+ do {+ result.push(loop);+ loop = radialNext[loop];+ } while (loop !== first);+ return result;+ }++ edgeFaceCount(edge) {+ const first = this.edges.arrays.loop[edge];+ if (first === -1) return 0;+ const radialNext = this.loops.arrays.radialNext;+ let count = 0;+ let loop = first;+ do {+ count++;+ loop = radialNext[loop];+ } while (loop !== first);+ return count;+ }++ removeEdge(edge) {+ while (this.edges.arrays.loop[edge] !== -1) {+ this.removeFace(this.loops.arrays.face[this.edges.arrays.loop[edge]]);+ }+ this.unlinkSlot(edge * 2);+ this.unlinkSlot(edge * 2 + 1);+ this.edges.release(edge);+ }++ // ----- loops and faces -----++ linkRadial(loop, edge) {+ const edgeLoop = this.edges.arrays.loop;+ const radialNext = this.loops.arrays.radialNext;+ const radialPrev = this.loops.arrays.radialPrev;+ const first = edgeLoop[edge];+ if (first === -1) {+ radialNext[loop] = loop;+ radialPrev[loop] = loop;+ edgeLoop[edge] = loop;+ return;+ }+ const last = radialPrev[first];+ radialNext[last] = loop;+ radialPrev[loop] = last;+ radialNext[loop] = first;+ radialPrev[first] = loop;+ }++ unlinkRadial(loop) {+ const edge = this.loops.arrays.edge[loop];+ const edgeLoop = this.edges.arrays.loop;+ const radialNext = this.loops.arrays.radialNext;+ const radialPrev = this.loops.arrays.radialPrev;+ const next = radialNext[loop];+ if (next === loop) {+ edgeLoop[edge] = -1;+ return;+ }+ const previous = radialPrev[loop];+ radialNext[previous] = next;+ radialPrev[next] = previous;+ if (edgeLoop[edge] === loop) edgeLoop[edge] = next;+ }++ /**+ * Create a face over existing vertices in winding order, creating missing edges.+ * Returns the face index. Rejects repeated vertices and duplicate faces over the same vertex cycle.+ */+ createFace(vertices) {+ const size = vertices.length;+ if (size < 3) throw new RangeError('A face needs at least three vertices.');+ if (new Set(vertices).size !== size) throw new RangeError('A face cannot repeat a vertex.');+ for (const vertex of vertices) {+ if (!this.vertices.isLive(vertex)) throw new RangeError(`Vertex ${vertex} does not exist.`);+ }+ const edges = new Array(size);+ for (let corner = 0; corner < size; corner++) {+ edges[corner] = this.ensureEdge(vertices[corner], vertices[(corner + 1) % size]);+ }+ const face = this.faces.allocate();+ const loopArrays = this.loops.arrays;+ let firstLoop = -1;+ let previousLoop = -1;+ for (let corner = 0; corner < size; corner++) {+ const loop = this.loops.allocate();+ loopArrays.vertex[loop] = vertices[corner];+ loopArrays.edge[loop] = edges[corner];+ loopArrays.face[loop] = face;+ if (previousLoop === -1) {+ firstLoop = loop;+ } else {+ loopArrays.next[previousLoop] = loop;+ loopArrays.prev[loop] = previousLoop;+ }+ previousLoop = loop;+ this.linkRadial(loop, edges[corner]);+ }+ loopArrays.next[previousLoop] = firstLoop;+ loopArrays.prev[firstLoop] = previousLoop;+ this.faces.arrays.loop[face] = firstLoop;+ this.faces.arrays.size[face] = size;+ return face;+ }++ /** Remove a face and its loops. Edges and vertices stay, as BM_face_kill. */+ removeFace(face) {+ const loopArrays = this.loops.arrays;+ const first = this.faces.arrays.loop[face];+ let loop = first;+ do {+ const next = loopArrays.next[loop];+ this.unlinkRadial(loop);+ this.loops.release(loop);+ loop = next;+ } while (loop !== first);+ this.faces.arrays.loop[face] = -1;+ this.faces.release(face);+ }++ /** Remove a vertex together with every edge and face using it. */+ removeVertex(vertex) {+ while (this.vertices.arrays.edgeSlot[vertex] !== -1) {+ this.removeEdge(this.vertices.arrays.edgeSlot[vertex] >> 1);+ }+ this.vertices.release(vertex);+ }++ faceLoops(face) {+ const result = [];+ const next = this.loops.arrays.next;+ const first = this.faces.arrays.loop[face];+ let loop = first;+ do {+ result.push(loop);+ loop = next[loop];+ } while (loop !== first);+ return result;+ }++ faceVertices(face) {+ return this.faceLoops(face).map(loop => this.loops.arrays.vertex[loop]);+ }++ /** Faces sharing an edge with the given face (each neighbour listed once). */+ faceNeighbors(face) {+ const neighbors = new Set();+ for (const loop of this.faceLoops(face)) {+ for (const other of this.edgeLoops(this.loops.arrays.edge[loop])) {+ const otherFace = this.loops.arrays.face[other];+ if (otherFace !== face) neighbors.add(otherFace);+ }+ }+ return [...neighbors];+ }++ *liveIndices(domain) {+ const store = this.storeForDomain(domain);+ for (let index = 0; index < store.count; index++) {+ if (!store.removed[index]) yield index;+ }+ }+}++function reserve(store, count) {+ store.ensureCapacity(count);+ store.count = count;+ store.liveCount = count;+}++/**+ * Build an EditMesh from MeshData in one pass over typed arrays, keeping element order (vertex, edge, face and loop+ * indices equal MeshData's vertex, edge, face and corner indices) and copying every attribute.+ */+export function editMesh(mesh) {+ const edit = new EditMesh({+ vertices: mesh.vertexCount, edges: mesh.edgeCount, loops: mesh.cornerCount, faces: mesh.faceCount,+ });+ for (const domain of DOMAINS) {+ for (const [name, attribute] of Object.entries(mesh.attributes[domain])) {+ edit.ensureAttribute(domain, name, attribute.data.constructor, attribute.size);+ }+ }+ reserve(edit.vertices, mesh.vertexCount);+ reserve(edit.edges, mesh.edgeCount);+ reserve(edit.loops, mesh.cornerCount);+ reserve(edit.faces, mesh.faceCount);+ edit.vertices.arrays.position.set(mesh.positions);+ const edgeVertex = edit.edges.arrays.vertex;+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const first = mesh.edgeVertices[edge * 2];+ const second = mesh.edgeVertices[edge * 2 + 1];+ if (edit.findEdge(first, second) !== -1) throw new RangeError(`MeshData has a duplicate edge at ${edge}.`);+ edgeVertex[edge * 2] = first;+ edgeVertex[edge * 2 + 1] = second;+ edit.linkSlot(edge * 2);+ edit.linkSlot(edge * 2 + 1);+ }+ const loopArrays = edit.loops.arrays;+ const faceLoop = edit.faces.arrays.loop;+ const faceSize = edit.faces.arrays.size;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ faceLoop[face] = start;+ faceSize[face] = end - start;+ for (let corner = start; corner < end; corner++) {+ loopArrays.vertex[corner] = mesh.cornerVertices[corner];+ loopArrays.edge[corner] = mesh.cornerEdges[corner];+ loopArrays.face[corner] = face;+ loopArrays.next[corner] = corner + 1 === end ? start : corner + 1;+ loopArrays.prev[corner] = corner === start ? end - 1 : corner - 1;+ edit.linkRadial(corner, mesh.cornerEdges[corner]);+ }+ }+ for (const domain of DOMAINS) {+ const store = edit.storeForDomain(domain);+ for (const [name, attribute] of Object.entries(mesh.attributes[domain])) {+ store.attributes.get(name).data.set(attribute.data);+ }+ }+ return edit;+}++function compactAttribute(attribute, liveIndices) {+ const size = attribute.size;+ const data = new attribute.data.constructor(liveIndices.length * size);+ for (let output = 0; output < liveIndices.length; output++) {+ const input = liveIndices[output];+ for (let component = 0; component < size; component++) {+ data[output * size + component] = attribute.data[input * size + component];+ }+ }+ return { data, size };+}++function liveIndexArray(store) {+ const live = new Uint32Array(store.liveCount);+ let output = 0;+ for (let index = 0; index < store.count; index++) {+ if (store.removed[index]) continue;+ live[output] = index;+ output++;+ }+ return live;+}++/** Compact an EditMesh into immutable MeshData. Loose vertices are kept; wire edges are dropped. */+export function meshData(edit) {+ const liveVertices = liveIndexArray(edit.vertices);+ if (!liveVertices.length) throw new RangeError('The mesh has no vertices left.');+ const vertexMap = new Int32Array(edit.vertices.count).fill(-1);+ for (let output = 0; output < liveVertices.length; output++) vertexMap[liveVertices[output]] = output;+ const sourcePositions = edit.vertices.arrays.position;+ const positions = new Float32Array(liveVertices.length * 3);+ for (let output = 0; output < liveVertices.length; output++) {+ const input = liveVertices[output];+ positions[output * 3] = sourcePositions[input * 3];+ positions[output * 3 + 1] = sourcePositions[input * 3 + 1];+ positions[output * 3 + 2] = sourcePositions[input * 3 + 2];+ }+ const liveFaces = liveIndexArray(edit.faces);+ if (!liveFaces.length) throw new RangeError('The mesh has no faces left.');+ const faceOffsets = new Uint32Array(liveFaces.length + 1);+ const faceSize = edit.faces.arrays.size;+ for (let output = 0; output < liveFaces.length; output++) {+ faceOffsets[output + 1] = faceOffsets[output] + faceSize[liveFaces[output]];+ }+ const cornerCount = faceOffsets[liveFaces.length];+ const cornerVertices = new Uint32Array(cornerCount);+ const cornerEdges = new Uint32Array(cornerCount);+ const liveLoops = new Uint32Array(cornerCount);+ const edgeMap = new Int32Array(edit.edges.count).fill(-1);+ const liveEdges = new Uint32Array(edit.edges.liveCount);+ let liveEdgeCount = 0;+ const loopArrays = edit.loops.arrays;+ const faceLoop = edit.faces.arrays.loop;+ let corner = 0;+ for (let output = 0; output < liveFaces.length; output++) {+ const first = faceLoop[liveFaces[output]];+ let loop = first;+ do {+ const edge = loopArrays.edge[loop];+ if (edgeMap[edge] === -1) {+ edgeMap[edge] = liveEdgeCount;+ liveEdges[liveEdgeCount] = edge;+ liveEdgeCount++;+ }+ cornerVertices[corner] = vertexMap[loopArrays.vertex[loop]];+ cornerEdges[corner] = edgeMap[edge];+ liveLoops[corner] = loop;+ corner++;+ loop = loopArrays.next[loop];+ } while (loop !== first);+ }+ const keptEdges = liveEdges.subarray(0, liveEdgeCount);+ const edgeVertices = new Uint32Array(liveEdgeCount * 2);+ const sourceEdgeVertex = edit.edges.arrays.vertex;+ for (let output = 0; output < liveEdgeCount; output++) {+ const edge = keptEdges[output];+ edgeVertices[output * 2] = vertexMap[sourceEdgeVertex[edge * 2]];+ edgeVertices[output * 2 + 1] = vertexMap[sourceEdgeVertex[edge * 2 + 1]];+ }+ const liveByDomain = { point: liveVertices, edge: keptEdges, face: liveFaces, corner: liveLoops };+ const attributes = {};+ for (const domain of DOMAINS) {+ attributes[domain] = {};+ for (const [name, attribute] of edit.storeForDomain(domain).attributes) {+ attributes[domain][name] = compactAttribute(attribute, liveByDomain[domain]);+ }+ }+ return createMeshData({ positions, faceOffsets, cornerVertices, edgeVertices, cornerEdges, attributes });+}diff --git a/src/mesh-lint.js b/src/mesh-lint.jsnew file mode 100644index 00000000..918e8b96--- /dev/null+++ b/src/mesh-lint.js@@ -0,0 +1,106 @@+import { meshBounds, tagCounts } from './mesh-data.js';+import { faceNormals } from './mesh-normals.js';+import { cornerFaces, edgeCornerTable, faceParts } from './mesh-topology.js';++const SAMPLE_LIMIT = 8;++// Every problem names the operation that usually fixes it, so an agent can act without another lookup.+const PROBLEMS = Object.freeze({+ 'non-manifold-edge': { severity: 'error', fix: 'Delete the extra faces or split the edge; booleans and solidify need two faces per edge.' },+ 'inconsistent-winding': { severity: 'error', fix: 'Run recalc_normals on the part so neighbouring faces wind the same way.' },+ 'inverted-part': { severity: 'error', fix: 'Run flip_normals on the part; its normals point inward.' },+ 'degenerate-face': { severity: 'error', fix: 'Run merge_by_distance or dissolve the zero-area faces.' },+ 'loose-vertex': { severity: 'warning', fix: 'Delete loose vertices; they do not render and confuse bounds.' },+ 'boundary-edge': { severity: 'warning', fix: 'Open surface. Fill the hole or add solidify if the part must be closed.' },+});++function addProblem(problems, kind, element) {+ let problem = problems.get(kind);+ if (!problem) {+ problem = { kind, ...PROBLEMS[kind], count: 0, sample: [] };+ problems.set(kind, problem);+ }+ problem.count++;+ if (problem.sample.length < SAMPLE_LIMIT) problem.sample.push(element);+}++/**+ * Signed volume of each part, from the divergence theorem over its triangulated fan.+ * Only meaningful for closed, consistently wound parts.+ */+function partVolumes(mesh, facePart, partCount) {+ const volumes = new Float64Array(partCount);+ const positions = mesh.positions;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ const anchor = mesh.cornerVertices[start] * 3;+ for (let corner = start + 1; corner + 1 < end; corner++) {+ const second = mesh.cornerVertices[corner] * 3;+ const third = mesh.cornerVertices[corner + 1] * 3;+ volumes[facePart[face]] += (+ positions[anchor] * (positions[second + 1] * positions[third + 2] - positions[second + 2] * positions[third + 1]) ++ positions[anchor + 1] * (positions[second + 2] * positions[third] - positions[second] * positions[third + 2]) ++ positions[anchor + 2] * (positions[second] * positions[third + 1] - positions[second + 1] * positions[third])+ ) / 6;+ }+ }+ return volumes;+}++/**+ * Check a mesh for problems that break later operations or rendering.+ * Returns { ok, counts, parts, tags, bounds, problems }, where each problem has kind, severity, count, a sample of+ * element indices (faces, edges or vertices by kind) and a suggested fix. ok is false when any error is present.+ */+export function lintMesh(mesh) {+ const problems = new Map();+ const table = edgeCornerTable(mesh);+ const facesOfCorners = cornerFaces(mesh);+ const { facePart, partCount } = faceParts(mesh, table, facesOfCorners);+ const partOpen = new Uint8Array(partCount);+ const partWindingBroken = new Uint8Array(partCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const start = table.edgeOffsets[edge];+ const faceCount = table.edgeOffsets[edge + 1] - start;+ const part = facePart[facesOfCorners[table.edgeCorners[start]]];+ if (faceCount === 1) {+ addProblem(problems, 'boundary-edge', edge);+ partOpen[part] = 1;+ } else if (faceCount > 2) {+ addProblem(problems, 'non-manifold-edge', edge);+ partOpen[part] = 1;+ } else if (mesh.cornerVertices[table.edgeCorners[start]] === mesh.cornerVertices[table.edgeCorners[start + 1]]) {+ addProblem(problems, 'inconsistent-winding', edge);+ partWindingBroken[part] = 1;+ }+ }+ const bounds = meshBounds(mesh);+ const diagonal = Math.hypot(...bounds.max.map((value, axis) => value - bounds.min[axis]));+ const minimumArea = (diagonal * 1e-7) ** 2;+ const { areas } = faceNormals(mesh);+ for (let face = 0; face < mesh.faceCount; face++) {+ if (areas[face] <= minimumArea) addProblem(problems, 'degenerate-face', face);+ }+ const used = new Uint8Array(mesh.vertexCount);+ for (const vertex of mesh.cornerVertices) used[vertex] = 1;+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {+ if (!used[vertex]) addProblem(problems, 'loose-vertex', vertex);+ }+ const volumes = partVolumes(mesh, facePart, partCount);+ let closedParts = 0;+ for (let part = 0; part < partCount; part++) {+ if (partOpen[part] || partWindingBroken[part]) continue;+ closedParts++;+ if (volumes[part] < 0) addProblem(problems, 'inverted-part', part);+ }+ const problemList = [...problems.values()];+ return {+ ok: !problemList.some(problem => problem.severity === 'error'),+ counts: { vertices: mesh.vertexCount, edges: mesh.edgeCount, faces: mesh.faceCount, corners: mesh.cornerCount },+ parts: { count: partCount, closed: closedParts },+ tags: tagCounts(mesh),+ bounds,+ problems: problemList,+ };+}diff --git a/src/mesh-normals.js b/src/mesh-normals.jsnew file mode 100644index 00000000..003d6f30--- /dev/null+++ b/src/mesh-normals.js@@ -0,0 +1,137 @@+import { cornerCycles, cornerFaces, edgeCornerTable, UnionFind } from './mesh-topology.js';++/**+ * Unit face normals by Newell's method, which handles non-planar polygons, and face areas.+ * Degenerate faces get a zero normal and zero area.+ */+export function faceNormals(mesh) {+ const normals = new Float32Array(mesh.faceCount * 3);+ const areas = new Float64Array(mesh.faceCount);+ const positions = mesh.positions;+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ let normalX = 0;+ let normalY = 0;+ let normalZ = 0;+ for (let corner = start; corner < end; corner++) {+ const current = mesh.cornerVertices[corner] * 3;+ const next = mesh.cornerVertices[corner + 1 === end ? start : corner + 1] * 3;+ normalX += (positions[current + 1] - positions[next + 1]) * (positions[current + 2] + positions[next + 2]);+ normalY += (positions[current + 2] - positions[next + 2]) * (positions[current] + positions[next]);+ normalZ += (positions[current] - positions[next]) * (positions[current + 1] + positions[next + 1]);+ }+ const length = Math.sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ);+ areas[face] = length / 2;+ if (length > 0) {+ normals[face * 3] = normalX / length;+ normals[face * 3 + 1] = normalY / length;+ normals[face * 3 + 2] = normalZ / length;+ }+ }+ return { normals, areas };+}++function cornerAngle(positions, previous, current, next) {+ const firstX = positions[previous] - positions[current];+ const firstY = positions[previous + 1] - positions[current + 1];+ const firstZ = positions[previous + 2] - positions[current + 2];+ const secondX = positions[next] - positions[current];+ const secondY = positions[next + 1] - positions[current + 1];+ const secondZ = positions[next + 2] - positions[current + 2];+ const crossX = firstY * secondZ - firstZ * secondY;+ const crossY = firstZ * secondX - firstX * secondZ;+ const crossZ = firstX * secondY - firstY * secondX;+ const crossLength = Math.sqrt(crossX * crossX + crossY * crossY + crossZ * crossZ);+ return Math.atan2(crossLength, firstX * secondX + firstY * secondY + firstZ * secondZ);+}++/**+ * Corner normals with hard edges, following Blender's model: corners around a vertex are smoothed together across+ * an edge unless the edge is marked sharp (edge attribute "sharp"), is a boundary or non-manifold edge, has faces+ * with opposite winding, or bends by more than sharpAngle (radians; Infinity disables the angle test).+ * Face normals are weighted by corner angle. Returns one normal per smooth group (groupNormals) and the group of+ * every corner (groupOfCorner); the normal of corner c is groupNormals[groupOfCorner[c]].+ */+export function cornerNormals(mesh, { sharpAngle = Infinity } = {}) {+ const { normals: faceNormal } = faceNormals(mesh);+ const { nextCorner, previousCorner } = cornerCycles(mesh);+ const facesOfCorners = cornerFaces(mesh);+ const table = edgeCornerTable(mesh);+ const sharp = mesh.attributes.edge.sharp?.data;+ const cosineLimit = Number.isFinite(sharpAngle) ? Math.cos(sharpAngle) : -2;+ const groups = new UnionFind(mesh.cornerCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (table.edgeOffsets[edge + 1] - table.edgeOffsets[edge] !== 2) continue;+ if (sharp && sharp[edge]) continue;+ const first = table.edgeCorners[table.edgeOffsets[edge]];+ const second = table.edgeCorners[table.edgeOffsets[edge] + 1];+ // Consistent winding runs the shared edge in opposite directions.+ if (mesh.cornerVertices[first] === mesh.cornerVertices[second]) continue;+ const firstFace = facesOfCorners[first];+ const secondFace = facesOfCorners[second];+ const cosine = faceNormal[firstFace * 3] * faceNormal[secondFace * 3] ++ faceNormal[firstFace * 3 + 1] * faceNormal[secondFace * 3 + 1] ++ faceNormal[firstFace * 3 + 2] * faceNormal[secondFace * 3 + 2];+ if (cosine < cosineLimit) continue;+ // first runs a->b and second runs b->a, so the corners at a are first and next(second), at b next(first) and second.+ groups.union(first, nextCorner[second]);+ groups.union(nextCorner[first], second);+ }+ // Number the smooth groups once, so accumulation and lookup avoid repeated find() calls.+ const groupOfCorner = new Uint32Array(mesh.cornerCount);+ const groupOfRoot = new Int32Array(mesh.cornerCount).fill(-1);+ const firstCorners = new Uint32Array(mesh.cornerCount);+ let groupCount = 0;+ for (let corner = 0; corner < mesh.cornerCount; corner++) {+ const root = groups.find(corner);+ if (groupOfRoot[root] === -1) {+ groupOfRoot[root] = groupCount;+ firstCorners[groupCount] = corner;+ groupCount++;+ }+ groupOfCorner[corner] = groupOfRoot[root];+ }+ const groupFirstCorner = firstCorners.subarray(0, groupCount);+ const accumulated = new Float64Array(groupCount * 3);+ const positions = mesh.positions;+ for (let corner = 0; corner < mesh.cornerCount; corner++) {+ const face = facesOfCorners[corner];+ const weight = cornerAngle(+ positions,+ mesh.cornerVertices[previousCorner[corner]] * 3,+ mesh.cornerVertices[corner] * 3,+ mesh.cornerVertices[nextCorner[corner]] * 3,+ );+ const group = groupOfCorner[corner];+ accumulated[group * 3] += faceNormal[face * 3] * weight;+ accumulated[group * 3 + 1] += faceNormal[face * 3 + 1] * weight;+ accumulated[group * 3 + 2] += faceNormal[face * 3 + 2] * weight;+ }+ const groupNormals = new Float32Array(groupCount * 3);+ for (let group = 0; group < groupCount; group++) {+ let normalX = accumulated[group * 3];+ let normalY = accumulated[group * 3 + 1];+ let normalZ = accumulated[group * 3 + 2];+ let length = Math.sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ);+ if (length === 0) {+ // A degenerate fan falls back to its own face normal, then to +Z.+ const face = facesOfCorners[groupFirstCorner[group]];+ normalX = faceNormal[face * 3];+ normalY = faceNormal[face * 3 + 1];+ normalZ = faceNormal[face * 3 + 2];+ length = Math.sqrt(normalX * normalX + normalY * normalY + normalZ * normalZ);+ if (length === 0) {+ normalZ = 1;+ length = 1;+ }+ }+ groupNormals[group * 3] = normalX / length;+ groupNormals[group * 3 + 1] = normalY / length;+ groupNormals[group * 3 + 2] = normalZ / length;+ }+ return {+ groupNormals, groupOfCorner, groupCount, groupFirstCorner, faceNormals: faceNormal,+ };+}+diff --git a/src/mesh-render.js b/src/mesh-render.jsnew file mode 100644index 00000000..3db570c8--- /dev/null+++ b/src/mesh-render.js@@ -0,0 +1,239 @@+import { cornerNormals } from './mesh-normals.js';+import { cornerCycles, edgeCornerTable, UnionFind } from './mesh-topology.js';++const MAX_EAR_CLIPPING_CORNERS = 4096;++function signedArea2d(points, polygon) {+ let area = 0;+ for (let index = 0; index < polygon.length; index++) {+ const current = polygon[index];+ const next = polygon[(index + 1) % polygon.length];+ area += points[current * 2] * points[next * 2 + 1] - points[next * 2] * points[current * 2 + 1];+ }+ return area / 2;+}++function cross2d(points, first, second, third) {+ return (points[second * 2] - points[first * 2]) * (points[third * 2 + 1] - points[first * 2 + 1]) -+ (points[second * 2 + 1] - points[first * 2 + 1]) * (points[third * 2] - points[first * 2]);+}++function pointInTriangle(points, point, first, second, third) {+ const firstSide = cross2d(points, first, second, point);+ const secondSide = cross2d(points, second, third, point);+ const thirdSide = cross2d(points, third, first, point);+ return firstSide >= 0 && secondSide >= 0 && thirdSide >= 0;+}++/**+ * Triangulate one polygon given as corner indices into a 2D point list (counter-clockwise).+ * O(n^2) ear clipping; falls back to a fan when no ear is found (self-intersecting input).+ */+function earClip(points, cornerCount, output) {+ const polygon = Array.from({ length: cornerCount }, (_, index) => index);+ // Clip in counter-clockwise order, then emit triangles in the face's own winding.+ const reversed = signedArea2d(points, polygon) < 0;+ if (reversed) polygon.reverse();+ const emit = (first, second, third) => {+ if (reversed) output.push(third, second, first);+ else output.push(first, second, third);+ };+ let guard = 0;+ while (polygon.length > 3 && guard < cornerCount * cornerCount) {+ guard++;+ let clipped = false;+ for (let index = 0; index < polygon.length; index++) {+ const previous = polygon[(index + polygon.length - 1) % polygon.length];+ const current = polygon[index];+ const next = polygon[(index + 1) % polygon.length];+ if (cross2d(points, previous, current, next) <= 0) continue;+ let containsOther = false;+ for (const other of polygon) {+ if (other === previous || other === current || other === next) continue;+ if (pointInTriangle(points, other, previous, current, next)) {+ containsOther = true;+ break;+ }+ }+ if (containsOther) continue;+ emit(previous, current, next);+ polygon.splice(index, 1);+ clipped = true;+ break;+ }+ if (!clipped) break;+ }+ for (let index = 1; index + 1 < polygon.length; index++) emit(polygon[0], polygon[index], polygon[index + 1]);+}++function projectFace(mesh, start, end, normal) {+ const absolute = normal.map(Math.abs);+ let dropAxis = 2;+ if (absolute[0] >= absolute[1] && absolute[0] >= absolute[2]) dropAxis = 0;+ else if (absolute[1] >= absolute[2]) dropAxis = 1;+ const firstAxis = (dropAxis + 1) % 3;+ const secondAxis = (dropAxis + 2) % 3;+ const flip = normal[dropAxis] < 0;+ const points = new Float64Array((end - start) * 2);+ for (let corner = start; corner < end; corner++) {+ const vertex = mesh.cornerVertices[corner] * 3;+ const index = corner - start;+ points[index * 2] = mesh.positions[vertex + (flip ? secondAxis : firstAxis)];+ points[index * 2 + 1] = mesh.positions[vertex + (flip ? firstAxis : secondAxis)];+ }+ return points;+}++function squaredDistance(positions, first, second) {+ const deltaX = positions[first * 3] - positions[second * 3];+ const deltaY = positions[first * 3 + 1] - positions[second * 3 + 1];+ const deltaZ = positions[first * 3 + 2] - positions[second * 3 + 2];+ return deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;+}++/**+ * Triangles as corner indices (three per triangle) and the face of each triangle.+ * Quads split along the shorter diagonal; larger polygons use ear clipping in the plane of their normal.+ */+export function triangulateMesh(mesh, faceNormal) {+ let triangleCount = 0;+ for (let face = 0; face < mesh.faceCount; face++) triangleCount += mesh.faceOffsets[face + 1] - mesh.faceOffsets[face] - 2;+ const triangleCorners = new Uint32Array(triangleCount * 3);+ const triangleFaces = new Uint32Array(triangleCount);+ const vertices = mesh.cornerVertices;+ const local = [];+ let output = 0;+ const write = (face, first, second, third) => {+ triangleCorners[output * 3] = first;+ triangleCorners[output * 3 + 1] = second;+ triangleCorners[output * 3 + 2] = third;+ triangleFaces[output] = face;+ output++;+ };+ for (let face = 0; face < mesh.faceCount; face++) {+ const start = mesh.faceOffsets[face];+ const end = mesh.faceOffsets[face + 1];+ const size = end - start;+ if (size === 3) {+ write(face, start, start + 1, start + 2);+ } else if (size === 4) {+ const firstDiagonal = squaredDistance(mesh.positions, vertices[start], vertices[start + 2]);+ const secondDiagonal = squaredDistance(mesh.positions, vertices[start + 1], vertices[start + 3]);+ if (firstDiagonal <= secondDiagonal) {+ write(face, start, start + 1, start + 2);+ write(face, start, start + 2, start + 3);+ } else {+ write(face, start, start + 1, start + 3);+ write(face, start + 1, start + 2, start + 3);+ }+ } else {+ if (size > MAX_EAR_CLIPPING_CORNERS) throw new RangeError(`Face ${face} has ${size} corners; triangulation supports ${MAX_EAR_CLIPPING_CORNERS}.`);+ const normal = [faceNormal[face * 3], faceNormal[face * 3 + 1], faceNormal[face * 3 + 2]];+ local.length = 0;+ earClip(projectFace(mesh, start, end, normal), size, local);+ for (let index = 0; index < local.length; index += 3) write(face, start + local[index], start + local[index + 1], start + local[index + 2]);+ }+ }+ return { triangleCorners, triangleFaces };+}++function equalCornerValues(attributes, first, second) {+ for (const attribute of attributes) {+ for (let component = 0; component < attribute.size; component++) {+ if (attribute.data[first * attribute.size + component] !== attribute.data[second * attribute.size + component]) return false;+ }+ }+ return true;+}++function joinRenderCorners(renderSets, groupOfCorner, splitAttributes, first, second) {+ if (groupOfCorner[first] !== groupOfCorner[second]) return;+ if (!equalCornerValues(splitAttributes, first, second)) return;+ renderSets.union(first, second);+}++/**+ * Convert MeshData into renderer geometry: Float32 positions, normals, optional uvs and colors, Uint32 triangles.+ * Render vertices are shared between corners of one vertex unless a hard edge or a UV/colour seam separates them.+ * The returned maps let a deform-only change re-gather positions without re-running this function.+ */+export function extractRender(mesh, { sharpAngle = Infinity } = {}) {+ const { groupNormals, groupOfCorner, groupCount, groupFirstCorner, faceNormals } = cornerNormals(mesh, { sharpAngle });+ const uvAttribute = mesh.attributes.corner.uv?.size === 2 ? mesh.attributes.corner.uv : undefined;+ const colorAttribute = mesh.attributes.corner.color?.size === 3 ? mesh.attributes.corner.color : undefined;+ const splitAttributes = [uvAttribute, colorAttribute].filter(Boolean);+ let cornerRenderVertex = groupOfCorner;+ let renderVertexCorner = groupFirstCorner;+ let renderVertexCount = groupCount;+ if (splitAttributes.length) {+ // Smooth groups that also agree on UV and colour across each shared edge become one render vertex.+ const { nextCorner } = cornerCycles(mesh);+ const table = edgeCornerTable(mesh);+ const renderSets = new UnionFind(mesh.cornerCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ if (table.edgeOffsets[edge + 1] - table.edgeOffsets[edge] !== 2) continue;+ const first = table.edgeCorners[table.edgeOffsets[edge]];+ const second = table.edgeCorners[table.edgeOffsets[edge] + 1];+ if (mesh.cornerVertices[first] === mesh.cornerVertices[second]) continue;+ // Opposite winding: the corners at the shared start vertex are first and next(second), and vice versa.+ joinRenderCorners(renderSets, groupOfCorner, splitAttributes, first, nextCorner[second]);+ joinRenderCorners(renderSets, groupOfCorner, splitAttributes, nextCorner[first], second);+ }+ cornerRenderVertex = new Uint32Array(mesh.cornerCount);+ const renderVertexOfRoot = new Int32Array(mesh.cornerCount).fill(-1);+ const firstCorners = new Uint32Array(mesh.cornerCount);+ renderVertexCount = 0;+ for (let corner = 0; corner < mesh.cornerCount; corner++) {+ const root = renderSets.find(corner);+ if (renderVertexOfRoot[root] === -1) {+ renderVertexOfRoot[root] = renderVertexCount;+ firstCorners[renderVertexCount] = corner;+ renderVertexCount++;+ }+ cornerRenderVertex[corner] = renderVertexOfRoot[root];+ }+ renderVertexCorner = firstCorners.subarray(0, renderVertexCount);+ }+ const positions = new Float32Array(renderVertexCount * 3);+ const normals = new Float32Array(renderVertexCount * 3);+ const renderVertexSource = new Uint32Array(renderVertexCount);+ const uvs = uvAttribute ? new Float32Array(renderVertexCount * 2) : undefined;+ const colors = colorAttribute ? new Float32Array(renderVertexCount * 3) : undefined;+ for (let renderVertex = 0; renderVertex < renderVertexCount; renderVertex++) {+ const corner = renderVertexCorner[renderVertex];+ const vertex = mesh.cornerVertices[corner];+ const group = groupOfCorner[corner];+ renderVertexSource[renderVertex] = vertex;+ positions[renderVertex * 3] = mesh.positions[vertex * 3];+ positions[renderVertex * 3 + 1] = mesh.positions[vertex * 3 + 1];+ positions[renderVertex * 3 + 2] = mesh.positions[vertex * 3 + 2];+ normals[renderVertex * 3] = groupNormals[group * 3];+ normals[renderVertex * 3 + 1] = groupNormals[group * 3 + 1];+ normals[renderVertex * 3 + 2] = groupNormals[group * 3 + 2];+ if (uvs) {+ uvs[renderVertex * 2] = uvAttribute.data[corner * 2];+ uvs[renderVertex * 2 + 1] = uvAttribute.data[corner * 2 + 1];+ }+ if (colors) {+ for (let channel = 0; channel < 3; channel++) colors[renderVertex * 3 + channel] = colorAttribute.data[corner * 3 + channel];+ }+ }+ const { triangleCorners, triangleFaces } = triangulateMesh(mesh, faceNormals);+ const indices = new Uint32Array(triangleCorners.length);+ for (let index = 0; index < triangleCorners.length; index++) indices[index] = cornerRenderVertex[triangleCorners[index]];+ const geometry = { positions, normals, indices };+ if (uvs) geometry.uvs = uvs;+ if (colors) geometry.colors = colors;+ return { geometry, renderVertexSource, cornerRenderVertex, triangleFaces };+}++/** Re-gather positions after a deform-only edit, reusing the maps from extractRender. */+export function gatherRenderPositions(mesh, renderVertexSource, target = new Float32Array(renderVertexSource.length * 3)) {+ for (let renderVertex = 0; renderVertex < renderVertexSource.length; renderVertex++) {+ const vertex = renderVertexSource[renderVertex];+ target[renderVertex * 3] = mesh.positions[vertex * 3];+ target[renderVertex * 3 + 1] = mesh.positions[vertex * 3 + 1];+ target[renderVertex * 3 + 2] = mesh.positions[vertex * 3 + 2];+ }+ return target;+}diff --git a/src/mesh-topology.js b/src/mesh-topology.jsnew file mode 100644index 00000000..243e3caa--- /dev/null+++ b/src/mesh-topology.js@@ -0,0 +1,100 @@+// Adjacency tables derived from MeshData on demand. Each is linear in the corner count.++/** Face index of every corner. */+export function cornerFaces(mesh) {+ const faces = new Uint32Array(mesh.cornerCount);+ for (let face = 0; face < mesh.faceCount; face++) {+ faces.fill(face, mesh.faceOffsets[face], mesh.faceOffsets[face + 1]);+ }+ return faces;+}++/** Next and previous corner within the same face. */+export function cornerCycles(mesh) {+ const nextCorner = new Uint32Array(mesh.cornerCount);+ const previousCorner = new Uint32Array(mesh.cornerCount);+ 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++) {+ const next = corner + 1 === end ? start : corner + 1;+ nextCorner[corner] = next;+ previousCorner[next] = corner;+ }+ }+ return { nextCorner, previousCorner };+}++/**+ * Corners grouped by edge, in compressed rows: edgeCorners[edgeOffsets[e] .. edgeOffsets[e + 1]) are the corners+ * whose edge (corner to next corner) is e. The row length is the number of faces using the edge.+ */+export function edgeCornerTable(mesh) {+ const edgeOffsets = new Uint32Array(mesh.edgeCount + 1);+ for (let corner = 0; corner < mesh.cornerCount; corner++) edgeOffsets[mesh.cornerEdges[corner] + 1]++;+ for (let edge = 0; edge < mesh.edgeCount; edge++) edgeOffsets[edge + 1] += edgeOffsets[edge];+ const fill = edgeOffsets.slice(0, mesh.edgeCount);+ const edgeCorners = new Uint32Array(mesh.cornerCount);+ for (let corner = 0; corner < mesh.cornerCount; corner++) {+ const edge = mesh.cornerEdges[corner];+ edgeCorners[fill[edge]] = corner;+ fill[edge]++;+ }+ return { edgeOffsets, edgeCorners };+}++/** Disjoint-set forest over integers with path halving and union by size. */+export class UnionFind {+ constructor(count) {+ this.parent = new Uint32Array(count);+ this.size = new Uint32Array(count).fill(1);+ for (let index = 0; index < count; index++) this.parent[index] = index;+ }++ find(index) {+ const parent = this.parent;+ while (parent[index] !== index) {+ parent[index] = parent[parent[index]];+ index = parent[index];+ }+ return index;+ }++ union(first, second) {+ let rootFirst = this.find(first);+ let rootSecond = this.find(second);+ if (rootFirst === rootSecond) return rootFirst;+ if (this.size[rootFirst] < this.size[rootSecond]) {+ const swap = rootFirst;+ rootFirst = rootSecond;+ rootSecond = swap;+ }+ this.parent[rootSecond] = rootFirst;+ this.size[rootFirst] += this.size[rootSecond];+ return rootFirst;+ }+}++/** Connected parts by shared edges. Returns the part index of every face and the part count. */+export function faceParts(mesh, table = edgeCornerTable(mesh), facesOfCorners = cornerFaces(mesh)) {+ const sets = new UnionFind(mesh.faceCount);+ for (let edge = 0; edge < mesh.edgeCount; edge++) {+ const start = table.edgeOffsets[edge];+ const end = table.edgeOffsets[edge + 1];+ for (let index = start + 1; index < end; index++) {+ sets.union(facesOfCorners[table.edgeCorners[start]], facesOfCorners[table.edgeCorners[index]]);+ }+ }+ const partOfRoot = new Map();+ const facePart = new Uint32Array(mesh.faceCount);+ for (let face = 0; face < mesh.faceCount; face++) {+ const root = sets.find(face);+ let part = partOfRoot.get(root);+ if (part === undefined) {+ part = partOfRoot.size;+ partOfRoot.set(root, part);+ }+ facePart[face] = part;+ }+ return { facePart, partCount: partOfRoot.size };+}diff --git a/src/mesh-validate.js b/src/mesh-validate.jsnew file mode 100644index 00000000..cccafb9d--- /dev/null+++ b/src/mesh-validate.js@@ -0,0 +1,113 @@+// Structural invariants of an EditMesh. Every operator test runs this after each step.++function fail(message) {+ throw new RangeError(`Topology invalid: ${message}`);+}++function checkVertices(edit) {+ const edgeSlot = edit.vertices.arrays.edgeSlot;+ const diskNext = edit.edges.arrays.diskNext;+ const diskPrev = edit.edges.arrays.diskPrev;+ const edgeVertex = edit.edges.arrays.vertex;+ const slotLimit = edit.edges.count * 2;+ let diskSlots = 0;+ for (const vertex of edit.liveIndices('point')) {+ const first = edgeSlot[vertex];+ if (first === -1) continue;+ let slot = first;+ let steps = 0;+ do {+ if (slot < 0 || slot >= slotLimit || edit.edges.removed[slot >> 1]) fail(`vertex ${vertex} disk reaches a removed or missing edge.`);+ if (edgeVertex[slot] !== vertex) fail(`vertex ${vertex} disk contains edge ${slot >> 1}, which does not use it.`);+ if (diskPrev[diskNext[slot]] !== slot) fail(`vertex ${vertex} disk links are not symmetric at edge ${slot >> 1}.`);+ steps++;+ if (steps > slotLimit) fail(`vertex ${vertex} disk cycle does not close.`);+ slot = diskNext[slot];+ } while (slot !== first);+ diskSlots += steps;+ }+ return diskSlots;+}++function checkEdges(edit, diskSlots) {+ const edgeVertex = edit.edges.arrays.vertex;+ const edgeLoop = edit.edges.arrays.loop;+ const loopArrays = edit.loops.arrays;+ let radialLoops = 0;+ let liveEdges = 0;+ for (const edge of edit.liveIndices('edge')) {+ liveEdges++;+ const first = edgeVertex[edge * 2];+ const second = edgeVertex[edge * 2 + 1];+ if (!edit.vertices.isLive(first) || !edit.vertices.isLive(second)) fail(`edge ${edge} uses a removed vertex.`);+ if (first === second) fail(`edge ${edge} is a loop on vertex ${first}.`);+ if (edit.findEdge(first, second) !== edge) fail(`edge ${edge} duplicates another edge between ${first} and ${second}.`);+ const firstLoop = edgeLoop[edge];+ if (firstLoop === -1) continue;+ let loop = firstLoop;+ let steps = 0;+ do {+ if (!edit.loops.isLive(loop)) fail(`edge ${edge} radial cycle reaches a removed loop.`);+ if (loopArrays.edge[loop] !== edge) fail(`edge ${edge} radial cycle contains loop ${loop} of edge ${loopArrays.edge[loop]}.`);+ if (loopArrays.radialPrev[loopArrays.radialNext[loop]] !== loop) fail(`edge ${edge} radial links are not symmetric.`);+ steps++;+ if (steps > edit.loops.count) fail(`edge ${edge} radial cycle does not close.`);+ loop = loopArrays.radialNext[loop];+ } while (loop !== firstLoop);+ radialLoops += steps;+ }+ if (diskSlots !== liveEdges * 2) fail(`disk cycles hold ${diskSlots} edge ends, expected ${liveEdges * 2}.`);+ return radialLoops;+}++function checkFaces(edit, radialLoops) {+ const loopArrays = edit.loops.arrays;+ let faceLoops = 0;+ // Last face that visited each vertex, to find repeated vertices without a Set per face.+ const visitedByFace = new Int32Array(edit.vertices.count).fill(-1);+ for (const face of edit.liveIndices('face')) {+ const first = edit.faces.arrays.loop[face];+ const size = edit.faces.arrays.size[face];+ if (size < 3) fail(`face ${face} has ${size} corners.`);+ let loop = first;+ let steps = 0;+ do {+ if (!edit.loops.isLive(loop)) fail(`face ${face} reaches a removed loop.`);+ if (loopArrays.face[loop] !== face) fail(`face ${face} contains loop ${loop} of face ${loopArrays.face[loop]}.`);+ if (loopArrays.prev[loopArrays.next[loop]] !== loop) fail(`face ${face} loop links are not symmetric.`);+ const vertex = loopArrays.vertex[loop];+ const nextVertex = loopArrays.vertex[loopArrays.next[loop]];+ const edge = loopArrays.edge[loop];+ const edgeFirst = edit.edges.arrays.vertex[edge * 2];+ const edgeSecond = edit.edges.arrays.vertex[edge * 2 + 1];+ const joins = (edgeFirst === vertex && edgeSecond === nextVertex) || (edgeFirst === nextVertex && edgeSecond === vertex);+ if (!joins) fail(`face ${face} loop ${loop} edge ${edge} does not join vertices ${vertex} and ${nextVertex}.`);+ if (visitedByFace[vertex] === face) fail(`face ${face} repeats vertex ${vertex}.`);+ visitedByFace[vertex] = face;+ steps++;+ if (steps > size) fail(`face ${face} has more loops than its size ${size}.`);+ loop = loopArrays.next[loop];+ } while (loop !== first);+ if (steps !== size) fail(`face ${face} has ${steps} loops but size ${size}.`);+ faceLoops += steps;+ }+ if (faceLoops !== edit.loops.liveCount) fail(`faces own ${faceLoops} loops but ${edit.loops.liveCount} are live.`);+ if (radialLoops !== faceLoops) fail(`radial cycles hold ${radialLoops} loops but faces own ${faceLoops}.`);+}++/**+ * Check every link of an EditMesh. Throws RangeError naming the first broken element.+ * Returns counts and the Euler characteristic V - E + F.+ */+export function validateTopology(edit) {+ const diskSlots = checkVertices(edit);+ const radialLoops = checkEdges(edit, diskSlots);+ checkFaces(edit, radialLoops);+ return {+ vertices: edit.vertexCount,+ edges: edit.edgeCount,+ faces: edit.faceCount,+ loops: edit.loopCount,+ euler: edit.vertexCount - edit.edgeCount + edit.faceCount,+ };+}diff --git a/src/mesh.js b/src/mesh.jsnew file mode 100644index 00000000..bca34a21--- /dev/null+++ b/src/mesh.js@@ -0,0 +1,13 @@+// Polygon mesh core for agent modeling: compact MeshData, half-edge EditMesh, conversion, normals, render+// extraction and lint. See docs/mesh.md.+export {+ createMeshData, deriveEdges, meshTags, facesWithTag, tagCounts, meshBounds,+ DOMAINS, TAG_PREFIX, MAX_MESH_VERTICES, MAX_MESH_CORNERS,+} from './mesh-data.js';+export { EditMesh, editMesh, meshData } from './mesh-edit.js';+export { validateTopology } from './mesh-validate.js';+export { faceNormals, cornerNormals } from './mesh-normals.js';+export { triangulateMesh, extractRender, gatherRenderPositions } from './mesh-render.js';+export { meshFromGeometry, joinTriangles, tagFacesByAxis, weldVertices, rebuildFromCorners, withFaceAttributes } from './mesh-convert.js';+export { lintMesh } from './mesh-lint.js';+export { cornerFaces, cornerCycles, edgeCornerTable, faceParts } from './mesh-topology.js';diff --git a/tests/mesh-core.test.js b/tests/mesh-core.test.jsnew file mode 100644index 00000000..ff5fd0c3--- /dev/null+++ b/tests/mesh-core.test.js@@ -0,0 +1,256 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import {+ createMeshData, editMesh, meshData, validateTopology, meshFromGeometry, extractRender, lintMesh,+ facesWithTag, tagCounts, triangulateMesh, faceNormals, gatherRenderPositions, EditMesh,+} from '../src/mesh.js';+import { box, sphere, cylinder, torus } from '../src/geometry.js';+import { lathe, extrude } from '../src/modeling.js';++function polygonMesh(positions, faces, attributes) {+ const faceOffsets = new Uint32Array(faces.length + 1);+ faces.forEach((face, index) => { faceOffsets[index + 1] = faceOffsets[index] + face.length; });+ return createMeshData({ positions: new Float32Array(positions), faceOffsets, cornerVertices: new Uint32Array(faces.flat()), attributes });+}++function unitCube() {+ return polygonMesh(+ [-1, -1, -1, 1, -1, -1, 1, 1, -1, -1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, -1, 1, 1],+ [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]],+ );+}++function grid(columns, rows) {+ const positions = new Float32Array((columns + 1) * (rows + 1) * 3);+ for (let row = 0; row <= rows; row++) {+ for (let column = 0; column <= columns; column++) {+ const offset = (row * (columns + 1) + column) * 3;+ positions[offset] = column;+ positions[offset + 2] = -row;+ }+ }+ const faceOffsets = new Uint32Array(columns * rows + 1);+ const cornerVertices = new Uint32Array(columns * rows * 4);+ for (let row = 0; row < rows; row++) {+ for (let column = 0; column < columns; column++) {+ const face = row * columns + column;+ const first = row * (columns + 1) + column;+ faceOffsets[face + 1] = (face + 1) * 4;+ cornerVertices.set([first, first + 1, first + columns + 2, first + columns + 1], face * 4);+ }+ }+ return createMeshData({ positions, faceOffsets, cornerVertices });+}++function triangleArea(positions, indices, offset) {+ const [a, b, c] = [indices[offset] * 3, indices[offset + 1] * 3, indices[offset + 2] * 3];+ const first = [0, 1, 2].map(axis => positions[b + axis] - positions[a + axis]);+ const second = [0, 1, 2].map(axis => positions[c + axis] - positions[a + axis]);+ return Math.hypot(first[1] * second[2] - first[2] * second[1], first[2] * second[0] - first[0] * second[2], first[0] * second[1] - first[1] * second[0]) / 2;+}++function surfaceArea(geometry) {+ let area = 0;+ for (let offset = 0; offset < geometry.indices.length; offset += 3) area += triangleArea(geometry.positions, geometry.indices, offset);+ return area;+}++test('MeshData derives unique edges for a cube', () => {+ const cube = unitCube();+ assert.equal(cube.vertexCount, 8);+ assert.equal(cube.edgeCount, 12);+ assert.equal(cube.faceCount, 6);+ assert.ok(Object.isFrozen(cube));+});++test('MeshData rejects invalid faces and attributes with actionable messages', () => {+ assert.throws(() => polygonMesh([0, 0, 0, 1, 0, 0], [[0, 1]]), /at least three corners/);+ assert.throws(() => polygonMesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [[0, 1, 5]]), /missing vertex 5/);+ assert.throws(() => polygonMesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [[0, 1, 1, 2]]), /repeats vertex/);+ assert.throws(() => polygonMesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [[0, 1, 2]], { face: { 'tag:top': { data: new Float32Array(1), size: 1 } } }), /Uint8Array/);+ assert.throws(() => polygonMesh([0, 0, 0, 1, 0, 0, 0, 1, 0], [[0, 1, 2]], { corner: { uv: { data: new Float32Array(4), size: 2 } } }), /needs 6 values/);+});++test('EditMesh round trip keeps topology, order and attributes', () => {+ const uv = new Float32Array(24 * 2).map((_, index) => index / 48);+ const source = polygonMesh(+ Array.from(unitCube().positions),+ [[0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]],+ { corner: { uv: { data: uv, size: 2 } }, face: { 'tag:top': { data: Uint8Array.from([0, 1, 0, 0, 0, 0]), size: 1 } } },+ );+ const edit = editMesh(source);+ assert.deepEqual(validateTopology(edit), { vertices: 8, edges: 12, faces: 6, loops: 24, euler: 2 });+ assert.equal(edit.vertexDegree(0), 3);+ assert.equal(edit.edgeFaceCount(edit.findEdge(0, 1)), 2);+ assert.deepEqual(edit.faceNeighbors(0).sort(), [2, 3, 4, 5]);+ const back = meshData(edit);+ assert.deepEqual(back.positions, source.positions);+ assert.deepEqual(back.faceOffsets, source.faceOffsets);+ assert.deepEqual(back.cornerVertices, source.cornerVertices);+ assert.deepEqual(back.edgeVertices, source.edgeVertices);+ assert.deepEqual(back.attributes.corner.uv.data, uv);+ assert.deepEqual(facesWithTag(back, 'top'), [1]);+});++test('EditMesh removal keeps every cycle valid and recycles indices', () => {+ const edit = editMesh(unitCube());+ edit.removeFace(0);+ assert.equal(validateTopology(edit).euler, 1);+ edit.removeVertex(6);+ assert.deepEqual(validateTopology(edit), { vertices: 7, edges: 9, faces: 2, loops: 8, euler: 0 });+ const vertex = edit.createVertex(1, 1, 1);+ assert.equal(vertex, 6, 'freed vertex index is reused');+ edit.createFace([1, 2, vertex, 5]);+ edit.createFace([2, 3, 7, vertex]);+ edit.createFace([4, 5, vertex, 7]);+ edit.createFace([0, 1, 2, 3].reverse());+ assert.deepEqual(validateTopology(edit), { vertices: 8, edges: 12, faces: 6, loops: 24, euler: 2 });+ assert.equal(lintMesh(meshData(edit)).ok, true);+});++test('EditMesh rejects faces with repeated or missing vertices', () => {+ const edit = new EditMesh();+ const a = edit.createVertex(0, 0, 0);+ const b = edit.createVertex(1, 0, 0);+ assert.throws(() => edit.createFace([a, b, a]), /repeat/);+ assert.throws(() => edit.createFace([a, b, 99]), /does not exist/);+ assert.throws(() => edit.ensureEdge(a, a), /distinct/);+});++test('validateTopology reports a corrupted link', () => {+ const edit = editMesh(unitCube());+ edit.loops.arrays.next[0] = 5;+ assert.throws(() => validateTopology(edit), /Topology invalid/);+});++test('random face removal and rebuilding keeps the topology valid', () => {+ let seed = 7;+ const random = () => {+ seed = (seed * 1103515245 + 12345) & 0x7fffffff;+ return seed / 0x7fffffff;+ };+ const edit = editMesh(grid(12, 12));+ for (let step = 0; step < 200; step++) {+ const faces = [...edit.liveIndices('face')];+ if (random() < 0.6 && faces.length > 10) {+ edit.removeFace(faces[Math.floor(random() * faces.length)]);+ } else {+ const vertices = [...edit.liveIndices('point')];+ const picked = new Set();+ while (picked.size < 3) picked.add(vertices[Math.floor(random() * vertices.length)]);+ const corners = [...picked];+ const [first, second, third] = corners;+ const occupied = [[first, second], [second, third], [third, first]].some(([from, to]) => {+ const edge = edit.findEdge(from, to);+ return edge !== -1 && edit.edgeLoops(edge).some(loop => edit.loops.arrays.vertex[loop] === from);+ });+ if (!occupied) edit.createFace(corners);+ }+ validateTopology(edit);+ }+ const compact = meshData(edit);+ validateTopology(editMesh(compact));+});++test('meshFromGeometry welds seams, joins quads, marks hard edges and tags a box', () => {+ const mesh = meshFromGeometry(box(0, 1));+ assert.equal(mesh.vertexCount, 8);+ assert.equal(mesh.faceCount, 6);+ assert.equal(mesh.edgeCount, 12);+ assert.ok(mesh.attributes.edge.sharp.data.every(value => value === 1), 'every box edge is hard');+ assert.deepEqual(tagCounts(mesh), { right: 1, left: 1, top: 1, bottom: 1, front: 1, back: 1, side: 4 });+ const report = lintMesh(mesh);+ assert.equal(report.ok, true);+ assert.equal(report.parts.closed, 1);+ assert.deepEqual(report.problems, []);+});++test('meshFromGeometry keeps a sphere smooth and closed', () => {+ const mesh = meshFromGeometry(sphere(32, 16));+ assert.equal(mesh.vertexCount, 32 * 15 + 2);+ const report = lintMesh(mesh);+ assert.equal(report.ok, true, JSON.stringify(report.problems));+ assert.equal(report.parts.count, 1);+ assert.ok(mesh.attributes.edge.sharp.data.every(value => value === 0), 'seam is not a hard edge');+ assert.ok(facesWithTag(mesh, 'top').length > 0);+});++test('extractRender reproduces area and hard edges of generators', () => {+ for (const geometry of [box(0, 1), box(0.1, 3), sphere(24, 12), cylinder(24, 0.05, 2), torus(0.2, 24, 12)]) {+ const mesh = meshFromGeometry(geometry);+ const { geometry: rendered } = extractRender(mesh);+ const expected = surfaceArea(geometry);+ assert.ok(Math.abs(surfaceArea(rendered) - expected) < expected * 1e-4, 'triangulated area matches the input');+ for (let index = 0; index < rendered.normals.length; index += 3) {+ assert.ok(Math.abs(Math.hypot(...rendered.normals.subarray(index, index + 3)) - 1) < 1e-5);+ }+ }+ const { geometry: cube } = extractRender(meshFromGeometry(box(0, 1)));+ assert.equal(cube.positions.length / 3, 24, 'hard cube corners split into one vertex per face');+ assert.equal(cube.indices.length / 3, 12);+});++test('extractRender splits UV seams but not normals, and respects sharpAngle', () => {+ const mesh = meshFromGeometry(lathe([[0, 0], [1, 0], [1, 1], [0, 1]], { segments: 16 }));+ assert.ok(mesh.attributes.corner.uv);+ const { geometry } = extractRender(mesh);+ assert.ok(geometry.uvs.length === geometry.positions.length / 3 * 2);+ const smooth = extractRender(unitCube()).geometry;+ assert.equal(smooth.positions.length / 3, 8, 'no sharp attribute and no angle limit keeps vertices shared');+ const hard = extractRender(unitCube(), { sharpAngle: Math.PI / 6 }).geometry;+ assert.equal(hard.positions.length / 3, 24);+});++test('triangulation handles concave n-gons in both windings', () => {+ const lShape = [[0, 0], [2, 0], [2, 1], [1, 1], [1, 2], [0, 2]];+ for (const order of [lShape, [...lShape].reverse()]) {+ const mesh = polygonMesh(order.flatMap(([x, z]) => [x, 0, z]), [order.map((_, index) => index)]);+ const { normals } = faceNormals(mesh);+ const { triangleCorners } = triangulateMesh(mesh, normals);+ assert.equal(triangleCorners.length, 12);+ const { geometry } = extractRender(mesh);+ assert.ok(Math.abs(surfaceArea(geometry) - 3) < 1e-6);+ for (let offset = 0; offset < geometry.indices.length; offset += 3) {+ const [a, b, c] = [0, 1, 2].map(corner => geometry.indices[offset + corner] * 3);+ const p = geometry.positions;+ const crossY = (p[c] - p[a]) * (p[b + 2] - p[a + 2]) - (p[c + 2] - p[a + 2]) * (p[b] - p[a]);+ assert.equal(Math.sign(crossY), Math.sign(normals[1]), 'triangles keep the face winding');+ }+ }+});++test('extrude with holes converts into one closed mesh', () => {+ const geometry = extrude([[-2, -2], [2, -2], [2, 2], [-2, 2]], { holes: [[[-1, -1], [-1, 1], [1, 1], [1, -1]]], depth: 0.5 });+ const mesh = meshFromGeometry(geometry);+ const report = lintMesh(mesh);+ assert.equal(report.ok, true, JSON.stringify(report.problems));+ assert.equal(report.parts.closed, 1);+ assert.ok(Math.abs(surfaceArea(extractRender(mesh).geometry) - surfaceArea(geometry)) < 1e-4);+});++test('lintMesh names open, non-manifold, inverted and loose problems with fixes', () => {+ const openBox = polygonMesh(Array.from(unitCube().positions), [[0, 3, 2, 1], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]);+ const open = lintMesh(openBox);+ assert.equal(open.ok, true);+ assert.equal(open.problems[0].kind, 'boundary-edge');+ assert.equal(open.problems[0].count, 4);+ const inside = polygonMesh(Array.from(unitCube().positions), [[0, 1, 2, 3], [4, 7, 6, 5], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0]]);+ const inverted = lintMesh(inside);+ assert.equal(inverted.ok, false);+ assert.equal(inverted.problems[0].kind, 'inverted-part');+ assert.match(inverted.problems[0].fix, /flip_normals/);+ const fin = polygonMesh([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 5, 5, 5], [[0, 1, 2], [1, 0, 3], [0, 1, 4]]);+ const kinds = lintMesh(fin).problems.map(problem => problem.kind);+ assert.ok(kinds.includes('non-manifold-edge'));+ assert.ok(kinds.includes('loose-vertex'));+ const flipped = polygonMesh(Array.from(unitCube().positions), [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]]);+ assert.ok(lintMesh(flipped).problems.some(problem => problem.kind === 'inconsistent-winding'));+});++test('gatherRenderPositions follows a deform-only edit', () => {+ const mesh = meshFromGeometry(sphere(16, 8));+ const { geometry, renderVertexSource } = extractRender(mesh);+ const moved = createMeshData({ ...mesh, positions: mesh.positions.map(value => value * 2), attributes: mesh.attributes });+ const positions = gatherRenderPositions(moved, renderVertexSource);+ assert.deepEqual(positions, geometry.positions.map(value => value * 2));+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 6cfb69b3..2287343f 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -22,6 +22,7 @@ export default defineConfig({sculpt: 'src/sculpt.js',surface: 'src/surface.js','mesh-query': 'src/mesh-query.js',+ mesh: 'src/mesh.js',shrinkwrap: 'src/shrinkwrap.js','surface-attachment': 'src/surface-attachment.js',physics: 'src/physics.js',