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

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

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

Sony Ericsson devices contain the ‘Lite’version of the same processor.4.6.1 OpenGL ES PrimerBefore we start, you will need a working knowledge of geometry in threedimensional space. You will also need to understand how to multiplymatrices.In OpenGL ES, a point in space is called a vertex. The most complexshape you can draw is a triangle. Each vertex can belong to severaltriangles, which facilitates the drawing of contiguous triangles formingmore complex geometric shapes. By drawing many triangles, you canapproximate pretty complex scenes.Each separate vertex can have its own color. The color of the area of atriangle depends on the colors of its three vertices.You can decide how far the coordinate system extends.

The axes pointtoward the right-hand side of the screen, toward the top of the screen andtoward you. Beware.The basic available transformations are translation and rotation. Theseare executed before you ask the system to draw your vertices.The OpenGL ES implementation keeps a current state matrix. Eachtransformation means multiplying the current state matrix by the transformation matrix and storing the result in the current state matrix.

Whendrawing, all coordinates are transformed using the current state matrix. Astack of current state matrices allows for temporary states and you canalways revert back to the original identity matrix.Textures are images that can be applied to a surface, even if it meansthe OpenGL ES implementation has to bend and warp them to fit yourrequirements. They give you finer control than colors, but have a muchhigher footprint.Since your screen is a 2D plane, the content of the 3D scene you wantto draw needs to be flattened.

This is called projection. All the examplesin this set of recipes will use the orthographic projection, which simplifiesthe amount of calculus you have to perform but doesn’t take perspectiveinto account at all.4.6.2 OpenGL to OpenGL ESEach OpenGL ES version maps to an OpenGL version. OpenGL ES v1.0is a subset of OpenGL v1.3 and OpenGL ES v1.1 is a subset of OpenGLv1.5.One main difference between the two standards is the availability ofinteger coordinate systems in OpenGL ES.

It was added to reflect theconsiderable proportion of smartphone CPUs without a Floating PointUnit. This would be a non-trivial change when porting desktop-class code3D GRAPHICS USING OPENGL ES219to a mobile platform, but the general performance improvement may beworth the effort.Because of the APIs that are unavailable in OpenGL ES, you probablywon’t be able to just use the code generated by your usual modeling tool.You can still display everything you want on the screen, but you mayhave to invest more effort in getting there.The later the OpenGL ES version you are targeting, the easier it shouldget for you, the developer. Unfortunately, this also translates to a loweravailability of handsets.All OpenGL polygons need to be expressed in terms of triangles inorder to be drawn using OpenGL ES.OpenGL ES only supports 2D textures, but you can still apply severaltextures at once, use reflections, fog, transparency, and so on.4.6.3 Easy Recipes4.6.3.1Full-Screen SetupAmount of time required: 40 minutesLocation of example code: \3D\BasicRequired libraries: libgles_cm.libRequired header file(s): GLES\egl.hRequired platform security capability(s): NoneProblem: You want to take over the whole screen to display 3D objects.Solution: Since we are going to display things on the screen, it just makessense to run all our code inside the standard Symbian OS applicationframework.The application view is a CCoeControl and you can use theassociated RWindow to initialize the OpenGL ES implementation.Beyond that, the OpenGL implementation needs to know how manybits the colors are encoded on.

