Главная » Просмотр файлов » Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008

Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888), страница 24

Файл №779888 Wiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (Symbian Books) 24 страницаWiley.Games.on.Symbian.OS.A.Handbook.for.Mobile.Development.Apr.2008 (779888) страница 242018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 24)

Pageflipping allows the CPU to startmodifying the pixel data in theback buffer as soon as the flipoccurs but, once the CPU hasfinished drawing to the backbuffer, it must wait for the verticalblank before it can continue.Page flipping may beimplemented on specifichardware versions ofCDirectScreenBitmap.3.7.2 The Off-screen Bitmap TechniqueThe most common and portable technique for double buffering is to usean off-screen bitmap (also known as a back buffer) owned by the game.The off-screen bitmap is where the background, tiles, and elements suchDOUBLE BUFFERING AND ANTI-TEARING85as high score are combined for each frame and then copied to the screenin one go.

The process of copying is often referred to as a ‘blit’.The following code shows how the game Roids, shown in Figure 3.9,creates an off-screen bitmap and a graphics context that allows all theusual drawing commands, such as line, fill, and blit, to be executed onthe off-screen buffer rather than in the window.Figure 3.9Roids makes use of an off-screen bitmapThe off-screen bitmap is stored in the variable iBackupBitmap ofthe game’s CONE control object, and is of type CWsBitmap, a classwhich specializes CFbsBitmap so that the underlying bitmap data canbe efficiently shared between the client and WSERV. It’s not mandatory touse CWsBitmap, but it’s faster than CFbsBitmap when using a windowgraphics context.iBackupBitmap = new (ELeave) CWsBitmap(iCoeEnv->WsSession());error=iBackupBitmap->Create(Rect().Size(),iEikonEnv->DefaultDisplayMode());Two more member variables, iBitmapDevice and iBitmapGc arerequired in order to establish a graphics context over the bitmap.iBitmapDevice = CFbsBitmapDevice::NewL(iBackupBitmap);User::LeaveIfError(iBitmapDevice->CreateContext(iBitmapGc));Once successfully created, iBitmapGc can now be drawn to insteadof SystemGc().

When the game model changes, the bitmap can beupdated and a DrawNow() command issued to the control. The CONEdrawing code is very simple since all it has to do is copy any invalidatedregions of the CCoeControl straight from the bitmap.86GRAPHICS ON SYMBIAN OSvoid CRoidsContainer::Draw(const TRect& aRect) const{CWindowGc& gc=SystemGc();gc.BitBlt(aRect.iTl, iBackupBitmap, aRect);}A good tip when creating drawing code is to divide the drawing ofindividual elements into methods which take a CGraphicsContextrather than using a specific GC.

This approach ensures that the graphicscontext can easily be varied, which is useful for switching between singleand double buffering to help debug drawing code. If you have a lot ofexisting code, it’s possible to use CCoeControl::SetGc() to divertcalls to SystemGc() to the off-screen bitmap.The Roids code extract below shows how a function can be structuredto draw to an arbitrary graphics context.void CRoidsContainer::DrawExplosionParticle(CGraphicsContext& aGc,const TExplosionFragment& aFragment) const{const MPolygon& shape = aFragment.DrawableShape();TInt gray = 255-aFragment.Age();aGc.SetPenColor(TRgb(gray, gray, gray));aGc.DrawLine(shape.PolyPoint(0), shape.PolyPoint(1) );}3.7.3 TearingTearing occurs when the contents of the screen is refreshed part waythrough drawing the next frame of animation, which is clearly undesirable.Tearing appears on-screen as a horizontal discontinuity between twoframes of an animation, as illustrated in Figure 3.10.

The applicationhas drawn frame n-1 and the display hardware is part way throughFigure 3.10 Example of two game frames appearing half and half, causing noticeabletearingDOUBLE BUFFERING AND ANTI-TEARING87refreshing the frame buffer when the application begins to render framen. A synchronization step is missing which results in a page tearing effect.If significant, the tearing can be very distracting to a player andultimately can contribute to eye strain or fatigue. To avoid tearing andprovide smooth updates, the display must be synchronized. For smoothrendering of graphics without any tearing artefacts, all changes to theframe buffer should be done during the short period after the display hasbeen refreshed and before the next refresh.Anti-tearing API OverviewLibrary to link againstscdv.libHeader to includecdsb.hRequired platform security capabilities NoneKey classesCDirectScreenBitmap,TAcceleratedBitmapInfoSymbian OS provides an API called CDirectScreenBitmap, whichprovides double buffering which (depending on the phone hardware) maybe synchronized to the LCD controller.

It’s often called the anti-tearingAPI since it’s the only documented way to synchronize screen updateswith the LCD display. It’s most commonly used for video rendering andhigh speed graphics.5 The Roids example uses the API as shown inFigure 3.11. The mechanism works like this:1. The game opens a DSA session with the window server as describedin section 3.6.2. The game asks for a CDirectScreenBitmap object for a portionof the screen (a rectangle).3. The game tells the API when the bitmap has finished being drawn toand asynchronously requests for it to be displayed.4. The game gets called back on the next ‘vsync’ and can start modifyingthe bitmap data again.5.

Loop to 3.5CDirectScreenBitmap relies on a specific implementation to be present on thetarget hardware. For a given device, there is no guarantee that such an implementation isavailable.88GRAPHICS ON SYMBIAN OSCActiveiStatus :TRequestStatusRunL() : void<<interface>>MDirectScreenAccess1Restart() : voidAbortNow() : void<<realize>>1CDirectScreenAccessCGfxDirectScreenBitmap11iDirectScreenAccess :CDirectScreenAccessiDSBitmap : CDirectScreenBitmapiWindow : RWindowStartL(aRect : TRect) : voidStopL() : voidBeginDraw():TAcceleratedBitmapInfoProcessFrame() : voidStartL() : voidGc() : CFbsBitGcScreenDevice() : CFbsScreenDeviceCDirectScreenBitmap11EndUpdate(aStatus : TRequestStatus) : voidBeginUpdate(aHardwareBitmap : TAcceleratedBitmapInfo) : voidCreate(aScreenRect : TRect) : voidFigure 3.11 Simplified representation of the direct screen bitmap example classOne thing to note is that, in using CDirectScreenBitmap, the LCDcontroller takes control of refreshing the display at the right moment.This may vary from device to device and will be dependent on the LCDdisplay refresh rate, so it’s not wise to use a game tick timer.

It’s alsoworth mentioning that the callback is not guaranteed to occur on thenext vertical sync, since other higher priority threads may pre-empt theapplication at any time.Initializing the bitmap is very simple when used with a DSA session.All that’s required is the rectangle representing the portion of screenwhich will be drawn directly.void CGfxDirectScreenBitmap::StartL(TRect& aRect){iControlScreenRect = aRect;User::LeaveIfError(iDSBitmap->Create(iControlScreenRect,CDirectScreenBitmap::EDoubleBuffer));//Initialize DSAiDirectScreenAccess -> StartL();ProcessFrame();}Each time the bitmap needs to be updated, the BeginUpdate()function must be called, which returns the bitmap information andmemory address of the bitmap area.TAcceleratedBitmapInfo CGfxDirectScreenBitmap::BeginDraw(){TAcceleratedBitmapInfo bitmapInfo;iDSBitmap->BeginUpdate(bitmapInfo);return bitmapInfo;}DOUBLE BUFFERING AND ANTI-TEARINGFigure 3.1289Manipulation of the display pixels using direct bitmapIn this simple example, ProcessFrame() gets the address of thebitmap and writes some RGB values directly into the bitmap data – theresulting output is shown in Figure 3.12.

The code is similar to the DSAexample described in section 3.6, but, this time, the bitmap coordinatesstart from coordinate (0,0). Note that the following code assumes a 24 bitsper pixel (bpp) bitmap with each pixel stored in 32 bits.void CGfxDirectScreenBitmap::ProcessFrame(){TAcceleratedBitmapInfo bmpInfo = BeginDraw();TUint32* lineAddress = (TUint32*)bmpInfo.iAddress;TInt width = bmpInfo.iSize.iWidth;TInt height = bmpInfo.iSize.iHeight;// Code assumes 4 byte wordsconst TInt rowWidthInWords = bmpInfo.iLinePitch>>4;TInt y=height;while(--y){TUint32* p=lineAddress;for(TInt x=0; x<width; x++){TRgb rgb(255,(x+iFrameCounter)%64 <<2,(y+(iFrameCounter/2))%64 << 2, 0);*(p++)=rgb._Color16MU();}lineAddress += rowWidthInWords; //}go to next row90GRAPHICS ON SYMBIAN OSiFrameCounter++;EndDraw();}All drawing is done to the back buffer and nothing is reflected onscreen until the call to: EndDraw().void CGfxDirectScreenBitmap::EndDraw(){if(IsActive()){Cancel();}iDSBitmap->EndUpdate(iStatus);SetActive();}CDirectScreenBitmap::EndUpdate(iStatus) starts the operation to update the screen.

Характеристики

Тип файла
PDF-файл
Размер
2,71 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6455
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее