C++ 渲染函数解析:生成主光线并投射到场景
这是一个渲染函数,用于生成主光线并将这些光线投射到场景中,最终将渲染结果保存到文件中。
首先创建一个大小为场景宽度和高度乘积的像素缓冲区。
std::vector<Vector3f> framebuffer(scene.width * scene.height);
计算缩放因子,这里使用了 tan 函数将场景的视角转换为缩放因子。
float scale = std::tan(deg2rad(scene.fov * 0.5f));
计算图像的宽高比。
float imageAspectRatio = (float)scene.width / (float)scene.height;
设置眼睛位置为原点。
Vector3f eye_pos(0);
使用嵌套循环遍历所有像素,生成主光线方向,计算出当前像素的位置,然后将其乘以缩放因子。
for (int j = 0; j < scene.height; ++j)
{
for (int i = 0; i < scene.width; ++i)
{
// generate primary ray direction
float x = (2*(((float)i+0.5)/scene.width-1) * imageAspectRatio * scale;
float y = (1.0-2*((float)j+0.5)/scene.height) * scale;
// TODO: Find the x and y positions of the current pixel to get the direction
// vector that passes through it.
// Also, don't forget to multiply both of them with the variable *scale*, and
// x (horizontal) variable with the *imageAspectRatio*
//vector = op,说明scene在z=-1,故znear距离人眼距离=1
Vector3f dir = normalize(Vector3f(x, y, -1)); // Don't forget to normalize this direction!
framebuffer[m++] = castRay(eye_pos, dir, scene, 0);
}
UpdateProgress(j / (float)scene.height);
}
将主光线方向归一化,然后将其传递给 castRay 函数,该函数将返回相应的颜色值,将其存储在像素缓冲区中。
Vector3f dir = normalize(Vector3f(x, y, -1)); // Don't forget to normalize this direction!
framebuffer[m++] = castRay(eye_pos, dir, scene, 0);
将像素缓冲区保存到文件中。
FILE* fp = fopen("binary.ppm", "wb");
(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] = (char)(255 * clamp(0, 1, framebuffer[i].x));
color[1] = (char)(255 * clamp(0, 1, framebuffer[i].y));
color[2] = (char)(255 * clamp(0, 1, framebuffer[i].z));
fwrite(color, 1, 3, fp);
}
fclose(fp);
注:在渲染过程中,还调用了 UpdateProgress 函数来更新进度条。
原文地址: https://www.cveoy.top/t/topic/ofmI 著作权归作者所有。请勿转载和采集!