From bd24bd4788f35daff0af5578ebc26e409465bde6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 17:39:18 +0000 Subject: [PATCH 1/3] web: GL probe names the failing GL call, checks lightmap data, heartbeat The probe showed the in-game trails are gone (frames are cleared), but a GL error (0x500, INVALID_ENUM) every frame, lit world surfaces rendering black, and a freeze after the first chamber loads. Extend it so the next diagnostics pin all three down: - Error hunt: for three short windows (frames 6-8, 200-203, 450-453) every WebGL call is followed by glGetError and the rejected calls are logged with their arguments. The wrappers are installed only for the window and removed after, so normal frames pay nothing. - Texture uploads: the first texSubImage2D/texImage2D calls are logged with size, format, UNPACK_ROW_LENGTH and a sample of their bytes (mean, share of non-zero), to see whether lightmap data reaches WebGL. - Heartbeat: an "alive" line with frame count and fps about every 10 s, so a freeze shows as the moment the lines stop. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Qy5DKdwTqGQqScWvJyNcft --- emscripten/pre.js | 102 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 101 insertions(+), 1 deletion(-) diff --git a/emscripten/pre.js b/emscripten/pre.js index ab4dfc7fdc..718eeb4218 100644 --- a/emscripten/pre.js +++ b/emscripten/pre.js @@ -860,7 +860,7 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { const FACTORS = { 0: '0', 1: '1', 0x300: 'sc', 0x301: '1-sc', 0x302: 'sa', 0x303: '1-sa', 0x304: 'da', 0x305: '1-da', 0x306: 'dc', 0x307: '1-dc', 0x308: 'sat' } const factor = f => FACTORS[f] ?? Number(f).toString(16) let frame = null - const resetFrame = () => { frame = { draws: 0, blendDraws: 0, noDepthTest: 0, noDepthWrite: 0, noColor: 0, funcs: {}, clears: [], fbSwitches: 0 } } + const resetFrame = () => { frame = { draws: 0, blendDraws: 0, noDepthTest: 0, noDepthWrite: 0, noColor: 0, funcs: {}, clears: [], fbSwitches: 0, uploads: 0 } } resetFrame() let frames = 0, reports = 0 const REPORT_AT = new Set([5, 30, 120, 300, 600]) @@ -903,10 +903,110 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { if(S.colorMask === 'none') frame.noColor++ } for(const name of ['drawElements', 'drawArrays', 'drawRangeElements', 'drawElementsInstanced', 'drawArraysInstanced']) wrap(name, onDraw) + // Texture uploads: lit surfaces render black, so check whether the texel + // data that reaches WebGL is actually filled in (lightmap pages are + // updated with texSubImage2D). Logs the first few uploads with a sample of + // their bytes. + const U = { rowLength: 0, skipPixels: 0, skipRows: 0 } + wrap('pixelStorei', (pname, value) => { + if(pname === 0x0CF2) U.rowLength = value + else if(pname === 0x0CF4) U.skipPixels = value + else if(pname === 0x0CF3) U.skipRows = value + }) + const BYTES_PER_TEXEL = { 0x1908: 4, 0x1907: 3, 0x1909: 1, 0x190A: 2, 0x1903: 1, 0x8227: 2 } + const sampleTexels = (w, h, format, type, data, offset) => { + if(!data || typeof data !== 'object' || type !== 0x1401) return 'no-data' + const bpp = BYTES_PER_TEXEL[format] + if(!bpp) return 'fmt 0x' + format.toString(16) + const rowBytes = (U.rowLength || w) * bpp + const base = (offset || 0) + U.skipRows * rowBytes + U.skipPixels * bpp + const rows = Math.min(h, 16), cols = Math.min(w * bpp, 512) + let sum = 0, n = 0, nonzero = 0 + for(let y = 0; y < rows; y++) { + const row = base + Math.floor(y * h / rows) * rowBytes + for(let x = 0; x < cols; x++) { + const v = data[row + x] | 0 + sum += v; n++; if(v) nonzero++ + } + } + return n ? `mean ${Math.round(sum / n)} nonzero ${Math.round(100 * nonzero / n)}%` : 'empty' + } + let subUploadLogs = 0, imageUploadLogs = 0 + wrap('texSubImage2D', (target, level, x, y, w, h, format, type, data, offset) => { + frame.uploads++ + if(subUploadLogs >= 10 || w * h < 64) return + subUploadLogs++ + render360Log(`[Render360 GL] texSubImage2D ${w}x${h} at ${x},${y} level ${level} fmt 0x${Number(format).toString(16)} rowLength ${U.rowLength}: ${sampleTexels(w, h, format, type, data, offset)}`) + }) + wrap('texImage2D', (target, level, internalformat, w, h, border, format, type, data, offset) => { + frame.uploads++ + if(imageUploadLogs >= 8 || level !== 0 || w < 128 || h < 128 || typeof w !== 'number') return + imageUploadLogs++ + render360Log(`[Render360 GL] texImage2D ${w}x${h} ifmt 0x${Number(internalformat).toString(16)} fmt 0x${Number(format).toString(16)}: ${sampleTexels(w, h, format, type, data, offset)}`) + }) + + // Error hunt: during a few frames, check glGetError after every call and + // name the calls WebGL rejects (diagnostics show a GL error every frame). + let hunting = false + const huntFound = new Map() + const fmtArg = a => typeof a === 'number' + ? (Number.isInteger(a) && a > 255 ? '0x' + a.toString(16) : String(a)) + : (a === null ? 'null' : (a?.constructor?.name || typeof a)) + const getError = P.getError + const huntOriginals = new Map() + // Wrappers go on only for the hunt window and come off after, so normal + // frames pay nothing for them. + const startHunt = () => { + for(const name of Object.getOwnPropertyNames(P)) { + if(name === 'getError' || name === 'constructor' || name === 'isContextLost') continue + const desc = Object.getOwnPropertyDescriptor(P, name) + if(!desc || typeof desc.value !== 'function') continue + const original = desc.value + huntOriginals.set(name, original) + P[name] = function(...args) { + const result = original.apply(this, args) + let e = 0 + try { e = getError.call(this) } catch(_) {} + if(e && huntFound.size < 12) { + const key = name + ':' + e + if(!huntFound.has(key)) huntFound.set(key, `${name}(${args.slice(0, 7).map(fmtArg).join(', ')}) -> 0x${e.toString(16)}`) + } + return result + } + } + hunting = true + } + const stopHunt = () => { + for(const [name, original] of huntOriginals) P[name] = original + huntOriginals.clear() + hunting = false + } + const HUNT_WINDOWS = [[6, 8], [200, 203], [450, 453]] + + // Heartbeat: a line every ~10 s while frames are being presented, so a + // freeze shows up as the time the lines stop. + let lastBeat = 0, beatFrames = 0, beats = 0 + wrap('blitFramebuffer', function() { if(S.drawFb) return // A blit to the canvas is ToGL presenting a frame. frames++ + for(const [start, end] of HUNT_WINDOWS) { + if(frames === start && !hunting) { try { getError.call(this) } catch(_) {} startHunt() } + if(frames === end && hunting) { + stopHunt() + render360Log(`[Render360 GL] error hunt frames ${start}-${end}: ${[...huntFound.values()].join(' | ') || 'no GL errors'}`) + huntFound.clear() + } + } + const now = performance.now() + if(!lastBeat) { lastBeat = now; beatFrames = frames } + else if(now - lastBeat > 10000 && beats < 60) { + beats++ + const fps = (frames - beatFrames) * 1000 / (now - lastBeat) + render360Log(`[Render360 GL] alive: frame ${frames}, ${fps.toFixed(1)} fps, ${frame.draws} draws, ${frame.uploads} uploads this frame`) + lastBeat = now; beatFrames = frames + } if(REPORT_AT.has(frames) || (frames > 600 && frames % 900 === 0 && reports < 20)) { reports++ let err = 0 From f7bb0eca9ec7d1f35483b9ca36285485c461519f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 10 Oct 2026 23:32:17 +0000 Subject: [PATCH 2/3] togles: fix the GL calls WebGL rejects (black lit surfaces); freeze probe The GL probe named the calls WebGL rejects in game: - texImage2D(GL_RGB8 internal format, GL_RGBA data) -> INVALID_OPERATION. D3DFMT_X8R8G8B8 is 4-byte BGRX data kept in a 3-channel GL_RGB8 texture, a pairing GLES 3 / WebGL 2 do not allow, so every such texture (normal maps, the engine's 1x1 white/grey/black fallback textures) had no image and sampled black. On web X8R8G8B8 is reported unsupported, so the material system converts those images to R8G8B8 when it loads them; convert_texture also promotes RGB8 to RGBA8 whenever 4-channel data arrives, so no texture is left without an image. - texParameter(GL_TEXTURE_BORDER_COLOR), the GL_CLAMP_TO_BORDER wrap mode and enable/disable(GL_FRAMEBUFFER_SRGB) -> INVALID_ENUM every frame. WebGL has none of them: skip the border colour, clamp to edge instead, and leave the sRGB write to the shader (as the web build already does). Freeze: frames stopped about 12 s into the first chamber. The probe now logs frames slower than 1.5 s with their draws, uploads and GPU buffer read-backs, counts read-backs in the heartbeat, adds the framebuffer status to INVALID_FRAMEBUFFER_OPERATION errors, and the page logs when the render thread stops presenting frames and when it resumes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Qy5DKdwTqGQqScWvJyNcft --- emscripten/pre.js | 48 +++++++++++++++++++++++++++++--- public/togles/linuxwin/cglmtex.h | 23 +++++++++++---- public/togles/linuxwin/glmgr.h | 4 +++ togles/linuxwin/cglmtex.cpp | 5 ++++ togles/linuxwin/dxabstract.cpp | 13 ++++++++- 5 files changed, 82 insertions(+), 11 deletions(-) diff --git a/emscripten/pre.js b/emscripten/pre.js index 718eeb4218..3c42922e8c 100644 --- a/emscripten/pre.js +++ b/emscripten/pre.js @@ -176,6 +176,27 @@ if(render360IsWindow && render360CrashChannel) { try { Module.printErr?.(String(event.data.text || '')) } catch(_) {} } }) + // Frame watchdog: the render worker pings every ~2 s while it presents + // frames. A thread that hangs cannot log anything itself, so the page + // notes when the pings stop (and when they come back). + let lastFramePing = 0, lastFrameCount = 0, stallReported = false + render360CrashChannel.addEventListener('message', event => { + if(event?.data?.type !== 'render360-frame' || event.data.launchId !== render360LaunchId) return + const now = performance.now() + if(stallReported) { + try { Module.printErr?.(`[Render360 GL] frames resumed after ${((now - lastFramePing) / 1000).toFixed(0)} s at frame ${event.data.frames}`) } catch(_) {} + stallReported = false + } + lastFramePing = now + lastFrameCount = event.data.frames + }) + setInterval(() => { + if(!lastFramePing || stallReported) return + const gap = performance.now() - lastFramePing + if(gap < 8000 || document.hidden) return + stallReported = true + try { Module.printErr?.(`[Render360 GL] stalled: no frame for ${(gap / 1000).toFixed(0)} s after frame ${lastFrameCount} (phase ${render360CrashState.phase})`) } catch(_) {} + }, 2000) render360CrashChannel.addEventListener('message', event => { const incoming = event?.data?.type === 'render360-crash-state' ? event.data.state : null if(!incoming || incoming.launchId !== render360LaunchId) return @@ -860,7 +881,7 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { const FACTORS = { 0: '0', 1: '1', 0x300: 'sc', 0x301: '1-sc', 0x302: 'sa', 0x303: '1-sa', 0x304: 'da', 0x305: '1-da', 0x306: 'dc', 0x307: '1-dc', 0x308: 'sat' } const factor = f => FACTORS[f] ?? Number(f).toString(16) let frame = null - const resetFrame = () => { frame = { draws: 0, blendDraws: 0, noDepthTest: 0, noDepthWrite: 0, noColor: 0, funcs: {}, clears: [], fbSwitches: 0, uploads: 0 } } + const resetFrame = () => { frame = { draws: 0, blendDraws: 0, noDepthTest: 0, noDepthWrite: 0, noColor: 0, funcs: {}, clears: [], fbSwitches: 0, uploads: 0, readbacks: 0, readbackBytes: 0, start: performance.now() } } resetFrame() let frames = 0, reports = 0 const REPORT_AT = new Set([5, 30, 120, 300, 600]) @@ -945,6 +966,12 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { render360Log(`[Render360 GL] texImage2D ${w}x${h} ifmt 0x${Number(internalformat).toString(16)} fmt 0x${Number(format).toString(16)}: ${sampleTexels(w, h, format, type, data, offset)}`) }) + // GPU buffer read-backs stall Safari until the GPU catches up; count them. + wrap('getBufferSubData', (target, offset, dst, dstOffset, length) => { + frame.readbacks++ + frame.readbackBytes += Number(length) || 0 + }) + // Error hunt: during a few frames, check glGetError after every call and // name the calls WebGL rejects (diagnostics show a GL error every frame). let hunting = false @@ -969,7 +996,11 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { try { e = getError.call(this) } catch(_) {} if(e && huntFound.size < 12) { const key = name + ':' + e - if(!huntFound.has(key)) huntFound.set(key, `${name}(${args.slice(0, 7).map(fmtArg).join(', ')}) -> 0x${e.toString(16)}`) + let status = '' + if(e === 0x506) { + try { status = ' fbstatus 0x' + this.checkFramebufferStatus(0x8CA9).toString(16) + '/0x' + this.checkFramebufferStatus(0x8CA8).toString(16) } catch(_) {} + } + if(!huntFound.has(key)) huntFound.set(key, `${name}(${args.slice(0, 7).map(fmtArg).join(', ')}) -> 0x${e.toString(16)}${status}`) } return result } @@ -985,7 +1016,7 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { // Heartbeat: a line every ~10 s while frames are being presented, so a // freeze shows up as the time the lines stop. - let lastBeat = 0, beatFrames = 0, beats = 0 + let lastBeat = 0, beatFrames = 0, beats = 0, slowFrames = 0, lastPing = 0 wrap('blitFramebuffer', function() { if(S.drawFb) return @@ -1000,11 +1031,20 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { } } const now = performance.now() + if(now - lastPing > 2000) { + lastPing = now + try { render360CrashChannel?.postMessage({ type: 'render360-frame', launchId: render360LaunchId, frames }) } catch(_) {} + } + const frameMs = now - frame.start + if(frameMs > 1500 && slowFrames < 15) { + slowFrames++ + render360Log(`[Render360 GL] slow frame ${frames}: ${(frameMs / 1000).toFixed(1)} s, ${frame.draws} draws, ${frame.uploads} uploads, ${frame.readbacks} buffer read-backs (${Math.round(frame.readbackBytes / 1024)} KiB)`) + } if(!lastBeat) { lastBeat = now; beatFrames = frames } else if(now - lastBeat > 10000 && beats < 60) { beats++ const fps = (frames - beatFrames) * 1000 / (now - lastBeat) - render360Log(`[Render360 GL] alive: frame ${frames}, ${fps.toFixed(1)} fps, ${frame.draws} draws, ${frame.uploads} uploads this frame`) + render360Log(`[Render360 GL] alive: frame ${frames}, ${fps.toFixed(1)} fps, ${frame.draws} draws, ${frame.uploads} uploads, ${frame.readbacks} read-backs this frame`) lastBeat = now; beatFrames = frames } if(REPORT_AT.has(frames) || (frames > 600 && frames % 900 === 0 && reports < 20)) { diff --git a/public/togles/linuxwin/cglmtex.h b/public/togles/linuxwin/cglmtex.h index 32c7ed043d..db96b266db 100644 --- a/public/togles/linuxwin/cglmtex.h +++ b/public/togles/linuxwin/cglmtex.h @@ -30,6 +30,17 @@ #ifndef CGLMTEX_H #define CGLMTEX_H +// WebGL 2 / GLES 3 have no border colour and no GL_CLAMP_TO_BORDER: both are +// INVALID_ENUM there (left a GL error every frame in the browser build), so +// clamp-to-border falls back to clamp-to-edge and the border colour is skipped. +#ifdef __EMSCRIPTEN__ +#define TOGL_CLAMP_TO_BORDER GL_CLAMP_TO_EDGE +#define TOGL_SET_BORDER_COLOR( call ) ((void)0) +#else +#define TOGL_CLAMP_TO_BORDER GL_CLAMP_TO_BORDER +#define TOGL_SET_BORDER_COLOR( call ) call +#endif + #pragma once #ifdef OSX @@ -298,7 +309,7 @@ struct GLMTexSamplingParams #ifndef OSX FORCEINLINE void SetToSamplerObject( GLuint nSamplerObject ) const { - static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, (GLenum)-1 }; + static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, TOGL_CLAMP_TO_BORDER, (GLenum)-1 }; static const GLenum dxtogl_magFilter[4] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_LINEAR }; static const GLenum dxtogl_minFilter[4][4] = // indexed by _D3DTEXTUREFILTERTYPE on both axes: [row is min filter][col is mip filter]. { @@ -323,7 +334,7 @@ struct GLMTexSamplingParams flBorderColor[2] = ((m_borderColor ) & 0xFF) * (1.0f/255.0f); //B flBorderColor[3] = ((m_borderColor >> 24) & 0xFF) * (1.0f/255.0f); //A } - gGL->glSamplerParameterfv( nSamplerObject, GL_TEXTURE_BORDER_COLOR, flBorderColor ); // <-- this crashes ATI's driver, remark it out + TOGL_SET_BORDER_COLOR( gGL->glSamplerParameterfv( nSamplerObject, GL_TEXTURE_BORDER_COLOR, flBorderColor ) ); gGL->glSamplerParameteri( nSamplerObject, GL_TEXTURE_MIN_LOD, m_packed.m_minLOD ); // gGL->glSamplerParameterfv( nSamplerObject, GL_TEXTURE_LOD_BIAS, &m_lodBias ); gGL->glSamplerParameteri( nSamplerObject, GL_TEXTURE_COMPARE_MODE_ARB, m_packed.m_compareMode ? GL_COMPARE_R_TO_TEXTURE_ARB : GL_NONE ); @@ -341,7 +352,7 @@ struct GLMTexSamplingParams inline void DeltaSetToTarget( GLenum target, const GLMTexSamplingParams &curState ) { - static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, (GLenum)-1 }; + static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, TOGL_CLAMP_TO_BORDER, (GLenum)-1 }; static const GLenum dxtogl_magFilter[4] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_LINEAR }; static const GLenum dxtogl_minFilter[4][4] = // indexed by _D3DTEXTUREFILTERTYPE on both axes: [row is min filter][col is mip filter]. { @@ -387,7 +398,7 @@ struct GLMTexSamplingParams flBorderColor[3] = ((m_borderColor >> 24) & 0xFF) * (1.0f/255.0f); //A } - gGL->glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, flBorderColor ); // <-- this crashes ATI's driver, remark it out + TOGL_SET_BORDER_COLOR( gGL->glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, flBorderColor ) ); } if ( m_packed.m_minLOD != curState.m_packed.m_minLOD ) @@ -418,7 +429,7 @@ struct GLMTexSamplingParams inline void SetToTarget( GLenum target ) { - static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_BORDER, (GLenum)-1 }; + static const GLenum dxtogl_addressMode[] = { GL_REPEAT, GL_CLAMP_TO_EDGE, TOGL_CLAMP_TO_BORDER, (GLenum)-1 }; static const GLenum dxtogl_magFilter[4] = { GL_NEAREST, GL_NEAREST, GL_LINEAR, GL_LINEAR }; static const GLenum dxtogl_minFilter[4][4] = // indexed by _D3DTEXTUREFILTERTYPE on both axes: [row is min filter][col is mip filter]. { @@ -443,7 +454,7 @@ struct GLMTexSamplingParams flBorderColor[2] = ((m_borderColor ) & 0xFF) * (1.0f/255.0f); //B flBorderColor[3] = ((m_borderColor >> 24) & 0xFF) * (1.0f/255.0f); //A } - gGL->glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, flBorderColor ); // <-- this crashes ATI's driver, remark it out + TOGL_SET_BORDER_COLOR( gGL->glTexParameterfv( target, GL_TEXTURE_BORDER_COLOR, flBorderColor ) ); gGL->glTexParameteri( target, GL_TEXTURE_MIN_LOD, m_packed.m_minLOD ); // gGL->glTexParameterfv( target, GL_TEXTURE_LOD_BIAS, &m_lodBias ); gGL->glTexParameteri( target, GL_TEXTURE_COMPARE_MODE_ARB, m_packed.m_compareMode ? GL_COMPARE_R_TO_TEXTURE_ARB : GL_NONE ); diff --git a/public/togles/linuxwin/glmgr.h b/public/togles/linuxwin/glmgr.h index 34d754436b..7fc7d46f7e 100644 --- a/public/togles/linuxwin/glmgr.h +++ b/public/togles/linuxwin/glmgr.h @@ -736,7 +736,11 @@ FORCEINLINE void GLContextSet( GLBlendEnableSRGB_t *src ) // GLint encoding = 0; // gGL->glGetFramebufferAttachmentParameteriv( GL_DRAW_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING, &encoding ); +#ifndef __EMSCRIPTEN__ + // WebGL has no GL_FRAMEBUFFER_SRGB switch (INVALID_ENUM every frame); the + // browser build does the sRGB write in the pixel shader instead. glSetEnable( GL_FRAMEBUFFER_SRGB_EXT, src->enable != 0 ); +#endif } FORCEINLINE void GLContextGet( GLBlendEnableSRGB_t *dst ) diff --git a/togles/linuxwin/cglmtex.cpp b/togles/linuxwin/cglmtex.cpp index 5f98bdadc8..ca0f20b8dc 100644 --- a/togles/linuxwin/cglmtex.cpp +++ b/togles/linuxwin/cglmtex.cpp @@ -3347,6 +3347,11 @@ void convert_texture( GLenum &internalformat, GLsizei width, GLsizei height, GLe if( internalformat == GL_SRGB8 && format == GL_RGBA ) internalformat = GL_SRGB8_ALPHA8; + // A 3-channel internal format with 4-channel data is invalid in GLES 3 / + // WebGL 2 (the texture gets no image at all), so promote it. + if( internalformat == GL_RGB8 && format == GL_RGBA ) + internalformat = GL_RGBA8; + if( format == GL_LUMINANCE || format == GL_LUMINANCE_ALPHA ) internalformat = format; diff --git a/togles/linuxwin/dxabstract.cpp b/togles/linuxwin/dxabstract.cpp index c73dc55dea..cd49cf7f9d 100644 --- a/togles/linuxwin/dxabstract.cpp +++ b/togles/linuxwin/dxabstract.cpp @@ -1407,8 +1407,19 @@ HRESULT IDirect3D9::CheckDeviceFormat(UINT Adapter,D3DDEVTYPE DeviceType,D3DFORM legalUsage |= D3DUSAGE_QUERY_SRGBREAD; break; - case D3DFMT_X8R8G8B8: legalUsage = D3DUSAGE_DYNAMIC | D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_QUERY_FILTER; + case D3DFMT_X8R8G8B8: +#ifdef __EMSCRIPTEN__ + // X8R8G8B8 is 4-byte BGRX data in a 3-channel GL_RGB8 texture; + // WebGL rejects that pairing (INVALID_OPERATION), so every such + // texture -- normal maps, the engine's 1x1 white/grey/black + // fallbacks -- had no image and sampled black. Report it + // unsupported so the material system converts those images to + // R8G8B8 (plain RGB, which WebGL accepts) when it loads them. + legalUsage = 0; +#else + legalUsage = D3DUSAGE_DYNAMIC | D3DUSAGE_AUTOGENMIPMAP | D3DUSAGE_QUERY_FILTER; legalUsage |= D3DUSAGE_QUERY_SRGBREAD | D3DUSAGE_QUERY_SRGBWRITE; +#endif break; // one and two channel textures... we'll have to fake these as four channel tex if we want to support them From a1c21181e30db9bfb82607664aac0998c74781e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 14 Oct 2026 19:27:23 +0000 Subject: [PATCH 3/3] togles: depth buffer matching the colour target on web; GL profile windows The probe showed clears and draws failing with framebuffer status 0x8CD9 (FRAMEBUFFER_INCOMPLETE_DIMENSIONS): WebGL 2 still requires every attachment of a framebuffer to have the same size, while Source renders into smaller targets (1024x512, 292x135, ...) with the full-screen 1168x540 depth buffer bound, as D3D9 allows. Everything drawn into those framebuffers was lost. On web such a framebuffer now gets a private depth buffer of the colour target's size (created once per size); those passes only touch the top-left of the big depth buffer and clear depth anyway. The menu also ran at 6-12 s per frame in the last run. Add profile windows (frames 11-13, 60-63, 240-243, or up to a slow frame) that count WebGL calls by name and time spent inside them versus the whole frame, so the next diagnostics show whether the time goes to WebGL or to the engine. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Qy5DKdwTqGQqScWvJyNcft --- emscripten/pre.js | 39 +++++++++++++++++++++++++ togles/linuxwin/dxabstract.cpp | 52 ++++++++++++++++++++++++++++++++++ 2 files changed, 91 insertions(+) diff --git a/emscripten/pre.js b/emscripten/pre.js index 3c42922e8c..4c6ae1f09d 100644 --- a/emscripten/pre.js +++ b/emscripten/pre.js @@ -1012,6 +1012,40 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { huntOriginals.clear() hunting = false } + // Profile windows: count WebGL calls by name and time spent inside them, + // to tell a GPU/driver-bound frame from one where the engine's own code + // (or a blocking read) eats the time. + const profOriginals = new Map() + let profCounts = null, profGlMs = 0, profStart = 0 + const startProfile = () => { + profCounts = new Map(); profGlMs = 0; profStart = performance.now() + for(const name of Object.getOwnPropertyNames(P)) { + if(name === 'constructor') continue + const desc = Object.getOwnPropertyDescriptor(P, name) + if(!desc || typeof desc.value !== 'function') continue + const original = desc.value + profOriginals.set(name, original) + P[name] = function(...args) { + const t0 = performance.now() + const result = original.apply(this, args) + const dt = performance.now() - t0 + profGlMs += dt + const c = profCounts.get(name) + if(c) { c.n++; c.ms += dt } else profCounts.set(name, { n: 1, ms: dt }) + return result + } + } + } + const stopProfile = (label) => { + for(const [name, original] of profOriginals) P[name] = original + profOriginals.clear() + const wall = performance.now() - profStart + const top = [...profCounts.entries()].sort((a, b) => b[1].ms - a[1].ms).slice(0, 8) + .map(([k, v]) => `${k} x${v.n} ${v.ms.toFixed(0)}ms`).join(', ') + render360Log(`[Render360 GL] profile ${label}: ${(wall / 1000).toFixed(1)} s wall, ${(profGlMs / 1000).toFixed(1)} s inside WebGL; top: ${top}`) + profCounts = null + } + const PROFILE_WINDOWS = [[11, 13], [60, 63], [240, 243]] const HUNT_WINDOWS = [[6, 8], [200, 203], [450, 453]] // Heartbeat: a line every ~10 s while frames are being presented, so a @@ -1022,6 +1056,10 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { if(S.drawFb) return // A blit to the canvas is ToGL presenting a frame. frames++ + for(const [start, end] of PROFILE_WINDOWS) { + if(frames === start && !profCounts && !hunting) startProfile() + if(frames === end && profCounts) stopProfile(`frames ${start}-${end}`) + } for(const [start, end] of HUNT_WINDOWS) { if(frames === start && !hunting) { try { getError.call(this) } catch(_) {} startHunt() } if(frames === end && hunting) { @@ -1039,6 +1077,7 @@ if(!render360IsWindow && typeof WebGL2RenderingContext !== 'undefined') (() => { if(frameMs > 1500 && slowFrames < 15) { slowFrames++ render360Log(`[Render360 GL] slow frame ${frames}: ${(frameMs / 1000).toFixed(1)} s, ${frame.draws} draws, ${frame.uploads} uploads, ${frame.readbacks} buffer read-backs (${Math.round(frame.readbackBytes / 1024)} KiB)`) + if(profCounts) stopProfile(`through slow frame ${frames}`) } if(!lastBeat) { lastBeat = now; beatFrames = frames } else if(now - lastBeat > 10000 && beats < 60) { diff --git a/togles/linuxwin/dxabstract.cpp b/togles/linuxwin/dxabstract.cpp index cd49cf7f9d..0fde459b02 100644 --- a/togles/linuxwin/dxabstract.cpp +++ b/togles/linuxwin/dxabstract.cpp @@ -3184,6 +3184,36 @@ HRESULT IDirect3DDevice9::CreateRenderTarget(UINT Width,UINT Height,D3DFORMAT Fo return result; } +#ifdef __EMSCRIPTEN__ +// WebGL 2 keeps WebGL 1's rule that every attachment of a framebuffer has the +// same size (FRAMEBUFFER_INCOMPLETE_DIMENSIONS, 0x8CD9), which desktop GL 3 and +// D3D9 dropped. Source renders into smaller targets (bloom, reflections, +// portal views) with the full-screen depth buffer still bound; every clear and +// draw into those framebuffers failed. Such a pass only ever touches the +// top-left of the big depth buffer and clears depth itself, so give it a +// private depth buffer of the colour target's size instead (one per size). +static CGLMTex *WebMatchingDepthTex( IDirect3DDevice9 *pDevice, IDirect3DSurface9 *pDepth, uint nWidth, uint nHeight ) +{ + struct WebDepthEntry_t { uint m_nWidth, m_nHeight; D3DFORMAT m_format; IDirect3DSurface9 *m_pSurface; }; + static CUtlVector< WebDepthEntry_t > s_entries; + + for ( int i = 0; i < s_entries.Count(); i++ ) + { + const WebDepthEntry_t &entry = s_entries[i]; + if ( entry.m_nWidth == nWidth && entry.m_nHeight == nHeight && entry.m_format == pDepth->m_desc.Format ) + return entry.m_pSurface->m_tex; + } + + IDirect3DSurface9 *pSurface = NULL; + if ( pDevice->CreateDepthStencilSurface( nWidth, nHeight, pDepth->m_desc.Format, D3DMULTISAMPLE_NONE, 0, FALSE, &pSurface, NULL ) != S_OK || !pSurface ) + return NULL; + + WebDepthEntry_t entry = { nWidth, nHeight, pDepth->m_desc.Format, pSurface }; + s_entries.AddToTail( entry ); + return pSurface->m_tex; +} +#endif + void IDirect3DDevice9::UpdateBoundFBO() { RenderTargetState_t renderTargetState; @@ -3232,6 +3262,28 @@ void IDirect3DDevice9::UpdateBoundFBO() depthParams.m_tex = m_pDepthStencil->m_tex; +#ifdef __EMSCRIPTEN__ + for ( uint i = 0; i < 4; i++ ) + { + if ( !m_pRenderTargets[i] ) + continue; + + const GLMTexLayoutKey &colorKey = m_pRenderTargets[i]->m_tex->m_layout->m_key; + const uint nMip = m_pRenderTargets[i]->m_mip; + const uint nWidth = MAX( 1u, (uint)colorKey.m_xSize >> nMip ); + const uint nHeight = MAX( 1u, (uint)colorKey.m_ySize >> nMip ); + const GLMTexLayoutKey &depthKey = depthParams.m_tex->m_layout->m_key; + + if ( ( nWidth != (uint)depthKey.m_xSize || nHeight != (uint)depthKey.m_ySize ) && !m_pDepthStencil->m_desc.MultiSampleType ) + { + CGLMTex *pMatching = WebMatchingDepthTex( this, m_pDepthStencil, nWidth, nHeight ); + if ( pMatching ) + depthParams.m_tex = pMatching; + } + break; + } +#endif + EGLMFBOAttachment destAttach = (depthParams.m_tex->m_layout->m_format->m_glDataFormat != 34041) ? kAttDepth : kAttDepthStencil; newFBO->TexAttach( &depthParams, destAttach );