下面是Sprite类的设定:
在原先的DEVICE的工程文件中添加"SpriteBatch.h",因为它也是个公共的类;sprite是相对简单的一个渲染部件。它包含在视窗任何位置任何范围来快速绘制图片,同时包含裁减、偏移和镜像等功能本游戏没有用到旋转和缩放属性。
struct CB
{
Matrix p;Vector4 c;//这里虽然使用了 4x4矩阵但没有进行任何的矩阵运算,仅仅是记录变换信息而已。
};
struct SpriteBatch
{
Device device;
ID3D11VertexShader* VS;//一个空的shader
ID3D11PixelShader* PS;//绘图的Shader
ID3D11GeometryShader* GS;//变换坐标位置的shader
ID3D11Buffer* cb;//提供给显卡的BYTE变量
CB cbo;//存储变量与显卡交互的中间媒介
float* p;//变换位置坐标
float Width, Height;//绘制的窗口大小
SpriteBatch(){}
SpriteBatch(Device dev)
{
device=dev;
p=new float[16];
ResetPos();
ResetUV();
ID3DBlob* blob;
UINT size=(UINT)strlen(Code_Sprite)+1;
D3DX11CompileFromMemory(Code_Sprite,size,0, 0,0, "VS","vs_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, 0, &blob, 0, 0);
device.dev->CreateVertexShader(blob->GetBufferPointer(),
blob->GetBufferSize(),0, &VS );
D3DX11CompileFromMemory(Code_Sprite,size,0, 0,0, "PS","ps_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, 0, &blob, 0, 0);
device.dev->CreatePixelShader(blob->GetBufferPointer(),
blob->GetBufferSize(),0, &PS );
D3DX11CompileFromMemory(Code_Sprite,size,0, 0,0, "GS","gs_4_0", D3DCOMPILE_ENABLE_STRICTNESS, 0, 0, &blob, 0, 0);
device.dev->CreateGeometryShader(blob->GetBufferPointer(),
blob->GetBufferSize(),0, &GS );
Kill(blob);
device.CreateConstantBuffer<CB>( cb);
void Begin()//和DX内置的sprite不同.我的sprite没有使用选项也没有End()属性,实际上也不需要他们。
{
device.context->IASetInputLayout(0);
device.context->VSSetShader(VS,0, 0 );
device.context->GSSetShader(GS,0, 0 );
device.context->PSSetShader(PS,0, 0 );
}
void SetTexture(Texture t)
{
device.context->PSSetShaderResources( 0, 1, &t.texture);
}
void Draw()
{ SetCB(); device.context->Draw(4,0);//显卡需要读入四个点来构成正方型
}
void Draw(Texture t, Vector4 c) {
ResetPos(); ResetUV(); cbo.c=c; SetTexture(t); Draw();
}//充满屏幕的绘制
void Draw(Texture t, float x, float y, float w, float h, Vector4 c)
{ ResetUV(); cbo.c=c; SetTexture(t); DrawQuad(x, y, w, h);
} //用于调整位置和大小的绘制
void Draw(Texture t, Vector2 pos, Rect r, Vector4 c, bool flip)
{
cbo.c=c; SetUV(t, r,flip); SetTexture(t);
DrawQuad(pos.X, pos.Y, (float)r.Width, (float)r.Height);
}//用于镜像和裁减和偏移的绘制
这里省略了个重要的画图环节 DrawQuad(x, y, w, h);它是绘图的核心。
在后面的游戏中将大量的使用这个类来绘制动态的2D元素。