Direct-X Learning notes--x model Import

Source: Internet
Author: User

I. INTRODUCTION

After experiencing the painful process of the previous handwritten cube, I finally got to the mesh model step. We do the game must not only use the cube ah, want to complex character model must be the art students use professional tools to create, these model files are defined in the shape of the mesh model and texture information, all we have to do is read this file, Then you can create a complex model based on the information in the file. However, plainly, these things DX has been defined for us, we carry an API on the line!

Create these models generally with 3DMAX or Maya software, however, I as a program are not very clear about the people, do not need to know this stuff too much, just need to know the format of its export is good. Typically the modeling software is exported in the format 3ds,.max,. OBJ,.MB etc., and. x is a format for DX, which we use in the learning phase. The x file is sufficient. As for the other, just a tool for identification, the function is the same. Or the old routine, back API.

We use. x file, this is usually the case. x file with several pictures. The x file records how these textures are used, which we don't need to be concerned about.


Two. Process

1. Based on. x file name reads and creates mesh:

The function is prototyped as follows:

HRESULT  d3dxloadmeshfromx (  __in   lpctstr pfilename,<span style= "White-space:pre" ></span>/ /. x file name  __in   DWORD options,<span style= "White-space:pre" ></span>//generally d3dxmesh_managed  __in   lpdirect3ddevice9 pd3ddevice,<span style= "white-space:pre" ></span>//device pointer  __out  Lpd3dxbuffer *ppadjacency,<span style= "white-space:pre" ></span>//grid Pro Info buffer pointer  __out  Lpd3dxbuffer *ppmaterials,<span style= "white-space:pre" ></span>//mesh material and texture information buffer pointer  __out  Lpd3dxbuffer *ppeffectinstances,<span style= "white-space:pre" ></span>//mesh effect buffer pointer  __out  DWORD *pnummaterials,<span style= "white-space:pre" ></span>//material information number  __out Lpd3dxmesh *ppMesh  <span style= "White-space:pre" pointer to ></span>//mesh pointer);

There is a new type of data type Lpd3dxbuffer, and we see that several kinds of information exist in the buffer that this type of pointer is pointing to. What if we want to get a specific type of information to be swollen?

DX provides us with a function: GetBufferPointer (); For example, if we want to get material information, we can write:

D3dxmaterial *pmtrl = (d3dxmaterial*) pmtrlbuffer->getbufferpointer ();

For example:

D3DXLOADMESHFROMX (TEXT ("Tiger. X "), d3dxmesh_managed, g_pdevice, &padjbuffer, &pmtrlbuffer, NULL, &g_dwnummtrls, &g_pmesh);
From Tiger. X creates a mesh model in which the information is stored in the buffer to which we passed the parameters.


2. Load material and texture information:

With the above function, we obtain material and texture information, which is stored in the buffer pointed to by Pmtrlbuffer, which is stored using the d3dxmaterial structure, which is defined as follows:

typedef struct D3DXMATERIAL {  d3dmaterial9 matd3d;<span style= "white-space:pre" ></span>//material information  LPSTR        ptexturefilename;<span style= "white-space:pre" ></span>//texture map filename} d3dxmaterial, * lpd3dxmaterial;

In this way, we can extract the mesh model's material and texture information from the buffer that the Pmtrlbuffer pointer points to, and use it in the object we want to draw. And the number of this structure is stored in the g_dwnummtrls, we just need to traverse, we can set the texture material.

For example:

<span style= "White-space:pre" ></span>lpd3dxbuffer padjbuffer = null;//temporary buffer pointer, storing object model information LPD3DXBUFFER Pmtrlbuffer = null;//temporary buffer pointer, store object texture material information//according to. The x file creates the mesh model D3DXLOADMESHFROMX (TEXT ("Tiger. X "), d3dxmesh_managed, g_pdevice, &padjbuffer, &pmtrlbuffer, NULL, &g_dwnummtrls, &g_pmesh);// Read material and texture data d3dxmaterial *pmtrl = (d3dxmaterial*) pmtrlbuffer->getbufferpointer ();//buffers that actually store materials and textures, dynamically request memory G_ Pmaterials = new D3dmaterial9[g_dwnummtrls];g_ptextures = new lpdirect3dtexture9[g_dwnummtrls];//is traversed according to the texture number of the material, Set material texture information for (int i = 0; i < G_dwnummtrls; i++) {g_pmaterials[i] = Pmtrl[i]. matd3d;//set material g_pmaterials[i]. Ambient = G_pmaterials[i]. diffuse;//setting ambient light g_ptextures[i] = Null;d3dxcreatetexturefromfilea (g_pdevice, Pmtrl[i].ptexturefilename, &g_ Ptextures[i]);//creates a texture based on the obtained texture file name}//releases the buffer safe_release (Padjbuffer) pointed to by the two pointers just passed to the D3DXLOADMESHFROMX function; Safe_release (Pmtrlbuffer);

In this way, our mesh model is created, the east is in the G_pmesh, we use only through the G_pmesh to be able to draw.


3. Draw the Mesh model:

Finally to the last step, so excited! Finally to see the model!

When drawing, but also need to sub-section, because there are several texture material information, so it is necessary to draw several times, this number of course there is the g_dwnummtrls, or the same, traverse a bit:

Before drawing, we need to set the material, the material exists in our g_pmaterials array, then we set the texture information, the texture information exists in our g_ptexture array.

Finally, using G_pmesh's Drawsubset () method, there is only one parameter, which is the traversal of I.

Example:

for (int i = 0; i < G_dwnummtrls; i++) {g_pdevice->setmaterial (&g_pmaterials[i]); g_pdevice->settexture (0, G _ptextures[i]); G_pmesh->drawsubset (i);}


Three. The example is done! Run a bit quickly, a tiger on the thick line ....



In this way, we can easily draw a beautiful model, rather than the painful hand-drawn cube .... However, everything is the first bitter sweet, no prior to the pain of the laying of the stage, directly using too high-end technology, will only make us more frivolous.


The full demo:

The footage uses DX's own tiger.x

D3DDemo.cpp: Defines the entry point for the application. #include "stdafx.h" #include "D3DDemo.h" #define max_loadstring 100#define safe_release (p) {if (p) {(P)->release ();  (p) = NULL;}} Global variables: hinstance hinst;//Current instance Tchar sztitle[max_loadstring];//title bar text tchar szwindowclass[max_loadstring];//main window class name// The forward declaration of the function contained in this code module: HWND g_hwnd; Atommyregisterclass (hinstance hinstance); Boolinitinstance (HINSTANCE, int.); LRESULT Callbackwndproc (HWND, UINT, WPARAM, LPARAM);//---------transform the content required by the 3D window------------lpdirect3d9 g_pd3d = NULL; D3D interface pointer Lpdirect3ddevice9 g_pdevice = NULL;//D3D device pointer//Create mesh object required content Lpd3dxmesh G_pmesh = null;//Mesh Object lpdirect3dtexture9* G_ptextures = null;//Mesh texture information d3dmaterial9* g_pmaterials = null;//Mesh material information DWORD g_dwnummtrls = 0;//Mesh material number//---------- Drawing a drawing step 3. Declare a vertex buffer pointer & an index buffer pointer lpdirect3dvertexbuffer9 G_PVB = NULL; Lpdirect3dindexbuffer9 G_PIB = null;void oncreatd3d () {g_pd3d = Direct3dcreate9 (d3d_sdk_version); if (!g_pD3D) return;// Method of detecting the capability of hardware equipment/*D3DCAPS9 caps; ZeroMemory (&caps, sizeof (caps)); G_pd3d->geTdevicecaps (D3dadapter_default, D3ddevtype_hal, &caps); *///Get related information, screen size, pixel attributes D3ddisplaymode D3DDM; ZeroMemory (&AMP;D3DDM, sizeof (D3DDM)); G_pd3d->getadapterdisplaymode (D3dadapter_default, &AMP;D3DDM);// Set full-screen mode d3dpresent_parameters D3DPP; ZeroMemory (&AMP;D3DPP, sizeof (D3DPP));/*d3dpp. windowed = FALSE;D3DPP. Backbufferwidth = D3DDM. WIDTH;D3DPP. Backbufferheight = D3DDM. HEIGHT;*/D3DPP. windowed = TRUE;D3DPP. Backbufferformat = D3DDM. FORMAT;D3DPP. BackBufferCount = 1;D3DPP. SwapEffect = d3dswapeffect_discard;//The original buffer data is discarded//whether automatic depth template buffering d3dpp is turned on. EnableAutoDepthStencil = true;//The current automatic depth template buffer format D3DPP. Autodepthstencilformat = d3dfmt_d16;//Each pixel has 16 bits of storage space, storage distance from the camera g_pd3d->createdevice (D3dadapter_default, D3ddevtype_hal, G_hwnd, d3dcreate_software_vertexprocessing, &AMP;D3DPP, &g_pdevice); if (!g_pDevice) return;// Set render state, set enable depth value G_pdevice->setrenderstate (d3drs_zenable, true);//Set render state, turn off light g_pdevice->setrenderstate (D3drs _lighting, false);//Set render state, cropping mode g_pdevice->setrenderstate (D3drs_cullmode, D3DCUll_none);//g_pdevice->setrenderstate (D3drs_cullmode, d3dcull_none);} void Createmesh () {Lpd3dxbuffer padjbuffer = null;//temporary buffer pointer, storage object model information Lpd3dxbuffer Pmtrlbuffer = null;//temporary buffer pointer, Store object Texture material information//according to. The x file creates the mesh model D3DXLOADMESHFROMX (TEXT ("Tiger. X "), d3dxmesh_managed, g_pdevice, &padjbuffer, &pmtrlbuffer, NULL, &g_dwnummtrls, &g_pmesh);// Read material and texture data d3dxmaterial *pmtrl = (d3dxmaterial*) pmtrlbuffer->getbufferpointer ();//buffers that actually store materials and textures, dynamically request memory G_ Pmaterials = new D3dmaterial9[g_dwnummtrls];g_ptextures = new lpdirect3dtexture9[g_dwnummtrls];//is traversed according to the texture number of the material, Set material texture information for (int i = 0; i < G_dwnummtrls; i++) {g_pmaterials[i] = Pmtrl[i]. matd3d;//set material g_pmaterials[i]. Ambient = G_pmaterials[i]. diffuse;//setting ambient light g_ptextures[i] = Null;d3dxcreatetexturefromfilea (g_pdevice, Pmtrl[i].ptexturefilename, &g_ Ptextures[i]);//creates a texture based on the obtained texture file name}//releases the buffer safe_release (Padjbuffer) pointed to by the two pointers just passed to the D3DXLOADMESHFROMX function; Safe_release (Pmtrlbuffer);} void OnInit () {//Initialize D3DONCREATD3D ();//Create Mesh model Createmesh ();} void OnDestroy (){if (!g_pdevice) g_pdevice->release (); g_pdevice = NULL;} void Onlogic (float felapsedtime) {}void Transform () {//worldtransform: World transform D3dxmatrixa16 matworld;d3dxmatrixa16 matscaling;//generates a scaling matrix d3dxmatrixscaling (&matscaling, 3.0f, 3.0f, 3.0f);//generates a rotation matrix around the y axis, stored in the Matrix D3dxmatrixrotationy ( &matworld,//output matrix 10.0f//angle); matworld = matscaling * Matworld;g_pdevice->settransform (D3dts_world, &matWo RLD)//viewtransform: Framing transform D3dxvector3 veyept (0.0f, 0.0f, -30.0f);//camera World coordinates D3dxvector3 VLOOKATPT (0.0f, 0.0f, 0.0f);// Observation Point World coordinates D3dxvector3 Vupvec (0.0f, 1.0f, 0.0f);//The upper vector of the camera, usually (0.0f, 1.0f, 0.0f) d3dxmatrixa16 Matview;//view transform Matrix// Based on the above results, the matrix is calculated and deposited into the Matrix D3DXMATRIXLOOKATLH (&matview, &veyept, &AMP;VLOOKATPT, &vupvec);//Framing Transformation g_pdevice- >settransform (D3dts_view, &matview);//projectiontransform: Projection transformation d3dxmatrixa16 matproj;//projection transformation matrix//Generate projection transformation matrix, deposited in the matrix above D3DXMATRIXPERSPECTIVEFOVLH (&matproj,//Output matrix D3DX_PI/4,//viewshed angle, generally pi/41.0f,//display aspect ratio 1.0f,// The near section distance of the viewport is 100.0f//The position of the cross-sectional distance of the camera.//InletLine projection transform G_pdevice->settransform (d3dts_projection, &matproj);} void OnRender (float felasedtime) {/////The first two parameters are 0 and null when the contents of the entire game window are emptied (clear background)//The third object is clear: The front means clear the color buffer, followed by the clear depth buffer, d3dclear_ Stencil emptying the template buffer g_pdevice->clear (0, NULL, d3dclear_target| D3dclear_zbuffer, D3dcolor_xrgb (0,100,100), 1.0f, 0); G_pdevice->beginscene (); Transform ();////----------Drawing a drawing step 6. Set the data source, set the flexible vertex format, draft the entity////set the data flow source//g_pdevice->setstreamsource (//0,// Data Flow pipeline Number (0-15)//g_pvb,//data source//0,//data stream offset//sizeof (stvertex)//bytes per data size//);////notifies the system data format for parsing data//g_pdevice-> SETFVF (D3dfvf_customvertex);//////Draft entity////g_pdevice->drawprimitive (////d3dpt_trianglestrip,//Triangle column////0,// Starting point number////15//number of elements////)////Set index cache//g_pdevice->setindices (G_PIB);//////use index cache to draw graphics//g_pdevice-> DrawIndexedPrimitive (//d3dpt_trianglelist,//Triangle column//0,//vertex starting point, starting at that vertex as index//0,//minimum index value, usually 0//24,//index vertex number//0,//start index , the number of//12//elements is plotted starting at the first index//); for (int i = 0; i < G_dwnummtrls; i++) {g_pdevice->setmaterial (&g_pmaterials[i]); G_pdevice->settexture (0, G_ptextures[i]); G_pmesh->drawsubset (i);} G_pdevice->endscene (); g_pdevice->present (null, NULL, NULL, NULL);}                     int Apientry _tWinMain (_in_ hinstance hinstance, _in_opt_ hinstance hprevinstance, _in_ LPTSTR lpcmdline, _in_ int ncmdshow) {unreferenced_parameter (hprevinstance); Unreferenced_parameter (lpCmdLine); TODO: Place the code here. MSG msg; Haccel hacceltable;//Initialization of global string LOADSTRING (HInstance, Ids_app_title, SzTitle, max_loadstring); LoadString (HInstance, Idc_d3ddemo, Szwindowclass, max_loadstring); MyRegisterClass (HINSTANCE);//Execution of application initialization: if (! InitInstance (HINSTANCE, nCmdShow)) {return FALSE;} hacceltable = Loadaccelerators (hinstance, Makeintresource (Idc_d3ddemo)); ZeroMemory (&msg, sizeof (msg)), while (msg.message! = wm_quit) {if (PeekMessage (&msg, NULL, 0, 0, pm_remove)) { TranslateMessage (&msg);D ispatchmessage (&msg);} else{static DWORD dwtime = timegettime ();D Word dwcurrenttime = timegettime ();D Word dwelapsedtime = DWCurrenttime-dwtime;float felapsedtime = dwelapsedtime * 0.001f;//------------Rendering and Logic section code----------onlogic ( Felapsedtime); OnRender (felapsedtime);//-----------------------------------------if (Dwelapsedtime < 1000/60) { Sleep (1000/60-dwelapsedtime);} Dwtime = Dwcurrenttime;}} OnDestroy (); return (int) Msg.wparam;} Function: MyRegisterClass ()////Purpose: Registers the window class. ATOM MyRegisterClass (hinstance hinstance) {wndclassex wcex;wcex.cbsize = sizeof (wndclassex); wcex.style= CS_HREDRAW | cs_vredraw;wcex.lpfnwndproc= wndproc;wcex.cbclsextra= 0;wcex.cbwndextra= 0;wcex.hinstance= hInstance;wcex.hIcon= LoadIcon (HInstance, Makeintresource (Idi_d3ddemo)); wcex.hcursor= loadcursor (NULL, Idc_arrow); Wcex.hbrBackground= ( Hbrush) (color_window+1); wcex.lpszmenuname= makeintresource (Idc_d3ddemo); wcex.lpszclassname= SzWindowClass; Wcex.hiconsm= LoadIcon (Wcex.hinstance, Makeintresource (Idi_small)); return RegisterClassEx (&wcex);} Function: InitInstance (hinstance, int)////Purpose: Save the instance handle and create the main window////Note:////in this function,We save the instance handle in the global variable and//create and display the main program window. BOOL InitInstance (hinstance hinstance, int ncmdshow) {hInst = hinstance;//Store instance handle in global variable G_hwnd = CreateWindow (Szwi   Ndowclass, SzTitle, Ws_overlappedwindow, Cw_usedefault, 0, cw_usedefault, 0, NULL, NULL, HINSTANCE, NULL);   if (!g_hwnd) {return FALSE;   } setmenu (G_hwnd, NULL);   ShowWindow (G_hwnd, ncmdshow);   UpdateWindow (G_hwnd);   OnInit (); return TRUE;} Functions: WndProc (HWND, UINT, WPARAM, LPARAM)////Purpose: Handles the message of the main window. wm_command-processing Application Menu//wm_paint-Draw main window//wm_destroy-send exit message and return////lresult CALLBACK WndProc (HWND g_hwnd, UINT Messa GE, WPARAM WPARAM, LPARAM LPARAM) {switch (message) {case Wm_keydown:if (WPARAM = vk_escape) postquitmessage (0); break; Case Wm_close:destroywindow (G_hwnd); Break;case wm_destroy:postquitmessage (0); Break;default:return DefWindowProc (g _hwnd, message, WParam, LParam);} return 0;}







Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Direct-X Learning notes--x model Import

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.