c++directxvertex-attributes

C++ directx 11 how to interleave unknown number of vertex attributes


I have read many articles saying to interleave vertex attributes by putting the data in a structure

struct Vertex
{
  XMFLOAT2A vertex;
  XMFLOAT3A color;
  .
  .
  .
 }

This works fine for tutorials but for real world models loaded from obj,colladae files, etc. It is impossible to know how many attributes a mesh contains in advance and you can't write every possible structure containing all possible combinations of attributes.

The only solution is to read all attributes first and then merge them into one large array.

The problem is I tried this approach and it doesn't work.

So how do I interleave an unknown number of attributes known only at run time? What should be the alignbyteoffset in the INPUT_LAYOUT_DESC? How do I interleave the data OpenGL style?


Solution

  • After days of typed structs and error's i have finally found a way using memcpy

    you can interleave pretty much any types of objects or primitive datatypes into an char array using this technique

    DirectX::XMFLOAT2 vertices[4] =
     {
       DirectX::XMFLOAT2(0.5f,0.5f)
      ,DirectX::XMFLOAT2(-0.5f,0.5f)
      ,DirectX::XMFLOAT2(-0.5f,-0.5f)
      ,DirectX::XMFLOAT2(0.5f,-0.5f)
     };
    
     DirectX::XMINT3 colors[4] =
     {
       DirectX::XMINT3(1,0,0)
      ,DirectX::XMINT3(0,1,0)
      ,DirectX::XMINT3(1,0,1)
      ,DirectX::XMINT3(1,1,0)
     };
    
     char data[sizeof(DirectX::XMFLOAT2) * 4 + sizeof(DirectX::XMINT3) * 4];
     char* ptr = data;
     DirectX::XMFLOAT2* vertex = vertices;
     DirectX::XMINT3* color = colors;
    
     for (int i = 0; i < 4; i++)
     {
       memcpy(ptr, vertex, sizeof(DirectX::XMFLOAT2)); //Copy & increment char pointer and vertex pointer
       ptr += sizeof(DirectX::XMFLOAT2);
       vertex += 1;
    
       memcpy(ptr, color, sizeof(DirectX::XMINT3)); //Copy & increment char pointer and color pointer
       ptr += sizeof(DirectX::XMINT3);
       color += 1;
     }
    

    Any suggestions or edit's to this solution are greatfully accepted

    and as for the alignbyteOffset we can use D3D11_APPEND_ALIGNED_ELEMENT and not worry about that