Search code examples
c++direct3ddirectx-9

Mesh Optimization


The class that generates the mesh. The higher the number of vertices, the more rapidly the frame falls, how should I optimize it? I've used the OptimizeInplace function, but I can only expect 10 frames of improvement.

void Sprite::initialize()
{
    LPD3DXBUFFER pD3DXMtrlBuffer;

    D3DXLoadMeshFromX(fileName.c_str(), D3DXMESH_SYSTEMMEM, Render->g_pDevice, NULL,
        &pD3DXMtrlBuffer, NULL, &m_dwNumMaterials, &m_pMesh);

    D3DXMATERIAL* d3dxMaterials = (D3DXMATERIAL*)pD3DXMtrlBuffer->GetBufferPointer();
    m_pMeshMaterials = new D3DMATERIAL9[m_dwNumMaterials];
    m_pMeshTextures = new LPDIRECT3DTEXTURE9[m_dwNumMaterials];

    for (DWORD i = 0; i < m_dwNumMaterials; i++)
    {
        m_pMeshMaterials[i] = d3dxMaterials[i].MatD3D;

        m_pMeshMaterials[i].Ambient = m_pMeshMaterials[i].Diffuse;
        
        m_pMeshTextures[i] = NULL;
        if (d3dxMaterials[i].pTextureFilename != NULL)
        {
            D3DXCreateTextureFromFileA(Render->g_pDevice, d3dxMaterials[i].pTextureFilename, &m_pMeshTextures[i]);
        }
    }
    pD3DXMtrlBuffer->Release();


    std::vector<DWORD> adjacencyBuffer(m_pMesh->GetNumFaces() * 3);
    m_pMesh->GenerateAdjacency(0.0f, &adjacencyBuffer[0]);
    m_pMesh->OptimizeInplace(
        D3DXMESHOPT_ATTRSORT |
        D3DXMESHOPT_COMPACT |
        D3DXMESHOPT_VERTEXCACHE,
        &adjacencyBuffer[0],
        0, 0, 0);
}
void Sprite::render()
{
    Render->g_pDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);

    for (DWORD i = 0; i < m_dwNumMaterials; i++)
    {
        Render->g_pDevice->SetMaterial(&m_pMeshMaterials[i]);
        Render->g_pDevice->SetTexture(0, m_pMeshTextures[i]);

        m_pMesh->DrawSubset(i);
    }
}

Solution

  • The more verticies you have, the more time GPU have to spend rendering mesh. You can't just infinitely optimize a mesh to get performance that you want.

    You can try replacing your current mesh optimization library with something more modern. There's DirectXMesh library from Microsoft: https://github.com/microsoft/DirectXMesh

    You can use OptimizeFaces followed by OptimizeVertices from that library and test whether it'll result in better performance.

    But you shouldn't expect way better performance by just optimizing mesh. You should look whether your rendering code can be optimized too.