Skip to content

Instantly share code, notes, and snippets.

@Yatekii
Created January 19, 2014 17:00
Show Gist options
  • Save Yatekii/8507566 to your computer and use it in GitHub Desktop.
Save Yatekii/8507566 to your computer and use it in GitHub Desktop.
Color Scene::TraceRay (const Ray& ray, double rIndex, int iterations) const{
Color pixel = Black;
Intersection intersection = Intersect(ray);
if (intersection.t != -1) {
pixel += ambientColor * intersection.shape->getMaterial()->getAmbient();
//reflection ray
Vector reflectionDirection = ray.direction - 2 * Dot(ray.direction, intersection.normal) * intersection.normal;
Ray reflectedRay(intersection.location + reflectionDirection * 0.000001, reflectionDirection);
for(int i = 0; i < lights.size(); i++){
Vector light = *lights[i];
//shadow ray
Vector shadowDirection = light - intersection.location;
Ray shadowRay(intersection.location + shadowDirection * 0.000001, shadowDirection);
//if not in shadow
Intersection shadowIntersection = Intersect(shadowRay);
if (shadowIntersection.t == -1) {
//diffuse part
double diffuseFactor = Dot(intersection.normal, shadowRay.direction);
if (diffuseFactor > 0)
pixel += lightColor * intersection.shape->getMaterial()->getDiffuse() * diffuseFactor;
//specular part
Vector R = shadowRay.direction - 2 * Dot(shadowRay.direction, intersection.normal) * intersection.normal;
double specularFactor = Dot(ray.direction, R);
if (specularFactor > 0) {
pixel += lightColor * intersection.shape->getMaterial()->getSpecular() * pow(specularFactor, intersection.shape->getMaterial()->getShininess());
}
}
}
if (intersection.shape->getMaterial()->getReflection() > 0 && iterations > 0) {
pixel += intersection.shape->getMaterial()->getSpecular() * TraceRay(reflectedRay, intersection.shape->getMaterial()->getRefraction(), --iterations) * intersection.shape->getMaterial()->getReflection();
}
}
else
pixel += backgroundColor;
return pixel;
//MASTER ALGORITHM HERE!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment