-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcamerarays.cpp
123 lines (94 loc) · 2.4 KB
/
camerarays.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/* Follow code in Camera rays. */
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <limits>
#include <vector>
#include "stdint.h"
#include "string.h"
#include "geometry.h"
#include "vertexdata.h"
#ifndef M_PI
#define M_PI 3.14159265
#endif
using namespace std;
float clamp(const float &a, const float &b, const float &c)
{
return max(a, min(b, c));
}
class Object
{
public:
Object() {}
virtual ~Object() {}
};
class Light
{
public:
Light() {}
virtual ~Light() {}
};
uint32_t width = 640;
uint32_t height = 480;
float angleOfView = 90;
Vec3f castRay(
Vec3f &orig,
Vec3f &dir,
vector<unique_ptr<Object>> &objects,
vector<unique_ptr<Object>> &lights,
uint32_t depth
)
{
Vec3f hitColor = (dir + Vec3f(1)) * 0.5;
return hitColor;
}
void render (
vector<unique_ptr<Object>> &objects,
vector<unique_ptr<Object>> &lights
)
{
Mat44f cameraToWorld;
float imageAspectRatio = width / (float)height;
float scale = tan(angleOfView / 2 * M_PI / 180);
const float kInfinity = std::numeric_limits<float>::max();
Vec3f minWorld(kInfinity), maxWorld(-kInfinity);
Vec3f *buffer = new Vec3f[width * height];
memset(buffer, 0, width * height);
Vec3f orig;
cameraToWorld.multiple(Vec3f(0), orig);
for (uint32_t j = 0; j < height; j++)
{
for (uint32_t i = 0; i < width; i++)
{
/* NDC */
float x = (2 * (i + 0.5) / (float)width - 1) * imageAspectRatio * scale;
float y = (2 * (j + 0.5) / (float)height - 1) * scale;
Vec3f dir;
cameraToWorld.multiple(Vec3f(x, y, -1), dir);
dir.normalize();
buffer[j * width + i] = castRay(orig, dir, objects, lights, 0);
}
}
// save to file
std::ofstream ofs;
ofs.open("./camerarays.ppm");
ofs << "P5\n" << width << " " << height << "\n255\n";
for (uint32_t i = 0; i < height * width; ++i) {
char r = (char)(255 * clamp(0, 1, buffer[i].x));
char g = (char)(255 * clamp(0, 1, buffer[i].y));
char b = (char)(255 * clamp(0, 1, buffer[i].z));
ofs << r << g << b;
}
ofs.write((char*)buffer, width * height);
ofs.close();
delete [] buffer;
}
int main()
{
vector<unique_ptr<Object>> objects;
vector<unique_ptr<Object>> lights;
render(objects, lights);
}