ShadowMesh.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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.meshMatrix = mesh.matrixWorld;
  16. this.frustumCulled = false;
  17. this.matrixAutoUpdate = false;
  18. }
  19. update( plane, lightPosition4D ) {
  20. // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm
  21. const dot = plane.normal.x * lightPosition4D.x + plane.normal.y * lightPosition4D.y + plane.normal.z * lightPosition4D.z + - plane.constant * lightPosition4D.w;
  22. const sme = _shadowMatrix.elements;
  23. sme[ 0 ] = dot - lightPosition4D.x * plane.normal.x;
  24. sme[ 4 ] = - lightPosition4D.x * plane.normal.y;
  25. sme[ 8 ] = - lightPosition4D.x * plane.normal.z;
  26. sme[ 12 ] = - lightPosition4D.x * - plane.constant;
  27. sme[ 1 ] = - lightPosition4D.y * plane.normal.x;
  28. sme[ 5 ] = dot - lightPosition4D.y * plane.normal.y;
  29. sme[ 9 ] = - lightPosition4D.y * plane.normal.z;
  30. sme[ 13 ] = - lightPosition4D.y * - plane.constant;
  31. sme[ 2 ] = - lightPosition4D.z * plane.normal.x;
  32. sme[ 6 ] = - lightPosition4D.z * plane.normal.y;
  33. sme[ 10 ] = dot - lightPosition4D.z * plane.normal.z;
  34. sme[ 14 ] = - lightPosition4D.z * - plane.constant;
  35. sme[ 3 ] = - lightPosition4D.w * plane.normal.x;
  36. sme[ 7 ] = - lightPosition4D.w * plane.normal.y;
  37. sme[ 11 ] = - lightPosition4D.w * plane.normal.z;
  38. sme[ 15 ] = dot - lightPosition4D.w * - plane.constant;
  39. this.matrix.multiplyMatrices( _shadowMatrix, this.meshMatrix );
  40. }
  41. }
  42. ShadowMesh.prototype.isShadowMesh = true;
  43. THREE.ShadowMesh = ShadowMesh;
  44. } )();