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));

相关推荐
不伤欣2 小时前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar4 小时前
vulkan游戏引擎test文件memory实现
游戏引擎
Magnum Lehar4 小时前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
快乐觉主吖8 小时前
Unity的日志管理类
android·unity·游戏引擎
WarPigs16 小时前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C1 天前
【业务框架】3C-相机-Cinemachine
unity
一线灵1 天前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎
Clank的游戏栈1 天前
Unity基于GraphView的可视化关卡编辑器开发指南
unity·编辑器·游戏引擎
海尔辛2 天前
Unity UI 性能优化--Sprite 篇
ui·unity·性能优化
三巧2 天前
Godot 敌人生成半径和围墙不匹配,导致敌人错误的生成在围墙外的解决代码
游戏引擎·godot