【Ray Tracing in One Weekend】(ch0~1)c++生成的第一张图片
2017-11-10 13:13
1051 查看
Chapter 0: Overview
作者讲了讲自己的教学经验以及有关光线追踪的一些事。作者推荐我们使用c++。
Chapter 1: Output an image
展示了如何用代码生成第一张图片。用到了PPM格式。这里 有PPM格式的详解。
书中实例代码如下(添加了输出到 txt 文件的代码,原代码只输出到命令行):
#include <iostream> #include <fstream> using namespace std; int main() { ofstream outfile; outfile.open("firstImage.txt"); int nx = 200; int ny = 100; outfile << "P3\n" << nx << " " << ny << "\n255\n"; for (int j = ny - 1; j >= 0; j--) { for (int i = 0; i < nx; i++) { float r = float(i) / float(nx); float g = float(j) / float(ny); float b = 0.2f; int ir = int(255.99f*r); int ig = int(255.99f*g); int ib = int(255.99f*b); outfile << ir << " " << ig << " " << ib << "\n"; } } outfile.close(); return 0; }
输出结果如下,拷贝 firstImage.txt 并修改后缀为 .ppm。
使用 Photoshop CC 2017 打开后,如图所示:
从如下三行代码中我们可以看到:
float r = float(i) / float(nx); float g = float(j) / float(ny); float b = 0.2f;
在RGB三色通道中,从上到下,绿色通道值减小;从左到右,红色通道值增加;而蓝色通道值不变。所得图片即上图。
我们可以在 Photoshop 中验证一下:
把蓝色通道值,即 B 固定为51,我们发现左边的拾色盘跟我们的图片一模一样。从上到下,G 值减小;从左到右,R 值增加。右上角为黄色(255,255,51)。
那如果我们想得到如下图中拾色盘中的图片,该怎么做呢?
观察得,R 值固定为100,从左到右 B 值增加,从上到下,G 值减小。则修改代码为:
float g = float(j) / float(ny); float b = float(i) / float(nx); int ir = 100; int ig = int(255.99f*g); int ib = int(255.99f*b);
所得图片如下:
相关文章推荐
- 问题三十:《Ray Tracing In One Weekend》封面图形生成
- 《Ray Tracing in One Weekend》——Chapter 9: Dielectrics
- 【Ray Tracing in One Weekend】(ch11&12)景深效果与封面图的渲染
- 《Ray Tracing in One Weekend》——Chapter 1: Output an image
- 《Ray Tracing in One Weekend》——Chapter 10: Positionable camera
- 《Ray Tracing in One Weekend》——Chapter 2: The vec3 class
- 【Ray Tracing in One Weekend】(ch5)法向量的可视化与多个球的出现
- 【Ray Tracing in One Weekend】(ch6)Ray Tracer 里的反走样
- 《Ray Tracing in One Weekend》——Chapter 11: Defocus Blur
- 【Ray Tracing in One Weekend】(ch9)Dielectrics
- 【Ray Tracing in One Weekend】(ch3)射线类
- 【Ray Tracing in One Weekend】(ch8)Metal&Lambertian
- 总结《Ray Tracing in One Weekend》
- 《Ray Tracing in One Weekend》——Chapter 3: Rays, a simple camera, and background
- 《Ray Tracing in One Weekend》——Chapter 4: Adding a sphere
- 【Ray Tracing in One Weekend】(ch10)Positionable camera
- 【Ray Tracing in One Weekend】(ch2)世界的基石?向量
- 《Ray Tracing in One Weekend》——Chapter 5: Surface normals and multiple objects
- 《Ray Tracing in One Weekend》——Chapter 6: Antialiasing
- 《Ray Tracing in One Weekend》——Chapter 12: What's next?