天行健 君子当自强而不息

纹理映射基础(5)

多级渐进纹理过滤

多级渐进纹理由一组分辨率逐渐降低的纹理序列组成,每一级纹理宽度和高度都是上一级纹理宽度和高度的一半。宽和高不一定相等,也就是说,这些纹理不一定都是正方形。

Direct3D在纹理映射时,自动选择一幅与物体大小最接近的纹理进行渲染。当物体离投影平面较远时,Direct3D会选择一张尺寸较小、分辨率较低的纹理进行渲染;当物体离投影平面较近时,Direct3D会选择一张尺寸较大、分辨率较高的纹理进行渲染。Direct3D将纹理序列看成一条多级渐进纹理链。链头处纹理的分辨率最高,下一级往后依次递减,链尾处纹理的分辨率最低。

Direct3D能估计出多级渐进纹理链中哪幅纹理的分辨率最接近想要的输出结果,然后它将像素映射到纹理空间。当最终显示的图形大小介于任意两级纹理图形之间时,Direct3D将两级纹理的相应元素进行混合后显示。

多级渐进纹理过滤能够有效地提高图形渲染速度,当物体离投影平面较远时,Direct3D会选择一张尺寸较小的纹理进行渲染,而无需经过复杂的诸如各项异性纹理过滤,并且由于这时纹理需要的显存比不使用多级渐进纹理时小,因此能有效地减少纹理载入显存的时间。

 

生成多级渐进纹理

可以通过调用Direct3D扩展实用库函数D3DXCreateTextureFromFileEx()自动生成多级渐进纹理序列,该函数的声明如下:

Creates a texture from a file. This is a more advanced function than D3DXCreateTextureFromFile.

HRESULT D3DXCreateTextureFromFileEx(
LPDIRECT3DDEVICE9 pDevice,
LPCTSTR pSrcFile,
UINT Width,
UINT Height,
UINT MipLevels,
DWORD Usage,
D3DFORMAT Format,
D3DPOOL Pool,
DWORD Filter,
DWORD MipFilter,
D3DCOLOR ColorKey,
D3DXIMAGE_INFO * pSrcInfo,
PALETTEENTRY * pPalette,
LPDIRECT3DTEXTURE9 * ppTexture
);

Parameters

pDevice
[in] Pointer to an IDirect3DDevice9 interface, representing the device to be associated with the texture.
pSrcFile
[in] Pointer to a string that specifies the filename. If the compiler settings require Unicode, the data type LPCTSTR resolves to LPCWSTR. Otherwise, the string data type resolves to LPCSTR. See Remarks.
Width
[in] Width in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is specified, the size will not be rounded.
Height
[in] Height, in pixels. If this value is zero or D3DX_DEFAULT, the dimensions are taken from the file and rounded up to a power of two. If the device supports non-power of 2 textures and D3DX_DEFAULT_NONPOW2 is sepcified, the size will not be rounded.
MipLevels
[in] Number of mip levels requested. If this value is zero or D3DX_DEFAULT, a complete mipmap chain is created. If D3DX_FROM_FILE, the size will be taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Usage
[in] 0, D3DUSAGE_RENDERTARGET, or D3DUSAGE_DYNAMIC. Setting this flag to D3DUSAGE_RENDERTARGET indicates that the surface is to be used as a render target. The resource can then be passed to the pNewRenderTarget parameter of the IDirect3DDevice9::SetRenderTarget method. If either D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC is specified, Pool must be set to D3DPOOL_DEFAULT, and the application should check that the device supports this operation by calling IDirect3D9::CheckDeviceFormat. D3DUSAGE_DYNAMIC indicates that the surface should be handled dynamically. See Using Dynamic Textures.
Format
[in] Member of the D3DFORMAT enumerated type, describing the requested pixel format for the texture. The returned texture might have a different format from that specified by Format. Applications should check the format of the returned texture. If D3DFMT_UNKNOWN, the format is taken from the file. If D3DFMT_FROM_FILE, the format is taken exactly as it is in the file, and the call will fail if this violates device capabilities.
Pool
[in] Member of the D3DPOOL enumerated type, describing the memory class into which the texture should be placed.
Filter
[in] A combination of one or more D3DX_FILTER constants controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_TRIANGLE | D3DX_FILTER_DITHER.
MipFilter
[in] A combination of one or more D3DX_FILTER constants controlling how the image is filtered. Specifying D3DX_DEFAULT for this parameter is the equivalent of specifying D3DX_FILTER_BOX. In addition, use bits 27-31 to specify the number of mip levels to be skipped (from the top of the mipmap chain) when a .dds texture is loaded into memory; this allows you to skip up to 32 levels.
ColorKey
[in] D3DCOLOR value to replace with transparent black, or 0 to disable the color key. This is always a 32-bit ARGB color, independent of the source image format. Alpha is significant and should usually be set to FF for opaque color keys. Thus, for opaque black, the value would be equal to 0xFF000000.
pSrcInfo
[in, out] Pointer to a D3DXIMAGE_INFO structure to be filled in with a description of the data in the source image file, or NULL.
pPalette
[out] Pointer to a PALETTEENTRY structure, representing a 256-color palette to fill in, or NULL.
ppTexture
[out] Address of a pointer to an IDirect3DTexture9 interface, representing the created texture object.

