Windows API Tutorials

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

Windows API Tutorials: краткое содержание, описание и аннотация

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

Windows API Tutorials — читать онлайн бесплатно полную книгу (весь текст) целиком

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

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

Интервал:

Закладка:

Сделать

_world = world;

// Set coopration with Windows

_draw. SetCoopNormal(h);

}

Back surface is created (and re-created) in response to WM_SIZE message. Surfaces are implemented in such a way that regular assignment operation does the right thing. It deallocates the previous surface and initializes a new one. Notice that the constructor of an OffScreenSurface takes the Direct::Draw object and the dimensions of the surface in pixels.

void View::Size (HWND h, int width, int height) {

_dx = width;

_dy = height;

if (_dx == 0 || _dy == 0) return;

_backSurface = Direct::OffScreenSurface(_draw, _dx, _dy);

}

Painting is slightly tricky. We have to get access to the primary drawing surface, which is the whole screen buffer. But since we are not using the full-screen mode, we want to draw only inside the rectangular area of our window. That's why we create a Direct::Clipper, to clip anything that would fall outside of that area. The clipper figures out the correct area using the handle to the window that we are passing to it.

Next, we create the primary surface and pass it the clipper. Now we can blit the image directly from our back surface to the screen. Again, since the primary surface represents the whole screen, we have to offset our blit by specifying the target rectangle. The auxillary class Direct::WinRect retrieves the coordinates of that rectangle.

void View::Paint (HWND h) {

if (_dx == 0 || _dy == 0) return;

// Clip to window

Direct::Clipperclipper (_draw);

clipper.SetHWnd (h);

// Screen surface

Direct::PrimarySurfacesurf (_draw);

surf.SetClipper (clipper);

Direct::WinRectrect (h);

// Blit from back surface to screen

surf. BltFrom(_backSurface, &rect);

}

Finally, the actual drawing is done using direct access to the back surface buffer. But first, we flood the back surface with white background. Then we construct the Direct::SurfaceBuf. This is the object that let's us set pixels directly into the buffer's memory (depending on implementation, it might be your video card memory or a chunk of your system memory). The details of our drawing algorithm are inessential here. Suffice it to say that the work of setting the pixel is done in the SetPixel method.

void View::Update () {

if (_dx == 0 || _dy == 0) return;

try {

// white background

_backSurface. Fill(RGB (255, 255, 255));

{

// Get direct access to back surface

Direct::SurfaceBufbuf (_backSurface);

// draw bitmap within a centered square

int side = 100;

if (_dx < side) side = _dx;

if (_dy < side) side = _dy;

int xOff = (_dx - side) / 2;

int yOff = (_dy - side) / 2;

assert (xOff >= 0);

assert (yOff >= 0);

double dxInv = 1.0 / side;

double dyInv = 1.0 / side;

for (int i = 0; i < side; ++i) {

for (int j = 0; j < side; ++j) {

double u = dxInv * i;

double v = dyInv * j;

COLORREF color = _world->GetTexel (u, v);

// draw pixel directly

buf. SetPixel(xOff + i, yOff + j, color);

}

}

}

// Paint will blit the image to screen

}

catch (char const * msg) {

::MessageBox (0, msg, "Viewer error", MB_OK | MB_ICONERROR);

throw;

}

catch (...) {

::MessageBox (0, "Unknown error", "Viewer error", MB_OK | MB_ICONERROR);

throw;

}

}

Besides being able to set individual pixels quickly, DirectX also provides ways to efficiently blit bitmaps or even use GDI functions to write to a surface.

Implementation

As mentioned before, all DirectDraw objects are enclosed in the Direct namespace. The fundamental object, Direct::Draw, is responsible for the initialization and the release of the DirectDraw subsystem. It can also be used to set up the cooperation level with Windows. It's easy to add more methods and options to this class, as the need arises.

namespace Direct { // Direct Draw object

class Draw {

public:

Draw ();

~Draw () {

_pDraw->Release ();

}

void SetCoopNormal (HWND h) {

HRESULT res = _pDraw->SetCooperativeLevel(h, DDSCL_NORMAL);

if (res != DD_OK) throw "Cannot set normal cooperative level";

}

IDirectDraw * operator-> () { return _pDraw; }

private:

IDirectDraw * _pDraw;

};

}

// implementation file

using namespace Direct;

Draw::Draw () {

HRESULT res = ::DirectDrawCreate (0, &_pDraw, 0);

if (res != DD_OK) throw "Cannot create Direct Draw object";

}

DirectDraw is based on COM interfaces, so it makes sense to encapsulate the "interface magic" in a handy template. The Direct::IFace class takes care of reference counting, pointer dereferencing and assignment (see the assignment of surfaces above).

template

class IFace {

public:

IFace (IFace & i) {

i->AddRef ();

_i = i._i;

}

~IFace () {

if (_i) _i->Release ();

}

void operator = (IFace & i) {

if (i._i) i._i->AddRef ();

if (_i) _i->Release ();

_i = i._i;

}

I * operator-> () { return _i; }

operator I * () { return _i; }

protected:

IFace () : _i (0) {}

protected:

I * _i;

};

A drawing surface is an example of an interface. First we define a generic surface, then we'll specialize it to primary and off-screen surfaces.

class Surface: public IFace {

friend class SurfaceBuf;

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

Интервал:

Закладка:

Сделать

Похожие книги на «Windows API Tutorials»

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


Отзывы о книге «Windows API Tutorials»

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

x