根据 DirectX 8.1 SDK samples/Multimedia/Direct3D/Tutorials/Tut05_Textures翻译
保留原文注释
请自行准备材质图片,文件名为banana.bmp,大小不限,建议为256*256
//-----------------------------------------------------------------------------
// File: Textures.cpp
//
// Desc: Better than just lights and materials, 3D objects look much more
// convincing when texture-mapped. Textures can be thought of as a sort
// of wallpaper, that is shrinkwrapped to fit a texture. Textures are
// typically loaded from image files, and D3DX provides a utility to
// function to do this for us. Like a vertex buffer, textures have
// Lock() and Unlock() functions to access (read or write) the image
// data. Textures have a width, height, miplevel, and pixel format. The
// miplevel is for "mipmapped" textures, an advanced performance-
// enhancing feature which uses lower resolutions of the texture for
// objects in the distance where detail is less noticeable. The pixel
// format determines how the colors are stored in a texel. The most
// common formats are the 16-bit R5G6B5 format (5 bits of red, 6-bits of
// green and 5 bits of blue) and the 32-bit A8R8G8B8 format (8 bits each
// of alpha, red, green, and blue).
//
// Textures are associated with geometry through texture coordinates.
// Each vertex has one or more sets of texture coordinates, which are
// named tu and tv and range from 0.0 to 1.0. Texture coordinates can be
// supplied by the geometry, or can be automatically generated using
// Direct3D texture coordinate generation (which is an advanced feature).
//-----------------------------------------------------------------------------
program Tut05_Textures;
uses
Windows,
Messages,
Direct3D8 in 'JEDI/Direct3D8.pas',
DXTypes in 'JEDI/DXTypes.pas',
DXFile in 'JEDI/DXFile.pas',
D3DX8 in 'JEDI/D3DX8.pas';
//-----------------------------------------------------------------------------
// Global variables
//-----------------------------------------------------------------------------
var
g_pD3D :IDirect3D8 = nil; // Used to create the D3DDevice
g_pd3dDevice:IDirect3DDevice8 = nil; // Our rendering device
g_pVB :IDirect3DVertexBuffer8 = nil; // Buffer to hold vertices
g_pTexture :IDirect3DTexture8 = nil; // Our texture
// A structure for our custom vertex type. We added texture coordinates
type
CUSTOMVERTEX=record
position:TD3DXVector3; // The position
color :TD3DColor; // The color
tu, tv :Single; // The texture coordinates
end;
// Our custom FVF, which describes our custom vertex structure
const D3DFVF_CUSTOMVERTEX = (D3DFVF_XYZ or D3DFVF_DIFFUSE or D3DFVF_TEX1);
//-----------------------------------------------------------------------------
// Name: InitD3D()
// Desc: Initializes Direct3D
//-----------------------------------------------------------------------------
function InitD3D(hWnd: THandle) :HRESULT;
var
d3ddm :TD3DDisplayMode;
d3dpp :TD3DPresentParameters;
begin
// Create the D3D object.
g_pD3D:=Direct3DCreate8(D3D_SDK_VERSION);
if g_pD3D=nil then begin
Result:=E_FAIL;
exit;
end;
// Get the current desktop display mode, so we can set up a back
// buffer of the same format
if FAILED(g_pD3D.GetAdapterDisplayMode( D3DADAPTER_DEFAULT, d3ddm )) then begin
Result:=E_FAIL;
exit;
end;
// Set up the structure used to create the D3DDevice. Since we are now
// using more complex geometry, we will create a device with a zbuffer.
Fillchar(d3dpp, sizeof(d3dpp), 0);
d3dpp.Windowed := TRUE;
d3dpp.SwapEffect := D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat := d3ddm.Format;
d3dpp.EnableAutoDepthStencil := TRUE;
d3dpp.AutoDepthStencilFormat := D3DFMT_D16;
// Create the Direct3D device.
if FAILED(g_pD3D.CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
d3dpp, g_pd3dDevice )) then begin
Result:=E_FAIL;
exit;
end;
// Turn off culling
g_pd3dDevice.SetRenderState( D3DRS_CULLMODE, D3DCULL_NONE );
// Turn off D3D lighting
g_pd3dDevice.SetRenderState( D3DRS_LIGHTING, Ord(FALSE) );
// Turn on the zbuffer
g_pd3dDevice.SetRenderState( D3DRS_ZENABLE, Ord(TRUE) );
Result:=S_OK;
end;
//-----------------------------------------------------------------------------
// Name: InitGeometry()
// Desc: Creates the scene geometry
//-----------------------------------------------------------------------------
function InitGeometry :HRESULT;
var
pVertices,P:^CUSTOMVERTEX;
i:DWORD;
theta:Single;
begin
// Use D3DX to create a texture from a file based image
if FAILED(D3DXCreateTextureFromFile( g_pd3dDevice, 'banana.bmp',
g_pTexture )) then begin
Result:=E_FAIL;
exit;
end;
// Create the vertex buffer.
if FAILED(g_pd3dDevice.CreateVertexBuffer(50*2*sizeof(CUSTOMVERTEX),
0, D3DFVF_CUSTOMVERTEX,
D3DPOOL_DEFAULT, g_pVB)) then begin
Result:=E_FAIL;
exit;
end;
// Fill the vertex buffer. We are setting the tu and tv texture
// coordinates, which range from 0.0 to 1.0
pVertices:=nil;
if FAILED(g_pVB.Lock(0, 0, PByte(pVertices), 0)) then begin
Result:=E_FAIL;
exit;
end;
for i:=0 to 49 do begin
theta:=(2*D3DX_PI*i)/(50-1);
P:=pVertices;
Inc(P,2*i+0);
P.position := D3DXVECTOR3( sin(theta),-1.0, cos(theta) );
P.color := $FFFFFF;
P.tu := i/(50-1);
P.tv := 1.0;
P:=pVertices;
Inc(P,2*i+1);
P.position := D3DXVECTOR3( sin(theta),1.0, cos(theta) );
P.color := $808080;
P.tu := i/(50-1);
P.tv := 0;
end;
g_pVB.Unlock;
pVertices:=nil;
Result:=S_OK;
end;
//-----------------------------------------------------------------------------
// Name: Cleanup()
// Desc: Releases all previously initialized objects
//-----------------------------------------------------------------------------
procedure Cleanup;
begin
g_pTexture :=nil;
g_pVB :=nil;
g_pd3dDevice:=nil;
g_pD3D :=nil;
end;
//-----------------------------------------------------------------------------
// Name: SetupMatrices()
// Desc: Sets up the world, view, and projection transform matrices.
//-----------------------------------------------------------------------------
procedure SetupMatrices;
var
matWorld, matView, matProj :TD3DXMatrix;
begin
// For our world matrix, we will just leave it as the identity
D3DXMatrixIdentity( matWorld );
D3DXMatrixRotationX( matWorld, GetTickCount/1000.0 ); //原文使用mmsystem的timeGetTime()/1000.0f
g_pd3dDevice.SetTransform( D3DTS_WORLD, matWorld );
// Set up our view matrix. A view matrix can be defined given an eye point,
// a point to lookat, and a direction for which way is up. Here, we set the
// eye five units back along the z-axis and up three units, look at the
// origin, and define "up" to be in the y-direction.
D3DXMatrixLookAtLH( matView, D3DXVECTOR3( 0.0, 3.0,-5.0 ),
D3DXVECTOR3( 0.0, 0.0, 0.0 ),
D3DXVECTOR3( 0.0, 1.0, 0.0 ) );
g_pd3dDevice.SetTransform( D3DTS_VIEW, matView );
// For the projection matrix, we set up a perspective transform (which
// transforms geometry from 3D view space to 2D viewport space, with
// a perspective divide making objects smaller in the distance). To build
// a perpsective transform, we need the field of view (1/4 pi is common),
// the aspect ratio, and the near and far clipping planes (which define at
// what distances geometry should be no longer be rendered).
D3DXMatrixPerspectiveFovLH( matProj, D3DX_PI/4, 1.0, 1.0, 100.0 );
g_pd3dDevice.SetTransform( D3DTS_PROJECTION, matProj );
end;
//-----------------------------------------------------------------------------
// Name: Render()
// Desc: Draws the scene
//-----------------------------------------------------------------------------
procedure Render;
begin
// Clear the backbuffer to a blue color
g_pd3dDevice.Clear( 0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER,
D3DCOLOR_XRGB(0,0,255), 1.0, 0 );
// Begin the scene
g_pd3dDevice.BeginScene;
// Setup the world, view, and projection matrices
SetupMatrices;
// Setup our texture. Using textures introduces the texture stage states,
// which govern how textures get blended together (in the case of multiple
// textures) and lighting information. In this case, we are modulating
// (blending) our texture with the diffuse color of the vertices.
g_pd3dDevice.SetTexture( 0, g_pTexture );
g_pd3dDevice.SetTextureStageState( 0, D3DTSS_COLOROP, D3DTOP_MODULATE );
g_pd3dDevice.SetTextureStageState( 0, D3DTSS_COLORARG1, D3DTA_TEXTURE );
g_pd3dDevice.SetTextureStageState( 0, D3DTSS_COLORARG2, D3DTA_DIFFUSE );
g_pd3dDevice.SetTextureStageState( 0, D3DTSS_ALPHAOP, D3DTOP_DISABLE );
// Render the vertex buffer contents
g_pd3dDevice.SetStreamSource( 0, g_pVB, sizeof(CUSTOMVERTEX) );
g_pd3dDevice.SetVertexShader( D3DFVF_CUSTOMVERTEX );
g_pd3dDevice.DrawPrimitive( D3DPT_TRIANGLESTRIP, 0, 2*50-2 );
// End the scene
g_pd3dDevice.EndScene;
// Present the backbuffer contents to the display
g_pd3dDevice.Present(nil, nil, 0, nil);
end;
//-----------------------------------------------------------------------------
// Name: MsgProc()
// Desc: The window's message handler
//-----------------------------------------------------------------------------
function MsgProc( h_Wnd : THandle; aMSG : Cardinal; wParam : Cardinal; lParam : Integer ) : LRESULT; stdcall;
begin
case aMSG of
WM_DESTROY:
PostQuitMessage( 0 );
end;
Result :=DefWindowProc(h_Wnd, aMSG, wParam, lParam);
end;
//-----------------------------------------------------------------------------
// Name: WinMain()
// Desc: The application's entry point
//-----------------------------------------------------------------------------
function WinMain( hInst :LongWord ) :Integer;
var
wc :TWndClassEx;
hWnd :THandle;
aMsg :TMsg;
begin
// Register the window class
FillChar(wc,sizeof(wc),0);
wc.cbSize:=sizeof(wc);
wc.style:=CS_CLASSDC;
wc.lpfnWndProc:=@MsgProc;
wc.cbClsExtra:=0;
wc.cbWndExtra:=0;
wc.hInstance:=hInst;
wc.hIcon:=0;
wc.hCursor:=0;
wc.hbrBackground:=0;
wc.lpszMenuName:=nil;
wc.lpszClassName:='D3D Tutorial';
wc.hIconSm:=0;
RegisterClassEx(wc);
// Create the application's window
hWnd := CreateWindow('D3D Tutorial', 'D3D Tutorial 05: Textures',
WS_OVERLAPPEDWINDOW, 100, 100, 300, 300,
GetDesktopWindow(), 0, wc.hInstance, nil);
// Initialize Direct3D
if SUCCEEDED(InitD3D(hWnd)) then
// Create the scene geometry
if SUCCEEDED(InitGeometry) then begin
// Show the window
ShowWindow( hWnd, SW_SHOWDEFAULT );
UpdateWindow( hWnd );
// Enter the message loop
Fillchar(aMSG, sizeof(aMSG), 0);
while not (aMsg.message = WM_QUIT) do
if PeekMessage( aMsg, 0, 0, 0, PM_REMOVE ) then begin
TranslateMessage ( aMsg ) ;
DispatchMessage ( aMsg ) ;
end else
Render;
end;
// Clean up everything and exit the app
Cleanup;
UnregisterClass( 'D3D Tutorial', wc.hInstance );
Result:=0;
end;
begin
WinMain(hInstance);
Halt(0);
end.