Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add weighted_normal and smooth_by_angle modifiers (Part of #42)

Nguyen Xuan An379a8275b544
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 84b6de65..47453488 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,7 @@
## Unreleased
+- Add the `weighted_normal` and `smooth_by_angle` modifiers as edits and stack nodes (part of issue #42). `smooth_by_angle` marks edges over an angle sharp and the rest smooth, overriding the geometry `smoothAngle`; `weighted_normal` stores an area-weighted normal per corner that the render extraction uses as is. The edge attribute `smooth` is new.
- Add the `lattice`, `curve`, `hook` and `wave` modifiers as edits and stack nodes (part of issue #42). `lattice` moves up to 64 control points of a grid over the mesh bounds, `curve` bends a mesh along a Catmull-Rom path, `hook` pulls the vertices near a point and `wave` is a travelling ripple that matches Blender 5.2 at the same frame on two cases. Lists are bounded and the errors name the limit.
- Add the `screw`, `wireframe` and `skin` modifiers as edits and stack nodes (part of issue #42). `screw` revolves the edges of a mesh about an axis with steps, iterations and lift, and `wireframe` leaves a rim on every face with thickness, offset and even offset; both match Blender 5.2 on counts, area and positions (`wireframe` on three cases, `screw` on two). `skin` is a simple version, a closed square tube per edge with a radius per vertex and no branch solver. Sizes are bounded and the errors say what to lower. Details are in `scene_capabilities` `meshModifiers`, and the modifier entry of the tool schemas is now an open object so it no longer grows with each modifier.
- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.
diff --git a/docs/mesh.md b/docs/mesh.md
index e5400661..6a6df092 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -197,7 +197,7 @@ These three (and `bevel`, below) work as edits and as stack nodes:
### Modifier stack
-A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook` and `wave` nodes (up to 16) evaluated after the
+A recipe mesh may carry `stack`, a list of `mirror`, `array`, `solidify`, `bevel`, `subdivide`, `uv_unwrap`, `set_position`, `displace`, `decimate`, `remesh`, `weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `weighted_normal` and `smooth_by_angle` nodes (up to 16) evaluated after the
edits without changing them, as Blender's modifier stack. Every prefix (the edit result, then each node) is cached
by its recipe text in a least-recently-used cache bounded at 64 entries and 64 MiB, so changing a late node reuses
the earlier work. Results list one entry per node with `cached: true` when reused. `meshCacheStats()` reports hits
@@ -208,7 +208,7 @@ as Blender's Apply modifier, which leaves the result unchanged.
### Whole-mesh modifiers
-`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook` and `wave` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
+`weld`, `triangulate`, `edge_split`, `smooth`, `simple_deform`, `cast`, `screw`, `wireframe`, `skin`, `lattice`, `curve`, `hook`, `wave`, `weighted_normal` and `smooth_by_angle` take no selection and no name, and work as edits or stack nodes. Their fields and defaults are plain data in `MESH_MODIFIER_NOTES` (`src/agent-scene-capabilities.js`), which `scene_capabilities` returns as `meshModifiers`; the code is in `src/mesh-modifiers.js` and `src/mesh-restructure.js`.
| op | fields | does |
| --- | --- | --- |
@@ -225,8 +225,10 @@ as Blender's Apply modifier, which leaves the result unchanged.
| `curve` | `path` (2 to 64 points), `axis` (x) | Bends the mesh along a Catmull-Rom path; the coordinate along the axis is the distance from the path start. |
| `hook` | `center`, `radius` (1), `translation`, `strength` (1), `falloff` (smooth) | Pulls the vertices within the radius by the translation, weighted by the falloff. |
| `wave` | `height` (0.5), `width` (1.5), `narrowness` (1.5), `speed` (0.25), `time` (0), `timeOffset`, `start`, `cyclic` (true), `axes` (xy), `normal` | A travelling gaussian ripple along z, equal to Blender Wave at the same frame. |
+| `weighted_normal` | `angle` (30), `weight` (50, 1 to 100) | Stores one shading normal per corner: faces around a vertex share it unless the edge is sharp or bends more than the angle, each face counting by its area to the power weight / 50. Put it last in the stack. |
+| `smooth_by_angle` | `angle` (30), `ignoreSharp` (false) | Marks edges bending more than the angle sharp and the others smooth, over the geometry `smoothAngle`; sharp edges made by hand, and the 12 of a box, stay sharp unless `ignoreSharp` is set. |
-`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. Not yet: `shrinkwrap`, `weighted_normal`, `smooth_by_angle` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.
+`triangulate` and `edge_split` check their output size before building it, against the same vertex and face limits as the other edits. Each op has cases in `tests/fixtures/blender/cases.json` and matches Blender 5.2 with no listed difference. `screw` and `wireframe` have cases in the same fixtures (the volume of the open screw strips differs by winding, listed in `differences.json`); `wave` matches Blender on two cases; `skin`, `lattice`, `curve` and `hook` are not compared with Blender, because each needs a second object there. The two normal modifiers are tested by their own properties, because the Blender comparison does not measure normals. Not yet: `shrinkwrap` and `scatter_on_surface` as stack nodes (`instances` already scatters), and cast shapes other than the sphere.
### Field expressions
diff --git a/docs/parity.md b/docs/parity.md
index 2d73357a..40600acd 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -3,7 +3,7 @@
This ledger compares 67js with each feature in the [Blender 5.2 manual](https://docs.blender.org/manual/en/latest/).
It is the record for the goal in issue #23. Use `npm run parity` to print the coverage of each section.
-Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 11 done, 25 partial, 24 missing and 1 out of scope, 8 of the done rows compared with Blender, 18% of the in-scope rows done.
+Modifier coverage (rows under `Modeling > Modifiers`, from `npm run parity`): 12 done, 25 partial, 23 missing and 1 out of scope, 8 of the done rows compared with Blender, 20% of the in-scope rows done.
## How to read it
@@ -108,8 +108,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Modeling > Modifiers > Deform > Warp Modifier | missing | No equivalent. | | |
| Modeling > Modifiers > Deform > Wave Modifier | partial | `wave` edit and stack node: height, width, narrowness, speed, frame `time`, offset, start, cyclic, x and y axes and along the normal. Positions match Blender at the same frame on 2 cases. No falloff, lifetime or damping, no texture and no vertex groups. | [mesh-deform-modifiers](../tests/mesh-deform-modifiers.test.js), [Blender results](../tests/fixtures/blender/golden.json) | #42 |
| Modeling > Modifiers > Normals > Normal Edit Modifier | missing | No equivalent. | | |
-| Modeling > Modifiers > Normals > Weighted Normal Modifier | missing | No equivalent. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
-| Modeling > Modifiers > Normals > Smooth By Angle Modifier | partial | `smoothAngle` is a geometry setting. It is not a stack node. Not in the first slice of #42, which took the modifiers agents use most. | | #42 |
+| Modeling > Modifiers > Normals > Weighted Normal Modifier | partial | `weighted_normal` edit and stack node: face area weighting with a `weight` from 1 to 100 (power weight / 50) inside smooth groups bounded by sharp edges and an `angle`, stored as one normal per corner that the render uses. No corner angle or face influence modes, no keep-sharp switch, no vertex groups and no Blender comparison of normals. | [mesh-normal-modifiers](../tests/mesh-normal-modifiers.test.js) | #42 |
+| Modeling > Modifiers > Normals > Smooth By Angle Modifier | done | `smooth_by_angle` edit and stack node with `angle` and `ignoreSharp`: edges bending more than the angle become sharp, the rest smooth, over the geometry `smoothAngle`. Hand-marked sharp edges stay unless ignored, as in Blender. No vertex groups and no Blender comparison of normals. | [mesh-normal-modifiers](../tests/mesh-normal-modifiers.test.js) | |
| Modeling > Modifiers > Physics > Cloth Modifier | partial | Recipe `cloth`: a position-based sheet solver with pinned edges, steady wind, gravity and fixed ball or box colliders, recorded at 60 frames a second so a seek repeats exactly. No self collision, no per-vertex stiffness or pin weights. A hanging sheet matches a Blender bake to 0.08 percent of its height; a sheet dropped on a ball does not match (mean vertex distance 63 percent of the sheet size at 2 s, 58 percent at 8 s). It is not stretch (longest edge 1.02 against 1.05, area 1.003 against 1.013); Blender's bake had not settled even at 8 s. See docs/physics.md. | [cloth](../tests/cloth.test.js), [cloth-blender](../tests/cloth-blender.test.js) | #62 |
| Modeling > Modifiers > Physics > Collision Modifier | partial | Rapier colliders fitted to recipe geometry as box, ball, capsule, convex hull or trimesh, so a body rests on an authored mesh. | [agent-physics](../tests/agent-physics.test.js) | #61 |
| Modeling > Modifiers > Physics > Dynamic Paint Modifier | missing | No equivalent. | | |
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index b39746c8..777e5640 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -137,6 +137,8 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
curve: 'bends the mesh along path, 2 to 64 points [x,y,z] through a Catmull-Rom spline. The coordinate along axis (x) is the distance from the path start, the other two become offsets in a twist-free frame; past the ends the mesh continues straight. Model the mesh along the axis starting at 0.',
hook: 'pulls the vertices within radius (1) of center [0,0,0] by translation [0,0,0] times strength 0 to 1 (1); falloff smooth (default), linear or constant.',
wave: 'a gaussian ripple of height 0.5 along z (normal true: along the vertex normal) that travels from start [0,0] over axes xy (default), x or y; width 1.5, narrowness 0 to 50 (1.5), speed 0.25 per frame, time 0 (a frame number), timeOffset 0, cyclic true repeats it. Matches Blender Wave at the same frame.',
+ weighted_normal: 'shading normals per corner: faces around a vertex share one normal unless the edge is sharp or bends more than angle (30) degrees, each face counting by its area to the power weight / 50 (weight 1 to 100, 50). Put it last in the stack: a later edit that changes the faces leaves the values stale.',
+ smooth_by_angle: 'marks edges bending more than angle (30, 0 to 180) degrees sharp and every other edge smooth, whatever the geometry smoothAngle says; ignoreSharp true also drops sharp marks made by hand (default false keeps them).',
});
// Organic shaping edits. Details stay here so the tool schemas stay small.
diff --git a/src/mesh-modifiers.js b/src/mesh-modifiers.js
index 3a7c7c7f..78e348d8 100644
--- a/src/mesh-modifiers.js
+++ b/src/mesh-modifiers.js
@@ -3,6 +3,7 @@ import { mergeByDistance } from './mesh-ops.js';
import { triangulateFaces, splitSharpEdges } from './mesh-restructure.js';
import { MODIFIER_OPERATIONS } from './mesh-operations.js';
import { normalizeGeneratorEdit, GENERATOR_RUNNERS } from './mesh-generator-modifiers.js';
+import { normalizeNormalEdit, NORMAL_RUNNERS } from './mesh-normal-modifiers.js';
import { isDeformModifier, normalizeDeformEdit, runDeformEdit } from './mesh-deform-modifiers.js';
// The whole-mesh modifiers as recipe operations: validation of their fields and running them on MeshData. Smooth, cast and
@@ -50,6 +51,10 @@ export function normalizeModifierEdit(edit, normalized, index, { finiteNumber, c
normalizeGeneratorEdit(edit, normalized, index, { finiteNumber, integerInRange, checkedField });
return;
}
+ if (Object.hasOwn(NORMAL_RUNNERS, edit.op)) {
+ normalizeNormalEdit(edit, normalized, index, { finiteNumber });
+ return;
+ }
if (isDeformModifier(edit.op)) {
normalizeDeformEdit(edit, normalized, index, { finiteNumber, integerInRange });
return;
@@ -181,6 +186,7 @@ function simpleDeformPositions(mesh, { mode, axis, angle, factor }) {
/** Run a modifier edit. Returns { mesh, result } where result holds the counts to report. */
export function runModifierEdit(mesh, edit, { maxVertices, maxFaces }) {
if (Object.hasOwn(GENERATOR_RUNNERS, edit.op)) return GENERATOR_RUNNERS[edit.op](mesh, edit, { maxVertices, maxFaces });
+ if (Object.hasOwn(NORMAL_RUNNERS, edit.op)) return { mesh: NORMAL_RUNNERS[edit.op](mesh, edit), result: {} };
if (isDeformModifier(edit.op)) return runDeformEdit(mesh, edit);
switch (edit.op) {
case 'weld': {
diff --git a/src/mesh-normal-modifiers.js b/src/mesh-normal-modifiers.js
new file mode 100644
index 00000000..bbf8f91d
--- /dev/null
+++ b/src/mesh-normal-modifiers.js
@@ -0,0 +1,90 @@
+import { createMeshData } from './mesh-data.js';
+import { faceNormals, cornerNormals } from './mesh-normals.js';
+import { edgeCornerTable, cornerFaces } from './mesh-topology.js';
+
+// Modifiers that decide how a mesh is shaded without moving it. smooth_by_angle writes the edge attributes `sharp` and
+// `smooth` that corner normals read, weighted_normal writes one normal per corner that the render extraction uses as is.
+
+export const DEFAULT_NORMAL_ANGLE = 30;
+export const MAXIMUM_NORMAL_WEIGHT = 100;
+const WEIGHT_REFERENCE = 50;
+const ANGLE_TOLERANCE = 1e-6;
+
+function withAttributes(mesh, { edge = {}, corner = {} }) {
+ return createMeshData({
+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,
+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges,
+ attributes: {
+ ...mesh.attributes,
+ edge: { ...mesh.attributes.edge, ...edge },
+ corner: { ...mesh.attributes.corner, ...corner },
+ },
+ });
+}
+
+/**
+ * Blender's Smooth by Angle: an edge shared by two faces whose normals differ by more than `angle` degrees is marked
+ * sharp, and every other such edge is marked smooth, which overrides the angle the geometry would otherwise use. Edges
+ * already marked sharp stay sharp unless `ignoreSharp` is set. Edges on a boundary or shared by three faces are not touched.
+ */
+export function smoothByAngle(mesh, { angle, ignoreSharp }) {
+ const normals = faceNormals(mesh).normals;
+ const table = edgeCornerTable(mesh);
+ const faces = cornerFaces(mesh);
+ const limit = Math.cos(angle * Math.PI / 180) - ANGLE_TOLERANCE;
+ const sharp = new Uint8Array(mesh.edgeCount);
+ const smooth = new Uint8Array(mesh.edgeCount);
+ const previousSharp = mesh.attributes.edge.sharp?.data;
+ for (let edge = 0; edge < mesh.edgeCount; edge++) {
+ const wasSharp = Boolean(previousSharp?.[edge]);
+ if (table.edgeOffsets[edge + 1] - table.edgeOffsets[edge] !== 2) {
+ sharp[edge] = wasSharp ? 1 : 0;
+ continue;
+ }
+ const first = faces[table.edgeCorners[table.edgeOffsets[edge]]] * 3;
+ const second = faces[table.edgeCorners[table.edgeOffsets[edge] + 1]] * 3;
+ const alignment = normals[first] * normals[second] + normals[first + 1] * normals[second + 1] + normals[first + 2] * normals[second + 2];
+ const bends = alignment < limit;
+ sharp[edge] = bends || (wasSharp && !ignoreSharp) ? 1 : 0;
+ smooth[edge] = sharp[edge] ? 0 : 1;
+ }
+ return withAttributes(mesh, { edge: { sharp: { data: sharp, size: 1 }, smooth: { data: smooth, size: 1 } } });
+}
+
+/**
+ * Blender's Weighted Normal in face area mode: the corners around a vertex that stay smoothed together (not across a sharp
+ * edge or one bending more than `angle` degrees) share one normal, the sum of their face normals each weighted by the face
+ * area to the power weight / 50. The result is stored as the corner attribute `normal`.
+ */
+export function weightedNormals(mesh, { angle, weight }) {
+ const { groupOfCorner, groupCount } = cornerNormals(mesh, { sharpAngle: angle * Math.PI / 180 });
+ const { normals, areas } = faceNormals(mesh);
+ const faces = cornerFaces(mesh);
+ const exponent = weight / WEIGHT_REFERENCE;
+ const sums = new Float64Array(groupCount * 3);
+ for (let corner = 0; corner < mesh.cornerCount; corner++) {
+ const face = faces[corner];
+ const scale = Math.pow(areas[face], exponent);
+ for (let axis = 0; axis < 3; axis++) sums[groupOfCorner[corner] * 3 + axis] += normals[face * 3 + axis] * scale;
+ }
+ const data = new Float32Array(mesh.cornerCount * 3);
+ for (let corner = 0; corner < mesh.cornerCount; corner++) {
+ const group = groupOfCorner[corner] * 3;
+ const length = Math.hypot(sums[group], sums[group + 1], sums[group + 2]);
+ const face = faces[corner] * 3;
+ for (let axis = 0; axis < 3; axis++) data[corner * 3 + axis] = length > 0 ? sums[group + axis] / length : normals[face + axis];
+ }
+ return withAttributes(mesh, { corner: { normal: { data, size: 3 } } });
+}
+
+export function normalizeNormalEdit(edit, normalized, index, { finiteNumber }) {
+ normalized.angle = edit.angle === undefined ? DEFAULT_NORMAL_ANGLE : finiteNumber(edit.angle, index, 'angle', { minimum: 0, maximum: 180 });
+ if (edit.op === 'smooth_by_angle') {
+ normalized.ignoreSharp = edit.ignoreSharp ?? false;
+ if (typeof normalized.ignoreSharp !== 'boolean') throw new TypeError(`Mesh edit ${index} (ignoreSharp must be a boolean)`);
+ return;
+ }
+ normalized.weight = edit.weight === undefined ? WEIGHT_REFERENCE : finiteNumber(edit.weight, index, 'weight', { minimum: 1, maximum: MAXIMUM_NORMAL_WEIGHT });
+}
+
+export const NORMAL_RUNNERS = Object.freeze({ smooth_by_angle: smoothByAngle, weighted_normal: weightedNormals });
diff --git a/src/mesh-normals.js b/src/mesh-normals.js
index c3d27241..5b0a3aaa 100644
--- a/src/mesh-normals.js
+++ b/src/mesh-normals.js
@@ -59,6 +59,7 @@ export function cornerNormals(mesh, { sharpAngle = Infinity } = {}) {
const facesOfCorners = cornerFaces(mesh);
const table = edgeCornerTable(mesh);
const sharp = mesh.attributes.edge.sharp?.data;
+ const smooth = mesh.attributes.edge.smooth?.data;
const cosineLimit = Number.isFinite(sharpAngle) ? Math.cos(sharpAngle) : -2;
const groups = new UnionFind(mesh.cornerCount);
for (let edge = 0; edge < mesh.edgeCount; edge++) {
@@ -73,7 +74,7 @@ export function cornerNormals(mesh, { sharpAngle = Infinity } = {}) {
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;
+ if (cosine < cosineLimit && !(smooth && smooth[edge])) 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);
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index 12c7abab..e820cd41 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -19,6 +19,8 @@ export const MODIFIER_OPERATIONS = Object.freeze({
curve: { fields: ['path', 'axis'], tags: [] },
hook: { fields: ['center', 'radius', 'translation', 'strength', 'falloff'], tags: [] },
wave: { fields: ['height', 'width', 'narrowness', 'speed', 'time', 'timeOffset', 'start', 'cyclic', 'axes', 'normal'], tags: [] },
+ weighted_normal: { fields: ['angle', 'weight'], tags: [] },
+ smooth_by_angle: { fields: ['angle', 'ignoreSharp'], tags: [] },
});
export const MESH_EDIT_OPERATIONS = Object.freeze({
diff --git a/src/mesh-render.js b/src/mesh-render.js
index 3db570c8..9168e657 100644
--- a/src/mesh-render.js
+++ b/src/mesh-render.js
@@ -161,7 +161,8 @@ 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);
+ const normalAttribute = mesh.attributes.corner.normal?.size === 3 ? mesh.attributes.corner.normal : undefined;
+ const splitAttributes = [uvAttribute, colorAttribute, normalAttribute].filter(Boolean);
let cornerRenderVertex = groupOfCorner;
let renderVertexCorner = groupFirstCorner;
let renderVertexCount = groupCount;
@@ -207,9 +208,11 @@ export function extractRender(mesh, { sharpAngle = Infinity } = {}) {
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];
+ const normalSource = normalAttribute ? normalAttribute.data : groupNormals;
+ const normalIndex = normalAttribute ? corner : group;
+ normals[renderVertex * 3] = normalSource[normalIndex * 3];
+ normals[renderVertex * 3 + 1] = normalSource[normalIndex * 3 + 1];
+ normals[renderVertex * 3 + 2] = normalSource[normalIndex * 3 + 2];
if (uvs) {
uvs[renderVertex * 2] = uvAttribute.data[corner * 2];
uvs[renderVertex * 2 + 1] = uvAttribute.data[corner * 2 + 1];
diff --git a/tests/mesh-normal-modifiers.test.js b/tests/mesh-normal-modifiers.test.js
new file mode 100644
index 00000000..0d156bf9
--- /dev/null
+++ b/tests/mesh-normal-modifiers.test.js
@@ -0,0 +1,78 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box } from '../src/geometry.js';
+import { meshFromGeometry, applyMeshEdits, evaluateMeshStack, normalizeMeshEdits } from '../src/mesh.js';
+import { createMeshData } from '../src/mesh-data.js';
+import { cornerNormals } from '../src/mesh-normals.js';
+import { extractRender } from '../src/mesh-render.js';
+
+const cube = () => meshFromGeometry(box(0, 1));
+const run = (mesh, edit) => applyMeshEdits(mesh, [edit]).mesh;
+const degrees = value => value * Math.PI / 180;
+
+// A big floor quad and a small wall quad bent 90 degrees up along their shared edge.
+function floorAndWall() {
+ return createMeshData({
+ positions: Float32Array.from([0, 0, 0, 4, 0, 0, 4, 4, 0, 0, 4, 0, 4, 0, 1, 4, 4, 1]),
+ faceOffsets: Uint32Array.from([0, 4, 8]),
+ cornerVertices: Uint32Array.from([0, 1, 2, 3, 1, 4, 5, 2]),
+ });
+}
+
+test('smooth_by_angle marks bends over the angle sharp and the rest smooth, over the angle the render would use', () => {
+ // The box primitive already marks its 12 edges sharp, so the first run has to ignore those marks.
+ const rounded = run(cube(), { op: 'smooth_by_angle', angle: 100, ignoreSharp: true });
+ assert.equal(rounded.attributes.edge.sharp.data.reduce((total, flag) => total + flag, 0), 0);
+ assert.equal(rounded.attributes.edge.smooth.data.reduce((total, flag) => total + flag, 0), 12);
+ assert.equal(cornerNormals(rounded, { sharpAngle: degrees(30) }).groupCount, 8, 'one normal per vertex even though 30 degrees would split every edge');
+ const hard = run(cube(), { op: 'smooth_by_angle', angle: 80 });
+ assert.equal(hard.attributes.edge.sharp.data.reduce((total, flag) => total + flag, 0), 12);
+ assert.equal(cornerNormals(hard, { sharpAngle: degrees(120) }).groupCount, 24);
+});
+
+test('smooth_by_angle keeps hand-marked sharp edges unless told to ignore them', () => {
+ const marked = run(cube(), { op: 'smooth_by_angle', angle: 100, ignoreSharp: true });
+ const sharpData = Uint8Array.from(marked.attributes.edge.sharp.data);
+ sharpData[0] = 1;
+ const withMark = createMeshData({
+ positions: marked.positions, faceOffsets: marked.faceOffsets, cornerVertices: marked.cornerVertices,
+ edgeVertices: marked.edgeVertices, cornerEdges: marked.cornerEdges,
+ attributes: { ...marked.attributes, edge: { ...marked.attributes.edge, sharp: { data: sharpData, size: 1 } } },
+ });
+ assert.equal(run(withMark, { op: 'smooth_by_angle', angle: 100 }).attributes.edge.sharp.data[0], 1);
+ assert.equal(run(withMark, { op: 'smooth_by_angle', angle: 100, ignoreSharp: true }).attributes.edge.sharp.data[0], 0);
+});
+
+test('weighted_normal tilts a shared vertex toward the larger face and the render uses the stored normals', () => {
+ const plain = cornerNormals(floorAndWall(), { sharpAngle: degrees(120) });
+ const weighted = run(floorAndWall(), { op: 'weighted_normal', angle: 120 });
+ const normal = weighted.attributes.corner.normal;
+ assert.equal(normal.size, 3);
+ assert.equal(normal.data.length, weighted.cornerCount * 3);
+ const sharedCorner = 1;
+ const plainTilt = plain.groupNormals[plain.groupOfCorner[sharedCorner] * 3 + 0];
+ const weightedTilt = normal.data[sharedCorner * 3];
+ assert.ok(Math.abs(weightedTilt) < Math.abs(plainTilt), `the wall pulls less when the floor is four times larger (${weightedTilt} against ${plainTilt})`);
+ assert.ok(Math.abs(Math.hypot(...normal.data.subarray(sharedCorner * 3, sharedCorner * 3 + 3)) - 1) < 1e-5);
+ const { geometry } = extractRender(weighted);
+ for (let index = 0; index < geometry.normals.length; index += 3) {
+ assert.ok(Math.abs(Math.hypot(geometry.normals[index], geometry.normals[index + 1], geometry.normals[index + 2]) - 1) < 1e-5);
+ }
+ assert.ok(geometry.normals.some((value, index) => index % 3 === 2 && value > 0.9), 'the floor keeps its upward normal');
+});
+
+test('a higher weight leans further toward the large face and sharp bends stay split', () => {
+ const lean = weight => Math.abs(run(floorAndWall(), { op: 'weighted_normal', angle: 120, weight }).attributes.corner.normal.data[3]);
+ assert.ok(lean(100) < lean(50) && lean(50) < lean(1));
+ const split = run(floorAndWall(), { op: 'weighted_normal', angle: 30 });
+ assert.equal(split.attributes.corner.normal.data[2], 1, 'the floor corner keeps the floor normal when the 90 degree edge is sharp');
+});
+
+test('the normal modifiers name their limits and run as stack nodes', () => {
+ assert.throws(() => normalizeMeshEdits([{ op: 'weighted_normal', weight: 0 }]), /weight must be a number from 1 to 100/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'weighted_normal', angle: 181 }]), /angle must be a number from 0 to 180/);
+ assert.throws(() => normalizeMeshEdits([{ op: 'smooth_by_angle', ignoreSharp: 1 }]), /ignoreSharp must be a boolean/);
+ const outcome = evaluateMeshStack(cube(), [{ op: 'smooth_by_angle', angle: 100 }, { op: 'weighted_normal' }]);
+ assert.equal(outcome.results.length, 2);
+ assert.ok(outcome.mesh.attributes.corner.normal);
+});