ShadowMesh.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /**
  2. * @author erichlof / http://github.com/erichlof
  3. *
  4. * A shadow Mesh that follows a shadow-casting Mesh in the scene, but is confined to a single plane.
  5. */
  6. import {
  7. Matrix4,
  8. Mesh,
  9. MeshBasicMaterial
  10. } from "../../../build/three.module.js";
  11. var ShadowMesh = function ( mesh ) {
  12. var shadowMaterial = new MeshBasicMaterial( {
  13. color: 0x000000,
  14. transparent: true,
  15. opacity: 0.6,
  16. depthWrite: false
  17. } );
  18. Mesh.call( this, mesh.geometry, shadowMaterial );
  19. this.meshMatrix = mesh.matrixWorld;
  20. this.frustumCulled = false;
  21. this.matrixAutoUpdate = false;
  22. };
  23. ShadowMesh.prototype = Object.create( Mesh.prototype );
  24. ShadowMesh.prototype.constructor = ShadowMesh;
  25. ShadowMesh.prototype.update = function () {
  26. var shadowMatrix = new Matrix4();
  27. return function ( plane, lightPosition4D ) {
  28. // based on https://www.opengl.org/archives/resources/features/StencilTalk/tsld021.htm
  29. var dot = plane.normal.x * lightPosition4D.x +
  30. plane.normal.y * lightPosition4D.y +
  31. plane.normal.z * lightPosition4D.z +
  32. - plane.constant * lightPosition4D.w;
  33. var sme = shadowMatrix.elements;
  34. sme[ 0 ] = dot - lightPosition4D.x * plane.normal.x;
  35. sme[ 4 ] = - lightPosition4D.x * plane.normal.y;
  36. sme[ 8 ] = - lightPosition4D.x * plane.normal.z;
  37. sme[ 12 ] = - lightPosition4D.x * - plane.constant;
  38. sme[ 1 ] = - lightPosition4D.y * plane.normal.x;
  39. sme[ 5 ] = dot - lightPosition4D.y * plane.normal.y;
  40. sme[ 9 ] = - lightPosition4D.y * plane.normal.z;
  41. sme[ 13 ] = - lightPosition4D.y * - plane.constant;
  42. sme[ 2 ] = - lightPosition4D.z * plane.normal.x;
  43. sme[ 6 ] = - lightPosition4D.z * plane.normal.y;
  44. sme[ 10 ] = dot - lightPosition4D.z * plane.normal.z;
  45. sme[ 14 ] = - lightPosition4D.z * - plane.constant;
  46. sme[ 3 ] = - lightPosition4D.w * plane.normal.x;
  47. sme[ 7 ] = - lightPosition4D.w * plane.normal.y;
  48. sme[ 11 ] = - lightPosition4D.w * plane.normal.z;
  49. sme[ 15 ] = dot - lightPosition4D.w * - plane.constant;
  50. this.matrix.multiplyMatrices( shadowMatrix, this.meshMatrix );
  51. };
  52. }();
  53. export { ShadowMesh };