GLTrans is a program I wrote to test out OpenGL, texturing, PNG loading, and alpha blending

Source Code

Here is the source code to the program, you will need the glpng library and headers too:

// GLTrans.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

// background texture
GLuint  texture1;

// foreground texture
GLuint  texture2;

void Update() {
	// when idle redraw the screen
	glutPostRedisplay();
}

void Display(void) {
	const float w = 2, h = 2;

	glClear(GL_COLOR_BUFFER_BIT);

	glLoadIdentity();
	glTranslatef(0, 0, -10);

	glEnable(GL_TEXTURE_2D);

	// draw background

	// bind background texture
	glBindTexture(GL_TEXTURE_2D, texture1);
	glColor3f(1, 1, 1);

	// draw background quad
	glBegin(GL_QUADS);
		glTexCoord2f(1, 1); glVertex3f( w, -h, 0);
		glTexCoord2f(1, 0); glVertex3f( w,  h, 0);
		glTexCoord2f(0, 0); glVertex3f(-w,  h, 0);
		glTexCoord2f(0, 1); glVertex3f(-w, -h, 0);
	glEnd();

	// Draw foreground

	// enable alpha blending
	glEnable (GL_BLEND);
	glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// bind foreground texture
	glBindTexture(GL_TEXTURE_2D, texture2);
	glColor4f(1, 1, 1, 0.5f);

	// draw foreground quad
	glBegin(GL_QUADS);
		glTexCoord2f(1, 1); glVertex3f( w, -h, 0);
		glTexCoord2f(1, 0); glVertex3f( w,  h, 0);
		glTexCoord2f(0, 0); glVertex3f(-w,  h, 0);
		glTexCoord2f(0, 1); glVertex3f(-w, -h, 0);
	glEnd();

	// disable textures and alpha blending
	glDisable (GL_TEXTURE_2D);
	glDisable (GL_BLEND);

	glutSwapBuffers();
}

void Reshape(int w, int h) {
	glViewport(0, 0, w, h);

	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(30, (float) w/h, 1, 100);

	glMatrixMode(GL_MODELVIEW);

	// redraw to prevent flickering
	Display();
}

// program entry point
int main(int argc, char* argv[]){

	// store info about our loaded png files in here
	pngInfo info1;
	pngInfo info2;

	// initialize glut
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); // note the rgbA <- added A for alpha
	glutInitWindowSize(300, 300);
	glutCreateWindow("glpng test"); // <- this was originally the glpng test program

	// load background texture
	texture1 = pngBind("back.png", PNG_NOMIPMAP, PNG_ALPHA, &info1, GL_CLAMP, GL_NEAREST, GL_NEAREST);

	if (texture1 == 0) {
		puts("Can't load back.png");
		exit(1);
	}

	// load foreground texture
	texture2 = pngBind("front.png", PNG_NOMIPMAP, PNG_ALPHA, &info2, GL_CLAMP, GL_NEAREST, GL_NEAREST);

	if (texture2 == 0) {
		puts("Can't load front.png");
		exit(1);
	}

	// print out some info on the images in the console
	printf("back.png Size=%i,%i Depth=%i Alpha=%in", info1.Width, info1.Height, info1.Depth, info1.Alpha);
	printf("front.png Size=%i,%i Depth=%i Alpha=%in", info2.Width, info2.Height, info2.Depth, info2.Alpha);

	// register glut functions
	glutIdleFunc(Update);
	glutDisplayFunc(Display);
	glutReshapeFunc(Reshape);

	// start the glut event loop
	glutMainLoop();

	// exit
	return 0;
}

Leave a Reply

*
*