Adding Open Source 3D Physics to Your iOS Applications (3)Using Bullet in Your iOS Application

Adding Open Source 3D Physics to Your iOS Applications (3)Using Bullet in Your iOS Application,第1张

概述Using Bullet in Your iOS Application All that remains is to build an application that actually uses Bullet and displays 3D objects. Apple's GLKit framework makes it relatively easy. Make the view cont Using Bullet in Your iOS Application

All that remains is to build an application that actually uses Bullet and displays 3D objects. Apple's GLKit framework makes it relatively easy.

Make the vIEw controller class generated by Xcode's Single VIEw Application template into a subclass of GLKVIEwController instead of UIVIEwCintroller. The PVIEwController.h file in the tutorial sample code contains the following lines:

#import <GLKit/GLKit.h> PVIEwController : @interfaceGLKVIEwController

Next,edit the MainStoryboard.storyboard file generated by Xcode's Single VIEw Application template. Set the class of the generated vIEw to GLKVIEw using Xcode's IDentity inspector,shown in figure 12.

Figure 12 Setting the vIEw's class to GLKVIEw

Add the GLKit and OpenGLES frameworks to the project. The easIEst way is to edit the project's Build Phases,as shown in figure 13. Press the + button in the link Binary with librarIEs section to add frameworks.

Figure 13 GLKit and OpenGLES frameworks added to the project

If you build and run the tutorial project Now,you should see a black screen. The next step is to create a physics simulation and draw something more interesting.

The tutorial source code includes a file named PAppDelegate.mm. The .mm extension tells Xcode to compile the file as Objective-C++ code intermixing C++ and Objective-C. The following code declares instance variables to store Bullet physics objects:

#import "PAppDelegate.h"#include "btBulletDynamicsCommon.h"#include <map> < *,*>    GModelShapeMap;  (){    *collisionConfiguration;    *dispatcher;    *overlapPingPairCache;    *solver;    *dynamicsWorld;   *> collisionShapes;       modelShapeMap;}@endtypedefstd::mapPPhysicsObjectbtCollisionObject@interfacePAppDelegatebtDefaultCollisionConfigurationbtCollisiondispatcherbtbroadphaseInterfacebtSequentialimpulseConstraintSolverbtdiscreteDynamicsWorldbtAlignedobjectArray<btCollisionShapeGModelShapeMap

The GModelShapeMap modelShapeMap variable is used to store the relationships between Objective-C objects representing Boxes and spheres and the corresponding shapes simulated by Bullet. A C++ map is a standard class similar in function to Cocoa touch'sNSDictionary class.

The physics simulation is initialized in PAppDelegate's -application:dIDFinishLaunchingWithOptions: method that's part of the Cocoa touch standard application delegate protocol. The simulation is configured to use Earth's gravitational acceleration of -9.81 meters per second2. Comments explain the steps needed to initialize Bullet. Don't worry if it doesn't make much sense to you. It's boilerplate code.

/////////////////////////////////////////////////////////////////// Creates needed physics simulation objects and configures// propertIEs such as the acceleration of gravity that seldom// if ever change while the application executes.- ()application:( *)application    dIDFinishLaunchingWithOptions:( *)launchOptions{    ///collision configuration contains default setup for memory,// collision setup. Advanced users can create their own    // configuration.     =        ();       ///use the default collision dispatcher. For parallel    // processing you can use a diffent dispatcher    // (see Extras/BulletMultiThreaded)     = 	        ();       ///btDbvtbroadphase is a good general purpose broadphase. You    // can also try out btAxis3Sweep.     =  ();       ///the default constraint solver. For parallel processing you    // can use a different solver (see Extras/BulletMultiThreaded)     =  ;        =        (,);       ->setGravity(());      return YES;}BOolUIApplicationNSDictionarycollisionConfigurationnewbtDefaultCollisionConfigurationdispatchernewbtCollisiondispatchercollisionConfigurationoverlapPingPairCachenewbtDbvtbroadphasesolvernewbtSequentialimpulseConstraintSolverdynamicsWorldnewbtdiscreteDynamicsWorlddispatcheroverlapPingPairCachesolvercollisionConfigurationdynamicsWorldbtVector30,-9.81,0

PAppDelegate's -applicationWillTerminate: method tears down the simulation built in -application:dIDFinishLaunchingWithOptions:. It's not necessary to implement -applicationWillTerminate: in the tutorial sample code because when the application terminates,iOS will automatically reclaim the memory and other resources consumed by the physics engine. The code is provIDed in PAppDelegate.mm as example to follow if you ever need to clean up the physics engine while the application continues to execute.

PAppDelegate provIDes the following -physicsUpdateWithelapsedtime: method. Call the method periodically to give the physics engine opportunitIEs to recalculate object positions and orIEntations.

