toytracer/vec3.cpp
2020-06-07 00:32:31 +02:00

40 lines
1.0 KiB
C++

#include "vec3.h"
Vec3 random_in_unit_sphere() {
while (true) {
auto p = Vec3::random(-1, 1);
if (p.length_squared() >= 1) continue;
return p;
}
}
Vec3 random_unit_vector() {
auto a = random_double(0, 2*pi);
auto z = random_double(-1, 1);
auto r = std::sqrt(1 - z*z);
return Vec3(r*std::cos(a), r*std::sin(a), z);
}
Vec3 random_in_hemisphere(const Vec3& normal) {
Vec3 in_unit_sphere = random_in_unit_sphere();
if (dot(in_unit_sphere, normal) > 0.0)
return in_unit_sphere;
else
return -in_unit_sphere;
}
Vec3 refract(const Vec3& uv, const Vec3& n, double etai_over_etat) {
auto cos_theta = dot(-uv, n);
Vec3 r_out_parallel = etai_over_etat * (uv + cos_theta*n);
Vec3 r_out_perp = - std::sqrt(1.0 - r_out_parallel.length_squared()) * n;
return r_out_parallel + r_out_perp;
}
Vec3 random_in_unit_disk() {
while (true) {
auto p = Vec3(random_double(-1, 1), random_double(-1, 1), 0);
if (p.length_squared() >= 1) continue;
return p;
}
}