Avoid Recompiling shaders

So I’m trying to build an app, which requires me to switch between different shaders. Basically there are three different shaders, but textures are random. At the moment, I’m creating a new material each time, which I think webGL will have to recompile the shader program every time. So I’m wondering if there’s a way I can save pre-compiled shaders, and each time just load them and switch to a specific texture.

I tried to use the code below, but after I switch the loaded shader is not working. I got a black screen instead of an error.

initMaterialSingleExperiment(initTexture) {
        const THREE = this.props.THREE;

        if (!this.exitingShaderMaterials['fSingle']){
          let texture = initTexture;
          if (!initTexture) {
              texture = this.defaultTexture;
          }

          const uniforms = {
              texture: {type: 't', value: texture},
          };

          this.exitingShaderMaterials['fSingle'] = new THREE.ShaderMaterial({
              uniforms: uniforms,
              vertexShader: Shaders['vPano'].src,
              fragmentShader: Shaders['fSingle'].src
          });
          this.exitingShaderMaterials['fSingle'].side = THREE.DoubleSide;
       }
       const shaderMaterial = this.exitingShaderMaterials['fSingle'];

        console.log('Single shader loaded....');
        return shaderMaterial;
    }

Author: Fantashit

1 thought on “Avoid Recompiling shaders

  1. At the moment, I’m creating a new material each time, which I think webGL will have to recompile the shader program every time.

    Not necessarily. We reuse programs internally.

    You can check renderer.info to see the amount of programs that have been created.

Comments are closed.