-
Notifications
You must be signed in to change notification settings - Fork 0
/
tracing.cpp
93 lines (75 loc) · 3 KB
/
tracing.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
#include "tracing.h"
#include <limits>
char clampToByte(double value) {
return (char)fmax(0, fmin(value, 255));
}
void traceRay(Scene& scene, Ray& ray, int bounceCount, Eigen::Array3d& outColor) {
double t_min = std::numeric_limits<double>::max();
Object* obj = nullptr;
int objSubId, tempSubId;
for (Object* o : scene.objects) {
// Check intersection with all objects in scene
double t = o->calcIntersectionParameter(ray, tempSubId);
if (t < t_min) {
// Store closest object
t_min = t;
obj = o;
objSubId = tempSubId;
}
}
if (obj == nullptr) {
outColor = scene.backgroundColor;
} else {
// Intersection point
Eigen::Vector3d x = ray.pointAt(t_min);
// Normal
Eigen::Vector3d normal;
obj->getNormalAtPoint(x, objSubId, normal);
// Ambient shading
outColor = obj->material->calcAmbient(scene.ambientLight);
for (PointLight& l : scene.pointLights) {
// Shadow ray
Ray s = Ray::Through(x + (l.pos - x).normalized() * scene.shadowRayEpsilon, l.pos);
double distanceToL = (l.pos - x).norm();
bool hasShadow = false;
for (Object* p : scene.objects) {
// Check intersection with all objects in scene
double t = p->calcIntersectionParameter(s, tempSubId);
if (t < std::numeric_limits<double>::max()
&& (s.pointAt(t) - x).norm() < distanceToL) {
// Ray intersects an object before the light
hasShadow = true;
break;
}
}
if (!hasShadow) {
// Diffuse and Specular shading
outColor += obj->material->calcDiffuseSpecular(x, normal, l, -(ray.direction()));
}
}
// Reflections
if (!obj->material->mirrorReflectance.isZero() && bounceCount < scene.maxRecursionDepth) {
// Direction: d + 2(-d.n)n
Eigen::Vector3d d = (ray.direction() + ((-ray.direction()).dot(normal)) * normal).normalized();
Ray r(x + d * scene.shadowRayEpsilon, d);
Eigen::Array3d reflectedColor;
traceRay(scene, r, bounceCount + 1, reflectedColor);
// Mirror shading
outColor += obj->material->calcMirror(reflectedColor);
}
}
}
void renderImage(Scene& scene, SceneImage& sceneImage) {
Ray* ray;
Eigen::Array3d color;
for (int i = 0; i < scene.camera.width; i++) {
for (int j = 0; j < scene.camera.height; j++) {
ray = scene.camera.constructRayThroughPixel(i, j);
// Primary rays start with zero bounce count
traceRay(scene, *ray, 0, color);
sceneImage.buffer[i][j * 3] = clampToByte(color[0]);
sceneImage.buffer[i][j * 3 + 1] = clampToByte(color[1]);
sceneImage.buffer[i][j * 3 + 2] = clampToByte(color[2]);
}
}
}