rayzor

view src/raytrace.cc @ 22:5380ff64e83f

minor changes from dos, and line endings cleanup
author John Tsiombikas <nuclear@member.fsf.org>
date Fri, 02 May 2014 14:32:58 +0300
parents 252999cd1a3f
children
line source
1 #include <assert.h>
2 #include <float.h>
3 #include "raytrace.h"
4 #include "rayzor.h"
5 #include "scene.h"
6 #include "logger.h"
8 Vector3 ray_trace(const Ray &ray, int iter)
9 {
10 RayHit hit;
11 if(!scene->intersect(ray, &hit)) {
12 return scene->get_background(ray);
13 }
15 return shade(hit, iter);
16 }
18 static inline float positive(float x)
19 {
20 return x < 0.0f ? 0.0f : x;
21 }
23 Vector3 shade(const RayHit &hit, int iter)
24 {
25 const Material &mtl = hit.obj->mtl;
27 Vector3 pos = hit.ray.origin + hit.ray.dir * hit.dist;
28 Vector3 norm = hit.obj->hit_normal(hit);
29 norm = normalize(transform(normal_matrix(hit.obj->get_matrix()), norm));
30 Vector3 vdir = -normalize(hit.ray.dir);
32 float ior = mtl.ior;
34 if(dot(norm, hit.ray.dir) > 0.0) {
35 norm = -norm;
36 ior = 1.0 / mtl.ior;
37 }
39 Vector3 color = scene->get_ambient();
41 // for each light, calculate local illumination
42 int num_lights = scene->get_light_count();
43 for(int i=0; i<num_lights; i++) {
44 const Light *lt = scene->get_light(i);
45 Vector3 ldir = lt->get_position() - pos;
46 Vector3 lcol = lt->get_color(pos);
48 RayHit hit;
49 if(!scene->intersect(Ray(pos, ldir), &hit) || hit.dist > 1.0) {
50 // if we can see the light, calculate and add its contribution
51 ldir.normalize();
52 float ndotl = positive(dot(norm, ldir));
53 Vector3 diffuse = mtl.diffuse * lcol * ndotl;
55 Vector3 hdir = normalize(ldir + vdir);
56 float ndoth = positive(dot(norm, hdir));
57 Vector3 specular = mtl.specular * lcol * pow(ndoth, mtl.roughness * 128.0);
59 color = color + lerp(specular, diffuse, mtl.roughness);
60 }
61 }
63 if(mtl.reflect > 1e-4 && iter < 6) {
64 Ray reflray(pos, reflect(vdir, norm));
66 Vector3 rcol = ray_trace(reflray, iter + 1) * mtl.specular * mtl.reflect;
67 color = color + rcol;
68 }
70 if(mtl.refract > 1e-4 && iter < 6) {
71 Ray refrray(pos, refract(vdir, norm, ior));
73 Vector3 rcol = ray_trace(refrray, iter + 1) * mtl.specular * mtl.refract;
74 color = color + rcol;
75 }
77 return color;
78 }