盒子画错了

Incorrect drawing of box

我画一个盒子形状有问题(它很长)

创建矩阵的代码(其中宽度和高度是 window 的大小):

GL.Enable(EnableCap.DepthTest);
                GL.DepthMask(true);
                GL.DepthFunc(DepthFunction.Lequal);

                float aspect = (float)width / (float)height;

                matrix = Matrix4.CreateTranslation(0, 0, -100) * // 100 > 51 
                                 Matrix4.CreatePerspectiveOffCenter(-aspect, aspect, 1, -1, 1, 1000);

绘制方框的代码:

public void Box(double w, double h, double d)
    {
        float x1 = (float)-w / 2f; float x2 = (float)w / 2f;
        float y1 = (float)-h / 2f; float y2 = (float)h / 2f;
        float z1 = (float)-d / 2f; float z2 = (float)d / 2f;

        var vertbuffer = new Vector3[]
        {
            // front
            new Vector3(x1, y1, z1),
            new Vector3(x2, y1, z1),
            new Vector3(x2, y2, z1),
            new Vector3(x1, y2, z1),

            // right
            new Vector3(x2, y1, z1),
            new Vector3(x2, y1, z2),
            new Vector3(x2, y2, z2),
            new Vector3(x2, y2, z1),

            // back
            new Vector3(x2, y1, z2),
            new Vector3(x1, y1, z2),
            new Vector3(x1, y2, z2),
            new Vector3(x2, y2, z2),

            // left
            new Vector3(x1, y1, z2),
            new Vector3(x1, y1, z1),
            new Vector3(x1, y2, z1),
            new Vector3(x1, y2, z2),

            // top
            new Vector3(x1, y1, z2),
            new Vector3(x2, y1, z2),
            new Vector3(x2, y1, z1),
            new Vector3(x1, y1, z1),

            // bottom
            new Vector3(x1, y2, z1),
            new Vector3(x2, y2, z1),
            new Vector3(x2, y2, z2),
            new Vector3(x1, y2, z2),
        };

        GL.EnableClientState(ArrayCap.VertexArray);
        GL.EnableClientState(ArrayCap.NormalArray);

        GL.VertexPointer(3, VertexPointerType.Float, Vector3.SizeInBytes, vertbuffer);
        GL.NormalPointer(NormalPointerType.Float, Vector3.SizeInBytes, normalBuffer);

        GL.Color4(fillColor);
        GL.DrawArrays(PrimitiveType.Quads, 0, vertbuffer.Length);

        GL.Color4(strokeColor);
        GL.LineWidth((float)strokeWeight);

        for (int i = 0; i < vertbuffer.Length / 4; i++)
        {
            GL.DrawArrays(PrimitiveType.LineLoop, i * 4, 4);
        }
    }

看起来前四边形确实没有画:

我试图减少 Matrix4.CreatePerspectiveOffCenter 的 depthFar 参数,但这不起作用。

编辑:我已经更新了代码。

不在近平面和远平面之间的所有几何体都被剪裁。

你的立方体的大小是 100, 100, 100。到近平面的距离是 1,到远平面的距离是 1000。
因此,相机与立方体中心的距离必须至少为51(d/2 + near = 100/2 +1),否则立方体的正面将被近平面切断Viewing frustum.

OpenGL 坐标系是 right handed system. The x axis points to the right and the y axis points up. The z axis is computed by the cross product x 轴和 y 轴并指向视图外。因此几何必须在负 z 方向移动。

我建议对大小为 100x100x100 的立方体使用以下投影和平移:

float aspect = (float)width/(float)height;
matrix = Matrix4.CreateTranslation(0, 0, -100) * // 100 > 51
    Matrix4.CreatePerspectiveOffCenter(-aspect, aspect, 1, -1, 1, 1000);