射线与椭圆体相交

时间:2018-09-01 18:15:10

标签: c++ math intersection

我正在尝试通过“挤压”空间并进行射线与球体来实现射线与椭球的交点:

  1. 创建对角线为椭圆形的mat3 S

  2. 通过将开始和方向乘以S的倒数来产生射线

  3. 在局部空间中与半径为1.0的球面相交的光线

  4. 将hitPoint乘以S即可取消压缩。

这是射线与球体:

float P = glm::dot(dir, sphereCenter-start);
float L = glm::distance(start, sphereCenter);
float d = sqrt(L*L - P*P);
if (d < radius) {
    float x0 = sqrt(1.f - d*d);
    hitPoint = start + dir*(P - x0);
    hitNormal = glm::normalize(hitPoint - sphereCenter);
}
else if (d == radius) {
    hitPoint = start + dir*P;
    hitNormal = glm::normalize(hitPoint - sphereCenter);
}
else {
    return false;
}
if (glm::distance(start, hitPoint) > dist) return false;
return true;

这是压扁的部分:

glm::vec3 S = start;
    glm::vec3 Dir = dir;

    auto sphereCenter = thisEntity()->transform()->getPosition();
    auto scale = thisEntity()->transform()->getScale();

    glm::mat3 q = glm::mat3(0);
    float x = _radius.x * scale.x;
    float y = _radius.y * scale.y;
    float z = _radius.z * scale.z;
    q[0][0] = x;
    q[1][1] = y;
    q[2][2] = z;
    glm::mat3 qI = glm::inverse(q);

    S = qI * S;
    Dir = qI * Dir;

    //calculate hit point in world space squished
    glm::vec3 hitPoint, hitNormal;
    if (!IntersectionsMath::instance()->segmentVsSphere(sphereCenter, S, Dir, dist, 1.f, hitPoint, hitNormal)) return;

    hitPoint = q * hitPoint;

    hit.pushHit(hitPoint, hitNormal, this);

当前的射线球体代码是针对世界位置的,我正在尝试使其在原点起作用,所以没关系。雷vs规则球面效果很好,椭球是问题所在。 我花了很多时间在此上,但某些地方出了问题。

1 个答案:

答案 0 :(得分:2)

问题:

  

扩展中心很重要。

解决方案:

  

对椭圆中心进行缩放。

...而不是您现在正在做的原点。这是因为,尽管射线的方向相同(只是方向矢量),但按比例缩放的源与球体中心之间的相对位移将有所不同:

  • 缩放原点(当前代码)

    来源S' = qI * S,居中C' = qI * C --- S' - C' = qI * (S - C)

  • 缩放椭球中心(正确步骤):

    来源S" = qI * (S - C),居中C" = C --- S" - C" = qI * (S - C) - C

两个位移因原始椭球的位置而异;因此,您当前的射线可能会错过/给出误报。


更正的代码:

// scale about the ellipsoid's position by subtracting before multiplying
// more appropriate name would be "ellipseCenter" to avoid confusion
S_ = qI * (S - sphereCenter);

// this ::normalize should really be in the intersection function
Dir_ = glm::normalize(qI * Dir); 

// calculate hit point in world space squished
// ... but around the origin in the squashed coordinate system
glm::vec3 hitPoint, hitNormal;
if (!IntersectionsMath::instance()->segmentVsSphere(
          glm::vec3::ZERO, S_, Dir_,
          dist, 1.f,
          hitPoint, hitNormal)) return;

// re-apply the offset
hitPoint = q * hitPoint + sphereCenter

// problem: hitNormal will not be correct for the ellipsoid when scaled
// solution: divide through each component by square of respective semi-axis
// (will provide proof upon request)
hitNormal.x /= (x * x); hitNormal.y /= (y * y); hitNormal.z /= (z * z);