- 在Vertex中增加D3DCOLOR类型的属性
- 着色分为平面着色和Gouraud着色。使用平面着色每个图元的每个像素都被一致的赋予第一个顶点所指定的颜色。
在gouraud着色模式下,图元中个像素的颜色值由各顶点的颜色经线性插值得到(平滑过渡)。
例程:具有颜色的三角形
IDirect3DDevice9* Device = 0;
const int WIDTH = 640;
const int HEIGHT = 480;
IDirect3DVertexBuffer9* VB;
D3DXMATRIX WorldMatrix;
//class and struct
struct Vertex
{
Vertex(){}
Vertex(float x, float y, float z, D3DCOLOR coler)
{
_x = x;
_y = y;
_z = z;
_color = coler;
}
float _x, _y, _z;
D3DCOLOR _color;
static const DWORD FVF;
};
const DWORD Vertex::FVF = D3DFVF_XYZ | D3DFVF_DIFFUSE;
//
// Framework Functions
//
bool Setup()
{
Device->CreateVertexBuffer(6*sizeof(Vertex), D3DUSAGE_WRITEONLY, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DPOOL_DEFAULT, &VB, 0);
Vertex* vertices;
VB->Lock(0, 0, (void**)&vertices, 0);
vertices[0] = Vertex(-1.0f, 0.0f, 2.0f, D3DCOLOR_XRGB(255,0,0));
vertices[1] = Vertex(0.0f, 1.0f, 2.0f, D3DCOLOR_XRGB(0, 255, 0));
vertices[2] = Vertex(1.0f, 0.0f, 2.0f, D3DCOLOR_XRGB(0, 0, 255));
//set proj Matrix
D3DXMATRIX proj;
D3DXMatrixPerspectiveFovLH(&proj, D3DX_PI*0.5, (float)WIDTH/(float)HEIGHT, 1.0f, 1000.0f);
Device->SetTransform(D3DTS_PROJECTION, &proj);
Device->SetRenderState(D3DRS_LIGHTING, false);
return true;
}
void Cleanup()
{
d3d::Release<IDirect3DVertexBuffer9*>(VB);
}
bool Display(float timeDelta)
{
if( Device ) // Only use Device methods if we have a valid device.
{
// Instruct the device to set each pixel on the back buffer black -
// D3DCLEAR_TARGET: 0x00000000 (black) - and to set each pixel on
// the depth buffer to a value of 1.0 - D3DCLEAR_ZBUFFER: 1.0f.
Device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0);
Device->BeginScene();
Device->SetStreamSource(0, VB, 0, sizeof(Vertex));
Device->SetFVF(Vertex::FVF);
D3DXMatrixTranslation(&WorldMatrix, -1.25, 0, 0); //设置平移矩阵
Device->SetTransform(D3DTS_WORLD, &WorldMatrix);
Device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_FLAT); //以第一个顶点涂上颜色
Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
D3DXMatrixTranslation(&WorldMatrix, 1.25, 0, 0); //设置平移矩阵
Device->SetTransform(D3DTS_WORLD, &WorldMatrix);
Device->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD); //Gouraud方式涂颜色
Device->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 1);
Device->EndScene();
// Swap the back and front buffers.
Device->Present(0, 0, 0, 0);
}
return true;
}
浙公网安备 33010602011771号