DirectX Game Programming Learning (ii) text display and basic primitive drawing

Source: Internet
Author: User
Tags define function win32 window

First, the text display

In the game development, in the game interface reality some text information is a very common thing, to learn DX game development, obviously understand how DX text display is essential. Characters contain many properties, such as color, size, bold, italic, and so on. We specify these font properties by using the Lpd3dfont object provided by DX, and then render again.

The specific process for text rendering using the WIN32 program framework is as follows:


Second, the basic element of the drawing

Regardless of the complexity of the object, it is ultimately composed of basic elements. In the field of CG (computer graphics), it is common to use one or more groups of polygons that surround the surface of an object to approximate a real object. Since the most simple polygon is a triangle, DX uses triangles to form most of the other polygons, and the triangular meshes approximate the complex three-dimensional objects.

DX defines 6 basic elements: Point list, line segment list, segment stripe, triangle, triangle strip, triangle fan.

1. Point list

A point list is a collection of vertices that are rendered independently of each point. You can use it in the scene to simulate the sky vision and so on.

2. List of segments

A list of segments is a series of independent segments. Can simulate the effect of heavy rain.

3. Line Band

is the interconnected line segment. It can be used to produce non-enclosing polygons.

4. Triangle List

The triangle list is a series of independent triangles.

5. Triangular bands

A triangular strip is a series of adjacent triangles, which reduces the number of vertices. Most of the objects in the 3D scene are made of triangular bands, which can be used to describe complex objects with less memory, less processing time, and higher efficiency.

6. Triangular fan

Similar to triangle bands, but all triangles share the same vertex. Just like a fan.

Third, what is vertex caching?

Vertex caching is a memory cache used by D3D to hold vertex data, which can hold any type of vertex data and can coordinate transformations, lighting processing, cropping, and so on for vertex data. The vertex data in the vertex cache represents the graphic to output to the screen.

Four, flexible vertex format FVF

In D3D, vertices in a vertex cache actually contain a number of attributes, such as vertex coordinates, color, normal direction, texture coordinates, and so on. With the flexible vertex format, users can customize what information is included in the vertices, not all of them.


Code:

-----------------------------------------------------------------------------//file:createdevice.cpp////Desc : This is the first tutorial for using Direct3D. In this tutorial, all//we be doing is creating a Direct3D device and using it to clear the//window.////Cop Yright (c) Microsoft Corporation. All rights reserved.//-----------------------------------------------------------------------------#include < d3d9.h> #pragma warning (disable:4996)//disable deprecated warning #include <strsafe.h> #pragma warning (defau lt:4996) #include <d3dx9core.h>//new//--------------------------------------------------------------------- --------//Global variables//----------------------------------------------------------------------------- Lpdirect3d9 g_pd3d = NULL; Direct3D object Lpdirect3ddevice9 g_pd3ddevice = NULL;   Direct3D render Device Object Lpd3dxfont G_pfont = 0;//Font Object wchar*strtext = L "Please enter the code for the entity you want to display: \ n 1: Point list \ n 2: List of segments \ n 3: line stripe \ n 4: Triangle list \ n 5: TriangleStripe \ n 6: Triangle fan \ ESC: Exit "; "\ n is a newline, and then a" \ "is a description of whether the string content does not end, the next line or the contents of the string" RECT clientrect;  Lpdirect3dvertexbuffer9 G_PVB = null;//Vertex cache object int g_itype = 1; Primitive type, each element corresponding to an integer value, stored in the variable, the initialization is plotted "1" corresponding to the entity//definition flexible vertex structure struct customvertex{float x,y,z,rhw;//defines the coordinate information DWORD color;}; #define D3DFVF_CUSTOMVERTEX (D3DFVF_XYZRHW | D3dfvf_diffuse)//define function to complete initialization of the entire vertex HRESULT INITVB () {//Vertex data CustomVertex vertices[] = {{50.0f,250.0f,0.5f,1.0f, 0xffff0000,},{150.0f,50.0f,0.5f,1.0f,0xffff0000,},{250.0f,250.0f,0.5f,1.0f,0xffff0000,},{350.0f,50.0f,0.5f, 1.0f,0xffff0000,},{450.0f,250.0f,0.5f,1.0f,0xffff0000,},{550.0f,50.0f,0.5f,1.0f,0xffff0000,},};//Create a vertex cache if ( FAILED (G_pd3ddevice->createvertexbuffer (6 * sizeof (CUSTOMVERTEX), 0,d3dfvf_customvertex,d3dpool_default,&g _pvb,null)) {return e_fail;} Populate vertex cache void* pvertices;if (FAILED (G_pvb->lock (0,sizeof), (vertices) void**)) return &pvertices,0; memcpy (Pvertices,vertices,sizeof (verticES); G_pvb->unlock (); return S_OK;} /* Description, a Direct3D object can create multiple Direct3D device objects, but all render device objects created by the D3D object share the same physical resources, resulting in severe performance degradation *///------------------------------ -----------------------------------------------//NAME:INITD3D ()//desc:initializes direct3d//------------------- ----------------------------------------------------------HRESULT INITD3D (hwnd hwnd) {//Create D3D object, which is used to create D3D device object if    (NULL = = (G_pd3d = Direct3dcreate9 (d3d_sdk_version))) return E_FAIL;  Set d3dpresent_parameters structure, prepare to create D3D device object/* Description before DX renders a window, you must first set the window according to the rendering needs, such as whether to use hardware rendering or software rendering, whether the rendering is using single or double buffering Whether a deep cache is required, whether templates, alpha caches, etc. are required.  When you set these parameters for a window, you cannot change them unless you destroy and create additional windows as needed.    The 3d feature of the window is set once, usually after the window is created, the name of the collection of these settings is d3dpresent_parameters*/d3dpresent_parameters D3DPP;    ZeroMemory (&AMP;D3DPP, sizeof (D3DPP)); D3DPP. Windowed = true;//full screen or window D3DPP. SwapEffect = d3dswapeffect_discard;//Specifies how the surface is exchanged in the swap chain. D3dswapeffect_discard: After the contents of the backing cache are copied to the screen, the contents of the fallback cache are invalidated and the D3DPP can be discarded. Backbufferformat = d3dfmt_unknown;//fallback buffer format, if not familiar, can be set to D3dfmt_UNKNOWN, it will use the format of the desktop/* When the preparation is finished, you can create the DX device object ROM because the DX object is the topmost object of the entire DX program, and the other objects will be used by its interface function to create parameter 1: Specify the physical display device to be represented by the object. Even if you use a display to create a device object Parameter 2: Device type, the HAL device is chosen here. The most important device is the hardware abstraction layer (HAL) device, which supports hardware rasterization acceleration and software and hardware vertex processing. The D3D accesses the hardware through the HAL. If the application is running on a computer that supports HAL, the best performance will be achieved by using the HAL device. The other is the reference device, which supports all D3D features, but is implemented in software, so it is slower for hardware. Parameter 3: Specifies the prompt window when the DX program transitions from foreground to background. Parameter 4: Specify how the D3D does the 3D operation, here the parameter meaning: DX software for vertex operation parameter 5: Develop an already initialized D3dpresent_parameters instance parameter 6: Return the created device, the created device object pointer is stored in the parameter */if ( FAILED (G_pd3d->createdevice (D3dadapter_default, D3ddevtype_hal, HWnd, D3dcreate_ Software_vertexprocessing, &AMP;D3DPP, &g_pd3ddevice)) {return e_f    AIL; }//-------------Fonts Section-----------------//Create Font objects//Device state would normally be set HEREif (FAILED (D3dxcreatefont (g_pd3 Ddevice,0,0,0,0,0,0,0,0,0,l "Arial", &g_pfont))) Return e_fail;//Get window client area getclientrect (hwnd,&clientrect);// --------------Vertex part-----------------//Set culling mode to not reject any face g_pd3ddevice->setrenderstate (D3drs_cullmode,d3dcull_nonE);//Set entity fill mode to wireframe mode g_pd3ddevice->setrenderstate (d3drs_fillmode,d3dfill_wireframe);//return S_OK;} -----------------------------------------------------------------------------//Name:cleanup ()//Desc:releases All previously initialized objects//empty the resource referenced before//------------------------------------------------------------------ -----------/*d3d object and D3D device object are system resources, if only apply for not release, must cause resource leakage, in the entire process, the requested object must be manually released. Because the D3D device object is created by the D3D object, the D3D device object is released first.    The last release created, the process of creating, releasing, and the stack structure is the same as */void Cleanup () {if (g_pd3ddevice! = NULL) g_pd3ddevice->release (); if (g_pd3d! = null) g_pd3d->release ();//Free font if (G_pfont! = null) {g_pfont->release ();} Releases the vertex cache object if (G_PVB! = NULL) {g_pvb->release ();}} -----------------------------------------------------------------------------//Name:render ()//Desc:draws the scene//-----------------------------------------------------------------------------VOID Render () {if (NULL = = G_    Pd3ddevice) return; Empty the background cache/* parameter 1:prects the number of rectangles in the group, and if the second parameter (*prects) is empty,It must be 0 here, and if not NULL, it must be a non-0 value parameter 2: An array of screen rectangles to be cleared, a pointer to an array of d3drect structures, which allows us to clear some part of the screen parameter 3: Specify on which surfaces to perform clear surface operations, D3dclear_ TARGET indicates the empty color cache parameter 4: What color is used to fill the cleared surface parameter 5: Set the value of the depth buffer parameter 6: Set the value of the template buffer */g_pd3ddevice->clear (0, NULL, D3dclear_target,    D3dcolor_xrgb (0, 0, 255), 1.0f, 0); Start drawing graphics in background cache if (SUCCEEDED (G_pd3ddevice->beginscene ())) {//Draw graphics in background cache G_pfont->drawtext (Null,strtex T,-1,&clientrect, Dt_noclip | Dt_left | DT_TOP,0XFFFFFFFF); G_pd3ddevice->setstreamsource (0,g_pvb,0,sizeof (CustomVertex)); G_pd3dDevice->SetFVF ( D3dfvf_customvertex), switch (g_itype) {case 1:g_pd3ddevice->drawprimitive (d3dpt_pointlist,0,6), Case 2:g_ Pd3ddevice->drawprimitive (d3dpt_linelist,0,3); Break;case 3:g_pd3ddevice->drawprimitive (D3DPT_LINESTRIP, 0,5); break;case 4:g_pd3ddevice->drawprimitive (d3dpt_trianglelist,0,2); Break;case 5:g_pd3dDevice-> DrawPrimitive (d3dpt_trianglestrip,0,4); Break;case 6:g_pd3ddevice->drawprimitive (D3DPT_TRIANGLEFAN,0,4); break        ;} End the scene G_pd3ddeviCe->endscene (); }//Will render the drawing in background cache to the foreground cache display/* Parameter 1: is a rectangular area of the fallback cache you want to display, set to NULL to display the contents of the entire fallback cache as parameter 2: Represents a display area, Set to NULL indicates that the entire customer displays area parameter 3: It can be used to display content to a different window. Set to NULL indicates that the current main window is displayed. Parameter 4: Is the minimum update area pointer, typically set to null*/g_pd3ddevice->present (null, NULL, NULL, NULL);} -----------------------------------------------------------------------------//Name:msgproc ()//Desc:the Window ' s Message handler//message handler function callback function//-------------------------------------------------------------------------- ---LRESULT WINAPI msgproc (HWND hwnd, UINT MSG, WPARAM WPARAM, LPARAM LPARAM) {switch (msg) {//window close case WM            _destroy:cleanup ();            PostQuitMessage (0);            Return 0;//window Plot case wm_paint:render ();            ValidateRect (HWnd, NULL); Return 0;case Wm_keyup:switch (wParam) {case vk_escape:cleanup ();     PostQuitMessage (0); Break;case 49:case 50:case 51:case 52:case 53:case 54:g_itype = (int) wparam-48;break;} } return DefWindowProc (HWnd, MSG, WParam, LPAram);} -----------------------------------------------------------------------------//Name:wwinmain ()//DESC: This is the entry function for the entire project, starting from here, the structure,/* Note that INITIALIZED3D is the resource requirement to complete the DX framework, and if the function is unsuccessful, the program cannot continue, but the program cannot continue if the Windows Framework resource has not been successfully requested. You should apply for Windows framework resources before you determine if INITIALIZED3D is successful, and if successful, enter the message loop-----------------------------wWinMain can handle Unicode characters. Instead, WinMain converts Unicode characters directly to ANSI characters (which can go wrong if you use Chinese) the first parameter: The application's current handle second: the previous handle to this instance of the application (running more than one) Third: the command line that does not contain the application. You can use CMD to pass a string instruction to the application fourth: How to make the window display id*///------------------------------------------------------------------------- ----INT WINAPI wWinMain (hinstance hInst, hinstance, LPWStr, INT) {unreferenced_parameter (hInst);/*WIN32 macro Unreferen Ced_parameter, you can use it to avoid the compiler's warning about parameters that are not referenced in the body of the function. While it is technically not necessary, it is a good programming habit to work hard to build 0 warning codes. Because this particular macro doesn't do anything, the compiler will optimize it. *///define window class/* this window class is defined as struct wndclassex, which contains various properties of the Win32 window, including the window's icon, menu, the application instance to which the window belongs, the appearance of the cursor, etc. */wndclassex WC = {Size Of (Wndclassex), CS_CLASSDC, Msgproc, 0L, 0L, GetModuleHandle (null), NULL, NULL, NULL, NULL, L "DirectX game Programming One", NULL};//Registration window class/* Send the WNDCLASSEX structure we created to the function registerclassex () and register the window class with the system. The function registerclassex () must be called before the window is created, which requires the address of the window class structure to be registered as an argument. If the function executes, the return value is 0 to indicate that the registration failed, and the reader should check the values of each member of the window class to see if there are any errors and make sure that they are valid values.     */RegisterClassEx (&AMP;WC); /* The next step is to create the actual window CreateWindow accept Unicode characters. If you are using a Unicode version, we must always enclose the string in quotation marks and then prefix it with an L to indicate that we are providing Unicode characters. -----parameter: lpclassname (optional)--the name of the window class (same name as the window class structure). Lpwindowname (optional)--the title bar text of the window. dwstyle--window-style logo. x--the horizontal position of the window. y--the vertical position of the window. The width of the nwidth--window. The height of the hheight--window. hWndParent (optional)--a handle to the parent window (for example, the new window is a pop-up or child window). HMenu (optional)--Window menu resource handle. HINSTANCE (optional)--the Application instance ID (the first parameter of the function wWinMain) lpparam (optional)--passing data to the window as a parameter of the window callback function proc---function CreateWindow (A) The return value is a non-empty handle */HWND hwnd = CreateWindow (L "DirectX game Programming One", L "DirectX game Programming One: Initialize D3D device", Ws_ove    Rlappedwindow, +, +, +, NULL, NULL, wc.hinstance, NULL); Initialize Direct3D Initialize the D3D device/* If the creation is successful, enter the message loop */if (SUCCEEDED (hWnd)) {//Display window if (SUCceeded (INITVB ())) {ShowWindow (hWnd, Sw_showdefault);        UpdateWindow (HWND);        Enter the message loop/*msg is a WIN32 structure for saving window messages, some of which are from the operating system, and the application will respond to these messages */MSG msg; while (GetMessage (&msg, NULL, 0, 0))//Extract Message {/* We can respond to this message by calling the TranslateMessage function and the DispatchMessage function Transla            Temessage is to convert the virtual key message to a character message, and the function dispatchmessage is to dispatch the message to the window program's callback function, which will be discussed in the next section */TranslateMessage (&AMP;MSG);        DispatchMessage (&AMP;MSG);    }} unregisterclass (L "DirectX game Programming One", wc.hinstance); return 0;}}




DirectX Game Programming Learning (ii) text display and basic primitive drawing

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.