刚开始学习D3D,安装完DirectX9后,在VS2008中新建Win32项目·
--------------------------------------------------------------
//设置好Direct3D的库链接,这里也可以通过项目属性的链接器 -- 附加依赖项完成添加;
#pragma comment(lib,"dxerr.lib")
#pragma comment(lib,"dxguid.lib")
#pragma comment(lib,"d3dx9d.lib")
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"winmm.lib")
#include <Windows.h>
#include <d3d9.h>
//////////////////////////////////////////////////////////////////////////
//D3D基础对象;
LPDIRECT3D9 g_pD3D = NULL;
//D3D设备对象;
LPDIRECT3DDEVICE9 g_pd3dDevice = NULL;
//----------------------------//
//初始d3d对象;
//----------------------------//
HRESULT InitializeD3D(HWND hwndTemp){
//创建D3D对象 通过该对象获得D3D设备的对象;
if (NULL==(g_pD3D=Direct3DCreate9(D3D_SDK_VERSION)))
{
return false;
}
//设置d3dpreame参数 用来创建设置d3d设备对象;
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory(&d3dpp,sizeof(d3dpp));
d3dpp.Windowed = true;//窗口模式;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
//创建获得D3D设备的对象;
if (FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT,D3DDEVTYPE_HAL,hwndTemp,D3DCREATE_SOFTWARE_VERTEXPROCESSING,&d3dpp,&g_pd3dDevice)))
{
return false;
}
return true;
}
///渲染图象///////////////////////////////////////////////////////////////////////
VOID Render(){
//清空后台缓存;
g_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,D3DCOLOR_XRGB(45,50,170),1.0f,0);
//开始绘制图形;
if (SUCCEEDED(g_pd3dDevice->BeginScene()))
{
//结束绘制;
g_pd3dDevice->EndScene();
}
//把绘制完毕的图形提交给前段 告诉设备可以进行相应的显示;
g_pd3dDevice->Present(NULL,NULL,NULL,NULL);
}
///结束释放资源///////////////////////////////////////////////////////////////////////
VOID CleanUp(){
//由上层往下逐渐释放;
if(!g_pd3dDevice){
g_pd3dDevice->Release();
}
if(!g_pD3D){
g_pD3D->Release();
}
}
///处理Win32消息循环///////////////////////////////////////////////////////////////////////
LRESULT WINAPI MsgProc(HWND hwnd,UINT msgid, WPARAM wParam, LPARAM LParam){
switch(msgid){
case WM_DESTROY:
CleanUp();
PostQuitMessage(0);
return 0;
case WM_PAINT:
Render();
ValidateRect(hwnd,NULL);
return 0;
}
return DefWindowProc(hwnd,msgid,wParam,LParam);
}
///创建windows窗口 程序入口///////////////////////////////////////////////////////////////////////
INT WINAPI WinMain(HINSTANCE hint,HINSTANCE,LPSTR,INT){
//注册窗口类;
WNDCLASSEX wc={sizeof(WNDCLASSEX),CS_CLASSDC,MsgProc,0L,0L,GetModuleHandle(NULL),NULL,NULL,NULL,NULL,L"ClassName",NULL};
RegisterClassEx(&wc);
//创建窗口;
HWND hwnd = CreateWindow(L"ClassName",L"D3D游戏编程",WS_OVERLAPPEDWINDOW ,200,100,600,500,NULL,NULL,wc.hInstance ,NULL);
//初始化Direct3D;
if (SUCCEEDED(InitializeD3D(hwnd)))
{
//显示主窗口;
ShowWindow(hwnd,SW_SHOWDEFAULT);
UpdateWindow(hwnd);
//进入消息循环;
MSG msg;
ZeroMemory(&msg,sizeof(msg));
while(msg.message!=WM_QUIT){
if (PeekMessage(&msg,NULL,0U,0U,PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
{//渲染图象;
Render();
}
}
}
UnregisterClass(L"ClassName",wc.hInstance);
return 0;
}
通过以上的代码,我们可以初步的理解基于Win32框架的Direct3D程序的基本结构。