Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Drive the material per pixel from geometry masks: wear blends paint to metal and dirt (#708)

Nguyen Xuan Anb87e127c5a13
diff --git a/changes/708-masks.md b/changes/708-masks.md
index e37bd103..682790c8 100644
--- a/changes/708-masks.md
+++ b/changes/708-masks.md
@@ -1 +1,2 @@
- Mesh edits gain geometry masks: vertex_group measure curvature, edge or occlusion, and vertex_color gradients along a group, so a mesh with no UVs can carry edge wear and dirt (#708)
+- Materials gain `wear`: a vertex group blends the material from paint to bare metal per pixel and a second group adds dirt, so a mesh with no UVs shows metal on its edges and dirt in its cavities (#708)
diff --git a/changes/708-masks.size.md b/changes/708-masks.size.md
index d26db138..2896e426 100644
--- a/changes/708-masks.size.md
+++ b/changes/708-masks.size.md
@@ -1,3 +1,14 @@
- scene:agent-scene: the measure and group-gradient text sits in scene_capabilities (147 bytes gzip), which agents read to use the masks
- scene:agent-scene+lazy: the three measures (curvature, edge, occlusion) and their validation, 1831 bytes gzip in all; they give a mesh with no UVs edge wear and cavity dirt, which no graph node can, because a baked texture knows only (u, v)
- goal:agent-scene: the bundle is over its goal already; the growth is agent-facing capability with a rendered proof
+- scene:agent-scene+renderer: material `wear` (validation, packing the two group weights into the fourth vertex colour component, the decode in the vertex shader, the blend in the fragment shader and its uniforms) grows the bundles; it adds no vertex attribute and a material without `wear` renders byte for byte as before (pixel diff of a six-part scene against main: identical), so the cost is the capability that a shared texture cannot give a mesh with no UVs
+- tool-cost: the material schema gains one short `wear` line and the "More fields" list one word, because agents need to find the field; its detail sits in the `materialWear` topic of scene_capabilities
+- entry:core: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- entry:line-art: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- entry:replace-textured-parts: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- entry:texture-update: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- scene:lit-box: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- scene:gltf-box: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- scene:gltf-box+lazy: the per-pixel wear blend (vertex shader decode, fragment blend, uniforms and the batch binding) is in the renderer and its shaders, about 730 bytes gzip on every bundle that carries the renderer; a mesh with no UVs cannot show metal on its edges or dirt in its cavities any other way, and a scene without wear draws byte for byte as before
+- goal:lit-box: the same renderer growth; the box scenes carry the renderer and cannot leave it out
+- goal:gltf-box: the same renderer growth; the box scenes carry the renderer and cannot leave it out
diff --git a/docs/mesh.md b/docs/mesh.md
index 05ad5c8a..c7c1c481 100644
--- a/docs/mesh.md
+++ b/docs/mesh.md
@@ -321,6 +321,11 @@ Uses:
`gradient` can also follow a vertex group instead of an axis: `{ "group": "wear", "colors": [dirt, paint, metal] }` blends two colors from weight 0 to 1, or three at
weights 0, 0.5 and 1, so `curvature` gives dirt in the dents, paint on flat faces and bare metal on the convex edges.
The renderer multiplies the material color by it and a GLB export writes it as `COLOR_0`. Faces not selected stay white until painted.
+- Material `wear` makes a group drive the material per pixel instead of tinting it: `"wear": { "mask": "edge", "metal": { "color": [0.56, 0.57, 0.58], "metallic": 1, "roughness": 0.3 }, "dirt": { "mask": "cavity", "color": [0.05, 0.04, 0.03], "roughness": 0.9 } }`.
+ The material's own `color`, `metallic` and `roughness` are the paint. Where the `mask` group is high the pixel turns to the metal layer; where the `dirt.mask` group is high it turns to dirt, which
+ removes metal and raises roughness. `threshold` (0.5) and `softness` (0.25, 0.001 to 0.5) set where and how sharply each mask switches (`dirt` has its own). Both masks must be vertex groups of the node's mesh;
+ a name that is not one is an error that lists the groups. The two weights travel in the fourth vertex colour component with 11 bits each, so no attribute is added and a material without `wear` renders as before.
+ It needs a mesh without baked floor sky visibility, and the rasterizer only: the path tracer and a GLB export keep the paint.
- `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/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index d08a34dd..8b568f59 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -150,6 +150,7 @@ const materialFields = {
...materialLayerFields,
subsurface: listed('subsurface', subsurface, 'Subsurface scattering (skin, wax, leaves): weight, radius [r,g,b], scale, color [r,g,b]; ranges in scene_capabilities materialSubsurface.').optional(),
snippet: z.record(z.string(), z.unknown()).nullable().optional().describe('GLSL fragment hook; scene_capabilities materialSnippet.'),
+ wear: z.record(z.string(), z.unknown()).nullable().optional().describe('Metal showing through paint and dirt, from vertex groups; scene_capabilities materialWear.'),
pattern: listed('pattern', materialPattern, 'Procedural texture; box mapping needs no UVs. type is a preset or graph (give graph); also mapping, colors, size, count, bump, seed, axis, resolution; see scene_capabilities pattern.', coreOf(materialPattern.shape, ['type'])).optional(),
map: z.strictObject({ sequence: z.strictObject({
frames: z.array(z.string().regex(/^[a-f0-9]{64}$/)).min(2).max(64),
@@ -168,7 +169,7 @@ const materialFields = {
};
const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']).optional().describe('Surface kind; liquid, foam, foliage, grass and water change how it renders: see scene_capabilities materialTags and water.');
const materialCore = coreOf(materialFields, ['color', 'metallic', 'roughness', 'emission', 'opacity']);
-const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, waterPreset, absorption, turbidity and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
+const materialMore = 'More fields: tag, alphaMode, doubleSided, emissiveColor, map, pattern, subsurface, snippet, wear, waterPreset, absorption, turbidity and the layers clearcoat, clearcoatRoughness, transmission, thickness, ior, attenuationColor, attenuationDistance, sheenColor, sheenRoughness, specular, specularColor, anisotropy, anisotropyRotation, iridescence, iridescenceIor, iridescenceThickness, toon; see scene_capabilities materialFields.';
const materialListed = (strictSchema, description, extraCore) => listed('materialFields', strictSchema, `${description} ${materialMore}`, { ...extraCore, ...materialCore });
const liquidOptics = z.strictObject({
thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 136639f3..b3255443 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -234,6 +234,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
note: MATERIAL_LAYER_NOTES[field],
})]))),
materialSubsurface: 'material.subsurface { weight, radius, scale, color } as Blender Principled BSDF Subsurface; surface tag, rasterizer only. Ranges in scene_create.',
+ materialWear: 'material.wear { mask, threshold 0.5, softness 0.25, metal { color, metallic 1, roughness 0.3 }, dirt { mask, threshold, softness, color, roughness 0.9 } }: the material own color, metallic and roughness are the paint; per pixel it turns to the metal layer where the vertex group mask is high, then to dirt (no metal, rougher) where the dirt group is high. Masks are vertex groups of the node mesh (vertex_group measure edge, curvature or occlusion), so a mesh with no UVs works. Rasterizer only; not with baked sky visibility.',
alphaModes: RECIPE_ALPHA_MODES,
materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
materialMappings: MATERIAL_MAPPINGS,
diff --git a/src/agent-scene.js b/src/agent-scene.js
index b63a5a3a..3cb6ef44 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -7,6 +7,7 @@ import { normalizeAgentLook, environmentPatchWithSetup, environmentLinksLights,
import { postStepSupport } from './shader-registry.js';
import { agentSceneModule, agentSceneModuleLoaded } from './agent-scene-modules.js';
import { MESH_SMOOTH_ANGLE_DEFAULT, CURVE_TEXT_LIMITS, AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { normalizeMaterialWear, geometryWithSurfaceMasks } from './material-wear.js';
import { ALL_LIGHTS_MASK, MATERIAL_LAYER_FIELDS, validateMaterialLayers } from './material-layers.js';
import { recipeDiagnostics, closedRoomDiagnostic } from './agent-diagnostics.js';
import { closedRoomShare, CLOSED_ROOM_SHARE } from './closed-room.js';
@@ -42,7 +43,7 @@ const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [
const RENDER_FLAG_FIELDS = ['visible', 'castShadow', 'receiveShadow', 'holdout', 'shadowCatcher'];
const PART_FLAG_FIELDS = RENDER_FLAG_FIELDS.slice(1);
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material', 'skin', 'relations', 'asset', 'vegetation', 'decal', 'depthLayer', 'blend', ...RENDER_FLAG_FIELDS];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'aov', ...MATERIAL_LAYER_FIELDS];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern', 'map', 'subsurface', 'snippet', 'waterPreset', 'absorption', 'turbidity', 'aov', 'wear', ...MATERIAL_LAYER_FIELDS];
const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'emissiveMap', 'layerMaps', 'transmissionMap', 'aovMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = [...Object.keys(CAMERA_DEFAULTS), ...CAMERA_LENS_FIELDS];
const LOOK_OPERATION_FIELDS = Object.freeze({
@@ -284,6 +285,7 @@ function materialFrom(value) {
result.aov = aov;
}
copyMaterialLayers(value, result);
+ if (value.wear) result.wear = normalizeMaterialWear(value.wear);
if (agentSceneModuleLoaded('worldMaterials')) {
agentSceneModule('worldMaterials').copyWaterFields(value, result, vector);
}
@@ -1457,8 +1459,9 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {
const usesVisibility = recipeUsesVisibility(recipe);
const nextParts = recipe.nodes.filter(node => node.geometry !== undefined).map(node => {
const binding = skinBindings.get(node.id);
- const geometry = binding?.geometry ?? geometries.get(node.geometry);
const material = materialHandles.get(node.material).output;
+ const sourceGeometry = binding?.geometry ?? geometries.get(node.geometry);
+ const geometry = material.wear ? geometryWithSurfaceMasks(sourceGeometry, material.wear, node.id) : sourceGeometry;
const assetExtras = assetRuntime.partExtras.get(node.id);
// Shape keys of a recipe mesh are morph targets with their own weights per part; an imported asset brings its own pose.
const shapeKeyMorph = geometry.morphTargetValues && !assetExtras?.morph ? { weights: Float32Array.from(geometry.morphTargetValues) } : undefined;
diff --git a/src/flush-clip.js b/src/flush-clip.js
index aeeddcff..7abcb548 100644
--- a/src/flush-clip.js
+++ b/src/flush-clip.js
@@ -11,7 +11,7 @@ import { float32Step } from './flush-search.js';
export const FLUSH_CUT_STRIDE = 10;
/** Shared area (square metres) under which a pair is ranked instead of cut: 1 cm2. */
export const FLUSH_CUT_MINIMUM_AREA = 1e-4;
-const PER_VERTEX_FIELDS = ['positions', 'normals', 'uvs', 'lightUvs', 'colors', 'skyVisibility'];
+const PER_VERTEX_FIELDS = ['positions', 'normals', 'uvs', 'lightUvs', 'colors', 'skyVisibility', 'surfaceMasks'];
const MARGIN_STEPS = 4;
const DEGENERATE_AREA_SHARE = 1e-12;
const CACHED_CUTS_PER_GEOMETRY = 8;
diff --git a/src/light-bake.js b/src/light-bake.js
index a9e61446..d729cf30 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -621,6 +621,7 @@ function unwrapIntoSecondUvSet(geometry, scale) {
const uvs = geometry.uvs ? new Float32Array(newCount * 2) : null;
const colors = geometry.colors ? new Float32Array(newCount * 3) : null;
const skyVisibility = geometry.skyVisibility ? new Float32Array(newCount) : null;
+ const surfaceMasks = geometry.surfaceMasks ? new Float32Array(newCount) : null;
for (let vertex = 0; vertex < newCount; vertex++) {
const source = Math.round(extracted.colors[vertex * 3]);
if (uvs) {
@@ -628,6 +629,7 @@ function unwrapIntoSecondUvSet(geometry, scale) {
uvs[vertex * 2 + 1] = geometry.uvs[source * 2 + 1];
}
if (skyVisibility) skyVisibility[vertex] = geometry.skyVisibility[source];
+ if (surfaceMasks) surfaceMasks[vertex] = geometry.surfaceMasks[source];
if (colors) {
for (let channel = 0; channel < 3; channel++) colors[vertex * 3 + channel] = geometry.colors[source * 3 + channel];
}
@@ -635,6 +637,7 @@ function unwrapIntoSecondUvSet(geometry, scale) {
if (uvs) result.uvs = uvs;
if (colors) result.colors = colors;
if (skyVisibility) result.skyVisibility = skyVisibility;
+ if (surfaceMasks) result.surfaceMasks = surfaceMasks;
return { geometry: result, utilization: Math.max(unwrapped.utilization, SURFACE_UTILIZATION_FLOOR) };
}
diff --git a/src/material-snapshot.js b/src/material-snapshot.js
index 7df220da..0fbf2256 100644
--- a/src/material-snapshot.js
+++ b/src/material-snapshot.js
@@ -6,7 +6,7 @@
export const SNAPSHOT_VALUE_FIELDS = Object.freeze(['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap', 'tag', 'alphaMode', 'alphaCutoff', 'opacity', 'doubleSided', 'occlusionStrength', 'moss', 'boxMapScale', 'boxMapAxis', 'lightMapScale', 'layerMaps', 'lightMask', 'clearcoat', 'clearcoatRoughness', 'transmission', 'thickness', 'ior', 'sheenRoughness', 'specular', 'anisotropy', 'anisotropyRotation', 'iridescence', 'iridescenceIor', 'iridescenceThickness', 'attenuationDistance', 'toon']);
/** Fields holding an array or descriptor, which can change in place. A material that sets one is never snapshotted. */
-export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor', 'subsurface']);
+export const SNAPSHOT_REFERENCE_FIELDS = Object.freeze(['normalScale', 'mossColor', 'lightMap', 'attenuationColor', 'sheenColor', 'specularColor', 'subsurface', 'wear']);
function hasNoReferenceFields(material) {
return material.normalScale === undefined &&
@@ -15,7 +15,8 @@ function hasNoReferenceFields(material) {
material.attenuationColor === undefined &&
material.sheenColor === undefined &&
material.specularColor === undefined &&
- material.subsurface === undefined;
+ material.subsurface === undefined &&
+ material.wear === undefined;
}
export class MaterialSnapshot {
diff --git a/src/material-wear.js b/src/material-wear.js
new file mode 100644
index 00000000..ef190c97
--- /dev/null
+++ b/src/material-wear.js
@@ -0,0 +1,150 @@
+import { invalidField } from './field-error.js';
+
+// Surface wear: a material takes one or two vertex groups (see the vertex_group `measure`) and blends its own paint
+// toward a metal layer where the first group is high, then toward dirt where the second group is high. The blend runs per
+// pixel in the main fragment shader, so a mesh with no UVs shows bare metal on its edges and dirt in its cavities.
+// The two weights ride in the fourth component of the vertex colour attribute as one integer (the attribute that carries
+// sky visibility, which is below 2), so no vertex attribute is added.
+
+export const WEAR_LIMITS = Object.freeze({
+ threshold: Object.freeze([0, 1]),
+ softness: Object.freeze([0.001, 0.5]),
+ levels: 2047,
+});
+export const WEAR_DEFAULTS = Object.freeze({ threshold: 0.5, softness: 0.25 });
+export const WEAR_METAL_DEFAULTS = Object.freeze({ color: Object.freeze([0.56, 0.57, 0.58]), metallic: 1, roughness: 0.3 });
+export const WEAR_DIRT_DEFAULTS = Object.freeze({ color: Object.freeze([0.05, 0.04, 0.03]), roughness: 0.9 });
+
+// Sky visibility is at most 1, so a packed value of 2 or more marks a vertex that carries wear.
+const PACK_OFFSET = 2;
+const PACK_BASE = WEAR_LIMITS.levels + 1;
+
+const WEAR_FIELDS = ['mask', 'threshold', 'softness', 'metal', 'dirt'];
+const DIRT_FIELDS = ['mask', 'threshold', 'softness', 'color', 'roughness'];
+const METAL_FIELDS = ['color', 'metallic', 'roughness'];
+
+function unitNumber(value, label, fallback, [minimum, maximum] = [0, 1]) {
+ const result = value ?? fallback;
+ if (typeof result !== 'number' || !(result >= minimum && result <= maximum)) {
+ throw invalidField(label, value, `a number from ${minimum} to ${maximum}, such as ${fallback}`, TypeError);
+ }
+ return result;
+}
+
+function colorOf(value, label, fallback) {
+ const result = value ?? fallback;
+ if (!Array.isArray(result) || result.length !== 3 || result.some(channel => typeof channel !== 'number' || !(channel >= 0 && channel <= 1))) {
+ throw invalidField(label, value, `three numbers from 0 to 1, such as [${fallback.join(', ')}]`, TypeError);
+ }
+ return Object.freeze([...result]);
+}
+
+function onlyKeys(value, allowed, label) {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ throw invalidField(label, value, 'an object, such as {}', TypeError);
+ }
+ for (const key of Object.keys(value)) {
+ if (!allowed.includes(key)) throw invalidField(`${label}.${key}`, value[key], `one of the fields ${allowed.join(', ')}; remove ${key}`, TypeError);
+ }
+}
+
+function maskName(value, label) {
+ if (typeof value !== 'string' || value === '' || value.length > 128) {
+ throw invalidField(label, value, 'the name of a vertex group of the mesh, such as "edge"; make it with a vertex_group mesh edit', TypeError);
+ }
+ return value;
+}
+
+/** Validate a material `wear` field and return a frozen copy with every default filled in. */
+export function normalizeMaterialWear(value) {
+ onlyKeys(value, WEAR_FIELDS, 'wear');
+ const metal = value.metal ?? {};
+ onlyKeys(metal, METAL_FIELDS, 'wear.metal');
+ const result = {
+ mask: maskName(value.mask, 'wear.mask'),
+ threshold: unitNumber(value.threshold, 'wear.threshold', WEAR_DEFAULTS.threshold, WEAR_LIMITS.threshold),
+ softness: unitNumber(value.softness, 'wear.softness', WEAR_DEFAULTS.softness, WEAR_LIMITS.softness),
+ metal: Object.freeze({
+ color: colorOf(metal.color, 'wear.metal.color', WEAR_METAL_DEFAULTS.color),
+ metallic: unitNumber(metal.metallic, 'wear.metal.metallic', WEAR_METAL_DEFAULTS.metallic),
+ roughness: unitNumber(metal.roughness, 'wear.metal.roughness', WEAR_METAL_DEFAULTS.roughness),
+ }),
+ };
+ if (value.dirt !== undefined) {
+ onlyKeys(value.dirt, DIRT_FIELDS, 'wear.dirt');
+ result.dirt = Object.freeze({
+ mask: maskName(value.dirt.mask, 'wear.dirt.mask'),
+ threshold: unitNumber(value.dirt.threshold, 'wear.dirt.threshold', WEAR_DEFAULTS.threshold, WEAR_LIMITS.threshold),
+ softness: unitNumber(value.dirt.softness, 'wear.dirt.softness', WEAR_DEFAULTS.softness, WEAR_LIMITS.softness),
+ color: colorOf(value.dirt.color, 'wear.dirt.color', WEAR_DIRT_DEFAULTS.color),
+ roughness: unitNumber(value.dirt.roughness, 'wear.dirt.roughness', WEAR_DIRT_DEFAULTS.roughness),
+ });
+ }
+ return Object.freeze(result);
+}
+
+function groupWeights(geometry, name, label, nodeId) {
+ const weights = geometry.vertexGroups?.[name];
+ if (!weights) {
+ const known = Object.keys(geometry.vertexGroups ?? {});
+ throw invalidField(label, name, `a vertex group of the mesh of node ${nodeId} (known groups: ${known.join(', ') || 'none'}); make one with a vertex_group mesh edit`);
+ }
+ return weights;
+}
+
+/** One packed number per vertex holding the quantized wear weight and dirt weight (0 without a dirt group). */
+export function packSurfaceMasks(geometry, wear, nodeId) {
+ const wearWeights = groupWeights(geometry, wear.mask, 'wear.mask', nodeId);
+ const dirtWeights = wear.dirt ? groupWeights(geometry, wear.dirt.mask, 'wear.dirt.mask', nodeId) : null;
+ const packed = new Float32Array(wearWeights.length);
+ const levels = WEAR_LIMITS.levels;
+ for (let vertex = 0; vertex < packed.length; vertex++) {
+ const wearLevel = Math.round(Math.min(1, Math.max(0, wearWeights[vertex])) * levels);
+ const dirtLevel = dirtWeights ? Math.round(Math.min(1, Math.max(0, dirtWeights[vertex])) * levels) : 0;
+ packed[vertex] = PACK_OFFSET + wearLevel * PACK_BASE + dirtLevel;
+ }
+ return packed;
+}
+
+/** Fractions of the packed value, as the vertex shader decodes it. Used by tests and the debug views. */
+export function unpackSurfaceMask(packed) {
+ if (packed < PACK_OFFSET) return { wear: 0, dirt: 0 };
+ const bits = packed - PACK_OFFSET;
+ const wearLevel = Math.floor(bits / PACK_BASE);
+ return { wear: wearLevel / WEAR_LIMITS.levels, dirt: (bits - wearLevel * PACK_BASE) / WEAR_LIMITS.levels };
+}
+
+const maskedByGeometry = new WeakMap();
+
+/**
+ * The geometry with `surfaceMasks` packed from the vertex groups the wear names. Cached per source geometry and wear,
+ * so a part keeps its identity between rebuilds and the renderer does not upload it again.
+ */
+export function geometryWithSurfaceMasks(geometry, wear, nodeId) {
+ if (geometry.skyVisibility) {
+ throw invalidField('wear', wear.mask, `a mesh without baked sky visibility (node ${nodeId} has it); remove wear or the floor sky bake`);
+ }
+ const key = `${wear.mask}|${wear.dirt?.mask ?? ''}`;
+ let variants = maskedByGeometry.get(geometry);
+ if (!variants) {
+ variants = new Map();
+ maskedByGeometry.set(geometry, variants);
+ }
+ let masked = variants.get(key);
+ if (!masked) {
+ masked = { ...geometry, surfaceMasks: packSurfaceMasks(geometry, wear, nodeId) };
+ variants.set(key, masked);
+ }
+ return masked;
+}
+
+/** The numbers the fragment shader reads: metal (rgb, metallic), dirt (rgb, roughness), shape (metal roughness, threshold, softness, dirt on) and dirt shape (threshold, softness). */
+export function wearUniformValues(wear) {
+ const dirt = wear.dirt;
+ return {
+ metal: [...wear.metal.color, wear.metal.metallic],
+ dirt: dirt ? [...dirt.color, dirt.roughness] : [0, 0, 0, 0],
+ shape: [wear.metal.roughness, wear.threshold, wear.softness, dirt ? 1 : 0],
+ dirtShape: dirt ? [dirt.threshold, dirt.softness] : [0.5, 0.25],
+ };
+}
diff --git a/src/renderer.js b/src/renderer.js
index 700ede71..5f836cbf 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -18,6 +18,7 @@ import { resolveVolumeFog, validateFogField } from './volumetric.js';
import { requireEnvironmentSupport } from './environment-shading.js';
import { materialLayerState, materialLayerValue } from './material-layers.js';
import { MaterialSnapshot } from './material-snapshot.js';
+import { wearUniformValues } from './material-wear.js';
import { fittedFogDensity } from './fog-fit.js';
import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';
import { resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';
@@ -108,12 +109,13 @@ function shaderFeaturesOfParts(parts) {
if (material.lightMask !== undefined) features.add('lightLinking');
if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');
if (material.subsurface?.weight > 0) features.add('subsurface');
+ if (material.wear) features.add('surfaceWear');
if (material.snippet) features.add(material.snippet.feature);
if (materialLayerValue(material, 'clearcoat') > 0) features.add('clearcoat');
if (materialLayerValue(material, 'sheenColor').some(channel => channel !== 0)) features.add('sheen');
if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);
// Without vertex colours the tint and sky visibility are the constants of the unbound attribute, so no varying carries them.
- if ([part.geometry, ...(part.lods ?? []).map(level => level.geometry)].some(geometry => geometry.colors || geometry.skyVisibility)) features.add('vertexColors');
+ if ([part.geometry, ...(part.lods ?? []).map(level => level.geometry)].some(geometry => geometry.colors || vertexAlpha(geometry))) features.add('vertexColors');
}
return features;
}
@@ -196,7 +198,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
if (material.layers || material.splat) requireSplatSupport().validate(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), material.layers ?? null, material.splat ?? null, material.layerMaps ?? null, material.environmentProbe ?? null, material.waterReflection ?? null, material.irradianceGrid ?? null];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), material.layers ?? null, material.splat ?? null, material.layerMaps ?? null, material.environmentProbe ?? null, material.waterReflection ?? null, material.irradianceGrid ?? null, material.wear ?? null];
}
// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
@@ -506,23 +508,28 @@ function interleaveUvSets(geometry) {
return combined;
}
-// Sky visibility rides in the fourth component of the vertex colour attribute, so the attribute layout stays the same.
+// Sky visibility, or the packed surface wear masks of a material with `wear`, rides in the fourth component of the vertex
+// colour attribute, so the attribute layout stays the same.
+function vertexAlpha(geometry) {
+ return geometry.surfaceMasks ?? geometry.skyVisibility;
+}
+
function interleaveColorsWithSkyVisibility(geometry) {
- const vertexCount = geometry.skyVisibility.length;
+ const vertexCount = vertexAlpha(geometry).length;
const combined = new Float32Array(vertexCount * 4);
for (let vertex = 0; vertex < vertexCount; vertex++) {
for (let channel = 0; channel < 3; channel++) {
combined[vertex * 4 + channel] = geometry.colors ? geometry.colors[vertex * 3 + channel] : 1;
}
- combined[vertex * 4 + 3] = geometry.skyVisibility[vertex];
+ combined[vertex * 4 + 3] = vertexAlpha(geometry)[vertex];
}
return combined;
}
function geometryBufferBytes(geometry) {
const plainBytes = ['positions', 'normals', 'colors', 'indices'].reduce((total, field) => total + (geometry[field]?.byteLength ?? 0), uvBufferBytes(geometry));
- if (!geometry.skyVisibility) return plainBytes;
- return plainBytes - (geometry.colors?.byteLength ?? 0) + geometry.skyVisibility.length * 16;
+ if (!vertexAlpha(geometry)) return plainBytes;
+ return plainBytes - (geometry.colors?.byteLength ?? 0) + vertexAlpha(geometry).length * 16;
}
function validateReplacementGeometry(geometry) {
@@ -829,7 +836,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', 'tintShadowMap', 'tintBlind', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', 'wearEnabled', 'wearMetal', 'wearDirt', 'wearShape', 'wearDirtShape', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', 'tintShadowMap', 'tintBlind', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -957,6 +964,18 @@ export class Renderer67 {
}
}
+ /** Sets the surface wear uniforms of a batch; a material without wear turns the term off. */
+ bindSurfaceWear(wear) {
+ const { context, uniforms } = this;
+ context.uniform1f(uniforms.wearEnabled, wear ? 1 : 0);
+ if (!wear) return;
+ const values = wearUniformValues(wear);
+ context.uniform4fv(uniforms.wearMetal, values.metal);
+ context.uniform4fv(uniforms.wearDirt, values.dirt);
+ context.uniform4fv(uniforms.wearShape, values.shape);
+ context.uniform2fv(uniforms.wearDirtShape, values.dirtShape);
+ }
+
/** Binds the geometry's vertex buffers and attributes into the bound vertex array. */
bindGeometryAttributes(geometry, material) {
const context = this.context;
@@ -967,10 +986,10 @@ export class Renderer67 {
if (geometry[field]) {
const target = field === 'indices' ? context.ELEMENT_ARRAY_BUFFER : context.ARRAY_BUFFER;
const values = field === 'uvs' && geometry.lightUvs ? interleaveUvSets(geometry) : geometry[field];
- geometryBuffers.set(field, this.uploadBuffer(target, field === 'colors' && geometry.skyVisibility ? interleaveColorsWithSkyVisibility(geometry) : values));
+ geometryBuffers.set(field, this.uploadBuffer(target, field === 'colors' && vertexAlpha(geometry) ? interleaveColorsWithSkyVisibility(geometry) : values));
}
}
- if (geometry.skyVisibility && !geometry.colors) geometryBuffers.set('colors', this.uploadBuffer(context.ARRAY_BUFFER, interleaveColorsWithSkyVisibility(geometry)));
+ if (vertexAlpha(geometry) && !geometry.colors) geometryBuffers.set('colors', this.uploadBuffer(context.ARRAY_BUFFER, interleaveColorsWithSkyVisibility(geometry)));
if (geometry.lightUvs && !geometry.uvs) geometryBuffers.set('uvs', this.uploadBuffer(context.ARRAY_BUFFER, interleaveUvSets(geometry)));
this.geometryBuffers.set(geometry, geometryBuffers);
}
@@ -992,11 +1011,11 @@ export class Renderer67 {
context.vertexAttrib2f(13, -1, -1);
}
if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
- if (geometry.skyVisibility && geometry.skyVisibility.length !== geometry.positions.length / 3) throw new Error('Geometry skyVisibility must hold one value for every vertex.');
- if (geometry.colors || geometry.skyVisibility) {
+ if (vertexAlpha(geometry) && vertexAlpha(geometry).length !== geometry.positions.length / 3) throw new Error('Geometry skyVisibility must hold one value for every vertex.');
+ if (geometry.colors || vertexAlpha(geometry)) {
context.bindBuffer(context.ARRAY_BUFFER, geometryBuffers.get('colors'));
context.enableVertexAttribArray(14);
- context.vertexAttribPointer(14, geometry.skyVisibility ? 4 : 3, context.FLOAT, false, 0, 0);
+ context.vertexAttribPointer(14, vertexAlpha(geometry) ? 4 : 3, context.FLOAT, false, 0, 0);
} else {
context.disableVertexAttribArray(14);
context.vertexAttrib3f(14, 1, 1, 1);
@@ -1152,7 +1171,7 @@ export class Renderer67 {
const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
const layerState = materialLayerState(parts[0].material);
const culling = this.createCullingState(parts);
- const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), tintedShadow: castsTintedShadow(parts[0]), tintBlind: Boolean(splat) || Object.keys(parts[0].material.layerMaps ?? {}).length >= 3, receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: renderPass(parts[0].material) };
+ const batch = { ...culling, alphaMode, alphaCutoff, opacity, doubleSided, mirrored: isMirroredMatrix(parts[0].matrix), layerState, wear: parts[0].material.wear ?? null, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, splat, lightMapTexture, texture: textures[0], map, skin, skinTexture, influenceTexture, crowd, crowdTexture, morph, morphTexture, morphWeights, indexCount: flushOrder?.indices.length ?? geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), tintedShadow: castsTintedShadow(parts[0]), tintBlind: Boolean(splat) || Object.keys(parts[0].material.layerMaps ?? {}).length >= 3, receivesShadow: receivesShadow(parts[0]), compositeMode: compositeModeOf(parts[0]), depthLayer: depthLayerOf(parts[0]), flushOrder, flushIndexBuffer, pass: renderPass(parts[0].material) };
if (parts[0].lods) culling.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level));
culling.shadowLevels?.levelGeometries.forEach((geometryOfLevel, level) => this.levelDraw(batch, level, batch.shadowLevels));
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, layerState, skin, jointMatrices: skin?.jointMatrices, skinIndices: geometry.skinIndices, skinWeights: geometry.skinWeights, morph, morphWeights: morph?.weights, morphTargets: geometry.morphTargets, normalMatrix: mat3.create(), committedMatrix: batch.instanceData.subarray(index * INSTANCE_STRIDE, index * INSTANCE_STRIDE + 16) }));
@@ -2342,6 +2361,7 @@ export class Renderer67 {
this.context.uniform2f(this.uniforms.normalScale, batch.mapState[5], batch.mapState[6]);
this.context.uniform1f(this.uniforms.occlusionStrength, batch.mapState[7]);
this.context.uniform4f(this.uniforms.materialMoss, batch.mapState[8], batch.mapState[9], batch.mapState[10], batch.mapState[11]);
+ this.bindSurfaceWear(batch.wear);
const layers = batch.layerState;
this.context.uniform3f(this.uniforms.materialDielectric, layers[0], layers[1], layers[2]);
this.context.uniform2f(this.uniforms.materialCoat, layers[3], layers[4]);
diff --git a/src/shaders.js b/src/shaders.js
index a47fb55b..6df18917 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -83,6 +83,9 @@ flat out mat3 boxNormalMatrix;
#ifdef VERTEX_COLORS
out vec3 vertexTint;
out float vertexSkyVisibility;
+#ifdef SURFACE_WEAR
+out vec2 vertexWear;
+#endif
#endif
out vec4 shadowPosition;
out vec2 textureUV, lightmapUV;
@@ -125,7 +128,16 @@ void main() {
#endif
#ifdef VERTEX_COLORS
vertexTint = USES_CROWD ? vec3(1.0) : vertexColor.rgb;
+#ifdef SURFACE_WEAR
+ // A packed value of 2 or more carries the wear and dirt weights (material-wear.js); below 2 it is sky visibility.
+ bool carriesWear = !USES_CROWD && vertexColor.a >= 2.0;
+ float maskBits = carriesWear ? vertexColor.a - 2.0 : 0.0;
+ float wearLevel = floor(maskBits / 2048.0);
+ vertexWear = vec2(wearLevel, maskBits - wearLevel * 2048.0) / 2047.0;
+ vertexSkyVisibility = (USES_CROWD || carriesWear) ? 1.0 : vertexColor.a;
+#else
vertexSkyVisibility = USES_CROWD ? 1.0 : vertexColor.a;
+#endif
#endif
shadowPosition = lightProjection * world;
gl_Position = viewProjection * world;
@@ -285,6 +297,16 @@ in float vertexSkyVisibility;
const vec3 vertexTint = vec3(1.0);
const float vertexSkyVisibility = 1.0;
#endif
+#if defined(VERTEX_COLORS) && defined(SURFACE_WEAR)
+in vec2 vertexWear;
+#else
+const vec2 vertexWear = vec2(0.0);
+#endif
+uniform float wearEnabled;
+uniform vec4 wearMetal;
+uniform vec4 wearDirt;
+uniform vec4 wearShape;
+uniform vec2 wearDirtShape;
in vec4 shadowPosition;
in vec2 textureUV, lightmapUV;
uniform sampler2D lightMap;
@@ -666,6 +688,19 @@ ${featureCode("surfaceHook")} float alpha = surfaceAlpha(textureAlpha);
metallic *= sampled.b;
roughness *= sampled.g;
}
+ if (USES_SURFACE_WEAR) {
+ // Bare metal where the wear mask is high, then dirt where the dirt mask is high (material-wear.js).
+ float worn = smoothstep(wearShape.y - wearShape.z, wearShape.y + wearShape.z, vertexWear.x);
+ color = mix(color, wearMetal.rgb, worn);
+ metallic = mix(metallic, wearMetal.w, worn);
+ roughness = mix(roughness, wearShape.x, worn);
+ if (wearShape.w > 0.5) {
+ float dirty = smoothstep(wearDirtShape.x - wearDirtShape.y, wearDirtShape.x + wearDirtShape.y, vertexWear.y);
+ color = mix(color, wearDirt.rgb, dirty);
+ metallic *= 1.0 - dirty;
+ roughness = mix(roughness, max(roughness, wearDirt.w), dirty);
+ }
+ }
float splatCavity = 1.0;
if (USES_SPLAT) applySplat(color, normal, roughness, splatCavity);
roughness = clamp(roughness, 0.075, 1.0);
@@ -830,6 +865,7 @@ const SHADER_FEATURE_CONDITIONS = {
renderPass: ['USES_RENDER_PASS', 'renderPassMode > 0.5 && renderPassMode < 5.5'],
sheen: ['USES_SHEEN', 'materialSheen.rgb != vec3(0.0)'],
clearcoat: ['USES_CLEARCOAT', 'materialCoat.x > 0.0'],
+ surfaceWear: ['USES_SURFACE_WEAR', 'wearEnabled > 0.5'],
};
// Lighting from an environment map and the built-in studio lighting are two code paths, and a frame takes one of them.
@@ -911,7 +947,7 @@ export const SHADER_FEATURES = Object.freeze([...Object.keys(SHADER_FEATURE_COND
// choice between them whether or not the uniform picks it, so a renderer without those parts compiles them out.
// The varyings that both shaders carry: per-vertex colours, and the per-instance values that a draw of one instance sets as uniforms.
function interpolantDefines(enabled) {
- return [['vertexColors', 'VERTEX_COLORS'], ['instanced', 'INSTANCED']].filter(([feature]) => enabled.has(feature)).map(([, macro]) => `#define ${macro}`);
+ return [['vertexColors', 'VERTEX_COLORS'], ['surfaceWear', 'SURFACE_WEAR'], ['instanced', 'INSTANCED']].filter(([feature]) => enabled.has(feature)).map(([, macro]) => `#define ${macro}`);
}
function vertexDefinitions(enabled) {
diff --git a/tests/material-wear.test.js b/tests/material-wear.test.js
new file mode 100644
index 00000000..7d92defc
--- /dev/null
+++ b/tests/material-wear.test.js
@@ -0,0 +1,84 @@
+import './support/load-agent-scene-modules.mjs';
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createAgentScene } from '../src/agent-scene.js';
+import { createFragmentShader, createVertexShader } from '../src/shaders.js';
+import { normalizeMaterialWear, packSurfaceMasks, unpackSurfaceMask, WEAR_LIMITS } from '../src/material-wear.js';
+
+const WEAR = { mask: 'edge', dirt: { mask: 'cavity' } };
+
+function recipeWith(material = {}) {
+ return {
+ format: '67js.scene',
+ schemaVersion: 1,
+ geometries: [{
+ id: 'hatch',
+ type: 'mesh',
+ base: { type: 'box', bevel: 0, subdivisions: 1 },
+ edits: [
+ { op: 'subdivide_edges', edges: { all: true }, cuts: 3 },
+ { op: 'inset_region', select: { tag: 'top' }, thickness: 0.18, depth: -0.14 },
+ { op: 'vertex_group', name: 'edge', measure: 'edge', angle: 45 },
+ { op: 'vertex_group', name: 'cavity', measure: 'occlusion', rays: 8, seed: 3 },
+ ],
+ }],
+ materials: [{ id: 'paint', color: [0.7, 0.05, 0.05], roughness: 0.5, ...material }],
+ nodes: [{ id: 'hatch', geometry: 'hatch', material: 'paint' }],
+ };
+}
+
+test('normalizeMaterialWear fills the defaults and freezes the result', () => {
+ const wear = normalizeMaterialWear(WEAR);
+ assert.equal(wear.threshold, 0.5);
+ assert.equal(wear.metal.metallic, 1);
+ assert.equal(wear.metal.roughness, 0.3);
+ assert.equal(wear.dirt.roughness, 0.9);
+ assert.ok(Object.isFrozen(wear) && Object.isFrozen(wear.metal) && Object.isFrozen(wear.dirt));
+});
+
+test('normalizeMaterialWear says what to pass', () => {
+ assert.throws(() => normalizeMaterialWear({}), /wear\.mask: got .*vertex group/);
+ assert.throws(() => normalizeMaterialWear({ mask: 'edge', softness: 0 }), /wear\.softness: .*0\.001 to 0\.5/);
+ assert.throws(() => normalizeMaterialWear({ mask: 'edge', metal: { color: [2, 0, 0] } }), /wear\.metal\.color: .*three numbers from 0 to 1/);
+ assert.throws(() => normalizeMaterialWear({ mask: 'edge', dirt: {} }), /wear\.dirt\.mask/);
+ assert.throws(() => normalizeMaterialWear({ mask: 'edge', paint: 1 }), /wear\.paint: .*one of the fields/);
+});
+
+test('packed masks round-trip within one quantization step and stay above sky visibility', () => {
+ const weights = Float32Array.from([0, 0.25, 0.5, 1]);
+ const geometry = { vertexGroups: { edge: weights, cavity: Float32Array.from([1, 0.5, 0.125, 0]) } };
+ const packed = packSurfaceMasks(geometry, normalizeMaterialWear(WEAR), 'hatch');
+ packed.forEach((value, vertex) => {
+ assert.ok(value >= 2, 'a packed value never reads as sky visibility');
+ const { wear, dirt } = unpackSurfaceMask(value);
+ assert.ok(Math.abs(wear - weights[vertex]) <= 1 / WEAR_LIMITS.levels);
+ assert.ok(Math.abs(dirt - geometry.vertexGroups.cavity[vertex]) <= 1 / WEAR_LIMITS.levels);
+ });
+});
+
+test('a material with wear gets surfaceMasks in its part, deterministically; one without keeps its geometry', () => {
+ const first = createAgentScene(recipeWith({ wear: WEAR }));
+ const second = createAgentScene(recipeWith({ wear: WEAR }));
+ const masks = first.parts[0].geometry.surfaceMasks;
+ assert.ok(masks instanceof Float32Array);
+ assert.equal(masks.length, first.parts[0].geometry.positions.length / 3);
+ assert.ok(masks.some(value => unpackSurfaceMask(value).wear === 1), 'the box folds are worn');
+ assert.ok(masks.some(value => unpackSurfaceMask(value).dirt > 0), 'the cavities hold dirt');
+ assert.deepEqual(Buffer.from(masks.buffer), Buffer.from(second.parts[0].geometry.surfaceMasks.buffer));
+ const plain = createAgentScene(recipeWith());
+ assert.equal(plain.parts[0].geometry.surfaceMasks, undefined);
+ assert.equal(plain.parts[0].material.wear, undefined);
+});
+
+test('a wear mask that is not a vertex group of the mesh names the groups that exist', () => {
+ assert.throws(() => createAgentScene(recipeWith({ wear: { mask: 'rust' } })), /wear\.mask: got "rust".*known groups: edge, cavity/);
+ assert.throws(() => createAgentScene(recipeWith({ wear: { mask: 'edge', dirt: { mask: 'mud' } } })), /wear\.dirt\.mask: got "mud".*known groups: edge, cavity/);
+});
+
+test('the shader carries the wear term only when the feature is on', () => {
+ const withWear = ['vertexColors', 'surfaceWear'];
+ assert.match(createVertexShader(withWear), /#define SURFACE_WEAR/);
+ assert.doesNotMatch(createVertexShader(['vertexColors']), /#define SURFACE_WEAR/);
+ assert.match(createFragmentShader(withWear), /#define USES_SURFACE_WEAR \(wearEnabled > 0\.5\)/);
+ assert.match(createFragmentShader(['vertexColors']), /#define USES_SURFACE_WEAR false/);
+});