-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsmallpt_rewrite.cpp
More file actions
1405 lines (1083 loc) · 36.8 KB
/
Copy pathsmallpt_rewrite.cpp
File metadata and controls
1405 lines (1083 loc) · 36.8 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
// `structured smallpt`, or call it `smallpbrt`
// http://www.kevinbeason.com/smallpt
#include <cmath> // smallpt, a Path Tracer by Kevin Beason, 2008
#include <cstdlib> // Make : g++ -O3 -fopenmp smallpt.cpp -o smallpt
#include <cstdio> // Remove "-fopenmp" for g++ version < 4.2
#include <algorithm>
#include <array>
#include <fstream>
#include <memory>
#include <numbers>
#include <random>
#include <string>
#include <string_view>
#include <vector>
using namespace std::literals::string_literals;
#pragma region Math/Utility
// https://github.com/infancy/pbrt-v3/blob/master/src/core/pbrt.h
using Float = double;
using Radian = Float;
using Degree = Float;
constexpr Float Infinity = std::numeric_limits<Float>::infinity();
constexpr Float Pi = std::numbers::pi;
constexpr Float InvPi = std::numbers::inv_pi;
constexpr Radian radians(Degree deg) { return (Pi / 180) * deg; }
constexpr Degree degrees(Radian rad) { return (180 / Pi) * rad; }
#pragma endregion
#pragma region Geometry
// https://www.pbr-book.org/3ed-2018/Geometry_and_Transformations
// https://github.com/infancy/pbrt-v3/blob/master/src/core/geometry.h
struct Vector2
{
Float x{}, y{};
Vector2() = default;
Vector2(Float x, Float y) : x{ x }, y{ y } {}
Float operator[](int index) const
{
if (index == 0) return x;
else return y;
}
Vector2 operator+(const Vector2& b) const { return Vector2(x + b.x, y + b.y); }
Vector2 operator-(const Vector2& b) const { return Vector2(x - b.x, y - b.y); }
friend Vector2 operator*(Float a, Vector2 b) { return Vector2(a * b.x, a * b.y); }
};
using Float2 = Vector2;
using Point2 = Vector2;
struct Vector3
{
union
{
struct { Float x, y, z; };
struct { Float r, g, b; };
};
Vector3() : x{ 0 }, y{ 0 }, z{ 0 } {}
Vector3(Float x, Float y, Float z) : x{ x }, y{ y }, z{ z } {}
Vector3 operator-() const { return Vector3(-x, -y, -z); }
Vector3 operator+(const Vector3& b) const { return Vector3(x + b.x, y + b.y, z + b.z); }
Vector3 operator-(const Vector3& b) const { return Vector3(x - b.x, y - b.y, z - b.z); }
Vector3 operator*(Float b) const { return Vector3(x * b, y * b, z * b); }
Vector3 operator/(Float b) const { return Vector3(x / b, y / b, z / b); }
Vector3 Normalize() const { return *this * (1 / sqrt(x * x + y * y + z * z)); }
Float Dot(const Vector3& b) const { return x * b.x + y * b.y + z * b.z; }
Vector3 Cross(const Vector3& b) const { return Vector3(y * b.z - z * b.y, z * b.x - x * b.z, x * b.y - y * b.x); }
friend Vector3 operator*(Float a, Vector3 v) { return v * a; }
friend Vector3 Normalize(const Vector3& a) { return a.Normalize(); }
friend Float Dot(const Vector3& a, const Vector3& b) { return a.Dot(b); }
friend Float AbsDot(const Vector3& a, const Vector3& b) { return std::abs(a.Dot(b)); }
friend Vector3 Cross(const Vector3& a, const Vector3& b) { return a.Cross(b); }
public:
// only for Color
Vector3 operator*(const Vector3& c) const { return Vector3(r * c.r, g * c.g, b * c.b); }
Float MaxComponentValue() const
{
return std::max({ r, g, b });
}
bool IsBlack() const { return (r <= 0) && (g <= 0) && (b <= 0); }
};
using Float3 = Vector3;
using Point3 = Vector3;
using Normal3 = Vector3;
using UnitVector3 = Vector3;
// https://www.pbr-book.org/3ed-2018/Color_and_Radiometry/RGBSpectrum_Implementation
using Color = Vector3;
// https://github.com/SmallVCM/SmallVCM/blob/master/src/frame.hxx
class Frame
{
public:
Frame(const Vector3& s, const Vector3& t, const Normal3& n) :
s_{ s.Normalize() },
t_{ t.Normalize() },
n_{ n.Normalize() }
{
}
Frame(const Normal3& n) :
n_{ n.Normalize() }
{
SetFromZ();
}
public:
// think if {s, t, n} is (1, 0, 0), (0, 1, 0), (0, 0, 1)
Vector3 ToLocal(const Vector3& worldVec3) const
{
return Vector3(
Dot(s_, worldVec3),
Dot(t_, worldVec3),
Dot(n_, worldVec3));
}
Vector3 ToWorld(const Vector3& localVec3) const
{
return
s_ * localVec3.x +
t_ * localVec3.y +
n_ * localVec3.z;
}
const Vector3& Binormal() const { return s_; }
const Vector3& Tangent() const { return t_; }
const Vector3& Normal() const { return n_; }
private:
void SetFromZ()
{
Vector3 tmp_s = (std::abs(n_.x) > 0.99f) ? Vector3(0, 1, 0) : Vector3(1, 0, 0);
t_ = Normalize(Cross(n_, tmp_s));
s_ = Normalize(Cross(t_, n_));
}
private:
// world frame basic vector
Vector3 s_{ 1, 0, 0 }; // x
Vector3 t_{ 0, 1, 0 }; // y
Normal3 n_{ 0, 0, 1 }; // z
};
// https://www.pbr-book.org/3ed-2018/Geometry_and_Transformations/Rays
struct Ray
{
Point3 origin;
UnitVector3 direction;
Float distance; // distance from ray to intersection
Ray(Point3 origin, UnitVector3 direction, Float distance = Infinity) :
origin{ origin }, direction{ direction }, distance{ distance }
{
}
Point3 operator()(Float t) const
{
return origin + t * direction;
}
};
// https://www.pbr-book.org/3ed-2018/Geometry_and_Transformations/Interactions
// https://github.com/infancy/pbrt-v3/blob/master/src/core/interaction.h
class BSDF;
class Primitive;
/*
surface intersection, called `SurfaceInteraction` on pbrt
prev n next
---- ^ ----
^ | ^
\ | ¦È /
wo \ | / wi is unknown, sampling for bsdf (or light)
\ | /
\|/
-------
isect
*/
class Isect
{
public:
Isect() = default;
Isect(const Point3& position, const Normal3& normal, UnitVector3 wo) :
position{ position },
normal{ normal },
wo{ wo }
{
}
public:
Point3 position{}; // world position of intersection
Normal3 normal{};
UnitVector3 wo{};
const BSDF* bsdf() const { return bsdfPtr.get(); }
Color Le() const { return emission; } // prev <- isect, against ray's direction
private:
std::unique_ptr<BSDF> bsdfPtr{};
Color emission{};
friend Primitive;
};
#pragma endregion
#pragma region Sampling
// https://www.pbr-book.org/3ed-2018/Monte_Carlo_Integration/2D_Sampling_with_Multidimensional_Transformations
// https://github.com/infancy/pbrt-v3/blob/master/src/core/sampling.h#L138-L153
// https://github.com/infancy/pbrt-v3/blob/master/src/core/sampling.cpp#L199-L230
Point2 UniformSampleDisk(const Float2& random)
{
Float radius = std::sqrt(random[0]);
Float theta = 2 * Pi * random[1];
return Point2(radius * std::cos(theta), radius * std::sin(theta));
}
// cosine-weighted sampling
inline Vector3 CosineSampleHemisphere(const Float2& random)
{
// Cosine importance sampling of the hemisphere for diffuse reflection
Point2 pDisk = UniformSampleDisk(random);
Float z = std::sqrt(std::max((Float)0, 1 - pDisk.x * pDisk.x - pDisk.y * pDisk.y));
return Vector3(pDisk.x, pDisk.y, z);
}
inline Float CosineHemispherePdf(Float cosTheta)
{
return cosTheta * InvPi;
}
#pragma endregion
#pragma region Sampler
// https://github.com/mmp/pbrt-v3/blob/master/src/core/rng.h
// random number generator
// https://github.com/SmallVCM/SmallVCM/blob/master/src/rng.hxx
class RNG
{
public:
RNG(int seed = 1234) : rngEngine(seed)
{
}
// [0, int_max]
int UniformInt()
{
return intDist(rngEngine);
}
// [0, uint_max]
uint32_t UniformUint()
{
return uintDist(rngEngine);
}
// [0, 1)
Float UniformFloat()
{
return float01Dist(rngEngine);
}
// [0, 1), [0, 1)
Float2 UniformFloat2()
{
return Float2(UniformFloat(), UniformFloat());
}
private:
std::mt19937_64 rngEngine;
std::uniform_int_distribution<int> intDist;
std::uniform_int_distribution<uint32_t> uintDist;
std::uniform_real_distribution<Float> float01Dist{ (Float)0, (Float)1 };
};
struct CameraSample
{
Point2 pFilm{}; // sample point's position on film
// Point2 pLens{};
};
// https://github.com/infancy/pbrt-v3/blob/master/src/core/sampler.h
class Sampler
{
public:
virtual ~Sampler() {}
Sampler(int samplesPerPixel) :
samplesPerPixel{ samplesPerPixel }
{
}
virtual int SamplesPerPixel()
{
return samplesPerPixel;
}
virtual std::unique_ptr<Sampler> Clone() = 0;
public:
virtual void StartPixel()
{
currentSampleIndex = 0;
}
virtual bool StartNextSample()
{
currentSampleIndex += 1;
return currentSampleIndex < samplesPerPixel;
}
public:
virtual Float Get1D() = 0;
virtual Vector2 Get2D() = 0;
virtual CameraSample GetCameraSample(Point2 pFilm) = 0;
protected:
RNG rng{};
int samplesPerPixel{};
int currentSampleIndex{};
};
// https://github.com/mmp/pbrt-v3/blob/master/src/samplers/random.cpp
class RandomSampler : public Sampler
{
public:
using Sampler::Sampler;
std::unique_ptr<Sampler> Clone() override
{
return std::make_unique<RandomSampler>(samplesPerPixel);
}
public:
Float Get1D() override
{
return rng.UniformFloat();
}
Vector2 Get2D() override
{
return rng.UniformFloat2();
}
CameraSample GetCameraSample(Point2 pFilm) override
{
return { pFilm + rng.UniformFloat2() };
}
};
// https://computergraphics.stackexchange.com/questions/3868/why-use-a-tent-filter-in-path-tracing
class TrapezoidalSampler : public Sampler
{
public:
using Sampler::Sampler;
int SamplesPerPixel() override
{
return samplesPerPixel * SubPixelNum;
}
std::unique_ptr<Sampler> Clone() override
{
return std::make_unique<TrapezoidalSampler>(samplesPerPixel);
}
public:
void StartPixel() override
{
Sampler::StartPixel();
currentSubPixelIndex = 0;
}
bool StartNextSample() override
{
currentSampleIndex += 1;
if (currentSampleIndex < samplesPerPixel)
{
return true;
}
else if (currentSampleIndex == samplesPerPixel)
{
currentSampleIndex = 0;
currentSubPixelIndex += 1;
return currentSubPixelIndex < SubPixelNum;
}
else
{
return false;
}
}
public:
Float Get1D() override
{
return rng.UniformFloat();
}
Vector2 Get2D() override
{
return rng.UniformFloat2();
}
CameraSample GetCameraSample(Point2 pFilm) override
{
int subPixelX = currentSubPixelIndex % 2;
int subPixelY = currentSubPixelIndex / 2;
Float random1 = 2 * rng.UniformFloat();
Float random2 = 2 * rng.UniformFloat();
// uniform dist [0, 1) => triangle dist [-1, 1)
Float deltaX = random1 < 1 ? sqrt(random1) - 1 : 1 - sqrt(2 - random1);
Float deltaY = random2 < 1 ? sqrt(random2) - 1 : 1 - sqrt(2 - random2);
Point2 samplePoint
{
(subPixelX + deltaX + 0.5) / 2,
(subPixelY + deltaY + 0.5) / 2
};
return { pFilm + samplePoint };
}
private:
static constexpr int SubPixelNum = 4; // 2x2
int currentSubPixelIndex{};
};
#pragma endregion
#pragma region Filter
// https://github.com/infancy/pbrt-v3/blob/master/src/core/filter.h
#pragma endregion
#pragma region Film
// https://github.com/infancy/pbrt-v3/blob/master/src/core/film.h
inline Float Clamp(Float x) { return x < 0 ? 0 : x > 1 ? 1 : x; }
inline Vector3 Clamp(Vector3 vec3) { return Vector3(Clamp(vec3.x), Clamp(vec3.y), Clamp(vec3.z)); }
inline int GammaEncoding(Float x) { return int(pow(Clamp(x), 1 / 2.2) * 255 + .5); }
/*
warpper of `Color pixels[]`
features:
* get/set color
* save image
*/
class Film
{
public:
Film(const Vector2& resolution, /*std::unique_ptr<Filter> filter,*/ const std::string& filename) :
fullResolution{ resolution },
filename{ filename },
pixels{ std::make_unique<Color[]>(Width() * Height()) }
{
}
public:
int Width() const { return (int)fullResolution.x; }
int Height() const { return (int)fullResolution.y; }
Vector2 Resolution() const { return fullResolution; }
Color& operator()(int x, int y)
{
return *(pixels.get() + Width() * y + x);
}
void add_color(int x, int y, const Color& delta)
{
Color& color_ = operator()(x, y);
color_ = color_ + delta;
}
public:
virtual bool store_image() const
{
return store_bmp_impl(filename, Width(), Height(), 3, (Float*)pixels.get());
}
// https://github.com/SmallVCM/SmallVCM/blob/master/src/framebuffer.hxx#L149-L215
static bool store_bmp_impl(const std::string& filename, int width, int height, int channel, const Float* floats)
{
std::fstream img_file(filename, std::ios::binary | std::ios::out);
uint32_t padding_line_bytes = (width * channel + 3) & (~3);
uint32_t padding_image_bytes = padding_line_bytes * height;
const uint32_t FILE_HEADER_SIZE = 14;
const uint32_t INFO_HEADER_SIZE = 40;
// write file header
struct BITMAP_FILE_HEADER_INFO_HEADER
{
// file header
//char8_t type[2]{ 'B', 'M' };
uint32_t file_size{};
uint32_t reserved{ 0 };
uint32_t databody_offset{ FILE_HEADER_SIZE + INFO_HEADER_SIZE };
// info header
uint32_t info_header_size{ INFO_HEADER_SIZE };
int32_t width{};
int32_t height{};
int16_t color_planes{ 1 };
int16_t per_pixel_bits{};
uint32_t compression{ 0 };
uint32_t image_bytes{ 0 };
uint32_t x_pixels_per_meter{ 0 };
uint32_t y_pixels_per_meter{ 0 };
uint32_t color_used{ 0 };
uint32_t color_important{ 0 };
}
bmp_header
{
.file_size{ FILE_HEADER_SIZE + INFO_HEADER_SIZE + padding_image_bytes },
.width{ width },
.height{ height },
.per_pixel_bits{ (int16_t)(channel * 8) },
//.image_bytes{ padding_image_bytes }
};
img_file
.write("BM", 2)
.write((char*)&bmp_header, sizeof(bmp_header));
// without color table
// gamma encoding
int byte_num = width * height * channel;
auto bytes = std::make_unique<uint8_t[]>(byte_num);
for (int i = 0; i < byte_num; i += 3)
{
// BGR
bytes[i] = GammaEncoding(floats[i + 2]);
bytes[i + 1] = GammaEncoding(floats[i + 1]);
bytes[i + 2] = GammaEncoding(floats[i]);
}
// write data body
int line_num = width * channel;
// bmp is stored from bottom to up
for (int y = height - 1; y >= 0; --y)
img_file.write((char*)(bytes.get() + y * line_num), line_num);
return true;
}
private:
const Vector2 fullResolution;
//std::unique_ptr<Filter> filter;
const std::string filename;
std::unique_ptr<Color[]> pixels;
};
#pragma endregion
#pragma region Camera
// https://www.pbr-book.org/3ed-2018/Camera_Models
// https://github.com/infancy/pbrt-v3/blob/master/src/core/camera.h
/*
pbrt camera space:
left hand
y (0, 1, 0) z(0, 0, 1)
| /
| /
| /
| /
| /
| /
|/_ _ _ _ _ _ x(1, 0, 0)
o
features:
generate ray
*/
class Camera
{
public:
virtual ~Camera() {}
Camera() {}
public:
virtual Ray GenerateRay(const CameraSample& sample) const = 0;
};
// https://github.com/infancy/pbrt-v3/blob/master/src/cameras/perspective.cpp
class PerspectiveCamera : public Camera
{
public:
PerspectiveCamera(const Vector3& position, const UnitVector3& direction, const Vector3& up,
Degree fov, Vector2 resolution) :
position{ position },
front{ direction },
up{ up },
resolution{ resolution }
{
// `front` is a unit vector, it's length is 1
Float tan_fov = std::tan(radians(fov) / 2);
right = this->up.Cross(front).Normalize() * tan_fov * Aspect();
this->up = front.Cross(right).Normalize() * tan_fov;
}
public:
virtual Ray GenerateRay(const CameraSample& sample) const
{
Vector3 direction =
front +
right * (sample.pFilm.x / resolution.x - 0.5) +
up * (0.5 - sample.pFilm.y / resolution.y);
return Ray{ position + direction * 140, direction.Normalize() };
}
private:
Float Aspect() { return resolution.x / resolution.y; }
private:
Vector3 position;
UnitVector3 front;
UnitVector3 right;
UnitVector3 up;
Vector2 resolution;
};
#pragma endregion
#pragma region Shape
// https://www.pbr-book.org/3ed-2018/Shapes
// https://github.com/infancy/pbrt-v3/blob/master/src/core/shape.h
class Shape
{
public:
virtual bool Intersect(Ray& ray, Isect* isect) const = 0;
};
class Sphere : public Shape
{
public:
Sphere(Float radius, Vector3 center) :
radius(radius), center(center)
{
}
public:
bool Intersect(Ray& ray, Isect* isect) const override
{
/*
ray: p(t) = o + t*d,
sphere: ||p - c||^2 = r^2
if ray and sphere have a intersection p, then:
||p(t) - c||^2 = r^2
=> ||o + t*d - c||^2 = r^2
=> (t*d + o - c).(t*d + o - c) = r^2
=> d.d*t^2 + 2d.(o-c)*t + (o-c).(o-c)-r^2 = 0
compare with:
at^2 + bt + c = 0
there have:
co = o - c
a = dot(d, d) = 1;
b = 2 * dot(d, co), neg_b' = dot(d, oc);
c = dot(co, co) - r^2;
so:
t = (-b +/- sqrt(b^2 - 4ac)) / 2a
= (-b +/- sqrt(b^2 - 4c)) / 2
= ((-2 * dot(d, co) +/- sqrt(4 * dot(d, co)^2 - 4 * (dot(co, co) - r^2))) / 2
= -dot(d, co) +/- sqrt( dot(d, co)^2 - dot(co, co) + r^2 )
= neg_b' +/- sqrt(Delta)
*/
Vector3 oc = center - ray.origin;
Float neg_b = oc.Dot(ray.direction);
Float det = neg_b * neg_b - oc.Dot(oc) + radius * radius;
bool hit = false;
Float distance = 0;
if (det >= 0)
{
Float sqrtDet = sqrt(det);
Float epsilon = 1e-4;
if (distance = neg_b - sqrtDet; distance > epsilon && distance < ray.distance)
{
hit = true;
}
else if (distance = neg_b + sqrtDet; distance > epsilon && distance < ray.distance)
{
hit = true;
}
}
if (hit)
{
ray.distance = distance;
Point3 hit_point = ray(distance);
*isect = Isect(hit_point, (hit_point - center).Normalize(), -ray.direction);
}
return hit;
}
private:
Float radius;
Point3 center;
};
#pragma endregion
#pragma region BSDF
// https://www.pbr-book.org/3ed-2018/Reflection_Models
// https://github.com/mmp/pbrt-v3/blob/master/src/core/reflection.h
// local shading coordinate
inline Float cosTheta(const Vector3& w) { return w.z; }
inline Float AbsCosTheta(const Vector3& w) { return std::abs(w.z); }
inline bool SameHemisphere(const Vector3& w, const Vector3& wp) { return w.z * wp.z > 0; }
struct BSDFSample
{
Color f; // scattering rate
Vector3 wi; // world wi
Float pdf{};
};
/*
https://www.pbr-book.org/3ed-2018/Reflection_Models#x0-GeometricSetting
shading frame:
z, n(0, 0, 1)
|
|
|
|
|_ _ _ _ _ _ x, s(1, 0, 0)
/ p
/
/
y, t(0, 1, 0)
*/
class BSDF
{
public:
virtual ~BSDF() = default;
BSDF(Frame shadingFrame) :
shadingFrame{ shadingFrame }
{
}
public:
// or called `eval`, `evaluate`
Color f(const Vector3& world_wo, const Vector3& world_wi) const
{
return f_(ToLocal(world_wo), ToLocal(world_wi));
}
Float Pdf(const Vector3& world_wo, const Vector3& world_wi) const
{
return Pdf_(ToLocal(world_wo), ToLocal(world_wi));
}
// or called `sample`, `sample_direction`
BSDFSample Sample_f(const Vector3& world_wo, const Float2& random) const
{
auto sample = Sample_f_(ToLocal(world_wo), random);
sample.wi = ToWorld(sample.wi);
return sample;
}
protected:
virtual Color f_(const Vector3& wo, const Vector3& wi) const = 0;
virtual Float Pdf_(const Vector3& wo, const Vector3& wi) const = 0;
virtual BSDFSample Sample_f_(const Vector3& wo, const Float2& random) const = 0;
private:
Vector3 ToLocal(const Vector3& worldVec3) const
{
return shadingFrame.ToLocal(worldVec3);
}
Vector3 ToWorld(const Vector3& localVec3) const
{
return shadingFrame.ToWorld(localVec3);
}
private:
Frame shadingFrame;
// extension point:
// std::array<bxdf_uptr, 2> BxDFList;
};
class LambertionReflection : public BSDF
{
public:
LambertionReflection(const Frame& shadingFrame, const Color& R) :
BSDF(shadingFrame), R{ R }
{
}
Color f_(const Vector3& wo, const Vector3& wi) const override { return R * InvPi; }
Float Pdf_(const Vector3& wo, const Vector3& wi) const override
{
return SameHemisphere(wo, wi) ? CosineHemispherePdf(AbsCosTheta(wi)) : 0;
}
BSDFSample Sample_f_(const Vector3& wo, const Float2& random) const override
{
BSDFSample sample;
// Cosine-sample the hemisphere, flipping the direction if necessary
sample.wi = CosineSampleHemisphere(random);
if (wo.z < 0)
sample.wi.z *= -1;
sample.pdf = Pdf_(wo, sample.wi);
sample.f = f_(wo, sample.wi);
return sample;
}
private:
Color R; // surface albedo, per-component is surface reflectance
};
class SpecularReflection : public BSDF
{
public:
SpecularReflection(const Frame& shadingFrame, const Color& R) :
BSDF(shadingFrame), R{ R }
{
}
Color f_(const Vector3& wo, const Vector3& wi) const override { return Color(); }
Float Pdf_(const Vector3& wo, const Vector3& wi) const override { return 0; }
BSDFSample Sample_f_(const Vector3& wo, const Float2& random) const override
{
// https://www.pbr-book.org/3ed-2018/Reflection_Models/Specular_Reflection_and_Transmission#SpecularReflection
// https://github.com/infancy/pbrt-v3/blob/master/src/core/reflection.h#L387-L408
// https://github.com/infancy/pbrt-v3/blob/master/src/core/reflection.cpp#L181-L191
BSDFSample sample;
sample.wi = Vector3(-wo.x, -wo.y, wo.z);
sample.pdf = 1;
sample.f = R / AbsCosTheta(sample.wi); // for `(R / cos_theta) * Li * cos_theta / pdf = R * Li`
return sample;
}
private:
Color R;
};
class FresnelSpecular : public BSDF
{
public:
FresnelSpecular(const Frame& shadingFrame, const Color& R, const Color& T, Float etaI, Float etaT) :
BSDF(shadingFrame), R{ R }, T{ T }, etaI{ etaI }, etaT{ etaT }
{
}
Color f_(const Vector3& wo, const Vector3& wi) const override { return Color(); }
Float Pdf_(const Vector3& wo, const Vector3& wi) const override { return 0; }
BSDFSample Sample_f_(const Vector3& wo, const Float2& random) const override
{
// https://www.pbr-book.org/3ed-2018/Reflection_Models/Specular_Reflection_and_Transmission#Fresnelalbedo
// https://github.com/infancy/pbrt-v3/blob/master/src/core/reflection.h#L440-L463
// https://github.com/infancy/pbrt-v3/blob/master/src/core/reflection.cpp#L627-L667
BSDFSample sample;
Normal3 normal(0, 0, 1); // use `z` as normal
bool into = normal.Dot(wo) > 0; // ray from outside going in?
Normal3 woNormal = into ? normal : normal * -1;
// IOR(index of refractive)
Float eta = into ? etaI / etaT : etaT / etaI;
// compute reflect direction by refection law
Vector3 reflectDirection = Vector3(-wo.x, -wo.y, wo.z);
// compute refract direction by Snell's law
// https://www.pbr-book.org/3ed-2018/Reflection_Models/Specular_Reflection_and_Transmission#SpecularTransmission see `Refract()`
Float cosThetaI = Dot(wo, woNormal);
Float cosThetaT2 = 1 - eta * eta * (1 - cosThetaI * cosThetaI);
if (cosThetaT2 < 0) // Total internal reflection
{
return sample;
}
Float cosThetaT = sqrt(cosThetaT2);
Vector3 refractDirection = (-wo * eta + woNormal * (cosThetaI * eta - cosThetaT)).Normalize();
// compute the fraction of incoming light that is reflected or transmitted
// by Schlick Approximation of Fresnel Dielectric 1994 https://en.wikipedia.org/wiki/Schlick%27s_approximation
Float a = etaT - etaI;
Float b = etaT + etaI;
Float R0 = a * a / (b * b);
Float c = 1 - (into ? cosThetaI : cosThetaT);
Float Re = R0 + (1 - R0) * c * c * c * c * c;
Float Tr = 1 - Re;
if (random[0] < Re) // Russian roulette
{
// Compute specular reflection for _FresnelSpecular_
sample.wi = reflectDirection;
sample.pdf = Re;
sample.f = (R * Re) / AbsCosTheta(sample.wi);
}
else
{
// Compute specular transmission for _FresnelSpecular_