Ipphones

  • Subscribe to our RSS feed.
  • Twitter
  • StumbleUpon
  • Reddit
  • Facebook
  • Digg

Saturday, 13 December 2008

NeHe Tutorials, Lesson 6 Ported to iPhone (sort of)

Posted on 17:19 by Unknown
I've ported NeHe Lesson 06. Sort of.

You see, OpenGL ES 1.1 doesn't support quads. NeHe selected a pyramid and a cube because they are easy shapes under OpenGL proper. However, the only polygon that OpenGL ES 1.1 knows about is the triangle. There are several variations on it - triangle strips, triangle fans, and triangles. As you saw when we ported Lesson 5, we had to split each quad into two triangles. That wasn't so bad when we were just drawing flat colors, but now that we're looking to map textures, it becomes a whole heck of a lot harder, because mapping a square texture to a triangle is, quite frankly, a pain in the ass.

Here is the link for the ported Lesson 6 project.

I only mapped two of the sides - front and back, the other aren't done and won't display right. It took me the better part of an hour before I finally gave up mapping all six sides. I hate releasing this unfinished, but I just can't afford the time right now to manually map the textures to all the triangle that make up the cube. Fortunately, there's rarely a need to manually map texture coordinates any more. Most 3D programs will export the texture coordinates for you, so all we really need to take from Lesson 06 is how to load the textures into memory and how to make them active. You should read the NeHe tutorial so you understand how texture mapping works, but it doesn't make sense to spend a lot of time on the process. In a future posting, we'll see how to take a 3D object created in Blender and import the texture coordinates along with the vertex data. In practice, it would be rare for you to manually map textures to individual polygons like this.

In Lesson 06, we have our first instance variable in the controller class. Because I needed to access the textures array from multiple methods, I couldn't just make another static variable. So, we now have an array of integers, and these integers will each refer to a texture loaded into OpenGL.
GLuint  texture[1];      // Storage For One Texture ( NEW ) 
In our setupView method, we prepare our texture just like is done in the NeHe Lesson 06
 glGenTextures(1, &texture[0]);
glBindTexture(GL_TEXTURE_2D, texture[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
We have to vary a little from the plan to actually load the texture from file. Instead of a .bmp file, we're going to load that compressed texture file I had you create in this blog posting. If you didn't do that, go do it now. You'll want to drag the .pvr4 file into the /Resources group of your project.

Once you've got the project in your texture, we can load it in our setupView method:
 NSString *path = [[NSBundle mainBundle] pathForResource:@"NeHe" ofType:@"pvr4"];
NSData *texData = [[NSData alloc] initWithContentsOfFile:path];
// Instead of glTexImage2D, we have to use glCompressedTexImage2D
glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, 256.0, 256.0, 0, (256.0 * 256.0) / 2, [texData bytes]);
[texData release];
A couple of things to notice - first, because our texture image is compressed, we had to use glCompressedTexImage2D() rather than glTexImage2D() as was done in the NeHe tutorial. The other thing is that we release the image data after we feed it to OpenGL - it creates its own copy of the texture, so we have to release to avoid leaking memory.

After that, the rest of the setup is pretty much the same as in the original tutorial:
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); 
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
// Enable blending
glEnable(GL_BLEND);
Where things get really different is in the drawView method. Some of you probably saw this coming, but we can't use glTexCoord2f() because we can't use glBegin() and glEnd() on the iPhone.

The solution is the same as before - we stuff all those texture coordinates into an array called (wait for it) a texture coordinate array. Texture coordinates in the array are just like the values you would pass to glTexCoord2f() - values between 0.0 and 1.0. Refer to the original tutorial for a description of how that mapping works. It's a little hard to grok. If you don't fully get it, don't worry - before long, we're going to write an object-loader that will handle that for us, and then we'll never have to remember how it works again. Here is the texture coordinate array I created for this lesson, but remember that only the first 16 values (corresponding to the first four polygons that make up the front and back of the cube) are actually valid and mapped.
 const GLfloat cubeTextureCoords[] = {
1.0, 1.0, // Front
0.0, 1.0,
0.0, 0.0,
1.0, 0.0,

0.0, 0.0, // Back
0.0, 1.0,
1.0, 1.0,
1.0, 0.0,

0.0, 0.0, // Top
1.0, 1.0,
1.0, 1.0,
1.0, 1.0,

0.0, 0.0, // Bottom
0.0, 1.0,
1.0, 1.0,
1.0, 1.0,

0.0, 0.0, // Left
1.0, 1.0,
1.0, 1.0,
1.0, 1.0,

0.0, 0.0, // Right
1.0, 1.0,
1.0, 1.0,
1.0, 1.0,
};
Before we make any calls to glDrawElements(), we have to tell OpenGL about the texture coordinates, and we do that using a function called glTexCoordPointer(), like so:
glTexCoordPointer(2, GL_FLOAT, 0, cubeTextureCoords);
The first argument to this function says that we have two mapping values for each element to be drawn. The second argument tells OpenGL that the texture array contains floating point values, the third is that parameter I keep telling you to ignore and just provide 0 for, and the last is the pointer to the actual texture coordinate array.