Return Values

If the function succeeds, the return value is D3D_OK. If the function fails, the return value can be one of the following: D3DERR_INVALIDCALL.

D3DERR_NOTAVAILABLED3DERR_OUTOFVIDEOMEMORYD3DXERR_INVALIDDATAE_OUTOFMEMORY

Remarks

The compiler setting also determines the function version. If Unicode is defined, the function call resolves to D3DXCreateTextureFromFileExW. Otherwise, the function call resolves to D3DXCreateTextureFromFileExA because ANSI strings are being used.

Use D3DXCheckTextureRequirements to determine if your device can support the texture given the current state.

This function supports the following file formats: .bmp, .dds, .dib, .hdr, .jpg, .pfm, .png, .ppm, and .tga. See D3DXIMAGE_FILEFORMAT.

Mipmapped textures automatically have each level filled with the loaded texture. When loading images into mipmapped textures, some devices are unable to go to a 1x1 image and this function will fail. If this happens, then the images need to be loaded manually.

For the best performance when using D3DXCreateTextureFromFileEx:

  1. Doing image scaling and format conversion at load time can be slow. Store images in the format and resolution they will be used. If the target hardware requires power of 2 dimensions, then create and store images using power of 2 dimensions.
  2. For mipmap image creation at load time, filter using D3DX_FILTER_BOX. A box filter is much faster than other filter types such as D3DX_FILTER_TRIANGLE.
  3. Consider using DDS files. Since DDS files can be used to represent any Direct3D 9 texture format, they are very easy for D3DX to read. Also, they can store mipmaps, so any mipmap-generation algorithms can be used to author the images.

When skipping mipmap levels while loading a .dds file, use the D3DX_SKIP_DDS_MIP_LEVELS macro to generate the MipFilter value. This macro takes the number of levels to skip and the filter type and returns the filter value, which would then be passed into the MipFilter parameter.

参数Format是D3DFORMAT枚举类型,指定纹理图形的格式,还可以将它设置为D3DFMT_DXT1 ~ D3DFMT_DXT5的值之一,表示生成DXT压缩纹理以节省空间。


Texture Constants

#define Description
D3DFMT_FROM_FILE Take the format exactly from a file.
D3DX_DEFAULT A default value.
D3DX_DEFAULT_NONPOW2 Do not round up numbers such as width or height to a power of two.
D3DX_FROM_FILE Take the texture dimensions exactly from a file.

These #defines are declared in d3dx9.h.


D3DXIMAGE_INFO

Returns a description of the original contents of an image file.

typedef struct D3DXIMAGE_INFO {
UINT Width;
UINT Height;
UINT Depth;
UINT MipLevels;
D3DFORMAT Format;
D3DRESOURCETYPE ResourceType;
D3DXIMAGE_FILEFORMAT ImageFileFormat;
} D3DXIMAGE_INFO, *LPD3DXIMAGE_INFO;

Members

Width
Width of original image in pixels.
Height
Height of original image in pixels.
Depth
Depth of original image in pixels.
MipLevels
Number of mip levels in original image.
Format
A value from the D3DFORMAT enumerated type that most closely describes the data in the original image.
ResourceType
Represents the type of the texture stored in the file. It is either D3DRTYPE_TEXTURE, D3DRTYPE_VOLUMETEXTURE, or D3DRTYPE_CubeTexture.
ImageFileFormat
Represents the format of the image file.

