Files
breeze/scripts/web-gpu-pixels.mjs
T
waozi 83764e68d7
Cloudflare Pages / Build and verify the site (push) Failing after 33m46s
Breeze build / Linux native (push) Successful in 51m32s
Integrate the maintained Breeze TSX package graph
2026-11-28 23:44:19 -03:00

48 lines
2.3 KiB
JavaScript

// Observe the retained presenter context. getContext during startup would
// initialize the surface with browser defaults before the renderer attaches.
export function getCanvasContext(canvas) {
if (typeof WebGL2RenderingContext === 'undefined') return null;
return globalThis.__ziranWeb?.perm.find(value =>
value instanceof WebGL2RenderingContext && value.canvas === canvas) || null;
}
export const canvasContextFinder = `(${getCanvasContext.toString()})`;
// Test-only snapshot of the actual WebGL2 presentation surface. Preserve the
// application's GL state and return the same top-down RGBA order as ImageData.
export function readCanvasPixels(canvas, x, y, width, height) {
const gl = getCanvasContext(canvas);
if (!gl || gl.isContextLost()) throw new Error('WebGL2 presentation is unavailable');
if (![x, y, width, height].every(Number.isInteger) || x < 0 || y < 0 ||
width <= 0 || height <= 0 || x + width > canvas.width || y + height > canvas.height) {
throw new Error('Invalid presentation snapshot bounds');
}
const framebuffer = gl.getParameter(gl.READ_FRAMEBUFFER_BINDING);
const buffer = gl.getParameter(gl.PIXEL_PACK_BUFFER_BINDING);
const pack = [gl.PACK_ALIGNMENT, gl.PACK_ROW_LENGTH, gl.PACK_SKIP_PIXELS, gl.PACK_SKIP_ROWS]
.map(name => [name, gl.getParameter(name)]);
const bottomUp = new Uint8Array(width * height * 4);
globalThis.__inbeGpuTestSnapshot = (globalThis.__inbeGpuTestSnapshot || 0) + 1;
try {
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, null);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
for (const [name] of pack) gl.pixelStorei(name, name === gl.PACK_ALIGNMENT ? 1 : 0);
gl.readPixels(x, canvas.height - y - height, width, height, gl.RGBA, gl.UNSIGNED_BYTE, bottomUp);
} finally {
for (const [name, value] of pack) gl.pixelStorei(name, value);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, buffer);
gl.bindFramebuffer(gl.READ_FRAMEBUFFER, framebuffer);
globalThis.__inbeGpuTestSnapshot--;
}
const pixels = new Uint8Array(bottomUp.length);
for (let row = 0; row < height; row++) {
pixels.set(bottomUp.subarray((height - row - 1) * width * 4, (height - row) * width * 4), row * width * 4);
}
return pixels;
}
export const canvasPixelReader = `((canvas, ...bounds) => {
const getCanvasContext = ${canvasContextFinder};
return (${readCanvasPixels.toString()})(canvas, ...bounds);
})`;