c++ - 平面和射线相交的参数常数 t 的值?

标签 c++ math graphics opencl plane

我正在实现射线和矩形相交测试。首先,我测试射线是否与平面相交,如果相交,然后我看看它是否位于矩形的边界内。

代码如下:

float intersectQuad(Ray r, float3 p1, float3 p2, float3 p3, float3 p4, float3* normal)
{
   float3 x1 = p2 - p1;
   float3 x2 = p4 - p1;
   float t;

   float3 n = normalize(cross(x2, x1));
   float denom = dot(n, r.dir); 

    if (denom > 0.00000000001) 
    { 
       float3 p0l0 = normalize(p1 - r.origin); 
       t = dot(p0l0, n) / denom; 

       printf(" %f ", t);

       if( t > 0.000000000001f )
       {
         float3 hitPoint = r.origin + r.dir * t;

         float3 V1 = normalize(p2 - p1);
         float3 V2 = normalize(p3 - p2);
         float3 V3 = normalize(p4 - p3);
         float3 V4 = normalize(p1 - p4);
         float3 V5 = normalize(hitPoint - p1);
         float3 V6 = normalize(hitPoint - p2);
         float3 V7 = normalize(hitPoint - p3);
         float3 V8 = normalize(hitPoint - p4);

         if (dot(V1,V5) < 0.0f) return 0.0f;
         if (dot(V2,V6) < 0.0f) return 0.0f;
         if (dot(V3,V7) < 0.0f) return 0.0f;
         if (dot(V4,V8) < 0.0f) return 0.0f;

         *normal = n;
         return t;
       }
    } 

 return 0.0f; 
}

我的理解是t的值应该是 0.0f < t < 1.0f 但是当我打印 t 的值时我有时会看到值 > 1.0f .

我的代码有问题吗?

最佳答案

首先,如果光线方向 vector 针对 r.origin + r.direction*t 进行归一化,则 t 是从原点到 hitPoint 的距离。该距离可以有任何值。

其次,我会将返回值类型更改为 bool,目的是避免浮点运算,以便在函数的调用范围内再次将结果与 0.0f 进行比较。

第三,根据个人喜好,使用提前退出技术按照以下方式重新格式化代码,并尽可能标记 const 值。

bool intersectQuad(Ray r, float3 p1, float3 p2, float3 p3, float3 p4, float3* outNormal, float* outT)
{
   const float3 x1 = p2 - p1;
   const float3 x2 = p4 - p1;
   const float3 n = normalize(cross(x2, x1));
   const float denom = dot(n, r.dir); 

   if (denom < 0.00000000001) return false;

   const float3 p0l0 = normalize(p1 - r.origin); 
   const float t = dot(p0l0, n) / denom; 

   printf(" %f ", t);

   if( t < 0.000000000001f ) return false;

   const float3 hitPoint = r.origin + r.dir * t;

   const float3 V1 = normalize(p2 - p1);
   const float3 V2 = normalize(p3 - p2);
   const float3 V3 = normalize(p4 - p3);
   const float3 V4 = normalize(p1 - p4);
   const float3 V5 = normalize(hitPoint - p1);
   const float3 V6 = normalize(hitPoint - p2);
   const float3 V7 = normalize(hitPoint - p3);
   const float3 V8 = normalize(hitPoint - p4);

   if (dot(V1,V5) < 0.0f) return false;
   if (dot(V2,V6) < 0.0f) return false;
   if (dot(V3,V7) < 0.0f) return false;
   if (dot(V4,V8) < 0.0f) return false;

   *outNormal = n;
   *outT = t;
   return true;
}

关于c++ - 平面和射线相交的参数常数 t 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55316227/

相关文章:

c++ - 什么是底层容器?

c++ - 概率密度的正交例程

javascript - 计算 d3 路径中的弧/点

opengl 3.3 z-fighting 正交 2d View

.net - 有没有一种简单的方法可以使用 .NET 将图像转换为灰度图像

c++ - Websphere MQ - 获取时出现错误,原因代码为 2042

c++ - BST 关于 C++ 错误

C++自动更新程序

algorithm - 什么样的数学可以帮助我解决编程问题?

java - 如何调整从 g.drawLine() 方法绘制的线条的粗细