0

我在 WPF 窗口中使用 SharpGL,并使用自定义着色器导航和绘制测量点云,以减少基于距离的点大小。一切运行良好,但我最近尝试添加通过鼠标单击选择最接近射线投射的点的功能。我在此链接中使用了步骤 0 到 4:http: //antongerdelan.net/opengl/raycasting.html

我面临的问题是光线似乎非常轻微地向相机矢量移动,导致我错过了我点击的点,只刮掉了它们的内边缘。我也在从相机位置开始绘制光线,所以最初光线应该在移动相机之前显示为一个点(向下看轨迹线),但我可以看到它清楚地绘制到屏幕中间。这是一个屏幕截图,显示了当我单击它的中心时射线错过了点的位置:

截屏

这是我用来计算光线开始和结束坐标的代码:

    public void CreateVerticesForMouseCoord(OpenGL gl, float winx, float winy)
    {

        int[] viewport = new int[4];
        gl.GetInteger(OpenGL.GL_VIEWPORT, viewport);
        float window_width = viewport[2];
        float window_height = viewport[3];

        Console.WriteLine("Window size: " + window_width + "," + window_height);

        vec4 clipPosition = new vec4(0.0f, 0.0f, 1.0f, 1.0f);

        // Normalize the x and y coordinates
        clipPosition.x = 2.0f * (winx / window_width) - 1.0f;
        clipPosition.y = -2.0f * (winy / window_height) + 1.0f;

        mat4 viewInv = glm.inverse(viewMatrix);
        mat4 projInv = glm.inverse(projectionMatrix);

        vec4 camPosition = projInv * clipPosition;
        camPosition.w = 0;
        camPosition.z = -1;
        vec4 worldPosition = viewInv * camPosition;

        vec4 camCamPos = new vec4(0.0f, 0.0f, 0.0f, 1.0f);
        vec4 objCamPos = glm.inverse(viewMatrix) * camCamPos;
        vec4 camCamDir = new vec4(0.0f, 0.0f, -1.0f, 0.0f);
        vec4 objCamDir = glm.inverse(viewMatrix) * camCamDir;

        float x1 = objCamPos.x + 30.0f * worldPosition.x;
        float y1 = objCamPos.y + 30.0f * worldPosition.y;
        float z1 = objCamPos.z + 30.0f * worldPosition.z;
        float x2 = objCamPos.x - 0.0f * worldPosition.x;
        float y2 = objCamPos.y - 0.0f * worldPosition.y;
        float z2 = objCamPos.z - 0.0f * worldPosition.z;

        Console.WriteLine("Screen coordinates: " + winx + ","+winy);
        Console.WriteLine("Clip coordinates: " + clipPosition.x + "," + clipPosition.y + "," + clipPosition.z+ ","+ clipPosition.w);
        Console.WriteLine("Camera coordinates: " + camPosition.x + "," + camPosition.y + "," + camPosition.z+","+ camPosition.w);
        Console.WriteLine("World coordinates: " + worldPosition.x + "," + worldPosition.y + "," + worldPosition.z+","+ worldPosition.w);

        Console.WriteLine("Camera Position: " + objCamPos.x + "," + objCamPos.y + "," + objCamPos.z + "," + objCamPos.w);
        Console.WriteLine("Camera Direction: " + objCamDir.x + "," + objCamDir.y + "," + objCamDir.z + "," + objCamDir.w);

        float[] mousePointArray = { x1, y1, z1, x2, y2, z2 };

输出如下所示:

    Window size: 470,314
    Screen coordinates: 316,184
    Clip coordinates: 0.3446808,-0.1719745,1,1
    Camera coordinates: 0.1877808,-0.06259361,-1,0
    World coordinates: 0.1877808,-0.06259361,-1,0
    Camera Position: 4,7,6,1
    Camera Direction: 0,0,-1,0

我单击的屏幕中心越远,偏移量似乎就越大。非常感谢我能得到诊断的任何帮助,我花了两天时间阅读文章并摆弄代码无济于事。

4

0 回答 0