DirectX8編程指南-1

DirectX Tutorial 1: Getting Started<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

DirectX 教程一:入門

What you will need

你需要準備什麼

DirectX 8.0 SDK (Downloadable from http://msdn.microsoft.com/directx)

DirectX 8.0 SDK (可以從 http://msdn.microsoft.com/directx 下載)
Microsoft Visual C++ 6 (SP5)

Microsoft Visual C++ 6 (升級包5)
General knowledge of Windows programming

對於Windows編程的大體上的認識
General knowledge of C++ and Object-Oriented programming

關於C++和麪向對象編程的總體知識

Introduction

導言

Welcome to my DirectX tutorials. This is the first in a number of tutorials that should at least help you on the way to make Windows games using Microsoft DirectX 8. I have decided to write these tutorials for two reasons. Firstly, I’m a complete beginner when it comes to DirectX. So, the idea is that as I learn, I can write a short tutorial that should reinforce my knowledge. Secondly, the SDK isn’t the most helpful thing in the world for complete beginners starting out in game development. Also, there isn’t a great deal of stuff out there on the Internet for beginners and DirectX 8, so this should help. One other thing, as I said, I am a beginner. So, if you spot something that is incorrect in these tutorials then please let me know by emailing me at: [email protected].

歡迎你閱讀我的DirectX教程。這是在很多教程中第一個應該至少可以在你使用Microsoft DirectX8通往製作Windows遊戲道路上幫助你的教程。我決定寫這些東西出於很多個原因。首先,當我拿起DirectX的時候我是一個徹底的初學者。因而,在我學習的過程中我有一個想法,我可以寫一個小的教程來加深我的理解。其次,對於剛進入遊戲開發領域的完全的初學者,SDK不是最有用的東西。而且,在網上沒有很多關於Directx8的材料給初學者,因此這個東西可能會很有幫助。另外一方面,正如我所說的,我是一個初學者。因此,如果你在這些教程中發現了一些不正確的東西,請通過發信往[email protected]使我知道它。

COM

What is COM? Well, the Component Object Model is basically a library of methods. You can create COM objects in your program and then call the methods that they expose to you. Methods are grouped together in collections of related methods. These collections are known as Interfaces. You could think of a COM object as a library of functions arranged by subject. DirectX provides a whole host of these libraries that will enable you to create 3D games. The best part is, that DirectX takes care of a lot of the hard stuff for you, so it is pretty easy to get something simple up and running.

什麼是COM?呃,組件對象模型基本上只是一個函數庫。你可以在你的程序中創建COM對象然後調用他提供給你的函數。函數和相關的函數集合在一起。這些吉他被稱之爲接口(Interface)。你可以把COM對象想象成函數按不同的主題排列的庫。DirectX提供可以使你創建3D遊戲的庫的一個完整host。最好的部分是,DirectX爲你作了許多苦差事,因而要使一些簡單的東西動起來相當的容易。

There is a lot more to COM than that, for a full description take a look in the SDK. All you really need to worry about is that you release all of your COM objects/interfaces before your program terminates. You should make sure that you release them in the reverse order to that which you created them. For example:

關於COM有許多比那些多很多的內容,要得到完整描述看看SDK。你所有真正需要關心的是在你程序終止之前釋放你所有的COM對象/接口。你應當確保你以和你創建他們時相反的順序釋放他們。例如:

1.   Create interface A.
2.   Create interface B.
3.   Release interface B.
4.   Release interface A.

You release the COM object by calling their Release method.

你通過調用Release函數釋放COM對象。

Page Flipping

翻頁

What is Page Flipping? Well, think of a flipbook. This is a number of pages with a slightly different drawing on each page. Then, when you hold the corner and “flip” the pages, it looks like the picture is moving. This is how DirectX Graphics works. You draw all of your objects onto a hidden page, known as the “Back Buffer”. Then when you have finished, flip it to the Front Buffer and repeat the process. As the user is looking at the new front buffer, your program will be drawing onto the back buffer.

什麼是Page Flipping?呃,想想flipbook。他是有很多繪有稍微不同的圖畫的頁的書。然後,當你提着一個角然後“flip”這些頁,看上去圖象就在移動。這就是DirectX Graphics如何工作的。你在一個隱藏的頁上繪上你所有的物體。那個隱藏的頁就是被稱爲“Back Buffer”的東西。然後當你繪完之後,把它翻到前面然後重複這個過程。當用戶在觀看前臺的時候,你的程序又在後面繪畫。

What would happen without Page Flipping? Without Page Flipping, the user would see each object appear as it was drawn, which isn’t what you want at all.

如果沒有Page Flipping會發生什麼?沒有Page Flipping,用戶可能看到每個物體的繪出過程,而這不是你根本不是你想要的。

So, your game will basically consist of a loop, known as the “Game Loop”. Each time around the loop you process your game logic so you know where your objects will be. Next, you clear the Back Buffer. Then draw the current scene onto it. When this is done, flip it to the front and start the loop again. This will continue until the game is shut down. You may have a number of Back Buffers, this is known as a “Swap Chain”.

因此,你的遊戲基本上包含一個循環,稱爲“遊戲循環”,每次在循環中,你處理你的遊戲邏輯因而你知道你的物體將到哪裏。然後,你清除Back Buffer。然後把當前場景繪進去。當這完成了之後,把flip到前面又一次開始循環。這個都要不停的進行,直到你的遊戲結束。你可能有很多的Back Buffer,這又稱爲“Swap Chain”(交換鏈)。

Devices

設備

What is a device? Basically, a device (as far as DirectX Graphics is concerned) is your machines 3D card. You can create an interface that represents your device and then use it to draw objects onto the back buffer.

什麼是設備?簡單來說,一個設備(就DirectX Graphic來說)是你機器的3D卡。你可以創建一個表示你的設備的接口然後使用它來在back buffer中繪物體。

Game Loop

遊戲循環

What is the game loop? Well, the game loop is a code loop that loops until the program is shut down. Inside the game loop is where it all happens: objects are drawn (rendered), game logic is processed (AI, moving objects and scoring etc) and Windows messages are processed. Then it's all done again until the program is closed down.

何爲遊戲循環?呃,遊戲循環是一個代碼循環知道你的程序結束爲止。在遊戲循環發生了下面的事情:物體被繪出(渲染),遊戲邏輯得到處理(人工智能,移動物體,統計得分等)和處理Windows消息。然後有一次重複這些知道程序結束。

Creating Your First Project

創建你第一個工程

Okay, that’s enough theory lets get started. Follow the step-by-step guide below to create your first DirectX Graphics project.

好的,理論已經足夠了,我們開始吧。跟隨下面的一步一步的指導來創建你的第一個DirectX Graphics工程

1. In Visual C++ create a new Win32 Application.
    a. File > New
    b. From the Projects tab select Win32 Application
    c. Enter a name for your project such as “DX Project 1”
    d. Select a folder for the location of your source code files
    e. Click Next
    f. Select the empty project option.
    g. Click Finish
2. Make sure that your project settings are correct.
    a. Project > Settings...
    b. On the Link tab, make sure that "d3d8.lib" is in the list of Object/Library Modules. If it isn’t simply type it in.
3. Make sure that your search paths are correct.
    a. Tools > Options > Directories Tab
    b. In the "Show directories for" drop-down, select "include files".
    c. If it does not exist already, add the following path: <SDK INSTALL PATH>/include.
    d. Make sure that this path is at the top of the list by clicking on the up arrow button (if needed).
    e. In the "Show directories for" drop-down, select "library files".
    f. If it does not exist already, add the following path: <SDK INSTALL PATH>/lib.
    g. Make sure that this path is at the top of the list by clicking on the up arrow button (if needed).
4. Add the source code.
    a. File > New
    b. From the Files tab, select C++ Source File
    c. Enter a filename such as “Main.cpp”
    d. Copy the code segment below, and then paste it into your new file.
5. Build and Run the program.
    a. Press F7 to build your project
    b. Press F5 to run

#include <d3d8.h>



LPDIRECT3D8 g_pD3D = NULL;
LPDIRECT3DDEVICE8 g_pD3DDevice = NULL;

HRESULT InitialiseD3D(HWND hWnd)
{
    
//First of all, create the main D3D object. If it is created successfully we
    //should get a pointer to an IDirect3D8 interface.

//首先,創建一個主要的D3D物體。如果它被成功創建了我們就獲得了一個指向Idirect3D8接口的指針。
    g_pD3D = Direct3DCreate8(D3D_SDK_VERSION);
    
if(g_pD3D == NULL)
    {
        
return E_FAIL;
    }

    
//Get the current display mode

//獲得當前的顯示模式
    D3DDISPLAYMODE d3ddm;
    
if(FAILED(g_pD3D->GetAdapterDisplayMode(D3DADAPTER_DEFAULT, &d3ddm)))
    {
        
return E_FAIL;
    }

    
//Create a structure to hold the settings for our device

//創建一個結構來保存我們設備的設置信息
    D3DPRESENT_PARAMETERS d3dpp;
    ZeroMemory(&d3dpp,
sizeof(d3dpp));

    
//Fill the structure.
    //We want our program to be windowed, and set the back buffer to a format
    //that matches our current display mode

//填充結構。

//我們想要我們的程序用窗口顯示,並且設置back buffer爲和我們當前顯示模式匹配的格式。
    d3dpp.Windowed = TRUE;
    d3dpp.SwapEffect = D3DSWAPEFFECT_COPY_VSYNC;
    d3dpp.BackBufferFormat = d3ddm.Format;

    
//Create a Direct3D device.

//創建一個Direct3D設備
    if(FAILED(g_pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd,
                                   D3DCREATE_SOFTWARE_VERTEXPROCESSING, &d3dpp, &g_pD3DDevice)))
    {
        
return E_FAIL;
    }
    
    
return S_OK;
}

void Render()
{
    
if(g_pD3DDevice == NULL)
    {
        
return;
    }

    
//Clear the backbuffer to a green color

//backbuffer清除爲綠色的
    g_pD3DDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 255, 0), 1.0f, 0);
    
    
//Begin the scene

//開始場景
    g_pD3DDevice->BeginScene();
    
    
//Rendering of our game objects will go here

//我們遊戲物體的渲染在這裏進行
    
    
//End the scene

//結束場景
    g_pD3DDevice->EndScene();
    
    
//Filp the back and front buffers so that whatever has been rendered on the back buffer
    //will now be visible on screen (front buffer).

//翻動backfront buffer因而無論在back buffer中如何渲染可以在屏幕上可見(front //buffer)
    g_pD3DDevice->Present(NULL, NULL, NULL, NULL);
}

void CleanUp()
{
    
if(g_pD3DDevice != NULL)
    {
        g_pD3DDevice->Release();
        g_pD3DDevice = NULL;
    }

    
if(g_pD3D != NULL)
    {
        g_pD3D->Release();
        g_pD3D = NULL;
    }
}

void GameLoop()
{
    
//Enter the game loop

//進入遊戲循環
    MSG msg;
    BOOL fMessage;

    PeekMessage(&msg, NULL, 0U, 0U, PM_NOREMOVE);
    
    
while(msg.message != WM_QUIT)
    {
        fMessage = PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE);

        
if(fMessage)
        {
            
//Process message

//處理消息
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
        
else
        {
            
//No message to process, so render the current scene

//沒有消息要處理,因此來渲染當前場景
            Render();
        }

    }
}

//The windows message handler

//窗口消息處理函數
LRESULT WINAPI WinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    
switch(msg)
    {
        
case WM_DESTROY:
            PostQuitMessage(0);
            
return 0;
        
break;
        
case WM_KEYUP:
            
switch (wParam)
            {
                
case VK_ESCAPE:
                    
//User has pressed the escape key, so quit

//用戶按下了escape鍵,退出
                    DestroyWindow(hWnd);
                    
return 0;
                
break;
            }
        
break;

    }

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

//Application entry point

//程序進入點
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE, LPSTR, INT)
{
    
//Register the window class

//註冊窗口類
    WNDCLASSEX wc = {sizeof(WNDCLASSEX), CS_CLASSDC, WinProc, 0L, 0L,
                     GetModuleHandle(NULL), NULL, NULL, NULL, NULL,
                     "DX Project 1", NULL};
    RegisterClassEx(&wc);

    
//Create the application's window

//創建程序的窗口
    HWND hWnd = CreateWindow("DX Project 1", "www.andypike.com: Tutorial 1",
                              WS_OVERLAPPEDWINDOW, 50, 50, 500, 500,
                              GetDesktopWindow(), NULL, wc.hInstance, NULL);

    
//Initialize Direct3D

//初始化Direct3D
    if(SUCCEEDED(InitialiseD3D(hWnd)))
    {
        
//Show our window

//顯示我們的窗口
        ShowWindow(hWnd, SW_SHOWDEFAULT);
        UpdateWindow(hWnd);

        
//Start game running: Enter the game loop

//開始程序的運行:進入遊戲循環
        GameLoop();
    }
    
    CleanUp();

    UnregisterClass("DX Project 1", wc.hInstance);
    
    
return 0;
}

