quick_recipes (779892), страница 41

Файл №779892 quick_recipes (Symbian Books) 41 страницаquick_recipes (779892) страница 412018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

That’s not a typo.You may have to modify the heap memory where the bitmap data isstored, rotating colors for each pixel, which means your CFbsBitmapbecomes pretty much unusable afterwards. Do not keep your bitmapheap locked when calling eglSwapBuffers or it may block.Tip: After glTexImage2D returns, the OpenGL ES implementation ismeant to have made a copy of all the pixel data so your CFbsBitmapobject can be released.

Using a JPEG texture instead of a multi-bitmapfile will reduce the application footprint but will require an extraasynchronous step with a CImageDecoder. See Recipe 4.5.2.1 formore information.4.6.4.2Part-Screen SetupAmount of time required: 50 minutesLocation of example code: \3D\PartScreenRequired libraries: libgles_cm.libRequired header file(s): GLES\egl.hRequired platform security capability(s): NoneProblem: You want to share the screen between 2D and 3D graphics.Solution: Instead of an RWindow object we are going to initialize ourOpenGL ES surface with a dynamic CWsBitmap (see the 2D graphics230SYMBIAN C++ RECIPESrecipes in Section 4.5 for more about this class). This approach is a goodway to control the size of what OpenGL ES considers to be the screen.Once the scene has been rendered to the CWsBitmap, it can bedisplayed just like any other 2D object, alongside CCoeControl objects.In this example, we rely on the application view to be a compoundcontrol, only allowing our 3D control to use the bottom half of thescreen.#include <W32STD.H> // and link to ws32.libclass CMyMainControl : public CCoeControl{private:void MakeSurfaceL(const TRect&, TDisplayMode);CWsBitmap* iPixmap;};const EGLint attrib_list[] = {EGL_BUFFER_SIZE, 32,EGL_SURFACE_TYPE, EGL_PIXMAP_BIT, EGL_NONE};void CMyMainControl::MakeSurfaceL(const TRect& aRect,TDisplayMode aMode){iPixmap = new (ELeave) CWsBitmap(iCoeEnv->WsSession());TSize halfScreen = Window().Size();halfScreen.iHeight /= 2;iPixmap->Create(halfScreen, aMode);iEglSurface = eglCreatePixmapSurface(iEglDisplay, iEglConfig,iPixmap, NULL);if ( iEglSurface == NULL ){User::Leave(KErrGeneral);}}void CMyMainControl::SizeChanged(){// Resize the image.TInt error = iPixmap->Resize(Window().Size());// You may want to display an error warning here.glViewport( 0, 0, Size().iWidth, Size().iHeight );}void CMyMainControl::Draw(const TRect& /*aRect*/ ) const{CWindowGc& gc = SystemGc();gc.BitBlt(TPoint(0,0), iPixmap);}What may go wrong when you do this: Resizing the bitmap couldraise issues with the OpenGL ES implementation so you may have torecreate the EGLSurface.

A code sample to illustrate this approach willbe included in the downloadable code package.3D GRAPHICS USING OPENGL ES231What may (also) go wrong when you do this: Handsets with hardwareaccelerated OpenGL ES implementations (e.g., Nokia N95, MotorolaMOTORIZR Z8) may not support bitmap surfaces. The alternativewould be to draw only parts of an RWindow surface or use a muchslower pBuffer surface. See the \3D\PartScreenAlternatecode sample for illustration.4.6.5 Advanced Recipes4.6.5.1Animate a SceneAmount of time required: 90 minutesLocation of example code: \3D\animateRequired libraries: libgles_cm.libRequired header file(s): GLES\egl.hRequired platform security capability(s): NoneProblem: You want to animate a 3D object (that is, to make it move).Solution: Animation in OpenGL ES is done by drawing the scene severaltimes per second, modifying it a little bit every time.

You can use anactive object that regenerates its own request completion to continuouslytrigger redraw events (Chapter 3 described how to use active objects andactive schedulers).Using a CPeriodic object is the most basic way of animating anOpenGL ES scene, but you can also write your own active objects toobtain finer control over the perceived speed of different 3D objects inyour scene. We will create an RTimer object for this purpose.The following code sample illustrates both techniques to perform twodifferent transformations at different speeds.Tip: A little trick is used in this example. Since we want to see a cyclicanimation, we use translation along the perimeter of an imaginarycircle on the screen.

That is why the iTranslateBy member variablein the sample below actually contains an angle.// Timer expires at this interval (in microseconds)const TInt KInterval = 500000;class CMyMainControl : public CCoeControl{public:static TInt DrawCallBack(TAny*);TInt TranslateBy() const;void SetTranslateBy(TInt);232SYMBIAN C++ RECIPESvoid RenderScene();private:CPeriodic* iRotator;CModifier* iModifier;TInt iTranslateBy;TInt iRotateBy;};class CModifier : public CActive{public:static CModifier* NewL(); // Implementation omitted for clarity∼CModifier();void Start();private:void RunL();void DoCancel();private:CModifier(CMyMainControl& aToModify);private:RTimer iTimer;CMyMainControl& iToModify;};CModifier::CModifier(CAnimatedControl& aToModify):CActive(CActive::EPriorityStandard), iToModify(aToModify){iTimer.CreateLocal();CActiveScheduler::Add(this);}CModifier::∼CModifier(){iTimer.Cancel();iTimer.Close();}void CModifier::Start(){iTimer.After(iStatus, KInterval);SetActive();}void CModifier::DoCancel(){iTimer.Cancel();}void CModifier::RunL(){TInt translate = iToModify.TranslateBy();if (translate >= 350){iToModify.SetTranslateBy(0);}else{iToModify.SetTranslateBy(translate + 10);3D GRAPHICS USING OPENGL ES233}// we will let the CPeriodic update the displayStart();}const TInt KSecondInterval = 100000;void CMyMainControl::ConstructL(const TRect& aRect){iRotator = CPeriodic::NewL( CActive::EPriorityIdle );iRotator->Start(KSecondInterval, KSecondInterval,TCallBack(CMyMainControl::DrawCallBack,this));iModifier = new (ELeave) CModifier(*this);iModifier->Start();}TInt CMyMainControl::DrawCallBack( TAny* aInstance ){CMyMainControl* instance = (CMyMainControl*) aInstance;instance->iRotateBy++;instance->RenderScene();return KErrNone;}void CMyMainControl::RenderScene(){GLubyte triangle [3 * 3] = {1,1,0, /**/ 0,1,0, /**/ 1,0,0};GLfloat xTranslate, yTranslate;xTranslate = 2.0f * FindCosine(iTranslateBy);yTranslate = 2.0f * FindSine(iTranslateBy);glEnableClientState( GL_VERTEX_ARRAY );glVertexPointer( 3, GL_BYTE, 0, triangles );glLoadIdentity();glPushMatrix();glRotatex( (iRotateBy / 2) << 16 , 1 << 16 , 0 , 0 );glRotatex( (iRotateBy / 3) << 16 , 0 , 1 << 16 , 0 );glTranslatef(xTranslate, yTranslate, 0.0f );glDrawArrays(GL_TRIANGLES, 0, 3);glPopMatrix();glDrawArrays(GL_TRIANGLES, 0, 36);eglSwapBuffers(iEglDisplay, iEglSurface);}TInt CMyMainControl::TranslateBy() const{return iTranslateBy;}void CMyMainControl::SetTranslateBy(TInt aTranslateBy){iTranslateBy = aTranslateBy;}What may go wrong when you do this: CPeriodic cannot be used toredraw too frequently to the screen, for risk of triggering a ViewSrv11 panic.234SYMBIAN C++ RECIPESTip: On S60 smartphones, you can call User::ResetInactivityTime() periodically to keep the screen backlit.4.6.5.2Adapt PerformancesAmount of time required: 1 hour to understand – months to execute!Problem: You want to adapt your animation to your target devices.Solution: On OpenGL platforms, developers have several techniquesthat allow for smooth animation of scenes, even when resources areconstrained:• Effects that refine the look of 3D objects can be switched on or off.• The number of objects displayed on the screen can be adjusted (byscreen resolution).• General code optimization techniques can be used.

OpenGL is onelevel above C-type code, so you cannot rely on the compiler makingthe right optimizations. A 3D-modeling tool might, though.• Knowing the inner workings of specific OpenGL implementations isalso useful. Constructors’ help forums are gold mines of information.These techniques are still valid in OpenGL ES. However, there areother factors to take into consideration:• Screen sizes can be diverse, and guaranteeing a suitable user experience across a range of devices requires some experimentation.• Required configurations need to enumerate specific handset models(or ranges), instead of CPU speed for example.• The amount and type of memory on smartphones is also more ofan issue than on desktop computers, so the speed/size trade-offs willneed to be revisited and textures should be used carefully.• At the time of writing, only a few handsets contain a hardware3D accelerating chip and their performances are wildly better thanthose without.

Yet, as a developer, you don’t want configurationmanagement to become your main nightmare. There are just so manymore interesting things to lose sleep over.• From an engineering standpoint, it makes sense to write an adaptiveanimation monitor that will decide in real time how complex the3D scene should be (how deep, how precise, etc.) and how fast 3Dobjects should move by measuring the time it takes to render a scene.3D GRAPHICS USING OPENGL ES235• Memory consumption can also be monitored in real time to adapt theresolution of the textures in use.• Mobile users are usually more forgiving about a 3D object not lookingas good as it would on their computer than about an error dialogpopping up in the middle of a game or a lagging animation.Since these recipes will probably be used by most to begin thedevelopment of games, it is worth mentioning that mobile games are notusually used in the same way as desktop games:• Users usually have minutes of available time, not hours, so loadingtime needs to be kept to a minimum and playability is paramount.Porting animation code will not be trivial since you will have to usenative Symbian OS APIs.• The user input controls are also variable between different smartphones and you may have to slow some objects down to make userinteraction possible.• Testing different animation algorithms and detail levels on differenthandsets will increase your time-to-market (Chapter 6 discusses thisfurther).• Involuntary interruptions are also common on smartphones.

This maylead to the implementation of a relative timer used for animating the3D scene only when it is in the foreground, as the system time couldsuddenly jump by several minutes if the game is interrupted by anincoming phone call.• There is another problem related to interruptions. If you monitorkey up and down events (instead of key pressed events) you mayonly get a key down event when the application is interrupted. Thecorresponding key up event would be delivered to another applicationin that case. After an interruption, a game should assume all keys havebeen released.4.6.6 ResourcesThe OpenGL ES specifications:• www.khronos.org/opengles/spec.The OpenGL ES v1.1 reference manual:• www.khronos.org/opengles/documentation/opengles1 1/gl eglref 1 1 20041110/index.html.The main hub of OpenGL ES resources:• www.khronos.org/developers/resources/opengles/.236SYMBIAN C++ RECIPESPowerVR also publishes SDKs and code samples:• www.imgtec.com/PowerVR/insider/index.asp.The Symbian Developer Library contains information about OpenGLES in the Graphics section of the Symbian OS Guide.

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

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

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

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