多級(jí)漸進(jìn)紋理過(guò)濾
多級(jí)漸進(jìn)紋理由一組分辨率逐漸降低的紋理序列組成,每一級(jí)紋理寬度和高度都是上一級(jí)紋理寬度和高度的一半。寬和高不一定相等,也就是說(shuō),這些紋理不一定都是正方形。
Direct3D在紋理映射時(shí),自動(dòng)選擇一幅與物體大小最接近的紋理進(jìn)行渲染。當(dāng)物體離投影平面較遠(yuǎn)時(shí),Direct3D會(huì)選擇一張尺寸較小、分辨率較低的紋理進(jìn)行渲染;當(dāng)物體離投影平面較近時(shí),Direct3D會(huì)選擇一張尺寸較大、分辨率較高的紋理進(jìn)行渲染。Direct3D將紋理序列看成一條多級(jí)漸進(jìn)紋理鏈。鏈頭處紋理的分辨率最高,下一級(jí)往后依次遞減,鏈尾處紋理的分辨率最低。
Direct3D能估計(jì)出多級(jí)漸進(jìn)紋理鏈中哪幅紋理的分辨率最接近想要的輸出結(jié)果,然后它將像素映射到紋理空間。當(dāng)最終顯示的圖形大小介于任意兩級(jí)紋理圖形之間時(shí),Direct3D將兩級(jí)紋理的相應(yīng)元素進(jìn)行混合后顯示。
多級(jí)漸進(jìn)紋理過(guò)濾能夠有效地提高圖形渲染速度,當(dāng)物體離投影平面較遠(yuǎn)時(shí),Direct3D會(huì)選擇一張尺寸較小的紋理進(jìn)行渲染,而無(wú)需經(jīng)過(guò)復(fù)雜的諸如各項(xiàng)異性紋理過(guò)濾,并且由于這時(shí)紋理需要的顯存比不使用多級(jí)漸進(jìn)紋理時(shí)小,因此能有效地減少紋理載入顯存的時(shí)間。
生成多級(jí)漸進(jìn)紋理
可以通過(guò)調(diào)用Direct3D擴(kuò)展實(shí)用庫(kù)函數(shù)D3DXCreateTextureFromFileEx()自動(dòng)生成多級(jí)漸進(jìn)紋理序列,該函數(shù)的聲明如下:
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:
- 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.
- 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.
- 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.
參數(shù)Format是D3DFORMAT枚舉類(lèi)型,指定紋理圖形的格式,還可以將它設(shè)置為D3DFMT_DXT1
~ D3DFMT_DXT5的值之一,表示生成DXT壓縮紋理以節(jié)省空間。
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.
設(shè)置多級(jí)漸進(jìn)紋理過(guò)濾方式
當(dāng)最終顯示的紋理貼圖大小介于任意兩級(jí)紋理之間時(shí),Direct3D能夠取得兩級(jí)紋理元素進(jìn)行混合后顯示,具體的混合方式由指定的多級(jí)漸進(jìn)紋理過(guò)濾方式?jīng)Q定。可以調(diào)用函數(shù)IDirect3DDevice9::SetSamplerState()設(shè)置多級(jí)漸進(jìn)紋理過(guò)濾方式,將第一個(gè)參數(shù)設(shè)為紋理層序號(hào),第二個(gè)參數(shù)設(shè)為D3DSAMP_MIPFILTER表示多級(jí)漸進(jìn)紋理過(guò)濾,第三個(gè)參數(shù)設(shè)為在相鄰紋理級(jí)之間的過(guò)濾方式,可取枚舉類(lèi)型D3DTEXTUREFILTERTYPE的任意值。下面的示例代碼設(shè)置相鄰紋理級(jí)之間的過(guò)濾方式為線性過(guò)濾。
g_device->SetSamplerState(0,
D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
如果將第三個(gè)參數(shù)設(shè)為D3DTEXF_NONE,那么就會(huì)一直使用最高一級(jí)的紋理,即禁用多級(jí)漸進(jìn)紋理過(guò)濾。如果將其設(shè)為D3DTEXF_POINT,就會(huì)只使用與圖元大小最匹配的一級(jí)紋理。如果將其設(shè)為D3DTEXF_LINEAR,Direct3D就將與圖元大小最匹配的兩級(jí)紋理以線性方式混合。
需要注意的是,多級(jí)紋理過(guò)濾是縮小和放大過(guò)濾器的結(jié)合。例如,如果將縮小和方法過(guò)濾器設(shè)為線性過(guò)濾,但是多級(jí)紋理過(guò)濾方式設(shè)為最近點(diǎn)采樣,Direct3D就會(huì)選擇與要顯示的紋理貼圖大小最接近的紋理級(jí)別,在該級(jí)紋理上完成雙線性紋理過(guò)濾,并將結(jié)果作為像素的值。如果將縮小、放大過(guò)濾器和多級(jí)漸進(jìn)紋理都設(shè)置為線性過(guò)濾,則Direct3D就會(huì)在兩個(gè)最接近的紋理級(jí)別上都進(jìn)行雙線性紋理過(guò)濾,然后再對(duì)相鄰兩級(jí)紋理圖形上對(duì)應(yīng)的兩個(gè)紋理顏色進(jìn)行加權(quán)平均,最后的結(jié)果作為單個(gè)像素值。這種為了圖元中的一個(gè)像素,而結(jié)合了兩幅紋理,共8個(gè)像素的技術(shù),稱(chēng)為“三線性過(guò)濾”,因?yàn)樗诩y理的三個(gè)方向----u、
v和紋理級(jí)別上都進(jìn)行了線性過(guò)濾。
可以通過(guò)IDirect3DDevice9::SetSamplerState()函數(shù)設(shè)置實(shí)際渲染時(shí)紋理過(guò)濾的最大級(jí)數(shù),其中需要將第二個(gè)參數(shù)設(shè)為D3DSAMP_MAXMIPLEVEL,第三個(gè)參數(shù)設(shè)為實(shí)際渲染時(shí)紋理過(guò)濾的最大級(jí)數(shù)。下面的示例代碼設(shè)置紋理層0的最大多級(jí)紋理過(guò)濾級(jí)數(shù)為16。
g_device->SetSamplerState(0,
D3DSAMP_MAXMIPLEVEL, 16);
還可以通過(guò)將IDirect3DDevice9::SetSamplerState()的第二個(gè)參數(shù)設(shè)為D3DSAMP_MIPMAPLODBIAS,設(shè)置多級(jí)紋理映射級(jí)數(shù)偏移值。如果對(duì)某個(gè)紋理映射設(shè)置正偏移值,得到的圖形結(jié)果就會(huì)比原來(lái)的更清晰,但鋸齒更多;反之設(shè)為負(fù)偏移值,得到的圖形結(jié)果就會(huì)更模糊。
多級(jí)漸進(jìn)紋理過(guò)濾示例程序
該程序創(chuàng)建了一幅多級(jí)漸進(jìn)紋理和一幅單級(jí)別紋理,按下數(shù)字鍵“1”則使用多級(jí)漸進(jìn)紋理,按下數(shù)字鍵“2”則使用單級(jí)別紋理。按下“↓”和“↑”則縮小和放大顯示的圖形,仔細(xì)觀察圖像的變化,可以看到多級(jí)漸進(jìn)紋理的效果。

