OpenGL Tutorial #5
-- "Blending" --

paradox/vivid

Introduction

Welcome to OpenGL tut numero cinq! What's up this time? Blending using OpenGL, I'll just show you how to do a blended rotating cube, pretty lame, but you can do something better with it, all you really need is a few nice models and ideas.

Alpha Blending

If you don't know the applications or theory of alpha blending either go to some previous Hugi issue (I saw in 15 I think) and learn it from there, or, better still, go to my Texture Generation article and read the explaination from it.

Under OpenGL there are lots of different ways to blend, eg Alpha Blending or saturated adds and others, I think there are nine ways in total, but I'm not sure.

To blend we first say, glEnable(GL_BLEND). Then we set the blending function, using glBlendFunc(), this takes two parameters, the operations on the source and destination pixels, here is how to alpha blend, glBlendFunc(GL_SRC_ALPHA, GL_ONE)

I am only 99% sure that that blending function is alpha blending, so please, don't flame me too hard.

Now we must set the alpha parameter, we can use glColor4f to do this, look - glColor4f(1.0f, 1.0f, 1.0f, 0.5f) specifies that the image be drawn at full brightness and half transparency.

Also, you can specify alpha values in for each pixel in a texture, by changing the function to load the texture,

glTexImage2D(GL_TEXTURE_2D, 0, 4, 256, 256, 0, GL_RGBA, GL_UNSIGNED_BYTE,
	     Texture);

Which means you can do all sorts of neat things...as you'd imagine.

Now you can have a rotating blended cube, but we're not finished yet.

Z Buffers

Ok, when you stick those 3 lines of code into your program it'll give wierd crap looking effects. First of all we disable back face culling, which is off by default anyway.

Now, we must also disable our depth buffer (which is really a z buffer but it is given this crap name by opengl), this is so we get overdraw to blend with. we do glDisable(GL_DEPTH_TEST), because the depth testing is on by default.

After doing the above your blending will look nice.

Lighting Models

Up until now you have been using the default parameters for your lighting model, however, you can set the lighting model with glLightModel.

There are various different lighting models, but we'll just deal with one, two sided lighting, to enable this you do:

glLightModelf(GL_LIGHT_MODEL_TWO_SIDE, 1.0f)

GL_LIGHT_MODEL_TWO_SIDE lights the back polygons as well as the front ones, and before it lights them it reverses their normals. This (obviously?!) has the effect that they are being lit from the front, it looks supercool when you do this using blending.

1.0f says to turn on two sided lighting.

Conclusion

Ok, well, thus ends another OpenGL basics tutorial, I hope you liked it a bit. Sorry again, for inaccuracies and other things unpleasant to you (just in this tutorial, not in life in general).

par'dox/vivid