What is a proper usage of fence synchronization in webgl2?

情到浓时终转凉″ 提交于 2021-01-29 09:20:00

问题


Looking for some patterns/code examples/best practices of appropriate usage of fences in webgl2 (gl.fenceSync) - best if it would be non blocking of JS thread.

    var fence = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);

    setTimeout(() => {
      gl.clientWaitSync(fence, gl.SYNC_FLUSH_COMMANDS_BIT, 1000000);
      gl.getBufferSubData(gl.TRANSFORM_FEEDBACK_BUFFER, 0, dataOut);
    }, 0);

回答1:


I'm just guessing to be honest, I'm not actually sure how useful syncs are in WebGL2 but I'd think you don't want to block then the pattern would be like this

function main() {
  const gl = document.createElement('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  
  callbackOnSync(gl, () => {
    console.log("done");
  });
  
  function callbackOnSync(gl, callback) {
    const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
    gl.flush();  // make sure the sync command is read

    setTimeout(checkSync);  

    function checkSync() {
      const timeout = 0;   // 0 = just check the status
      const bitflags = 0;
      const status = gl.clientWaitSync(sync, bitflags, timeout);
      switch (status) {
        case gl.TIMEOUT_EXPIRED:
          // it's not done, check again next time
          return setTimeout(checkSync);
        case gl.WAIT_FAILED:
          throw new Error('should never get here');
        default:
          // it's done!
          gl.deleteSync(sync);

          callback();
      }
    }
  }
}

main();


来源:https://stackoverflow.com/questions/54494712/what-is-a-proper-usage-of-fence-synchronization-in-webgl2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!