Question

Me and my crew just ported our game from java2d to LWJGL and want to add lighting now. What we exactly want to add:

  • items/entities that emit light and are moveable.
  • Static lighting

We've googled for quite some time now but are kind of lost because we have no idea where to start. We've seen the alpha mapping method but couldn't really get it to work.

I would be glad if someone could give me an answer.

Thanks!

Was it helpful?

Solution

Creating lights is probably easier than one would think! The following code will create a light and enable lighting, though different parameters can be used also you can change and use things like GL_SPECULAR, etc.

FloatBuffer ambient = BufferUtils.createFloatBuffer(4);
ambient.put(new float[] { 0.05f, 0.05f, 0.05f, 1f, });
ambient.flip();    

FloatBuffer position = BufferUtils.createFloatBuffer(4);
position.put(new float[] { 0f, 0f, 0f, 1f, });
position.flip();    

glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightModel(GL_LIGHT_MODEL_AMBIENT, ambient);
glLight(GL_LIGHT0, GL_POSITION, position);

Remember that you need to use and calculate normals, because light gets calculated using them.

If you don't use textures and want light to be applied to simple colors, then you can add the following where you initialize your OpenGL states.

glEnable(GL_COLOR_MATERIAL);

Also if there are some part you don't want to be affected by lighting like UI, then before rendering the UI you call glDisable(GL_LIGHTING); and then you call glEnable(GL_LIGHTING); again after then UI if you want lighting to be enabled afterwards.

Remember

If you don't statically import classes, then just to notify you that glEnable(GL_LIGHTING); would be GL11.glEnable(GL11.GL_LIGHTING); like everything else I just showed you.

Also take in mind that OpenGL only contains 0 lights from GL_LIGHT0 to GL_LIGHT7, though more lights can easily be created within different ways.

Important if you think using OpenGL lights will generate shadows, then this code will disappoint you, creating shadows is a combination of OpenGL lights and some advanced FBO work, if I remember correctly.

Extra

If you want movable lighting the you just need to update the glLight(GL_LIGHT0, GL_POSITION, position); each time you move the light.

Here is a little Lighting Types tutorial, I found just by searching "opengl lighting", the tutorial though is written in C++, but OpenGL functions are almost the same no matter which language you're using, only some tiny changes which is easy to spot and change. http://www.swiftless.com/tutorials/opengl/lighting_types.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top