gpt4 book ai didi

c++ - GLSL Sphere - 射线相交几何解决方案

转载 作者:行者123 更新时间:2023-12-03 06:54:57 26 4
gpt4 key购买 nike

我正在尝试在 GLSL 中实现球体射线相交,包括几何和解析解。我在解决 geom one 时遇到了麻烦,它应该与我如何返回 true 或 false 有关:

bool hitSphere(Ray ray, Sphere sphere, float t_min, float t_max, out float t_out) {
// Geometric solution
float R2 = sphere.radius * sphere.radius;
vec3 L = sphere.position - ray.origin;
float tca = dot(L, normalize(ray.direction));
// if(tca < 0) return false;

float D2 = dot(L, L) - tca * tca;
if(D2 > R2) return false;
float thc = sqrt(R2 - D2);
float t0 = tca - thc;
float t1 = tca + thc;

if(t0 < t_max && t0 > t_min) {
t_out = t0;
return true;
}

if(t1 < t_max && t1 > t_min) {
t_out = t1;
return true;
}

return false;
}
enter image description here
我认为问题在于我如何处理 t0 和 t1 对于无、一种或两种交叉情况。
编辑:确实有效的分析版本:
vec3 oc = ray.origin - sphere.position;
float a = dot(ray.direction, ray.direction);
float b = dot(oc, ray.direction);
float c = dot(oc, oc) - sphere.radius * sphere.radius;

float discriminant = b * b - a * c;

if (discriminant > 0.0f) {
if(b > 0)
t_out = (-b + sqrt(discriminant)) / a;
else
t_out = (-b - sqrt(discriminant)) / a;

if(t_out < t_max && t_out > t_min) {
return true;
}
}

return false;
Analytical Result

最佳答案

该问题是由 t_out 引起的.该算法必须计算 t_out那样,那个X是射线和球体表面的交点,对于:

X = ray.origin + ray.direction * t_out; 
在工作算法中 t_out取决于 ray.direction的长度. t_out变小,如果 vector 的幅度 ray.direction更伟大。
在算法中,它不起作用, ray.direction被归一化。
float tca = dot(L, normalize(ray.direction));

因此 t_out计算光线方向长度为 1。实际上您计算的是 t_out'哪里 t_out' = t_out * length(ray.direction) .
t0分别 t1ray.direction的长度:
bool hitSphere_2(Ray ray, Sphere sphere, float t_min, float t_max, out float t_out)
{
float R2 = sphere.radius * sphere.radius;
vec3 L = sphere.position - ray.origin;
float tca = dot(L, normalize(ray.direction));
// if(tca < 0) return false;

float D2 = dot(L, L) - tca * tca;
if(D2 > R2) return false;
float thc = sqrt(R2 - D2);
float t0 = tca - thc;
float t1 = tca + thc;

if (t0 < t_max && t0 > t_min) {
t_out = t0 / length(ray.direction); // <---
return true;
}

if (t1 < t_max && t1 > t_min) {
t_out = t1 / length(ray.direction); // <---
return true;
}

return false;
}

关于c++ - GLSL Sphere - 射线相交几何解决方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63922206/

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