我的基本问题是 - 使用“gluUnProject”从我的鼠标/光标位置获取射线或法线向量的正确方法是什么。
我已将 mesa glu C 代码中的“gluUnProject”代码转换为 C#。
public Vector3 UnProject(Matrix4 projectionMatrix, Matrix4 viewMatrix, int viewX, int viewY, int viewWidth, int viewHeight)
{
var finalMatrix = viewMatrix.Multiply(projectionMatrix).Invert();
var vec = new Vector4(this, 1);
vec.X = (vec.X - viewX) / viewWidth;
vec.Y = (vec.Y - viewY) / viewHeight;
vec = (vec * 2) - 1;
vec.Y = -vec.Y;
var outVec = vec.Transform(finalMatrix);
outVec.X /= outVec.W;
outVec.Y /= outVec.W;
outVec.Z /= outVec.W;
return outVec.ToVector3();
}
然后我从我的 Camera 对象中调用此方法:
public Vector3 UnProject(Vector3 screenPosition)
{
return screenPosition.UnProject(ProjectionMatrix, ViewMatrix, ViewPort.Location.X, ViewPort.Location.Y, ViewPort.Size.X, ViewPort.Size.Y);
}
为了从射线中获取我的法线向量,我这样做:
var rayLoc = camera.UnProject(new Vector3(Game.Mouse.Location, 0));
var rayLoc2 = camera.UnProject(new Vector3(Game.Mouse.Location, 1));
var rayDirection = (rayLoc2 - rayLoc).Normalize();
一切正常,直到我将我的 LookAt 点移到 X 中的 1 上并在 X 和 Y 轴上稍微旋转相机。之后,向量不再正确。我不知道我做错了什么??
编辑:仔细观察后,我认为我的 Matrix4.Invert 方法可能是原因。我正在尝试使用 Row Major,有什么想法吗?
public Matrix4 Invert()
{
var mat = new Matrix4(
new Vector4(
Y.Y*Z.Z*W.W - Y.Y*Z.W*W.Z - Z.Y*Y.Z*W.W + Z.Y*Y.W*W.Z + W.Y*Y.Z*Z.W - W.Y*Y.W*Z.Z,
-Y.X*Z.Z*W.W + Y.X*Z.W*W.Z + Z.X*Y.Z*W.W - Z.X*Y.W*W.Z - W.X*Y.Z*Z.W + W.X*Y.W*Z.Z,
Y.X*Z.Y*W.W - Y.X*Z.W*W.Y - Z.X*Y.Y*W.W + Z.X*Y.Y*W.Y + W.X*Y.Y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