-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCRay.cpp
More file actions
5275 lines (4665 loc) · 252 KB
/
CRay.cpp
File metadata and controls
5275 lines (4665 loc) · 252 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
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
File: CRay.cpp
Description: CRay Source File
Authors:
Kostas Vardis
Implementation file of the engine.
*/
// global includes //////////////////////////////
// basic global defines
#ifdef _WIN32
#include <windows.h> // used for OutputDebugString and isDebuggerPresent
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
#endif
// add this for C++11 support
#if !defined _MSC_VER || _MSC_VER < 1910
//#include "Global/Compatibility.h"
#endif
#if defined (_WIN32) && defined (_MSC_VER)
#define WINMSVC
#endif
#if defined (_WIN32) && defined (_MSC_VER) && !defined(NDEBUG)
#define WINMSVCDEBUG
#endif
#ifdef WINMSVC
#define _DISABLE_EXTENDED_ALIGNED_STORAGE //VS warning
#endif
#ifdef WINMSVCDEBUG
#define CR_BREAK { if (IsDebuggerPresent()) __debugbreak(); }
#else
#define CR_BREAK
#endif
#define PRAGMA_REMINDER __FILE__ ": Reminder: "
#include <cstring>
#define SOURCEPATH_LENGTH strlen(SOURCEPATH) + 1
#define SOURCE_FILENAME &__FILE__[SOURCEPATH_LENGTH]
#define FILE_NAME(name) (std::string(name).find(SOURCEPATH) != std::string::npos) ? SOURCE_FILENAME : __FILE__
// the following defines are for asserts, popup dialogs and log messages
// asserts
#define CRAY_ASSERT_IF_FALSE_MSG(expr, fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_ASSERT)){if (!static_cast<bool>(expr)){RAYENGINE::pushMessage(CR_LOGGER_ASSERT, "Assert: %s (%d): %s: " fmt NEWLINESTR , FILE_NAME(__FILE__), __LINE__, #expr, ##__VA_ARGS__); flushLastMessage(); CR_BREAK}}}
#define CRAY_ASSERT_IF_FALSE(expr) {if(RAYENGINE::isLogLevel(CR_LOGGER_ASSERT)){if (!static_cast<bool>(expr)){RAYENGINE::pushMessage(CR_LOGGER_ASSERT, "Assert: %s (%d): %s: " NEWLINESTR , FILE_NAME(__FILE__), __LINE__, #expr); flushLastMessage(); CR_BREAK}}}
#define CRAY_ASSERT_ALWAYS(expr) {if(RAYENGINE::isLogLevel(CR_LOGGER_ASSERT)){RAYENGINE::pushMessage(CR_LOGGER_ASSERT, "Assert: %s (%d): %s: " NEWLINESTR , FILE_NAME(__FILE__), __LINE__, #expr); flushLastMessage(); CR_BREAK}}
#define CRAY_ASSERT_ALWAYS_MSG(expr, fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_ASSERT)){RAYENGINE::pushMessage(CR_LOGGER_ASSERT, "Assert: %s (%d): %s: " fmt NEWLINESTR , FILE_NAME(__FILE__), __LINE__, #expr, ##__VA_ARGS__); flushLastMessage(); CR_BREAK}}
//#define EYE_SPACE_SHADING
// These should be only enabled inside code for debugging purposes
//#define ENABLE_FORCE_LOG // prints verbose log information regardless of Log filter
#ifdef ENABLE_FORCE_LOG
#define CRAY_FORCE_LOG(fmt, ...) {RAYENGINE::pushMessage(CR_LOGGER_DEBUG, fmt NEWLINESTR, ##__VA_ARGS__); flushLastMessage();}
#else
#define CRAY_FORCE_LOG(fmt, ...)
#endif
#define ENABLE_DEBUG_CURRENT_PIXEL // allows CRAY_DEBUG to print values for selected pixel (set via CR_debug_setTestPixel)
#ifdef ENABLE_DEBUG_CURRENT_PIXEL
#define CRAY_DEBUG_PIXEL(fmt, ...) {if(RAYENGINE::isValidDebugPixel()) {pushMessage(CR_LOGGER_DEBUG, "Debug: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__); flushLastMessage();}}
#else
#define CRAY_DEBUG_PIXEL(fmt, ...)
#endif
#define NEWLINESTR "\n"
#ifndef NDEBUG
#define CRAY_INFO(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_INFO)) {RAYENGINE::pushMessage(CR_LOGGER_INFO, "Info: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__);}}
#define CRAY_WARNING(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_WARNING)) {RAYENGINE::pushMessage(CR_LOGGER_WARNING, "Warning: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__);}}
#define CRAY_ERROR(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_ERROR)) {RAYENGINE::pushMessage(CR_LOGGER_ERROR, "Error: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__);}}
#define CRAY_DEBUG(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_DEBUG)) {RAYENGINE::pushMessage(CR_LOGGER_DEBUG, "Debug: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__);}}
#else
#define CRAY_INFO(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_INFO)) {RAYENGINE::pushMessage(CR_LOGGER_INFO, "Info: " fmt NEWLINESTR, ##__VA_ARGS__);}}
#define CRAY_WARNING(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_WARNING)) {RAYENGINE::pushMessage(CR_LOGGER_WARNING, "Warning: " fmt NEWLINESTR, ##__VA_ARGS__);}}
#define CRAY_ERROR(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_ERROR)) {RAYENGINE::pushMessage(CR_LOGGER_ERROR, "Error: " fmt NEWLINESTR, ##__VA_ARGS__);}}
#define CRAY_DEBUG(fmt, ...) {if(RAYENGINE::isLogLevel(CR_LOGGER_DEBUG)) {RAYENGINE::pushMessage(CR_LOGGER_DEBUG, "Debug: %s(): " fmt NEWLINESTR, __func__, ##__VA_ARGS__);}}
#endif
#define CHECK_RETURN_IF_UNINITIALIZED_ENGINE() {if(RAYENGINE::s_global_engine == nullptr) { CRAY_WARNING("Engine has not been initialized. Call CR_init."); return; }}
#define CHECK_RETURN_IF_UNINITIALIZED_SCENE() {if(RAYENGINE::s_global_scene == nullptr) { CRAY_WARNING("Scene empty. Skipping."); return; }}
#define CHECK_RETURN_VALUE_IF_UNINITIALIZED_ENGINE(x) {if(RAYENGINE::s_global_engine == nullptr) { CRAY_WARNING("Engine has not been initialized. Call CR_init."); return x; }}
#define CHECK_RETURN_IF_STARTED_ENGINE() {if(RAYENGINE::s_global_engine->m_started) { CRAY_WARNING("Rendering in progress. Skipping."); return; }}
#define CHECK_RETURN_VALUE_IF_STARTED_ENGINE(x) {if(RAYENGINE::s_global_engine->m_started) { CRAY_WARNING("Rendering in progress. Skipping."); return x; }}
#define CHECK_RETURN_IF_NOT_STARTED_ENGINE() {if(!RAYENGINE::s_global_engine->m_started) { CRAY_WARNING("Rendering has not started. Skipping."); return; }}
// includes ////////////////////////////////////////
#if defined(_WIN32)
#ifndef NOMINMAX
#define NOMINMAX
#endif
#endif
#include <cstdarg>
#include <random>
#include <thread>
#include <algorithm>
#include <queue>
#include <vector>
#include <array>
#include <stack>
#include <cstring>
#include <mutex>
#include <future>
#include <memory>
#include <map>
#include <sstream>
#include <iomanip>
#include <string>
#include "CRay.h"
#define GLM_FORCE_SILENT_WARNINGS // disable some GLM warnings
#include "glm/vec3.hpp"
#include "glm/vec2.hpp"
#include "glm/common.hpp"
#include "glm/exponential.hpp"
#include <glm/geometric.hpp>
#include <glm/gtc/constants.hpp>
#include <glm/gtc/epsilon.hpp>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/transform.hpp>
#include <glm/glm.hpp>
#ifdef DOUBLE_PRECISION
#define mat4 dmat4
#define mat4x4 dmat4x4
#define vec4 dvec4
#define vec3 dvec3
#define vec2 dvec2
#define isDouble true
#define FLOAT_ZERO_NEXT 1.401298464e-45
#define FLOAT_ONE_BEFORE 9.999999404e-01
#define FLOAT_MAX_FULL_INTEGER 0x20000000000000ull // 9007199254740992 or 2^53
#define FLOAT_MAX_FULL_INTEGER_MINUS_ONE 0x1fffffffffffffull // 9007199254740991 2^53 - 1
#else
#define isDouble false
#define FLOAT_ZERO_NEXT 1.401298464e-45
#define FLOAT_ONE_BEFORE 9.999999404e-01
#define FLOAT_MAX_FULL_INTEGER 0x1000000u // 16777216 or 2^24
#define FLOAT_MAX_FULL_INTEGER_MINUS_ONE 0x00FFFFFFu // 16777215 or 2^24-1
#endif
#define FLOAT_TOLERANCE_10 cr_float(1.0e-10) // 0.0000000001
#define FLOAT_TOLERANCE_6 cr_float(1.0e-06) // 0.000001
#define FLOAT_TOLERANCE_5 cr_float(1.0e-05) // 0.00001
#define FLOAT_TOLERANCE_4 cr_float(1.0e-04) // 0.0001
#define FLOAT_TOLERANCE_3 cr_float(1.0e-03) // 0.001
#define FLOAT_TOLERANCE_2 cr_float(1.0e-02) // 0.01
#define FLOAT_TOLERANCE_1 cr_float(1.0e-01) // 0.1
#define FLOAT_TOLERANCE FLOAT_TOLERANCE_6
#define GLOBAL_RAY_EPSILON FLOAT_TOLERANCE_6
namespace RAYENGINE {
// forward declarations and defines
void flushLastMessage();
void pushMessage(CRAY_LOGGERENTRY type, const char* fmt, ...);
bool isLogLevel(enum CRAY_LOGGERENTRY type);
bool isValidDebugPixel();
// Helper functions
bool isValidFloat(cr_float x) {
bool valid = !glm::isnan(x) && !glm::isinf(x);
CRAY_ASSERT_IF_FALSE_MSG(valid, "Invalid float value: %f", x)
return valid;
}
bool isValidVec3(const glm::vec3& x) {
bool valid = !glm::any(glm::isnan(x)) && !glm::any(glm::isinf(x));
CRAY_ASSERT_IF_FALSE_MSG(valid, "Invalid vec3 values: %f, %f, %f", x.x, x.y, x.z)
return valid;
}
glm::vec3 transformPoint(const glm::mat4x4& mat, const glm::vec3& point) { return mat * glm::vec4(point, 1); }
glm::vec3 transformVector(const glm::mat4x4& mat, const glm::vec3& point) { return mat * glm::vec4(point, 0); }
void updateRunningSum(double& old_value, double new_value, double iterations) {
old_value = old_value + ((new_value - old_value) / iterations);
}
template <typename T>
std::string NumberToString(const T& Number, int32_t decimal_precision = 2) {
std::stringstream ss;
ss << std::setprecision(decimal_precision) << std::fixed << Number;
return ss.str();
}
template <typename T>
std::string convertToCapacitySizeString(const T& size, int32_t decimal_precision = 2) {
std::string res = "";
double byte = sizeof(char);
double KB = 1024 * byte;
double MB = 1024 * KB;
double GB = 1024 * MB;
double s = static_cast<double>(size);
if (s > GB) {
s /= GB;
res = NumberToString(s, decimal_precision).append("GB");
}
else if (s > MB) {
s /= MB;
res = NumberToString(s, decimal_precision).append("MB");
}
else if (s > KB) {
s /= KB;
res = NumberToString(s, decimal_precision).append("KB");
}
else {
s /= byte;
res = NumberToString(s, 0).append("b");
}
return res;
}
template <typename T>
std::string convertToTimeString(const T& time_ms) {
std::string res = "";
double seconds = 1000;
double minutes = seconds * 60;
double hours = minutes * 60;
double t = static_cast<double>(time_ms);
if (t > hours) {
int32_t h = static_cast<int32_t>(t / hours);
t -= h * hours;
res += NumberToString(h, 0).append(" hour") + ((h > 1) ? "s" : "");
}
if (!res.empty() || t > minutes) {
int32_t m = static_cast<int32_t>(t / minutes);
t -= m * minutes;
res += (res.empty() ? res : ", ") + NumberToString(m, 0).append(" min") + ((m > 1) ? "s" : "");
}
if (!res.empty() || t > seconds) {
int32_t s = static_cast<int32_t>(t / seconds);
t -= s * seconds;
res += (res.empty() ? res : ", ") + NumberToString(s, 0).append(" sec") + ((s > 1) ? "s" : "");
}
if (!res.empty() || t > 0) {
res += (res.empty() ? res : ", ") + NumberToString(t, 2).append(" ms");
}
return res;
}
// source: https://refractiveindex.info
// sampled at wavelength 526nm
static std::map<CRAY_IOR_DIELECTRICS, cr_float> dielectrics_ior = {
// plastics
{CR_DIELECTRIC_Acrylic_glass, 1.4941},
{CR_DIELECTRIC_Polystyrene, 1.5992},
{CR_DIELECTRIC_Polycarbonate, 1.5926},
// crystals
{CR_DIELECTRIC_Diamond, 2.4258},
{CR_DIELECTRIC_Ice, 1.3119},
{CR_DIELECTRIC_Sapphire, 1.7721},
// glass
{CR_DIELECTRIC_Crown_Glass_bk7, 1.5198},
{CR_DIELECTRIC_Soda_lime_glass, 1.5264},
// liquids
{CR_DIELECTRIC_Water_25C, 1.3340},
{CR_DIELECTRIC_Acetone_20C, 1.3616},
// gasses
{CR_DIELECTRIC_Air, 1.00027834},
{CR_DIELECTRIC_Carbon_dioxide, 1.00045113}
};
// source: https://refractiveindex.info
// sampled at wavelengths 645nm, 526nm, 444nm
static std::map<enum CRAY_IOR_CONDUCTORS, cr_vec3> conductors_ior = {
{CR_CONDUCTOR_Alluminium_Al, cr_vec3{1.3211, 0.88045, 0.59765}},
{CR_CONDUCTOR_Brass_CuZn, cr_vec3{0.44400, 0.58460, 1.1522}},
{CR_CONDUCTOR_Copper_Cu, cr_vec3{0.28046, 0.85418, 1.3284}},
{CR_CONDUCTOR_Gold_Au, cr_vec3{0.18601, 0.59580, 1.4120}},
{CR_CONDUCTOR_Iron_Fe, cr_vec3{2.9067, 2.8761, 2.5515}},
{CR_CONDUCTOR_Silver_Ag, cr_vec3{0.15865, 0.14215, 0.13534}}
};
static std::map<enum CRAY_IOR_CONDUCTORS, cr_vec3> conductors_k = {
{ CR_CONDUCTOR_Alluminium_Al, cr_vec3{7.4178, 6.1455, 5.2337} },
{ CR_CONDUCTOR_Brass_CuZn, cr_vec3{3.6520, 2.5264, 1.8098} },
{ CR_CONDUCTOR_Copper_Cu, cr_vec3{3.5587, 2.4518, 2.2949} },
{ CR_CONDUCTOR_Gold_Au, cr_vec3{3.3762, 2.0765, 1.7827} },
{ CR_CONDUCTOR_Iron_Fe, cr_vec3{3.0833, 2.9136, 2.7490} },
{ CR_CONDUCTOR_Silver_Ag, cr_vec3{3.8930, 3.0051, 2.3275} }
};
struct NonCopyable {
NonCopyable() = default;
virtual ~NonCopyable() = default;
NonCopyable(const NonCopyable&) = delete;
NonCopyable& operator=(const NonCopyable&) = delete;
NonCopyable(NonCopyable&&) = delete;
NonCopyable& operator = (NonCopyable&&) = delete;
};
// RNG
template<bool is64>
struct AbstractRNGInterfaceT : public NonCopyable {
using seed_type = typename std::conditional<is64, uint64_t, uint32_t>::type;
seed_type seed_uint = { 0 };
virtual void reset_seed(seed_type seed) = 0;
virtual cr_float rand_f() = 0;
virtual cr_float rand_f_range(cr_float min, cr_float max) = 0;
};
// Marsaglia, G "Xorshift RNGs". Journal of Statistical Software
template<bool is64>
struct FastRNGT : AbstractRNGInterfaceT<is64> {
using seed_type = typename AbstractRNGInterfaceT<is64>::seed_type;
using AbstractRNGInterfaceT<is64>::seed_uint;
//32-bit
template <bool _is64 = is64,
typename std::enable_if<(!_is64), bool>::type = 0>
seed_type rand_uint() {
seed_type& y = seed_uint;
y ^= (y << 13);
y ^= (y >> 17);
y ^= (y << 5);
return y;
}
//64-bit
template <bool _is64 = is64,
typename std::enable_if<(_is64), bool>::type = 0>
seed_type rand_uint() {
seed_type& y = seed_uint;
y ^= (y << 13);
y ^= (y >> 7);
y ^= (y << 17);
return y;
}
void reset_seed(seed_type seed) override {
seed_uint = seed;
}
cr_float rand_f() override {
seed_type res = rand_uint();
cr_float f = (res & FLOAT_MAX_FULL_INTEGER_MINUS_ONE) / cr_float(FLOAT_MAX_FULL_INTEGER_MINUS_ONE);
return f;
}
cr_float rand_f_range(cr_float min, cr_float max) override {
return min + rand_f() * (max - min);
}
};
template<bool is64>
struct RNGT : AbstractRNGInterfaceT<is64> {
using seed_type = typename AbstractRNGInterfaceT<is64>::seed_type;
using AbstractRNGInterfaceT<is64>::seed_uint;
using mt19937_engine = typename std::conditional<is64, std::mt19937_64, std::mt19937>::type;
mt19937_engine gen;
std::uniform_real_distribution<cr_float> dist{ 0, FLOAT_ONE_BEFORE };
void reset_seed(seed_type seed) override {
gen.seed(seed);
seed_uint = seed;
}
cr_float rand_f() override {
cr_float f = dist(gen);
CRAY_ASSERT_IF_FALSE_MSG(f > 0.0 && f < 1.0, "rand_f out of bounds %f", f);
return f;
}
cr_float rand_f_range(cr_float min, cr_float max) override {
return min + dist(gen) * (max - min);
}
};
using AbstractRNGInterface = typename std::conditional<isDouble, AbstractRNGInterfaceT<true>, AbstractRNGInterfaceT<false>>::type;
using RNG = typename std::conditional<isDouble, RNGT<true>, RNGT<false>>::type;
using FastRNG = typename std::conditional<isDouble, FastRNGT<true>, FastRNGT<false>>::type;
static thread_local std::unique_ptr<AbstractRNGInterface> current_rng = std::make_unique<RNG>();
cr_float rand_f() { return current_rng->rand_f(); }
cr_float rand_f_range(cr_float min, cr_float max) { return current_rng->rand_f_range(min, max); }
void rand_reset() { current_rng.reset(); }
void rand_reset_seed(uint32_t seed) { current_rng->reset_seed(seed); }
static bool s_use_fast_rng = false;
void rand_set_fast_rng(bool fast) {
if (fast || s_use_fast_rng) {
current_rng = std::make_unique<FastRNG>();
}
else {
current_rng = std::make_unique<RNG>();
}
}
void rand_use_fast_rng(bool enable) {
s_use_fast_rng = enable;
}
bool rand_is_fast_rng() {
return s_use_fast_rng;
}
//thread_local static RNG current_rng;
//CR_float rand_f() { return current_rng.rand_f(); }
//CR_float rand_f_range(CR_float min, CR_float max) { return current_rng.rand_f_range(min, max); }
//void rand_reset() {}
//void rand_reset_seed(uint32_t seed) { current_rng.reset_seed(seed); }
//void rand_set_fast_rng(bool) {}
struct Stats {
uint64_t m_ray_depth = { 0 };
uint64_t m_number_rays = { 0 };
uint64_t m_number_rays_total = { 0 };
double m_primitive_intersections = { 0 };
double m_node_traversals = { 0 };
double m_primitive_intersections_avg = { 0 };
double m_node_traversals_avg = { 0 };
uint64_t m_number_shadow_rays = { 0 };
uint64_t m_number_shadow_rays_total = { 0 };
double m_primitive_intersections_shadow = { 0 };
double m_node_traversals_shadow = { 0 };
double m_primitive_intersections_shadow_avg = { 0 };
double m_node_traversals_shadow_avg = { 0 };
double m_running_sum_iterations = { 1 };
void addRayTraversal() { ++m_number_rays; }
void addPrimitiveIntersection() { ++m_primitive_intersections; }
void addNodeTraversal() { ++m_node_traversals; }
void addShadowRayTraversal() { ++m_number_shadow_rays; }
void addShadowPrimitiveIntersection() { ++m_primitive_intersections_shadow; }
void addShadowNodeTraversal() { ++m_node_traversals_shadow; }
void addRayDepth(int32_t ray_depth) { m_ray_depth += ray_depth; }
void clear() {
m_ray_depth = 0;
m_number_rays = 0;
m_number_rays_total = 0;
m_primitive_intersections = 0;
m_node_traversals = 0;
m_primitive_intersections_avg = 0;
m_node_traversals_avg = 0;
m_number_shadow_rays = 0;
m_number_shadow_rays_total = 0;
m_primitive_intersections_shadow = 0;
m_node_traversals_shadow = 0;
m_primitive_intersections_shadow_avg = 0;
m_node_traversals_shadow_avg = 0;
m_running_sum_iterations = 1;
}
void add(Stats& stats) {
m_number_rays += stats.m_number_rays_total;
m_number_shadow_rays += stats.m_number_shadow_rays_total;
m_ray_depth += stats.m_ray_depth;
updateRunningSum(m_primitive_intersections_avg, stats.m_primitive_intersections_avg, m_running_sum_iterations);
updateRunningSum(m_node_traversals_avg, stats.m_node_traversals_avg, m_running_sum_iterations);
updateRunningSum(m_primitive_intersections_shadow_avg, stats.m_primitive_intersections_shadow_avg, m_running_sum_iterations);
updateRunningSum(m_node_traversals_shadow_avg, stats.m_node_traversals_shadow_avg, m_running_sum_iterations);
++m_running_sum_iterations;
stats.clear();
}
void updateThreadRunningSum() {
updateRunningSum(m_primitive_intersections_avg, m_number_rays > 0 ? m_primitive_intersections / double(m_number_rays) : 0.0, m_running_sum_iterations);
updateRunningSum(m_node_traversals_avg, m_number_rays > 0 ? m_node_traversals / double(m_number_rays) : 0.0, m_running_sum_iterations);
m_number_rays_total += m_number_rays;
m_number_rays = 0;
updateRunningSum(m_primitive_intersections_shadow_avg, m_number_shadow_rays > 0 ? m_primitive_intersections_shadow / double(m_number_shadow_rays) : 0.0, m_running_sum_iterations);
updateRunningSum(m_node_traversals_shadow_avg, m_number_shadow_rays > 0 ? m_node_traversals_shadow / double(m_number_shadow_rays) : 0.0, m_running_sum_iterations);
m_number_shadow_rays_total += m_number_shadow_rays;
m_number_shadow_rays = 0;
m_primitive_intersections = 0;
m_primitive_intersections_shadow = 0;
m_node_traversals = 0;
m_node_traversals_shadow = 0;
++m_running_sum_iterations;
}
};
struct DebugData {
glm::vec2 current_pixel = { glm::vec2(0.0) };
#ifdef ENABLE_DEBUG_CURRENT_PIXEL
bool enabled = false;
glm::ivec2 target_pixel_start = { glm::ivec2(-1) };
glm::ivec2 target_pixel_end = { glm::ivec2(-1) };
#endif
};
struct GlobalSettings {
// stats
Stats m_stats;
// debug data
DebugData m_debug_data;
const glm::vec2& getCurrentPixel() { return m_debug_data.current_pixel; }
#ifdef ENABLE_DEBUG_CURRENT_PIXEL
bool isPixel() {
return
(m_debug_data.enabled &&
glm::all(glm::greaterThanEqual(glm::ivec2(m_debug_data.current_pixel), m_debug_data.target_pixel_start)) &&
glm::all(glm::lessThanEqual(glm::ivec2(m_debug_data.current_pixel), m_debug_data.target_pixel_end)));
}
#endif
// helpers
std::string m_output_name = { "result" };
// logging
enum CRAY_LOGGERENTRY m_minimum_log_level = { CR_LOGGER_WARNING };
bool m_print_progress_bar_stdout = { true };
bool m_print_to_stdout = { true };
FILE* m_file = { nullptr };
// gamma/tonemapping
bool m_rgb = { false };
cr_float m_exposure = { 2.0 };
cr_float m_gamma = { 2.2 };
cr_float m_inverse_gamma = { cr_float(1.0) / m_gamma };
// AO
int32_t m_ao_samples_per_pixel = { 1 };
cr_float m_ao_range = { 0.0 };
// path tracing
int32_t m_max_depth = { 10 };
int32_t m_samples_per_pixel = { 1 };
bool m_russian_roulette = { true };
// enabled only when interactive rendering is requested
bool m_interactive = { false };
};
static thread_local std::unique_ptr<GlobalSettings> s_thread_settings = { nullptr };
static GlobalSettings* s_global_settings = { nullptr };
struct Color {
Color() : data(glm::vec3(0)) {}
explicit Color(const cr_vec3& color) : data(color.x, color.y, color.z) {}
explicit Color(const glm::vec3& color) : data(color) {}
explicit Color(cr_float color) : data(color) {}
explicit Color(cr_float x, cr_float y, cr_float z) : data(x, y, z) { }
union {
glm::vec3 data = { glm::vec3(0) };
struct { cr_float x, y, z; };
};
Color& operator+=(const Color& rhs) { this->data += rhs.data; return *this; }
Color operator+(const Color& rhs) const {
Color tmp = *this;
return tmp += rhs;
}
Color& operator-=(const Color& rhs) { this->data += -rhs.data; return *this; }
Color operator-(const Color& rhs) const {
Color tmp = *this;
return tmp -= rhs;
}
Color& operator*=(const Color& rhs) { this->data *= rhs.data; return *this; }
Color operator*(const Color& rhs) const {
Color tmp = *this;
return tmp *= rhs;
}
Color& operator/=(const Color& rhs) { this->data /= rhs.data; return *this; }
Color operator/(const Color& rhs) const {
Color tmp = *this;
return tmp /= rhs;
}
// overloading float
Color& operator+=(const cr_float& scalar) { this->data += scalar; return *this; }
friend Color operator+(const Color& lhs, const cr_float& scalar) {
Color tmp = lhs;
return tmp += scalar;
}
Color& operator-=(const cr_float& scalar) { this->data -= scalar; return *this; }
friend Color operator-(const Color& lhs, const cr_float& scalar) {
Color tmp = lhs;
return tmp += -scalar;
}
Color& operator*=(const cr_float& scalar) { this->data *= scalar; return *this; }
friend Color operator*(const Color& lhs, const cr_float& scalar) {
Color tmp = lhs;
return tmp *= scalar;
}
Color& operator/=(const cr_float& scalar) { this->data /= scalar; return *this; }
friend Color operator/(const Color& lhs, const cr_float& scalar) {
Color tmp = lhs;
return tmp /= scalar;
}
// overloading vec3
Color& operator+=(const glm::vec3& scalar) { this->data += scalar; return *this; }
friend Color operator+(const Color& lhs, const glm::vec3& scalar) {
Color tmp = lhs;
return tmp += scalar;
}
Color& operator-=(const glm::vec3& scalar) { this->data -= scalar; return *this; }
friend Color operator-(const Color& lhs, const glm::vec3& scalar) {
Color tmp = lhs;
return tmp += -scalar;
}
Color& operator*=(const glm::vec3& scalar) { this->data *= scalar; return *this; }
friend Color operator*(const Color& lhs, const glm::vec3& scalar) {
Color tmp = lhs;
return tmp *= scalar;
}
Color& operator/=(const glm::vec3& scalar) { this->data /= scalar; return *this; }
friend Color operator/(const Color& lhs, const glm::vec3& scalar) {
Color tmp = lhs;
return tmp /= scalar;
}
bool isNot(const Color& color) const { return glm::any(glm::notEqual(this->data, color.data)); }
static uint8_t toUnsignedByte(cr_float val) { return static_cast<uint8_t>(val * 255.0); }
static Color Black() { return Color(0.0); }
static Color White() { return Color(1.0); }
};
// Generates a sample on a sphere using a uniform distribution
// Returns the generated sample
glm::vec3 getUniformSphereSample() {
glm::vec2 r;
r.x = rand_f();
r.y = rand_f();
cr_float phi = r.x * 2.0 * glm::pi<cr_float>();
cr_float cosTheta = 1.0 - 2.0 * r.y;
cr_float sinTheta = glm::sqrt(1.0 - cosTheta * cosTheta);
return glm::vec3(glm::cos(phi) * sinTheta, glm::sin(phi) * sinTheta, cosTheta);
}
// Returns the PDF from uniform spherical distribution
cr_float getUniformSphereSamplePDF() {
// pdf is 1 over 4pi
return glm::one_over_two_pi<cr_float>() * 0.5;
}
// Generates a sample on a disc using a uniform distribution
// Returns the generated sample
glm::vec2 getUniformDiscSample() {
glm::vec2 r;
r.x = rand_f();
r.y = rand_f();
cr_float phi = r.x * r.x * 2.0 * glm::pi<cr_float>();
cr_float radius = glm::sqrt(r.y);
return glm::vec2(glm::cos(phi) * radius, glm::sin(phi) * radius);
}
// Returns the PDF from uniform disc distribution
cr_float getUniformDiscSamplePDF() {
// pdf is 1 over 4pi
return glm::one_over_pi<cr_float>();
}
// Generates a sample on a hemisphere using a uniform distribution
// Returns the generated sample
glm::vec3 getUniformHemisphereSample() {
glm::vec2 r;
r.x = rand_f();
r.y = rand_f();
cr_float radius = glm::sqrt(glm::max(0.0, 1.0 - r.x * r.x));
cr_float phi = 2.0 * glm::pi<cr_float>() * r.y;
cr_float x = radius * glm::cos(phi);
cr_float y = radius * glm::sin(phi);
return glm::vec3(x, y, r.x);
}
// Returns the PDF from uniform hemispherical distribution
cr_float getUniformHemisphereSamplePDF() {
// pdf is 1 over 2pi
return glm::one_over_two_pi<cr_float>();
}
// Generates a sample on a hemisphere using a cosine-weighted distribution
// Returns the generated sample
glm::vec3 getCosineHemisphereSample() {
glm::vec2 r;
r.x = rand_f();
r.y = rand_f();
cr_float phi = r.x * 2.0 * glm::pi<cr_float>();
// theta is acos(sqrt(r.y))
cr_float sinTheta = glm::sqrt(1 - r.y);
cr_float cosTheta = glm::sqrt(r.y);
return glm::vec3(glm::cos(phi) * sinTheta, glm::sin(phi) * sinTheta, cosTheta);
}
// Returns the PDF from cosine hemispherical distribution
cr_float getCosineHemisphereSamplePDF(const glm::vec3& sample) {
return glm::abs(sample.z) * glm::one_over_pi<cr_float>();
}
// Obtains an OBN basis, e.g. for world<->local transformations
void getOrthonormalBasis(glm::vec3& bitangent, glm::vec3& tangent, const glm::vec3& normal) {
// calculate tangent, bitangent
//tangent = glm::cross(normal, glm::vec3(0.0, 1.0, 0.0));
//if (glm::dot(tangent, tangent) < FLOAT_TOLERANCE_3)
// tangent = glm::cross(normal, glm::vec3(1.0, 0.0, 0.0));
//tangent = glm::normalize(tangent);
//bitangent = glm::normalize(glm::cross(normal, tangent));
// Building An Orthonormal Basis, Revisited., Duff et al, JCGT. 2017, Listing 3.
cr_float sign = std::copysignf(1.0, normal.z);
const cr_float a = -1.0 / (sign + normal.z);
const cr_float b = normal.x * normal.y * a;
tangent = glm::vec3(1.0 + sign * normal.x * normal.x * a, sign * b, -sign * normal.x);
bitangent = glm::vec3(b, sign + normal.y * normal.y * a, -normal.y);
}
// The Fresnel term for dielectric media (e.g. air<->water)
// Parameters:
// - cosThetaIncident, the cosine of the incident angle
// - nIncident, the index of refraction for the incident medium
// - nIncident, the index of refraction for the transmitted medium
// returns the Fresnel term
// source: https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/
// source: https://people.cs.kuleuven.be/~philip.dutre/GI/TotalCompendium.pdf
Color FresnelDielectric(cr_float cosThetaIncident, cr_float nIncident, cr_float nTransmitted) {
if (nTransmitted <= 0.0) {
// return 1 for pure-reflective surfaces (e.g. mirrors)
return Color::White();
}
cosThetaIncident = glm::clamp(cosThetaIncident, cr_float(-1.0), cr_float(1.0));
//CRAY_ASSERT_IF_FALSE(cosThetaIncident >= -1 && cosThetaIncident <= 1);
// compute sinThetaIncident
cr_float sinThetaIncident = glm::sqrt(1.0 - cosThetaIncident * cosThetaIncident);
CRAY_ASSERT_IF_FALSE(sinThetaIncident >= 0 && sinThetaIncident <= 1);
// compute ThetaT using Snell's Law
cr_float sinThetaT = sinThetaIncident * nIncident / nTransmitted;
// if total internal reflection (transmitted angle > pi/2) no transmission occurs
if (sinThetaT >= 1) {
return Color(1);
}
// float relative_ior = nT / nI;
// compute Fresnel for dielectric-dielectric interface
cr_float cosThetaTransmitted = glm::sqrt(1.0 - sinThetaT * sinThetaT);
CRAY_ASSERT_IF_FALSE(cosThetaTransmitted > 0 && cosThetaTransmitted <= 1);
cr_float nIncident_cosThetaIncident = nIncident * cosThetaIncident;
cr_float nIncident_cosThetaTransmitted = nIncident * cosThetaTransmitted;
cr_float nTransmitted_cosThetaIncident = nTransmitted * cosThetaIncident;
cr_float nTransmitted_cosThetaTransmitted = nTransmitted * cosThetaTransmitted;
cr_float R_parallel = (nTransmitted_cosThetaIncident - nIncident_cosThetaTransmitted) /
(nTransmitted_cosThetaIncident + nIncident_cosThetaTransmitted);
cr_float R_perpendicular = (nIncident_cosThetaIncident - nTransmitted_cosThetaTransmitted) /
(nIncident_cosThetaIncident + nTransmitted_cosThetaTransmitted);
return Color(((R_parallel * R_parallel) + (R_perpendicular * R_perpendicular)) * 0.5);
}
// The Fresnel term for dielectric-conductor media (e.g. air<->metal). Assumes dielectric is air~=1
// Parameters:
// - cosThetaIncident, the cosine of the incident angle
// - nIncident, the index of refraction for the incident medium
// - nIncident, the index of refraction for the transmitted medium
// returns the Fresnel term
// source: https://seblagarde.wordpress.com/2013/04/29/memo-on-fresnel-equations/
// source: https://people.cs.kuleuven.be/~philip.dutre/GI/TotalCompendium.pdf
Color FresnelConductor(cr_float cosThetaIncident, cr_float nIncident, const glm::vec3& nTransmitted, const glm::vec3& k) {
cr_float CosTheta2 = cosThetaIncident * cosThetaIncident;
cr_float SinTheta2 = 1 - cosThetaIncident;
glm::vec3 eta = nTransmitted / nIncident;
glm::vec3 Eta2 = eta * eta;
glm::vec3 Etak2 = k * k / (nIncident * nIncident);
glm::vec3 t0 = Eta2 - Etak2 - SinTheta2;
glm::vec3 a2plusb2 = glm::sqrt(t0 * t0 + cr_float(4.0) * Eta2 * Etak2);
glm::vec3 t1 = a2plusb2 + CosTheta2;
glm::vec3 a = glm::sqrt(cr_float(0.5) * (a2plusb2 + t0));
glm::vec3 t2 = cr_float(2.0) * a * cosThetaIncident;
glm::vec3 R_perpendicular = (t1 - t2) / (t1 + t2);
glm::vec3 t3 = CosTheta2 * a2plusb2 + SinTheta2 * SinTheta2;
glm::vec3 t4 = t2 * SinTheta2;
glm::vec3 R_parallel = R_perpendicular * (t3 - t4) / (t3 + t4);
return Color((R_parallel + R_perpendicular) * cr_float(0.5));
}
// The Fresnel term using Shlick's approximation.
// Parameters:
// - cosThetaIncident, the cosine of the incident angle
// - nIncident, the index of refraction for the incident medium
// - nIncident, the index of refraction for the transmitted medium
// returns the Fresnel term
cr_float FresnelSchlick(cr_float cosThetaIncident, cr_float nIncident, cr_float nTransmitted) {
cr_float R0 = (nIncident - nTransmitted) / (nIncident + nTransmitted);
R0 *= R0;
cr_float u = 1.0 - cosThetaIncident;
cr_float u5 = u * u;
u5 = u5 * u5 * u;
return glm::min(1.0, R0 + (1.0 - R0) * u5);
}
// The Trowbridge-Reitz (GGX) isotropic NDF distribution, describing how the microfacet normals are distributed over the microsurface
// Parameters:
// - NH, the cosine of the angle between normal and microfacet normal
// - m, the roughness (width) parameter
// returns the NDF
cr_float Distribution_GGX_isotropic(cr_float NH, cr_float m) {
if (NH <= 0.0) {
return 0.0;
}
cr_float NH2 = NH * NH;
cr_float m2 = glm::max(cr_float(0.0), m * m);
cr_float denom = (NH2 * (m2 - 1) + 1);
denom = glm::pi<cr_float>() * denom * denom;
cr_float D = m2 / denom;
CRAY_ASSERT_IF_FALSE(D > 0);
return D;
}
// The Trowbridge-Reitz (GGX) Shadowing-Masking function, describing the portion of the microsurface visible in one direction I and O
// Parameters:
// - hV, cosine of the angle between microfacet normal and (I or O) dir
// - NV, cosine of the angle between normal and (I or O) dir
// - m, the roughness (width) parameter
// returns the Geometric term
cr_float Geometric1_GGX(cr_float HV, cr_float NV, cr_float m) {
if (HV / NV <= 0.0) {
return 0.0;
}
cr_float m2 = glm::max(cr_float(0.0), m * m);
cr_float cos_theta2_v = NV * NV;
cr_float tan_theta_v = (1.0 - cos_theta2_v) / cos_theta2_v;
cr_float denom = 1 + glm::sqrt(1 + m2 * tan_theta_v);
return (2.0) / denom;
}
// The bi-directional Trowbridge-Reitz (GGX) Shadowing-Masking function, describing the portion of the microsurface visible in both directions I and O
// Parameters:
// - HI, cosine of the angle between microfacet normal and incoming (light) dir
// - HO, cosine of the angle between microfacet normal and out (view) dirr
// - NI, cosine of the angle between normal and incoming (light) dir
// - NO, cosine of the angle between normal and out (view) dirr
// - m, the roughness (width) parameter
// returns the Geometric term
cr_float Geometric_Smith_GGX(cr_float HI, cr_float HO, cr_float NI, cr_float NO, cr_float m) {
return Geometric1_GGX(HI, NI, m) * Geometric1_GGX(HO, NO, m);
}
// Generates a new direction based on the GGX function
// Parameters:
// - roughness. the the roughness (width) parameter
// returns the new direction
glm::vec3 generateMicrofacetH_GGX(cr_float roughness) {
glm::vec2 r;
r.x = rand_f();
r.y = rand_f();
// generate microfacet
cr_float tantheta = roughness * glm::sqrt(r.x) / glm::sqrt(1.0 - r.x);
cr_float tantheta2 = tantheta * tantheta;
cr_float costheta = glm::sqrt(1.0 / (1.0 + tantheta2));
cr_float sintheta = glm::sqrt(1.0 - costheta * costheta);
cr_float phi = 2.0 * glm::pi<cr_float>() * r.y;
return glm::vec3(glm::cos(phi) * sintheta, glm::sin(phi) * sintheta, costheta);
}
// Converts a [0-1] roughness value to GGX alpha
// http://www.pbr-book.org/3ed-2018/Reflection_Models/Microfacet_Models.html
cr_float GGXRoughnessToAlpha(cr_float roughness) {
roughness = glm::max(roughness, static_cast<cr_float>(1e-3f));
cr_float x = glm::log(roughness);
return 1.62142 + 0.819955 * x + 0.1734 * x * x + 0.0171201 * x * x * x +
0.000640711 * x * x * x * x;
}
// Source for the microfacet sampling distributions:
// Microfacet Models for Refraction through Rough Surfaces (Walter B. et al.), EGSR 2007
// x1, x2 : uniformly distributed numbers [0, 1)
// GGX Sampling:
// theta_m = arctan(a_g * sqrt(x1) / sqrt(1 - x1))
// phi_m = 2 * p * x2
cr_float getMicrofacetPDF(cr_float HN, cr_float roughness) {
return Distribution_GGX_isotropic(HN, roughness) * glm::abs(HN);
}
// Basic Tracing Classes
struct Framebuffer {
glm::ivec2 m_dimensions = { glm::uvec2(32) };
std::unique_ptr<float[]> m_float_data_ptr = { nullptr };
std::unique_ptr<uint8_t[]> m_rgb_data_ptr = { nullptr };
int32_t m_num_channels = { 3 };
std::unique_ptr<uint32_t[]> m_iteration_ptr = { nullptr };
bool m_realloc = { false };
void requestRealloc() { m_realloc = true; }
void setDimensions(int32_t width, int32_t height) {
glm::ivec2 dimensions = glm::max(glm::ivec2(width, height), glm::ivec2(32));
if (m_dimensions != dimensions || m_float_data_ptr == nullptr) {
m_realloc = true;
}
m_dimensions = dimensions;
}
void alloc() {
if (!m_realloc) {
return;
}
m_float_data_ptr = std::make_unique<float[]>(m_dimensions.x * m_dimensions.y * m_num_channels);
if (s_global_settings->m_rgb) {
m_rgb_data_ptr = std::make_unique<uint8_t[]>(m_dimensions.x * m_dimensions.y * m_num_channels);
}
else {
m_rgb_data_ptr.reset();
}
if (s_global_settings->m_interactive) {
m_iteration_ptr = std::make_unique<uint32_t[]>(m_dimensions.x * m_dimensions.y);
}
else {
m_iteration_ptr.reset();
}
m_realloc = false;
}
void clear(unsigned char value) {
memset(m_float_data_ptr.get(), value, getFloatByteSize());
if (s_global_settings->m_rgb) {
memset(m_rgb_data_ptr.get(), value, getRGBByteSize());
}
}
void clearIteration(int32_t value) {
if (m_realloc) {
alloc();
}
if (s_global_settings->m_interactive) {
memset(m_iteration_ptr.get(), value, m_dimensions.x * m_dimensions.y * sizeof(uint32_t));
}
}
// source: http://filmicworlds.com/blog/filmic-tonemapping-operators/
glm::vec3 Uncharted2ToneMappingF(const glm::vec3& color) {
cr_float A = 0.15; cr_float B = 0.50; cr_float C = 0.10;
cr_float D = 0.20; cr_float E = 0.02; cr_float F = 0.30;
return ((color * (A * color + C * B) + D * E) / (color * (A * color + B) + D * F)) - E / F;
}
glm::vec3 Uncharted2ToneMapping(const glm::vec3& color) {
return gammaCorrect(Uncharted2ToneMappingF(color * s_thread_settings->m_exposure) * cr_float(1.3790642466494378));
}
glm::vec3 ReinhardToneMapping(const glm::vec3& color) {
return gammaCorrect((color * s_thread_settings->m_exposure) / (glm::vec3(1.0) + color * s_thread_settings->m_exposure));
}
glm::vec3 gammaCorrect(const glm::vec3& color) {
return glm::pow(glm::clamp(color, glm::vec3(0.0), glm::vec3(1.0)), glm::vec3(s_thread_settings->m_inverse_gamma));
}
glm::vec3 tonemap(const glm::vec3& color) {
return s_thread_settings->m_exposure > 0.0 ? Uncharted2ToneMapping(color) : gammaCorrect(color);
}
void WriteColor(const Color& color, int32_t x, int32_t y) {
size_t position = (y * m_dimensions.x * m_num_channels) + (x * m_num_channels);
glm::vec3 updated_color = color.data;
if (s_thread_settings->m_interactive) {
size_t iteration_position = (y * m_dimensions.x) + x;
cr_float iteration = cr_float(++m_iteration_ptr[iteration_position]);
glm::vec3 old_val(0.0);
for (int32_t i = 0; i < m_num_channels; ++i) {
old_val[i] = iteration > 1 ? cr_float(m_float_data_ptr[position + i]) : 0.0;
}
updated_color = old_val + ((updated_color - old_val) / cr_float(iteration));
}
for (int32_t i = 0; i < m_num_channels; ++i) {
m_float_data_ptr[position + i] = float(updated_color[i]);
}
if (s_thread_settings->m_rgb) {
glm::vec3 gamma_corrected = tonemap(updated_color);
for (int32_t i = 0; i < m_num_channels; ++i) {
m_rgb_data_ptr[position + i] = Color::toUnsignedByte(gamma_corrected[i]);
}
}
CRAY_DEBUG_PIXEL("(%.2f, %.2f) Color: %f, %f, %f, Stored: %f, %f, %f", s_thread_settings->getCurrentPixel().x, s_thread_settings->getCurrentPixel().y,
color.x, color.y, color.z, m_float_data_ptr[position + 0], m_float_data_ptr[position + 2], m_float_data_ptr[position + 2]);