《OGRE 3D 渲染引擎原理与架构》4.2 衰减与范围

点光/聚光按 1/(c + l·d + q·d²) 随距离衰减,并受 range 上限截断;聚光再乘内/外锥半角余弦的 falloff 幂因子。lab 复现距离衰减与聚光因子的两个公式及边界行为。

4.2 衰减与范围

4.1 定了光源类型与默认值,但「光怎么随距离变弱」还没说。点光与聚光的光强按标准的二次衰减公式随距离下降,并被 range 上限一刀截断;方向光来自无穷远,不衰减。聚光在距离衰减之上还要乘一层锥角因子——内锥以内全亮、外锥以外全灭、过渡带按 falloff 幂渐变。

本章与站内既有内容的分工

cg 三卷讲过光强与距离的物理关系(平方反比),但没有落在引擎参数上。本节把 OGRE 的衰减四元组与聚光因子公式讲透,并说明为什么常数项 1 表示「不衰减」。4.3 讲光源颜色与材质合成,5 章阴影相机也会复用 getSpotlightOuterAngle 这类角度参数。

衰减四元组与公式

setAttenuation 的文档注释把四个参数的含义写得最清楚:range 是绝对上限、constant 常数项 1 表示永不衰减、linear 线性项、quadratic 二次项加曲率:

// OgreMain/include/OgreLight.h:setAttenuation 文档(v14.6.3 源码摘录,已删减)
        /** Sets the attenuation parameters of the light source i.e. how it diminishes with distance.

            Lights normally get fainter the further they are away. Also, each light is given a maximum range
            beyond which it cannot affect any objects.
        @par
            Light attenuation is not applicable to directional lights since they have an infinite range and
            constant intensity.
        @par
            This follows a standard attenuation approach - see any good 3D text for the details of what they mean
        @param range
            The absolute upper range of the light in world units.
        @param constant
            The constant factor in the attenuation formula: 1.0 means never attenuate, 0.0 is complete attenuation.
        @param linear
            The linear factor in the attenuation formula: 1 means attenuate evenly over the distance.
        @param quadratic
            The quadratic factor in the attenuation formula: adds a curvature to the attenuation formula.
        */
        void setAttenuation(float range, float constant, float linear, float quadratic)
        {
            mAttenuation = {range, constant, linear, quadratic};
        }

四个数存进一个 Vector4f mAttenuation,配套 getter 各自取一个分量:

// OgreMain/include/OgreLight.h:getAttenuation 系列(v14.6.3 源码摘录,已删减)
        /** Returns the absolute upper range of the light.
        */
        float getAttenuationRange(void) const { return mAttenuation[0]; }

        /** Returns the constant factor in the attenuation formula.
        */
        float getAttenuationConstant(void) const { return mAttenuation[1]; }

        /** Returns the linear factor in the attenuation formula.
        */
        float getAttenuationLinear(void) const { return mAttenuation[2]; }

        /** Returns the quadric factor in the attenuation formula.
        */
        float getAttenuationQuadric(void) const { return mAttenuation[3]; }

        /// Returns all the attenuation params as (range, constant, linear, quadratic)
        const Vector4f& getAttenuation() const { return mAttenuation; }

着色器端(或任何消费方)按标准公式计算:

衰减因子 A = 1 / (c + l·d + q·d²),且 d > range 时 A = 0
  • 默认 (100000, 1, 0, 0):A = 1/1 = 1,任何距离都不衰减——这是新光源的「先亮着,再自己调」策略。
  • (100000, 0, 1, 0):A = 1/d,纯线性衰减,25 单位处 0.04。
  • (100000, 0, 1, 0.01):A = 1/(d + 0.01d²),10 单位处 1/11 ≈ 0.0909,二次项让远距离更快暗下去。
  • range 不是公式变量而是截断开关:d > range 直接判 0,避免远处贡献噪声。

聚光因子:锥角上的幂渐变

聚光在距离衰减之外还有锥角衰减。OGRE 把它打包成 getSpotlightParams 的 4D 向量交给着色器:x = cos(内角/2)、y = cos(外角/2)、z = falloff、w = 1(标记是聚光)。注释直接给出因子公式:

