2
0

GPUStatsPanel.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import Stats from '../libs/stats.module.js';
  2. // https://www.khronos.org/registry/webgl/extensions/EXT_disjoint_timer_query_webgl2/
  3. export class GPUStatsPanel extends Stats.Panel {
  4. constructor( context, name = 'GPU MS' ) {
  5. super( name, '#f90', '#210' );
  6. const extension = context.getExtension( 'EXT_disjoint_timer_query_webgl2' );
  7. if ( extension === null ) {
  8. console.warn( 'GPUStatsPanel: disjoint_time_query extension not available.' );
  9. }
  10. this.context = context;
  11. this.extension = extension;
  12. this.maxTime = 30;
  13. this.activeQueries = 0;
  14. this.startQuery = function () {
  15. const gl = this.context;
  16. const ext = this.extension;
  17. if ( ext === null ) {
  18. return;
  19. }
  20. // create the query object
  21. const query = gl.createQuery();
  22. gl.beginQuery( ext.TIME_ELAPSED_EXT, query );
  23. this.activeQueries ++;
  24. const checkQuery = () => {
  25. // check if the query is available and valid
  26. const available = gl.getQueryParameter( query, gl.QUERY_RESULT_AVAILABLE );
  27. const disjoint = gl.getParameter( ext.GPU_DISJOINT_EXT );
  28. const ns = gl.getQueryParameter( query, gl.QUERY_RESULT );
  29. const ms = ns * 1e-6;
  30. if ( available ) {
  31. // update the display if it is valid
  32. if ( ! disjoint ) {
  33. this.update( ms, this.maxTime );
  34. }
  35. gl.deleteQuery( query );
  36. this.activeQueries --;
  37. } else if ( gl.isContextLost() === false ) {
  38. // otherwise try again the next frame
  39. requestAnimationFrame( checkQuery );
  40. }
  41. };
  42. requestAnimationFrame( checkQuery );
  43. };
  44. this.endQuery = function () {
  45. // finish the query measurement
  46. const ext = this.extension;
  47. const gl = this.context;
  48. if ( ext === null ) {
  49. return;
  50. }
  51. gl.endQuery( ext.TIME_ELAPSED_EXT );
  52. };
  53. }
  54. }