• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
The Magical Pot

Utilizing the alpha channel on an image with OpenGL

16 posts in this topic

Hi!

 

I'm making a game using SDL and OpenGL and I've thought about how I should handle transparency in images. I don't think color keying is a good option, so the method I'm going to use is that I'm going to utilize the alpha channel on images. If I've understood it right, you have to tell the computer what the alpha channel means, so what I would want to do is to tell the computer that the alpha channel represents transparency. When I try to use the alpha channel for transparency, every pixel that doesn't have 100% opacity is given the color FFFFFF.

 

My question is simply: how do I set the alpha channel to transparency with OpenGL?

0

Share this post


Link to post
Share on other sites

Thanks for the link :) At the start of my application I enable blending like so glEnable( GL_BLEND ) and then write glBlendFunc(GL_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA), every texture I draw don't show up on the screen even though all of them are completely opaque. I tried all of the argument combinations provided under "Examples", but I get the same issue. The equations are a little bit cryptic to me, so I'm sort of having trouble solving my issue. Any suggestions?

0

Share this post


Link to post
Share on other sites

In order for us to help with your problem, you need to provide specifics: post relevant code (setup, render, etc...) and perhaps post a screenshot of the actual result at one of the image sharing sites such as imgur.com along with a description of what you expect to happen so we can compare it with what is actually happening. As you might imagine, merely posting a sentence such as "every texture I draw don't show up on the screen" really isn't all that helpful for debugging.

0

Share this post


Link to post
Share on other sites

Thanks for the link smile.png At the start of my application I enable blending like so glEnable( GL_BLEND ) and then write glBlendFunc(GL_SRC_ALPHAGL_ONE_MINUS_SRC_ALPHA), every texture I draw don't show up on the screen even though all of them are completely opaque. I tried all of the argument combinations provided under "Examples", but I get the same issue. The equations are a little bit cryptic to me, so I'm sort of having trouble solving my issue. Any suggestions?

 

Did your texture show on the screen before you enabled GL_BLEND?  post some source code for us to see.

0

Share this post


Link to post
Share on other sites

I use SDL for everything except for rendering, which I use OpenGL for. I initialize OpenGL with this function (this is with blending enabled):

bool initGL()
{
    //Set the viewport
    glViewport( 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT );

    //Initialize Projection Matrix
    glMatrixMode( GL_PROJECTION );
    glLoadIdentity();
    glOrtho( 0.0, SCREEN_WIDTH, SCREEN_HEIGHT, 0.0, 1.0, -1.0 );

    //Initialize Modelview Matrix
    glMatrixMode( GL_MODELVIEW );
    glLoadIdentity();

    //Initialize clear color
    glClearColor( 0.f, 0.f, 0.f, 1.f );

    //Enable texturing
    glEnable( GL_TEXTURE_2D );

    //Enable blending
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable( GL_BLEND );

    //Check for error
    GLenum error = glGetError();
    if( error != GL_NO_ERROR )
    {
        printf( "Error initializing OpenGL!\n" );
        return false;
    }

    return true;
}

The Image in this post shows what the application renders without the enabling of blending on the left side, the right side is what it renders when I enable blending. The blue window within the application is made out of pieces of textures for the frame and the center is a colored quad, so when I render textures, they're not shown, but when I render geometrical shapes without textures, they're shown.

 

The for the rendering of that blue window within my application is quite large, so I'm just going to take out the rendering of one piece of texture and the rendering of a non-textured quad:

 

Non-texture quad rendering:

        /******Window fill******/

	glLoadIdentity();		//Remove any previous transformations
	glDisable( GL_TEXTURE_2D );		//Temporarily disable textures so that the colors won't get messed up

	glTranslatef( box.x + ThemeTemplate->quadWidth, box.y + ThemeTemplate->quadHeight, 0.f ); //Move to rendering point

	//Render the window fill
	glColor3ub( 0, 17, 34 );
        glBegin( GL_QUADS );
            glVertex2f( 0.f, 0.f );
            glVertex2f( box.w - ( ThemeTemplate->quadWidth * 2 ), 0.f );
            glVertex2f( box.w - ( ThemeTemplate->quadWidth * 2 ), box.h - ( ThemeTemplate->quadHeight * 2 ) );
            glVertex2f( 0.f, box.h - ( ThemeTemplate->quadHeight * 2 ) );
        glEnd();

	glEnable( GL_TEXTURE_2D );		//Re-enable textures
	glColor3f( 1, 1, 1 );		//Reset the color

	/******------End------******/

I basically just render a quad at a preset location with the color R0 G17 B34 and then reset the color to FFFFFF so that the next thing that's rendered won't have its colors messed up by this quad's colors.

 

Texture rendering:

/******Top edge******/

glLoadIdentity();		//Remove any previous transformations

//Texture coordinates
ThemeTemplate->texLeft = 16.f / TexWidth;
ThemeTemplate->texRight = 18.f / TexWidth;
ThemeTemplate->texTop = 0.f;
ThemeTemplate->texBottom = 8.f / TexHeight;

//Set translation point
TranslateX = box.x + ThemeTemplate->quadWidth;
TranslateY = box.y;

glTranslatef( TranslateX, TranslateY, 0.f );		//Move to rendering point

//Fill the whole space
for ( int positionX = 0; positionX < ( box.w - ( ThemeTemplate->quadWidth * 2 ) ); positionX += 2 )
{
	//Render textured quad
	glBegin( GL_QUADS );
	   glTexCoord2f( ThemeTemplate->texLeft,  ThemeTemplate->texTop );    glVertex2f          ( 0.f,	0.f );

	  glTexCoord2f( ThemeTemplate->texRight, ThemeTemplate->texTop );    glVertex2f(          2.f,	0.f );

	  glTexCoord2f( ThemeTemplate->texRight, ThemeTemplate->texBottom ); glVertex2f(          2.f,	ThemeTemplate->quadHeight );

	  glTexCoord2f( ThemeTemplate->texLeft,  ThemeTemplate->texBottom ); glVertex2f(          0.f,	ThemeTemplate->quadHeight );
	glEnd();

	glTranslatef( 2, 0, 0.f );	//Update rendering point
}

/******------End------******/

This is the top egde of the window's frame, I first select a piece of a sprite sheet and then set the rendering point. The frame is build up by small textures lined up to form a frame, so the for loop just makes sure that the textures are rendered next to each other. I then simply make a quad and render a texture that comes from a section of a spritesheet, this section is set with 'ThemeTemplate->texLeft' ect.

 

I'm quite confused when it comes to the source of the problem as I'm new to OpenGL, but perhaps the problem lies in my loading of textures?

 

(Sorry for the code dump)

bool Texture::load_texture( SDL_Surface *image )
{
	// Check that the image's width is a power of 2
        if ( (image->w & (image->w - 1)) != 0 )
	   fprintf( stderr, "warning: image.bmp's width is not a power of 2\n");
    
        // Also check if the height is a power of 2
        if ( (image->h & (image->h - 1)) != 0 )
           fprintf( stderr, "warning: image.bmp's height is not a power of 2\n");

	//Get the number of channels in the SDL_Surface
	nOfColors = image->format->BytesPerPixel;
	if ( nOfColors == 4 )
	{
		fprintf( stderr, "4 channels on texture\n" );
		if ( image->format->Rmask == 0x000000ff )
			texFormat = GL_RGBA;
		else
			texFormat = GL_BGRA;
	}
	else if ( nOfColors == 3 )
	{
		fprintf( stderr, "3 channels on texture\n" );
		if ( image->format->Rmask == 0x000000ff )
			texFormat = GL_RGB;
		else
			texFormat = GL_BGR;
	}
	else
	{
		fprintf( stderr, "warning: the image is not truecolor\n" );
		//This error should not go unhandled
	}
    
        // Have OpenGL generate a texture object handle for us
        glGenTextures( 1, &data );
    
        // Bind the texture object
        glBindTexture( GL_TEXTURE_2D, data );
        
        // Edit the texture object's image data using the information SDL_Surface gives us
	glTexImage2D( GL_TEXTURE_2D, 0, nOfColors, image->w, image->h, 0, texFormat, GL_        UNSIGNED_BYTE, image->pixels );

	// Set the texture's stretching properties
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );

	// Unbind texture
        glBindTexture( GL_TEXTURE_2D, NULL );

	// Save the dimensions of the texture
	TextureWidth = (float)image->w;
	TextureHeight = (float)image->h;

	return true;
}

The output to stderr is "4 channels on texture", for every texture, so all of the textures in my application has 4 channels. (I'm loading .png files, so they should also have 4 channels).

 

Let me know if there's something else you need to know.

0

Share this post


Link to post
Share on other sites

You need to call glBindTexture( GL_TEXTURE_2D, yourTextureID ); before you call glBegin( GL_QUADS ) for your textured quads.  Are you doing this? 

0

Share this post


Link to post
Share on other sites

You need to call glBindTexture( GL_TEXTURE_2D, yourTextureID ); before you call glBegin( GL_QUADS ) for your textured quads.  Are you doing this? 

Yes, there's a line in the last code snippet 'bool Texture::load_texture( SDL_Surface *image )' where I call that function

// Bind the texture object
glBindTexture( GL_TEXTURE_2D, data );

This line is executed before I draw anything.

 

I also forgot to show the picture, so here it is: https://twitter.com/TheMagicalPot/status/359349302939754496

 

"The Image in this post shows what the application renders without the enabling of blending on the left side, the right side is what it renders when I enable blending. The blue window within the application is made out of pieces of textures for the frame and the center is a colored quad, so when I render textures, they're not shown, but when I render geometrical shapes without textures, they're shown."

0

Share this post


Link to post
Share on other sites

 

You need to call glBindTexture( GL_TEXTURE_2D, yourTextureID ); before you call glBegin( GL_QUADS ) for your textured quads.  Are you doing this? 

Yes, there's a line in the last code snippet 'bool Texture::load_texture( SDL_Surface *image )' where I call that function

 

I see that you bind a texture when you are creating the texture, but at the end you also unbind glBindTexture( GL_TEXTURE_2D, NULL );

 

This means that you have no texture active.  If you go and try to render a texture but you don't have a texture bound, then you are not going to see anything.  

 

When you are calling glTexCoord2f, you need to make sure that you have a bound texture.  I don't see a glBindTexture call in that part of your code.

 

As a simple test, delete glBindTexture( GL_TEXTURE_2D, NULL )

1

Share this post


Link to post
Share on other sites


As a simple test, delete glBindTexture( GL_TEXTURE_2D, NULL )

It didn't solve the problem. I forgot to add a piece of code, I bind the texture right before I render it:

glBindTexture( GL_TEXTURE_2D, ThemeTemplate->TemplateSheet->get_data() );		//Set texture ID

I really don't know what the problem is, but maybe it has something to do with the arguments passed when I enable blending?

0

Share this post


Link to post
Share on other sites

perhaps your texture file loader code is not working.... did you look in your debugger to see what values you have for:

 

image->w

image->h

image->pixels

0

Share this post


Link to post
Share on other sites

The values for image->w and image->h are correct, I have no idea about how to check image->pixel which is a pointer of type void, but when I write image->pixels as an integer, the output for a 32x32 texture is "86048840" if that says anything.

 

I searched a bit more about other people who have the same problem, but the only solution I've found was to switch over to the DevIL which takes care of image loading.

0

Share this post


Link to post
Share on other sites

your image->pixels value will be a bunch of bytes that represent all your pixel data.  For example if you are sending RGBA values then you will have 4 bytes per pixel.  each byte is just a value from 0 to 255 which represents the color or alpha value.  

0

Share this post


Link to post
Share on other sites

I still don't know how to check such information, but it seems like there shouldn't be anything wrong with the pixels since the textures work fine when blending isn't enabled. It however seems like this problem isn't really going anywhere, so I could try with the DevIL image loading library instead of SDL's one.

0

Share this post


Link to post
Share on other sites

Ok, I gave up on SDL's image loading thingy and switched over to DevIL and it worked perfectly. For me I just added this piece of code right after I initialized OpenGL:

glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_BLEND );

This will basically enable blending (check out http://www.opengl.org/sdk/docs/man/xhtml/glBlendFunc.xml for more information about glBlendFunc).

 

To find out how to install and load images with DevIL into OpenGL textures, I'd recommend this link: http://lazyfoo.net/tutorials/OpenGL/06_loading_a_texture/index.php

 

Note: for Visual Studio users, you have to open up 'ilu.h' and replace the line:

#include <IL/il.h>

With:

#include <il.h>

Since Visual Studio don't include certain files in the same way that other IDEs do.

 

That worked for me, I hope it works for anyone else who's having the same problem :)

0

Share this post


Link to post
Share on other sites

It might actually be the case that SDL only supports colorkeying and not blending, that might explain it since I've successfully used SDL for colorkeying while blending didn't work.

0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0