Function to extend standard Materials

This is a little helper function to create a THREE.ShaderMaterial extending a standard material. The second parameter is optional.

How it is used:

const myMaterial = THREE.ShaderMaterial.extend(THREE.MeshPhongMaterial, {

    // Will be prepended to vertex and fragment code
    header: 'varying vec3 vEye;',

    
    // Insert code lines by hinting at a existing
    vertex: {
        // Inserts the line after #include <fog_vertex>
        '#include <fog_vertex>': 'vEye = normalize(cameraPosition - w.xyz);'
    },
    fragment: {
        '#include <envmap_fragment>': 'diffuseColor.rgb += pow(dot(vNormal, vEye), 3.0);'
    },
    
    
    // Properties to apply to the new THREE.ShaderMaterial
    material: {
        skinning: true
    },
    
    
    // Uniforms (will be applied to existing or added)
    uniforms: {
        diffuse: new THREE.Color(0xffffff)
    }
    
});

Code:

https://mevedia.com/share/ShaderMaterialExtend.js

3 Likes

I’ve updated the code to automatically set the constants (such as USE_MAP) when the corresponding maps are set as uniform.

Also here is an example extending the THREE.MeshPhongMaterial with a fresnel effect:
https://codepen.io/Fyrestar/pen/RzVLYd

3 Likes