-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
75 lines (60 loc) · 2.52 KB
/
Copy pathmain.cpp
File metadata and controls
75 lines (60 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include "vec3.h"
#include "color.h"
#include "ray.h"
#include "hittable.h"
#include "sphere.h"
#include "hittable_list.h"
#include "rtweekend.h"
#include<iostream>
color ray_color(const ray& r, const hittable& world){
//Check if the ray hits any object in the world
hit_record rec;
if(world.hit(r,0,infinity,rec)){
return 0.5* (rec.normal + color(1,1,1));
}
vec3 unit_direction= unit_vector(r.direction());
auto a= 0.5*(unit_direction.y()+1.0); // 0 means the ray is pointing down, 1 means the ray is pointing up
return (1.0-a) * color(1.0,1.5,1.0) + a*color(0.5,0.7,1.0); // smooth gradient background with white and light blue colors
}
int main(){
// Image
auto ratio= 16.0/9.0;
int image_width= 800;
//Calculate height based on aspect ratio
int image_height= int(image_width/ratio);
image_height= (image_height<1)? 1 : image_height; // ensure height is at least 1
//world
hittable_list world;
world.add(make_shared<sphere>(point3(0,0,-1),0.5)); //makes sphere at center
world.add(make_shared<sphere>(point3(0,-100.5,-1),100)); //creates ground sphere
world.add(make_shared<sphere>(point3(-0.5,0,-1),0.3)); //makes sphere at left
world.add(make_shared<sphere>(point3(0.5,0,-1),0.3)); //makes sphere at right
//Camera
auto focal_length= 1.0;
auto viewport_height= 2.0;
auto viewport_width= viewport_height* (double(image_width)/image_height);
auto camera_center= point3(0,0,0);
//Calculate the vectors across the horizonal and down the vertical viewport edges
auto viewport_u= vec3(viewport_width,0,0);
auto viewport_v= vec3(0,-viewport_height,0);
//Calculate the horizonal and vertical delta vectors from pixel to pixel
auto pixel_delta_u= viewport_u/image_width;
auto pixel_delta_v= viewport_v/image_height;
//Calculate the location of upper left pixel
auto viewport_upper_left= camera_center - vec3(0, 0, focal_length) - viewport_u/2 - viewport_v/2;
auto pixel00_loc = viewport_upper_left + 0.5 * (pixel_delta_u + pixel_delta_v);
//Render the image
std::cout<<"P3\n"<<image_width<<" "<<image_height<<"\n255\n";
for(int j=0;j<image_height;j++){
std::clog<<"Scanlines remaining: "<<image_height-j<<"\n"<<std::flush;
for(int i=0;i<image_width;i++){
auto pixel_center= pixel00_loc + (i*pixel_delta_u) + (j*pixel_delta_v);
auto ray_direction= pixel_center - camera_center;
ray r(camera_center, ray_direction);
color pixel_color= ray_color(r,world);
write_color(std::cout, pixel_color);
}
}
std::clog<<"\rDone. \n";
return 0;
}