You should finish up with a window with a green background (shown below). Okay, it’s not much I know, but everyone has to start somewhere.

你將看到一個綠色背景的窗口顯示出來(如下)。好的,所知不多,但是每個人必須要從某處入手。

<?xml:namespace prefix = v ns = "urn:schemas-microsoft-com:vml" />圖片略

So, what is going on here?

呃,這裏幹了一些什麼?

WinMain
This is the applications entry point. Code execution will start here. This is where we register, create and show our window. Once that is complete, we initialise Direct3D and enter our game loop.

這是程序的入口點。程序執行從這裏開始。這是我們註冊,創建和顯示我們窗口的地方。一旦完成這些,我們初始化Direct3D並進入我們的遊戲循環。

WinProc
This is the applications message handler. Whenever Windows sends a message to our application, it will be handled by this function. Notice that there are two messages that our application will handle: WM_DESTROY and WM_KEYUP, all other messages are passed to DefWindowProc for default message processing.

這是程序消息的處理函數。無論何時Windows發送一個消息給我們的程序,它將被這個函數處理。注意我們程序要處理兩個消息:WM_DESTROYWM_KEYUP,所有其它的消息被髮送給DefWindowProc來進行缺省的消息處理。

g_pD3D
This is a pointer to an IDirect3D8 interface. From this interface we will create our Direct3D Device.

這會是一個指向IDirect3D8接口的指針。用這個接口我們將要創建我們的Direct3D 設備。

g_pD3DDevice
This is a pointer to an IDirect3DDevice8 interface. This will actually represent your hardware graphics card.

這是一個指向Idirect3Ddevice8的接口。這實際代表你的硬件的圖形卡。

InitialiseD3D
This does exactly that: initialise Direct3D. First of all, we create the IDirect3D8 object. From this object we can determine the users current display mode. Finally, we use this information to create a compatible device.

這實際是這樣作的:初始化Direct3D。首先,我們創建Idirect3D8對象。用這個對象,我們可以決定用戶當前的顯示模式。最終,我們使用這些信息來創建一個兼容的設備。

GameLoop
Once our window is created this function is called. This function contains the main game loop. If there are no windows messages to handle, it calls our Render() function.

一旦我們窗口被創建,這個函數就被調用。這個函數包含一個主遊戲循環。如果沒有Windows消息要處理,它調用我們的Render()函數。

Render
Firstly we clear the back buffer ready for drawing. Then we use the BeginScene method of our device object to tell DirectX that we are about to start drawing. We can then start to draw our game objects (Tutorial 2). Once we have finished drawing, we use the EndScene method of our device object to tell DirectX that we have finished drawing. The final step is to "flip" (present) the back buffer, this will display our game objects to the user.

首先我們清除了back buffer來準備繪畫。然後我們使用我們設備對象的BeginScene函數來告訴Directx我們要開始繪畫了。然後我們可以開始繪我們遊戲的物體(教程2)。一旦我們完成了繪圖,我們使用我們設備對象的EndScene函數來告訴DirectX我們已經完成了繪圖。最後一步是“flip(翻動)”(呈現)back buffer,這將顯示我們的遊戲物體給用戶。

CleanUp
Simply cleans up by releasing our objects.

簡單地通過釋放我們的對象來作清理工作。

Summary

總結

Ok, that’s it for the first tutorial. I know that the finished program wasn’t the most spectacular thing in the world, but just wait for the next tutorial when we will be drawing some shapes!

好的,第一章就是這樣的了。我知道完成的程序不是世界上最引人注目的程序,但只要等到下一個教程當我們就可以畫一些圖形了!

發佈了61 篇原創文章 · 獲贊 1 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章