Login  Register

Re: Rendering transparent triangles with opengl...

Posted by Xerxes Rånby on May 26, 2015; 7:38pm
URL: https://forum.jogamp.org/Rendering-transparent-triangles-with-opengl-tp4034507p4034528.html

I took a look at your code and have identified some logical errors made:

#1
You have requested alpha bits in the GLCapabilites
caps.setAlphaBits(8);
making it possible for the alpha part of each draw operation to be stored on the destination surface.
You also use the following blend function
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
causing the source triangles alpha part to control opaqueness when drawing the triangles.
This combination do not work for you because the alpha is used twice.

I have two suggested "solutions" to you:

A: Do not request a surface with AlphaBits, use:
caps.setAlphaBits(0);
This will make alpha blending behave as you expected, the alpha is then only used once to control the opaqueness of each triangle and no traces of the alpha is stored at the destination surface.
Like this:


B: If you want a surface with AlphaBits, use the following blend function:
"Premultiplied Alpha Blending"
gl.glBlendFunc(GL.GL_ONE, GL.GL_ONE_MINUS_SRC_ALPHA);

This make the triangles slightly brighter compared to your Java2D version but the effect is similar.
This blending mode work for both caps.setAlphaBits(0); and caps.setAlphaBits(8);

I really enjoyed the following page while writing this answer that describes the OpenGL Blending stage using GLSL equations:
http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Transparency

#2
When storing the gl pixels to a BufferedImage you should use:
bufferUtil = new AWTGLReadBufferUtil(glp, true);
image = bufferUtil.readPixelsToBufferedImage(gl, false);

This will make the red and blue correct in the generated png file.

#3
Your Java2D example and your JOGL example do not use the random number generator identically therefore you got two different compositions of triangles despite using the same random number generator seed.

#4
Your JOGL example happened to render 100000 triangles while your Java2D example rendered 100.
You may want to drop the for loop around render 100 random triangles ;)

for (int i = 0; i < 1000; i++) {
            TrianglesJoglHelper.renderRandomTriangles(gl, rng, 100, Width, Height);


I had to fix 2,3&4 in order to be able to compare the jogl and your java2d output.