1
\$\begingroup\$

I've got a single vertex buffer and an index buffer for a cube in Directx9. I now want to generate a LPD3DXMESH object from them, so that I can manage mouse picking and other stuff with the cube model. How can I achieve this? Here's the code of my vertex and index buffers:

CUSTOMVERTEX vertices[] =
{
    { -3.0f, 3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, 3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, -3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, -3.0f, -3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, 3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, 3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { -3.0f, -3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
    { 3.0f, -3.0f, 3.0f, D3DCOLOR_XRGB(0, 0, 0), },
};

d3ddev->CreateVertexBuffer(8 * sizeof(CUSTOMVERTEX),
                           0,
                           CUSTOMFVF,
                           D3DPOOL_MANAGED,
                           &vertex_buffer,
                           NULL);

VOID* pVoid;
vertex_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, vertices, sizeof(vertices));
vertex_buffer->Unlock();

short indices[] =
{
    0, 1, 2,
    2, 1, 3,
    4, 0, 6,
    6, 0, 2,
    7, 5, 6,
    6, 5, 4,
    3, 1, 7,
    7, 1, 5,
    4, 5, 0,
    0, 5, 1,
    3, 7, 2,
    2, 7, 6,
};

d3ddev->CreateIndexBuffer(36 * sizeof(short),
                          0,
                          D3DFMT_INDEX16,
                          D3DPOOL_MANAGED,
                          &index_buffer,
                          NULL);

index_buffer->Lock(0, 0, (void**)&pVoid, 0);
memcpy(pVoid, indices, sizeof(indices));
index_buffer->Unlock();
\$\endgroup\$
3
\$\begingroup\$

You can't, as far as I recall, create a mesh directly from vertex or index buffers (as the mesh object wants to maintain those buffers itself). You can create it from the vertex and index data you already have though:

  1. Create the mesh using D3DXCreateMeshFVF, providing the appropriate vertex format information and the correct face and index counts.

  2. Use LockVertexBuffer and LockIndexBuffer on the resulting mesh (they are both base class methods) to get pointers to the buffer content.

  3. Copy your data into the resulting pointers.

  4. Unlock the buffers.

With this method you don't need to call CreateVertexBuffer or CreateIndexBuffer yourself, as the mesh will do so. Make sure you pass the correct flags to the mesh-creation function to ensure the underlying buffers are created in the (managed) pool you expect them to be in.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.