How to add shadows to custom shader material?

Depending on your shader, if it’s just a minor change/addition you could use onBeforeCompile on a built-in material. I also made a plugin to make extending material more easy and clean, also to replicate code to the depth/distance material required for shadows when doing vertex transformations.

Specifically this line from the example

// testMaterial is your ShaderMaterial you extended from a built-in
testMaterial.customDepthMaterial = THREE.extendMaterial( THREE.MeshDepthMaterial, {

	template: testMaterial

} );

You could also extend a minimal built-in material that suits your usecase and just remove the includes you don’t need, for instance:

fragment: {

	'@#include <alphamap_pars_fragment>': '',
	'@#include <alphamap_fragment>': '',
	'@#include <clearcoat_normal_fragment_begin>': '',
	'@#include <clearcoat_normal_fragment_maps>': '',
	'@#include <clearcoat_normalmap_pars_fragment>': '',
	'@#include <clipping_planes_fragment>': '',
	'@#include <clipping_planes_pars_fragment>': ''
	// etc..
}

But if you don’t need any other built-in feature you should just use the custom shader code, the relevant inlcudes for shadows aren’t too many.

3 Likes