Before you can call glDrawElements, you have to enable texture coordinate arrays, by making this call:
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
Like the other enable functions, you can call this once during setup, or you can enable and disable it during application execution. Because only one of our two objects is getting mapped, we enable it before we draw the cube, and disable it afterwards, which will keep the pyramid from getting mapped as well.

In order for texture mapping to work, we must also call
glEnable(GL_TEXTURE_2D);
This only has to be called once in setup, or you can also enable and disable it during application execution, though typically it's just turned on at the beginning.

That's pretty much it. When we call glDrawElements(), it will automatically fetch the coordinate data and map the last texture that was bound. We only have one, which we bound during setup by calling glGenTextures() and glBindTexture().

If we had a lot of textures (which you will in most situations), you would typically load them all in during setup, and then activate different ones by making subsequent calls to glBindTexture(), which does double duty, both creating, and activating existing textures. The last one that was passed to glBindTextures() is the one that will get mapped when you draw.

This was a tough lesson to port. They opted to map the cube because it was easy - square sides, square textures, very simple mapping. We're not that lucky on the iPhone, so I hope you'll forgive the fact that this one is incomplete. In return, I promise to show you how to load objects with texture maps. Probably not for a week or two, though.
Email ThisBlogThis!Share to XShare to Facebook
Posted in iPhone SDK, NeHe, OpenGL ES | No comments
Newer Post Older Post Home

0 comments:

Post a Comment

Subscribe to: Post Comments (Atom)

Popular Posts

  • Strong Encryption for Cocoa / Cocoa Touch
    Please do not use this code! Instead, check out Jim Dovey's Common Crypto code from AQToolkit . AES is a strong encryption standard tha...
  • Texture Coordinate Arrays or Things Nobody Tells You
    For some reason, a lot of OpenGL stuff just isn't well documented. Yes, I read the Red Book chapter on texturing. It didn't have a s...
  • Dynamically adding class objects
    Okay, folks, the first draft of the book is done, and I have some breathing room until the chapters start coming back from the tech reviewer...
  • Web Services Fun
    Before we work more with libxml, let's talk about web services. Web services are a good practical application of XML and, it would seem ...
  • An OpenGL Project Template for Xcode
    I'm not a fan of the OpenGL ES Application project template that ships with the iPhone SDK. It's a pain in the ass to go in and dele...
  • Handling Double Taps
    Alright, since the NDA is down, let's celebrate by posting some information, shall we? One question that I see posted a lot by new iPhon...
  • Twittering iPhone Developer List
    Tim Haines, the developer of the excellent BurnBall game, has started a list of iPhone developers who use Twitter. The last time I checked,...
  • More on OpenGL and Normals
    In an earlier post I talked about surface normals in OpenGL. In writing the Wavefront OBJ loading class, I've learned far more about no...
  • OpenGL ES From the Ground Up, Part 1 Addendum: Alphabet Soup
    One problem with blog postings is that they are self-edited. For my postings here, I have no external technical review and no copy editing d...
  • Writing
    I'm pretty swamped with writing work at the moment. The book project is going pretty well, and I'm fortunate to have a very experien...

