学习一门开发语言的第一件事情当然是搭建一个可运行的环境,然后运行一个可成功执行的案例。
本人在学习DirectX的第一个工程的时候,参考了雨凇MoMo的一篇文章(https://www.xuanyusong.com/archives/802),但是看了之后,还是不知道如何才能运行起来。
然后,又参考了一篇文章(https://blog.csdn.net/chenwu_843402773/article/details/8077935)。
通过参考第二篇文章中的一些内容,最终把第一篇文章中的案例运行了起来,在此做一下记录,具体原理,相信随着学习 Direct 的逐渐升入,会理解的,现在不做过多说明,哈哈哈哈哈哈。。。
1 #include2 3 #define WINDOW_CLASS "UGPDX" //宏定义窗口类名称 4 #define WINDOW_NAME "MyFirstDirectProject" //宏定义窗口名称 5 6 LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); 7 LPDIRECT3D9 g_pD3D = NULL; 8 LPDIRECT3DDEVICE9 g_pDevice = NULL; 9 HRESULT InitD3D(HWND hwnd); 10 void Cleanup(); 11 void Render(); 12 13 int WINAPI WinMain(HINSTANCE hInst, HINSTANCE prevhInst, LPSTR cmdLine, int show) 14 { 15 WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, 16 GetModuleHandle(NULL), NULL, NULL, NULL, NULL, 17 WINDOW_CLASS, NULL }; 18 RegisterClassEx(&wc); 19 20 HWND hWnd = CreateWindow(WINDOW_CLASS, WINDOW_NAME, WS_OVERLAPPEDWINDOW, 21 100, 100, 640, 480, GetDesktopWindow(), NULL, 22 wc.hInstance, NULL); 23 24 25 if (InitD3D(hWnd) == S_OK) 26 { 27 ShowWindow(hWnd, SW_SHOWDEFAULT); 28 UpdateWindow(hWnd); 29 30 MSG msg; 31 ZeroMemory(&msg, sizeof(msg)); 32 33 while (msg.message != WM_QUIT) 34 { 35 if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) 36 { 37 TranslateMessage(&msg); 38 DispatchMessage(&msg); 39 } 40 else 41 { 42 Render(); 43 } 44 } 45 } 46 47 UnregisterClass(WINDOW_CLASS, wc.hInstance); 48 49 return 0; 50 } 51 LRESULT WINAPI MsgProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) 52 { 53 switch (msg) 54 { 55 case WM_DESTROY: 56 PostQuitMessage(0); 57 return 0; 58 break; 59 60 case WM_KEYUP: 61 if (wParam == VK_ESCAPE) PostQuitMessage(0); 62 break; 63 } 64 65 return DefWindowProc(hWnd, msg, wParam, lParam); 66 } 67 68 HRESULT InitD3D(HWND hwnd) 69 { 70 if (NULL == (g_pD3D = Direct3DCreate9(D3D_SDK_VERSION))) 71 { 72 return E_FAIL; 73 } 74 75 D3DPRESENT_PARAMETERS d3dpparams; 76 ZeroMemory(&d3dpparams, sizeof(d3dpparams)); 77 d3dpparams.Windowed = true; 78 d3dpparams.SwapEffect = D3DSWAPEFFECT_DISCARD; 79 d3dpparams.BackBufferFormat = D3DFMT_UNKNOWN; 80 81 if (FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, 82 D3DDEVTYPE_HAL, 83 hwnd, 84 D3DCREATE_SOFTWARE_VERTEXPROCESSING, 85 &d3dpparams, 86 &g_pDevice))) 87 { 88 return E_FAIL; 89 } 90 91 return S_OK; 92 } 93 94 void Cleanup() 95 { 96 if (NULL != g_pDevice) 97 { 98 g_pDevice->Release(); 99 }100 if (NULL != g_pD3D)101 {102 g_pD3D->Release();103 }104 }105 106 107 void Render()108 {109 if (NULL == g_pDevice)110 {111 return;112 }113 114 g_pDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(30, 60, 90), 1.0f, 0);115 116 if (SUCCEEDED(g_pDevice->BeginScene()))117 {118 g_pDevice->EndScene();119 }120 121 g_pDevice->Present(NULL, NULL, NULL, NULL);122 }
运行结果: