""

Archive for June, 2009

gl_java_ubuntu1

Here are the detailed steps to set up or install JOGL on your ubuntu. First of all you have to download the jogl library(according to your machine) from here . I am using Ubuntu 8.04 on intel board so i downloaded jogl-1.1.1-linux-i586.zip.

So extract the zip file. Now open the folder that you have just now extracted. Go to lib folder.

STEP 1: Now you have to copy four .so files i.e libjogl.so, libjogl_awt.so, libjogl_cg.so, libgluegen-rt.so to [javainstalation directory]/jre/lib/i386

Open the terminal window and type: sudo cp libjogl.so /usr/lib/java/jdk1.6.0_13/jre/lib/i386

similarly you have to copy other three .so files.

*you have to provide you java installation path*

jogl1

Now you can check the destination if files has been copied.

jogl21

STEP 2: Now copy jogl.jar and gluegen-rt.jar to [java installation di]/jre/lib/ext

run this command to copy: sudo cp jogl.jar /usr/lib/java/jdk1.6.0_13/jre/lib/ext

simillarly copy gluegen-rt.jar

*you have to provide your java installation path*

jogl3

You can check:

jogl4

STEP 3: SO thats it. Now lets test the simple jogl code.

import javax.media.opengl.GLCapabilities;

public class Hello{
public static void main (String args[]) {
try {
System.loadLibrary(“jogl”);
System.out.println(
“Hello World! (The native libraries are installed.)”
);
GLCapabilities caps = new GLCapabilities();
System.out.println(
“Hello JOGL! (The jar appears to be available.)”
);
} catch (Exception e) {
System.out.println(e);
}
}
}

Now compile this Hello.java and the run it. Here is the output:

jogl-final

So thats it. Now your are off to fly and write your jogl apps.

Thanks.

Alpha Blending using OpenGL with SDL

sdl_opengl

Alpha Blending is a convex combination of two colors allowing for transparency effects in computer graphics. Blending is used to combine the color of a given pixel that is about to be drawn with the pixel that is already on the screen. How the colors are combined is based on the alpha value of the colors, and/or the blending function that is being used. Alpha is a 4th color component usually specified at the end.

Alpha Blending in SDL is slow because its not a hardware accelerated. To get a better performance there is OpenGL which is hardware accelerated. So here i’l show you how to use alpha blending using opengl with sdl.


glColor4f(1.0f,1.0f,1.0f,alpha); // full Brightness, Alpha

glBlendFunc(GL_SRC_ALPHA,GL_ONE); // Blending Function for  translucency based on source alpha value>

First line set the color to full brightness with alpha value. An alpha value of 0.0 would mean that the material is completely transparent . A value of 1.0 would be totally opaque. The primitive’s opacity is specified using glColor4*(). RGB specifies the color, and the alpha parameter specifies the opacity.


glEnable(GL_BLEND);                      // Turn Blending on

glDisable(GL_DEPTH_TEST);        //Turn Depth Testing off

So this is it what you will required to achieve alpha blending.

Below code is a simple FADE IN/FADE OUT program. When UP arow key is pressed then 2d sprite will fade out and when DOWN key is pressed then 2d sprite will fade in.

alpha

Here is the full Source Code:

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL;     //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

float alpha=1.0f;
bool UP=false;         //Up key is pressed/released
bool DOWN=false;       //DOWN key is pressed/released

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

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

// 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 );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
glClear( GL_COLOR_BUFFER_BIT );   // Clear the screen before drawing

glTranslatef(300.0,200.0,0.0);

glBindTexture( GL_TEXTURE_2D, texture );   // Bind the texture to which subsequent calls refer to

glColor4f(1.0f,1.0f,1.0f,alpha);            // Full Brightness, Alpha
glBlendFunc(GL_SRC_ALPHA,GL_ONE);           // // Blending Function For Translucency Based On Source Alpha Value

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D );        // Need this to display a texture
glEnable(GL_BLEND);                  // Turn Blending On
glDisable(GL_DEPTH_TEST);         //Turn Depth Testing Off

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=true;
break;
case SDLK_DOWN:
DOWN=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_UP:
UP=false;
break;
case SDLK_DOWN:
DOWN=false;
break;
}
}
}

// If UP key is pressed

if(UP==true){
if(alpha<1.0f)         // make sure alpha value is not greater than maximum value 1.0
alpha+=0.01f;       //increase the alpha value, fade out
drawImage();
}

