Beginning DirectX11 Game Programming Reading Notes 2 step by step start the first DirectX11 Program

Source: Internet
Author: User
Tags win32 window
Document directory
  • 1. Add the main. cpp source file.
  • 2. Compile win32 sdk code and program entry
  • 3. Initialization window and Message Processing
  • Create a project to an existing solution
  • Go to project properties and configure the additional link library.
  • Set the Reference Path of the Linked Library
  • Initialize Direct3D
  • Create a template project
  • Usage,
  • Main. cpp add call

The best learning method is hands-on operations. The following code can be downloaded from the official website of books.

 

The following is based on the development environment of Windows 7 + VS2010. Make sure that you have installed DXSDK.

 

Start to write the first DirectX program. 1. Run VS2010 to create a project named "blakwindow ".

 

2. Add the Windows creation code. The current project will be used as a template for subsequent exercise projects.

 

1. Add the main. cpp source file. 2. Compile the win32 sdk code.
#include <Windows.h>int WINAPI wWinMain(HINSTANCE hInstance,HINSTANCE prevInstance,    LPWSTR cmdLine,int cmdShow){    return 0;}

Here we use wWinMain to replace WinMain and support Unicode parameters. Corresponding parameter 3 type LPWSTR

 

3. Initialization window and Message Processing
# Include <Windows. h> lresult callback WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam); int WINAPI wWinMain (HINSTANCE hInstance, HINSTANCE prevInstance, LPWSTR cmdLine, int cmdShow) {UNREFERENCED_PARAMETER (prevInstance); UNREFERENCED_PARAMETER (Parameter Line); // registration window WNDCLASSEX wndClass = {0}; wndClass. cbSize = sizeof (WNDCLASSEX); wndClass. style = CS_HREDRAW | CS_VREDRAW; wndClass. lpfnWndProc = WndPro C; wndClass. hInstance = hInstance; wndClass. hCursor = LoadCursor (NULL, IDC_ARROW); wndClass. hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); wndClass. lpszMenuName = NULL; wndClass. lpszClassName = "DX11GeoWindowClass"; if (! RegisterClassEx (& wndClass) {return-1 ;}// create a window RECT rc = {0, 640,480}; AdjustWindowRect (& rc, WS_OVERLAPPEDWINDOW, FALSE ); HWND hwnd = create0000wa ("DX11GeoWindowClass", "Blank Win32 Window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, rc. right-rc.left, rc. bottom-rc.top, NULL, NULL, hInstance, NULL); if (! Hwnd) return-1; // display ShowWindow (hwnd, cmdShow); // message Processing MSG = {0}; while (msg. message! = WM_QUIT) {if (PeekMessage (& msg, 0,0, 0, PM_REMOVE) {TranslateMessage (& msg); DispatchMessage (& msg) ;}} return 0 ;} lresult callback WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) {switch (message) {case WM_PAINT: break; case WM_DESTROY: PostQuitMessage (0); break; default: return DefWindowProc (hwnd, message, wParam, lParam) ;}return 0 ;}

For the basic framework of the Win32 SDK window program, refer to MSDN. Here, UNREFERENCED_PARAMETER is used to tell the compiler that the parameter is not used, so as to avoid warning from the compiler.

Develop a good programming style for handling all warning prompts

 

Running effect,

 

 

3. Create a project in the new project, and use the existing solution.

 

Go to project properties and configure the additional link library.

D3d11. lib; d3dx11. lib; dxerr. lib note, separated by commas

 

Set the Reference Path of the Linked Library

$ (DXSDK_DIR) Include; $ (DXSDK_DIR) Lib \ x86;

 

Initialize Direct3D

Steps,

  1. Define the driver type, Feature Level, and switch chain of the created Device
  2. Create a device type
  3. Create a rendering target
  4. Set View

 

The driver types of the created device include,

  • Hardware acceleration: The best performance, also known as HAL (Hardware Abstraction Layer)
  • WARP: Newly Added DX11. Windows Advanced raster platform, using software simulation. Microsoft has greatly optimized the commands.
  • Software driver: developers write their own rendering driver plug-ins. DXSDK is not required. However, it is not recommended to use programs with high performance requirements.
  • REFERENCE: The software simulates all D3D features and is slow. It is generally used for development and supports DXSDK.
  • NULL: essentially the same as REFERENCE, but no rendering Function

Feature Level,

  • 11.0
  • 10.1
  • 10.0

 

What is an exchange chain?

Used for buffering before and after switching (can be understood as the previous frame or the next frame for continuous output), including the following description attributes

  • Buffer quantity (multiple groups are allowed)
  • Output length and width
  • Buffer format
  • FPS. General LCD display 60 HZ
