5.2 阴影相机设置
5.1 定了「用什么技术」,5.2 解决「从哪看阴影」。纹理阴影要先渲染一张光源视角的深度图,但「光源视角」对三类光源各不相同:方向光没有位置,用正交投影沿光方向回退;聚光看它的锥角;点光要覆盖全方向。OGRE 把这段逻辑抽象成 ShadowCameraSetup 接口,默认实现按光源类型摆相机,Focused 版在默认基础上再聚焦可见区域。
本章与站内既有内容的分工
5.1 的 ShadowTechnique 决定「要不要阴影纹理」,本节决定「纹理相机怎么放」。4.1 的 getDerivedDirection/getDerivedPosition 在这里被消费:方向光的挤出、聚光的 FOV、点光的位置全部来自 Light 的推导数据。5.3 的 ShadowTextureManager 只管纹理资源的复用,与相机摆放正交。
ShadowCameraSetup:可插拔的抽象
接口只有一个纯虚函数 getShadowCamera,参数把「主相机、光源、纹理相机」一起传进来,由实现决定纹理相机的投影与位置。类注释点明动机:默认均匀视锥的纹素利用率差,近处纹素大、容易走样,所以把相机摆放做成可替换策略:
// OgreMain/include/OgreShadowCameraSetup.h:ShadowCameraSetup(v14.6.3 源码摘录,已删减)
/** This class allows you to plug in new ways to define the camera setup when
rendering and projecting shadow textures.
The default projection used when rendering shadow textures is a uniform
frustum. This is pretty straight forward but doesn't make the best use of
the space in the shadow map since texels closer to the camera will be larger,
resulting in 'jaggies'. There are several ways to distribute the texels
in the shadow texture differently, and this class allows you to override
that.
@par
Ogre is provided with several alternative shadow camera setups, including
LiSPSM (LiSPSMShadowCameraSetup) and Plane Optimal (PlaneOptimalShadowCameraSetup).
...
*/
class _OgreExport ShadowCameraSetup : public ShadowDataAlloc
{
public:
/// Function to implement -- must set the shadow camera properties
virtual void getShadowCamera (const SceneManager *sm, const Camera *cam,
const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const = 0;
/// Need virtual destructor in case subclasses use it
virtual ~ShadowCameraSetup() {}
};
DefaultShadowCameraSetup 继承它实现「普通阴影贴图」,是 setShadowTechnique 开启纹理阴影后的默认选择:
// OgreMain/include/OgreShadowCameraSetup.h:DefaultShadowCameraSetup(v14.6.3 源码摘录,已删减)
/** Implements default shadow camera setup
This implements the default shadow camera setup algorithm. This is what might
be referred to as "normal" shadow mapping.
*/
class _OgreExport DefaultShadowCameraSetup : public ShadowCameraSetup
{
public:
...
static ShadowCameraSetupPtr create()
{
return std::make_shared<DefaultShadowCameraSetup>();
}
/// Default shadow camera setup
void getShadowCamera (const SceneManager *sm, const Camera *cam,
const Viewport *vp, const Light *light, Camera *texCam, size_t iteration) const override;
};
方向光:正交投影 + 挤出
方向光这段最复杂。先把相机复位(清掉自定义矩阵)、设远近裁剪;阴影距离未配置时用「近裁剪 × 300」兜底。然后设正交投影,窗口覆盖 2 × shadowDist;相机位置放在「沿光方向回退挤出距离」处,朝向用 lookRotation 从光方向构造,并按世界纹素大小取整位置以抑制抖动:
// OgreMain/src/OgreShadowCameraSetup.cpp:DefaultShadowCameraSetup::getShadowCamera(方向光)(v14.6.3 源码摘录,已删减)
// Directional lights
if (light->getType() == Light::LT_DIRECTIONAL)
{
// now we need the clip distance
if(auto farClip = texCam->getFarClipDistance())
shadowDist = farClip;
// Set ortho projection
texCam->setProjectionType(PT_ORTHOGRAPHIC);
// set ortho window so that texture covers far dist
texCam->setOrthoWindow(shadowDist * 2, shadowDist * 2);
// Calculate look at position
Vector3 target = cam->getDerivedPosition() +
(cam->getDerivedDirection() * shadowOffset);
// Calculate direction, which same as directional light direction
dir = - light->getDerivedDirection(); // backwards since point down -z
dir.normalise();
// Calculate position
// We want to be in the -ve direction of the light direction
// far enough to project for the dir light extrusion distance
pos = target + dir * sm->getShadowDirectionalLightExtrusionDistance();
...
Matrix3 rot = Math::lookRotation(dir, up);
...
//snap to nearest texel
lightSpacePos.x -= std::fmod(lightSpacePos.x, worldTexelSize);
lightSpacePos.y -= std::fmod(lightSpacePos.y, worldTexelSize);
...
texCam->getParentNode()->setPosition(pos);
texCam->getParentNode()->setOrientation(rot);
}
注意 dir = -light->getDerivedDirection():光源沿 -Z 照亮,纹理相机要沿光方向回看投影面,所以取反。up 默认 UNIT_Y,与 dir 重合时改用 UNIT_Z——这是所有分支都要做的防共线处理。
聚光:外角 ×1.2 的透视
聚光把纹理相机设成透视,FOV 略大于聚光外角以保证覆盖,再封顶 175°。相机位置与朝向由阴影渲染器预置,这里不覆盖:
// OgreMain/src/OgreShadowCameraSetup.cpp:getShadowCamera(聚光/面光)(v14.6.3 源码摘录,已删减)
// Spotlight
else if (light->getType() == Light::LT_SPOTLIGHT || light->getType() == Light::LT_RECTLIGHT)
{
// Set perspective projection
texCam->setProjectionType(PT_PERSPECTIVE);
// set FOV slightly larger than the spotlight range to ensure coverage
Radian fovy = light->getSpotlightOuterAngle()*1.2;
// limit angle
if (fovy.valueDegrees() > 175)
fovy = Degree(175);
texCam->setFOVy(fovy);
// keep position & orientation set by ShadowRenderer::prepareShadowTextures
}
1.2 倍是经验值:稍微超出外角,保证锥边上的接收者不因精度边缘而露影。
点光:120° 透视
点光需要全方向覆盖,但 OGRE 的默认相机只拍一个方向,所以用 120° 宽透视作为六个面(cubemap)中每一面的相机。位置取光源位置,朝向看向目标点:
// OgreMain/src/OgreShadowCameraSetup.cpp:getShadowCamera(点光)(v14.6.3 源码摘录,已删减)
// Point light
else
{
// Set perspective projection
texCam->setProjectionType(PT_PERSPECTIVE);
// Use 120 degree FOV for point light to ensure coverage more area
texCam->setFOVy(Degree(120));
// Calculate look at position
Vector3 target = cam->getDerivedPosition() +
(cam->getDerivedDirection() * shadowOffset);
// Calculate position, which same as point light position
pos = light->getDerivedPosition();
dir = (pos - target); // backwards since point down -z
dir.normalise();
...
texCam->getParentNode()->setOrientation(Math::lookRotation(dir, up));
// keep position set by ShadowRenderer::prepareShadowTextures
}
Focused:聚焦可见区域
FocusedShadowCameraSetup 继承默认实现:先跑默认相机,再取 getVisibleObjectsBoundsInfo 的包围盒(含相机位置);sceneBB 为空就直接返回默认矩阵——这是「没有东西可见就不折腾」的兜底。非空时计算体 B(相机视锥 ∩ 场景包围盒再与光源做凸包),最后覆盖两套自定义矩阵:
// OgreMain/src/OgreShadowCameraSetupFocused.cpp:FocusedShadowCameraSetup::getShadowCamera(v14.6.3 源码摘录,已删减)
// calculate standard shadow mapping matrix
DefaultShadowCameraSetup::getShadowCamera(sm, cam, vp, light, texCam, iteration);
mLightFrustumCamera = texCam;
// build scene bounding box
const VisibleObjectsBoundsInfo& visInfo = sm->getVisibleObjectsBoundsInfo(texCam);
AxisAlignedBox sceneBB = visInfo.aabb;
...
sceneBB.merge(cam->getDerivedPosition());
// in case the sceneBB is empty (e.g. nothing visible to the cam) simply
// return the standard shadow mapping matrix
if (sceneBB.isNull())
{
return;
}
...
// set the two custom matrices
texCam->setCustomViewMatrix(true, LView);
texCam->setCustomProjectionMatrix(true, LProj);
聚焦的代价是注释里说的「swimming」:投影矩阵随可见区域每帧重算,阴影在接收面上可能轻微漂移,但换来的是阴影贴图纹素利用率大幅提升——同一张纹理只装可见区域,而非整条光路。
源码定位
OgreMain/include/OgreShadowCameraSetup.h:ShadowCameraSetup抽象基类与DefaultShadowCameraSetupOgreMain/src/OgreShadowCameraSetup.cpp:DefaultShadowCameraSetup::getShadowCamera(三分支)OgreMain/include/OgreShadowCameraSetupFocused.h与src/OgreShadowCameraSetupFocused.cpp:FocusedShadowCameraSetup、calculateB、transformToUnitCubeOgreMain/include/OgreShadowCameraSetupLiSPSM.h:LiSPSMShadowCameraSetup(进阶算法,同样继承自ShadowCameraSetup)
上游引用固定到 OGRE v14.6.3 源码 。
可运行产物:C++ 最小验证
下面复现阴影相机设置:抽象接口、方向光的正交投影与挤出定位、聚光的 1.2 倍 FOV 与 175° 封顶、点光的 120° 透视与看向目标、Focused 的「sceneBB 空则回退默认」。它与 src/05-2-shadow-camera-setup.cpp 逐字节一致:
// file: src/05-2-shadow-camera-setup.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/05-2-shadow-camera-setup.cpp -o bin/05-2-shadow-camera-setup && ./bin/05-2-shadow-camera-setup
//
// 复现 OgreShadowCameraSetup.h / OgreShadowCameraSetup.cpp /
// OgreShadowCameraSetupFocused.cpp 的阴影相机设置:
// ShadowCameraSetup 抽象基类 + 纯虚 getShadowCamera;
// DefaultShadowCameraSetup:方向光 → 正交投影,位置 = 目标点 + 方向×挤出距离;
// 聚光 → 透视 fov = 外角×1.2(上限 175°);点光 → 透视 fov=120°;
// 开头先复位 custom view/projection 矩阵;
// FocusedShadowCameraSetup:先跑默认,sceneBB 为空即回退默认,
// 非空才设两套自定义矩阵。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"
#include <cmath>
#include <cstdint>
namespace ogre_repro {
struct Vec3 {
float x, y, z;
};
inline Vec3 norm(const Vec3& v) {
float l = std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
return Vec3{v.x / l, v.y / l, v.z / l};
}
inline bool vecEq(const Vec3& a, const Vec3& b) {
return a.x == b.x && a.y == b.y && a.z == b.z;
}
enum ProjectionType : uint8_t { PT_ORTHOGRAPHIC = 0, PT_PERSPECTIVE = 1 };
// 朝向:dir = 看向方向,up = 上方向(已正交化)
struct Orientation {
Vec3 dir;
Vec3 up;
};
// 对应 Math::lookRotation(dir, up):把 up 对 dir 做 Gram-Schmidt 正交化
Orientation lookRotation(const Vec3& dir, Vec3 up) {
Vec3 d = norm(dir);
float dp = up.x * d.x + up.y * d.y + up.z * d.z;
up = norm(Vec3{up.x - dp * d.x, up.y - dp * d.y, up.z - dp * d.z});
return Orientation{d, up};
}
// 阴影纹理相机(Camera 的最小实现)
struct Camera {
ProjectionType projType = PT_PERSPECTIVE;
float fov = 45.0f;
float orthoWindow = 0.0f;
Vec3 position = Vec3{0, 0, 0};
Orientation orientation = Orientation{{0, 0, -1}, {0, 1, 0}};
float nearClip = 1.0f, farClip = 100.0f;
bool customView = false, customProj = false;
void setCustomViewMatrix(bool v) { customView = v; }
void setCustomProjectionMatrix(bool v) { customProj = v; }
void setProjectionType(ProjectionType t) { projType = t; }
void setFOVy(float f) { fov = f; }
void setOrthoWindow(float w, float /*h*/) { orthoWindow = w; }
void setPosition(const Vec3& p) { position = p; }
void setOrientation(const Orientation& o) { orientation = o; }
};
struct Light {
enum LightTypes : uint8_t { LT_POINT = 0, LT_DIRECTIONAL = 1, LT_SPOTLIGHT = 2 };
LightTypes type = LT_POINT;
Vec3 derivedDir = Vec3{0, 0, -1};
Vec3 derivedPosition = Vec3{0, 0, 0};
float spotOuter = 40.0f;
float shadowFarDistance = 0.0f;
};
// 对应 ShadowCameraSetup 抽象基类
class ShadowCameraSetup {
public:
virtual void getShadowCamera(const Camera& cam, const Light& light,
Camera& texCam, float shadowOffset,
float extrusion) const = 0;
virtual ~ShadowCameraSetup() = default;
};
// 对应 DefaultShadowCameraSetup
class DefaultShadowCameraSetup : public ShadowCameraSetup {
public:
void getShadowCamera(const Camera& cam, const Light& light, Camera& texCam,
float shadowOffset, float extrusion) const override {
// 复位自定义矩阵(对应 setCustomViewMatrix(false) 等)
texCam.setCustomViewMatrix(false);
texCam.setCustomProjectionMatrix(false);
// shadowDist:未设阴影距离时用 近裁剪 × 300
float shadowDist = light.shadowFarDistance;
if (shadowDist == 0.0f) shadowDist = cam.nearClip * 300.0f;
// 目标点:相机位置沿视线偏移 shadowOffset
Vec3 target{cam.position.x + cam.orientation.dir.x * shadowOffset,
cam.position.y + cam.orientation.dir.y * shadowOffset,
cam.position.z + cam.orientation.dir.z * shadowOffset};
if (light.type == Light::LT_DIRECTIONAL) {
// 正交窗口覆盖 2×shadowDist
texCam.setProjectionType(PT_ORTHOGRAPHIC);
texCam.setOrthoWindow(shadowDist * 2, shadowDist * 2);
// 方向 = -lightDir(OGRE 约定向下 -z)
Vec3 dir = norm(Vec3{-light.derivedDir.x, -light.derivedDir.y,
-light.derivedDir.z});
Vec3 pos{target.x + dir.x * extrusion, target.y + dir.y * extrusion,
target.z + dir.z * extrusion};
texCam.setPosition(pos);
Vec3 up{0, 1, 0};
float dotu = up.x * dir.x + up.y * dir.y + up.z * dir.z;
if (std::abs(dotu) >= 1.0f) up = Vec3{0, 0, 1}; // 与 dir 重合换 UNIT_Z
texCam.setOrientation(lookRotation(dir, up));
} else if (light.type == Light::LT_SPOTLIGHT) {
// 透视 + 外角×1.2,上限 175°
texCam.setProjectionType(PT_PERSPECTIVE);
float fov = light.spotOuter * 1.2f;
if (fov > 175.0f) fov = 175.0f;
texCam.setFOVy(fov);
} else {
// 点光:透视 120°
texCam.setProjectionType(PT_PERSPECTIVE);
texCam.setFOVy(120.0f);
texCam.setPosition(light.derivedPosition);
Vec3 dir = norm(Vec3{light.derivedPosition.x - target.x,
light.derivedPosition.y - target.y,
light.derivedPosition.z - target.z});
Vec3 up{0, 1, 0};
float dotu = up.x * dir.x + up.y * dir.y + up.z * dir.z;
if (std::abs(dotu) >= 1.0f) up = Vec3{0, 0, 1};
texCam.setOrientation(lookRotation(dir, up));
}
}
};
// 对应 FocusedShadowCameraSetup:sceneBB 为空回退默认
class FocusedShadowCameraSetup : public DefaultShadowCameraSetup {
public:
bool sceneBBNull = true;
void getShadowCamera(const Camera& cam, const Light& light, Camera& texCam,
float shadowOffset, float extrusion) const override {
DefaultShadowCameraSetup::getShadowCamera(cam, light, texCam, shadowOffset,
extrusion);
// 对应:sceneBB 为空 → 直接返回(沿用默认矩阵)
if (sceneBBNull) return;
// 对应:计算 bodyB 后设两套自定义矩阵
texCam.setCustomViewMatrix(true);
texCam.setCustomProjectionMatrix(true);
}
};
} // namespace ogre_repro
int main() {
using namespace ogre_repro;
// 主相机:原点朝 -z
Camera cam;
cam.position = Vec3{0, 0, 0};
cam.orientation = Orientation{{0, 0, -1}, {0, 1, 0}};
cam.nearClip = 1.0f;
DefaultShadowCameraSetup def;
// 方向光:正交投影,shadowDist = near×300,位置 = target + dir×100
Light dirLight;
dirLight.type = Light::LT_DIRECTIONAL;
dirLight.derivedDir = Vec3{0, 0, -1};
dirLight.shadowFarDistance = 0.0f;
Camera t1;
def.getShadowCamera(cam, dirLight, t1, 0.0f, 100.0f);
CHECK_EQ(static_cast<int>(t1.projType), static_cast<int>(PT_ORTHOGRAPHIC));
CHECK_EQ(t1.orthoWindow, 600.0f);
CHECK(vecEq(t1.position, Vec3{0, 0, 100}));
CHECK(vecEq(t1.orientation.dir, Vec3{0, 0, 1}));
CHECK(vecEq(t1.orientation.up, Vec3{0, 1, 0}));
CHECK(!t1.customView && !t1.customProj); // 默认先复位自定义矩阵
// 聚光:透视,fov = 40×1.2 = 48
Light spot;
spot.type = Light::LT_SPOTLIGHT;
spot.spotOuter = 40.0f;
Camera t2;
def.getShadowCamera(cam, spot, t2, 0.0f, 100.0f);
CHECK_EQ(static_cast<int>(t2.projType), static_cast<int>(PT_PERSPECTIVE));
CHECK_EQ(t2.fov, 48.0f);
// 聚光角度上限:170×1.2 = 204 → 封顶 175
spot.spotOuter = 170.0f;
Camera t2b;
def.getShadowCamera(cam, spot, t2b, 0.0f, 100.0f);
CHECK_EQ(t2b.fov, 175.0f);
// 点光:透视 120°,位置 = 光源位置,朝向看向目标点
Light pt;
pt.type = Light::LT_POINT;
pt.derivedPosition = Vec3{0, 0, -10};
Camera t3;
def.getShadowCamera(cam, pt, t3, 0.0f, 100.0f);
CHECK_EQ(static_cast<int>(t3.projType), static_cast<int>(PT_PERSPECTIVE));
CHECK_EQ(t3.fov, 120.0f);
CHECK(vecEq(t3.position, Vec3{0, 0, -10}));
CHECK(vecEq(t3.orientation.dir, Vec3{0, 0, -1}));
// Focused:sceneBB 为空 → 回退默认(不设自定义矩阵)
FocusedShadowCameraSetup foc;
foc.sceneBBNull = true;
Camera t4;
foc.getShadowCamera(cam, spot, t4, 0.0f, 100.0f);
CHECK(!t4.customView);
CHECK(!t4.customProj);
CHECK_EQ(static_cast<int>(t4.projType), static_cast<int>(PT_PERSPECTIVE));
// Focused:sceneBB 非空 → 设两套自定义矩阵
foc.sceneBBNull = false;
Camera t5;
foc.getShadowCamera(cam, dirLight, t5, 0.0f, 100.0f);
CHECK(t5.customView);
CHECK(t5.customProj);
// 类型层级:Focused 派生自 Default,Default 派生自 ShadowCameraSetup
CHECK(dynamic_cast<const DefaultShadowCameraSetup*>(&foc) != nullptr);
CHECK(dynamic_cast<const ShadowCameraSetup*>(&foc) != nullptr);
CHECK(dynamic_cast<const ShadowCameraSetup*>(&def) != nullptr);
return lab::report("05-2 阴影相机设置:默认/聚焦相机");
}
本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译零警告,断言 21/21 通过。
小结
ShadowCameraSetup抽象基类把纹理相机摆放做成可插拔策略,默认实现即「普通阴影贴图」。- 方向光:正交投影、窗口 2×shadowDist、位置沿光方向回退挤出距离、按纹素取整抑制抖动。
- 聚光:透视 FOV = 外角×1.2、上限 175°;点光:透视 120°、位置取光源位置。
FocusedShadowCameraSetup先跑默认,sceneBB 空则回退,非空才覆盖两套自定义矩阵聚焦可见区域。
阅读导航:上一节:5.1 阴影技术总览 · 下一节:5.3 纹理阴影与投射 。
继续阅读
探索更多技术文章
浏览归档,发现更多关于系统设计、工具链和工程实践的内容。