Jary316
Jary316

Reputation: 321

OpenGL Fade in / fade out a texture2D

I am writing an application that displays .jpg files that are stored as Texture2D (RGB) in OpenGL. I want to smoothly change from one texture2D to the next by fading to black, then fading into the next texture.

After looking for some explanation I wrote something like this.

void renderTexture()
{
  glMatrixMode(GL_MODELVIEW);

  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, mTexture);

  gluSphere(mQuad, 1.0f, 50, 50);

  glBindTexture(GL_TEXTURE_2D, 0);
}

void fadeToBlack()
{
  glEnable(GL_BLEND);
  glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

  for (GLfloat alpha = 1.0; alpha > 0.0; alpha -= 0.05)
  {
    glColor4f(0.0, 0.0, 0.0, alpha);
    renderTexture();

    glFlush();
    glutSwapBuffers();
  }

  glDisable(GL_BLEND);
}

Unfortunately, this does not fade to black but instead switches to black immediately. I must have some misunderstanding on how GL_BLEND is working here. Can somebody please point out what I am doing wrong?

** EDIT: This did the trick. Thanks a lot j-p and Benjamin for the pointers **

void fadeToBlack()
{
  for (GLfloat alpha = 1.0; alpha > 0.0; alpha -= 0.001)
  {
    renderTexture();
    glColor4f(alpha, alpha, alpha, alpha);

    glFlush();
    glutSwapBuffers();
  }
  glColor4f(1.0, 1.0, 1.0, 1.0);
}

Upvotes: 0

Views: 1685

Answers (1)

Benjamin James Drury
Benjamin James Drury

Reputation: 2383

The for loop will be executing so quickly that the texture changes will appear to happen instantly.

Upvotes: 1

Related Questions