PALETTEENTRY

Specifies the color and usage of an entry in a logical palette.

typedef struct PALETTEENTRY {
BYTE peRed;
BYTE peGreen;
BYTE peBlue;
BYTE peFlags;
} PALETTEENTRY, *LPPALETTEENTRY;

Members

peRed
The red intensity value for the palette entry.
peGreen
The green intensity value for the palette entry.
peBlue
The blue intensity value for the palette entry.
peFlags
The alpha intensity value for the palette entry. Note that as of DirectX 8, this member is treated differently than documented in the Platform SDK.

 

设置多级渐进纹理过滤方式

当最终显示的纹理贴图大小介于任意两级纹理之间时,Direct3D能够取得两级纹理元素进行混合后显示,具体的混合方式由指定的多级渐进纹理过滤方式决定。可以调用函数IDirect3DDevice9::SetSamplerState()设置多级渐进纹理过滤方式,将第一个参数设为纹理层序号,第二个参数设为D3DSAMP_MIPFILTER表示多级渐进纹理过滤,第三个参数设为在相邻纹理级之间的过滤方式,可取枚举类型D3DTEXTUREFILTERTYPE的任意值。下面的示例代码设置相邻纹理级之间的过滤方式为线性过滤。

g_device->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);

如果将第三个参数设为D3DTEXF_NONE,那么就会一直使用最高一级的纹理,即禁用多级渐进纹理过滤。如果将其设为D3DTEXF_POINT,就会只使用与图元大小最匹配的一级纹理。如果将其设为D3DTEXF_LINEAR,Direct3D就将与图元大小最匹配的两级纹理以线性方式混合。

需要注意的是,多级纹理过滤是缩小和放大过滤器的结合。例如,如果将缩小和方法过滤器设为线性过滤,但是多级纹理过滤方式设为最近点采样,Direct3D就会选择与要显示的纹理贴图大小最接近的纹理级别,在该级纹理上完成双线性纹理过滤,并将结果作为像素的值。如果将缩小、放大过滤器和多级渐进纹理都设置为线性过滤,则Direct3D就会在两个最接近的纹理级别上都进行双线性纹理过滤,然后再对相邻两级纹理图形上对应的两个纹理颜色进行加权平均,最后的结果作为单个像素值。这种为了图元中的一个像素,而结合了两幅纹理,共8个像素的技术,称为“三线性过滤”,因为它在纹理的三个方向----u、 v和纹理级别上都进行了线性过滤。

可以通过IDirect3DDevice9::SetSamplerState()函数设置实际渲染时纹理过滤的最大级数,其中需要将第二个参数设为D3DSAMP_MAXMIPLEVEL,第三个参数设为实际渲染时纹理过滤的最大级数。下面的示例代码设置纹理层0的最大多级纹理过滤级数为16。

g_device->SetSamplerState(0, D3DSAMP_MAXMIPLEVEL, 16);

还可以通过将IDirect3DDevice9::SetSamplerState()的第二个参数设为D3DSAMP_MIPMAPLODBIAS,设置多级纹理映射级数偏移值。如果对某个纹理映射设置正偏移值,得到的图形结果就会比原来的更清晰,但锯齿更多;反之设为负偏移值,得到的图形结果就会更模糊。

 

多级渐进纹理过滤示例程序

该程序创建了一幅多级渐进纹理和一幅单级别纹理,按下数字键“1”则使用多级渐进纹理,按下数字键“2”则使用单级别纹理。按下“↓”和“↑”则缩小和放大显示的图形,仔细观察图像的变化,可以看到多级渐进纹理的效果。

使用MipMap纹理过滤

 

使用单级纹理过滤(即禁用多级纹理过滤)

 

源程序:

#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;
IDirect3DVertexBuffer9
* g_vertex_buffer;
IDirect3DTexture9
*        g_texture;
IDirect3DTexture9
*        g_mip_texture;
float                    g_distance = -10;    // distance from camera to image
bool                    g_use_mip_texture = true;

struct sCustomVertex
{
    
float x, y, z;
    
float u, v;
};

