Receive shadow doesn't work for all instances of InstancedMesh

Hi,

I’ve been struggling to get receiveShadow property to work for instanced mesh. I’m using a directional light and have added a customDepthMaterial based on ShaderMaterial but only castShadow works for the instances, whereas receiveShadow works only for the origin instance, i.e. whatever shadow is received by the origin instance, it is applied on all of the instances. I would like each instance to cast and receive shadows independently.

Screenshots:


Here all the instances are casting shadows individually.


When I add a mesh that casts a shadow on top of the origin instance (although invisible, I assume, the origin instance is placed at 0, 0, 0), all the instances receive the shadow that the origin instance receives.

How can I make each instance of the instanced mesh to receive shadows independently?

Link to the project + code: https://f56lrk.csb.app/

Edit:

I’ve also taken into account these findings of this post Shadow for instances:

  1. When using Directional Light, you do need a customDepthMaterial
  2. When using PointLight, you do need a customDistanceMaterial
  3. It does not matter if you modify a material using onBeforeCompile, or take the shaders from THREE.ShaderLib, modify them and feed them to ShaderMaterial.

The same post suggests a solution which serves as another example with the same issue but implemented with InstancedBufferGeometry, a point light and a customDistanceMaterial based on MeshDistanceMaterial:


Again, here all the instances are casting shadows individually.


When I add a mesh that casts a shadow on top of the origin instance (although invisible, I assume, the origin instance is placed at 0, 0, 0), all the instances receive the shadow that the origin instance receives.

Link to this project + code: https://biw9mf.csb.app/

My wild guess for a solution is that something has to be added to the fragment shader of the customDepthMaterial/customDistanceMaterial to make receiveShadow work the same way the vertex shader is edited and castShadow works. I thought that I have to use ShaderMaterial and add the lights: true parameter and the THREE.UniformsLib.lights uniform but it still doesn’t work.