Чтение онлайн

на главную

Жанры

DirectX 8. Начинаем работу с DirectX Graphics

Поздняков Константин

Шрифт:

if (SUCCEEDED(InitD3D(hWnd))) {

 PostInitialize(200.0f, 200.0f);

 // This is my added line. The values of

 // 200.0f were chosen based on the sizes

 // used in the call to CreateWindow.

 ShowWindow(hWnd, SW_SHOWDEFAULT);

 …

void Render2D
 — This function is called each time you want to render your scene. Again, the Render function of the Tutorial now looks like this:

VOID Render {

 if (NULL == g_pd3dDevice) return;

 // Clear the backbuffer to a blue color

 g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,255), 1.0f, 0);

 // Begin the scene

 g_pd3dDevice->BeginScene;

 Render2D; //My added line…

 // End the scene

 g_pd3dDevice->EndScene;

 // Present the backbuffer contents to the display

 g_pd3dDevice->Present(NULL, NULL, NULL, NULL);

}

OK, that's our shell of an application. Now for the good stuff…

Setting Up for 2D drawing in D3D

NOTE: This is where we start talking about some of the nasty math involved with D3D. Don't be alarmed - if you want to, you can choose to ignore most of the detailsЕ Most Direct3D drawing is controlled by three matrices: the projection matrix, the world matrix, and the view matrix. The first one we'll talk about is the projection matrix. You can think of the projection matrix as defining the properties of the lens of your camera. In 3D applications, it defines things like perspective, etc. But, we don't want perspective - we are talking about 2D!! So, we can talk about orthogonal projections. To make a long story very short, this allows us to draw in 2D without all the added properties of 3D drawing. To create an orthogonal matrix, we need to call

D3DXMatrixOrthoLH
and this will create a matrix for us. The other matrices (view and world) define the position of the camera and the position of the world (or an object in the world). For our 2D drawing, we don't need to move the camera, and we don't want to move the world for now, so we'll use an identity matrix, which basically sets the camera and world in a default position. We can create identity matrices with
D3DXMatrixIdentity
. To use the D3DX functions, we need to add:

#include <d3dx8.h>

and add d3dx8dt.lib to the list of linked libraries. Once that was set up, the PostInitialize function now looks like this:

void PostInitialize(float WindowWidth, float WindowHeight) {

 D3DXMATRIX Ortho2D;

 D3DXMATRIX Identity;

 D3DXMatrixOrthoLH(&Ortho2D, WindowWidth, WindowHeight, 0.0f, 1.0f);

 D3DXMatrixIdentity(&Identity);

 g_pd3dDevice->SetTransform(D3DTS_PROJECTION, &Ortho2D);

 g_pd3dDevice->SetTransform(D3DTS_WORLD, &Identity);

 g_pd3dDevice->SetTransform(D3DTS_VIEW, &Identity);

}

We are now set up for 2D drawing, now we need something to draw. The way things are set up, our drawing area goes from —WindowWidth/2 to WindowWidth/2 and -WindowHeight/2 to WindowHeight/2. One thing to note, in this code, the width and the height are being specified in pixels. This allows us to think about everything in terms of pixels, but we could have set the width and height to say 1.0 and that would have allowed us to specify sizes, etc. in terms of percentages of the screen space, which would be nice for supporting multiple resolutions easily. Changing the matrix allows for all sorts of neat things, but for simplicity, we'll talk about pixels for nowЕ Setting Up a 2D "Panel"

When I draw in 2D, I have a class called CDX8Panel that encapsulates everything I need to draw a 2D rectangle. For simplicity, and it avoid a C++ explanation, I have pulled out the code here. However, as we build up our code to draw a panel, you'll probably see the value of such a class or higher level API if you don't use C++. Also, we are about to recreate much that goes on in the ID3DXSprite interface. I'm explaining the basics here to show the way things work, but you may want to use the sprite interface if it suits your needs.

My definition of a panel is simply a 2D textured rectangle that we are going to draw on the screen. Drawing a panel will be extremely similar to a 2D blit. Experienced 2D programmers may think that this is a lot of work for a blit, but that work pays off with the amount of special effects that it enables. First, we have to think about the geometry of our rectangle. This involves thinking about vertices. If you have 3D hardware, the hardware will process these vertices extremely quickly. If you have 2D hardware, we are talking about so few vertices that they will be processed very quickly by the CPU. First, let's define our vertex format. Place the following code near the #includes:

struct PANELVERTEX {

 FLOAT x, y, z;

 DWORD color;

 FLOAT u, v;

};

#define D3DFVF_PANELVERTEX (D3DFVF_XYZ | D3DFVF_DIFFUSE | D3DFVF_TEX1)

This structure and Flexible Vertex Format (FVF) specify that we are talking about a vertex that has a position, a color, and a set of texture coordinates.

Now we need a vertex buffer. Add the following line of code to the list of globals. Again, for simplicity, I'm making it global — this is not a demonstration of good coding practice.

LPDIRECT3DVERTEXBUFFER8 g_pVertices = NULL;

Now, add the following lines of code to the PostInitialize function (explanation to follow):

float PanelWidth = 50.0f;

float PanelHeight = 100.0f;

g_pd3dDevice->CreateVertexBuffer(4 * sizeof(PANELVERTEX), D3DUSAGE_WRITEONLY,

 D3DFVF_PANELVERTEX, D3DPOOL_MANAGED, &g_pVertices);

PANELVERTEX* pVertices = NULL;

g_pVertices->Lock(0, 4 * sizeof(PANELVERTEX), (BYTE**)&pVertices, 0);

//Set all the colors to white

pVertices[0].color = pVertices[1].color = pVertices[2].color = pVertices[3].color = 0xffffffff;

//Set positions and texture coordinates

pVertices[0].x = pVertices[3].x = -PanelWidth / 2.0f;

pVertices[1].x = pVertices[2].x = PanelWidth / 2.0f;

pVertices[0].y = pVertices[1].y = PanelHeight / 2.0f;

pVertices[2].y = pVertices[3].y = -PanelHeight / 2.0f;

Поделиться:
Популярные книги

Черный Маг Императора 13

Герда Александр
13. Черный маг императора
Фантастика:
попаданцы
аниме
сказочная фантастика
фэнтези
5.00
рейтинг книги
Черный Маг Императора 13

Последняя Арена 4

Греков Сергей
4. Последняя Арена
Фантастика:
рпг
постапокалипсис
5.00
рейтинг книги
Последняя Арена 4

Маяк надежды

Кас Маркус
5. Артефактор
Фантастика:
городское фэнтези
попаданцы
аниме
5.00
рейтинг книги
Маяк надежды

Великий перелом

Ланцов Михаил Алексеевич
2. Фрунзе
Фантастика:
попаданцы
альтернативная история
5.00
рейтинг книги
Великий перелом

Сопротивляйся мне

Вечная Ольга
3. Порочная власть
Любовные романы:
современные любовные романы
эро литература
6.00
рейтинг книги
Сопротивляйся мне

Инквизитор Тьмы 2

Шмаков Алексей Семенович
2. Инквизитор Тьмы
Фантастика:
попаданцы
альтернативная история
аниме
5.00
рейтинг книги
Инквизитор Тьмы 2

Мастер Разума V

Кронос Александр
5. Мастер Разума
Фантастика:
городское фэнтези
попаданцы
5.00
рейтинг книги
Мастер Разума V

Бандит 2

Щепетнов Евгений Владимирович
2. Петр Синельников
Фантастика:
боевая фантастика
5.73
рейтинг книги
Бандит 2

Истребители. Трилогия

Поселягин Владимир Геннадьевич
Фантастика:
альтернативная история
7.30
рейтинг книги
Истребители. Трилогия

Гардемарин Ее Величества. Инкарнация

Уленгов Юрий
1. Гардемарин ее величества
Фантастика:
городское фэнтези
попаданцы
альтернативная история
аниме
фантастика: прочее
5.00
рейтинг книги
Гардемарин Ее Величества. Инкарнация

Падение Твердыни

Распопов Дмитрий Викторович
6. Венецианский купец
Фантастика:
попаданцы
альтернативная история
5.33
рейтинг книги
Падение Твердыни

"Дальние горизонты. Дух". Компиляция. Книги 1-25

Усманов Хайдарали
Собрание сочинений
Фантастика:
фэнтези
боевая фантастика
попаданцы
5.00
рейтинг книги
Дальние горизонты. Дух. Компиляция. Книги 1-25

Ох уж этот Мин Джин Хо 2

Кронос Александр
2. Мин Джин Хо
Фантастика:
попаданцы
5.00
рейтинг книги
Ох уж этот Мин Джин Хо 2

Энфис 6

Кронос Александр
6. Эрра
Фантастика:
героическая фантастика
рпг
аниме
5.00
рейтинг книги
Энфис 6