Search code examples
three.jsglslwebglstatic-analysisglsles

Declare external global variables for glsl validator / webgl / three.js


I'm building a project with three.js and importing glsl files externally (with glsl-ify-loader) for use in a Three ShaderMaterial.

When using ShaderMaterial, Three prepends global variables like projectionMatrix, modelViewMatrix to my shader code pre-compilation when it concats the shader. So when I write my shader all i need is (as a simple example):

varying vec3 vNormal;

void main () {
  vNormal = normal;
  gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}

... or similar.

My problem is that I'm using the glsl validator on my shader files which subsequently thinks that the pre-declared three variables are undeclared.

In JS, with eslint you could put /* global aGlobalVariableHere */ to appease the lint gods.

Is there anyway of doing this with the glsl validator? I can't find any resources that suggest how I could go about it.


Solution

  • You could use THREE.RawShaderMaterial (see docs), instead of ShaderMaterial. They're identical, except Raw doesn't prepend any uniforms or attributes to your shader at all, you have to do it manually. Then your linter will no longer act surprised:

    Top of vertex shader:

    precision highp float;
    
    uniform mat4 modelMatrix;
    uniform mat4 viewMatrix;
    uniform mat4 projectionMatrix;
    uniform vec3 cameraPosition;
    // ...
    
    attribute vec3 position;
    attribute vec3 normal;
    attribute vec2 uv;
    // ...
    

    You can read this page to see what uniforms and attributes get automatically added so you can add them yourself if needed in your shader code.