Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Merge feat/scene-kits into alpha materials; draw blend batches after the liquid and foam pass

Nguyen Xuan Ancd0026c2e6cc
diff --cc docs/guide.md
index f8ebf5ea,1a12525c..3ad982d0
--- a/docs/guide.md
+++ b/docs/guide.md
@@@ -187,10 -199,10 +199,12 @@@ The optional GLB addon creates these de
Tags select specialized behavior: `armor` allows studio finish overrides. `floor` is a studio floor. `water` adds animated normals and ripples. `foliage` and `grass` add wind.
+`material.alphaMode` is `'opaque'` (default), `'mask'` (cutout at `alphaCutoff`, default 0.5, shadows follow it) or `'blend'` (drawn last, back to front, no depth write). `material.opacity` (default 1) multiplies the base map alpha. `material.doubleSided` (default false) disables back-face culling and lights both faces. These are batch state and cannot change after upload. See `docs/material-maps.md`.
+
`terrain` adds surface variation. `fire` and `smoke` support film effects. `unlit` is a flat color. Other tags use ordinary PBR shading.
+ `water` flattens normals into a rippled pond and only suits horizontal surfaces. Shaped water uses `liquid`: it is drawn after the opaque scene, refracts what lies behind it, darkens with thickness and reflects the environment by the Fresnel term. Its `color` is the light one metre of liquid lets through, so `[0.56, 0.84, 0.88]` is clear blue-green water. `foam` draws soft alpha-blended droplets for whitewater. Tune both with `frame.liquid` or `environment.liquid`: `{ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 }`. A liquid refracts opaque parts only.
+
## Renderer reference
`new Renderer67(canvas, parts, options)` owns GPU geometry, texture and target allocations. Constructor options:
diff --cc src/renderer.js
index 8dd19aa9,133c62eb..42f43456
--- a/src/renderer.js
+++ b/src/renderer.js
@@@ -9,18 -9,35 +9,38 @@@ import { resolveVolumeFog } from './vol
import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';
import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';
- const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };
+ const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10, liquid: 11, foam: 12 };
+ // Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.
+ const TRANSLUCENT_TAGS = new Set(['liquid', 'foam']);
+ const DEFAULT_LIQUID = Object.freeze({ thickness: 0.5, ior: 1.33, refraction: 1, scattering: 1, foamOpacity: 0.55, foamSoftness: 1 });
const INSTANCE_STRIDE = 41;
+const ALPHA_MODES = { opaque: 0, mask: 1, blend: 2 };
const ZERO_VECTOR = Object.freeze([0, 0, 0]);
const MATERIAL_MAPS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_UNIFORMS = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];
const MAP_FLAGS = ['hasBaseMap', 'hasNormalMap', 'hasMetallicRoughnessMap', 'hasOcclusionMap', 'hasEmissiveMap'];
const DEFAULT_NORMAL_SCALE = [1, 1];
- const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);
+ const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke', 'liquid', 'foam']);
+
+ function renderPass(material) {
+ return TRANSLUCENT_TAGS.has(material.tag) ? material.tag : 'opaque';
+ }
+
+ function batchPass(batch) {
+ return batch.pass ?? 'opaque';
+ }
+
+ export function resolveLiquidOptics(options = {}) {
+ const optics = { ...DEFAULT_LIQUID, ...options };
+ for (const [name, minimum, maximum] of [['thickness', 0, 100], ['ior', 1, 3], ['refraction', 0, 4], ['scattering', 0, 10], ['foamOpacity', 0, 1], ['foamSoftness', 0, 1]]) {
+ const value = optics[name];
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) throw new RangeError(`liquid.${name} must be between ${minimum} and ${maximum}.`);
+ }
+ return optics;
+ }
const SKIN_UNIFORMS = ['skinEnabled', 'skinInfluences', 'jointPalette'];
+const ALPHA_UNIFORMS = ['alphaMode', 'alphaCutoff', 'materialOpacity', 'alphaToCoverage', 'doubleSided'];
+const DEPTH_ALPHA_UNIFORMS = ['alphaMasked', 'alphaCutoff', 'materialOpacity', 'hasBaseMap', 'baseMap'];
const MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];
function validateMaterialMaps(material) {
@@@ -165,7 -158,7 +185,7 @@@ export function groupParts(parts, batch
const key = batching ? part.geometry : part;
if (!groups.has(key)) groups.set(key, new Map());
let maps = groups.get(key);
- for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), ...materialAlphaState(part.material)]) {
- for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, part.castShadow !== false, renderPass(part.material)]) {
++ for (const value of [...materialMapState(part.material), part.skin ?? null, part.morph ?? null, castsShadow(part), renderPass(part.material), ...materialAlphaState(part.material)]) {
if (!maps.has(value)) maps.set(value, new Map());
maps = maps.get(value);
}
@@@ -332,8 -337,9 +364,10 @@@ export class Renderer67
this.bloomProgram = compileProgram(this.context, fullscreenVertex, bloomFragment);
this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));
this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
+ this.liquidProgram = compileProgram(this.context, vertexShader, liquidFragmentShader);
+ this.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));
}
+ this.depthAlphaUniforms = Object.fromEntries(DEPTH_ALPHA_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));
this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');
this.partCount = parts.length;
@@@ -483,8 -490,7 +518,8 @@@
const morph = parts[0].morph ?? null;
const morphTexture = morph ? this.createMorphTexture(geometry, morph) : null;
const morphWeights = morph ? new Float32Array(morph.weights) : null;
- const batch = { parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: parts[0].castShadow !== false, pass: renderPass(parts[0].material) };
+ const [alphaMode, alphaCutoff, opacity, doubleSided] = materialAlphaState(parts[0].material);
- const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]) };
++ const batch = { alphaMode, alphaCutoff, opacity, doubleSided, parts: [...parts], vertexArray, instanceBuffer, instanceData, textures, mapState, texture: textures[0], map, skin, skinTexture, influenceTexture, morph, morphTexture, morphWeights, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor', castShadow: castsShadow(parts[0]), pass: renderPass(parts[0].material) };
parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map, mapState, 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) }));
return batch;
}
@@@ -517,10 -523,8 +552,10 @@@
const batch = location?.batch;
const mapState = materialMapState(first.material);
const sameParts = batch?.parts.length === group.length && batch.parts.every((part, index) => part === group[index]);
- const sameState = location?.geometry === first.geometry && batch?.castShadow === (first.castShadow !== false) &&
+ const alphaState = materialAlphaState(first.material);
+ const sameState = location?.geometry === first.geometry && batch?.castShadow === castsShadow(first) &&
- batch.floor === (first.material.tag === 'floor') &&
+ batch.floor === (first.material.tag === 'floor') && batchPass(batch) === renderPass(first.material) &&
+ [batch.alphaMode, batch.alphaCutoff, batch.opacity, batch.doubleSided].every((value, index) => value === alphaState[index]) &&
batch.mapState.every((value, index) => value === mapState[index]);
if (sameParts && sameState) {
retained.add(batch);
@@@ -649,11 -653,9 +684,12 @@@
const location = this.partLocations.get(part);
if (!location) throw new Error(`Unknown part identity: ${part.name}`);
if (part.castShadow !== undefined && typeof part.castShadow !== 'boolean') throw new TypeError('castShadow must be a boolean');
- if ((part.castShadow !== false) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ if (castsShadow(part) !== location.batch.castShadow) throw new Error(`Shadow casting changes require a new renderer: ${part.name}`);
+ const alphaState = materialAlphaState(part.material);
+ const batchAlphaState = [location.batch.alphaMode, location.batch.alphaCutoff, location.batch.opacity, location.batch.doubleSided];
+ if (alphaState.some((value, index) => value !== batchAlphaState[index])) throw new Error(`Alpha mode, cutoff, opacity and double-sided changes require a new renderer: ${part.name}`);
if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
+ if (renderPass(part.material) !== batchPass(location.batch)) throw new Error(`Moving a part into or out of the liquid or foam pass requires replaceParts: ${part.name}`);
if ((part.skin ?? null) !== location.skin || part.skin?.jointMatrices !== location.jointMatrices || part.geometry.skinIndices !== location.skinIndices || part.geometry.skinWeights !== location.skinWeights) throw new Error(`Skin identity changes require a new renderer: ${part.name}`);
if (part.skin) {
if (PROCEDURAL_MATERIAL_TAGS.has(part.material.tag)) throw new Error('Skinned parts require a standard material tag.');
@@@ -943,88 -1003,6 +1040,100 @@@
}
}
+ /** Culling, cutout and opacity state for one batch, in the color pass (textured) or the shadow depth pass. */
+ applyAlphaState(batch, textured) {
+ const context = this.context;
+ if (batch.doubleSided) {
+ context.disable(context.CULL_FACE);
+ } else {
+ context.enable(context.CULL_FACE);
+ }
+ const masked = batch.alphaMode === 'mask';
+ if (!textured) {
+ const uniforms = this.depthAlphaUniforms;
+ context.uniform1f(uniforms.alphaMasked, masked ? 1 : 0);
+ context.uniform1f(uniforms.alphaCutoff, batch.alphaCutoff);
+ context.uniform1f(uniforms.materialOpacity, batch.opacity);
+ context.uniform1f(uniforms.hasBaseMap, batch.mapState[0] ? 1 : 0);
+ if (masked) {
+ context.activeTexture(context.TEXTURE0 + 1);
+ context.bindTexture(context.TEXTURE_2D, batch.textures[0]);
+ }
+ return;
+ }
+ const useCoverage = masked && this.samples > 1 && !this.benchmark;
+ if (useCoverage) {
+ context.enable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ } else {
+ context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ }
+ const uniforms = this.uniforms;
+ context.uniform1f(uniforms.alphaMode, ALPHA_MODES[batch.alphaMode]);
+ context.uniform1f(uniforms.alphaCutoff, batch.alphaCutoff);
+ context.uniform1f(uniforms.materialOpacity, batch.opacity);
+ context.uniform1f(uniforms.alphaToCoverage, useCoverage ? 1 : 0);
+ context.uniform1f(uniforms.doubleSided, batch.doubleSided ? 1 : 0);
+ }
+
+ /** Reorders a blend batch's instances back to front for this eye; translation columns stand in for object centers. */
+ uploadSortedInstances(batch, eye) {
+ if (batch.instanceCount < 2) return;
+ const data = batch.instanceData;
+ const distances = Array.from({ length: batch.instanceCount }, (unused, index) => {
+ const offset = index * INSTANCE_STRIDE;
+ return { index, distance: Math.hypot(data[offset + 12] - eye[0], data[offset + 13] - eye[1], data[offset + 14] - eye[2]) };
+ });
+ distances.sort((first, second) => second.distance - first.distance);
+ batch.sortedData ??= new Float32Array(data.length);
+ distances.forEach(({ index }, rank) => {
+ batch.sortedData.set(data.subarray(index * INSTANCE_STRIDE, (index + 1) * INSTANCE_STRIDE), rank * INSTANCE_STRIDE);
+ });
+ this.context.bindBuffer(this.context.ARRAY_BUFFER, batch.instanceBuffer);
+ this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.sortedData);
+ }
+
+ /** Alpha-blended batches draw after opaque and masked geometry, farthest first, without writing depth. */
- drawBlendBatches(eye) {
++ drawBlendBatches(frame) {
+ const context = this.context;
- const blendBatches = this.batches.filter(batch => batch.alphaMode === 'blend');
++ const eye = frame.eye;
++ const blendBatches = this.batches.filter(batch => batch.alphaMode === 'blend' && batchPass(batch) === 'opaque');
+ if (blendBatches.length === 0) return;
++ // The liquid and foam pass may have switched program, texture unit 0 and the viewport.
++ context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);
++ context.viewport(0, 0, this.canvas.width, this.canvas.height);
++ context.enable(context.DEPTH_TEST);
++ context.useProgram(this.program);
++ context.activeTexture(context.TEXTURE0);
++ context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
++ context.uniform1i(this.uniforms.shadowMap, 0);
+ const distance = (batch) => {
+ let total = 0;
+ for (let index = 0; index < batch.instanceCount; index++) {
+ const offset = index * INSTANCE_STRIDE;
+ total += Math.hypot(batch.instanceData[offset + 12] - eye[0], batch.instanceData[offset + 13] - eye[1], batch.instanceData[offset + 14] - eye[2]);
+ }
+ return total / batch.instanceCount;
+ };
+ const ordered = blendBatches.map(batch => ({ batch, distance: distance(batch) })).sort((first, second) => second.distance - first.distance);
+ context.enable(context.BLEND);
+ context.blendFuncSeparate(context.SRC_ALPHA, context.ONE_MINUS_SRC_ALPHA, context.ONE, context.ONE_MINUS_SRC_ALPHA);
+ context.depthMask(false);
+ for (const { batch } of ordered) {
+ this.uploadSortedInstances(batch, eye);
+ this.drawAlphaBatch(batch, true);
+ }
+ context.depthMask(true);
+ context.disable(context.BLEND);
++ context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
++ context.enable(context.CULL_FACE);
++ context.bindVertexArray(null);
+ }
+
+ drawAlphaBatch(batch, textured) {
+ this.applyAlphaState(batch, textured);
+ this.drawBatch(batch, textured);
+ }
+
drawBatch(batch, textured = false) {
if (this.hasMorphs) {
const uniforms = textured ? this.uniforms : this.depthMorphUniforms;
@@@ -1129,11 -1107,11 +1238,18 @@@
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
- for (const batch of this.batches) if (batch.alphaMode !== 'blend') this.drawAlphaBatch(batch, true);
- this.drawBlendBatches(eye);
+ for (const batch of this.batches) {
- if (this.benchmark || batchPass(batch) === 'opaque') this.drawBatch(batch, true);
++ if (this.benchmark) {
++ this.drawBatch(batch, true);
++ } else if (batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend') {
++ this.drawAlphaBatch(batch, true);
++ }
+ }
+ context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
+ context.enable(context.CULL_FACE);
context.bindVertexArray(null);
+ if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount);
++ if (!this.benchmark) this.drawBlendBatches(frame);
if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);
this.cpuMilliseconds = performance.now() - start;
}