else if(DOWN==true){    //If DOWN key is pressed
if(alpha>0.0f)       // make sure value of alpha is not less than 0.0f
alpha-=0.01f;      // decrease the alpha value, fade in
drawImage();
}

}

clean_up();
return 0;
}

So thats it. Now you are off to fly.

Gracias.


java_ubuntu

When u install sun’s jdk manually on ubuntu, java classpath doesn’t get set automatically unlike in windows. So when you enter command javac in terminal window, it says “javac  command not found”. So here is the very simple way to set up the classpath for java on ubuntu.

STEP 1 : Open the terminal window.

STEP 2: Type sudo gedit /etc/bash.bash.rc. Press enter.

STEP 3: Now gedit editor will open up. Now at the end of file just write:

PATH=$PATH:/usr/lib/java/jdk1.6.0_13/bin

export PATH

**You have to provide the path of bin folder in java installation deirectory.**

screenshot-12

STEP 4: Now save the file and close the editor and terminal. Open new terminal window and type javac and press enter, all the java options and flags will come up.

Thats it.

Thanks.

If you are making a java program for windows operating system only then  wouldn’t it be easy to have a exe file for your java program and distribute it to the users and user would find easy to execute your program. Well i guess yes because exe would definetly make easy for users to execute your java programs. So:

Q. How to make an exe file for your java program ?

A. exe4J.

exe4j is a Java exe maker that helps you integrate your Java applications into the Windows operating environment, whether they are service, GUI or command line applications. If you want your own process name instead of java.exe in the task manager and a user friendly task-bar grouping in Windows XP, exe4j does the job. exe4j helps you with starting your Java applications in a safe way, displaying native splash screens, detecting or distributing suitable JREs and JDKs, startup error handling and much more.

Check out the features of exe4J. Download(i would suggest you to download zip archive) the exe4J from here.

Ok now i’ll show you the steps to use exe4J for making exe. So download the exe4J zip archive and extract it to your preference location. Here i’ll be showing you how to create exe file for your java executable jar file. So lets first write a simple swing frame application which will just create a frame.

import javax.swing.*;

public class Test
{
public Test(){
JFrame frame=new JFrame(“test”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,300);
frame.setVisible(true);
}
public static void main(String[] args){
new Test();
}
}

Ok save Test.java it in some folder ( I have saved it in E:/java_programs).

Now open your  command prompt, navigate to the folder where Test.java file is saved and compile the Test.java using command javac Test.java

Now we’ll create a manifest file which will be needed to make an executable jar file. So this is the way you write your manifest file:

Main-Class: Test

First line on your manifest file will be Main-Class:<space>main-class(class file with the main method). then new line<enter>. You have to provide one new line after first line. Then save it as manifest.txt to the same folder where your Test.class file is saved.

Now we’ll create the executable jar file. Syntax is:  jar -cvmf manifest.txt <name of jar file that you will create> class file/package if used

so open up your command prompt, navigate to the folder where Test.class file and manifest file is saved. Then enter command jar -cvmf manifest.txt test.jar Test.class and press enter. Yout executable jar file is created. You can check and test it(java -jar test.jar).

Now executable jar file is ready. So now i’ll show you the steps to make exe from your executable jar file.

STEP 1: Open the folder that u had extracted. Go to bin folder. Double click exe4j launcher. Now exe4j window will open up. Click next.

1

STEP 2: Choose “JAR in EXE” mode. Click next.

2

STEP 3: Now give the name for your application. I have given “app”. Then give the path of the location where you want to save the exe file. I have given the path of location where my class, manifest and jar file are located i.e E:/java_programs. Click next.

3

STEP 4: Now choose your executable type from list of radio buttons. In our case we will choose GUI application. Then give the name of exe file that we are making.  I have provided test. Now check the boxes as shown in the screenshot. And Click next.

4

STEP 5: Now give the name of your main class. In our case its Test. Don’t put the .class extension, just give the name. Now don’t click next.

5

STEP 6: You can see the the gree plus button on above screenshot. Click that and a window will open up. Check the archive radio button above.Now we have to provide the executable jar file to the Archive, so browse the location where your executable jar file is saved. Add it. Click OK. Click next.

6

