-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathTracing.cpp
More file actions
80 lines (63 loc) · 2.59 KB
/
PathTracing.cpp
File metadata and controls
80 lines (63 loc) · 2.59 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
76
77
78
79
80
#include "PathTracing.h"
Eigen::Vector3f Graphics::PathTracing::Reflect(const Vector3f& vec, const Vector3f& normal)
{
return vec - 2 * vec.dot(normal) * normal;
}
bool Graphics::PathTracing::PathIntersect(const Ray& ray, const RenderObject::VectorObjects& objects, const RenderObject* excludeObject, float maxDistance,
float& distance, Vector3f& normal, RenderObject*& hitObject)
{
distance = maxDistance;
float currentDistance;
Vector3f currentNormal;
for (size_t i = 0; i < objects.size(); i++)
{
if (objects[i] != excludeObject &&
objects[i]->RayIntersect(ray, currentDistance, currentNormal) &&
currentDistance < distance)
{
distance = currentDistance;
normal = currentNormal;
hitObject = objects[i];
}
}
return distance != maxDistance;
}
Eigen::Vector3f Graphics::PathTracing::PathTrace(Ray ray, const RenderObject::VectorObjects& objects, float maxDistance, int maxReflections)
{
Vector3f light = Vector3f::Zero(); // sum of lights
Vector3f reflectivity = Vector3f::Ones();
float distance;
Vector3f normal;
Material* material;
Ray newRay{};
RenderObject* lastObject = nullptr;
Vector3f lightDir = Vector3f::Ones().normalized();
Ray lightRay{Vector3f::Zero(), lightDir};
for (int i = 0; i < maxReflections; i++)
{
if (PathIntersect(ray, objects, lastObject, maxDistance, distance, normal, /* out */ lastObject))
{
material = lastObject->material;
newRay.origin = ray.origin + distance * ray.direction;
newRay.direction = MathEigen::lerp(Reflect(ray.direction, normal), normal, material->roughness);
newRay.direction.normalize();
ray = newRay;
light += reflectivity.cwiseProduct(material->emittance);
reflectivity = reflectivity.cwiseProduct(material->reflectance);
// Calculate shadows
lightRay.origin = ray.origin + 0.1f * lightDir;
RenderObject* _l;
if (PathIntersect(lightRay, objects, nullptr, maxDistance, distance, normal, _l))
{
light = (light - Vector3f::Constant(0.25f));// .cwiseMax(Vector3f::Zero());
}
}
else
{
Vector3f skyboxColor = MathEigen::lerp(Vector3f::Zero().eval(), Vector3f(1, 1, 2), 0.5f * ray.direction.y() + 0.25f);
light += reflectivity.cwiseProduct(skyboxColor);
break;
}
}
return light;
}