milgra
about
articles
projects
blogroll
bit-101
coding horror
blameit
failblog
beszeljukmac
sghu
navigation
posts
docs
admin
|
2010-01-17 iPhone openGL ES basics - textures as point sprites
January 15th, 2010
|
Okay, let's continue from "The minimal iphone opengl es application".
Let's go to the point in MinimalAppDelegate where we bind glview's layer to opengl's renderbuffer.
[ context renderbufferStorage : GL_RENDERBUFFER_OES fromDrawable : ( CAEAGLLayer * ) glview.layer ];
So we want some texture. The simplest form of a texture in opengl is a point sprite. OpenGL maps the given texture to the wanted point with the wanted size. Sounds simple, and it is.
First we have to load an image we want to use as a texture. Create a gradient sphere with alpha in a photo editor, save it as a transparent png.
We use UIImage for loading the image.
CGImageRef brushImage = [ UIImage imageNamed : @"Particle.png" ].CGImage;
We have to extract the raw byte data from the image, we use Core Foundation's DataGetBytePointer function to get the pointer to the byte array provided by CGImage's dataprovider.
GLubyte* brushData = ( GLubyte * ) CFDataGetBytePtr( CGDataProviderCopyData ( CGImageGetDataProvider ( brushImage ) ) );
We have it now, texture generation comes
GLuint brushTexture;
glGenTextures( 1 , &brushTexture );
glBindTexture( GL_TEXTURE_2D , brushTexture );
Let's set up a linear filter for the texture
glTexParameteri( GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_LINEAR );
And finally create the texture from our bytearray
glTexImage2D( GL_TEXTURE_2D , 0 , GL_RGBA , CGImageGetWidth( brushImage ) , CGImageGetHeight( brushImage ) , 0 , GL_RGBA , GL_UNSIGNED_BYTE , brushData );
Yaaay. Don't forget to free brushData array.
We have the texture, let's draw it as point sprites.We want to see smooth alpha transitions, so we have to enable alpha blending.
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE);
Let's set up the screen's dimensions for orthographic projection and for the viewport.
glMatrixMode( GL_PROJECTION );
glOrthof( 0 , 320 , 0 , 480 , -1 , 1 );
glViewport( 0 , 0 , 320 , 480 );
Enable 2D textures and point sprites.
glEnable( GL_TEXTURE_2D );
glEnable( GL_POINT_SPRITE_OES );
glTexEnvf(GL_POINT_SPRITE_OES, GL_COORD_REPLACE_OES, GL_TRUE );
Set up points for the sprites
glPointSize( 100 );
GLfloat points [ ] = { 130 , 200 , 100 , 204 };
Enable vertex array for writing
glEnableClientState(GL_VERTEX_ARRAY);
Assign vertex pointer
glVertexPointer( 2 , GL_FLOAT , 0 , points );
And finally, draw vertexes.
glDrawArrays( GL_POINTS , 0 , 2 );
And display renderbuffer.
[ context presentRenderbuffer : GL_RENDERBUFFER_OES ];
Run/debug it, you'll see two beautiful intersecting clouds :D
Download source.
MilGra
|
|