Threejs 渲染阴影流程

效果展示

首先我们通过创建场景,为场景添加1个平行光,1个平面,1 个球体;并渲染带阴影的场景。

ini 复制代码
const settings = {
  cameraX: 6,
  cameraY: 12,
  posX: -3.5,
  posY: 7.5,
  posZ: 5.0,
  targetX: 3.5,
  targetY: 0,
  targetZ: 3.5,
  projWidth: 10,
  projHeight: 10,
  perspective: false,
  fieldOfView: 120,
  bias: -0.006
};

export function DirectionLightShadowInThree(canvas: HTMLCanvasElement) {

  const { width, height } = canvas.getBoundingClientRect();

  const aspect = width / height;

  const scene = new Scene();

  const renderer = new WebGL1Renderer({
    canvas
  });
  renderer.shadowMap.enabled = true;
  renderer.outputColorSpace = LinearSRGBColorSpace;
  // renderer.shadowMap.type = PCFSoftShadowMap;
  // renderer.outputEncoding = THREE.sRGBEncoding;
  // 这个开启才会渲染阴影贴图
    // 创建一个数字纹理
    const data = new Uint8Array([  // data
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
      0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC,
      0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF, 0xCC, 0xFF,
    ]);
    
    // const dataTexture = new DataTexture(data, 8, 8, LuminanceFormat, UnsignedByteType)
  
    // dataTexture.needsUpdate = true;
    // create a buffer with color data
  
  const _width = 8;
  const _height = 8;
  
  const camera = new PerspectiveCamera(60, aspect, 1, 2000);
  camera.position.set(
    settings.cameraX,
    settings.cameraY,
    15
  );
  camera.lookAt(new Vector3())
  // // used the buffer to create a DataTexture
  
  const texture = new DataTexture( data, _width, _height, LuminanceFormat, UnsignedByteType);
  // texture.mipmaps = [texture]
  texture.needsUpdate = true;


  const dirLight = new DirectionalLight();
  dirLight.castShadow = true;
  dirLight.target.position.set( 0, 0, 0 );

  // const lighthelper = new DirectionalLightHelper(dirLight);
  const planeMat = new MeshPhongMaterial({
    map: texture,
    color: new Color(0.5, 0.5, 1)
  });
  const sphereMat = new MeshPhongMaterial({
    map: texture,
    color: new Color(1, 0.5, 0.5)
  });

  const sphereGeometry = new SphereGeometry(1, 32, 24);
  
  const planeGeo = new PlaneGeometry(20, 20);

  dirLight.position.set(settings.posX, settings.posY, settings.posZ);

  dirLight.lookAt(new Vector3())

  const plane = new Mesh(planeGeo, planeMat);

  plane.receiveShadow = true;
  
  plane.rotation.x = - 0.5 * Math.PI;
  
  const sphere = new Mesh(sphereGeometry, sphereMat);

  sphere.castShadow = true;
  sphere.position.set(2, 3, 4);
  // sphere.updateMatrixWorld();
  scene.add(plane)

  scene.add(dirLight)
  scene.add(sphere)

  renderer.render(scene, camera);



}

threejs 渲染阴影的前置条件是

  1. 开启渲染器的阴影贴图 就是 renderer.shadowMap.enabled = true;
  2. 对需要投身阴影的模型设置 castShadow 属性为 true
  3. 对需要能产生阴影的光设置 castShadow 属性为 true
  4. 需要接收阴影的模型设置 receiveShadow 属性为 true

最终效果如下图所示

Threejs 是如何产生模型阴影的

  1. 根据灯光信息,渲染阴影贴图

1.1 首先记录能产生阴影的灯光

csharp 复制代码
// projectObject 函数内会有这样一段,处理灯光

if ( object.isLight ) {

        currentRenderState.pushLight( object );

        if ( object.castShadow ) {

                currentRenderState.pushShadow( object );

        }

}

1.2 根据灯光 执行WebGLShadowMap 的render 渲染阴影贴图 // 渲染灯光下的深度信息 // 渲染了尝试贴图后 shadowMap.render( shadowsArray, scene, camera );

