How to compose two fbos with the correct depth?

Hi. I would like to have a Final fbo with depth, initially transparent. I would grow items on a Growing fbo. When items are done growing, I would draw them into Final. The depth should be right, so if the growing item is further back behind other things, it should be occluded, if it’s closer, it should be visible.

I did this experiment but I couldn’t get the depth of both fbo’s mixing. The second one is always on front. Comments are my random experiments :slight_smile:

#include "ofApp.h"

//--------------------------------------------------------------
void ofApp::setup(){

    ofFbo::Settings settings;
    settings.width = 400;
    settings.height = 400;
    settings.useDepth = true;
    fboRed.allocate(settings);
    fboGreen.allocate(settings);

}

//--------------------------------------------------------------
void ofApp::update(){

    //fboRed.activateAllDrawBuffers();
    //fboGreen.activateAllDrawBuffers();

    //fboRed.clearDepthBuffer(0);
    fboRed.begin();
    ofClear(255, 0);
    ofTranslate(200, 200);
    ofRotateYDeg(ofGetFrameNum());
    ofSetColor(ofColor::red);
    ofDrawBox(200, 50, 5);
    fboRed.end();

    //fboGreen.clearDepthBuffer(0);
    fboGreen.begin();
    ofClear(255, 0);
    ofTranslate(200, 200);
    ofRotateYDeg(ofGetFrameNum() * -1.0f);
    ofSetColor(ofColor::green);
    ofDrawBox(200, 50, 5);
    fboGreen.end();

}

//--------------------------------------------------------------
void ofApp::draw(){
    //ofEnableDepthTest();
    //ofSetDepthTest(true);
    ofBackground(0);
    fboRed.draw(0, 0);
    fboGreen.draw(0, 0);  // <-- this is always on top
}

image
How could I make use of the depth stored on each fbo, so the second one is not always on top?

you need to create a shader that takes two textures for the color and two for the depth and do the depth testing manually in the fragment shader for each pixel check the depth of the first and second buffer and draw one or the other if the depth of the first is greater than the second or viceversa

1 Like

You can also get the depth stencil from the FBO