动态顶点缓冲区创建失败

时间:2014-08-31 05:59:35

标签: c++ directx-11

我正在尝试创建一个动态顶点缓冲区,以便我可以使用ID3D11DeviceContext :: Map()写入缓冲区。但是,每次我尝试创建顶点缓冲区时都会失败。这是我的代码。我在其他项目中成功完成了这项工作,所以我不知道为什么我写的不起作用。这是代码:

//create vertex buffer
    Vertex* vertices = static_cast<Vertex*>(std::malloc((4000) * sizeof(Vertex)));
    for (int i = 0; i < 4000; i++)
    {
        vertices[i].pos.x = 0.0f;
        vertices[i].pos.y = 0.0f;
        vertices[i].pos.z = 0.0f;
        vertices[i].tex.x = 0.0f;
        vertices[i].tex.y = 0.0f;
    }
    D3D11_BUFFER_DESC bd;
    ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof( Vertex ) * 4000;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = vertices; 
    HRESULT hr = Device->CreateBuffer( &bd, &InitData, &VertexBuffer );

    std::free(vertices);

在搞乱代码之后,我注意到这段代码成功了:

//create vertex buffer
    Vertex* vertices = static_cast<Vertex*>(std::malloc((4000) * sizeof(Vertex)));
    for (int i = 0; i < 4000; i++)
    {
        vertices[i].pos.x = 0.0f;
        vertices[i].pos.y = 0.0f;
        vertices[i].pos.z = 0.0f;
        vertices[i].tex.x = 0.0f;
        vertices[i].tex.y = 0.0f;
    }
    D3D11_BUFFER_DESC bd;
    ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DYNAMIC;
    bd.ByteWidth = sizeof( Vertex ) * 4000;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = 0;
    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = vertices; 
    HRESULT hr = Device->CreateBuffer( &bd, &InitData, &VertexBuffer );

    std::free(vertices);

此代码也成功了:

//create vertex buffer
    Vertex* vertices = static_cast<Vertex*>(std::malloc((4000) * sizeof(Vertex)));
    for (int i = 0; i < 4000; i++)
    {
        vertices[i].pos.x = 0.0f;
        vertices[i].pos.y = 0.0f;
        vertices[i].pos.z = 0.0f;
        vertices[i].tex.x = 0.0f;
        vertices[i].tex.y = 0.0f;
    }
    D3D11_BUFFER_DESC bd;
    ZeroMemory( &bd, sizeof(bd) );
    bd.Usage = D3D11_USAGE_DEFAULT;
    bd.ByteWidth = sizeof( Vertex ) * 4000;
    bd.BindFlags = D3D11_BIND_VERTEX_BUFFER;
    bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
    D3D11_SUBRESOURCE_DATA InitData;
    ZeroMemory( &InitData, sizeof(InitData) );
    InitData.pSysMem = vertices; 
    HRESULT hr = Device->CreateBuffer( &bd, &InitData, &VertexBuffer );

    std::free(vertices);

当bd.Usage = D3D11_USAGE_DYNAMIC和bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE同时,似乎只能创建顶点缓冲区。关于问题是什么的任何想法?

1 个答案:

答案 0 :(得分:1)

我记得刚才有这个问题。正如MSDN所说,当您将资源创建为动态资源时,您应该使用ID3D11DeviceContext :: Map()来填充它。即使这是第一次。因此,当您创建缓冲区时,只需尝试传递NULL而不是&amp; InitData。创建缓冲区后,映射并填充。据我所知,这解决了我的问题。这是来源。

http://msdn.microsoft.com/en-us/library/windows/desktop/ff476899%28v=vs.85%29.aspx