/////////////////////////////////////////////////////////////////// Turn the crank on the physics simulation to calculate // positions and orIEntations of collision shapes if// necessary. The simulation performs up to 32 interpolation// steps depending on the amount of elapsed time,and each step// represents 1/120 seconds of elapsed time.- ()physicsUpdateWithelapsedtime:()seconds;{   dynamicsWorld->stepSimulation(seconds,/);}voIDNSTimeInterval321120.0f

That's all it takes to start using Bullet physics for iOS. The simulation doesn't produce any interesting results unless some objects are added and set in motion to collIDe with each other. It's time to create,register,and draw physics objects.

GLKit provIDes most of the features needed. The tutorial project includes files named sphere.h and cube.h containing data declarations for 3D shapes. The data consists of vertex positions and "normal" vectors. Each shape is drawn as a List of connected triangles. The normal vectors provIDe information used to calculate how much simulated light reflects from each triangle.

The PVIEwController class implements all of the drawing for the tutorial. The drawing code is suboptimal to keep the code simple,and it turns out not to matter at run time. Profiling the tutorial code reveals that less than 20% of the application's execution time is spent drawing. Even if the drawing code is removed entirely,the application only runs 20% faster.

PVIEwController declares the following propertIEs. The baseEffect property stores an instance of GLKit's GLKBaseEffect class. Modern GPUs are programmable allowing almost unlimited flexibility when rendering 3D graphics. The programs running on the GPU are sometimes called effects. GLKBaseEffect encapsulates the GPU programs needed by simple applications so that you don't need to dive into GPU programming when getting started.

@interface  ()@property (strong,nonatomic,reaDWrite)    *baseEffect;@property (strong,reaDWrite)     *BoxPhysicsObjects;@property (strong,reaDWrite)     *spherePhysicsObjects;@property (strong,reaDWrite)     *immovableBoxPhysicsObjects;   @endPVIEwControllerGLKBaseEffectNSMutableArrayNSMutableArrayNSMutableArray

Other than baseEffect,the other propertIEs all store arrays of Objective-C objects representing spheres and Boxes in the simulation. Bullet only recalculates positions for physics objects that have mass. Objects created with zero mass are therefore immovable within the simulation. They don't become displaced when other objects collIDe or fall in response to gravity. The immovableBoxPhysicsObjects property stores an array of zero mass Boxes used to form a floor. Without a few immovable objects in the simulation,all of the other objects would quickly fall out of vIEw as the result of simulated gravity.

Two GLKVIEwController methods provIDe the key to drawing with GLKit: -update and -glkVIEw:drawInRect:. The –update method is called periodically in sync with the iOS device display refresh rate. The display always refreshes 60 times per second,butGLKVIEwController's default behavior is to call –update at 30Hz. In other words, –update is called once for every two display refreshes. GLKVIEwController can be configured to call –update at other rates,but 30 times per second works well for simulations. Right after calling –update, GLKVIEwController tells the vIEw it controls to display,and the vIEw calls back to GLKVIEwController's -glkVIEw:drawInRect:. Therefore,you implement simulation update in –update and implement custom 3D drawing code in -glkVIEw:drawInRect:.

/////////////////////////////////////////////////////////////////// This method is called automatically at the update rate of the // receiver (default 30 Hz). This method is implemented to// update the physics simulation and remove any simulated objects// that have fallen out of vIEw.- ()update{    *appDelegate =       [[] ];      [appDelegate :      .];   // Remove objects that have fallen out of vIEw from the    // physics simulation   [ ];}voIDPAppDelegateUIApplication sharedApplicationdelegatephysicsUpdateWithelapsedtimeselftimeSinceLastUpdateselfremoveOutOfVIEwObjects

The following drawing code sets baseEffect propertIEs to match the orIEntation of the iOS device,specifIEs perspective,positions a light,and prepares for drawing 3D objects. Theaspect ratio is the ratio of a vIEw's wIDth to its height. The aspect ratio may change when an iOS device is rotated from portrait orIEntation to landscape and back. Perspectivedefines how much of the 3D scene is visible at once and how objects in the distance appear smaller than objects up close.

In the real world,we only see objects that reflect light into our eyes. We perceive the shape of objects because different amounts of light reflect for different parts of the objects. Setting the baseEffect's light position controls how OpenGL calculates the amount of simulated light reflected off each part of a virtual 3D object. Calling [self.baseEffect preparetoDraw] tells the base effect to prepare a suitable GPU program for execution.

