Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add retained animation buffers and bounded HDR material effects

Nguyen Xuan Ana9cde141ff23
diff --git a/src/budget.js b/src/budget.js
index 609a7ad3..7494d12f 100644
--- a/src/budget.js
+++ b/src/budget.js
@@ -7,22 +7,45 @@ export const RENDER_PRESETS = Object.freeze({
cpu: { width: 640, height: 360, samples: 1, fps: 12, memoryBudgetMiB: 192 },
});
-export function estimateFrameBytes(width, height, samples, shadowResolution = 2048) {
+export function estimateTextureBytes(width, height, { mipmaps = true } = {}) {
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0) throw new Error('Texture dimensions must be positive integers.');
+ let bytes = 0;
+ do {
+ bytes += width * height * 4;
+ if (!mipmaps || (width === 1 && height === 1)) break;
+ width = Math.max(1, Math.floor(width / 2));
+ height = Math.max(1, Math.floor(height / 2));
+ } while (true);
+ return bytes;
+}
+
+export function estimateFrameBytes(width, height, samples, shadowResolution = 2048, { hdr = false, bloom = false } = {}) {
// Color/depth MSAA, resolve texture, browser buffers and one screenshot/encoder staging frame.
- return width * height * (8 * Math.max(1, samples) + 20) + shadowResolution ** 2 * 4;
+ const colorBytes = hdr ? 8 : 4;
+ const frameBytes = width * height * ((colorBytes + 4) * Math.max(1, samples) + colorBytes + 16);
+ const bloomBytes = bloom ? Math.ceil(width / 2) * Math.ceil(height / 2) * colorBytes * 2 : 0;
+ return frameBytes + bloomBytes + shadowResolution ** 2 * 4;
}
-export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memoryBudgetMiB = 256, geometryBytes = 0, shadowResolution = 2048, maximumSize = 8192 }) {
+export function planRenderSize({ width, height, pixelRatio = 1, samples = 4, memoryBudgetMiB = 256, geometryBytes = 0, textureBytes = 0, hdr = false, bloom = false, shadowResolution = 2048, maximumSize = 8192 }) {
for (const value of [width, height, pixelRatio, samples, memoryBudgetMiB, maximumSize]) {
if (!Number.isFinite(value) || value <= 0) throw new Error('Render dimensions, sample count and budget must be positive finite numbers.');
}
if (geometryBytes < 0 || !Number.isFinite(geometryBytes)) throw new Error('Geometry memory must be a nonnegative finite number.');
- const available = memoryBudgetMiB * MEBIBYTE - geometryBytes - shadowResolution ** 2 * 4;
- if (available < 64 * 64 * (8 * samples + 20)) throw new Error('Memory budget cannot hold the scene and a minimum render target. Lower scene detail or increase the budget.');
+ if (textureBytes < 0 || !Number.isFinite(textureBytes)) throw new Error('Texture memory must be a nonnegative finite number.');
+ if (!Number.isFinite(shadowResolution) || shadowResolution < 0) throw new Error('Shadow resolution must be nonnegative and finite.');
+ const available = memoryBudgetMiB * MEBIBYTE - geometryBytes - textureBytes - shadowResolution ** 2 * 4;
+ const bytesPerPixel = (hdr ? 12 : 8) * Math.max(1, samples) + (hdr ? 24 : 20) + (bloom ? hdr ? 4 : 2 : 0);
+ if (available < estimateFrameBytes(64, 64, samples, 0, { hdr, bloom })) throw new Error('Memory budget cannot hold the scene and a minimum render target. Lower scene detail or increase the budget.');
const requestedWidth = Math.max(1, Math.round(width * pixelRatio));
const requestedHeight = Math.max(1, Math.round(height * pixelRatio));
- const scale = Math.min(1, maximumSize / requestedWidth, maximumSize / requestedHeight, Math.sqrt(available / (requestedWidth * requestedHeight * (8 * samples + 20))));
- const renderWidth = Math.max(1, Math.floor(requestedWidth * scale));
- const renderHeight = Math.max(1, Math.floor(requestedHeight * scale));
- return { width: renderWidth, height: renderHeight, samples, estimatedBytes: estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution) + geometryBytes, reduced: scale < 1 };
+ const scale = Math.min(1, maximumSize / requestedWidth, maximumSize / requestedHeight, Math.sqrt(available / (requestedWidth * requestedHeight * bytesPerPixel)));
+ let renderWidth = Math.max(1, Math.floor(requestedWidth * scale));
+ let renderHeight = Math.max(1, Math.floor(requestedHeight * scale));
+ const budget = memoryBudgetMiB * MEBIBYTE;
+ while (estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom }) + geometryBytes + textureBytes > budget) {
+ renderWidth = Math.max(1, renderWidth - 1);
+ renderHeight = Math.max(1, renderHeight - 1);
+ }
+ return { width: renderWidth, height: renderHeight, samples, hdr, bloom, textureBytes, estimatedBytes: estimateFrameBytes(renderWidth, renderHeight, samples, shadowResolution, { hdr, bloom }) + geometryBytes + textureBytes, reduced: renderWidth < requestedWidth || renderHeight < requestedHeight };
}
diff --git a/src/post.js b/src/post.js
index 590eaf9f..f800a50e 100644
--- a/src/post.js
+++ b/src/post.js
@@ -11,6 +11,12 @@ export const postFragment = `#version 300 es
precision highp float;
in vec2 textureCoordinate;
uniform sampler2D frameTexture;
+uniform sampler2D bloomTexture;
+uniform float bloomStrength;
+uniform float hdrEnabled;
+uniform vec3 grade;
+uniform float vignette;
+uniform float grainAmount;
uniform vec2 resolution;
uniform float monochrome;
uniform float fade;
@@ -93,12 +99,20 @@ void main() {
float secondLuma = luminance(second);
vec3 color = secondLuma < minimumLuma || secondLuma > maximumLuma ? first : second;
if (maximumLuma - minimumLuma < max(0.03, maximumLuma * 0.125)) color = center;
+ if (bloomStrength > 0.0) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;
+ if (hdrEnabled > 0.5) {
+ color = clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);
+ color = pow(color, vec3(1.0 / 2.2));
+ }
if (volumeExplosion > 0.5) color = explosion(color);
color = mix(color, vec3(luminance(color)), monochrome);
+ if (grade.x != 1.0) color = mix(vec3(luminance(color)), color, grade.x);
+ if (grade.y != 1.0) color = (color - 0.5) * grade.y + 0.5;
+ if (grade.z != 0.0) color *= vec3(1.0 + grade.z * 0.1, 1.0, 1.0 - grade.z * 0.1);
vec2 centered = textureCoordinate * 2.0 - 1.0;
- color *= 1.0 - cinematic * 0.20 * dot(centered, centered);
+ color *= max(0.0, 1.0 - (cinematic * 0.20 + vignette) * dot(centered, centered));
float grain = fract(sin(dot(gl_FragCoord.xy + floor(time * 24.0), vec2(12.9898, 78.233))) * 43758.5453) - 0.5;
- color += grain * 0.018 * cinematic;
+ color += grain * (0.018 * cinematic + grainAmount);
outputColor = vec4(color * (1.0 - fade), 1.0);
}`;
@@ -112,6 +126,7 @@ uniform mat4 inverseViewProjection;
uniform vec3 eye;
uniform float time;
uniform float daylight;
+uniform float hdrEnabled;
out vec4 outputColor;
float noise(vec2 position) {
return sin(position.x * 2.1 + sin(position.y * 1.3)) * 0.5 + sin(position.y * 2.8 - position.x * 0.8) * 0.3;
@@ -128,5 +143,30 @@ void main() {
float cloud = smoothstep(0.1, 0.55, noise(cloudPosition) + noise(cloudPosition * 2.4) * 0.25);
cloud *= smoothstep(0.02, 0.22, direction.y) * (1.0 - smoothstep(0.5, 0.95, direction.y));
color = mix(color, mix(skyBottom, vec3(0.94, 0.93, 0.85), 0.7), cloud * 0.28 * daylight);
+ outputColor = vec4(hdrEnabled > 0.5 ? pow(max(color, vec3(0)), vec3(2.2)) : color, 1.0);
+}`;
+
+export const bloomFragment = `#version 300 es
+precision highp float;
+in vec2 textureCoordinate;
+uniform sampler2D sourceTexture;
+uniform vec2 texelDirection;
+uniform float threshold;
+uniform float extract;
+out vec4 outputColor;
+vec3 sampleBloom(vec2 coordinate) {
+ vec3 color = texture(sourceTexture, coordinate).rgb;
+ if (extract > 0.5) {
+ float peak = max(color.r, max(color.g, color.b));
+ color *= max(peak - threshold, 0.0) / max(peak, 0.00001);
+ }
+ return color;
+}
+void main() {
+ vec3 color = sampleBloom(textureCoordinate) * 0.227027;
+ color += sampleBloom(textureCoordinate + texelDirection * 1.384615) * 0.316216;
+ color += sampleBloom(textureCoordinate - texelDirection * 1.384615) * 0.316216;
+ color += sampleBloom(textureCoordinate + texelDirection * 3.230769) * 0.070270;
+ color += sampleBloom(textureCoordinate - texelDirection * 3.230769) * 0.070270;
outputColor = vec4(color, 1.0);
}`;
diff --git a/src/renderer.js b/src/renderer.js
index 2349fe32..c3e5aa67 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -1,9 +1,35 @@
import { mat4, mat3 } from 'gl-matrix';
import { vertexShader, fragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';
-import { fullscreenVertex, postFragment, skyFragment } from './post.js';
-import { planRenderSize } from './budget.js';
+import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './post.js';
+import { planRenderSize, estimateTextureBytes } from './budget.js';
+import { applyProjection } from './camera.js';
+import { resolveEffects } from './effects.js';
-const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9 };
+const MATERIAL_TAGS = { armor: 1, floor: 2, water: 3, foliage: 4, terrain: 5, grass: 7, fire: 8, smoke: 9, unlit: 10 };
+const INSTANCE_STRIDE = 41;
+
+function validateTransform(part) {
+ const finiteFloat = value => Number.isFinite(value) && Number.isFinite(Math.fround(value));
+ if (part.matrix?.length !== 16 || !Array.from(part.matrix).every(finiteFloat)) throw new Error(`Invalid transform: ${part.name}`);
+ const normalMatrix = mat3.normalFromMat4(mat3.create(), part.matrix);
+ if (!normalMatrix || !Array.from(normalMatrix).every(Number.isFinite)) throw new Error(`Singular transform: ${part.name}`);
+ for (const value of [part.material.color, part.material.emissiveColor ?? part.material.color, part.assembly?.offset ?? [0, 0, 0], part.assembly?.detailOffset ?? [0, 0, 0]]) {
+ if (value.length !== 3 || !Array.from(value).every(finiteFloat)) throw new Error(`Invalid instance vector: ${part.name}`);
+ }
+ if (![part.material.metallic, part.material.roughness, part.material.emission ?? 0].every(finiteFloat)) throw new Error(`Invalid material: ${part.name}`);
+ return normalMatrix;
+}
+
+function packInstance(data, index, part, normalMatrix) {
+ const offset = index * INSTANCE_STRIDE;
+ data.set(part.matrix, offset);
+ data.set(normalMatrix, offset + 16);
+ data.set(part.material.color, offset + 25);
+ data.set([part.material.metallic, part.material.roughness, part.material.emission ?? 0, MATERIAL_TAGS[part.material.tag] ?? 0], offset + 28);
+ data.set(part.assembly?.offset ?? [0, 0, 0], offset + 32);
+ data.set(part.assembly?.detailOffset ?? [0, 0, 0], offset + 35);
+ data.set(part.material.emissiveColor ?? part.material.color, offset + 38);
+}
function compileProgram(context, vertexSource, fragmentSource) {
const program = context.createProgram();
@@ -48,19 +74,44 @@ function groundPart() {
export function groupParts(parts, batching = true) {
const groups = new Map();
for (const part of parts) {
- if (part.matrix.length !== 16 || !Array.from(part.matrix).every(Number.isFinite)) {
- throw new Error(`Invalid transform: ${part.name}`);
- }
+ validateTransform(part);
const key = batching ? part.geometry : part;
- if (!groups.has(key)) groups.set(key, []);
- groups.get(key).push(part);
+ if (!groups.has(key)) groups.set(key, new Map());
+ const maps = groups.get(key);
+ const map = part.material.map ?? null;
+ if (!maps.has(map)) maps.set(map, []);
+ maps.get(map).push(part);
}
- return [...groups.values()];
+ return [...groups.values()].flatMap(maps => [...maps.values()]);
+}
+
+export function textureDescriptorInfo(map, maximumSize = Infinity) {
+ const width = map.image?.naturalWidth ?? map.image?.width;
+ const height = map.image?.naturalHeight ?? map.image?.height;
+ if (!Number.isInteger(width) || !Number.isInteger(height) || width <= 0 || height <= 0 || width > maximumSize || height > maximumSize) throw new Error('Texture image dimensions are invalid or exceed MAX_TEXTURE_SIZE.');
+ if ((map.uvChannel ?? 0) !== 0) throw new Error('Only texture UV channel 0 is supported.');
+ if (map.colorSpace && !['srgb', 'linear'].includes(map.colorSpace)) throw new Error('Texture color space must be srgb or linear.');
+ const wrapS = map.wrapS ?? 10497;
+ const wrapT = map.wrapT ?? 10497;
+ const minFilter = map.minFilter ?? 9987;
+ const magFilter = map.magFilter ?? 9729;
+ if (![10497, 33071, 33648].includes(wrapS) || ![10497, 33071, 33648].includes(wrapT)) throw new Error('Unsupported texture wrap mode.');
+ if (![9728, 9729, 9984, 9985, 9986, 9987].includes(minFilter) || ![9728, 9729].includes(magFilter)) throw new Error('Unsupported texture filtering mode.');
+ const mipmaps = minFilter >= 9984;
+ return { width, height, wrapS, wrapT, minFilter, magFilter, mipmaps, bytes: estimateTextureBytes(width, height, { mipmaps }) };
+}
+
+function sampleCount(context, format, requested) {
+ const colorCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, format, context.SAMPLES));
+ const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, context.DEPTH_COMPONENT24, context.SAMPLES));
+ return Math.max(0, ...colorCounts.filter(count => count <= requested && depthCounts.includes(count)));
}
export class Renderer67 {
- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, samples = 4, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {
+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, samples = 4, hdr = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {} } = {}) {
this.canvas = canvas;
+ if (!Number.isInteger(samples) || samples < 1) throw new Error('MSAA sample count must be a positive integer.');
+ if (new Set(parts).size !== parts.length) throw new Error('Scene parts must have distinct object identities for animation.');
this.context = canvas.getContext('webgl2', { antialias: true, alpha: false, powerPreference: 'high-performance' });
if (!this.context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');
this.pixelRatio = pixelRatio;
@@ -69,10 +120,30 @@ export class Renderer67 {
this.environment = environment;
this.shadowBounds = shadowBounds;
this.memoryBudgetMiB = memoryBudgetMiB;
- this.samples = benchmark ? 1 : Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES));
+ this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));
+ this.multisampleSamples = benchmark ? 0 : sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(samples, this.context.getParameter(this.context.MAX_SAMPLES)));
+ this.samples = Math.max(1, this.multisampleSamples);
+ this.capabilities = { hdr: this.hdr, hdrRequested: Boolean(hdr), hdrFallbackReason: hdr && !this.hdr ? benchmark ? 'HDR is disabled in benchmark mode' : 'EXT_color_buffer_float is unavailable' : null, samples: this.multisampleSamples };
this.geometryBytes = 0;
this.buffers = [];
this.batches = [];
+ this.partLocations = new Map();
+ this.textures = new Map();
+ this.textureBytes = 4;
+ this.shadowsDirty = true;
+ const groups = groupParts(ground ? [...parts, groundPart()] : parts, batching);
+ const textureLimit = this.context.getParameter(this.context.MAX_TEXTURE_SIZE);
+ const maps = new Set(groups.map(group => group[0].material.map).filter(Boolean));
+ for (const map of maps) this.textureBytes += textureDescriptorInfo(map, textureLimit).bytes;
+ this.capabilities.maximumTextureSize = textureLimit;
+ for (const group of groups) {
+ const geometry = group[0].geometry;
+ if (geometry.uvs && geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
+ if (group[0].material.map && !geometry.uvs) throw new Error('Textured geometry requires UV channel 0.');
+ if (geometry.colors && geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
+ }
+ const expectedGeometryBytes = groups.reduce((total, group) => total + ['positions', 'normals', 'indices', 'uvs', 'colors'].reduce((bytes, field) => bytes + (group[0].geometry[field]?.byteLength ?? 0), 0) + group.length * INSTANCE_STRIDE * 4, 0);
+ planRenderSize({ width: Math.max(1, canvas.clientWidth), height: Math.max(1, canvas.clientHeight), pixelRatio, samples: this.samples, memoryBudgetMiB, geometryBytes: expectedGeometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !benchmark, maximumSize: textureLimit });
this.view = mat4.create();
this.projection = mat4.create();
this.viewProjection = mat4.create();
@@ -80,32 +151,69 @@ export class Renderer67 {
this.inverseViewProjection = mat4.create();
this.program = compileProgram(this.context, benchmark ? benchmarkVertexShader : vertexShader, benchmark ? benchmarkFragmentShader : fragmentShader);
this.depthProgram = compileProgram(this.context, depthVertexShader, depthFragmentShader);
- this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
+ this.uniforms = Object.fromEntries(['viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'baseMap', 'hasBaseMap', 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'lightDirection', 'fogColor', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount'].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
if (!benchmark) {
this.postProgram = compileProgram(this.context, fullscreenVertex, postFragment);
this.skyProgram = compileProgram(this.context, fullscreenVertex, skyFragment);
- this.postUniforms = Object.fromEntries(['frameTexture', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));
- this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));
+ this.postUniforms = Object.fromEntries(['frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));
+ 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.depthUniform = this.context.getUniformLocation(this.depthProgram, 'lightProjection');
this.depthAssemblyUniform = this.context.getUniformLocation(this.depthProgram, 'assemblyAmount');
this.partCount = parts.length;
this.triangles = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);
- groupParts(ground ? [...parts, groundPart()] : parts, batching).forEach((group) => this.batches.push(this.uploadBatch(group)));
+ this.whiteTexture = this.createTexture(null);
+ groups.forEach((group) => this.batches.push(this.uploadBatch(group)));
this.createShadowMap();
this.resize();
if (!this.benchmark && !this.multisampleFramebuffer) this.allocateFrameTargets(this.canvas.width, this.canvas.height);
}
- uploadBuffer(target, data) {
+ uploadBuffer(target, data, usage = this.context.STATIC_DRAW) {
const buffer = this.context.createBuffer();
this.buffers.push(buffer);
this.context.bindBuffer(target, buffer);
- this.context.bufferData(target, data, this.context.STATIC_DRAW);
+ this.context.bufferData(target, data, usage);
this.geometryBytes += data.byteLength;
return buffer;
}
+ createTexture(map) {
+ if (this.textures.has(map)) return this.textures.get(map);
+ const context = this.context;
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D, texture);
+ const previousFlip = context.getParameter(context.UNPACK_FLIP_Y_WEBGL);
+ const previousColorSpace = context.getParameter(context.UNPACK_COLORSPACE_CONVERSION_WEBGL);
+ try {
+ context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, map?.flipY ?? false);
+ context.pixelStorei(context.UNPACK_COLORSPACE_CONVERSION_WEBGL, context.NONE);
+ if (map) {
+ const info = textureDescriptorInfo(map, context.getParameter(context.MAX_TEXTURE_SIZE));
+ context.texImage2D(context.TEXTURE_2D, 0, map.colorSpace === 'linear' ? context.RGBA8 : context.SRGB8_ALPHA8, context.RGBA, context.UNSIGNED_BYTE, map.image);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, info.wrapS);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, info.wrapT);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, info.minFilter);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, info.magFilter);
+ if (info.mipmaps) context.generateMipmap(context.TEXTURE_2D);
+ } else {
+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA8, 1, 1, 0, context.RGBA, context.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ }
+ } catch (error) {
+ context.deleteTexture(texture);
+ throw error;
+ } finally {
+ context.pixelStorei(context.UNPACK_FLIP_Y_WEBGL, previousFlip);
+ context.pixelStorei(context.UNPACK_COLORSPACE_CONVERSION_WEBGL, previousColorSpace);
+ }
+ this.textures.set(map, texture);
+ return texture;
+ }
+
uploadBatch(parts) {
const context = this.context;
const geometry = parts[0].geometry;
@@ -116,29 +224,67 @@ export class Renderer67 {
context.enableVertexAttribArray(location);
context.vertexAttribPointer(location, 3, context.FLOAT, false, 0, 0);
}
+ if (geometry.uvs) {
+ if (geometry.uvs.length !== geometry.positions.length / 3 * 2) throw new Error('Geometry UV count must match the vertex count.');
+ this.uploadBuffer(context.ARRAY_BUFFER, geometry.uvs);
+ context.enableVertexAttribArray(13);
+ context.vertexAttribPointer(13, 2, context.FLOAT, false, 0, 0);
+ } else {
+ if (parts[0].material.map) throw new Error('Textured geometry requires UV channel 0.');
+ context.disableVertexAttribArray(13);
+ context.vertexAttrib2f(13, 0, 0);
+ }
+ if (geometry.colors) {
+ if (geometry.colors.length !== geometry.positions.length) throw new Error('Geometry colors must contain RGB for every vertex.');
+ this.uploadBuffer(context.ARRAY_BUFFER, geometry.colors);
+ context.enableVertexAttribArray(14);
+ context.vertexAttribPointer(14, 3, context.FLOAT, false, 0, 0);
+ } else {
+ context.disableVertexAttribArray(14);
+ context.vertexAttrib3f(14, 1, 1, 1);
+ }
this.uploadBuffer(context.ELEMENT_ARRAY_BUFFER, geometry.indices);
- const stride = 38;
+ const stride = INSTANCE_STRIDE;
const instanceData = new Float32Array(parts.length * stride);
const normalMatrix = mat3.create();
parts.forEach((part, index) => {
- const offset = index * stride;
- if (!mat3.normalFromMat4(normalMatrix, part.matrix)) throw new Error(`Singular transform: ${part.name}`);
- instanceData.set(part.matrix, offset);
- instanceData.set(normalMatrix, offset + 16);
- instanceData.set(part.material.color, offset + 25);
- instanceData.set([part.material.metallic, part.material.roughness, part.material.emission ?? 0, MATERIAL_TAGS[part.material.tag] ?? 0], offset + 28);
- instanceData.set(part.assembly?.offset ?? [0, 0, 0], offset + 32);
- instanceData.set(part.assembly?.detailOffset ?? [0, 0, 0], offset + 35);
+ mat3.normalFromMat4(normalMatrix, part.matrix);
+ packInstance(instanceData, index, part, normalMatrix);
});
- this.uploadBuffer(context.ARRAY_BUFFER, instanceData);
+ const instanceBuffer = this.uploadBuffer(context.ARRAY_BUFFER, instanceData, context.DYNAMIC_DRAW);
for (let column = 0; column < 4; column++) this.attribute(2 + column, 4, stride * 4, column * 16);
for (let column = 0; column < 3; column++) this.attribute(6 + column, 3, stride * 4, 64 + column * 12);
this.attribute(9, 3, stride * 4, 100);
this.attribute(10, 4, stride * 4, 112);
this.attribute(11, 3, stride * 4, 128);
this.attribute(12, 3, stride * 4, 140);
+ this.attribute(15, 3, stride * 4, 152);
context.bindVertexArray(null);
- return { vertexArray, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };
+ const map = parts[0].material.map ?? null;
+ const batch = { vertexArray, instanceBuffer, instanceData, texture: this.createTexture(map), map, indexCount: geometry.indices.length, instanceCount: parts.length, floor: parts[0].material.tag === 'floor' };
+ parts.forEach((part, index) => this.partLocations.set(part, { batch, index, geometry: part.geometry, map }));
+ return batch;
+ }
+
+ updateParts(parts, { shadows = true } = {}) {
+ const prepared = parts.map(part => {
+ const location = this.partLocations.get(part);
+ if (!location) throw new Error(`Unknown part identity: ${part.name}`);
+ if (part.geometry !== location.geometry) throw new Error(`Geometry changes require a new renderer: ${part.name}`);
+ if ((part.material.map ?? null) !== location.map) throw new Error(`Texture map changes require a new renderer: ${part.name}`);
+ return { part, location, normalMatrix: validateTransform(part) };
+ });
+ const batches = new Set();
+ for (const { part, location, normalMatrix } of prepared) {
+ packInstance(location.batch.instanceData, location.index, part, normalMatrix);
+ batches.add(location.batch);
+ }
+ for (const batch of batches) {
+ this.context.bindBuffer(this.context.ARRAY_BUFFER, batch.instanceBuffer);
+ this.context.bufferSubData(this.context.ARRAY_BUFFER, 0, batch.instanceData);
+ }
+ if (shadows && prepared.length > 0) this.shadowsDirty = true;
+ return prepared.length;
}
attribute(location, size, stride, offset) {
@@ -180,10 +326,11 @@ export class Renderer67 {
for (const batch of this.batches) if (!batch.floor) this.drawBatch(batch);
context.disable(context.POLYGON_OFFSET_FILL);
context.bindFramebuffer(context.FRAMEBUFFER, null);
+ this.shadowsDirty = false;
}
resize() {
- const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, maximumSize: this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE) });
+ const plan = planRenderSize({ width: Math.max(1, this.canvas.clientWidth), height: Math.max(1, this.canvas.clientHeight), pixelRatio: this.pixelRatio, samples: this.samples, memoryBudgetMiB: this.memoryBudgetMiB, geometryBytes: this.geometryBytes, textureBytes: this.textureBytes, hdr: this.hdr, bloom: !this.benchmark, maximumSize: Math.min(this.context.getParameter(this.context.MAX_RENDERBUFFER_SIZE), this.context.getParameter(this.context.MAX_TEXTURE_SIZE)) });
const { width, height } = plan;
this.memoryPlan = plan;
if (this.canvas.width !== width || this.canvas.height !== height) {
@@ -202,6 +349,16 @@ export class Renderer67 {
if (this.multisampleColor) context.deleteRenderbuffer(this.multisampleColor);
if (this.multisampleDepth) context.deleteRenderbuffer(this.multisampleDepth);
if (this.frameTexture) context.deleteTexture(this.frameTexture);
+ for (const target of this.bloomTargets ?? []) {
+ context.deleteTexture(target.texture);
+ context.deleteFramebuffer(target.framebuffer);
+ }
+ this.bloomTargets = [];
+ this.multisampleFramebuffer = null;
+ this.resolveFramebuffer = null;
+ this.multisampleColor = null;
+ this.multisampleDepth = null;
+ this.frameTexture = null;
}
allocateFrameTargets(width, height) {
@@ -211,16 +368,16 @@ export class Renderer67 {
context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);
this.multisampleColor = context.createRenderbuffer();
context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleColor);
- context.renderbufferStorageMultisample(context.RENDERBUFFER, this.samples, context.RGBA8, width, height);
+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, this.hdr ? context.RGBA16F : context.RGBA8, width, height);
context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, this.multisampleColor);
this.multisampleDepth = context.createRenderbuffer();
context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleDepth);
- context.renderbufferStorageMultisample(context.RENDERBUFFER, this.samples, context.DEPTH_COMPONENT24, width, height);
+ context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context.DEPTH_COMPONENT24, width, height);
context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, this.multisampleDepth);
if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Multisample framebuffer allocation failed. Choose a lower quality preset.');
this.frameTexture = context.createTexture();
context.bindTexture(context.TEXTURE_2D, this.frameTexture);
- context.texImage2D(context.TEXTURE_2D, 0, context.RGBA8, width, height, 0, context.RGBA, context.UNSIGNED_BYTE, null);
+ context.texImage2D(context.TEXTURE_2D, 0, this.hdr ? context.RGBA16F : context.RGBA8, width, height, 0, context.RGBA, this.hdr ? context.HALF_FLOAT : context.UNSIGNED_BYTE, null);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
@@ -229,6 +386,22 @@ export class Renderer67 {
context.bindFramebuffer(context.FRAMEBUFFER, this.resolveFramebuffer);
context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.frameTexture, 0);
if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');
+ this.bloomWidth = Math.max(1, Math.ceil(width / 2));
+ this.bloomHeight = Math.max(1, Math.ceil(height / 2));
+ for (let index = 0; index < 2; index++) {
+ const texture = context.createTexture();
+ const framebuffer = context.createFramebuffer();
+ this.bloomTargets.push({ texture, framebuffer });
+ context.bindTexture(context.TEXTURE_2D, texture);
+ context.texImage2D(context.TEXTURE_2D, 0, this.hdr ? context.RGBA16F : context.RGBA8, this.bloomWidth, this.bloomHeight, 0, context.RGBA, this.hdr ? context.HALF_FLOAT : context.UNSIGNED_BYTE, null);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);
+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);
+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Bloom framebuffer allocation failed. Choose a lower quality preset.');
+ }
context.bindFramebuffer(context.FRAMEBUFFER, null);
}
@@ -246,15 +419,18 @@ export class Renderer67 {
context.uniform3fv(this.skyUniforms.eye, frame.eye);
context.uniform1f(this.skyUniforms.time, frame.time ?? 0);
context.uniform1f(this.skyUniforms.daylight, environment.daylight);
+ context.uniform1f(this.skyUniforms.hdrEnabled, this.hdr ? 1 : 0);
context.drawArrays(context.TRIANGLES, 0, 3);
}
- resolveFrame(frame) {
+ resolveFrame(frame, effects) {
const context = this.context;
context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);
context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);
context.blitFramebuffer(0, 0, this.canvas.width, this.canvas.height, 0, 0, this.canvas.width, this.canvas.height, context.COLOR_BUFFER_BIT, context.NEAREST);
+ if (effects.bloom.strength > 0) this.drawBloom(effects.bloom);
context.bindFramebuffer(context.FRAMEBUFFER, null);
+ context.viewport(0, 0, this.canvas.width, this.canvas.height);
context.disable(context.DEPTH_TEST);
context.disable(context.CULL_FACE);
context.bindVertexArray(null);
@@ -262,6 +438,14 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.frameTexture);
context.uniform1i(this.postUniforms.frameTexture, 0);
+ context.activeTexture(context.TEXTURE2);
+ context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);
+ context.uniform1i(this.postUniforms.bloomTexture, 2);
+ context.uniform1f(this.postUniforms.bloomStrength, effects.bloom.strength);
+ context.uniform1f(this.postUniforms.hdrEnabled, this.hdr ? 1 : 0);
+ context.uniform3f(this.postUniforms.grade, effects.saturation, effects.contrast, effects.temperature);
+ context.uniform1f(this.postUniforms.vignette, effects.vignette);
+ context.uniform1f(this.postUniforms.grainAmount, effects.grain);
context.uniform2f(this.postUniforms.resolution, this.canvas.width, this.canvas.height);
context.uniform1f(this.postUniforms.monochrome, frame.monochrome ?? 0);
context.uniform1f(this.postUniforms.fade, frame.fade ?? 0);
@@ -274,22 +458,48 @@ export class Renderer67 {
context.drawArrays(context.TRIANGLES, 0, 3);
}
- drawBatch(batch) {
+ drawBloom(bloom) {
+ const context = this.context;
+ context.disable(context.DEPTH_TEST);
+ context.disable(context.CULL_FACE);
+ context.bindVertexArray(null);
+ context.useProgram(this.bloomProgram);
+ context.viewport(0, 0, this.bloomWidth, this.bloomHeight);
+ context.uniform1i(this.bloomUniforms.sourceTexture, 0);
+ context.uniform1f(this.bloomUniforms.threshold, bloom.threshold);
+ for (let pass = 0; pass < 2; pass++) {
+ context.bindFramebuffer(context.FRAMEBUFFER, this.bloomTargets[pass].framebuffer);
+ context.activeTexture(context.TEXTURE0);
+ context.bindTexture(context.TEXTURE_2D, pass === 0 ? this.frameTexture : this.bloomTargets[0].texture);
+ context.uniform1f(this.bloomUniforms.extract, pass === 0 ? 1 : 0);
+ context.uniform2f(this.bloomUniforms.texelDirection, pass === 0 ? bloom.radius / this.bloomWidth : 0, pass === 1 ? bloom.radius / this.bloomHeight : 0);
+ context.drawArrays(context.TRIANGLES, 0, 3);
+ }
+ }
+
+ drawBatch(batch, textured = false) {
+ if (textured && !this.benchmark) {
+ this.context.activeTexture(this.context.TEXTURE1);
+ this.context.bindTexture(this.context.TEXTURE_2D, batch.texture);
+ this.context.uniform1i(this.uniforms.baseMap, 1);
+ this.context.uniform1f(this.uniforms.hasBaseMap, batch.map ? 1 : 0);
+ }
this.context.bindVertexArray(batch.vertexArray);
this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);
}
render(frame) {
const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;
+ const effects = resolveEffects(frame.effects);
const start = performance.now();
const context = this.context;
const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));
- if (this.assemblyAmount !== assemblyAmount) {
+ if (this.assemblyAmount !== assemblyAmount || this.shadowsDirty) {
this.assemblyAmount = assemblyAmount;
this.createShadowMap();
}
- if (frame.fov) mat4.perspective(this.projection, frame.fov * Math.PI / 180, this.canvas.width / this.canvas.height, 0.1, this.world ? 600 : 100);
- mat4.lookAt(this.view, eye, target, [0, 1, 0]);
+ 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);
mat4.invert(this.inverseViewProjection, this.viewProjection);
context.bindFramebuffer(context.FRAMEBUFFER, this.benchmark ? null : this.multisampleFramebuffer);
@@ -307,6 +517,7 @@ export class Renderer67 {
context.uniform2fv(this.uniforms.armorSurface, armorSurface);
context.uniform1f(this.uniforms.exposure, exposure);
context.uniform1f(this.uniforms.inspection, inspection ? 1 : 0);
+ context.uniform1f(this.uniforms.hdrEnabled, this.hdr ? 1 : 0);
const environment = { lightDirection: [-3, 6, 4], fogColor: [0.35, 0.43, 0.43], fogDensity: 0.006, daylight: 1, explosionCenter: [0, 0, 0], ...this.environment, ...frame.environment };
context.uniform1f(this.uniforms.time, frame.time ?? 0);
context.uniform1f(this.uniforms.wind, frame.wind ?? 0.3);
@@ -323,9 +534,9 @@ export class Renderer67 {
context.activeTexture(context.TEXTURE0);
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
- for (const batch of this.batches) this.drawBatch(batch);
+ for (const batch of this.batches) this.drawBatch(batch, true);
context.bindVertexArray(null);
- if (!this.benchmark) this.resolveFrame(frame);
+ if (!this.benchmark) this.resolveFrame(frame, effects);
this.cpuMilliseconds = performance.now() - start;
}
@@ -339,5 +550,9 @@ export class Renderer67 {
this.context.deleteProgram(this.depthProgram);
if (this.postProgram) this.context.deleteProgram(this.postProgram);
if (this.skyProgram) this.context.deleteProgram(this.skyProgram);
+ if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);
+ for (const texture of this.textures.values()) this.context.deleteTexture(texture);
+ this.textures.clear();
+ this.partLocations.clear();
}
}
diff --git a/src/shaders.js b/src/shaders.js
index 17a41478..6ca8344d 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -8,6 +8,9 @@ layout(location=9) in vec3 instanceColor;
layout(location=10) in vec4 instanceSurface;
layout(location=11) in vec3 assemblyOffset;
layout(location=12) in vec3 assemblyDetailOffset;
+layout(location=13) in vec2 uv;
+layout(location=14) in vec3 vertexColor;
+layout(location=15) in vec3 instanceEmissive;
uniform mat4 viewProjection;
uniform mat4 lightProjection;
uniform float time;
@@ -20,6 +23,9 @@ out vec3 worldNormal;
flat out vec3 baseColor;
flat out vec4 surface;
out vec4 shadowPosition;
+out vec2 textureUV;
+out vec3 vertexTint;
+flat out vec3 emissionColor;
void main() {
vec4 world = instanceMatrix * vec4(position, 1.0);
world.xyz += assemblyOffset * assemblyAmount + assemblyDetailOffset * smoothstep(0.3, 1.0, assemblyAmount);
@@ -35,6 +41,9 @@ void main() {
worldPosition = world.xyz;
worldNormal = normalize(instanceNormal * normal);
baseColor = instanceColor;
+ textureUV = uv;
+ vertexTint = vertexColor;
+ emissionColor = instanceEmissive;
surface = instanceSurface;
shadowPosition = lightProjection * world;
gl_Position = viewProjection * world;
@@ -85,6 +94,9 @@ 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 vec3 armorColor;
uniform vec2 armorSurface;
@@ -100,6 +112,9 @@ uniform vec3 waterRipple;
uniform float rippleTime;
uniform float explosionProgress;
uniform sampler2D shadowMap;
+uniform sampler2D baseMap;
+uniform float hasBaseMap;
+uniform float hdrEnabled;
out vec4 outputColor;
const float PI = 3.14159265359;
@@ -156,6 +171,13 @@ void main() {
vec3 normal = normalize(worldNormal);
vec3 viewDirection = normalize(eye - worldPosition);
vec3 color = mix(baseColor, armorColor, step(0.5, surface.w) * (1.0 - step(1.5, surface.w)));
+ color *= vertexTint;
+ if (hasBaseMap > 0.5) color *= texture(baseMap, textureUV).rgb;
+ if (surface.w == 10.0) {
+ vec3 radiance = color * exposure + emissionColor * surface.z;
+ outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), 1.0);
+ return;
+ }
float metallic = surface.x;
float roughness = clamp(surface.y, 0.075, 1.0);
if (surface.w > 0.5 && surface.w < 1.5) {
@@ -192,7 +214,7 @@ void main() {
radiance += studio(reflect(-viewDirection, normal), roughness) * reflectance * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode);
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));
if (surface.w == 4.0 || surface.w == 7.0) radiance += color * max(dot(-normal, normalize(lightDirection)), 0.0) * 0.3 * daylight;
- radiance += color * surface.z;
+ radiance += emissionColor * surface.z;
if (surface.w == 3.0) {
float reflectivity = 0.20 + 0.65 * pow(1.0 - max(dot(normal, viewDirection), 0.0), 3.0);
vec3 reflection = mix(vec3(0.12, 0.24, 0.28), vec3(0.40, 0.63, 0.78), clamp(reflect(-viewDirection, normal).y, 0.0, 1.0));
@@ -217,11 +239,12 @@ void main() {
float fog = 1.0 - exp(-length(worldPosition - eye) * fogDensity);
radiance = mix(radiance, fogColor, fog * worldMode);
if (inspection > 0.5) radiance = normal * 0.5 + 0.5;
- outputColor = vec4(pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);
+ outputColor = vec4(hdrEnabled > 0.5 ? max(radiance * exposure, vec3(0)) : pow(toneMap(radiance * exposure), vec3(1.0 / 2.2)), 1.0);
if (surface.w == 2.0 && inspection < 0.5) {
float distanceFade = exp(-length(worldPosition.xz) * 0.08);
float contact = 1.0 - 0.1 * exp(-dot(worldPosition.xz, worldPosition.xz) * 1.4);
vec3 floorColor = mix(vec3(0.145, 0.162, 0.177), vec3(0.17, 0.19, 0.205), distanceFade);
- outputColor = vec4(floorColor * (0.72 + 0.28 * visibility) * contact, 1.0);
+ vec3 result = floorColor * (0.72 + 0.28 * visibility) * contact;
+ outputColor = vec4(hdrEnabled > 0.5 ? pow(result, vec3(2.2)) : result, 1.0);
}
}`;
diff --git a/tests/budget.test.js b/tests/budget.test.js
index 887b122c..953647e3 100644
--- a/tests/budget.test.js
+++ b/tests/budget.test.js
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
-import { planRenderSize, RENDER_PRESETS } from '../src/budget.js';
+import { planRenderSize, RENDER_PRESETS, estimateFrameBytes, estimateTextureBytes } from '../src/budget.js';
test('high resolution render targets shrink before exceeding their memory budget', () => {
const plan = planRenderSize({ width: 7680, height: 4320, samples: 4, memoryBudgetMiB: 128, geometryBytes: 20 * 1024 ** 2 });
@@ -9,6 +9,20 @@ test('high resolution render targets shrink before exceeding their memory budget
assert.ok(Math.abs(plan.width / plan.height - 16 / 9) < 0.003);
});
+test('HDR, two half-resolution bloom targets and cached texture mipmaps fit inside the budget', () => {
+ const textureBytes = estimateTextureBytes(2048, 2048);
+ assert.equal(textureBytes, 22369620);
+ assert.equal(estimateTextureBytes(3, 5), 72);
+ assert.equal(estimateTextureBytes(3, 5, { mipmaps: false }), 60);
+ const plan = planRenderSize({ width: 7681, height: 4321, hdr: true, bloom: true, textureBytes, samples: 4, memoryBudgetMiB: 128 });
+ assert.ok(plan.reduced);
+ assert.ok(plan.estimatedBytes <= 128 * 1024 ** 2);
+ assert.equal(plan.estimatedBytes, estimateFrameBytes(plan.width, plan.height, 4, 2048, { hdr: true, bloom: true }) + textureBytes);
+ assert.ok(estimateFrameBytes(100, 101, 4, 0, { hdr: true, bloom: true }) > estimateFrameBytes(100, 101, 4, 0));
+ assert.throws(() => planRenderSize({ width: 640, height: 360, textureBytes: 200 * 1024 ** 2, memoryBudgetMiB: 128 }), /cannot hold/);
+ assert.throws(() => estimateTextureBytes(-1, 32), /positive/);
+});
+
test('presets fit their budget and device texture limits', () => {
for (const preset of Object.values(RENDER_PRESETS)) {
const plan = planRenderSize({ ...preset, maximumSize: 1024 });
diff --git a/tests/renderer.test.js b/tests/renderer.test.js
new file mode 100644
index 00000000..1a66df9e
--- /dev/null
+++ b/tests/renderer.test.js
@@ -0,0 +1,80 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { mat4 } from 'gl-matrix';
+import { Renderer67, groupParts, textureDescriptorInfo } from '../src/renderer.js';
+
+function part(name, geometry = {}, map) {
+ return { name, geometry, matrix: mat4.create(), material: { color: [0.1, 0.2, 0.3], metallic: 0.5, roughness: 0.3, emission: 0, map } };
+}
+
+function retainedRenderer(parts) {
+ const writes = [];
+ const renderer = Object.create(Renderer67.prototype);
+ const batch = { instanceBuffer: {}, instanceData: new Float32Array(parts.length * 41).fill(7) };
+ renderer.context = { ARRAY_BUFFER: 34962, bindBuffer() {}, bufferSubData(target, offset, data) { writes.push({ target, offset, data: Array.from(data) }); } };
+ renderer.partLocations = new Map(parts.map((item, index) => [item, { batch, index, geometry: item.geometry, map: item.material.map ?? null }]));
+ renderer.shadowsDirty = false;
+ return { renderer, batch, writes };
+}
+
+test('batching shares geometry only when texture descriptor identities also match', () => {
+ const geometry = {};
+ const map = {};
+ const parts = [part('first', geometry, map), part('second', geometry, map), part('other texture', geometry, {}), part('no texture', geometry)];
+ const groups = groupParts(parts);
+ assert.equal(groups.length, 3);
+ assert.equal(groups[0].length, 2);
+ assert.equal(groupParts(parts, false).length, 4);
+});
+
+test('instance animation reuses retained buffers, updates inverse-transpose normals and RGB emission', () => {
+ const parts = [part('moving'), part('static')];
+ const { renderer, batch, writes } = retainedRenderer(parts);
+ const data = batch.instanceData;
+ const buffer = batch.instanceBuffer;
+ mat4.fromScaling(parts[0].matrix, [2, 3, 4]);
+ parts[0].matrix[12] = 2.5;
+ parts[0].material.emissiveColor = [3, 0.5, 0.1];
+ assert.equal(renderer.updateParts([parts[0]], { shadows: false }), 1);
+ assert.equal(batch.instanceData, data);
+ assert.equal(batch.instanceBuffer, buffer);
+ assert.equal(writes.length, 1);
+ assert.equal(data[12], 2.5);
+ assert.equal(data[16], 0.5);
+ assert.ok(Math.abs(data[20] - 1 / 3) < 1e-6);
+ assert.equal(data[24], 0.25);
+ assert.equal(data[38], 3);
+ assert.equal(renderer.shadowsDirty, false);
+ renderer.updateParts(parts);
+ assert.equal(writes.length, 2, 'one upload for a changed batch');
+ assert.equal(renderer.shadowsDirty, true);
+});
+
+test('mixed invalid updates fail atomically before CPU or GPU instance data changes', () => {
+ const parts = [part('valid'), part('invalid')];
+ const { renderer, batch, writes } = retainedRenderer(parts);
+ const original = Array.from(batch.instanceData);
+ parts[0].matrix[12] = 9;
+ parts[1].matrix[0] = 0;
+ assert.throws(() => renderer.updateParts(parts), /Singular/);
+ assert.deepEqual(Array.from(batch.instanceData), original);
+ assert.equal(writes.length, 0);
+ mat4.identity(parts[1].matrix);
+ parts[1].geometry = {};
+ assert.throws(() => renderer.updateParts(parts), /Geometry changes/);
+ assert.equal(writes.length, 0);
+ assert.throws(() => renderer.updateParts([part('not uploaded')]), /Unknown part/);
+ parts[0].material.emissiveColor = [1e200, 0, 0];
+ assert.throws(() => renderer.updateParts([parts[0]]), /Invalid instance vector/);
+ assert.equal(writes.length, 0);
+});
+
+test('texture descriptor preflight validates dimensions, channel, samplers and mipmap bytes', () => {
+ const info = textureDescriptorInfo({ image: { width: 4, height: 4 }, colorSpace: 'srgb', uvChannel: 0 }, 16);
+ assert.equal(info.bytes, 84);
+ assert.equal(info.mipmaps, true);
+ assert.equal(textureDescriptorInfo({ image: { width: 4, height: 4 }, minFilter: 9729 }, 16).bytes, 64);
+ assert.throws(() => textureDescriptorInfo({ image: { width: 32, height: 32 } }, 16), /MAX_TEXTURE_SIZE/);
+ assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, uvChannel: 1 }), /channel 0/);
+ assert.throws(() => textureDescriptorInfo({ image: { width: 4, height: 4 }, minFilter: 4 }), /filtering/);
+});