ShadowMesh.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. ( function () {
  2. /**
  3. * A shadow THREE.Mesh that follows a shadow-casting THREE.Mesh in the scene, but is confined to a single plane.
  4. */
  5. const _shadowMatrix = new THREE.Matrix4();
  6. class ShadowMesh extends THREE.Mesh {
  7. constructor( mesh ) {
  8. const shadowMaterial = new THREE.MeshBasicMaterial( {
  9. color: 0x000000,
  10. transparent: true,
  11. opacity: 0.6,
  12. depthWrite: false
  13. } );
  14. super( mesh.geometry, shadowMaterial );
  15. this.isShadowMesh = true;
  16. this.meshMatrix = mesh.matrixWorld;
  17. this.frustumCulled = false;
  18. this.matrixAutoUpdate = false;
  19. }
  20. update( plane, lightPosition4D ) {
  21. // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm
  22. const dot = plane.normal.x * lightPosition4D.x + plane.normal.y * lightPosition4D.y + plane.normal.z * lightPosition4D.z + - plane.constant * lightPosition4D.w;
  23. const sme = _shadowMatrix.elements;
  24. sme[ 0 ] = dot - lightPosition4D.x * plane.normal.x;
  25. sme[ 4 ] = - lightPosition4D.x * plane.normal.y;
  26. sme[ 8 ] = - lightPosition4D.x * plane.normal.z;
  27. sme[ 12 ] = - lightPosition4D.x * - plane.constant;
  28. sme[ 1 ] = - lightPosition4D.y * plane.normal.x;
  29. sme[ 5 ] = dot - lightPosition4D.y * plane.normal.y;
  30. sme[ 9 ] = - lightPosition4D.y * plane.normal.z;
  31. sme[ 13 ] = - lightPosition4D.y * - plane.constant;
  32. sme[ 2 ] = - lightPosition4D.z * plane.normal.x;
  33. sme[ 6 ] = - lightPosition4D.z * plane.normal.y;
  34. sme[ 10 ] = dot - lightPosition4D.z * plane.normal.z;
  35. sme[ 14 ] = - lightPosition4D.z * - plane.constant;
  36. sme[ 3 ] = - lightPosition4D.w * plane.normal.x;
  37. sme[ 7 ] = - lightPosition4D.w * plane.normal.y;
  38. sme[ 11 ] = - lightPosition4D.w * plane.normal.z;
  39. sme[ 15 ] = dot - lightPosition4D.w * - plane.constant;
  40. this.matrix.multiplyMatrices( _shadowMatrix, this.meshMatrix );
  41. }
  42. }
  43. THREE.ShadowMesh = ShadowMesh;
  44. } )();