光线跟踪对象处于错误的位置

时间:2013-10-27 11:51:08

标签: graphics 3d raytracing

我正在写一个简单的光线着色器,我正试图用一个立方体和一些代表圆点的球体来制作一个骰子。球体是正确的,但立方体的两侧是x,y和z轴。立方体以0,0,0为中心。

我检查过顶点的坐标是否正确。我假设我的射线计算是正确的,因为球体位于正确的位置。

以下是光线计算的代码

Ray Image::RayThruPixel(float i, float j)
{
    float alpha = m_tanFOVx * ((j - m_halfWidth) / m_halfWidth);
    float beta = m_tanFOVy * ((m_halfHeight - i) / m_halfHeight);
    vec3 *coordFrame = m_camera.CoordFrame();
    vec3 p1 = (coordFrame[U_VEC] * alpha) + (coordFrame[V_VEC] * beta) - coordFrame[W_VEC];
    return Ray(m_camera.Eye(), p1);
}

其中m_tanFOVx为tan(FOVx / 2),m_tanFOVy为tan(FOVy / 2),FOVx和FOVy为弧度。

要找到光线和三角形的交点,我的代码如下:

 bool Triangle::Intersection(Ray ray, float &fDistance)
{
    static float epsilon = 0.000001;
    bool bHit = false;
    float fMinDist(10000000);


    float divisor = glm::dot(ray.p1, normal);

    // if divisor == 0 then the ray is parallel with the triangle
    if(divisor > -epsilon && divisor < epsilon)
    {
        bHit = false;
    }
    else
    {
        float t = (glm::dot(v0, normal) - glm::dot(ray.p0, normal)) / divisor;
        if(t > 0)
        {
            vec3 P = ray.p0 + (ray.p1 * t);
            vec3 v2 = P - m_vertexA;

            v0 = m_vertexB - m_vertexA;
            v1 = m_vertexC - m_vertexA;
            normal = glm::normalize(glm::cross(v0, v1));

            d00 = glm::dot(v0, v0);
            d01 = glm::dot(v0, v1);
            d11 = glm::dot(v1, v1);
            denom = d00 * d11 - d01 * d01;

            float d20 = glm::dot(v2, v0);
            float d21 = glm::dot(v2, v1);

            float alpha = (d11 * d20 - d01 * d21) / denom;
            float beta = (d00 * d21 - d01 * d20) / denom;
            float gamma = 1.0 - alpha - beta;

            vec3 testP = alpha * m_vertexA + beta * m_vertexB + gamma * m_vertexC;
            if((alpha >= 0 ) &&
                (beta >= 0) &&
                (alpha + beta <= 1))
            {
                bHit = true;
                fDistance = t;
            }
        }
   }
    return bHit;
}

0 个答案:

没有答案