Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who can tell me what this bit of C++ does?

Tags:

c++

directx

CUSTOMVERTEX* pVertexArray;

if( FAILED( m_pVB->Lock( 0, 0, (void**)&pVertexArray, 0 ) ) ) {
    return E_FAIL;
}


pVertexArray[0].position = D3DXVECTOR3(-1.0, -1.0,  1.0);
pVertexArray[1].position = D3DXVECTOR3(-1.0,  1.0,  1.0);
pVertexArray[2].position = D3DXVECTOR3( 1.0, -1.0,  1.0);
...

I've not touched C++ for a while - hence the topic but this bit of code is confusing myself. After the m_pVB->Lock is called the array is initialized.

This is great and all but the problem I'm having is how this happens. The code underneath uses nine elements, but another function (pretty much copy/paste) of the code I'm working with only access say four elements.

CUSTOMVERTEX is a struct, but I was under the impression that this matters not and that an array of structs/objects need to be initialized to a fixed size.

Can anyone clear this up?

Edit:

Given the replies, how does it know that I require nine elements in the array, or four etc...?

So as long as the buffer is big enough, the elements are legal. If so, this code is setting the buffer size if I'm not mistaken.

if( FAILED( m_pd3dDevice->CreateVertexBuffer( vertexCount * sizeof(CUSTOMVERTEX), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &m_pVB, NULL ) ) ) {
        return E_FAIL;
}
like image 590
Finglas Avatar asked Dec 17 '25 22:12

Finglas


2 Answers

m_pVB points to a graphics object, in this case presumably a vertex buffer. The data held by this object will not generally be in CPU-accessible memory - it may be held in onboard RAM of your graphics hardware or not allocated at all; and it may be in use by the GPU at any particular time; so if you want to read from it or write to it, you need to tell your graphics subsystem this, and that's what the Lock() function does - synchronise with the GPU, ensure there is a buffer in main memory big enough for the data and it contains the data you expect at this time from the CPU's point of view, and return to you the pointer to that main memory. There will need to be a corresponding Unlock() call to tell the GPU that you are done reading / mutating the object.

To answer your question about how the size of the buffer is determined, look at where the vertex buffer is being constructed - you should see a description of the vertex format and an element count being passed to the function that creates it.

like image 80
moonshadow Avatar answered Dec 20 '25 13:12

moonshadow


You're pasing a pointer to the CUSTOMVERTEX pointer (pointer to a pointer) into the lock function so lock itself must be/ needs to be creating the CUSTOMVERTEX object and setting your pointer to point to the object it creates.

like image 45
Patrick Avatar answered Dec 20 '25 11:12

Patrick