光线跟踪的算法

1,原理

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

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

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值