Marjan
Marjan

Reputation: 1418

Custom shader not affected by fog in Three.js

I have a sphere to which I add glow through a custom shader.

I have fog on my scene, which affects the sphere, but not the glow (when I zoom out the sphere disappears, but the glow stays).

How do I make the fog affect the glow?

Here's a codepen with the whole scene:

http://codepen.io/marjan-georgiev/pen/WrmPLY?editors=0010

Here is my glow material code

glowMaterial(){
  return new THREE.ShaderMaterial({
    side: THREE.BackSide,
    blending: THREE.AdditiveBlending,
    transparent: true,
    fog: true,

    uniforms: THREE.UniformsUtils.merge([
      THREE.UniformsLib[ "fog" ],
      {
        "c":   { type: "f", value: 0 },
        "p":   { type: "f", value: 4.5 },
        glowColor: { type: "c", value: Node.defaults.glowColor },
        viewVector: { type: "v3", value: {x: 0, y: 0, z: 400} },
        fog: true
      },
    ]),

    fragmentShader: `
      uniform vec3 glowColor;
      varying float intensity;
      ${THREE.ShaderChunk[ "common" ]}
      ${THREE.ShaderChunk[ "fog_pars_fragment" ]}
      void main()
      {
        vec3 outgoingLight = vec3( 0.0 );
        vec3 glow = glowColor * intensity;
        ${THREE.ShaderChunk[ "fog_fragment" ]}
        gl_FragColor = vec4(glow, 1.0 );
      }
    `,

    vertexShader: `
      uniform vec3 viewVector;
      uniform float c;
      uniform float p;
      varying float intensity;
      void main()
      {
        vec3 vNormal = normalize( normalMatrix * normal );
        vec3 vNormel = normalize( normalMatrix * viewVector );
        intensity = pow( c - dot(vNormal, vNormel), p );

        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
      }
    `
  });
}

Upvotes: 1

Views: 1959

Answers (1)

2pha
2pha

Reputation: 10155

Take a look at the fog fragment for r70 (which you are using) HERE and you will see that it is applying fog to gl_FragColor.
Moving the fog_fragment to after you set gl_FragColor should make fog have an affect on your shader.

fragmentShader: '
  uniform vec3 glowColor;
  varying float intensity;
  ${THREE.ShaderChunk[ "common" ]}
  ${THREE.ShaderChunk[ "fog_pars_fragment" ]}
  void main()
  {
    vec3 outgoingLight = vec3( 0.0 );
    vec3 glow = glowColor * intensity;
    gl_FragColor = vec4(glow, 1.0 );
    ${THREE.ShaderChunk[ "fog_fragment" ]}
  }
',

Upvotes: 3

Related Questions