Assuming you are only interested indisplaying 3D graphics on the handset main screen, you can then writecode that will work no matter what the configuration of your phone:#include <GLES/egl.h> // and#include <coecntrl.h> // and#ifdef __SERIES60_3X__#include <aknviewappui.h> ////#include <akndef.h>#else#include <QikAppUi.h> // and#endiflink to libgles_cm.liblink to cone.liband link to avkon.lib, eikcore.liband eiksrv.liblink to qikcore.libclass CMyMainControl;#ifdef __SERIES60_3X__class C3DAppUi : public CAknAppUi220SYMBIAN C++ RECIPES#elseclass C3DAppUi : public CQikAppUi#endif{public:void ConstructL();∼C3DAppUi(); // delete iAppContainerprivate:CMyMainControl* iAppContainer;};void C3DAppUi::ConstructL(){BaseConstructL();iAppContainer = new (ELeave) CMyMainControl;iAppContainer->SetMopParent(this);iAppContainer->ConstructL( Rect() );}class CMyMainControl : public CCoeControl{public:void ConstructL(const TRect&);∼CMyMainControl();static void CleanupConfigList(TAny* aList);private:void SizeChanged();private: // OpenGL ES stuffEGLDisplay iEglDisplay;EGLSurface iEglSurface;EGLContext iEglContext;EGLConfig iEglConfig;};void CMyMainControl::CleanupConfigList(TAny* aList){EGLConfig* configList = (EGLConfig*)aList;User::Free(configList);}void CMyMainControl::ConstructL(const TRect& /*aRect*/){CreateWindowL();SetExtentToWholeScreen(); // Take the whole screenActivateL();iEglDisplay = eglGetDisplay( EGL_DEFAULT_DISPLAY );if ( NULL == iEglDisplay ){User::Leave(KErrGeneral);}if ( eglInitialize( iEglDisplay, NULL, NULL ) == EGL_FALSE ){User::Leave(KErrGeneral);}EGLConfig* configList = NULL;EGLint numOfConfigs = 0;EGLint configSize= 0;3D GRAPHICS USING OPENGL ESif ( eglGetConfigs( iEglDisplay, configList, configSize,&numOfConfigs ) == EGL_FALSE ){User::Leave(KErrGeneral);}configSize = numOfConfigs;configList = (EGLConfig*)User::Alloc(sizeof(EGLConfig) * configSize);User::LeaveIfNull(configList);CleanupStack::PushL(TCleanupItem(&CMyMainControl::CleanupConfigList, configList));TDisplayMode dMode = Window().DisplayMode();TInt bufferSize = 0;switch ( dMode ){case(EColor4K):bufferSize = 12;break;case(EColor64K):bufferSize = 16;break;case(EColor16M):bufferSize = 24;break;case(EColor16MU):case(EColor16MA):bufferSize = 32;break;default:User::Leave(KErrGeneral);break;}const EGLint attrib_list[] = {EGL_BUFFER_SIZE, bufferSize,EGL_NONE};if ( eglChooseConfig( iEglDisplay, attrib_list, configList,configSize, &numOfConfigs ) == EGL_FALSE ){User::Leave(KErrGeneral);}iEglConfig = configList[0];CleanupStack::PopAndDestroy();iEglSurface = eglCreateWindowSurface( iEglDisplay, iEglConfig,&Window(), NULL );if ( NULL == iEglSurface ){User::Leave(KErrGeneral);}iEglContext = eglCreateContext( iEglDisplay, iEglConfig,EGL_NO_CONTEXT, NULL );if ( EGL_NO_CONTEXT == iEglContext ){221222SYMBIAN C++ RECIPESUser::Leave(KErrGeneral);}if ( eglMakeCurrent( iEglDisplay, iEglSurface, iEglSurface,iEglContext ) == EGL_FALSE ){User::Leave(KErrGeneral);}const TInt width = Size().iWidth;const TInt height = Size().iHeight;const GLfloat aspectRatio = (GLfloat)width / (GLfloat)height;glMatrixMode( GL_PROJECTION );//decide how big our 3D space is.//and use orthographic projection.glOrthof( PLANE_LEFT*aspectRatio, PLANE_RIGHT*aspectRatio,PLANE_BOTTOM, PLANE_TOP, PLANE_NEAR, PLANE_FAR );glMatrixMode( GL_MODELVIEW );}CMyMainControl::∼CMyMainControl(){eglMakeCurrent( iEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE,EGL_NO_CONTEXT );eglDestroySurface( iEglDisplay, iEglSurface );eglDestroyContext( iEglDisplay, iEglContext );eglTerminate( iEglDisplay );}void CMyMainControl::SizeChanged(){glViewport( 0, 0, Size().iWidth, Size().iHeight );}4.6.3.2Display a 3D ObjectAmount of time required: 40 minutesLocation of example code: \3D\BasicRequired libraries: libgles_cm.libRequired header file(s): GLES\egl.hRequired platform security capability(s): NoneProblem: You want to display a simple 3D object.Solution: Usually the most basic example in 3D objects is a cube.

Let’smake one centered on the origin of the integer coordinate system, witheach side being a 2 × 2 square.We can also draw the largest sphere that fits into this cube (except weare going to place it right on top of the cube, so we can see it). Now, thisis where math begins and a float coordinate system is useful.

What wedraw won’t be an exact sphere. It will be a model of the sphere built usingtriangles (a.k.a. polygons). And we have to come up with the coordinatesfor the three points of each triangle on our own.3D GRAPHICS USING OPENGL ES223We suggest you start by drawing the following on a piece of paper:• Let’s say we want to approximate the quarter of a circle in a 2D planeby drawing 10 points: 1 point per 10 degrees.• The full circle is 40 points (4 of them are redundant) and all thecoordinates can be found by using the sine and cosine mathematicalfunctions.• Add a dimension: we need 40 circles to simulate a sphere (1 isredundant) and we end up with 1,600 points (266 of them areredundant).• All that’s left is to create all the triangles between adjoining points.• Looking at our 2D circle and the next one like it in the 3D space(the original circle rotated by 10 degrees on the Y axis), you cansee adjoining points forming 36 rectangles, each of them made up of2 triangles.• We need to go through the whole 180 degrees (still rotating on theY axis) worth of rectangles so our sphere model is made up of 1,296triangles.Feel free to get up and fetch some kind of mental stimulant to recover.Nothing illegal, though.Creating a cube made of two triangles per side is easy enough to putall the points into an array in memory.

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

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

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

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