/////////////////////////////////////////////////////////////////// GLKVIEw delegate method: Called by the vIEw controller's vIEw// whenever Cocoa touch asks the vIEw controller's vIEw to// draw itself. (In this case,render into a frame buffer that// shares memory with a Core Animation Layer)- ()glkVIEw:( *)vIEw drawInRect:()rect{   // Calculate the aspect ratio for the scene and setup a    // perspective projection      aspectRatio =    ()vIEw. / ()vIEw.;      // Set the projection to match the aspect ratio   .. =    (      (),// Standard fIEld of vIEw      aspectRatio,// Don't make near plane too close      ); // Far arbitrarily far enough to contain scene      // Configure a light   ... =    (,);// Directional light         [. ];   // Clear Frame Buffer (erase prevIoUs drawing)   (|);      [ ];   [ ];      }voIDGLKVIEwCGRectconstGLfloatGLfloatdrawableWIDthGLfloatdrawableHeightselfbaseEffecttransform.projectionMatrixGLKMatrix4MakePerspectiveGLKMathdegreesToradians35.0f0.2f200.0fselfbaseEffectlight0positionGLKVector4Make0.6f1.0f0.4f0.0fselfbaseEffectpreparetoDrawglClearGL_color_BUFFER_BITGL_DEPTH_BUFFER_BITselfdrawPhysicssphereObjectsselfdrawPhysicsBoxObjects

OpenGL ES is a technology for controlling GPUs. Parts of OpenGL ES execute on the GPU itself,and other parts execute on the cpu. Programs call a library of C functions provIDed by OpenGL to tell OpenGL what to do. The glClear() function,called in the tutorial's -glkVIEw:drawInRect:, erases prevIoUs drawing and discards prevIoUsly calculated information about which 3D objects are in front of others.

PVIEwController's –drawPhysicssphereObjects and –drawPhysicsBoxObjects methods draw spheres and Boxes with positions and orIEntations calculated by the physics engine. Without going into a lot of detail,each of the methods calls OpenGL ES functions to specify where to find vertex data defining triangles. Then the triangles are drawn by calling code similar to the following:

      // Draw triangles using the first three vertices in the       // currently bound vertex buffer      (,// Start with first vertex in currently bound buffer         sphereNumVerts);glDrawArraysGL_TRIANGLES0

OpenGL ES can only draw points,lines segments,and triangles. Complex shapes are composed of many triangles. The shapes in this tutorial are defined in sphere.h and cube.h. The shapes were initially drawn in a free open source 3D modeling application called Blender. Modeling is the term used by artists who create 3D shapes. The created models are exported from Blender in .obj file format and then converted into C header files suitable for direct use with OpenGL. Conversion is performed by an open source Perl language script.

It takes a little more work to setup GLKit. PVIEwController's -vIEwDIDLoad method shows representative boilerplate code. This article glosses over methods like PVIEwController's –addRandomPhysicsObject. The code for adding physics objects is straightforward and particular to this tutorial. You'll most likely add different objects with different logic in your physics simulation projects.

Conclusion

The simulation provIDes remarkably complex and varIEd interaction between objects. The downloadable code is available in two variants. The Physics zip file (3dphyslibios_physics.zip) contains a Physics folder with an Xcode project. If you have built the Bullet demo applications for Mac OS X,you can copy the Physics folder into your bullet-2.80-rev2531 folder,double-click the Physics.xcodeproj file and press Run. A separate larger PhysicsPlusBullet zip file (3dphyslibios_physicsplusbullet.zip) contains the tutorial example and the needed Bullet source code combined. As always with open source,it's better to get the source code directly from the maintainers instead of grabbing a snapshot preserved in a tutorial's .zip file. Nevertheless,if you're impatIEnt,the PhysicsPlusBullet zip file will get you up and running quickly.

This article provIDed a whirlwind tour of two large and powerful frameworks,Bullet and GLKit. It's not difficult to combine the two technologIEs in iOS applications. like many open source librarIEs,Bullet is relatively easy to compile for iOS in spite of quirks related to the tools and Coding style used by the library's authors. GLKit enables development of interesting and visually complex 3D applications with very little code. The tutorial implements all of its drawing in about 200 lines of code including comments and blank lines.

If you are interested in a more thorough introduction to 3D graphics concepts and GLKit,my new book, Learning OpenGL ES for iOS: A Hands-on Guide to Modern 3D Graphics Programming,is complete and available Now as a Rough Cut electronic edition. Look for the Title at your favorite bookstore in the fall. Free sample codefrom the book is available.

总结

以上是内存溢出为你收集整理的Adding Open Source 3D Physics to Your iOS Applications (3)Using Bullet in Your iOS Application全部内容,希望文章能够帮你解决Adding Open Source 3D Physics to Your iOS Applications (3)Using Bullet in Your iOS Application所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1055090.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存