【发布时间】:2021-11-26 22:57:11
【问题描述】:
我目前正在从头开始阅读《计算机图形学》一书,但在我的 rust 项目中无法获得第一章中关于 raytracer 的示例。 我正在使用image crate 来渲染图片。我将坐标从渲染器(x 和 y,原点左上角)转换为我的视口(原点在中间,z 在 10)。
fn canvas_to_viewport(x: u32, y: u32, scene: &Scene) -> Point {
let x: f64 = x as f64 - (scene.width as f64 / 2.) ;
let y: f64 = y as f64 - (scene.width as f64 / 2.) ;
// x * viewport width / camera width
// y * viewport height / camera height
Point {
x: x * 1.,
y: y * 1.,
z: 10.
}
}
然后我通过我的 trace_ray 函数获取像素的颜色,该函数使用辅助函数 intersect_ray_sphere 查找与球体最近的交点。
fn trace_ray(camera: Point, viewport: Point, t_min: f64, _t_max: f64, spheres: &Vec<Sphere>) -> Color {
let mut closest_t = 1000.;
let mut closest_sphere_color = Color (255,255,255);
for sphere in spheres {
let (t1, t2) = intersect_ray_sphere(camera, viewport, &sphere);
if t1 > t_min && t1 < closest_t {
closest_t = t1;
closest_sphere_color = sphere.color;
};
if t2 > t_min && t2 < closest_t {
closest_t = t2;
closest_sphere_color = sphere.color;
};
}
closest_sphere_color
}
fn intersect_ray_sphere(o: Point, d: Point, sphere: &Sphere) -> (f64, f64) {
let r = sphere.radius;
let co = Point {
x: o.x - sphere.center.x,
y: o.y - sphere.center.y,
z: o.z - sphere.center.z
};
let a = dot_product(&d, &d);
let b = 2. * dot_product(&co, &d);
let c = dot_product(&co, &co) - r*r;
let discriminant = b*b - 4.*a*c;
if discriminant < 0. {
return (1000., 1000.);
};
let t1 = (-b + discriminant.sqrt()) / (2.*a);
let t2 = (-b - discriminant.sqrt()) / (2.*a);
return (t1, t2)
}
如您在此处所见,离中间较远的球体是扭曲的:
我玩过几乎所有的参数,但似乎无法弄清楚。非常感谢您的每一次帮助。
【问题讨论】:
-
简单愚蠢的问题,但在顶部你有
let y: ...,然后对于y,你使用scene.width,实际上它可能应该是scene.height。 -
谢谢我已经注意到了这个错误,但不幸的是它没有帮助。
标签: rust graphics 3d raytracing