Search code examples
openglalphablendingalpha-transparency

OpenGL alpha blending inside an transparent object


I have encountered a problem when simulation transparency in OpenGL. Here is the scenario:

I have a ship which is represented by a sphere. Now I though about adding a shield around the ship. I chose a sphere too, but with a larger radius and set the alpha factor 0.5 ( opacity ). However, the shield doesn't appear and the colors don't blend( as if it was not there ).

The camera is located in the center of the 1st sphere. I think the problem is that I'm inside the sphere, so opengl will just ignore it(not draw it).

The code looks like this:

//ship colors setup with alpha 1.0f
glutSolidSphere(1, 100, 100); original sphere ( ship )
//shield colors setup with alpha 0.5f
glutSolidSphere(3, 100, 100); //the shield whose colors should blend with the rest of  the scene

I have though to simulate the shield with a parallelepiped in front of the ship. However this is not what I want...

EDIT: I have found the mistake. I was setting the near param of gluPerspective() too high, so even though i was setting the alpha value correctly, the camera was in front of the object all the time so there was no way of seeing it.


Solution

  • Seems to work here:

    #include <GL/glut.h>
    
    void display()
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(0, 0, -5);
    
        glDisable(GL_BLEND); 
        glColor4ub(255,0,0,255);
        glutSolidCube(1.0);
    
        glEnable(GL_BLEND); 
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glColor4ub(0,255,0,64);
        glutSolidSphere(1.5, 100, 100);
    
        glFlush();
        glutSwapBuffers();
    }
    
    void reshape(int w, int h)
    {
        glViewport(0, 0, w, h);
    
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        gluPerspective( 60, (double)w / (double)h, 0.01, 100 );
    }
    
    int main(int argc, char **argv)
    {
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE);
    
        glutInitWindowSize(800,600);
        glutCreateWindow("Blending");
    
        glutDisplayFunc(display);
        glutReshapeFunc(reshape);
        glutMainLoop();
        return EXIT_SUCCESS;
    }