|
|
学习 d3directX编程
4.14 顶点索引画3d立方体
//这个例子是 一个立方体 8个点 因为有很多点是共用了
//所以用索引 要把表明展开分成三角形
CUSTOMVERTEX vects[]=
{
{0.0f,1.0f,0.0f, 1.0f,0.0f,0.0f},
{0.0f,1.0f,1.0f, 1.0f, 1.0f,0.0f},
{1.0f,1.0f,1.0f , 1.0f ,1.0f, 1.0f},
{1.0f , 1.0f , 0.0f , 1.0f , 0.0f, 1.0f},
{0.0f,0.0f, 0.0f, 1.0f , 0.0f,0.0f},
{0.0f, 0.0f , 1.0f, 1.0f , 1.0f , 0.0f},
{1.0f , 0.0f, 1.0f ,1.0f, 1.0f , 1.0f },
{1.0f , 0.0f , 0.0f , 1.0f , 0.0f , 1.0f }
};
//在纸上 画出草图 用三角形带 索引顶点
//direct3d有16位索引 和32位索引
WORD indexBuf[]=
{
4,0,7,3,6,2,5,1,4,0,//四个侧面
0,1,3,2, //上侧面
5,4,6,7 //底侧面
};
void *pIndex;
// Init the font
m_pFont->InitDeviceObjects( m_pd3dDevice );
D3DXCreateTextureFromFile(m_pd3dDevice, "directX.bmp", &m_pTex);
// Create the vertex buffer?
if( FAILED( hr = m_pd3dDevice->CreateVertexBuffer(8*sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_MANAGED, &m_pVB, NULL ) ) )
return DXTRACE_ERR( "CreateVertexBuffer", hr );
// Fill the vertex buffer with 2 triangles
CUSTOMVERTEX* pVertices;
if( FAILED( hr = m_pVB->Lock( 0, sizeof(vects), (VOID**)&pVertices, 0 ) ) )
return DXTRACE_ERR( "Lock", hr );
memcpy(pVertices,vects,sizeof(vects));
m_pVB->Unlock();
// sizeof(indexBuf)/2计算出顶点数目
if( FAILED( m_pd3dDevice->CreateIndexBuffer( sizeof(indexBuf)/2*sizeof(WORD),
NULL, D3DFMT_INDEX16,
D3DPOOL_DEFAULT, &m_pIndex ,NULL) ) )
return E_FAIL;
if (FAILED(hr=m_pIndex->Lock(0,sizeof(indexBuf),&pIndex,NULL)))
{
return DXTRACE_ERR( "locd index buf fail", hr );
}
memcpy(pIndex,indexBuf,sizeof(indexBuf));
m_pIndex->Unlock();
在画场景中
m_pd3dDevice->SetStreamSource( 0, m_pVB, 0, sizeof(CUSTOMVERTEX) );
m_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
m_pd3dDevice->SetIndices( m_pIndex ); // 设定我们的顶点索引
//函数原型HRESULT DrawIndexedPrimitive( D3DPRIMITIVETYPE Type,
// INT BaseVertexIndex,
// UINT MinIndex,
// UINT NumVertices,
// UINT StartIndex,
// UINT PrimitiveCount
);
m_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP ,0,0,8,0,8); //4个侧面 8个三角形
m_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP ,0,0,8,10,2); //上侧面
m_pd3dDevice->DrawIndexedPrimitive(D3DPT_TRIANGLESTRIP ,0,0,8,14,2);//下侧面
|
|