Due to this question I have changed the method of rendering portals. Before I was using FBO and rendering to a texture, but somehow I failed. Now I switched to a stencil buffer method.
My problem is that I don't know how to set properly the stencil buffer parameters. I'm doing it like in this tutorial. I have done rendering virtual scenes to portals, but the problem is that the portals are visible always, even if they are behind the wall.
Here's my code:
glClearStencil(0);
glClear(GL_STENCIL_BUFFER_BIT | GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_STENCIL_TEST);
glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE);
glDepthMask(GL_FALSE);
glStencilFunc(GL_NEVER, 0, 0xFF);
glStencilOp(GL_INCR, GL_KEEP, GL_KEEP);
// here goes rendering the portal geometry //
// here some other properties for rendering the virtual scene
// in a portal, but that does not matter now
// this part is important:
glStencilFunc(GL_NOTEQUAL, 1, 0xFF);
glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); // this shows image 1
glStencilOp(GL_ZERO, GL_KEEP, GL_KEEP); // this shows image 2 and 3
// here goes rendering main scene //
Here are this images:
Image 1:

When changing the first glStencilOp to the second one I got it working:

But then problem occurs in other place like here:

How to deal with it?