Transparency Holdout

The thing is, a render in Panda generally doesn’t have a transparent background. It’s usually opaque.

However, if the clear-colour were to contain 0 alpha, then I would imagine that this technique would indeed produce a transparent cutout, as it would show the backdrop–in that case transparency–in the cutout region.

Put it this way:

  • At the start of the frame, with a clear-colour that’s transparent, you have a buffer that contains pixels with an alpha of zero.
  • Then we render the “cutout” object, while–being transparent–doesn’t change the colour-buffer–but does change the depth-buffer.
  • Then we render the “solid” object, which changes both the colour- and depth- buffers–but only where it passes the depth-test, which it won’t where the “cutout” object was placed.

Thus we end up with a transparent hole in the middle of the “solid” object.

Here below is a short program that demonstrates this. Press “space” to record a screenshot, which you should find has a transparent background and hole.

from direct.showbase.ShowBase import ShowBase

from panda3d import __version__ as pandaVersion
print (pandaVersion)

import sys
print (sys.version)

class Game(ShowBase):
    def __init__(self):
        ShowBase.__init__(self)

        self.setBackgroundColor(0, 1, 0, 0)

        obj1 = loader.loadModel("panda")
        obj1.reparentTo(render)
        obj1.setPos(0, 25, -7)
        obj1.setBin("fixed", 0)

        obj2 = loader.loadModel("smiley")
        obj2.reparentTo(render)
        obj2.setPos(0, 15, 0)
        obj2.setColorScale(0, 0, 0, 0.01)
        obj2.setTransparency(True)
        obj1.setBin("fixed", 1)

        self.accept("space", self.takeScreenshot)

    def takeScreenshot(self):
        self.win.saveScreenshot("test.png")

app = Game()
app.run()

The only caveat is that if the “cutout” object’s colour-scale is set to have an alpha of “0” (or indeed, below a certain threshold), it doesn’t seem to be rendered at all. Hence my setting the alpha above to “0.01”. I don’t know offhand if there’s a way to disable this behaviour–but I’d be very unsurprised if there was!

But otherwise, you should find that this produces a screenshot with a transparent cutout in the middle of a solid model!

(I tried embedding the rendered screenshot, but it looks like transparency doesn’t show up on the forum. Just run the program, and you should see!)

1 Like