IDirect3DDevice9* g_Device = NULL;
IDirect3DVertexBuffer9* g_VB = 0; //立方体顶点
IDirect3DIndexBuffer9* g_IB = 0; //索引数据
struct Vertex {
Vertex(){}
Vertex(float x, float y, float z)
{ _x = x; _y=y; _z=z; }
float _x, _y, _z;
static const DWORD FVF;
};
const DWORD Vertex::FVF = D3DFVF_XYZ;
//创建顶点,索引缓存
g_Device->CreateVertexBuffer(8*sizeof(Vertex),
D3DUSAGE_WRITEONLY,
Vertex::FVF,
D3DPOOL_MANAGED,
&g_VB,
0);
g_Device->CreateIndexBuffer(36*sizeof(DWORD),
D3DUSAGE_WRITEONLY,
D3DFMT_INDEX16,
D3DPOOL_MANAGED,
&g_IB,
0);
//向立方体的顶点缓存填充数据
Vertex* vertices;
g_VB->Lock(0, 0, (void**)&vertices, 0);
vertices[0]=Vertex(-1.0f, -1.0f, -1.0f);
vertices[1]=Vertex(-1.0f, 1.0f, -1.0f);
vertices[2]=Vertex(1.0f, 1.0f, -1.0f);
vertices[3]=Vertex(1.0f, -1.0f, -1.0f);
vertices[4]=Vertex(-1.0f, -1.0f, 1.0f);
vertices[5]=Vertex(-1.0f, 1.0f, 1.0f);
vertices[6]=Vertex(1.0f, 1.0f, 1.0f);
vertices[7]=Vertex(1.0f, -1.0f, 1.0f);
g_VB->Unlock();
//定义立方体的三角形
WORD* indices = 0;
g_IB->Lock(0,0,(void**)&indices, 0);
//前面
indices[0]=0; indices[1]=1; indices[2]=2;
indices[3]=0; indices[4]=2; indices[5]=3;
//背面
indices[6]=4; indices[7]=6; indices[8]=5;
indices[9]=4; indices[10]=7; indices[11]=6;
//左面
indices[12]=4; indices[13]=5; indices[14]=1;
indices[15]=4; indices[16]=1; indices[17]=0;
//右面
indices[18]=3; indices[19]=2; indices[20]=6;
indices[21]=3; indices[22]=6; indices[23]=7;
//顶部
indices[24]=1; indices[25]=5; indices[26]=6;
indices[27]=1; indices[28]=6; indices[29]=2;
//底部
indices[30]=4; indices[31]=0; indices[32]=3;
indices[33]=4; indices[34]=3; indices[35]=7;
g_IB->Unlock();
//照相机位置(视图矩阵)
D3DXVECTOR3 poistion(0.0f,0.0f,-5.0f);
D3DXVECTOR3 target(0.0f,0.0f,0.0f);
D3DXVECTOR3 up(0.0f,1.0f,0.0f);
D3DXMATRIX V;
D3DXMatrixLookAtLH(&V, &poistion, &target, &up);
g_Device->SetTransform(D3DTS_VIEW, &V);
//投影矩阵
D3DXMATRIX proj;
D3DXMatrixPerspectiveFovLH(&proj,
D3DX_PI*0.5f, //90-degree
(float)WINDOW_WIDTH/(float)WINDOW_HEIGHT,
1.0f,
1000.0f);
g_Device->SetTransform(D3DTS_PROJECTION, &proj);
//渲染状态(填充模式:框架填充)
g_Device->SetRenderState(D3DRS_FILLMODE, D3DFILL_WIREFRAME);
if (g_Device)
{
//旋转立方体
D3DXMATRIX Rx, Ry;
//x轴旋转45弧度
D3DXMatrixRotationX(&Rx, 3.14f/4.0f);
//每一帧中增加y轴的弧度
static float y = 0.0f;
D3DXMatrixRotationY(&Ry, y);
y += timeDelta;
//当y轴旋转2周时,重新回到0弧度
if (y>=6.28f)
y=0.0f;
//结合x轴与y轴的旋转矩阵
D3DXMATRIX p = Rx * Ry;
g_Device->SetTransform(D3DTS_WORLD, &p);
//清空目标缓存和深度缓存
g_Device->Clear(0,0,D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER,
0xffffffff, 1.0f, 0);
//开始绘制场景
g_Device->BeginScene();
g_Device->SetStreamSource(0, g_VB, 0,sizeof(Vertex)); //设置资源流
g_Device->SetIndices(g_IB); //设置索引缓存
g_Device->SetFVF(Vertex::FVF); //设置顶点格式
//利用索引缓存绘制
g_Device->DrawIndexedPrimitive(D3DPT_TRIANGLELIST,0,0,8,0,12);
g_Device->EndScene();//结束绘制场景
//翻转表面
g_Device->Present(0,0,0,0);