Under the Bridge

Snippet: Texture Sizes

Here’s a cute little snippet for automatically transmogrifying your OpenGL textures into iPhone-acceptable dimensions at runtime if you don’t want to go to the trouble of sorting out the source assets, because maybe you’re porting existing assets from another platform, or your artists can’t follow directions, or whatever:

First off, figure out power-of-two dimensions:

  1. //     Adjust the width and height to be a power of two
  2. if( (_width != 1) && (_width & (_width – 1)) )
  3. {
  4. i = 1;
  5. while((sizeToFit ? 2 * i : i) < _width)
  6. i *= 2;
  7. _width = i;
  8. }
  9. if( (_height != 1) && (_height & (_height – 1)) )
  10. {
  11. i = 1;
  12. while((sizeToFit ? 2 * i : i) < _height)
  13. i *= 2;
  14. _height = i;
  15. }

You could figure that out on your own no doubt, but you might miss this; if it turns out that the image is too big, your friend CGAffineTransform can sort that out for you!

  1. //      scale down an image greater than the max texture size
  2. while((_width > kMaxTextureSize) || (_height > kMaxTextureSize))
  3. {
  4. _width /= 2;
  5. _height /= 2;
  6. transform = CGAffineTransformScale(transform, 0.5, 0.5);
  7. imageSize.x *= 0.5;
  8. imageSize.y *= 0.5;
  9. }

That’s quicker than going through and canonizing a large asset base yourself, indeed. Read the rest of the article for further explanation; and this is part of the D’Jinn Engine for the iPhone which can be found on Google Code. Enjoy!

h/t: iPhoneDevelopmentBits!

0