D3d learning notes-create a d3d environment window

Source: Internet
Author: User

Today is the first time I open my website here. I will first explain that writing this document is not a tutorial. I am not an expert either. I just want to have a deeper understanding of direct3d, at the same time, if you see these things unfortunately, I hope it will be helpful to you.

 

At the same time, I solemnly declare that this post will not be reprinted. I am not an expert and it is inevitable to make mistakes. However, if someone else is misled, it is a big mistake. I hope you will forgive me. Thank you for choosing...

The code and description I wrote here are not my own understanding. I have referenced the SDK and other books and some instructions on the Internet. Because of the large number of examples, I have not listed them one by one, about copyright (if such a simple thing is held copyrighted. Haha) Please do not investigate too much, it is all for learning.

Although you have already used d3d to find something, if you want to understand d3d, you can only say that you are a layman. Now, you have decided to learn about d3d from the grassroots level: let's start with: we are programming in windows, so we have to generate a window: in windows, there is a winmain function, which is the portal of the window program: int winapi winmain (hinstance hinst, hinstance, lpstr, INT); this is the function header. it indicates the winmain function. Hinstance hinst is an instance object. Because the following parameters are not used in the d3d program, the parameter name is not added. The following is a detailed explanation of the function body of the winmain function. (Including d3d environment initialization) {// registration window class

Wndclassex WC = {sizeof (wndclassex), cs_classdc, msgproc, 0l, 0l, getmodulehandle (null), null,

L "classname", null };

// To generate a window in Windows, you must first register a window class and use the object of this class to create a window. below is the structure typedef struct _ wndclass {

Uint style; // window style * wndproc lpfnwndproc; // a remote pointer to the message processing function of the specified window * int cbclsextra; // specify the number of additional bytes * int cbwndextra after being allocated to the window class structure; // specify the number of additional bytes handle hinstance after being allocated to the window instance; // specify the instance handle * hicon for the window process; // specify the hcursor icon for the window; // specify the window mouse hbrush hbrbackground; // specify the background image of the window. The value is "maid". // The Name Of The menu resource in the window is "maid". // The Name Of The window class *} wndclass;

// We can see that this struct is very complex, but fortunately we don't need to assign values to all of them. We only need a few items in it. For example, I only specify the items in the preceding window and use the window class above to register the window: registerclassex (& WC); // This is the registration window // create window

Hwnd = createwindow (L "classname", l "Basic Elements", ws_overlappedwindow, 100,100,600,300,

Getasktopwindow (), null, WC. hinstance, null );

After the registration window, call createwindow to create a window. The function declaration is as follows: hwnd createwindow (

Lpctstr Lpclassname, Lpctstr Lpwindowname, DWORD Dwstyle, Int X, Int Y, Int Nwidth, Int Nheight, Hwnd Hwndparent, Hmenu Hmenu, Hinstance Hinstance, Lpvoid Lpparam);

For more information about this function, see http://msdn.microsoft.com/zh-cn/library/ms632679 (En-US, vs.85). aspx

The following is the environment for initializing d3d. This initialization function is not implemented here. The initd3d content will be provided later // initialize direct3d.