STEP 7: Now we have to configure the JRE. So provide the minimum jre version and maximum jre version to be used by the user. Then click next.

7

STEP 8: Now we have to configure splash screen (if you want to). I haven’t provided splash screen so i have chosed no splash screen. You can give your choice. Click next.

8

STEP 9: Now we have to configure messages like if you want to give error message when user does not have JRE installed in his/her machine. Click next.

9

STEP 10: Now the last step of the wizard. If you want to save the configuration then click save as. I haven’t saved the configuration so i clicked EXIT. Then it will ask me if i want to save the configuration. Click NO(if you want to save click yes). So Thats it. Done.

10

Now navigate the output folder where u have saved the exe file. In our case we provided the same folder where our jar and class files are located. In below screenshot you can see that test.exe file has been created.

111

Now double click test.exe and message box(“executable was created using evalustion version of exe4J”) will open. Just click ok. Then application will run. In our program we created a frame so frame will get displayed.

13

So thats it. You are off. Your exe has been created. Now you can distribute this exe to windows user. But i f u want to make a cross-platform distributed file then this methos is not recommended. This is for only windows environment.

Thanks.


Slick2D engine is a high performance 2d game library based on a LWJGL(Lightweight Java Game Library). You can see the current features of Slick2D in their site. Download the library from here.
You can check the games made in Slick2D engine http://www.cokeandcode.com/ and http://slick.cokeandcode.com/gallery.php.

Tutorials : There are good and easy to go tutorials for beginners.

Now download the library. So here i’ll be telling how to setup the library with netbeans 6.5.1 so that u can write compile and run slick games easily and fast. I am using Ubuntu 8.04(Hardy heron), steps are similar for setting up in windows.

STEP 1: Download the library and save it in some appropriate place.
STEP 2: Open your Netbeans 6.5.1.
STEP 3: Go to tool->libraries. Library Manager window will open. Click New Library. Give it a name Slick. Then click OK.

screenshot-11

STEP 4: Now click classpath tab. Click Add Jar/Folder. Browse the folder where u have saved Your slick library. Go to lib folder and add all the jar files except slick.jar. Click OK

screenshot-2

STEP 5: Click JavaDoc tab. Click add/zip floder. Browse ur slick folder and select javadoc folder and add it. So done. Click OK.

screenshot-3

STEP 6: Ok so your slick library has been created. Now few steps remaining to complete the full set up. Create a new java project called SlickTest. Now Right Click SlickTest project, then click properties. Project properties window will open up. At left side, under categories select Libraries. Now at right side click Compile tab. Now Click Add Jar/Folder. Browse ur slick folder, go to lib folder, select slick.jar and add it.

screenshot-4

STEP 7: Now click Run tab. Click Add Library. Add Library window will open up. From there select Slick library that we previously created. Then add it.

screenshot-5

FINAL STEP 8 : Now at left side select Run. At Right side, go to VM Options, there u have to provide the parameter/argument that will link lwjgl libraries to your application. So at VM Options textbox, For Ubuntu users write: -Djava.library.path=lwjgl library path For Windows user write: -Djava.library.path=”lwjgl library path”. And Click Ok


Thats it Windows users have to put the path within double quotes. Here lwjgl library path is the path to the location where .so files for ubuntu linux(liblwjgl.so, liblwjgl64.so, libodejava.so,libopenal.so etc) and .dll for windows(liblwjgl.dll, liblwjgl64.dll, libodejava.dll,libopenal.dll etc) are located.

NOTE: Beware when you copy double quotes from this post

For windows user .dll files comes with slick library but linux users have to download the native .so lib files.

So now you are done and lets write a simple program for testing. This code will just create a window. Create a class called Test under the project that we had created.

package com.padam.testing;

import org.newdawn.slick.AppGameContainer;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;

/**
*
* @author padam
*/
public class Test extends BasicGame{

public Test(String name){
super(name);
}

public static void main(String[] args){
try {
AppGameContainer container = new AppGameContainer(new Test(“Game”));
container.setDisplayMode(800,600,false);
container.start();
} catch (SlickException e) {
e.printStackTrace();
}
}

@Override
public void init(GameContainer gc) throws SlickException {

}

@Override
public void update(GameContainer gc, int delta) throws SlickException {

}

public void render(GameContainer gc, Graphics g) throws SlickException {

}

}

