Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Mesh: vertex colors and vertex groups, read by displace and cloth pinning (issue #613)

Nguyen Xuan An05aba58c83b5
diff --git a/changes/613.md b/changes/613.md
new file mode 100644
index 00000000..4d7cb8af
--- /dev/null
+++ b/changes/613.md
@@ -0,0 +1 @@
+- `vertex_group` and `vertex_color` mesh edits write named weights and vertex colors; `displace` and cloth `pinGroup` read a group, and colors export as `COLOR_0` (#613)
diff --git a/changes/613.size.md b/changes/613.size.md
new file mode 100644
index 00000000..6213524a
--- /dev/null
+++ b/changes/613.size.md
@@ -0,0 +1,6 @@
+- tool-total: the two new mesh_edit ops (vertex_group, vertex_color) and the group and pinGroup fields add 1496 bytes of schema; the field details sit in scene_capabilities meshAttributes (#613)
+- tool:mesh_edit: vertex_group and vertex_color are the two ops that let an agent weight and paint a mesh, 1411 bytes; the select and field types are shortened to a one-line description
+- result:scene_capabilities: meshAttributes explains both ops, group and pinGroup in about 1 KB, so the tool schemas do not carry that text
+- scene:agent-scene: capability notes and the cloth pinGroup check in the core bundle, 406 bytes gzip (#613)
+- scene:agent-scene+lazy: the vertex attribute edits, group-aware displace and per-vertex group arrays in the mesh engine, 2121 bytes gzip
+- goal:agent-scene: weights and vertex colors are an agent-facing capability that Blender users expect; the code itself loads only with meshes
diff --git a/docs/mesh.md b/docs/mesh.md
index 26d2cab5..30136ea0 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -269,7 +269,16 @@ Uses:
expressions evaluated on the input positions, so vertex order never matters. It moves the vertices of the selected faces.
- `displace` (`select`, `field`, `strength`, `midlevel`, `direction`) is Blender's Displace modifier with a field as
the texture: each vertex moves by `(field - midlevel) * strength` along `normal` (default), `x`, `y` or `z`.
+ `displace` also takes `group`, the name of a vertex group: each move is scaled by the vertex's weight.
- Both are also stack nodes, so a late change reuses the cached earlier nodes.
+- `vertex_group` (`name`, `select`, and one of `weight`, `field` or `gradient`) writes the weights, 0 to 1, of a named group for the
+ vertices of the selected faces; the others keep theirs (0 in a new group). `gradient` is `{ "axis": "y", "range": [0, 1], "weights": [0, 1] }`,
+ a straight blend between the weights at the two ends of the range along the axis. Up to 32 groups. `displace` reads one with
+ `group`, and a cloth sheet holds the vertices of weight 0.5 or more with `pinGroup` (see [physics.md](physics.md)). Groups are
+ point attributes: run `vertex_group` after the shape edits, because a stack node that rebuilds the mesh (`mirror`, `array`) drops them.
+- `vertex_color` (`select`, and one of `color`, `field` or `gradient`) sets the corner colors of the selected faces. `color` is
+ `[r, g, b]` from 0 to 1, `field` a vector expression of the vertex, and `gradient` is `{ "axis": "y", "range": [0, 1], "colors": [[0, 0, 1], [1, 0, 0]] }`.
+ The renderer multiplies the material color by it and a GLB export writes it as `COLOR_0`. Faces not selected stay white until painted.
- `instances` on a recipe node repeats its geometry at points; see [agent-scene.md](agent-scene.md#instances-on-points).
Blender comparison: `tests/blender-golden.test.js` runs `set_position` against a Geometry Nodes Set Position node
diff --git a/docs/physics.md b/docs/physics.md
index fcb2ce96..2a72bb45 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -424,6 +424,7 @@ A recipe `cloth` section records deformable sheets with a position-based solver
- Moving colliders and pins follow any node or bone, including a walking character, and are read at every solver substep, so a seek still equals playing to that time:
- `{ "attach": "leftHand", "shape": "ball", "radius": 0.08, "offset": [0, 0, 0] }` is a ball on a node. `{ "attach": "upperArm", "shape": "capsule", "to": "lowerArm", "radius": 0.05 }` runs a capsule from one node (plus `offset`) to another (plus `toOffset`). Radius 0.001 to 10 m.
- `{ "armature": "rig", "radiusFraction": 0.2, "exclude": ["head"] }` adds one capsule per bone, head to tail, the radius a fraction (0.02 to 0.5, default 0.2) of the bone length as the ragdoll fits it. A bone with no length is skipped.
+ - A sheet on a mesh geometry can hold chosen vertices with `pinGroup: "hem"`, the name of a vertex group made by a `vertex_group` mesh edit; vertices of weight 0.5 or more are pinned, on their own or together with `pin`. An unknown name fails and lists the groups the mesh has.
- A sheet's `pinTo: { "node": "chest", "weight": 1 }` makes the pinned edges (`pin`) ride that node, keeping their rest offset in its space. Weight 1 holds them on the node; 0.01 to under 1 pulls them toward it by that fraction on every pass, so they sag and lag.
- Up to 64 moving balls and capsules, counting every bone. The node poses come from the recipe's motion tracks and IK; a physics ragdoll or body is not followed. Points are pushed out of the capsules, not whole triangles, so a coarse sheet can still cut a corner of a thin limb: use a finer grid than the limb is wide. A cape on the reference walker (24 by 24 grid, 5 s, about 2.5 s to bake on the dev machine) stays outside every limb capsule in `tests/cloth-moving.test.js`.
- The bake runs when the scene is created: 60 frames a second, 4 substeps and 8 constraint passes a frame, constraints solved in a fixed order with no random numbers. `sample(time)` blends the two nearest frames, so the same time always gives the same positions and a seek backwards repeats them. Time zero is the authored sheet and a time past `duration` holds the last frame.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index aaea8696..d58b73d2 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -313,6 +313,8 @@ function primitiveGeometries(identified) {
const selectRule = z.record(z.string(), z.unknown()).describe('Face rule: {"all":true}, {"tag":"top"}, {"normal":[0,1,0],"maxAngle":10}, {"inside":{"min":[x,y,z],"max":[x,y,z]}} (centroids), {"faces":[i]}, {"and"|"or":[rules]}, {"not":rule}, {"grow":rule,"steps":1}, {"boundary":rule}, {"field":expr}. Tags: top, bottom, side, left, right, front, back, <name>.cap|side|rim.');
const editName = z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/).optional().describe('Tag prefix. Defaults to <op>-<index>.');
const edgeRule = z.record(z.string(), z.unknown()).describe('Edge rule: {"all":true}, {"angle":30}, {"along":[x,y,z]}, {"between":[faceRule,faceRule]}, {"boundaryOf":faceRule} or {"open":true} for boundary edges (also {"open":{"inside":{"min":[x,y,z],"max":[x,y,z]}}}).');
+const shortSelect = z.record(z.string(), z.unknown()).describe('Face rule, as in set_position.');
+const shortField = z.union([finite, z.record(z.string(), z.unknown())]);
const meshEdit = z.discriminatedUnion('op', [
z.strictObject({ op: z.literal('extrude_face_region'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each connected region\'s average normal (negative pushes in).'), direction: vector3.optional().describe('Move along this direction instead of the normal.'), alongNormals: z.boolean().optional().describe('Move each vertex along its own normal instead, keeping the region joined: use for rings and curved bands.') }),
z.strictObject({ op: z.literal('extrude_individual'), select: selectRule.optional(), name: editName, offset: finite.describe('Distance along each face\'s own normal.'), direction: vector3.optional() }),
@@ -363,6 +365,8 @@ const meshEdit = z.discriminatedUnion('op', [
type: z.enum(['inflate', 'displace', 'smooth']), center: vector3, radius: finite, strength: finite, direction: vector3.optional(),
})).min(1).max(32),
}).describe('Brush strokes on the vertices of the selected faces, in order. Fields and units in scene_capabilities meshSculpt.'),
+ z.strictObject({ op: z.literal('vertex_group'), name: z.string().max(48), select: shortSelect.optional(), weight: unit.optional(), field: shortField.optional(), gradient: z.record(z.string(), z.unknown()).optional() }).describe('Vertex group weights 0-1: weight, field or gradient. See meshAttributes.'),
+ z.strictObject({ op: z.literal('vertex_color'), select: shortSelect.optional(), color: vector3.optional(), field: shortField.optional(), gradient: z.record(z.string(), z.unknown()).optional() }).describe('Vertex colors: color, vector field or gradient. See meshAttributes.'),
z.strictObject({
op: z.literal('shrinkwrap'), select: selectRule.optional(),
target: z.record(z.string(), z.unknown()).describe('Primitive to wrap onto, a record like a boolean cutter ({"type":"sphere"}), placed by translation, rotation and scale.'),
@@ -381,6 +385,7 @@ const stackNodes = [
field: fieldExpression.describe('Number expression used as the texture.'),
strength: finite.optional().describe('Defaults to 1.'), midlevel: finite.optional().describe('Field value that does not move. Defaults to 0.5, the middle of noise.'),
direction: z.enum(['normal', 'x', 'y', 'z']).optional().describe('Defaults to normal.'),
+ group: z.string().max(48).optional(),
}).describe('Blender Displace with a field as the texture: each vertex moves by (field - midlevel) * strength.'),
z.strictObject({ op: z.literal('mirror'), name: editName, axis: z.enum(['x', 'y', 'z']).optional().describe('Mirror across the plane through the local origin perpendicular to this axis. Defaults to x.'), merge: bounded(0, 1000).optional().describe('Vertices this close to the plane are shared by both halves. Defaults to 0.001. Faces lying in the plane are removed, so a closed half becomes a closed whole.') }),
z.strictObject({ op: z.literal('array'), name: editName, count: z.number().int().min(1).max(256).optional(), offset: vector3.optional().describe('Constant step between copies.'), relativeOffset: vector3.optional().describe('Step in bounding-box sizes. Defaults to [1, 0, 0] unless offset is given.'), merge: bounded(0, 1000).optional().describe('Weld touching copies and remove the faces between them.') }),
@@ -571,6 +576,7 @@ const looseRecord = z.record(z.string(), z.unknown()).meta({ id: 'LooseRecord' }
const clothSheet = z.strictObject({
node: identifier.describe('Root mesh node.'),
pin: z.array(z.enum(['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bottomLeft', 'bottomRight'])).max(8).optional(),
+ pinGroup: z.string().max(48).optional(),
pinTo: looseRecord.optional(),
stiffness: unit.optional(), bend: unit.optional(), density: positive.optional(), damping: nonnegative.optional(), friction: unit.optional(), thickness: nonnegative.optional(),
});
diff --git a/skills/build-67js-scene/references/mesh-modeling.md b/skills/build-67js-scene/references/mesh-modeling.md
index 2bca742b..752b7765 100644
--- a/skills/build-67js-scene/references/mesh-modeling.md
+++ b/skills/build-67js-scene/references/mesh-modeling.md
@@ -19,6 +19,9 @@ requires a clean lint, so keep them valid when the API changes.
radius 1 and height 1 centred on the origin (`bevel: 0`); `sphere` has radius 1; `lathe` turns a profile;
`extrude` makes outlines with holes. Set proportions first by translating tagged faces, so later widths and offsets
stay in real units: a 0.5 x 0.6 x 1.0 box is `right` by -0.25, `left` by 0.25, `top` by -0.4.
+ Paint and weight after the shape edits: `vertex_color` (`color`, `field` or a two-color `gradient`) colors the selected faces and
+ exports as `COLOR_0`; `vertex_group` (`name` plus `weight`, `field` or `gradient`) makes weights that `displace` reads with `group`
+ and a cloth sheet reads with `pinGroup`. Example: `{ "op": "vertex_group", "name": "hem", "gradient": { "axis": "y", "range": [-0.5, 0.5], "weights": [1, 0] } }`.
3. Add edits in small batches with `mesh_edit` (or in the recipe). Name every edit (`name: "lid"` gives `lid.cap`,
`lid.side`); an unnamed one gets `<op>-<index>`, which is hard to predict. Select faces by tags, never by index.
4. After each batch read the `mesh_edit` result: `edits[i].selected`, `tags` and `edges` say what each edit touched;
diff --git a/src/agent-cloth.js b/src/agent-cloth.js
index 512750e3..05a33c0d 100644
--- a/src/agent-cloth.js
+++ b/src/agent-cloth.js
@@ -21,7 +21,7 @@ const PIN_EDGES = ['top', 'bottom', 'left', 'right', 'topLeft', 'topRight', 'bot
const COLLIDER_SHAPES = ['ball', 'box'];
const MOVING_SHAPES = ['ball', 'capsule'];
const CLOTH_FIELDS = ['duration', 'gravity', 'wind', 'sheets', 'colliders'];
-const SHEET_FIELDS = ['node', 'pin', 'pinTo', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];
+const SHEET_FIELDS = ['node', 'pin', 'pinGroup', 'pinTo', 'stiffness', 'bend', 'density', 'damping', 'friction', 'thickness'];
const PIN_TO_FIELDS = ['node', 'weight'];
const FIXED_COLLIDER_FIELDS = ['node', 'shape'];
// A ball or capsule that rides on a node: the capsule runs from `attach` (plus offset) to `to` (plus toOffset).
@@ -29,6 +29,9 @@ const MOVING_COLLIDER_FIELDS = ['attach', 'shape', 'radius', 'offset', 'to', 'to
// One capsule per bone of an armature, radius a fraction of the bone length as the ragdoll fits it.
const FITTED_COLLIDER_FIELDS = ['armature', 'radiusFraction', 'exclude'];
const PIN_TOLERANCE = 1e-4;
+// A vertex of the pin group is held when its weight is at least this much.
+const PIN_GROUP_THRESHOLD = 0.5;
+const GROUP_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
const NO_PATCHES = new Map();
function normalizeSheet(input, context) {
@@ -44,10 +47,16 @@ function normalizeSheet(input, context) {
}
sheet.pin = [...new Set(edges)];
}
+ if (input.pinGroup !== undefined) {
+ if (typeof input.pinGroup !== 'string' || !GROUP_NAME_PATTERN.test(input.pinGroup)) {
+ throw new RangeError('Cloth pinGroup must be the name of a vertex group on the sheet mesh.');
+ }
+ sheet.pinGroup = input.pinGroup;
+ }
if (input.pinTo !== undefined) {
knownKeys(input.pinTo, PIN_TO_FIELDS, 'cloth pinTo');
- if (!sheet.pin?.length) {
- throw new RangeError('Cloth pinTo moves the pinned edges, so the sheet needs pin too.');
+ if (!sheet.pin?.length && !sheet.pinGroup) {
+ throw new RangeError('Cloth pinTo moves the pinned vertices, so the sheet needs pin too (or pinGroup).');
}
const target = existingNode(input.pinTo.node, context, 'Cloth pinTo');
if (target === input.node) {
@@ -189,9 +198,21 @@ function colliderFor(collider, node, geometry) {
return { kind: 'box', center, axes, halfExtents };
}
-// Particles on the requested edges of the sheet's local bounds, so 'top' is the row of highest local y.
-function pinnedParticles(localPositions, representatives, pin) {
- if (!pin?.length) return [];
+// The weights of the sheet's pin group per render vertex, or null without one. A name the mesh lacks is an error that lists the groups it has.
+function pinGroupWeights(sheet, geometry) {
+ if (!sheet.pinGroup) return null;
+ const weights = geometry.vertexGroups?.[sheet.pinGroup];
+ if (!weights) {
+ const known = Object.keys(geometry.vertexGroups ?? {});
+ throw new RangeError(`Cloth pinGroup ${sheet.pinGroup} is not a vertex group of ${sheet.node}. Known groups: ${known.join(', ') || 'none'}. Make one with a vertex_group mesh edit.`);
+ }
+ return weights;
+}
+
+// Particles on the requested edges of the sheet's local bounds, so 'top' is the row of highest local y, plus the particles
+// whose vertex weighs at least half in the pin group.
+function pinnedParticles(localPositions, representatives, pin, groupWeights = null) {
+ if (!pin?.length && !groupWeights) return [];
const particlePositions = representatives.map(vertex => localPositions.subarray(vertex * 3, vertex * 3 + 3));
const { minimum, maximum } = localBounds(particlePositions.reduce((all, point) => [...all, ...point], []));
const tolerance = PIN_TOLERANCE * Math.max(maximum[0] - minimum[0], maximum[1] - minimum[1], 1e-6);
@@ -204,7 +225,9 @@ function pinnedParticles(localPositions, representatives, pin) {
};
const pinned = [];
particlePositions.forEach((point, particle) => {
- if (pin.some(edge => tests[edge](point))) pinned.push(particle);
+ const onPinnedEdge = pin?.some(edge => tests[edge](point));
+ const inPinGroup = groupWeights !== null && groupWeights[representatives[particle]] >= PIN_GROUP_THRESHOLD;
+ if (onPinnedEdge || inPinGroup) pinned.push(particle);
});
return pinned;
}
@@ -348,7 +371,7 @@ function bakeSheet(sheet, cloth, node, geometry, colliders, frameCount, movingSe
}
worldPositions.set(world, particle * 3);
});
- const pinned = pinnedParticles(geometry.positions, welded.representatives, sheet.pin);
+ const pinned = pinnedParticles(geometry.positions, welded.representatives, sheet.pin, pinGroupWeights(sheet, geometry));
const needsMoving = Boolean(movingSetup && (sheet.pinTo || movingSetup.specs.length));
const moving = needsMoving ? createMovingBodies(sheet, pinned, worldPositions, movingSetup, frameCount) : null;
const recording = Object.freeze({ ...runKernel('cloth', [worldPositions, welded.triangles, {
@@ -403,7 +426,7 @@ function sheetReport(baked, node, sheet) {
const round = values => values.map(value => Number(value.toFixed(4)));
return {
node: node.id, particles: recording.particleCount, triangles: welded.triangles.length / 3, vertices: geometry.positions.length / 3,
- pinned: pinnedParticles(geometry.positions, welded.representatives, sheet.pin).length,
+ pinned: pinnedParticles(geometry.positions, welded.representatives, sheet.pin, pinGroupWeights(sheet, geometry)).length,
finalBoundsMin: round(minimum), finalBoundsMax: round(maximum),
};
}
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index efc33124..1adacac5 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -154,6 +154,12 @@ export const MESH_MODIFIER_NOTES = Object.freeze({
smooth_by_angle: 'edges bending over angle 30 (0-180) become sharp, others smooth, over smoothAngle; ignoreSharp true also clears hand-made sharp edges.',
});
+// Vertex colors and groups. Details stay here so the tool schemas stay small.
+export const MESH_ATTRIBUTE_NOTES = Object.freeze({
+ vertex_group: 'name (required) sets the weights 0-1 of the vertices of the selected faces; the rest keep theirs (0 in a new group). One of weight (1), field (number expression) or gradient { axis x|y|z, range [low, high], weights [atLow, atHigh] }. At most 32 groups. displace takes group: name and scales each move by the weight; cloth sheets take pinGroup: name and hold vertices of weight 0.5 or more. Put it after the shape edits: a stack node that rebuilds the mesh (mirror, array and so on) drops groups.',
+ vertex_color: 'sets the corner colors (0-1, linear, white until set) of the selected faces. One of color [r, g, b], field (vector expression of the vertex) or gradient { axis, range [low, high], colors [[r,g,b] atLow, [r,g,b] atHigh] }. Shown by the renderer and written as COLOR_0 in a GLB; it multiplies the material color.',
+});
+
// Organic shaping edits. Details stay here so the tool schemas stay small.
export const MESH_SCULPT_NOTES = Object.freeze({
sculpt: 'strokes run in order on the vertices of the selected faces; other vertices stay, so a tag confines them. A stroke has type inflate (along the vertex normal), displace (along direction, needed) or smooth (strength 0 to 1), center and radius, strength in mesh units (negative pushes in). Falloff is smooth to zero at the radius. For bulges, dents and softened forms.',
@@ -171,6 +177,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),
meshModifiers: MESH_MODIFIER_NOTES,
meshSculpt: MESH_SCULPT_NOTES,
+ meshAttributes: MESH_ATTRIBUTE_NOTES,
fieldExpressions: Object.freeze({
operators: FIELD_OPERATOR_NAMES, attributes: FIELD_ATTRIBUTES,
maxNodes: MAX_FIELD_NODES, maxDepth: MAX_FIELD_DEPTH, maxElements: MAX_FIELD_ELEMENTS,
@@ -264,7 +271,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
cloth: Object.freeze({
sheetGeometry: 'grid { segments 1-64 }: unit sheet in XY facing +Z, sized by node scale; any triangle mesh works',
defaults: Object.freeze({ stiffness: 0.9, bend: 0.1, density: 0.2, damping: 0.3, friction: 0.3, thickness: 0.01, colliderShape: 'box' }),
- notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes with no motion track or physics body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude } (a capsule per bone). Sheet pinTo { node, weight } rides the pinned edges on a node. No self collision.',
+ notes: 'density kg/m2, damping 1/s, thickness m, wind m/s steady. Pin edges are of the local bounds. Colliders { node, shape ball|box } are fixed fits to geometry bounds and, like sheets, root nodes with no motion track or physics body. Moving: { attach, shape ball|capsule, radius, offset, to, toOffset } or { armature, radiusFraction, exclude } (a capsule per bone). Sheet pinGroup names a vertex group of the sheet mesh whose vertices (weight 0.5 or more) are held, with or without pin. Sheet pinTo { node, weight } rides the pinned edges on a node. No self collision.',
limits: Object.freeze({ maxSheets: 8, maxColliders: 16, maxMovingColliders: 64, maxDuration: 10, maxParticles: 5000, framesPerSecond: 60, substeps: 4, iterations: 8 }),
}),
// Recipe particles: closed-form from seeded launch values, so any time is computed directly and a seek never replays.
diff --git a/src/mesh-attribute-edits.js b/src/mesh-attribute-edits.js
new file mode 100644
index 00000000..2db8130f
--- /dev/null
+++ b/src/mesh-attribute-edits.js
@@ -0,0 +1,142 @@
+import { createMeshData, GROUP_PREFIX, vertexGroupNames } from './mesh-data.js';
+import { evaluateField, meshFieldContext } from './mesh-fields.js';
+import { selectedVertices } from './mesh-field-edits.js';
+import { selectFaces } from './mesh-select.js';
+
+// Vertex colors (the corner attribute "color", three floats in 0 to 1) and vertex groups (the point attributes
+// "group:<name>", one weight in 0 to 1 per vertex). Both are set by one value, a field expression or a gradient along
+// an axis, on the faces a rule selects. Modifiers and cloth read a group by name.
+
+export const GRADIENT_AXES = Object.freeze(['x', 'y', 'z']);
+export const MAX_VERTEX_GROUPS = 32;
+const COLOR_ATTRIBUTE = 'color';
+const AXIS_OFFSETS = Object.freeze({ x: 0, y: 1, z: 2 });
+
+function editError(index, message) {
+ return new TypeError(`Mesh edit ${index} (${message})`);
+}
+
+function unitNumber(value, index, label, finiteNumber) {
+ return finiteNumber(value, index, label, { minimum: 0, maximum: 1 });
+}
+
+function normalizeGradient(gradient, normalized, index, { finiteNumber, valuesKey, readValue }) {
+ if (!gradient || typeof gradient !== 'object' || Array.isArray(gradient)) {
+ throw editError(index, `gradient must be { axis, range: [low, high], ${valuesKey}: [atLow, atHigh] }`);
+ }
+ for (const key of Object.keys(gradient)) {
+ if (!['axis', 'range', valuesKey].includes(key)) throw editError(index, `gradient does not take ${key}; fields: axis, range, ${valuesKey}`);
+ }
+ if (!GRADIENT_AXES.includes(gradient.axis)) throw editError(index, `gradient.axis must be one of ${GRADIENT_AXES.join(', ')}`);
+ if (!Array.isArray(gradient.range) || gradient.range.length !== 2) throw editError(index, 'gradient.range needs two numbers, low then high');
+ const range = gradient.range.map(value => finiteNumber(value, index, 'gradient.range'));
+ if (!(range[0] < range[1])) throw editError(index, 'gradient.range must have low below high');
+ if (!Array.isArray(gradient[valuesKey]) || gradient[valuesKey].length !== 2) {
+ throw editError(index, `gradient.${valuesKey} needs two entries, the value at the low end then at the high end`);
+ }
+ normalized.gradient = { axis: gradient.axis, range, [valuesKey]: gradient[valuesKey].map((value, side) => readValue(value, `gradient.${valuesKey}[${side}]`)) };
+}
+
+function rejectSecondSource(edit, index, sources) {
+ const given = sources.filter(source => edit[source] !== undefined);
+ if (given.length > 1) throw editError(index, `give only one of ${sources.join(', ')}`);
+ return given[0];
+}
+
+/** Validate a vertex_group edit: a required name and at most one of weight, field or gradient (default weight 1). */
+export function normalizeVertexGroupEdit(edit, normalized, index, { finiteNumber, checkedField }) {
+ const source = rejectSecondSource(edit, index, ['weight', 'field', 'gradient']);
+ if (source === 'field') {
+ normalized.field = checkedField(edit.field, index, 'field', 'scalar');
+ } else if (source === 'gradient') {
+ normalizeGradient(edit.gradient, normalized, index, {
+ finiteNumber, valuesKey: 'weights', readValue: (value, label) => unitNumber(value, index, label, finiteNumber),
+ });
+ } else {
+ normalized.weight = edit.weight === undefined ? 1 : unitNumber(edit.weight, index, 'weight', finiteNumber);
+ }
+}
+
+/** Validate a vertex_color edit: color [r, g, b], a vector field or a two-color gradient (default white). */
+export function normalizeVertexColorEdit(edit, normalized, index, { finiteNumber, checkedField }) {
+ const readColor = (value, label) => {
+ if (!Array.isArray(value) || value.length !== 3) throw editError(index, `${label} needs three numbers from 0 to 1`);
+ return value.map(channel => unitNumber(channel, index, label, finiteNumber));
+ };
+ const source = rejectSecondSource(edit, index, ['color', 'field', 'gradient']);
+ if (source === 'field') {
+ normalized.field = checkedField(edit.field, index, 'field', 'vector');
+ } else if (source === 'gradient') {
+ normalizeGradient(edit.gradient, normalized, index, { finiteNumber, valuesKey: 'colors', readValue: readColor });
+ } else {
+ normalized.color = edit.color === undefined ? [1, 1, 1] : readColor(edit.color, 'color');
+ }
+}
+
+function withAttribute(mesh, domain, name, attribute) {
+ const attributes = { point: { ...mesh.attributes.point }, edge: { ...mesh.attributes.edge }, face: { ...mesh.attributes.face }, corner: { ...mesh.attributes.corner } };
+ attributes[domain][name] = attribute;
+ return createMeshData({
+ positions: mesh.positions, faceOffsets: mesh.faceOffsets, cornerVertices: mesh.cornerVertices,
+ edgeVertices: mesh.edgeVertices, cornerEdges: mesh.cornerEdges, attributes,
+ });
+}
+
+// Where each vertex sits along the gradient axis, 0 at range low and 1 at range high.
+function gradientFractions(mesh, gradient) {
+ const offset = AXIS_OFFSETS[gradient.axis];
+ const [low, high] = gradient.range;
+ const fractions = new Float64Array(mesh.vertexCount);
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const fraction = (mesh.positions[vertex * 3 + offset] - low) / (high - low);
+ fractions[vertex] = Math.min(1, Math.max(0, fraction));
+ }
+ return fractions;
+}
+
+/** Set the weight of a named group for the vertices of the selected faces; other vertices keep their weight (0 in a new group). */
+export function setVertexGroup(mesh, { select, name, weight, field, gradient }) {
+ const attributeName = GROUP_PREFIX + name;
+ const existing = mesh.attributes.point[attributeName];
+ if (!existing && vertexGroupNames(mesh).length >= MAX_VERTEX_GROUPS) {
+ throw new RangeError(`A mesh holds at most ${MAX_VERTEX_GROUPS} vertex groups.`);
+ }
+ const weights = existing ? Float32Array.from(existing.data) : new Float32Array(mesh.vertexCount);
+ const flags = selectedVertices(mesh, select);
+ const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point'), { kind: 'scalar' }).values;
+ const fractions = gradient ? gradientFractions(mesh, gradient) : null;
+ let assignedVertices = 0;
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ if (!flags[vertex]) continue;
+ assignedVertices++;
+ let value = weight;
+ if (fieldValues) value = fieldValues[vertex];
+ if (fractions) value = gradient.weights[0] + (gradient.weights[1] - gradient.weights[0]) * fractions[vertex];
+ weights[vertex] = Math.min(1, Math.max(0, value));
+ }
+ return { mesh: withAttribute(mesh, 'point', attributeName, { data: weights, size: 1 }), assignedVertices };
+}
+
+/** Set the corner colors of the selected faces; corners of other faces keep their color (white when the mesh had none). */
+export function setVertexColor(mesh, { select, color, field, gradient }) {
+ const existing = mesh.attributes.corner[COLOR_ATTRIBUTE];
+ const colors = existing?.size === 3 ? Float32Array.from(existing.data) : new Float32Array(mesh.cornerCount * 3).fill(1);
+ const faceMask = select ? selectFaces(mesh, select) : null;
+ const fieldValues = field === undefined ? null : evaluateField(field, meshFieldContext(mesh, 'point'), { kind: 'vector' }).values;
+ const fractions = gradient ? gradientFractions(mesh, gradient) : null;
+ let assignedCorners = 0;
+ for (let face = 0; face < mesh.faceCount; face++) {
+ if (faceMask && !faceMask[face]) continue;
+ for (let corner = mesh.faceOffsets[face]; corner < mesh.faceOffsets[face + 1]; corner++) {
+ const vertex = mesh.cornerVertices[corner];
+ assignedCorners++;
+ for (let channel = 0; channel < 3; channel++) {
+ let value = color?.[channel];
+ if (fieldValues) value = fieldValues[vertex * 3 + channel];
+ if (fractions) value = gradient.colors[0][channel] + (gradient.colors[1][channel] - gradient.colors[0][channel]) * fractions[vertex];
+ colors[corner * 3 + channel] = Math.min(1, Math.max(0, value));
+ }
+ }
+ }
+ return { mesh: withAttribute(mesh, 'corner', COLOR_ATTRIBUTE, { data: colors, size: 3 }), assignedCorners };
+}
diff --git a/src/mesh-data.js b/src/mesh-data.js
index fed009d5..c0174968 100644
--- a/src/mesh-data.js
+++ b/src/mesh-data.js
@@ -5,6 +5,7 @@ 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:';
+export const GROUP_PREFIX = 'group:';
const RESERVED_ATTRIBUTE_NAMES = new Set(['__proto__', 'constructor', 'prototype']);
const ATTRIBUTE_TYPES = new Map([
@@ -173,6 +174,20 @@ export function meshTags(mesh) {
return Object.keys(mesh.attributes.face).filter(name => name.startsWith(TAG_PREFIX)).map(name => name.slice(TAG_PREFIX.length));
}
+/** Names of vertex groups (point attributes "group:<name>" of one float weight per vertex), without the prefix. */
+export function vertexGroupNames(mesh) {
+ return Object.keys(mesh.attributes.point).filter(name => name.startsWith(GROUP_PREFIX)).map(name => name.slice(GROUP_PREFIX.length));
+}
+
+/** The weight of every vertex in a named group. Throws a message listing the known groups when the name is unknown. */
+export function vertexGroupWeights(mesh, name) {
+ const attribute = mesh.attributes.point[GROUP_PREFIX + name];
+ if (!attribute || attribute.size !== 1) {
+ throw new RangeError(`Unknown vertex group ${name}. Known groups: ${vertexGroupNames(mesh).join(', ') || 'none'}. Make one with a vertex_group edit before this one.`);
+ }
+ return attribute.data;
+}
+
/** Face indices carrying a tag. */
export function facesWithTag(mesh, tag) {
const attribute = mesh.attributes.face[TAG_PREFIX + tag];
diff --git a/src/mesh-field-edits.js b/src/mesh-field-edits.js
index 7c1e5041..82e847b6 100644
--- a/src/mesh-field-edits.js
+++ b/src/mesh-field-edits.js
@@ -1,4 +1,4 @@
-import { createMeshData } from './mesh-data.js';
+import { createMeshData, vertexGroupWeights } from './mesh-data.js';
import { evaluateField, meshFieldContext } from './mesh-fields.js';
import { vertexNormals } from './mesh-normals.js';
import { selectFaces } from './mesh-select.js';
@@ -57,18 +57,22 @@ export function setPosition(mesh, { select, position, offset }) {
* Blender's Displace modifier with a field as the texture: each vertex of the selected faces moves by
* (field - midlevel) * strength along its normal or an axis.
*/
-export function displaceMesh(mesh, { select, field, strength = 1, midlevel = 0.5, direction = 'normal' }) {
+export function displaceMesh(mesh, { select, field, strength = 1, midlevel = 0.5, direction = 'normal', group }) {
const context = meshFieldContext(mesh, 'point');
const { values } = evaluateField(field, context, { kind: 'scalar' });
const normals = direction === 'normal' ? vertexNormals(mesh) : null;
const axis = AXIS_DIRECTIONS.get(direction);
const flags = selectedVertices(mesh, select);
+ // A vertex group scales the move per vertex, as the vertex group of Blender's Displace modifier.
+ const groupWeights = group === undefined ? null : vertexGroupWeights(mesh, group);
const positions = new Float32Array(mesh.positions);
let movedVertices = 0;
for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
if (!flags[vertex]) continue;
+ const weight = groupWeights ? groupWeights[vertex] : 1;
+ if (weight === 0) continue;
movedVertices++;
- const distance = (values[vertex] - midlevel) * strength;
+ const distance = (values[vertex] - midlevel) * strength * weight;
for (let component = 0; component < 3; component++) {
const along = normals ? normals[vertex * 3 + component] : axis[component];
positions[vertex * 3 + component] += distance * along;
diff --git a/src/mesh-operations.js b/src/mesh-operations.js
index e820cd41..f1cf9d9b 100644
--- a/src/mesh-operations.js
+++ b/src/mesh-operations.js
@@ -52,7 +52,9 @@ export const MESH_EDIT_OPERATIONS = Object.freeze({
grid_fill: { fields: ['edges', 'name'], tags: ['fill'] },
knife_project: { fields: ['name', 'path', 'direction'], tags: ['cut'] },
set_position: { fields: ['select', 'position', 'offset'], tags: [] },
- displace: { fields: ['select', 'field', 'strength', 'midlevel', 'direction'], tags: [] },
+ displace: { fields: ['select', 'field', 'strength', 'midlevel', 'direction', 'group'], tags: [] },
+ vertex_group: { fields: ['select', 'name', 'weight', 'field', 'gradient'], tags: [] },
+ vertex_color: { fields: ['select', 'color', 'field', 'gradient'], tags: [] },
decimate: { fields: ['ratio'], tags: [] },
remesh: { fields: ['voxelSize', 'resolution'], tags: [] },
sculpt: { fields: ['select', 'strokes'], tags: [] },
diff --git a/src/mesh-recipe.js b/src/mesh-recipe.js
index 7a11dcea..ae260c3c 100644
--- a/src/mesh-recipe.js
+++ b/src/mesh-recipe.js
@@ -14,6 +14,7 @@ import { unwrapUv } from './mesh-uv.js';
import { runKernel, KernelDeferred } from './kernel-offload.js';
import { validateField } from './mesh-fields.js';
import { setPosition, displaceMesh, DISPLACE_DIRECTIONS } from './mesh-field-edits.js';
+import { normalizeVertexColorEdit, normalizeVertexGroupEdit, setVertexColor, setVertexGroup } from './mesh-attribute-edits.js';
import { subdivideMesh, subdivisionSize, MAX_SUBDIVISION_LEVELS, MAX_CREASE_SHARPNESS } from './mesh-subdivide.js';
import { decimateMesh } from './mesh-decimate.js';
import { isModifierOperation, normalizeModifierEdit, runModifierEdit } from './mesh-modifiers.js';
@@ -112,7 +113,7 @@ export function normalizeMeshEdits(edits) {
normalized.select = edit.select ?? { all: true };
}
if (definition.fields.includes('name')) {
- const name = edit.name ?? (edit.op === 'tag' ? undefined : `${edit.op.split('_')[0]}-${index + 1}`);
+ const name = edit.name ?? (['tag', 'vertex_group'].includes(edit.op) ? undefined : `${edit.op.split('_')[0]}-${index + 1}`);
if (typeof name !== 'string' || !NAME_PATTERN.test(name)) throw editError(index, 'name must be 1 to 48 letters, digits, dots, dashes or underscores');
normalized.name = name;
}
@@ -261,6 +262,16 @@ export function normalizeMeshEdits(edits) {
normalized.midlevel = edit.midlevel === undefined ? 0.5 : finiteNumber(edit.midlevel, index, 'midlevel');
if (edit.direction !== undefined && !DISPLACE_DIRECTIONS.includes(edit.direction)) throw editError(index, `direction must be one of ${DISPLACE_DIRECTIONS.join(', ')}`);
normalized.direction = edit.direction ?? 'normal';
+ if (edit.group !== undefined) {
+ if (typeof edit.group !== 'string' || !NAME_PATTERN.test(edit.group)) throw editError(index, 'group must be the name of a vertex group');
+ normalized.group = edit.group;
+ }
+ break;
+ case 'vertex_group':
+ normalizeVertexGroupEdit(edit, normalized, index, { finiteNumber, checkedField });
+ break;
+ case 'vertex_color':
+ normalizeVertexColorEdit(edit, normalized, index, { finiteNumber, checkedField });
break;
case 'decimate':
normalized.ratio = finiteNumber(edit.ratio, index, 'ratio', { minimum: 0, maximum: 1, exclusiveMinimum: true });
@@ -443,6 +454,21 @@ function runEdit(current, edit, index, { resolveCutter, limits }) {
result.movedVertices = outcome.movedVertices;
return { mesh: outcome.mesh, result };
}
+ if (edit.op === 'vertex_group' || edit.op === 'vertex_color') {
+ let outcome;
+ try {
+ outcome = edit.op === 'vertex_group' ? setVertexGroup(current, edit) : setVertexColor(current, edit);
+ } catch (error) {
+ throw new error.constructor(`Mesh edit ${index} (${edit.op}): ${error.message}`);
+ }
+ if (edit.op === 'vertex_group') {
+ result.group = edit.name;
+ result.assignedVertices = outcome.assignedVertices;
+ } else {
+ result.assignedCorners = outcome.assignedCorners;
+ }
+ return { mesh: outcome.mesh, result };
+ }
if (edit.op === 'sculpt' || edit.op === 'shrinkwrap') {
let outcome;
try {
diff --git a/src/mesh-render.js b/src/mesh-render.js
index 9168e657..c14c0901 100644
--- a/src/mesh-render.js
+++ b/src/mesh-render.js
@@ -1,3 +1,4 @@
+import { vertexGroupNames, vertexGroupWeights } from './mesh-data.js';
import { cornerNormals } from './mesh-normals.js';
import { cornerCycles, edgeCornerTable, UnionFind } from './mesh-topology.js';
@@ -152,6 +153,18 @@ function joinRenderCorners(renderSets, groupOfCorner, splitAttributes, first, se
renderSets.union(first, second);
}
+// Vertex group weights per render vertex, so cloth and other bakes can read a group by name. Absent when the mesh has none.
+function renderVertexGroups(mesh, renderVertexSource) {
+ const names = vertexGroupNames(mesh);
+ if (!names.length) return undefined;
+ const groups = {};
+ for (const name of names) {
+ const weights = vertexGroupWeights(mesh, name);
+ groups[name] = Float32Array.from(renderVertexSource, vertex => weights[vertex]);
+ }
+ return groups;
+}
+
/**
* 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.
@@ -227,6 +240,8 @@ export function extractRender(mesh, { sharpAngle = Infinity } = {}) {
const geometry = { positions, normals, indices };
if (uvs) geometry.uvs = uvs;
if (colors) geometry.colors = colors;
+ const vertexGroups = renderVertexGroups(mesh, renderVertexSource);
+ if (vertexGroups) geometry.vertexGroups = vertexGroups;
return { geometry, renderVertexSource, cornerRenderVertex, triangleFaces };
}
diff --git a/tests/mesh-vertex-groups.test.js b/tests/mesh-vertex-groups.test.js
new file mode 100644
index 00000000..6e8c7132
--- /dev/null
+++ b/tests/mesh-vertex-groups.test.js
@@ -0,0 +1,136 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { box } from '../src/geometry.js';
+import { meshFromGeometry, applyMeshEdits } from '../src/mesh.js';
+import { createAgentScene } from '../src/agent-scene.js';
+import { exportGlb } from '../src/export.js';
+import { vertexGroupWeights } from '../src/mesh-data.js';
+
+const slab = () => meshFromGeometry(box(0, 4));
+const bottomToTopHalf = { name: 'upper', gradient: { axis: 'y', range: [-0.5, 0.5], weights: [0, 1] } };
+
+function topFaceHeights(mesh) {
+ const heights = [];
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) heights.push(mesh.positions[vertex * 3 + 1]);
+ return heights;
+}
+
+test('a vertex group limits a displace edit to the vertices it weighs', () => {
+ const base = slab();
+ const grouped = applyMeshEdits(base, [
+ { op: 'vertex_group', name: 'top', select: { tag: 'top' }, weight: 1 },
+ { op: 'displace', field: 1, strength: 0.2, midlevel: 0, direction: 'y', group: 'top' },
+ ]).mesh;
+ const weights = vertexGroupWeights(grouped, 'top');
+ let moved = 0;
+ for (let vertex = 0; vertex < grouped.vertexCount; vertex++) {
+ const shift = grouped.positions[vertex * 3 + 1] - base.positions[vertex * 3 + 1];
+ if (weights[vertex] === 1) {
+ assert.ok(Math.abs(shift - 0.2) < 1e-6, `grouped vertex ${vertex} moved by ${shift}`);
+ moved++;
+ } else {
+ assert.equal(shift, 0, `ungrouped vertex ${vertex} must stay`);
+ }
+ }
+ assert.ok(moved > 0 && moved < grouped.vertexCount, 'the group holds some, not all, vertices');
+ const ungrouped = applyMeshEdits(base, [{ op: 'displace', field: 1, strength: 0.2, midlevel: 0, direction: 'y' }]).mesh;
+ assert.ok(topFaceHeights(ungrouped).every((height, vertex) => Math.abs(height - base.positions[vertex * 3 + 1] - 0.2) < 1e-6));
+});
+
+test('a gradient writes partial weights that scale the displacement', () => {
+ const base = slab();
+ const mesh = applyMeshEdits(base, [
+ { op: 'vertex_group', ...bottomToTopHalf },
+ { op: 'displace', field: 1, strength: 1, midlevel: 0, direction: 'x', group: 'upper' },
+ ]).mesh;
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ const expected = Math.min(1, Math.max(0, base.positions[vertex * 3 + 1] + 0.5));
+ assert.ok(Math.abs(vertexGroupWeights(mesh, 'upper')[vertex] - expected) < 1e-6);
+ assert.ok(Math.abs(mesh.positions[vertex * 3] - base.positions[vertex * 3] - expected) < 1e-6);
+ }
+});
+
+test('a field sets weights and an unknown group names the groups that exist', () => {
+ const mesh = applyMeshEdits(slab(), [
+ { op: 'vertex_group', name: 'ramp', field: { attr: 'position', component: 'x' } },
+ ]).mesh;
+ const weights = vertexGroupWeights(mesh, 'ramp');
+ for (let vertex = 0; vertex < mesh.vertexCount; vertex++) {
+ assert.ok(Math.abs(weights[vertex] - Math.max(0, mesh.positions[vertex * 3])) < 1e-6);
+ }
+ assert.throws(() => applyMeshEdits(mesh, [{ op: 'displace', field: 1, group: 'missing' }]), /Unknown vertex group missing.*ramp/);
+ assert.throws(() => applyMeshEdits(slab(), [{ op: 'vertex_group', weight: 1 }]), /name/);
+ assert.throws(() => applyMeshEdits(slab(), [{ op: 'vertex_group', name: 'bad', weight: 2 }]), /weight/);
+ assert.throws(() => applyMeshEdits(slab(), [{ op: 'vertex_group', name: 'both', weight: 1, field: 1 }]), /only one/);
+});
+
+test('vertex_color writes corner colors for the selected faces only', () => {
+ const mesh = applyMeshEdits(slab(), [{ op: 'vertex_color', select: { tag: 'top' }, color: [1, 0, 0] }]).mesh;
+ const colors = mesh.attributes.corner.color.data;
+ let red = 0;
+ let white = 0;
+ for (let index = 0; index < mesh.cornerCount; index++) {
+ const isRed = colors[index * 3] === 1 && colors[index * 3 + 1] === 0 && colors[index * 3 + 2] === 0;
+ const isWhite = colors[index * 3] === 1 && colors[index * 3 + 1] === 1 && colors[index * 3 + 2] === 1;
+ red += isRed ? 1 : 0;
+ white += isWhite ? 1 : 0;
+ }
+ assert.ok(red > 0 && white > 0 && red + white === mesh.cornerCount);
+ assert.throws(() => applyMeshEdits(slab(), [{ op: 'vertex_color', color: [2, 0, 0] }]), /color/);
+});
+
+function recipeWithColors() {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{
+ id: 'block', type: 'mesh', base: { type: 'box', bevel: 0, subdivisions: 2 },
+ edits: [{ op: 'vertex_color', gradient: { axis: 'y', range: [-0.5, 0.5], colors: [[0, 0, 1], [1, 0, 0]] } }],
+ }],
+ materials: [{ id: 'paint' }],
+ nodes: [{ id: 'block', geometry: 'block', material: 'paint' }],
+ };
+}
+
+function glbJson(glb) {
+ const bytes = new Uint8Array(glb);
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ const jsonLength = view.getUint32(12, true);
+ return JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + jsonLength)));
+}
+
+test('vertex colors of a recipe mesh reach the part and export as COLOR_0 in a GLB', () => {
+ const scene = createAgentScene(recipeWithColors());
+ const geometry = scene.parts[0].geometry;
+ assert.equal(geometry.colors.length, geometry.positions.length);
+ for (let vertex = 0; vertex < geometry.positions.length / 3; vertex++) {
+ const expectedRed = Math.min(1, Math.max(0, geometry.positions[vertex * 3 + 1] + 0.5));
+ assert.ok(Math.abs(geometry.colors[vertex * 3] - expectedRed) < 1e-6);
+ }
+ const document = glbJson(exportGlb(scene.parts));
+ assert.ok(document.meshes[0].primitives[0].attributes.COLOR_0 !== undefined, 'the GLB carries COLOR_0');
+});
+
+test('cloth holds the vertices of a pin group', () => {
+ const recipe = {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{
+ id: 'sheet', type: 'mesh', base: { type: 'grid', segments: 6 },
+ edits: [{ op: 'vertex_group', name: 'hem', gradient: { axis: 'x', range: [-0.5, -0.4], weights: [1, 0] } }],
+ }],
+ materials: [{ id: 'fabric', doubleSided: true }],
+ nodes: [{ id: 'flag', geometry: 'sheet', material: 'fabric', translation: [0, 2, 0] }],
+ cloth: { duration: 1, sheets: [{ node: 'flag', pinGroup: 'hem' }] },
+ };
+ const scene = createAgentScene(recipe);
+ scene.sampleMotion(1);
+ const positions = scene.parts[0].geometry.positions;
+ let heldLeft = 0;
+ let sagging = 0;
+ for (let vertex = 0; vertex < positions.length / 3; vertex++) {
+ if (positions[vertex * 3] < -0.49) heldLeft++;
+ if (positions[vertex * 3] > 0.3 && positions[vertex * 3 + 1] < -0.2) sagging++;
+ }
+ assert.ok(heldLeft > 0);
+ assert.ok(sagging > 0, 'the free side falls under gravity');
+});