LWJGL lighting

Started by Skatty, July 06, 2013, 08:17:53

Previous topic - Next topic

Skatty

Hello

I have voxel engine, like minecraft and i would ask you: how i can implement a simple light into a game? Like on example i put a sun-light, set its x,y,z power and angle and it light in that direction

Morin

Sunlight is parallel rays, so there is no (x, y, z) -- the light comes from an infinitely far plane, not from a point.

Other than that, you'll have to compute the effect of the light on every surface (polygon). Again, for sunlight, the only thing that matters is the angle between the light rays and the polygon plane.

For simple light, let's assume:
- purely diffuse reflection
- white light
- no shadows

Then the effect of the light boils down to computing the cosine of the angle between light rays and the polygon plane normal. Assuming you have normalized both the lght direction vector and the polygon normal vector, that cosine is the dot product of the two vectors:

c = -(lightDirectionX * polygonNormalX + lightDirectionY * polygonNormalY + lightDirectionZ * polygonNormalZ)

The negation is needed because/if normals point out of the cubes, because then normals are in opposite direction to the light rays.

Again, for minecraft, the polygon normals are usually very simple (e.g. (0, 1, 0) for the top face of a cube), so that equation is further simplified. The light direction is something you can control, and even modify to simulate day and night.

Then, just multiply the arguments to glColor with that c value above.

Morin

Slightly more advanced: Don't just use c for glColor, but

- cap c so it can't go below zero
- use e.g. (0.7 * c + 0.3).

Then unlit cube sides won't be totally dark. (This is in fact bringing ambient reflection into the scene, in addition to diffuse reflection)


quew8

This: http://arcsynthesis.org/gltut/ has a great tutorial on lighting in OpenGL (along with a lot of other great stuff).
Also, it has been ported to LWJGL by ra4king over 10 months (show some love) http://www.java-gaming.org/topics/fully-ported-arcsynthesis-tutorial-code/29767/view.html.