Читаем DirectX 8. Начинаем работу с DirectX Graphics полностью

This article describes how to setup DirectDraw displays and surfaces with minimal effort using the common libs included in the DirectX SDK. This can be particularly helpful for those who want a quick way of doing things, while still maintining control of their application's basic framework. Please note the fact that these classes abstract quite a few things, and I highly recommend peering into their functions at some point to see how things are done on a lower level.

Setting it Up

For this article, I'm assuming you have Microsoft Visual C++, and the DirectX 8.1 SDK. If not, please adapt to portions of this article accordingly. Anyway, start up Visual C++, and create a new Win32 Application project. Then go into your DirectX SDK's samples\multimedia\common\include directory, and copy dxutil.h and ddutil.h to your project folder. Then go to samples\multimedia\common\src, and do the same with dxutil.cpp, and ddutil.cpp. Add the four files to your project, and link to the following libraries: dxguid.lib, ddraw.lib, winmm.lib. Now, you create a new C++ source file document, and add it to your project as well. This will be the file we'll work with throughout the tutorial.

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))) {

Перейти на страницу:

Похожие книги

Основы программирования в Linux
Основы программирования в Linux

В четвертом издании популярного руководства даны основы программирования в операционной системе Linux. Рассмотрены: использование библиотек C/C++ и стан­дартных средств разработки, организация системных вызовов, файловый ввод/вывод, взаимодействие процессов, программирование средствами командной оболочки, создание графических пользовательских интерфейсов с помощью инструментальных средств GTK+ или Qt, применение сокетов и др. Описана компиляция программ, их компоновка c библиотеками и работа с терминальным вводом/выводом. Даны приемы написания приложений в средах GNOME® и KDE®, хранения данных с использованием СУБД MySQL® и отладки программ. Книга хорошо структурирована, что делает обучение легким и быстрым. Для начинающих Linux-программистов

Нейл Мэтью , Ричард Стоунс , Татьяна Коротяева

ОС и Сети / Программирование / Книги по IT
97 этюдов для архитекторов программных систем
97 этюдов для архитекторов программных систем

Успешная карьера архитектора программного обеспечения требует хорошего владения как технической, так и деловой сторонами вопросов, связанных с проектированием архитектуры. В этой необычной книге ведущие архитекторы ПО со всего света обсуждают важные принципы разработки, выходящие далеко за пределы чисто технических вопросов.?Архитектор ПО выполняет роль посредника между командой разработчиков и бизнес-руководством компании, поэтому чтобы добиться успеха в этой профессии, необходимо не только овладеть различными технологиями, но и обеспечить работу над проектом в соответствии с бизнес-целями. В книге более 50 архитекторов рассказывают о том, что считают самым важным в своей работе, дают советы, как организовать общение с другими участниками проекта, как снизить сложность архитектуры, как оказывать поддержку разработчикам. Они щедро делятся множеством полезных идей и приемов, которые вынесли из своего многолетнего опыта. Авторы надеются, что книга станет источником вдохновения и руководством к действию для многих профессиональных программистов.

Билл де Ора , Майкл Хайгард , Нил Форд

Программирование, программы, базы данных / Базы данных / Программирование / Книги по IT
Программист-прагматик. Путь от подмастерья к мастеру
Программист-прагматик. Путь от подмастерья к мастеру

Находясь на переднем крае программирования, книга "Программист-прагматик. Путь от подмастерья к мастеру" абстрагируется от всевозрастающей специализации и технических тонкостей разработки программ на современном уровне, чтобы исследовать суть процесса – требования к работоспособной и поддерживаемой программе, приводящей пользователей в восторг. Книга охватывает различные темы – от личной ответственности и карьерного роста до архитектурных методик, придающих программам гибкость и простоту в адаптации и повторном использовании.Прочитав эту книгу, вы научитесь:Бороться с недостатками программного обеспечения;Избегать ловушек, связанных с дублированием знания;Создавать гибкие, динамичные и адаптируемые программы;Избегать программирования в расчете на совпадение;Защищать вашу программу при помощи контрактов, утверждений и исключений;Собирать реальные требования;Осуществлять безжалостное и эффективное тестирование;Приводить в восторг ваших пользователей;Формировать команды из программистов-прагматиков и с помощью автоматизации делать ваши разработки более точными.

А. Алексашин , Дэвид Томас , Эндрю Хант

Программирование / Книги по IT