NOTE: Linux and Mac users must download the lwjgl library. Then browse the folder and go to native folder. There choose your native OS folder. That will be your lwjgl library path thatt will go to VM Options parameter as specified on last step or you can copy the .so/native files to your convenient location and provide that path to VM Options parameter.
Now after this just test the above code. You may get a runtime error saying:

Exception in thread “main” java.lang.LinkageError: Version mismatch: jar version is ’16’, native libary version is ’17’
at org.lwjgl.Sys.(Sys.java:105)
at org.lwjgl.opengl.Display.(Display.java:128)
at org.newdawn.slick.AppGameContainer$1.run(AppGameContainer.java:39)
at java.security.AccessController.doPrivileged(Native Method)
at org.newdawn.slick.AppGameContainer.(AppGameContainer.java:36)
at com.padam.testing.Test.main(Test.java:26)
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

Linux/Mac/Solaris might face this problem because lwjgl jar files that comes with slick might be of older version which won’t match with the new lwjgl native .so/native files that u have downloaded. This means that the lwjgl jar files and lwjgl native/ .so files doesn’t match. So what u have to do is browse lwjgl folder that u have downloaded and go to jar folder and copy all the jar files and paste/replace the old jar files in the lib folder located in slick folder or location of slick library.

So Thats it. If u face any problem, comment it.

Gracias.


Rotating 2D Sprite: In my previous post i showed how to move a 2D sprite in two dimensional screen using Opengl with SDL. Now in this post i’l show how to rotate a 2D sprite using Opengl with SDL.

In Opengl, rotation can be made about x axis, y axis and z axis. In different axis rotation occurs differently like:

about X axis: like closing your laptop

about Y axis: like turning a page in a book

about Z axis: like the hands of a clock

So to rotate our 2D sprite we use glRotatef(angle,x,y,z). If you want to rotate about x axis the the value of x will be 1.0, y and z will be 0.0. How much angle do you want to rotate your sprite is determined by the value of angle to glRotatef() parameter.

So here is the drawImage() function to draw and rotate the 2D sprite:

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

glTranslatef(300.0,200.0,0.0);

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );

glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

In opengl, rotation happens about origin of the screen i.e(0,0). But we want rotation to happen about the centre of the 2D sprite. So instead of drawing the top left vertex at 0,0 you draw it at -imgWidth / 2, -imgHeight / 2, you draw the bottom right vertex at imgWidth / 2, imgHeight / 2, etc, etc. Our size of the quad is 128*128 as we are mapping the texture of size 128*128 to quad. So we’ll draw our quad as (-64,-64) to (64,64) so that (0,0) is directly at the center of the 2D sprite and when we rotate our sprite then rotation will happen about the center of the 2D sprite.


while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}

if(LEFT==true){
spin=spin+2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}

In while loop inside main function we are handling key event. As user presses left arrow key then we increment the angle and redraw the 2D sprite. I have used the same style as in previous posts i.e i have used two bool state variables(LEFT and RIGHT), when user presses left arrow key then LEFT becomes TRUE then angle is updated and 2D sprite is redrawn with rotation.

In this program, when left arrow key is pressed then sprite rotates towards east and when right arrow key is pressed then sprite rotates towards west.

 2D Sprite after rotation

2D Sprite after rotation

Here is the full source code

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

static GLfloat spin=0.0;
float x=100,y=100;
bool LEFT=false;
bool RIGHT=false;

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

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

// 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 );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{
// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

glTranslatef(300.0,200.0,0.0);
glRotatef( spin, 0.0, 0.0, 1.0 );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( -64, -64, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 64, -64, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 64, 64, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( -64, 64, 0 );
glEnd();
glLoadIdentity();

SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=true;
break;
case SDLK_RIGHT:
RIGHT=true;
break;
case SDLK_ESCAPE:
quit=true;
break;
}
}
//If a key was released
else if( event.type == SDL_KEYUP )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_LEFT:
LEFT=false;
break;
case SDLK_RIGHT:
RIGHT=false;
break;
}
}
}

if(LEFT==true){
spin=spin+2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}
else if(RIGHT==true){
spin=spin-2;
if(spin>360.0)
spin=spin-360.0;
drawImage();
}

}

clean_up();
return 0;
}

So Thats it. I hope this of any help to you and gives u some idea on rotation of 2D sprite using opengl and sdl.

Gracias.