If (succeeded (initd3d (hwnd) // initialize the d3d environment and provide the implementation steps later. {// Display the Main Window

Showwindow (hwnd, sw_showdefault );

// Call windowsapi to display the generated window. hwnd is the window handle generated when the window is generated.

Updatewindow (hwnd); // update window

// Enter the message loop

MSG; // message structure in Windows: zeromemory (& MSG, sizeof (MSG); // clear the message structure. While (msg. message! = Wm_quit) // enters the message loop and ends when the message exits. {

If (peekmessage (& MSG, null, 0u, 0u, pm_remove ))

// Obtain messages from the Windows message queue. For detailed function usage, see msdn

{Translatemessage (& MSG); // translation message dispatchmessage (& MSG); // transfer message} else {render (); // if there is no message, rendering graphics, function implementation, provided later }}

}

Unregisterclass (L "classname", WC. hinstance); // cancel the newly registered window class object when exiting.

Return 0;

} The above is all about the winmain function. The following describes the implementation of the initd3d function: hresult initd3d (hwnd)

{// Create a direct3d object. This object is used to create the direct3d device object if (null = (g_pd3d = direct3dcreate9 (d3d_sdk_version )))

Return e_fail;

// Set the d3dpresent_parameters structure to create a direct3d device object

D3dpresent_parameters d3dpp; // declare the struct zeromemory (& d3dpp, sizeof (d3dpp); // clear the struct d3dpp. incluwed = true; // allow window Customization

D3dpp. swapeffect = d3dswapeffect_discard;

// Copy the background buffer directly to the foreground and clear the background buffer.

D3dpp. backbufferformat = d3dfmt_unknown; // The display format is the same as that of the current video card.

// Create a direct3d device object

If (failed (g_pd3d-> createdevice (d3dadapter_default, d3ddevtype_hal, hwnd, d3dcreate_software_vertexprocessing, & d3dpp, & g_pd3ddevice) {return e_fail;

}

Return s_ OK;} The content above is initd3d: // create a direct3d object, which is used to create a direct3d device object

If (null = (g_pd3d = direct3dcreate9 (d3d_sdk_version )))

Return e_fail;

Create a direct3d object. This object is used to create a direct3d device object. The above content has specific explanations. Here we will explain in detail the structure of the d3dpresent_parameters struct as follows: backbufferwidth: width of full-screen backup Buffer

Backbufferheight: full-screen backup buffer height backbufferformat: device window handle pull wed: full screen or window enableautodepthstencer: Activate depth buffer autodepthstencilformat: depth buffer format fullscreen_refreshrateinhz: Display update rate

Presentationinterval: Maximum image refresh speed

We have used three quantities above, and the others all adopt the system default. After d3dpresent_parameters is created, call the createdevice function with the newly created direct3d object to create the device. For example, g_pd3d-> createdevice (d3dadapter_default, d3ddevtype_hal, hwnd,

D3dcreate_software_vertexprocessing,

& D3dpp, & g_pd3ddevice)

This function is described as follows:Hresult createdevice (Uint Adapter,D3ddevtype Devicetype,Hwnd Hfocuswindow,DWORD Behaviorflags,D3dpresent_parameters * Ppresentationparameters,Idirect3ddevice9 ** Ppreturneddeviceinterface ); Adapter:Specifies the serial number of the video card and specifies the video card used to create the environment. The default value is d3dadapter_default.Devicetype:Specify the device type. We use hardware acceleration here. D3ddevtype_hal: Make sure your machine supports hardware acceleration. Not supported.Hfocuswindow:Specifies the prompt window when the direct3d program is changed from the foreground to the background. When direct3d is running in full screen mode, the window must be a top-level window. When running in window mode, this member can be set to null. In this case, the window is the window specified by the hdecivewindow member in the d3dpresent_parameters structure.Behaviorflags:Specify how the direct3d device works. We use d3dcreate_software_vertexprocessing to perform fixed-point operations by direct3d software.PpresentationparametersThis parameter uses the d3dpresent_parameters struct we just declared. Just enter the d3dpp we set here.PpreturneddeviceinterfaceThe entry pointer of the device environment should be well preserved. We spent so much effort to get it out. If it was lost, the consequences would be very serious. Now we have to create a window for the d3d environment. Well, I'm happy. Let's take a look at the remaining functions: render (); this function is responsible for rendering our scenario. How to render it? Wait and see :( haha) void render ()

{// Clear the background buffer g_pd3ddevice-> clear (0, null, d3dclear_target, d3dcolor_xrgb (45, 50,170), 1.0f, 0 ); // start drawing the image in the background buffer if (succeeded (g_pd3ddevice-> beginscene ())) {// draw a graph in the background buffer here // end rendering the graph g_pd3ddevice-> endscene () in the background buffer ();

}

// Submit the drawing drawn in the background buffer area to the front-end buffer area for display.

G_pd3ddevice-> present (null, null );

}

Let's take a look at it. It's actually nothing mysterious, right? Well, of course, it's so simple, because it's just a framework, huh, so it's just a preparation for rendering, nothing is rendered. First, this function: g_pd3ddevice-> clear (0, null, d3dclear_target, d3dcolor_xrgb (45, 50,170), 1.0f, 0); its role is to clear the view, buffer and other content of one or more faces. The declaration of this function is as follows:HresultClear (DWORD Count, Const d3drect * Prects, DWORD Flags,D3dcolor Color,Float Z, DWORD Stencel); Count:This parameter specifies the number of rectangles in the array pointed to by the next parameter prects. If prects is empty, this parameter must be 0. If prects is not empty, this parameter cannot be set to 0. set it to 0.Prects:This parameter is a pointer to d3drect. This array contains the rectangular area to be cleared. We set it to null.FlagsSpecify the buffer to be cleared. Any combination of d3dclear_target, d3dclear_zbuffer, and d3dclear_stencer indicates clearing the color buffer, depth buffer, template buffer, or their combination. Here we use the clear color buffer.Color:Specify the fill color after clearing the color buffer. We specify to Blue Z: Specify the depth value of each pixel in the depth buffer after the depth buffer is cleared. Stencel: Specifies the template value corresponding to each pixel in the buffer after the template buffer is cleared. I will introduce some things that I don't understand later. Well, it's good. After an important function in rendering is introduced, the progress is a little slow. It doesn't matter. To clarify it, it should be clear. It cannot be very eager for success, that would not do well, huh, huh. Come on. We continue .. the following is g_pd3ddevice-> beginscene (). It is obvious that we have used the environment portal that we just got out of the box. In fact, we also used it. You can see it. This is very important, you cannot discard it. So what is the beginscene function? In fact, beginscene and endscene are two functions that must be used during rendering. beginscene notifies the direct3d device to start drawing rendering. Otherwise, errors will occur. So let's give a solid notification, well, after the rendering is complete, we are using the endscene notification to end the rendering. In this way, no exception occurs. Well, there is only one function left. The present function submits the image in the background buffer we have drawn to the foreground for display. The declaration is as follows:Hresult present (Const rect * Psourcerect,Const rect * Pdestrect,Hwnd Hdestwindowoverride,Const rgndata * Pdirtyregion );In fact, in most cases, the values of the first two parameters and the last one are null, which indicates updating all Regions of the buffer,Psourcerect:Copy the source rectangular area pointer.Pdestrect:Copy the rectangular area pointer of the target.Hdestwindowoverride:Points to the currently drawn drawing window handle. If this parameter is 0, it indicates that when the current window handle is the device environment we created, g_pd3d-> createdevice (d3dadapter_default, d3ddevtype_hal, hwnd, d3dcreate_software_vertexprocessing, & d3dpp, & g_pd3ddevice) the value of hdevicewindow in d3dpp.Pdirtyregion:The smallest update area. So far. The content of the render function is described. I am a little tired. I insist on the introduction. It's not enough... The following functions are relatively simple and not much can be studied. However, they are also very important. Void cleanup ()

{// Release the direct3d device object if (g_pd3ddevice! = NULL)

G_pd3ddevice-> release ();

// Release the direct3d object

If (g_pd3d! = NULL) g_pd3d-> release ();

}

The above code releases the environment and resource objects we have created. It is not a good habit to release resources after the program ends.

The following is our windows message callback function: lresult winapi msgproc (hwnd, uint MSG, wparam, lparam) {Switch (MSG) {Case wm_destroy: cleanup (); postquitmessage (0); Return 0; Case wm_paint: render (); validaterect (hwnd, null); Return 0;} return defwindowproc (hwnd, MSG, wparam, lparam );} I believe you are familiar with this callback function, so I will not talk about it. Here we have processed some basic message information. The above is the creation of the Win32 d3d environment window. For your own learning, if you see it "Unfortunately", I hope it will be helpful to you. The following is all the source code of this program. Create an empty Win32 project and copy the source code. if the environment is configured properly, there should be no problems, there are many introductions on the Environment configuration online, so I will not talk about it anymore. Take a break .... Source code: // ================================================ ===================================================/ /Desc: the simplest direct3d program, // ================================================ ================================================ # include <d3d9. h> // variable // global variable // ------------------------------------------------------------------------------------- lpdirect3d9 g_pd3d = NULL; // Direct3d object lpdirect3ddevice9 g_pd3ddevice = NULL; // direct3d device object // initialize // Desc: Initialize direct3d // inithresult initd3d (hwnd) {// create direct3d object, this object is used to create the direct3d device object if (null = (g_pd3d = direct3dcreate9 (d3d_sdk_version) return e_fail; // set D3 Dpresent_parameters structure, prepare to create the direct3d device object d3dpresent_parameters d3dpp; zeromemory (& d3dpp, sizeof (d3dpp); d3dpp. required wed = true; d3dpp. swapeffect = d3dswapeffect_discard; d3dpp. backbufferformat = success; // create a direct3d device object if (failed (g_pd3d-> createdevice (d3dadapter_default, d3ddevtype_hal, hwnd, hidden, & d3dpp, & g_pd3ddevice) {return e_fail ;} return s_ OK ;} // Release // Desc: Release the created object // release void cleanup () {// release the direct3d device object if (g_pd3ddevice! = NULL) g_pd3ddevice-> release (); // release the direct3d object if (g_pd3d! = NULL) g_pd3d-> release ();} // render // Desc: rendering image // define void render () {// clear background buffer g_pd3ddevice-> clear (0, null, d3dclear_target, d3dcolor_xrgb (45, 50,170), 1.0f, 0); // start drawing the image in the background buffer if (succeeded (g_pd3ddevice-> beginscene ())) {// draw a graph in the background buffer here // The end is slowed down in the background Punch area rendering graphics g_pd3ddevice-> endscene () ;}// submit the graphics drawn in the background buffer to the foreground buffer display g_pd3ddevice-> present (null, null);} // notify // Desc: Message Processing // receive lresult winapi msgproc (hwnd, uint MSG, wparam, lparam) {Switch (MSG) {Case wm_destroy: clea NUP (); postquitmessage (0); Return 0; Case wm_paint: render (); validaterect (hwnd, null); Return 0;} return defwindowproc (hwnd, MSG, wparam, lparam);} // vertex // Desc: program entry // vertex int winapi winmain (hinstance hinst, hinstance, lpstr, INT) {// registration window Wndclassex WC = {sizeof (wndclassex), cs_classdc, msgproc, 0l, 0l, getmodulehandle (null), null, l "classname", null }; registerclassex (& WC); // create the window hwnd = createwindow (L "classname", l "simplest direct3d program", ws_overlappedwindow, 200,100,600,500, null, null, WC. hinstance, null); // initialize direct3d if (succeeded (initd3d (hwnd) {// display the main window showwindow (hwnd, sw_showdefault); up Datewindow (hwnd); // enter the message loop MSG; zeromemory (& MSG, sizeof (MSG); While (msg. message! = Wm_quit) {If (peekmessage (& MSG, null, 0u, 0u, pm_remove) {translatemessage (& MSG); dispatchmessage (& MSG);} else {render (); // rendered image }}unregisterclass (L "classname", WC. hinstance); Return 0;} By the way, this article will not be reprinted. If my level is not high, it will be a shame if an error occurs .. Thank you for your understanding.

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.