GPUStatsPanel.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. this.activeQueries --;
  36. } else if ( gl.isContextLost() === false ) {
  37. // otherwise try again the next frame
  38. requestAnimationFrame( checkQuery );
  39. }
  40. };
  41. requestAnimationFrame( checkQuery );
  42. };
  43. this.endQuery = function () {
  44. // finish the query measurement
  45. const ext = this.extension;
  46. const gl = this.context;
  47. if ( ext === null ) {
  48. return;
  49. }
  50. gl.endQuery( ext.TIME_ELAPSED_EXT );
  51. };
  52. }
  53. }