Andy Pike - DirectX 8 Programming Tutorial

Здесь есть возможность читать онлайн «Andy Pike - DirectX 8 Programming Tutorial» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

DirectX 8 Programming Tutorial: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «DirectX 8 Programming Tutorial»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

DirectX 8 Programming Tutorial — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «DirectX 8 Programming Tutorial», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

pVertices[2].x = (m_nWidth) / 2.0f;

pVertices[2].y = –(m_nHeight) / 2.0f;

pVertices[3].x = (m_nWidth) / 2.0f;

pVertices[3].y = m_nHeight / 2.0f;

pVertices[0].z = 1.0f;

pVertices[1].z = 1.0f;

pVertices[2].z = 1.0f;

pVertices[3].z = 1.0f;

//Set the texture coordinates of the vertices

pVertices[0].u = 0.0f;

pVertices[0].v = 1.0f;

pVertices[1].u = 0.0f;

pVertices[1].v = 0.0f;

pVertices[2].u = 1.0f;

pVertices[2].v = 1.0f;

pVertices[3].u = 1.0f;

pVertices[3].v = 0.0f;

m_pVertexBuffer->Unlock();

return true;

}

bool CPanel::SetTexture(const char *szTextureFilePath, DWORD dwKeyColour) {

if (FAILED(D3DXCreateTextureFromFileEx(m_pD3DDevice, szTextureFilePath, 0, 0, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, dwKeyColour, NULL, NULL, &m_pTexture))) {

return false;

}

return true;

}

DWORD CPanel::Render() {

m_pD3DDevice->SetStreamSource(0, m_pVertexBuffer, sizeof(PANEL_CUSTOMVERTEX));

m_pD3DDevice->SetVertexShader(PANEL_D3DFVF_CUSTOMVERTEX);

if (m_pTexture != NULL) {

m_pD3DDevice->SetTexture(0, m_pTexture);

m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);

} else {

m_pD3DDevice->SetTexture(0, NULL);

}

m_pD3DDevice->DrawPrimitive(D3DPT_TRIANGLESTRIP, 0, 2);

return 2; //Return the number of polygons rendered

}

void CPanel::MoveTo(int x, int y) {

//x and y specify the top left corner of the panel in screen coordinates

D3DXMATRIX matMove;

x –= (m_nScreenWidth / 2) – (m_nWidth / 2);

y –= (m_nScreenHeight / 2) – (m_nHeight / 2);

D3DXMatrixTranslation(&matMove, (float)x, –(float)y, 0.0f);

m_pD3DDevice->SetTransform(D3DTS_WORLD, &matMove);

}

The only slight changes from usual are that the SetTexture and Render methods have changed to enable texture transparencies (we will look at this in a moment).

There is also a new function called MoveTo which will move the panel from the centre of the screen, to any position you specify. It takes two parameters x and y which are screen coordinates for the top left corner of the panel. We then use the normal matrix translation functions to move the panel. We can also rotate the panel by using the normal rotation matrices.

Texture Transparency

The first thing to do is to enable alpha blending so that we can use transparent textures. We do this with a few calls to SetRenderState, the code to enable alpha blending is shown below:

//Enable alpha blending so we can use transparent textures

m_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);

//Set how the texture should be blended (use alpha)

m_pD3DDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);

m_pD3DDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);

There are two further changes to make. The first is the way we load the textures. We need to use the D3DXCreateTextureFromFileEx function, this will enable us to specify a key colour. This means that any pixel in the texture that is the same colour as the key colour will be made transparent. Fig 11.1, 11.2 and 11.3 below show the three textures that I have used for this tutorial. I have specified that the black pixels should be transparent.

D3DXCreateTextureFromFileEx(m_pD3DDevice, szTextureFilePath, 0, 0, 0, 0, D3DFMT_UNKNOWN, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, dwKeyColour, NULL, NULL, &m_pTexture);

Fig 11.1

Fig 11.2

Fig 11.3

The second change is how the texture should be rendered. The SetTextureStageState function has been changed in the Render method of CPanel to render the texture using transparencies.

m_pD3DDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE);

From the last tutorial we have three rotating spaceships. We've added some 2D elements to the scene, each with some transparency in the texture. The final scene when rendered will look something like the screenshot below:

Summary

Now, we have completed the basics to rendering graphics in DirectX. There is lots more advanced topics in DirectX Graphics which we will cover in future tutorials. In the next tutorial we will see how to add some user interaction with the keyboard and mouse using DirectInput, vital to any game.

DirectX Tutorial 12: Keyboard and Mouse Input

Introduction

In this tutorial we will create a simple Earth object that the user can control. The user will be able to use the mouse to change the Earth's position. The user will also be able to change the Earth's scale and rotation by using the keyboard. You can download the full source code by clicking the "Download Source" link above.

DirectInput

So far we have been using Direct3D to draw 3D objects. Now we want to add some user interaction to our application. We can do this by using DirectInput. DirectInput allows us to get data from any input device: mouse, keyboard or joystick. We can then use this data to change elements in our scene. In this tutorial we will be looking at the mouse and keyboard only, we'll take a look at joysticks in a future tutorial.

In our application, we will need to do the following steps to add user interaction.

· Initialise DirectInput

· Setup the keyboard

· Setup the mouse

· For each frame, get the state of the keyboard and mouse and use it to modify the scene

· Once finished, clean up DirectInput

Include and Library files

First thing's first. To use DirectInput we need to add a new include file and two library files to our project. If you don't add these to your project you'll get compiler and linker errors. I've included the new header file in Game.h just below where I have included d3dx8.h. You can add the library files by going to Project > Settings… then on the Link tab, type the new library file names into the Object/Library Modules input box. The new files are listed below:

· dinput.h

· dinput8.lib

· dxguid.lib

The Controls

The controls for this tutorial will be as follows:

· Up arrow: Scale Earth up

· Down arrow: Scale Earth down

· Left arrow: Rotate Earth more to the left

· Right arrow: Rotate Earth more to the right

· Move mouse: Change Earth x and y position

· Left mouse button: Stop Earth rotation

· Right mouse button: Start Earth rotation at default speed and direction

Initialising DirectInput

The first thing we need to do is to initialise DirectInput. To do this, I have a new function called InitialiseDirectInput that is called from the main CGame::Initialise function. The code snippet below will create a DirectInput object that we will use to create further objects for user input.

//Create the DirectInput object

if (FAILED(DirectInput8Create(hInst, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&m_pDirectInput, NULL))) {

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «DirectX 8 Programming Tutorial»

Представляем Вашему вниманию похожие книги на «DirectX 8 Programming Tutorial» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «DirectX 8 Programming Tutorial»

Обсуждение, отзывы о книге «DirectX 8 Programming Tutorial» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x