Unity中URP下计算额外灯的方向

文章目录


前言

在上一篇文章中,我们获取了URP下额外灯的数据。

在这篇文章中,我们用获取到的数据来计算额外灯的方向。


一、为什么额外灯的方向,不像主平行灯一样直接获取?

1、主平行灯

  • 对于模型的每一个顶点来说,无论顶点位置在哪?我们主平行灯的方向都是不会改变的
  • 我们使用的是,模型顶点指向主平行灯,他们的方向也是一致的

2、额外灯中,包含 点光源、聚光灯 和 平行灯

  • 点光源 和 聚光灯

对于这两种额外灯类型来说:

照射到模型每一个顶点上,额外灯的方向是不一致的,都需要单独计算

我们使用的是模型顶点指向 额外灯

  • 平行灯
    和主平行光实例图一样

二、获得模型顶点指向额外灯的单位向量

  • 在这里Unity没有使用normalise函数归一化,而是使用了原始的方法
  • 模型顶点指向额外光:
  • l i g h t V e c t o r = l i g h t P o s i t i o n W S − p o s i t i o n W S lightVector = lightPositionWS - positionWS lightVector=lightPositionWS−positionWS
  • 向量归一化:
  • l i g h t D i r e c t i o n = l i g h t V e c t o r ∣ l i g h t V e c t o r ∣ = l i g h t V e c t o r 1 l i g h t V e c t o r ⋅ l i g h t V e c t o r lightDirection = \frac{lightVector}{\lvert lightVector\rvert}=lightVector\frac{1}{\sqrt{lightVector·lightVector}} lightDirection=∣lightVector∣lightVector=lightVectorlightVector⋅lightVector 1

三、Unity中的实现

  • 计算得到顶点指向额外灯的方向
  • lightPositionWS.w:代表额外灯类型(平行光=0,点灯=1)

float3 lightVector = lightPositionWS.xyz - positionWS * lightPositionWS.w;

  • 防止 点积 出现零在分母的情况,对其取了一个最大值

float distanceSqr = max(dot(lightVector, lightVector), HALF_MIN);

  • 最后,带入公式: l i g h t D i r e c t i o n = l i g h t V e c t o r ∣ l i g h t V e c t o r ∣ lightDirection = \frac{lightVector}{\lvert lightVector\rvert} lightDirection=∣lightVector∣lightVector,得到额外灯方向单位向量

half3 lightDirection = half3(lightVector * rsqrt(distanceSqr));

相关推荐
Miss_SQ21 小时前
Webgl打包后删除StreamingAssets文件夹下多余资源
unity·c#·webgl
Monkey_Xuan1 天前
C#中的引用传递和值传递
unity·c#
CreasyChan1 天前
C# LINQ 深度解析:优缺点与性能陷阱
unity·c#·游戏开发
freshman1181 天前
Unity动画控制
unity
IMPYLH1 天前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
AI视觉网奇2 天前
虚幻引擎 metahuman
游戏引擎·虚幻
技术探讨者2 天前
Unity 框架:从核心构成到实践应用的全面解析
unity·游戏引擎
牛掰是怎么形成的2 天前
Unity Legacy动画与骨骼动画的本质区别
unity·游戏引擎
weixin_458360912 天前
Unity使用Cursor Editor
unity