rayzor

diff src/raytrace.cc @ 19:252999cd1a3f

added reflection and refraction
author John Tsiombikas <nuclear@member.fsf.org>
date Tue, 15 Apr 2014 00:59:37 +0300
parents 79609d482762
children 5380ff64e83f
line diff
     1.1 --- a/src/raytrace.cc	Mon Apr 14 18:35:37 2014 +0300
     1.2 +++ b/src/raytrace.cc	Tue Apr 15 00:59:37 2014 +0300
     1.3 @@ -22,17 +22,23 @@
     1.4  
     1.5  Vector3 shade(const RayHit &hit, int iter)
     1.6  {
     1.7 +	const Material &mtl = hit.obj->mtl;
     1.8 +
     1.9  	Vector3 pos = hit.ray.origin + hit.ray.dir * hit.dist;
    1.10  	Vector3 norm = hit.obj->hit_normal(hit);
    1.11  	norm = normalize(transform(normal_matrix(hit.obj->get_matrix()), norm));
    1.12  	Vector3 vdir = -normalize(hit.ray.dir);
    1.13  
    1.14 +	float ior = mtl.ior;
    1.15 +
    1.16 +	if(dot(norm, hit.ray.dir) > 0.0) {
    1.17 +		norm = -norm;
    1.18 +		ior = 1.0 / mtl.ior;
    1.19 +	}
    1.20 +
    1.21  	Vector3 color = scene->get_ambient();
    1.22  
    1.23 -	const Vector3 &kd = hit.obj->mtl.diffuse;
    1.24 -	const Vector3 &ks = hit.obj->mtl.specular;
    1.25 -	float roughness = hit.obj->mtl.roughness;
    1.26 -
    1.27 +	// for each light, calculate local illumination
    1.28  	int num_lights = scene->get_light_count();
    1.29  	for(int i=0; i<num_lights; i++) {
    1.30  		const Light *lt = scene->get_light(i);
    1.31 @@ -44,15 +50,29 @@
    1.32  			// if we can see the light, calculate and add its contribution
    1.33  			ldir.normalize();
    1.34  			float ndotl = positive(dot(norm, ldir));
    1.35 -			Vector3 diffuse = kd * lcol * ndotl;
    1.36 +			Vector3 diffuse = mtl.diffuse * lcol * ndotl;
    1.37  
    1.38  			Vector3 hdir = normalize(ldir + vdir);
    1.39  			float ndoth = positive(dot(norm, hdir));
    1.40 -			Vector3 specular = ks * lcol * pow(ndoth, roughness * 128.0);
    1.41 +			Vector3 specular = mtl.specular * lcol * pow(ndoth, mtl.roughness * 128.0);
    1.42  
    1.43 -			color = color + lerp(specular, diffuse, roughness);
    1.44 +			color = color + lerp(specular, diffuse, mtl.roughness);
    1.45  		}
    1.46  	}
    1.47  
    1.48 +	if(mtl.reflect > 1e-4 && iter < 6) {
    1.49 +		Ray reflray(pos, reflect(vdir, norm));
    1.50 +
    1.51 +		Vector3 rcol = ray_trace(reflray, iter + 1) * mtl.specular * mtl.reflect;
    1.52 +		color = color + rcol;
    1.53 +	}
    1.54 +
    1.55 +	if(mtl.refract > 1e-4 && iter < 6) {
    1.56 +		Ray refrray(pos, refract(vdir, norm,  ior));
    1.57 +
    1.58 +		Vector3 rcol = ray_trace(refrray, iter + 1) * mtl.specular * mtl.refract;
    1.59 +		color = color + rcol;
    1.60 +	}
    1.61 +
    1.62  	return color;
    1.63  }