3D engine that AI agents drive
Add equirect HDR image-based lighting (WIP)
Nguyen Xuan Andc3e7ba869e7
diff --git a/package.json b/package.jsonindex fd5f9ac9..1e4030ea 100644--- a/package.json+++ b/package.json@@ -77,6 +77,7 @@"./addons/physics": "./build/physics.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 --git a/src/environment.js b/src/environment.jsnew file mode 100644index 00000000..53998753--- /dev/null+++ b/src/environment.js@@ -0,0 +1,392 @@+// Image-based lighting from equirectangular HDR maps.+// Convention: image row 0 is straight up, the image centre looks toward -Z, and+// `rotation` turns the environment about +Y in radians.++export const ENVIRONMENT_ROUGHNESS_LEVELS = 7;+export const ENVIRONMENT_BRDF_SIZE = 128;+export const MAXIMUM_ENVIRONMENT_SIZE = 16384;+const MAXIMUM_SPECULAR_WIDTH = 1024;+const HALF_FLOAT_MAXIMUM = 65504;+const PREFILTER_SAMPLES = 256;++function requireIntegerInRange(value, name, minimum, maximum) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw new RangeError(`Environment map ${name} must be an integer between ${minimum} and ${maximum}.`);+ }+}++function requireNumberInRange(value, name, minimum, maximum) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {+ throw new RangeError(`Environment map ${name} must be a finite number between ${minimum} and ${maximum}.`);+ }+}++export function createEnvironmentMap({ width, height, data, intensity = 1, rotation = 0, showBackground = false, backgroundBlur = 0 } = {}) {+ requireIntegerInRange(width, 'width', 4, MAXIMUM_ENVIRONMENT_SIZE);+ requireIntegerInRange(height, 'height', 2, MAXIMUM_ENVIRONMENT_SIZE);+ if (!(data instanceof Float32Array)) throw new TypeError('Environment map data must be a Float32Array of linear RGB or RGBA values.');+ const pixelCount = width * height;+ const channels = data.length === pixelCount * 3 ? 3 : data.length === pixelCount * 4 ? 4 : 0;+ if (!channels) throw new RangeError('Environment map data length must equal width * height * 3 or width * height * 4.');+ for (let index = 0; index < data.length; index++) {+ if (!Number.isFinite(data[index])) throw new RangeError('Environment map data must contain only finite values.');+ }+ requireNumberInRange(intensity, 'intensity', 0, 1000);+ requireNumberInRange(rotation, 'rotation', -1e6, 1e6);+ requireNumberInRange(backgroundBlur, 'backgroundBlur', 0, 1);+ if (typeof showBackground !== 'boolean') throw new TypeError('Environment map showBackground must be a boolean.');+ return Object.freeze({ kind: 'environment-map', width, height, channels, data, intensity, rotation, showBackground, backgroundBlur });+}++// The renderer accepts descriptors that were spread from a created map (to animate rotation), so it re-checks the shape without rescanning the data.+export function assertEnvironmentMap(map) {+ if (map?.kind !== 'environment-map' || !(map.data instanceof Float32Array)) {+ throw new TypeError('environment.map must be created with createEnvironmentMap.');+ }+ if (map.data.length !== map.width * map.height * map.channels) throw new RangeError('Environment map data length does not match its dimensions.');+ requireNumberInRange(map.intensity, 'intensity', 0, 1000);+ requireNumberInRange(map.rotation, 'rotation', -1e6, 1e6);+ requireNumberInRange(map.backgroundBlur, 'backgroundBlur', 0, 1);+}++export function environmentSpecularLayout(map) {+ const scale = Math.min(1, MAXIMUM_SPECULAR_WIDTH / map.width);+ const width = Math.max(4, Math.round(map.width * scale));+ const height = Math.max(2, Math.round(map.height * scale));+ const levelCount = Math.min(ENVIRONMENT_ROUGHNESS_LEVELS, Math.floor(Math.log2(Math.max(width, height))) + 1);+ const levels = [];+ let bytes = ENVIRONMENT_BRDF_SIZE * ENVIRONMENT_BRDF_SIZE * 4;+ for (let level = 0; level < levelCount; level++) {+ const levelWidth = Math.max(1, width >> level);+ const levelHeight = Math.max(1, height >> level);+ levels.push({ width: levelWidth, height: levelHeight });+ bytes += levelWidth * levelHeight * 8;+ }+ return { width, height, levelCount, levels, bytes };+}++// Persistent GPU bytes: the prefiltered half-float chain and the BRDF lookup. The source upload is freed once prefiltering ends.+export function estimateEnvironmentBytes(map, textureLimit = MAXIMUM_ENVIRONMENT_SIZE) {+ assertEnvironmentMap(map);+ if (map.width > textureLimit || map.height > textureLimit) {+ throw new RangeError(`Environment map ${map.width}x${map.height} exceeds the GPU texture limit of ${textureLimit}.`);+ }+ return environmentSpecularLayout(map).bytes;+}++const BASIS_SCALES = [0.282095, 0.488603, 0.488603, 0.488603, 1.092548, 1.092548, 0.315392, 1.092548, 0.546274];+// Lambert convolution factors A_l / pi for bands 0, 1 and 2.+const BAND_FACTORS = [1, 2 / 3, 2 / 3, 2 / 3, 1 / 4, 1 / 4, 1 / 4, 1 / 4, 1 / 4];++function sphericalHarmonicBasis(x, y, z) {+ return [1, y, z, x, x * y, y * z, 3 * z * z - 1, x * z, x * x - y * y];+}++// Returns 27 floats (9 RGB triples) with basis constants and the Lambert kernel folded in,+// so evaluateIrradiance(coefficients, normal) is the diffuse radiance for a white surface.+export function computeIrradianceCoefficients(map) {+ assertEnvironmentMap(map);+ const { width, height, channels, data } = map;+ const columnSine = new Float64Array(width);+ const columnCosine = new Float64Array(width);+ for (let column = 0; column < width; column++) {+ const azimuth = ((column + 0.5) / width - 0.5) * 2 * Math.PI;+ columnSine[column] = Math.sin(azimuth);+ columnCosine[column] = Math.cos(azimuth);+ }+ const sums = new Float64Array(27);+ const pixelSolidAngleScale = (2 * Math.PI / width) * (Math.PI / height);+ for (let row = 0; row < height; row++) {+ const polar = (row + 0.5) / height * Math.PI;+ const sinePolar = Math.sin(polar);+ const y = Math.cos(polar);+ const weight = sinePolar * pixelSolidAngleScale;+ for (let column = 0; column < width; column++) {+ const basis = sphericalHarmonicBasis(sinePolar * columnSine[column], y, -sinePolar * columnCosine[column]);+ const offset = (row * width + column) * channels;+ for (let term = 0; term < 9; term++) {+ const termWeight = basis[term] * weight;+ sums[term * 3] += data[offset] * termWeight;+ sums[term * 3 + 1] += data[offset + 1] * termWeight;+ sums[term * 3 + 2] += data[offset + 2] * termWeight;+ }+ }+ }+ const coefficients = new Float32Array(27);+ for (let term = 0; term < 9; term++) {+ // The constant applies once when projecting onto the basis and once when reconstructing.+ const scale = BASIS_SCALES[term] ** 2 * BAND_FACTORS[term];+ for (let channel = 0; channel < 3; channel++) coefficients[term * 3 + channel] = sums[term * 3 + channel] * scale;+ }+ return coefficients;+}++export function evaluateIrradiance(coefficients, normal) {+ const [x, y, z] = normal;+ const basis = sphericalHarmonicBasis(x, y, z);+ const result = [0, 0, 0];+ for (let term = 0; term < 9; term++) {+ for (let channel = 0; channel < 3; channel++) result[channel] += coefficients[term * 3 + channel] * basis[term];+ }+ return result.map(value => Math.max(value, 0));+}++function paddedHalfFloatSource(map) {+ const pixelCount = map.width * map.height;+ const padded = new Float32Array(pixelCount * 4);+ for (let pixel = 0; pixel < pixelCount; pixel++) {+ const source = pixel * map.channels;+ const target = pixel * 4;+ padded[target] = Math.min(Math.max(map.data[source], 0), HALF_FLOAT_MAXIMUM);+ padded[target + 1] = Math.min(Math.max(map.data[source + 1], 0), HALF_FLOAT_MAXIMUM);+ padded[target + 2] = Math.min(Math.max(map.data[source + 2], 0), HALF_FLOAT_MAXIMUM);+ padded[target + 3] = 1;+ }+ return padded;+}++const equirectangularGlsl = `+vec3 directionFromEquirectangular(vec2 coordinates) {+ float azimuth = (coordinates.x - 0.5) * 6.28318530718;+ float polar = coordinates.y * 3.14159265359;+ return vec3(sin(polar) * sin(azimuth), cos(polar), -sin(polar) * cos(azimuth));+}+vec2 equirectangularFromDirection(vec3 direction) {+ return vec2(atan(direction.x, -direction.z) * 0.15915494309 + 0.5, acos(clamp(direction.y, -1.0, 1.0)) * 0.31830988618);+}+`;++const prefilterFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+uniform sampler2D sourceMap;+uniform vec2 sourceSize;+uniform float roughness;+uniform float sourceLevelOffset;+out vec4 outputColor;+const float PI = 3.14159265359;+const uint SAMPLE_COUNT = ${PREFILTER_SAMPLES}u;+${equirectangularGlsl}+float radicalInverse(uint bits) {+ bits = (bits << 16u) | (bits >> 16u);+ bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);+ bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);+ bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);+ bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);+ return float(bits) * 2.3283064365386963e-10;+}+void main() {+ if (roughness < 0.001) {+ outputColor = vec4(min(textureLod(sourceMap, textureCoordinate, sourceLevelOffset).rgb, 65000.0), 1.0);+ return;+ }+ vec3 normal = directionFromEquirectangular(textureCoordinate);+ vec3 helper = abs(normal.y) < 0.999 ? vec3(0.0, 1.0, 0.0) : vec3(1.0, 0.0, 0.0);+ vec3 tangent = normalize(cross(helper, normal));+ vec3 bitangent = cross(normal, tangent);+ float alphaSquared = pow(roughness, 4.0);+ float texelSolidAngle = 4.0 * PI / (sourceSize.x * sourceSize.y);+ vec3 total = vec3(0.0);+ float totalWeight = 0.0;+ for (uint index = 0u; index < SAMPLE_COUNT; index++) {+ float firstRandom = float(index) / float(SAMPLE_COUNT);+ float secondRandom = radicalInverse(index);+ float cosineHalf = sqrt((1.0 - secondRandom) / (1.0 + (alphaSquared - 1.0) * secondRandom));+ float sineHalf = sqrt(max(1.0 - cosineHalf * cosineHalf, 0.0));+ float azimuth = 2.0 * PI * firstRandom;+ vec3 halfway = tangent * (sineHalf * cos(azimuth)) + bitangent * (sineHalf * sin(azimuth)) + normal * cosineHalf;+ vec3 light = reflect(-normal, halfway);+ float normalLight = dot(normal, light);+ if (normalLight <= 0.0) continue;+ float denominator = cosineHalf * cosineHalf * (alphaSquared - 1.0) + 1.0;+ float distribution = alphaSquared / (PI * denominator * denominator);+ // With N = V the half-vector density reduces to D / 4.+ float sampleSolidAngle = 1.0 / (float(SAMPLE_COUNT) * distribution * 0.25 + 0.0001);+ // Sampling a coarser source level for wide lobes keeps a bright sun from leaving fireflies.+ float sourceLevel = max(0.5 * log2(sampleSolidAngle / texelSolidAngle) + 1.0, 0.0);+ total += textureLod(sourceMap, equirectangularFromDirection(light), sourceLevel).rgb * normalLight;+ totalWeight += normalLight;+ }+ outputColor = vec4(min(total / max(totalWeight, 0.0001), 65000.0), 1.0);+}`;++const brdfFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+out vec4 outputColor;+const float PI = 3.14159265359;+const uint SAMPLE_COUNT = 256u;+float radicalInverse(uint bits) {+ bits = (bits << 16u) | (bits >> 16u);+ bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);+ bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);+ bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);+ bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);+ return float(bits) * 2.3283064365386963e-10;+}+void main() {+ float normalView = max(textureCoordinate.x, 0.001);+ float roughness = max(textureCoordinate.y, 0.02);+ float alpha = roughness * roughness;+ float alphaSquared = alpha * alpha;+ float visibilityBias = alpha * 0.5;+ vec3 view = vec3(sqrt(1.0 - normalView * normalView), 0.0, normalView);+ float scale = 0.0;+ float offset = 0.0;+ for (uint index = 0u; index < SAMPLE_COUNT; index++) {+ float firstRandom = float(index) / float(SAMPLE_COUNT);+ float secondRandom = radicalInverse(index);+ float cosineHalf = sqrt((1.0 - secondRandom) / (1.0 + (alphaSquared - 1.0) * secondRandom));+ float sineHalf = sqrt(max(1.0 - cosineHalf * cosineHalf, 0.0));+ float azimuth = 2.0 * PI * firstRandom;+ vec3 halfway = vec3(sineHalf * cos(azimuth), sineHalf * sin(azimuth), cosineHalf);+ vec3 light = 2.0 * dot(view, halfway) * halfway - view;+ float normalLight = max(light.z, 0.0);+ float normalHalf = max(halfway.z, 0.0);+ float viewHalf = max(dot(view, halfway), 0.0);+ if (normalLight <= 0.0) continue;+ float geometry = (normalLight / (normalLight * (1.0 - visibilityBias) + visibilityBias)) * (normalView / (normalView * (1.0 - visibilityBias) + visibilityBias));+ float visibility = geometry * viewHalf / max(normalHalf * normalView, 0.0001);+ float fresnelTerm = pow(1.0 - viewHalf, 5.0);+ scale += (1.0 - fresnelTerm) * visibility;+ offset += fresnelTerm * visibility;+ }+ outputColor = vec4(scale / float(SAMPLE_COUNT), offset / float(SAMPLE_COUNT), 0.0, 1.0);+}`;++// Shared lookup: rotation, intensity and the prefiltered chain, sampled by direction and roughness level.+export const environmentLookupGlsl = `+uniform sampler2D environmentSpecular;+uniform vec2 environmentRotation;+uniform float environmentIntensity;+uniform float environmentLevelMax;+${equirectangularGlsl}+vec3 environmentDirection(vec3 direction) {+ return vec3(environmentRotation.x * direction.x - environmentRotation.y * direction.z, direction.y, environmentRotation.y * direction.x + environmentRotation.x * direction.z);+}+vec3 environmentRadiance(vec3 direction, float level) {+ return textureLod(environmentSpecular, equirectangularFromDirection(environmentDirection(direction)), level).rgb * environmentIntensity;+}+`;++export const environmentShadingGlsl = `+uniform sampler2D environmentBrdf;+uniform float environmentEnabled;+uniform vec3 environmentIrradiance[9];+vec3 environmentDiffuse(vec3 normal) {+ vec3 mapped = environmentDirection(normal);+ vec3 result = environmentIrradiance[0]+ + environmentIrradiance[1] * mapped.y+ + environmentIrradiance[2] * mapped.z+ + environmentIrradiance[3] * mapped.x+ + environmentIrradiance[4] * (mapped.x * mapped.y)+ + environmentIrradiance[5] * (mapped.y * mapped.z)+ + environmentIrradiance[6] * (3.0 * mapped.z * mapped.z - 1.0)+ + environmentIrradiance[7] * (mapped.x * mapped.z)+ + environmentIrradiance[8] * (mapped.x * mapped.x - mapped.y * mapped.y);+ return max(result, vec3(0.0)) * environmentIntensity;+}+vec3 environmentLighting(vec3 normal, vec3 viewDirection, vec3 color, float metallic, float roughness, float occlusion, float ambient) {+ float normalView = clamp(dot(normal, viewDirection), 0.001, 1.0);+ vec3 baseReflectance = mix(vec3(0.04), color, metallic);+ vec2 lookup = texture(environmentBrdf, vec2(normalView, roughness)).rg;+ vec3 specularColor = baseReflectance * lookup.x + lookup.y;+ vec3 specular = environmentRadiance(reflect(-viewDirection, normal), roughness * environmentLevelMax) * specularColor;+ vec3 diffuse = environmentDiffuse(normal) * color * (1.0 - metallic) * (1.0 - specularColor);+ return (specular + diffuse) * occlusion * ambient;+}+`;++export const environmentBackgroundFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+uniform mat4 inverseViewProjection;+uniform vec3 eye;+uniform float backgroundLevel;+uniform float exposure;+uniform float hdrEnabled;+out vec4 outputColor;+${environmentLookupGlsl}+vec3 toneMap(vec3 color) {+ return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);+}+void main() {+ vec4 world = inverseViewProjection * vec4(textureCoordinate * 2.0 - 1.0, 1.0, 1.0);+ vec3 direction = normalize(world.xyz / world.w - eye);+ vec3 radiance = environmentRadiance(direction, backgroundLevel);+ outputColor = vec4(hdrEnabled > 0.5 ? min(radiance * exposure, vec3(65504.0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);+}`;++function createHalfFloatTexture(context, internalFormat, levelCount, width, height, { wrapHorizontally }) {+ const texture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, texture);+ context.texStorage2D(context.TEXTURE_2D, levelCount, internalFormat, width, height);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, levelCount > 1 ? context.LINEAR_MIPMAP_LINEAR : context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, wrapHorizontally ? context.REPEAT : context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ return texture;+}++function drawIntoLevel(context, framebuffer, texture, level, width, height) {+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, level);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Environment prefilter framebuffer is incomplete.');+ context.viewport(0, 0, width, height);+ context.drawArrays(context.TRIANGLES, 0, 3);+}++// Prefilters once at load: GGX-convolved equirect mip chain (level = roughness), split-sum BRDF lookup and L2 spherical harmonics.+export function createEnvironmentResources(context, map, { compileProgram, fullscreenVertex }) {+ assertEnvironmentMap(map);+ if (!context.getExtension('EXT_color_buffer_float')) throw new Error('Environment maps require EXT_color_buffer_float.');+ const started = performance.now();+ const layout = environmentSpecularLayout(map);+ const sourceLevelCount = Math.floor(Math.log2(Math.max(map.width, map.height))) + 1;+ const sourceTexture = createHalfFloatTexture(context, context.RGBA16F, sourceLevelCount, map.width, map.height, { wrapHorizontally: true });+ context.texSubImage2D(context.TEXTURE_2D, 0, 0, 0, map.width, map.height, context.RGBA, context.FLOAT, paddedHalfFloatSource(map));+ context.generateMipmap(context.TEXTURE_2D);+ const specularTexture = createHalfFloatTexture(context, context.RGBA16F, layout.levelCount, layout.width, layout.height, { wrapHorizontally: true });+ const brdfTexture = createHalfFloatTexture(context, context.RG16F, 1, ENVIRONMENT_BRDF_SIZE, ENVIRONMENT_BRDF_SIZE, { wrapHorizontally: false });+ const framebuffer = context.createFramebuffer();+ const prefilterProgram = compileProgram(context, fullscreenVertex, prefilterFragment);+ const brdfProgram = compileProgram(context, fullscreenVertex, brdfFragment);+ context.disable(context.DEPTH_TEST);+ context.disable(context.CULL_FACE);+ context.disable(context.BLEND);+ context.disable(context.SCISSOR_TEST);+ context.bindVertexArray(null);+ context.useProgram(prefilterProgram);+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D, sourceTexture);+ context.uniform1i(context.getUniformLocation(prefilterProgram, 'sourceMap'), 0);+ context.uniform2f(context.getUniformLocation(prefilterProgram, 'sourceSize'), map.width, map.height);+ const roughnessUniform = context.getUniformLocation(prefilterProgram, 'roughness');+ const levelOffsetUniform = context.getUniformLocation(prefilterProgram, 'sourceLevelOffset');+ for (let level = 0; level < layout.levelCount; level++) {+ context.uniform1f(roughnessUniform, level / Math.max(1, layout.levelCount - 1));+ context.uniform1f(levelOffsetUniform, Math.max(0, Math.log2(map.width / layout.levels[level].width)));+ drawIntoLevel(context, framebuffer, specularTexture, level, layout.levels[level].width, layout.levels[level].height);+ }+ context.useProgram(brdfProgram);+ drawIntoLevel(context, framebuffer, brdfTexture, 0, ENVIRONMENT_BRDF_SIZE, ENVIRONMENT_BRDF_SIZE);+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ context.deleteFramebuffer(framebuffer);+ context.deleteProgram(prefilterProgram);+ context.deleteProgram(brdfProgram);+ context.deleteTexture(sourceTexture);+ context.finish();+ return {+ data: map.data,+ specularTexture,+ brdfTexture,+ levelCount: layout.levelCount,+ bytes: layout.bytes,+ irradiance: computeIrradianceCoefficients(map),+ prefilterMilliseconds: performance.now() - started,+ dispose() {+ context.deleteTexture(specularTexture);+ context.deleteTexture(brdfTexture);+ },+ };+}diff --git a/src/hdri.js b/src/hdri.jsnew file mode 100644index 00000000..a065b380--- /dev/null+++ b/src/hdri.js@@ -0,0 +1,107 @@+import { createEnvironmentMap, MAXIMUM_ENVIRONMENT_SIZE } from './environment.js';++const MAXIMUM_FILE_BYTES = 256 * 1024 ** 2;+const MINIMUM_RUN_LENGTH_WIDTH = 8;+const MAXIMUM_RUN_LENGTH_WIDTH = 32767;++function readLine(bytes, start) {+ let end = start;+ while (end < bytes.length && bytes[end] !== 0x0a) end++;+ if (end >= bytes.length) throw new Error('Radiance HDR header is truncated.');+ const text = String.fromCharCode(...bytes.subarray(start, Math.min(end, start + 256)));+ return { text: text.replace(/\r$/, ''), next: end + 1 };+}++function parseHeader(bytes) {+ let line = readLine(bytes, 0);+ if (!line.text.startsWith('#?')) throw new Error('Not a Radiance HDR file: missing #? signature.');+ let formatFound = false;+ let position = line.next;+ for (;;) {+ line = readLine(bytes, position);+ position = line.next;+ if (line.text === '') break;+ if (line.text.startsWith('FORMAT=')) {+ if (line.text !== 'FORMAT=32-bit_rle_rgbe') throw new Error(`Unsupported Radiance HDR format: ${line.text}.`);+ formatFound = true;+ }+ }+ if (!formatFound) throw new Error('Radiance HDR header has no FORMAT=32-bit_rle_rgbe line.');+ line = readLine(bytes, position);+ const resolution = /^-Y (\d+) \+X (\d+)$/.exec(line.text);+ if (!resolution) throw new Error('Unsupported Radiance HDR orientation. Only "-Y height +X width" is supported.');+ const height = Number(resolution[1]);+ const width = Number(resolution[2]);+ if (width < 1 || height < 1 || width > MAXIMUM_ENVIRONMENT_SIZE || height > MAXIMUM_ENVIRONMENT_SIZE) throw new RangeError('Radiance HDR dimensions are outside the supported range.');+ return { width, height, dataStart: line.next };+}++function readRunLengthScanline(bytes, startPosition, width, scanline) {+ let position = startPosition + 4;+ for (let channel = 0; channel < 4; channel++) {+ let column = 0;+ while (column < width) {+ if (position >= bytes.length) throw new Error('Radiance HDR pixel data is truncated.');+ const count = bytes[position++];+ const isRun = count > 128;+ const length = isRun ? count - 128 : count;+ if (length === 0 || column + length > width) throw new Error('Radiance HDR run length is invalid.');+ if (isRun) {+ if (position >= bytes.length) throw new Error('Radiance HDR pixel data is truncated.');+ const value = bytes[position++];+ for (let index = 0; index < length; index++) scanline[(column + index) * 4 + channel] = value;+ } else {+ if (position + length > bytes.length) throw new Error('Radiance HDR pixel data is truncated.');+ for (let index = 0; index < length; index++) scanline[(column + index) * 4 + channel] = bytes[position + index];+ position += length;+ }+ column += length;+ }+ }+ return position;+}++function startsRunLengthScanline(bytes, position, width) {+ return width >= MINIMUM_RUN_LENGTH_WIDTH && width <= MAXIMUM_RUN_LENGTH_WIDTH+ && bytes[position] === 2 && bytes[position + 1] === 2+ && ((bytes[position + 2] << 8) | bytes[position + 3]) === width;+}++// Parses Radiance RGBE (.hdr) data into linear RGB floats, top row first.+export function parseRadianceHdr(buffer) {+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);+ if (bytes.length > MAXIMUM_FILE_BYTES) throw new RangeError('Radiance HDR file is larger than 256 MiB.');+ const { width, height, dataStart } = parseHeader(bytes);+ const data = new Float32Array(width * height * 3);+ const scanline = new Uint8Array(width * 4);+ let position = dataStart;+ for (let row = 0; row < height; row++) {+ if (startsRunLengthScanline(bytes, position, width)) {+ position = readRunLengthScanline(bytes, position, width, scanline);+ } else {+ if (position + width * 4 > bytes.length) throw new Error('Radiance HDR pixel data is truncated.');+ scanline.set(bytes.subarray(position, position + width * 4));+ position += width * 4;+ }+ for (let column = 0; column < width; column++) {+ const exponent = scanline[column * 4 + 3];+ const target = (row * width + column) * 3;+ if (exponent === 0) continue;+ const scale = 2 ** (exponent - 136);+ data[target] = scanline[column * 4] * scale;+ data[target + 1] = scanline[column * 4 + 1] * scale;+ data[target + 2] = scanline[column * 4 + 2] * scale;+ }+ }+ return { width, height, data };+}++// Fetches a .hdr file (for example a 1k or 2k Poly Haven HDRI) and returns an environment map descriptor.+export async function loadHdri(url, { intensity, rotation, showBackground, backgroundBlur, signal, fetchImplementation = globalThis.fetch } = {}) {+ const response = await fetchImplementation(url, { signal });+ if (!response.ok) throw new Error(`HDRI download failed: HTTP ${response.status}.`);+ const parsed = parseRadianceHdr(await response.arrayBuffer());+ return createEnvironmentMap({ ...parsed, intensity, rotation, showBackground, backgroundBlur });+}++export { createEnvironmentMap };diff --git a/src/index.js b/src/index.jsindex ee32db44..e8509045 100644--- a/src/index.js+++ b/src/index.js@@ -8,6 +8,7 @@ export { createAnimationMixer } from './animation-mixer.js';export { createSceneGraph } from './scene-graph.js';export { createSkinPose, updateSkinPose } from './skinning.js';export { createMorphPose, MAX_MORPH_TARGETS } from './morph.js';+export { createEnvironmentMap } from './environment.js';export { RENDER_PRESETS, planRenderSize, estimateFrameBytes } from './budget.js';export { assemblyOffset } from './assembly.js';diff --git a/src/renderer.js b/src/renderer.jsindex 58b19af1..32518c18 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -6,6 +6,7 @@ import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';import { resolveVolumeFog } from './volumetric.js';+import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, estimateEnvironmentBytes } from './environment.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';import { validateMorphGeometry, validateMorphPose, validateMorphTransform, packMorphTargets } from './morph.js';@@ -19,6 +20,9 @@ const DEFAULT_NORMAL_SCALE = [1, 1];const PROCEDURAL_MATERIAL_TAGS = new Set(['water', 'foliage', 'grass', 'terrain', 'floor', 'fire', 'smoke']);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_SPECULAR_UNIT = 9;+const ENVIRONMENT_BRDF_UNIT = 10;function validateMaterialMaps(material) {if (PROCEDURAL_MATERIAL_TAGS.has(material.tag)) {@@ -274,6 +278,10 @@ export class Renderer67 {}}this.capabilities.maximumTextureSize = textureLimit;+ this.environmentResources = null;+ this.environmentBackgroundProgram = null;+ this.environmentBytes = !benchmark && environment.map ? estimateEnvironmentBytes(environment.map, textureLimit) : 0;+ this.textureBytes += this.environmentBytes;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.');@@ -296,6 +304,7 @@ export class Renderer67 {for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);}+ for (const name of ENVIRONMENT_UNIFORMS) this.uniforms[name] = this.context.getUniformLocation(this.program, name);this.depthSkinUniforms = Object.fromEntries(SKIN_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));this.depthMorphUniforms = Object.fromEntries(MORPH_UNIFORMS.map(name => [name, this.context.getUniformLocation(this.depthProgram, name)]));if (!benchmark) {@@ -325,6 +334,7 @@ export class Renderer67 {this.context.activeTexture(this.context.TEXTURE0 + unit);this.context.bindTexture(this.context.TEXTURE_2D, this.whiteTexture);}+ this.initializeEnvironment(environment.map);groups.forEach((group) => this.batches.push(this.uploadBatch(group)));this.createShadowMap();this.resize();@@ -812,6 +822,84 @@ export class Renderer67 {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);+ 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) {+ const context = this.context;+ context.uniform1f(this.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);+ }++ 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 };@@ -964,6 +1052,7 @@ export class Renderer67 {this.assemblyAmount = assemblyAmount;this.createShadowMap();}+ const environmentMap = this.activateEnvironment(environment.map);applyProjection(this.projection, frame, this.canvas.width / this.canvas.height, { world: this.world });mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);mat4.multiply(this.viewProjection, this.projection, this.view);@@ -976,7 +1065,8 @@ export class Renderer67 {context.clearColor(0.145, 0.162, 0.177, 1);}context.clear(context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT);- if (this.world && !this.benchmark) this.drawSky(frame);+ const environmentBackgroundDrawn = this.drawEnvironmentBackground(environmentMap, frame, exposure);+ if (this.world && !this.benchmark && !environmentBackgroundDrawn) this.drawSky(frame);context.enable(context.DEPTH_TEST);context.enable(context.CULL_FACE);context.useProgram(this.program);@@ -1010,6 +1100,7 @@ export class Renderer67 {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);context.bindVertexArray(null);if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);@@ -1028,6 +1119,8 @@ export class Renderer67 {if (this.postProgram) this.context.deleteProgram(this.postProgram);if (this.skyProgram) this.context.deleteProgram(this.skyProgram);if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);+ if (this.environmentBackgroundProgram) this.context.deleteProgram(this.environmentBackgroundProgram);+ this.environmentResources?.dispose();for (const texture of this.textures.values()) this.context.deleteTexture(texture);this.textures.clear();for (const cache of [this.skinTextures, this.influenceTextures, this.morphTextures]) {diff --git a/src/shaders.js b/src/shaders.jsindex 55aa29cb..e3ed42e5 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -1,4 +1,5 @@import { MAX_MORPH_TARGETS } from './morph.js';+import { environmentLookupGlsl, environmentShadingGlsl } from './environment.js';const morphingShader = `uniform float morphEnabled;@@ -263,6 +264,8 @@ vec3 studio(vec3 direction, float roughness) {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);}+${environmentLookupGlsl}+${environmentShadingGlsl}vec3 illuminate(vec3 normal, vec3 viewDirection, vec3 lightDirection, vec3 radiance, vec3 color, float metallic, float roughness) {float normalLight = max(dot(normal, lightDirection), 0.0);@@ -396,8 +399,12 @@ void main() {vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));float occlusion = 1.0;if (hasOcclusionMap > 0.5) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);- radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;- radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;+ if (environmentEnabled > 0.5) {+ radiance += environmentLighting(normal, viewDirection, color, metallic, roughness, occlusion, ambientIntensity);+ } else {+ radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;+ radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;+ }vec3 keyResponse = keyColor / mix(vec3(5.2, 4.7, 4.1), vec3(3.7, 3.4, 2.9), worldMode);keyResponse *= mix(daylight, 1.0, worldMode);if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * keyResponse;diff --git a/tests/environment.test.js b/tests/environment.test.jsnew file mode 100644index 00000000..c8afd3bd--- /dev/null+++ b/tests/environment.test.js@@ -0,0 +1,122 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { createEnvironmentMap, computeIrradianceCoefficients, evaluateIrradiance, estimateEnvironmentBytes, environmentSpecularLayout, ENVIRONMENT_BRDF_SIZE } from '../src/environment.js';+import { parseRadianceHdr, loadHdri } from '../src/hdri.js';++function filledMap(width, height, fillPixel, extra = {}) {+ const data = new Float32Array(width * height * 3);+ for (let row = 0; row < height; row++) {+ for (let column = 0; column < width; column++) {+ data.set(fillPixel(column, row), (row * width + column) * 3);+ }+ }+ return createEnvironmentMap({ width, height, data, ...extra });+}++function hdrHeader(width, height) {+ return `#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y ${height} +X ${width}\n`;+}++function concatenate(...parts) {+ const total = parts.reduce((sum, part) => sum + part.length, 0);+ const result = new Uint8Array(total);+ let offset = 0;+ for (const part of parts) {+ result.set(part, offset);+ offset += part.length;+ }+ return result;+}++test('spherical harmonic irradiance of a constant environment is constant in every direction', () => {+ const map = filledMap(64, 32, () => [0.5, 1, 2]);+ const coefficients = computeIrradianceCoefficients(map);+ for (const normal of [[0, 1, 0], [0, -1, 0], [1, 0, 0], [0, 0, -1], [0.577, 0.577, 0.577]]) {+ const irradiance = evaluateIrradiance(coefficients, normal);+ assert.ok(Math.abs(irradiance[0] - 0.5) < 0.01, `red ${irradiance[0]}`);+ assert.ok(Math.abs(irradiance[1] - 1) < 0.01, `green ${irradiance[1]}`);+ assert.ok(Math.abs(irradiance[2] - 2) < 0.02, `blue ${irradiance[2]}`);+ }+});++test('spherical harmonic irradiance follows a sky above, ground below split', () => {+ const map = filledMap(64, 32, (column, row) => (row < 16 ? [1, 1, 1] : [0, 0, 0]));+ const coefficients = computeIrradianceCoefficients(map);+ const up = evaluateIrradiance(coefficients, [0, 1, 0])[0];+ const down = evaluateIrradiance(coefficients, [0, -1, 0])[0];+ const side = evaluateIrradiance(coefficients, [1, 0, 0])[0];+ assert.ok(up > 0.9 && up < 1.05, `up ${up}`);+ assert.ok(down < 0.1, `down ${down}`);+ assert.ok(Math.abs(side - 0.5) < 0.05, `side ${side}`);+});++test('RGBE parsing decodes flat and run-length scanlines', () => {+ const flatPixels = Uint8Array.from([128, 64, 0, 129, 0, 0, 0, 0, 255, 255, 255, 128, 1, 2, 3, 136]);+ const flat = parseRadianceHdr(concatenate(new TextEncoder().encode(hdrHeader(4, 1)), flatPixels));+ assert.equal(flat.width, 4);+ assert.equal(flat.height, 1);+ assert.deepEqual(Array.from(flat.data.slice(0, 6)), [1, 0.5, 0, 0, 0, 0]);+ assert.ok(Math.abs(flat.data[6] - 255 / 256) < 1e-6);+ assert.deepEqual(Array.from(flat.data.slice(9, 12)), [1, 2, 3]);++ const width = 8;+ const runLengthRow = [2, 2, 0, width];+ for (const value of [128, 64, 32, 130]) runLengthRow.push(128 + width, value);+ const encoded = parseRadianceHdr(concatenate(new TextEncoder().encode(hdrHeader(width, 1)), Uint8Array.from(runLengthRow)));+ assert.deepEqual(Array.from(encoded.data.slice(0, 3)), [2, 1, 0.5]);+ assert.deepEqual(Array.from(encoded.data.slice(21, 24)), [2, 1, 0.5]);+});++test('RGBE parsing rejects malformed files', () => {+ const encoder = new TextEncoder();+ assert.throws(() => parseRadianceHdr(encoder.encode('not an hdr\n')), /#\?/);+ assert.throws(() => parseRadianceHdr(encoder.encode('#?RADIANCE\nFORMAT=32-bit_rle_xyze\n\n-Y 1 +X 1\n')), /Unsupported Radiance HDR format/);+ assert.throws(() => parseRadianceHdr(encoder.encode('#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n+Y 1 +X 1\n')), /orientation/);+ assert.throws(() => parseRadianceHdr(concatenate(encoder.encode(hdrHeader(4, 1)), Uint8Array.from([1, 2, 3]))), /truncated/);+ const badRun = concatenate(encoder.encode(hdrHeader(8, 1)), Uint8Array.from([2, 2, 0, 8, 128 + 9, 1]));+ assert.throws(() => parseRadianceHdr(badRun), /run length/);+});++test('loadHdri fetches and wraps the parsed file in an environment map', async () => {+ const bytes = concatenate(new TextEncoder().encode(hdrHeader(4, 2)), new Uint8Array(4 * 2 * 4).fill(128));+ const fetchImplementation = async (url) => ({ ok: url.endsWith('.hdr'), status: 200, arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) });+ const map = await loadHdri('sky.hdr', { intensity: 2, showBackground: true, fetchImplementation });+ assert.equal(map.width, 4);+ assert.equal(map.intensity, 2);+ assert.equal(map.showBackground, true);+ await assert.rejects(loadHdri('sky.png', { fetchImplementation }), /HTTP/);+});++test('environment map validation names the offending field', () => {+ const data = new Float32Array(8 * 4 * 3);+ assert.throws(() => createEnvironmentMap({ width: 8.5, height: 4, data }), /width/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data: new Float32Array(10) }), /data length/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data: Array.from(data) }), /Float32Array/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data, intensity: -1 }), /intensity/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data, rotation: Number.NaN }), /rotation/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data, backgroundBlur: 2 }), /backgroundBlur/);+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data, showBackground: 'yes' }), /showBackground/);+ const infinite = new Float32Array(data);+ infinite[5] = Number.POSITIVE_INFINITY;+ assert.throws(() => createEnvironmentMap({ width: 8, height: 4, data: infinite }), /finite/);+ const map = createEnvironmentMap({ width: 8, height: 4, data });+ assert.equal(Object.isFrozen(map), true);+ assert.equal(map.channels, 3);+ assert.equal(createEnvironmentMap({ width: 8, height: 4, data: new Float32Array(8 * 4 * 4) }).channels, 4);+});++test('environment memory accounting counts the half-float chain and the BRDF lookup', () => {+ const map = { kind: 'environment-map', width: 2048, height: 1024, channels: 3, data: new Float32Array(2048 * 1024 * 3), intensity: 1, rotation: 0, showBackground: false, backgroundBlur: 0 };+ const layout = environmentSpecularLayout(map);+ assert.equal(layout.width, 1024);+ assert.equal(layout.height, 512);+ assert.equal(layout.levelCount, 7);+ let expected = ENVIRONMENT_BRDF_SIZE * ENVIRONMENT_BRDF_SIZE * 4;+ for (let level = 0; level < 7; level++) expected += (1024 >> level) * (512 >> level) * 8;+ assert.equal(estimateEnvironmentBytes(map, 4096), expected);+ assert.ok(expected < 8 * 1024 ** 2);+ assert.throws(() => estimateEnvironmentBytes(map, 1024), /texture limit/);+ const small = createEnvironmentMap({ width: 16, height: 8, data: new Float32Array(16 * 8 * 3) });+ assert.equal(environmentSpecularLayout(small).levelCount, 5);+ assert.throws(() => estimateEnvironmentBytes({ ...small, data: new Float32Array(3) }, 4096), /data length/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 2dbbd098..3717fc4c 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -27,6 +27,7 @@ export default defineConfig({physics: 'src/physics.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`,