1,原理

由于从光源发出的光线有无穷多条,使得直接从光源出发对光线进行跟踪变得非常困难。实际上,从光源发出的光线只有少数经由场景的反射和透射(折射)后到达观察者的眼中。为此标准光线跟踪算法采用逆向跟踪技术完成整个场景的绘制。

光线跟踪思路:从视点出发,通过图像平面上每个像素中心向场景发出一条光线,光线的起点为视点,方向为像素中心和视点连线单位向量。光线与离视点最近的场景物体表面交点有三种可能:

  1. 当前交点所在的物体表面为理想漫射面,跟踪结束。
  2. 当前交点所在的物体表面为理想镜面,光线沿其镜面发射方向继续跟踪。
  3. 当前交点所在的物体表面为规则透射面,光线沿其规则透射方向继续跟踪。

python光线追踪 朗伯 光线跟踪算法技术_光亮度

图-1 三个半透明玻璃球场景跟踪图

如图-1中,场景中有三个半透明玻璃球,视点发出光线与场景最近交点为P1,使用任意局部光照模型(opengl使用的是phong模型)可以计算出P1点处的局部光亮度Ilocal,为了计算周围环境在P1点处产生的镜面发射光和规则折射光,光线1在P1点处衍生出两支光线:反射光2和折射光3。P1处的光照由三部分组成:Ilocal + ks * I2 + kt * I3

I3 为折射光线3的颜色,Kt为折射率

I2为反射光线2的颜色,Ks为反射率

I3 I2的计算需要递归。

2,伪代码



1. void TraceRay(const Vec3& start, const Vec3& direction, int
2. { 
3. Vec3 intersectionPoint, reflectedDirection, transmittedDirection; 
4. Color localColor, reflectedColor, transmittedColor; 
5. if
6. color = Black; //#000 
7. } 
8. else
9. Ray ray(start, direction); //取start起点,方向direction为跟踪射线; 
10. if
11. color = BackgroundColor; 
12. else
13. 计算理起始点start最近的交点intersectionPoint, 
14. 记录相交物体intersectionObject, 
15. 
16. // #1 
17. Shade(intersectionObject, intersectionPoint, localColor);  
18. 
19. // #2 
20. if
21. 计算跟踪光想S在intersectionPoint处的反射光线方向reflectedDirection,  
22. TraceRay(intersectionPoint, reflectedDirection, depth+1, reflectedColor); 
23. } 
24. // #3 
25. if
26. 计算跟踪光线S在intersectionPoint处的规则透射光线方向transmittedDirection, 
27. TraceRay(intersectionPoint, transmittedDirection, depth+1, transmittedColor); 
28. } 
29. // #summarize 
30. color = localColor + Ks * reflectedColor + Kt * transmittedColor;  
31. }// else 
32. } //else 
33. } 
34. // 局部光照模型计算交点intersectionPoint处的局部光亮度localColor 
35. void Shade(const Object& intersectionObj, const
36. { 
37. 确定intersectionObj在intersectionPoint处的单位法向量N, 
38. 漫反射系数Kd, 
39. 镜面反射系数Ks, 
40. 环境反射系数Ka; 
41. localColor = Ka * Ia; //Ia为环境光亮度 
42. for
43. 计算入射光线单位向量L和虚拟镜面法向单位向量H, 
44. // 由Phong模型计算光源PointLight在intersectionPoint处的漫反射和镜面反射光亮度 
45. localColor += ( Ipointlight * ( Kd * (N.dot(L)) + Ks * (N.dot(H))^n ) ); 
46. } 
47. }