使用MipMap紋理過(guò)濾

使用單級(jí)紋理過(guò)濾(即禁用多級(jí)紋理過(guò)濾)
源程序:
#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.0f, 0.0f, g_distance);
D3DXVECTOR3 at(0.0f, 0.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/4, 1.0f, 1.0f, 100.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", 0, 0, 0, 0, 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", 0, 0, 1, 0, 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.0f, 1.0f},
{ -3, 3, 0.0f, 0.0f, 0.0f},
{ 3, -3, 0.0f, 1.0f, 1.0f},
{ 3, 3, 0.0f, 1.0f, 0.0f }
};
g_device->CreateVertexBuffer(sizeof(vertices), 0, D3DFVF_CUSTOM_VERTEX, D3DPOOL_MANAGED, &g_vertex_buffer, NULL);
void* ptr;
g_vertex_buffer->Lock(0, 0, (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(5, 5, 5), 1.0f, 0);
g_device->BeginScene();
g_device->SetTexture(0, g_use_mip_texture ? g_mip_texture : g_texture);
g_device->SetStreamSource(0, g_vertex_buffer, 0, sizeof(sCustomVertex));
g_device->SetFVF(D3DFVF_CUSTOM_VERTEX);
g_device->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);
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, 200, 100, 800, 600,
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, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
render();
Sleep(10);
}
}
cleanup();
UnregisterClass(CLASS_NAME, wc.hInstance);
return 0;
}