其实DirectX9.0里有非常详细的教程和参考,大多数人只需要看看这些帮助就可以自己学习D3D了,我的这篇文章适合那些很懒但想快速入门、不懂英文或编程知识很欠缺的人看。装好DirectX9.0后,打开VC.net,新建一个Win32工程,在StdAfx.h里添加下面的语句:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">#include <d3d9.h> // D3D</font></span><span style="FONT-SIZE: 9pt"><font face="Courier New">标准头文件<br>#include <D3dx9math.h> // D3D数学库头文件<br>#include <stdio.h> // 这个不用我说了吧?<br>#pragma comment( lib, "d3d9" ) // D3D的静态库<br>#pragma comment( lib, "d3dx9" ) // D3D数学库的静态库</font></span></div>
</td>
</tr>
</tbody>
然后把winmain所在文件的代码做如下的修改:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">#include "stdafx.h"<br>#define </font><a href="http://www.yesky.com/key/1435/156435.html" target=_blank><font face="Courier New">MAX</font></a><font face="Courier New">_LOADSTRING 100<br><br>HINSTANCE g_hInst;<br>HWND g_hWnd;<br>IDirect3D9 *g_pD3D;<br>IDirect3DDevice9 *g_pd3dDevice;<br>IDirect3DVertexBuffer9 *g_pVB;<br><br>TCHAR szTitle[</font><a href="http://www.yesky.com/key/1081/161081.html" target=_blank><font face="Courier New">MAX</font></a><font face="Courier New">_LOADSTRING];<br>TCHAR szWindowClass[MAX_LOADSTRING];<br>ATOM MyRegisterClass(HINSTANCE hInstance);<br>BOOL InitInstance(HINSTANCE, int);<br>LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);<br>LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);<br>void OnIdle( void );<br>void OnCreate( HWND hWnd );<br>HRESULT InitD3D( void );<br>HRESULT CreateObject( void );<br>void ReleaseD3D( void );<br>HRESULT SetModalMatrix( void );<br>HRESULT SetProjMatrix( WORD wWidth, WORD wHeight );<br>void BeforePaint( void );<br>int APIENTRY _tWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)<br>{<br></font></span><span style="FONT-SIZE: 9pt"><font face="Courier New"> MSG msg;<br> HACCEL hAccelTable;<br><br> LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);<br> LoadString(hInstance, IDC_D3DTEST, szWindowClass, MAX_LOADSTRING);<br> MyRegisterClass(hInstance);<br><br> if (!InitInstance (hInstance, nCmdShow)) <br> {<br> return FALSE;<br> }<br><br> hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_D3DTEST);<br><br> while ( true )<br> {<br> if ( PeekMessage( &msg, NULL, 0, 0, PM_REMOVE ) )<br> {<br> if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) <br> {<br> TranslateMessage(&msg);<br> DispatchMessage(&msg);<br> }<br> continue;<br> }<br> if ( WM_QUIT == msg.message )<br> {<br> break;<br> }<br> OnIdle();<br> } <br> UnregisterClass( szWindowClass, g_hInst );<br> return (int)msg.wParam;<br>}<br><br>ATOM MyRegisterClass( HINSTANCE hInstance )<br>{<br> WNDCLASSEX wcex;<br> wcex.cbSize = sizeof(WNDCLASSEX); <br> wcex.style = CS_HREDRAW | CS_VREDRAW;<br> wcex.lpfnWndProc = (WNDPROC)WndProc;<br> wcex.cbClsExtra = 0;<br> wcex.cbWndExtra = 0;<br> wcex.hInstance = hInstance;<br> wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_D3DTEST);<br> wcex.hCursor = LoadCursor(NULL, IDC_ARROW);<br> wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);<br> wcex.lpszMenuName = (LPCTSTR)IDC_D3DTEST;<br> wcex.lpszClassName = szWindowClass;<br> wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);<br> return RegisterClassEx(&wcex);<br>}<br><br>BOOL InitInstance( HINSTANCE hInstance, int nCmdShow )<br>{<br> g_hInst = hInstance;<br> CreateWindow( szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL );<br> if ( !g_hWnd )<br> {<br> return FALSE;<br> }<br> ShowWindow( g_hWnd, nCmdShow );<br> UpdateWindow( g_hWnd );<br> return TRUE;<br>}<br><br>LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)<br>{<br> int wmId, wmEvent;<br> </font><a href="http://www.yesky.com/key/656/160656.html" target=_blank><font face="Courier New">switch</font></a><font face="Courier New"> (message) <br> {<br> case WM_CREATE:<br> OnCreate( hWnd );<br> break;<br> case WM_COMMAND:<br> wmId = LOWORD(wParam); <br> wmEvent = HIWORD(wParam); <br> switch (wmId)<br> {<br> case </font><a href="http://www.yesky.com/key/2371/152371.html" target=_blank><font face="Courier New">IDM</font></a><font face="Courier New">_EXIT:<br> DestroyWindow(hWnd);<br> break;<br> default:<br> return DefWindowProc(hWnd, message, wParam, lParam);<br> }<br> break;<br> case WM_SIZE:<br> SetProjMatrix( LOWORD( lParam ), HIWORD( lParam ) );<br> break;<br> case WM_DESTROY:<br> ReleaseD3D();<br> PostQuitMessage(0);<br> break;<br> default:<br> return DefWindowProc(hWnd, message, wParam, lParam);<br> }<br> return 0;<br>}<br><br>void OnCreate( HWND hWnd )<br>{<br> g_hWnd = hWnd;<br> InitD3D();<br> CreateObject();<br>}<br><br>void ReleaseD3D( void )<br>{<br>}<br><br>HRESULT InitD3D( void )<br>{<br> return S_OK;<br>}<br><br>void BeforePaint( void )<br>{<br>}<br><br>HRESULT CreateObject( void )<br>{<br> return S_OK;<br>}<br><br>void OnIdle( void )<br>{<br>}<br><br>HRESULT SetModalMatrix( void )<br>{<br> return S_OK;<br>}<br><br>HRESULT SetProjMatrix( WORD wWidth, WORD wHeight )<br>{<br> return S_OK;<br>}</font></span></div>
</td>
</tr>
</tbody>
上面的代码仅是一个框架,仔细研究过上篇文章的朋友应该非常清楚这些代码的含意,不过我还是需要大至讲解一下。在InitInstance函数中,初始化程序实例的开始,我们将该实例的句柄放到全局变量中去,以便以后使用:
g_hInst = hInstance;
在创建窗体时,我并没有直接将CreateWindow的返回值——创建成功的窗体句柄赋给全局变量g_hWnd,因为CreateWindow函数在执行中会引发几个消息,其中有WM_CREATE,在这个消息的处理函数中OnCreate中,我执行了下面的语句:
g_hWnd = hWnd;
这样,我们就可以早一点用到g_hWnd了。SetProjMatrix是设置投影矩阵的,投影矩形仅受窗口纵横比影响,所以在WM_SIZE事件时调用时就可以了。而SetModalMatrix是设置模型矩阵的,也就是眼睛点和视点之类的东东,所以它一定要在Rander的时候,准确的说是在Render之前执行。InitD3D在窗体创建时调用,用于初始化D3D设备。CreateObject和InitD3D一样是初始化函数,它用于创建三维对象。
下面我们来填写代码,首先是初始化,我们在InitD3D函数里填写下面的代码:
g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );
if( NULL == g_pD3D )
{
return E_FAIL;
}
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof(d3dpp) );
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
g_pD3D->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd,
D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE,
&d3dpp, &g_pd3dDevice );
g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );
g_pd3dDevice->SetRenderState( D3DRS_AMBIENT,
D3DCOLOR_COLORVALUE( 0.3f, 0.3f, 0.3f, 1.0 ) );
g_pd3dDevice->LightEnable( 0, TRUE);
D3DMATERIAL9 mtrl;
ZeroMemory( &mtrl, sizeof(mtrl) );
mtrl.Diffuse.r = mtrl.Ambient.r = 140.0f / 255.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 200.0f / 255.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 255.0f / 255.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
g_pd3dDevice->SetMaterial( &mtrl );
return S_OK;
Direct3DCreate9函数为我们创建了一个D3D接口指针,并将接口指针返回到全局变量中保存起来,参数必须为D3D_SDK_VERSION。D3DPRESENT_PARAMETERS是一个结构体,它就像OpenGL中的PixelFormat一样,是创建时指定设备的一些属性的。
d3dpp.Windowed = TRUE; // 设备是窗口设备而不是全屏
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; // 翻转缓冲区时不改动后台缓冲
d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8; // ARGB颜色模式
在这之后,我们就可以调用CreateDevice来创建设备了,第一个参数指定使用主显示驱动,第二个参数指定该设备是否使用硬件来处理显示,第三个参数当然是你的窗体句柄,第四个参数如果指定D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_PUREDEVICE效率会提高不少。
g_pd3dDevice->SetRenderState( D3DRS_LIGHTING, TRUE );
g_pd3dDevice->SetRenderState( D3DRS_AMBIENT, D3DCOLOR_COLORVALUE( 0.6f, 0.6f, 0.6f, 1.0 ) );
这两句用于打开灯光和设置环境光照颜色。接着我设置了材质:
mtrl.Diffuse.r = mtrl.Ambient.r = 140.0f / 255.0f;
mtrl.Diffuse.g = mtrl.Ambient.g = 200.0f / 255.0f;
mtrl.Diffuse.b = mtrl.Ambient.b = 255.0f / 255.0f;
mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;
为了和上一篇的例程做对比,我使用了相同的材质。当CreateDevice执行成功后,我们就该创建基于D3D的三维物体了。
D3DVECTOR SrcBox[] = {
{ 5.0f, 5.0f, 0.0f }, { 5.0f, 5.0f, 10.0f },
{ 5.0f, -5.0f, 0.0f }, { 5.0f, -5.0f, 10.0f },
{-5.0f, -5.0f, 0.0f }, {-5.0f, -5.0f, 10.0f },
{-5.0f, 5.0f, 0.0f }, {-5.0f, 5.0f, 10.0f },
};
WORD wIndex[] ={
0, 4, 6, 0, 2, 4,
0, 6, 7, 0, 7, 1,
0, 3, 2, 0, 1, 3,
5, 2, 3, 5, 4, 2,
5, 6, 4, 5, 7, 6,
5, 1, 7, 5, 3, 1,
};
要说明的是D3D为我们准备了很好用的结构体D3DVECTOR,封装了三维座标的X、Y和Z。我们还需要再定义一个我们自己的结构体来存放我们的三维座标信息:
struct CUSTOMVERTEX
{
D3DVECTOR pos;
D3DVECTOR normal;
};
第一个成员pos用来存储顶点座标数据,第二个成员normal用来存储这个点所在平面的法向量——这个概念我在上一篇讲过的。和OpenGL一样,我们同样需要按索引序展开顶点数组:
CUSTOMVERTEX ExpandBox[sizeof(wIndex) / sizeof(WORD)];
for ( int i = 0; i < 36; i++ )
{
ExpandBox[i].pos = SrcBox[ wIndex[i] ];
}
然后用下面的代码为顶点计算法向量。
for ( i = 0; i < 12; i++ )
{
D3DVECTOR Tri[3];
Tri[0] = ExpandBox[ i * 3 + 0 ].pos;
Tri[1] = ExpandBox[ i * 3 + 1 ].pos;
Tri[2] = ExpandBox[ i * 3 + 2 ].pos;
ExpandBox[ i * 3 + 0 ].normal.x = 0.0f;
ExpandBox[ i * 3 + 0 ].normal.y = 0.0f;
ExpandBox[ i * 3 + 0 ].normal.z = 1.0f;
CalcNormal( Tri, &(ExpandBox[ i * 3 + 0 ].normal) );
ExpandBox[ i * 3 + 1 ].normal = ExpandBox[ i * 3 + 0 ].normal;
ExpandBox[ i * 3 + 2 ].normal = ExpandBox[ i * 3 + 0 ].normal;
}
在这里我需要花点篇幅讲一个概念,一个仅在D3D中存在的概念FVF。D3D在处理显示数据时和OpenGL的方式不大一样,OpenGL是指定独立的数组,比如VertexBuffer、IndexBuffer、NormalBuffer等,而D3D是把每一个顶点的这些数据放在一起,组成一个单元进行处理,也就是说只有一个数组,而在数组的每一个元素中都包括了单个顶点的所有数据,所以他被称为Flexible Vertex Format,我刚才定义的结构体CUSTOMVERTEX也就是做为数组的一个单元。每一个单元可以包含你所需要的信息,比如你只需要顶点座标数据和颜色,那么你只需要对那个结构体稍加修改就可以了,但是怎么让D3D 知道你的结构体里包含哪些数据呢?当然,我们可以在CreateVertexBuffer的时候指定一个参数来告诉D3D:D3DFVF_XYZ | D3DFVF_NORMAL,在很多地方我们都可能用到这个值,所以为了方便使用和维护我们定义一个宏来表示它:
#define D3DFVF_CUSTOMVERTEX ( D3DFVF_XYZ | D3DFVF_NORMAL )
那么到这里你可以会问另一个问题,也许D3D可以知道我们的元素里包含顶点的哪些数据,但D3D又是怎样得知这些数据在结构体里,也就是在内存中的排列顺序的呢?很不幸,D3D无法得知你的排列顺序,但D3D指定了这些数据的排列顺序,比如法向量一定在顶点后面,而颜色又一定要放在法向量后面。关于这个排列顺序表你得去看看MSDN里关于Vertex Formats的详细说明了。下面我们来创建顶点数组:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">if( FAILED( g_pd3dDevice->CreateVertexBuffer( sizeof(ExpandBox),<br>0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL ) ) )<br>{<br></font></span><span style="FONT-SIZE: 9pt"><font face="Courier New"> return E_FAIL;<br>}</font></span></div>
</td>
</tr>
</tbody>
这些参数上面都提到过,相信你一看就会明白,我就不多说了。怎样把我们的方盒数据存储进这创建好的顶点缓冲区呢?DirectX有自己的内存管理方式,也就是Lock和UnLock的模式:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">VOID* pVertices;<br><br>if( FAILED( g_pVB->Lock( 0, sizeof(ExpandBox), (void**)&pVertices, 0 ) ) )<br><br>return E_FAIL;<br><br>MoveMemory( pVertices, ExpandBox, sizeof(ExpandBox) );<br><br>g_pVB->Unlock();</font></span></div>
</td>
</tr>
</tbody>
和OpenGL一样,在初始化工作结束后,必须要做的另一件事就是设置矩阵,首先是投影矩阵,我们把这些代码加到SetProjMatrix函数中去:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">D3DXMATRIX matProj;<br>D3DXMatrixPerspectiveFovLH( &matProj, D3DX_PI/4, (float)wWidth / (float)wHeight, 1.0f, 100.0f );<br><br>return g_pd3dDevice->SetTransform( D3DTS_PROJECTION, &matProj );</font></span></div>
</td>
</tr>
</tbody>
然后是视图矩阵,把下面的代码加到SetModalMatrix中
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">static float fRadius = 0.5f;<br>fRadius -= 0.003f;<br>if ( fRadius < 0)<br>{<br></font></span><span style="FONT-SIZE: 9pt"><font face="Courier New"> fRadius = D3DX_PI * 2 ;<br>}<br><br>D3DXMATRIX matWorld;<br>D3DXMatrixRotationZ( &matWorld, 0.0f );<br>if ( FAILED( g_pd3dDevice->SetTransform( D3DTS_WORLD, &matWorld ) ) )<br>{<br> return E_FAIL;<br>}<br><br>D3DXMATRIX matView;<br>D3DXMatrixLookAtLH( &matView, &D3DXVECTOR3( cosf( fRadius ) * 40.0f, sinf( fRadius ) * 40.0f, 30.0 ), &D3DXVECTOR3( 0.0f, 0.0f, 0.0f ), &D3DXVECTOR3( 0.0f, 0.0f, 1.0f ) );<br><br>g_pd3dDevice->SetTransform( D3DTS_VIEW, &matView );<br>return S_OK;</font></span></div>
</td>
</tr>
</tbody>
我想我不说你也可以理解这些代码的含义,是不是和OpenGL非常相似呢?好的,现在一切准备工作就续,现在我们可以开始绘制方盒了。找到OnIdel处理函数,然后在这里添加下面的代码:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">if ( g_pd3dDevice != NULL )<br>{<br></font></span><span style="FONT-SIZE: 9pt"><font face="Courier New"> g_pd3dDevice->Clear( 0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255,255,200), 1.0f, 0 );<br> if ( SUCCEEDED( g_pd3dDevice->BeginScene() ) )<br> {<br> BeforePaint();<br> if ( FAILED( SetModalMatrix() ) )<br> {<br> return;<br> }<br> g_pd3dDevice->SetStreamSource( 0, g_pVB, 0, sizeof(CUSTOMVERTEX) );<br> g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );<br> g_pd3dDevice->DrawPrimitive( D3DPT_TRIANGLELIST, 0, 12 );<br> g_pd3dDevice->EndScene();<br> g_pd3dDevice->Present( NULL, NULL, NULL, NULL );<br> }<br>} </font></span></div>
</td>
</tr>
</tbody>
g_pd3dDevice->Clear相当于glClear, g_pd3dDevice->BeginScene和g_pd3dDevice->EndScene 相当于glBegin和glEnd,g_pd3dDevice->SetStreamSource 相当于glSet**Pointer,g_pd3dDevice->DrawPrimitive 相当于glDrawArray,g_pd3dDevice->Present相当于SwapBuffer,这里和OpenGL的不同之处在于D3D在这里要设备FVF,一个很简单的过程:
g_pd3dDevice->SetFVF( D3DFVF_CUSTOMVERTEX );
另外,D3D的背景色是在Clear的时候指定的。现在你可以运行你的程序了,但是你会发现,盒子是黑色的一片,那是因为你没有打开任何光源。而OpenGL在没有打开任何光源时物体是纯白色的,呵呵,具有一定的迷惑性哦~现在我们来打开一个灯,来照亮这个物体。就在BeforePaint里:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt">
<div><span style="FONT-SIZE: 9pt"><font face="Courier New">D3DLIGHT9 light;<br>ZeroMemory( &light, sizeof(light) );<br>light.Position = D3DXVECTOR3( 30.0f, 30.0f, 30.0f );<br>light.Attenuation1 = 0.05f;<br>light.Diffuse.r = 1.0f;<br>light.Diffuse.g = 1.0f;<br>light.Diffuse.b = 1.0f;<br>light.Range = 1000.0f;<br>light.Type = D3DLIGHT_POINT;<br>g_pd3dDevice->SetLight( 0, &light );<br>g_pd3dDevice->LightEnable( 0, TRUE);</font></span></div>
</td>
</tr>
</tbody>
为什么要放在BeforePaint里呢?因为我们在后面还可以实现动态光影的效果,也就是让光源动起来。这里要格外注意的时,这个顶不是方向光源,是一个点光源,D3DLIGHT_POINT,它的光是没有方向,从座标点向四周任何方向发散的,他也具有衰减性,你可以设置三个衰减分量,在D3D里的衰减公式是:Atten = 1 / ( att0 + att1 * d + att2 * d * d )所以,当你的三个衰减值都为0时,就会出错。在这里我们用到了att1,让它等于0.05,很小的值对吗?越小表示衰减越小,光照也就越强。
现在你的代码应该是这样样子:
<tbody>
<tr>
<td style="PADDING-RIGHT: 0.75pt; PADDING-LEFT: 0.75pt; FONT-SIZE: 10pt; PADDING-BOTTOM: 0.75pt; PADDING-TOP: 0.75pt; FONT-FAMILY: Times New Roman">
<p>// D3D006.cpp : 定义应用程序的入口点。<br>//</p>
<p>#include "stdafx.h"<br>#include "D3D006.h"</p>
<p>#define MAX_LOADSTRING 100<br>#define D3DFVF_CUSTOMVERTEX ( D3DFVF_XYZ | D3DFVF_NORMAL )</p>
<p>struct CUSTOMVERTEX<br>{<br> D3DVECTOR pos;<br> D3DVECTOR normal;<br>};</p>
<p>// 全局变量:<br>HWND g_hWnd;<br>IDirect3D9 *g_pD3D;<br>IDirect3DDevice9 *g_pd3dDevice;<br>IDirect3DVertexBuffer9 *g_pVB;</p>
<p>HINSTANCE hInst; // 当前实例<br>TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本<br>TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名</p>
<p>// 此代码模块中包含的函数的前向声明:<br>ATOM MyRegisterClass(HINSTANCE hInstance);<br>BOOL InitInstance(HINSTANCE, int);<br>LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);<br>INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);</p>
<p>void OnIdle( void );<br>void OnCreate( HWND hWnd );<br>HRESULT InitD3D( void );<br>HRESULT CreateObject( void );<br>void ReleaseD3D( void );<br>HRESULT SetModalMatrix( void );<br>HRESULT SetProjMatrix( WORD wWidth, WORD wHeight );<br>void BeforePaint( void );<br>void CalcNormal( const D3DVECTOR *pVertices, D3DVECTOR *pNormal )<br>{<br> D3DVECTOR v1, v2;<br> v1.x = pVertices[0].x - pVertices[1].x;<br> v1.y = pVertices[0].y - pVertices[1].y;<br> v1.z = pVertices[0].z - pVertices[1].z;<br> v2.x = pVertices[1].x - pVertices[2].x;<br> v2.y = pVertices[1].y - pVertices[2].y;<br> v2.z = pVertices[1].z - pVertices[2].z;<br> D3DXVECTOR3 Temp( v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z,v1.x * v2.y - v1.y * v2.x );<br> D3DXVec3Normalize( (D3DXVECTOR3*)pNormal, &Temp );<br>}</p>
<p>class CTimer<br>{<br>public:<br> CTimer() {QueryPerformanceFrequency(&m_Frequency); Start();}<br> void Start() {QueryPerformanceCounter(&m_StartCount);}<br> double End() {LARGE_INTEGER CurrentCount;QueryPerformanceCounter(&CurrentCount);return double(CurrentCount.LowPart - m_StartCount.LowPart) / (double)m_Frequency.LowPart;}</p>
<p>private:<br> LARGE_INTEGER m_Frequency;<br> LARGE_INTEGER m_StartCount;<br>};</p>
<p>int APIENTRY _tWinMain(HINSTANCE hInstance,<br> HINSTANCE hPrevInstance,<br> LPTSTR lpCmdLine,<br> int nCmdShow)<br>{<br> UNREFERENCED_PARAMETER(hPrevInstance);<br> UNREFERENCED_PARAMETER(lpCmdLine);</p>
<p> // TODO: 在此放置代码。<br> MSG msg;<br> HACCEL hAccelTable;</p>
<p> // 初始化全局字符串<br> LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);<br> LoadString(hInstance, IDC_D3D006, szWindowClass, MAX_LOADSTRING);<br> MyRegisterClass(hInstance);</p>
<p> // 执行应用程序初始化:<br> if (!InitInstance (hInstance, nCmdShow))<br> {<br> return FALSE;<br> }</p>
<p> hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_D3D006));</p>
<p> // 主消息循环:<br> while (true)<br> {<br> if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))<br> {<br> if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))<br> {<br> TranslateMessage(&msg);<br> DispatchMessage(&msg);<br> }<br> continue;<br> }<br> if (WM_QUIT == msg.message)<br> {<br> break;<br> }<br> OnIdle();<br> }</p>
<p> UnregisterClass(szWindowClass, hInst);</p>
<p> return (int) msg.wParam;<br>}</p>
<p> </p>
<p>//<br>// 函数: MyRegisterClass()<br>//<br>// 目的: 注册窗口类。<br>//<br>// 注释:<br>//<br>// 仅当希望<br>// 此代码与添加到 Windows 95 中的“RegisterClassEx”<br>// 函数之前的 Win32 系统兼容时,才需要此函数及其用法。调用此函数十分重要,<br>// 这样应用程序就可以获得关联的<br>// “格式正确的”小图标。<br>//<br>ATOM MyRegisterClass(HINSTANCE hInstance)<br>{<br> WNDCLASSEX wcex;</p>
<p> wcex.cbSize = sizeof(WNDCLASSEX);</p>
<p> wcex.style = CS_HREDRAW | CS_VREDRAW;<br> wcex.lpfnWndProc = WndProc;<br> wcex.cbClsExtra = 0;<br> wcex.cbWndExtra = 0;<br> wcex.hInstance = hInstance;<br> wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_D3D006));<br> wcex.hCursor = LoadCursor(NULL, IDC_ARROW);<br> wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);<br> wcex.lpszMenuName = MAKEINTRESOURCE(IDC_D3D006);<br> wcex.lpszClassName = szWindowClass;<br> wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL));</p>
<p> return RegisterClassEx(&wcex);<br>}</p>
<p>//<br>// 函数: InitInstance(HINSTANCE, int)<br>//<br>// 目的: 保存实例句柄并创建主窗口<br>//<br>// 注释:<br>//<br>// 在此函数中,我们在全局变量中保存实例句柄并<br>// 创建和显示主程序窗口。<br>//<br>BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)<br>{<br> HWND hWnd;</p>
<p> hInst = hInstance; // 将实例句柄存储在全局变量中</p>
<p> hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,<br> CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);</p>
<p> if (!hWnd)<br> {<br> return FALSE;<br> }</p>
<p> ShowWindow(hWnd, nCmdShow);<br> UpdateWindow(hWnd);</p>
<p> return TRUE;<br>}</p>
<p>//<br>// 函数: WndProc(HWND, UINT, WPARAM, LPARAM)<br>//<br>// 目的: 处理主窗口的消息。<br>//<br>// WM_COMMAND - 处理应用程序菜单<br>// WM_PAINT - 绘制主窗口<br>// WM_DESTROY - 发送退出消息并返回<br>//<br>//<br>LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)<br>{<br> int wmId, wmEvent;<br> PAINTSTRUCT ps;<br> HDC hdc;</p>
<p> switch (message)<br> {<br> case WM_CREATE:<br> OnCreate(hWnd);<br> break;<br> case WM_COMMAND:<br> wmId = LOWORD(wParam);<br> wmEvent = HIWORD(wParam);<br> // 分析菜单选择:<br> switch (wmId)<br> {<br> case IDM_ABOUT:<br> DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);<br> break;<br> case IDM_EXIT:<br> DestroyWindow(hWnd);<br> break;<br> default:<br> return DefWindowProc(hWnd, message, wParam, lParam);<br> }<br> break;<br> case WM_PAINT:<br> hdc = BeginPaint(hWnd, &ps);<br> // TODO: 在此添加任意绘图代码...<br> EndPaint(hWnd, &ps);<br> break;<br> case WM_SIZE:<br> SetProjMatrix( LOWORD( lParam ), HIWORD( lParam ) );<br> break;<br> case WM_DESTROY:<br> ReleaseD3D();<br> PostQuitMessage(0);<br> break;<br> default:<br> return DefWindowProc(hWnd, message, wParam, lParam);<br> }<br> return 0;<br>}</p>
<p>// “关于”框的消息处理程序。<br>INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)<br>{<br> UNREFERENCED_PARAMETER(lParam);<br> switch (message)<br> {<br> case WM_INITDIALOG:<br> return (INT_PTR)TRUE;</p>
<p> case WM_COMMAND:<br> if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)<br> {<br> EndDialog(hDlg, LOWORD(wParam));<br> return (INT_PTR)TRUE;<br> }<br> break;<br> }<br> return (INT_PTR)FALSE;<br>}</p>
<p>void OnCreate(HWND hWnd)<br>{<br> g_hWnd = hWnd;<br> InitD3D();<br> CreateObject();<br>}</p>
<p>void ReleaseD3D()<br>{<br> if (g_pVB != NULL)<br> {<br> g_pVB->Release();<br> }<br> if (g_pd3dDevice != NULL)<br> {<br> g_pd3dDevice->Release();<br> }<br> if (g_pD3D != NULL)<br> {<br> g_pD3D->Release();<br> }<br>}</p>
<p>HRESULT InitD3D()<br>{<br> g_pD3D = Direct3DCreate9(D3D_SDK_VERSION);<br> D3DPRESENT_PARAMETERS d3dpp;<br> ZeroMemory(&d3dpp, sizeof(d3dpp));<br> d3dpp.Windowed = TRUE;<br> d3dpp.SwapEffect= D3DSWAPEFFECT_DISCARD;<br> d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;<br> g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, g_hWnd,<br> D3DCREATE_HARDWARE_VERTEXPROCESSING|D3DCREATE_PUREDEVICE,<br> &d3dpp, &g_pd3dDevice);<br> g_pd3dDevice->SetRenderState(D3DRS_LIGHTING, TRUE);<br> g_pd3dDevice->SetRenderState(D3DRS_AMBIENT,<br> D3DCOLOR_COLORVALUE(0.6f, 0.6f, 0.6f, 1.0));<br> g_pd3dDevice->LightEnable(0, TRUE);</p>
<p> D3DMATERIAL9 mtrl;<br> ZeroMemory(&mtrl, sizeof(mtrl));<br> mtrl.Diffuse.r = mtrl.Ambient.r = 140.0f / 255.0f;<br> mtrl.Diffuse.b = mtrl.Ambient.b = 200.0f / 255.0f;<br> mtrl.Diffuse.g = mtrl.Ambient.g = 255.0f / 255.0f;<br> mtrl.Diffuse.a = mtrl.Ambient.a = 1.0f;<br> g_pd3dDevice->SetMaterial(&mtrl);</p>
<p> return S_OK;<br>}</p>
<p>void BeforePaint(void)<br>{<br> D3DLIGHT9 light;<br> ZeroMemory(&light, sizeof(light));<br> light.Position = D3DXVECTOR3(30.0f, 30.0f, 30.0f);<br> light.Attenuation1 = 0.5f;<br> light.Diffuse.r = 1.0f;<br> light.Diffuse.g = 1.0f;<br> light.Diffuse.b = 1.0f;<br> light.Range = 1000.0f;<br> light.Type = D3DLIGHT_POINT;<br> g_pd3dDevice->SetLight(0, &light);<br> g_pd3dDevice->LightEnable(0, TRUE);<br>}</p>
<p>HRESULT CreateObject()<br>{<br> D3DVECTOR SrcBox[]={<br> { 5.0f, 5.0f, 0.0f},{ 5.0f, 5.0f, 10.0f},<br> { 5.0f, -5.0f, 0.0f},{ 5.0f, -5.0f, 10.0f},<br> {-5.0f, -5.0f, 0.0f},{-5.0f, -5.0f, 10.0f},<br> {-5.0f, 5.0f, 0.0f},{-5.0f, 5.0f, 10.0f},<br> };<br> WORD wIndex[]={<br> 0,4,6,0,2,4,<br> 0,6,7,0,7,1,<br> 0,3,2,0,1,3,<br> 5,2,3,5,4,2,<br> 5,6,4,5,7,6,<br> 5,1,7,5,3,1,<br> };<br> CUSTOMVERTEX ExpandBox[sizeof(wIndex)/sizeof(WORD)];<br> for (int i = 0; i < 36; i++)<br> {<br> ExpandBox[i].pos = SrcBox[wIndex[i]];<br> }<br> for (int i = 0; i < 12; i++)<br> {<br> D3DVECTOR Tri[3];<br> Tri[0] = ExpandBox[i * 3 + 0].pos;<br> Tri[1] = ExpandBox[i * 3 + 1].pos;<br> Tri[2] = ExpandBox[i * 3 + 2].pos;<br> ExpandBox[i * 3 + 0].normal.x = 0.0f;<br> ExpandBox[i * 3 + 0].normal.y = 0.0f;<br> ExpandBox[i * 3 + 0].normal.z = 1.0f;<br> CalcNormal(Tri, &(ExpandBox[i * 3 + 0].normal));<br> ExpandBox[i * 3 + 1].normal = ExpandBox[i * 3 + 0].normal;<br> ExpandBox[i * 3 + 2].normal = ExpandBox[i * 3 + 0].normal;<br> }<br> g_pd3dDevice->CreateVertexBuffer(sizeof(ExpandBox), 0, D3DFVF_CUSTOMVERTEX, D3DPOOL_DEFAULT, &g_pVB, NULL);<br> VOID* pVertices;<br> g_pVB->Lock(0, sizeof(ExpandBox), (void**)&pVertices, 0);<br> MoveMemory(pVertices, ExpandBox, sizeof(ExpandBox));<br> g_pVB->Unlock();</p>
<p> return S_OK;<br>}</p>
<p>void OnIdle()<br>{<br> static CTimer t;<br> static double dt = t.End();<br> double temp = t.End();<br> char szValue[256];<br> sprintf(szValue, "当前帧率:%f", 1/(temp-dt));<br> SetWindowTextA(g_hWnd, szValue);<br> dt = temp;<br> if (g_pd3dDevice != NULL)<br> {<br> g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(255,255,200), 1.0f, 0);<br> if (SUCCEEDED(g_pd3dDevice->BeginScene()))<br> {<br> BeforePaint();<br> if (FAILED(SetModalMatrix()))<br> {<br> return;<br> }<br> g_pd3dDevice->SetStreamSource(0, g_pVB, 0, sizeof(CUSTOMVERTEX));<br> g_pd3dDevice->SetFVF(D3DFVF_CUSTOMVERTEX);<br> g_pd3dDevice->DrawPrimitive(D3DPT_TRIANGLELIST, 0, 12);<br> g_pd3dDevice->EndScene();<br> g_pd3dDevice->Present(NULL, NULL, NULL, NULL);<br> }<br> }<br>}</p>
<p>HRESULT SetModalMatrix()<br>{<br> static float fRadius = 0.5f;<br> fRadius -= 0.003f;<br> if (fRadius < 0)<br> {<br> fRadius = D3DX_PI * 2;<br> }<br> D3DXMATRIX matWorld;<br> D3DXMatrixRotationZ(&matWorld, 0.0f);<br> if (FAILED(g_pd3dDevice->SetTransform(D3DTS_WORLD, &matWorld)))<br> {<br> return E_FAIL;<br> }<br> D3DXMATRIX matView;<br> D3DXMatrixLookAtLH(&matView, &D3DXVECTOR3(cosf(fRadius)*40.0f, sinf(fRadius)*40.0f, 30.0),<br> &D3DXVECTOR3(0.0f, 0.0f, 0.0f), &D3DXVECTOR3(0.0f, 0.0f, 1.0f));<br> g_pd3dDevice->SetTransform(D3DTS_VIEW, &matView);</p>
<p> return S_OK;<br>}</p>
<p>HRESULT SetProjMatrix(WORD wWidth, WORD wHeight)<br>{<br> D3DXMATRIX matProj;<br> D3DXMatrixPerspectiveFovLH(&matProj, D3DX_PI/4, (float)wWidth/(float)wHeight,1.0f, 100.0f);<br> return g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &matProj);<br>}</p>
</td>
</tr>
</tbody>
看看和OpenGL做出来的哪个效果更好一些呢?我想使用D3D来做这些事会很方便吧。