首页 > 解决方案 > 应用投影矩阵后对象消失

问题描述

我正在尝试使用 DirectX 显示 3D 立方体。我创建了一个 x64 c++ windows 应用程序,以下顶点和索引描述了立方体(注意立方体故意没有底部)

Vertex cube[]
{
    {-0.25f, -0.5f, 0.25f},
    {-0.25f, 0.5f, 0.25f},
    {0.25f, 0.5f, 0.25f},
    {0.25f, -0.5f, 0.25f},

    {-0.25f, -0.5f, 0.5f},
    {-0.25f, 0.5f, 0.5f},
    {0.25f, 0.5f, 0.5f},
    {0.25f, -0.5f, 0.5f}
};

unsigned short cubeIndices[]{
    0, 1, 2, // front
    0, 2, 3,

    4, 5, 6, // back
    4, 6, 7,

    1, 5, 6, // top
    1, 6, 2,

    0, 4, 5, // left
    0, 5, 1,

    3, 2, 6, // right
    3, 6, 7 
};

我没有深度/模板视图,因为我认为我不需要它,因为它只是一个简单的立方体。我创建了一个常量缓冲区

struct ConstantBuffer {
    DirectX::XMMATRIX model;
    DirectX::XMMATRIX view;
    DirectX::XMMATRIX projection;
};

这个缓冲区是根据我从 SDK 的 DirectXMath 库中使用的方法填充的。

    // Based on MSDN, direct x uses left handed und looks in positive Z
    m_constantBufferData.model = m_constantBufferData.model * DirectX::XMMatrixTranslation(0.0f, 0.0f, 8.0f); // move it by 8 units in positive z)
    m_constantBufferData.view = DirectX::XMMatrixIdentity(); // I assume we do not need to put anything in view, because the object is in positive z and center

    m_constantBufferData.projection = DirectX::XMMatrixPerspectiveFovLH(DirectX::XMConvertToRadians(90.0f), 1920.0f/1080.0f, 0.1f, 100.0f);
    //m_constantBufferData.projection = DirectX::XMMatrixOrthographicLH(1920.0f, 1080.0f, 0.1f, 100.0f);

BackBuffer 和 Window 的大小为 1920x1080 像素。

我的顶点着色器如下所示:

cbuffer simpleConstantBuffer : register(b0)
{
    matrix model;
    matrix view;
    matrix projection;
}

float4 main(float4 pos : POSITION) : SV_POSITION
{
    float4 output = pos;

    output = mul(output, model);
    output = mul(output, view);
    output = mul(output, projection);

    return output;
}

我不知道有什么问题。屏幕上没有绘制任何内容,尽管我的像素着色器输出红色,如果我将所有矩阵设置为单位矩阵,我会看到渲染的立方体的红色正面。我认为它与透视矩阵有关(正交也不起作用)?

任何想法如何进一步调试或可能有什么问题?

更新:作为补充,这是 nvidia nsight 向我展示的常量缓冲区中的矩阵,以防万一:

Model:
(1.00, 0.00, 0.00, 0.00)
(0.00, 1.00, 0.00, 0.00)
(0.00, 0.00, 1.00, 8.00)
(0.00, 0.00, 0.00, 1.00)

View:
(1.00, 0.00, 0.00, 0.00)
(0.00, 1.00, 0.00, 0.00)
(0.00, 0.00, 1.00, 1.00)
(0.00, 0.00, 0.00, 1.00)

Projection:
(0.56, 0.00, 0.00, 0.00)
(0.00, 1.00, 0.00, 0.00)
(0.00, 0.00, 1.00, -0.10)
(0.00, 0.00, 1.00, 0.00)

标签: c++mathmatrixdirectxdirect3d

解决方案


在查看 Microsoft github 页面上的一些示例后,我才弄清楚了。出于某种原因,他们使用 XMMatrixTranspose。应用后,它的工作原理。

但是,如果它是相同的技术,我不知道为什么我必须使用它,这意味着纯 DirectX 和 HLSL 着色器。我认为它们都是列/行专业的,没有什么不同。但似乎矩阵函数返回另一种格式。


推荐阅读