Direct3D成长日记(01):创建和显示Direct3D窗口
源程序:
////文件名称 :Direct3DBasics.cpp//作者 :shenzi//完成时间 :2009.05.03//说明 :Direct3D成长日记(01):创建和显示Direct3D窗口。////包含头文件,相应库:#include <windows.h>#include <d3d9.h>#pragma comment(lib,"d3d9.lib")//全局变量声明:LPDIRECT3D9 g_pD3D = NULL; //Direct3D接口指针LPDIRECT3DDEVICE9 g_pD3DDevice = NULL;//Direct3D设备指针#define WINDOW_CLASS_NAME L"Direct3D"#define WINDOW_NAME L"Direct3DBasics Tutorial"#define SCREEN_WIDTH 300#define SCREEN_HEIGHT 300//函数声明:HRESULT InitD3D( HWND); //初始化Direct3Dvoid RenderFrame( void); //场景渲染void CleanD3D( void); //释放资源//WINDOWS 消息处理函数:LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM);//WinMain函数:int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hprevInstance, LPSTR lpCmdLine, int nCmdShow){ //变量声明: HWND hwnd; MSG msg; WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); //创建窗口类 wc.cbClsExtra = 0; wc.cbSize = sizeof(WNDCLASSEX); wc.cbWndExtra = 0; wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.hCursor = LoadCursor( NULL, IDC_ARROW); wc.hIcon = LoadIcon( NULL, IDI_APPLICATION); wc.hInstance = hInstance; wc.lpfnWndProc = WndProc; wc.lpszClassName = WINDOW_CLASS_NAME; wc.lpszMenuName = NULL; wc.style = CS_HREDRAW | CS_VREDRAW; //注册窗口类 RegisterClassEx(&wc); //初始化窗口 hwnd = CreateWindowEx( NULL, WINDOW_CLASS_NAME, WINDOW_NAME, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, SCREEN_WIDTH, SCREEN_HEIGHT, NULL, NULL, hInstance, NULL); //显示,更新窗口: ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); InitD3D(hwnd); ZeroMemory(&msg, sizeof(MSG)); //消息循环: while( msg.message != WM_QUIT ) { if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) ) { TranslateMessage( &msg ); DispatchMessage( &msg ); } else RenderFrame(); } UnregisterClass( WINDOW_CLASS_NAME, wc.hInstance ); return 0;}LRESULT WINAPI WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ){ switch( msg ) { case WM_DESTROY: CleanD3D(); PostQuitMessage( 0 ); return 0; } return DefWindowProc( hWnd, msg, wParam, lParam );}HRESULT InitD3D(HWND hwnd){ //创建D3D对象: if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION))) { return E_FAIL; } //定义窗口的显示信息: D3DPRESENT_PARAMETERS d3dpp; ZeroMemory( &d3dpp, sizeof(d3dpp)); d3dpp.Windowed = TRUE; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.hDeviceWindow = hwnd; //创建D3D设备: if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice))) { return E_FAIL; } return S_OK;}void RenderFrame(void){ if(NULL == g_pD3DDevice) return; //清空背景缓冲区: g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 250, 250), 1.0f, 0); if(SUCCEEDED(g_pD3DDevice->BeginScene())) { //渲染场景: g_pD3DDevice->EndScene(); } //把渲染的场景显示在窗口: g_pD3DDevice->Present(NULL, NULL, NULL, NULL); }void CleanD3D(void){ //释放资源 if(NULL != g_pD3DDevice) g_pD3DDevice->Release(); if(NULL != g_pD3D) g_pD3D->Release(); g_pD3DDevice = NULL; g_pD3D = NULL;}
程序运行结果: