forked from paulo-pagliosa/Ds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRayTracer.cpp
363 lines (308 loc) · 9.79 KB
/
RayTracer.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
//[]---------------------------------------------------------------[]
//| |
//| Copyright (C) 2018, 2023 Paulo Pagliosa. |
//| |
//| This software is provided 'as-is', without any express or |
//| implied warranty. In no event will the authors be held liable |
//| for any damages arising from the use of this software. |
//| |
//| Permission is granted to anyone to use this software for any |
//| purpose, including commercial applications, and to alter it and |
//| redistribute it freely, subject to the following restrictions: |
//| |
//| 1. The origin of this software must not be misrepresented; you |
//| must not claim that you wrote the original software. If you use |
//| this software in a product, an acknowledgment in the product |
//| documentation would be appreciated but is not required. |
//| |
//| 2. Altered source versions must be plainly marked as such, and |
//| must not be misrepresented as being the original software. |
//| |
//| 3. This notice may not be removed or altered from any source |
//| distribution. |
//| |
//[]---------------------------------------------------------------[]
//
// OVERVIEW: RayTracer.cpp
// ========
// Source file for simple ray tracer.
//
// Author: Paulo Pagliosa
// Last revision: 30/07/2023
#include "graphics/Camera.h"
#include "utils/Stopwatch.h"
#include "RayTracer.h"
#include <iostream>
using namespace std;
namespace cg
{ // begin namespace cg
namespace
{ // begin namespace
inline void
printElapsedTime(const char* s, Stopwatch::ms_time time)
{
printf("%sElapsed time: %g ms\n", s, time);
}
} // end namespace
/////////////////////////////////////////////////////////////////////
//
// RayTracer implementation
// =========
RayTracer::RayTracer(SceneBase& scene, Camera& camera):
Renderer{scene, camera},
_maxRecursionLevel{6},
_minWeight{minMinWeight}
{
// do nothing
}
void
RayTracer::update()
{
// Delete current BVH before creating a new one
_bvh = nullptr;
PrimitiveBVH::PrimitiveArray primitives;
auto np = uint32_t(0);
primitives.reserve(_scene->actorCount());
for (auto actor : _scene->actors())
if (actor->visible)
{
auto p = actor->mapper()->primitive();
assert(p != nullptr);
if (p->canIntersect())
{
primitives.push_back(p);
np++;
}
}
_bvh = new PrimitiveBVH{std::move(primitives)};
}
void
RayTracer::render()
{
throw std::runtime_error("RayTracer::render() invoked");
}
void
RayTracer::renderImage(Image& image)
{
Stopwatch timer;
update();
timer.start();
{
const auto& m = _camera->cameraToWorldMatrix();
// VRC axes
_vrc.u = m[0];
_vrc.v = m[1];
_vrc.n = m[2];
}
// init auxiliary mapping variables
auto w = image.width(), h = image.height();
setImageSize(w, h);
_Iw = math::inverse(float(w));
_Ih = math::inverse(float(h));
{
auto wh = _camera->windowHeight();
if (w >= h)
_Vw = (_Vh = wh) * w * _Ih;
else
_Vh = (_Vw = wh) * h * _Iw;
}
// init pixel ray
float F, B;
_camera->clippingPlanes(F, B);
if (_camera->projectionType() == Camera::Perspective)
{
// distance from the camera position to a frustum back corner
auto z = B / F * 0.5f;
B = vec3f{_Vw * z, _Vh * z, B}.length();
}
_pixelRay.tMin = F;
_pixelRay.tMax = B;
_pixelRay.set(_camera->position(), -_vrc.n);
_numberOfRays = _numberOfHits = 0;
scan(image);
auto et = timer.time();
std::cout << "\nNumber of rays: " << _numberOfRays;
std::cout << "\nNumber of hits: " << _numberOfHits;
printElapsedTime("\nDONE! ", et);
}
void
RayTracer::setPixelRay(float x, float y)
//[]---------------------------------------------------[]
//| Set pixel ray |
//| @param x coordinate of the pixel |
//| @param y cordinates of the pixel |
//[]---------------------------------------------------[]
{
auto p = imageToWindow(x, y);
switch (_camera->projectionType())
{
case Camera::Perspective:
_pixelRay.direction = (p - _camera->nearPlane() * _vrc.n).versor();
break;
case Camera::Parallel:
_pixelRay.origin = _camera->position() + p;
break;
}
}
void
RayTracer::scan(Image& image)
{
ImageBuffer scanLine{_viewport.w, 1};
for (auto j = 0; j < _viewport.h; j++)
{
auto y = (float)j + 0.5f;
printf("Scanning line %d of %d\r", j + 1, _viewport.h);
for (auto i = 0; i < _viewport.w; i++)
scanLine[i] = shoot((float)i + 0.5f, y);
image.setData(0, j, scanLine);
}
}
Color
RayTracer::shoot(float x, float y)
//[]---------------------------------------------------[]
//| Shoot a pixel ray |
//| @param x coordinate of the pixel |
//| @param y cordinates of the pixel |
//| @return RGB color of the pixel |
//[]---------------------------------------------------[]
{
// set pixel ray
setPixelRay(x, y);
// trace pixel ray
Color color = trace(_pixelRay, 0, 1);
// adjust RGB color
if (color.r > 1.0f)
color.r = 1.0f;
if (color.g > 1.0f)
color.g = 1.0f;
if (color.b > 1.0f)
color.b = 1.0f;
// return pixel color
return color;
}
Color
RayTracer::trace(const Ray3f& ray, uint32_t level, float weight)
//[]---------------------------------------------------[]
//| Trace a ray |
//| @param the ray |
//| @param recursion level |
//| @param ray weight |
//| @return color of the ray |
//[]---------------------------------------------------[]
{
if (level > _maxRecursionLevel)
return Color::black;
++_numberOfRays;
Intersection hit;
return intersect(ray, hit) ? shade(ray, hit, level, weight) : background();
}
inline constexpr auto
rt_eps()
{
return 1e-4f;
}
bool
RayTracer::intersect(const Ray3f& ray, Intersection& hit)
//[]---------------------------------------------------[]
//| Ray/object intersection |
//| @param the ray (input) |
//| @param information on intersection (output) |
//| @return true if the ray intersects an object |
//[]---------------------------------------------------[]
{
hit.object = nullptr;
hit.distance = ray.tMax;
return _bvh->intersect(ray, hit) ? ++_numberOfHits : false;
}
inline auto
maxRGB(const Color& c)
{
return math::max(math::max(c.r, c.g), c.b);
}
Color
RayTracer::shade(const Ray3f& ray,
Intersection& hit,
uint32_t level,
float weight)
//[]---------------------------------------------------[]
//| Shade a point P |
//| @param the ray (input) |
//| @param information on intersection (input) |
//| @param recursion level |
//| @param ray weight |
//| @return color at point P |
//[]---------------------------------------------------[]
{
auto primitive = (Primitive*)hit.object;
assert(nullptr != primitive);
auto N = primitive->normal(hit);
const auto& V = ray.direction;
auto NV = N.dot(V);
// Make sure "real" normal is on right side
if (NV > 0)
N.negate(), NV = -NV;
auto R = V - (2 * NV) * N; // reflection vector
// Start with ambient lighting
auto m = primitive->material();
auto color = _scene->ambientLight * m->ambient;
auto P = ray(hit.distance);
// Compute direct lighting
for (auto light : _scene->lights())
{
// If the light is turned off, then continue
if (!light->isTurnedOn())
continue;
vec3f L;
float d;
// If the point P is out of the light range (for finite
// point light or spotlight), then continue
if (!light->lightVector(P, L, d))
continue;
auto NL = N.dot(L);
// If light vector is backfaced, then continue
if (NL <= 0)
continue;
auto lightRay = Ray3f{P + L * rt_eps(), L};
lightRay.tMax = d;
++_numberOfRays;
// If the point P is shadowed, then continue
if (shadow(lightRay))
continue;
auto lc = light->lightColor(d);
color += lc * m->diffuse * NL;
if (m->shine <= 0 || (d = R.dot(L)) <= 0)
continue;
color += lc * m->spot * pow(d, m->shine);
}
// Compute specular reflection
if (m->specular != Color::black)
{
weight *= maxRGB(m->specular);
if (weight > _minWeight && level < _maxRecursionLevel)
{
auto reflectionRay = Ray3f{P + R * rt_eps(), R};
color += m->specular * trace(reflectionRay, level + 1, weight);
}
}
return color;
}
Color
RayTracer::background() const
//[]---------------------------------------------------[]
//| Background |
//| @return background color |
//[]---------------------------------------------------[]
{
return _scene->backgroundColor;
}
bool
RayTracer::shadow(const Ray3f& ray)
//[]---------------------------------------------------[]
//| Verifiy if ray is a shadow ray |
//| @param the ray (input) |
//| @return true if the ray intersects an object |
//[]---------------------------------------------------[]
{
return _bvh->intersect(ray) ? ++_numberOfHits : false;
}
} // end namespace cg