请使用PyGame实现一个简单的光线追踪(Ray Tracing)系统,并解释其核心算法和性能瓶颈。

import pygame
import numpy as np

# 初始化 PyGame
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Simple Ray Tracing')

# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

# 定义光源和物体
light_pos = np.array([400, 300, -100])  # 光源位置
light_color = np.array([1.0, 1.0, 1.0])  # 光源颜色
sphere_pos = np.array([400, 300, 0])  # 球体位置
sphere_radius = 100  # 球体半径

# 光线追踪函数
def ray_trace(ray_origin, ray_dir):
    # 计算光线与球体的交点
    oc = ray_origin - sphere_pos
    a = np.dot(ray_dir, ray_dir)
    b = 2.0 * np.dot(oc, ray_dir)
    c = np.dot(oc, oc) - sphere_radius ** 2
    discriminant = b ** 2 - 4 * a * c

    if discriminant < 0:
        return None  # 没有交点
    else:
        t = (-b - np.sqrt(discriminant)) / (2.0 * a)  # 最近交点
        hit_point = ray_origin + t * ray_dir
        return hit_point

# 渲染函数
def render():
    screen.fill(BLACK)
    for x in range(screen_width):
        for y in range(screen_height):
            # 创建从相机到像素的光线
            ray_origin = np.array([x, y, -100])
            ray_dir = np.array([0, 0, 1])
            hit_point = ray_trace(ray_origin, ray_dir)

            if hit_point is not None:
                # 计算光照
                normal = (hit_point - sphere_pos) / sphere_radius
                light_dir = (light_pos - hit_point)
                light_dir = light_dir / np.linalg.norm(light_dir)
                intensity = max(0, np.dot(normal, light_dir))
                color = (intensity * light_color * 255).astype(int)
                color = np.clip(color, 0, 255)
                screen.set_at((x, y), color)
    pygame.display.flip()

# 主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    render()

pygame.quit()

核心算法解释

  1. 光线生成:从相机位置(屏幕像素)发射光线,方向通常是垂直于屏幕(Z轴方向)。
  2. 交点计算:通过光线与球体的几何方程求解交点。球体的方程为 (p - c)^2 = r^2,其中 p 是光线上的一点,c 是球心,r 是半径。
  3. 光照计算:如果光线与球体相交,计算交点的法向量(从球心到交点的单位向量)。然后根据光照方向(光源到交点的向量)与法向量的点积,计算光照强度。
  4. 颜色渲染:光照强度乘以光源颜色,得到最终像素颜色。

性能瓶颈

  1. 计算复杂度:每个像素都需要计算光线与物体的交点,时间复杂度为 O(N*M),其中 N 是像素数量,M 是物体数量。当场景复杂时,性能会急剧下降。
  2. 浮点运算:光线追踪需要大量浮点数运算(如点积、平方根等),这对CPU是一个挑战。
  3. 阴影和反射:如果实现阴影或反射效果,需要额外计算多条光线,进一步增加计算量。

示例说明

  • 上述代码实现了一个简单的光线追踪场景,包含一个球体和一个光源。
  • 通过遍历屏幕像素,计算光线与球体的交点,并根据光照生成颜色。
  • 光照模型为漫反射(Lambertian),使用法向量与光照方向的点积计算。