Categories

  • 3D Models
  • Ad Hoc Distribution
  • ADC
  • Address Book
  • Amazon
  • Anaglyphs
  • App Store
  • Apple
  • Apple DTS
  • Apple Store
  • Application Store
  • articles
  • Award
  • Background Processing
  • Barcodes
  • Beta
  • Blog
  • Blogger
  • Blogging
  • Blogs
  • Blogspot
  • Book project
  • Bug Reporting
  • Captain Obvious
  • Categories
  • Censorship
  • CFFoundation
  • CGAffineTransform
  • Clang Static Analyzer
  • Cocoa
  • Cocoa Touch
  • Code Reuse
  • Code Signing
  • Computer
  • conferences
  • Controller Classes
  • Core Animation
  • Daring Fireball
  • Database
  • Debugging
  • Defect
  • Delegates
  • Design Awards
  • Developer Certifications
  • Discussion Forums
  • Edit Mode
  • employment opportunities
  • Encryption
  • Enterprise
  • Errata
  • free code
  • Free software
  • Full Screen
  • Game Programming
  • Gestures
  • Getting Started
  • goof
  • Google Code
  • Google Maps
  • Gotcha
  • Help
  • HIG
  • HTTP PUT
  • Idiots
  • Idle Timer
  • Images
  • Instruments
  • Interface Builder
  • iPHone
  • iPhone Applications
  • iPhone Dev Center
  • iPhone Developers
  • iPhone OS 3.0
  • iPhone SDK
  • iPhone SDK PNG
  • iPhone Simulator
  • iPhoneSDK
  • iPod
  • Job Opportunities.
  • k
  • Key Value Observing
  • Keynote
  • KVO
  • Landscape Mode
  • Learn Cocoa
  • Learn Cocoa on the Mac
  • libxml
  • Licensing
  • Mac Developers
  • Mac OS X
  • Macworld Expo
  • Microsoft
  • NDA
  • NeHe
  • New Category
  • New Release
  • NSFileHandle
  • NSMutableArray
  • NSMutableURLRequest
  • NSXML
  • Object-Oriented Design
  • Objective-C
  • Open Source
  • OpenGL ES
  • Optimizations
  • Other blogs
  • Paired Arrays
  • Parsing
  • Particle Engine
  • Party
  • PeopleSoft
  • Performance
  • Persistence
  • Pink Screen of Death
  • Piracy
  • Pixar
  • Podcasts
  • Press Release WTF
  • Press Releases WTF
  • private APIs Google
  • Project Template
  • Properties
  • Random Numbers
  • Rant
  • Rejected
  • Resources
  • Responder Chain
  • REST
  • Reverse Engineering
  • Rumors
  • Runtime
  • Sample Code
  • Screencast
  • screenshot
  • Scroll Views
  • snippet
  • Snow Leopard.
  • SOAP
  • Sockets
  • Source
  • Splash Screen
  • SQLite
  • SQLitePersistentObjects
  • Steve Jobs
  • Steve-Note
  • Strings
  • Stupidity
  • Subversion
  • Table Views
  • Taps
  • Template
  • Tip
  • Tips
  • Tririga
  • tutorials
  • Twitter
  • UIAlertView
  • UIColor
  • UIImage
  • UIPickerView
  • UIScrollView
  • UITextField
  • UIView
  • UIWebView
  • Update
  • Utilities
  • UUID
  • Vacation
  • Version Control
  • Web Services
  • Writing
  • WTF
  • WWDC
  • Xcode
  • XML

Blog Archive

  • ►  2009 (141)
    • ►  May (14)
    • ►  April (30)
    • ►  March (48)
    • ►  February (26)
    • ►  January (23)
  • ▼  2008 (163)
    • ▼  December (46)
      • Coming Soon - My OpenGL Particle Engine
      • Updated OpenGL ES Xcode Project Template
      • Another Wavefront OBJ loader
      • PVRTC Textures & OpenGL resources from Apple
      • A Reusable Date Drill-Down Controller
      • Learn Objective-C on the Mac is Shipping
      • We broke Amazon's Top 100 Books
      • Reusable Controllers
      • Wavefront OBJ Loader - Another Update
      • Almost There...
      • Texture Coordinate Arrays or Things Nobody Tells You
      • Happy Holidays
      • OpenGL ES Extensions on the iPhone
      • Texture Mapping is Coming
      • And we have a Winner
      • More on UIAlertView and Landscape Problem
      • UIAlertView & Landscape Mode
      • More on OpenGL and Normals
      • Wavefront OBJ Loader - Normals Done...
      • Progress on the Wavefront OBJ Loader
      • Andy Ihnatko on Apple & the Macworld Expo
      • gluLookAt()
      • MacWorld 2009
      • 3D Models as C Header Files
      • OpenGL Postings
      • The Start of a WaveFront OBJ File Loader Class
      • More on Outlets - Instance Variables vs. Properties
      • Just for Fun: OpenGL Icosahedron
      • Surface Normals in OpenGL
      • NeHe Tutorials, Lesson 6 Ported to iPhone (sort of)
      • Lesson 5 Code Fixed
      • OpenGL Warning!
      • Preparations for Porting NeHe Lesson 06
      • NeHe Tutorials, Lesson 5 Ported to iPhone
      • Captain Obvious Discusses OpenGL Function Document...
      • NeHe Tutorials, Lesson 4 Ported to iPhone
      • NeHe Tutorials, Lesson 3 Ported to iPhone
      • OpenGL Project Template Redux
      • NeHe Tutorials, Lesson 2 Ported to iPhone
      • gluPerspective
      • An OpenGL Project Template for Xcode
      • Back in town
      • Next Few Days
      • Outlets - Property vs. Instance Variable
      • Speaking of Errata...
      • Happy Belated Thanksgiving
    • ►  November (25)
    • ►  October (44)
    • ►  September (2)
    • ►  August (5)
    • ►  July (2)
    • ►  June (9)
    • ►  May (2)
    • ►  April (11)
    • ►  March (17)
Powered by Blogger.

About Me

Unknown
View my complete profile