Dynamic Vertex Declartion

Started by
4 comments, last by Hodgman 11 years, 10 months ago
I'm writing a model viewer that needs to accept a wide vareity of potential vertex formats. Models may or may not have color, texturecoords, normals, weights, and so on.

I'm trying to figure out how I can dynamically allocate memory and then create a [font=Consolas, Menlo, Monaco,][background=transparent]D3DVERTEXELEMENT9 that has the correct offsets and usage declarations.[/background][/font]

[font="Consolas, Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif"][color="#000000"]I'm sort of at a loss as to how I might go about doing this. Does anyone have any advice, or ideas to get me started?[/font]

Advertisement
Which part of the problem are you having trouble with?

Something like this helpful?D3DVERTEXELEMENT9 elements[17];
D3DVERTEXELEMENT9 end = D3DDECL_END();
for( ... )//read format from model file?
elements = ...
assert( i <= 16 );
elements = end;
IDirect3DVertexDeclaration9* result = 0;
HRESULT hr = device.CreateVertexDeclaration(elements, &result);
The part I am confused about is how to store the vertex data.

[source lang="cpp"]
struct MYVERTS
{
float x,y,z,u,v;
DWORD colr;
float nx,ny,nz;
};[/source]

That's the struct I am using right now. I create an array of those, each holding a single vert. My problem is that the mesh I am loading may not have color, or it may have a weight. That would mean I would need a unique struct for every possible arrangement.

How can I dynamically allocate the memory while the program is running?

The user will input while the application is running so I will have no idea what format needs to be created until the file is parsed in.
You don't need a C++ struct to represent your per-vertex data. You can just allocate a raw array of bytes, and work with that. To access a certain element within a vertex you just need to know the offset from the start of each vertex.
Ahhh, that makes sense. I hate to keep asking for hand holding on this but what exactly is the best way to go about that. If I have a 3 floats (position, 1 DWORD (color), and a 3 floats (a normal).

That would be 28 bytes. So how do I allocate and populate the raw memory?
I'm guessing you don't have one 28 byte vertex in your file, but some N amount of them. From your file, you should be able to fetch or compute the number of bytes per vertex, and the number of vertices total, and you can then make a buffer that is big enough:
[font=courier new,courier,monospace]HRESULT hr = device.CreateVertexBuffer( 28 * numVerts, 0, 0, D3DPOOL_MANAGED, &result, 0 );[/font]
Then you can lock the buffer, and copy the data from the file straight into it.

This topic is closed to new replies.

Advertisement