以示例代码说明,此处用的是平行光。会在DirectilnalLightShadow 中保存渲染后的阴影深度信息(就是通过 WebGLRenderTarget 记录纹理,结合 MeshDepthMaterial)。

1.3 将贴图信息写入着色器中,供后面生成程序时用

在 setupLights 方法中会将相应光的贴图信息写入WebGLUniforms 中,后面传入着色器内。

ini 复制代码
if ( light.isDirectionalLight ) {
// 平行光
const uniforms = cache.get( light );

uniforms.color.copy( light.color ).multiplyScalar( light.intensity * scaleFactor );

if ( light.castShadow ) {

        const shadow = light.shadow;

        const shadowUniforms = shadowCache.get( light );

        shadowUniforms.shadowBias = shadow.bias;
        shadowUniforms.shadowNormalBias = shadow.normalBias;
        shadowUniforms.shadowRadius = shadow.radius;
        shadowUniforms.shadowMapSize = shadow.mapSize;

        state.directionalShadow[ directionalLength ] = shadowUniforms;
        state.directionalShadowMap[ directionalLength ] = shadowMap;
        state.directionalShadowMatrix[ directionalLength ] = light.shadow.matrix;

        numDirectionalShadows ++;

}

state.directional[ directionalLength ] = uniforms;

directionalLength ++;

}

src/renderers/shaders/shaderChunk/shadowmap_pars_vertext.glsl

定义

ini 复制代码
    // 灯光的模型矩阵
    uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ];
    varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];

src/renderers/shaders/shaderChunk/shadowmap_vertext.glsl 计算阴影纹理坐标

ini 复制代码
#if NUM_DIR_LIGHT_SHADOWS > 0

#pragma unroll_loop_start
for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) {
   // worldPosition 模型的 position
   shadowWorldPosition = worldPosition + 
   vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 );
   
   vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition;

}
       

src/renderers/shaders/shaderChunk/shadowmap_pars_fragment.glsl 定义变量

ini 复制代码
   
    // 获取深度贴图
    uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ];
    // 贴图纹理坐标
    varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ];
    

src/renderers/shaders/shaderChunk/lights_fragment_begin.glsl 中调用 getShadow 获取阴影信息

ini 复制代码
#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct )

 DirectionalLight directionalLight;
 #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0
 DirectionalLightShadow directionalLightShadow;
 #endif

 #pragma unroll_loop_start
 for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) {

 	directionalLight = directionalLights[ i ];

 	getDirectionalLightInfo( directionalLight, geometry, directLight );

 	#if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS )
 	directionalLightShadow = directionalLightShadows[ i ];
 	directLight.color *= all( bvec2( directLight.visible, receiveShadow ) ) 
 		? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) 
 		: 1.0;
 	#endif

 	RE_Direct( directLight, geometry, material, reflectedLight );

 }
相关推荐
YeeWang31 分钟前
🎉 Eficy 让你的 Cherry Studio 直接生成可预览的 React 页面
前端·javascript
gnip32 分钟前
Jenkins部署前端项目实战方案
前端·javascript·架构
Orange3015111 小时前
《深入源码理解webpack构建流程》
前端·javascript·webpack·typescript·node.js·es6
lovepenny1 小时前
Failed to resolve entry for package "js-demo-tools". The package may have ......
前端·npm
超凌1 小时前
threejs 创建了10w条THREE.Line,销毁数据,等待了10秒
前端
车厘小团子2 小时前
🎨 前端多主题最佳实践:用 Less Map + generate-css 打造自动化主题系统
前端·架构·less
芒果1252 小时前
SVG图片通过img引入修改颜色
前端
海云前端12 小时前
前端面试ai对话聊天通信怎么实现?面试实际经验
前端
一枚前端小能手2 小时前
🔧 半夜被Bug叫醒的痛苦,错误监控帮你早发现
前端
Juchecar2 小时前
Vue 3 单页应用Router路由跳转示例
前端