// OgreMain/src/OgreAutoParamDataSource.cpp:getSpotlightParams(v14.6.3 源码摘录,已删减)
    Vector4f AutoParamDataSource::getSpotlightParams(size_t index) const
    {
        // inner, outer, fallof, isSpot
        const Light& l = getLight(index);
        if (l.getType() == Light::LT_SPOTLIGHT)
        {
            return Vector4f(Math::Cos(l.getSpotlightInnerAngle().valueRadians() * 0.5f),
                           Math::Cos(l.getSpotlightOuterAngle().valueRadians() * 0.5f),
                           l.getSpotlightFalloff(),
                           1.0);
        }
        ...
        else
        {
            // Use safe values which result in no change to point & dir light calcs
            // The spot factor applied to the usual lighting calc is 
            // pow((dot(spotDir, lightDir) - y) / (x - y), z)
            // Therefore if we set z to 0.0f then the factor will always be 1
            // since pow(anything, 0) == 1
            ...
            return Vector4f(1.0, 0.0, 0.0, 0.0); // since the main op is pow(.., vec4.z), this will result in 1.0
        }
    }

注意两个细节。第一,取的是半角的余弦:内角 30° → cos(15°) ≈ 0.9659,外角 40° → cos(20°) ≈ 0.9397。第二,对非聚光光源返回 (1, 0, 0, 0),让 pow(..., 0) = 1——同一份着色器代码对点光/方向光也能跑,这就是 4.1 归一思想的延续。实际聚光因子:

S = pow((dot(spotDir, lightDir) - y) / (x - y), z)

其中 dot 是像素到光方向与光轴的夹角余弦,x/y 是半角余弦,z 是 falloff。S 的行为是三段:dot ≥ x(内锥内)恒为 1;dot ≤ y(外锥外)恒为 0;中间按 z 次幂渐变——默认 z=2 让过渡更锐利。

源码定位

上游引用固定到 OGRE v14.6.3 源码 。

可运行产物:C++ 最小验证

下面复现衰减与聚光两个公式:距离衰减的截断语义、纯线性/二次组合、聚光因子的三段行为与 falloff 幂渐变。它与 src/04-2-light-attenuation.cpp 逐字节一致:

// file: src/04-2-light-attenuation.cpp
// tier: L1
// verify: clang++ -std=c++20 -I. src/04-2-light-attenuation.cpp -o bin/04-2-light-attenuation && ./bin/04-2-light-attenuation
//
// 复现 OgreLight.h / OgreAutoParamDataSource.cpp 的衰减与聚光公式:
//   衰减因子 = 1 / (constant + linear*d + quadratic*d²),
//     超出 getAttenuationRange() 后截为 0;
//   聚光因子 = pow((dot(spotDir, lightDir) - cos(outer/2)) /
//                 (cos(inner/2) - cos(outer/2)), falloff),
//     内锥以内 = 1,外锥以外 = 0。
// 独立最小验证,非 OGRE 源码。
#include "verify.h"

#include <cmath>
#include <cstdint>

namespace ogre_repro {

inline float rad(float deg) { return deg * 3.14159265f / 180.0f; }

// 对应 OgreLight.h:衰减四元组 (range, constant, linear, quadratic)
struct Attenuation {
  float range, constant, linear, quadratic;
};

// 对应着色器通用衰减:1/(c + l·d + q·d²),超范围截 0
float attenuationFactor(const Attenuation& a, float dist) {
  if (dist > a.range) return 0.0f;
  float denom = a.constant + a.linear * dist + a.quadratic * dist * dist;
  return 1.0f / denom;
}

// 对应 OgreAutoParamDataSource::getSpotlightParams 注释的聚光因子
//   pow((dot - y) / (x - y), z),x=cos(inner/2), y=cos(outer/2), z=falloff
float spotFactor(float cosAngle, float cosInner, float cosOuter, float falloff) {
  if (cosAngle >= cosInner) return 1.0f;
  if (cosAngle <= cosOuter) return 0.0f;
  float x = (cosAngle - cosOuter) / (cosInner - cosOuter);
  return std::pow(x, falloff);
}

inline bool near(float a, float b, float eps = 1e-5f) {
  return std::abs(a - b) <= eps;
}

}  // namespace ogre_repro

