完整代码看这里。
Tutorial04.fx
//--------------------------------------------------------------------------------------
//常缓存结构变量
//--------------------------------------------------------------------------------------
cbuffer MatrixCoord : register( b0 )
{
matrix world;
matrix view;
matrix projection;
}
//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
float4 Pos : SV_POSITION;
float4 Color : COLOR0;
};
//--------------------------------------------------------------------------------------
// 顶点着色器输出结构
//--------------------------------------------------------------------------------------
VS_OUTPUT VS( float4 Pos : POSITION, float4 Color : COLOR )
{
VS_OUTPUT output = (VS_OUTPUT)0;
output.Pos = mul( Pos, world );
output.Pos = mul( output.Pos, view );
output.Pos = mul( output.Pos, projection );
output.Color = Color;<pre name="code" class="cpp">#include <Windows.h>
#include <d3d11.h>
#include <D3DX11.h>
#include <D3Dcompiler.h>
#include <xnamath.h>
#include <tchar.h>
//顶点结构
struct SimpleVertex
{
XMFLOAT3 Pos;//位置
XMFLOAT4 Color;//颜色
};
//相机矩阵
struct MatrixCoord
{
XMMATRIX world;
XMMATRIX view;
XMMATRIX projection;
};
//全局变量
HINSTANCE g_hInstance = NULL;
HWND g_hWnd = NULL;
D3D_DRIVER_TYPE g_driverType = D3D_DRIVER_TYPE_HARDWARE;
D3D_FEATURE_LEVEL g_featureLevel = D3D_FEATURE_LEVEL_11_0;
ID3D11Device* g_device = NULL;
ID3D11DeviceContext* g_deviceContext = NULL;
IDXGISwapChain* g_swapChain = NULL;
ID3D11RenderTargetView* g_renderTargetView = NULL;
ID3D11VertexShader* g_vertexShader = NULL;
ID3D11PixelShader* g_pixelShader = NULL;
ID3D11InputLayout* g_inputLayout = NULL;
ID3D11Buffer* g_vertexBuffer = NULL;
ID3D11Buffer* g_indexBuffer = NULL;
ID3D11Buffer* g_constantBuffer = NULL;
XMMATRIX g_world;
XMMATRIX g_view;
XMMATRIX g_projection;
//全局函数
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow );
HRESULT InitDevice();
HRESULT CompileShaderFromFile( WCHAR* filename, LPCSTR entrypoint, LPCSTR shaderModel, ID3DBlob** pBlob);
LRESULT CALLBACK WndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam );
void Render();
void ShutdownDevice();
//主函数
int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPreInstance, LPWSTR nCmdLine, int nCmdShow )
{
HRESULT hResult;
g_hInstance = hInstance;
//初始化窗口
hResult = InitWindow( g_hInstance, nCmdShow );
if ( FAILED(hResult) )
{
return 0;
}
//初始化设备
hResult = InitDevice();
if ( FAILED(hResult) )
{
return 0;
}
//消息循环
MSG msg = { 0 };
while ( WM_QUIT != msg.message )
{
if ( PeekMessage( &msg, g_hWnd, 0, 0, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
else
{
Render();
}
}
return ( int )msg.wParam;
}
//初始化窗口
HRESULT InitWindow( HINSTANCE hInstance, int nCmdShow )
{
HRESULT hResult;
//创建窗口类
WNDCLASSEX wcex;
wcex.cbClsExtra = 0;
wcex.cbSize = sizeof( wcex );