Skip to content
Permalink
Browse files

diffuse lighting

  • Loading branch information
ssloy committed Jan 20, 2019
1 parent c19c430 commit 9a728fff2bbebb1eedd86e1ac89f657d43191609
Showing with 19 additions and 5 deletions.
  1. BIN out.jpg
  2. +19 −5 tinyraytracer.cpp
BIN +12.9 KB (140%) out.jpg
Binary file not shown.
@@ -5,6 +5,12 @@
#include <vector>
#include "geometry.h"

struct Light {
Light(const Vec3f &p, const float &i) : position(p), intensity(i) {}
Vec3f position;
float intensity;
};

struct Material {
Material(const Vec3f &color) : diffuse_color(color) {}
Material() : diffuse_color() {}
@@ -46,18 +52,23 @@ bool scene_intersect(const Vec3f &orig, const Vec3f &dir, const std::vector<Sphe
return spheres_dist<1000;
}

Vec3f cast_ray(const Vec3f &orig, const Vec3f &dir, const std::vector<Sphere> &spheres) {
Vec3f cast_ray(const Vec3f &orig, const Vec3f &dir, const std::vector<Sphere> &spheres, const std::vector<Light> &lights) {
Vec3f point, N;
Material material;

if (!scene_intersect(orig, dir, spheres, point, N, material)) {
return Vec3f(0.2, 0.7, 0.8); // background color
}

return material.diffuse_color;
float diffuse_light_intensity = 0;
for (size_t i=0; i<lights.size(); i++) {
Vec3f light_dir = (lights[i].position - point).normalize();
diffuse_light_intensity += lights[i].intensity * std::max(0.f, light_dir*N);
}
return material.diffuse_color * diffuse_light_intensity;
}

void render(const std::vector<Sphere> &spheres) {
void render(const std::vector<Sphere> &spheres, const std::vector<Light> &lights) {
const int width = 1024;
const int height = 768;
const int fov = M_PI/2.;
@@ -69,7 +80,7 @@ void render(const std::vector<Sphere> &spheres) {
float x = (2*(i + 0.5)/(float)width - 1)*tan(fov/2.)*width/(float)height;
float y = -(2*(j + 0.5)/(float)height - 1)*tan(fov/2.);
Vec3f dir = Vec3f(x, y, -1).normalize();
framebuffer[i+j*width] = cast_ray(Vec3f(0,0,0), dir, spheres);
framebuffer[i+j*width] = cast_ray(Vec3f(0,0,0), dir, spheres, lights);
}
}

@@ -94,7 +105,10 @@ int main() {
spheres.push_back(Sphere(Vec3f( 1.5, -0.5, -18), 3, red_rubber));
spheres.push_back(Sphere(Vec3f( 7, 5, -18), 4, ivory));

render(spheres);
std::vector<Light> lights;
lights.push_back(Light(Vec3f(-20, 20, 20), 1.5));

render(spheres, lights);

return 0;
}

0 comments on commit 9a728ff

Please sign in to comment.
You can’t perform that action at this time.