Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Let agent recipes author liquid, foam and blended materials

Nguyen Xuan An95ad42d2a680
diff --git a/docs/agent-scene.md b/docs/agent-scene.md
index 811ddd17..03ca9223 100644
--- a/docs/agent-scene.md
+++ b/docs/agent-scene.md
@@ -77,16 +77,21 @@ 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`, and optional `emissiveColor`.
-The defaults are `surface`, `[0.5, 0.5, 0.5]`, `0`, `0.5`, and `0`.
-The tag can be `surface` or `unlit` and remains fixed during editing.
+Materials contain `id`, `tag`, `color`, `metallic`, `roughness`, `emission`, optional `emissiveColor`, `opacity`, `alphaMode` and `doubleSided`.
+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.
+Set liquid optics with `environment.liquid`: `thickness`, `ior`, `refraction`, `scattering`, `foamOpacity` and `foamSoftness`.
Colors use linear RGB.
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 procedural material tags are outside this version.
+Textures and the other procedural material tags are outside this version.
Nodes contain `id`, optional `label`, `parent`, `translation`, `rotation`, and `scale`.
Mesh nodes also require both `geometry` and `material` resource IDs.
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index c46881f0..62247f57 100644
--- a/scripts/mcp-server.mjs
+++ b/scripts/mcp-server.mjs
@@ -32,7 +32,19 @@ const materialFields = {
roughness: unit.optional(),
emission: nonnegative.optional().describe('Emission multiplier. Backend checks Float32 radiance products.'),
emissiveColor: z.tuple([nonnegative, nonnegative, nonnegative]).optional().describe('Independent linear RGB emission color.'),
+ opacity: unit.optional().describe('Surface opacity. Any value below one draws the material blended (glass, windows, visors).'),
+ alphaMode: z.enum(['opaque', 'blend']).optional().describe('blend draws after opaque geometry, sorted back to front.'),
+ doubleSided: z.boolean().optional().describe('Draw and light both faces (thin sheets, leaves, cloth).'),
};
+const materialTag = z.enum(['surface', 'unlit', 'liquid', 'foam']).optional().describe('liquid refracts what lies behind it and absorbs by thickness: color is the light one metre lets through. foam is soft blended whitewater.');
+const liquidOptics = z.strictObject({
+ thickness: z.number().min(0).max(100).optional().describe('Metres of liquid where it faces the camera.'),
+ ior: z.number().min(1).max(3).optional(),
+ refraction: z.number().min(0).max(4).optional(),
+ scattering: z.number().min(0).max(10).optional(),
+ foamOpacity: unit.optional(),
+ foamSoftness: unit.optional(),
+});
const cameraFields = {
eye: vector3.optional().describe('Camera position in world coordinates.'),
target: vector3.optional().describe('World point toward which the camera looks.'),
@@ -76,6 +88,7 @@ const environment = z.strictObject({
fogColor: color.optional(),
fogDensity: bounded(0, 10).optional(),
volumeFog: volumeFog.optional().describe('Bounded depth-clipped directional scattering; requires HDR support.'),
+ liquid: liquidOptics.optional().describe('Optics for materials tagged liquid or foam.'),
});
const effects = z.strictObject({
exposure: bounded(0.01, 16).optional(),
@@ -140,7 +153,7 @@ const recipe = z.strictObject({
format: z.literal('67js.scene'),
schemaVersion: z.literal(1),
geometries: z.array(geometry).max(256),
- materials: z.array(z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields })).max(256),
+ materials: z.array(z.strictObject({ id: identifier, tag: materialTag, ...materialFields })).max(256),
nodes: z.array(nodeRecord).max(4096),
camera: z.strictObject(cameraFields).optional(),
environment: environment.optional(),
@@ -180,7 +193,7 @@ const operation = z.discriminatedUnion('type', [
z.strictObject({ type: z.literal('remove-node'), id: identifier, recursive: z.boolean().optional().describe('Remove descendants too. Defaults to false; dangling children reject the batch.') }),
z.strictObject({ type: z.literal('add-geometry'), geometry }),
z.strictObject({ type: z.literal('remove-geometry'), id: identifier }),
- z.strictObject({ type: z.literal('add-material'), material: z.strictObject({ id: identifier, tag: z.enum(['surface', 'unlit']).optional(), ...materialFields }) }),
+ z.strictObject({ type: z.literal('add-material'), material: z.strictObject({ id: identifier, tag: materialTag, ...materialFields }) }),
z.strictObject({ type: z.literal('remove-material'), id: identifier }),
]);
const sessionFields = { sessionId: z.uuid().describe('Session UUID returned by scene_create.') };
diff --git a/src/agent-look.js b/src/agent-look.js
index 4423034a..62452847 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -2,11 +2,13 @@ import { mat4 } from 'gl-matrix';
import { createLightingState, updateLightingState, MAX_POINT_LIGHTS } from './lighting.js';
import { resolveEffects } from './effects.js';
import { resolveVolumeFog } from './volumetric.js';
+import { resolveLiquidOptics } from './renderer.js';
const ENVIRONMENT_FIELDS = [
'world', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',
- 'daylight', 'pointLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog',
+ 'daylight', 'pointLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid',
];
+const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];
const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'bloom'];
const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];
const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range'];
@@ -160,6 +162,11 @@ function environmentFrom(input = {}) {
fogDensity: numberInRange(fallback(input.fogDensity, 0.006), 0, 10, 'fogDensity'),
volumeFog: volumeFogFrom(input.volumeFog),
};
+ // Optional so recipes without liquids keep their exported shape.
+ if (input.liquid !== undefined) {
+ knownKeys(input.liquid, LIQUID_FIELDS, 'liquid');
+ environment.liquid = copiedJson(resolveLiquidOptics(copiedJson(input.liquid)));
+ }
updateLightingState(createLightingState(), environment, { world });
return environment;
}
diff --git a/src/agent-scene.js b/src/agent-scene.js
index 77f0012e..83e71bbf 100644
--- a/src/agent-scene.js
+++ b/src/agent-scene.js
@@ -14,7 +14,9 @@ const DEFAULT_LIMITS = Object.freeze({
});
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'];
+const MATERIAL_FIELDS = ['color', 'metallic', 'roughness', 'emission', 'emissiveColor', 'opacity', 'alphaMode', 'doubleSided'];
+// Procedural recipes have no textures, so cutout masking has nothing to cut.
+const RECIPE_ALPHA_MODES = ['opaque', 'blend'];
const CAMERA_FIELDS = Object.keys(CAMERA_DEFAULTS);
const LOOK_OPERATION_FIELDS = Object.freeze({
'set-environment': 'environment',
@@ -39,7 +41,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({
'add-geometry', 'remove-geometry', 'add-material', 'remove-material',
'set-environment', 'set-effects', 'set-shadow', 'set-motion',
]),
- materialTags: Object.freeze(['surface', 'unlit']),
+ materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam']),
+ alphaModes: Object.freeze(RECIPE_ALPHA_MODES),
fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,
authoredLook: true, maxPointLights: 8,
proceduralMotion: true,
@@ -195,7 +198,22 @@ function materialFrom(value) {
const result = { id: value.id, tag: defaultValue(value.tag, 'surface'), color: vector(defaultValue(value.color, [0.5, 0.5, 0.5]), 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 surface or unlit.');
+ throw new RangeError(`Material tag must be one of ${AGENT_SCENE_CAPABILITIES.materialTags.join(', ')}.`);
+ }
+ result.opacity = defaultValue(value.opacity, 1);
+ finite(result.opacity, 'opacity');
+ if (result.opacity < 0 || result.opacity > 1) {
+ throw new RangeError('opacity must be within zero and one.');
+ }
+ const requestedAlphaMode = defaultValue(value.alphaMode, 'opaque');
+ if (!RECIPE_ALPHA_MODES.includes(requestedAlphaMode)) {
+ throw new RangeError(`alphaMode must be one of ${RECIPE_ALPHA_MODES.join(', ')}.`);
+ }
+ // The renderer ignores opacity on opaque surfaces, so any opacity below one means blending.
+ result.alphaMode = result.opacity < 1 ? 'blend' : requestedAlphaMode;
+ result.doubleSided = defaultValue(value.doubleSided, false);
+ if (typeof result.doubleSided !== 'boolean') {
+ throw new TypeError('doubleSided must be boolean.');
}
for (const field of ['metallic', 'roughness']) {
finite(result[field], field);
@@ -473,6 +491,10 @@ function geometryStats(records) {
return { vertices, geometryBytes, estimatedGeometryBytes };
}
+function batchSignature(material) {
+ return `${material.tag}|${material.alphaMode}|${material.opacity}|${material.doubleSided}`;
+}
+
function materialHandle(snapshot) {
const holder = { snapshot };
const output = {};
@@ -684,7 +706,8 @@ export function createAgentScene(input, inputLimits = {}) {
const snapshot = immutableMaterial(material);
const preferredHandle = preferred?.materialHandles.get(material.id);
const activeHandle = removedMaterials.has(material.id) ? null : state?.materialHandles.get(material.id);
- const existing = [preferredHandle, activeHandle].find(handle => handle?.holder.snapshot.tag === material.tag);
+ // The renderer keeps tag, blending, opacity and sidedness per batch, so a handle is reused only when all match.
+ const existing = [preferredHandle, activeHandle].find(handle => handle && batchSignature(handle.holder.snapshot) === batchSignature(material));
const handle = existing ?? materialHandle(snapshot);
materialHandles.set(material.id, handle);
}
diff --git a/tests/agent-scene.test.js b/tests/agent-scene.test.js
index 73f09b3d..6807c02c 100644
--- a/tests/agent-scene.test.js
+++ b/tests/agent-scene.test.js
@@ -82,6 +82,32 @@ test('shader arithmetic rejects cancelling product overflow and nonfinite emissi
assert.throws(() => createAgentScene(input), /half-float HDR/);
});
+test('recipes author liquid, foam and blended glass with batch-safe material handles', () => {
+ assert.deepEqual(AGENT_SCENE_CAPABILITIES.materialTags, ['surface', 'unlit', 'liquid', 'foam']);
+ const input = recipe();
+ input.materials.push({ id: 'water', tag: 'liquid', color: [0.56, 0.84, 0.88], roughness: 0.05 });
+ input.materials.push({ id: 'glass', color: [0.9, 0.95, 1], opacity: 0.3, doubleSided: true });
+ input.environment = { liquid: { thickness: 0.8 } };
+ const session = createAgentScene(input);
+ const exported = session.exportRecipe();
+ const glass = exported.materials.find(material => material.id === 'glass');
+ assert.equal(glass.alphaMode, 'blend', 'opacity below one opts into blending');
+ assert.equal(glass.doubleSided, true);
+ assert.equal(exported.materials.find(material => material.id === 'finish').alphaMode, 'opaque');
+ assert.equal(session.environment.liquid.thickness, 0.8);
+ assert.equal(session.environment.liquid.ior, 1.33);
+ const finishMaterial = session.parts.find(part => part.name === 'child').material;
+ session.apply([{ type: 'set-material', id: 'finish', color: [1, 0, 0] }], { expectedRevision: 0 });
+ assert.equal(session.parts.find(part => part.name === 'child').material, finishMaterial, 'a color edit keeps the batch');
+ session.apply([{ type: 'set-material', id: 'finish', opacity: 0.5 }], { expectedRevision: 1 });
+ const blended = session.parts.find(part => part.name === 'child').material;
+ assert.notEqual(blended, finishMaterial, 'blending changes the batch, so the part is replaced');
+ assert.equal(blended.alphaMode, 'blend');
+ assert.throws(() => session.apply([{ type: 'set-material', id: 'finish', alphaMode: 'mask' }], { expectedRevision: 2 }), /alphaMode/);
+ assert.throws(() => session.apply([{ type: 'set-environment', environment: { liquid: { ior: 9 } } }], { expectedRevision: 2 }), /liquid\.ior/);
+ assert.throws(() => session.apply([{ type: 'set-environment', environment: { liquid: { depth: 1 } } }], { expectedRevision: 2 }), /Unknown liquid/);
+});
+
test('trailing sparse array holes reject recipes and command batches without commit', () => {
const input = recipe();
input.nodes.length++;