int main() {
  using namespace ogre_repro;

  // 默认衰减 (100000, 1, 0, 0):常数项 1 → 全程 1/1 = 1,距离不减
  Attenuation def{100000.0f, 1.0f, 0.0f, 0.0f};
  CHECK(near(attenuationFactor(def, 0.0f), 1.0f));
  CHECK(near(attenuationFactor(def, 100.0f), 1.0f));
  CHECK(near(attenuationFactor(def, 50000.0f), 1.0f));

  // 限制范围:超 range 截 0,范围内照常算
  Attenuation ranged{100.0f, 1.0f, 0.0f, 0.0f};
  CHECK(near(attenuationFactor(ranged, 200.0f), 0.0f));
  CHECK(near(attenuationFactor(ranged, 99.0f), 1.0f));
  CHECK(near(attenuationFactor(ranged, 100.0f), 1.0f));

  // 线性项:1/(0 + 1·25) = 0.04(range 给大值,不触发截断)
  Attenuation lin{100000.0f, 0.0f, 1.0f, 0.0f};
  CHECK(near(attenuationFactor(lin, 25.0f), 0.04f));

  // 常数项 1 且 d=0:1/1 = 1
  Attenuation c1{100000.0f, 1.0f, 1.0f, 0.0f};
  CHECK(near(attenuationFactor(c1, 0.0f), 1.0f));

  // 二次项:1/(0 + 1·10 + 0.01·100) = 1/11
  Attenuation quad{100000.0f, 0.0f, 1.0f, 0.01f};
  CHECK(near(attenuationFactor(quad, 10.0f), 1.0f / 11.0f));

  // 聚光参数:cos(30/2)=cos15°、cos(40/2)=cos20°,默认 falloff=2
  float cosInner = std::cos(rad(15.0f));
  float cosOuter = std::cos(rad(20.0f));
  CHECK(cosInner > cosOuter);

  // 内锥以内 → 1,外锥以外 → 0
  CHECK(near(spotFactor(0.99f, cosInner, cosOuter, 2.0f), 1.0f));
  CHECK(near(spotFactor(cosInner, cosInner, cosOuter, 2.0f), 1.0f));
  CHECK(near(spotFactor(0.90f, cosInner, cosOuter, 2.0f), 0.0f));
  CHECK(near(spotFactor(cosOuter, cosInner, cosOuter, 2.0f), 0.0f));

  // 过渡带:falloff=1 时线性,falloff=2 时平方
  float base = (0.95f - cosOuter) / (cosInner - cosOuter);
  CHECK(near(spotFactor(0.95f, cosInner, cosOuter, 1.0f), base));
  CHECK(near(spotFactor(0.95f, cosInner, cosOuter, 2.0f), base * base));
  CHECK(base > 0.0f && base < 1.0f);

  // 默认 Light 聚光角内 30° 外 40°,取半角正是 cos15°/cos20°
  CHECK(near(std::cos(rad(30.0f) * 0.5f), cosInner));
  CHECK(near(std::cos(rad(40.0f) * 0.5f), cosOuter));

  return lab::report("04-2 衰减与范围:距离衰减/聚光因子");
}

本机实测(Apple clang 16,clang++ -std=c++20 -Wall):编译零警告,断言 19/19 通过。

小结

  • 衰减四元组 (range, constant, linear, quadratic) 进公式 A = 1/(c + l·d + q·d²),d > range 时 A = 0。
  • 默认 constant=1 表示永不衰减;方向光有无限范围与恒定强度,不参与。
  • 聚光因子 S = pow((dot - y)/(x - y), z),x/y 是内/外半角余弦,内锥内 1、外锥外 0。
  • getSpotlightParams 对非聚光返回 (1,0,0,0),靠 pow(·,0)=1 让同一段着色器兼容所有光源。

阅读导航:上一节:4.1 光源类型 · 下一节:4.3 光照视觉参数 。

继续阅读

探索更多技术文章

浏览归档,发现更多关于系统设计、工具链和工程实践的内容。

全部文章 返回首页

「books」更多文章

  1. 《大规模分布式计算深入解析》15.3 落地:从 Neo4j 到自研图引擎
  2. 《大规模分布式计算深入解析·图计算与图数据库内核》 · 目录与学习路径(45 篇)
  3. 《大规模分布式计算深入解析》15.2 十一卷主线:从切分到图