Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void part2()
- {
- std::cout << "Part 2: Simple ray tracer, one sphere with orthographic projection" << std::endl;
- const std::string filename("part2.png");
- MatrixXd C = MatrixXd::Zero(800,800); // Store the color
- MatrixXd A = MatrixXd::Zero(800,800); // Store the alpha mask
- // The camera is orthographic, pointing in the direction -z and covering the unit square (-1,1) in x and y
- Vector3d origin(-1,1,1);
- Vector3d x_displacement(2.0/C.cols(),0,0);
- Vector3d y_displacement(0,-2.0/C.rows(),0);
- // Single light source
- const Vector3d light_position(-1,1,1);
- for (unsigned i=0;i<C.cols();i++)
- {
- for (unsigned j=0;j<C.rows();j++)
- {
- // Prepare the ray
- Vector3d ray_origin = origin + double(i)*x_displacement + double(j)*y_displacement;
- Vector3d ray_direction = RowVector3d(0,0,-1);
- // Intersect with the sphere
- // NOTE: this is a special case of a sphere centered in the origin and for orthographic rays aligned with the z axis
- Vector2d ray_on_xy(ray_origin(0),ray_origin(1));
- const double sphere_radius = 0.9;
- if (ray_on_xy.norm()<sphere_radius)
- {
- // The ray hit the sphere, compute the exact intersection point
- Vector3d ray_intersection(ray_on_xy(0),ray_on_xy(1),sqrt(sphere_radius*sphere_radius - ray_on_xy.squaredNorm()));
- // Compute normal at the intersection point
- Vector3d ray_normal = ray_intersection.normalized();
- // Simple diffuse model
- C(i,j) = (light_position-ray_intersection).normalized().transpose() * ray_normal;
- // Clamp to zero
- C(i,j) = max(C(i,j),0.);
- // Disable the alpha mask for this pixel
- A(i,j) = 1;
- }
- }
- }
- // Save to png
- write_matrix_to_png(C,C,C,A,filename);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement