Главная » Просмотр файлов » 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), страница 25

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

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

This asynchronous method completes whenthe display has been updated, to indicate that the bitmap can be reusedto draw the next frame.3.7.4 A Waste of Time?One issue with waiting for synchronization is that the waiting time ispotentially wasted. The game cannot do any rendering to the directbitmap until its thread’s active scheduler has processed the request andcalled RunL(). It is not uncommon to ignore the vsync callback andtune the drawing code for the hardware.

Another solution is to use triplebuffering, so that there is another back buffer to render to, while thescreen refreshes. Triple buffering is usually a bit excessive in terms ofmemory, and it requires an extra blit.3.8 Pixel Color RepresentationsIn computer graphics, a bitmap is most commonly represented by a twodimensional array of picture elements (pixels) which can be presentedto an output device for display to a (human) viewer. Since bitmapsare usually closely tied to the display hardware, there are a plethoraof different formats. Mobile phones, like desktop PCs, have supporteda various screen sizes and color depths over the years. For example,the Psion Series 5 and Series 5MX devices (which were based on anantecedent of Symbian OS as it is today) used 4 and 16 shades of grayrespectively, whereas the latest smartphones support 18-bit or 24-bitcolor displays.PIXEL COLOR REPRESENTATIONS91Each pixel in a bitmap is a representation of the color that willultimately be displayed on a screen pixel.

This can either be an index toa palette entry (common with 256 or fewer color displays) or a vectorin a color space. The most common color spaces are grayscale intensity,RGB, or YUV. YUV is derived from television standards and is often usedas the output from video codecs and camera hardware, but is seldomused in games. Symbian OS graphics interfaces support indexed palettes,grayscale, and various RGB color modes, with RGB being, by far, themost common format used in games.Table 3.2 shows the different formats allowed for both screens andbitmaps.Table 3.2 Screen and bitmap display modes available on Symbian OSDisplayModeBits perpixel (bpp)NotesEGray2Monochrome displaymode (1 bpp).Chiefly used for binary masks (i.e.,one bit to denote if a pixel is opaqueor transparent).EGray4Four grayscalesdisplay mode (2 bpp).Not commonly used.EGray1616 grayscales displaymode (4 bpp).Not commonly used.EGray256256 grayscalesdisplay mode (8 bpp).Used primarily for alpha channelmasks, where 0–255 grayscalerepresents an increasing opacity.EColor16Low color EGA,16 color displaymode (4 bpp).Not commonly used.EColor256256 color displaymode (8 bpp).Websafe or Netscape palette, andintermediate gray levels.

Chieflyused with a palette when loadingicons and animated GIFs.EColor64K‘64,000’ 65536 colordisplay mode(16 bpp: RGB565).Native mode for 16 bpp display.(continued overleaf )92GRAPHICS ON SYMBIAN OSTable 3.2 (continued )DisplayModeBits perpixel (bpp)NotesEColor16MTrue color displaymode (24 bpp:RGB888).Not used in practice. It is morecompact than 16MU (3 bytes perpixel, rather than 4 bytes) but lessefficient to process as the number ofbits per pixel is not a power of 2.Displays rarely support its use.EColor4K4096 color display(12 bpp: XRGB4444).Native mode for 12 bpp displays(such as the Nokia 9210).EColor16MUTrue color displaymode (32 bpp:XRGB8888).Common display format for 18 bppand 24 bpp displays (but the top byteis unused and unspecified).

18 bpphardware takes the 24 bpp datawhich software produces and ditherson the fly/drop the two leastsignificant bits of each colorcomponent.EColor16MADisplay mode withalpha (32 bpp:ARGB8888 – 24 bppcolor plus 8 bppalpha).Only used for bitmaps with alphachannels which need to becombined with transparency onscreen.Note that the display mode of a bitmap in memory is independentof the screen. Graphics context functions such as BitBlit() willautomatically convert a bitmap to the depth of the target – be it anotherbitmap or the frame buffer.3.8.1 Bitmap Drawing (Blitting) PerformanceThe availability of different screen modes shown in Table 3.2 means thatdifferent depth bitmaps can be combined as they are drawn.

There isnothing stopping a game from storing tiles in 256 colors, blitting them toa 4K off-screen bitmap and then copying the bitmap to a 24 bpp display.Having said that, there is an implicit performance penalty when blittingfrom a source to a destination with a different depth. The penalty maybe significant, for example, when porting code which is optimized fora particular screen mode. In order to quantify the cost, a small profilingapp was written which:PIXEL COLOR REPRESENTATIONS93• creates a bitmap in each of the formats listed in the table above• blits the bitmap several times and takes the mean time for each displayformat.The results, shown in Figures 3.13 and 3.14, show the frames persecond achieved for each format on two different Symbian smartphones,the Nokia E61 and Nokia N95.6BitBlit speed in FPS on Nokia Devices from two segments800700600500E61N954003002001000EGray2EGray4EGray16EGray256EColor16ECoolr256ECoolr64KECoolr16MEColor4KCol1or6MUECol1or6MAFigure 3.13 Blit speed in fps for each bitmap format on hardwareBlit Speeds of different modes (S603.2 Emulator)2000180016001400120010008006004002000FPSy2raEG6y456y1raEGraEGEG616ory2raEColECK25orol6M64orEColr1ECoolgbER4KECAU6Morol1orolC6M1orolECFigure 3.14 Blit speed in fps for each bitmap format on the S60 3.2 emulator6I’ve discussed the results in an article called Blit speed and bitmap depth, which canbe found on my blog at twmdesign.co.uk/theblog/?p=52.94GRAPHICS ON SYMBIAN OSThe result that stands out from the data collected is that the defaultdisplay format for both the devices and the emulator is EColor16MU;the graphs clearly show a drastic performance increase when using thismode.

This leads to the following conclusions:• the bitmap depth should match the screen when performance is aconsideration• there is a trade off between memory and speed. Storing game tilesas 256 bpp index modes may use only one quarter of the memorycompared to the equivalent EColor16MU, but it takes almost threetimes as long to render• two devices from the same manufacturer may have radically differentperformances, depending on their hardware• the emulator is not reliable for realistic data about graphics performance. Figure 3.14 shows that the emulator is blitting approximately600 % faster in mode EColor16MU compared to the Nokia E61 (and260 % faster than the Nokia N95).3.8.2 Grayscale Images as MasksFor grayscale images, the pixel value is a single number that representsthe pixel’s brightness.

The most common pixel format is the byte image,where this number is stored as an 8-bit integer giving a range of possiblevalues from 0 to 255. Typically, zero is taken to be black, and 255taken to be white; values in between make up the different shades ofgray.Grayscale images (mode EGray256) are most commonly used asalpha masks for specifying transparency when using functions such asCBitmapContext::BitBltMasked().3.8.3 Access to the Bitmap DataA CFbsBitmap is a client-side handle to the actual bitmap residing inthe font and bitmap server’s heap. The font and bitmap server (known asFBServ for short) has two heaps: a small heap and a large heap.

Bitmaps ofless than 16 KB (previously 4 KB in Symbian OS v9.2 and earlier releases)are stored in the small heap, and bitmaps larger than this threshold arestored on the large heap.The reason for having two heaps is to make it easier for the system toreclaim space made available by an application freeing a large bitmapobject, by minimizing heap fragmentation.

Fragmentation occurs whenlarge bitmaps are de-allocated, leaving holes in the heap. SymbianPIXEL COLOR REPRESENTATIONS95OS currently only supports shrinking heaps from the end and, withoutdefragmentation, the memory ocupied by those holes effectively becomesunusable.To avoid potential waste, at certain safe points, FBServ will reclaim thememory by shuffling up the bitmaps on the large heap in order to fill anyholes. The memory committed to the heap can be reduced by shrinkingfrom the end.

The heap should be locked while pixel data is being reador manipulated, since the actual memory location of the pixel data mayotherwise change as the heap is defragmented.There are three ways of accessing the pixel data:• TBitmapUtil – safely reads and writes a pixel at a time• CFbsBitmap::GetScanLine()/SetScanLine() – copies ascan line into a buffer that can be accessed and modified before beingput back in the original• CFbsBitmap::DataAddress() – returns the memory location ofthe pixel data for direct manipulation of the bitmap in place.The first two methods are safe, since they lock the large heap ifnecessary, but they may not be as efficient for all bitmap manipulationtasks. Let’s consider each of the methods in more detail.TBitmapUtilRoids uses TBitmapUtil to draw single pixels onto the off-screenbitmap, as illustrated by Figure 3.15.

During development, I discoveredthat use of TBitmapUtil is negligible on the frame rate for plotting aFigure 3.15 Starburst from the game Roids are drawn using TBitmapUtil96GRAPHICS ON SYMBIAN OSthousand or fewer pixels. But I found it to be too slow when processingentire frames or bitmaps in real time.void CRoidsContainer::DrawBackgroundStars(CWsBitmap& aBitmap) const{TBitmapUtil bUtil(&aBitmap);TDisplayMode display = iEikonEnv->DefaultDisplayMode();bUtil.Begin(TPoint(0,0));for(TInt i=0; i<EMaxStars; i++){TPoint point(iStars[i].iX, iStars[i].iY);bUtil.SetPos(point);TInt gray = i%200 + 55; // A simple calculation to vary the colorTRgb rgb(gray,gray,gray);bUtil.SetPixel(rgb._Color16MU());}bUtil.End();}Note that code must explicitly deal with different color depths whensetting a pixel value.

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

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

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

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