3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Add the Glaze backend boundary with WebGL2 as its only implementation (#901)
Nguyen Xuan An2778911685b4
diff --git a/changes/901.md b/changes/901.mdnew file mode 100644index 00000000..c65914c2--- /dev/null+++ b/changes/901.md@@ -0,0 +1 @@+- Glaze now draws through a backend boundary (`GlazeBackend`) for its context, frame targets, MSAA resolve and opaque draws, with WebGL2 as the only implementation; frames are unchanged (#901).diff --git a/changes/901.size.md b/changes/901.size.mdnew file mode 100644index 00000000..5bc7fa32--- /dev/null+++ b/changes/901.size.md@@ -0,0 +1,11 @@+- entry:core: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- entry:core+lazy: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:lit-box: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:lit-box+lazy: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:gltf-box: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:gltf-box+lazy: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:agent-scene: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- scene:agent-scene+lazy: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- goal:lit-box: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- goal:gltf-box: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context calls+- goal:agent-scene: the Glaze backend boundary (#901) adds about 600 bytes gzip of method wrappers that keep the same GL calls; it is the first part of the move that lets a WebGPU backend replace them, and the bytes shrink as pass files move onto it and drop their own context callsdiff --git a/docs/webgpu-decision.md b/docs/webgpu-decision.mdindex 009b1a9a..e8c24cc2 100644--- a/docs/webgpu-decision.md+++ b/docs/webgpu-decision.md@@ -194,3 +194,9 @@ The 16 path tracer reference scenes at 480 by 270, 32 samples, no denoiser, FLIPFifteen scenes are within 0.002 (the bar is 0.005). `fog` uses volume fog, which the WGSL kernel does not trace: `traceOnWebGpu` throws `The WebGPU path tracer does not trace volume fog yet. Use backend "gpu" for this scene.` and the same for subsurface scattering (no reference scene uses it). Neither is ported and neither is hidden: a caller falls back to `gpu`. Not done: fog and subsurface in WGSL, the texel bake and the GPU bake on WebGPU, hardware ray queries for the native package, a run on another adapter or browser, and the shading-sorted path on a scene with many expensive materials.Without `navigator.gpu`, or with no adapter, the backend throws and names `gpu` and `cpu`; the MCP `cpu` runtime has neither. No default backend changed.++## The Glaze backend boundary (issue #901)++`src/glaze-backend.js` names what the real-time renderer asks of a graphics API: create a buffer, a multisample target and a resolve target, start and finish a program, draw indexed and instanced, resolve MSAA, set winding and read pixels. `src/glaze-backend-webgl2.js` is the only implementation and issues the calls the renderer made itself before, in the same order. `CrucibleRenderer` opens its context, allocates and releases its frame targets, resolves MSAA, starts its programs and draws opaque batches through it, and keeps `renderer.context` (the same raw context as `renderer.backend.context`) for the files that have not moved. No WebGPU backend exists yet; nothing is chosen at start-up.++Still on the raw context, to move in later parts of slice 1: `src/reversed-depth.js` (respecifies the depth stores), `fog-shader.js`, `line-art.js`, `mesh-blend.js`, `liquid-renderer.js`, `mesh-volume-pass.js`, `user-pass.js`, `gaussian-splats.js`, `splat-renderer.js`, `render-passes.js`, `post-steps.js`, `cascaded-shadows.js`, `environment.js`, `float-output.js` (readback), the shadow, sky, post, bloom and ambient-occlusion draws and the texture and uniform calls inside `src/renderer.js`.diff --git a/src/glaze-backend-webgl2.js b/src/glaze-backend-webgl2.jsnew file mode 100644index 00000000..bb5e9cba--- /dev/null+++ b/src/glaze-backend-webgl2.js@@ -0,0 +1,150 @@+// The WebGL2 implementation of the Glaze backend boundary (glaze-backend.js). Every method issues the calls that+// CrucibleRenderer made itself before the boundary existed, in the same order, so a frame does not change.++import { startProgram, finishProgram } from './gl-program.js';++const CONTEXT_OPTIONS_BASE = { antialias: true, premultipliedAlpha: true, powerPreference: 'high-performance' };++export class WebGL2GlazeBackend {+ /** `context` is the raw WebGL2 context. Pass files not yet ported to the boundary still draw with it directly. */+ constructor(context) {+ this.name = 'webgl2';+ this.context = context;+ }++ /** Opens the WebGL2 context of a canvas. Throws when the browser has none. */+ static create(canvas, { transparent = false } = {}) {+ const context = canvas.getContext('webgl2', { ...CONTEXT_OPTIONS_BASE, alpha: Boolean(transparent) });+ if (!context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');+ return new WebGL2GlazeBackend(context);+ }++ createBuffer() {+ return this.context.createBuffer();+ }++ /** Fills a buffer. Kept apart from createBuffer so a caller owns the buffer before an upload that may throw. */+ uploadBuffer(target, buffer, data, usage = this.context.STATIC_DRAW) {+ this.context.bindBuffer(target, buffer);+ this.context.bufferData(target, data, usage);+ }++ deleteBuffer(buffer) {+ this.context.deleteBuffer(buffer);+ }++ /** The largest MSAA sample count at most `requested` that the driver offers for both `colorFormat` and a 24-bit depth store (0 when none). */+ supportedSampleCount(colorFormat, requested) {+ const context = this.context;+ const limited = Math.min(requested, context.getParameter(context.MAX_SAMPLES));+ const colorCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, colorFormat, context.SAMPLES));+ const depthCounts = Array.from(context.getInternalformatParameter(context.RENDERBUFFER, context.DEPTH_COMPONENT24, context.SAMPLES));+ return Math.max(0, ...colorCounts.filter((count) => count <= limited && depthCounts.includes(count)));+ }++ /** A multisampled colour and 24-bit depth framebuffer. Returns { framebuffer, colorBuffer, depthBuffer }. */+ createMultisampleTarget({ width, height, samples, hdr }) {+ const context = this.context;+ const framebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ const colorBuffer = context.createRenderbuffer();+ context.bindRenderbuffer(context.RENDERBUFFER, colorBuffer);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, samples, hdr ? context.RGBA16F : context.RGBA8, width, height);+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.RENDERBUFFER, colorBuffer);+ const depthBuffer = context.createRenderbuffer();+ context.bindRenderbuffer(context.RENDERBUFFER, depthBuffer);+ context.renderbufferStorageMultisample(context.RENDERBUFFER, samples, context.DEPTH_COMPONENT24, width, height);+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, depthBuffer);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) {+ context.deleteFramebuffer(framebuffer);+ context.deleteRenderbuffer(colorBuffer);+ context.deleteRenderbuffer(depthBuffer);+ throw new Error('Multisample framebuffer allocation failed. Choose a lower quality preset.');+ }+ return { framebuffer, colorBuffer, depthBuffer };+ }++ /** A single-sample framebuffer with a linear colour texture and, with `depth`, a readable 24-bit depth texture. Returns { framebuffer, colorTexture, depthTexture }. */+ createResolveTarget({ width, height, hdr, depth }) {+ const context = this.context;+ const colorTexture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, colorTexture);+ context.texImage2D(context.TEXTURE_2D, 0, hdr ? context.RGBA16F : context.RGBA8, width, height, 0, context.RGBA, hdr ? context.HALF_FLOAT : context.UNSIGNED_BYTE, null);+ this.setClampedFiltering(context.LINEAR);+ const framebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, colorTexture, 0);+ let depthTexture = null;+ if (depth) {+ depthTexture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, depthTexture);+ context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, width, height, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);+ this.setClampedFiltering(context.NEAREST);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, depthTexture, 0);+ }+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) {+ context.deleteFramebuffer(framebuffer);+ context.deleteTexture(colorTexture);+ if (depthTexture) context.deleteTexture(depthTexture);+ throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');+ }+ return { framebuffer, colorTexture, depthTexture };+ }++ setClampedFiltering(filter) {+ const context = this.context;+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, filter);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, filter);+ 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);+ }++ deleteFramebuffer(framebuffer) {+ this.context.deleteFramebuffer(framebuffer);+ }++ deleteRenderbuffer(renderbuffer) {+ this.context.deleteRenderbuffer(renderbuffer);+ }++ deleteTexture(texture) {+ this.context.deleteTexture(texture);+ }++ /** Draws to the canvas again. */+ bindCanvasTarget() {+ this.context.bindFramebuffer(this.context.FRAMEBUFFER, null);+ }++ /** Resolves a multisample target into a single-sample one with the nearest filter; depth is copied too when `depth` is set. */+ resolveMultisample({ source, destination, width, height, depth }) {+ const context = this.context;+ context.bindFramebuffer(context.READ_FRAMEBUFFER, source);+ context.bindFramebuffer(context.DRAW_FRAMEBUFFER, destination);+ context.blitFramebuffer(0, 0, width, height, 0, 0, width, height, context.COLOR_BUFFER_BIT | (depth ? context.DEPTH_BUFFER_BIT : 0), context.NEAREST);+ }++ /** Starts building a program without waiting for the driver (see gl-program.js). */+ startProgram(vertexSource, fragmentSource) {+ return startProgram(this.context, vertexSource, fragmentSource);+ }++ finishProgram(pendingProgram) {+ return finishProgram(this.context, pendingProgram);+ }++ /** Draws `indexCount` 32-bit indices as triangles, `instanceCount` times, from index `firstIndex` of the bound vertex array. */+ drawIndexedInstanced(indexCount, instanceCount, firstIndex = 0) {+ this.context.drawElementsInstanced(this.context.TRIANGLES, indexCount, this.context.UNSIGNED_INT, firstIndex * 4, instanceCount);+ }++ /** Mirrored geometry reverses screen winding: clockwise triangles are then the front faces. */+ setFrontFaceClockwise(clockwise) {+ this.context.frontFace(clockwise ? this.context.CW : this.context.CCW);+ }++ /** Reads a rectangle of the bound framebuffer into `destination`. */+ readPixels(x, y, width, height, format, type, destination) {+ this.context.readPixels(x, y, width, height, format, type, destination);+ }+}diff --git a/src/glaze-backend.js b/src/glaze-backend.jsnew file mode 100644index 00000000..a7097d58--- /dev/null+++ b/src/glaze-backend.js@@ -0,0 +1,10 @@+// The Glaze backend boundary (#901): what the real-time renderer asks of a graphics API (see glaze-backend-webgl2.js for the list of calls).+// WebGL2 is the only implementation today. The renderer's frame core calls the backend instead of the raw context; pass files not yet+// ported still use `backend.context` directly.++import { WebGL2GlazeBackend } from './glaze-backend-webgl2.js';++/** Opens the canvas with the one backend there is; WebGL2 stays the fallback once another backend exists. */+export function createGlazeBackend(canvas, options = {}) {+ return WebGL2GlazeBackend.create(canvas, options);+}diff --git a/src/renderer.js b/src/renderer.jsindex 70acdb48..2d9c3cb5 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -4,7 +4,8 @@ import { mat4, mat3 } from 'gl-matrix';import { BLEND_FACTORS } from './blend-output.js';import { SPLAT_UNITS, requireSplatSupport, layerTextureSupport, LIGHT_SHADING_FEATURE, FRAGMENT_SHADOW_POSITION_FEATURE, SHADING_MODES, LIGHT_SHADING_MAXIMUM_SAMPLES, createVertexShader, vertexShader, liquidFragmentSource, createFragmentShader, liquidPassDrawer, createDepthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader, viewTransformShader, createDepthVertexShader } from './shaders.js';import { postFragment, createPostFragment, GRID_MOTION_STEP, NOISE_OCTAVES_STEP, localVolumeKindSteps, POST_STEPS, POST_STEPS_WITH_OPTIONAL_CODE, skyFragment, bloomFragment } from './post.js';-import { fullscreenVertex, startProgram, finishProgram, compileProgram, ProgramNotReady, isLinkComplete, setPreparing, releaseStartedPrograms } from './gl-program.js';+import { createGlazeBackend } from './glaze-backend.js';+import { fullscreenVertex, compileProgram, ProgramNotReady, isLinkComplete, setPreparing, releaseStartedPrograms } from './gl-program.js';import { ambientOcclusionFragment } from './ambient-occlusion.js';import { planRenderSize, estimateTextureBytes, estimateFrameBytes, memoryBudgetError } from './budget.js';import { applyProjection } from './camera.js';@@ -619,12 +620,6 @@ export function textureDescriptorInfo(map, maximumSize = Infinity) {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)));-}-// Light-mapped geometry uploads its two UV sets as one four-wide attribute (zeros where channel 0 is absent).function uvBufferBytes(geometry) {if (!geometry.lightUvs) return geometry.uvs?.byteLength ?? 0;@@ -738,8 +733,8 @@ export class CrucibleRenderer {updateLightingState(this.lighting, environment, { world });const volume = resolveVolumeFog(environment.volumeFog);if (volume.density > 0 && (!depth || benchmark || transparent || !hdr)) throw new Error('Volume fog requires depth:true, hdr:true, an opaque canvas and normal rendering');- this.context = canvas.getContext('webgl2', { antialias: true, alpha: Boolean(transparent), premultipliedAlpha: true, powerPreference: 'high-performance' });- if (!this.context) throw new Error('WebGL2 is unavailable. Enable hardware acceleration or use a supported browser.');+ this.backend = createGlazeBackend(canvas, { transparent });+ this.context = this.backend.context;this.transparent = Boolean(transparent);this.pixelRatio = pixelRatio;this.benchmark = benchmark;@@ -889,12 +884,12 @@ export class CrucibleRenderer {if (reversedDepthWanted) prepareCameraRelativeProgram(this);const pending = {main: this.startMainProgram(),- depth: startProgram(this.context, createDepthVertexShader(this.shaderFeatures), createDepthFragmentShader(this.shaderFeatures)),+ depth: this.backend.startProgram(createDepthVertexShader(this.shaderFeatures), createDepthFragmentShader(this.shaderFeatures)),};if (!benchmark) {- pending.post = startProgram(this.context, fullscreenVertex, this.withViewTransform(postFragment, 'post'));- pending.sky = startProgram(this.context, fullscreenVertex, skyFragment);- pending.bloom = startProgram(this.context, fullscreenVertex, bloomFragment);+ pending.post = this.backend.startProgram(fullscreenVertex, this.withViewTransform(postFragment, 'post'));+ pending.sky = this.backend.startProgram(fullscreenVertex, skyFragment);+ pending.bloom = this.backend.startProgram(fullscreenVertex, bloomFragment);if (environment.map) this.startEnvironmentPrograms();}// The driver links the programs on its own threads while the textures and buffers upload; only then is the link result read.@@ -912,15 +907,15 @@ export class CrucibleRenderer {this.pendingConstruction = null;const benchmark = this.benchmark;this.finishMainProgram(pending.main);- this.depthProgram = finishProgram(this.context, pending.depth);+ this.depthProgram = this.backend.finishProgram(pending.depth);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) {- this.postProgram = finishProgram(this.context, pending.post);- this.skyProgram = finishProgram(this.context, pending.sky);+ this.postProgram = this.backend.finishProgram(pending.post);+ this.skyProgram = this.backend.finishProgram(pending.sky);this.postUniforms = postUniformLocations(this.context, this.postProgram);this.postVariants = new Map();- this.bloomProgram = finishProgram(this.context, pending.bloom);+ this.bloomProgram = this.backend.finishProgram(pending.bloom);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)]));}@@ -1040,10 +1035,10 @@ export class CrucibleRenderer {if (this.benchmark) return;const context = this.context;this.rebuildMainProgram();- for (const variant of this.postVariants.values()) context.deleteProgram(variant.pending ? finishProgram(context, variant.pending) : variant.program);+ for (const variant of this.postVariants.values()) context.deleteProgram(variant.pending ? this.backend.finishProgram(variant.pending) : variant.program);this.postVariants.clear();context.deleteProgram(this.postProgram);- this.postProgram = finishProgram(context, startProgram(context, fullscreenVertex, this.withViewTransform(postFragment, 'post')));+ this.postProgram = this.backend.finishProgram(this.backend.startProgram(fullscreenVertex, this.withViewTransform(postFragment, 'post')));this.postUniforms = postUniformLocations(context, this.postProgram);// The liquid pass builds its program on its next draw, with the new curve (liquid-renderer.js).if (this.liquidProgram) context.deleteProgram(this.liquidProgram);@@ -1062,7 +1057,7 @@ export class CrucibleRenderer {startMainProgram() {const benchmark = this.benchmark;const fragmentSource = benchmark ? benchmarkFragmentShader : this.withViewTransform(createFragmentShader(this.shaderFeatures), 'main');- return startProgram(this.context, benchmark ? benchmarkVertexShader : createVertexShader(this.shaderFeatures), fragmentSource);+ return this.backend.startProgram(benchmark ? benchmarkVertexShader : createVertexShader(this.shaderFeatures), fragmentSource);}buildMainProgram() {@@ -1070,7 +1065,7 @@ export class CrucibleRenderer {}finishMainProgram(pendingProgram) {- this.program = finishProgram(this.context, pendingProgram);+ this.program = this.backend.finishProgram(pendingProgram);this.uniforms = Object.fromEntries(['materialDielectric', 'materialEmissionFresnel', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'flushBias', 'clipPerMetre', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', 'shadowBiasPerSlope', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', 'wearEnabled', 'wearMetal', 'wearDirt', 'wearShape', 'wearDirtShape', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', 'baseColor', 'surface', 'instanceEmission', 'instanceOpacity', 'boxNormalMatrix', 'shadowBlind', 'compositeMode', 'tintShadowMap', 'tintBlind', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));for (const name of LIGHT_UNIFORMS) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);@@ -1096,7 +1091,7 @@ export class CrucibleRenderer {if (this.benchmark) return 0;const requestedSamples = this.denseSamples == null ? this.baseSamples : samplesForDensity(parts, this.canvas, this.pixelRatio, this.baseSamples, this.denseSamples);const shaded = this.shading === 'light' ? Math.min(requestedSamples, LIGHT_SHADING_MAXIMUM_SAMPLES) : requestedSamples;- return sampleCount(this.context, this.hdr ? this.context.RGBA16F : this.context.RGBA8, Math.min(shaded, this.context.getParameter(this.context.MAX_SAMPLES)));+ return this.backend.supportedSampleCount(this.hdr ? this.context.RGBA16F : this.context.RGBA8, shaded);}get samples() {@@ -1104,10 +1099,9 @@ export class CrucibleRenderer {}uploadBuffer(target, data, usage = this.context.STATIC_DRAW) {- const buffer = this.context.createBuffer();+ const buffer = this.backend.createBuffer();this.buffers.push(buffer);- this.context.bindBuffer(target, buffer);- this.context.bufferData(target, data, usage);+ this.backend.uploadBuffer(target, buffer, data, usage);this.geometryBytes += data.byteLength;return buffer;}@@ -1370,17 +1364,16 @@ export class CrucibleRenderer {context.bindVertexArray(draw.vertexArray);// Only level 0 holds the ranked index order; the simpler levels draw far away, as one range.if (flushRanges && level === 0) this.drawFlushRanges(batch, flushRanges, count);- else context.drawElementsInstanced(context.TRIANGLES, draw.indexCount, context.UNSIGNED_INT, 0, count);+ else this.backend.drawIndexedInstanced(draw.indexCount, count);}}/** Draws a batch rank by rank from its ranked index order (flush-resolve.js), each rank a little closer in depth. */drawFlushRanges(batch, ranges, instanceCount) {- const context = this.context;const base = (batch.depthLayer ?? 0) * RANKS_PER_LAYER;for (const range of ranges) {this.applyDepthRank(base + range.rank);- context.drawElementsInstanced(context.TRIANGLES, range.count, context.UNSIGNED_INT, range.start * 4, instanceCount);+ this.backend.drawIndexedInstanced(range.count, instanceCount, range.start);}this.applyDepthRank(base);}@@ -2029,12 +2022,12 @@ export class CrucibleRenderer {releaseFrameTargets() {const context = this.context;- if (this.multisampleFramebuffer) context.deleteFramebuffer(this.multisampleFramebuffer);- if (this.resolveFramebuffer) context.deleteFramebuffer(this.resolveFramebuffer);- if (this.multisampleColor) context.deleteRenderbuffer(this.multisampleColor);- if (this.multisampleDepth) context.deleteRenderbuffer(this.multisampleDepth);- if (this.frameTexture) context.deleteTexture(this.frameTexture);- if (this.depthTexture) context.deleteTexture(this.depthTexture);+ if (this.multisampleFramebuffer) this.backend.deleteFramebuffer(this.multisampleFramebuffer);+ if (this.resolveFramebuffer) this.backend.deleteFramebuffer(this.resolveFramebuffer);+ if (this.multisampleColor) this.backend.deleteRenderbuffer(this.multisampleColor);+ if (this.multisampleDepth) this.backend.deleteRenderbuffer(this.multisampleDepth);+ if (this.frameTexture) this.backend.deleteTexture(this.frameTexture);+ if (this.depthTexture) this.backend.deleteTexture(this.depthTexture);for (const target of this.bloomTargets ?? []) {context.deleteTexture(target.texture);context.deleteFramebuffer(target.framebuffer);@@ -2113,56 +2106,31 @@ export class CrucibleRenderer {}allocateFrameTargets(width, height) {- const context = this.context;this.releaseFrameTargets();- this.multisampleFramebuffer = context.createFramebuffer();- context.bindFramebuffer(context.FRAMEBUFFER, this.multisampleFramebuffer);- this.multisampleColor = context.createRenderbuffer();- context.bindRenderbuffer(context.RENDERBUFFER, this.multisampleColor);- 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);// 24 bits at least (issue #751): 16 bits is one step per 1.5 cm at 10 m. Reversed depth respecifies this store as 32-bit float.const depthFormat = 'DEPTH_COMPONENT24';- context.renderbufferStorageMultisample(context.RENDERBUFFER, this.multisampleSamples, context[depthFormat], 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.');+ const multisample = this.backend.createMultisampleTarget({ width, height, samples: this.multisampleSamples, hdr: this.hdr });+ this.multisampleFramebuffer = multisample.framebuffer;+ this.multisampleColor = multisample.colorBuffer;+ this.multisampleDepth = multisample.depthBuffer;this.renderTargets.record('multisampleColor', { width, height, format: this.hdr ? 'RGBA16F' : 'RGBA8', samples: this.multisampleSamples });this.renderTargets.record('multisampleDepth', { width, height, format: depthFormat, samples: this.multisampleSamples });this.renderTargets.record('frameColor', { width, height, format: this.hdr ? 'RGBA16F' : 'RGBA8' });- this.frameTexture = context.createTexture();- context.bindTexture(context.TEXTURE_2D, this.frameTexture);- 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);- context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);- this.resolveFramebuffer = context.createFramebuffer();- context.bindFramebuffer(context.FRAMEBUFFER, this.resolveFramebuffer);- context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, this.frameTexture, 0);- if (this.depth) {- this.depthTexture = context.createTexture();- context.bindTexture(context.TEXTURE_2D, this.depthTexture);- context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, width, height, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);- context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);- context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);- 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.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.depthTexture, 0);- this.renderTargets.record('sceneDepth', { width, height, format: 'DEPTH_COMPONENT24' });- }- if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Resolve framebuffer allocation failed. Choose a lower quality preset.');+ const resolve = this.backend.createResolveTarget({ width, height, hdr: this.hdr, depth: this.depth });+ this.resolveFramebuffer = resolve.framebuffer;+ this.frameTexture = resolve.colorTexture;+ this.depthTexture = resolve.depthTexture;+ if (this.depth) this.renderTargets.record('sceneDepth', { width, height, format: depthFormat });this.bloomWidth = Math.max(1, Math.ceil(width / 2));this.bloomHeight = Math.max(1, Math.ceil(height / 2));- context.bindFramebuffer(context.FRAMEBUFFER, null);+ this.backend.bindCanvasTarget();}// The prefilter and BRDF programs build while the other programs do, instead of after them.startEnvironmentPrograms() {this.pendingEnvironmentPrograms = new Map();for (const fragmentSource of [requireEnvironmentSupport().prefilterFragment, requireEnvironmentSupport().brdfFragment]) {- this.pendingEnvironmentPrograms.set(fragmentSource, startProgram(this.context, fullscreenVertex, fragmentSource));+ this.pendingEnvironmentPrograms.set(fragmentSource, this.backend.startProgram(fullscreenVertex, fragmentSource));}}@@ -2170,7 +2138,7 @@ export class CrucibleRenderer {const pendingProgram = this.pendingEnvironmentPrograms?.get(fragmentSource);if (!pendingProgram) return compileProgram(context, vertexSource, fragmentSource);this.pendingEnvironmentPrograms.delete(fragmentSource);- return finishProgram(context, pendingProgram);+ return this.backend.finishProgram(pendingProgram);}initializeEnvironment(map) {@@ -2337,14 +2305,14 @@ export class CrucibleRenderer {const key = steps.join(',');let variant = this.postVariants.get(key);if (!variant) {- variant = { pending: startProgram(this.context, fullscreenVertex, this.withViewTransform(createPostFragment(steps), 'post')) };+ variant = { pending: this.backend.startProgram(fullscreenVertex, this.withViewTransform(createPostFragment(steps), 'post')) };this.postVariants.set(key, variant);}if (variant.pending) {const parallelCompile = this.context.getExtension('KHR_parallel_shader_compile');const building = !this.exactFrames && parallelCompile && !POST_STEPS_WITH_OPTIONAL_CODE.some(step => steps.includes(step)) && !this.context.getProgramParameter(variant.pending.program, parallelCompile.COMPLETION_STATUS_KHR);if (building) return { program: this.postProgram, uniforms: this.postUniforms };- variant.program = finishProgram(this.context, variant.pending);+ variant.program = this.backend.finishProgram(variant.pending);variant.uniforms = postUniformLocations(this.context, variant.program);variant.pending = null;}@@ -2363,9 +2331,7 @@ export class CrucibleRenderer {resolveFrame(frame, effects, environment, volume) {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 | (this.depth ? context.DEPTH_BUFFER_BIT : 0), context.NEAREST);+ this.backend.resolveMultisample({ source: this.multisampleFramebuffer, destination: this.resolveFramebuffer, width: this.canvas.width, height: this.canvas.height, depth: this.depth });this.restoreSingleLevelFiltering();let sourceTexture = this.frameTexture;for (const stage of this.postStages) sourceTexture = stage.apply(this, frame, effects, sourceTexture) ?? sourceTexture;@@ -2713,7 +2679,7 @@ export class CrucibleRenderer {}if (textured && !this.benchmark && this.shaderFeatures?.has('instanced') === false)this.setSingleInstanceUniforms(batch.instanceData);// A reflecting matrix reverses screen winding: clockwise triangles are the front faces of a mirrored batch.- if (batch.mirrored) this.context.frontFace(this.context.CW);+ if (batch.mirrored) this.backend.setFrontFaceClockwise(true);// The shadow pass (not textured) draws the whole index buffer; its order does not matter there.const flushRanges = textured && !this.benchmark ? batch.flushOrder?.ranges ?? null : null;if (selection && !selection.isEverything) {@@ -2721,9 +2687,9 @@ export class CrucibleRenderer {} else {this.context.bindVertexArray(batch.vertexArray);if (flushRanges) this.drawFlushRanges(batch, flushRanges, batch.instanceCount);- else this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);+ else this.backend.drawIndexedInstanced(batch.indexCount, batch.instanceCount);}- if (batch.mirrored) this.context.frontFace(this.context.CCW);+ if (batch.mirrored) this.backend.setFrontFaceClockwise(false);}// A render pass draws raw material data instead of the lit image; the addon validates frame.pass and returns the shader mode.@@ -2966,7 +2932,7 @@ export class CrucibleRenderer {this.context.deleteProgram(this.depthProgram);if (this.postProgram) this.context.deleteProgram(this.postProgram);// A program still linking must finish first: deleting it mid-link leaves a GL error that the next renderer on this context sees.- for (const variant of this.postVariants?.values() ?? []) this.context.deleteProgram(variant.pending ? finishProgram(this.context, variant.pending) : variant.program);+ for (const variant of this.postVariants?.values() ?? []) this.context.deleteProgram(variant.pending ? this.backend.finishProgram(variant.pending) : variant.program);if (this.skyProgram) this.context.deleteProgram(this.skyProgram);if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);if (this.occlusionProgram) this.context.deleteProgram(this.occlusionProgram);diff --git a/tests/dense-samples.test.js b/tests/dense-samples.test.jsindex 253a6651..29898895 100644--- a/tests/dense-samples.test.js+++ b/tests/dense-samples.test.js@@ -2,6 +2,7 @@import test from 'node:test';import assert from 'node:assert/strict';import { CrucibleRenderer, samplesForDensity, DENSE_TRIANGLES_PER_PIXEL } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';function partWithTriangles(count) {return { geometry: { indices: new Uint32Array(count * 3) } };@@ -57,7 +58,7 @@ function resizingRenderer({ clientWidth, clientHeight, parts }) {const renderer = Object.create(CrucibleRenderer.prototype);const allocations = [];Object.assign(renderer, {- context, canvas, pixelRatio: 1, hdr: false, benchmark: false, shading: 'full', baseSamples: 4, denseSamples: 2, densityParts: parts, fitParts: [...parts, partWithTriangles(5000)], world: false,+ context, backend: new WebGL2GlazeBackend(context), canvas, pixelRatio: 1, hdr: false, benchmark: false, shading: 'full', baseSamples: 4, denseSamples: 2, densityParts: parts, fitParts: [...parts, partWithTriangles(5000)], world: false,projection: new Float32Array(16), capabilities: { samples: 4 }, geometryBytes: 0, textureBytes: 0, depth: false, memoryBudgetMiB: 4096, maximumMemoryBudgetMiB: 4096,allocateFrameTargets(width, height) { allocations.push([width, height, this.multisampleSamples]); },});diff --git a/tests/exact-frames-post-program.test.js b/tests/exact-frames-post-program.test.jsindex 4b4dee13..2ea891c4 100644--- a/tests/exact-frames-post-program.test.js+++ b/tests/exact-frames-post-program.test.js@@ -1,6 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';import { CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';// A frame drawn while the driver still builds its post program uses the program with every step, whose maths differs from the// specialised program by a half-float step on some pixels, so a cold first frame differed from a warm one (#1767). A renderer@@ -34,6 +35,7 @@ function createStubRenderer({ exactFrames }) {const renderer = Object.create(CrucibleRenderer.prototype);Object.assign(renderer, {context,+ backend: new WebGL2GlazeBackend(context),exactFrames,postProgram: { name: 'fallback' },postUniforms: { name: 'fallback uniforms' },diff --git a/tests/flush-resolve.test.js b/tests/flush-resolve.test.jsindex b5f45f98..0e251480 100644--- a/tests/flush-resolve.test.js+++ b/tests/flush-resolve.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import { flushOrderOf, MAXIMUM_FLUSH_RANK } from '../src/depth-layer.js';import { resolveFlush } from '../src/flush-resolve.js';import { CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';import { vertexShader } from '../src/shaders.js';const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];@@ -249,7 +250,7 @@ test('a depth rank is a metric bias plus a slope-only offset, switched off for rtest('a ranked batch draws one range per rank above its own layer and ends on the layer', () => {const { calls, context } = recordingContext();- const fake = { context, uniforms: {}, applyDepthRank: CrucibleRenderer.prototype.applyDepthRank };+ const fake = { context, backend: new WebGL2GlazeBackend(context), uniforms: {}, applyDepthRank: CrucibleRenderer.prototype.applyDepthRank };const ranges = [{ start: 0, count: 6, rank: 0 }, { start: 6, count: 12, rank: 3 }];CrucibleRenderer.prototype.drawFlushRanges.call(fake, { depthLayer: 1 }, ranges, 5);assert.deepEqual(calls.filter(call => call[0] === 'draw'), [['draw', 6, 0, 5], ['draw', 12, 24, 5]]);diff --git a/tests/glaze-backend.test.js b/tests/glaze-backend.test.jsnew file mode 100644index 00000000..42c51455--- /dev/null+++ b/tests/glaze-backend.test.js@@ -0,0 +1,185 @@+// The Glaze backend boundary (#901): the WebGL2 implementation issues exactly the GL calls CrucibleRenderer made itself before the boundary existed.+// A recording context stands in for WebGL2; the expected lists below are the calls of the old renderer code, in order.+import test from 'node:test';+import assert from 'node:assert/strict';+import { createGlazeBackend } from '../src/glaze-backend.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';++// Constants answer their own name, so the log reads GL_CONSTANT; methods log their call and return a numbered object.+function createRecordingContext(overrides = {}) {+ const calls = [];+ let created = 0;+ const values = { COLOR_BUFFER_BIT: 16384, DEPTH_BUFFER_BIT: 256, checkFramebufferStatus: () => 'FRAMEBUFFER_COMPLETE', ...overrides };+ const context = new Proxy({}, {+ get(target, name) {+ if (name in values) return values[name];+ if (/^[A-Z0-9_]+$/.test(name)) return name;+ return (...args) => {+ calls.push([name, ...args.map((argument) => (argument === null || typeof argument !== 'object' ? argument : argument.label ?? 'data'))]);+ if (name.startsWith('create')) return { label: `${name.slice(6).toLowerCase()}${++created}` };+ return undefined;+ };+ },+ });+ return { context, calls };+}++test('a multisample target allocates the same calls as the renderer did, in the same order', () => {+ const { context, calls } = createRecordingContext();+ const backend = new WebGL2GlazeBackend(context);+ const target = backend.createMultisampleTarget({ width: 64, height: 32, samples: 4, hdr: true });+ assert.deepEqual(calls, [+ ['createFramebuffer'],+ ['bindFramebuffer', 'FRAMEBUFFER', 'framebuffer1'],+ ['createRenderbuffer'],+ ['bindRenderbuffer', 'RENDERBUFFER', 'renderbuffer2'],+ ['renderbufferStorageMultisample', 'RENDERBUFFER', 4, 'RGBA16F', 64, 32],+ ['framebufferRenderbuffer', 'FRAMEBUFFER', 'COLOR_ATTACHMENT0', 'RENDERBUFFER', 'renderbuffer2'],+ ['createRenderbuffer'],+ ['bindRenderbuffer', 'RENDERBUFFER', 'renderbuffer3'],+ ['renderbufferStorageMultisample', 'RENDERBUFFER', 4, 'DEPTH_COMPONENT24', 64, 32],+ ['framebufferRenderbuffer', 'FRAMEBUFFER', 'DEPTH_ATTACHMENT', 'RENDERBUFFER', 'renderbuffer3'],+ ]);+ assert.deepEqual([target.framebuffer.label, target.colorBuffer.label, target.depthBuffer.label], ['framebuffer1', 'renderbuffer2', 'renderbuffer3']);+});++test('a resolve target creates its colour texture, framebuffer and depth texture in the old order', () => {+ const { context, calls } = createRecordingContext();+ const backend = new WebGL2GlazeBackend(context);+ const target = backend.createResolveTarget({ width: 8, height: 4, hdr: false, depth: true });+ const filtering = (filter) => [+ ['texParameteri', 'TEXTURE_2D', 'TEXTURE_MIN_FILTER', filter],+ ['texParameteri', 'TEXTURE_2D', 'TEXTURE_MAG_FILTER', filter],+ ['texParameteri', 'TEXTURE_2D', 'TEXTURE_WRAP_S', 'CLAMP_TO_EDGE'],+ ['texParameteri', 'TEXTURE_2D', 'TEXTURE_WRAP_T', 'CLAMP_TO_EDGE'],+ ];+ assert.deepEqual(calls, [+ ['createTexture'],+ ['bindTexture', 'TEXTURE_2D', 'texture1'],+ ['texImage2D', 'TEXTURE_2D', 0, 'RGBA8', 8, 4, 0, 'RGBA', 'UNSIGNED_BYTE', null],+ ...filtering('LINEAR'),+ ['createFramebuffer'],+ ['bindFramebuffer', 'FRAMEBUFFER', 'framebuffer2'],+ ['framebufferTexture2D', 'FRAMEBUFFER', 'COLOR_ATTACHMENT0', 'TEXTURE_2D', 'texture1', 0],+ ['createTexture'],+ ['bindTexture', 'TEXTURE_2D', 'texture3'],+ ['texImage2D', 'TEXTURE_2D', 0, 'DEPTH_COMPONENT24', 8, 4, 0, 'DEPTH_COMPONENT', 'UNSIGNED_INT', null],+ ...filtering('NEAREST'),+ ['framebufferTexture2D', 'FRAMEBUFFER', 'DEPTH_ATTACHMENT', 'TEXTURE_2D', 'texture3', 0],+ ]);+ assert.equal(target.depthTexture.label, 'texture3');+});++test('a target that is not complete throws the renderer error', () => {+ const { context, calls } = createRecordingContext({ checkFramebufferStatus: () => 'FRAMEBUFFER_UNSUPPORTED' });+ const backend = new WebGL2GlazeBackend(context);+ assert.throws(() => backend.createMultisampleTarget({ width: 1, height: 1, samples: 4, hdr: false }), /Multisample framebuffer allocation failed/);+ assert.throws(() => backend.createResolveTarget({ width: 1, height: 1, hdr: false, depth: false }), /Resolve framebuffer allocation failed/);+ assert.deepEqual(calls.filter(([name]) => name.startsWith('delete')), [['deleteFramebuffer', 'framebuffer1'], ['deleteRenderbuffer', 'renderbuffer2'], ['deleteRenderbuffer', 'renderbuffer3'], ['deleteFramebuffer', 'framebuffer5'], ['deleteTexture', 'texture4']], 'a failed allocation releases what it created');+});++test('resolving a multisample target binds read and draw and blits colour, and depth when asked', () => {+ const { context, calls } = createRecordingContext();+ const backend = new WebGL2GlazeBackend(context);+ backend.resolveMultisample({ source: { label: 'source' }, destination: { label: 'destination' }, width: 640, height: 480, depth: false });+ backend.resolveMultisample({ source: { label: 'source' }, destination: { label: 'destination' }, width: 640, height: 480, depth: true });+ assert.deepEqual(calls, [+ ['bindFramebuffer', 'READ_FRAMEBUFFER', 'source'],+ ['bindFramebuffer', 'DRAW_FRAMEBUFFER', 'destination'],+ ['blitFramebuffer', 0, 0, 640, 480, 0, 0, 640, 480, 16384, 'NEAREST'],+ ['bindFramebuffer', 'READ_FRAMEBUFFER', 'source'],+ ['bindFramebuffer', 'DRAW_FRAMEBUFFER', 'destination'],+ ['blitFramebuffer', 0, 0, 640, 480, 0, 0, 640, 480, 16384 | 256, 'NEAREST'],+ ]);+});++test('a draw is one drawElementsInstanced call over 32-bit indices, offset in bytes', () => {+ const { context, calls } = createRecordingContext();+ const backend = new WebGL2GlazeBackend(context);+ backend.drawIndexedInstanced(36, 5);+ backend.drawIndexedInstanced(12, 3, 24);+ assert.deepEqual(calls, [+ ['drawElementsInstanced', 'TRIANGLES', 36, 'UNSIGNED_INT', 0, 5],+ ['drawElementsInstanced', 'TRIANGLES', 12, 'UNSIGNED_INT', 96, 3],+ ]);+});++test('mirrored winding, buffers, readback and canvas binding wrap the single GL call they replace', () => {+ const { context, calls } = createRecordingContext();+ const backend = new WebGL2GlazeBackend(context);+ backend.setFrontFaceClockwise(true);+ backend.setFrontFaceClockwise(false);+ const buffer = backend.createBuffer();+ backend.uploadBuffer('ARRAY_BUFFER', buffer, new Float32Array(3));+ backend.deleteBuffer(buffer);+ backend.bindCanvasTarget();+ backend.readPixels(0, 0, 2, 2, 'RGBA', 'FLOAT', new Float32Array(16));+ assert.deepEqual(calls, [+ ['frontFace', 'CW'],+ ['frontFace', 'CCW'],+ ['createBuffer'],+ ['bindBuffer', 'ARRAY_BUFFER', 'buffer1'],+ ['bufferData', 'ARRAY_BUFFER', 'data', 'STATIC_DRAW'],+ ['deleteBuffer', 'buffer1'],+ ['bindFramebuffer', 'FRAMEBUFFER', null],+ ['readPixels', 0, 0, 2, 2, 'RGBA', 'FLOAT', 'data'],+ ]);+});++test('the sample count is the largest one the driver offers for colour and depth, within the request and MAX_SAMPLES', () => {+ const { context } = createRecordingContext({+ getParameter: () => 4,+ getInternalformatParameter: (target, format) => (format === 'DEPTH_COMPONENT24' ? [8, 4, 2, 1] : [8, 4, 1]),+ });+ const backend = new WebGL2GlazeBackend(context);+ assert.equal(backend.supportedSampleCount('RGBA8', 16), 4);+ assert.equal(backend.supportedSampleCount('RGBA8', 2), 1);+ assert.equal(backend.supportedSampleCount('RGBA8', 0), 0);+});++test('the canvas opens as WebGL2 and a missing context says what to do', () => {+ const { context } = createRecordingContext();+ const requested = [];+ const backend = createGlazeBackend({ getContext: (type, options) => (requested.push([type, options]), context) }, { transparent: true });+ assert.equal(backend.name, 'webgl2');+ assert.equal(backend.context, context);+ assert.deepEqual(requested, [['webgl2', { antialias: true, premultipliedAlpha: true, powerPreference: 'high-performance', alpha: true }]]);+ assert.throws(() => createGlazeBackend({ getContext: () => null }), /WebGL2 is unavailable\. Enable hardware acceleration/);+});++// The renderer's frame core goes through the boundary: a real frame (headless Chrome, SwiftShader) allocates its targets,+// draws and resolves through the backend, and the backend wraps the context the unported passes still use.+test('a rendered frame allocates, draws and resolves through the backend', async (testContext) => {+ const { withDevServerPage } = await import('./helpers/dev-server-browser.js');+ await withDevServerPage(testContext, async (page) => {+ const result = await page.evaluate(async () => {+ const { box } = await import('/src/geometry.js');+ const { CrucibleRenderer } = await import('/src/renderer.js');+ const canvas = document.createElement('canvas');+ canvas.width = 64;+ canvas.height = 64;+ document.body.append(canvas);+ const parts = [{ name: 'cube', geometry: box(0, 1), matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0.5, 0, 1]), material: { id: 'cube', tag: 'surface', color: [0.8, 0.3, 0.2], metallic: 0, roughness: 0.5 } }];+ const renderer = new CrucibleRenderer(canvas, parts, { ground: false, samples: 4, pixelRatio: 1, depth: true });+ const names = ['createMultisampleTarget', 'createResolveTarget', 'resolveMultisample', 'drawIndexedInstanced', 'startProgram', 'createBuffer'];+ const counts = Object.fromEntries(names.map((name) => [name, 0]));+ for (const name of names) {+ const original = renderer.backend[name].bind(renderer.backend);+ renderer.backend[name] = (...args) => (counts[name]++, original(...args));+ }+ renderer.allocateFrameTargets(canvas.width, canvas.height);+ renderer.render({ eye: [0, 2, 4], target: [0, 0.5, 0] });+ const backendIsSharedWithContext = renderer.backend.context === renderer.context;+ const glError = renderer.context.getError();+ renderer.dispose?.();+ return { counts, backendIsSharedWithContext, glError, backendName: renderer.backend.name };+ });+ assert.equal(result.backendName, 'webgl2');+ assert.ok(result.backendIsSharedWithContext);+ assert.equal(result.glError, 0);+ assert.equal(result.counts.createMultisampleTarget, 1);+ assert.equal(result.counts.createResolveTarget, 1);+ assert.ok(result.counts.resolveMultisample >= 1, 'the frame resolves through the backend');+ assert.ok(result.counts.drawIndexedInstanced >= 1, 'the opaque draw goes through the backend');+ });+});diff --git a/tests/mirrored-winding.test.js b/tests/mirrored-winding.test.jsindex b6e02770..28e5262a 100644--- a/tests/mirrored-winding.test.js+++ b/tests/mirrored-winding.test.js@@ -3,6 +3,7 @@ import test from 'node:test';import { mat3 } from 'gl-matrix';import { materialLayerState } from '../src/material-layers.js';import { groupParts, isMirroredMatrix, CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';const quad = {positions: new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]),@@ -45,6 +46,7 @@ test('a mirrored batch draws with clockwise front faces and restores the defaultfrontFace(mode) { calls.push(`frontFace ${mode}`); },drawElementsInstanced() { calls.push('draw'); },};+ renderer.backend = new WebGL2GlazeBackend(renderer.context);renderer.drawBatch({ mirrored: true, indexCount: 6, instanceCount: 1 });renderer.drawBatch({ mirrored: false, indexCount: 6, instanceCount: 1 });assert.deepEqual(calls, ['frontFace cw', 'draw', 'frontFace ccw', 'draw']);@@ -64,6 +66,7 @@ test('updateParts regroups once when a part crosses a mirror instead of throwingbatch.mirrored = isMirroredMatrix(part.matrix);};renderer.context = { ARRAY_BUFFER: 1, bindBuffer() {}, bufferSubData() {} };+ renderer.backend = new WebGL2GlazeBackend(renderer.context);for (const scaleX of [1, 0.5, -0.5, -1, -0.25, 0.75]) {part.matrix[0] = scaleX;assert.equal(renderer.updateParts([part]), 1);diff --git a/tests/morph-renderer.test.js b/tests/morph-renderer.test.jsindex 1285e4e4..11f1e905 100644--- a/tests/morph-renderer.test.js+++ b/tests/morph-renderer.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import { mat4, mat3 } from 'gl-matrix';import { box } from '../src/geometry.js';import { CrucibleRenderer, groupParts } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';import { createMorphPose, validateMorphGeometry } from '../src/morph.js';import { materialLayerState } from '../src/material-layers.js';@@ -97,6 +98,7 @@ test('main and shadow draws upload the retained morph weights and disable morphsTEXTURE0: 33984, activeTexture() {}, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},uniform1f(name, value) { uploads.push([name, value]); }, uniform1i() {}, uniform1fv(name, values) { uploads.push([name, values]); },};+ renderer.backend = new WebGL2GlazeBackend(renderer.context);const batch = { morph: {}, morphTexture: { info: { vertexCount: 3, targetCount: 1 }, texture: {} }, morphWeights: new Float32Array([0.5]) };renderer.drawBatch(batch, true);renderer.drawBatch(batch);@@ -116,6 +118,7 @@ test('a batch with more than 64 targets uploads its 64 largest weights with theiTEXTURE0: 33984, activeTexture() {}, bindTexture() {}, bindVertexArray() {}, drawElementsInstanced() {},uniform1f() {}, uniform1i(name, value) { uploads[name] = value; }, uniform1fv(name, values) { uploads[name] = [...values]; },};+ renderer.backend = new WebGL2GlazeBackend(renderer.context);const morphWeights = new Float32Array(175);morphWeights[170] = 0.25;morphWeights[7] = 1;diff --git a/tests/render-culling.test.js b/tests/render-culling.test.jsindex cba84a34..b4227ee1 100644--- a/tests/render-culling.test.js+++ b/tests/render-culling.test.js@@ -4,6 +4,7 @@ import { mat4 } from 'gl-matrix';import { box, sphere } from '../src/geometry.js';import { generateGeometryLods } from '../src/mesh-lod.js';import { CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';import { InstanceSelection, chooseLevel, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from '../src/render-culling.js';const STRIDE = 42;@@ -102,6 +103,7 @@ function drawingRenderer(parts) {bufferSubData: (target, offset, data, start, length) => calls.push({ upload: length / STRIDE }),drawElementsInstanced: (mode, count, type, offset, instances) => calls.push({ indices: count, instances }),};+ renderer.backend = new WebGL2GlazeBackend(renderer.context);renderer.createTexture = () => null;renderer.partLocations = new Map();renderer.uploadBuffer = (target, data) => {diff --git a/tests/render-target-memory.test.js b/tests/render-target-memory.test.jsindex 0c2f5386..831ebae9 100644--- a/tests/render-target-memory.test.js+++ b/tests/render-target-memory.test.js@@ -1,6 +1,7 @@import test from 'node:test';import assert from 'node:assert/strict';import { CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';import { RenderTargetLedger } from '../src/render-target-ledger.js';import { useCompactColor } from '../src/compact-color.js';import { CascadedShadows } from '../src/cascaded-shadows.js';@@ -46,7 +47,7 @@ function shadowRenderer(batches) {const { context, sizes } = recordingContext();const renderer = Object.create(CrucibleRenderer.prototype);Object.assign(renderer, {- context, batches, renderTargets: new RenderTargetLedger(), world: null, activeLightDirection: [1, 2, 3], shadowBounds: {},+ context, backend: new WebGL2GlazeBackend(context), batches, renderTargets: new RenderTargetLedger(), world: null, activeLightDirection: [1, 2, 3], shadowBounds: {},lightProjection: new Float32Array(16), windState: { time: 0, strength: 0 }, drawShadowCasters() {},});return { renderer, sizes };@@ -75,7 +76,7 @@ function frameTargetRenderer(depth) {const { context } = recordingContext();const renderer = Object.create(CrucibleRenderer.prototype);Object.assign(renderer, {- context, depth, hdr: true, multisampleSamples: 4, renderTargets: new RenderTargetLedger(), releaseFrameTargets() {},+ context, backend: new WebGL2GlazeBackend(context), depth, hdr: true, multisampleSamples: 4, renderTargets: new RenderTargetLedger(), releaseFrameTargets() {},});return renderer;}diff --git a/tests/renderer-topology.test.js b/tests/renderer-topology.test.jsindex ff4a3c2b..72af7175 100644--- a/tests/renderer-topology.test.js+++ b/tests/renderer-topology.test.js@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';import { mat4 } from 'gl-matrix';import { box, sphere } from '../src/geometry.js';import { CrucibleRenderer } from '../src/renderer.js';+import { WebGL2GlazeBackend } from '../src/glaze-backend-webgl2.js';import '../src/replace-textured-parts.js';function part(name, geometry) {@@ -46,6 +47,7 @@ function allocationRenderer() {return error;},};+ renderer.backend = new WebGL2GlazeBackend(renderer.context);renderer.canvas = { width: 64, height: 64 };renderer.multisampleSamples = 0;renderer.memoryBudgetMiB = 64;