Objective 3D includes convenience classes for loading and manipulating shaders and textures. This tutorial will start where the basic tutorial left off, and add a texture to the quad that will be colored by a shader. If you didn't complete the basic tutorial you can download the files to work with.
O3D_Texture *t;
We want to load our texture in the prepareOpenGL method of our implementation file; we can do this with the following line of code:
t = [[O3D_Texture alloc] initWithBitmap:[[NSBundle mainBundle] pathForResource:@"colormap.png" ofType:nil]];
This assumes the bitmap file will be located in the Resources folder of your application, which is the default behavior if you've added the file to your project.
glEnable( GL_TEXTURE_2D );
[t bind];
Finally, we need tell OpenGL which corners of our texture are mapped to which corners of our quad. We do this with a call to glTexCoord2 before we define each vertex of our quad. The code for this is as follows:
glBegin(GL_QUADS); { glTexCoord2f(0.0f, 0.0f); glVertex3f(-.2, -.2, -2); glTexCoord2f(1, 0.0f); glVertex3f( .2, -.2, -2); glTexCoord2f(1, 1); glVertex3f( .2, .2, -2); glTexCoord2f(0.0f, 1); glVertex3f(-.2, .2, -2); } glEnd();
This will NOT be a tutorial on how to write shaders. You can use the very simple shaders included in the project to try out this tutorial. This tutorial starts from where we left off after the texture tutorial.
Bring the test.vert and the test.frag shader files into your project.
Drag the test.vert and the test.frag shader files into the copy files build phase of your project. Alternatively, leave them wherever you want on your hard drive and enter the absolute path in the next step.
Load the shader files in your prepareOpenGL method:
s = [[O3D_Shader alloc] initWithVertexPath:[[NSBundle mainBundle] pathForResource:@"test.vert" ofType:nil] fragmentPath:[[NSBundle mainBundle] pathForResource:@"test.frag" ofType:nil]];
Remember to release s in your dealloc method.