3D engine that AI agents drive
Merge feat/scene-kits and feed environment maps to the liquid shader
Nguyen Xuan An5ede43c13e5c
diff --cc package.jsonindex 1e4030ea,6b3e12a7..61448a4a--- a/package.json+++ b/package.json@@@ -75,9 -75,9 +75,10 @@@"./addons/shrinkwrap": "./build/shrinkwrap.js","./addons/surface-attachment": "./build/surface-attachment.js","./addons/physics": "./build/physics.js",+ "./addons/spume": "./build/spume.js","./addons/agent-scene": "./build/agent-scene.js","./addons/agent-asset": "./build/agent-asset.js",+ "./addons/hdri": "./build/hdri.js","./package.json": "./package.json"},"scripts": {diff --cc src/renderer.jsindex 32518c18,133c62eb..037d5c21--- a/src/renderer.js+++ b/src/renderer.js@@@ -17,12 -19,26 +20,30 @@@ const MATERIAL_MAPS = ['map', 'normalMaconst 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 MORPH_UNIFORMS = ['morphEnabled', 'morphVertexCount', 'morphTargetCount', 'morphWeights[0]', 'morphTargets'];- const ENVIRONMENT_UNIFORMS = ['environmentSpecular', 'environmentBrdf', 'environmentEnabled', 'environmentIntensity', 'environmentRotation', 'environmentLevelMax', 'environmentIrradiance[0]'];++const ENVIRONMENT_LOOKUP_UNIFORMS = ['environmentSpecular', 'environmentEnabled', 'environmentIntensity', 'environmentRotation', 'environmentLevelMax'];++const ENVIRONMENT_UNIFORMS = [...ENVIRONMENT_LOOKUP_UNIFORMS, 'environmentBrdf', 'environmentIrradiance[0]'];+const ENVIRONMENT_SPECULAR_UNIT = 9;+const ENVIRONMENT_BRDF_UNIT = 10;function validateMaterialMaps(material) {if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {@@@ -314,6 -337,8 +347,8 @@@ export class Renderer67this.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.liquidUniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'sceneColor', 'resolution', 'exposure', 'hdrEnabled', 'worldMode', 'daylight', 'lightDirection', 'keyColor', 'ambientIntensity', 'fogColor', 'fogDensity', 'liquidOptics', 'foamShape', ...ENVIRONMENT_LOOKUP_UNIFORMS, 'time', 'wind', 'explosionProgress', 'explosionCenter', 'assemblyAmount', ...SKIN_UNIFORMS, ...MORPH_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.liquidProgram, name)]));}this.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');@@@ -822,84 -848,6 +859,88 @@@context.bindFramebuffer(context.FRAMEBUFFER, null);}+ initializeEnvironment(map) {+ const context = this.context;+ context.useProgram(this.program);+ context.uniform1i(this.uniforms.environmentSpecular, ENVIRONMENT_SPECULAR_UNIT);+ context.uniform1i(this.uniforms.environmentBrdf, ENVIRONMENT_BRDF_UNIT);++ if (this.liquidProgram) {++ context.useProgram(this.liquidProgram);++ context.uniform1i(this.liquidUniforms.environmentSpecular, ENVIRONMENT_SPECULAR_UNIT);++ }+ this.bindEnvironmentTextures(this.whiteTexture, this.whiteTexture);+ if (!this.benchmark && map) this.prepareEnvironment(map);+ }++ bindEnvironmentTextures(specularTexture, brdfTexture) {+ const context = this.context;+ context.activeTexture(context.TEXTURE0 + ENVIRONMENT_SPECULAR_UNIT);+ context.bindTexture(context.TEXTURE_2D, specularTexture);+ context.activeTexture(context.TEXTURE0 + ENVIRONMENT_BRDF_UNIT);+ context.bindTexture(context.TEXTURE_2D, brdfTexture);+ }++ // Prefilters a map the first time it is seen; maps spread from one created map share its data and reuse the GPU textures. Returns true when new textures were built.+ prepareEnvironment(map) {+ assertEnvironmentMap(map);+ if (this.environmentResources?.data === map.data) return false;+ estimateEnvironmentBytes(map, this.capabilities.maximumTextureSize);+ const resources = createEnvironmentResources(this.context, map, { compileProgram, fullscreenVertex });+ this.environmentResources?.dispose();+ this.environmentResources = resources;+ this.textureBytes += resources.bytes - this.environmentBytes;+ this.environmentBytes = resources.bytes;+ return true;+ }++ // Binds the prefiltered textures for this frame and returns the active map, or null for the built-in studio lighting.+ activateEnvironment(map) {+ if (this.benchmark || !map) {+ this.bindEnvironmentTextures(this.whiteTexture, this.whiteTexture);+ return null;+ }+ if (this.prepareEnvironment(map)) this.resize();+ this.bindEnvironmentTextures(this.environmentResources.specularTexture, this.environmentResources.brdfTexture);+ return map;+ }+- applyEnvironmentUniforms(map) {++ applyEnvironmentUniforms(map, uniforms = this.uniforms) {+ const context = this.context;- context.uniform1f(this.uniforms.environmentEnabled, map ? 1 : 0);++ context.uniform1f(uniforms.environmentEnabled, map ? 1 : 0);+ if (!map) return;- context.uniform3fv(this.uniforms['environmentIrradiance[0]'], this.environmentResources.irradiance);- context.uniform1f(this.uniforms.environmentIntensity, map.intensity);- context.uniform2f(this.uniforms.environmentRotation, Math.cos(map.rotation), Math.sin(map.rotation));- context.uniform1f(this.uniforms.environmentLevelMax, this.environmentResources.levelCount - 1);++ if (uniforms['environmentIrradiance[0]']) context.uniform3fv(uniforms['environmentIrradiance[0]'], this.environmentResources.irradiance);++ context.uniform1f(uniforms.environmentIntensity, map.intensity);++ context.uniform2f(uniforms.environmentRotation, Math.cos(map.rotation), Math.sin(map.rotation));++ context.uniform1f(uniforms.environmentLevelMax, this.environmentResources.levelCount - 1);+ }++ drawEnvironmentBackground(map, frame, exposure) {+ if (!map?.showBackground || this.transparent) return false;+ const context = this.context;+ if (!this.environmentBackgroundProgram) {+ this.environmentBackgroundProgram = compileProgram(context, fullscreenVertex, environmentBackgroundFragment);+ const names = ['inverseViewProjection', 'eye', 'backgroundLevel', 'exposure', 'hdrEnabled', 'environmentSpecular', 'environmentRotation', 'environmentIntensity', 'environmentLevelMax'];+ this.environmentBackgroundUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.environmentBackgroundProgram, name)]));+ }+ const uniforms = this.environmentBackgroundUniforms;+ const levelMax = this.environmentResources.levelCount - 1;+ context.disable(context.DEPTH_TEST);+ context.disable(context.CULL_FACE);+ context.bindVertexArray(null);+ context.useProgram(this.environmentBackgroundProgram);+ context.uniformMatrix4fv(uniforms.inverseViewProjection, false, this.inverseViewProjection);+ context.uniform3fv(uniforms.eye, frame.eye);+ context.uniform1f(uniforms.backgroundLevel, map.backgroundBlur * levelMax);+ context.uniform1f(uniforms.exposure, exposure);+ context.uniform1f(uniforms.hdrEnabled, this.hdr ? 1 : 0);+ context.uniform1i(uniforms.environmentSpecular, ENVIRONMENT_SPECULAR_UNIT);+ context.uniform2f(uniforms.environmentRotation, Math.cos(map.rotation), Math.sin(map.rotation));+ context.uniform1f(uniforms.environmentIntensity, map.intensity);+ context.uniform1f(uniforms.environmentLevelMax, levelMax);+ context.drawArrays(context.TRIANGLES, 0, 3);+ return true;+ }+drawSky(frame) {const context = this.context;const environment = { skyTop: [0.20, 0.38, 0.52], skyBottom: [0.62, 0.70, 0.67], lightDirection: [-3, 6, 4], daylight: 1, ...this.environment, ...frame.environment };@@@ -975,6 -923,67 +1016,68 @@@context.drawArrays(context.TRIANGLES, 0, 3);}- drawTranslucent(frame, environment, assemblyAmount) {++ drawTranslucent(frame, environment, assemblyAmount, environmentMap) {+ const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');+ const foams = this.batches.filter(batch => batchPass(batch) === 'foam');+ if (liquids.length === 0 && foams.length === 0) return;+ const optics = resolveLiquidOptics({ ...environment.liquid, ...frame.liquid });+ const context = this.context;+ const width = this.canvas.width;+ const height = this.canvas.height;+ // Liquids refract the opaque scene, so resolve it into frameTexture before drawing them on top.+ context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);+ context.blitFramebuffer(0, 0, width, height, 0, 0, width, height, context.COLOR_BUFFER_BIT, context.NEAREST);+ context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);+ context.viewport(0, 0, width, height);+ context.enable(context.DEPTH_TEST);+ context.enable(context.CULL_FACE);+ context.useProgram(this.liquidProgram);+ const uniforms = this.liquidUniforms;+ context.uniformMatrix4fv(uniforms.viewProjection, false, this.viewProjection);+ context.uniformMatrix4fv(uniforms.lightProjection, false, this.lightProjection);+ context.uniform3fv(uniforms.eye, frame.eye);+ context.uniform2f(uniforms.resolution, width, height);+ context.uniform1f(uniforms.exposure, frame.exposure ?? 1);+ context.uniform1f(uniforms.hdrEnabled, this.hdr ? 1 : 0);+ context.uniform1f(uniforms.worldMode, this.world ? 1 : 0);+ context.uniform1f(uniforms.daylight, environment.daylight);+ context.uniform3fv(uniforms.lightDirection, environment.lightDirection);+ context.uniform3fv(uniforms.keyColor, this.lighting.keyColor);+ context.uniform1f(uniforms.ambientIntensity, this.lighting.ambientIntensity);+ context.uniform3fv(uniforms.fogColor, environment.fogColor);+ context.uniform1f(uniforms.fogDensity, environment.fogDensity);+ context.uniform4f(uniforms.liquidOptics, optics.thickness, optics.ior, optics.refraction, optics.scattering);+ context.uniform2f(uniforms.foamShape, optics.foamOpacity, optics.foamSoftness);++ this.applyEnvironmentUniforms(environmentMap, uniforms);+ context.uniform1f(uniforms.time, frame.time ?? 0);+ context.uniform1f(uniforms.wind, frame.wind ?? 0.3);+ context.uniform1f(uniforms.explosionProgress, frame.explosionProgress ?? 1);+ context.uniform3fv(uniforms.explosionCenter, environment.explosionCenter);+ context.uniform1f(uniforms.assemblyAmount, assemblyAmount);+ if (uniforms.skinEnabled) context.uniform1f(uniforms.skinEnabled, 0);+ if (uniforms.morphEnabled) context.uniform1f(uniforms.morphEnabled, 0);+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D, this.frameTexture);+ context.uniform1i(uniforms.sceneColor, 0);+ for (const batch of liquids) {+ context.bindVertexArray(batch.vertexArray);+ context.drawElementsInstanced(context.TRIANGLES, batch.indexCount, context.UNSIGNED_INT, 0, batch.instanceCount);+ }+ if (foams.length > 0) {+ 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 foams) {+ context.bindVertexArray(batch.vertexArray);+ context.drawElementsInstanced(context.TRIANGLES, batch.indexCount, context.UNSIGNED_INT, 0, batch.instanceCount);+ }+ context.depthMask(true);+ context.disable(context.BLEND);+ }+ context.bindVertexArray(null);+ }+drawBloom(bloom) {const context = this.context;context.disable(context.DEPTH_TEST);@@@ -1100,9 -1107,11 +1203,12 @@@context.activeTexture(context.TEXTURE0);context.bindTexture(context.TEXTURE_2D, this.shadowTexture);context.uniform1i(this.uniforms.shadowMap, 0);+ this.applyEnvironmentUniforms(environmentMap);- for (const batch of this.batches) this.drawBatch(batch, true);+ for (const batch of this.batches) {+ if (this.benchmark || batchPass(batch) === 'opaque') this.drawBatch(batch, true);+ }context.bindVertexArray(null);- if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount);++ if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);this.cpuMilliseconds = performance.now() - start;}diff --cc src/shaders.jsindex e3ed42e5,ab4a7500..6653fe5a--- a/src/shaders.js+++ b/src/shaders.js@@@ -153,6 -152,120 +153,124 @@@ out vec4 outputColorvoid main() { outputColor = vec4(color, 1.0); }`;+ // Liquid and foam are drawn after the opaque scene, which is resolved into sceneColor first.+ // Liquid: refraction through the scene, Beer-Lambert absorption over a convex-body thickness+ // estimate, in-scattering, Fresnel environment reflection and a GGX key highlight.+ // Foam: soft blended droplets whose alpha falls off toward their silhouettes.+ export const liquidFragmentShader = `#version 300 es+ precision highp float;+ in vec3 worldPosition;+ in vec3 worldNormal;+ flat in vec3 baseColor;+ flat in vec4 surface;+ in vec4 shadowPosition;+ in vec2 textureUV;+ in vec3 vertexTint;+ flat in vec3 emissionColor;+ uniform vec3 eye;+ uniform mat4 viewProjection;+ uniform sampler2D sceneColor;+ uniform vec2 resolution;+ uniform float exposure;+ uniform float hdrEnabled;+ uniform float worldMode;+ uniform float daylight;+ uniform vec3 lightDirection;+ uniform vec3 keyColor;+ uniform float ambientIntensity;+ uniform vec3 fogColor;+ uniform float fogDensity;+ // x: thickness in metres, y: index of refraction, z: refraction strength, w: scattering+ uniform vec4 liquidOptics;+ // x: foam opacity, y: foam edge softness+ uniform vec2 foamShape;+ out vec4 outputColor;+ const float PI = 3.14159265359;++ vec3 toneMap(vec3 color) {+ return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);+ }+++${environmentLookupGlsl}++uniform float environmentEnabled;+++ vec3 environmentColor(vec3 direction, float roughness) {++ if (environmentEnabled > 0.5) return environmentRadiance(direction, roughness * environmentLevelMax);+ if (worldMode > 0.5) {+ vec3 zenith = vec3(0.20, 0.38, 0.52) * max(daylight, 0.08);+ return mix(fogColor * 0.75, zenith, smoothstep(-0.15, 0.7, direction.y));+ }+ vec3 color = mix(vec3(0.025, 0.035, 0.045), vec3(0.22, 0.25, 0.27), smoothstep(-0.3, 0.8, direction.y));+ float blur = roughness * 0.35;+ float key = smoothstep(0.80 - blur, 0.87, dot(direction, normalize(vec3(-3.0, 5.0, 4.0))));+ float rim = smoothstep(0.90 - blur, 0.97, dot(direction, normalize(vec3(4.0, 2.0, -3.0))));+ float strip = exp(-pow((direction.x + 0.6) / (0.035 + blur), 2.0)) * smoothstep(-0.1, 0.6, direction.y);+ return color + key * vec3(2.8, 2.2, 1.6) + rim * vec3(0.5, 1.6, 1.5) + strip * vec3(0.7);+ }++ float specularLobe(vec3 normal, vec3 viewDirection, vec3 light, float roughness) {+ float normalLight = max(dot(normal, light), 0.0);+ if (normalLight == 0.0) return 0.0;+ vec3 halfway = normalize(viewDirection + light);+ float normalView = max(dot(normal, viewDirection), 0.001);+ float normalHalf = max(dot(normal, halfway), 0.0);+ float alpha = roughness * roughness;+ float denominator = normalHalf * normalHalf * (alpha * alpha - 1.0) + 1.0;+ float distribution = alpha * alpha / max(PI * denominator * denominator, 0.00001);+ float masking = pow(roughness + 1.0, 2.0) / 8.0;+ float geometry = normalView / (normalView * (1.0 - masking) + masking) * normalLight / (normalLight * (1.0 - masking) + masking);+ return distribution * geometry / max(4.0 * normalView * normalLight, 0.001) * normalLight;+ }++ vec3 ambientLight(vec3 normal) {+ vec3 studioAmbient = vec3(0.16, 0.20, 0.22) * (0.45 + 0.55 * max(normal.y, 0.0));+ vec3 worldAmbient = vec3(0.19, 0.25, 0.30) * max(daylight, 0.08) * (0.45 + 0.55 * max(normal.y, 0.0));+ return mix(studioAmbient, worldAmbient, worldMode) * ambientIntensity;+ }++ vec3 displayed(vec3 radiance) {+ return hdrEnabled > 0.5 ? clamp(radiance * exposure, vec3(0), vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2));+ }++ void main() {+ vec3 normal = normalize(worldNormal);+ if (!gl_FrontFacing) normal = -normal;+ vec3 viewDirection = normalize(eye - worldPosition);+ float facing = max(dot(normal, viewDirection), 0.0);+ vec3 light = normalize(lightDirection);+ vec3 color = baseColor * vertexTint;+ float fog = (1.0 - exp(-length(worldPosition - eye) * fogDensity)) * worldMode;++ if (surface.w == 12.0) {+ float alpha = foamShape.x * smoothstep(0.0, max(foamShape.y, 0.001), facing);+ if (alpha < 0.004) discard;+ float wrapped = max(dot(normal, light) * 0.5 + 0.5, 0.0);+ vec3 radiance = color * (ambientLight(normal) * 1.6 + keyColor * wrapped * 0.32);+ radiance = mix(radiance, fogColor, fog);+ outputColor = vec4(displayed(radiance), alpha);+ return;+ }++ float roughness = clamp(surface.y, 0.02, 1.0);+ vec2 screen = gl_FragCoord.xy / resolution;+ // A convex body is thickest where it faces the camera and thins to nothing at its silhouette.+ float thickness = liquidOptics.x * mix(0.15, 1.0, facing);+ vec3 bent = refract(-viewDirection, normal, 1.0 / liquidOptics.y);+ vec4 projected = viewProjection * vec4(worldPosition + bent * thickness, 1.0);+ vec2 refracted = projected.w > 0.0 ? projected.xy / projected.w * 0.5 + 0.5 : screen;+ refracted = clamp(mix(screen, refracted, liquidOptics.z), vec2(0.001), vec2(0.999));+ vec3 behind = texture(sceneColor, refracted).rgb;+ // The material colour is what one metre of this liquid lets through.+ vec3 transmittance = pow(clamp(color, vec3(0.001), vec3(1.0)), vec3(thickness));+ float reflectance = 0.02 + 0.98 * pow(1.0 - facing, 5.0);+ vec3 inScatter = color * (ambientLight(normal) + keyColor * max(dot(normal, light), 0.0) * 0.2) * liquidOptics.w * (1.0 - transmittance);+ vec3 reflection = environmentColor(reflect(-viewDirection, normal), roughness) * ambientIntensity;+ vec3 highlight = keyColor * specularLobe(normal, viewDirection, light, roughness);+ vec3 surfaceLight = inScatter * (1.0 - reflectance) + reflection * reflectance + highlight;+ surfaceLight = mix(surfaceLight, fogColor, fog);+ outputColor = vec4(behind * transmittance * (1.0 - reflectance) * (1.0 - fog) + displayed(surfaceLight), 1.0);+ }`;+export const fragmentShader = `#version 300 esprecision highp float;in vec3 worldPosition;diff --cc vite.lib.config.jsindex 3717fc4c,b90d09e4..fd407d67--- a/vite.lib.config.js+++ b/vite.lib.config.js@@@ -25,9 -25,9 +25,10 @@@ export default defineConfig(shrinkwrap: 'src/shrinkwrap.js','surface-attachment': 'src/surface-attachment.js',physics: 'src/physics.js',+ spume: 'src/spume.js','agent-scene': 'src/agent-scene.js','agent-asset': 'src/agent-asset.js',+ hdri: 'src/hdri.js',},formats: ['es'],fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,