C++ 渲染器主渲染函数解析:逐行解释 Render 函数
该函数是渲染器的主要渲染函数,用于迭代图像中的每个像素,生成主光线并将这些光线投射到场景中。帧缓冲区的内容将保存到文件中。
- 第 2-3 行:定义了一个帧缓冲区,用于存储渲染后的像素颜色值。
- 第 5 行:计算了一个比例因子,用于将图像的视野角度转换为屏幕上的像素坐标。
- 第 8 行:定义了一个 eye_pos 变量,即视点位置,这里默认为原点。
- 第 9 行:定义了一个变量 m,用于遍历帧缓冲区。
- 第 10-23 行:嵌套循环遍历每个像素,计算出每个像素的光线方向,并调用 castRay 函数进行投射,得到该像素的颜色值,最后将该颜色值存储到帧缓冲区中。
- 第 24 行:更新渲染进度。
- 第 27-39 行:将帧缓冲区中的颜色值保存到文件中,生成 PPM 格式的图像文件。
// [comment]
// The main render function. This where we iterate over all pixels in the image, generate
// primary rays and cast these rays into the scene. The content of the framebuffer is
// saved to a file.
// [/comment]
void Renderer::Render(const Scene& scene)
{
std::vector<Vector3f> framebuffer(scene.width * scene.height);
//
float scale = std::tan(deg2rad(scene.fov * 0.5f));
//宽高比
float imageAspectRatio = (float)scene.width / (float)scene.height;
// Use this variable as the eye position to start your rays.
Vector3f eye_pos(0);
int m = 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);
}
// save framebuffer to file
FILE* fp = fopen('binary.ppm', 'wb');
(void)fprintf(fp, 'P6
%d %d
255
', 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);
}
原文地址: https://www.cveoy.top/t/topic/ofmB 著作权归作者所有。请勿转载和采集!