C++ 渲染器主函数解析:生成光线并渲染场景
这是一个渲染器的主函数,用于在图像上迭代所有像素,生成主光线并将这些光线投射到场景中。帧缓冲区的内容将保存到文件中。
代码中的注释解释如下:
- 首先创建一个大小为场景宽度 x 场景高度的像素帧缓冲区。
- 计算缩放比例,这里使用了场景的视角角度,并将其转换为弧度。
- 计算图像的宽高比,它等于宽度除以高度。
- 确定起始点的位置 'eye_pos',这是我们的视点位置。在这里设置为(0,0,0)。
- 开始迭代每个像素。使用当前像素的x和y位置来计算通过它的方向向量。使用该方向向量和视点位置调用 'castRay' 函数,该函数返回该像素的颜色值,并将其存储在帧缓冲区中。
- 最后将帧缓冲区的内容保存到一个文件中。
// [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\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);
}
原文地址: https://www.cveoy.top/t/topic/ofmF 著作权归作者所有。请勿转载和采集!