在webgl2中篱笆同步的正确用法是什么?

时间:2019-02-02 15:53:53

标签: javascript webgl webgl2

寻找一些模式/代码示例/在webgl2(gl.fenceSync)中适当使用围栏的最佳实践-最好是不阻塞JS线程。

    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 个答案:

答案 0 :(得分:0)

我只是在说老实话,我实际上不确定WebGL2中的同步有多么有用,但我认为您不想阻止该模式,就像这样

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();