Ray Tracing in One Weekend Part3
完成到第七章抗锯齿的内容
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #include <iostream> #include<fstream> #include<string> #include "v3d.h" #include "ray.h" #include "color.h" #include "rtweekend.h" #include "hittable_list.h" #include "sphere.h" #include"camera.h" using namespace std; // Type aliases for vec3 using point3 = vec3; // 3D point using color = vec3; // RGB color double hit_sphere( const point3& center, double radius, const ray& r) { vec3 oc = r.origin() - center; auto a = r.direction().length_squared(); //t2b⋅b+2tb⋅(A−C)+(A−C)⋅(A−C)−r2=0 函数关于t, P(t)=A+tb auto half_b = dot(oc, r.direction()); auto c = oc.length_squared() - radius * radius; auto discriminant = half_b * half_b - a * c; if (discriminant < 0) { return -1.0; } else { return (-half_b - sqrt (discriminant)) / a; } } color ray_color( const ray& r , const hittable& world) { hit_record rec; if (world.hit(r, 0, infinity, rec)){ //如果打中了球,在球的范围内,就变成彩色 return 0.5 * (rec.normal + color(1, 1, 1)); } vec3 unit_direction = unit_vector(r.direction()); //显示蓝色背景 auto back = 0.5 * (unit_direction.y() + 1.0); return (1.0 - back) * color(1.0, 1.0, 1.0) + back * color(0.5, 0.7, 1.0); } int main() { // Image const auto aspect_ratio = 16.0 / 9.0; const int image_width = 400; const int image_height = static_cast < int >(image_width / aspect_ratio); const int sample_per_pixel = 100; //采样次数 // World hittable_list world; world.add(make_shared<sphere>(point3(0, 0, -1), 0.5)); world.add(make_shared<sphere>(point3(0, -100.5, -1), 100)); // Camera camera cam; //定义函数放到头文件里面了 // Render ofstream file( "graph1-2.ppm" ); file << "P3\n" << image_width << ' ' << image_height << "\n255\n" ; for ( int j = image_height - 1; j >= 0; --j) { std::cerr << "\rScanlines remaining: " << j << ' ' << std::flush; for ( int i = 0; i < image_width; ++i) { color pix_color(0, 0, 0); for ( int s = 0; s < sample_per_pixel; s++) { //采样100次,即图片的每个点位都发出的光通过random随机不同方向,取样100次求平均值 auto u = (i + random_double()) / (image_width - 1); auto v = (j + random_double()) / (image_height - 1); ray r = cam.get_ray(u, v); pix_color += ray_color(r, world); } write_color(file, pix_color,sample_per_pixel); } } std::cerr << "\nDone.\n" ; } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话