Ray Sphere Intersection:处理角落情况

时间:2012-07-08 04:42:52

标签: geometry intersection raytracing

我正在努力在2d中实现强大的射线球体交叉例程。我一起破解了一个相当小的功能,我无法正常调试,因为它在GPU上运行。我的灵感来自于: Circle line-segment collision detection algorithm?http://paulbourke.net/geometry/sphereline/。我不知道我应该在哪里寻找错误。我错过了一些明显的东西吗由于我对实际的圆弧段碰撞感兴趣,因此我检查圆是否包围线的情况作为交点返回。

以下是相关的代码段:

bool CircleSegmentIntersection2d(float2 x0, float2 x1, float2 center, float r) {

float2 d = x1-x0;
float2 f = x0-center;

float a = dot2d(d,d);
float b = 2*dot2d(f,d);
float c = dot2d(f,f)-r*r;

float discriminant = b*b-4*a*c;

if( discriminant < 0 ) {
      // no intersection
      return false;
} else {
    discriminant = sqrt(discriminant);
    // either solution may be on or off the ray so need to test both
    float sol1 = (-b + discriminant)/(2*a);
    float sol2 = (-b - discriminant)/(2*a);

    float t0 = min(sol1, sol2);
    float t1 = max(sol1, sol2);

    if (t1 < 0)
        return false;

    // Line segment doesn't intersect and on outside of sphere, in which case both values of t will either be less than 0 or greater than 1.
    if (0 < t0 && 0 < t1 || t0 > 1 && t1 > 1)
        return false;

    // Line segment doesn't intersect and is inside sphere, in which case one value of t will be negative and the other greater than 1.
    if (t0 < 0 && t1 > 1) {
        return true;
    }

    // Line segment intersects at one point, in which case one value of t will be between 0 and 1 and the other not.
    if (t0 < 0 && 0 <= t1 && t1 <= 1) {
        return true;
    }

    // Line segment intersects at two points, in which case both values of t will be between 0 and 1.
    if (0 <= t1 && t1 <= 1 && 0 <= t0 && t0 <= 1) {
        return true;
    }

    // Line segment is tangential to the sphere, in which case both values of t will be the same and between 0 and 1.
    if (length(t0-t1) < 0.005f) {
        return true;
    }
}

return false;

}

其中dot2d由:

定义
float dot2d(float2 a, float2 b) {
return a.x*b.x+a.y*b.y;
}

谢谢你的时间!

0 个答案:

没有答案