如何给 3D 面添加自定义光源方向?

解读

在国内算法/数据可视化岗位的面试中,这道题常被用来区分“只会调接口”与“真正理解 Matplotlib 3D 渲染管线”的候选人。
面试官真正想听的是:

  1. 你能否定位到 3D 面片的光照计算入口(Poly3DCollection 的 set_3d_properties → _shade_colors);
  2. 你能否绕过 Matplotlib 内置的固定光源(硬编码在 mpl_toolkits.mplot3d.art3d._light_source 方向向量),把自定义光源方向注入到面片法向量与光照模型计算中;
  3. 你能否兼顾性能与可维护性,不破坏 Agg 后端缓存、不触发多余 draw()。
    一句话:“改光源方向”不是改颜色,而是改法向量与光照模型之间的点积权重,且必须在线程安全的事件循环里完成。

知识点

  • mpl_toolkits.mplot3d.art3d.Poly3DCollection:3D 面片的 Artist 载体,_facecolors 存储最终 RGBA。
  • art3d._shade_colors(color, normals, lightsource):硬编码光源方向为 (-1, -1, -1) 的 Lambert 漫反射模型。
  • **Poly3DCollection.set_3d_properties(verts, *args, kwargs):在 C++ Agg 渲染前同步 Python 层法向量数组。
  • matplotlib.colors.LightSource:2D 专用类,3D 场景下需重新实现或 monkey-patch其 shade_rgb 方法。
  • 事件循环安全:GUI 后端(Qt5Agg、TkAgg)中,光源方向必须在主线程通过 canvas.draw_idle() 刷新,否则 SegFault。
  • PEP8 与性能:30 万行代码里,任何对 _shade_colors 的热路径修改必须加 lru_cache,避免 2000+ 单元测试超时。

答案

给面试官一个可落地、可单元测试、不 hack 私有属性的标准答案,分三步:

  1. 自定义 LightSource 子类,重写 illuminate(self, normals, direction),把入射方向暴露为参数:
from mpl_toolkits.mplot3d.art3d import _shade_colors
from matplotlib.colors import LightSource

class CustomLightSource(LightSource):
    def __init__(self, azdeg=0, altdeg=0, direction=None):
        super().__init__(azdeg, altdeg)
        # direction 优先,与 Matplotlib 官方逻辑保持一致
        self.direction = direction or self._direction_from_angles()

    def _direction_from_angles(self):
        az, alt = np.deg2rad(self.azdeg), np.deg2rad(self.altdeg)
        return np.array([np.cos(az) * np.cos(alt),
                         np.sin(az) * np.cos(alt),
                         np.sin(alt)])

    def illuminate(self, normals, fraction=1.0):
        # 归一化
        norms = np.linalg.norm(normals, axis=1, keepdims=True)
        normals = normals / np.where(norms == 0, 1, norms)
        direction = self.direction / np.linalg.norm(self.direction)
        # Lambert 漫反射
        intensity = np.dot(normals, direction).clip(0, 1) * fraction
        return intensity
  1. 在构建 Poly3DCollection 后、add_collection3d 前,把自定义光源注入:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

# 生成一个 3D 面片:单位球 8 面体
from mpl_toolkits.mplot3d import Axes3D
u = np.linspace(0, 2*np.pi, 5)
v = np.linspace(0, np.pi, 5)
x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones_like(u), np.cos(v))
verts = [list(zip(x[i], y[i], z[i])) for i in range(len(x))]

# 创建 Poly3DCollection
poly = Poly3DCollection(verts, edgecolors='k', linewidths=0.3)

# 关键:自定义光源方向
custom_dir = np.array([1, 0.5, -1], dtype=float)
light = CustomLightSource(direction=custom_dir)

# 手动计算 _facecolors
normals = poly._vec_normals  # 3.6+ 公开属性
intensity = light.illuminate(normals)
base_color = np.array([0.2, 0.5, 0.9, 1.0])
poly.set_facecolors(base_color * intensity[:, None])

ax.add_collection3d(poly)
ax.set_box_aspect([1,1,1])
plt.show()
  1. 单元测试:
def test_custom_light_direction():
    from mpl_toolkits.mplot3d.art3d import _shade_colors
    # 固定法向量朝上的面片
    normals = np.array([[0, 0, 1]])
    light = CustomLightSource(direction=[0, 0, 1])
    intensity = light.illuminate(normals)
    assert np.allclose(intensity, 1.0, atol=1e-5)

至此,不改动 Matplotlib 源码、不触碰 C++ Agg 层,就完成了“3D 面自定义光源方向”的正式交付。

拓展思考

  • GPU 加速:若面试场景换成 WebGL(JupyterLab 的 ipympl),可把方向向量直接送顶点着色器,在 GLSL 里做 Lambert,避免 Python 层逐面片光照计算。
  • 多光源与阴影:在科研出版场景,需叠加环境光 + 平行光 + 点光源,可扩展 CustomLightSource 为列表,并在 illuminate 里返回叠加强度;阴影需引入 shadow mapping,Matplotlib 暂无官方支持,可离线用 PyTorch3D 渲染再贴回 Figure 的 AxesImage。
  • 版本兼容性:Matplotlib 3.8 之后,_vec_normals 属性可能改名,需在 CI 里加 @pytest.mark.skipif(mpl.version_info < (3, 6), reason="normals attr"),保障 1.5 亿次年下载量的下游库不炸。