#define D3DFVF_CUSTOM_VERTEX (D3DFVF_XYZ | D3DFVF_TEX1) 

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

    
// setup view matrix

    D3DXVECTOR3 eye(
0.0f0.0f, g_distance);
    D3DXVECTOR3 at(
0.0f0.0f0.0f);
    D3DXVECTOR3 up(
0.0f1.0f0.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.0f100.0f);
    g_device
->SetTransform(D3DTS_PROJECTION, &mat_proj);
}

bool init_graphics()
{    
    
/*
    HRESULT D3DXCreateTextureFromFileEx(
      LPDIRECT3DDEVICE9 pDevice,
      LPCTSTR pSrcFile,
      UINT Width,
      UINT Height,
      UINT MipLevels,
      DWORD Usage,
      D3DFORMAT Format,
      D3DPOOL Pool,
      DWORD Filter,
      DWORD MipFilter,
      D3DCOLOR ColorKey,
      D3DXIMAGE_INFO * pSrcInfo,
      PALETTEENTRY * pPalette,
      LPDIRECT3DTEXTURE9 * ppTexture
    );
    
*/

    
// create mipmap texture object
    if(FAILED(D3DXCreateTextureFromFileEx(g_device, "texture.jpg"0000, D3DFMT_X8R8G8B8, D3DPOOL_MANAGED,
                                          D3DX_DEFAULT, D3DX_DEFAULT, 
0xFF000000, NULL, NULL, &g_mip_texture)))
    {
        MessageBox(NULL, 
"Create mipmap texture failed!""ERROR", MB_OK);
        
return false;
    }
    
    
// create normal texture object, set MipLevels as 1, disable mipmap.
    if(FAILED(D3DXCreateTextureFromFileEx(g_device, "texture.jpg"0010, D3DFMT_X8R8G8B8, D3DPOOL_MANAGED,
                                          D3DX_DEFAULT, D3DX_DEFAULT, 
0xFF000000, NULL, NULL, &g_texture)))
    {
        MessageBox(NULL, 
"Create texture failed!""ERROR", MB_OK);
        
return false;
    }

    sCustomVertex vertices[] 
=
    {
        { 
-3,   -3,  0.0f,  0.0f1.0f},   
        { 
-3,    3,  0.0f,  0.0f0.0f},    
        {  
3,   -3,  0.0f,  1.0f1.0f},    
        {  
3,    3,  0.0f,  1.0f0.0f }

    };

    g_device
->CreateVertexBuffer(sizeof(vertices), 0, D3DFVF_CUSTOM_VERTEX, D3DPOOL_MANAGED, &g_vertex_buffer, NULL);

    
void* ptr;

    g_vertex_buffer
->Lock(00, (void**)&ptr, 0);
    memcpy(ptr, vertices, 
sizeof(vertices));    
    g_vertex_buffer
->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;

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

    g_device
->SetRenderState(D3DRS_LIGHTING, FALSE);
    g_device
->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
    
    
return true;
}

void cleanup()
{
    release_com(g_texture);
    release_com(g_mip_texture);
    release_com(g_vertex_buffer);
    release_com(g_device);
    release_com(g_d3d);
}

void render()
{
    setup_matrices();

    g_device
->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(555), 1.0f0);

    g_device
->BeginScene();

    g_device
->SetTexture(0, g_use_mip_texture ? g_mip_texture : g_texture);

    g_device
->SetStreamSource(0, g_vertex_buffer, 0sizeof(sCustomVertex));
    g_device
->SetFVF(D3DFVF_CUSTOM_VERTEX);
    g_device
->DrawPrimitive(D3DPT_TRIANGLESTRIP, 02);

    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 VK_ESCAPE:
            DestroyWindow(hwnd);
            
break;

        
case 49:    // press key "1", use mipmap texture filter mode
            g_use_mip_texture = true;
            
break;

        
case 50:    // press key "2", use normal texture filter mode
            g_use_mip_texture = false;
            
break;

        
case VK_DOWN:
            g_distance 
-= 0.1f;
            
break;

        
case VK_UP:
            g_distance 
+= 0.1f;
            
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, 200100800600,
                             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();
            Sleep(
10);
        }
    }

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

    
return 0;
}

 

posted on 2008-05-07 11:53 lovedday 阅读(2301) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


公告

导航

统计

常用链接

随笔分类(178)

3D游戏编程相关链接

搜索

最新评论