How do I draw a mirror mirroring something in OpenGL?

user1939871 picture user1939871 · Dec 11, 2013 · Viewed 13.8k times · Source

From my understanding is that to mirror in OpenGL, you basically draw the scene, then you flip everything over and draw it again, except only make it visible through the mirror, thus creating a perfectly flipped image in the mirror. But the problem I see, is that when doing this, the only mirrors that can see other mirrors are ones rendered after the previous mirrors. So if I render mirror 1 then mirror 2, mirror 1 can't see mirror 2, but mirror 2 can see mirror 1. How do I effectively mirror a mirror without this happening?

Answer

jozxyqk picture jozxyqk · Dec 11, 2013

There are two common ways to render reflections with multiple/recursive reflections...

  1. Render to a texture and apply that texture to the mirror surface.

    An advantage of this is you can use the mirror textures of other mirrors from the previous frame. While this introduces small delay, it doesn't hurt performance when you want to see through many mirrors. If this is an issue you could re-render to the reflection textures a few times before the main camera render.

    You can also use this method if the mirror isn't perfectly planar, for example this works well for ripples in water. In fact this can even be extended with cube maps to support approximate arbitrary reflections.

    enter image description here

  2. Portal rendering where, as you say, use the stencil buffer to mask off the mirror surface, flip the scene around the mirror's plane, and re-render.

    Mirror rendering is just a special case of portal rendering. This can be done recursively but it gets quite complicated as you have to manage the depth buffer correctly. You will also need a spatial data structure for your scene, so you don't have to do a full re-render and only render what you can see through the mirror (or it gets very slow very quickly). If you go down this path, I'd suggest taking it slowly and include lots of visual debugging and use a simple and intuitive test scene.

    enter image description here

    (There are lots of pages on single-reflection stencil buffer use, but this isn't what you're after so I won't bother listing some)

*Please note these links are just the result of a few minutes googling. Feel free to edit and remove/add.