Moving 2D Sprite: SO on my previous post i showed you the code to display a 2D sprite using OpenGl with SDL. Now i’ll show how to move a 2D Sprite using opengl with sdl. There will be some minor changes in the code and rest will be the same.

I’ll write the new changes in black and bold and rest are the same as in previous code on my previous post.

Here is the full code:


#include "SDL.h"

#include "SDL_image.h"

#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object

GLenum texture_format=NULL;

GLint nofcolors;

SDL_Event event;

bool LEFT=false;

bool RIGHT=false;

float x=100.0,y=100.0;

int loadImage()

{

SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2

if ( (surface->w & (surface->w - 1)) != 0 ) {

printf("warning: image.bmp's width is not a power of 2\n");

}

// Also check if the height is a power of 2

if ( (surface->h & (surface->h - 1)) != 0 ) {

printf("warning: image.bmp's height is not a power of 2\n");

}

//get number of channels in the SDL surface

nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel

if(nofcolors==4)

{

if(surface->format->Rmask==0x000000ff)

texture_format=GL_RGBA;

else

texture_format=GL_BGRA;

}

else if(nofcolors==3) //no alpha channel

{

if(surface->format->Rmask==0x000000ff)

texture_format=GL_RGB;

else

texture_format=GL_BGR;

}

else

{

printf("warning: the image is not truecolor...this will break ");

}

// Have OpenGL generate a texture object handle for us

glGenTextures( 1, &texture );

// Bind the texture object

glBindTexture( GL_TEXTURE_2D, texture );

// 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 );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,

texture_format, GL_UNSIGNED_BYTE, surface->pixels );

}

else {

printf("SDL could not load image.bmp: %s\n", SDL_GetError());

SDL_Quit();

return 1;

}

// Free the SDL_Surface only if it was successfully created

if ( surface ) {

SDL_FreeSurface( surface );

}

}

void drawImage()

{

// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

int init()

{

SDL_Surface *screen;

// Slightly different SDL initialization

if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {

printf("Unable to initialize SDL: %s\n", SDL_GetError());

return 1;

}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL|SDL_FULLSCREEN);

if ( !screen ) {

printf("Unable to set video mode: %s\n", SDL_GetError());

return 1;

}

}

void init_GL()

{

// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );

glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );

glLoadIdentity();

}

void clean_up()

{

glDeleteTextures( 1, &texture );

SDL_Quit();

}

int main(int argc, char *argv[])

{

//Make sure the program waits for a quit

bool quit = false;

init();

init_GL();

loadImage();

drawImage();

while( quit == false )

{

if( SDL_PollEvent( &event ) )

{

//If a key was pressed

if( event.type == SDL_KEYDOWN )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=true;

break;

case SDLK_RIGHT:

RIGHT=true;

break;

case SDLK_ESCAPE:

quit=true;

break;

}

}

//If a key was released

else if( event.type == SDL_KEYUP )

{

switch( event.key.keysym.sym )

{

case SDLK_LEFT:

LEFT=false;

break;

case SDLK_RIGHT:

RIGHT=false;

break;

}

}

}

if(LEFT==true){

x-=2;

drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

}

clean_up();

return 0;

}

In above code i have used two bool variable(LEFT and RIGHT) and two float variables(x and y) to store the position of  sprite. In the main function inside the loop we are taking the key input from the user. So when the user press left arrow key “LEFT bool variable is assigned TRUE” and when user releases the left arrow key ” LEFT bool variable is assigned FALSE”. Same applies for pressing right arrow key. So in this code :

if(LEFT==true){

x-=2;

drawImage();

}

else if(RIGHT==true){

x+=2;

drawImage();

}

when left arrow key is pressed “LEFT bool variable becomes TRUE” and x position of sprite is incremented by 2. Then we draw the sprite again. And when left arrow key is released “LEFT bool variable becomes FALSE” which means x position of sprite should not be updated. Same concept applies for moving right.

Now we have code to update the x and y position of  sprite. But how to render the sprite with updated x and y coordinates. This is done by gTranslatef(x,y,z) function. It translates the position of sprite. So we’ll be updating x and y to move the sprite, and z will be zero. So in this code:

void drawImage()

{

// Clear the screen before drawing

glClear( GL_COLOR_BUFFER_BIT );

glTranslatef( x, y, 0 );

// Bind the texture to which subsequent calls refer to

glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );

// Top-left vertex (corner)

glTexCoord2i( 0, 0 );

glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)

glTexCoord2i( 1, 0 );

glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)

glTexCoord2i( 1, 1 );

glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)

glTexCoord2i( 0, 1 );

glVertex3f( 100, 228, 0 );

glEnd();

glLoadIdentity();

SDL_GL_SwapBuffers();

}

when we update the position of x and y then we call the above function where we have included new code glTranslatef(x,y,z) which will make the sprite to be drawn in given x.y and z location.

So thats it. I hope this will give u some pretty basic idea. Now you can write your own code for moving 2d Sprite.

Gracias.


In many forums, i have seen people asking about making 2D games using OpenGl and there weren’t any satisfactory answers. So i searched the google on doing 2D graphics using Opengl. Surprisingly there were not many results on that, there were very very few info on doing 2D graphics using OpenGl.

So i did some research on this and came up with this code. I hope this will be of some use to those who wants to get started making 2D games using OpenGl. I don’t claim that this code is efficient way to do it. I am still learning OpenGl. But this code will give you a base to start off.

Here i’ll be using SDL with OpenGL. I’l be using SDL for creating the window, taking input, and loading texture data. And I’ll be using SDL_image extension library to load images(BMP, PNM, XPM, LBM, PCX, GIF, JPEG, TGA and PNG files.). Lastly, Opengl wiil be used for rendering the graphics.

If you don’t know how to set up libraries then here is the guide to set up SDL, guide to setup SDL_image extension library and guide to set up OpenGl.

This code has been tested on windows using visual studio 2005.

So lets start:

#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

First we will include the necessary header files.


GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

texture is the handle to our texture object. texture_format will store the information about the image loaded. A SDL_Event structure stores event data for us to handle.


int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

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

// 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 );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

This is the loadImage() function to load the image. First we’ll use Img_Load() function to load an image. Then we’ll check whether the height and width of an image is power of 2. If its not a power of 2 then program will terminate. Then we’ll check the information of image i.e if image contains alpha channel or not. So according to that we’ll use our texture_format. Lastly we’l map the image to the texture object. glBindTexture(GL_TEXTURE_2D, &texture) tells OpenGL to bind the named texture texture to a texture target. The main function of glBindTexture is to assign a texture name to texture data. In this case we’re telling OpenGL there is memory available at &texture. When we create the texture, it will be stored in the memory that &texture references.


void drawImage()
{

// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( 100, 228, 0 );
glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

This is the drawImage() function. As name suggest this will render our 2D sprite. There is nothing to explain here. We are creating a quad and mapping our texture to the quad and rendering that quad.

To properly map a texture onto a quad, you have to make sure the top right of the texture is mapped to the top right of the quad. The top left of the texture is mapped to the top left of the quad, the bottom right of the texture is mapped to the bottom right of the quad, and finally, the bottom left of the texture is mapped to the bottom left of the quad. If the corners of the texture do not match the same corners of the quad, the image may appear upside down, sideways, or not at all.

The first value of glTexCoord2i is the X coordinate. 0 is the left side of the texture  and 1 is the right side of the texture. The second value of glTexCoord2f is the Y coordinate 0 is the bottom of the texture and 1 is the top of the texture.


int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

This is a  init() function to set up the window.We create our OpenGL window. When we want to use OpenGL we pass the SDL_OPENGL flag to SDL_SetVideoMode() instead of SDL_SWSURFACE. Now the window will use OpenGL’s hardware accelerated rendering instead of SDL’s software rendering.


void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

This function will set up out Opengl world. The first thing we do is set the clear color.When we clear the screen, we want it to be black. So we set the clear color to be black (R, G, B, A) with glClearColor(). Then we set the matrix mode to projection using glMatrixMode(). Then we intialize the projection matrix by calling glLoadIdentity(). glLoadIdentity() essentially resets the matrix by setting it to be the identity matrix.We are using Orthographic projection for projecting two-dimensional image onto a two-dimensional screen. Above code glOrtho( 0, 640, 480, 0, -1, 1 ); will create two-dimensional screen with top left(0,0) and bottom right(640,480).

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

The above function will clean up the resource and then terminate the window.

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE:
quit=true;
break;
}
}

}
}

clean_up();
return 0;
}

This is the main function. We’ll be calling all the function i.e setting up window and OpenGl; loading Sprite and rendering it.

