Fresnel Shader or similar effect

Yes you can apply this to an existing material.

You’ll need to figure out where to inject the fragment shader code - it should happen before the lighting / fog calculations are applied.

You’ll find existing materials defined here and the corresponding shader chunks here

When THREE.js compiles the materials, it goes through the shader code and everytime it sees something that looks like #include <some_shader_chunk> it will replace that bit with the corresponding shader chunk.

If we take MeshPhongMaterial as an example, first we decide where we want the fresnel calculations to happen.
A good point would be after the material’s map and/or color have been applied - this means you can use the fresnel stuff as an effect on top the existing look of your material, and any lighting calculations would then happen on top of that.

A read through the material will show you this would happen here:

#include <map_fragment>
#include <color_fragment>

So you would inject the fragment shader code the following way:


material.onBeforeCompile = shader =>{
  shader.fragmentShader = shader.fragmentShader.replace(
    '#include <color_fragment>',
    'relevant code here'
  )
}

Don’t forget to repeat the same process for:

  • stuff above the main() function in the vertex shader
  • stuff inside the main() function in the vertex shader
  • stuff above the main() function in the fragment shader