gpt4 book ai didi

c++ - 光线追踪球体反射错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:07 25 4
gpt4 key购买 nike

我正在尝试实现光线追踪算法,但我在计算球形物体的反射光线时遇到了一些问题。看来对于某些特定的光线,反射光线恰好通过并与追迹光线共线。波纹管是我如何记录射线 - 球体交点:

bool Sphere::intersectLocal(const ray & r, isect & i) const {
Vec3d P = r.getPosition();
Vec3d D = r.getDirection();
//D.normalize();
double a = dot(D, D);
double b = 2 * dot(P, D);
double c = dot(P, P) - 1;
double delta = b * b - 4 * a * c;
if (delta < 0)
return false;
if (delta == 0) {
double t = -b / 2 * a;
Vec3d Q = P + t * D;
Vec3d N = Q;
N.normalize();
i.setT(t);
i.setN(N);
i.setObject(this);
return true;
}
if (delta > 0) {
double t1 = (-b - sqrt(delta)) / 2 * a;
double t2 = (-b + sqrt(delta)) / 2 * a;
double t;
if (t1 > 0) t = t1;
else if (t2 > 0) t = t2;
else return false;
Vec3d N = P + t * D;
N.normalize();
i.setT(t);
i.setN(N);
i.setObject(this);
return true;
}
return false;
}

这就是我计算每个交叉点的反射光线的方式:

isect i;
if (scene - > intersect(r, i)) {
// An intersection occured!
const Material & m = i.getMaterial();
double t = i.t;
Vec3d N = i.N;
Vec3d I = m.shade(scene, r, i); //local illumination
if (!m.kr(i).iszero() && depth >= 0) {
// compute reflection direction
Vec3d raydir = r.getDirection();
Vec3d refldir = 2 * dot(-raydir, i.N) * i.N + raydir;
refldir.normalize();
ray reflectionRay = ray(r.at(i.t), refldir, ray::RayType::REFLECTION);
Vec3d reflection = traceRay(reflectionRay, thresh, depth - 1);
Vec3d R = reflection;
I += R;
}
return I;
} else {
// No intersection. This ray travels to infinity, so we color
// it according to the background color, which in this (simple) case
// is just black.
return Vec3d(0.0, 0.0, 0.0);
}

上面的代码似乎对于球体上光线相交的大多数点都可以正常工作,但对于其他点,它并没有像我预期的那样反射

enter image description here

enter image description here

enter image description here

最佳答案

如果我没看错,这会使法线面向与光线相同的方向。所以对于 ray==normal==reflected ray 什么都不会反射。

Vec3d Q = P + t * D;
Vec3d N = Q;

关于c++ - 光线追踪球体反射错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47858571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com