LibKing » Книги » comp-programming » Сергей Ваткин - DirectX 8. Начинаем работу с DirectX Graphics

Сергей Ваткин - DirectX 8. Начинаем работу с DirectX Graphics

Тут можно читать онлайн Сергей Ваткин - DirectX 8. Начинаем работу с DirectX Graphics - бесплатно полную версию книги (целиком). Жанр: comp-programming. Здесь Вы можете читать полную версию (весь текст) онлайн без регистрации и SMS на сайте LibKing.Ru (ЛибКинг) или прочесть краткое содержание, предисловие (аннотацию), описание и ознакомиться с отзывами (комментариями) о произведении.
libking
  • Название:
    DirectX 8. Начинаем работу с DirectX Graphics
  • Автор:
  • Жанр:
  • Издательство:
    неизвестно
  • Год:
    неизвестен
  • ISBN:
    нет данных
  • Рейтинг:
    4/5. Голосов: 81
  • Избранное:
    Добавить в избранное
  • Ваша оценка:

Сергей Ваткин - DirectX 8. Начинаем работу с DirectX Graphics краткое содержание

DirectX 8. Начинаем работу с DirectX Graphics - описание и краткое содержание, автор Сергей Ваткин, читайте бесплатно онлайн на сайте электронной библиотеки LibKing.Ru

DirectX 8. Начинаем работу с DirectX Graphics - читать онлайн бесплатно полную версию (весь текст целиком)

DirectX 8. Начинаем работу с DirectX Graphics - читать книгу онлайн бесплатно, автор Сергей Ваткин
Тёмная тема

Шрифт:

Сбросить

Интервал:

Закладка:

Сделать
The Code

Now that we've got that out of the way, we can get down and dirty with some actual code! Let's start off with this:

#define WIN32_LEAN_AND_MEAN

#include

#include "dxutil.h"

#include "ddutil.h"

Standard procedure here. We #define WIN32_LEAN_AND_MEAN, so all that icky MFC stuff doesn't bloat our program (just a good practice if you aren't using MFC). Then we include dxutil.h, and ddutil.h, the two centerpieces of this article. They provide shortcut classes to make programming with DirectX in general less taxing.

//globals

bool g_bActive = false;

CDisplay *g_pDisplay = NULL;

CSurface *g_pText = NULL;

//function prototypes

bool InitDD(HWND);

void CleanUp();

void GameLoop();

Pretty self explanatory. Our first global, g_bActive, is a flag to let our application know whether or not it's okay to run the game. If we didn't have this flag, our application could potentially attempt to draw something onto our DirectDraw surface after it's been destroyed. While this is usually a problem at the end of the program where it isn't that big of a deal, it generates an illegal operation error, and we don't want that, now do we? g_pDisplay is our display object. CDisplay is the main class in ddutil. It holds our front and back buffers, as well as functionality for accessing them, drawing surfaces onto them, creating surfaces, etc. g_pText is our text surface. We will draw text onto this surface (as you've probably figured out), and blit it onto our screen. Note how both objects are pointers, and are initialized to NULL.

Now for the function prototypes. InitDD() simply initializes DirectDraw. Thanks to the DDraw Common Files, this is a fairly simple procedure (but we'll get to that later). CleanUp() calls the destructor to our g_pDisplay object, which essentially shuts down DDraw, and cleans up all of our surfaces. GameLoop() is obviously where you'd put your game.

LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {

switch(uMsg) {

case WM_CREATE:

InitDD(hWnd);

g_bActive=true;

break;

case WM_CLOSE:

g_bActive=false;

CleanUp();

DestroyWindow(hWnd);

break;

case WM_DESTROY:

PostQuitMessage(0);

break;

case WM_MOVE:

g_pDisplay->UpdateBounds();

break;

case WM_SIZE:

g_pDisplay->UpdateBounds();

break;

default:

return DefWindowProc(hWnd, uMsg, wParam, lParam);

break;

}

return 0;

}

Standard Windows Procedure function here. On the WM_CREATE event, we initialize DirectDraw, and set our g_bActive flag to true, so our GameLoop() function is executed. When WM_CLOSE is called, we want to set our active flag to false (again, so our app doesn't try to draw to our DDraw screen after its been destroyed), then call our CleanUp() function, and finally destroy our window. It's important that you handle the WM_MOVE and WM_SIZE events, because otherwise DirectDraw will not know the window has been moved or resized and will continue drawing in the same position on your screen, in spite of where on the screen the window has moved.

bool InitDD(HWND hWnd) {

//dd init code

g_pDisplay = new CDisplay();

if (FAILED(g_pDisplay->CreateWindowedDisplay(hWnd, 640, 480))) {

MessageBox(NULL, "Failed to Initialize DirectDraw", "DirectDraw Initialization Failure", MB_OK | MB_ICONERROR);

return false;

}

return true;

}

The infamous InitDD() function… but wait, it's only several lines! This is what the common libs were made for! We now have all the DirectDraw setup garbage out of the way, effortlessly! Again, you'll notice that it's done a lot for you. If you don't really care to know the exact procedure of what has been abstracted from you, at least get the gist of it. It will help out if you have to go back and change the cooperative level or whatnot. Note that this is a boolean function, so if you like, you can do error checking (which I, for some reason or another, decided to omit in this article).

void CleanUp() {

SAFE_DELETE(g_pDisplay);

}

Simple enough. This function calls on the SAFE_DELETE macro defined in dxutil to delete our display object, and call the destructor.

void MainLoop() {

g_pDisplay->CreateSurfaceFromText(&g_pText, NULL, "DDraw using Common Files", RGB(0,0,0), RGB(0,255,0));

g_pDisplay->Clear(0);

g_pDisplay->Blt(0, 0, g_pText, 0);

g_pDisplay->Present();

g_pText->Destroy();

}

This is where you'd want to put your game. In order to give you an example of how surface objects work, we've made a simple text surface and drawn some text onto it. Note that we destroy g_pText at the end, because it is recreated every cycle and not doing so would eventually eat up quite a bit of memory.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int iShowCmd) {

WNDCLASSEX wc;

HWND hWnd;

MSG lpMsg;

wc.cbClsExtra=0;

wc.cbSize=sizeof(WNDCLASSEX);

wc.cbWndExtra=0;

wc.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);

wc.hCursor=LoadCursor(NULL, IDC_ARROW);

wc.hIcon=LoadIcon(NULL, IDI_APPLICATION);

wc.hIconSm=LoadIcon(NULL, IDI_APPLICATION);

wc.hInstance=hInstance;

wc.lpfnWndProc=WndProc;

wc.lpszClassName="wc";

wc.lpszMenuName=0;

wc.style=CS_HREDRAW | CS_VREDRAW;

if (!RegisterClassEx(&wc)) {

MessageBox(NULL, "Couldn't Register Window Class", "Window Class Registration Failure", MB_OK | MB_ICONERROR);

return 0;

}

hWnd = CreateWindowEx(NULL, "wc", "DirectDraw Common Files in Action", WS_POPUPWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 640, 480, 0, 0, hInstance, 0);

if (hWnd == NULL) {

MessageBox(NULL, "Failed to Create Window", "Window Creation Failure", MB_OK | MB_ICONERROR);

return 0;

}

ShowWindow(hWnd, SW_SHOW);

UpdateWindow(hWnd);

while (lpMsg.message != WM_QUIT) {

if(PeekMessage(&lpMsg, 0, 0, 0, PM_REMOVE)) {

TranslateMessage(&lpMsg);

DispatchMessage(&lpMsg);

} else if(g_bActive) {

MainLoop();

}

}

return lpMsg.wParam;

}

The longest function in our application, WinMain(). As usual, we setup our window class, create our window, show and update it, and go into the message loop. The loop is different from usual because we dont want the processing of our game to interfere with the processing of messages. We use our g_bActive flag to see if its safe to call our game loop, which involves blitting things onto the screen, and at the end of it all we finally return lpMsg.wParam (I'm honestly not sure why, but thats how it's done in every other Win32 app, so oh well).

Pretty simple, huh? 135 lines of code and we're already blitting stuff to the screen. Feel free to explore these classes further, and experiment with things like color keying, loading surfaces from bitmaps, ect. This is a very cool shortcut to using DDraw. It makes things easy without sacrificing control (you can always go back and edit the classes if you want) or performance. One thing to note is that on my computer if I don't draw anything onto the screen using this framework, the application will lock up (which is why I've included text output here). This shouldn't be much of an issue, seeing as how your game will more than likely be blitting things onto the screen (unless there's some new art style which I'm not aware of).

Have fun!

Разработка графического движка

#1: Введение

Автор: Константин "Dreaddog" Поздняков
Об авторе

Константин Поздняков заканчивает Кемеровский Государственный Университет на кафедре ЮНЕСКО по НИТ. Его диплом достаточно тесно связан с трехмерной графикой и Direct3D в частности. Разрабатывает свой собственный движок. Недавно получил статус MCP (Microsoft Certified Professional) по Visual C++ 6 Desktop. Разработкой игр занимается очень серьезно, планирует связать свою карьеру именно с игровым трехмерным программированием.

Составляющие Игрового Графического Движка

Эта статья ставит своей целью описать (по возможности наиболее полно) возможности игрового движка современного уровня. Я попытался классифицировать потребности в реализации, требуемой от программиста. Здесь не обсуждаются подробно реализации каждого конкретного элемента. Этому будут посвящены следующие статьи, а не этот обзор.

Современный игровой движок должен уметь:

1. Рисовать интерфейс.

2. Рисовать курсор.

3. Рисовать сцену.

Это те пункты, которые касаются графической части, а кроме того:

4. Использовать файл настроек для инициализации.

5. Проводить проверку состояния устройства и выдавать ошибку при их несоблюдении.

6. Современный графический движок не должен в реальном времени изменять параметры устройства или режим работы (оконный/полноэкранный).

7. Уметь загружать файлы из сжатого файла, причем делать это асинхронно.

8. Вести файл протокола.

9. Уметь в реальном времени изменять параметры, не требующие изменения устройства.

10. Контролировать ошибки и правильно их обходить.

11. Корректно чистить после себя при загрузке дополнительной информации.

Читать дальше
Тёмная тема

Шрифт:

Сбросить

Интервал:

Закладка:

Сделать


Сергей Ваткин читать все книги автора по порядку

Сергей Ваткин - все книги автора в одном месте читать по порядку полные версии на сайте онлайн библиотеки LibKing.




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


Отзывы читателей о книге DirectX 8. Начинаем работу с DirectX Graphics, автор: Сергей Ваткин. Читайте комментарии и мнения людей о произведении.


Понравилась книга? Поделитесь впечатлениями - оставьте Ваш отзыв или расскажите друзьям

Напишите свой комментарий
Большинство книг на сайте опубликовано легально на правах партнёрской программы ЛитРес. Если Ваша книга была опубликована с нарушениями авторских прав, пожалуйста, направьте Вашу жалобу на PGEgaHJlZj0ibWFpbHRvOmFidXNlQGxpYmtpbmcucnUiIHJlbD0ibm9mb2xsb3ciPmFidXNlQGxpYmtpbmcucnU8L2E+ или заполните форму обратной связи.
img img img img img