Wednesday, September 30, 2009

Drawing HTML with JOGL Part 1: Textures

I recently decided to start working with JOGL to help a friend with an assignment. He needed to be able to render basic HTML with JOGL. My first order of business was to simply draw a texture after, of course, getting a basic jogl app compiling and running.

Here is what I came up with:
// enable 2D textures
gl.glEnable(GL.GL_TEXTURE_2D);

// select modulate to mix texture with color for shading
gl.glTexEnvf(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE,
GL.GL_MODULATE);

// create the texture, you may need to find an alternative
// if this method is not available for the jogl version
// you use.
texture = TextureIO.newTexture(image, false);

// set the texture parameters to allow for proper displaying
texture.setTexParameteri(GL.GL_TEXTURE_WRAP_S, GL.GL_REPEAT);
texture.setTexParameteri(GL.GL_TEXTURE_WRAP_T, GL.GL_REPEAT);
texture.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
texture.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);

texture.bind(); // only after settings texture properties
I put the above in the GLEventListener init() method.

And then the following to render it in the display() method.
GL gl = drawable.getGL();

//variables for controlling the rendered geometry
float startX = 0.25f;
float startY = 0.25f;
float width = 0.50f;
float height = 0.50f;

//This is the good part.

//use the clear color we set
gl.glClear(GL.GL_COLOR_BUFFER_BIT);

//the gl draw mode
gl.glBegin(GL.GL_QUADS);

//set the texture coordinates for the next vertex
gl.glTexCoord2d(1.0, 1.0);

//add a two-dimensional vertex
gl.glVertex2f(startX + width, startY);

gl.glTexCoord2d(0.0, 1.0);
gl.glVertex2f(startX, startY);

gl.glTexCoord2d(0.0, 0.0);
gl.glVertex2f(startX, startY + height);

gl.glTexCoord2d(1.0, 0.0);
gl.glVertex2f(startX + width, startY + height);

gl.glEnd();

//show the back buffer if double buffering was set
gl.glFlush();
The image is a BufferedImage which was created within the program but you can use a file object in it's place to load textures directly from file.

Here is the full source code for the example:
This example uses JOGL version 1.1.1a and should work with the NetBeans plugin you can obtain the version from JOGL's website go to the "Archived Builds" page from the navigation menu on the left. Then find the jsr-231-1.1.1a folder

No comments:

Post a Comment