Skip to content

3D engine that AI agents drive

Hold sharp-edge rims within a slope of their neighbours when displacing (#2224)

Nguyen Xuan An0662cda2bee5
diff --git a/changes/2224.md b/changes/2224.md
index f5937880..7c63bdcf 100644
--- a/changes/2224.md
+++ b/changes/2224.md
@@ -1 +1 @@
-- `displace` along the normal no longer folds a welded, sharp-edged mesh over at its edges: sharp vertices move to the meeting point of their sides, and a deep inward move near an edge is limited to a slope; smooth meshes are unchanged (#2224).
+- `displace` along the normal no longer folds a welded, sharp-edged mesh over at its edges: sharp vertices move to the meeting point of their sides, a deep inward move near an edge is limited to a slope, and a rim vertex stays within a slope of its neighbours on each side; smooth meshes are unchanged (#2224).
diff --git a/src/mesh-displace-directions.js b/src/mesh-displace-directions.js
index 97dbeb45..938d9dbe 100644
--- a/src/mesh-displace-directions.js
+++ b/src/mesh-displace-directions.js
@@ -6,7 +6,9 @@ import { faceNormals, vertexNormals } from './mesh-normals.js';
// planes (a miter): each flat side keeps its shape and moves by the depth its own neighbours move by.
// A miter slides the vertex along the sides by that depth, so an inward move of more than the spacing would push the
// vertex past its neighbours and fold the surface again. Inward depth near a sharp vertex is therefore limited to half
-// the shortest edge there, growing by INWARD_SLOPE per unit of distance along the surface, so it stays a slope.
+// the shortest edge there, growing by SIDE_SLOPE per unit of distance along the surface, so it stays a slope. Outward,
+// a sharp vertex may rise above its neighbours on a side by at most SIDE_SLOPE per unit of edge length, so no rim
+// overhangs the face below it.
/** Adjacent faces that bend apart by more than 60 degrees make their shared vertices sharp. */
const SHARP_BEND_COSINE = Math.cos(60 * Math.PI / 180);
@@ -16,8 +18,8 @@ const MAX_SIDES = 3;
/** A miter longer than this many times the largest side depth (a very acute edge) is shortened, so a spike cannot shoot off. */
const MAX_MITER_RATIO = 2;
const SINGULAR_DETERMINANT = 1e-9;
-/** How much deeper an inward move may get per unit of distance along the surface from a sharp vertex. Below 1 so the vertex stays ahead of its neighbour. */
-const INWARD_SLOPE = 0.4;
+/** How much deeper an inward move may get, and how far a sharp vertex may stand out from a neighbour, per unit of edge length. Below 1 so no strip tilts past 22 degrees from its side. */
+const SIDE_SLOPE = 0.4;
/**
* The move of every vertex as xyz triples, given the signed distance each one is asked to move (positive is outward).
@@ -27,13 +29,13 @@ const INWARD_SLOPE = 0.4;
export function displacementOffsets(mesh, distances) {
const normals = vertexNormals(mesh);
const sharpVertices = findSharpVertices(mesh);
- if (sharpVertices.size) limitInwardDistances(mesh, distances, sharpVertices);
+ const limits = sharpVertices.size ? limitInwardDistances(mesh, distances, sharpVertices) : null;
const offsets = new Float64Array(mesh.vertexCount * 3);
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
for (let axis = 0; axis < 3; axis++) offsets[vertex * 3 + axis] = distances[vertex] * normals[vertex * 3 + axis];
}
for (const [vertex, corner] of sharpVertices) {
- const miter = miterOffset(mesh, vertex, corner, distances, sharpVertices);
+ const miter = miterOffset(mesh, vertex, corner, distances, sharpVertices, limits[vertex]);
if (miter) offsets.set(miter, vertex * 3);
}
return offsets;
@@ -100,13 +102,16 @@ function edgeLength(mesh, first, second) {
return Math.hypot(...[0, 1, 2].map(axis => mesh.positions[first * 3 + axis] - mesh.positions[second * 3 + axis]));
}
-/** Clamp inward distances (negative) to half the shortest edge at a sharp vertex plus INWARD_SLOPE per unit of distance from it. */
+/**
+ * Clamp inward distances (negative) to half the shortest edge at a sharp vertex plus SIDE_SLOPE per unit of distance from
+ * it. Returns the limit of every vertex.
+ */
function limitInwardDistances(mesh, distances, sharpVertices) {
const limits = new Float64Array(mesh.vertexCount).fill(Infinity);
- const heap = new LimitHeap();
+ const queue = [];
for (const [vertex, corner] of sharpVertices) {
limits[vertex] = corner.shortestEdge / 2;
- heap.push(limits[vertex], vertex);
+ queue.push(vertex);
}
const neighbours = Array.from({ length: mesh.vertexCount }, () => []);
for (let edge = 0; edge < mesh.edgeCount; edge++) {
@@ -116,42 +121,30 @@ function limitInwardDistances(mesh, distances, sharpVertices) {
neighbours[first].push(second, length);
neighbours[second].push(first, length);
}
- while (heap.size) {
- const { limit, vertex } = heap.pop();
- if (limit > limits[vertex]) continue;
+ // Label-correcting relaxation: a vertex is queued again whenever a shorter route lowers its limit.
+ for (let head = 0; head < queue.length; head++) {
+ const vertex = queue[head];
const list = neighbours[vertex];
for (let index = 0; index < list.length; index += 2) {
- const reached = limit + INWARD_SLOPE * list[index + 1];
+ const reached = limits[vertex] + SIDE_SLOPE * list[index + 1];
if (reached >= limits[list[index]]) continue;
limits[list[index]] = reached;
- heap.push(reached, list[index]);
+ queue.push(list[index]);
}
}
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
if (distances[vertex] < -limits[vertex]) distances[vertex] = -limits[vertex];
}
+ return limits;
}
/**
- * The move that puts a sharp vertex on the offset plane of every side, each side moved by the mean distance of its
- * smooth vertices (the vertex's own distance when a side has none). Null when the sides are dependent.
+ * The move that puts a sharp vertex on the offset plane of every side. A side moves by the mean distance of the smooth
+ * vertices next to the vertex along its edges (the vertex's own distance when it has none), held within SIDE_SLOPE of
+ * each of them and above the inward limit. Null when the sides are dependent.
*/
-function miterOffset(mesh, vertex, { sides }, distances, sharpVertices) {
- const depths = sides.map(side => {
- let sum = 0;
- let count = 0;
- const seen = new Set();
- for (const face of side.faces) {
- for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
- const other = mesh.cornerVertices[corner];
- if (sharpVertices.has(other) || seen.has(other)) continue;
- seen.add(other);
- sum += distances[other];
- count++;
- }
- }
- return count ? sum / count : distances[vertex];
- });
+function miterOffset(mesh, vertex, { sides }, distances, sharpVertices, inwardLimit) {
+ const depths = sides.map(side => sideDepth(mesh, vertex, side.faces, distances, sharpVertices, inwardLimit));
const gram = sides.map(first => sides.map(second => first.normal[0] * second.normal[0] + first.normal[1] * second.normal[1] + first.normal[2] * second.normal[2]));
const weights = solve(gram, depths);
if (!weights) return null;
@@ -165,6 +158,27 @@ function miterOffset(mesh, vertex, { sides }, distances, sharpVertices) {
return offset.map(value => value * scale);
}
+function sideDepth(mesh, vertex, faces, distances, sharpVertices, inwardLimit) {
+ const seen = new Set();
+ let sum = 0;
+ let highest = Infinity;
+ for (const face of faces) {
+ const start = mesh.faceOffsets[face];
+ const end = mesh.faceOffsets[face + 1];
+ for (let corner = start; corner < end; corner++) {
+ if (mesh.cornerVertices[corner] !== vertex) continue;
+ for (const neighbour of [mesh.cornerVertices[corner === start ? end - 1 : corner - 1], mesh.cornerVertices[corner + 1 === end ? start : corner + 1]]) {
+ if (sharpVertices.has(neighbour) || seen.has(neighbour)) continue;
+ seen.add(neighbour);
+ sum += distances[neighbour];
+ highest = Math.min(highest, distances[neighbour] + SIDE_SLOPE * edgeLength(mesh, vertex, neighbour));
+ }
+ }
+ }
+ if (!seen.size) return distances[vertex];
+ return Math.max(Math.min(sum / seen.size, highest), -inwardLimit);
+}
+
/** Solve gram * weights = depths for 2 or 3 sides by Cramer's rule; null when the matrix is singular. */
function solve(gram, depths) {
const determinant = determinantOf(gram);
@@ -178,55 +192,3 @@ function determinantOf(matrix) {
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1][2] * matrix[2][0])
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1][1] * matrix[2][0]);
}
-
-/** Binary min-heap of (limit, vertex), ordered by limit and then vertex so the result never depends on insertion order. */
-class LimitHeap {
- constructor() {
- this.limits = [];
- this.vertices = [];
- }
-
- get size() {
- return this.limits.length;
- }
-
- before(first, second) {
- return this.limits[first] < this.limits[second] || (this.limits[first] === this.limits[second] && this.vertices[first] < this.vertices[second]);
- }
-
- swap(first, second) {
- [this.limits[first], this.limits[second]] = [this.limits[second], this.limits[first]];
- [this.vertices[first], this.vertices[second]] = [this.vertices[second], this.vertices[first]];
- }
-
- push(limit, vertex) {
- this.limits.push(limit);
- this.vertices.push(vertex);
- let index = this.limits.length - 1;
- while (index > 0 && this.before(index, (index - 1) >> 1)) {
- this.swap(index, (index - 1) >> 1);
- index = (index - 1) >> 1;
- }
- }
-
- pop() {
- const top = { limit: this.limits[0], vertex: this.vertices[0] };
- const lastLimit = this.limits.pop();
- const lastVertex = this.vertices.pop();
- if (this.limits.length) {
- this.limits[0] = lastLimit;
- this.vertices[0] = lastVertex;
- let index = 0;
- for (;;) {
- let smallest = index;
- for (const child of [index * 2 + 1, index * 2 + 2]) {
- if (child < this.limits.length && this.before(child, smallest)) smallest = child;
- }
- if (smallest === index) break;
- this.swap(index, smallest);
- index = smallest;
- }
- }
- return top;
- }
-}
diff --git a/tests/mesh-displace-sharp-edges.test.js b/tests/mesh-displace-sharp-edges.test.js
index 0c6dbeea..d5a3274d 100644
--- a/tests/mesh-displace-sharp-edges.test.js
+++ b/tests/mesh-displace-sharp-edges.test.js
@@ -6,7 +6,7 @@ import { applyMeshEdits, meshFromGeometry } from '../src/mesh.js';
import { evaluateField, meshFieldContext } from '../src/mesh-fields.js';
import { lintMesh } from '../src/mesh-lint.js';
import { vertexNormals } from '../src/mesh-normals.js';
-import { sharpSubdividedBox } from './support/sharp-subdivided-box.js';
+import { overhangingEdgeVertices, sharpSubdividedBox } from './support/sharp-subdivided-box.js';
const noiseDisplace = [{ op: 'displace', field: { noise: { scale: 3, seed: 7 } }, strength: 0.4 }];
@@ -22,6 +22,15 @@ test('a noise displace of a subdivided sharp box leaves no folded edge (#2224)',
assert.equal(problemCounts(displaced)['folded-face'], undefined);
});
+test('no rim vertex of a displaced sharp box stands out from the side face next to it (#2224)', () => {
+ for (const [spans, scale] of [[64, 3], [24, 6]]) {
+ const box = sharpSubdividedBox(spans);
+ const displaced = applyMeshEdits(box, [{ op: 'displace', field: { noise: { scale, seed: 7 } }, strength: 0.4 }]).mesh;
+ assert.equal(overhangingEdgeVertices(box, displaced), 0, `${spans} spans, noise scale ${scale}`);
+ assert.equal(problemCounts(displaced)['folded-face'], undefined);
+ }
+});
+
test('a coarse sharp box displaces without NaN and keeps every vertex near its start', () => {
const box = sharpSubdividedBox(2);
const displaced = applyMeshEdits(box, noiseDisplace).mesh;
diff --git a/tests/support/sharp-subdivided-box.js b/tests/support/sharp-subdivided-box.js
index 164b96b5..68937afd 100644
--- a/tests/support/sharp-subdivided-box.js
+++ b/tests/support/sharp-subdivided-box.js
@@ -28,3 +28,29 @@ export function sharpSubdividedBox(spans) {
}
return meshFromGeometry({ positions: new Float32Array(positions), indices: new Uint32Array(indices) });
}
+
+/** How far a rim vertex may stand out from a neighbour on one of its sides, per unit of edge length, before it counts as overhanging. */
+const OVERHANG_SLOPE = 0.5;
+
+/**
+ * Vertices on an edge of a sharp box that stand out from a neighbour on one of their sides by more than OVERHANG_SLOPE
+ * per unit of edge length: the rim juts past the side face next to it and the strip between them tilts toward its underside.
+ */
+export function overhangingEdgeVertices(box, displaced) {
+ const onEdge = vertex => [0, 1, 2].filter(axis => Math.abs(box.positions[vertex * 3 + axis]) > 0.5 - 1e-6).length >= 2;
+ const overhanging = new Set();
+ for (let edge = 0; edge < box.edgeCount; edge++) {
+ const pair = [box.edgeVertices[edge * 2], box.edgeVertices[edge * 2 + 1]];
+ for (const [rim, neighbour] of [pair, [pair[1], pair[0]]]) {
+ if (!onEdge(rim) || onEdge(neighbour)) continue;
+ for (let axis = 0; axis < 3; axis++) {
+ if (Math.abs(box.positions[rim * 3 + axis]) < 0.5 - 1e-6 || box.positions[rim * 3 + axis] !== box.positions[neighbour * 3 + axis]) continue;
+ const outward = Math.sign(box.positions[rim * 3 + axis]);
+ const standOut = ((displaced.positions[rim * 3 + axis] - box.positions[rim * 3 + axis]) - (displaced.positions[neighbour * 3 + axis] - box.positions[neighbour * 3 + axis])) * outward;
+ const length = Math.hypot(...[0, 1, 2].map(other => box.positions[rim * 3 + other] - box.positions[neighbour * 3 + other]));
+ if (standOut > OVERHANG_SLOPE * length) overhanging.add(rim);
+ }
+ }
+ }
+ return overhanging.size;
+}