Define the description of the switching link.
DXGI_SWAP_CHAIN_DESC swapChainDesc; ZeroMemory (& swapChainDesc, sizeof (swapChainDesc); swapChainDesc. bufferCount = 1; // Number of buffers swapChainDesc. bufferDesc. width = width; // swapChainDesc. bufferDesc. height = height; swapChainDesc. bufferDesc. format = DXGI_FORMAT_R8G8B8A8_UNORM; // Format: swapChainDesc. bufferDesc. refreshRate. numerator = 60; // FPS swapChainDesc. bufferDesc. refreshRate. denominator = 1; swapChainDesc. bufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDesc. outputWindow = hwnd; swapChainDesc. optional wed = true; // whether the window format is false; swapChainDesc. sampleDesc. count = 1; swapChainDesc. sampleDesc. quality = 0;

 

Create a switch chain, device context,
Unsigned int creationFlags = 0; # ifdef _ DEBUG creationFlags | = D3D11_CREATE_DEVICE_DEBUG; # endif HRESULT result; unsigned int driver = 0; // ** create device, context, and switch chain for (driver = 0; driver <totalDriverTypes; ++ driver) {result = D3D11CreateDeviceAndSwapChain (0, driverTypes [driver], 0, creationFlags, featureLevels, totalFeatureLevels, D3D11_SDK_VERSION, & swapChainDesc, & swapChain _, & d3dDevice _, & feature Level _, & d3dContext _); if (SUCCEEDED (result) {driverType _ = driverTypes [driver]; break ;}} if (FAILED (result )) {DXTRACE_MSG ("Failed to create the Direct3D device! "); Return false ;}
 
Create a rendering target
 
ID3D11Texture2D * backBufferTexture; result = swapChain _-> GetBuffer (0, _ uuidof (ID3D11Texture2D), (LPVOID *) & backBufferTexture); if (FAILED (result )) {DXTRACE_MSG ("Failed to get the swap chain back buffer! "); Return false;} // ** create a rendering target result = d3dDevice _-> CreateRenderTargetView (backBufferTexture, 0, & backBufferTarget _); if (backBufferTexture) backBufferTexture-> Release (); if (FAILED (result) {DXTRACE_MSG ("Failed to create the render target view! "); Return false;} d3dContext _-> OMSetRenderTargets (1, & backBufferTarget _, 0 );

Set perspective
D3D11_VIEWPORT viewport;    viewport.Width = static_cast<float>(width);    viewport.Height = static_cast<float>(height);    viewport.MinDepth = 0.0f;    viewport.MaxDepth = 1.0f;    viewport.TopLeftX = 0.0f;    viewport.TopLeftY = 0.0f;    d3dContext_->RSSetViewports( 1, &viewport );
 
 
Perform Drawing and rendering
    if( d3dContext_ == 0 )        return;    float clearColor[4] = { 0.0f, 0.0f, 0.25f, 1.0f };    d3dContext_->ClearRenderTargetView( backBufferTarget_, clearColor );    swapChain_->Present( 0, 0 );
 
 
Develop computer hardware,

The NVS5400M video card of the T430 notebook supports DX11 and 128-Bit Memory interfaces, which are divided into 2 GB and 1 GB memory. The T410 uses a NVS3100M video card and does not support DX11.

To debug the DX11 feature, you must support the DX11 video card.

 

Create a template project

D3D initialization and destruction code is required in many projects. To avoid repeated writing, a class DX11DemoBase is generated here.

class Dx11DemoBase{public:    Dx11DemoBase();    virtual ~Dx11DemoBase();    bool Initialize( HINSTANCE hInstance, HWND hwnd );    void Shutdown( );    virtual bool LoadContent( );    virtual void UnloadContent( );    virtual void Update( float dt ) = 0;    virtual void Render( ) = 0;protected:    HINSTANCE hInstance_;    HWND hwnd_;    D3D_DRIVER_TYPE driverType_;    D3D_FEATURE_LEVEL featureLevel_;    ID3D11Device* d3dDevice_;    ID3D11DeviceContext* d3dContext_;    IDXGISwapChain* swapChain_;    ID3D11RenderTargetView* backBufferTarget_;};

 

Usage,

Inherit this class in project implementation,

#include "dx11demobase.h"class BlankDemo :    public Dx11DemoBase{public:    BlankDemo(void);    virtual ~BlankDemo(void);    bool LoadContent( );    void UnloadContent( );    void Update( float dt );    void Render( );};

Main. cpp add call
BlankDemo demo; // initialize DX object bool result = demo. initialize (hInstance, hwnd); if (result = false) return-1; // Message Processing MSG = {0}; while (msg. message! = WM_QUIT) {if (PeekMessage (& msg, 0, 0, PM_REMOVE) {TranslateMessage (& msg); DispatchMessage (& msg );} // ** DX object action demo. update (0.0f); demo. render ();} // release the DX object demo. shutdown ();
 
Another method is std: auto_prt.
Std: auto_ptr <Dx11DemoBase> demo (new BlankDemo (); // Initialize the DX object bool result = demo-> Initialize (hInstance, hwnd); if (result = false) return-1; // Message Processing MSG = {0}; while (msg. message! = WM_QUIT) {if (PeekMessage (& msg, 0, 0, PM_REMOVE) {TranslateMessage (& msg); DispatchMessage (& msg );} // ** DX object action demo-> Update (0.0f); demo-> Render ();} // release DX object demo-> Shutdown ();

The advantage of std: auto_prt is that the memory can be automatically released when the scope is exceeded. It is automatically released even if it exits unexpectedly. Recommended Practice.

 

Final Run,

 

DX programming error handling,

Three methods are supported,

  • TCHAR * DXGetErrorDescription (HRESULT hr) // get detailed error description
  • TCHAR * DXGetErrorString (HRESULT hr) // only the error code is returned and there is no description
  • HRESULT DXTrace (CHAR * strFile, DWORD dwline, HRESULT hr, CHAR * strMsg, BOOL bPopMsgBox)

DXTrace displays text messages with detailed Error Descriptions, along with code file names and error line prompts. According to different parameters, three macros should be matched,

  • DXTRACE_ERR (str, hr) // display the custom text and detailed error description corresponding to hr in the debugging window
  • DXTRACE_ERR_MSGBOX (str, hr) // the message box is displayed.
  • DXTRACE_MSG (str) // display custom text in the debug output window

These macros are useful in debugging DX programs.

 

The following describes how to implement 2D rendering.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.