Andy Pike - DirectX 8 Programming Tutorial
Здесь есть возможность читать онлайн «Andy Pike - DirectX 8 Programming Tutorial» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.
- Название:DirectX 8 Programming Tutorial
- Автор:
- Жанр:
- Год:неизвестен
- ISBN:нет данных
- Рейтинг книги:5 / 5. Голосов: 1
-
Избранное:Добавить в избранное
- Отзывы:
-
Ваша оценка:
- 100
- 1
- 2
- 3
- 4
- 5
DirectX 8 Programming Tutorial: краткое содержание, описание и аннотация
Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «DirectX 8 Programming Tutorial»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.
DirectX 8 Programming Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком
Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «DirectX 8 Programming Tutorial», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.
Интервал:
Закладка:
}
void CleanUp() {
SafeRelease(g_pVertexBuffer);
SafeRelease(g_pD3DDevice);
SafeRelease(g_pD3D);
}
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
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 3", NULL
};
RegisterClassEx(&wc);
//Create the application's window
HWND hWnd = CreateWindow("DX Project 3", "www.andypike.com: Tutorial 3", WS_OVERLAPPEDWINDOW, 50, 50, 500, 500, GetDesktopWindow(), NULL, wc.hInstance, NULL);
//Initialize Direct3D
if (SUCCEEDED(InitialiseD3D(hWnd))) {
//Show our window
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
//Initialize Vertex Buffer
if (SUCCEEDED(InitialiseVertexBuffer())) {
//Start game running: Enter the game loop
GameLoop();
}
}
CleanUp();
UnregisterClass("DX Project 3", wc.hInstance);
return 0;
}
You should finish up with a window with a black background and a multi-coloured cube in the middle rotating (shown below).
So, what have we added/changed:
Include and lib files
We have a new header file, which replaces the old one. The new header file is:
We also have two new lib files to specify in our project settings (as in tutorial 1). They are: "d3dx8.lib" and "winmm.lib".
CUSTOMVERTEX
We have changed our custom vertex to only include x, y, z and colour values. These will allow us to specify a point in 3D space and a colour.
D3DFVF_CUSTOMVERTEX
To match our custom vertex structure, we have modified our FVF. We now use the flags D3DFVF_XYZ and D3DFVF_DIFFUSE.
InitaliseD3D
We have enabled Backface Culling (explained above). We use the SetRenderState function to do this, notice that we use the D3DCULL_CCW flag to specify that we want DirectX to cull the anti-clockwise faces.
We have also used the SetRenderState function to specify that we want to disable lighting, this is because we have given a colour (light) value to each of our vertices.
InitaliseVertexBuffer
Here we have set the values for our 18 vertices. Each vertex has a comment next to it with it's number, these numbers match the diagrams above (Fig 3.3 and 3.4). The cube is centred about the origin (0, 0, 0) and is 10 units wide/high/deep.
SetupRotation
SetupRotation is a new function. Here we call the functions D3DXMatrixRotationX, D3DXMatrixRotationY and D3DXMatrixRotationZ to generate rotation matrices and store them in three D3DXMATRIX structures. Next, we multiply the three matrices together to form one world matrix, we call the SetTransform function to apply the transformation to our vertices.
SetupCamera
SetupCamera is a new function. Here we setup the camera. We set it's position in 3D space to be (0, 0, –30) and point it at the origin (0,0,0). We have centred our cube around the origin. We also specify that the y axis points up. We use the D3DXMatrixLookAtLH to generate the view matrix and then use the SetTransform function to apply the transformation.
SetupPerspective
SetupPerspective is another new function. Here we setup the camera's lens. We have decided to have a field of view of PI/4 (normal) and an aspect ratio of 1. We have decided to set the near clipping path to 1, this means that polygons closer than one unit to the camera will be cropped. We have also decided to set the far clipping path to 500, this means that polygons more than 500 units away will be cropped.
Render
In the Render function, we call the three new functions SetupRotation, SetupCamera and SetupPerspective. These functions are called before we render the polygons.
We render the polygons by using three triangle strips, one for the top, one for the sides and one for the bottom.
That's it for another tutorial. In this tutorial we learnt about Backface Culling, Matrices, 3D World Space and how a cube is made up using triangular polygons. In the next tutorial, we will arrange our code so far into classes and make our application full screen.
DirectX Tutorial 4: Full Screen and Depth Buffers
In this tutorial we will convert our single file into two classes: CGame and CCuboid. CGame will contain the main code such as initialisation, the game loop and rendering. CCuboid will be used to create cuboid objects, you can specify position and size. CCuboid also has a Render function that should be called in the CGame render function. I have not made any major changes to the code from the last tutorial, so you should find it pretty easy to understand. We will change our program to be full screen rather than windowed and we'll take a look at depth buffers. From now on, I will not show all of the program code in the tutorial as I have done so far (they're getting to long). Instead, I'll only show you the snippets of code that are new or have been modified. You can download the full source code by clicking the "Download Source" link above.
Using a Depth Buffer (also called a z-buffer) ensures that polygons are rendered correctly based on their depth (distance from the camera). Lets say, for example, that in your scene you have two squares – one blue and one green. The blue one has a z value of 10 and the green square has a z value of 20 (the camera is at the origin). This means that the blue square is in front of the green one. A depth buffer is used to make sure that where one object is in front of another, the correct one is rendered. DirectX will test a pixel on the screen against an object to see how close it is to the camera. It stores this value in the depth buffer. It will then test the same pixel against the next object and compares it's distance with the value held in the depth buffer. If it is shorter, it'll overwrite the old value with the new one, otherwise it will be ignored (there is something in front of it). This will determine what colour the pixel will be, blue or green. Fig 4.1 below, shows this for a given pixel on the rendering surface.
Читать дальшеИнтервал:
Закладка:
Похожие книги на «DirectX 8 Programming Tutorial»
Представляем Вашему вниманию похожие книги на «DirectX 8 Programming Tutorial» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.
Обсуждение, отзывы о книге «DirectX 8 Programming Tutorial» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.