我正在用java编写一个光线追踪器,并且我能够追踪球体,但我相信我追踪三角形的方式有问题。
据我了解,这是基本算法:
- 首先确定射线是否与plane三角形已打开。
- 剪裁所有点,使它们与三角形位于同一平面上(因此
xy
以平面为例)。
- 根据沿着新平面向任意方向发出射线时穿过的多边形边的数量,确定潜在的交点是落在三角形内部还是外部。
现在,这是我的实现(特别是第一点):
public Vector getIntersectionVector(Ray ray)
{
Vector planeIntersectionVector = getPlaneIntersectionVector(ray, getPlaneNormal());
if (planeIntersectionVector != null)
{
if (isIntersectionVectorInsideTriangle(planeIntersectionVector))
{
return planeIntersectionVector;
}
else
{
return null;
}
}
else
{
return null;
}
}
Where getPlaceIntersectionVector()
is:
private Vector getPlaneIntersectionVector(Ray ray, Vector planeNormal)
{
double vd = planeNormal.dotProduct(ray.getDirection());
//(p_n \dot r_d) == 0, parallel. (p_n \dot r_d) > 0 Plane normal pointing away from ray.
if (vd >= 0)
{
return null;
}
double distance = planeNormal.distance(0d, 0d, 0d);
double vo = -(planeNormal.dotProduct(ray.getOrigin()) + distance);
double intersectionDistance = vo / vd;
//intersectionDistance <= 0 means the "intersection" is behind the ray, so not a real intersection
return (intersectionDistance <= 0) ? null : ray.getLocation(intersectionDistance);
}
Which basically tries to mimic this:
And this:
Where t
is the distance along the ray that the point hits, ro is the origin of the ray, rd is the direction of the ray, pn refers to the plane normal of the triangle/plane, and d
is the distance from the plane that the triangle is on to the origin (0,0,0)
我这样做错了吗?当我从图像中的第一个像素发出光线时(0,0)
,我看到intersectionDistance
(or t
) 差不多1100
,直觉上这对我来说似乎是错误的。我认为交点会更近。
以下是相关数据:
射线原点(0,0,1)
,射线方向大致为(0.000917, -0.4689, -0.8833)
.
三角形的顶点为(-0.2, 0.1, 0.1)
, (-0.2, -0.5, 0.2)
, (-0.2, 0.1, -0.3)
,这使得飞机正常(-1, 0, 0)
.
根据我的代码,射线与平面相交1090
正如我之前提到的,距离对我来说似乎是错误的。场景在每个方向上都只有 -1.0 到 1.0,这意味着交叉路口距离非常非常远。
我做的平面交叉错了吗?
请让我知道哪里需要澄清,以及您是否需要更多信息。