参考:https://blog.csdn.net/qq_36242312/article/details/116307626
思路
上节课的代码:
Triangle::getIntersection
inline Intersection Triangle::getIntersection(Ray ray)
{
Intersection inter;
if (dotProduct(ray.direction, normal) > 0)
return inter;
double u, v, t_tmp = 0;
Vector3f pvec = crossProduct(ray.direction, e2);
double det = dotProduct(e1, pvec);
if (fabs(det) < EPSILON)
return inter;
double det_inv = 1. / det;
Vector3f tvec = ray.origin - v0;
u = dotProduct(tvec, pvec) * det_inv;
if (u < 0 || u > 1)
return inter;
Vector3f qvec = crossProduct(tvec, e1);
v = dotProduct(ray.direction, qvec) * det_inv;
if (v < 0 || u + v > 1)
return inter;
t_tmp = dotProduct(e2, qvec) * det_inv;
if (t_tmp < 0)
{
return inter;
}
inter.distance = t_tmp;
inter.coords = ray(t_tmp);
inter.happened = true;
inter.m = m;
inter.normal = normal;
inter.obj = this;
return inter;
}
Bounds3::IntersectP
inline bool Bounds3::IntersectP(const Ray& ray, const Vector3f& invDir, const std::array<int, 3>& dirIsNeg) const
{
// 光线进入点
float tEnter = -std::numeric_limits<float>::infinity();
// 光线离开点
float tExit = std::numeric_limits<float>::infinity();
for (int i = 0; i < 3; i++)
{
float min = (pMin[i] - ray.origin[i]) * invDir[i];
float max = (pMax[i] - ray.origin[i]) * invDir[i];
// 坐标为负的话,需要进行交换
if (!dirIsNeg[i])
{
std::swap(min, max);
}
tEnter = std::max(min, tEnter);
tExit = std::min(max, tExit);
}
return tEnter <= tExit && tExit >= 0;
}
BVHAccel::getIntersection
Intersection BVHAccel::getIntersection(BVHBuildNode* node, const Ray& ray) const
{
Intersection inter;
// 光线方向
float x = ray.direction.x;
float y = ray.direction.y;
float z = ray.direction.z;
// 判断坐标是否为负
std::array<int, 3> dirsIsNeg{ int(x > 0),int(y > 0),int(z > 0) };
// 判断结点的包围盒与光线是否相交
if (node->bounds.IntersectP(ray, ray.direction_inv, dirsIsNeg) == false) return inter;
if (node->left == nullptr && node->right == nullptr)
{
inter = node->object->getIntersection(ray);
return inter;
}
// 递归判断子节点是否存在与光线相交的情况
auto hit1 = getIntersection(node->left, ray);
auto hit2 = getIntersection(node->right, ray);
if (hit1.distance < hit2.distance)
return hit1;
return hit2;
}
本次作业的代码:
①实现着色过程:
castRay(const Ray ray, int depth) in Scene.cpp: 是用来实现 Path Tracing 算法的,它会用到以下几个函数/变量:
intersect(const Ray ray) in Scene.cpp: 求一条光线与场景的交点
sampleLight(Intersection pos, float pdf) in Scene.cpp: 在场景的所有光源上按面积 uniform 地 sample 一个点,并计算该 sample 的概率密度
sample(const Vector3f wi, const Vector3f N) in Material.cpp: 按照该材质的性质,给定入射方向与法向量,用某种分布采样一个出射方向
pdf(const Vector3f wi, const Vector3f wo, const Vector3f N) in Material.cpp: 给定一对入射、出射方向与法向量,计算 sample 方法得到该出射方向的概率密度
eval(const Vector3f wi, const Vector3f wo, const Vector3f N) in Material.cpp: 给定一对入射、出射方向与法向量,计算这种情况下的 f_r 值
RussianRoulette in Scene.cpp: P_RR, Russian Roulette 的概率
需要注意的几点:
1、我们将光照对物体表面某一点的贡献分为光源和其他反射物,当光源直接能够打到物体上时,不需要再考虑其他反射物的贡献,因为这根光线直接击中了光源
2、需要判断每一根光线是否击中光源
3、没有击中光源才需要通过 Russian Roulette 来计算其他反射物的光照贡献(间接光照)
// Implementation of Path Tracing
Vector3f Scene::castRay(const Ray &ray, int depth) const
{
// TO DO Implement Path Tracing Algorithm here
//hero:检测从像素采样的光线
Intersection inter = intersect(ray);
if (inter.happened)
{
if (inter.m->hasEmission())
{
if (depth == 0)
{
//射线采样到光源,且在最前面,直接返回对光源的采样、
return inter.m->getEmission();
}
else return Vector3f(0, 0, 0);
}
Vector3f L_dir(0, 0, 0);
Vector3f L_indir(0, 0, 0);
//随机sample灯光
Intersection lightInter;
float pdf_light = 0.0f;
//hero:可以理解随机从面光源上采集了一个点,而且每次都构建一个直接光部分(但是照到与否要进行判断)
sampleLight(lightInter, pdf_light);
auto& N = inter.normal;
auto& NN = lightInter.normal;
auto& objPos = inter.coords;
auto& lightPos = lightInter.coords;
float lightDistance = diff.x * diff.x + diff.y * diff.y + diff.z * diff.z;
Ray light(objPos, lightDir);
Intersection light2obj = intersect(light);
// hero:如果反射击中光源,就证明光源无遮挡
if (light2obj.happened && (light2obj.coords - lightPos).norm() < 1e-2)
{
//hero:ray.direction视线方向、lightDir灯方向、N物体采样点的法向,f_r是BDRF(与物体的材质有关,决定了反射贡献)
Vector3f f_r = inter.m->eval(ray.direction, lightDir, N);
//下面直接考虑灯光的直接光照部分
L_dir = lightInter.emit * f_r * dotProduct(lightDir, N) * dotProduct(-lightDir, NN) / lightDistance / pdf_light;
}
//hero:小于俄罗斯轮盘的随机数,则继续进行pathTracing
if (get_random_float() < RussianRoulette)
{
//按照物理属性随机一个可能的采样方向
Vector3f nextDir = inter.m->sample(ray.direction, N).normalized();
//构建下一条采样路线,进行pathtracing
Ray nextRay(objPos, nextDir);
//检查是否有交叉物
Intersection nextInter = intersect(nextRay);
//如果二次碰撞采样,是漫反射物体
if (nextInter.happened && !nextInter.m->hasEmission())
{
//根据wo、wi,计算该采样路线的pdf(概率密度)
float pdf = inter.m->pdf(ray.direction, nextDir, N);
//hero:计算BDRF
Vector3f f_r = inter.m->eval(ray.direction, nextDir, N);
/*hero:①由于使用RussianRoulette,要确保E = P * (Lo / P) + (1 - P) * 0 = Lo(最终期望值)②且递归进行,因为每次castRay都至少计算了L_dir,所以下个采样就符合radiance直接光照 */
L_indir = castRay(nextRay, depth + 1) * f_r * dotProduct(nextDir, N) / pdf / RussianRoulette;
}
}
return L_dir + L_indir;
}
//没有与物体交叉则为0;
return Vector3f(0, 0, 0);
}
② 多线程
我们可以将成像平面进行分块,然后分块地计算 Path Tracing
需要修改 Renderer::Render(const Scene& scene)
void Renderer::Render(const Scene& scene)
{
std::vector<Vector3f> framebuffer(scene.width * scene.height);
float scale = tan(deg2rad(scene.fov * 0.5));
float imageAspectRatio = scene.width / (float)scene.height;
//hero:自定义了一个位置
Vector3f eye_pos(278, 273, -800);
int m = 0;
// 射线数量
int spp = 16;
std::cout << "SPP: " << spp << "\n";
int process = 0;
// 创造匿名函数,为不同线程划分不同块
auto castRayMultiThreading = [&](uint32_t rowStart, uint32_t rowEnd, uint32_t colStart, uint32_t colEnd)
{
for (uint32_t j = rowStart; j < rowEnd; ++j) {
int m = j * scene.width + colStart;
for (uint32_t i = colStart; i < colEnd; ++i) {
// generate primary ray direction
float x = (2 * (i + 0.5) / (float)scene.width - 1) *
imageAspectRatio * scale;
float y = (1 - 2 * (j + 0.5) / (float)scene.height) * scale;
Vector3f dir = normalize(Vector3f(-x, y, 1));
//hero:改进了,每个像素采样spp个射线
for (int k = 0; k < spp; k++) {
framebuffer[m] += scene.castRay(Ray(eye_pos, dir), 0) / spp;
}
m++;
process++;
}
// 互斥锁,用于打印处理进程
std::lock_guard<std::mutex> g1(mutex_ins);
UpdateProgress(1.0 * process / scene.width / scene.height);
}
};
int id = 0;
constexpr int bx = 5;
constexpr int by = 5;
//开个5*5的线程
std::thread th[bx * by];
int strideX = (scene.width + 1) / bx;
int strideY = (scene.height + 1) / by;
// 分块计算光线追踪
for (int i = 0; i < scene.height; i += strideX)
{
for (int j = 0; j < scene.width; j += strideY)
{
//每一个线程负责渲染5*5的块
th[id] = std::thread(castRayMultiThreading, i, std::min(i + strideX, scene.height), j, std::min(j + strideY, scene.width));
id++;
}
}
for (int i = 0; i < bx * by; i++) th[i].join();
UpdateProgress(1.f);
//for (uint32_t j = 0; j < scene.height; ++j) {
// for (uint32_t i = 0; i < scene.width; ++i) {
// // generate primary ray direction
// float x = (2 * (i + 0.5) / (float)scene.width - 1) *
// imageAspectRatio * scale;
// float y = (1 - 2 * (j + 0.5) / (float)scene.height) * scale;
// Vector3f dir = normalize(Vector3f(-x, y, 1));
// for (int k = 0; k < spp; k++){
// framebuffer[m] += scene.castRay(Ray(eye_pos, dir), 0) / spp;
// }
// m++;
// }
// UpdateProgress(j / (float)scene.height);
//}
//UpdateProgress(1.f);
// save framebuffer to file
FILE* fp;
errno_t error;
// save framebuffer to file
//FILE* fp = fopen_s("binary.ppm", "wb", "w+");
error = fopen_s(&fp, "D:\\color\\color.txt", "w+");
(void)fprintf(fp, "P6\n%d %d\n255\n", scene.width, scene.height);
for (auto i = 0; i < scene.height * scene.width; ++i) {
static unsigned char color[3];
color[0] = (unsigned char)(255 * std::pow(clamp(0, 1, framebuffer[i].x), 0.6f));
color[1] = (unsigned char)(255 * std::pow(clamp(0, 1, framebuffer[i].y), 0.6f));
color[2] = (unsigned char)(255 * std::pow(clamp(0, 1, framebuffer[i].z), 0.6f));
fwrite(color, 1, 3, fp);
}
fclose(fp);
}