So thats it. Now your are off.

program

displaying 2D sprite(PNG) using OpenGl with SDL

You can save this image(flower.png) for testing.

flower

So here is the full code:


#include "SDL.h"
#include "SDL_image.h"
#include "SDL_opengl.h"

#include <stdio.h>

GLuint texture=NULL; //this is a handle to our texture object
GLenum texture_format=NULL;
GLint nofcolors;

SDL_Event event;

int loadImage()
{
SDL_Surface *surface; // this surface will tell us the details of the image

if ( (surface = IMG_Load("flower.png")) ) {

// Check that the image's width is a power of 2
if ( (surface->w & (surface->w - 1)) != 0 ) {
printf("warning: image.bmp's width is not a power of 2\n");
}

// Also check if the height is a power of 2
if ( (surface->h & (surface->h - 1)) != 0 ) {
printf("warning: image.bmp's height is not a power of 2\n");
}

//get number of channels in the SDL surface
nofcolors=surface->format->BytesPerPixel;

//contains an alpha channel
if(nofcolors==4)
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGBA;
else
texture_format=GL_BGRA;
}
else if(nofcolors==3) //no alpha channel
{
if(surface->format->Rmask==0x000000ff)
texture_format=GL_RGB;
else
texture_format=GL_BGR;
}
else
{
printf("warning: the image is not truecolor...this will break ");
}

// Have OpenGL generate a texture object handle for us
glGenTextures( 1, &texture );

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

// 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 );

glTexImage2D( GL_TEXTURE_2D, 0, nofcolors, surface->w, surface->h, 0,
texture_format, GL_UNSIGNED_BYTE, surface->pixels );
}
else {
printf("SDL could not load image.bmp: %s\n", SDL_GetError());
SDL_Quit();
return 1;
}

// Free the SDL_Surface only if it was successfully created
if ( surface ) {
SDL_FreeSurface( surface );
}
}

void drawImage()
{

// Clear the screen before drawing
glClear( GL_COLOR_BUFFER_BIT );

// Bind the texture to which subsequent calls refer to
glBindTexture( GL_TEXTURE_2D, texture );

glBegin( GL_QUADS );
// Top-left vertex (corner)
glTexCoord2i( 0, 0 );
glVertex3f( 100, 100, 0 );

// Bottom-left vertex (corner)
glTexCoord2i( 1, 0 );
glVertex3f( 228, 100, 0 );

// Bottom-right vertex (corner)
glTexCoord2i( 1, 1 );
glVertex3f( 228, 228, 0 );

// Top-right vertex (corner)
glTexCoord2i( 0, 1 );
glVertex3f( 100, 228, 0 );
glEnd();
glLoadIdentity();
SDL_GL_SwapBuffers();
}

int init()
{
SDL_Surface *screen;

// Slightly different SDL initialization
if ( SDL_Init(SDL_INIT_VIDEO) != 0 ) {
printf("Unable to initialize SDL: %s\n", SDL_GetError());
return 1;
}

SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );

screen = SDL_SetVideoMode( 640, 480, 16, SDL_OPENGL);
if ( !screen ) {
printf("Unable to set video mode: %s\n", SDL_GetError());
return 1;
}
}

void init_GL()
{
// Set the OpenGL state after creating the context with SDL_SetVideoMode

glClearColor( 0, 0, 0, 0 );

glEnable( GL_TEXTURE_2D ); // Need this to display a texture

glViewport( 0, 0, 640, 480 );

glMatrixMode( GL_PROJECTION );
glLoadIdentity();

glOrtho( 0, 640, 480, 0, -1, 1 );

glMatrixMode( GL_MODELVIEW );
glLoadIdentity();
}

void clean_up()
{
glDeleteTextures( 1, &texture );

SDL_Quit();
}

int main(int argc, char *argv[])
{
//Make sure the program waits for a quit
bool quit = false;

init();
init_GL();
loadImage();
drawImage();

while( quit == false )
{
if( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
//Adjust the velocity
switch( event.key.keysym.sym )
{
case SDLK_ESCAPE:
quit=true;
break;
}
}

}
}

clean_up();
return 0;
}

So i hope this will give u a base to start off. On the next post i’l tell you how to move the 2d Sprite in the screen. I’ll show u how to handle the key events in my next post.

Gracias.