How do you add light with multiple passes in OpenGL?

1.4k views Asked by At

I have two functions that I want to combine the results of:

drawAmbient
drawDirectional

They each work fine individually, drawing the scene with the ambient light only, or the directional light only. I want to show both the ambient and directional light but am having a bit of trouble. I try this:

[self drawAmbient];

glEnable(GL_BLEND);
glBlendEquation(GL_FUNC_ADD);
glBlendFunc(GL_ONE, GL_ONE);

[self drawDirectional];

glDisable(GL_BLEND);

but I only see the results from first draw. I calculate the depth in the same way for both sets of draw calls. I could always just render to texture and blend the textures, but that seems redundant. Is there I way that I can add the lighting together when rendering to the default framebuffer?

2

There are 2 answers

0
Christian Rau On BEST ANSWER

You say you calculate the depth the same way in both passes. This is of course correct, but as the default depth comparison function is GL_LESS, nothing will actually be rendered in the second pass, since the depth is never less than what is currently in the depth buffer.

So for the second pass just change the depth test to

glDepthFunc(GL_EQUAL);

and then back to

glDepthFunc(GL_LESS);

Or you may also set it to GL_LEQUAL for the whole runtime to cover both cases.

1
brigadir On

As far as I know, you should render lighting to separate render targets and then combine them. So you will have rendered scene into these targets:

  • textured without lighting
  • summary diffuse lighting (fill with ambient color and additively render all light sources)
  • summary specular lighting (if you use specular component)

Then combine textures, so final_color = textured * diffuse + specular.