Skip to content

Instantly share code, notes, and snippets.

@w8r
Created January 25, 2024 12:35
Show Gist options
  • Save w8r/34ed717ffffc5453a5d3e17c40582c3c to your computer and use it in GitHub Desktop.
Save w8r/34ed717ffffc5453a5d3e17c40582c3c to your computer and use it in GitHub Desktop.
readPixelsAsync.ts
const clientWaitAsync = function (gl, sync, flags = 0, interval_ms = 10) {
return new Promise<void>(function (resolve, reject) {
const check = () => {
const res = gl.clientWaitSync(sync, flags, 0);
if (res === gl.WAIT_FAILED) {
reject();
return;
}
if (res === gl.TIMEOUT_EXPIRED) {
setTimeout(check, interval_ms);
return;
}
resolve();
};
check();
});
};
export const readPixelsAsync = (gl, width, height, buffer) => {
const bufpak = gl.createBuffer();
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, bufpak);
gl.bufferData(gl.PIXEL_PACK_BUFFER, buffer.byteLength, gl.STREAM_READ);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.FLOAT, 0);
const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
if (!sync) return null;
gl.flush();
return clientWaitAsync(gl, sync, 0, 10).then(() => {
gl.deleteSync(sync);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, bufpak);
gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, buffer);
gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
gl.deleteBuffer(bufpak);
return buffer;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment