Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add procedural material patterns to recipes

Nguyen Xuan An1a1b7bd77b19
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4be0862a..e96a8baa 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add the recipe material field `pattern`: eleven seeded, tileable procedural surfaces (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric, noise) that need no UVs, keep their real size under node scale, and can change while a scene is open
+- Add periodic gradient, ridged and cellular noise for those patterns
- Close `extrude` solids whose holes have aligned edges: their caps left T-junctions, so the mesh was open and booleans refused it
- Let `mesh_inspect` take `geometry` as well as `geometries`, matching `mesh_edit` and `mesh_stack`
- Say in the MCP schema that `box` and `cylinder` are bevelled by default, and how to get exact sizes
diff --git a/bench/agent-modeling/README.md b/bench/agent-modeling/README.md
index 78bf0a48..701b7fe9 100644
--- a/bench/agent-modeling/README.md
+++ b/bench/agent-modeling/README.md
@@ -33,6 +33,7 @@ own mesh report:
| bracket | Two plates and two holes |
| soap | Rounding every edge (bevel) |
| crate-uv | The crate with even UVs |
+| crate-wood | The crate with a wood material pattern, to see whether agents find `pattern` |
`references.mjs` holds one hand-built solution per task. `tests/agent-modeling-suite.test.js` checks that every
reference passes and that broken variants fail. That keeps a wrong checker from costing an agent run.
diff --git a/bench/agent-modeling/check.mjs b/bench/agent-modeling/check.mjs
index 390773ae..f074324a 100644
--- a/bench/agent-modeling/check.mjs
+++ b/bench/agent-modeling/check.mjs
@@ -52,6 +52,10 @@ function checkOne(check, measures) {
const problems = [...blockedOpen.map(point => `blocked at ${point}`), ...missing.map(point => `missing at ${point}`)];
return { pass: problems.length === 0, detail: problems.join('; ') || `${check.open.length} open, ${check.solid.length} solid along ${check.axis}` };
}
+ case 'pattern': {
+ const found = measures.patternTypes.filter(type => check.types.includes(type));
+ return { pass: found.length > 0, detail: measures.patternTypes.join(', ') || 'no material pattern' };
+ }
case 'tips':
return { pass: measures.tips === check.equals, detail: `${measures.tips} tips` };
case 'triangles':
diff --git a/bench/agent-modeling/measure.mjs b/bench/agent-modeling/measure.mjs
index 7fce9099..3b9e389b 100644
--- a/bench/agent-modeling/measure.mjs
+++ b/bench/agent-modeling/measure.mjs
@@ -233,6 +233,7 @@ export async function measureRecipe(recipe) {
const allClosed = closedParts === parts;
return {
nodes: geometries.length,
+ patternTypes: scene.exportRecipe().materials.filter(material => material.pattern).map(material => material.pattern.type),
parts,
closedParts,
holes: allClosed ? (2 * parts - eulerCharacteristic) / 2 : null,
diff --git a/bench/agent-modeling/references.mjs b/bench/agent-modeling/references.mjs
index d0b97881..3dda8b6d 100644
--- a/bench/agent-modeling/references.mjs
+++ b/bench/agent-modeling/references.mjs
@@ -62,6 +62,13 @@ export const REFERENCES = {
[{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: crateEdits }],
[{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],
),
+ 'crate-wood': {
+ ...scene(
+ [{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: crateEdits }],
+ [{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],
+ ),
+ materials: [{ id: 'paint', pattern: { type: 'planks', size: 0.6, count: 5 }, roughness: 1 }],
+ },
'crate-uv': scene(
[{ id: 'crate', type: 'mesh', base: { type: 'box', bevel: 0 }, edits: [...crateEdits, { op: 'uv_unwrap' }] }],
[{ id: 'crate', geometry: 'crate', translation: [0, 0.3, 0] }],
diff --git a/bench/agent-modeling/results/2026-10-30-12-33-sonnet-pattern-cold.json b/bench/agent-modeling/results/2026-10-30-12-33-sonnet-pattern-cold.json
new file mode 100644
index 00000000..1d96cf2b
--- /dev/null
+++ b/bench/agent-modeling/results/2026-10-30-12-33-sonnet-pattern-cold.json
@@ -0,0 +1,43 @@
+{
+ "run": "2026-10-30-12-33-sonnet-pattern-cold",
+ "model": "claude-sonnet-5-5",
+ "date": "2026-10-30T12:34:25.374Z",
+ "passed": 1,
+ "tasks": 1,
+ "toolCalls": 3,
+ "costUsd": 0.44,
+ "records": [
+ {
+ "task": "crate-wood",
+ "pass": true,
+ "passed": 9,
+ "total": 9,
+ "failed": [],
+ "model": "claude-sonnet-5-5",
+ "toolCalls": 3,
+ "toolErrors": 0,
+ "toolsByName": {
+ "ToolSearch": 1,
+ "scene_create": 1,
+ "scene_look": 1,
+ "scene_export_recipe": 1
+ },
+ "features": {
+ "geometryTypes": [
+ "mesh",
+ "box"
+ ],
+ "meshOperations": [
+ "boolean"
+ ]
+ },
+ "turns": 5,
+ "costUsd": 0.4370352,
+ "inputTokens": 474165,
+ "outputTokens": 2018,
+ "wallSeconds": 33,
+ "exitCode": 0,
+ "stopped": "success"
+ }
+ ]
+}
diff --git a/bench/agent-modeling/tasks.mjs b/bench/agent-modeling/tasks.mjs
index 73614d77..706279cb 100644
--- a/bench/agent-modeling/tasks.mjs
+++ b/bench/agent-modeling/tasks.mjs
@@ -150,6 +150,13 @@ inset about 0.05 m from the top edges and 0.03 m tall. Give every part UV coordi
stretching.`,
checks: [...crateChecks, { kind: 'uv', maxStretch: 0.15 }],
},
+ {
+ id: 'crate-wood',
+ prompt: `A wooden crate that looks like real wood, not a flat colour. The body is a 0.6 m cube. Each of its four
+sides has a recessed panel: a frame about 0.04 m wide around a panel sunk about 0.02 m into the side. On top sits a
+raised lid, inset about 0.05 m from the top edges and 0.03 m tall.`,
+ checks: [...crateChecks, { kind: 'pattern', types: ['wood', 'planks'] }],
+ },
];
export function taskById(id) {
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 03ca9223..dd84d0a8 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -77,13 +77,13 @@ Modeling point inputs have a maximum of 4096 points.
An extrusion has at most 128 holes and 4096 total contour points.
Shared resource IDs generate geometry once, regardless of the number of mesh nodes.
-Materials contain `id`, `tag`, `color`, `metallic`, `roughness`, `emission`, optional `emissiveColor`, `opacity`, `alphaMode` and `doubleSided`.
+Materials contain `id`, `tag`, `color`, `metallic`, `roughness`, `emission`, optional `emissiveColor`, `opacity`, `alphaMode`, `doubleSided` and `pattern`.
The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, `0`, opacity `1`, `opaque` and `false`.
The tag can be `surface`, `unlit`, `liquid` or `foam` and remains fixed during editing.
`liquid` refracts and tints what lies behind it: its color is the light one metre lets through, so `[0.56, 0.84, 0.88]` is clear water. `foam` draws soft blended droplets.
Any `opacity` below one draws the material blended after opaque geometry, which suits glass, windows and visors. `alphaMode` accepts `opaque` or `blend`; cutout masking needs a texture and is not available in procedural recipes.
`doubleSided` draws and lights both faces of thin sheets.
-Changing the tag, opacity, blending or sidedness replaces the affected parts in the renderer; color, metallic, roughness and emission edits keep them.
+Changing the tag, opacity, blending, sidedness or pattern replaces the affected parts in the renderer; color, metallic, roughness and emission edits keep them.
Set liquid optics with `environment.liquid`: `thickness`, `ior`, `refraction`, `scattering`, `foamOpacity` and `foamSoftness`.
Colors use linear RGB.
@@ -91,7 +91,39 @@ Base color, metallic, and roughness range from zero to one.
Emission and independent emissive color must be nonnegative finite Float32 numbers.
Their component products must also remain finite at Float32 precision.
Unlit emissive radiance is capped at 65500 per component to fit the half-float HDR target.
-Textures and the other procedural material tags are outside this version.
+Image textures and the other procedural material tags are outside this version.
+
+### Material patterns
+
+`pattern` gives a `surface` material a procedural texture, baked once and shared by every material with the same definition:
+
+```json
+{ "id": "oak", "pattern": { "type": "wood", "size": 0.6, "axis": "z" }, "roughness": 1 }
+```
+
+| Field | Meaning |
+| --- | --- |
+| `type` | `noise`, `wood`, `planks`, `bricks`, `tiles`, `marble`, `stone`, `concrete`, `metal`, `rust` or `fabric` |
+| `colors` | Two linear RGB colours to mix, darker first. `bricks` also takes a third, for the mortar. Each type has defaults |
+| `size` | Metres per repeat of the texture, from 0.01 to 100 |
+| `count` | Features per repeat, from 1 to 64: planks, bricks or tiles across, wood rings, or noise cells |
+| `bump` | Relief strength, from 0 (flat) to 4 |
+| `seed` | Nonnegative whole number. The same definition always bakes the same pixels |
+| `axis` | Object axis the grain runs along: `x`, `y` (default) or `z` |
+| `resolution` | Texture size: 256, 512 (default) or 1024 |
+
+A pattern needs no UVs. The texture is projected along the object's three axes and blended by the surface normal, so it
+works on every geometry type and after mesh edits. Coordinates are in metres on the object, after its node scale, so a
+stretched box keeps the texture's real size and the pattern moves with the node. Corners between faces show where one
+projection meets another; `uv_unwrap` results are not used by patterns.
+
+`color` defaults to white and tints the pattern. `roughness` and `metallic` scale what the pattern stores, so use
+`roughness: 1` for its own surface and `metallic: 1` for `metal` and `rust` (rust stores where it is no longer metal).
+
+A scene holds at most 16 different patterns, and materials that differ only in `color`, `roughness` or `metallic`
+share one. Each takes about 4 MiB of texture memory at 512. Measured in Node on a Ryzen 5 5600X, baking at 512 took
+about 0.2 to 0.55 s per pattern, which happens when the scene first renders it. Changing a pattern rebuilds the
+renderer.
Nodes contain `id`, optional `label`, `parent`, `translation`, `rotation`, and `scale`.
Mesh nodes also require both `geometry` and `material` resource IDs.
@@ -132,7 +164,7 @@ Final resource references and hierarchy must be valid before publication.
| Operation | Fields |
| --- | --- |
| `set-node` | `id`, optional `translation`, `rotation`, `scale`, `parent`, `label`, `geometry`, `material` |
-| `set-material` | `id`, optional `color`, `metallic`, `roughness`, `emission`, `emissiveColor` |
+| `set-material` | `id`, optional `color`, `metallic`, `roughness`, `emission`, `emissiveColor`, `pattern` |
| `set-camera` | Optional `eye`, `target`, `up`, `fov`, `near`, `far` directly on the command |
| `add-geometry` | `geometry`, containing a complete geometry record |
| `remove-geometry` | `id` |
diff --git a/docs/mcp.md b/docs/mcp.md
index d9489586..98a9d625 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -189,6 +189,7 @@ Checkpoints retain their resource handles for exact restoration. Active, checkpo
Release unused checkpoints to free that ownership before adding detail.
The preview reconciles rigid, untextured parts while retaining shader programs, render targets and shared geometry buffers.
+A scene with material patterns gets a new renderer on each topology change instead, because textured parts are not streamed.
Unchanged draw batches remain allocated. Changed instance groups receive new instance buffers. Retired buffers are released.
Staging must fit alongside the current render allocations, so a replacement can fail its GPU budget even when the final scene alone fits.
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index 52ac3c6e..1ab73ca0 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -61,6 +61,19 @@ function renderInfo(renderer) {
};
}
+function hasPatternTextures(parts) {
+ return parts.some(part => part.material.boxMapScale);
+}
+
+// replaceParts streams only untextured parts, so a topology change around pattern textures takes a new renderer.
+function rebuildRenderer(record) {
+ record.renderer.dispose();
+ record.renderer = null;
+ resetCanvas();
+ record.renderer = initializeRenderer(record.scene, record.options);
+ record.shadowKey = null;
+}
+
function draw(record, time = 0, camera = record.scene.camera) {
if (!record.renderer) throw new Error('The scene renderer is leased to a render job.');
if (record.renderer.context.isContextLost()) {
@@ -69,7 +82,13 @@ function draw(record, time = 0, camera = record.scene.camera) {
// Shrink the existing target first so a smaller look can recover a staging-budget failure.
record.renderer.resize();
if (record.rendererTopology !== record.scene.topologyRevision) {
- record.renderer.replaceParts(record.scene.parts);
+ const textured = hasPatternTextures(record.scene.parts);
+ if (textured || record.rendererTextured) {
+ rebuildRenderer(record);
+ } else {
+ record.renderer.replaceParts(record.scene.parts);
+ }
+ record.rendererTextured = textured;
record.rendererTopology = record.scene.topologyRevision;
record.renderer.resize();
} else {
@@ -151,7 +170,7 @@ function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {
try {
renderer = initializeRenderer(scene, { memoryBudgetMiB, backend });
const record = { scene, renderer, asset, sessionId, options: { memoryBudgetMiB, backend },
- checkpoints: new Map(), rendererTopology: scene.topologyRevision };
+ checkpoints: new Map(), rendererTopology: scene.topologyRevision, rendererTextured: hasPatternTextures(scene.parts) };
draw(record);
const result = status(record);
if (backend === 'gpu' && /swiftshader|llvmpipe|software/i.test(result.render.graphics)) {
@@ -239,6 +258,7 @@ window.__agentPreview = {
try {
record.renderer = initializeRenderer(record.scene, record.options);
record.rendererTopology = record.scene.topologyRevision;
+ record.rendererTextured = hasPatternTextures(record.scene.parts);
record.shadowKey = null;
draw(record);
return status(record);
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index e82e4691..e2c2cdb9 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -5,6 +5,7 @@ import { setPriority, constants } from 'node:os';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import packageMetadata from '../package.json' with { type: 'json' };
+import { MATERIAL_PATTERN_TYPES } from '../src/agent-scene-capabilities.js';
const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
const positive = finite.positive();
@@ -26,7 +27,18 @@ const nodeFields = {
scale: z.tuple([positive, positive, positive]).optional().describe('Positive local XYZ scale.'),
};
const nodeRecord = z.strictObject({ id: identifier, geometry: identifier.optional(), material: identifier.optional(), ...nodeFields });
+const materialPattern = z.strictObject({
+ type: z.enum(MATERIAL_PATTERN_TYPES).describe('Surface look. Directional types (wood, planks, metal) run along axis.'),
+ colors: z.array(color).min(2).max(3).optional().describe('Linear RGB colours to mix, darker first. Bricks take a third for the mortar. Each type has good defaults.'),
+ size: z.number().min(0.01).max(100).optional().describe('Metres per repeat of the texture, so it keeps its real size on any object and node scale.'),
+ count: z.number().int().min(1).max(64).optional().describe('Features per repeat: planks, bricks across, tiles across, wood rings or noise cells.'),
+ bump: z.number().min(0).max(4).optional().describe('Relief strength. 0 is flat.'),
+ seed: z.number().int().min(0).max(2147483647).optional(),
+ axis: z.enum(['x', 'y', 'z']).optional().describe('Object axis the grain runs along. Defaults to y.'),
+ resolution: z.union([z.literal(256), z.literal(512), z.literal(1024)]).optional().describe('Texture size. Defaults to 512; each pattern takes about 4 MiB at 512.'),
+}).describe('Procedural texture baked for this material. Needs no UVs: it is projected along the object axes. color then tints it (defaults to white), and roughness and metallic scale it.');
const materialFields = {
+ pattern: materialPattern.optional(),
color: color.optional().describe('Linear RGB base color, each component between zero and one.'),
metallic: unit.optional(),
roughness: unit.optional(),
diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.md
index aabd94fb..ced0c789 100644
--- a/skills/build-67js-scene/SKILL.md
+++ b/skills/build-67js-scene/SKILL.md
@@ -37,6 +37,7 @@ Use `simplify-code` and `engineering-workflows` for implementation.
- A rigid accessory on a morphing or skinned surface uses optional `src/surface-attachment.js` and `docs/surface-attachment.md`.
- Agent scene recipes use optional `src/agent-scene.js` and `docs/agent-scene.md`. Verify source versus published availability before importing.
- Polygon modeling by an agent (extrude, inset, loop cut, bevel, booleans, mirror, array, solidify) uses the recipe `mesh` geometry and the MCP tools `mesh_inspect`, `mesh_edit` and `mesh_stack`. Read [mesh-modeling.md](references/mesh-modeling.md) before the first edit; check that the checkout's `docs/mesh.md` exists, since it is unreleased after npm 0.10.0.
+- A surface look in a recipe (wood, planks, bricks, tiles, marble, stone, concrete, metal, rust, fabric) uses the material `pattern` field, which needs no UVs. See "Material patterns" in the checkout's `docs/agent-scene.md`.
- Agent tool calls use the installed `67js-mcp` stdio server from release `0.5.0` onward. Read `docs/mcp.md` for launch and PNG feedback.
- Agent render jobs use `docs/agent-render-jobs.md`. Check source versus published support, configure a private store and poll until terminal.
- Agent procedural animation uses `docs/agent-motion.md` from release `0.7.0`. Author recipe tracks, then seek through `sampleMotion` or MCP `motionTime`.
diff --git a/skills/build-67js-scene/references/mesh-modeling.md b/skills/build-67js-scene/references/mesh-modeling.md
index 97f4e621..e4061973 100644
--- a/skills/build-67js-scene/references/mesh-modeling.md
+++ b/skills/build-67js-scene/references/mesh-modeling.md
@@ -3,8 +3,8 @@
<!-- skill-navigation:start -->
This is the [mesh modeling guide](#mesh-modeling-for-agents). Read [Workflow](#workflow) and
[Choosing faces and edges](#choosing-faces-and-edges) completely before the first edit. Read the
-[Recipes](#recipes) entry closest to the shape you are building, and [Errors and fixes](#errors-and-fixes) when a
-call fails. The full contract (every op, field and default) is the checkout's `docs/mesh.md`; `docs/mcp.md` lists
+[Recipes](#recipes) entry closest to the shape you are building, [Giving a part a surface](#giving-a-part-a-surface) for
+textures, and [Errors and fixes](#errors-and-fixes) when a call fails. The full contract (every op, field and default) is the checkout's `docs/mesh.md`; `docs/mcp.md` lists
the tools.
<!-- skill-navigation:end -->
@@ -181,6 +181,19 @@ A planter (open box with walls) and a rounded soap bar:
] }
```
+## Giving a part a surface
+
+A material `pattern` textures any part with no UVs, after any edits. `size` is metres per repeat, so it stays right on
+a scaled node. Use `roughness: 1` so the pattern's own surface shows, and `metallic: 1` for `metal` and `rust`:
+
+```text
+{ "id": "crate-wood", "pattern": { "type": "planks", "size": 0.8, "count": 5 }, "roughness": 1 }
+{ "id": "drum-metal", "pattern": { "type": "rust", "size": 0.6 }, "metallic": 1, "roughness": 1 }
+```
+
+Run a grain along a long part with `axis` (`"axis": "x"` for a plank lying along X), and tint with `color` instead of
+adding another pattern: a scene holds at most 16 different ones. `uv_unwrap` is for exporting, not for patterns.
+
## Errors and fixes
| Message contains | Do |
diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.js
index 3380b52c..de5696ec 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -9,7 +9,10 @@ export const AGENT_SCENE_DEFAULT_LIMITS = Object.freeze({
maxOperations: 256, maxCheckpoints: 8, maxRecipeBytes: 1024 * 1024,
});
-// Procedural recipes have no textures, so cutout masking has nothing to cut.
+export const MATERIAL_PATTERN_TYPES = Object.freeze(['noise', 'wood', 'planks', 'bricks', 'tiles', 'marble', 'stone', 'concrete', 'metal', 'rust', 'fabric']);
+export const MAX_MATERIAL_PATTERNS = 16;
+
+// Recipe textures are opaque patterns, so cutout masking has nothing to cut.
export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend']);
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
@@ -24,6 +27,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
]),
materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
alphaModes: RECIPE_ALPHA_MODES,
+ materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
authoredLook: true, maxPointLights: 8,
proceduralMotion: true,
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 14f4228f..f1fa6147 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -7,7 +7,8 @@ import { normalizeAgentLook } from './agent-look.js';
import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';
import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';
import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, MAX_MATERIAL_PATTERNS, RECIPE_ALPHA_MODES } from './agent-scene-capabilities.js';
+import { materialPatternTextures, normalizeMaterialPattern } from './material-patterns.js';
export { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS };
export { normalizeAgentLook, resolveAgentShadow } from './agent-look.js';
export { needsMeshBooleans } from './agent-mesh.js';
@@ -17,7 +18,8 @@ const DEFAULT_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAX_MESH_REPORTS = 16;
const CAMERA_DEFAULTS = Object.freeze({ eye: [4, 3, 5], target: [0, 0, 0], up: [0, 1, 0], fov: 45, near: 0.1, far: 1000 });
const NODE_FIELDS = ['translation', 'rotation', 'scale', 'parent', 'label', 'geometry', 'material'];
-const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided'];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided', 'pattern'];
+const PATTERN_TEXTURE_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'boxMapScale', 'boxMapAxis'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
const LOOK_OPERATION_FIELDS = Object.freeze({
'set-environment': 'environment',
@@ -181,11 +183,17 @@ function resources(values, maximum, label, validate) {
function materialFrom(value) {
knownKeys(value, ['id', 'tag', ...MATERIAL_FIELDS], 'material');
- const result = { id: value.id, tag: defaultValue(value.tag, 'surface'), color: vector(defaultValue(value.color, [0.5, 0.5, 0.5]), 3, 'color'),
+ // A pattern brings its own colours, so the color field tints it and leaves it unchanged by default.
+ const defaultColor = value.pattern === undefined ? [0.5, 0.5, 0.5] : [1, 1, 1];
+ const result = { id: value.id, tag: defaultValue(value.tag, 'surface'), color: vector(defaultValue(value.color, defaultColor), 3, 'color'),
metallic: defaultValue(value.metallic, 0), roughness: defaultValue(value.roughness, 0.5), emission: defaultValue(value.emission, 0) };
if (!AGENT_SCENE_CAPABILITIES.materialTags.includes(result.tag)) {
throw new RangeError(`Material tag must be one of ${AGENT_SCENE_CAPABILITIES.materialTags.join(', ')}.`);
}
+ if (value.pattern !== undefined) {
+ if (result.tag !== 'surface') throw new RangeError('Material pattern needs the surface tag.');
+ result.pattern = normalizeMaterialPattern(value.pattern);
+ }
result.opacity = defaultValue(value.opacity, 1);
finite(result.opacity, 'opacity');
if (result.opacity < 0 || result.opacity > 1) {
@@ -483,6 +491,10 @@ function normalizeRecipe(input, limits) {
return definition;
});
recipe.materials = resources(recipe.materials, limits.maxMaterials, 'materials', materialFrom);
+ const distinctPatterns = new Set(recipe.materials.filter(material => material.pattern).map(material => JSON.stringify(material.pattern)));
+ if (distinctPatterns.size > MAX_MATERIAL_PATTERNS) {
+ throw new RangeError(`A scene holds at most ${MAX_MATERIAL_PATTERNS} different material patterns; it has ${distinctPatterns.size}. Reuse a pattern and tint it with color.`);
+ }
recipe.nodes = resources(recipe.nodes, limits.maxNodes, 'nodes', nodeFrom);
recipe.camera = cameraFrom(recipe.camera);
const look = {};
@@ -512,7 +524,8 @@ function geometryStats(records) {
}
function batchSignature(material) {
- return `${material.tag}|${material.alphaMode}|${material.opacity}|${material.doubleSided}`;
+ // Textures are fixed per renderer, so a changed pattern rebuilds it like a changed tag does.
+ return `${material.tag}|${material.alphaMode}|${material.opacity}|${material.doubleSided}|${JSON.stringify(material.pattern ?? null)}`;
}
function materialHandle(snapshot) {
@@ -526,6 +539,15 @@ function materialHandle(snapshot) {
},
});
}
+ for (const field of PATTERN_TEXTURE_FIELDS) {
+ Object.defineProperty(output, field, {
+ enumerable: true,
+ // Baked on first read, so validating or inspecting a recipe never pays for it.
+ get() {
+ return holder.snapshot.pattern ? materialPatternTextures(holder.snapshot.pattern)[field] : undefined;
+ },
+ });
+ }
return { holder, output: Object.freeze(output) };
}
diff --git a/src/material-patterns.js b/src/material-patterns.js
new file mode 100644
index 00000000..f1f8259b
--- /dev/null
+++ b/src/material-patterns.js
@@ -0,0 +1,372 @@
+import { MATERIAL_PATTERN_TYPES } from './agent-scene-capabilities.js';
+
+// Procedural surface patterns for recipe materials: seeded, tileable and baked on the CPU into the same texture
+// descriptors a loaded material uses. Texture coordinates run 0 to 1 and every noise is periodic over that square, so
+// a pattern repeats without a visible seam. Directional patterns (wood, planks, brushed metal) run along V.
+
+function hashCell(cellX, cellY, seed) {
+ let hash = Math.imul(cellX, 0x27d4eb2d) ^ Math.imul(cellY, 0x165667b1) ^ Math.imul(seed, 0x9e3779b1);
+ hash = Math.imul(hash ^ (hash >>> 15), 0x85ebca6b);
+ hash = Math.imul(hash ^ (hash >>> 13), 0xc2b2ae35);
+ return (hash ^ (hash >>> 16)) >>> 0;
+}
+
+const wrapCell = (cell, period) => ((cell % period) + period) % period;
+const smootherStep = value => value * value * value * (value * (value * 6 - 15) + 10);
+const clampUnit = value => Math.min(1, Math.max(0, value));
+const smoothStep = (minimum, maximum, value) => {
+ const position = clampUnit((value - minimum) / (maximum - minimum));
+ return position * position * (3 - 2 * position);
+};
+
+function cornerGradient(cellX, cellY, offsetX, offsetY, seed) {
+ const angle = hashCell(cellX, cellY, seed) / 4294967296 * Math.PI * 2;
+ return Math.cos(angle) * offsetX + Math.sin(angle) * offsetY;
+}
+
+/** Gradient noise in about -1 to 1, periodic over [0, 1) with the given whole number of cells per axis. */
+export function gradientNoise(positionU, positionV, cellsU, cellsV, seed = 0) {
+ const scaledU = positionU * cellsU;
+ const scaledV = positionV * cellsV;
+ const floorU = Math.floor(scaledU);
+ const floorV = Math.floor(scaledV);
+ const fractionU = scaledU - floorU;
+ const fractionV = scaledV - floorV;
+ const left = wrapCell(floorU, cellsU);
+ const right = wrapCell(floorU + 1, cellsU);
+ const bottom = wrapCell(floorV, cellsV);
+ const top = wrapCell(floorV + 1, cellsV);
+ const blendU = smootherStep(fractionU);
+ const blendV = smootherStep(fractionV);
+ const lower = cornerGradient(left, bottom, fractionU, fractionV, seed) * (1 - blendU)
+ + cornerGradient(right, bottom, fractionU - 1, fractionV, seed) * blendU;
+ const upper = cornerGradient(left, top, fractionU, fractionV - 1, seed) * (1 - blendU)
+ + cornerGradient(right, top, fractionU - 1, fractionV - 1, seed) * blendU;
+ return (lower * (1 - blendV) + upper * blendV) * 1.5;
+}
+
+/** Fractal sum of gradientNoise in about -1 to 1. Each octave doubles the cells, so it stays periodic. */
+export function fractalNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 5, gain = 0.5) {
+ let total = 0;
+ let amplitude = 1;
+ let amplitudeSum = 0;
+ for (let octave = 0; octave < octaves; octave++) {
+ total += gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 131) * amplitude;
+ amplitudeSum += amplitude;
+ amplitude *= gain;
+ }
+ return total / amplitudeSum;
+}
+
+/** Ridged fractal noise in 0 to 1: sharp crests where the gradient noise crosses zero. */
+export function ridgedNoise(positionU, positionV, cellsU, cellsV, seed = 0, octaves = 4) {
+ let total = 0;
+ let amplitude = 1;
+ let amplitudeSum = 0;
+ for (let octave = 0; octave < octaves; octave++) {
+ const ridge = 1 - Math.abs(gradientNoise(positionU, positionV, cellsU << octave, cellsV << octave, seed + octave * 211));
+ total += ridge * ridge * amplitude;
+ amplitudeSum += amplitude;
+ amplitude *= 0.5;
+ }
+ return total / amplitudeSum;
+}
+
+/** Periodic Worley noise: distances to the nearest and second nearest feature point, in cell units. */
+export function cellularNoise(positionU, positionV, cells, seed = 0) {
+ const scaledU = positionU * cells;
+ const scaledV = positionV * cells;
+ const floorU = Math.floor(scaledU);
+ const floorV = Math.floor(scaledV);
+ let nearest = Infinity;
+ let second = Infinity;
+ for (let offsetV = -1; offsetV <= 1; offsetV++) {
+ for (let offsetU = -1; offsetU <= 1; offsetU++) {
+ const cellU = floorU + offsetU;
+ const cellV = floorV + offsetV;
+ const hash = hashCell(wrapCell(cellU, cells), wrapCell(cellV, cells), seed);
+ const pointU = cellU + (hash & 0xffff) / 65536;
+ const pointV = cellV + (hash >>> 16) / 65536;
+ const distance = Math.hypot(pointU - scaledU, pointV - scaledV);
+ if (distance < nearest) {
+ second = nearest;
+ nearest = distance;
+ } else if (distance < second) {
+ second = distance;
+ }
+ }
+ }
+ return { nearest, second };
+}
+
+function unitHash(cellX, cellY, seed) {
+ return hashCell(cellX, cellY, seed) / 4294967296;
+}
+
+/** Laid-out courses of blocks with a running bond: which block a point is in and how far it is from the joint. */
+function blockLayout(positionU, positionV, columns, rows, jointWidth, offset) {
+ const scaledV = positionV * rows;
+ const row = Math.floor(scaledV);
+ const scaledU = positionU * columns + (row % 2 === 1 ? offset : 0);
+ const column = Math.floor(scaledU);
+ const fractionU = scaledU - column;
+ const fractionV = scaledV - row;
+ const jointU = Math.min(fractionU, 1 - fractionU) / columns;
+ const jointV = Math.min(fractionV, 1 - fractionV) / rows;
+ const edge = Math.min(jointU, jointV);
+ return { row, column: wrapCell(column, columns), body: smoothStep(jointWidth * 0.5, jointWidth * 1.5, edge) };
+}
+
+function woodGrain(positionU, positionV, seed, rings) {
+ // Long, gentle waves: real grain drifts sideways far less than it runs along the board.
+ const warp = fractalNoise(positionU, positionV, 2, 1, seed, 3) * 1.6;
+ const ringPosition = positionU * rings + warp;
+ const ring = ringPosition - Math.floor(ringPosition);
+ // Slow growth across the ring, then a quick dark edge, softened so it does not read as a drawn line.
+ const earlyLate = ring < 0.85 ? ring / 0.85 : (1 - ring) / 0.15;
+ const fibre = fractalNoise(positionU, positionV, 128, 2, seed + 7, 3) * 0.5 + 0.5;
+ const pore = fractalNoise(positionU, positionV, 256, 8, seed + 11, 2) * 0.5 + 0.5;
+ return { tone: clampUnit(earlyLate * 0.45 + fibre * 0.4 + pore * 0.15), fibre };
+}
+
+// Each sampler returns tone (0 picks the first colour, 1 the second), height, roughness and metal, all 0 to 1.
+const PATTERN_SAMPLERS = {
+ noise(positionU, positionV, seed, count) {
+ const value = fractalNoise(positionU, positionV, count, count, seed, 6) * 0.5 + 0.5;
+ return { tone: smoothStep(0.25, 0.75, value), height: value, roughness: 0.75 + value * 0.25, metal: 1 };
+ },
+ wood(positionU, positionV, seed, count) {
+ const { tone, fibre } = woodGrain(positionU, positionV, seed, count);
+ return { tone, height: tone * 0.5 + fibre * 0.5, roughness: 0.75 + (1 - tone) * 0.25, metal: 1 };
+ },
+ planks(positionU, positionV, seed, count) {
+ const scaled = positionU * count;
+ const plank = Math.floor(scaled);
+ const fraction = scaled - plank;
+ const stagger = unitHash(plank, 0, seed);
+ const length = positionV + stagger;
+ const endJoint = Math.min(length - Math.floor(length), 1 - (length - Math.floor(length)));
+ const edge = Math.min(Math.min(fraction, 1 - fraction) / count, endJoint);
+ const body = smoothStep(0.0015, 0.005, edge);
+ const shift = unitHash(wrapCell(plank, count), 1, seed);
+ const { tone, fibre } = woodGrain(positionU, wrapUnit(positionV + shift), seed + wrapCell(plank, count) * 17, 12);
+ const plankTone = clampUnit(tone * 0.8 + unitHash(wrapCell(plank, count), 2, seed) * 0.2);
+ return { tone: plankTone * body, height: (0.55 + fibre * 0.25) * body, roughness: 0.75 + (1 - plankTone) * 0.2 + (1 - body) * 0.05, metal: 1 };
+ },
+ bricks(positionU, positionV, seed, count) {
+ const rows = count * 2;
+ const { row, column, body } = blockLayout(positionU, positionV, count, rows, 0.006, 0.5);
+ const shade = unitHash(column, wrapCell(row, rows), seed);
+ const surface = fractalNoise(positionU, positionV, 24, 24, seed + 3, 4) * 0.5 + 0.5;
+ const tone = clampUnit(shade * 0.6 + surface * 0.4);
+ return { tone, joint: 1 - body, height: body * (0.75 + surface * 0.25), roughness: 0.85 + surface * 0.15, metal: 1 };
+ },
+ tiles(positionU, positionV, seed, count) {
+ const { row, column, body } = blockLayout(positionU, positionV, count, count, 0.004, 0);
+ const shade = unitHash(column, wrapCell(row, count), seed);
+ const surface = fractalNoise(positionU, positionV, 8, 8, seed + 5, 3) * 0.5 + 0.5;
+ const tone = clampUnit(0.75 + shade * 0.2 + surface * 0.05);
+ return { tone: tone * body, height: body * (0.9 + surface * 0.1), roughness: body > 0.5 ? 0.45 + surface * 0.15 : 1, metal: 1 };
+ },
+ marble(positionU, positionV, seed, count) {
+ const cloud = fractalNoise(positionU, positionV, count, count, seed, 5) * 0.5 + 0.5;
+ const veins = ridgedNoise(positionU, positionV, count, count, seed + 11, 4);
+ const vein = smoothStep(0.72, 0.95, veins);
+ return { tone: clampUnit(0.75 + cloud * 0.25 - vein), height: 0.5, roughness: 0.3 + vein * 0.2, metal: 1 };
+ },
+ stone(positionU, positionV, seed, count) {
+ const ridges = ridgedNoise(positionU, positionV, count, count, seed, 5);
+ const { nearest, second } = cellularNoise(positionU, positionV, count * 2, seed + 9);
+ const crack = smoothStep(0, 0.07, second - nearest);
+ const value = clampUnit(ridges * 0.8 + 0.1);
+ return { tone: value * (0.6 + crack * 0.4), height: value * 0.7 + crack * 0.3, roughness: 0.85 + (1 - value) * 0.15, metal: 1 };
+ },
+ concrete(positionU, positionV, seed, count) {
+ const cloud = fractalNoise(positionU, positionV, count, count, seed, 6) * 0.5 + 0.5;
+ const { nearest } = cellularNoise(positionU, positionV, count * 16, seed + 13);
+ const pit = smoothStep(0.02, 0.12, nearest);
+ return { tone: clampUnit(cloud * 0.9 + 0.05) * (0.7 + pit * 0.3), height: 0.5 + (pit - 1) * 0.4 + cloud * 0.1, roughness: 0.85 + cloud * 0.15, metal: 1 };
+ },
+ metal(positionU, positionV, seed, count) {
+ const streak = fractalNoise(positionU, positionV, count * 16, 2, seed, 4) * 0.5 + 0.5;
+ const blotch = fractalNoise(positionU, positionV, 4, 4, seed + 3, 3) * 0.5 + 0.5;
+ return { tone: clampUnit(streak * 0.7 + blotch * 0.3), height: streak * 0.25, roughness: 0.55 + streak * 0.35 + blotch * 0.1, metal: 1 };
+ },
+ rust(positionU, positionV, seed, count) {
+ const patches = fractalNoise(positionU, positionV, count, count, seed, 6) * 0.5 + 0.5;
+ const flakes = fractalNoise(positionU, positionV, count * 16, count * 16, seed + 3, 3) * 0.5 + 0.5;
+ const rusted = smoothStep(0.42, 0.58, patches + (flakes - 0.5) * 0.15);
+ return { tone: rusted * (0.5 + flakes * 0.5), height: rusted * (0.4 + flakes * 0.6), roughness: 0.45 + rusted * 0.55, metal: 1 - rusted };
+ },
+ fabric(positionU, positionV, seed, count) {
+ const threads = count * 16;
+ const warpThread = Math.sin(positionU * threads * Math.PI * 2) * 0.5 + 0.5;
+ const weftThread = Math.sin(positionV * threads * Math.PI * 2) * 0.5 + 0.5;
+ const cell = Math.floor(positionU * threads) + Math.floor(positionV * threads);
+ const over = cell % 2 === 0 ? warpThread : weftThread;
+ const slub = fractalNoise(positionU, positionV, 16, 16, seed, 3) * 0.5 + 0.5;
+ return { tone: clampUnit(over * 0.5 + slub * 0.5), height: over, roughness: 0.9 + slub * 0.1, metal: 1 };
+ },
+};
+
+function wrapUnit(value) {
+ return value - Math.floor(value);
+}
+
+// Colours are linear RGB, as recipe colours are. `size` is metres per repeat of the texture.
+const PATTERN_DEFAULTS = {
+ noise: { colors: [[0.2, 0.2, 0.2], [0.7, 0.7, 0.7]], size: 1, count: 4, bump: 0.5 },
+ wood: { colors: [[0.16, 0.07, 0.025], [0.5, 0.27, 0.11]], size: 0.6, count: 12, bump: 0.4 },
+ planks: { colors: [[0.12, 0.055, 0.02], [0.46, 0.25, 0.1]], size: 1, count: 6, bump: 0.8 },
+ bricks: { colors: [[0.33, 0.1, 0.06], [0.52, 0.2, 0.12], [0.45, 0.42, 0.38]], size: 1, count: 4, bump: 1 },
+ tiles: { colors: [[0.32, 0.32, 0.31], [0.75, 0.75, 0.72]], size: 1, count: 4, bump: 0.8 },
+ marble: { colors: [[0.2, 0.2, 0.22], [0.85, 0.84, 0.82]], size: 1, count: 3, bump: 0 },
+ stone: { colors: [[0.09, 0.085, 0.08], [0.42, 0.4, 0.37]], size: 1.5, count: 4, bump: 1.4 },
+ concrete: { colors: [[0.24, 0.24, 0.23], [0.5, 0.5, 0.48]], size: 2, count: 4, bump: 0.4 },
+ metal: { colors: [[0.5, 0.5, 0.52], [0.8, 0.8, 0.82]], size: 0.5, count: 4, bump: 0.15 },
+ rust: { colors: [[0.55, 0.55, 0.56], [0.22, 0.07, 0.025]], size: 1, count: 4, bump: 0.7 },
+ fabric: { colors: [[0.2, 0.2, 0.25], [0.45, 0.45, 0.55]], size: 0.25, count: 4, bump: 0.5 },
+};
+
+const RESOLUTIONS = [256, 512, 1024];
+const MAX_COUNT = 64;
+
+function patternError(message) {
+ return new RangeError(`Material pattern ${message}`);
+}
+
+function checkedColors(value, type) {
+ const fieldHint = 'colors must be two linear RGB colours from 0 to 1 (three for bricks: the third is the mortar)';
+ const expected = PATTERN_DEFAULTS[type].colors.length;
+ if (!Array.isArray(value) || (value.length !== 2 && value.length !== expected)) throw patternError(fieldHint);
+ for (const entry of value) {
+ if (!Array.isArray(entry) || entry.length !== 3 || entry.some(component => !Number.isFinite(component) || component < 0 || component > 1)) throw patternError(fieldHint);
+ }
+ return value.map(entry => [...entry]);
+}
+
+function checkedNumber(value, name, minimum, maximum) {
+ if (!Number.isFinite(value) || value < minimum || value > maximum) throw patternError(`${name} must be a number from ${minimum} to ${maximum}.`);
+ return value;
+}
+
+/** Validate a recipe pattern and fill in its defaults. A normalized pattern normalizes to itself. */
+export function normalizeMaterialPattern(value) {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw patternError(`must be an object such as { "type": "wood" }. Types: ${MATERIAL_PATTERN_TYPES.join(', ')}.`);
+ const known = ['type', 'colors', 'size', 'count', 'bump', 'seed', 'axis', 'resolution'];
+ for (const key of Object.keys(value)) {
+ if (!known.includes(key)) throw patternError(`does not take ${key}. Fields: ${known.join(', ')}.`);
+ }
+ if (!Object.hasOwn(PATTERN_DEFAULTS, value.type ?? '')) throw patternError(`type must be one of ${MATERIAL_PATTERN_TYPES.join(', ')}.`);
+ const defaults = PATTERN_DEFAULTS[value.type];
+ const count = value.count ?? defaults.count;
+ if (!Number.isInteger(count) || count < 1 || count > MAX_COUNT) throw patternError(`count must be a whole number from 1 to ${MAX_COUNT}.`);
+ const seed = value.seed ?? 1;
+ if (!Number.isInteger(seed) || seed < 0 || seed > 0x7fffffff) throw patternError('seed must be a nonnegative whole number.');
+ const axis = value.axis ?? 'y';
+ if (!['x', 'y', 'z'].includes(axis)) throw patternError('axis must be x, y or z: the object axis the grain runs along.');
+ const resolution = value.resolution ?? 512;
+ if (!RESOLUTIONS.includes(resolution)) throw patternError(`resolution must be one of ${RESOLUTIONS.join(', ')}.`);
+ return {
+ type: value.type,
+ colors: value.colors === undefined ? defaults.colors.map(entry => [...entry]) : checkedColors(value.colors, value.type),
+ size: checkedNumber(value.size ?? defaults.size, 'size', 0.01, 100),
+ count,
+ bump: checkedNumber(value.bump ?? defaults.bump, 'bump', 0, 4),
+ seed,
+ axis,
+ resolution,
+ };
+}
+
+function linearToSrgbByte(value) {
+ const encoded = value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
+ return Math.round(clampUnit(encoded) * 255);
+}
+
+function createImage(data, width, height) {
+ // Browsers upload ImageData directly; Node only reads the pixels, as tests and tools do.
+ return typeof ImageData === 'function' ? new ImageData(data, width, height) : { width, height, data };
+}
+
+/** Bake a normalized pattern into { map, normalMap, metallicRoughnessMap } texture descriptors. Deterministic. */
+export function bakeMaterialPattern(pattern) {
+ const { resolution, type, seed, count, colors, bump, size } = pattern;
+ const sampler = PATTERN_SAMPLERS[type];
+ const pixelCount = resolution * resolution;
+ const heights = new Float32Array(pixelCount);
+ const colorData = new Uint8ClampedArray(pixelCount * 4);
+ const surfaceData = new Uint8ClampedArray(pixelCount * 4);
+ const [firstColor, secondColor, jointColor] = colors;
+ for (let row = 0; row < resolution; row++) {
+ for (let column = 0; column < resolution; column++) {
+ const pixel = row * resolution + column;
+ const sample = sampler((column + 0.5) / resolution, (row + 0.5) / resolution, seed, count);
+ heights[pixel] = sample.height;
+ const tone = clampUnit(sample.tone);
+ // Bricks have a third colour for the mortar.
+ const joint = jointColor ? sample.joint ?? 0 : 0;
+ const offset = pixel * 4;
+ for (let channel = 0; channel < 3; channel++) {
+ const body = firstColor[channel] + (secondColor[channel] - firstColor[channel]) * tone;
+ colorData[offset + channel] = linearToSrgbByte(joint > 0 ? body + (jointColor[channel] - body) * joint : body);
+ }
+ colorData[offset + 3] = 255;
+ surfaceData[offset] = 255;
+ surfaceData[offset + 1] = Math.round(clampUnit(sample.roughness) * 255);
+ surfaceData[offset + 2] = Math.round(clampUnit(sample.metal) * 255);
+ surfaceData[offset + 3] = 255;
+ }
+ }
+ const normalData = new Uint8ClampedArray(pixelCount * 4);
+ // Height differences are per texel; scale them so a bump of 1 reads the same at any resolution.
+ const slopeScale = bump * resolution / 64;
+ for (let row = 0; row < resolution; row++) {
+ const rowAbove = (row + 1) % resolution;
+ const rowBelow = (row + resolution - 1) % resolution;
+ for (let column = 0; column < resolution; column++) {
+ const columnRight = (column + 1) % resolution;
+ const columnLeft = (column + resolution - 1) % resolution;
+ const slopeU = (heights[row * resolution + columnRight] - heights[row * resolution + columnLeft]) * slopeScale;
+ const slopeV = (heights[rowAbove * resolution + column] - heights[rowBelow * resolution + column]) * slopeScale;
+ const length = Math.hypot(slopeU, slopeV, 1);
+ const offset = (row * resolution + column) * 4;
+ normalData[offset] = Math.round((-slopeU / length * 0.5 + 0.5) * 255);
+ normalData[offset + 1] = Math.round((-slopeV / length * 0.5 + 0.5) * 255);
+ normalData[offset + 2] = Math.round((1 / length * 0.5 + 0.5) * 255);
+ normalData[offset + 3] = 255;
+ }
+ }
+ return {
+ map: { image: createImage(colorData, resolution, resolution), colorSpace: 'srgb' },
+ normalMap: { image: createImage(normalData, resolution, resolution), colorSpace: 'linear' },
+ metallicRoughnessMap: { image: createImage(surfaceData, resolution, resolution), colorSpace: 'linear' },
+ boxMapScale: 1 / size,
+ boxMapAxis: ['x', 'y', 'z'].indexOf(pattern.axis),
+ };
+}
+
+const bakedPatterns = new Map();
+const MAX_BAKED_PATTERNS = 32;
+// The renderer reads these fields for every part on every update, so a pattern object remembers its result. It also
+// keeps the same descriptors alive for as long as a material holds them, because a renderer rejects changed textures.
+const bakedByPatternObject = new WeakMap();
+
+/** The baked textures of a pattern, shared by every material with the same definition. */
+export function materialPatternTextures(pattern) {
+ const remembered = bakedByPatternObject.get(pattern);
+ if (remembered) return remembered;
+ const key = JSON.stringify(pattern);
+ let baked = bakedPatterns.get(key);
+ if (baked) {
+ bakedPatterns.delete(key);
+ } else {
+ baked = bakeMaterialPattern(pattern);
+ if (bakedPatterns.size >= MAX_BAKED_PATTERNS) bakedPatterns.delete(bakedPatterns.keys().next().value);
+ }
+ bakedPatterns.set(key, baked);
+ bakedByPatternObject.set(pattern, baked);
+ return baked;
+}
+
+export { PATTERN_DEFAULTS };
diff --git a/src/renderer.js b/src/renderer.js
index 72c013ac..e1978f55 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -100,7 +100,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(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), ...splatBatchState(material)];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...splatBatchState(material)];
}
function validateAlphaMaterial(material) {
@@ -389,7 +389,7 @@ export class Renderer67 {
for (const group of groups) {
const geometry = group[0].geometry;
if (geometry.uvs && geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
- if (hasMaterialMap(group[0].material) && !geometry.uvs) throw new Error('Textured geometry requires UV channel 0.');
+ if (hasMaterialMap(group[0].material) && !geometry.uvs && !group[0].material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');
for (const coordinate of geometry.uvs ?? []) {
if (!Number.isFinite(coordinate)) throw new Error('Geometry UVs must be finite.');
}
@@ -404,7 +404,7 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...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', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['boxMapScale', 'boxMapAxis', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...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', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -626,7 +626,7 @@ export class Renderer67 {
context.enableVertexAttribArray(13);
context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);
} else {
- if (hasMaterialMap(parts[0].material)) throw new Error('Textured geometry requires UV channel 0.');
+ if (hasMaterialMap(parts[0].material) && !parts[0].material.boxMapScale) throw new Error('Textured geometry requires UV channel 0.');
context.disableVertexAttribArray(13);
// (-1, -1) marks "no UVs": grass wind then bends by local height instead of by blade position.
context.vertexAttrib2f(13, -1, -1);
@@ -1414,6 +1414,8 @@ 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.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);
+ this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);
this.bindSplat(batch.splat);
}
this.context.bindVertexArray(batch.vertexArray);
diff --git a/src/shaders.js b/src/shaders.js
index 45ce7db6..652826fd 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -117,6 +117,9 @@ out vec4 shadowPosition;
out vec2 textureUV;
out vec3 vertexTint;
flat out vec3 emissionColor;
+out vec3 boxPosition;
+out vec3 boxNormal;
+flat out mat3 boxNormalMatrix;
${skinningShader}
${morphingShader}
${windShader}
@@ -135,6 +138,10 @@ void main() {
vec3 localNormal = morphedNormal(normal);
vec3 deformedNormal = skinEnabled > 0.5 ? transpose(inverse(mat3(deformation))) * localNormal : localNormal;
worldNormal = normalize(instanceNormal * deformedNormal);
+ // Metres along the object's own axes, so a pattern follows a moving node and is not stretched by its scale.
+ boxPosition = morphedPosition(position) * vec3(length(instanceMatrix[0].xyz), length(instanceMatrix[1].xyz), length(instanceMatrix[2].xyz));
+ boxNormal = deformedNormal;
+ boxNormalMatrix = instanceNormal;
baseColor = instanceColor;
textureUV = uv;
vertexTint = vertexColor;
@@ -369,6 +376,11 @@ uniform float hasOcclusionMap;
uniform float hasEmissiveMap;
uniform vec2 normalScale;
uniform float occlusionStrength;
+in vec3 boxPosition;
+in vec3 boxNormal;
+flat in mat3 boxNormalMatrix;
+uniform float boxMapScale;
+uniform int boxMapAxis;
uniform vec4 materialMoss;
uniform float hdrEnabled;
uniform float alphaMode;
@@ -467,6 +479,41 @@ vec3 toneMap(vec3 color) {
return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);
}
+// Box projection: three texture lookups along the object axes, blended by the normal, so a surface needs no UVs.
+// Swapping two axes makes the texture's V direction, and with it a grain, run along the chosen axis.
+vec3 boxAxisSwap(vec3 value) {
+ if (boxMapAxis == 0) return value.yxz;
+ if (boxMapAxis == 2) return value.xzy;
+ return value;
+}
+
+vec3 boxWeights(vec3 direction) {
+ vec3 weights = pow(abs(direction), vec3(8.0));
+ return weights / max(weights.x + weights.y + weights.z, 1e-5);
+}
+
+vec4 sampleBox(sampler2D source) {
+ vec3 coordinates = boxAxisSwap(boxPosition) * boxMapScale;
+ vec3 weights = boxWeights(boxAxisSwap(normalize(boxNormal)));
+ return texture(source, coordinates.zy) * weights.x + texture(source, coordinates.xz) * weights.y + texture(source, coordinates.xy) * weights.z;
+}
+
+// Whiteout blend of the three tangent-space normals, done in object space and then moved to world space.
+vec3 boxMappedNormal(vec3 normal) {
+ vec3 coordinates = boxAxisSwap(boxPosition) * boxMapScale;
+ vec3 objectNormal = boxAxisSwap(normalize(boxNormal));
+ vec3 weights = boxWeights(objectNormal);
+ vec3 sampleX = texture(normalMap, coordinates.zy).xyz * 2.0 - 1.0;
+ vec3 sampleY = texture(normalMap, coordinates.xz).xyz * 2.0 - 1.0;
+ vec3 sampleZ = texture(normalMap, coordinates.xy).xyz * 2.0 - 1.0;
+ vec3 blendX = vec3(sampleX.xy * normalScale + objectNormal.zy, abs(sampleX.z) * objectNormal.x);
+ vec3 blendY = vec3(sampleY.xy * normalScale + objectNormal.xz, abs(sampleY.z) * objectNormal.y);
+ vec3 blendZ = vec3(sampleZ.xy * normalScale + objectNormal.xy, abs(sampleZ.z) * objectNormal.z);
+ vec3 blended = blendX.zyx * weights.x + blendY.xzy * weights.y + blendZ * weights.z;
+ vec3 world = normalize(boxNormalMatrix * boxAxisSwap(blended));
+ return dot(world, normal) < 0.0 ? -world : world;
+}
+
vec3 mappedNormal(vec3 normal) {
vec3 positionX = dFdx(worldPosition);
vec3 positionY = dFdy(worldPosition);
@@ -529,13 +576,13 @@ void main() {
// canopy, so the back face keeps it instead of flipping to point into the crown.
bool canopyShaded = surface.w == 4.0 || surface.w == 7.0;
if (doubleSided > 0.5 && !gl_FrontFacing && !canopyShaded) normal = -normal;
- if (hasNormalMap > 0.5) normal = mappedNormal(normal);
+ if (hasNormalMap > 0.5) normal = boxMapScale > 0.0 ? boxMappedNormal(normal) : mappedNormal(normal);
vec3 viewDirection = normalize(eye - worldPosition);
vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));
if (splatEnabled < 0.5) color *= vertexTint;
float textureAlpha = 1.0;
if (hasBaseMap > 0.5) {
- vec4 sampledBase = texture(baseMap, textureUV);
+ vec4 sampledBase = boxMapScale > 0.0 ? sampleBox(baseMap) : texture(baseMap, textureUV);
color *= sampledBase.rgb;
textureAlpha = sampledBase.a;
}
@@ -554,7 +601,7 @@ void main() {
roughness = armorSurface.y;
}
if (hasMetallicRoughnessMap > 0.5) {
- vec4 sampled = texture(metallicRoughnessMap, textureUV);
+ vec4 sampled = boxMapScale > 0.0 ? sampleBox(metallicRoughnessMap) : texture(metallicRoughnessMap, textureUV);
metallic *= sampled.b;
roughness *= sampled.g;
}
diff --git a/tests/material-patterns.test.js b/tests/material-patterns.test.js
new file mode 100644
index 00000000..658556ed
--- /dev/null
+++ b/tests/material-patterns.test.js
@@ -0,0 +1,157 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { bakeMaterialPattern, cellularNoise, fractalNoise, gradientNoise, materialPatternTextures, normalizeMaterialPattern, PATTERN_DEFAULTS, ridgedNoise } from '../src/material-patterns.js';
+import { MATERIAL_PATTERN_TYPES, MAX_MATERIAL_PATTERNS } from '../src/agent-scene-capabilities.js';
+import { createAgentScene } from '../src/agent-scene.js';
+
+const baseScene = materials => ({
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'block', type: 'box', bevel: 0 }],
+ materials,
+ nodes: [{ id: 'part', geometry: 'block', material: materials[0].id }],
+});
+
+function bake(type, overrides = {}) {
+ return bakeMaterialPattern(normalizeMaterialPattern({ type, resolution: 256, ...overrides }));
+}
+
+function meanColumnStep(image, firstColumn, secondColumn) {
+ let total = 0;
+ for (let row = 0; row < image.height; row++) {
+ for (let channel = 0; channel < 3; channel++) {
+ const first = image.data[(row * image.width + firstColumn) * 4 + channel];
+ const second = image.data[(row * image.width + secondColumn) * 4 + channel];
+ total += Math.abs(first - second);
+ }
+ }
+ return total / (image.height * 3);
+}
+
+function meanRowStep(image, firstRow, secondRow) {
+ let total = 0;
+ for (let column = 0; column < image.width; column++) {
+ for (let channel = 0; channel < 3; channel++) {
+ const first = image.data[(firstRow * image.width + column) * 4 + channel];
+ const second = image.data[(secondRow * image.width + column) * 4 + channel];
+ total += Math.abs(first - second);
+ }
+ }
+ return total / (image.width * 3);
+}
+
+test('noise is periodic over the unit square', () => {
+ for (const [positionU, positionV] of [[0.13, 0.71], [0.5, 0.25], [0.999, 0.001]]) {
+ assert.ok(Math.abs(gradientNoise(positionU, positionV, 4, 4, 3) - gradientNoise(positionU + 1, positionV, 4, 4, 3)) < 1e-9);
+ assert.ok(Math.abs(fractalNoise(positionU, positionV, 3, 2, 3) - fractalNoise(positionU, positionV + 1, 3, 2, 3)) < 1e-9);
+ assert.ok(Math.abs(ridgedNoise(positionU, positionV, 3, 3, 3) - ridgedNoise(positionU + 1, positionV + 1, 3, 3, 3)) < 1e-9);
+ assert.ok(Math.abs(cellularNoise(positionU, positionV, 5, 3).nearest - cellularNoise(positionU + 1, positionV, 5, 3).nearest) < 1e-9);
+ }
+});
+
+test('gradient noise spreads over its range and stays bounded', () => {
+ let minimum = Infinity;
+ let maximum = -Infinity;
+ for (let sample = 0; sample < 4000; sample++) {
+ const value = gradientNoise((sample * 0.6180339) % 1, (sample * 0.7548776) % 1, 8, 8, 5);
+ minimum = Math.min(minimum, value);
+ maximum = Math.max(maximum, value);
+ }
+ assert.ok(minimum < -0.5 && maximum > 0.5, `${minimum} to ${maximum}`);
+ assert.ok(minimum >= -1.2 && maximum <= 1.2, `${minimum} to ${maximum}`);
+});
+
+test('every pattern tiles: the step across the seam is like any other step', () => {
+ for (const type of MATERIAL_PATTERN_TYPES) {
+ const { image } = bake(type).map;
+ let largestInsideU = 0;
+ let largestInsideV = 0;
+ for (let index = 0; index < image.width - 1; index++) {
+ largestInsideU = Math.max(largestInsideU, meanColumnStep(image, index, index + 1));
+ largestInsideV = Math.max(largestInsideV, meanRowStep(image, index, index + 1));
+ }
+ const seamU = meanColumnStep(image, image.width - 1, 0);
+ const seamV = meanRowStep(image, image.height - 1, 0);
+ assert.ok(seamU <= largestInsideU + 1, `${type} across U: ${seamU} vs ${largestInsideU}`);
+ assert.ok(seamV <= largestInsideV + 1, `${type} across V: ${seamV} vs ${largestInsideV}`);
+ }
+});
+
+test('patterns are deterministic and change with the seed', () => {
+ for (const type of MATERIAL_PATTERN_TYPES) {
+ const first = bake(type).map.image.data;
+ const again = bake(type).map.image.data;
+ assert.deepEqual(first, again, type);
+ const reseeded = bake(type, { seed: 2 }).map.image.data;
+ assert.notDeepEqual(first, reseeded, type);
+ }
+});
+
+test('bump 0 gives a flat normal map, and rust is less metallic where it has rusted', () => {
+ const flat = bake('stone', { bump: 0 }).normalMap.image.data;
+ for (let offset = 0; offset < 4000; offset += 4) {
+ assert.deepEqual([flat[offset], flat[offset + 1], flat[offset + 2]], [128, 128, 255]);
+ }
+ const { data } = bake('rust').metallicRoughnessMap.image;
+ const metalValues = new Set();
+ for (let offset = 2; offset < data.length; offset += 4 * 97) metalValues.add(data[offset]);
+ assert.ok(Math.min(...metalValues) < 40 && Math.max(...metalValues) > 200);
+});
+
+test('a normalized pattern normalizes to itself and bad fields say what to pass', () => {
+ assert.deepEqual(Object.keys(PATTERN_DEFAULTS).sort(), [...MATERIAL_PATTERN_TYPES].sort());
+ const normalized = normalizeMaterialPattern({ type: 'bricks', size: 2 });
+ assert.deepEqual(normalizeMaterialPattern(normalized), normalized);
+ assert.throws(() => normalizeMaterialPattern({ type: 'plasma' }), /type must be one of noise, wood/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', colour: [] }), /does not take colour/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', size: 0 }), /size must be a number/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', colors: [[0, 0, 2], [1, 1, 1]] }), /colors must be/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', colors: [[0, 0, 0], [1, 1, 1], [1, 1, 1]] }), /colors must be/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', resolution: 300 }), /resolution must be one of/);
+ assert.throws(() => normalizeMaterialPattern({ type: 'wood', axis: 'w' }), /axis must be/);
+ assert.equal(normalizeMaterialPattern({ type: 'bricks', colors: [[0, 0, 0], [1, 1, 1], [0.5, 0.5, 0.5]] }).colors.length, 3);
+});
+
+test('recipe materials carry patterns as textures without needing UVs', () => {
+ const scene = createAgentScene(baseScene([{ id: 'oak', pattern: { type: 'wood', size: 0.5, axis: 'x' }, roughness: 0.8 }]));
+ const [part] = scene.parts;
+ assert.equal(part.geometry.uvs, undefined);
+ assert.equal(part.material.boxMapScale, 2);
+ assert.equal(part.material.boxMapAxis, 0);
+ assert.equal(part.material.map.colorSpace, 'srgb');
+ assert.equal(part.material.normalMap.colorSpace, 'linear');
+ assert.equal(part.material.map, part.material.map);
+ assert.deepEqual(Array.from(part.material.color), [1, 1, 1]);
+ const exported = scene.exportRecipe().materials[0];
+ assert.equal(exported.pattern.type, 'wood');
+ assert.equal(exported.pattern.size, 0.5);
+ const reloaded = createAgentScene({ ...baseScene([exported]) });
+ assert.equal(reloaded.parts[0].material.map, part.material.map);
+});
+
+test('a material without a pattern is unchanged', () => {
+ const scene = createAgentScene(baseScene([{ id: 'plain' }]));
+ const { material } = scene.parts[0];
+ assert.deepEqual(Array.from(material.color), [0.5, 0.5, 0.5]);
+ assert.equal(material.map, undefined);
+ assert.equal(material.boxMapScale, undefined);
+ assert.equal(scene.exportRecipe().materials[0].pattern, undefined);
+});
+
+test('patterns need the surface tag and a scene holds a bounded number', () => {
+ assert.throws(() => createAgentScene(baseScene([{ id: 'glow', tag: 'unlit', pattern: { type: 'wood' } }])), /needs the surface tag/);
+ const tooMany = Array.from({ length: MAX_MATERIAL_PATTERNS + 1 }, (_, index) => ({ id: `material-${index}`, pattern: { type: 'wood', seed: index } }));
+ assert.throws(() => createAgentScene(baseScene(tooMany)), /at most 16 different material patterns/);
+ const shared = Array.from({ length: MAX_MATERIAL_PATTERNS + 1 }, (_, index) => ({ id: `material-${index}`, pattern: { type: 'wood' }, color: [index / 17, 1, 1] }));
+ assert.doesNotThrow(() => createAgentScene(baseScene(shared)));
+});
+
+test('changing a pattern rebuilds the renderer resources, and changing its tint does not', () => {
+ const scene = createAgentScene(baseScene([{ id: 'oak', pattern: { type: 'wood' } }]));
+ const before = scene.topologyRevision;
+ scene.apply([{ type: 'set-material', id: 'oak', color: [0.5, 0.5, 0.5] }], { expectedRevision: scene.revision });
+ assert.equal(scene.topologyRevision, before);
+ assert.deepEqual(Array.from(scene.parts[0].material.color), [0.5, 0.5, 0.5]);
+ scene.apply([{ type: 'set-material', id: 'oak', pattern: { type: 'bricks' } }], { expectedRevision: scene.revision });
+ assert.equal(scene.topologyRevision, before + 1);
+ assert.equal(scene.parts[0].material.map, materialPatternTextures(scene.exportRecipe().materials[0].pattern).map);
+});