• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            天行健 君子當自強而不息

            深度測試與alpha混合(1)

            在繪制復雜的三維場景時,不可避免地會出現(xiàn)物體間的相互遮擋,在這種情況下,為了正確地繪制場景需要使用深度測試。半透明物體的繪制不同于不透明物體,Direct3D通過alpha混合實現(xiàn)半透明物體的繪制。深度測試可以簡化復雜場景的繪制,alpha混合可以使繪制的三維場景更完整、更逼真。

            在復雜的場景中,通常有多個物體需要繪制,這些物體之間通常會存在遮擋關系,離觀察點較遠的物體會因為近處物體的者的遮擋而不可見或只有部分可見,Direct3D圖形系統(tǒng)提供了深度測試功能來實現(xiàn)這種效果。

             

            深度緩沖區(qū)與深度測試

            要理解深度測試,首先需要理解深度緩沖區(qū)。深度緩沖區(qū)是Direct3D用來存儲繪制到屏幕上的每個像素點的深度信息的一塊內存緩沖區(qū)。當Direct3D將一個場景渲染到目標表面上時,它使用深度緩沖區(qū)來決定光柵化后各個多邊形的像素的前后遮擋關系,最終決定哪個顏色值被繪制出來。也就是說,Direct3D通過比較當前繪制的像素點的深度和對應深度緩沖區(qū)的點的深度值來決定是否繪制當前像素。如果深度測試結果為TRUE,則繪制當前像素,并用當前像素點的深度來更新深度緩沖區(qū),反之則不予繪制。通常情況下,深度緩沖區(qū)對應于屏幕大小的一塊二維區(qū)域。

            對一個啟用了深度緩沖區(qū)的場景進行光柵化操作時,渲染表面上的每個點都要進行深度測試。在深度測試開始時,深度緩沖區(qū)的深度值被設置為該場景可能出現(xiàn)的最大值,渲染表面上的顏色值被設置為背景顏色值。然后測試場景內即將繪制的每個多邊形,看它是否小于存儲在深度緩沖區(qū)中的深度值,如果該多邊形的深度值更小,則該深度值被更新到深度緩沖區(qū)中,并將渲染表面上當前點的顏色值替換為該多邊形的顏色。如果多邊形在這一點的深度值更大,將繼續(xù)測試列表中的下一個多邊形。

             

            創(chuàng)建深度緩沖區(qū)

            若要在Direct3D圖形程序中應用深度測試,首先必須在創(chuàng)建Direct3D渲染設備時創(chuàng)建深度緩沖區(qū),示例代碼如下:

            D3DPRESENT_PARAMETERS d3dpp;
            ZeroMemory(&d3dpp, sizeof(d3dpp));
            d3dpp.Windowed			= TRUE;
            d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
            d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
            d3dpp.EnableAutoDepthStencil = TRUE; // 表示由Direct3D創(chuàng)建并管理一個深度緩沖區(qū)
            d3dpp.AutoDepthStencilFormat = D3DFMT_D16; // 表示深度緩沖區(qū)中每一個像素的深度值由16位的二進制數(shù)表示
            if(FAILED(g_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
            &d3dpp, &g_device)))
            {
            return false;
            }


            激活深度測試

            深度緩沖區(qū)隨Direct3D渲染設備創(chuàng)建好后,調用Direct3D渲染狀態(tài)設置函數(shù)IDirect3DDevice9::SetRenderState(),將第一個參數(shù)設為D3DRS_ZENABLE,第二個參數(shù)設為TRUE,激活深度測試:

            g_device->SetRenderState(D3DRS_ZENABLE,		 TRUE);

             

            設置深度測試函數(shù)

            接下來依然調用IDirect3DDevice9::SetRenderState()函數(shù)設置深度測試函數(shù),第一個參數(shù)設置為D3DRS_ZFUNC:

            D3DRS_ZFUNC
            One member of the D3DCMPFUNC enumerated type. The default value is D3DCMP_LESSEQUAL. This member enables an application to accept or reject a pixel, based on its distance from the camera.

            The depth value of the pixel is compared with the depth-buffer value. If the depth value of the pixel passes the comparison function, the pixel is written.

            The depth value is written to the depth buffer only if the render state is TRUE.

            Software rasterizers and many hardware accelerators work faster if the depth test fails, because there is no need to filter and modulate the texture if the pixel is not going to be rendered.

            第二個參數(shù)設置為想要設置的深度測試函數(shù),它屬于D3DCMPFUNC枚舉類型,定義如下:

            Defines the supported compare functions.

            typedef enum D3DCMPFUNC
            {
            D3DCMP_NEVER = 1,
            D3DCMP_LESS = 2,
            D3DCMP_EQUAL = 3,
            D3DCMP_LESSEQUAL = 4,
            D3DCMP_GREATER = 5,
            D3DCMP_NOTEQUAL = 6,
            D3DCMP_GREATEREQUAL = 7,
            D3DCMP_ALWAYS = 8,
            D3DCMP_FORCE_DWORD = 0x7fffffff,
            } D3DCMPFUNC, *LPD3DCMPFUNC;

            Constants

            D3DCMP_NEVER
            Always fail the test.
            D3DCMP_LESS
            Accept the new pixel if its value is less than the value of the current pixel.
            D3DCMP_EQUAL
            Accept the new pixel if its value equals the value of the current pixel.
            D3DCMP_LESSEQUAL
            Accept the new pixel if its value is less than or equal to the value of the current pixel.
            D3DCMP_GREATER
            Accept the new pixel if its value is greater than the value of the current pixel.
            D3DCMP_NOTEQUAL
            Accept the new pixel if its value does not equal the value of the current pixel.
            D3DCMP_GREATEREQUAL
            Accept the new pixel if its value is greater than or equal to the value of the current pixel.
            D3DCMP_ALWAYS
            Always pass the test.
            D3DCMP_FORCE_DWORD
            Forces this enumeration to compile to 32 bits in size. Without this value, some compilers would allow this enumeration to compile to a size other than 32 bits. This value is not used.

            Remarks

            The values in this enumerated type define the supported compare functions for the D3DRS_ZFUNC, D3DRS_ALPHAFUNC, and D3DRS_STENCILFUNC render states.

            通常情況下,深度測試函數(shù)設置為D3DCMP_LESS,表示當測試點深度值小于深度緩沖區(qū)中相應值時,通過深度測試并繪制相關像素,這樣沒有被遮擋的物體才顯示,而被遮擋的物體就不顯示。示例代碼如下:

            g_device->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESS);

             

            更新深度緩沖區(qū)

            設置了深度測試函數(shù)后,還需要設置深度測試成功時對深度緩沖區(qū)如何操作,是保持原來的深度值,還是用當前像素的深度值更新對應的數(shù)值。

            D3DRS_ZWRITEENABLE
            TRUE to enable the application to write to the depth buffer. The default value is TRUE. This member enables an application to prevent the system from updating the depth buffer with new depth values. If FALSE, depth comparisons are still made according to the render state D3DRS_ZFUNC, assuming that depth buffering is taking place, but depth values are not written to the buffer.

            示例代碼如下:

            g_device->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);

            表示如果通過測試,則用當前像素的深度值更新深度緩沖區(qū)中對應的數(shù)值,這是最常用的設置,也是默認設置。

             

            示例程序

            該示例程序繪制了一個矩形和一個坦克模型,其中先繪制矩形,再繪制坦克模型,而且坦克模型在矩形的后面被遮擋住。如果按下"1"鍵,則禁用深度測試,這時坦克雖然被矩形遮擋住,但仍然被繪制出來了;如果按下"2"鍵,則啟用深度測試,這時坦克模型被矩形遮擋住,沒有繪制出來。

            按下數(shù)字鍵"1",禁用深度測試,被矩形部分遮住的坦克被繪制出來。

             

            按下數(shù)字鍵"2",啟用深度測試,被矩形部分遮住的坦克沒有被繪制出來。

             

            源程序:

            #include <d3dx9.h>

            #pragma warning(disable : 
            4127)

            #define CLASS_NAME    "GameApp"

            #define release_com(p)    do { if(p) { (p)->Release(); (p) = NULL; } } while(0)

            IDirect3D9
            *                g_d3d;
            IDirect3DDevice9
            *        g_device;

            ID3DXMesh
            *                g_mesh;
            D3DMATERIAL9
            *            g_mesh_materials;
            IDirect3DTexture9
            **        g_mesh_textures;
            DWORD                    g_num_materials;
            IDirect3DVertexBuffer9
            * g_shutter_vb;

            D3DXMATRIX                g_mat_tank;
            D3DXMATRIX                g_mat_shutter;

            struct sCustomVertex
            {   
                
            float x, y, z;   
                DWORD color;     
            };

            #define D3DFVF_CUSTOM_VERTEX   (D3DFVF_XYZ | D3DFVF_DIFFUSE)

            void setup_matrices()
            {
                
            // setup world matrix
                D3DXMATRIX mat_world;
                D3DXMatrixIdentity(
            &mat_world);
                g_device
            ->SetTransform(D3DTS_WORLD, &mat_world);

                
            // setup view matrix

                D3DXVECTOR3 eye(
            0.0f2.0f-30.0f);
                D3DXVECTOR3 at(
            0.0f,  2.0f,   0.0f);
                D3DXVECTOR3 up(
            0.0f,  1.0f,   0.0f);

                D3DXMATRIX mat_view;
                D3DXMatrixLookAtLH(
            &mat_view, &eye, &at, &up);
                g_device
            ->SetTransform(D3DTS_VIEW, &mat_view);

                
            // setup projection matrix
                D3DXMATRIX mat_proj;
                D3DXMatrixPerspectiveFovLH(
            &mat_proj, D3DX_PI/41.0f1.0f500.0f);
                g_device
            ->SetTransform(D3DTS_PROJECTION, &mat_proj);
            }

            bool init_geometry()
            {
                ID3DXBuffer
            * material_buffer;

                
            /*
                 D3DXLoadMeshFromXA(
                    LPCSTR pFilename, 
                    DWORD Options, 
                    LPDIRECT3DDEVICE9 pD3DDevice, 
                    LPD3DXBUFFER *ppAdjacency,
                    LPD3DXBUFFER *ppMaterials, 
                    LPD3DXBUFFER *ppEffectInstances, 
                    DWORD *pNumMaterials,
                    LPD3DXMESH *ppMesh);
                
            */

                
            if(FAILED(D3DXLoadMeshFromX("tank.x", D3DXMESH_SYSTEMMEM, g_device, NULL, &material_buffer, NULL,
                                            
            &g_num_materials, &g_mesh)))
                {
                    MessageBox(NULL, 
            "Could not find tank.x""ERROR", MB_OK);
                    
            return false;
                }

                D3DXMATERIAL
            * xmaterials = (D3DXMATERIAL*) material_buffer->GetBufferPointer();

                g_mesh_materials 
            = new D3DMATERIAL9[g_num_materials];
                g_mesh_textures     
            = new IDirect3DTexture9*[g_num_materials];

                
            for(DWORD i = 0; i < g_num_materials; i++)
                {
                    g_mesh_materials[i] 
            = xmaterials[i].MatD3D;

                    
            // set ambient reflected coefficient, because .x file do not set it.
                    g_mesh_materials[i].Ambient = g_mesh_materials[i].Diffuse;

                    g_mesh_textures[i] 
            = NULL;

                    
            if(xmaterials[i].pTextureFilename != NULL && strlen(xmaterials[i].pTextureFilename) > 0)    
                        D3DXCreateTextureFromFile(g_device, xmaterials[i].pTextureFilename, 
            &g_mesh_textures[i]);    
                }

                material_buffer
            ->Release();

                
            // create shutter vertex buffer

                sCustomVertex vertices[] 
            =
                {
                    { 
            -8,   -2,  -10.0f,   0xFFFFFF00},     
                    { 
            -8,    6,  -10.0f,   0xFFFFFF00},    
                    {  
            8,   -2,  -10.0f,   0xFFFFFF00},    
                    {  
            8,    6,  -10.0f,   0xFFFFFF00}
                };

                g_device
            ->CreateVertexBuffer(sizeof(vertices), 0, D3DFVF_CUSTOM_VERTEX, D3DPOOL_DEFAULT, &g_shutter_vb, NULL);
                
                
            void* ptr;
                g_shutter_vb
            ->Lock(0sizeof(vertices),  &ptr, 0);
                memcpy(ptr, vertices, 
            sizeof(vertices));
                g_shutter_vb
            ->Unlock();

                
            return true;
            }

            bool init_d3d(HWND hwnd)
            {
                g_d3d 
            = Direct3DCreate9(D3D_SDK_VERSION);

                
            if(g_d3d == NULL)
                    
            return false;

                D3DPRESENT_PARAMETERS d3dpp;
                ZeroMemory(
            &d3dpp, sizeof(d3dpp));

                d3dpp.Windowed                    
            = TRUE;
                d3dpp.SwapEffect                
            = D3DSWAPEFFECT_DISCARD;
                d3dpp.BackBufferFormat            
            = D3DFMT_UNKNOWN;
                d3dpp.EnableAutoDepthStencil    
            = TRUE;
                d3dpp.AutoDepthStencilFormat    
            = D3DFMT_D16;

                
            if(FAILED(g_d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_SOFTWARE_VERTEXPROCESSING,
                                              
            &d3dpp, &g_device)))
                {
                    
            return false;
                }
                
                
            if(! init_geometry())
                    
            return false;

                setup_matrices();    

                g_device
            ->SetRenderState(D3DRS_ZENABLE,         TRUE);
                g_device
            ->SetRenderState(D3DRS_ZFUNC,         D3DCMP_LESS);
                g_device
            ->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);

                g_device
            ->SetRenderState(D3DRS_AMBIENT, 0xFF00BB00);

                
            // rotate tank

                D3DXQUATERNION quat;
                D3DXMATRIX mat_rotation;

                D3DXMatrixIdentity(
            &g_mat_tank);

                D3DXQuaternionRotationYawPitchRoll(
            &quat, D3DX_PI/4-D3DX_PI/40.0f);
                D3DXMatrixRotationQuaternion(
            &mat_rotation, &quat);
                D3DXMatrixMultiply(
            &g_mat_tank, &mat_rotation, &g_mat_tank);

                D3DXMatrixIdentity(
            &g_mat_shutter);
                
                
            return true;
            }

            void cleanup()
            {
                delete[] g_mesh_materials;

                
            if(g_mesh_textures)
                {
                    
            for(DWORD i = 0; i < g_num_materials; i++)
                        release_com(g_mesh_textures[i]);

                    delete[] g_mesh_textures;
                }
                
                release_com(g_mesh);
                release_com(g_shutter_vb);
                release_com(g_device);
                release_com(g_d3d);
            }

            void render()
            {
                g_device
            ->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(555), 1.0f0);

                g_device
            ->BeginScene();

                
            // render shutter
                g_device->SetRenderState(D3DRS_LIGHTING, FALSE);
                g_device
            ->SetTransform(D3DTS_WORLD, &g_mat_shutter);
                g_device
            ->SetStreamSource(0, g_shutter_vb, 0sizeof(sCustomVertex));
                g_device
            ->SetFVF(D3DFVF_CUSTOM_VERTEX);
                g_device
            ->DrawPrimitive(D3DPT_TRIANGLESTRIP, 02);

                
            // render tank
                g_device->SetRenderState(D3DRS_LIGHTING, TRUE);
                g_device
            ->SetTransform(D3DTS_WORLD, &g_mat_tank);

                
            for(DWORD i = 0; i < g_num_materials; i++)
                {
                    g_device
            ->SetMaterial(&g_mesh_materials[i]);
                    g_device
            ->SetTexture(0, g_mesh_textures[i]);

                    g_mesh
            ->DrawSubset(i);
                }        
                
                g_device
            ->EndScene();

                g_device
            ->Present(NULL, NULL, NULL, NULL);
            }

            LRESULT WINAPI WinProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
            {
                
            switch(msg)
                {
                
            case WM_KEYDOWN:
                    
            switch(wParam)
                    {
                    
            case 49// press key "1", disable depth test.
                        g_device->SetRenderState(D3DRS_ZENABLE, FALSE);
                        
            break;

                    
            case 50// press key "2", enable depth test.
                        g_device->SetRenderState(D3DRS_ZENABLE, TRUE);
                        
            break;

                    
            case VK_ESCAPE:
                        DestroyWindow(hwnd);
                        
            break;
                    }    

                    
            break;

                
            case WM_DESTROY:
                    PostQuitMessage(
            0);
                    
            return 0;
                }

                
            return DefWindowProc(hwnd, msg, wParam, lParam);
            }

            int WINAPI WinMain(HINSTANCE inst, HINSTANCE, LPSTR, INT)
            {
                WNDCLASSEX wc;

                wc.cbSize            
            = sizeof(WNDCLASSEX);
                wc.style            
            = CS_CLASSDC;
                wc.lpfnWndProc        
            = WinProc;
                wc.cbClsExtra        
            = 0;
                wc.cbWndExtra        
            = 0;
                wc.hInstance        
            = inst;
                wc.hIcon            
            = NULL;
                wc.hCursor            
            = NULL;
                wc.hbrBackground    
            = NULL;
                wc.lpszMenuName        
            = NULL;
                wc.lpszClassName    
            = CLASS_NAME;
                wc.hIconSm            
            = NULL;

                
            if(! RegisterClassEx(&wc))
                    
            return -1;

                HWND hwnd 
            = CreateWindow(CLASS_NAME, "Direct3D App", WS_OVERLAPPEDWINDOW, 200100640480,
                                         NULL, NULL, wc.hInstance, NULL);    

                
            if(hwnd == NULL)
                    
            return -1;

                
            if(init_d3d(hwnd))
                {
                    ShowWindow(hwnd, SW_SHOWDEFAULT);
                    UpdateWindow(hwnd);

                    MSG msg;
                    ZeroMemory(
            &msg, sizeof(msg));

                    
            while(msg.message != WM_QUIT)
                    {
                        
            if(PeekMessage(&msg, NULL, 00, PM_REMOVE))
                        {
                            TranslateMessage(
            &msg);
                            DispatchMessage(
            &msg);
                        }
                            
                        render();
                    }
                }

                cleanup();
                UnregisterClass(CLASS_NAME, wc.hInstance);    

                
            return 0;
            }

             

            下載示例工程


            posted on 2008-05-09 17:45 lovedday 閱讀(3737) 評論(6)  編輯 收藏 引用

            評論

            # re: 深度測試與alpha混合(1) 2008-07-21 16:09 宋明建

            真的寫的不錯,看了你寫的東西后,我總算看懂了個一二三。不像有的書,看了半天,不知所云。
            頂!  回復  更多評論   

            # re: 深度測試與alpha混合(1) 2008-11-25 15:27 flysnow

            寫的太好了,狂頂下,感謝樓主  回復  更多評論   

            # re: 深度測試與alpha混合(1)[未登錄] 2008-11-25 22:52 Flash


            無論從哪個角度看,

            你對生活,對技術都是理解很深的人!

              回復  更多評論   

            # re: 深度測試與alpha混合(1) 2009-06-05 08:53 ROCK

            3q  回復  更多評論   

            # re: 深度測試與alpha混合(1) 2010-11-11 23:36 bob

            嗯 寫的不錯 多謝了  回復  更多評論   

            # re: 深度測試與alpha混合(1)[未登錄] 2012-01-17 00:31 star

            THX,讓知識鞏固了不少  回復  更多評論   

            公告

            導航

            統(tǒng)計

            常用鏈接

            隨筆分類(178)

            3D游戲編程相關鏈接

            搜索

            最新評論

            国产女人aaa级久久久级| 精品无码人妻久久久久久| 久久无码AV中文出轨人妻| 久久婷婷是五月综合色狠狠| 久久久久久久久久久精品尤物| 2021国内久久精品| 国产一区二区精品久久| 合区精品久久久中文字幕一区| 人妻无码久久一区二区三区免费 | 日本久久中文字幕| 久久ww精品w免费人成| 日韩电影久久久被窝网| 久久久久久午夜成人影院| 久久天天躁狠狠躁夜夜2020老熟妇 | 久久久久国产一级毛片高清版| 久久久久亚洲av成人无码电影 | 中文精品久久久久人妻| 99久久人人爽亚洲精品美女 | 成人国内精品久久久久影院| 久久久久国产视频电影| 成人国内精品久久久久影院| 久久精品国产亚洲av麻豆图片| 国产午夜福利精品久久| 成人综合伊人五月婷久久| 久久久亚洲裙底偷窥综合 | 狠狠综合久久AV一区二区三区| 久久er国产精品免费观看8| 久久99精品久久久久久| 久久九九精品99国产精品| 国内精品久久久久影院老司| 久久精品亚洲福利| 精品国产91久久久久久久a | 国产精品免费看久久久| 久久久精品人妻一区二区三区蜜桃 | 综合久久一区二区三区 | 国产毛片久久久久久国产毛片| 国产情侣久久久久aⅴ免费| 无码人妻久久一区二区三区免费 | 潮喷大喷水系列无码久久精品| 久久99国产综合精品免费| 99久久免费国产特黄|