You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用glm::perspective时2D四边形无法渲染的问题排查

DirectX12中glm透视相机无法渲染2D四边形,正交相机正常的问题及解决

尝试用DirectX12渲染简单2D四边形时,使用glm::perspective的透视相机无法显示图形,但正交相机可以正常工作,目的是为后续3D渲染做准备。

原透视相机实现代码

ConstantBufferData cb_data{};
cb_data.model = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // 等价于glm::mat4(1.0f)

glm::mat4 view_matrix = glm::mat4(1.0f);
glm::mat4 proj_matrix =
    glm::perspective(45.0f, (float)width / height, 0.1f, 100.f);

cb_data.view_proj = view_matrix * proj_matrix;

注:width和height为窗口实际宽高,数值确认正确。

正常工作的正交相机代码

glm::mat4 proj_matrix = glm::ortho(-1.6f, 1.6f, -0.9f, 0.9f, -1.0f, 1.0f);

顶点与索引数据

Vertex vertices[] = {
    {glm::vec3(0.5f, 0.5f, 0.0f), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f)},
    {glm::vec3(0.5f, -0.5f, 0.0f), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f)},
    {glm::vec3(-0.5f, -0.5f, 0.0f), glm::vec4(0.0f, 0.0f, 1.0f, 1.0f)},
    {glm::vec3(-0.5f, 0.5f, 0.0f), glm::vec4(1.0f, 1.0f, 0.0f, 1.0f)},
};

UINT16 indices[] = {
    0, 1, 2, 2, 3, 0,
};

顶点着色器代码

cbuffer ModelConstantBuffer : register(b0)
{
    matrix modelMatrix;
    matrix viewProjectionMatrix;
};

struct VSInput
{
    float3 position : POSITION;
    float4 color : COLOR;
};

struct VSOutput
{
    float4 position : SV_POSITION;
    float4 color : COLOR;
};

VSOutput main(VSInput input)
{
    VSOutput output;
    output.color = input.color;
    
    float4 pos = float4(input.position, 1.0f);

    pos = mul(pos, modelMatrix);
    pos = mul(pos, viewProjectionMatrix);
    output.position = pos;
    
    output.position = pos;
    return output;
}

问题解决(编辑补充)

使用glm库时,需要注意两个关键点:

  • 赋值矩阵前必须调用glm::transpose转换矩阵布局
  • 视图矩阵需使用右手坐标系的观察矩阵,示例:
    glm::mat4 view_matrix = glm::lookAtRH({0.0f, 0.7f, 1.5f}, {0.0f, -0.1f, 0.0f}, {0.0f, 1.0f, 0.0f});
    

最终改用DirectX数学库实现,代码如下:

ConstantBufferData cb_data{};

XMStoreFloat4x4(
    &cb_data.model,
    XMMatrixTranspose(XMMatrixRotationY(XMConvertToRadians(64.0f))));

XMMATRIX proj_matrix = XMMatrixPerspectiveFovRH(
    XMConvertToRadians(45.0f), (float)width / height, 0.01f, 100.0f);

static const XMVECTORF32 eye = {0.0f, 0.7f, 1.5f, 0.0f};
static const XMVECTORF32 at = {0.0f, -0.1f, 0.0f, 0.0f};
static const XMVECTORF32 up = {0.0f, 1.0f, 0.0f, 0.0f};

XMStoreFloat4x4(
    &cb_data.view_proj,
    XMMatrixTranspose(XMMatrixLookAtRH(eye, at, up) * proj_matrix));

内容的提问来源于stack exchange,提问作者user15137953

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 23:37:08